Beispiel #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})
Beispiel #2
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))
Beispiel #3
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('账号已被回收')
Beispiel #4
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)
Beispiel #5
0
 def __check_password(self, password):
     if not password or len(password) < 4:
         raise ParamsError('密码长度低于4位')
     zh_pattern = re.compile(r'[\u4e00-\u9fa5]+')
     match = zh_pattern.search(password)
     if match:
         raise ParamsError(u'密码包含中文字符')
     return True
Beispiel #6
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)
Beispiel #7
0
 def __check_adname(self, adname, adid):
     """账户名校验"""
     if not adname or adid:
         return True
     suexist = Admin.query.filter_by(ADname=adname, isdelete=False).first()
     if suexist and suexist.ADid != adid:
         raise ParamsError('用户名已存在')
     return True
Beispiel #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})
Beispiel #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})
Beispiel #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})
Beispiel #11
0
 def _check_time(self, check_time):
     if not check_time:
         return
     # 日期校验
     if not isinstance(check_time, datetime):
         try:
             check_time = datetime.strptime(str(check_time),
                                            format_for_web_second)
         except:
             raise ParamsError(
                 '日期格式不对,具体格式为{}'.format(format_for_web_second))
     return check_time
Beispiel #12
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))
Beispiel #13
0
    def __check_identifyingcode(self, ustelphone, identifyingcode):
        """验证码校验"""
        # identifyingcode = str(data.get('identifyingcode'))
        if not ustelphone or not identifyingcode:
            raise ParamsError("验证码/手机号缺失")
        idcode = IdentifyingCode.query.filter(
            IdentifyingCode.ICtelphone == ustelphone,
            IdentifyingCode.isdelete == False).order_by(
                IdentifyingCode.createtime.desc()).first_()

        if not idcode or str(idcode.ICcode) != identifyingcode:
            current_app.logger.info(
                'get identifyingcode ={0} get idcode = {1}'.format(
                    identifyingcode, idcode.ICcode))
            raise ParamsError('验证码有误')

        timenow = datetime.now()
        if (timenow - idcode.createtime).seconds > 600:
            current_app.logger.info('get timenow ={0}, sendtime = {1}'.format(
                timenow, idcode.createtime))
            raise ParamsError('验证码已经过期')
        return True
Beispiel #14
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)
Beispiel #15
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)
Beispiel #16
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)
Beispiel #17
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("用户名或密码错误")
Beispiel #18
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)
Beispiel #19
0
    def _upload_file(self, file, folder):
        filename = file.filename
        shuffix = os.path.splitext(filename)[-1]
        current_app.logger.info(">>>  Upload File Shuffix is {0}  <<<".format(shuffix))
        shuffix = shuffix.lower()
        if self.allowed_file(shuffix):
            img_name = self.new_name(shuffix)
            time_now = datetime.now()
            year = str(time_now.year)
            month = str(time_now.month)
            day = str(time_now.day)
            newPath = os.path.join(current_app.config['BASEDIR'], 'img', folder, year, month, day)
            if not os.path.isdir(newPath):
                os.makedirs(newPath)
            newFile = os.path.join(newPath, img_name)
            file.save(newFile)  # 保存图片
            data = '/img/{folder}/{year}/{month}/{day}/{img_name}'.format(folder=folder, year=year,
                                                                          month=month, day=day,
                                                                          img_name=img_name)
            if shuffix in ['.mp4', '.avi', '.wmv', '.mov', '.3gp', '.flv', '.mpg']:
                upload_type = 'video'
                # 生成视频缩略图
                thum_origin_name = img_name.split('.')[0]
                thum_name = video2frames(newFile, newPath, output_prefix=thum_origin_name,
                                         extract_time_points=(2,), jpg_quality=80)
                video_thum = '/img/{}/{}/{}/{}/{}'.format(folder, year, month, day,
                                                          thum_name.get('thumbnail_name_list')[0])
                dur_second = int(thum_name.get('video_duration', 0))
                minute = dur_second // 60
                second = dur_second % 60
                minute_str = '0' + str(minute) if minute < 10 else str(minute)
                second_str = '0' + str(second) if second < 10 else str(second)
                video_dur = minute_str + ':' + second_str

                if current_app.config.get('IMG_TO_OSS'):
                    try:
                        qiniu_oss.save(data=newFile, filename=data[1:])
                    except Exception as e:
                        current_app.logger.error(">>>  视频上传到七牛云出错 : {}  <<<".format(e))
                        raise ParamsError('上传视频失败,请稍后再试')

                video_thumbnail_path = os.path.join(newPath, thum_name.get('thumbnail_name_list')[0])

                if current_app.config.get('IMG_TO_OSS'):
                    try:
                        qiniu_oss.save(data=video_thumbnail_path, filename=video_thum[1:])
                    except Exception as e:
                        current_app.logger.error(">>>  视频预览图上传到七牛云出错 : {}  <<<".format(e))
            else:
                upload_type = 'image'
                video_thum = ''
                video_dur = ''

                # 读取
                # img = Image.open(thumbnail_img)
                # img_size = '_' + 'x'.join(map(str, img.size))
                # path_with_size = thumbnail_img + img_size + shuffix
                # data += (img_size + shuffix)
                # img.save(path_with_size)
                # os.remove(newFile)

                # 生成压缩图
                try:
                    thumbnail_img = CompressPicture().resize_img(ori_img=newFile, ratio=0.8, save_q=80)
                except Exception as e:
                    current_app.logger.info(">>>  Resize Picture Error : {}  <<<".format(e))
                    raise ParamsError('图片格式错误,请检查后重新上传(请勿强制更改图片后缀名)')
                data += '_' + thumbnail_img.split('_')[-1]
                # 上传到七牛云,并删除本地压缩图
                if current_app.config.get('IMG_TO_OSS'):
                    try:
                        qiniu_oss.save(data=thumbnail_img, filename=data[1:])
                        # os.remove(str(newFile + '_' + thumbnail_img.split('_')[-1]))
                    except Exception as e:
                        current_app.logger.error(">>>  图片上传到七牛云出错 : {}  <<<".format(e))
                        raise ParamsError('上传图片失败,请稍后再试')
            current_app.logger.info(">>>  Upload File Path is  {}  <<<".format(data))
            return data, video_thum, video_dur, upload_type
        else:
            raise SystemError(u'上传有误, 不支持的文件类型 {}'.format(shuffix))
Beispiel #20
0
 def check_file_size(self):
     max_file_size = 100 * 1024 * 1024
     upload_file_size = request.content_length
     current_app.logger.info(">>>  Upload File Size is {0} MB <<<".format(round(upload_file_size / 1048576, 2)))
     if upload_file_size > max_file_size:
         raise ParamsError("上传文件过大,请上传小于100MB的文件")
Beispiel #21
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})
Beispiel #22
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})
Beispiel #23
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})
Beispiel #24
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('创建管理员成功')
Beispiel #25
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("操作成功")