Exemplo n.º 1
0
class CItems:
    def __init__(self):
        self.sproduct = SProducts()

    def list(self):
        """列出标签"""
        form = ItemListForm().valid_data()
        ittype = form.ittype.data
        psid = form.psid.data
        kw = form.kw.data
        recommend = form.recommend.data
        recommend = True if str(recommend) == '1' else None

        # 如果查询商品对应的标签, 则可以传场景的id
        items_query = Items.query.filter_(Items.isdelete == False, Items.ITtype == ittype,
                                          Items.ITrecommend == recommend, Items.ITauthority != ItemAuthrity.other.value,
                                          Items.ITposition != ItemPostion.other.value,
                                          )

        if psid:
            items_query = items_query.outerjoin(SceneItem, SceneItem.ITid == Items.ITid
                                                ).filter_(SceneItem.isdelete == False,
                                                          SceneItem.PSid == psid,
                                                          )

            scene_items = [sit.ITid for sit in
                           SceneItem.query.filter(SceneItem.PSid == psid, SceneItem.isdelete == False,
                                                  ProductScene.isdelete == False).all()]
            prscene_count = Products.query.outerjoin(ProductItems, ProductItems.PRid == Products.PRid
                                                     ).filter(Products.isdelete == False,
                                                              Products.PRfeatured == True,
                                                              Products.PRstatus == ProductStatus.usual.value,
                                                              ProductItems.isdelete == False,
                                                              ProductItems.ITid.in_(list(set(scene_items)))
                                                              ).count()
            if not prscene_count:
                items_query = items_query.filter(Items.ITid != 'planet_featured')  # 如果该场景下没有精选商品,不显示“大行星精选”标签

        if is_supplizer():
            # 供应商下不显示被限时场景关联着的标签
            time_limit_itids = [it.ITid for it in
                                Items.query.join(SceneItem, SceneItem.ITid == Items.ITid
                                                 ).join(ProductScene, ProductScene.PSid == SceneItem.PSid
                                                        ).filter(SceneItem.isdelete == False,
                                                                 ProductScene.isdelete == False,
                                                                 Items.isdelete == False,
                                                                 ProductScene.PStimelimited == True).all()]
            items_query = items_query.filter(Items.ITauthority == ItemAuthrity.no_limit.value,
                                             Items.ITposition.in_([ItemPostion.scene.value,
                                                                   ItemPostion.news_bind.value,
                                                                   ItemPostion.index.value]
                                                                  ),
                                             Items.ITid.notin_(time_limit_itids),
                                             Items.ITid != 'planet_featured'
                                             )
        if is_admin():
            items_query = items_query.filter(Items.ITid != 'planet_featured')

        if kw:
            items_query = items_query.filter(
                Items.ITname.contains(kw)
            )
        items_query = items_query.order_by(Items.ITsort.asc(), Items.createtime.desc())

        # 普通用户默认获取已经自选过的圈子标签
        if str(ittype) == str(ItemType.news.value):
            uid = request.user.id if common_user() else None
            items = self._filter_new_items(uid=uid, option=form.option.data)
            return Success(data=items)
        items = items_query.all()
        for item in items:
            item.fill('ITtype_zh', ItemType(item.ITtype).zh_value)
            if item.ITtype == ItemType.product.value:
                pr_scene = ProductScene.query.outerjoin(SceneItem, SceneItem.PSid == ProductScene.PSid
                                                        ).filter_(SceneItem.isdelete == False,
                                                                  SceneItem.ITid == item.ITid,
                                                                  ProductScene.isdelete == False).all()
                if (is_supplizer() or is_admin()) and pr_scene:
                    psname_list = str([ps.PSname for ps in pr_scene])
                    psname_list = re.sub(r'[\[\]\'\,]+', '', psname_list)
                    item.ITname = getattr(item, 'ITname', '') + ' / ' + str(psname_list)  # 后台要显示标签所属场景

                item.fill('prscene', pr_scene)
        return Success('获取成功', data=items)

    def _filter_new_items(self, uid=None, option=None):
        """筛选出用户自选的圈子标签"""
        ucs = list()
        if uid:
            ucs = UserCollectionLog.query.filter_by_(UCLcollector=uid,
                                                     UCLcoType=CollectionType.news_tag.value).first()
        item_query = Items.query.filter(Items.isdelete == False,
                                        Items.ITtype == ItemType.news.value)
        if option and int(option) == NewsItemPostion.category.value:
            if ucs:
                itids = json.loads(ucs.UCLcollection)
                my_item = item_query.filter(Items.ITid.in_(itids)).order_by(func.field(Items.ITid, *itids)).all()
                candidate_item = item_query.filter(Items.ITid.notin_(itids)).all()

            else:
                my_item = item_query.all()
                candidate_item = []
            items = dict(my_item=my_item, candidate_item=candidate_item)
        elif option and (int(option) == NewsItemPostion.homepage.value or int(option) == NewsItemPostion.post.value):
            if ucs:
                itids = json.loads(ucs.UCLcollection)
                items = item_query.filter(Items.ITid.in_(itids), Items.ITid != 'mynews'
                                          ).order_by(func.field(Items.ITid, *itids)).all()

            else:
                items = item_query.filter(Items.ITid != 'mynews').all()
        else:
            if ucs:
                itids = json.loads(ucs.UCLcollection)
                current_app.logger.info("itids = {}".format(itids))
                items = item_query.filter(Items.ITid.in_(itids)).order_by(func.field(Items.ITid, *itids)).all()

            else:
                items = item_query.all()
        return items

    @admin_required
    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)
            BASEADMIN().create_action(AdminActionS.insert.value, 'Items', itid)
            # 标签场景标签表
            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)
                    BASEADMIN().create_action(AdminActionS.insert.value, 'SceneItem', psi)
            s.add_all(s_list)
        return Success('添加成功', {'itid': itid})

    @admin_required
    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})

    def _check_itsort(self, itsort, ittype):

        if itsort < 1:
            return 1
        count_item = Items.query.filter_by_(ITtype=ittype).count()
        if itsort > count_item:
            return count_item
        return itsort
Exemplo n.º 2
0
class CSku(object):
    def __init__(self):
        self.sproduct = SProducts()

    @token_required
    def add(self):
        """添加sku"""
        data = parameter_required(
            ('prid', 'skuattritedetail', 'skupic', 'skuprice', 'skustock'))
        prid = data.get('prid')
        # 验证
        product = self.sproduct.get_product_by_prid(prid, '商品不存在')
        skuattritedetail = data.get('skuattritedetail')
        prattribute = json.loads(product.PRattribute)
        if len(skuattritedetail) != len(prattribute) or not isinstance(
                skuattritedetail, list):
            raise ParamsError('skuattritedetail 参数不准确')
        price = data.get('skuprice')
        stock = data.get('skustock')
        assert price > 0 and stock > 0, '价格或库存参数不准确'
        # 添加
        with self.sproduct.auto_commit() as s:
            sku_instance = ProductSku.create({
                'SKUid':
                str(uuid.uuid4()),
                'PRid':
                prid,
                'SKUpic':
                data.get('skupic'),
                'SKUattriteDetail':
                json.dumps(skuattritedetail),
                'SKUprice':
                round(price, 2),
                'SKUstock':
                stock
            })
            s.add(sku_instance)
            if is_admin():
                BASEADMIN().create_action(AdminActionS.insert.value,
                                          'ProductSku', str(uuid.uuid4()))
        return Success('添加成功', {'skuid': sku_instance.SKUid})

    @token_required
    def update(self):
        data = parameter_required(('skuid', ))
        skuid = data.get('skuid')
        price = data.get('skuprice')
        stock = data.get('skustock')
        if price:
            if price < 0:
                raise ParamsError('价格小于0')
            price = round(price, 2)
        if stock and stock < 0:
            raise ParamsError('库存小于0')
        skuattritedetail = data.get('skuattritedetail')
        with self.sproduct.auto_commit() as s:
            sku = s.query(ProductSku).filter_by_({
                'SKUid': skuid
            }).first_('sku不存在')
            product = self.sproduct.get_product_by_prid(sku.PRid)
            prattribute = json.loads(product.PRattribute)
            if len(skuattritedetail) != len(prattribute) or not isinstance(
                    skuattritedetail, list):
                raise ParamsError('skuattritedetail 参数不准确')
            skuattritedetail = json.dumps(skuattritedetail)
            sku_dict = {
                'SKUpic': data.get('skupic'),
                'SKUprice': price,
                'SKUstock': stock,
                'SKUattriteDetail': skuattritedetail,
            }
            [setattr(sku, k, v) for k, v in sku_dict.items() if v is not None]
            s.add(sku)
            if is_admin():
                BASEADMIN().create_action(AdminActionS.update.value,
                                          'ProductSku', skuid)
        return Success('更新成功')

    @admin_required
    def delete(self):
        data = parameter_required(('skuid', ))
        skuid = data.get('skuid')
        with self.sproduct.auto_commit() as s:
            count = s.query(ProductSku).filter_by_({"SKUid": skuid}).delete_()
            BASEADMIN().create_action(AdminActionS.delete.value, 'ProductSku',
                                      skuid)
            if not count:
                raise NotFound('不存在的sku')
        return Success('删除成功')
Exemplo n.º 3
0
class CBrands(object):
    def __init__(self):
        self.sproduct = SProducts()

    @token_required
    def create(self):
        """创建品牌"""
        data = BrandsCreateForm().valid_data()
        pblogo = data.pblogo.data
        pbname = data.pbname.data
        pbdesc = data.pbdesc.data
        pblinks = data.pblinks.data
        itids = data.itids.data
        suid = data.suid.data
        pbbackgroud = data.pbbackgroud.data
        with self.sproduct.auto_commit() as s:
            s_list = []
            pbid = str(uuid.uuid1())
            pb_dict = {
                'PBid': pbid,
                'PBlogo': pblogo,
                'PBname': pbname,
                'PBdesc': pbdesc,
                'PBlinks': pblinks,
                'PBbackgroud': pbbackgroud,
                'SUid': suid
            }
            pb_instance = ProductBrand.create(pb_dict)
            s_list.append(pb_instance)
            # 创建标签-品牌中间表
            if itids:
                for itid in itids:
                    s.query(Items).filter_by_({
                        'ITid': itid,
                        'ITtype': ItemType.brand.value
                    }).first_('{}标签不存在或类型不正确'.format(itid))
                    brand_with_pbitem_instance = BrandWithItems.create({
                        'BWIid':
                        str(uuid.uuid4()),
                        'ITid':
                        itid,
                        'PBid':
                        pbid
                    })
                    s_list.append(brand_with_pbitem_instance)

            s.add_all(s_list)
        return Success('添加成功', {'pbid': pb_instance.PBid})

    def list(self):
        form = BrandsListForm().valid_data()
        pbstatus = dict(form.pbstatus.choices).get(form.pbstatus.data)
        free = dict(form.free.choices).get(form.free.data)
        time_order = dict(form.time_order.choices).get(form.time_order.data)
        itid = form.itid.data
        itid = itid.split('|') if itid else []
        kw = form.kw.data
        brand_query = ProductBrand.query.filter_(
            ProductBrand.isdelete == False, ProductBrand.PBstatus == pbstatus)
        if itid:
            brand_query = brand_query.join(
                BrandWithItems,
                ProductBrand.PBid == BrandWithItems.PBid).filter(
                    BrandWithItems.isdelete == False,
                    BrandWithItems.ITid.in_(itid))
        if is_supplizer():
            current_app.logger.info('供应商查看品牌列表..')
            brand_query = brand_query.filter(
                ProductBrand.SUid == request.user.id)
        if free is True:
            brand_query = brand_query.filter(ProductBrand.SUid.is_(None))
        elif free is False:
            brand_query = brand_query.filter(ProductBrand.SUid.isnot(None))
        if kw:
            brand_query = brand_query.filter(ProductBrand.PBname.contains(kw))
        brands = brand_query.order_by(time_order).all_with_page()
        for brand in brands:
            brand.fill('PBstatus_en', ProductBrandStatus(brand.PBstatus).name)
            brand.fill('PBstatus_zh',
                       ProductBrandStatus(brand.PBstatus).zh_value)
            brand.add('createtime')
            # 标签
            print(brand.PBid)
            pb_items = Items.query.filter_by().join(
                BrandWithItems, Items.ITid == BrandWithItems.ITid).filter_(
                    BrandWithItems.PBid == brand.PBid,
                    BrandWithItems.isdelete == False,
                ).all()
            brand.fill('items', pb_items)
            if is_admin() or brand.SUid:
                supplizer = Supplizer.query.filter(
                    Supplizer.isdelete == False,
                    Supplizer.SUid == brand.SUid).first()
                if not supplizer:
                    with db.auto_commit():
                        brand.SUid = None
                        db.session.add(brand)
                    continue
                supplizer.fields = [
                    'SUloginPhone', 'SUlinkPhone', 'SUname', 'SUlinkman',
                    'SUheader'
                ]
                brand.fill('supplizer', supplizer)
        return Success(data=brands)

    def get(self):
        data = parameter_required(('pbid', ))
        pbid = data.get('pbid')
        product_brand = ProductBrand.query.filter_by({
            'PBid': pbid
        }).first_('品牌不存在')
        product_brand.fill('pbstatus_en',
                           ProductStatus(product_brand.PBstatus).name)
        return Success(data=product_brand)

    def list_with_group(self):
        form = BrandsListForm().valid_data()
        time_order = dict(form.time_order.choices).get(form.time_order.data)
        pbstatus = dict(form.pbstatus.choices).get(form.pbstatus.data)
        itid = form.itid.data
        if not itid:
            # todo 默认不会展示首页标签
            pass
        itid = itid.split('|') if itid else []
        print(itid)
        with self.sproduct.auto_commit() as s:
            items = s.query(Items).filter_(
                Items.ITtype == ItemType.brand.value,
                Items.ITid.in_(itid)).filter_by_().order_by(
                    Items.ITsort).all_(True)
            res = []
            for item in items:
                itid = item.ITid
                brands = self._get_brand_list(s,
                                              itid,
                                              pbstatus,
                                              time_order,
                                              page=False,
                                              pb_in_sub=False)
                if not brands:
                    continue
                item.fill('brands', brands)
                res.append(item)
        return Success(data=res)

    @token_required
    def off_shelves(self):
        """上下架"""
        data = parameter_required(('pbid', ))
        pbid = data.get('pbid')
        pbstatus = data.get('pbstatus', 'up')
        with self.sproduct.auto_commit() as s:
            product_brand_instance = s.query(ProductBrand).filter_by_({
                'PBid':
                pbid
            }).first_('品牌不存在')
            s_list = []
            if pbstatus == 'up':
                # 上架
                product_brand_instance.PBstatus = ProductBrandStatus.upper.value
                s_list.append(product_brand_instance)
                msg = '上架成功'
            else:
                # 下架品牌
                product_brand_instance.PBstatus = ProductBrandStatus.off_shelves.value
                s_list.append(product_brand_instance)
                # 下架商品
                s.query(Products).filter_by_({
                    'PBid': pbid
                }).update({'PRstatus': ProductStatus.off_shelves.value})
                msg = '下架成功'
            s.add_all(s_list)
        return Success(msg)

    @token_required
    def update(self):
        data = BrandUpdateForm().valid_data()
        pblogo = data.pblogo.data
        pbname = data.pbname.data
        pbdesc = data.pbdesc.data
        pblinks = data.pblinks.data
        itids = data.itids.data
        suid = data.suid.data
        pbbackgroud = data.pbbackgroud.data
        pbid = data.pbid.data

        with self.sproduct.auto_commit() as s:
            s_list = []
            product_brand_instance = s.query(ProductBrand).filter_by_({
                'PBid':
                pbid
            }).first_('不存在的品牌')
            product_brand_instance.update({
                'PBlogo': pblogo,
                'PBname': pbname,
                'PBdesc': pbdesc,
                'PBlinks': pblinks,
                'PBbackgroud': pbbackgroud,
                'SUid': suid
            })
            s_list.append(product_brand_instance)
            # 品牌已经关联的中间
            old_item_id = s.query(BrandWithItems.ITid).filter_by_({
                'PBid': pbid
            }).all()
            old_item_id = [x.ITid for x in old_item_id]
            if itids:
                for itid in itids:
                    if itid in old_item_id:
                        old_item_id.remove(itid)
                        # 已经存在
                        continue
                    # 如果没在之前的表中
                    else:
                        s.query(Items).filter_by_({
                            'ITid':
                            itid,
                            'ITtype':
                            ItemType.brand.value
                        }).first_('{}标签不存在或类型不正确'.format(itid))
                        brand_with_pbitem_instance = BrandWithItems.create({
                            'BWIid':
                            str(uuid.uuid4()),
                            'ITid':
                            itid,
                            'PBid':
                            pbid
                        })
                        s_list.append(brand_with_pbitem_instance)
                # 删除
                s.query(BrandWithItems).filter_(
                    BrandWithItems.ITid.notin_(itids),
                    BrandWithItems.PBid == pbid,
                    BrandWithItems.isdelete == False).delete_(
                        synchronize_session=False)
            s.add_all(s_list)
        return Success('更新成功')

    @admin_required
    def delete(self):
        # todo 记录删除操作管理员
        data = parameter_required(('pbid', ))
        pbid = data.get('pbid')
        with db.auto_commit():
            brand = ProductBrand.query.filter(
                ProductBrand.PBid == pbid,
                ProductBrand.isdelete == False).first_('品牌不存在')
            brand.isdelete = True
            db.session.add(brand)
            # 商品下架
            off_products = Products.query.filter(
                Products.isdelete == False, Products.PBid == pbid).update(
                    {'PRstatus': ProductStatus.off_shelves.value})
        return Success('删除成功')

    def _get_brand_list(self,
                        s,
                        itid,
                        pbstatus,
                        time_order=(),
                        pb_in_sub=True,
                        page=True):
        itid = itid.split('|') if itid else []
        print(itid)
        brands = s.query(ProductBrand).filter_by_(). \
            outerjoin(BrandWithItems, ProductBrand.PBid == BrandWithItems.PBid). \
            filter_(
            or_(BrandWithItems.isdelete == False, BrandWithItems.isdelete.is_(None)),
            BrandWithItems.ITid.in_(itid),
            ProductBrand.PBstatus == pbstatus,
        ).order_by(ProductBrand.createtime).all_(page)
        for brand in brands:
            brand.fill('PBstatus_en', ProductBrandStatus(brand.PBstatus).name)
            brand.fill('PBstatus_zh',
                       ProductBrandStatus(brand.PBstatus).zh_value)
            # 标签
            pb_items = s.query(Items).filter_by().join(
                BrandWithItems, Items.ITid == BrandWithItems.ITid).filter_(
                    BrandWithItems.PBid == brand.PBid,
                    BrandWithItems.isdelete == False,
                ).all()
            if pb_in_sub:
                brand.fill('pb_items', pb_items)
        return brands
Exemplo n.º 4
0
class CBrands(object):
    def __init__(self):
        self.sproduct = SProducts()
        self.itid_re_pr = 'home_recommend'
        self.itid_re_ca = 'home_recommend_category'
        self.prfields = ['PRprice', 'PRtitle', 'PRmainpic', 'PRlinePrice', 'PRid']
        self.br_new = 5
        # 前台不展示的pbid(野, 大行星)
        self.hide_pbid = ('68bad064-14e9-11e9-b226-00163e13a3e3', '9e8692a4-43c0-11e9-b590-00163e13a3e3')

    @token_required
    def create(self):
        """创建品牌"""
        data = BrandsCreateForm().valid_data()
        pblogo = data.pblogo.data
        pbname = data.pbname.data
        pbdesc = data.pbdesc.data
        pblinks = data.pblinks.data
        itids = data.itids.data
        suid = data.suid.data
        pbbackgroud = data.pbbackgroud.data
        pbsort = data.pbsort.data
        with self.sproduct.auto_commit() as s:
            s_list = []
            pbid = str(uuid.uuid1())
            pbsort = self._check_sort(pbsort, model=ProductBrand, default=1)
            pb_dict = {
                'PBid': pbid,
                'PBlogo': pblogo,
                'PBname': pbname,
                'PBdesc': pbdesc,
                'PBlinks': pblinks,
                'PBbackgroud': pbbackgroud,
                'PBsort': pbsort,
                'SUid': suid,
                'PBintegralPayRate': data.pbintegralpayrate.data
            }
            pb_instance = ProductBrand.create(pb_dict)
            s_list.append(pb_instance)
            # 创建标签-品牌中间表
            if itids:
                for itid in itids:
                    s.query(Items).filter_by_({'ITid': itid, 'ITtype': ItemType.brand.value}).first_(
                        '{}标签不存在或类型不正确'.format(itid))
                    brand_with_pbitem_instance = BrandWithItems.create({
                        'BWIid': str(uuid.uuid4()),
                        'ITid': itid,
                        'PBid': pbid
                    })
                    s_list.append(brand_with_pbitem_instance)

            s.add_all(s_list)
        return Success('添加成功', {'pbid': pb_instance.PBid})

    def list(self):
        form = BrandsListForm().valid_data()
        pbstatus = dict(form.pbstatus.choices).get(form.pbstatus.data)
        free = dict(form.free.choices).get(form.free.data)
        # time_order = dict(form.time_order.choices).get(form.time_order.data)
        itid = form.itid.data
        itid = itid.split('|') if itid else []
        kw = form.kw.data
        brand_query = ProductBrand.query.filter_(
            ProductBrand.isdelete == False,
            ProductBrand.PBstatus == pbstatus
        )
        if itid:
            brand_query = brand_query.join(
                BrandWithItems, ProductBrand.PBid == BrandWithItems.PBid
            ).filter(
                BrandWithItems.isdelete == False,
                BrandWithItems.ITid.in_(itid)
            )
        if is_supplizer():
            current_app.logger.info('供应商查看品牌列表..')
            brand_query = brand_query.filter(
                ProductBrand.SUid == request.user.id
            )
        if free is True:
            brand_query = brand_query.filter(
                ProductBrand.SUid.is_(None)
            )
        elif free is False:
            brand_query = brand_query.filter(
                ProductBrand.SUid.isnot(None)
            )
        if kw:
            brand_query = brand_query.filter(
                ProductBrand.PBname.contains(kw)
            )
        if common_user():
            brand_query = brand_query.filter(ProductBrand.PBid.notin_(self.hide_pbid))
        brands = brand_query.order_by(ProductBrand.PBsort.asc(), ProductBrand.createtime.desc()).all_with_page()

        for brand in brands:
            brand.fill('PBstatus_en', ProductBrandStatus(brand.PBstatus).name)
            brand.fill('PBstatus_zh', ProductBrandStatus(brand.PBstatus).zh_value)
            brand.add('createtime')
            # 标签
            print(brand.PBid)
            pb_items = Items.query.filter_by().join(BrandWithItems, Items.ITid == BrandWithItems.ITid).filter_(
                BrandWithItems.PBid == brand.PBid,
                BrandWithItems.isdelete == False,
            ).all()
            brand.fill('items', pb_items)
            if is_admin() or brand.SUid:
                supplizer = Supplizer.query.filter(
                    Supplizer.isdelete == False,
                    Supplizer.SUid == brand.SUid
                ).first()
                if not supplizer:
                    with db.auto_commit():
                        brand.SUid = None
                        db.session.add(brand)
                    continue
                supplizer.fields = ['SUloginPhone', 'SUlinkPhone', 'SUname', 'SUlinkman', 'SUheader']
                brand.fill('supplizer', supplizer)
            self._fill_brand(brand, recommend_pr=True, coupon=True)

        return Success(data=brands)

    def get(self):
        data = parameter_required(('pbid',))
        pbid = data.get('pbid')
        product_brand = ProductBrand.query.filter_by({'PBid': pbid}).first_('品牌不存在')
        product_brand.fill('pbstatus_en', ProductStatus(product_brand.PBstatus).name)
        self._fill_brand(product_brand, new_product=True, banner_show=True)
        return Success(data=product_brand)

    def list_with_group(self):
        form = BrandsListForm().valid_data()
        time_order = dict(form.time_order.choices).get(form.time_order.data)
        pbstatus = dict(form.pbstatus.choices).get(form.pbstatus.data)
        itid = form.itid.data
        if not itid:
            # todo 默认不会展示首页标签
            pass
        itid = itid.split('|') if itid else []
        print(itid)
        with self.sproduct.auto_commit() as s:
            items = s.query(Items).filter_(
                Items.ITtype == ItemType.brand.value,
                Items.ITid.in_(itid)
            ).filter_by_().order_by(Items.ITsort).all_(True)
            res = []
            for item in items:
                itid = item.ITid
                brands = self._get_brand_list(s, itid, pbstatus, time_order, page=False, pb_in_sub=False)
                if not brands:
                    continue
                item.fill('brands', brands)
                res.append(item)
        return Success(data=res)

    @token_required
    def off_shelves(self):
        """上下架"""
        data = parameter_required(('pbid',))
        pbid = data.get('pbid')
        pbstatus = data.get('pbstatus', 'up')
        with self.sproduct.auto_commit() as s:
            product_brand_instance = s.query(ProductBrand).filter_by_({
                'PBid': pbid
            }).first_('品牌不存在')
            s_list = []
            if pbstatus == 'up':
                # 上架
                product_brand_instance.PBstatus = ProductBrandStatus.upper.value
                s_list.append(product_brand_instance)
                msg = '上架成功'
            else:
                # 下架品牌
                product_brand_instance.PBstatus = ProductBrandStatus.off_shelves.value
                s_list.append(product_brand_instance)
                # 下架商品
                s.query(Products).filter_by_({'PBid': pbid}).update({
                    'PRstatus': ProductStatus.off_shelves.value
                })
                msg = '下架成功'
            s.add_all(s_list)
        return Success(msg)

    @token_required
    def update(self):
        data = BrandUpdateForm().valid_data()
        pblogo = data.pblogo.data
        pbname = data.pbname.data
        pbdesc = data.pbdesc.data
        pblinks = data.pblinks.data
        itids = data.itids.data
        suid = data.suid.data
        pbbackgroud = data.pbbackgroud.data
        pbid = data.pbid.data
        pbsort = data.pbsort.data

        with self.sproduct.auto_commit() as s:
            s_list = []
            product_brand_instance = s.query(ProductBrand).filter_by_({
                'PBid': pbid
            }).first_('不存在的品牌')
            if pbsort:
                pbsort = self._check_sort(pbsort, model=ProductBrand)
            else:
                pbsort = None
            product_brand_instance.update({
                'PBlogo': pblogo,
                'PBname': pbname,
                'PBdesc': pbdesc,
                'PBlinks': pblinks,
                'PBbackgroud': pbbackgroud,
                'SUid': suid,
                'PBsort': pbsort,
                'PBintegralPayRate': data.pbintegralpayrate.data
            })
            s_list.append(product_brand_instance)
            # 品牌已经关联的中间
            old_item_id = s.query(BrandWithItems.ITid).filter_by_({'PBid': pbid}).all()
            old_item_id = [x.ITid for x in old_item_id]
            if itids:
                for itid in itids:
                    if itid in old_item_id:
                        old_item_id.remove(itid)
                        # 已经存在
                        continue
                    # 如果没在之前的表中
                    else:
                        s.query(Items).filter_by_({'ITid': itid, 'ITtype': ItemType.brand.value}).first_(
                            '{}标签不存在或类型不正确'.format(itid))
                        brand_with_pbitem_instance = BrandWithItems.create({
                            'BWIid': str(uuid.uuid4()),
                            'ITid': itid,
                            'PBid': pbid
                        })
                        s_list.append(brand_with_pbitem_instance)
                # 删除
                s.query(BrandWithItems).filter_(BrandWithItems.ITid.notin_(itids),
                                                BrandWithItems.PBid == pbid,
                                                BrandWithItems.isdelete == False).delete_(synchronize_session=False)
            s.add_all(s_list)
        return Success('更新成功')

    @admin_required
    def delete(self):
        # todo 记录删除操作管理员
        data = parameter_required(('pbid',))
        pbid = data.get('pbid')
        with db.auto_commit():
            brand = ProductBrand.query.filter(
                ProductBrand.PBid == pbid,
                ProductBrand.isdelete == False
            ).first_('品牌不存在')
            brand.isdelete = True
            db.session.add(brand)
            BASEADMIN().create_action(AdminActionS.delete.value, 'ProductBrand', pbid)
            # 商品下架
            off_products = Products.query.filter(
                Products.isdelete == False,
                Products.PBid == pbid
            ).update({
                'PRstatus': ProductStatus.off_shelves.value
            })
        return Success('删除成功')

    def _get_brand_list(self, s, itid, pbstatus, time_order=(), pb_in_sub=True, page=True):
        itid = itid.split('|') if itid else []
        print(itid)
        brands = s.query(ProductBrand).filter_by_(). \
            outerjoin(BrandWithItems, ProductBrand.PBid == BrandWithItems.PBid). \
            filter_(
            or_(BrandWithItems.isdelete == False, BrandWithItems.isdelete.is_(None)),
            BrandWithItems.ITid.in_(itid),
            ProductBrand.PBstatus == pbstatus,
        ).order_by(ProductBrand.createtime).all_(page)
        for brand in brands:
            brand.fill('PBstatus_en', ProductBrandStatus(brand.PBstatus).name)
            brand.fill('PBstatus_zh', ProductBrandStatus(brand.PBstatus).zh_value)
            # 标签
            pb_items = s.query(Items).filter_by().join(BrandWithItems, Items.ITid == BrandWithItems.ITid).filter_(
                BrandWithItems.PBid == brand.PBid,
                BrandWithItems.isdelete == False,
            ).all()
            if pb_in_sub:
                brand.fill('pb_items', pb_items)
        return brands

    def _fill_brand(self, brand, **kwargs):
        product_num, product_fields, = kwargs.get('product_num', 3), kwargs.get('product_fields', list())
        new_product = kwargs.get('new_product', False)
        banner_show = kwargs.get('banner_show', False)
        recommend_pr = kwargs.get('recommend_pr', False)
        coupon = kwargs.get('coupon', False)

        if not product_fields:
            product_fields = self.prfields[:]

        if coupon:
            user = None
            if common_user():
                user = get_current_user()
            brand_coupon = self._get_brand_coupon(brand.SUid, user)

            if brand_coupon:
                from planet.control.CCoupon import CCoupon
                ccoupon = CCoupon()
                usid = user.USid if user else None
                ccoupon._coupon(brand_coupon, usid=usid, fill_con=False)
                product_num -= 1

                brand.fill('coupon', brand_coupon)

        # 推荐商品
        if recommend_pr:
            brand_recommend_product = self._recommend_pb_product(brand.PBid).all()[:product_num]
            pr_supplement_id = list()
            if brand_recommend_product:
                for product in brand_recommend_product:
                    product.fields = product_fields
                    pr_supplement_id.append(product.PRid)

            supplement_num = product_num - len(brand_recommend_product)
            if supplement_num:
                supplement_product = Products.query.filter(
                    Products.isdelete == false(), Products.PBid == brand.PBid).order_by(
                    Products.createtime.desc(), Products.PRid.notin_(pr_supplement_id)).all()
                brand_recommend_product.extend(supplement_product[:supplement_num])
            if brand_recommend_product:
                brand.fill('recommend', brand_recommend_product)

        # 新品推荐
        if new_product:
            brand_new_prodct = Products.query.filter(
                Products.isdelete == false(), Products.PBid == brand.PBid).order_by(Products.createtime.desc()).all()
            brand_new_prodct = brand_new_prodct[:self.br_new]
            if brand_new_prodct:
                for product in brand_new_prodct: product.fields = product_fields
                brand.fill('new', brand_new_prodct)

        # todo 填充动态
        # brand.fill('BrandTweets', list())

        # 填充banner
        if banner_show:
            bb_list = BrandBanner.query.filter(
                BrandBanner.PBid == brand.PBid, BrandBanner.isdelete == false()).order_by(
                BrandBanner.BBsort.asc(), BrandBanner.createtime.desc()).all()
            bbs = self._fill_bb(bb_list)
            if bbs:
                brand.fill('brandbanner', bbs)

    def _recommend_pb_product(self, pbid):
        return Products.query.filter(
            Items.isdelete == false(),
            ProductItems.isdelete == false(),
            Products.isdelete == false(),
            Items.ITid == self.itid_re_pr,
            ProductItems.ITid == Items.ITid,
            Products.PRid == ProductItems.PRid,
            Products.PRstatus == ProductStatus.usual.value,
            Products.PBid == pbid
        ).order_by(ProductItems.createtime.desc())

    def get_recommend_product(self):
        pbid = parameter_required({'pbid': '品牌已下架'})
        ProductBrand.query.filter(ProductBrand.PBid == pbid, ProductBrand.isdelete == false()).first_('品牌已下架')
        pb_list = self._recommend_pb_product(pbid).all_with_page()
        return Success(data=pb_list)

    def _get_brand_coupon(self, suid, user=None, coid_list=[]):
        brand_coupon = Coupon.query.filter(
            Items.isdelete == false(),
            CouponItem.isdelete == false(),
            Coupon.isdelete == false(),
            Items.ITid == self.itid_re_ca,
            CouponItem.ITid == Items.ITid,
            CouponItem.COid == Coupon.COid,
            Coupon.SUid == suid,
            Coupon.COid.notin_(coid_list)
        ).order_by(CouponItem.createtime.desc()).first()
        if not brand_coupon:
            return
        # 过滤已领优惠券
        if user:
            # user = get_current_user()
            couponuser = CouponUser.query.filter(
                CouponUser.USid == user.USid,
                CouponUser.COid == brand_coupon.COid,
                CouponUser.isdelete == false()
            ).first()
            if couponuser:
                coid_list.append(brand_coupon.COid)
                return self._get_brand_coupon(suid, user, coid_list)

        return brand_coupon

    @token_required
    def set_banner(self):
        data = parameter_required({'pbid': '品牌唯一值缺失'})
        pbid = data.get('pbid')
        if is_supplizer():

            supplizer = get_current_supplizer()
            ProductBrand.query.filter(
                ProductBrand.PBid == pbid, ProductBrand.SUid == supplizer.SUid).first_('只能修改自己的品牌')
        elif is_admin():
            ProductBrand.query.filter(
                ProductBrand.PBid == pbid).first_('品牌不存在')
        else:
            raise AuthorityError()
        bbid = data.get('bbid')
        bbcontent = data.get('bbcontent')
        if bbcontent:
            try:
                bbcontent = json.dumps(bbcontent)
            except Exception as e:
                current_app.logger.info('转置json 出错 bbcontent = {} e = {}'.format(bbcontent, e))
        bbsort = data.get('bbsort')
        if bbsort:
            bbsort = self._check_sort(bbsort, model=BrandBanner, filter_args=[BrandBanner.PBid == pbid], default=1)
        with db.auto_commit():
            if bbid:
                if data.get('delete'):
                    BrandBanner.query.filter(BrandBanner.BBid == bbid, BrandBanner.isdelete == false()).delete_(
                        synchronize_session=False)
                    return Success('删除成功')

                bb = BrandBanner.query.filter(BrandBanner.BBid == bbid, BrandBanner.isdelete == false()).first()
                if bb:
                    if bbsort:
                        bb.BBsort = bbsort
                    if bbcontent:
                        bb.BBcontent = bbcontent
                    return Success('更新成功', data=bbid)
            bbid = str(uuid.uuid1())
            if not bbcontent:
                raise ParamsError('轮播图图片路由缺失')
            bb = BrandBanner.create({
                'BBid': bbid,
                'PBid': pbid,
                'BBsort': bbsort or 1,
                'BBcontent': bbcontent
            })
            db.session.add(bb)

        return Success('添加成功', data=bbid)

    def _check_sort(self, sort, model=BrandBanner, filter_args=[], default=None):
        if not sort:
            return default
        try:
            sort = int(sort)
        except:
            current_app.logger.info('转置数字失败 sort = {}'.format(sort))
            return default

        if sort < 1:
            return 1

        bbcount = model.query.filter(model.isdelete == false(), *filter_args).count()
        if sort > bbcount:
            if bbcount >= 1:
                return bbcount
            else:
                return 1
        return sort

    def get_banner(self):
        pbid = parameter_required({'pbid': '品牌唯一值缺失'}).get('pbid')
        bb_list = BrandBanner.query.filter(BrandBanner.PBid == pbid, BrandBanner.isdelete == false()).order_by(
            BrandBanner.BBsort.asc(), BrandBanner.createtime.desc()).all()
        bbs = self._fill_bb(bb_list)
        return Success(data=bbs)

    def _fill_bb(self, bb_list):
        bbs = list()
        for bb in bb_list:
            bbcontent = bb.BBcontent
            try:
                bbcontent = json.loads(bbcontent)
            except:
                current_app.logger.info('转换json 失败 bbid = {}'.format(bb.BBid))
                continue
            bb.fill('bbcontent', bbcontent)
            bbs.append(bb)
        return bbs
Exemplo n.º 5
0
class CScene(object):
    def __init__(self):
        self.sproducts = SProducts()

    def list(self):
        """列出所有场景"""
        now = datetime.now()
        form = SceneListForm().valid_data()
        kw = form.kw.data
        query = ProductScene.query.filter(ProductScene.isdelete == False)
        if kw:
            query = query.filter(ProductScene.PSname.contains(kw))
        scenes = query.order_by(ProductScene.PSsort, ProductScene.createtime).all()
        res = list()
        for scene in scenes:
            if scene.PStimelimited:
                if scene.PSstarttime < now < scene.PSendtime:
                    countdown = scene.PSendtime - now
                    hours = str(countdown.days * 24 + (countdown.seconds // 3600))
                    minutes = str((countdown.seconds % 3600) // 60)
                    seconds = str((countdown.seconds % 3600) % 60)

                    scene.fill('countdown', "{}:{}:{}".format('0' + hours if len(hours) == 1 else hours,
                                                              '0' + minutes if len(minutes) == 1 else minutes,
                                                              '0' + seconds if len(seconds) == 1 else seconds))
                else:
                    if is_tourist() or common_user():
                        continue
            res.append(scene)
        return Success(data=res)

    @admin_required
    def create(self):
        """创建场景"""
        form = SceneCreateForm().valid_data()
        psendtime = form.psendtime.data
        with self.sproducts.auto_commit() as s:
            scene_dict = {
                'PSid': str(uuid.uuid1()),
                'PSpic': form.pspic.data,
                'PSname': form.psname.data,
                'PSsort': form.pssort.data,
                'PStimelimited': form.pstimelimited.data,
                'PSstarttime': form.psstarttime.data,
                'PSendtime': psendtime
            }
            product_scene_instance = ProductScene.create(scene_dict)
            s.add(product_scene_instance)

            # 每个场景下默认增加一个“大行星精选”标签
            default_scene_item = SceneItem.create({
                'SIid': str(uuid.uuid1()),
                'PSid': scene_dict.get('PSid'),
                'ITid': 'planet_featured'
            })
            s.add(default_scene_item)
            BASEADMIN().create_action(AdminActionS.insert.value, 'ProductScene', str(uuid.uuid1()))
        if form.pstimelimited.data:
            from planet.extensions.tasks import cancel_scene_association
            current_app.logger.info('限时场景结束时间 : {} '.format(psendtime))
            scene_task_id = cancel_scene_association.apply_async(args=(scene_dict['PSid'],),
                                                                 eta=psendtime - timedelta(hours=8), )

            current_app.logger.info("场景id{}  任务返回的task_id: {}".format(scene_dict['PSid'], scene_task_id))
            conn.set(scene_dict['PSid'], scene_task_id)

        return Success('创建成功', data={'psid': product_scene_instance.PSid})

    @admin_required
    def update(self):
        form = SceneUpdateForm().valid_data()
        psid, pspic, psname, pssort = form.psid.data, form.pspic.data, form.psname.data, form.pssort.data
        pstimelimited, psstarttime, psendtime = form.pstimelimited.data, form.psstarttime.data, form.psendtime.data
        isdelete = form.isdelete.data
        with db.auto_commit():
            pssort = self._check_sort(pssort)
            product_scene = ProductScene.query.filter(ProductScene.isdelete == False,
                                                      ProductScene.PSid == psid
                                                      ).first_('不存在的场景')
            if isdelete:
                SceneItem.query.filter_by(PSid=psid).delete_()
                product_scene.isdelete = True
                admin_action = AdminActions.create({
                    'ADid': request.user.id,
                    'AAaction': 2,
                    'AAmodel': ProductScene,
                    'AAdetail': request.detail,
                    'AAkey': psid
                })
                db.session.add(admin_action)
                conn.delete(psid)
            else:
                product_scene.update({
                    "PSpic": pspic,
                    "PSname": psname,
                    "PSsort": pssort,
                    "PStimelimited": pstimelimited,
                    "PSstarttime": psstarttime,
                    "PSendtime": psendtime,
                }, null='not')
                db.session.add(product_scene)
                BASEADMIN().create_action(AdminActionS.update.value, 'ProductScene', psid)
            if form.pstimelimited.data:

                from planet.extensions.tasks import cancel_scene_association, celery
                current_app.logger.info('更新限时场景结束时间为 : {} '.format(psendtime))
                # celery.control.revoke(task_id=psid, terminate=True, signal='SIGKILL')
                exist_task = conn.get(psid)
                if exist_task:
                    exist_task = str(exist_task, encoding='utf-8')
                    current_app.logger.info('场景已有任务id: {}'.format(exist_task))
                    celery.AsyncResult(exist_task).revoke()

                scene_task_id = cancel_scene_association.apply_async(args=(psid,),
                                                                     eta=psendtime - timedelta(hours=8), )

                conn.set(psid, scene_task_id)

        return Success('更新成功', {'psid': psid})

    def _check_sort(self, pssort):
        if not pssort:
            return 1
        pssort = int(pssort)
        if pssort < 1:
            return 1
        count_ps = ProductScene.query.filter_by_().count()
        if pssort > count_ps:
            return count_ps
        return pssort
Exemplo n.º 6
0
class CItems:
    def __init__(self):
        self.sproduct = SProducts()

    def list(self):
        """列出标签"""
        form = ItemListForm().valid_data()
        ittype = form.ittype.data
        psid = form.psid.data
        kw = form.kw.data
        recommend = form.recommend.data
        recommend = True if str(recommend) == '1' else None

        # 如果查询商品对应的标签, 则可以传场景的id
        items_query = Items.query.filter_(
            Items.isdelete == False,
            Items.ITtype == ittype,
            Items.ITrecommend == recommend,
            Items.ITauthority != ItemAuthrity.other.value,
            Items.ITposition != ItemPostion.other.value,
        )

        if psid:
            items_query = items_query.outerjoin(
                SceneItem, SceneItem.ITid == Items.ITid).filter_(
                    SceneItem.isdelete == False,
                    SceneItem.PSid == psid,
                )

            scene_items = [
                sit.ITid for sit in SceneItem.query.filter(
                    SceneItem.PSid == psid, SceneItem.isdelete == False,
                    ProductScene.isdelete == False).all()
            ]
            prscene_count = Products.query.outerjoin(
                ProductItems, ProductItems.PRid == Products.PRid).filter(
                    Products.isdelete == False, Products.PRfeatured == True,
                    Products.PRstatus == ProductStatus.usual.value,
                    ProductItems.isdelete == False,
                    ProductItems.ITid.in_(list(set(scene_items)))).count()
            if not prscene_count:
                items_query = items_query.filter(
                    Items.ITid !=
                    'planet_featured')  # 如果该场景下没有精选商品,不显示“大行星精选”标签

        if is_supplizer():

            time_limit_itids = [
                it.ITid for it in
                Items.query.join(SceneItem, SceneItem.ITid == Items.ITid).join(
                    ProductScene, ProductScene.PSid == SceneItem.PSid).filter(
                        SceneItem.isdelete == False, ProductScene.isdelete ==
                        False, Items.isdelete == False,
                        ProductScene.PStimelimited == True).all()
            ]
            items_query = items_query.filter(
                Items.ITauthority == ItemAuthrity.no_limit.value,
                Items.ITposition.in_(
                    [ItemPostion.scene.value, ItemPostion.news_bind.value]),
                Items.ITid.notin_(time_limit_itids))

        if kw:
            items_query = items_query.filter(Items.ITname.contains(kw))
        items_query = items_query.order_by(Items.ITposition.desc(),
                                           Items.ITsort.asc(),
                                           Items.createtime.desc())
        items = items_query.all()
        for item in items:
            item.fill('ITtype_zh', ItemType(item.ITtype).zh_value)
            if item.ITtype == ItemType.product.value:
                pr_scene = ProductScene.query.outerjoin(
                    SceneItem, SceneItem.PSid == ProductScene.PSid).filter_(
                        SceneItem.isdelete == False,
                        SceneItem.ITid == item.ITid,
                        ProductScene.isdelete == False).all()
                item.fill('prscene', pr_scene)
        return Success('获取成功', data=items)

    @admin_required
    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})

    @admin_required
    def update(self):
        """修改标签"""
        form = ItemUpdateForm().valid_data()
        psid = form.psid.data
        itid = form.itid.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'
        ] 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 == form.itname.data,
                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': form.itname.data,
                '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)

            # 标签场景标签表
            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)
                    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 = [] 为空时,删除所有该标签场景的关联
        return Success('修改成功', {'itid': itid})

    def _check_itsort(self, itsort, ittype):

        if itsort < 1:
            return 1
        count_item = Items.query.filter_by_(ITtype=ittype).count()
        if itsort > count_item:
            return count_item
        return itsort