Example #1
0
 def __fill_approval(self, pt, start, content, **kwargs):
     if pt.PTid == 'tocash':
         return self.__fill_cash(start, content, **kwargs)
     elif pt.PTid == 'toagent':
         return self.__fill_agent(start, content)
     elif pt.PTid == 'toshelves':
         return self.__fill_shelves(start, content)
     elif pt.PTid == 'topublish':
         return self.__fill_publish(start, content)
     elif pt.PTid == 'toguessnum':
         return self.__fill_guessnum(start, content)
     elif pt.PTid == 'tomagicbox':
         return self.__fill_magicbox(start, content)
     elif pt.PTid == 'tofreshmanfirstproduct':
         return self.__fill_freshmanfirstproduct(start, content)
     elif pt.PTid == 'totrialcommodity':
         return self.__fill_trialcommodity(start, content)
     elif pt.PTid == 'toreturn':
         # todo 退货申请目前没有图
         raise ParamsError('退货申请前往订单页面实现')
     elif pt.PTid == 'toactivationcode':
         return self.__fill_activationcode(start, content)
     elif pt.PTid == 'tosettlenment':
         return self.__fill_settlenment(start, content)
     else:
         raise ParamsError('参数异常, 请检查审批类型是否被删除。如果新增了审批类型,请联系开发实现后续逻辑')
Example #2
0
    def set_linkcontent(self):
        body = request.json
        admin = get_current_admin()
        current_app.logger.info('当前管理员是 {}'.format(admin.ADname))
        lcid = body.get('lcid')
        lccontent = body.get('lccontent')
        with db.auto_commit():
            if lcid:
                lc = LinkContent.query.filter(LinkContent.LCid == lcid, LinkContent.isdelete == False).first()
                if body.get('delete'):
                    current_app.logger.info('开始删除富文本内容 lcid = {}'.format(lcid))
                    if not lc:
                        raise ParamsError('该内容已删除')
                    lc.isdelete = True
                    return Success('删除成功', data=lcid)
                if lc:
                    current_app.logger.info('开始更新富文本内容 lcid = {}'.format(lcid))
                    if lccontent:
                        lc.LCcontent = lccontent
                    db.session.add(lc)
                    return Success('更新成功', data=lcid)

            if not lccontent:
                raise ParamsError('富文本内容不能为空')
            lc = LinkContent.create({
                'LCid': str(uuid.uuid1()),
                'LCcontent': lccontent
            })
            current_app.logger.info('开始创建富文本内容 lcid = {}'.format(lc.LCid))
            db.session.add(lc)
            return Success('添加成功', data=lc.LCid)
Example #3
0
    def _send_order(self, om, olcompany, olexpressno):
        """
        订单发货
        :param om: 主单对象
        :param olcompany: 快递公司
        :param olexpressno: 快递单号
        :return: object
        """
        lcompany = LogisticsCompnay.query.filter_by_(LCname=olcompany).first()
        if not lcompany:
            raise ParamsError("订单号 {} ,填写的快递公司不存在, 请检查后重试".format(om.OMno))
        # 清除之前可能存在的异常物流
        OrderLogistics.query.filter(
            OrderLogistics.OMid == om.OMid,
            OrderLogistics.isdelete == False).delete_()
        # 检验单号是否填写错误
        response = Logistics().get_logistic(olexpressno, lcompany.LCcode)
        if not bool(response) or response.get('status') not in ['0', '205']:
            raise ParamsError("订单号 {} ,填写的物流信息错误,请检查快递公司与单号无误后重新上传模板".format(
                om.OMno))

        # 添加物流记录
        order_logistics_instance = OrderLogistics.create({
            'OLid':
            str(uuid.uuid1()),
            'OMid':
            om.OMid,
            'OLcompany':
            lcompany.LCcode,
            'OLexpressNo':
            olexpressno,
        })
        return order_logistics_instance
Example #4
0
    def check_qualification(self, opid=None, omid=None):
        if omid:
            om = OrderMain.query.filter(OrderMain.OMid == omid,
                                        OrderMain.isdelete == False).first()
            if not om:
                raise ParamsError('订单已删除')

            if om.OMinRefund == False:
                raise ParamsError('请对已发起售后的商品订单发起仲裁')

            ora = OrderRefundApply.query.filter(
                OrderRefundApply.isdelete == False,
                OrderRefundApply.OMid == omid, OrderRefundApply.ORAstatus ==
                ApplyStatus.reject.value).first()

            if not ora:
                raise StatusError('该售后处理中,请等待处理结果')

        if opid:
            op = OrderPart.query.filter(OrderPart.OPid == opid,
                                        OrderPart.isdelete == False).first()

            if not op:
                raise ParamsError('副单已删除')
            if op.OPisinORA == False:
                raise StatusError('请对已发起售后的订单发起仲裁')

            ora = OrderRefundApply.query.filter(
                OrderRefundApply.OPid == opid,
                OrderRefundApply.isdelete == False, OrderRefundApply.ORAstatus
                == ApplyStatus.reject.value).first()

            if not ora:
                raise StatusError('该订单售后处理中,请等待处理结果')
Example #5
0
    def set_supplizeraccount(self):
        if not is_supplizer():
            raise AuthorityError

        from flask import request
        from planet.control.CUser import CUser
        data = request.json
        cuser = CUser()
        cardno = data.get('sacardno')
        cardno = re.sub(r'\s', '', str(cardno))
        cuser._CUser__check_card_num(cardno)
        check_res = cuser._verify_cardnum(cardno)  # 检验卡号
        if not check_res.data.get('validated'):
            raise ParamsError('请输入正确的银行卡号')
        checked_res = cuser._verify_cardnum(data.get('sabankaccount'))
        # if not checked_res.data.get('validated'):
        #     raise ParamsError('请输入正确的开票账户银行卡号')
        checked_name = cuser._verify_chinese(data.get('sacardname'))
        if not checked_name or len(checked_name[0]) < 2:
            raise ParamsError('请输入正确的开户人姓名')
        current_app.logger.info('用户输入银行名为:{}'.format(data.get('sabankname')))
        bankname = check_res.data.get('cnbankname')
        try:
            WexinBankCode(bankname)
        except Exception:
            raise ParamsError('系统暂不支持该银行提现,请更换银行后重新保存')
        data['sabankname'] = bankname
        current_app.logger.info('校验后更改银行名为:{}'.format(data.get('sabankname')))

        sa = SupplizerAccount.query.filter(
            SupplizerAccount.SUid == request.user.id,
            SupplizerAccount.isdelete == False).first()
        if sa:
            for key in sa.__dict__:
                if str(key).lower() in data:
                    if re.match(r'^(said|suid)$', str(key).lower()):
                        continue
                    if str(key).lower() == 'sacardno':
                        setattr(sa, key, cardno)
                        continue
                    setattr(sa, key, data.get(str(key).lower()))
        else:
            sa_dict = {}
            for key in SupplizerAccount.__dict__:

                if str(key).lower() in data:
                    if not data.get(str(key).lower()):
                        continue
                    if str(key).lower() == 'suid':
                        continue
                    if str(key).lower() == 'sacardno':
                        sa_dict.setdefault(key, cardno)
                        continue
                    sa_dict.setdefault(key, data.get(str(key).lower()))
            sa_dict.setdefault('SAid', str(uuid.uuid1()))
            sa_dict.setdefault('SUid', request.user.id)
            sa = SupplizerAccount.create(sa_dict)
            db.session.add(sa)

        return Success('设置供应商账户信息成功')
Example #6
0
 def _create_essay(self, data):
     """随笔"""
     text, image, video = data.get('text'), data.get('image'), data.get(
         'video')
     # if image:
     #     current_app.logger.error("图片校验测试")
     #     current_app.logger.error(mp_miniprogram.img_sec_check(image))
     if image and not isinstance(image, list):
         raise ParamsError('image 格式错误')
     if image and video:
         raise ParamsError('不能同时选择图片和视频')
     if image and len(image) > 9:
         raise ParamsError('最多可上传9张图片')
     video = {
         'url': self._check_upload_url(video.get('url')),
         'thumbnail': video.get('thumbnail'),
         'duration': video.get('duration')
     } if video else None
     content = {
         'text':
         text,
         'image':
         [self._check_upload_url(i, msg='图片格式错误, 请检查后重新上传')
          for i in image] if image else None,
         'video':
         video
     }
     content = json.dumps(content)
     return {'TRcontent': content, 'TRlocation': data.get('trlocation')}
Example #7
0
 def update(self):
     data = parameter_required(('skuid', ))
     skuid = data.get('skuid')
     price = data.get('skuprice')
     stock = data.get('skustock')
     if price:
         if price < 0:
             raise ParamsError('价格小于0')
         price = round(price, 2)
     if stock and stock < 0:
         raise ParamsError('库存小于0')
     skuattritedetail = data.get('skuattritedetail')
     with self.sproduct.auto_commit() as s:
         sku = s.query(ProductSku).filter_by_({
             'SKUid': skuid
         }).first_('sku不存在')
         product = self.sproduct.get_product_by_prid(sku.PRid)
         prattribute = json.loads(product.PRattribute)
         if len(skuattritedetail) != len(prattribute) or not isinstance(
                 skuattritedetail, list):
             raise ParamsError('skuattritedetail 参数不准确')
         skuattritedetail = json.dumps(skuattritedetail)
         sku_dict = {
             'SKUpic': data.get('skupic'),
             'SKUprice': price,
             'SKUstock': stock,
             'SKUattriteDetail': skuattritedetail,
         }
         [setattr(sku, k, v) for k, v in sku_dict.items() if v is not None]
         s.add(sku)
         if is_admin():
             BASEADMIN().create_action(AdminActionS.update.value,
                                       'ProductSku', skuid)
     return Success('更新成功')
Example #8
0
 def create_apply(self):
     """提交购买申请"""
     data = parameter_required(
         ('acabankname', 'acabanksn', 'acaname', 'vouchers'))
     acabankname = data.get('acabankname')
     acabanksn = data.get('acabanksn')
     if len(acabanksn) < 10 or len(acabanksn) > 30:
         raise ParamsError('卡号错误')
     if re.findall('\D', acabanksn):
         raise ParamsError('卡号错误')
     acaname = data.get('acaname')
     vouchers = data.get('vouchers')
     if not vouchers or (not isinstance(vouchers,
                                        list)) or (len(vouchers) > 4):
         raise ParamsError('凭证有误')
     with db.auto_commit():
         apply = ActivationCodeApply.create({
             'ACAid': str(uuid.uuid1()),
             'USid': request.user.id,
             'ACAname': acaname,
             'ACAbankSn': acabanksn,
             'ACAbankname': acabankname,
             'ACAvouchers': vouchers
         })
         db.session.add(apply)
     self.create_approval('toactivationcode', request.user.id, apply.ACAid)
     return Success('提交成功')
Example #9
0
 def add_travelrecord(self):
     """创建时光记录"""
     user = User.query.filter_by_(
         USid=getattr(request, 'user').id).first_('请重新登录')
     data = parameter_required(('trtype', 'trstatus'))
     plid = data.get('plid')
     try:
         TravelRecordStatus(data.get('trstatus'))
     except Exception:
         raise ParamsError('trstatus 参数错误')
     trtype = str(data.get('trtype'))
     if trtype == str(TravelRecordType.raiders.value):  # 攻略
         parameter_required(
             {
                 'trproducts': '推荐携带物品',
                 'trbudget': '预算',
                 'trcontent': '活动详情',
                 'trlocation': '景区'
             },
             datafrom=data)
         tr_dict = self._create_raiders(data)
     elif trtype == str(TravelRecordType.travels.value):  # 游记
         parameter_required(
             {
                 'trtitle': '标题',
                 'trcontent': '游记内容',
                 'trlocation': '景区'
             },
             datafrom=data)
         tr_dict = self._create_travels(data)
     elif trtype == str(TravelRecordType.essay.value):  # 随笔
         parameter_required({'text': '随笔内容'}, datafrom=data)
         tr_dict = self._create_essay(data)
     else:
         raise ParamsError('type 参数错误')
     with db.auto_commit():
         travelrecord_dict = {
             'TRid': str(uuid.uuid1()),
             'AuthorID': user.USid,
             'TRtype': trtype,
             'TRstatus': data.get('trstatus'),
             # 'TRstatus': TravelRecordStatus.auditing.value  # todo 待审核状态
             'PLid': plid if plid else None
         }
         travelrecord_dict.update(tr_dict)
         try:
             check_content = travelrecord_dict.get('TRcontent')
             if trtype == str(TravelRecordType.essay.value):
                 check_content = json.loads(check_content).get('text')
             mp_miniprogram.msg_sec_check(check_content)
         except WeixinMPError:
             travelrecord_dict['isdelete'] = True
         db.session.add(TravelRecord.create(travelrecord_dict))
     try:
         current_app.logger.info('content_sec_check: {}'.format(
             mp_miniprogram.msg_sec_check(check_content)))
     except WeixinMPError:
         raise ParamsError('您输入的内容含有部分敏感词汇,请检查后重新发布')
     return Success('发布成功', {'trid': travelrecord_dict['TRid']})
Example #10
0
    def update(self):
        """更新景区介绍"""
        admin = Admin.query.filter_by_(
            ADid=getattr(request, 'user').id).first_('请重新登录')
        data = parameter_required(('sspid', 'aaid', 'sspcontent', 'sspname',
                                   'ssplevel', 'sspmainimg'))
        aaid, sspcontent, ssplevel = data.get('aaid'), data.get(
            'sspcontent'), data.get('ssplevel')
        sspid = data.get('sspid')
        scenic_instance = ScenicSpot.query.filter_by_(
            SSPid=sspid).first_('未找到该景区信息')
        sspname = data.get('sspname')
        parentid = data.get('parentid')

        if parentid == sspid:
            raise ParamsError('关联景区不能选择自身')
        associated = ScenicSpot.query.filter_by_(
            ParentID=scenic_instance.SSPid).first()
        if not scenic_instance.ParentID and associated and parentid:
            raise ParamsError('该景区作为顶级景区已被其他景区关联,不允许再将此景区关联到其他景区下')

        exsit_other = ScenicSpot.query.filter(
            ScenicSpot.isdelete == false(), ScenicSpot.SSPname == sspname,
            ScenicSpot.SSPid != sspid).first()
        if exsit_other:
            raise ParamsError('景区名称重复')
        if parentid:
            ScenicSpot.query.filter(
                ScenicSpot.SSPid == parentid, ScenicSpot.isdelete == false(),
                ScenicSpot.ParentID.is_(None)).first_('关联景区选择错误')

        # 地址拼接
        address = db.session.query(
            AddressProvince.APname, AddressCity.ACname,
            AddressArea.AAname).filter(
                AddressArea.ACid == AddressCity.ACid,
                AddressCity.APid == AddressProvince.APid,
                AddressArea.AAid == aaid).first_('地址有误')
        address = '-'.join(address)
        if not re.match(r'^[1-5]$', str(ssplevel)):
            raise ParamsError('景区等级请填写1到5之间的整数')
        with db.auto_commit():
            scenic_instance.update(
                {
                    'AAid': aaid,
                    'ADid': admin.ADid,
                    'SSParea': address,
                    'SSPcontent': sspcontent,
                    'SSPname': sspname,
                    'SSPlevel': ssplevel,
                    'SSPmainimg': data.get('sspmainimg'),
                    'ParentID': parentid
                },
                null='no')
            db.session.add(scenic_instance)
            self.BaseAdmin.create_action(AdminActionS.update.value,
                                         'ScenicSpot', scenic_instance.SSPid)
        return Success('更新成功', {'sspid': scenic_instance.SSPid})
Example #11
0
 def _integralpay(self, data, usid):
     """星币支付"""
     with db.auto_commit():
         model_bean = list()
         omid, omtruemount = data.get('omid'), data.get('omtruemount')
         uspaycode = data.get('uspaycode')
         order_main = OrderMain.query.filter_by_({
             'OMid':
             omid,
             'USid':
             usid,
             'OMstatus':
             OrderMainStatus.wait_pay.value,
             'OMfrom':
             OrderFrom.integral_store.value,
             'OMtrueMount':
             omtruemount
         }).first_('订单信息错误')
         user = User.query.filter(User.USid == usid,
                                  User.isdelete == False).first_("请重新登录")
         if not user.USpaycode:
             raise ParamsError('请在 “我的 - 安全中心” 设置支付密码后重试')
         if not (uspaycode
                 and check_password_hash(user.USpaycode, uspaycode)):
             raise ParamsError('请输入正确的支付密码')
         # 增加星币消费记录
         userintegral_dict = UserIntegral.create({
             'UIid':
             str(uuid.uuid1()),
             'USid':
             user.USid,
             'UIintegral':
             order_main.OMtrueMount,
             'UIaction':
             UserIntegralAction.consumption.value,
             'UItype':
             UserIntegralType.expenditure.value,
             'OPayno':
             order_main.OPayno
         })
         model_bean.append(userintegral_dict)
         # 扣除用户积分
         if user.USintegral < omtruemount:
             raise PoorScore('用户星币余额不足')
         user.update({
             'USintegral':
             int(user.USintegral) - int(order_main.OMtrueMount)
         })
         model_bean.append(user)
         # 更改订单状态
         order_main.update({'OMstatus': OrderMainStatus.wait_send.value})
         model_bean.append(order_main)
         db.session.add_all(model_bean)
     return Success('支付成功', dict(omid=omid))
Example #12
0
 def add(self):
     """添加景区介绍"""
     admin = Admin.query.filter_by_(
         ADid=getattr(request, 'user').id).first_('请重新登录')
     data = parameter_required(
         ('aaid', 'sspcontent', 'sspname', 'ssplevel', 'sspmainimg'))
     aaid, sspcontent, ssplevel = data.get('aaid'), data.get(
         'sspcontent'), data.get('ssplevel')
     sspname = data.get('sspname')
     parentid = data.get('parentid')
     exsit = ScenicSpot.query.filter(ScenicSpot.isdelete == false(),
                                     ScenicSpot.SSPname == sspname).first()
     if exsit:
         raise ParamsError('已添加过该景区')
     if parentid:
         ScenicSpot.query.filter(
             ScenicSpot.SSPid == parentid, ScenicSpot.isdelete == false(),
             ScenicSpot.ParentID.is_(None)).first_('关联景区选择错误')
     # 地址拼接
     address = db.session.query(
         AddressProvince.APname, AddressCity.ACname,
         AddressArea.AAname).filter(
             AddressArea.ACid == AddressCity.ACid,
             AddressCity.APid == AddressProvince.APid,
             AddressArea.AAid == aaid).first_('地址有误')
     address = '-'.join(address)
     if not re.match(r'^[1-5]$', str(ssplevel)):
         raise ParamsError('景区等级请填写1到5之间的整数')
     with db.auto_commit():
         scenic_instance = ScenicSpot.create({
             'SSPid':
             str(uuid.uuid1()),
             'ADid':
             admin.ADid,
             'AAid':
             aaid,
             'SSParea':
             address,
             'SSPcontent':
             sspcontent,
             'SSPname':
             sspname,
             'SSPlevel':
             ssplevel,
             'SSPmainimg':
             data.get('sspmainimg'),
             'ParentID':
             parentid
         })
         db.session.add(scenic_instance)
         self.BaseAdmin.create_action(AdminActionS.insert.value,
                                      'ScenicSpot', scenic_instance.SSPid)
     return Success('添加成功', {'sspid': scenic_instance.SSPid})
Example #13
0
 def _check_gear_price(self, gear_list):
     if not isinstance(gear_list, list):
         raise ParamsError(
             '参数{}错误, 请按格式传递参数: 如 ["10-20", "15-30"]'.format(gear_list))
     for item in gear_list:
         tmp = list(map(lambda x: self._check_isint(x),
                        item.split('-')))  # 校验每一项是否是整数
         try:
             if tmp[0] >= tmp[1] or tmp[0] == tmp[1] == 0:
                 raise ParamsError('每档随机变化金额中填写的第二个数字需大于第一个数字')
         except IndexError:
             raise ParamsError('请按格式合理传递参数: 如 ["10-20", "15-30"]')
     return json.dumps(gear_list)
 def my_wallet(self):
     """我的钱包页(消费记录、提现记录)"""
     args = request.args.to_dict()
     date, option = args.get('date'), args.get('option')
     user = User.query.filter(User.isdelete == false(),
                              User.USid == getattr(
                                  request, 'user').id).first_('请重新登录')
     if date and not re.match(r'^20\d{2}-\d{2}$', str(date)):
         raise ParamsError('date 格式错误')
     year, month = str(date).split('-') if date else (datetime.now().year,
                                                      datetime.now().month)
     if option == 'expense':
         transactions, total = self._get_transactions(
             user, year, month, args)
     elif option == 'withdraw':
         transactions, total = self._get_withdraw(user, year, month)
     else:
         raise ParamsError('type 参数错误')
     user_wallet = UserWallet.query.filter(
         UserWallet.isdelete == false(),
         UserWallet.USid == user.USid).first()
     if user_wallet:
         uwcash = user_wallet.UWcash
     else:
         with db.auto_commit():
             user_wallet_instance = UserWallet.create({
                 'UWid':
                 str(uuid.uuid1()),
                 'USid':
                 user.USid,
                 'CommisionFor':
                 ApplyFrom.user.value,
                 'UWbalance':
                 Decimal('0.00'),
                 'UWtotal':
                 Decimal('0.00'),
                 'UWcash':
                 Decimal('0.00'),
                 'UWexpect':
                 Decimal('0.00')
             })
             db.session.add(user_wallet_instance)
             uwcash = 0
     response = {
         'uwcash': uwcash,
         'transactions': transactions,
         'total': total
     }
     return Success(data=response)
Example #15
0
    def __update_questoutline(self, data, qo_model, qotype, qo_filter=None):
        """
        修改问题分类
        :param data: request的data
        :param qo_model: 通过id筛选的问题分类
        :param qo_filter: 通过名称筛选的问题分类
        :return: 出现分类名重复会报错,否则静默处理
        """
        qanaction = ""
        if data.get('qoicon') and qo_model.QOicon != data.get('qoicon'):
            qanaction += '修改icon为 {0}'.format(data.get('qoicon'))
            qo_model.QOicon = data.get('qoicon')
        if data.get('qoname') and qo_model.QOname != data.get('qoname'):

            if qo_filter:
                raise ParamsError('问题分类名不能与已有分类名相同')
            qanaction += '修改name为 {0}'.format(data.get('qoname'))
            qo_model.QOname = data.get('qoname')
        if qotype != int(qo_model.QOtype):
            qanaction += '修改类型为{0}'.format(qotype)
            qo_model.QOtype = qotype
        if qanaction:
            qan_instance = QuestAnswerNote.create({
                'QANid': str(uuid.uuid1()),
                'QANcontent': qanaction,
                'QANtargetId': qo_model.QOid,
                'QANtype': QuestAnswerNoteType.qo.value,
                'QANcreateid': request.user.id,
            })
            db.session.add(qan_instance)
Example #16
0
 def update(self):
     """更新购物车"""
     data = parameter_required(('caid', ))
     caid = data.get('caid')
     usid = request.user.id
     card = self.scart.get_card_one({'CAid': caid, 'USid': usid}, error='购物车不存在')  # card就是cart.
     # 默认的sku和数量
     skuid = data.get('skuid') or card.SKUid
     try:
         num = int(data.get('canums', card.CAnums))
         if num < 0:
             raise TypeError()
     except TypeError as e:
         raise ParamsError('num类型错误')
     msg = '更新成功'
     with self.scart.auto_commit() as session:
         # 数量为0执行删除
         if num == 0:
             session.query(Carts).filter_by({'CAid': caid}).delete_()
             msg = '删除成功'
         else:
             session.query(ProductSku).filter_by_({'SKUid': skuid}).first_('商品sku不存在')
             session.query(Carts).filter_by({'CAid': caid}).update({
                 'SKUid': skuid,
                 'CAnums': num
             })
     return Success(msg)
Example #17
0
 def set_award(self):
     """设置中奖"""
     data = parameter_required('tsoid')
     tsoid = data.get('tsoid')
     ticket_order = TicketsOrder.query.filter(TicketsOrder.isdelete == false(),
                                              TicketsOrder.TSOid == tsoid,
                                              TicketsOrder.TSOstatus == TicketsOrderStatus.pending.value
                                              ).first_('状态错误')
     ticket = Ticket.query.filter(Ticket.isdelete == false(), Ticket.TIid == ticket_order.TIid).first()
     if not ticket or ticket.TIstatus != TicketStatus.over.value:
         raise ParamsError('抢票尚未结束')
     award_num = self._query_award_num(ticket.TIid)
     current_app.logger.info('已中奖数:{} / {}'.format(award_num, ticket.TInum))
     if award_num >= ticket.TInum:
         raise StatusError('已达最大发放票数')
     with db.auto_commit():
         update_dict = {'TSOqrcode': 'https://play.bigxingxing.com/img/qrcode/2019/9/3/QRCODE.png',
                        'TSOstatus': TicketsOrderStatus.has_won.value}
         if ticket.TIdeposit == ticket.TIprice:  # 第二次支付押金0元的情况
             update_dict['TSOstatus'] = TicketsOrderStatus.completed.value
         ticket_order.update(update_dict)
         db.session.add(ticket_order)
         db.session.flush()
         awarded_num = self._query_award_num(ticket.TIid)
         current_app.logger.info('设置后中奖数:{} / {}'.format(awarded_num, ticket.TInum))
         if awarded_num == ticket.TInum:  # 未中奖退钱
             other_to = self._query_not_won(ticket.TIid)
             total_row_count = 0
             for oto in other_to:
                 row_count = self._deposit_refund(oto)
                 total_row_count += row_count
             current_app.logger.info('共{}条未中奖'.format(total_row_count))
     return Success('设置成功', data=tsoid)
Example #18
0
 def __get_approvalcontent(self, pt, startid, avcontentid, **kwargs):
     start, content = self.__fill_approval(pt, startid, avcontentid,
                                           **kwargs)
     gennerc_log('get start {0} content {1}'.format(start, content))
     if not (start or content):
         raise ParamsError('审批流创建失败,发起人或需审批内容已被删除')
     return start, content
Example #19
0
 def batch_upload(self):
     if is_tourist():
         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张图片')
     # todo 视频数量限制
     data = parameter_required()
     folder = self.allowed_folder(data.get('type'))
     file_url_list = []
     for file in files.values():
         upload_file = self._upload_file(file, folder)
         file_dict = {
             'data': upload_file[0],
             'video_thum': upload_file[1],
             'video_dur': upload_file[2],
             'upload_type': upload_file[3]
         }
         file_url_list.append(file_dict)
     return Success('上传成功', file_url_list)
Example #20
0
    def upload_delivery_file(self):
        """
        订单批量发货,文件上传入口
        :return:
        """
        if is_admin():
            Admin.query.filter_by(ADid=request.user.id,
                                  ADstatus=AdminStatus.normal.value,
                                  isdelete=False).first_('管理员账号错误')
        elif is_supplizer():
            Supplizer.query.filter_by(SUid=request.user.id,
                                      SUstatus=UserStatus.usual.value,
                                      isdelete=False).first_('供应商账号状态错误')
        else:
            raise TokenError('未登录')
        file = request.files.get('file')
        if not file:
            raise ParamsError('未上传文件')
        current_app.logger.info('Start Add Delivery Template {}'.format(
            datetime.now()))
        folder = 'xls'
        # 接收数据保存到服务器
        file_path = self._save_excel(file, folder)

        # 进行订单发货
        nrows = self._order_delivery(file_path)
        if is_admin():
            with db.auto_commit():
                BASEADMIN().create_action(AdminActionS.insert.value, 'file',
                                          file_path)

        current_app.logger.info('End Add Delivery Template {}'.format(
            datetime.now()))
        return Success('批量发货成功, 共发货 {} 个订单'.format(nrows - 1))
Example #21
0
 def download(self):
     if not is_supplizer() and not is_admin():
         raise AuthorityError()
     args = parameter_required(('type', ))
     type = args.get('type')
     try:
         tp = getattr(ExcelTemplateType, type).value
     except Exception:
         raise ParamsError('type 参数错误')
     current_app.logger.info('start download template')
     template_path = os.path.join(current_app.config['BASEDIR'], 'img',
                                  'xls')
     current_app.logger.info('template path {}'.format(template_path))
     if tp:
         current_app.logger.info('is file {}'.format(
             os.path.isfile(
                 os.path.join(template_path, 'deliverytemplate.xlsx'))))
         return send_from_directory(template_path,
                                    'deliverytemplate.xlsx',
                                    as_attachment=True)
     current_app.logger.info('is file {}'.format(
         os.path.isfile(os.path.join(template_path, 'template.xlsx'))))
     return send_from_directory(template_path,
                                'template.xlsx',
                                as_attachment=True)
Example #22
0
    def get(self):
        """商品详情"""
        args = request.args.to_dict()
        gpid, ggid, gg = args.get('gpid'), args.get('ggid'), None
        if not gpid and not ggid:
            raise ParamsError('gpid | ggid 至少需要其一')
        if ggid:
            gg = GuessGroup.query.filter(GuessGroup.isdelete == False, GuessGroup.GGid == ggid,
                                         # GuessGroup.GGendtime >= datetime.datetime.now()
                                         ).first_('该拼团已结束')
            gpid = gg.GPid
        agree_status = GroupGoodsProduct.GPstatus == ApplyStatus.agree.value
        filter_args = [GroupGoodsProduct.isdelete == False, GroupGoodsProduct.GPid == gpid]

        if common_user() or is_tourist():
            filter_args.append(agree_status)

        try:
            if gg and gg.GGstatus == GuessGroupStatus.completed.value and agree_status in filter_args:
                filter_args.remove(agree_status)

            gp = GroupGoodsProduct.query.filter(*filter_args).first_()
            product = self._fill_gp(gp, gg)
        except Exception as e :
            current_app.logger.error('The error is {}'.format(e))
            raise StatusError("该拼团活动已结束")
        return Success('获取成功', data=product)
Example #23
0
 def get_linkcontent(self):
     data = parameter_required('lcid')
     lcid = data.get('lcid')
     lc = LinkContent.query.filter_by(LCid=lcid, isdelete=False).first()
     if not lc:
         raise ParamsError('链接失效')
     return Success(data=lc)
Example #24
0
    def __update_quest(self, data, qu_model, qu_filter=None):
        """
        修改问题分类
        :param data: request的data
        :param qu_model: 通过id筛选的问题分类
        :param qu_filter: 通过名称筛选的问题分类
        :return: 出现分类名重复会报错,否则静默处理
        """
        if data.get('quest') and qu_model.QUquest != data.get('quest'):

            if qu_filter:
                raise ParamsError('问题分类名不能与已有分类名相同')

            qu_model.QUquest = data.get('quest')

            qan_instance = QuestAnswerNote.create({
                'QANid':
                str(uuid.uuid1()),
                'QANcontent':
                '修改quest 为 {0}'.format(data.get('quest')),
                'QANcreateid':
                request.user.id,
                'QANtargetId':
                qu_model.QUid,
                'QANtype':
                QuestAnswerNoteType.qu.value
            })
            db.session.add(qan_instance)
Example #25
0
 def delete_apply(self):
     """删除申请"""
     if is_supplizer():
         usid = request.user.id
         sup = Supplizer.query.filter_by_(SUid=usid).first_('供应商信息错误')
         current_app.logger.info(
             'Supplizer {} delete magicbox apply'.format(sup.SUname))
     elif is_admin():
         usid = request.user.id
         admin = Admin.query.filter_by_(ADid=usid).first_('管理员信息错误')
         current_app.logger.info('Admin {} magicbox apply'.format(
             admin.ADname))
         sup = None
     else:
         raise AuthorityError()
     data = parameter_required(('mbaid', ))
     mbaid = data.get('mbaid')
     with db.auto_commit():
         apply_info = MagicBoxApply.query.filter_by_(
             MBAid=mbaid).first_('无此申请记录')
         if sup and apply_info.SUid != sup.SUid:
             raise ParamsError('只能删除自己提交的申请')
         if apply_info.MBAstatus not in [
                 ApplyStatus.cancle.value, ApplyStatus.reject.value,
                 ApplyStatus.shelves.value
         ]:
             raise StatusError('只能删除已下架、已拒绝、已撤销状态下的申请')
         apply_info.isdelete = True
         MagicBoxApplySku.query.filter_by_(MBAid=apply_info.MBAid).delete_()
         if is_admin():
             BASEADMIN().create_action(AdminActionS.delete.value,
                                       'MagicBoxApply', mbaid)
     return Success('删除成功', {'mbaid': mbaid})
Example #26
0
    def on_send_msg(self, data):
        current_app.logger.info(data)
        userid = session.get('id')

        current_app.logger.info('send message', userid)
        if not userid:
            return return_res(AuthorityError)
        roomid = data.get('roid')
        message = data.get('umsgtext')
        umsgtype = data.get('umsgtype') or 0
        try:
            umsgtype = UserMessageTyep(int(umsgtype)).value
        except:
            umsgtype = 0

        if message == "":
            return return_res(ParamsError('内容不能为空'))

        from planet.control.CMessage import CMessage
        cmsg = CMessage()
        umsg = cmsg.send_msg(message, umsgtype, roomid, userid)
        current_app.logger.info('写入成功')
        self.socketio.emit('new_message', umsg, room=roomid)
        current_app.logger.info('发送成功')
        return return_res(Success('发送成功'))
Example #27
0
 def check_file_size(self):
     max_file_size = 50 * 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("上传文件过大,请上传小于50MB的文件")
Example #28
0
    def _pay_to_bankcard(self, cn):
        """
        付款到银行卡号
        :param cn:
        :return:
        """
        try:
            enc_bank_no = self._to_encrypt(cn.CNcardNo)
            enc_true_name = self._to_encrypt(cn.CNcardName)
            bank_code = WexinBankCode(cn.CNbankName).zh_value
        except Exception as e:
            current_app.logger.error('提现到银行卡,参数加密出错:{}'.format(e))
            raise ParamsError('服务器繁忙,请稍后再试')

        try:
            result = self.wx_pay.pay_individual_to_card(
                partner_trade_no=self.wx_pay.nonce_str,
                enc_bank_no=enc_bank_no,
                enc_true_name=enc_true_name,
                bank_code=bank_code,
                amount=int(
                    Decimal(cn.CNcashNum).quantize(Decimal('0.00')) * 100))
            current_app.logger.info('微信提现到银行卡, response: {}'.format(request))
        except Exception as e:
            current_app.logger.error('微信提现返回错误:{}'.format(e))
            raise StatusError('微信商户平台: {}'.format(e))
        return result
Example #29
0
 def _save_excel(self, file, folder):
     """
     保存文件到本地,方便后续读取数据
     :param file:
     :param folder:
     :return:
     """
     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)
         current_app.logger.info(
             ">>>  Upload File Path is  {}  <<<".format(newFile))
         return newFile
     else:
         raise ParamsError(u"不支持的文件类型 '{}' ,请上传正确的Excel模板".format(shuffix))
 def delete(self):
     """删除申请"""
     # if is_supplizer():
     #     usid = request.user.id
     #     sup = Supplizer.query.filter_by_(SUid=usid).first_('供应商信息错误')
     #     suid = sup.SUid
     #     current_app.logger.info('Supplizer {} delete integral apply'.format(sup.SUname))
     if is_admin():
         usid = request.user.id
         admin = Admin.query.filter_by_(ADid=usid).first_('管理员信息错误')
         current_app.logger.info('Admin {} delete integral apply'.format(
             admin.ADname))
         sup = None
         suid = None
     else:
         raise AuthorityError()
     data = parameter_required(('ipid', ))
     ipid = data.get('ipid')
     with db.auto_commit():
         apply_info = IntegralProduct.query.filter_by(
             IPid=ipid, isdelete=False).first_('没有该商品记录')
         if sup and apply_info.SUid != suid:
             raise ParamsError('只能删除自己提交的申请')
         if apply_info.IPstatus not in [
                 ApplyStatus.cancle.value, ApplyStatus.reject.value,
                 ApplyStatus.shelves.value
         ]:
             raise StatusError('只能删除已下架或已撤销状态下的申请')
         apply_info.isdelete = True
         IntegralProductSku.query.filter(
             IntegralProductSku.IPid == apply_info.IPid).delete_()
         if is_admin():
             BASEADMIN().create_action(AdminActionS.delete.value,
                                       'IntegralProduct', apply_info.IPid)
     return Success('删除成功', {'ipid': ipid})