예제 #1
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})
예제 #2
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('账号已被回收')
예제 #3
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))
예제 #4
0
    def get_userlevelsetting(self):
        admin = get_current_admin()
        usllist = UserLevelSetting.query.filter(
            UserLevelSetting.isdelete == false()).order_by(
                UserLevelSetting.ULSlevel.desc()).all()

        return Success('获取成功', data=usllist)
예제 #5
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})
예제 #6
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)
예제 #7
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)
예제 #8
0
 def get_uc(self):
     admin = get_current_admin()
     data = parameter_required(('ucid'), )
     uc = UnitCategory.query.filter(
         UnitCategory.UCid == data.get('ucid'),
         UnitCategory.isdelete == false()).first_('分类已删除')
     self._fill_uc(uc)
     return Success('获取成功', data=uc)
예제 #9
0
 def list_uc(self):
     admin = get_current_admin()
     uclist = UnitCategory.query.filter(
         UnitCategory.isdelete == false()).order_by(
             UnitCategory.UCsort.desc(),
             UnitCategory.createtime.desc()).all_with_page()
     for uc in uclist:
         self._fill_uc(uc)
     return Success('获取成功', data=uclist)
예제 #10
0
 def list_mp_banner(self):
     """小程序轮播图获取"""
     filter_args = [Banner.isdelete == false(), ]
     if not is_admin():
         filter_args.append(Banner.BNshow == true())
     mpbs = Banner.query.filter(*filter_args).order_by(Banner.BNsort.desc(),
                                                       Banner.createtime.desc()).all()
     [x.hide('ADid') for x in mpbs]
     return Success(data=mpbs)
예제 #11
0
 def test_login():
     """测试登录"""
     data = parameter_required()
     tel = data.get('ustelphone')
     user = User.query.filter(User.isdelete == false(),
                              User.UStelphone == tel).first()
     if not user:
         raise NotFound
     token = usid_to_token(user.USid, model='User', username=user.USname)
     return Success(data={'token': token, 'usname': user.USname})
예제 #12
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)
예제 #13
0
 def remove(self):
     data = parameter_required(('img_url',))
     try:
         img_url = data.get('img_url')
         dirs = img_url.split('/')[-6:]
         name_shuffer = dirs[-1]
         name = name_shuffer.split('.')[0]
         if not 'anonymous' in name and request.user.id not in name:
             raise NotFound()
         path = os.path.join(current_app.config['BASEDIR'], '/'.join(dirs))
         os.remove(path)
     except Exception as e:
         raise NotFound()
     return Success(u'删除成功')
예제 #14
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)
예제 #15
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})
예제 #16
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})
예제 #17
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)
예제 #18
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})
예제 #19
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)
예제 #20
0
 def upload_img(self):
     if is_anonymous():
         current_app.logger.info(">>>  Tourist Uploading Files  <<<")
     else:
         current_app.logger.info(">>>  {} Uploading Files  <<<".format(request.user.model))
     self.check_file_size()
     file = request.files.get('file')
     data = parameter_required()
     if not data:
         data = request.form
         current_app.logger.info('form : {}'.format(data))
     current_app.logger.info('type is {}'.format(data.get('type')))
     folder = self.allowed_folder(data.get('type'))
     if not file:
         raise ParamsError(u'上传有误')
     file_data, video_thum, video_dur, upload_type = self._upload_file(file, folder)
     # return Success('上传成功', data={'url': file_data, 'video_thum': video_thum, 'video_dur': video_dur,
     #                              'upload_type': upload_type})
     file_data = HTTP_HOST + file_data
     return Success('上传成功', data=file_data).get_body(video_thum=video_thum, video_dur=video_dur,
                                                     upload_type=upload_type)
예제 #21
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))
예제 #22
0
 def batch_upload(self):
     if is_anonymous():
         current_app.logger.info(">>>  Tourist Bulk Uploading Files  <<<")
     else:
         current_app.logger.info(">>>  {} Bulk Uploading Files  <<<".format(request.user.model))
     self.check_file_size()
     files = request.files.to_dict()
     current_app.logger.info(">>> Uploading {} Files  <<<".format(len(files)))
     if len(files) > 30:
         raise ParamsError('最多可同时上传30张图片')
     data = parameter_required()
     folder = self.allowed_folder(data.get('type'))
     file_url_list = []
     for file in files.values():
         file_data, video_thum, video_dur, upload_type = self._upload_file(file, folder)
         file_dict = {
             'url': file_data,
             'video_thum': video_thum,
             'video_dur': video_dur,
             'upload_type': upload_type
         }
         file_url_list.append(file_dict)
     return Success('上传成功', file_url_list)
예제 #23
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)
예제 #24
0
    def get_admin_list(self):
        """获取管理员列表"""
        superadmin = get_current_admin()
        if superadmin.ADlevel != AdminLevel.super_admin.value or \
                superadmin.ADstatus != AdminStatus.normal.value:
            raise AuthorityError('当前非超管权限')
        args = request.args.to_dict()
        page = args.get('page_num')
        count = args.get('page_size')
        if page and count:
            admins = Admin.query.filter(
                Admin.isdelete == false(),
                Admin.ADlevel == AdminLevel.common_admin.value).order_by(
                    Admin.createtime.desc()).all_with_page()
        else:
            admins = Admin.query.filter(
                Admin.isdelete == false(),
                Admin.ADlevel == AdminLevel.common_admin.value).order_by(
                    Admin.createtime.desc()).all()
        for admin in admins:
            admin.fields = [
                'ADid', 'ADname', 'ADheader', 'createtime', 'ADnum'
            ]
            admin.fill('adlevel', AdminLevel(admin.ADlevel).zh_value)
            admin.fill('adstatus', AdminStatus(admin.ADstatus).zh_value)
            admin.fill('adpassword', '*' * 6)
            admin.fill('adtelphone', admin.ADtelephone)
            admin_login = UserLoginTime.query.filter_by_(
                USid=admin.ADid,
                ULtype=UserLoginTimetype.admin.value).order_by(
                    UserLoginTime.createtime.desc()).first()
            logintime = None
            if admin_login:
                logintime = admin_login.createtime
            admin.fill('logintime', logintime)

        return Success('获取管理员列表成功', data=admins)
예제 #25
0
    def get_user_list(self):
        admin = get_current_admin()
        if not admin:
            raise AuthorityError
        data = parameter_required()
        ustelphone = data.get('ustelphone')
        usname = data.get('usname')
        uslevel = data.get('uslevel')
        filter_args = [User.isdelete == false()]
        if ustelphone:
            filter_args.append(User.UStelphone.ilike(
                '%{}%'.format(ustelphone)))
        if usname:
            filter_args.append(User.USname.ilike('%{}%'.format(usname)))
        if uslevel or uslevel == 0:
            try:
                uslevel = int(uslevel)
            except Exception:
                raise ParamsError('等级只能是整数')

            filter_args.append(User.USlevel == uslevel)

        user_list = User.query.filter(*filter_args).all_with_page()
        return Success('获取成功', data=user_list)
예제 #26
0
    def admin_login(self):
        """管理员登录"""
        data = parameter_required(('adname', 'adpassword'))
        admin = Admin.query.filter(
            Admin.isdelete == false(),
            Admin.ADname == data.get('adname')).first_('用户不存在')

        # 密码验证
        if admin and check_password_hash(admin.ADpassword,
                                         data.get("adpassword")):
            current_app.logger.info('管理员登录成功 %s' % admin.ADname)
            # 创建管理员登录记录
            ul_instance = UserLoginTime.create({
                "ULTid":
                str(uuid.uuid1()),
                "USid":
                admin.ADid,
                "USTip":
                request.remote_addr,
                "ULtype":
                UserLoginTimetype.admin.value,
                "UserAgent":
                request.user_agent.string
            })
            db.session.add(ul_instance)
            token = usid_to_token(admin.ADid,
                                  'Admin',
                                  admin.ADlevel,
                                  username=admin.ADname)
            admin.fields = ['ADname', 'ADheader', 'ADlevel']

            admin.fill('adlevel', AdminLevel(admin.ADlevel).zh_value)
            admin.fill('adstatus', AdminStatus(admin.ADstatus).zh_value)

            return Success('登录成功', data={'token': token, "admin": admin})
        return ParamsError("用户名或密码错误")
예제 #27
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})
예제 #28
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('创建管理员成功')
예제 #29
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)
예제 #30
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("操作成功")