Ejemplo n.º 1
0
    def create_order(self):
        data = parameter_required(
            ('tcid', 'pbid', 'skuid', 'omclient', 'uaid', 'opaytype'))
        usid = request.user.id
        user = self._verify_user(usid)
        current_app.logger.info('User {} is buying a trialcommodity'.format(
            user.USname))
        if user.USlevel != UserIdentityStatus.agent.value:
            raise AuthorityError('试用商品仅店主可购,请升级为店主后再次购买')
        uaid = data.get('uaid')
        tcid = data.get('tcid')
        opaytype = data.get('opaytype')  # 支付方式
        try:
            omclient = int(data.get('omclient', Client.wechat.value))  # 下单设备
            Client(omclient)
        except Exception:
            raise ParamsError('客户端来源错误')
        with db.auto_commit():
            # 用户的地址信息
            user_address_instance = db.session.query(UserAddress).filter_by_({
                'UAid':
                uaid,
                'USid':
                usid
            }).first_('地址信息不存在')
            omrecvphone = user_address_instance.UAphone
            areaid = user_address_instance.AAid
            # 地址拼接
            area, city, province = db.session.query(
                AddressArea, AddressCity, AddressProvince).filter(
                    AddressArea.ACid == AddressCity.ACid,
                    AddressCity.APid == AddressProvince.APid).filter(
                        AddressArea.AAid == areaid).first_('地址有误')
            address = getattr(province, "APname", '') + getattr(
                city, "ACname", '') + getattr(area, "AAname", '')
            omrecvaddress = address + user_address_instance.UAtext
            omrecvname = user_address_instance.UAname
            opayno = self.wx_pay.nonce_str
            model_bean = []

            omid = str(uuid.uuid1())
            pbid = data.get('pbid')
            ommessage = data.get('ommessage')
            product_brand_instance = db.session.query(ProductBrand).filter_by_(
                {
                    'PBid': pbid
                }).first_('品牌id: {}不存在'.format(pbid))

            opid = str(uuid.uuid1())
            skuid = data.get('skuid')
            opnum = int(data.get('nums', 1))
            assert opnum > 0, 'nums <= 0, 参数错误'
            sku_instance = db.session.query(TrialCommoditySku).filter_by_({
                'SKUid':
                skuid
            }).first_('skuid: {}不存在'.format(skuid))
            if sku_instance.TCid != tcid:
                raise ParamsError('skuid 与 tcid, 商品不对应')
            assert int(sku_instance.SKUstock) - int(opnum) >= 0, '商品库存不足'
            product_instance = db.session.query(TrialCommodity).filter_by_({
                'TCid':
                tcid
            }).first_('skuid: {}对应的商品不存在'.format(skuid))
            if product_instance.PBid != pbid:
                raise ParamsError('品牌id: {}与skuid: {}不对应'.format(pbid, skuid))
            small_total = Decimal(str(product_instance.TCdeposit)) * opnum
            order_part_dict = {
                'OMid': omid,
                'OPid': opid,
                'PRid': product_instance.TCid,
                'SKUid': skuid,
                'PRattribute': product_instance.TCattribute,
                'SKUattriteDetail': sku_instance.SKUattriteDetail,
                'PRtitle': product_instance.TCtitle,
                'SKUprice': sku_instance.SKUprice,
                'PRmainpic': product_instance.TCmainpic,
                'OPnum': opnum,
                'OPsubTotal': small_total,
                'PRfrom': product_instance.TCfrom,
                'UPperid': user.USid,
                # 'UPperid2': user.USid,
            }
            order_part_instance = OrderPart.create(order_part_dict)
            model_bean.append(order_part_instance)

            # 对应商品销量 + num sku库存 -num
            db.session.query(TrialCommodity).filter_by_(TCid=tcid).update({
                'TCsalesValue':
                TrialCommodity.TCsalesValue + opnum,
                'TCstocks':
                TrialCommodity.TCstocks - opnum
            })
            db.session.query(TrialCommoditySku).filter_by_(SKUid=skuid).update(
                {'SKUstock': TrialCommoditySku.SKUstock - opnum})
            createdid = product_instance.CreaterId if product_instance.TCfrom == ApplyFrom.supplizer.value else None

            # 主单
            order_main_dict = {
                'OMid': omid,
                'OMno': self._generic_omno(),
                'OPayno': opayno,
                'USid': usid,
                'OMfrom': OrderFrom.trial_commodity.value,
                'PBname': product_brand_instance.PBname,
                'PBid': pbid,
                'OMclient': omclient,
                'OMfreight': 0,  # 运费暂时为0 / product_instance.TCfreight
                'OMmount': small_total,
                'OMmessage': ommessage,
                'OMtrueMount': small_total,
                # 收货信息
                'OMrecvPhone': omrecvphone,
                'OMrecvName': omrecvname,
                'OMrecvAddress': omrecvaddress,
                'PRcreateId': createdid,
                'UseCoupon': False  # 试用商品不能使用优惠券
            }
            order_main_instance = OrderMain.create(order_main_dict)
            model_bean.append(order_main_instance)

            # 支付数据表
            order_pay_dict = {
                'OPayid': str(uuid.uuid4()),
                'OPayno': opayno,
                'OPayType': opaytype,
                'OPayMount': small_total,
            }
            order_pay_instance = OrderPay.create(order_pay_dict)
            model_bean.append(order_pay_instance)
            db.session.add_all(model_bean)
        from planet.extensions.tasks import auto_cancle_order
        auto_cancle_order.apply_async(
            args=([omid], ),
            countdown=30 * 60,
            expires=40 * 60,
        )
        # 生成支付信息
        body = product_instance.TCtitle
        pay_args = self._pay_detail(omclient,
                                    opaytype,
                                    opayno,
                                    float(small_total),
                                    body,
                                    openid=user.USopenid1 or user.USopenid2)
        response = {
            'pay_type': PayType(opaytype).name,
            'opaytype': opaytype,
            'args': pay_args
        }
        return Success('创建成功', data=response)
Ejemplo n.º 2
0
    def add_order(self):
        """购买, 返回支付参数"""
        data = parameter_required(('skuid', 'omclient', 'uaid', 'opaytype'))
        try:
            omclient = int(data.get('omclient', Client.wechat.value))  # 下单设备
            Client(omclient)
        except Exception as e:
            raise ParamsError('客户端或商品来源错误')
        # 只可以买一次
        usid = request.user.id
        user = get_current_user()
        exists_order = OrderMain.query.filter(
            OrderMain.USid == usid,
            OrderMain.isdelete == False,
            OrderPart.isdelete == False,
            ProductItems.isdelete == False,
            Items.isdelete == False,
            # OrderMain.USid == usid,
            # OrderMain.OMstatus == OrderMainStatus.ready.value,
            OrderPart.PRid == ProductItems.PRid,
            ProductItems.ITid == Items.ITid,
            Items.ITname != '开店大礼包',
            OrderPart.OMid == OrderMain.OMid,
            OrderMain.OMstatus > OrderMainStatus.wait_pay.value).first()
        # cuser = CUser()
        # cuser._check_gift_order()
        if exists_order:
            raise StatusError('您不是新人')
        try:
            opaytype = int(data.get('opaytype'))
        except ValueError:
            raise StatusError('支付方式异常, 未创建订单')
        skuid = data.get('skuid')
        uaid = data.get('uaid')
        # 该sku是否是活动sku
        today = date.today()
        # 新人商品sku
        fresh_man_sku = FreshManFirstSku.query.join(
            FreshManFirstProduct,
            FreshManFirstSku.FMFPid == FreshManFirstProduct.FMFPid).join(
                FreshManFirstApply, FreshManFirstApply.FMFAid ==
                FreshManFirstProduct.FMFAid).filter(
                    FreshManFirstApply.FMFAstatus == ApplyStatus.agree.value,
                    FreshManFirstApply.AgreeStartime <= today,
                    FreshManFirstApply.AgreeEndtime >= today,
                    FreshManFirstSku.isdelete == False,
                    FreshManFirstProduct.isdelete == False,
                    FreshManFirstApply.isdelete == False,
                    FreshManFirstSku.SKUid == skuid,
                ).first_('当前商品未在活动中')

        with db.auto_commit():
            if fresh_man_sku.FMFPstock is not None:
                if fresh_man_sku.FMFPstock < 0:
                    raise StatusError('库存不足')
                fresh_man_sku.FMFPstock -= 1
                db.session.add(fresh_man_sku)
            Activity.query.filter_by_({
                'ACtype': ActivityType.fresh_man.value,
                'ACshow': True
            }).first_('活动未在进行')
            # 新人商品
            fresh_first_product = FreshManFirstProduct.query.filter_by_({
                'FMFPid':
                fresh_man_sku.FMFPid
            }).first_('当前商品未在活动中')
            # sku详情
            product_sku = ProductSku.query.filter_by_({
                'SKUid': skuid
            }).first_('商品属性已删除')
            # 商品详情
            product_instance = Products.query.filter_by({
                'PRid':
                fresh_first_product.PRid
            }).first_('商品已删除')
            product_category = ProductCategory.query.filter_by(
                PCid=product_instance.PCid).first()
            # 活动申请详情
            fresh_first_apply = FreshManFirstApply.query.filter(
                FreshManFirstApply.isdelete == False,
                FreshManFirstApply.FMFAid == fresh_first_product.FMFAid,
            ).first_('活动不存在')
            suid = fresh_first_apply.SUid if fresh_first_apply.FMFAfrom else None
            # 地址拼接
            user_address_instance = UserAddress.query.filter_by_({
                'UAid': uaid,
                'USid': usid
            }).first_('地址信息不存在')
            omrecvphone = user_address_instance.UAphone
            areaid = user_address_instance.AAid
            area, city, province = db.session.query(
                AddressArea, AddressCity, AddressProvince).filter(
                    AddressArea.ACid == AddressCity.ACid,
                    AddressCity.APid == AddressProvince.APid).filter(
                        AddressArea.AAid == areaid).first_('地址有误')
            address = getattr(province, "APname", '') + getattr(
                city, "ACname", '') + getattr(area, "AAname", '')
            omrecvaddress = address + user_address_instance.UAtext
            omrecvname = user_address_instance.UAname
            # 判断是否是别人分享而来
            secret_usid = data.get('secret_usid')
            if secret_usid:
                try:
                    from_usid = self._base_decode(secret_usid)
                    # 来源用户是否购买
                    from_user_order = OrderMain.query.filter_by().filter(
                        OrderMain.USid == from_usid,
                        OrderMain.OMstatus > OrderMainStatus.wait_pay.value,
                        OrderMain.OMfrom == OrderFrom.fresh_man.value,
                    ).first()
                except ValueError:
                    current_app.logger.info(
                        'secret_usid decode error : {}'.format(secret_usid))
                    from_user_order = None
            else:
                from_user_order = None

            # 创建订单
            omid = str(uuid.uuid1())
            opayno = self.wx_pay.nonce_str
            price = fresh_man_sku.SKUprice
            # 主单
            order_main_dict = {
                'OMid': omid,
                'OMno': self._generic_omno(),
                'OPayno': opayno,
                'USid': usid,
                'OMfrom': OrderFrom.fresh_man.value,
                'PBname': fresh_first_product.PBname,
                'PBid': fresh_first_product.PBid,
                'OMclient': omclient,
                'OMfreight': 0,  # 运费暂时为0
                'OMmount': price,
                'OMmessage': data.get('ommessage'),
                'OMtrueMount': price,
                # 收货信息
                'OMrecvPhone': omrecvphone,
                'OMrecvName': omrecvname,
                'OMrecvAddress': omrecvaddress,
                'PRcreateId': suid
            }
            order_main_instance = OrderMain.create(order_main_dict)
            db.session.add(order_main_instance)
            # 副单
            order_part_dict = {
                'OPid': str(uuid.uuid1()),
                'OMid': omid,
                'SKUid': skuid,
                'PRid': fresh_first_product.PRid,
                'PRattribute': fresh_first_product.PRattribute,
                'SKUattriteDetail': product_sku.SKUattriteDetail,
                'SKUprice': price,
                'PRtitle': fresh_first_product.PRtitle,
                'SKUsn': product_sku.SKUsn,
                'PCname': product_category.PCname,
                'PRmainpic': fresh_first_product.PRmainpic,
                'OPnum': 1,
                # # 副单商品来源
                'PRfrom': product_instance.PRfrom,
                'UPperid': getattr(user, 'USsupper1', ''),
                'UPperid2': getattr(user, 'USsupper2', ''),
                'UPperid3': getattr(user, 'USsupper3', ''),
                'USCommission1': getattr(user, 'USCommission1', ''),
                'USCommission2': getattr(user, 'USCommission2', ''),
                'USCommission3': getattr(user, 'USCommission3', '')
            }
            order_part_instance = OrderPart.create(order_part_dict)
            db.session.add(order_part_instance)
            # 支付数据表
            order_pay_dict = {
                'OPayid': str(uuid.uuid1()),
                'OPayno': opayno,
                'OPayType': opaytype,
                'OPayMount': price,
            }
            order_pay_instance = OrderPay.create(order_pay_dict)
            db.session.add(order_pay_instance)
            # 新人首单参与记录
            fresh_man_join_dict = {
                'FMJFid': str(uuid.uuid1()),
                'OMid': omid,
                'OMprice': price
            }
            if from_user_order:
                fresh_man_join_dict['UPid'] = from_usid
            join_instance = FreshManJoinFlow.create(fresh_man_join_dict)
            db.session.add(join_instance)
            # 删除未支付的新人订单
            if exists_order:
                exists_order.isdelete = True
                db.session.add(exists_order)
        from planet.extensions.tasks import auto_cancle_order

        auto_cancle_order.apply_async(
            args=([omid], ),
            countdown=30 * 60,
            expires=40 * 60,
        )
        # 生成支付信息
        body = product_instance.PRtitle
        current_user = get_current_user()
        openid = current_user.USopenid1 or current_user.USopenid2
        pay_args = self._pay_detail(omclient,
                                    opaytype,
                                    opayno,
                                    float(price),
                                    body,
                                    openid=openid)
        response = {
            'pay_type': PayType(opaytype).name,
            'opaytype': opaytype,
            'args': pay_args
        }
        return Success('创建订单成功', data=response)
Ejemplo n.º 3
0
    def order(self):
        """下单"""
        data = parameter_required(
            ('ipid', 'pbid', 'ipsid', 'omclient', 'uaid'))
        usid = request.user.id
        user = User.query.filter_by_(USid=usid).first_("请重新登录")
        current_app.logger.info('User {} is buying a Integral Product'.format(
            user.USname))
        uaid = data.get('uaid')
        ipid = data.get('ipid')
        opaytype = data.get('opaytype', 30)  # 支付方式
        try:
            omclient = int(data.get('omclient', Client.wechat.value))  # 下单设备
            Client(omclient)
        except Exception:
            raise ParamsError('客户端来源错误')
        with db.auto_commit():
            # 用户的地址信息
            user_address_instance = db.session.query(UserAddress).filter_by_({
                'UAid':
                uaid,
                'USid':
                usid
            }).first_('地址信息不存在')
            omrecvphone = user_address_instance.UAphone
            areaid = user_address_instance.AAid
            # 地址拼接
            area, city, province = db.session.query(
                AddressArea, AddressCity, AddressProvince).filter(
                    AddressArea.ACid == AddressCity.ACid,
                    AddressCity.APid == AddressProvince.APid).filter(
                        AddressArea.AAid == areaid).first_('地址有误')
            address = getattr(province, "APname", '') + getattr(
                city, "ACname", '') + getattr(area, "AAname", '')
            omrecvaddress = address + user_address_instance.UAtext
            omrecvname = user_address_instance.UAname
            opayno = self.wx_pay.nonce_str
            model_bean = []

            omid = str(uuid.uuid1())
            pbid = data.get('pbid')
            ommessage = data.get('ommessage')
            product_brand_instance = db.session.query(ProductBrand).filter_by_(
                {
                    'PBid': pbid
                }).first_('品牌id: {}不存在'.format(pbid))

            opid = str(uuid.uuid1())
            skuid = data.get('ipsid')
            opnum = int(data.get('nums', 1))
            # opnum = 1  # 购买数量暂时只支持一件
            # assert opnum > 0, 'nums <= 0, 参数错误'
            sku_instance = IntegralProductSku.query.filter_by_(
                IPSid=skuid).first_('ipsid: {}不存在'.format(skuid))
            product_sku = ProductSku.query.filter_by_(
                SKUid=sku_instance.SKUid).first_("商品sku不存在")
            if sku_instance.IPid != ipid:
                raise ParamsError('skuid 与 ipid 商品不对应')
            if int(sku_instance.IPSstock) - int(opnum) < 0:
                raise StatusError('商品库存不足')
            integral_product = IntegralProduct.query.filter(
                IntegralProduct.IPid == ipid,
                IntegralProduct.isdelete == False,
                IntegralProduct.IPstatus == ApplyStatus.agree.value,
            ).first_("ipid: {}对应的星币商品不存在")
            product_instance = Products.query.filter(
                Products.isdelete == False,
                Products.PRid == integral_product.PRid,
                Products.PRstatus == ProductStatus.usual.value).first_(
                    'ipid: {}对应的商品不存在'.format(skuid))
            if product_instance.PBid != pbid:
                raise ParamsError('品牌id: {}与skuid: {}不对应'.format(pbid, skuid))
            small_total = int(sku_instance.SKUprice) * opnum
            order_part_dict = {
                'OMid': omid,
                'OPid': opid,
                'PRid': integral_product.IPid,  # 是星币商品id,不是原商品
                'SKUid': skuid,
                'PRattribute': product_instance.PRattribute,
                'SKUattriteDetail': product_sku.SKUattriteDetail,
                'PRtitle': product_instance.PRtitle,
                'SKUprice': sku_instance.SKUprice,
                'PRmainpic': product_instance.PRmainpic,
                'OPnum': opnum,
                'OPsubTotal': small_total,
                'PRfrom': product_instance.PRfrom,
            }
            order_part_instance = OrderPart.create(order_part_dict)
            model_bean.append(order_part_instance)

            # 对应商品销量 + num sku库存 -num
            db.session.query(IntegralProduct).filter_by_(IPid=ipid).update(
                {'IPsaleVolume': IntegralProduct.IPsaleVolume + opnum})
            db.session.query(IntegralProductSku).filter_by_(
                IPSid=skuid).update(
                    {'IPSstock': IntegralProductSku.IPSstock - opnum})

            # 主单
            order_main_dict = {
                'OMid': omid,
                'OMno': self._generic_omno(),
                'OPayno': opayno,
                'USid': usid,
                'OMfrom': OrderFrom.integral_store.value,
                'PBname': product_brand_instance.PBname,
                'PBid': product_brand_instance.PBid,
                'OMclient': omclient,
                'OMfreight': 0,  # 运费暂时为0
                'OMmount': small_total,
                'OMmessage': ommessage,
                'OMtrueMount': small_total,
                # 收货信息
                'OMrecvPhone': omrecvphone,
                'OMrecvName': omrecvname,
                'OMrecvAddress': omrecvaddress,
                'PRcreateId': product_instance.CreaterId,
                'UseCoupon': False
            }
            order_main_instance = OrderMain.create(order_main_dict)
            model_bean.append(order_main_instance)

            # 支付数据表
            order_pay_dict = {
                'OPayid': str(uuid.uuid1()),
                'OPayno': opayno,
                'OPayType': PayType.integralpay.value,  # 星币支付
                'OPayMount': small_total,
            }
            order_pay_instance = OrderPay.create(order_pay_dict)
            model_bean.append(order_pay_instance)
            db.session.add_all(model_bean)
        from planet.extensions.tasks import auto_cancle_order
        auto_cancle_order.apply_async(
            args=([omid], ),
            countdown=30 * 60,
            expires=40 * 60,
        )
        # # 生成支付信息
        # body = product_instance.TCtitle
        # pay_args = self._pay_detail(omclient, opaytype, opayno, float(small_total), body,
        #                             openid=user.USopenid1 or user.USopenid2)
        response = {
            'pay_type': PayType(opaytype).name,
            'opaytype': opaytype,
            'usintegral': getattr(user, 'USintegral', 0),
            'omid': omid,
            'omtruemount': small_total
            # 'args': pay_args
        }
        return Success('创建成功', data=response)
Ejemplo n.º 4
0
    def order(self):
        """下单"""
        data = parameter_required(('gpid', 'pbid', 'gsid', 'omclient', 'uaid'))
        usid = request.user.id
        user = User.query.filter_by_(USid=usid).first_("请重新登录")
        current_app.logger.info('User {} is buying a guess group Product'.format(user.USname))
        uaid = data.get('uaid')
        gpid = data.get('gpid')
        opaytype = data.get('opaytype', 0)  # 支付方式
        if datetime.datetime.now().hour >= 21:
            raise StatusError(' ^_^  正在等待今日开奖 (每日21:00后停止竞猜,请明日再来)')
        try:
            omclient = int(data.get('omclient', Client.wechat.value))  # 下单设备
            Client(omclient)
        except Exception:
            raise ParamsError('客户端来源错误')
        with db.auto_commit():
            # 用户的地址信息
            user_address_instance = db.session.query(UserAddress).filter_by_({'UAid': uaid, 'USid': usid}).first_(
                '地址信息不存在')
            omrecvphone = user_address_instance.UAphone
            areaid = user_address_instance.AAid
            # 地址拼接
            area, city, province = db.session.query(AddressArea, AddressCity, AddressProvince).filter(
                AddressArea.ACid == AddressCity.ACid, AddressCity.APid == AddressProvince.APid).filter(
                AddressArea.AAid == areaid).first_('地址有误')
            address = getattr(province, "APname", '') + getattr(city, "ACname", '') + getattr(area, "AAname", '')
            omrecvaddress = address + user_address_instance.UAtext
            omrecvname = user_address_instance.UAname
            opayno = self.wx_pay.nonce_str
            model_bean = []

            omid = str(uuid.uuid1())
            pbid = data.get('pbid')
            ommessage = data.get('ommessage')
            product_brand_instance = ProductBrand.query.filter_by_(PBid=pbid,
                                                                   PBstatus=ProductBrandStatus.upper.value
                                                                   ).first_('该品牌已下架')

            opid = str(uuid.uuid1())
            gsid = data.get('gsid')
            opnum = int(data.get('nums', 1))
            opnum = 1  # 购买数量暂时只支持一件
            # assert opnum > 0, 'nums <= 0, 参数错误'
            sku_instance = GroupGoodsSku.query.filter_by_(GSid=gsid).first_('gsid: {} 不存在'.format(gsid))
            product_sku = ProductSku.query.filter_by_(SKUid=sku_instance.SKUid).first_("商品sku不存在")
            if sku_instance.GPid != gpid:
                raise ParamsError('gsid 与 gpid 商品不对应')
            if int(sku_instance.GSstock) - int(opnum) < 0:
                raise StatusError('商品库存不足')
            group_product = GroupGoodsProduct.query.filter(GroupGoodsProduct.GPid == gpid,
                                                           GroupGoodsProduct.isdelete == False,
                                                           GroupGoodsProduct.GPstatus == ApplyStatus.agree.value,
                                                           ).first_("该拼团商品已下架")
            if self.verify_have_paid(group_product):
                raise StatusError('您已付过该商品押金,可直接参与该商品的拼团')
            product_instance = Products.query.filter(Products.isdelete == False,
                                                     Products.PRid == group_product.PRid,
                                                     Products.PRstatus == ProductStatus.usual.value
                                                     ).first_("该商品已下架")
            product_category = ProductCategory.query.filter_by(PCid=product_instance.PCid).first()
            if product_instance.PBid != pbid:
                raise ParamsError('品牌id {} 与商品id {} 不对应'.format(pbid, gsid))
            small_total = Decimal(sku_instance.SKUPrice) * Decimal(opnum)
            order_part_dict = {
                'OMid': omid,
                'OPid': opid,
                'PRid': group_product.GPid,  # 是拼团商品id,不是原商品
                'SKUid': gsid,  # 拼团商品的gsid
                'PRattribute': product_instance.PRattribute,
                'SKUattriteDetail': product_sku.SKUattriteDetail,
                'SKUprice': sku_instance.SKUPrice,
                'PRtitle': product_instance.PRtitle,
                'SKUsn': product_sku.SKUsn,
                'PCname': product_category.PCname,
                'PRmainpic': product_instance.PRmainpic,
                'OPnum': opnum,
                'OPsubTotal': small_total,
                'PRfrom': product_instance.PRfrom,
                'SkudevideRate': product_sku.SkudevideRate,
                'UPperid': user.USsupper1,
                'UPperid2': user.USsupper2,
                'UPperid3': user.USsupper3,
                'USCommission1': user.USCommission1,
                'USCommission2': user.USCommission2,
                'USCommission3': user.USCommission3
            }
            order_part_instance = OrderPart.create(order_part_dict)
            model_bean.append(order_part_instance)

            # 对应商品销量 + num sku库存 -num
            db.session.query(Products).filter_by_(PRid=group_product.PRid
                                                  ).update({'PRsalesValue': Products.PRsalesValue + opnum})
            db.session.query(GroupGoodsSku).filter_by_(GSid=gsid
                                                       ).update({'GSstock': GroupGoodsSku.GSstock - opnum})

            # 主单
            order_main_dict = {
                'OMid': omid,
                'OMno': self._generic_omno(),
                'OPayno': opayno,
                'USid': usid,
                'OMfrom': OrderFrom.guess_group.value,
                'PBname': product_brand_instance.PBname,
                'PBid': product_brand_instance.PBid,
                'OMclient': omclient,
                'OMfreight': 0,  # 运费暂时为0
                'OMmount': small_total,
                'OMmessage': ommessage,
                'OMtrueMount': small_total,
                # 收货信息
                'OMrecvPhone': omrecvphone,
                'OMrecvName': omrecvname,
                'OMrecvAddress': omrecvaddress,
                'PRcreateId': product_instance.CreaterId,
                'UseCoupon': False
            }
            order_main_instance = OrderMain.create(order_main_dict)
            model_bean.append(order_main_instance)

            # 支付数据表
            order_pay_dict = {
                'OPayid': str(uuid.uuid1()),
                'OPayno': opayno,
                'OPayType': PayType.wechat_pay.value,
                'OPayMount': small_total,
            }
            order_pay_instance = OrderPay.create(order_pay_dict)
            model_bean.append(order_pay_instance)
            db.session.add_all(model_bean)
        from planet.extensions.tasks import auto_cancle_order
        auto_cancle_order.apply_async(args=([omid],), countdown=30 * 60, expires=40 * 60, )
        # 生成支付信息
        body = product_instance.PRtitle
        pay_args = self._pay_detail(omclient, opaytype, opayno, round(float(small_total), 2), body,
                                    openid=user.USopenid2)
        response = {
            'pay_type': PayType(opaytype).name,
            'opaytype': opaytype,
            'omid': omid,
            'omtruemount': small_total,
            'args': pay_args
        }
        return Success('创建成功', data=response)
Ejemplo n.º 5
0
 def validate_omclient(self, raw):
     Client(raw.data)
Ejemplo n.º 6
0
    def pay(self):
        """订单发起支付"""
        data = parameter_required(('omid', ))
        omid = data.get('omid')
        usid = request.user.id
        try:
            omclient = int(data.get('omclient',
                                    Client.wechat.value))  # 客户端(app或者微信)
            Client(omclient)
            opaytype = int(data.get('opaytype',
                                    PayType.wechat_pay.value))  # 付款方式
            PayType(opaytype)
        except ValueError as e:
            raise e
        except Exception as e:
            raise ParamsError('客户端或支付方式类型错误')
        from planet.control.CUser import CUser
        cuser = CUser()
        if opaytype == PayType.integralpay.value:
            return self._integralpay(data, usid)
        with db.auto_commit():
            opayno = self.wx_pay.nonce_str
            order_main = OrderMain.query.filter_by_({
                'OMid':
                omid,
                'USid':
                usid,
                'OMstatus':
                OrderMainStatus.wait_pay.value
            }).first_('不存在的订单')
            # 原支付流水删除
            OrderPay.query.filter_by({'OPayno': order_main.OPayno}).delete_()
            # 更改订单支付编号
            order_main.OPayno = opayno
            # 判断订单是否是开店大礼包
            # 是否是开店大礼包
            if order_main.OMlogisticType == OMlogisticTypeEnum.online.value:
                cuser = CUser()
                cuser._check_gift_order('重复购买开店大礼包')
            db.session.add(order_main)
            pay_price = order_main.OMtrueMount

            # 魔术礼盒订单
            if order_main.OMfrom == OrderFrom.magic_box.value:
                magic_box_join = MagicBoxJoin.query.filter(
                    MagicBoxJoin.isdelete == False,
                    MagicBoxJoin.OMid == order_main.OMid,
                    MagicBoxJoin.MBJstatus ==
                    MagicBoxJoinStatus.pending.value).first()
                pay_price = float(order_main.OMtrueMount) - float(
                    magic_box_join.MBJcurrentPrice)
                if pay_price <= 0:
                    pay_price = 0.01
            # 新建支付流水
            if order_main.OMintegralpayed and order_main.OMintegralpayed > 0:
                db.session.add(
                    OrderPay.create({
                        'OPayid': str(uuid.uuid1()),
                        'OPayno': opayno,
                        'OPayType': PayType.mixedpay.value,
                        'OPayMount': order_main.OMintegralpayed
                    }))
            order_pay_instance = OrderPay.create({
                'OPayid': str(uuid.uuid1()),
                'OPayno': opayno,
                'OPayType': opaytype,
                'OPayMount': pay_price,
            })
            # 付款时候的body信息
            order_parts = OrderPart.query.filter_by_({'OMid': omid}).all()
            body = ''.join([getattr(x, 'PRtitle', '') for x in order_parts])
            db.session.add(order_pay_instance)
        user = User.query.filter(User.USid == order_main.USid).first()
        pay_args = self._pay_detail(omclient,
                                    opaytype,
                                    opayno,
                                    float(pay_price),
                                    body,
                                    openid=user.USopenid2)
        response = {
            'pay_type': PayType(opaytype).name,
            'opaytype': opaytype,
            'args': pay_args
        }
        return Success('生成付款参数成功', response)