def fix_evaluate_status_error(): """修改评价异常数据(已评价,未修改状态)""" current_app.logger.info("-----> 开始检测商品评价异常数据 <-----") with db.auto_commit(): order_evaluations = OrderEvaluation.query.filter_by_().all() count = 0 for oe in order_evaluations: om = OrderMain.query.filter( OrderMain.OMid == oe.OMid, OrderMain.OMfrom.in_( [OrderFrom.carts.value, OrderFrom.product_info.value])).first() if not om: om_info = OrderMain.query.filter( OrderMain.OMid == oe.OMid).first() current_app.logger.info( "--> 存在有评价,主单已删除或来自活动订单,OMid为{0}, OMfrom为{1} <--".format( str(oe.OMid), str(om_info.OMfrom))) continue omid = om.OMid omstatus = om.OMstatus if int(omstatus) == OrderMainStatus.wait_comment.value: current_app.logger.info( "--> 已存在评价的主单id为 {},未修改前的主单状态为{} <--".format( str(omid), str(omstatus))) current_app.logger.info("--> 开始更改状态 <--") upinfo = OrderMain.query.filter_by_(OMid=omid).update( {'OMstatus': OrderMainStatus.ready.value}) count += 1 if upinfo: current_app.logger.info("--> {}:更改状态成功 <--".format( str(omid))) else: current_app.logger.info("--> {}:更改失败 <--".format( str(omid))) current_app.logger.info( "--------------分割线----------------------") current_app.logger.info( "--------------分割线----------------------") else: current_app.logger.info("-----> 没有发现商品评价异常数据 <-----") current_app.logger.info("-----> 更新结束,共更改{}条数据 <-----".format( str(count)))
def create_category(self): """创建分类""" self._check_admin(request.user.id) data = parameter_required(( 'mcname', 'mctype', )) mctype = data.get('mctype', 0) mcsort = data.get('mcsort') mcparentid = data.get('mcparentid') with db.auto_commit(): if mctype == CategoryType.material.value: if not mcparentid: raise ParamsError('mcparentid 不能为空') parent_category = MaterialCategory.query.filter_by_( MCid=mcparentid).first_('上级分类不存在') if parent_category.MCid == 'knowledge_classroom': raise ParamsError('不允许在该层下创建分类') # 知识课堂下不允许创建二级分类 mcsort = self._check_sort(mctype, mcsort, mcparentid) category_dict = { 'MCid': str(uuid.uuid1()), 'MCname': data.get('mcname'), 'MCparentid': mcparentid, 'MClevel': parent_category.MClevel + 1, 'MCsort': mcsort, 'MCtype': mctype } if category_dict['MClevel'] > 3: raise ParamsError('超出分类最高层级') if mcparentid == 'hot_topic': # 热门话题有简介 和 图片 category_dict['MCpicture'] = data.get('mcpicture') category_dict['MCdesc'] = data.get('mcdesc') else: category_dict = { 'MCid': str(uuid.uuid1()), 'MCname': data.get('mcname'), 'MClevel': 1, 'MCsort': mcsort, 'MCtype': mctype } category_instance = MaterialCategory.create(category_dict) db.session.add(category_instance) return Success('创建成功', data=dict(MCid=category_dict['MCid']))
def start(self): """用户发起拼团""" # data = parameter_required(('prid', )) user = get_current_user() now = datetime.datetime.now() # now = datetime.datetime.now() data = parameter_required(('gbid', )) gb = GroupBuying.query.filter( GroupBuying.GBstarttime <= now, GroupBuying.GBendtime >= now, GroupBuying.GBid == data.get('gbid'), GroupBuying.isdelete == False).first_('活动已结束') self._check_bgtimes(data.get('gbid'), user.USid, gb.GBtimes) with db.auto_commit(): gi = GroupbuyingItem.create({ 'GIid': str(uuid.uuid1()), 'GBid': gb.GBid, 'GIstatus': GroupbuyingItemStatus.underway.value }) gu = GroupbuyingUser.create({ 'GUid': str(uuid.uuid1()), 'GIid': gi.GIid, 'USid': user.USid, 'UShead': user.USheader, 'USname': user.USname, 'GUstatus': GroupbuyingUserStatus.waitpay.value }) # TODO 异步任务,24h 修改超时状态 db.session.add(gi) db.session.add(gu) return Success('发起拼团成功')
def create_comment(self): user = self._check_user(request.user.id) data = parameter_required(( 'mtid', 'mcocontent', )) mtid = data.get('mtid') Material.query.filter_by_(MTid=mtid).first_('评论文章不存在或已删除') with db.auto_commit(): mco_dict = { 'MCOid': str(uuid.uuid1()), 'MTid': mtid, 'MCOcontent': data.get('mcocontent'), 'MCOstatus': MaterialCommentStatus.auditing.value, 'MCOauthor': user.USid, 'MCOauthorname': user.USname, 'MCOauthoravatar': user.USheader } mco_instance = MaterialComment.create(mco_dict) db.session.add(mco_instance) return Success('评论成功,正在审核中', data=dict(mcoid=mco_dict['MCOid']))
def auto_agree_task(avid): current_app.logger.info('avid is {}'.format(avid)) from bechi.control.CApproval import CApproval cp = CApproval() with db.auto_commit(): approval = Approval.query.filter( Approval.isdelete == False, Approval.AVstatus == ApplyStatus.wait_check.value, Approval.AVid == avid).first() if approval: current_app.logger.info('5分钟自动同意') current_app.logger.info(dict(approval)) else: current_app.logger.info('该审批已提前处理') try: cp.agree_action(approval) approval.AVstatus = ApplyStatus.agree.value except NotFound: current_app.logger.info('审批流状态有误') # 如果不存在的商品, 需要将审批流失效 approval.AVstatus = ApplyStatus.cancle.value db.session.add(approval)
def fetch_share_deal(): """获取昨日的收盘""" with db.auto_commit(): s_list = [] share_stock = ShareStock() yesterday_result = share_stock.new_result() yesterday = date.today() - timedelta(days=1) # 昨日结果 db_yesterday = CorrectNum.query.filter( cast(CorrectNum.CNdate, Date) == yesterday).first() if not db_yesterday: # 昨日 current_app.logger.info('写入昨日数据') correct_instance = CorrectNum.create({ 'CNid': str(uuid.uuid4()), 'CNnum': yesterday_result, 'CNdate': yesterday }) s_list.append(correct_instance) # 判断是否有猜对的 guess_nums = GuessNum.query.filter_by({ 'GNnum': yesterday_result, 'GNdate': db_yesterday }).all() for guess_num in guess_nums: exists_in_flow = GuessAwardFlow.query.filter_by_({ 'GNid': guess_num.GNid }).first() if not exists_in_flow: guess_award_flow_instance = GuessAwardFlow.create({ 'GAFid': str(uuid.uuid4()), 'GNid': guess_num.GNid, }) s_list.append(guess_award_flow_instance) if s_list: db.session.add_all(s_list)
def get(self): """获取主单物流""" data = parameter_required(('omid', )) omid = data.get('omid') with db.auto_commit(): order_logistics = OrderLogistics.query.filter_by_({ 'OMid': omid }).first_('未获得物流信息') time_now = datetime.now() if (not order_logistics.OLdata or (time_now - order_logistics.updatetime).total_seconds() > 6 * 3600)\ and order_logistics.OLsignStatus != 3: # 没有data信息或超过6小时 并且状态不是已签收 order_logistics = self._get_logistics(order_logistics) logistics_company = LogisticsCompnay.query.filter_by_({ 'LCcode': order_logistics.OLcompany }).first() order_logistics.fill( 'OLsignStatus_en', LogisticsSignStatus(order_logistics.OLsignStatus).name) order_logistics.fill('logistics_company', logistics_company) order_logistics.OLdata = json.loads(order_logistics.OLdata) order_logistics.OLlastresult = json.loads(order_logistics.OLlastresult) return Success(data=order_logistics)
def create(self): data = parameter_required(('starttime', 'endtime', 'gbnum', 'prid', 'gpprice', 'skus', 'gbtimes')) starttime, endtime = self._check_time(data.get('starttime'), data.get('endtime')) if not self._check_pint(data.get('gbnum')): raise ParamsError('gbnum 格式错误') if not self._check_pint(data.get('gbtimes')): raise ParamsError('gbtimes 格式错误') product = Products.query.filter( Products.isdelete == False, Products.PRid == data.get('prid'), Products.PRstatus == ProductStatus.usual.value).first_('商品未上架') # todo 校验商品不在同一时间的其他活动里 self._check_product(data.get('prid'), starttime, endtime) with db.auto_commit(): instance_list = [] gb_instance = GroupBuying.create({ 'GBid': str(uuid.uuid1()), 'GBstarttime': starttime, 'GBendtime': endtime, 'GBnum': data.get('gbnum'), 'GBtimes': data.get('gbtimes'), 'GBstatus': GroupBuyingStatus.wait_check.value }) instance_list.append(gb_instance) instance_list.extend( self._add_groupbuying_product(data, product, gb_instance.GBid)) db.session.add_all(instance_list) return Success('申请成功')
def update_product(self): """更新商品""" data = parameter_required(('prid', )) # product_from = ProductFrom.platform.value prid = data.get('prid') pbid = data.get('pbid') # 品牌id pcid = data.get('pcid') # 分类id images = data.get('images') skus = data.get('skus') prdescription = data.get('prdescription') if data.get('prsalesvaluefake'): # if not re.match(r'^\d+$', str(data.get('prsalesvaluefake'))): if not self._check_pint(data.get('prsalesvaluefake')): raise ParamsError('虚拟销量数据异常') else: data['prsalesvaluefake'] = 0 with db.auto_commit(): session_list = [] # 商品 prattribute = data.get('prattribute') product = Products.query.filter_by_({'PRid': prid}).first_('商品不存在') prmarks = data.get('prmarks') # 备注 if prmarks: try: prmarks = json.dumps(prmarks) if not isinstance(prmarks, dict): raise TypeError except Exception as e: pass if pcid: product_category = ProductCategory.query.filter( ProductCategory.PCid == pcid, ProductCategory.isdelete == False).first_('指定目录不存在') # sku, 有skuid为修改, 无skuid为新增 if skus: new_sku = [] sku_ids = [] # 此时传入的skuid prstock = 0 for index, sku in enumerate(skus): skuattritedetail = sku.get('skuattritedetail') if not isinstance( skuattritedetail, list) or len(skuattritedetail) != len(prattribute): raise ParamsError('skuattritedetail与prattribute不符') skuprice = int(sku.get('skuprice', 0)) skustock = int(sku.get('skustock', 0)) assert skuprice > 0 and skustock >= 0, 'sku价格或库存错误' # 更新或添加删除 if 'skuid' in sku: skuid = sku.get('skuid') sn = sku.get('skusn') # self._check_sn(sn=sn, skuid=skuid) sku_ids.append(skuid) sku_instance = ProductSku.query.filter_by({ 'SKUid': skuid }).first_('sku不存在') sku_instance.update({ 'SKUpic': sku.get('skupic'), 'SKUattriteDetail': json.dumps(skuattritedetail), 'SKUstock': int(skustock), 'SKUprice': sku.get('skuprice'), 'SKUsn': sn }) else: sku_instance = ProductSku.create({ 'SKUid': str(uuid.uuid1()), 'PRid': prid, 'SKUpic': sku.get('skupic'), 'SKUprice': round(skuprice, 2), 'SKUstock': int(skustock), 'SKUattriteDetail': json.dumps(skuattritedetail), 'SKUsn': sku.get('skusn'), }) new_sku.append(sku_instance) session_list.append(sku_instance) prstock += sku_instance.SKUstock # 剩下的就是删除 old_sku = ProductSku.query.filter( ProductSku.isdelete == False, ProductSku.PRid == prid, ProductSku.SKUid.notin_(sku_ids)).delete_( synchronize_session=False) current_app.logger.info( '删除了{}个不需要的sku, 更新了{}个sku, 添加了{}个新sku '.format( old_sku, len(sku_ids), len(new_sku))) prdesc = data.get('prdesc') product_dict = { 'PRtitle': data.get('prtitle'), 'PRprice': data.get('prprice'), 'PRlinePrice': data.get('prlineprice'), 'PRfreight': data.get('prfreight'), 'PRstocks': prstock, 'PRmainpic': data.get('prmainpic'), 'PCid': pcid, 'PBid': pbid, 'PRdesc': prdesc, 'PRattribute': json.dumps(prattribute), 'PRremarks': prmarks, 'PRdescription': prdescription, 'PRsalesValueFake': int(data.get('prsalesvaluefake')), 'PRstatus': ProductStatus.auditing.value, # 'PRfeatured': prfeatured, } product.update(product_dict) if product.PRstocks == 0: product.PRstatus = ProductStatus.sell_out.value session_list.append(product) # sku value pskuvalue = data.get('pskuvalue') if pskuvalue: if not isinstance(pskuvalue, list) or len(pskuvalue) != len( json.loads(product.PRattribute)): raise ParamsError('pskuvalue与prattribute不符') # todo skudetail校验 # sku_value表 exists_sku_value = ProductSkuValue.query.filter_by_({ 'PRid': prid }).first() if exists_sku_value: exists_sku_value.update( {'PSKUvalue': json.dumps(pskuvalue)}) session_list.append(exists_sku_value) else: sku_value_instance = ProductSkuValue.create({ 'PSKUid': str(uuid.uuid1()), 'PRid': prid, 'PSKUvalue': json.dumps(pskuvalue) }) session_list.append(sku_value_instance) else: sku_value_instance = ProductSkuValue.query.filter_by_({ 'PRid': prid, }).first() if sku_value_instance: # 默认如果不传就删除原来的, 防止value混乱, todo sku_value_instance.isdelete = True session_list.append(sku_value_instance) # images, 有piid为修改, 无piid为新增 if images: piids = [] new_piids = [] for image in images: if 'piid' in image: # 修改 piid = image.get('piid') piids.append(piid) image_instance = ProductImage.query.filter_by({ 'PIid': piid }).first_('商品图片信息不存在') else: # 新增 piid = str(uuid.uuid1()) image_instance = ProductImage() new_piids.append(piid) image_dict = { 'PIid': piid, 'PRid': prid, 'PIpic': image.get('pipic'), 'PIsort': image.get('pisort'), 'isdelete': image.get('isdelete') } image_instance.update(image_dict) session_list.append(image_instance) # 删除其他 delete_images = ProductImage.query.filter( ProductImage.isdelete == False, ProductImage.PIid.notin_(piids), ProductImage.PRid == prid, ).delete_(synchronize_session=False) current_app.logger.info('删除了{}个图片, 修改了{}个, 新增了{}个 '.format( delete_images, len(piids), len(new_piids))) db.session.add_all(session_list) return Success('更新成功')
def add_product(self): # if is_admin(): product_from = ProductFrom.platform.value # else: # raise AuthorityError() data = parameter_required(('pcid', 'prtitle', 'prprice', 'prattribute', 'prmainpic', 'prdesc', 'images', 'skus')) pbid = data.get('pbid') # 品牌id pcid = data.get('pcid') # 3级分类id images = data.get('images') skus = data.get('skus') # prfeatured = data.get('prfeatured', False) prdescription = data.get('prdescription') # 简要描述 # PCtype 是表示分类等级, 该系统只有两级 product_category = ProductCategory.query.filter( ProductCategory.PCid == pcid, ProductCategory.isdelete == False).first_('指定目录不存在') if data.get('prsalesvaluefake'): # if not re.match(r'^\d+$', str(data.get('prsalesvaluefake'))): if not self._check_pint(data.get('prsalesvaluefake')): raise ParamsError('虚拟销量数据异常') else: data['prsalesvaluefake'] = 0 prstocks = 0 with db.auto_commit() as s: session_list = [] # 商品 prattribute = data.get('prattribute') prid = str(uuid.uuid1()) prmarks = data.get('prmarks') # 备注 if prmarks: try: prmarks = json.dumps(prmarks) if not isinstance(prmarks, dict): raise TypeError except Exception: pass prdesc = data.get('prdesc') if prdesc: if not isinstance(prdesc, list): raise ParamsError('prdesc 格式不正确') # sku sku_detail_list = [] # 一个临时的列表, 使用记录的sku_detail来检测sku_value是否符合规范 for index, sku in enumerate(skus): sn = sku.get('skusn') # self._check_sn(sn=sn) skuattritedetail = sku.get('skuattritedetail') if not isinstance( skuattritedetail, list) or len(skuattritedetail) != len(prattribute): raise ParamsError('skuattritedetail与prattribute不符') sku_detail_list.append(skuattritedetail) skuprice = float(sku.get('skuprice')) skustock = int(sku.get('skustock')) assert skuprice > 0 and skustock >= 0, 'sku价格或库存错误' prstocks += int(skustock) sku_dict = { 'SKUid': str(uuid.uuid1()), 'PRid': prid, 'SKUpic': sku.get('skupic'), 'SKUprice': round(skuprice, 2), 'SKUstock': int(skustock), 'SKUattriteDetail': json.dumps(skuattritedetail), 'SKUsn': sn } sku_instance = ProductSku.create(sku_dict) session_list.append(sku_instance) # 商品 product_dict = { 'PRid': prid, 'PRtitle': data.get('prtitle'), 'PRprice': data.get('prprice'), 'PRlinePrice': data.get('prlineprice'), 'PRfreight': data.get('prfreight'), 'PRstocks': prstocks, 'PRmainpic': data.get('prmainpic'), 'PCid': pcid, 'PBid': pbid, 'PRdesc': prdesc, 'PRattribute': json.dumps(prattribute), 'PRremarks': prmarks, 'PRfrom': product_from, 'CreaterId': request.user.id, 'PRsalesValueFake': int(data.get('prsalesvaluefake')), 'PRdescription': prdescription, # 描述 # 'PRfeatured': prfeatured, # 是否为精选 } # 库存为0 的话直接售罄 if prstocks == 0: product_dict['PRstatus'] = ProductStatus.sell_out.value product_instance = Products.create(product_dict) session_list.append(product_instance) # sku value pskuvalue = data.get('pskuvalue') if pskuvalue: if not isinstance(pskuvalue, list) or len(pskuvalue) != len(prattribute): raise ParamsError('pskuvalue与prattribute不符') sku_reverce = [] for index in range(len(prattribute)): value = list( set([ attribute[index] for attribute in sku_detail_list ])) sku_reverce.append(value) # 对应位置的列表元素应该相同 if set(value) != set(pskuvalue[index]): raise ParamsError('请核对pskuvalue') # sku_value表 sku_value_instance = ProductSkuValue.create({ 'PSKUid': str(uuid.uuid1()), 'PRid': prid, 'PSKUvalue': json.dumps(pskuvalue) }) session_list.append(sku_value_instance) # images for image in images: image_dict = { 'PIid': str(uuid.uuid1()), 'PRid': prid, 'PIpic': image.get('pipic'), 'PIsort': image.get('pisort'), } image_instance = ProductImage.create(image_dict) session_list.append(image_instance) s.add_all(session_list) return Success('添加成功', {'prid': prid})
def get_produt_list(self): data = parameter_required() try: order, desc_asc = data.get('order_type', 'time|desc').split('|') # 排序方式 order_enum = { 'time': Products.updatetime, 'sale_value': Products.PRsalesValue, 'price': Products.PRprice, } assert order in order_enum and desc_asc in ['desc', 'asc' ], 'order_type 参数错误' except Exception as e: raise e kw = data.get('kw', '').split() or [''] # 关键词 # pbid = data.get('pbid') # 品牌 # 分类参数 pcid = data.get('pcid') # 分类id pcid = pcid.split('|') if pcid else [] pcids = self._sub_category_id(pcid) pcids = list(set(pcids)) skusn = data.get('skusn') prstatus = data.get('prstatus') if not is_admin(): prstatus = prstatus or 'usual' # 商品状态 if prstatus: prstatus = getattr(ProductStatus, prstatus).value product_order = order_enum.get(order) if desc_asc == 'desc': by_order = product_order.desc() else: by_order = product_order.asc() # filter_args = [ and_(*[Products.PRtitle.contains(x) for x in kw]), Products.PCid.in_(pcids), Products.PRstatus == prstatus, ] query = Products.query.filter(Products.isdelete == False) if skusn: query = query.outerjoin( ProductSku, ProductSku.PRid == Products.PRid).filter( ProductSku.isdelete == False, ProductSku.SKUsn.ilike("%{}%".format(skusn))) products = query.filter_( *filter_args).order_by(by_order).all_with_page() # 填充 for product in products: product.fill('prstatus_en', ProductStatus(product.PRstatus).name) product.fill('prstatus_zh', ProductStatus(product.PRstatus).zh_value) # 品牌 # brand = self.sproduct.get_product_brand_one({'PBid': product.PBid}) # brand = ProductBrand.query.filter(ProductBrand.PBid == product.PBid).first() or {} # product.fill('brand', brand) product.PRattribute = json.loads(product.PRattribute) product.PRremarks = json.loads( getattr(product, 'PRremarks') or '{}') if is_admin(): # 分类 category = self._up_category(product.PCid) product.fill('category', category) # sku skus = ProductSku.query.filter( ProductSku.isdelete == False, ProductSku.PRid == product.PRid).all() for sku in skus: sku.SKUattriteDetail = json.loads(sku.SKUattriteDetail) product.fill('skus', skus) # product.PRdesc = json.loads(getattr(product, 'PRdesc') or '[]') # 搜索记录表 if kw != [''] and not is_tourist(): with db.auto_commit(): db.session.expunge_all() instance = UserSearchHistory.create({ 'USHid': str(uuid.uuid1()), 'USid': request.user.id, 'USHname': ' '.join(kw) }) current_app.logger.info(dict(instance)) db.session.add(instance) return Success(data=products)
def make_items(): with db.auto_commit(): s_list = [] # index_hot_items = Items.create({ # 人气热卖标签 # 'ITid': 'index_hot', # id为'index' # 'ITname': '人气热卖', # 'ITdesc': '这是首页的人气热卖', # 'ITtype': ItemType.product.value, # 'ITauthority': ItemAuthrity.no_limit.value, # 'ITposition': ItemPostion.index.value # }) # s_list.append(index_hot_items) # # index_brands_items = Items.create({ # 'ITid': 'index_brand', # 'ITname': '品牌推荐', # 'ITdesc': '这是首页才会出现的品牌推荐', # 'ITtype': ItemType.brand.value, # 'ITposition': ItemPostion.index.value # }) # s_list.append(index_brands_items) # index_brands_product_items = Items.create({ # 'ITid': 'index_brand_product', # 'ITname': '品牌推荐商品', # 'ITdesc': '这是首页才会出现的品牌商品', # 'ITposition': ItemPostion.index.value # }) # s_list.append(index_brands_product_items) # # index_recommend_product_for_you_items = Items.create({ # 'ITid': 'index_recommend_product_for_you', # 'ITname': '首页为您推荐', # 'ITdesc': '首页的为您推荐的商品', # 'ITposition': ItemPostion.index.value # }) # s_list.append(index_recommend_product_for_you_items) material_category = MaterialCategory.create({ 'MCid': 'case_community', 'MCname': '案例社区', 'MClevel': 1, 'MCsort': -3, 'MCtype': CategoryType.material.value, }) s_list.append(material_category) knowledge_classroom = MaterialCategory.create({ 'MCid': 'knowledge_classroom', 'MCname': '知识课堂', 'MClevel': 1, 'MCsort': -2, 'MCtype': CategoryType.material.value, }) s_list.append(knowledge_classroom) disease_treatment = MaterialCategory.create({ 'MCid': 'disease_treatment', 'MCname': '疾病治疗', 'MCparentid': 'knowledge_classroom', 'MClevel': 2, 'MCsort': -2, 'MCtype': CategoryType.material.value, }) s_list.append(disease_treatment) health_encyclopedia = MaterialCategory.create({ 'MCid': 'health_encyclopedia', 'MCname': '健康百科', 'MCparentid': 'knowledge_classroom', 'MClevel': 2, 'MCsort': -1, 'MCtype': CategoryType.material.value, }) s_list.append(health_encyclopedia) hot_topic = MaterialCategory.create({ 'MCid': 'hot_topic', 'MCname': '热门话题', 'MClevel': 1, 'MCsort': -1, 'MCtype': CategoryType.material.value, }) s_list.append(hot_topic) db.session.add_all(s_list)
def pay(self): """订单发起支付""" data = parameter_required(('omid', )) omid = data.get('omid') usid = request.user.id try: omclient = int(data.get('omclient', Client.wechat.value)) # 客户端(app或者微信) Client(omclient) opaytype = int(data.get('opaytype', PayType.wechat_pay.value)) # 付款方式 PayType(opaytype) except ValueError as e: raise e except Exception as e: raise ParamsError('客户端或支付方式类型错误') from bechi.control.CUser import CUser cuser = CUser() with db.auto_commit(): opayno = self.wx_pay.nonce_str order_main = OrderMain.query.filter_by_({ 'OMid': omid, 'USid': usid, 'OMstatus': OrderMainStatus.wait_pay.value }).first_('不存在的订单') # 原支付流水删除 OrderPay.query.filter_by({'OPayno': order_main.OPayno}).delete_() # 更改订单支付编号 order_main.OPayno = opayno # 判断订单是否是开店大礼包 # 是否是开店大礼包 if order_main.OMlogisticType == OMlogisticTypeEnum.online.value: cuser = CUser() cuser._check_gift_order('重复购买开店大礼包') db.session.add(order_main) # 新建支付流水 order_pay_instance = OrderPay.create({ 'OPayid': str(uuid.uuid1()), 'OPayno': opayno, 'OPayType': opaytype, 'OPayMount': order_main.OMtrueMount }) # 付款时候的body信息 order_parts = OrderPart.query.filter_by_({'OMid': omid}).all() body = ''.join([getattr(x, 'PRtitle', '') for x in order_parts]) db.session.add(order_pay_instance) user = User.query.filter(User.USid == order_main.USid).first() pay_args = self._pay_detail(omclient, opaytype, opayno, float(order_main.OMtrueMount), body, openid=user.USopenid1 or user.USopenid2) response = { 'pay_type': PayType(opaytype).name, 'opaytype': opaytype, 'args': pay_args } return Success('生成付款参数成功', response)
def auto_evaluate(): """超时自动评价订单""" cfs = ConfigSettings() limit_time = cfs.get_item('order_auto', 'auto_evaluate_day') with db.auto_commit(): s_list = list() current_app.logger.info( ">>>>>> 开始检测超过{0}天未评价的商品订单 <<<<<<".format(limit_time)) from bechi.control.COrder import COrder corder = COrder() count = 0 order_mains = OrderMain.query.filter( OrderMain.OMstatus == OrderMainStatus.wait_comment.value, OrderMain.OMfrom.in_([ OrderFrom.carts.value, OrderFrom.product_info.value ]), OrderMain.createtime <= datetime.now() - timedelta(days=int(limit_time))).all() # 所有超过30天待评价的商品订单 if not order_mains: current_app.logger.info( ">>>>>> 没有超过{0}天未评价的商品订单 <<<<<<".format(limit_time)) else: for order_main in order_mains: order_parts = OrderPart.query.filter_by_( OMid=order_main.OMid).all() # 主单下所有副单 for order_part in order_parts: if order_part.OPisinORA is True: continue exist_evaluation = OrderEvaluation.query.filter_by_( OPid=order_part.OPid).first() if exist_evaluation: current_app.logger.info( ">>>>> ERROR, 该副单已存在评价, OPid : {}, OMid : {}". format(order_part.OPid, order_part.OMid)) continue user = User.query.filter_by(USid=order_main.USid).first() if order_part.OPisinORA: continue # user_commision = UserCommission.query.filter( # UserCommission.isdelete == False, # UserCommission.OPid == order_part.OPid # ).update({ # 'UCstatus': UserCommissionStatus.in_account.value # }) corder._commsion_into_count(order_part) # 佣金到账 corder._tosalesvolume(order_main.OMtrueMount, user.USid) # 销售额统计 # current_app.logger.info('佣金到账数量 {}'.format(user_commision)) if user: usname, usheader = user.USname, user.USheader else: usname, usheader = '神秘的客官', '' evaluation_dict = { 'OEid': str(uuid.uuid1()), 'USid': order_main.USid, 'USname': usname, 'USheader': usheader, 'OPid': order_part.OPid, 'OMid': order_main.OMid, 'PRid': order_part.PRid, 'SKUattriteDetail': order_part.SKUattriteDetail, 'OEtext': '此用户没有填写评价。', 'OEscore': 5, } evaluation_instance = OrderEvaluation.create( evaluation_dict) s_list.append(evaluation_instance) count += 1 current_app.logger.info( ">>>>>> 评价第{0}条,OPid :{1} <<<<<<".format( str(count), str(order_part.OPid))) # 佣金到账 # 商品总体评分变化 try: product_info = Products.query.filter_by_( PRid=order_part.PRid).first() average_score = round( (float(product_info.PRaverageScore) + 10) / 2) Products.query.filter_by_(PRid=order_part.PRid).update( {'PRaverageScore': average_score}) except Exception as e: current_app.logger.info( "更改商品评分失败, 商品可能已被删除;Update Product Score ERROR :{}" .format(e)) # 更改主单待评价状态为已完成 change_status = OrderMain.query.filter_by_( OMid=order_main.OMid).update( {'OMstatus': OrderMainStatus.ready.value}) if change_status: current_app.logger.info( ">>>>>> 主单状态更改成功 OMid : {} <<<<<<".format( str(order_main.OMid))) else: current_app.logger.info( ">>>>>> 主单状态更改失败 OMid : {} <<<<<<".format( str(order_main.OMid))) if s_list: db.session.add_all(s_list) current_app.logger.info( ">>>>>> 自动评价任务结束,共更改{}条数据 <<<<<<".format(count))
def post_dietitian(self): """创建营养师""" data = parameter_required(('mcids', 'dtname', 'dtphone', 'dtavatar', 'dtqrcode', 'dtintroduction')) dtphone = data.get('dtphone') dtid = data.get('dtid') mcids = data.get('mcids') if not re.match('^1[345789][0-9]{9}$', str(dtphone)): raise ParamsError('请输入正确的手机号码') with db.auto_commit(): session_list = list() dietitian_dict = { 'DTname': data.get('dtname'), 'DTphone': data.get('dtphone'), 'DTavatar': data.get('dtavatar'), 'DTqrcode': data.get('dtqrcode'), 'DTintroduction': data.get('dtintroduction'), 'DTisrecommend': data.get('dtisrecommend', False) } if dtid: dietitian = Dietitian.query.filter_by_( DTid=dtid).first_('要修改的营养师资料不存在') if data.get('isdelete'): dietitian.update({'isdelete': True}) DietitianCategoryRelated.query.filter( DietitianCategoryRelated.DTid == dietitian.DTid, DietitianCategoryRelated.isdelete == False).delete_() session_list.append(dietitian) else: dietitian.update(dietitian_dict) session_list.append(dietitian) ids = list() for mcid in mcids: ids.append(mcid) mc = MaterialCategory.query.filter_by_( MCid=mcid, MCtype=CategoryType.dietitian.value).first() if not mc: session_list.append( DietitianCategoryRelated.create({ 'DCRid': str(uuid.uuid1()), 'DTid': dietitian_dict['DTid'], 'MCid': mcid })) DietitianCategoryRelated.query.filter( DietitianCategoryRelated.DTid == dietitian.DTid, DietitianCategoryRelated.isdelete == False, DietitianCategoryRelated.MCid.notin_(ids)).delete_() else: dietitian_dict['DTid'] = str(uuid.uuid1()) dietitian = Dietitian.create(dietitian_dict) session_list.append(dietitian) for mcid in mcids: MaterialCategory.query.filter_by_( MCid=mcid, MCtype=CategoryType.dietitian.value).first_('分类不存在') session_list.append( DietitianCategoryRelated.create({ 'DCRid': str(uuid.uuid1()), 'DTid': dietitian_dict['DTid'], 'MCid': mcid })) db.session.add_all(session_list) return Success('修改成功')
def post_material(self): """创建/更新素材""" admin = self._check_admin(request.user.id) data = parameter_required(('mttitle', 'mtcontent', 'mcids')) mttitle, mtcontent, mtpicture, mtvideo = (data.get('mttitle'), data.get('mtcontent'), data.get('mtpicture'), data.get('mtvideo')) mtfakeviews, mtfakefavorite = data.get('mtfakeviews', 0), data.get( 'mtfakefavorite', 0) mtfakeforward = data.get('mtfakeforward', 0) mtid = data.get('mtid') mcids = data.get('mcids') or [] for rex_str in [mtfakeviews, mtfakefavorite, mtfakeforward]: if not re.match(r'^[0-9]+$', str(rex_str)): raise ParamsError('虚拟量只能输入数字') if mtpicture and isinstance(mtpicture, list): mtpicture = json.dump(mtpicture) if mtvideo and isinstance(mtvideo, list): mtvideo = json.dump(mtvideo) with db.auto_commit(): material_dict = { 'MTauthor': admin.ADid, 'MTauthorname': admin.ADname, 'MTauthoravatar': admin.ADheader, 'MTtitle': mttitle, 'MTcontent': mtcontent, 'MTtext': data.get('mttext'), 'MTpicture': mtpicture, 'MTvideo': mtvideo, 'MTfakeviews': mtfakeviews, 'MTfakefavorite': mtfakefavorite, 'MTfakeforward': mtfakeforward, 'MTisrecommend': data.get('mtisrecommend'), 'MTsort': data.get('mtsort') } if mtid: material_instance = Material.query.filter_by_( MTid=mtid).first_('要修改的文章不存在') if data.get('isdelete'): material_instance.update({'isdelete': True}) MaterialCategoryRelated.query.filter_by( MTid=mtid, isdelete=False).delete_() # 删除分类关联 MaterialFavorite.query.filter_by( MTid=mtid, isdelete=False).delete_() # 删除点赞 MaterialComment.query.filter_by( MTid=mtid, isdelete=False).delete_() # 删除评论 else: material_instance.update(material_dict) ids = list() for mcid in mcids: ids.append(mcid) mcr = MaterialCategoryRelated.query.filter_by( MCid=mcid, MTid=mtid, isdelete=False).first() if not mcr: db.session.add( MaterialCategoryRelated.create({ 'MCRid': str(uuid.uuid1()), 'MTid': mtid, 'MCid': mcid })) MaterialCategoryRelated.query.filter( MaterialCategoryRelated.MCid.notin_(ids), MaterialCategoryRelated.isdelete == False).delete_() else: material_dict['MTid'] = str(uuid.uuid1()) material_instance = Material.create(material_dict) for mcid in mcids: db.session.add( MaterialCategoryRelated.create({ 'MCRid': str(uuid.uuid1()), 'MTid': mtid, 'MCid': mcid })) db.session.add(material_instance) return Success('修改成功', data=dict(MTid=mtid or material_dict['MTid']))