示例#1
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}')
示例#2
0
    def list(self):
        data = parameter_required()
        filter_args = [
            Product.isdelete == false(), ProductCategory.isdelete == false()
        ]
        if is_admin():
            _ = get_current_admin()
        elif is_user():
            user = get_current_user()
            if not user.USinWhiteList:
                raise AuthorityError('用户无权限,请联系管理员')
        else:
            raise AuthorityError

        pcid = data.get('pcid')
        prname = data.get('prname')
        if pcid:
            filter_args.append(Product.PCid == pcid)
        if prname:
            filter_args.append(Product.PRname.ilike('%{}%'.format(prname)))
        product_list = Product.query.join(
            ProductCategory, ProductCategory.PCid == Product.PCid).filter(
                *filter_args).order_by(
                    Product.PRsort.desc(),
                    Product.createtime.desc()).all_with_page()
        for product in product_list:
            self._fill_pcname(product)
        return Success('获取成功', data=product_list)
示例#3
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)
示例#4
0
    def useristory(self):
        """用户查询记录"""
        data = parameter_required()
        usname, ustelphone, starttime, endtime = data.get('usname'), data.get(
            'ustelphone'), data.get('starttime'), data.get('endtime')

        filter_args = []
        if is_user():
            user = get_current_user()
            filter_args.append(User.USid == user.USid)
        if usname:
            filter_args.append(User.USname.ilike("%{}%".format(usname)))
        if ustelphone:
            filter_args.append(
                (User.UStelphone.ilike("%{}%".format(ustelphone))))

        starttime = self._check_time(starttime)
        endtime = self._check_time(endtime)
        if starttime:
            filter_args.append(UserHistory.createtime >= starttime)
        if endtime:
            filter_args.append(UserHistory.createtime <= endtime)

        uhlist = UserHistory.query.join(
            User, User.USid == UserHistory.USid).filter(*filter_args).order_by(
                UserHistory.createtime.desc()).all_with_page()
        productdict = {}
        product_list = Product.query.join(
            UserHistory, UserHistory.PRid == Product.PRid).filter(
                Product.isdelete == false(),
                UserHistory.isdelete == false()).all()
        for product in product_list:
            productdict[product.PRid] = product.PRname

        user_list = User.query.join(UserHistory,
                                    UserHistory.USid == User.USid).filter(
                                        User.isdelete == false(),
                                        UserHistory.isdelete == false()).all()
        user_dict = {user_item.USid: user_item for user_item in user_list}
        for uh in uhlist:
            uh.add("createtime")
            uh.fill('prname', productdict.get(uh.PRid))
            user_item = user_dict.get(uh.USid)
            uh.fill('usname', user_item.USname)
            uh.fill('ustelphone', user_item.UStelphone)
            uh.fill('uhparams', json.loads(uh.UHparams))
            uh.fill('uhcost', json.loads(uh.UHcost or '[]'))
        return Success("获取查询记录成功", data=uhlist)
示例#5
0
    def get(self):
        if is_admin():
            _ = get_current_admin()
        elif is_user():
            user = get_current_user()
            if not user.USinWhiteList:
                raise AuthorityError('用户无权限,请联系管理员')
        else:
            raise AuthorityError

        data = parameter_required(('prid', ))
        prid = data.get('prid')
        product = Product.query.join(
            ProductCategory, ProductCategory.PCid == Product.PCid).filter(
                Product.PRid == prid, Product.isdelete == false(),
                ProductCategory.isdelete == false()).first_("产品已删除")
        self._fill_pcname(product)
        return Success('获取成功', data=product)
示例#6
0
    def download(self):
        """导出"""
        data = parameter_required(('uhid', ))
        uhid = data.get('uhid')
        uh = UserHistory.query.filter(
            UserHistory.UHid == uhid,
            UserHistory.isdelete == false()).first_('查询记录已删除')

        if is_user():
            uhcost = json.loads(uh.UHcost)
            return Success('获取成功', data=uhcost)

        filepath, filename = uh.UHabs, uh.UHfile,
        if not os.path.isfile(os.path.join(filepath, filename)):
            raise ParamsError('报表未能成功导出')
        return send_from_directory(filepath,
                                   filename,
                                   as_attachment=True,
                                   cache_timeout=-1)
示例#7
0
 def list_pp(self):
     data = parameter_required(('prid', ))
     if is_admin():
         _ = get_current_admin()
     elif is_user():
         user = get_current_user()
         if not user.USinWhiteList:
             raise AuthorityError('用户无权限,请联系管理员')
     else:
         raise AuthorityError
     prid = data.get('prid')
     product = Product.query.filter(
         Product.PRid == prid, Product.isdelete == false()).first_('产品已删除')
     pplist = ProductParams.query.filter(
         ProductParams.PRid == prid,
         ProductParams.isdelete == false()).order_by(
             ProductParams.PPsort.desc(),
             ProductParams.createtime.desc()).all()
     for pp in pplist:
         pp.fill('prname', product.PRname)
         # 产品参数填充
         self._fill_ppv(pp)
     return Success('获取成功', data=pplist)
示例#8
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})