Example #1
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})
Example #2
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)
Example #3
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('修改成功')
Example #4
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)
Example #5
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)
Example #6
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('更新成功')
Example #7
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)
Example #8
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)
Example #9
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("审批操作完成")
Example #10
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('修改成功')
Example #11
0
 def send_reset_password_code(self):
     """发送修改验证码"""
     raise AuthorityError('功能暂未开放')
Example #12
0
 def delete(self):
     """删除"""
     raise AuthorityError('暂不提供该功能')
Example #13
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})
Example #14
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})