Ejemplo n.º 1
0
 def validate_gnnum(self, raw):
     try:
         float(raw.data)
     except ValueError:
         raise ParamsError('数字格式不正确')
     is_exists = GuessNum.query.filter(
         GuessNum.USid == request.user.id,
         GuessNum.isdelete == False,
         cast(GuessNum.createtime, Date) == date.today(),
     ).first()
     if is_exists:
         raise DumpliError('今日已参与')
Ejemplo n.º 2
0
    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})
Ejemplo n.º 3
0
 def create(self):
     form = ItemCreateForm().valid_data()
     psid = form.psid.data
     itname = form.itname.data
     itsort = form.itsort.data
     itdesc = form.itdesc.data
     ittype = form.ittype.data
     itrecommend = form.itrecommend.data
     itid = str(uuid.uuid1())
     with self.sproduct.auto_commit() as s:
         if s.query(Items).filter_by(ITname=itname,
                                     ITtype=ittype,
                                     isdelete=False).first():
             raise DumpliError("您输入的标签名已存在")
         s_list = []
         # 添加标签
         item_dict = {
             'ITid': itid,
             'ITname': itname,
             'ITsort': itsort,
             'ITdesc': itdesc,
             'ITtype': ittype,
             'ITrecommend': itrecommend
         }
         items_instance = Items.create(item_dict)
         s_list.append(items_instance)
         # 标签场景标签表
         if psid:
             for psi in psid:
                 s.query(ProductScene).filter_by_({
                     'PSid': psi
                 }).first_('不存在的场景')
                 scene_item_dict = {
                     'PSid': psi,
                     'ITid': itid,
                     'SIid': str(uuid.uuid1())
                 }
                 scene_item_instance = SceneItem.create(scene_item_dict)
                 s_list.append(scene_item_instance)
         s.add_all(s_list)
     return Success('添加成功', {'itid': itid})
Ejemplo n.º 4
0
 def send_reset_password_code(self):
     """发送修改验证码"""
     if not is_supplizer():
         raise AuthorityError()
     form = SupplizerSendCodeForm().valid_data()
     mobile = form.suloginphone.data
     Supplizer.query.filter(
         Supplizer.isdelete == False,
         Supplizer.SUloginPhone == mobile).first_('不存在的供应商')
     exist_code = conn.get(mobile + '_code')
     if exist_code:
         return DumpliError('重复发送')
     nums = [str(x) for x in range(10)]
     code = ''.join([random.choice(nums) for _ in range(6)])
     key = mobile + '_code'
     conn.set(key, code, ex=60)  # 60s过期
     params = {"code": code}
     app = current_app._get_current_object()
     send_task = Thread(target=self._async_send_code,
                        args=(mobile, params, app),
                        name='send_code')
     send_task.start()
     return Success('发送成功')
Ejemplo n.º 5
0
 def create(self):
     """添加"""
     if is_admin():
         Admin.query.filter_by_(ADid=request.user.id).first_('账号状态异常')
         current_app.logger.info(">>>  Admin Create a Supplizer  <<<")
     elif is_tourist():
         current_app.logger.info(
             ">>>  Tourist Uploading Supplizer Files  <<<")
     else:
         raise AuthorityError('无权限')
     form = SupplizerCreateForm().valid_data()
     pbids = form.pbids.data
     suid = str(uuid.uuid1())
     if is_admin():
         sustatus = UserStatus.usual.value
         sudeposit = form.sudeposit.data
     else:
         sustatus = UserStatus.auditing.value
         sudeposit = 0
     supassword = generate_password_hash(
         form.supassword.data) if form.supassword.data else None
     try:
         with db.auto_commit():
             supperlizer = Supplizer.create({
                 'SUid':
                 suid,
                 'SUlinkPhone':
                 form.sulinkphone.data,
                 'SUloginPhone':
                 form.suloginphone.data,
                 'SUname':
                 form.suname.data,
                 'SUlinkman':
                 form.sulinkman.data,
                 'SUbaseRate':
                 form.subaserate.data,
                 'SUaddress':
                 form.suaddress.data,
                 'SUdeposit':
                 sudeposit,
                 'SUstatus':
                 sustatus,  # 管理员添加的可直接上线
                 'SUbanksn':
                 form.subanksn.data,
                 'SUbankname':
                 form.subankname.data,
                 'SUpassword':
                 supassword,
                 'SUheader':
                 form.suheader.data,
                 'SUcontract':
                 form.sucontract.data,
                 'SUbusinessLicense':
                 form.subusinesslicense.data,
                 'SUregisteredFund':
                 form.suregisteredfund.data,
                 'SUmainCategory':
                 form.sumaincategory.data,
                 'SUregisteredTime':
                 form.suregisteredtime.data,
                 'SUlegalPerson':
                 form.sulegalperson.data,
                 'SUemail':
                 form.suemail.data,
                 'SUlegalPersonIDcardFront':
                 form.sulegalpersonidcardfront.data,
                 'SUlegalPersonIDcardBack':
                 form.sulegalpersonidcardback.data,
             })
             db.session.add(supperlizer)
             if is_admin():
                 BASEADMIN().create_action(AdminActionS.insert.value,
                                           'Supplizer', suid)
             if pbids:
                 for pbid in pbids:
                     product_brand = ProductBrand.query.filter(
                         ProductBrand.isdelete == False,
                         ProductBrand.PBid == pbid).first()
                     if not product_brand:
                         raise NotFound('品牌不存在')
                     if product_brand.SUid:
                         raise DumpliError('品牌已有供应商')
                     product_brand.SUid = supperlizer.SUid
                     db.session.add(product_brand)
             if sudeposit and is_admin():
                 SupplizerDepositLog.create({
                     'SDLid': str(uuid.uuid1()),
                     'SUid': suid,
                     'SDLnum': Decimal(sudeposit),
                     'SDafter': Decimal(sudeposit),
                     'SDbefore': 0,
                     'SDLacid': request.user.id,
                 })
                 BASEADMIN().create_action(AdminActionS.insert.value,
                                           'SupplizerDepositLog',
                                           str(uuid.uuid1()))
     except IntegrityError:
         raise ParamsError('手机号重复')
     return Success('创建成功', data={'suid': supperlizer.SUid})
Ejemplo n.º 6
0
    def update(self):
        """更新供应商信息"""
        if not is_admin() and not is_supplizer():
            raise AuthorityError()
        form = SupplizerUpdateForm().valid_data()
        pbids = form.pbids.data
        with db.auto_commit():
            supplizer = Supplizer.query.filter(
                Supplizer.isdelete == False,
                Supplizer.SUid == form.suid.data).first_('供应商不存在')
            supplizer_dict = {
                'SUlinkPhone': form.sulinkphone.data,
                'SUname': form.suname.data,
                'SUlinkman': form.sulinkman.data,
                'SUaddress': form.suaddress.data,
                'SUbanksn': form.subanksn.data,
                'SUbankname': form.subankname.data,
                # 'SUpassword': generate_password_hash(form.supassword.data),  # todo 是不是要加上
                'SUheader': form.suheader.data,
                'SUcontract': form.sucontract.data,
                'SUbusinessLicense': form.subusinesslicense.data,
                'SUregisteredFund': form.suregisteredfund.data,
                'SUmainCategory': form.sumaincategory.data,
                'SUregisteredTime': form.suregisteredtime.data,
                'SUlegalPerson': form.sulegalperson.data,
                'SUemail': form.suemail.data,
                'SUlegalPersonIDcardFront': form.sulegalpersonidcardfront.data,
                'SUlegalPersonIDcardBack': form.sulegalpersonidcardback.data,
            }
            if is_admin():
                if form.subaserate.data:
                    supplizer_dict['SUbaseRate'] = form.subaserate.data,
                if isinstance(form.sustatus.data, int):
                    supplizer_dict['SUstatus'] = form.sustatus.data
                    if form.sustatus.data == UserStatus.usual.value and not supplizer.SUpassword:
                        supplizer_dict['SUpassword'] = generate_password_hash(
                            supplizer.SUloginPhone)
                if form.sudeposit.data:
                    sudeposit = form.sudeposit.data
                    supplizer_dict['SUdeposit'] = Decimal(sudeposit)
                    if Decimal(sudeposit) != Decimal(
                            getattr(supplizer, 'SUdeposit', 0)):  # 押金有变化时进行记录
                        depositlog = SupplizerDepositLog.create({
                            'SDLid':
                            str(uuid.uuid1()),
                            'SUid':
                            form.suid.data,
                            'SDLnum':
                            Decimal(sudeposit) -
                            Decimal(getattr(supplizer, 'SUdeposit', 0)),
                            'SDafter':
                            Decimal(sudeposit),
                            'SDbefore':
                            Decimal(getattr(supplizer, 'SUdeposit', 0)),
                            'SDLacid':
                            request.user.id,
                        })
                        db.session.add(depositlog)
                        BASEADMIN().create_action(AdminActionS.insert.value,
                                                  'SupplizerDepositLog',
                                                  str(uuid.uuid1()))

            supplizer.update(supplizer_dict, null='dont ignore')
            db.session.add(supplizer)
            if is_admin():
                BASEADMIN().create_action(AdminActionS.update.value,
                                          'Supplizer', form.suid.data)
            if pbids and is_admin():
                for pbid in pbids:
                    product_brand = ProductBrand.query.filter(
                        ProductBrand.isdelete == False,
                        ProductBrand.PBid == pbid).first()
                    if not product_brand:
                        raise NotFound('品牌不存在')
                    if product_brand.SUid and product_brand.SUid != supplizer.SUid:
                        raise DumpliError('品牌已有供应商')
                    # if product_brand.PBstatus ==
                    # todo 品牌已下架
                    product_brand.SUid = form.suid.data
                    db.session.add(product_brand)
                # 删除其他的关联
                ProductBrand.query.filter(
                    ProductBrand.isdelete == False,
                    ProductBrand.SUid == form.suid.data,
                    ProductBrand.PBid.notin_(pbids)).update(
                        {'SUid': None}, synchronize_session=False)
        return Success('更新成功')
Ejemplo n.º 7
0
 def validate_suloginphone(self, raw):
     is_exists = Supplizer.query.filter_by_().filter_(
         Supplizer.SUloginPhone == raw.data,
         Supplizer.isdelete == False).first()
     if is_exists:
         raise DumpliError('登陆手机号已存在')
Ejemplo n.º 8
0
    def apply_award(self):
        """申请添加商品"""
        if not (is_supplizer() or is_admin()):
            raise AuthorityError()
        data = parameter_required(('prid', 'prprice', 'skus', 'tlaid'))
        tlp = TimeLimitedProduct.query.filter(
            # TimeLimitedProduct.TLAstatus != ApplyStatus.agree.value,
            TimeLimitedProduct.isdelete == False,
            TimeLimitedProduct.TLAid == data.get('tlaid'),
            TimeLimitedProduct.PRid == data.get('prid')).first()
        if tlp:
            raise DumpliError('重复提交')
        filter_args = {
            Products.PRid == data.get('prid'), Products.isdelete == False,
            Products.PRstatus == ProductStatus.usual.value
        }
        if is_supplizer():
            tlp_from = ApplyFrom.supplizer.value
            suid = request.user.id
            filter_args.add(Products.PRfrom == tlp_from)
            filter_args.add(Products.CreaterId == suid)
        else:
            tlp_from = ApplyFrom.platform.value
            filter_args.add(Products.PRfrom == tlp_from)
            suid = None
        # tlp_from = ApplyFrom.supplizer.value if is_supplizer() else ApplyFrom.platform.value
        with db.auto_commit():
            product = Products.query.filter(*filter_args).first_('只能选择自己的商品')
            # instance_list = list()
            skus = data.get('skus')
            tla = TimeLimitedActivity.query.filter(
                TimeLimitedActivity.isdelete == False,
                TimeLimitedActivity.TLAstatus ==
                TimeLimitedStatus.waiting.value, TimeLimitedActivity.TLAid ==
                data.get('tlaid')).first_('活动已停止报名')
            tlp = TimeLimitedProduct.create({
                'TLPid': str(uuid.uuid1()),
                'TLAid': tla.TLAid,
                'TLAfrom': tlp_from,
                'SUid': suid,
                'PRid': product.PRid,
                # 'PRmainpic': product.PRmainpic,
                # 'PRattribute': product.PRattribute,
                # 'PBid': product.PBid,
                # 'PBname': product.PBname,
                # 'PRtitle': product.PRtitle,
                'PRprice': data.get('prprice')
            })
            instance_list = [tlp]
            for sku in skus:
                skuid = sku.get('skuid')
                skuprice = sku.get('skuprice')
                skustock = sku.get('skustock')
                sku_instance = ProductSku.query.filter_by(
                    isdelete=False, PRid=product.PRid,
                    SKUid=skuid).first_('商品sku信息不存在')
                self._update_stock(-int(skustock), product, sku_instance)
                tls = TimeLimitedSku.create({
                    'TLSid': str(uuid.uuid1()),
                    'TLPid': tlp.TLPid,
                    'TLSstock': skustock,
                    'SKUid': skuid,
                    'SKUprice': skuprice
                })

                instance_list.append(tls)
                # prstock += skustock
            db.session.add_all(instance_list)
            if is_admin():
                BASEADMIN().create_action(AdminActionS.insert.value,
                                          'TimeLimitedProduct',
                                          str(uuid.uuid1()))

        # todo  添加到审批流
        super(CTimeLimited, self).create_approval('totimelimited',
                                                  request.user.id,
                                                  tlp.TLPid,
                                                  applyfrom=tlp_from)

        return Success('申请成功', {'tlpid': tlp.TLPid})
Ejemplo n.º 9
0
    def open(self):
        """好友帮拆"""
        # 判断帮拆活动总控制是否结束
        Activity.query.filter_by({
            'ACtype': ActivityType.magic_box.value
        }).first_('活动已结束')

        form = MagicBoxOpenForm().valid_data()
        mbjid = form.mbjid.data
        level = form.level.data
        levle_attr = dict(form.level.choices).get(level)
        usid = request.user.id
        # 源参与记录
        magic_box_join = MagicBoxJoin.query.filter_by({
            'MBJid': mbjid
        }).first_('请点击好友发来邀请链接')
        if magic_box_join.MBJstatus != ActivityRecvStatus.wait_recv.value:
            raise StatusError('已领奖或已过期')
        if magic_box_join.USid == request.user.id:
            raise NotFound('仅可打开好友分享的魔盒')
        mbaid = magic_box_join.MBAid
        # 活动是否在进行
        magic_box_apply = MagicBoxApply.query.filter_by_().filter(
            MagicBoxApply.MBAid == mbaid,
            MagicBoxApply.MBAstatus == ApplyStatus.agree.value).first_('活动不存在')
        today = date.today()
        lasting = magic_box_apply.AgreeEndtime >= today
        if not lasting:
            raise StatusError('活动过期')
        with db.auto_commit():
            # 是否已经帮开奖
            ready_open = MagicBoxOpen.query.filter_by_({
                'USid': usid,
                'MBJid': mbjid
            }).first()
            if ready_open:
                raise DumpliError('已经帮好友拆过')

            # 价格变动随机
            current_level_str = getattr(magic_box_apply, levle_attr)
            current_level_json = json.loads(
                current_level_str)  # 列表 ["1-2", "3-4"]

            current_level_json[0] = list(
                map(lambda x: int(x) * -1,
                    current_level_json[0].split('-')))  # 第0个元素是-
            if len(current_level_json) == 2:
                current_level_json[1] = list(
                    map(int, current_level_json[1].split('-')))  # 第1个元素是+
            # todo level2, 减价: 增价  7:3
            if level == 2:
                random_num = random.randint(0, 9)
                random_choice_first = current_level_json[
                    0] if random_num < 7 else current_level_json[1]
            # todo level3, 减价: 增加  6:4
            elif level == 3:
                random_num = random.randint(0, 9)
                random_choice_first = current_level_json[
                    0] if random_num < 6 else current_level_json[1]
            else:
                random_choice_first = random.choice(
                    current_level_json)  # 选择是- 还是+
            final_reduce = random.uniform(*random_choice_first)  # 最终价格变动
            final_reduce = round(Decimal(final_reduce), 2)
            # 价格计算
            final_price = Decimal(
                magic_box_join.MBJcurrentPrice) + final_reduce
            if final_price > magic_box_apply.SKUprice:
                final_price = magic_box_apply.SKUprice
            if final_price < magic_box_apply.SKUminPrice:
                final_price = magic_box_apply.SKUminPrice
            final_price = round(final_price, 2)
            # 帮拆记录
            user = User.query.filter_by_({'USid': usid}).first()
            mb_open = MagicBoxOpen.create({
                'MBOid': str(uuid.uuid1()),
                'USid': usid,
                'MBJid': mbjid,
                'MBOgear': int(level),
                'MBOresult': float(final_reduce),
                'MBOprice': float(final_price),
                'USname': user.USname
            })
            # 源参与价格修改
            magic_box_join.MBJcurrentPrice = float(final_price)
            db.session.add(mb_open)
        return Success(data={
            'final_reduce': float(final_reduce),
            'final_price': float(final_price)
        })
Ejemplo n.º 10
0
    def open(self):
        """好友帮拆"""
        usid = request.user.id
        user = User.query.filter_by_(USid=usid).first_('请重新登录')
        data = parameter_required(('mbjid', 'level'))
        mbjid, level = data.get('mbjid'), data.get('level')
        if not re.match(r'^[123]$', str(level)):
            raise ParamsError('level 参数错误')

        levle_attr = {
            '1': 'Gearsone',
            '2': 'Gearstwo',
            '3': 'Gearsthree'
        }.get(level)

        magic_box_join = MagicBoxJoin.query.filter_by(
            isdelete=False,
            MBJid=mbjid,
            MBJstatus=MagicBoxJoinStatus.pending.value).first_('该礼盒活动已结束')
        if magic_box_join.USid == user.USid:
            raise NotFound('不能给自己拆盒子, 快去找小伙伴帮忙吧 ~')
        mbaid = magic_box_join.MBAid
        # 活动是否在进行
        magic_box_apply = MagicBoxApply.query.filter(
            MagicBoxApply.MBAid == mbaid, MagicBoxApply.MBAstatus ==
            ApplyStatus.agree.value).first_('该礼盒商品已下架')
        magic_box_sku = MagicBoxApplySku.query.filter_by_(
            MBSid=magic_box_join.MBSid).first()
        # sku_origin_price = db.session.query(ProductSku.SKUprice).filter_by_(SKUid=magic_box_sku.SKUid).scalar()
        with db.auto_commit():
            # 是否已经帮开奖
            ready_open = MagicBoxOpen.query.filter_by_(USid=usid,
                                                       MBJid=mbjid).first()
            if ready_open:
                raise DumpliError('您已帮好友拆过该礼盒了')

            # 价格变动随机
            current_level_str = getattr(magic_box_apply, levle_attr)
            current_level_json = json.loads(
                current_level_str)  # 列表 ["1-2", "3-4"]
            current_level_json[0] = list(
                map(lambda x: int(x) * -1,
                    current_level_json[0].split('-')))  # 第0个元素是-
            if len(current_level_json) == 2:
                current_level_json[1] = list(
                    map(int, current_level_json[1].split('-')))  # 第1个元素是+

            if str(level) == '2':
                one = (current_level_json[0][1] -
                       current_level_json[0][0]) * -1
                two = current_level_json[1][1] - current_level_json[1][0]
                probably = round(float(round(one / (one + two), 2) * 100), 2)
                current_app.logger.info('选择了 B 档,减价几率{}%'.format(probably))
                random_num = random.randint(0, 99)
                random_choice_first = current_level_json[
                    0] if random_num < probably else current_level_json[1]
            elif str(level) == '3':
                one = (current_level_json[0][1] -
                       current_level_json[0][0]) * -1
                two = current_level_json[1][1] - current_level_json[1][0]
                probably = round(float(round(one / (one + two), 2) * 100), 2)
                current_app.logger.info('选择了 C 档,减价几率{}%'.format(probably))
                random_num = random.randint(0, 99)
                random_choice_first = current_level_json[
                    0] if random_num < probably else current_level_json[1]
            else:
                current_app.logger.info('选择了 A 档')
                random_choice_first = random.choice(
                    current_level_json)  # 选择是- 还是+
            final_reduce = random.uniform(*random_choice_first)  # 最终价格变动
            final_reduce = round(Decimal(final_reduce), 2)
            current_app.logger.info('价格实际变动 {}'.format(final_reduce))

            if final_reduce < 0:
                action = MagicBoxOpenAction.reduce.value
            else:
                action = MagicBoxOpenAction.increase.value

            # 价格计算
            final_price = Decimal(
                magic_box_join.MBJcurrentPrice) + final_reduce
            if final_price < magic_box_sku.LowestPrice:
                final_price = magic_box_sku.LowestPrice
                final_reduce = Decimal(magic_box_sku.LowestPrice) - Decimal(
                    magic_box_join.MBJcurrentPrice)
            if final_price >= Decimal(magic_box_sku.SKUprice):
                final_price = Decimal(magic_box_sku.SKUprice)
                final_reduce = Decimal(magic_box_sku.SKUprice) - Decimal(
                    magic_box_join.MBJcurrentPrice)
            final_price = round(final_price, 2)

            if float(final_reduce) < 0:
                result = -1 * round(float(final_reduce), 2)
            else:
                result = round(float(final_reduce), 2)

            # 帮拆记录
            mb_open = MagicBoxOpen.create({
                'MBOid': str(uuid.uuid1()),
                'USid': usid,
                'USname': user.USname,
                'USheader': user.USheader,
                'MBJid': mbjid,
                'MBOgear': int(level),
                'MBOresult': result,
                'MBOaction': action,
                'MBOprice': float(final_price),
            })
            db.session.add(mb_open)

            # 源参与价格修改
            magic_box_join.MBJcurrentPrice = float(final_price)
        return Success('已成功助力',
                       data={
                           'action': action,
                           'final_reduce': result,
                           'final_price': float(final_price)
                       })
Ejemplo n.º 11
0
    def apply(self):
        """申请添加商品"""

        if is_admin():
            admin = Admin.query.filter_by_(
                ADid=request.user.id).first_("账号状态错误")
            ipfrom = ApplyFrom.platform.value
            uid = admin.ADid
        # elif is_supplizer():
        #     sup = Supplizer.query.filter_by_(SUid=request.user.id).first_("账号状态错误")
        #     ipfrom = ApplyFrom.supplizer.value
        #     uid = sup.SUid
        else:
            raise AuthorityError()
        data = parameter_required(('prid', 'ipprice', 'skus'))
        prid, ipprice, skus = data.get('prid'), data.get('ipprice',
                                                         0), data.get('skus')
        ipprice = self._check_price(ipprice)

        ip = IntegralProduct.query.filter(
            IntegralProduct.isdelete == False,
            IntegralProduct.PRid == prid,
        ).first()
        if ip:
            raise DumpliError('该商品申请已存在')
        filter_args = [
            Products.PRid == prid, Products.isdelete == False,
            Products.PRstatus == ProductStatus.usual.value
        ]
        if is_supplizer():  # 供应商只能添加自己的
            filter_args.append(Products.PRfrom == ipfrom)
            filter_args.append(Products.CreaterId == uid)
        instance_list = list()
        with db.auto_commit():
            product = Products.query.filter(*filter_args).first_('只能选择自己的商品')
            ip_instance = IntegralProduct.create({
                'IPid':
                str(uuid.uuid1()),
                'SUid':
                uid,
                'IPfrom':
                ipfrom,
                'PRid':
                prid,
                'IPstatus':
                ApplyStatus.wait_check.value,
                'IPprice':
                ipprice
            })
            instance_list.append(ip_instance)
            for sku in skus:
                parameter_required(('skuid', 'skuprice', 'ipsstock'),
                                   datafrom=sku)
                skuid, skuprice, ipsstock = sku.get('skuid'), sku.get(
                    'skuprice'), sku.get('ipsstock')
                skuprice = self._check_price(skuprice)
                ipsstock = self._check_price(ipsstock)
                sku_instance = ProductSku.query.filter_by(
                    isdelete=False, PRid=product.PRid,
                    SKUid=skuid).first_('商品sku信息不存在')
                # 从商品sku中减库存
                super(CIntegralStore,
                      self)._update_stock(-int(ipsstock), product,
                                          sku_instance)
                ipsku_instance = IntegralProductSku.create({
                    'IPSid':
                    str(uuid.uuid1()),
                    'IPid':
                    ip_instance.IPid,
                    'IPSstock':
                    ipsstock,
                    'SKUid':
                    skuid,
                    'SKUprice':
                    skuprice
                })
                instance_list.append(ipsku_instance)
            db.session.add_all(instance_list)
            if is_admin():
                BASEADMIN().create_action(AdminActionS.insert.value,
                                          'IntegralProduct', str(uuid.uuid1()))
        super(CIntegralStore, self).create_approval('tointegral',
                                                    uid,
                                                    ip_instance.IPid,
                                                    applyfrom=ipfrom)
        return Success('申请成功', data=dict(IPid=ip_instance.IPid))
Ejemplo n.º 12
0
    def _order_main_refund(self, omid, usid, data):
        with self.strade.auto_commit() as s:
            s_list = []
            OrderRefundNotes.query.filter(
                OrderRefundNotes.isdelete == False,
                OrderRefundNotes.OMid == omid).delete_()
            order_main = s.query(OrderMain).filter_(
                OrderMain.OMid == omid,
                OrderMain.OMstatus.notin_([
                    OrderMainStatus.wait_pay.value,
                    OrderMainStatus.cancle.value,
                    OrderMainStatus.ready.value,
                ]), OrderMain.USid == usid).first_('不存在的订单')
            if order_main.OMinRefund is True:
                raise DumpliError('已经在售后中')
            # 之前的申请
            apply = OrderRefundApply.query.filter(
                OrderRefundApply.isdelete == False,
                OrderRefundApply.OMid == order_main.OMid,
                OrderRefundApply.ORAstatus.notin_([
                    ApplyStatus.reject.value,
                    ApplyStatus.cancle.value,
                ]),
            ).first()
            if apply:
                raise DumpliError('订单已在售后中, 请勿重复申请')
            if apply:
                apply.isdelete = True
                s_list.append(apply)
            # 申请主单售后, 所有的副单不可以有在未撤销的售后状态或未被拒绝
            order_parts_in_refund = OrderPart.query.filter_by_({
                'OMid':
                omid,
                'OPisinORA':
                True
            }).all()
            for order_part in order_parts_in_refund:
                part_apply = OrderRefundApply.query.filter_by_({
                    'OPid':
                    order_part.OPid
                }).first()
                # if not cancled_apply:
                #     raise DumpliError('订单中有商品已在售后中, 请勿重复申请')
                if part_apply and part_apply.ORAstatus != ApplyStatus.cancle.value:
                    raise DumpliError('订单中有商品已在售后中, 请勿重复申请')
                elif part_apply:
                    part_apply.isdelete = True
                    s_list.append(part_apply)
            order_main.OMinRefund = True  # 主单状态
            s_list.append(order_main)
            # 申请参数校验
            oraproductstatus = int(data.get('oraproductstatus'))  # 是否已经收到货
            ORAproductStatus(oraproductstatus)

            orastate = int(
                data.get('orastate', OrderRefundORAstate.goods_money.value))
            try:
                OrderRefundORAstate(orastate)
            except Exception as e:
                raise ParamsError('orastate参数错误')
            oramount = data.get('oramount')
            if oramount:
                oramount = Decimal(str(oramount))
            if not oramount or oramount > order_main.OMtrueMount:
                raise ParamsError('oramount退款金额不正确')
            # 不改变副单的状态
            # order_parts = s.query(OrderPart).filter_by_({'OMid': omid}).all()
            # for order_part in order_parts:
            #     order_part.OPisinORA = True  # 附单状态
            #     s_list.append(order_part)
            # 添加申请表
            oraddtionvoucher = data.get('oraddtionvoucher')
            oraaddtion = data.get('oraaddtion')
            order_refund_apply_dict = {
                'ORAid': str(uuid.uuid1()),
                'OMid': omid,
                'ORAsn': self._generic_no(),
                'USid': usid,
                'ORAmount': oramount,
                'ORaddtionVoucher': oraddtionvoucher,
                'ORAaddtion': oraaddtion,
                'ORAreason': data.get('orareason'),
                'ORAproductStatus': oraproductstatus,
                'ORAstate': orastate,
            }
            order_refund_apply_instance = OrderRefundApply.create(
                order_refund_apply_dict)
            s_list.append(order_refund_apply_instance)
            s.add_all(s_list)
            current_app.logger.info(
                'the order_main refund apply id(oraid) is {}'.format(
                    order_refund_apply_dict['ORAid']))
Ejemplo n.º 13
0
    def _order_part_refund(self, opid, usid, data):
        with self.strade.auto_commit() as s:
            s_list = []
            # 副单
            order_part = s.query(OrderPart).filter(
                OrderPart.OPid == opid,
                OrderPart.isdelete == False).first_('不存在的订单详情')
            # 删除原来的
            OrderRefundNotes.query.filter(
                OrderRefundNotes.isdelete == False,
                OrderRefundNotes.OPid == order_part.OPid).delete_()
            # 所在主单的副单个数
            order_part_count = OrderPart.query.filter_by_({
                'OMid':
                order_part.OMid
            }).count()
            current_app.logger.info(
                '当前副单所在主单有 {} 个商品'.format(order_part_count))
            if order_part_count == 1:
                # 如果只有一个副单, 则改为申请主单售后
                current_app.logger.info('改为主单售后')
                return self._order_main_refund(order_part.OMid, usid, data)

            # 副单售后
            if order_part.OPisinORA is True:
                cancled_apply = OrderRefundApply.query.filter_by_({
                    'ORAstatus':
                    ApplyStatus.cancle.value,
                    'OPid':
                    opid
                }).first()
                if not cancled_apply:
                    raise DumpliError('重复申请')
                # 删除之前已经撤销的售后
                cancled_apply.isdelete = True
                s_list.append(cancled_apply)
            # 主单售后状态
            omid = order_part.OMid
            order_main = s.query(OrderMain).filter_(
                OrderMain.OMid == omid,
                OrderMain.OMstatus.notin_([
                    OrderMainStatus.wait_pay.value,
                    OrderMainStatus.cancle.value,
                    OrderMainStatus.ready.value,
                ]), OrderMain.USid == usid).first_('不存在的订单')
            if order_main.OMinRefund == True:
                raise DumpliError('主订单已在售后中, 请勿重复申请')
            apply = OrderRefundApply.query.filter(
                OrderRefundApply.OPid == opid,
                OrderRefundApply.isdelete == False, OrderRefundApply.ORAstatus
                != ApplyStatus.reject.value).first()
            if apply and apply.ORAstatus != ApplyStatus.cancle.value:
                raise DumpliError('订单已在售后中, 请勿重复申请')
            elif apply:
                current_app.logger.info('删除原来副单售后申请')
                apply.isdelete = True
                s_list.append(apply)
            # 不改变主单的状态
            # order_main.OMinRefund = True  # 主单状态
            # s_list.append(order_main)

            order_part.OPisinORA = True  # 附单状态
            s_list.append(order_part)
            # 申请参数校验
            oraproductstatus = data.get('oraproductstatus')
            ORAproductStatus(oraproductstatus)
            oramount = data.get('oramount')
            if oramount:
                oramount = Decimal(str((oramount)))
            if not oramount or oramount > order_part.OPsubTrueTotal:
                raise ParamsError('退款金额不正确')
            oraddtionvoucher = data.get('oraddtionvoucher')
            if oraddtionvoucher and isinstance(oraddtionvoucher, list):
                oraddtionvoucher = oraddtionvoucher
            else:
                oraddtionvoucher = None
            oraaddtion = data.get('oraaddtion')
            orastate = data.get('orastate',
                                OrderRefundORAstate.goods_money.value)
            try:
                OrderRefundORAstate(orastate)
            except Exception as e:
                raise ParamsError('orastate参数错误')
            # 添加申请表
            order_refund_apply_dict = {
                'ORAid': str(uuid.uuid1()),
                # 'OMid': omid,
                'ORAsn': self._generic_no(),
                'OPid': opid,
                'USid': usid,
                'ORAmount': oramount,
                'ORaddtionVoucher': oraddtionvoucher,
                'ORAaddtion': oraaddtion,
                'ORAreason': data.get('orareason'),
                'ORAproductStatus': oraproductstatus,
                'ORAstate': orastate,
            }
            order_refund_apply_instance = OrderRefundApply.create(
                order_refund_apply_dict)
            s_list.append(order_refund_apply_instance)
            s.add_all(s_list)
            current_app.logger.info(
                'the order_part refund apply id(oraid) is {}'.format(
                    order_refund_apply_dict['ORAid']))
Ejemplo n.º 14
0
    def _order_main_refund(self, omid, usid, data):
        with self.strade.auto_commit() as s:
            s_list = []
            OrderRefundNotes.query.filter(
                OrderRefundNotes.isdelete == False,
                OrderRefundNotes.OMid == omid).delete_()
            order_main = s.query(OrderMain).filter_(
                OrderMain.OMid == omid,
                OrderMain.OMstatus.notin_([
                    OrderMainStatus.wait_pay.value,
                    OrderMainStatus.cancle.value,
                    OrderMainStatus.ready.value,
                ]), OrderMain.USid == usid).first_('不存在的订单')
            if order_main.OMinRefund is True:
                raise DumpliError('已经在售后中')
            if order_main.OMfrom == OrderFrom.integral_store.value:
                raise StatusError('星币商城订单暂不支持退换货,如有问题请及时联系客服')
            elif order_main.OMfrom == OrderFrom.trial_commodity.value:
                raise StatusError('试用商品订单暂不支持退换货,如有问题请及时联系客服')
            elif order_main.OMfrom == OrderFrom.guess_group.value:  # 拼团竞猜申请退款时
                guess_record = GuessRecord.query.filter(
                    GuessRecord.isdelete == False,
                    GuessRecord.OMid == order_main.OMid, GuessRecord.GRstatus
                    == GuessRecordStatus.valid.value).first()
                if guess_record:
                    current_app.logger.info('拼团订单申请售后,GRid {}'.format(
                        guess_record.GRid))

                    guess_record.GRstatus = GuessRecordStatus.invalid.value  # 拼团记录改为失效
                    guess_group = GuessGroup.query.filter(
                        GuessGroup.isdelete == False,
                        GuessGroup.GGid == guess_record.GGid).first()
                    if guess_group and guess_group.GGstatus in (
                            GuessGroupStatus.pending.value,
                            GuessGroupStatus.waiting.value):
                        if guess_group.USid == order_main.USid:
                            current_app.logger.info(
                                '拼团GGid {} ;发起人申请售后'.format(guess_group.GGid))
                            guess_group.GGstatus = GuessGroupStatus.failed.value  # 如果是拼团发起人,该团直接拼团失败
                            # 退还其余两人押金
                            grs = GuessRecord.query.filter(
                                GuessRecord.isdelete == False,
                                GuessRecord.USid != order_main.USid,
                                GuessRecord.GGid == guess_group.GGid,
                                GuessRecord.GRstatus ==
                                GuessRecordStatus.valid.value).all()
                            for gr in grs:
                                # gr.GRstatus = GuessRecordStatus.invalid.value
                                current_app.logger.info('退还参与者 {} 的押金'.format(
                                    gr.USid))
                                order_part = OrderPart.query.filter_by_(
                                    OMid=gr.OMid).first()  # 参与者的副单
                                tem_order_main = OrderMain.query.filter_by_(
                                    OMid=gr.OMid).first()  # 参与者主单
                                self.corder._cancle(
                                    tem_order_main)  # 参与者主单改为取消
                                # 参与者退还押金
                                price = order_part.OPsubTrueTotal
                                user_commision_dict = {
                                    'UCid':
                                    str(uuid.uuid1()),
                                    'UCcommission':
                                    Decimal(price).quantize(Decimal('0.00')),
                                    'USid':
                                    tem_order_main.USid,
                                    'UCstatus':
                                    UserCommissionStatus.in_account.value,
                                    'UCtype':
                                    UserCommissionType.group_refund.value,
                                    'PRtitle':
                                    f'[拼团押金]{order_part.PRtitle}',
                                    'SKUpic':
                                    order_part.PRmainpic,
                                    'OMid':
                                    order_part.OMid,
                                    'OPid':
                                    order_part.OPid
                                }
                                db.session.add(
                                    UserCommission.create(user_commision_dict))

                                user_wallet = UserWallet.query.filter_by_(
                                    USid=tem_order_main.USid).first()

                                if user_wallet:
                                    user_wallet.UWbalance = Decimal(
                                        str(user_wallet.UWbalance
                                            or 0)) + Decimal(str(price))
                                    user_wallet.UWtotal = Decimal(
                                        str(user_wallet.UWtotal
                                            or 0)) + Decimal(str(price))
                                    user_wallet.UWcash = Decimal(
                                        str(user_wallet.UWcash
                                            or 0)) + Decimal(str(price))
                                    db.session.add(user_wallet)
                                else:
                                    user_wallet_instance = UserWallet.create({
                                        'UWid':
                                        str(uuid.uuid1()),
                                        'USid':
                                        tem_order_main.USid,
                                        'UWbalance':
                                        Decimal(price).quantize(
                                            Decimal('0.00')),
                                        'UWtotal':
                                        Decimal(price).quantize(
                                            Decimal('0.00')),
                                        'UWcash':
                                        Decimal(price).quantize(
                                            Decimal('0.00')),
                                        # 'UWexpect': user_commision.UCcommission,
                                        'CommisionFor':
                                        ApplyFrom.user.value
                                    })
                                    db.session.add(user_wallet_instance)
                        else:
                            if guess_group.GGstatus == GuessGroupStatus.waiting.value:
                                current_app.logger.info('拼团等待开奖中,改为正在拼')
                                guess_group.GGstatus = GuessGroupStatus.pending.value

            # 之前的申请
            apply = OrderRefundApply.query.filter(
                OrderRefundApply.isdelete == False,
                OrderRefundApply.OMid == order_main.OMid,
                OrderRefundApply.ORAstatus.notin_([
                    ApplyStatus.reject.value,
                    ApplyStatus.cancle.value,
                ]),
            ).first()
            if apply:
                raise DumpliError('订单已在售后中, 请勿重复申请')
            if apply:
                apply.isdelete = True
                s_list.append(apply)
            # 申请主单售后, 所有的副单不可以有在未撤销的售后状态或未被拒绝
            order_parts_in_refund = OrderPart.query.filter_by_({
                'OMid':
                omid,
                'OPisinORA':
                True
            }).all()
            for order_part in order_parts_in_refund:
                part_apply = OrderRefundApply.query.filter_by_({
                    'OPid':
                    order_part.OPid
                }).first()
                # if not cancled_apply:
                #     raise DumpliError('订单中有商品已在售后中, 请勿重复申请')
                if part_apply and part_apply.ORAstatus != ApplyStatus.cancle.value:
                    raise DumpliError('订单中有商品已在售后中, 请勿重复申请')
                elif part_apply:
                    part_apply.isdelete = True
                    s_list.append(part_apply)
            order_main.OMinRefund = True  # 主单状态
            s_list.append(order_main)
            # 申请参数校验
            oraproductstatus = int(data.get('oraproductstatus'))  # 是否已经收到货
            ORAproductStatus(oraproductstatus)

            orastate = int(
                data.get('orastate', OrderRefundORAstate.goods_money.value))
            try:
                OrderRefundORAstate(orastate)
            except Exception as e:
                raise ParamsError('orastate参数错误')
            oramount = data.get('oramount')
            if oramount:
                oramount = Decimal(str(oramount))
            if not oramount or oramount > order_main.OMtrueMount:
                raise ParamsError('oramount退款金额不正确')
            # 不改变副单的状态
            # order_parts = s.query(OrderPart).filter_by_({'OMid': omid}).all()
            # for order_part in order_parts:
            #     order_part.OPisinORA = True  # 附单状态
            #     s_list.append(order_part)
            # 添加申请表
            oraddtionvoucher = data.get('oraddtionvoucher')
            oraaddtion = data.get('oraaddtion')
            order_refund_apply_dict = {
                'ORAid': str(uuid.uuid1()),
                'OMid': omid,
                'ORAsn': self._generic_no(),
                'USid': usid,
                'ORAmount': oramount,
                'ORaddtionVoucher': oraddtionvoucher,
                'ORAaddtion': oraaddtion,
                'ORAreason': data.get('orareason'),
                'ORAproductStatus': oraproductstatus,
                'ORAstate': orastate,
            }
            order_refund_apply_instance = OrderRefundApply.create(
                order_refund_apply_dict)
            s_list.append(order_refund_apply_instance)
            s.add_all(s_list)
            current_app.logger.info(
                'the order_main refund apply id(oraid) is {}'.format(
                    order_refund_apply_dict['ORAid']))