コード例 #1
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('该订单售后处理中,请等待处理结果')
コード例 #2
0
    def send(self):
        """发货"""
        data = parameter_required(('omid', 'olcompany', 'olexpressno'))
        omid = data.get('omid')
        olcompany = data.get('olcompany')
        olexpressno = data.get('olexpressno')
        with self.strade.auto_commit() as s:
            s_list = []
            order_main_instance = s.query(OrderMain).filter_by_({
                'OMid': omid,
            }).first_('订单不存在')

            if order_main_instance.OMfrom == OrderFrom.guess_group.value:
                guess_group = GuessGroup.query.outerjoin(
                    OrderPart,
                    OrderPart.PRid == GuessGroup.GPid
                ).outerjoin(OrderMain,
                            OrderMain.OMid == OrderPart.OMid
                            ).filter(OrderMain.isdelete == False,
                                     OrderMain.OMstatus == OrderMainStatus.wait_send.value,
                                     OrderPart.OMid == order_main_instance.OMid,
                                     ).first()
                if not guess_group or (guess_group.GGstatus != GuessGroupStatus.completed.value):
                    raise StatusError('该拼团订单尚未完成, 不能提前发货')

            # if order_main_instance.OMstatus != OrderMainStatus.wait_send.value:
            #     raise StatusError('订单状态不正确')
            if order_main_instance.OMinRefund is True:
                raise StatusError('商品在售后状态')
            s.query(LogisticsCompnay).filter_by_({
                'LCcode': olcompany
            }).first_('快递公司不存在')
            # 之前物流记录判断
            order_logistics_instance_old = OrderLogistics.query.filter(
                OrderLogistics.OMid == omid,
                OrderLogistics.isdelete == False,
            ).first()
            if order_logistics_instance_old:
                order_logistics_instance_old.isdelete = True

            # 添加物流记录
            order_logistics_instance = OrderLogistics.create({
                'OLid': str(uuid.uuid1()),
                'OMid': omid,
                'OLcompany': olcompany,
                'OLexpressNo': olexpressno,
            })
            s_list.append(order_logistics_instance)
            # 更改主单状态
            order_main_instance.OMstatus = OrderMainStatus.wait_recv.value
            s_list.append(order_main_instance)
            s.add_all(s_list)
        return Success('发货成功')
コード例 #3
0
    def shelves(self):
        """下架申请"""
        if is_supplizer():
            usid = request.user.id
            sup = Supplizer.query.filter_by_(SUid=usid).first_('供应商信息错误')
            current_app.logger.info('Supplizer {} shelf 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 {} shelf magicbox apply'.format(
                admin.ADname))
            sup = None
        else:
            raise AuthorityError()
        data = parameter_required(('mbaid', ))
        mbaid = data.get('mbaid')
        pending_box = MagicBoxJoin.query.filter(
            MagicBoxJoin.isdelete == False,
            MagicBoxJoin.MBJstatus == MagicBoxJoinStatus.pending.value,
            MagicBoxJoin.MBSendtime >= datetime.now().date(),
            MagicBoxJoin.MBAid == mbaid).first()
        if pending_box:
            current_app.logger.info('仍存在未完成礼盒 MBJid: {}'.format(
                pending_box.MBJid))
            raise StatusError('该商品仍有正在分享中的礼盒未完成,暂不能下架')

        with db.auto_commit():
            apply_info = MagicBoxApply.query.filter_by_(
                MBAid=mbaid).first_('无此申请记录')
            if sup and apply_info.SUid != usid:
                raise StatusError('只能下架自己的申请')
            if apply_info.MBAstatus != ApplyStatus.agree.value:
                raise StatusError('只能下架已通过的申请')
            apply_info.MBAstatus = ApplyStatus.shelves.value
            if is_admin():
                BASEADMIN().create_action(AdminActionS.update.value,
                                          'MagicBoxApply', mbaid)
            # 返回库存
            product = Products.query.filter_by(PRid=apply_info.PRid,
                                               isdelete=False).first_('商品信息出错')
            mbs_old = MagicBoxApplySku.query.filter(
                MagicBoxApplySku.MBAid == apply_info.MBAid,
                MagicBoxApplySku.isdelete == False,
            ).all()
            for sku in mbs_old:
                sku_instance = ProductSku.query.filter_by(
                    isdelete=False, PRid=product.PRid,
                    SKUid=sku.SKUid).first_('商品sku信息不存在')
                super(CMagicBox, self)._update_stock(int(sku.MBSstock),
                                                     product, sku_instance)
        return Success('下架成功', {'mbaid': mbaid})
コード例 #4
0
ファイル: CNews.py プロジェクト: shuaibinliu/python_planet
 def del_news(self):
     """删除资讯"""
     if is_tourist():
         raise TokenError()
     elif is_admin():
         usid = request.user.id
         admin = self._check_admin(usid)
         current_app.logger.info('Admin {0} deleted a news'.format(
             admin.ADname))
     elif is_supplizer():
         usid = request.user.id
         sup = self._check_supplizer(usid)
         current_app.logger.info('Supplizer {0} deleted a news'.format(
             sup.SUname))
     else:
         usid = request.user.id
         user = self.snews.get_user_by_id(usid)
         current_app.logger.info('User {0} deleted a news'.format(
             user.USname))
     data = parameter_required(('neid', ))
     neids = data.get('neid')
     with db.auto_commit():
         for neid in neids:
             news = News.query.filter_by_(NEid=neid).first_('未找到该资讯或已被删除')
             if is_admin():
                 if news.NEstatus != NewsStatus.refuse.value:
                     raise StatusError('只能删除已下架状态的资讯')
             else:
                 if news.USid != usid:
                     raise StatusError('只能删除自己发布的资讯')
             News.query.filter_by(NEid=neid, isdelete=False).delete_()
             NewsTag.query.filter_by(NEid=neid).delete_()  # 删除标签关联
             NewsComment.query.filter_by(NEid=neid).delete_()  # 删除评论
             NewsFavorite.query.filter_by(NEid=neid).delete_()  # 删除点赞
             NewsTrample.query.filter_by(NEid=neid).delete_()  # 删除点踩
             # 如果在审核中,同时取消在进行的审批流
             try:
                 if news.NEstatus == NewsStatus.auditing.value:
                     approval_info = Approval.query.filter_by_(
                         AVcontent=neid,
                         AVstartid=news.USid,
                         AVstatus=ApplyStatus.wait_check.value).first()
                     approval_info.update(
                         {'AVstatus': ApplyStatus.cancle.value})
                     db.session.add(approval_info)
             except Exception as e:
                 current_app.logger.error('删除圈子相关审批流时出错: {}'.format(e))
     return Success('删除成功', {'neid': neids})
コード例 #5
0
ファイル: CCoupon.py プロジェクト: haobin12358/python_planet
    def create_code(self):
        data = parameter_required(('coid', 'conum'))
        coid = data.get('coid')
        conum = data.get('conum')
        with db.auto_commit():
            coupon = Coupon.query.filter_by(COid=coid,
                                            isdelete=False,
                                            COcode=1).first_('该优惠券不能生成兑换码')
            # 校验剩余数量
            if coupon.COlimitNum:
                if int(coupon.COremainNum) < int(conum):
                    raise StatusError('兑换数量超过剩余数量')
                coupon.update(
                    {'COremainNum': int(coupon.COremainNum) - int(conum)})
            # isinstance_list = [coupon]
            db.session.add(coupon)
            for _ in range(int(data.get('conum'))):
                ccid = str(uuid.uuid1())
                cccode = self.coupen_code()
                coupon_code = CouponCode.create({
                    'CCid': ccid,
                    'COid': coid,
                    'CCcode': cccode
                })
                db.session.add(coupon_code)
                BASEADMIN().create_action(AdminActionS.insert.value,
                                          'CouponCode', coid)
                db.session.flush()

        return Success('生成激活码成功', data={'coid': coid, 'conum': conum})
コード例 #6
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)
コード例 #7
0
 def del_commodity(self):
     """删除试用商品"""
     if is_supplizer():
         usid = request.user.id
         sup = self._check_supplizer(usid)
         current_app.logger.info('Supplizer {} delete commodity'.format(
             sup.SUname))
     elif is_admin():
         usid = request.user.id
         admin = self._check_admin(usid)
         current_app.logger.info('Admin {} delete commodity'.format(
             admin.ADname))
         sup = None
     else:
         raise AuthorityError()
     data = parameter_required(("tcid", ))
     tcid = data.get('tcid')
     commodity = TrialCommodity.query.filter_by_(
         TCid=tcid).first_('未找到商品信息, tcid参数异常')
     if sup:
         assert commodity.CreaterId == usid, '供应商只能删除自己上传的商品'
     if commodity.TCstatus not in [
             TrialCommodityStatus.reject.value,
             TrialCommodityStatus.cancel.value
     ]:
         raise StatusError('只能删除已下架或已撤销的商品')
     with db.auto_commit():
         TrialCommodity.query.filter_by(TCid=tcid).delete_()
         TrialCommodityImage.query.filter_by(TCid=tcid).delete_()
         TrialCommoditySku.query.filter_by(TCid=tcid).delete_()
         TrialCommoditySkuValue.query.filter_by(TCid=tcid).delete_()
     return Success('删除成功', {'tcid': tcid})
コード例 #8
0
ファイル: CPay.py プロジェクト: haobin12358/python_planet
    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
コード例 #9
0
 def shelves(self):
     """批量下架试用商品"""
     if is_supplizer():
         usid = request.user.id
         sup = self._check_supplizer(usid)
         current_app.logger.info('Supplizer {} shelves commodity'.format(
             sup.SUname))
     elif is_admin():
         usid = request.user.id
         admin = self._check_admin(usid)
         current_app.logger.info('Admin {} shelves commodity'.format(
             admin.ADname))
         sup = None
     else:
         raise AuthorityError()
     data = parameter_required(("tcids", ))
     tcid_list = data.get('tcids')
     for tcid in tcid_list:
         commodity = TrialCommodity.query.filter_by_(
             TCid=tcid).first_('未找到商品信息, tcid参数异常')
         if sup:
             assert commodity.CreaterId == usid, '供应商只能下架自己上传的商品'
         if commodity.TCstatus != TrialCommodityStatus.upper.value:
             raise StatusError('只能下架正在上架状态的商品')
         with db.auto_commit():
             commodity.TCstatus = TrialCommodityStatus.reject.value
     return Success('下架成功', {'tcid': tcid_list})
コード例 #10
0
 def resubmit_apply(self):
     """重新提交申请"""
     if is_supplizer():
         usid = request.user.id
         sup = self._check_supplizer(usid)
         current_app.logger.info('Supplizer {} resubmit commodity'.format(
             sup.SUname))
         nefrom = ApplyFrom.supplizer.value
     elif is_admin():
         usid = request.user.id
         admin = self._check_admin(usid)
         current_app.logger.info('Admin {} resubmit commodity'.format(
             admin.ADname))
         nefrom = ApplyFrom.platform.value
         sup = None
     else:
         raise AuthorityError()
     data = parameter_required(('tcid', ))
     tcid = data.get('tcid')
     with db.auto_commit():
         commodity = TrialCommodity.query.filter_by_(
             TCid=tcid).first_('无此商品信息')
         if commodity.TCstatus not in [
                 TrialCommodityStatus.cancel.value,
                 TrialCommodityStatus.reject.value
         ]:
             raise StatusError('只有撤销或已下架状态的申请可以重新提交')
         if sup:
             if commodity.CreaterId != usid:
                 raise AuthorityError('仅可重新提交自己上传的商品')
         commodity.TCstatus = TrialCommodityStatus.auditing.value
         # 重新创建一个审批流
     super().create_approval('totrialcommodity', usid, tcid, nefrom)
     return Success('提交成功', {'tcid': tcid})
コード例 #11
0
 def shelves(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:
             assert apply_info.SUid == usid, '供应商只能下架自己的申请'
         if apply_info.MBAstatus != ApplyStatus.agree.value:
             raise StatusError('只能下架已通过的申请')
         apply_info.MBAstatus = ApplyStatus.reject.value
     return Success('下架成功', {'mbaid': mbaid})
コード例 #12
0
 def cancel_commodity_apply(self):
     """撤销自己的申请"""
     if is_supplizer():
         usid = request.user.id
         sup = self._check_supplizer(usid)
         current_app.logger.info('Supplizer {} cancel commodity'.format(
             sup.SUname))
     elif is_admin():
         usid = request.user.id
         admin = self._check_admin(usid)
         current_app.logger.info('Admin {} cancel commodity'.format(
             admin.ADname))
     else:
         raise AuthorityError()
     data = parameter_required(('tcid', ))
     tcid = data.get('tcid')
     with db.auto_commit():
         commodity = TrialCommodity.query.filter_by_(
             TCid=tcid).first_('无此商品信息')
         if commodity.TCstatus != TrialCommodityStatus.auditing.value:
             raise StatusError('只有在审核状态的申请可以撤销')
         if commodity.CreaterId != request.user.id:
             raise AuthorityError('仅可撤销自己提交的申请')
         commodity.TCstatus = TrialCommodityStatus.cancel.value
         # 同时将正在进行的审批流改为取消
         approval_info = Approval.query.filter_by_(
             AVcontent=tcid,
             AVstartid=request.user.id,
             AVstatus=ApplyStatus.wait_check.value).first()
         approval_info.AVstatus = ApplyStatus.cancle.value
     return Success('取消成功', {'tcid': tcid})
コード例 #13
0
 def shelf_award(self):
     """撤销申请"""
     if not (is_supplizer() or is_admin()):
         raise AuthorityError()
     data = parameter_required(('mbaid', ))
     mbaid = data.get('mbaid')
     with db.auto_commit():
         apply_info = MagicBoxApply.query.filter_by_(
             MBAid=mbaid).first_('无此申请记录')
         other_apply_info = MagicBoxApply.query.filter(
             MagicBoxApply.isdelete == False,
             MagicBoxApply.MBAid != mbaid,
             MagicBoxApply.MBAstatus.notin_(
                 [ApplyStatus.cancle.value, ApplyStatus.reject.value]),
             MagicBoxApply.OSid == apply_info.OSid,
         ).first()
         current_app.logger.info("其他的同库存申请 --> {}".format(other_apply_info))
         if apply_info.MBAstatus != ApplyStatus.wait_check.value:
             raise StatusError('只有在审核状态的申请可以撤销')
         if apply_info.SUid != request.user.id:
             raise AuthorityError('仅可撤销自己提交的申请')
         apply_info.MBAstatus = ApplyStatus.cancle.value
         # 是否修改库存
         if not other_apply_info:
             out_stock = OutStock.query.filter(
                 OutStock.isdelete == False,
                 OutStock.OSid == apply_info.OSid).first()
             self._update_stock(out_stock.OSnum, skuid=apply_info.SKUid)
         # 同时将正在进行的审批流改为取消
         approval_info = Approval.query.filter_by_(
             AVcontent=mbaid,
             AVstartid=request.user.id,
             AVstatus=ApplyStatus.wait_check.value).first()
         approval_info.AVstatus = ApplyStatus.cancle.value
     return Success('取消成功', {'mbaid': mbaid})
コード例 #14
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:
             assert apply_info.SUid == usid, '供应商只能删除自己提交的申请'
         if apply_info.MBAstatus not in [
                 ApplyStatus.cancle.value, ApplyStatus.reject.value
         ]:
             raise StatusError('只能删除已拒绝或已撤销状态下的申请')
         apply_info.isdelete = True
     return Success('删除成功', {'mbaid': mbaid})
コード例 #15
0
ファイル: CTicket.py プロジェクト: haobin12358/python_planet
 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)
コード例 #16
0
 def send(self):
     """买家发货"""
     form = RefundSendForm().valid_data()
     oraid = form.oraid.data
     orlogisticcompany = form.orlogisticcompany.data
     orlogisticsn = form.orlogisticsn.data
     with self.strade.auto_commit() as s:
         # 判断
         s.query(LogisticsCompnay).filter_by_({
             'LCcode': orlogisticcompany
         }).first_('物流公司不存在')
         order_refund_instance = s.query(OrderRefund).filter_by_({
             'ORAid':
             oraid
         }).first_('申请未同意或不存在')
         if order_refund_instance.ORstatus > OrderRefundOrstatus.wait_send.value:
             raise StatusError('重复发货')
         # 写入退货表
         order_refund_instance.update({
             'ORlogisticCompany':
             orlogisticcompany,
             'ORlogisticsn':
             orlogisticsn,
             'ORstatus':
             OrderRefundOrstatus.wait_recv.value,
         })
         s.add(order_refund_instance)
     return Success('发货成功')
コード例 #17
0
    def delete(self):
        """删除"""
        data = parameter_required(('suid', ))
        suid = data.get('suid')
        with db.auto_commit():
            supplizer = Supplizer.query.filter(
                Supplizer.isdelete == False,
                Supplizer.SUid == suid).first_('供应商不存在')
            if self._check_lasting_order(suid=suid):
                raise StatusError('供应商部分订单正在进行')

            supplizer.isdelete = True
            db.session.add(supplizer)
            BASEADMIN().create_action(AdminActionS.delete.value, 'Supplizer',
                                      suid)
            # 品牌删除
            productbrands = ProductBrand.query.filter(
                ProductBrand.isdelete == False,
                ProductBrand.SUid == suid).all()
            current_app.logger.info('删除供应商{}'.format(supplizer.SUname))
            for pb in productbrands:
                pb.isdelete = True
                db.session.add(pb)
                # 商品删除
                delete_product = Products.query.filter(
                    Products.isdelete == False,
                    Products.PBid == pb.PBid).update(
                        {'PRstatus': ProductStatus.off_shelves.value})
        return Success('删除成功')
コード例 #18
0
 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})
コード例 #19
0
ファイル: CNews.py プロジェクト: shuaibinliu/python_planet
 def create_comment(self):
     usid = request.user.id
     user = self.snews.get_user_by_id(usid)
     usname, usheader = user.USname, user.USheader
     current_app.logger.info('User {0}  created a news commentary'.format(
         user.USname))
     data = parameter_required(('neid', 'nctext'))
     neid = data.get('neid')
     new_info = self.snews.get_news_content({
         'NEid': neid,
         'isdelete': False
     })
     if new_info.NEstatus != NewsStatus.usual.value:
         raise StatusError('该资讯当前状态不允许进行评论')
     ncid = data.get('ncid')
     comment_ncid = str(uuid.uuid1())
     reply_ncid = str(uuid.uuid1())
     # 直接评论资讯
     if ncid in self.empty:
         with self.snews.auto_commit() as nc:
             comment = NewsComment.create({
                 'NCid': comment_ncid,
                 'NEid': neid,
                 'USid': usid,
                 'USname': usname,
                 'USheader': usheader,
                 'NCtext': data.get('nctext'),
             })
             nc.add(comment)
         # 评论后返回刷新结果
         news_comment = NewsComment.query.filter_by_(
             NCid=comment_ncid).first()
         self._get_one_comment(news_comment, neid, usid)
     else:
         # 回复资讯评论
         ori_news_comment = NewsComment.query.filter(
             NewsComment.NCid == ncid,
             NewsComment.isdelete == False).first()
         if not ori_news_comment:
             raise NotFound('该评论已删除')
         ncrootid = ori_news_comment.NCrootid
         if not ncrootid:
             ncrootid = ncid
         with self.snews.auto_commit() as r:
             reply = NewsComment.create({
                 'NCid': reply_ncid,
                 'NEid': neid,
                 'USid': usid,
                 'USname': usname,
                 'USheader': usheader,
                 'NCtext': data.get('nctext'),
                 'NCparentid': ncid,
                 'NCrootid': ncrootid,
             })
             r.add(reply)
         # 评论后返回刷新结果
         news_comment = NewsComment.query.filter_by_(NCid=ncrootid).first()
         self._get_one_comment(news_comment, neid, usid)
     return Success('评论成功', data=news_comment)
コード例 #20
0
ファイル: CCoupon.py プロジェクト: haobin12358/python_planet
 def code(self):
     """兑换码领优惠劵"""
     usid = request.user.id
     data = parameter_required(('cccode', ))
     CCcode = data.get('cccode')
     with self.strade.auto_commit() as s:
         s_list = []
         couponcode = s.query(CouponCode).filter_by_({
             'CCcode': CCcode
         }).first_('兑换码不存在')
         if couponcode.CCused:
             raise ParamsError('兑换码已被使用')
         coid = couponcode.COid
         coupon = s.query(Coupon).filter_by_({'COid': coid}).first_()
         # 优惠券状态是否可领取
         coupon_user_count = s.query(CouponUser).filter_by_({
             'COid': coid,
             'USid': usid
         }).count()
         # 领取过多
         if coupon.COcollectNum and coupon_user_count >= coupon.COcollectNum:
             raise StatusError('已经领取过')
         # 发放完毕或抢空
         # 2019-4-27 兑换码创建时保证库存
         # if coupon.COlimitNum:
         #     # 共领取的数量
         #     if not coupon.COremainNum:
         #         raise StatusError('已发放完毕')
         #     coupon.COremainNum = coupon.COremainNum - 1  # 剩余数量减1
         #     s_list.append(coupon)
         if coupon.COsendStarttime and coupon.COsendStarttime > datetime.now(
         ):
             raise StatusError('未开抢')
         if coupon.COsendEndtime and coupon.COsendEndtime < datetime.now():
             raise StatusError('来晚了')
         # 写入couponuser
         coupon_user_dict = {
             'UCid': str(uuid.uuid4()),
             'COid': coid,
             'USid': usid,
         }
         coupon_user_instance = CouponUser.create(coupon_user_dict)
         # 优惠券减1
         s_list.append(coupon_user_instance)
         s.add_all(s_list)
     return Success('领取成功')
コード例 #21
0
 def shelf(self):
     """下架"""
     # if is_supplizer():
     #     usid = request.user.id
     #     sup = Supplizer.query.filter_by_(SUid=usid).first_('供应商信息错误')
     #     current_app.logger.info('Supplizer {} shelf 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 {} shelf integral apply'.format(
             admin.ADname))
         sup = None
     else:
         raise AuthorityError()
     data = parameter_required(('ipid', ))
     ipid = data.get('ipid')
     with db.auto_commit():
         ip = IntegralProduct.query.filter_by_(IPid=ipid).first_('无此申请记录')
         if sup and ip.SUid != usid:
             raise StatusError('只能下架自己的商品')
         if ip.IPstatus != ApplyStatus.agree.value:
             raise StatusError('只能下架已上架的商品')
         ip.IPstatus = ApplyStatus.shelves.value
         if is_admin():
             BASEADMIN().create_action(AdminActionS.update.value,
                                       'IntegralProduct', ipid)
         # 返回库存
         product = Products.query.filter_by(PRid=ip.PRid,
                                            isdelete=False).first_('商品信息出错')
         ips_old = IntegralProductSku.query.filter(
             IntegralProductSku.IPid == ip.IPid,
             IntegralProductSku.isdelete == False,
             IntegralProduct.isdelete == False,
         ).all()
         for sku in ips_old:
             sku_instance = ProductSku.query.filter_by(
                 isdelete=False, PRid=product.PRid,
                 SKUid=sku.SKUid).first_('商品sku信息不存在')
             super(CIntegralStore,
                   self)._update_stock(int(sku.IPSstock), product,
                                       sku_instance)
     return Success('下架成功', {'ipid': ipid})
コード例 #22
0
 def fetch(self):
     """领取优惠券"""
     form = CouponFetchForm().valid_data()
     coid = form.coid.data
     usid = request.user.id
     with self.strade.auto_commit() as s:
         s_list = []
         # 优惠券状态是否可领取
         coupon = s.query(Coupon).filter_by_({
             'COid': coid,
             'COcanCollect': True
         }).first_('优惠券不存在或不可领取')
         coupon_user_count = s.query(CouponUser).filter_by_({
             'COid': coid,
             'USid': usid
         }).count()
         # 领取过多
         if coupon.COcollectNum and coupon_user_count > coupon.COcollectNum:
             raise StatusError('已经领取过')
         # 发放完毕或抢空
         if coupon.COlimitNum:
             # 共领取的数量
             if not coupon.COremainNum:
                 raise StatusError('已发放完毕')
             coupon.COremainNum = coupon.COremainNum - 1  # 剩余数量减1
             s_list.append(coupon)
         if coupon.COsendStarttime and coupon.COsendStarttime > datetime.now(
         ):
             raise StatusError('未开抢')
         if coupon.COsendEndtime and coupon.COsendEndtime < datetime.now():
             raise StatusError('来晚了')
         # 写入couponuser
         coupon_user_dict = {
             'UCid': str(uuid.uuid4()),
             'COid': coid,
             'USid': usid,
         }
         coupon_user_instance = CouponUser.create(coupon_user_dict)
         # 优惠券减1
         s_list.append(coupon_user_instance)
         s.add_all(s_list)
     return Success('领取成功')
コード例 #23
0
 def shelf(self):
     """下架"""
     if is_supplizer():
         usid = request.user.id
         sup = Supplizer.query.filter_by_(SUid=usid).first_('供应商信息错误')
         current_app.logger.info('Supplizer {} shelf guess group apply'.format(sup.SUname))
     elif is_admin():
         usid = request.user.id
         admin = Admin.query.filter_by_(ADid=usid).first_('管理员信息错误')
         current_app.logger.info('Admin {} shelf guess group apply'.format(admin.ADname))
         sup = None
     else:
         raise AuthorityError()
     data = parameter_required(('gpid',))
     gpid = data.get('gpid')
     pending_group = GuessGroup.query.filter(GuessGroup.isdelete == False,
                                             GuessGroup.GGstatus.in_((GuessGroupStatus.pending.value,
                                                                      GuessGroupStatus.waiting.value)),
                                             GuessGroup.GGendtime >= datetime.datetime.now(),
                                             GuessGroup.GPid == gpid).first()
     if pending_group:
         raise StatusError('该商品仍有拼团未完成,暂不能下架')
     with db.auto_commit():
         gp = GroupGoodsProduct.query.filter_by_(GPid=gpid).first_('无此申请记录')
         if sup and gp.SUid != usid:
             raise StatusError('只能下架自己的商品')
         if gp.GPstatus != ApplyStatus.agree.value:
             raise StatusError('只能下架已上架的商品')
         gp.GPstatus = ApplyStatus.shelves.value
         if is_admin():
             BASEADMIN().create_action(AdminActionS.update.value, 'GroupGoodsProduct', gpid)
         # 返回库存
         product = Products.query.filter_by(PRid=gp.PRid, isdelete=False).first_('商品信息出错')
         gps_old = GroupGoodsSku.query.filter(GroupGoodsSku.GPid == gp.GPid,
                                              GroupGoodsSku.isdelete == False,
                                              ).all()
         for sku in gps_old:
             sku_instance = ProductSku.query.filter_by(isdelete=False, PRid=product.PRid,
                                                       SKUid=sku.SKUid).first_('商品sku信息不存在')
             super(CGuessGroup, self)._update_stock(int(sku.GSstock), product, sku_instance)
     return Success('下架成功', {'gpid': gpid})
コード例 #24
0
    def shelf_award(self):
        """撤销申请"""
        if not (is_supplizer() or is_admin()):
            raise AuthorityError()
        data = parameter_required(('tlpid', ))
        tlpid = data.get('tlpid')
        if is_supplizer():
            tlp_from = ApplyFrom.supplizer.value
            suid = request.user.id

        else:
            tlp_from = ApplyFrom.platform.value

            suid = None
        with db.auto_commit():
            apply_info = TimeLimitedProduct.query.filter_by(
                TLPid=tlpid, isdelete=False).first_('无此申请记录')

            if apply_info.TLAstatus != ApplyStatus.wait_check.value:
                raise StatusError('只有在审核状态的申请可以撤销')
            if apply_info.SUid != suid:
                raise AuthorityError('仅可撤销自己提交的申请')
            apply_info.TLAstatus = ApplyStatus.cancle.value

            # 获取原商品属性
            # gnap_old = GuessNumAwardProduct.query.filter(GuessNumAwardProduct.GNAAid == apply_info.GNAAid,
            #                                                 GuessNumAwardProduct.isdelete == False).first()
            product = Products.query.filter_by(PRid=apply_info.PRid,
                                               PRfrom=tlp_from,
                                               isdelete=False).first_('商品信息出错')
            # 获取原sku属性
            tls_list = TimeLimitedSku.query.filter(
                TimeLimitedSku.isdelete == False,
                TimeLimitedSku.TLPid == apply_info.TLPid).all()

            # 遍历原sku 将库存退出去
            for sku in tls_list:
                sku_instance = ProductSku.query.filter_by(
                    isdelete=False, PRid=product.PRid,
                    SKUid=sku.SKUid).first_('商品sku信息不存在')
                self._update_stock(int(sku.TLSstock), product, sku_instance)

            # 同时将正在进行的审批流改为取消 todo
            approval_info = Approval.query.filter_by(
                AVcontent=tlpid,
                AVstartid=request.user.id,
                isdelete=False,
                AVstatus=ApplyStatus.wait_check.value).first()
            approval_info.AVstatus = ApplyStatus.cancle.value
            if is_admin():
                BASEADMIN().create_action(AdminActionS.update.value,
                                          'TimeLimitedProduct', tlpid)
        return Success('取消成功', {'tlpid': tlpid})
コード例 #25
0
ファイル: CTicket.py プロジェクト: haobin12358/python_planet
 def _patch_ticket_order(self, tsoid, user, opayno, instance_list, tscode_list):
     tso = TicketsOrder.query.filter(TicketsOrder.isdelete == false(), TicketsOrder.TSOid == tsoid,
                                     TicketsOrder.USid == user.USid).first_('未找到该信息')
     if tso.TSOstatus != TicketsOrderStatus.has_won.value:
         raise StatusError('支付条件未满足')
     ticket = Ticket.query.filter(Ticket.isdelete == false(), Ticket.TIid == tso.TIid
                                  ).first_('未找到该门票信息')
     mount_price = ticket.TIprice - ticket.TIdeposit
     ticket_deposit = self._creat_ticket_deposit(tsoid, TicketDepositType.patch.value, mount_price, opayno)
     instance_list.append(ticket_deposit)
     tscode_list.append(tso.TSOcode)
     return ticket, mount_price, instance_list, tscode_list
コード例 #26
0
ファイル: CItems.py プロジェクト: haobin12358/python_planet
    def update(self):
        """修改标签"""
        form = ItemUpdateForm().valid_data()
        psid = form.psid.data
        itid = form.itid.data
        itname = form.itname  # 这里不要在后面加data
        isdelete = form.isdelete.data
        if itid in ['planet_featured', 'index_hot', 'news_bind_product', 'news_bind_coupon', 'index_brand',
                    'index_brand_product', 'index_recommend_product_for_you', 'upgrade_product', 'mynews'
                    ] and isdelete is True:
            raise StatusError('系统默认标签不能被删除')

        Items.query.filter_by_(ITid=itid).first_("未找到该标签")
        if not isdelete and Items.query.filter(Items.ITid != itid, Items.ITname == itname,
                                               Items.ITtype == form.ittype.data, Items.isdelete == False).first():
            raise DumpliError("您输入的标签名已存在")
        with db.auto_commit():
            itsort = self._check_itsort(form.itsort.data, form.ittype.data)
            item_dict = {'ITname': itname,
                         'ITsort': itsort,
                         'ITdesc': form.itdesc.data,
                         'ITtype': form.ittype.data,
                         'ITrecommend': form.itrecommend.data,
                         'isdelete': isdelete
                         }
            # item_dict = {k: v for k, v in item_dict.items() if v is not None}
            Items.query.filter_by_(ITid=itid).update(item_dict)
            BASEADMIN().create_action(AdminActionS.update.value, 'Items', itid)
            # 标签场景标签表
            if psid:
                old_psids = list()
                scene_items = SceneItem.query.filter_by_(ITid=itid).all()
                [old_psids.append(scene_item.PSid) for scene_item in scene_items]  # 获取已存在的关联psid
                for psi in psid:
                    ProductScene.query.filter_by_({'PSid': psi}).first_('不存在的场景')
                    if psi not in old_psids:
                        scene_item_dict = {
                            'PSid': psi,
                            'ITid': itid,
                            'SIid': str(uuid.uuid1())
                        }
                        scene_item_instance = SceneItem.create(scene_item_dict)
                        db.session.add(scene_item_instance)
                        BASEADMIN().create_action(AdminActionS.insert.value, 'SceneItem', psi)
                    else:
                        old_psids.remove(psi)
                [SceneItem.query.filter_by(PSid=droped_psid, ITid=itid).delete_() for droped_psid in old_psids]
            else:
                SceneItem.query.filter_by(ITid=itid).delete_()  # psid = [] 为空时,删除所有该标签场景的关联
                BASEADMIN().create_action(AdminActionS.delete.value, 'SceneItem', itid)
        return Success('修改成功', {'itid': itid})
コード例 #27
0
 def del_award(self):
     """删除申请"""
     if not is_supplizer() and not is_admin():
         raise AuthorityError()
     form = ShelfFreshManfirstOrder().valid_data()
     fmfaid = form.fmfaid.data
     with db.auto_commit():
         apply_info = FreshManFirstApply.query.filter_by_(FMFAid=fmfaid).first_('申请未找到或已删除')
         if is_supplizer():
             assert apply_info.SUid == request.user.id, '供应商只能删除自己提交的申请'
         if apply_info.FMFAstatus not in [ApplyStatus.cancle.value, ApplyStatus.reject.value]:
             raise StatusError('只能删除已拒绝或已撤销状态下的申请')
         apply_info.isdelete = True
         if is_admin():
             BASEADMIN().create_action(AdminActionS.delete.value, 'FreshManFirstApply', fmfaid)
     return Success('删除成功', {'fmfaid': fmfaid})
コード例 #28
0
ファイル: CPay.py プロジェクト: haobin12358/python_planet
 def _pay_to_user(self, cn):
     """
     付款到用户微信零钱
     :return:
     """
     user = User.query.filter_by_(USid=cn.USid).first_("提现用户状态异常,请检查后重试")
     try:
         result = self.wx_pay.pay_individual(
             partner_trade_no=self.wx_pay.nonce_str,
             openid=user.USopenid2,
             amount=int(
                 Decimal(cn.CNcashNum).quantize(Decimal('0.00')) * 100),
             desc="大行星零钱转出",
             spbill_create_ip=self.wx_pay.remote_addr)
         current_app.logger.info('微信提现到零钱, response: {}'.format(request))
     except Exception as e:
         current_app.logger.error('微信提现返回错误:{}'.format(e))
         raise StatusError('微信商户平台: {}'.format(e))
     return result
コード例 #29
0
ファイル: CTicket.py プロジェクト: haobin12358/python_planet
    def _deposit_refund(self, to_info):
        usid, tiid, tsoids = to_info
        tsoids = tsoids.split(',')
        current_app.logger.info('deposit refund, TSOids:{}'.format(tsoids))
        td_info = db.session.query(TicketDeposit.OPayno, func.sum(TicketDeposit.TDdeposit)
                                   ).filter(TicketDeposit.isdelete == false(),
                                            TicketDeposit.TSOid.in_(tsoids)).group_by(TicketDeposit.OPayno).all()
        current_app.logger.info('td_info:{}'.format(td_info))
        for td in td_info:
            opayno, return_price = td
            current_app.logger.info('found refund opayno: {}, mount:{}'.format(opayno, return_price))
            mount_price = db.session.query(func.sum(TicketDeposit.TDdeposit)).filter(
                TicketDeposit.isdelete == false(),
                TicketDeposit.OPayno == opayno).scalar()
            current_app.logger.info('refund mount: {}; total deposit:{}'.format(return_price, mount_price))
            current_app.logger.info('refund usid: {}'.format(usid))

            if API_HOST != 'https://www.bigxingxing.com':
                mount_price = 0.01
                return_price = 0.01
            trr = TicketRefundRecord.create({'TRRid': str(uuid.uuid1()),
                                             'USid': usid,
                                             'TRRredund': return_price,
                                             'TRRtotal': mount_price,
                                             'OPayno': opayno})
            db.session.add(trr)
            try:
                super(CTicket, self)._refund_to_user(
                    out_trade_no=opayno,
                    out_request_no=trr.TRRid,
                    mount=return_price,
                    old_total_fee=mount_price
                )
            except Exception as e:
                raise StatusError('微信商户平台:{}'.format(e))

        row_count = TicketsOrder.query.filter(TicketsOrder.isdelete == false(),
                                              TicketsOrder.TSOid.in_(tsoids)
                                              ).update({'TSOstatus': TicketsOrderStatus.not_won.value},
                                                       synchronize_session=False)
        current_app.logger.info('change status to not won, count: {}'.format(row_count))
        return row_count
コード例 #30
0
 def join(self):
     """参与活动, 分享前(或分享后调用), 创建用户的参与记录
     """
     # 判断帮拆活动总控制是否结束
     Activity.query.filter_by({
         'ACtype': ActivityType.magic_box.value
     }).first_('活动已结束')
     form = MagicBoxJoinForm().valid_data()
     mbaid = form.mbaid.data
     usid = request.user.id
     with db.auto_commit():
         today = date.today()
         magic_box_apply = MagicBoxApply.query.filter_by_().filter(
             MagicBoxApply.AgreeStartime <= today,
             MagicBoxApply.AgreeEndtime >= today,
             MagicBoxApply.MBAid == mbaid).first_('活动结束')
         # 已参与则不再新建记录
         magic_box_join = MagicBoxJoin.query.filter_by_({
             'USid': usid,
             'MBAid': mbaid
         }).first()
         if not magic_box_join:
             # 一期活动只可参与一次
             magic_box_join = MagicBoxJoin.create({
                 'MBJid':
                 str(uuid.uuid1()),
                 'USid':
                 usid,
                 'MBAid':
                 mbaid,
                 'MBJprice':
                 magic_box_apply.SKUprice,
             })
             db.session.add(magic_box_join)
         else:
             # 但是可以多次分享
             if magic_box_join.MBJstatus == ActivityRecvStatus.ready_recv.value:
                 raise StatusError('本期已参与')
     return Success('参与成功', data={'mbjid': magic_box_join.MBJid})