Beispiel #1
0
    def deal_single_approval(self, data, admin=None, sup=None):
        parameter_required(('avid', 'anaction', 'anabo'), datafrom=data)
        approval_model = Approval.query.filter_by_(
            AVid=data.get('avid'),
            AVstatus=ApplyStatus.wait_check.value).first_('审批已处理')
        if is_admin():
            Permission.query.filter(
                Permission.isdelete == False,
                AdminPermission.isdelete == False,
                Permission.PIid == AdminPermission.PIid,
                AdminPermission.ADid == request.user.id,
                Permission.PTid == approval_model.PTid,
                Permission.PELevel == approval_model.AVlevel).first_('权限不足')
            avadname = admin.ADname
            adid = admin.ADid
        else:
            avadname = sup.SUname
            adid = sup.SUid
        # 审批流水记录
        approvalnote_dict = {
            "ANid": str(uuid.uuid1()),
            "AVid": data.get("avid"),
            "AVadname": avadname,
            "ADid": adid,
            "ANaction": data.get('anaction'),
            "ANabo": data.get("anabo")
        }
        apn_instance = ApprovalNotes.create(approvalnote_dict)
        db.session.add(apn_instance)
        if is_admin():
            BaseAdmin().create_action(AdminActionS.insert.value,
                                      'ApprovalNotes', str(uuid.uuid1()))

        if int(data.get("anaction")) == ApprovalAction.agree.value:
            # 审批操作是否为同意
            pm_model = Permission.query.filter(
                Permission.isdelete == False,
                Permission.PTid == approval_model.PTid,
                Permission.PELevel == int(approval_model.AVlevel) + 1).first()
            if pm_model:
                # 如果还有下一级审批人
                approval_model.AVlevel = str(int(approval_model.AVlevel) + 1)
            else:
                # 没有下一级审批人了
                approval_model.AVstatus = ApplyStatus.agree.value
                self.agree_action(approval_model, data)
        else:
            # 审批操作为拒绝
            approval_model.AVstatus = ApplyStatus.reject.value
            self.refuse_action(approval_model, data.get('anabo'))
Beispiel #2
0
 def list_product(self):
     """商品列表"""
     args = request.args.to_dict()
     filter_args = []
     if not (is_admin() or is_supplizer()):
         filter_args.append(Product.PRstatus.notin_((ProductStatus.interrupt.value, ProductStatus.reject.value,
                                                     ProductStatus.pending.value)))
     if is_supplizer():
         filter_args.append(Product.SUid == getattr(request, 'user').id)
     prlimited = args.get('prtimelimeted')
     if str(prlimited) in '01':
         filter_args.append(Product.PRtimeLimeted == prlimited)
     products = Product.query.filter(Product.isdelete == false(), *filter_args
                                     ).order_by(func.field(Product.PRstatus, ProductStatus.active.value,
                                                           ProductStatus.ready.value, ProductStatus.over.value),
                                                Product.PRissueStartTime.asc(),
                                                Product.createtime.desc()).all_with_page()
     products_fields = ['PRid', 'PRname', 'PRimg', 'PRlinePrice', 'PRtruePrice', 'PRnum', 'PRtimeLimeted',
                        'PRstatus', 'prstatus_zh', 'apply_num', 'PRissueStartTime', 'PRissueEndTime',
                        'PRuseStartTime', 'PRuseEndTime', 'interrupt', 'apply_num_str', 'buyer_avatar',
                        'start_time_str']
     for product in products:
         self._fill_product(product)
         product.fields = products_fields
         if not product.PRtimeLimeted:
             product.PRnum = '无限量'
     return Success(data=products)
Beispiel #3
0
 def create_product(self):
     """创建商品"""
     if is_admin():
         product_from = ProductFrom.platform.value
     elif is_supplizer():
         product_from = ProductFrom.supplizer.value
     else:
         raise AuthorityError('当前用户无权进行该操作')
     data = request.json
     product_dict = self._validate_ticket_param(data)
     if Product.query.filter(Product.isdelete == false(), Product.PRname == data.get('prname')).first():
         raise ParamsError('该商品名称已存在')
     with db.auto_commit():
         product_dict.update({'PRid': str(uuid.uuid1()),
                              'CreatorId': getattr(request, 'user').id,
                              'CreatorType': getattr(request, 'user').model,
                              'PRname': data.get('prname'),
                              'PRimg': data.get('primg'),
                              'PRdetails': data.get('prdetails'),
                              # 'PRstatus': ProductStatus.ready.value if product_dict.get(
                              #     'PRtimeLimeted') else ProductStatus.active.value,
                              'PRstatus': ProductStatus.pending.value
                              })
         product = Product.create(product_dict)
         db.session.add(product)
     # 0702 增加审批
     # if product.PRtimeLimeted:  # 限时商品,添加异步任务
     #     add_async_task(func=start_product, start_time=product.PRissueStartTime, func_args=(product.PRid,),
     #                    conn_id='start_product{}'.format(product.PRid))
     #     add_async_task(func=end_product, start_time=product.PRissueEndTime, func_args=(product.PRid,),
     #                    conn_id='end_product{}'.format(product.PRid))
     self.base_approval.create_approval('toshelves', request.user.id, product.PRid, product_from)
     self.base_admin.create_action(AdminActionS.insert.value, 'Product', product.PRid)
     return Success('创建成功', data={'prid': product.PRid})
Beispiel #4
0
    def update(self):
        """更新供应商信息"""
        if not is_admin() and not is_supplizer():
            raise AuthorityError()
        form = SupplizerUpdateForm().valid_data()
        pbids = form.pbids.data
        with db.auto_commit():
            supplizer = Supplizer.query.filter(
                Supplizer.isdelete == False,
                Supplizer.SUid == form.suid.data).first_('供应商不存在')
            supplizer_dict = {
                'SUlinkPhone': form.sulinkphone.data,
                'SUname': form.suname.data,
                'SUlinkman': form.sulinkman.data,
                'SUaddress': form.suaddress.data,
                'SUbanksn': form.subanksn.data,
                'SUbankname': form.subankname.data,
                # 'SUpassword': generate_password_hash(form.supassword.data),  # 暂时去掉
                'SUheader': form.suheader.data,
                'SUcontract': form.sucontract.data,
                'SUbusinessLicense': form.subusinesslicense.data,
                'SUregisteredFund': form.suregisteredfund.data,
                'SUmainCategory': form.sumaincategory.data,
                # 'SUregisteredTime': form.suregisteredtime.data,
                'SUlegalPerson': form.sulegalperson.data,
                'SUemail': form.suemail.data,
                'SUlegalPersonIDcardFront': form.sulegalpersonidcardfront.data,
                'SUlegalPersonIDcardBack': form.sulegalpersonidcardback.data,
            }
            if is_admin():
                # if form.subaserate.data:
                #     supplizer_dict['SUbaseRate'] = form.subaserate.data,
                if isinstance(form.sustatus.data, int):
                    supplizer_dict['SUstatus'] = form.sustatus.data
                    if form.sustatus.data == UserStatus.usual.value and not supplizer.SUpassword:
                        supplizer_dict['SUpassword'] = generate_password_hash(
                            supplizer.SUloginPhone)

            supplizer.update(supplizer_dict, null='dont ignore')
            db.session.add(supplizer)
            if is_admin():
                self.base_admin.create_action(AdminActionS.update.value,
                                              'Supplizer', form.suid.data)
        return Success('更新成功')
Beispiel #5
0
 def get_approvalnotes(self):
     """查看审批的所有流程"""
     if not (is_admin() or is_supplizer()):
         raise AuthorityError('权限不足')
     data = parameter_required(('avid', ))
     an_list = ApprovalNotes.query.filter_by_(
         AVid=data.get('avid')).order_by(ApprovalNotes.createtime).all()
     for an in an_list:
         an.fill('anaction', ApprovalAction(an.ANaction).zh_value)
     return Success('获取审批记录成功', data=an_list)
Beispiel #6
0
 def change_password(self):
     if not is_supplizer() and not is_admin():
         raise AuthorityError()
     form = SupplizerChangePasswordForm().valid_data()
     old_password = form.oldpassword.data
     supassword = form.supassword.data
     suid = form.suid.data
     with db.auto_commit():
         supplizer = Supplizer.query.filter(
             Supplizer.isdelete == False,
             Supplizer.SUid == suid).first_('不存在的供应商')
         if not is_admin() and not check_password_hash(
                 supplizer.SUpassword, old_password):
             raise AuthorityError('原密码错误')
         supplizer.SUpassword = generate_password_hash(supassword)
         db.session.add(supplizer)
         if is_admin():
             self.base_admin.create_action(AdminActionS.update.value,
                                           'Supplizer', suid)
     return Success('修改成功')
Beispiel #7
0
 def list_mp_banner(self):
     """小程序轮播图获取"""
     filter_args = []
     if not is_admin():
         filter_args.append(MiniProgramBanner.MPBshow == true())
     mpbs = MiniProgramBanner.query.filter(
         MiniProgramBanner.isdelete == false(),
         *filter_args).order_by(MiniProgramBanner.MPBsort.asc(),
                                MiniProgramBanner.createtime.desc()).all()
     [x.hide('ADid') for x in mpbs]
     return Success(data=mpbs)
Beispiel #8
0
    def get_dealing_approval(self):
        """管理员查看自己名下可以处理的审批流 概览"""
        if is_admin():
            admin = Admin.query.filter_by_(
                ADid=request.user.id).first_('管理员账号已被回收')
            if not admin:
                current_app.logger.info('get admin failed id is {0}'.format(
                    admin.ADid))
                raise NotFound("该管理员已被删除")
            # pttype = request.args.to_dict().get('pttypo')
            pt_list = PermissionType.query.filter(
                PermissionType.PTid == Permission.PTid,
                Permission.PIid == AdminPermission.PIid,
                AdminPermission.ADid == admin.ADid,
                PermissionType.isdelete == False,
                AdminPermission.isdelete == False,
                Permission.isdelete == False).order_by(
                    PermissionType.createtime.desc()).all()
            # pi_list = AdminPermission.query.filter_by_(ADid=admin.ADid).all()
            for pt in pt_list:
                ap_num = Approval.query.filter(
                    Approval.PTid == pt.PTid,
                    Approval.AVlevel == Permission.PELevel,
                    Permission.PTid == pt.PTid,
                    Permission.PIid == AdminPermission.PIid,
                    AdminPermission.ADid == admin.ADid,
                    Approval.AVstatus == ApplyStatus.wait_check.value,
                    Approval.isdelete == False, Permission.isdelete == False,
                    AdminPermission.isdelete == False).count()
                pt.fill('approval_num', ap_num)
        elif is_supplizer():
            sup = Supplizer.query.filter_by_(
                SUid=request.user.id).first_('供应商账号已回收')
            pt_list = PermissionType.query.filter(
                PermissionType.PTid == Approval.PTid,
                Approval.AVstartid == sup.SUid,
                Approval.AVstatus == ApplyStatus.wait_check.value,
                PermissionType.isdelete == False,
                Approval.isdelete == False).all()
            if not pt_list:
                pt_list = PermissionType.query.filter_by_(
                    PTid='tointegral').all()
            # todo 供应商的审批类型筛选
            for pt in pt_list:
                ap_num = Approval.query.filter(
                    Approval.AVstartid == sup.SUid, Approval.PTid == pt.PTid,
                    Approval.isdelete == False).count()

                pt.fill('approval_num', ap_num)
        else:
            pt_list = []

        return Success('获取审批流类型成功', data=pt_list)
Beispiel #9
0
    def get_duration_activation(self):
        data = parameter_required('tistarttime', 'tiendtime')
        if is_admin():
            usid = data.get('usid')
        elif is_user():
            usid = getattr(request, 'user').id
        else:
            raise AuthorityError('请登录')
        start = self._trans_time(data.get('tistarttime'))
        end = self._trans_time(data.get('tiendtime'))

        at_list = Activation.query.filter(
            Activation.USid == usid, Activation.createtime >= start, Activation.createtime <= end).all_with_page()
        for at in at_list:
            self._fill_at(at)
        return Success(data=at_list)
Beispiel #10
0
 def get(self):
     if not is_admin() and not is_supplizer():
         raise AuthorityError()
     form = SupplizerGetForm().valid_data()
     supplizer = form.supplizer
     self._fill_supplizer(supplizer)
     # pbs = ProductBrand.query.filter(
     #     ProductBrand.isdelete == False,
     #     ProductBrand.SUid == supplizer.SUid
     # ).all()
     # for pb in pbs:
     #     if pb:
     #         pb.pbstatus_zh = ProductBrandStatus(pb.PBstatus).zh_value
     #         pb.add('pbstatus_zh')
     supplizer.fill('pbs', [])
     supplizer.fill('SUbaseRate', 0)
     return Success(data=supplizer)
Beispiel #11
0
    def set_verifier(self):
        form = SetVerifier().valid_data()
        if is_admin():
            suid = form.suid.data
            assert suid, '供应商未指定'
        elif is_supplizer():
            suid = request.user.id
        else:
            raise AuthorityError()
        sup = Supplizer.query.filter(
            Supplizer.isdelete == false(),
            Supplizer.SUstatus == UserStatus.usual.value,
            Supplizer.SUid == suid).first_('供应商状态异常')
        if sup.SUgrade != SupplizerGrade.ticket.value:
            raise StatusError('仅虚拟商品供应商可设置核销员')
        phone_list = form.phone_list.data
        tvid_list = []
        instence_list = []
        phone_list = {}.fromkeys(phone_list).keys()
        with db.auto_commit():
            for phone in phone_list:
                User.query.filter(
                    User.isdelete == false(),
                    User.UStelephone == phone).first_(f'没有手机号为 {phone} 用户 ')
                tv = ProductVerifier.query.filter_by(SUid=suid,
                                                     PVphone=phone).first()
                if not tv:
                    tv = ProductVerifier.create({
                        'PVid': str(uuid.uuid1()),
                        'SUid': suid,
                        'PVphone': phone
                    })
                    instence_list.append(tv)
                tvid_list.append(tv.PVid)

            db.session.add_all(instence_list)
            # 删除无效的
            ProductVerifier.query.filter(
                ProductVerifier.isdelete == false(),
                ProductVerifier.SUid == suid,
                ProductVerifier.PVid.notin_(tvid_list)).delete_(
                    synchronize_session=False)
        return Success('修改成功', data=suid)
Beispiel #12
0
 def history_detail(self):
     if not is_supplizer() and not is_admin():
         raise AuthorityError()
     days = request.args.to_dict().get('days')
     if days:
         days = days.replace(' ', '').split(',')
         days = list(map(lambda x: datetime.strptime(x, '%Y-%m-%d').date(), days))
     else:
         days = []
     suid = request.user.id if is_supplizer() else None
     datas = []
     for day in days:
         data = {
             'day_total': self._history_order('total', day=day,
                                              status=(OrderMain.OMstatus > OrderStatus.pending.value,
                                                      OrderMain.OMpayType == PayType.cash.value),
                                              suid=suid),
             'day_count': self._history_order('count', day=day, suid=suid),
             'wai_pay_count': self._history_order('count', day=day,
                                                  status=(OrderMain.OMstatus == OrderStatus.wait_pay.value,),
                                                  suid=suid),
             # 'in_refund': self._inrefund(day=day, suid=suid),
             'in_refund': 0,
             'day': day
         }
         datas.append(data)
     if not days:
         # 获取系统全部
         data = {
             'day_total': self._history_order('total',
                                              status=(OrderMain.OMstatus > OrderStatus.pending.value,
                                                      OrderMain.OMpayType == PayType.cash.value),
                                              suid=suid),
             'day_count': self._history_order('count', suid=suid),
             'wai_pay_count': 0,
             'in_refund': 0,
             'day': None
         }
         datas.append(data)
     return Success(data=datas)
Beispiel #13
0
    def deal_approval(self):
        """管理员处理审批流"""
        if is_admin():
            admin = Admin.query.filter_by_(
                ADid=request.user.id).first_("该管理员已被删除")
            sup = None
        elif is_supplizer():
            sup = Supplizer.query.filter_by_(
                SUid=request.user.id).first_("账号状态错误,请重新登录")
            admin = None
        else:
            raise AuthorityError('权限不足')

        receive_data = request.json
        with db.auto_commit():
            if isinstance(receive_data, list):
                for data in receive_data:
                    self.deal_single_approval(data, admin, sup)
            else:
                self.deal_single_approval(receive_data, admin, sup)

        return Success("审批操作完成")
Beispiel #14
0
 def reset_password(self):
     form = SupplizerResetPasswordForm().valid_data()
     mobile = form.suloginphone.data
     password = form.supassword.data
     # if is_supplizer():
     #     code = form.code.data
     #     correct_code = conn.get(mobile + '_code')
     #     if correct_code:
     #         correct_code = correct_code.decode()
     #     current_app.logger.info('correct code is {}, code is {}'.format(correct_code, code))
     #     if code != correct_code:
     #         raise ParamsError('验证码错误')
     if not is_admin():
         raise AuthorityError()
     with db.auto_commit():
         supplizer = Supplizer.query.filter(
             Supplizer.isdelete == False,
             Supplizer.SUloginPhone == mobile).first()
         supplizer.update({'SUpassword': generate_password_hash(password)})
         db.session.add(supplizer)
         self.base_admin.create_action(AdminActionS.update.value,
                                       'Supplizer', supplizer.SUid)
     return Success('修改成功')
Beispiel #15
0
 def create(self):
     """添加"""
     if is_admin():
         Admin.query.filter_by_(ADid=request.user.id).first_('账号状态异常')
         current_app.logger.info(">>>  Admin Create a Supplizer  <<<")
     elif is_anonymous():
         current_app.logger.info(
             ">>>  Tourist Uploading Supplizer Files  <<<")
     else:
         raise AuthorityError('无权限')
     form = SupplizerCreateForm().valid_data()
     if isinstance(form.sugrade.data, int) and form.sugrade.data == 0:
         raise AuthorityError('暂时只支持添加虚拟商品供应商')
     suid = str(uuid.uuid1())
     if is_admin():
         sustatus = UserStatus.usual.value
         sudeposit = form.sudeposit.data
     else:
         sustatus = UserStatus.auditing.value
         sudeposit = 0
     supassword = generate_password_hash(
         form.supassword.data) if form.supassword.data else None
     try:
         with db.auto_commit():
             supperlizer = Supplizer.create({
                 'SUid':
                 suid,
                 'SUlinkPhone':
                 form.sulinkphone.data,
                 'SUloginPhone':
                 form.suloginphone.data,
                 'SUname':
                 form.suname.data,
                 'SUlinkman':
                 form.sulinkman.data,
                 # 'SUbaseRate': form.subaserate.data,
                 'SUaddress':
                 form.suaddress.data,
                 'SUdeposit':
                 sudeposit,
                 'SUstatus':
                 sustatus,  # 管理员添加的可直接上线
                 'SUbanksn':
                 form.subanksn.data,
                 'SUbankname':
                 form.subankname.data,
                 'SUpassword':
                 supassword,
                 'SUheader':
                 form.suheader.data,
                 'SUcontract':
                 form.sucontract.data,
                 'SUbusinessLicense':
                 form.subusinesslicense.data,
                 'SUregisteredFund':
                 form.suregisteredfund.data,
                 'SUmainCategory':
                 form.sumaincategory.data,
                 'SUregisteredTime':
                 form.suregisteredtime.data,
                 'SUlegalPerson':
                 form.sulegalperson.data,
                 'SUemail':
                 form.suemail.data,
                 'SUlegalPersonIDcardFront':
                 form.sulegalpersonidcardfront.data,
                 'SUlegalPersonIDcardBack':
                 form.sulegalpersonidcardback.data,
                 'SUgrade':
                 form.sugrade.data or 0,
             })
             db.session.add(supperlizer)
             if is_admin():
                 self.base_admin.create_action(AdminActionS.insert.value,
                                               'Supplizer', suid)
             # if pbiminActionS.insert.value, 'SupplizerDepositLog', str(uuid.uuid1()))
     except IntegrityError:
         raise ParamsError('手机号重复')
     return Success('创建成功', data={'suid': supperlizer.SUid})
Beispiel #16
0
    def get_approval_list(self):
        data = parameter_required(('ptid', ))
        filter_starttime, filter_endtime = data.get(
            'starttime', '2018-12-01'), data.get('endtime', '2100-01-01')
        avstatus = data.get('avstatus', "")
        current_app.logger.info('get avstatus {0} '.format(avstatus))
        if avstatus and avstatus != 'all':
            avstatus = getattr(ApplyStatus, data.get('avstatus'), None)
        else:
            avstatus = None

        if is_admin():
            admin = Admin.query.filter_by_(ADid=request.user.id).first_()
            if not admin:
                current_app.logger.info('get admin failed id is {0}'.format(
                    request.user.id))
                raise NotFound("该管理员已被删除")

            pt = PermissionType.query.filter_by_(PTid=data.get('ptid')).first()
            # ptytype = ActivityType(int(data.get('pttype'))).name
            ap_querry = Approval.query.filter(
                Approval.PTid == pt.PTid,
                Approval.AVlevel == Permission.PELevel,
                Permission.PTid == Approval.PTid,
                Permission.PIid == AdminPermission.PIid,
                AdminPermission.ADid == admin.ADid,
                Approval.isdelete == False,
                Permission.isdelete == False,
                AdminPermission.isdelete == False,
            )
            if avstatus is not None:
                current_app.logger.info('sql avstatus = {0}'.format(
                    avstatus.value))
                ap_querry = ap_querry.filter(
                    Approval.AVstatus == avstatus.value)

            ap_list = ap_querry.order_by(
                Approval.AVstatus.desc(),
                Approval.createtime.desc()).all_with_page()
        else:
            try:
                status = getattr(ApplyStatus, data.get('avstatus',
                                                       'wait_check'),
                                 'wait_check').value
            except Exception as e:
                current_app.logger.error(
                    "sup approval list status error :{}".format(e))
                status = None
            pt = PermissionType.query.filter_by_(
                PTid=data.get('ptid')).first_('审批类型不存在')
            sup = Supplizer.query.filter_by_(
                SUid=request.user.id).first_('供应商不存在')

            ap_list = Approval.query.filter_by_(
                AVstartid=sup.SUid).all_with_page()
        res = []
        for ap in ap_list:
            if not ap.AVstartdetail:
                continue
            ap.hide('AVcontentdetail', 'AVstartdetail')
            content = ap.AVcontentdetail or 'null'
            content = json.loads(content)
            if content.get('prid') and content.get('suname'):
                pr_nums = db.session.query(func.count(Product.PRid)).filter(
                    Product.isdelete == false(),
                    Product.PRstatus.in_((ProductStatus.ready.value,
                                          ProductStatus.active.value)),
                    Product.SUid == content.get('suid'),
                ).scalar() or 0  # 当前已上架的商品数
                content[
                    'suname'] = f'{content.get("suname")} » 现有{pr_nums}件商品上架'
                start = ap.AVstartdetail or 'null'

                ap.fill('content', content)
                ap.fill('start', json.loads(start))
                ap.add('createtime')
                ap.fill('avstatus_en', ApplyStatus(ap.AVstatus).name)
                ap.fill('avstatus_zh', ApplyStatus(ap.AVstatus).zh_value)
                res.append(ap)

        return Success('获取待审批列表成功', data=res)
Beispiel #17
0
    def update_product(self):
        """编辑商品"""
        if is_admin():
            product_from = ProductFrom.platform.value
        elif is_supplizer():
            product_from = ProductFrom.supplizer.value
        else:
            raise AuthorityError('当前用户无权进行该操作')
        data = parameter_required('prid')
        product = Product.query.filter(Product.isdelete == false(),
                                       Product.PRid == data.get('prid')).first_('未找到该商品信息')
        if Product.query.filter(Product.isdelete == false(), Product.PRname == data.get('prname'),
                                Product.PRid != Product.PRid, Product.PRstatus != ProductStatus.over.value).first():
            raise ParamsError('该商品名已存在')
        approval_flag = 0
        with db.auto_commit():
            if data.get('delete'):
                if product.PRstatus == ProductStatus.active.value:
                    raise ParamsError('无法直接删除正在发放中的商品')
                if OrderMain.query.filter(OrderMain.isdelete == false(),
                                          OrderMain.OMstatus > OrderStatus.not_won.value,
                                          OrderMain.PRid == product.PRid).first():
                    raise StatusError('暂时无法直接删除已产生购买记录的商品')
                product.update({'isdelete': True})
                # 取消异步任务
                cancel_async_task('start_product{}'.format(product.PRid))
                cancel_async_task('end_product{}'.format(product.PRid))
                self.base_admin.create_action(AdminActionS.delete.value, 'Product', product.PRid)
                # 同时将正在进行的审批流改为取消
                self.base_approval.cancel_approval(product.PRid, request.user.id)
            elif data.get('interrupt'):
                if product.PRstatus > ProductStatus.active.value:
                    raise StatusError('该状态下无法中止')
                product.update({'PRstatus': ProductStatus.interrupt.value})
                cancel_async_task('start_product{}'.format(product.PRid))
                cancel_async_task('end_product{}'.format(product.PRid))
                self.base_admin.create_action(AdminActionS.update.value, 'Product', product.PRid)
                # 同时将正在进行的审批流改为取消
                self.base_approval.cancel_approval(product.PRid, request.user.id)
            else:
                approval_flag = 1
                if product.PRstatus < ProductStatus.interrupt.value:
                    raise ParamsError('仅可编辑已中止发放或已结束的商品')
                product_dict = self._validate_ticket_param(data)
                product_dict.update({'PRname': data.get('prname'),
                                     'PRimg': data.get('primg'),
                                     'PRdetails': data.get('prdetails'),
                                     # 'PRstatus': ProductStatus.ready.value if product_dict.get(
                                     #     'PRtimeLimeted') else ProductStatus.active.value,
                                     'PRstatus': ProductStatus.pending.value
                                     })
                self.base_approval.cancel_approval(product.PRid, request.user.id)  # 同时将正在进行的审批流改为取消
                if product.PRstatus == ProductStatus.interrupt.value:  # 中止的情况
                    current_app.logger.info('edit interrupt ticket')
                    product.update(product_dict, null='not')
                else:  # 已结束的情况,重新发起
                    current_app.logger.info('edit ended ticket')
                    product_dict.update({'PRid': str(uuid.uuid1()),
                                         'CreatorId': getattr(request, 'user').id,
                                         'CreatorType': getattr(request, 'user').model})
                    product = Product.create(product_dict)
                cancel_async_task('start_product{}'.format(product.PRid))
                cancel_async_task('end_product{}'.format(product.PRid))

                self.base_admin.create_action(AdminActionS.insert.value, 'Product', product.PRid)
            db.session.add(product)
        if approval_flag:
            self.base_approval.create_approval('toshelves', request.user.id, product.PRid, product_from)
        return Success('编辑成功', data={'prid': product.PRid})
Beispiel #18
0
    def list(self):
        """供应商列表"""
        form = SupplizerListForm().valid_data()
        kw = form.kw.data
        mobile = form.mobile.data
        sustatus = form.sustatus.data
        option = form.option.data
        sugrade = form.sugrade.data
        # if sugrade is not None or sugrade:
        #     sugrade = int(sugrade)
        if str(sugrade).isdigit():
            sugrade = int(sugrade)
        else:
            sugrade = None

        if option == 'ticket':
            return self._list_ticket_sup()
        filter_args = {
            Supplizer.isdelete == false(),
        }
        if sugrade:
            filter_args.add(Supplizer.SUgrade == sugrade)
        if sustatus or sustatus == 0:
            filter_args.add(Supplizer.SUstatus == sustatus)
        if kw:
            filter_args.add(Supplizer.SUname.contains(kw))
        if mobile:
            filter_args.add(Supplizer.SUlinkPhone.contains(mobile))
        if is_supplizer():
            filter_args.add(Supplizer.SUid == getattr(request, 'user').id)
        supplizers = Supplizer.query.filter(*filter_args).order_by(
            Supplizer.createtime.desc()).all_with_page()

        for supplizer in supplizers:
            supplizer.hide('SUpassword')
            if is_admin():
                # pbs = ProductBrand.query.filter(
                #     ProductBrand.isdelete == False,
                #     ProductBrand.SUid == supplizer.SUid
                # ).all()
                # for pb in pbs:
                #     if pb:
                #         pb.pbstatus_zh = ProductBrandStatus(pb.PBstatus).zh_value
                #         pb.add('pbstatus_zh')
                pb = namedtuple('ProductBrand', [
                    'PBid', 'PBlogo', 'PBname', 'PBdesc', 'PBlinks',
                    'PBbackgroud', 'PBstatus', 'SUid', 'PBintegralPayRate',
                    'PBslogan', 'PBthemeColor', 'PBpublicity', 'PBsort'
                ])
                # pbs = [pb('', '', '', '', '', '', 0, '', 0, '', '', '', 1)]
                pbs = []
                supplizer.fill('pbs', pbs)
            # 收益
            favor = UserWallet.query.filter(
                UserWallet.isdelete == False,
                UserWallet.USid == supplizer.SUid,
                UserWallet.CommisionFor == ApplyFrom.supplizer.value).first()
            supplizer.fill('uwbalance', getattr(favor, 'UWbalance', 0))
            supplizer.fill('uwtotal', getattr(favor, 'UWtotal', 0))
            supplizer.fill('uwcash', getattr(favor, 'UWcash', 0))
            supplizer.fill('uwexpect', getattr(favor, 'UWexpect', 0))
            supplizer.fill('subaserate', 0)
            supplizer.fill('sustatus_zh',
                           UserStatus(supplizer.SUstatus).zh_value)
            supplizer.fill('sustatus_en', UserStatus(supplizer.SUstatus).name)
        return Success(data=supplizers)