class Transaction(db.Document):
    userId = db.ObjectIdField(required=True)
    fromAddress = db.StringField(required=True, max_length=200)
    fromCurrency = db.StringField(required=True, max_length=20)
    toAddress = db.StringField(required=True, max_length=200)
    toCurrency = db.StringField(required=True, max_length=20)
    amount = db.DecimalField(required=True, precision=10)
    senderDeviceId = db.IntField(required=False)
    senderIp = db.StringField(required=False, max_length=20)
    country = db.StringField(required=False, max_length=20)
    transactedAt = db.DateTimeField(
        required=False)  # StringField(required=False, max_length=15)
    score = db.DecimalField(required=True, default=0)
    txHash = db.StringField(required=False, max_length=200)
    createdAt = db.DateTimeField(default=datetime.utcnow)
    updatedAt = db.DateTimeField()
    updatedBy = db.StringField(max_length=100)

    meta = {
        'collection':
        'transactions',
        'indexes': [
            'userId', 'fromAddress', 'fromCurrency', '-transactedAt',
            '-createdAt', 'score'
        ]
    }
class UserAccessToken(db.Document):
    userId = db.ObjectIdField(required=True)
    accessToken = db.StringField(required=True, max_length=1000)
    expireAt = db.DateTimeField(required=True)
    CreatedAt = db.DateTimeField(default=datetime.utcnow)

    meta = {
        'collection': 'userAccessToken',
        'indexes': ['userId', '-accessToken', 'expireAt']
    }
class UserApi(db.Document):
    userId = db.ObjectIdField(required=True)
    apiName = db.StringField(max_length=100)
    apiKey = db.StringField(required=True, unique=True, max_length=100)
    apiSecret = db.StringField(required=True, max_length=300)
    isActive = db.BooleanField(required=True, default=True)
    createdAt = db.DateTimeField(required=True, default=datetime.utcnow)
    createdBy = db.StringField(required=True, max_length=100)
    updatedAt = db.DateTimeField()
    updatedBy = db.StringField(max_length=100)

    meta = {
        'collection': 'userApi',
        'indexes': ['userId', 'apiKey', '-createdAt']
    }
Exemplo n.º 4
0
class Complete(db.Document):
    # 问卷完成时间
    completeTime = db.DateTimeField(default=datetime.utcnow)
    # 完成内容
    completeData = db.ListField()
    # 用户ip信息
    ipCondition = db.DictField()
    # 对应问卷 id
    targetQuestionnaireId = db.IntField()

    # ip condition  问卷填报者的ip信息

    # 增添一条完成记录
    def createCompleteData(self, data, qid, ip=None):
        q = Questionnaire.objects.filter(questionnaireId=qid).first()
        if not q:
            raise NoQuestionnaire
        if q.ipControl and ip in q.questionnaireIP:
            raise SameIp
        if ip is not None:
            q.questionnaireIP.append(ip)
        completes = data['completeData']
        self.completeData = completes
        self.makeResolution(completes)
        self.ipCondition = DataCalculate.getPlace(ip)
        self.targetQuestionnaireId = qid
        self.save()

    @staticmethod
    def makeResolution(completes):
        for c in completes:
            Resolution(targetProblemId=c['targetProblemId'],
                       type=c['type'],
                       resolution=c['resolution']).save()

    @staticmethod
    def addCompleteNumber(qid, completes):
        from app.models.problem import Problem
        ps = Problem.objects.filter(
            targetQuestionnaireId=qid).order_by('problemId')
        for index, p in enumerate(ps):
            p.addCompletes(completes[index])
            p.save()

    @staticmethod
    def getCompleteAmount(qid):
        cs = Complete.objects.filter(targetQuestionnaireId=qid)
        return len(cs)

    # 获得目标省份
    def getIpProvince(self):
        # 去掉'省'字 否则前端显示不了
        return self.ipCondition['pro'][:-1]
class User(db.Document):
    username = db.StringField(required=True, unique=True, max_length=100)
    password = db.StringField(required=True, max_length=100)
    company = db.StringField(max_length=100)
    email = db.StringField(required=True, max_length=100)
    contactNumber = db.StringField(max_length=100)
    address = db.StringField(max_length=200)
    billingType = db.ObjectIdField()
    emailVerified = db.BooleanField(required=True, default=False)
    roleType = db.StringField(required=True,
                              default="User",
                              regex=r'^(Admin|User)$')
    isActive = db.BooleanField(required=True, default=True)
    lastSignin = db.DateTimeField()
    createdAt = db.DateTimeField(required=True, default=datetime.utcnow)
    createdBy = db.StringField(required=True)
    updatedAt = db.DateTimeField()
    updatedBy = db.StringField(max_length=100)

    meta = {
        'collection': 'user',
        'indexes': ['username', 'email', '-createdAt']
    }
Exemplo n.º 6
0
class Sensor(db.Document):
    device_uuid = db.StringField()
    sensort_type_options = ["temperature", "humidity"]
    sensor_type = db.StringField(choices=sensort_type_options)
    sensor_value = db.FloatField(min_value=0.0, max_value=100.0)
    sensor_reading_time = db.DateTimeField()
class Questionnaire(db.Document):
    # 发布者的唯一标识
    ownerId = db.StringField()
    # 问卷唯一标识
    questionnaireId = db.IntField()
    '''全局开关'''
    # 问卷运行状态
    condition = db.BooleanField(default=False)
    # 问卷是否加密
    isSecret = db.BooleanField(default=False)
    # 微信限制
    wechatControl = db.BooleanField(default=False)
    # ip限制
    ipControl = db.BooleanField(default=False)
    # 设备限制
    equipmentControl = db.BooleanField(default=False)
    # 截止时间限制
    deadlineControl = db.BooleanField(default=False)
    '''全局设置'''
    # 问卷密码
    secretKey = db.StringField(default=None)
    # 问卷截止时间
    deadline = db.DateTimeField(default=datetime.utcnow)
    # 问卷最后一次更新时间
    renewTime = db.DateTimeField(default=datetime.utcnow)
    '''答题次数'''
    # 问卷访问过的ip
    questionnaireIP = db.ListField(default=[])
    '''基本信息'''
    title = db.StringField(default="请为这个问卷创建一个标题")
    subTitle = db.StringField(default="请为这个问卷创建一个副标题")

    def getQuestionnaireId(self):
        return self.questionnaireId

    # 问卷不在限制时间范围内 将其状态置为false 表示不可访问
    def makeItDead(self):
        self.condition = False
        self.save()

    # 新建一个问卷
    def createQuestionnaire(self, ownerId):
        t = getUniqueId()
        self.questionnaireId = t
        self.ownerId = ownerId
        self.save()
        return self.questionnaireId

    # 返回前端的问卷状态 type 0 表示不需要密码  type1 表示需要密码
    def getConditionJson(self, isAdmin):
        payLoad = {
            "questionnaireId": self.questionnaireId,
            "condition": self.condition,
            "isSecret": self.isSecret,
            "wechatControl": self.wechatControl,
            "ipControl": self.ipControl,
            "equipmentControl": self.equipmentControl,
            "deadlineControl": self.deadlineControl,
            "deadline": self.deadline,
            "renewTime": self.renewTime,
            "title": self.title,
            "subTitle": self.subTitle,
            "secretKey": self.secretKey if isAdmin else None,
        }
        return payLoad

    @staticmethod
    def deleteQuestionnaire(ownerId, questionnaireId):
        q = Questionnaire.objects.filter(
            ownerId=ownerId, questionnaireId=questionnaireId).first()
        if not q:
            raise NoQuestionnaire
        q.delete()

    @staticmethod
    def editQuestionnaire(ownerId, questionnaireId, form):
        q = Questionnaire.objects.filter(
            ownerId=ownerId, questionnaireId=questionnaireId).first()
        if not q:
            raise NoQuestionnaire
        keys = form.jsonKeys
        for info in keys:
            # 防止传入null时值被重置
            if form[info].data is not None:
                q[info] = form[info].data
        q.save()

    @staticmethod
    def getConditions(questionnaireId, isAdmin):
        q = Questionnaire.objects.filter(
            questionnaireId=questionnaireId).first()
        if not q:
            raise NoQuestionnaire
        if checkTimeIsDead(q):
            q.makeItDead()
        return q.getConditionJson(isAdmin=isAdmin)

    @staticmethod
    def checkSecretKey(questionnaireId, key):
        from app.models.problem import Problem
        q = Questionnaire.objects.filter(
            questionnaireId=questionnaireId).first()
        if not q:
            raise NoQuestionnaire
        if q.secretKey != key and q.isSecret:
            raise WrongProblemSecretKey
        return {
            "basicInfo": q.getConditionJson(isAdmin=False),
            "problems": Problem.getProblems(questionnaireId)
        }

    @staticmethod
    def getQuestionnaire(ownerId, questionnaireId, isAdmin):
        from app.models.problem import Problem
        q = Questionnaire.objects.filter(
            ownerId=ownerId, questionnaireId=questionnaireId).first()
        if not q:
            raise NoQuestionnaire
        return {
            "basicInfo": q.getConditionJson(isAdmin=isAdmin),
            "problems": Problem.getProblems(questionnaireId)
        }

    def getQuestionniareQRCode(self):
        code = QRcode(str(self.questionnaireId))
        return code.showQRImg()

    def downloadQuestionnaireQRCode(self):
        code = QRcode(str(self.questionnaireId))
        return code.downloadQRImg()

    @staticmethod
    def getAllQuestionnaire(ownerId):
        qs = Questionnaire.objects.filter(ownerId=ownerId)
        res = []
        for q in qs:
            res.append(q.getConditionJson(isAdmin=False))
        return res

    @staticmethod
    def getAnalysisData(qid):
        from app.models.problem import Problem
        from app.models.complete import Complete
        from app.utils.dataCalculate import DataCalculate
        # 拿到所有problems
        resolutions = []
        q = Questionnaire.objects.filter(questionnaireId=qid).first()
        if not q:
            raise NoQuestionnaire
        problems = Problem.objects.filter(targetQuestionnaireId=qid)
        completes = Complete.getCompleteAmount(qid)
        for p in problems:
            res = p.getResolution()
            resolutions.append(res)
        return {
            "data": resolutions,
            "basicInfo": {
                "totalComplete": completes,
                "renewTime": q.renewTime,
                "title": q.title,
            },
            "provinceInfo": DataCalculate.getProvinceData(qid)
        }

    @staticmethod
    def getTemplatesBasicInfo(page):
        from app.models.user import User
        if not page:
            raise ParameterException
        tuid = User.getTemplateUserId()
        beginIndex = (page - 1) * 10
        ts = Questionnaire.objects.filter(ownerId=tuid)[beginIndex:beginIndex +
                                                        10]
        templateList = []
        for t in ts:
            templateList.append({
                "title": t.title,
                "renewTime": t.renewTime,
                "info": t.subTitle,
                "id": t.questionnaireId
            })
        return templateList

    @staticmethod
    def getTemplatesAmount():
        from app.models.user import User
        tuid = User.getTemplateUserId()
        return len(Questionnaire.objects.filter(ownerId=tuid))

    @staticmethod
    def copyTemplates(qid, uid):
        from app.models.user import User
        from app.models.problem import Problem
        templateUserId = User.getTemplateUserId()
        # 获得目标模板
        newqid = getUniqueId()
        q = Questionnaire.objects.filter(questionnaireId=qid,
                                         ownerId=templateUserId).first()
        if not q:
            raise NoQuestionnaire
        Questionnaire.createByTemplates(uid, newqid, q.title, q.subTitle)
        ps = Problem.objects.filter(targetQuestionnaireId=qid)
        if not ps:
            raise NoProblem
        for p in ps:
            Problem.createByTemplates(p.title, p.type, p.options,
                                      getUniqueId(), uid, newqid)

    @staticmethod
    def createByTemplates(uid, qid, title, subTitle):
        Questionnaire(ownerId=uid,
                      questionnaireId=qid,
                      title=title,
                      subTitle=subTitle).save()