Ejemplo n.º 1
0
    def update_white_list(self):
        admin = get_current_admin()
        if not admin:
            raise AuthorityError
        data = parameter_required(("usid", "action"))
        usid = data.get('usid')
        action = data.get("action", 10)

        if action:
            try:
                action = WhiteListAction(int(action)).value
            except:
                raise ParamsError('action 只能是整数')

        user = User.query.filter(User.USid == usid,
                                 User.isdelete == false()).first()
        if not user:
            raise ParamsError('用户不在本系统')
        with db.auto_commit():
            if action == WhiteListAction.putin.value:
                if user.USinWhiteList:
                    raise ParamsError('用户已在白名单')
                user.USinWhiteList = True
            elif action == WhiteListAction.delete.value:
                if not user.USinWhiteList:
                    raise ParamsError('用户不在白名单')
                user.USinWhiteList = False
            else:
                raise ParamsError('参数异常')
            db.session.add(user)
        return Success(data='{}修改成功'.format(user.USname))
Ejemplo n.º 2
0
def _invitation_records():
    secret_user_id = request.args.to_dict().get('secret_usid')
    if not secret_user_id:
        return
    from inquiry.extensions.interface.user_interface import is_user
    if not is_user():
        return
    current_app.logger.info('>>>>>>>>record invitation<<<<<<<<')
    try:
        inviter_id = base_decode(secret_user_id)
        current_app.logger.info(f'secret_usid --> inviter_id: {inviter_id}')
    except Exception as e:
        current_app.logger.error(f'解析secret_usid时出错: {e}')
        return
    usid = getattr(request, 'user').id
    if inviter_id == usid:
        current_app.logger.info('inviter == invitee')
        return
    from inquiry.models.user import UserInvitation
    from inquiry.extensions.register_ext import db
    import uuid
    try:
        with db.auto_commit():
            uin = UserInvitation.create({
                'UINid': str(uuid.uuid1()),
                'USInviter': inviter_id,
                'USInvited': usid,
                'UINapi': request.path
            })
            current_app.logger.info(f'{request.path} 创建邀请记录')
            db.session.add(uin)
    except Exception as e:
        current_app.logger.error(f'存储邀请记录时出错: {e}')
Ejemplo n.º 3
0
    def bind_phone(self):
        """小程序绑定手机号更新用户"""
        data = parameter_required((
            'ustelphone',
            'identifyingcode',
        ))
        ustelphone = data.get('ustelphone')
        if not ustelphone:
            raise ParamsError('为获得更优质的服务,请允许授权您的手机号码')

        user = self._get_exist_user((User.USid == getattr(request,
                                                          'user').id, ))
        if user.UStelphone:
            raise TokenError('您已绑定过手机号码')
        self.__check_identifyingcode(ustelphone, data.get("identifyingcode"))

        covered_number = str(ustelphone).replace(str(ustelphone)[3:7], '*' * 4)

        if self._get_exist_user((User.USid != getattr(request, 'user').id,
                                 User.UStelphone == ustelphone)):
            raise ParamsError(f'该手机号({covered_number})已被其他用户绑定,请联系客服处理')

        with db.auto_commit():
            user.update({'UStelphone': ustelphone})
            db.session.add(user)
            res_user = user

        token = usid_to_token(res_user.USid,
                              level=res_user.USlevel,
                              username=res_user.USname)  # 更换token
        response = {'phonenumber': covered_number, 'token': token}
        current_app.logger.info('return_data: {}'.format(response))
        return Success('绑定成功', response)
Ejemplo n.º 4
0
    def set_mp_banner(self):
        """小程序轮播图"""
        data = parameter_required(('bnurl',))
        bnid = data.get('bnid')
        bndict = {'BNurl': data.get('bnurl'),
                  'BNsort': data.get('bnsort'),
                  'BNshow': data.get('bnshow'),
                  'contentlink': data.get('contentlink')}
        with db.auto_commit():
            if not bnid:
                bndict['BNid'] = str(uuid.uuid1())
                bndict['ADid'] = getattr(request, 'user').id
                bn_instance = Banner.create(bndict)

                msg = '添加成功'
            else:
                bn_instance = Banner.query.filter_by(BNid=bnid, isdelete=false()).first_('未找到该轮播图信息')
                if data.get('delete'):
                    bn_instance.update({'isdelete': True})
                    msg = '删除成功'
                else:
                    bn_instance.update(bndict, null='not')
                    msg = '编辑成功'
            db.session.add(bn_instance)
        return Success(message=msg, data={'bnid': bn_instance.BNid})
Ejemplo n.º 5
0
    def update_admin_password(self):
        """更新管理员密码"""
        if not is_admin():
            raise AuthorityError('权限不足')

        data = parameter_required(
            ('password_old', 'password_new', 'password_repeat'))
        admin = get_current_admin()
        pwd_new = data.get('password_new')
        pwd_old = data.get('password_old')
        pwd_repeat = data.get('password_repeat')
        if pwd_new != pwd_repeat:
            raise ParamsError('两次输入的密码不同')
        with db.auto_commit():
            if check_password_hash(admin.ADpassword, pwd_old):
                self.__check_password(pwd_new)
                admin.ADpassword = generate_password_hash(pwd_new)
                # BASEADMIN().create_action(AdminActionS.update.value, 'none', 'none')
                db.session.add(admin)
                return Success('更新密码成功')
            current_app.logger.info('{0} update pwd failed'.format(
                admin.ADname))
            raise ParamsError('旧密码有误')

        raise AuthorityError('账号已被回收')
Ejemplo n.º 6
0
 def set_uc(self):
     admin = get_current_admin()
     data = parameter_required()
     ucid, ucname, ucsort = data.get('ucid'), data.get('ucname'), data.get(
         'ucsort')
     ucdict = {}
     if ucname:
         ucdict['UCname'] = ucname
     if ucsort:
         try:
             ucsort = int(ucsort)
         except:
             raise ParamsError('权重只能是整数')
         ucdict['UCsort'] = ucsort
     with db.auto_commit():
         if not ucid:
             if not ucname:
                 raise ParamsError('分类名缺失')
             ucdict['UCid'] = str(uuid.uuid1())
             ucinstance = UnitCategory.create(ucdict)
             msg = '添加成功'
         else:
             ucinstance = UnitCategory.query.filter(
                 UnitCategory.UCid == ucid,
                 UnitCategory.isdelete == false()).first_('分类已删除')
             if data.get('delete'):
                 ucinstance.update({'isdelete': True})
                 msg = '删除成功'
             else:
                 ucinstance.update(ucdict)
                 msg = '更新成功'
         db.session.add(ucinstance)
     return Success(message=msg, data={'ucid': ucinstance.UCid})
Ejemplo n.º 7
0
    def get_inforcode(self):
        """发送/校验验证码"""
        args = request.args.to_dict()
        # print('get inforcode args: {0}'.format(args))
        Utel = args.get('ustelphone')
        if not Utel or not re.match(r'^1[1-9][0-9]{9}$', str(Utel)):
            raise ParamsError('请输入正确的手机号码')
        if is_user():
            user = User.query.filter_by_(USid=request.user.id).first()
            if (user and user.UStelphone) and str(Utel) != user.UStelphone:
                raise ParamsError('请使用已绑定手机号 {} 获取验证码'
                                  ''.format(
                                      str(user.UStelphone).replace(
                                          str(user.UStelphone)[3:7], '*' * 4)))
        # 拼接验证码字符串(6位)
        code = ""
        while len(code) < 6:
            item = random.randint(1, 9)
            code = code + str(item)

        # 获取当前时间,与上一次获取的时间进行比较,小于60秒的获取直接报错

        time_time = datetime.now()

        # 根据电话号码获取时间
        time_up = IdentifyingCode.query.filter(
            IdentifyingCode.ICtelphone == Utel,
            IdentifyingCode.isdelete == False).order_by(
                IdentifyingCode.createtime.desc()).first_()
        # print("this is time up %s", time_up)

        if time_up:
            delta = time_time - time_up.createtime
            if delta.seconds < 60:
                raise TimeError("验证码已发送")

        with db.auto_commit():
            newidcode = IdentifyingCode.create({
                "ICtelphone": Utel,
                "ICcode": code,
                "ICid": str(uuid.uuid1())
            })
            db.session.add(newidcode)

        params = {"code": code}
        response_send_message = SendSMS(Utel, params)

        if not response_send_message:
            raise SystemError('发送验证码失败')

        response = {'ustelphone': Utel}
        return Success('获取验证码成功', data=response)
Ejemplo n.º 8
0
    def set_proudct(self):
        admin = get_current_admin()

        data = parameter_required()
        prid, prname, pcid, prsort = data.get('prid'), data.get(
            'prname'), data.get('pcid'), data.get('prsort')
        product_dict = {"ADid": admin.ADid}
        if prname:
            product_dict['PRname'] = prname
        if pcid:
            pc = ProductCategory.query.filter(
                ProductCategory.PCid == pcid,
                ProductCategory.isdelete == false()).first_('分类已删除')

            product_dict['PCid'] = pc.PCid
        if prsort:
            try:
                prsort = int(prsort)
            except:
                raise ParamsError('权重只能是整数')
            product_dict['PRsort'] = prsort
        with db.auto_commit():
            if not prid:
                if not prname:
                    raise ParamsError('缺少产品名')
                if not pcid:
                    raise ParamsError('缺少分类ID')

                product_dict['PRid'] = str(uuid.uuid1())
                product = Product.create(product_dict)
                msg = '添加成功'

            else:
                product = Product.query.filter(
                    Product.PRid == prid,
                    Product.isdelete == false()).first_('产品已删除')

                if data.get('delete'):
                    product.update({'isdelete': True})
                    msg = '删除成功'
                else:
                    product.update(product_dict)
                    msg = '编辑成功'

            db.session.add(product)
        return Success(message=msg, data={'prid': product.PRid})
Ejemplo n.º 9
0
 def set_userlevelsetting(self):
     admin = get_current_admin()
     data = parameter_required()
     ulsid, ulslevel, ulscoefficient = data.get('ulsid'), data.get(
         'ulslevel'), data.get('ulscoefficient')
     ulsdict = {}
     if ulslevel or ulslevel == 0:
         try:
             ulslevel = int(ulslevel)
         except:
             raise ParamsError('等级只能是整数')
         ulsdict['ULSlevel'] = ulslevel
     if ulscoefficient or ulscoefficient == 0:
         try:
             ulscoefficient = Decimal(ulscoefficient)
         except:
             raise ParamsError('系数只能是数字')
         ulsdict['ULScoefficient'] = ulscoefficient
     with db.auto_commit():
         if not ulsid:
             if not ulslevel:
                 raise ParamsError('等级参数缺失')
             if not ulscoefficient:
                 raise ParamsError('系数缺失')
             ulsdict['ULSid'] = str(uuid.uuid1())
             # 同级校验
             uls = UserLevelSetting.query.filter(
                 UserLevelSetting.isdelete == false(),
                 UserLevelSetting.ULSlevel == ulslevel).first()
             if uls:
                 raise ParamsError('该等级已设置对应系数')
             ulsinstance = UserLevelSetting.create(ulsdict)
             msg = '添加成功'
         else:
             ulsinstance = UserLevelSetting.query.filter(
                 UserLevelSetting.isdelete == false(),
                 UserLevelSetting.ULSid == ulsid).first_('系数设置已删除')
             if data.get('delete'):
                 ulsinstance.update({'isdelete': True})
                 msg = '删除成功'
             else:
                 ulsinstance.update(ulsdict)
                 msg = '更新成功'
         db.session.add(ulsinstance)
     return Success(msg, data={'ulsid': ulsinstance.ULSid})
Ejemplo n.º 10
0
    def set_pc(self):
        _ = get_current_admin()

        data = parameter_required()
        pcid, pcname, pcsort, pcurl, pcicon = data.get('pcid'), data.get(
            'pcname'), data.get('pcsort'), data.get('pcurl'), data.get(
                'pcicon')
        pc_dict = {}
        if pcname:
            pc_dict['PCname'] = pcname
        # if pcurl:
        pc_dict['PCurl'] = pcurl
        if pcicon:
            pc_dict['PCicon'] = pcicon
        if pcsort:
            try:
                pcsort = int(pcsort)
            except:
                raise ParamsError('权重只能是整数')
            pc_dict['PCsort'] = pcsort
        with db.auto_commit():
            if not pcid:
                if not pcname:
                    raise ParamsError('缺少分类名')
                if not pcicon:
                    raise ParamsError('缺少icon')
                pc_dict['PCid'] = str(uuid.uuid1())
                pc = ProductCategory.create(pc_dict)
                msg = '添加成功'

            else:
                pc = ProductCategory.query.filter(
                    ProductCategory.PCid == pcid,
                    ProductCategory.isdelete == false()).first_('分类已删除')

                if data.get('delete'):
                    pc.update({'isdelete': True})
                    msg = '删除成功'
                else:
                    pc.update(pc_dict, null='not ignore')
                    msg = '编辑成功'

            db.session.add(pc)
        return Success(message=msg, data={'pcid': pc.PCid})
Ejemplo n.º 11
0
    def update_user_level(self):
        admin = get_current_admin()
        if not admin:
            raise AuthorityError
        data = parameter_required(("usid", "uslevel"))
        usid = data.get('usid')
        uslevel = data.get("uslevel", 0)

        if uslevel or uslevel == 0:
            try:
                uslevel = int(uslevel)
            except:
                raise ParamsError('uslevel 只能是整数')

        user = User.query.filter(User.USid == usid,
                                 User.isdelete == false()).first()
        if not user:
            raise ParamsError('用户不在本系统')
        with db.auto_commit():
            user.USlevel = uslevel
            db.session.add(user)
        return Success(data='{}修改成功'.format(user.USname))
Ejemplo n.º 12
0
    def update_admin(self):
        """更新管理员信息"""
        if not is_admin():
            raise AuthorityError('权限不足')
        data = request.json or {}
        admin = get_current_admin()
        if admin.ADstatus != AdminStatus.normal.value:
            raise AuthorityError('权限不足')
        update_admin = {}
        action_list = []
        with db.auto_commit():
            if data.get("adname"):
                update_admin['ADname'] = data.get("adname")
                action_list.append(
                    str(AdminAction.ADname.value) + '为' +
                    str(data.get("adname")) + '\n')

            if data.get('adheader'):
                update_admin['ADheader'] = data.get("adheader")
                action_list.append(str(AdminAction.ADheader.value) + '\n')
            if data.get('adtelphone'):
                # self.__check_identifyingcode(data.get('adtelphone'), data.get('identifyingcode'))
                update_admin['ADtelephone'] = data.get('adtelphone')
                action_list.append(
                    str(AdminAction.ADtelphone.value) + '为' +
                    str(data.get("adtelphone")) + '\n')
            password = data.get('adpassword')
            if password and password != '*' * 6:
                self.__check_password(password)
                password = generate_password_hash(password)
                update_admin['ADpassword'] = password
                action_list.append(
                    str(AdminAction.ADpassword.value) + '为' + str(password) +
                    '\n')

            if admin.ADlevel == AdminLevel.super_admin.value:
                filter_adid = data.get('adid') or admin.ADid
                if getattr(AdminLevel, data.get('adlevel', ""), ""):
                    update_admin['ADlevel'] = getattr(
                        AdminLevel, data.get('adlevel')).value
                    action_list.append(
                        str(AdminAction.ADlevel.value) + '为' +
                        getattr(AdminLevel, data.get('adlevel')).zh_value +
                        '\n')
                if getattr(AdminStatus, data.get('adstatus', ""), ""):
                    update_admin['ADstatus'] = getattr(
                        AdminStatus, data.get('adstatus')).value
                    action_list.append(
                        str(AdminAction.ADstatus.value) + '为' +
                        getattr(AdminStatus, data.get('adstatus')).zh_value +
                        '\n')
            else:
                filter_adid = admin.ADid
            self.__check_adname(data.get("adname"), filter_adid)

            update_admin = {
                k: v
                for k, v in update_admin.items() if v or v == 0
            }
            update_result = Admin.query.filter(
                Admin.ADid == filter_adid,
                Admin.isdelete == false()).update(update_admin)
            if not update_result:
                raise ParamsError('管理员不存在')
            filter_admin = Admin.query.filter(
                Admin.isdelete == false(),
                Admin.ADid == filter_adid).first_('管理员不存在')

            action_str = admin.ADname + '修改' + filter_admin.ADname + ','.join(
                action_list)

            an_instance = AdminNotes.create({
                'ANid': str(uuid.uuid1()),
                'ADid': filter_adid,
                'ANaction': action_str,
                "ANdoneid": request.user.id
            })
            db.session.add(an_instance)
        # if is_admin():
        #     self.base_admin.create_action(AdminActionS.insert.value, 'AdminNotes', str(uuid.uuid1()))
        return Success("操作成功")
Ejemplo n.º 13
0
    def add_admin_by_superadmin(self):
        """超级管理员添加普通管理"""
        superadmin = get_current_admin()
        if superadmin.ADlevel != AdminLevel.super_admin.value or \
                superadmin.ADstatus != AdminStatus.normal.value:
            raise AuthorityError('当前非超管权限')

        data = request.json
        current_app.logger.info("add admin data is %s" % data)
        parameter_required(('adname', 'adpassword', 'adtelphone'))
        adid = str(uuid.uuid1())
        password = data.get('adpassword')
        # 密码校验
        self.__check_password(password)

        adname = data.get('adname')
        adlevel = getattr(AdminLevel, data.get('adlevel', ''))
        adlevel = 2 if not adlevel else int(adlevel.value)
        header = data.get('adheader') or GithubAvatarGenerator().save_avatar(
            adid)
        # 等级校验
        if adlevel not in [1, 2, 3]:
            raise ParamsError('adlevel参数错误')
        telephone = data.get('adtelphone')
        if not re.match(r'^1[0-9]{10}$', str(telephone)):
            raise ParamsError('手机号格式错误')
        # 账户名校验
        self.__check_adname(adname, adid)
        adnum = self.__get_adnum()
        # 创建管理员
        with db.auto_commit():
            adinstance = Admin.create({
                'ADid':
                adid,
                'ADnum':
                adnum,
                'ADname':
                adname,
                'ADtelephone':
                telephone,
                'ADfirstpwd':
                password,
                'ADfirstname':
                adname,
                'ADpassword':
                generate_password_hash(password),
                'ADheader':
                header,
                'ADlevel':
                adlevel,
                'ADstatus':
                0,
            })
            db.session.add(adinstance)

            # 创建管理员变更记录
            an_instance = AdminNotes.create({
                'ANid':
                str(uuid.uuid1()),
                'ADid':
                adid,
                'ANaction':
                '{0} 创建管理员{1} 等级{2}'.format(superadmin.ADname, adname,
                                            adlevel),
                "ANdoneid":
                request.user.id
            })

            db.session.add(an_instance)
        return Success('创建管理员成功')
Ejemplo n.º 14
0
    def mini_program_login(self):
        args = request.json
        code = args.get("code")
        info = args.get("info")
        current_app.logger.info('info: {}'.format(info))
        userinfo = info.get('userInfo')
        if not userinfo:
            raise TokenError

        mplogin = WeixinLogin(MiniProgramAppId, MiniProgramAppSecret)
        try:
            get_data = mplogin.jscode2session(code)
            current_app.logger.info(
                'get_code2session_response: {}'.format(get_data))
            session_key = get_data.get('session_key')
            openid = get_data.get('openid')
            unionid = get_data.get('unionid')
        except Exception as e:
            current_app.logger.error('mp_login_error : {}'.format(e))
            raise WXLoginError
        if not unionid or not openid:
            current_app.logger.info('pre get unionid: {}'.format(unionid))
            current_app.logger.info('pre get openid: {}'.format(openid))
            encrypteddata = info.get('encryptedData')
            iv = info.get('iv')
            try:
                encrypted_user_info = self._decrypt_encrypted_user_data(
                    encrypteddata, session_key, iv)
                unionid = encrypted_user_info.get('unionId')
                openid = encrypted_user_info.get('openId')
                current_app.logger.info(
                    'encrypted_user_info: {}'.format(encrypted_user_info))
            except Exception as e:
                current_app.logger.error('用户信息解密失败: {}'.format(e))

        current_app.logger.info('get unionid is {}'.format(unionid))
        current_app.logger.info('get openid is {}'.format(openid))
        user = self._get_exist_user((User.USopenid == openid, ))
        if user:
            current_app.logger.info('get exist user by openid: {}'.format(
                user.__dict__))
        elif unionid:
            user = self._get_exist_user((User.USunionid == unionid, ))
            if user:
                current_app.logger.info('get exist user by unionid: {}'.format(
                    user.__dict__))

        head = self._get_local_head(userinfo.get("avatarUrl"), openid)
        current_app.logger.info('get head = {}'.format(head))
        sex = userinfo.get('gender')
        sex = int(sex) if str(sex) in '12' else 0

        user_update_dict = {
            'USheader': head,
            'USname': userinfo.get('nickName'),
            'USopenid': openid,
            'USgender': sex,
            'USunionid': unionid
        }
        with db.auto_commit():

            if user:
                usid = user.USid

                user.update(user_update_dict)
            else:
                current_app.logger.info('This is a new guy : {}'.format(
                    userinfo.get('nickName')))

                usid = str(uuid.uuid1())

                user = User.create({
                    'USid': usid,
                    'USname': userinfo.get('nickName'),
                    'USgender': sex,
                    'USheader': head,
                    'USlevel': 1,
                    'USopenid': openid,
                    'USunionid': unionid,
                })
            db.session.add(user)
            db.session.flush()

            userloggintime = UserLoginTime.create({
                "ULTid": str(uuid.uuid1()),
                "USid": usid,
                "USTip": request.remote_addr
            })
            useragent = _get_user_agent()
            if useragent:
                setattr(userloggintime, 'OSVersion', useragent[0])
                setattr(userloggintime, 'PhoneModel', useragent[1])
                setattr(userloggintime, 'WechatVersion', useragent[2])
                setattr(userloggintime, 'NetType', useragent[3])
                setattr(userloggintime, 'UserAgent', useragent[4])
            db.session.add(userloggintime)

        token = usid_to_token(user.USid,
                              level=user.USlevel,
                              username=user.USname)
        binded_phone = True if user and user.UStelphone else False
        inwhitelist = bool(user and user.USinWhiteList)
        data = {
            'token': token,
            'binded_phone': binded_phone,
            'inwhitelist': inwhitelist,
            'session_key': session_key
        }
        current_app.logger.info('return_data : {}'.format(data))
        return Success('登录成功', data=data)
Ejemplo n.º 15
0
    def calculation(self):
        """通过参数计算价格"""
        if not is_user():
            raise AuthorityError

        user = get_current_user()
        if not user.USinWhiteList:
            raise AuthorityError

        data = parameter_required(('prid', 'params'))
        prid = data.get('prid')
        product = Product.query.filter(
            Product.PRid == prid, Product.isdelete == false()).first_('商品已删除')
        params = data.get('params')
        # 参数分析
        wide = 0
        high = 0
        area = 0
        pillarshigh = 0
        perimeter = 0
        minner = 0
        ppvidlist = []
        try:
            for param in params:
                if param.get('ppvid'):
                    ppvidlist.append(param.get('ppvid'))
                pptype = int(param.get('pptype'))
                if pptype == ProductParamsType.wide.value:
                    wide = Decimal(param.get('value'))
                elif pptype == ProductParamsType.high.value:
                    high = Decimal(param.get('value'))
                elif pptype == ProductParamsType.pillarshigh.value:
                    pillarshigh = Decimal(param.get('value'))
        except:
            raise ParamsError('参数异常')

        area = wide * high
        perimeter = 2 * (wide + high)
        minner = min(wide, high)

        # 获取价格系数
        ul = UserLevelSetting.query.filter(
            UserLevelSetting.ULSlevel == user.USlevel,
            UserLevelSetting.isdelete == false()).first()
        coefficient = Decimal(ul.ULScoefficient if ul else 1)
        # 先计算固定成本
        filter_proudct = [
            or_(and_(Unit.PRid == product.PRid, ),
                Unit.PRid == None), Unit.PCid == product.PCid,
            Unit.isdelete == false(), UnitCategory.isdelete == false()
        ]
        import configparser
        conf = configparser.ConfigParser()
        conf_path = os.path.join(BASEDIR, 'inquiry', 'config',
                                 'lightprice.cfg')

        conf.read(conf_path)
        subway = conf.get('subway', 'subway')
        if product.PRid == subway:
            filter_proudct.append(Unit.UNtype == UnitType.metro.value)

        # 成本
        cost = Decimal('0')
        cost_item_list = []
        # unlist = Unit.query.join(UnitCategory, UnitCategory.UCid == Unit.UCid).filter(*filter_proudct,
        #                                                                               Unit.UCrequired == True).all()
        # for un in unlist:
        #     cost += self._add_price(cost, cost_item_list, un, coefficient)
        # 计算除人工费的其他费用
        unlist = Unit.query.join(UnitCategory,
                                 UnitCategory.UCid == Unit.UCid).filter(
                                     *filter_proudct,
                                     Unit.UNtype != UnitType.cost.value,
                                     Unit.UNtype != UnitType.mount.value,
                                     or_(Unit.PPVid == None,
                                         Unit.PPVid.in_(ppvidlist))).order_by(
                                             UnitCategory.UCsort.desc(),
                                             Unit.UNtype.asc(),
                                             Unit.UNlimit.asc()).all()

        for un in unlist:
            if un.UCrequired == True:
                if un.UNtype:
                    if un.UNtype == UnitType.wide.value:
                        if not self._check_limit(wide, un):
                            continue
                    elif un.UNtype == UnitType.high.value:
                        if not self._check_limit(high, un):
                            continue
                    elif un.UNtype == UnitType.pillarshigh.value:
                        if not self._check_limit(pillarshigh, un):
                            continue
                    elif un.UNtype == UnitType.perimeter.value:
                        if not self._check_limit(perimeter, un):
                            continue
                    elif un.UNtype == UnitType.area.value:
                        if not self._check_limit(area, un):
                            continue
                    elif un.UNtype == UnitType.alarea.value:
                        if not self._check_limit(area, un):
                            continue
                    elif un.UNtype == UnitType.minner.value:
                        if not self._check_limit(minner, un):
                            continue

                cost += self._add_price(cost, cost_item_list, un, coefficient)
                continue
            if un.UNtype == UnitType.wide.value:
                if self._check_limit(wide, un):
                    cost += self._add_price(cost, cost_item_list, un,
                                            coefficient, wide)
                continue
            elif un.UNtype == UnitType.high.value:
                if self._check_limit(high, un):
                    cost += self._add_price(cost, cost_item_list, un,
                                            coefficient, high)
                continue
            elif un.UNtype == UnitType.pillarshigh.value:
                if self._check_limit(pillarshigh, un):
                    cost += self._add_price(cost, cost_item_list, un,
                                            coefficient, pillarshigh)
                continue
            elif un.UNtype == UnitType.perimeter.value:
                if self._check_limit(perimeter, un):
                    cost += self._add_price(cost, cost_item_list, un,
                                            coefficient, perimeter)
                continue
            elif un.UNtype == UnitType.area.value:
                if self._check_limit(area, un):
                    cost += self._add_price(cost, cost_item_list, un,
                                            coefficient, area)
                continue
            elif un.UNtype == UnitType.alarea.value:
                if self._check_limit(area, un):
                    cost += self._add_price(cost, cost_item_list, un,
                                            coefficient, perimeter)
            elif un.UNtype == UnitType.minner.value:
                if self._check_limit(minner, un):
                    cost += self._add_price(cost, cost_item_list, un,
                                            coefficient, minner)
                continue
            else:
                cost += self._add_price(cost, cost_item_list, un, coefficient)
                continue
        # 计算电源费用 todo 限制产品
        if wide and high:
            cost += self._caculate_power(ppvidlist, wide, high, cost_item_list,
                                         coefficient, conf)
        # 计算人工费等依赖成本的费用
        unlist = Unit.query.join(UnitCategory,
                                 UnitCategory.UCid == Unit.UCid).filter(
                                     *filter_proudct,
                                     Unit.UNtype == UnitType.cost.value,
                                     or_(Unit.PPVid == None,
                                         Unit.PPVid.in_(ppvidlist))).order_by(
                                             Unit.UNtype.asc(),
                                             Unit.UNlimit.asc()).all()
        # mount = Decimal(0)
        ex_cost = Decimal(0)

        current_app.logger.info('get cost = {}'.format(cost))
        for un in unlist:
            ex_cost += self._add_ex_cost(cost, cost_item_list, un, coefficient)
        current_app.logger.info('get ex cost = {}'.format(ex_cost))
        mount = cost + ex_cost
        current_app.logger.info('get mount = {}'.format(mount))

        # 计算 依赖总额的费用
        unlist = Unit.query.join(UnitCategory,
                                 UnitCategory.UCid == Unit.UCid).filter(
                                     *filter_proudct,
                                     Unit.UNtype == UnitType.mount.value,
                                     or_(Unit.PPVid == None,
                                         Unit.PPVid.in_(ppvidlist))).order_by(
                                             Unit.UNtype.asc(),
                                             Unit.UNlimit.asc()).all()

        final_mount = mount
        for un in unlist:
            final_mount += self._add_ex_cost(mount, cost_item_list, un,
                                             coefficient)

        current_app.logger.info('get final_mount = {}'.format(final_mount))

        cost_item_list.append(('合计', '', '', '', '', final_mount))
        # 建立表格 todo
        filepath, filename = self._create_table(cost_item_list)
        cost_dict_list = [{
            'ucname': item[0],
            'unname': item[1],
            'ununit': "{} * {}".format(item[2], item[4]),
            'ununitprice': item[3],
            'mount': item[5]
        } for item in cost_item_list]

        # 创建查询记录
        with db.auto_commit():
            uh = UserHistory.create({
                "UHid":
                str(uuid.uuid1()),
                "USid":
                user.USid,
                "UHparams":
                json.dumps(params, cls=JSONEncoder),
                "PRid":
                prid,
                "UHprice":
                final_mount,
                "UHcost":
                json.dumps(cost_dict_list, cls=JSONEncoder),
                "UHfile":
                filename,
                "UHabs":
                filepath,
            })
            db.session.add(uh)
        return Success('询价成功', data={"mount": mount, "uhid": uh.UHid})
Ejemplo n.º 16
0
    def set_un(self):
        admin = get_current_admin()
        data = parameter_required()
        unid, ucid, unname, prid, ucrequired, ununit, ununitprice, untype, unlimit, unlimitmin, pcid, ppvid, unexnum = data.get(
            'unid'), data.get('ucid'), data.get('unname'), data.get(
                'prid'), data.get('ucrequired'), data.get('ununit'), data.get(
                    'ununitprice'), data.get('untype'), data.get(
                        'unlimit'), data.get('unlimitmin'), data.get(
                            'pcid'), data.get('ppvid'), data.get('unexnum')
        undict = {}
        if unname:
            undict['UNname'] = unname
        if ucid:
            uc = UnitCategory.query.filter(
                UnitCategory.UCid == ucid,
                UnitCategory.isdelete == false()).first_('分类已删除')
        undict['UCid'] = ucid
        if prid:
            product = Product.query.filter(
                Product.PRid == prid,
                Product.isdelete == false()).first_('商品已删除')
        undict['PRid'] = prid
        if pcid:
            pc = ProductCategory.query.filter(
                ProductCategory.PCid == pcid,
                ProductCategory.isdelete == false()).first_("商品分类已删除")
        undict['PCid'] = pcid
        if ununit:
            undict['UNunit'] = ununit
        if ppvid:
            ppv = ProductParamsValue.query.filter(
                ProductParamsValue.PPVid == ppvid,
                ProductParamsValue.isdelete == false()).first_('参数值已删除')
        undict['PPVid'] = ppvid
        if ununitprice:
            try:
                ununitprice = Decimal(ununitprice)
            except:
                raise ParamsError('单价只能是数字')
            undict['UNunitPrice'] = ununitprice
        if untype:
            try:
                untype = UnitType(int(untype)).value
            except:
                raise ParamsError('参数类型有误')
        undict['UNtype'] = untype or 0
        if unlimit:
            try:
                unlimit = Decimal(unlimit)
            except:
                raise ParamsError('最大值只能是数字')
        undict['UNlimit'] = unlimit or 0
        if unlimitmin:
            try:
                unlimitmin = Decimal(unlimitmin)
            except:
                raise ParamsError('最小值只能是数字')
            undict['UNlimitMin'] = unlimitmin or 0
        undict['UCrequired'] = bool(ucrequired)
        if unexnum:
            try:
                ununitprice = Decimal(unexnum)
            except:
                raise ParamsError('倍数系数只能是数字')
            undict['UNexnum'] = unexnum

        with db.auto_commit():
            if not unid:
                if not unname:
                    raise ParamsError('计算名缺失')
                if not ununitprice:
                    raise ParamsError('单价缺失')
                if not (pcid or prid):
                    raise ParamsError('商品或者商品分类必须指定')
                if not unexnum:
                    undict['UNexnum'] = 1
                undict['UNid'] = str(uuid.uuid1())
                uninstance = Unit.create(undict)
                msg = '添加成功'
            else:
                uninstance = Unit.query.filter(
                    Unit.UNid == unid,
                    Unit.isdelete == false()).first_('部件已删除')
                if data.get('delete'):
                    uninstance.update({'isdelete': True})
                    msg = '删除成功'
                else:
                    uninstance.update(undict, null='not ignore')
                    msg = '更新成功'
            db.session.add(uninstance)
        return Success(message=msg, data={'ucid': uninstance.UNid})
Ejemplo n.º 17
0
    def set_pp(self):
        _ = get_current_admin()

        data = parameter_required()
        ppid, prid, ppname, pprequired, pptype, ppremarks, ppunit, ppsort, ppvlist = data.get(
            'ppid'), data.get('prid'), data.get('ppname'), data.get(
                'pprequired'), data.get('pptype'), data.get(
                    'ppremarks'), data.get('ppunit'), data.get(
                        'ppsort'), data.get('ppvlist', [])
        pp_dict = {}
        if ppname:
            pp_dict['PPname'] = ppname
        if prid:
            _ = Product.query.filter(
                Product.PRid == prid,
                Product.isdelete == false()).first_('商品已删除')
            pp_dict['PRid'] = prid
        # if pprequired:
        pp_dict['PPrequired'] = bool(pprequired)
        if ppsort:
            try:
                ppsort = int(ppsort)
            except:
                raise ParamsError('权重只能是整数')
            pp_dict['PPsort'] = ppsort
        if pptype:
            try:
                pptype = ProductParamsType(int(pptype)).value
            except:
                raise ParamsError('类型有误')
            pp_dict['PPtype'] = pptype
        # if ppunit:
        pp_dict['PPunit'] = ppunit
        if ppremarks:
            pp_dict['PPremarks'] = ppremarks

        with db.auto_commit():
            if not ppid:
                # if not prid:
                #     raise ParamsError('需绑定产品')
                if not ppname:
                    raise ParamsError('缺少参数名')
                if not pptype:
                    raise ParamsError('缺少参数类型')
                pp_dict['PPid'] = str(uuid.uuid1())
                pp = ProductParams.create(pp_dict)
                msg = '添加成功'
            else:
                pp = ProductParams.query.filter(
                    ProductParams.PPid == ppid,
                    ProductParams.isdelete == false()).first_('参数已删除')

                if data.get('delete'):
                    pp.update({'isdelete': True})
                    msg = '删除成功'
                else:
                    pp.update(pp_dict, null='not ignore')
                    msg = '编辑成功'

            db.session.add(pp)
            if isinstance(ppvlist, list):
                # ProductParamsValue.query.filter(ProductParams.PPid == pp.PPid).delete_()
                ppvidlist = []
                instance_list = []
                for ppv in ppvlist:
                    ppvvalue = ppv.get('ppvvalue')
                    ppvprice = ppv.get('ppvprice', 0)
                    ppvid = ppv.get('ppvid')
                    if ppvprice:
                        try:
                            ppvprice = Decimal(str(ppvprice))
                        except:
                            raise ParamsError('单价只能是数字')
                    ppvdict = {
                        'PPid': pp.PPid,
                        "PPVvalue": ppvvalue,
                        "PPVprice": ppvprice
                    }
                    if ppvid:
                        ppv_instance = ProductParamsValue.query.filter(
                            ProductParamsValue.PPVid == ppvid,
                            ProductParamsValue.isdelete == false()).first()
                        if ppv_instance:
                            ppv_instance.update(ppvdict)
                        else:
                            ppvdict.setdefault('PPVid', str(uuid.uuid1()))
                            ppv_instance = ProductParamsValue.create(ppvdict)
                    else:
                        ppvdict.setdefault('PPVid', str(uuid.uuid1()))
                        ppv_instance = ProductParamsValue.create(ppvdict)
                    frontids = ppv.get('frontid', [])
                    if isinstance(frontids, list):
                        fpids = []
                        for frontid in frontids:
                            front = ProductParams.query.filter(
                                ProductParams.PPid == frontid).first_(
                                    "后续参数已删除")
                            fp_instance = FrontParams.query.filter(
                                FrontParams.PPid == front.PPid,
                                FrontParams.PPVid == ppv_instance.PPVid,
                                FrontParams.isdelete == false()).first()
                            if not fp_instance:
                                fp_instance = FrontParams.create({
                                    "FPid":
                                    str(uuid.uuid1()),
                                    "PPid":
                                    front.PPid,
                                    "PPVid":
                                    ppv_instance.PPVid,
                                })
                                instance_list.append(fp_instance)
                            fpids.append(fp_instance.FPid)
                            front.PRid = ""
                            instance_list.append(front)

                        unused_fp = FrontParams.query.filter(
                            FrontParams.PPVid == ppv_instance.PPVid,
                            FrontParams.FPid.notin_(fpids),
                            FrontParams.isdelete == false()).all()
                        # 删除无用绑定
                        for fp in unused_fp:
                            unused_pp = ProductParams.query.filter(
                                ProductParams.PPid == fp.PPid,
                                ProductParams.isdelete == false()).first()
                            if unused_pp:
                                unused_pp.PRid = pp.PRid
                                instance_list.append(unused_pp)
                            fp.isdelete = True
                            instance_list.append(fp)

                    ppvidlist.append(ppv_instance.PPVid)
                    instance_list.append(ppv_instance)
                db.session.add_all(instance_list)
                unused_ppv = ProductParamsValue.query.filter(
                    ProductParamsValue.PPid == pp.PPid,
                    ProductParamsValue.PPVid.notin_(ppvidlist)).all()
                ProductParamsValue.query.filter(
                    ProductParamsValue.PPid == pp.PPid,
                    ProductParamsValue.PPVid.notin_(ppvidlist)).delete_(
                        synchronize_session=False)

        return Success(message=msg, data={'ppid': pp.PPid})