def upload_delivery_file(self): """ 订单批量发货,文件上传入口 :return: """ if is_admin(): Admin.query.filter_by(ADid=request.user.id, ADstatus=AdminStatus.normal.value, isdelete=False).first_('管理员账号错误') elif is_supplizer(): Supplizer.query.filter_by(SUid=request.user.id, SUstatus=UserStatus.usual.value, isdelete=False).first_('供应商账号状态错误') else: raise TokenError('未登录') file = request.files.get('file') if not file: raise ParamsError('未上传文件') current_app.logger.info('Start Add Delivery Template {}'.format( datetime.now())) folder = 'xls' # 接收数据保存到服务器 file_path = self._save_excel(file, folder) # 进行订单发货 nrows = self._order_delivery(file_path) if is_admin(): with db.auto_commit(): BASEADMIN().create_action(AdminActionS.insert.value, 'file', file_path) current_app.logger.info('End Add Delivery Template {}'.format( datetime.now())) return Success('批量发货成功, 共发货 {} 个订单'.format(nrows - 1))
def del_news(self): """删除资讯""" if is_tourist(): raise TokenError() elif is_admin(): usid = request.user.id admin = self._check_admin(usid) current_app.logger.info('Admin {0} deleted a news'.format( admin.ADname)) elif is_supplizer(): usid = request.user.id sup = self._check_supplizer(usid) current_app.logger.info('Supplizer {0} deleted a news'.format( sup.SUname)) else: usid = request.user.id user = self.snews.get_user_by_id(usid) current_app.logger.info('User {0} deleted a news'.format( user.USname)) data = parameter_required(('neid', )) neids = data.get('neid') with db.auto_commit(): for neid in neids: news = News.query.filter_by_(NEid=neid).first_('未找到该资讯或已被删除') if is_admin(): if news.NEstatus != NewsStatus.refuse.value: raise StatusError('只能删除已下架状态的资讯') else: if news.USid != usid: raise StatusError('只能删除自己发布的资讯') News.query.filter_by(NEid=neid, isdelete=False).delete_() NewsTag.query.filter_by(NEid=neid).delete_() # 删除标签关联 NewsComment.query.filter_by(NEid=neid).delete_() # 删除评论 NewsFavorite.query.filter_by(NEid=neid).delete_() # 删除点赞 NewsTrample.query.filter_by(NEid=neid).delete_() # 删除点踩 # 如果在审核中,同时取消在进行的审批流 try: if news.NEstatus == NewsStatus.auditing.value: approval_info = Approval.query.filter_by_( AVcontent=neid, AVstartid=news.USid, AVstatus=ApplyStatus.wait_check.value).first() approval_info.update( {'AVstatus': ApplyStatus.cancle.value}) db.session.add(approval_info) except Exception as e: current_app.logger.error('删除圈子相关审批流时出错: {}'.format(e)) return Success('删除成功', {'neid': neids})
def add_toilet(self): """添加厕所""" if common_user(): creator = User.query.filter_by_( USid=getattr(request, 'user').id).first_('请重新登录') creator_id = creator.USid creator_type = ApplyFrom.user.value elif is_admin(): creator = Admin.query.filter_by_( ADid=getattr(request, 'user').id).first_('请重新登录') creator_id = creator.ADid creator_type = ApplyFrom.platform.value else: raise TokenError('请重新登录') data = parameter_required({ 'latitude': '纬度', 'longitude': '经度', 'toimage': '图片' }) latitude, longitude = data.get('latitude'), data.get('longitude') latitude, longitude = self.cplay.check_lat_and_long( latitude, longitude) if common_user() and latitude and longitude: self.BaseController.get_user_location(latitude, longitude, creator_id) exist = Toilet.query.filter(Toilet.isdelete == false(), Toilet.longitude == longitude, Toilet.latitude == latitude).first() if exist: raise ParamsError('该位置的厕所已被上传过') with db.auto_commit(): toilet = Toilet.create({ 'TOid': str(uuid.uuid1()), 'creatorID': creator_id, 'creatorType': creator_type, 'longitude': longitude, 'latitude': latitude, 'TOimage': data.get('toimage'), 'TOstatus': ApprovalAction.submit.value }) db.session.add(toilet) super(CScenicSpot, self).create_approval('totoilet', creator_id, toilet.TOid, creator_type) return Success('上传成功', data={'toid': toilet.TOid})
def update_toilet(self): """编辑厕所""" if not is_admin(): raise TokenError('请重新登录') data = parameter_required(('toid', 'latitude', 'longitude', 'toimage')) latitude, longitude = data.get('latitude'), data.get('longitude') latitude, longitude = self.cplay.check_lat_and_long( latitude, longitude) toilet = Toilet.query.filter( Toilet.isdelete == false(), Toilet.TOid == data.get('toid')).first_('未找到相应厕所信息') with db.auto_commit(): if data.get('delete'): toilet.update({'isdelete': True}) self.BaseAdmin.create_action(AdminActionS.delete.value, 'Toilet', toilet.TOid) else: toilet.update({ 'longitude': longitude, 'latitude': latitude, 'TOimage': data.get('toimage'), 'TOstatus': ApprovalAction.submit.value }) self.BaseAdmin.create_action(AdminActionS.update.value, 'Toilet', toilet.TOid) db.session.add(toilet) # 如果有正在进行的审批,取消 approval_info = Approval.query.filter( Approval.AVcontent == toilet.TOid, or_(Approval.AVstartid == toilet.creatorID, Approval.AVstartid == getattr(request, 'user').id), Approval.AVstatus == ApplyStatus.wait_check.value, Approval.isdelete == false()).first() if approval_info: approval_info.AVstatus = ApplyStatus.cancle.value super(CScenicSpot, self).create_approval('totoilet', getattr(request, 'user').id, toilet.TOid, ApplyFrom.platform.value) return Success('编辑成功', data={'toid': toilet.TOid})
def new_name(self, shuffix): import string import random myStr = string.ascii_letters + '12345678' from itsdangerous import SignatureExpired try: if hasattr(request, 'user'): usid = request.user.id else: from itsdangerous import TimedJSONWebSignatureSerializer as Serializer s = Serializer(current_app.config['SECRET_KEY']) token = request.form.get('token') or request.args.get('token') user = s.loads(token) current_app.logger.info('current user : {}'.format(user)) usid = user.get('id') except SignatureExpired: raise TokenError('登录超时,请重新登录') except Exception as e: current_app.logger.error('Error is {}'.format(e)) usid = 'anonymous' res = ''.join(random.choice(myStr) for _ in range(20)) + usid + shuffix return res
def upload_products_file(self): """ 批量导入商品,文件上传入口 :return: """ if is_admin(): Admin.query.filter_by(ADid=request.user.id, ADstatus=AdminStatus.normal.value, isdelete=False).first_('管理员账号错误') elif is_supplizer(): Supplizer.query.filter_by(SUid=request.user.id, SUstatus=UserStatus.usual.value, isdelete=False).first_('供应商账号状态错误') else: raise TokenError('未登录') file = request.files.get('file') if not file: raise ParamsError('未上传文件') data = parameter_required() current_app.logger.info('start add template {}'.format(datetime.now())) folder = 'xls' # 接收数据保存到服务器 file_path = self._save_excel(file, folder) self._insertproduct(file_path) if self._url_list: get_url_local.apply_async( args=[self._url_list], countdown=1, expires=1 * 60, ) self._url_list = list() current_app.logger.info('end add template {}'.format(datetime.now())) if is_admin(): BASEADMIN().create_action(AdminActionS.insert.value, 'file', file_path) return Success('上传成功')
def create_news(self): """创建资讯""" user = get_current_user() admin = get_current_admin() if user: usid, usname, usheader = user.USid, user.USname, user.USheader current_app.logger.info('User {0} created a news'.format(usname)) nefrom = ApplyFrom.user.value elif admin: usid, usname, usheader = admin.ADid, admin.ADname, admin.ADheader current_app.logger.info('Admin {0} created a news'.format(usname)) nefrom = ApplyFrom.platform.value elif is_supplizer(): supplizer = Supplizer.query.filter_by_( SUid=request.user.id).first() usid, usname, usheader = supplizer.SUid, supplizer.SUname, supplizer.SUheader current_app.logger.info( 'Supplizer {0} created a news'.format(usname)) nefrom = ApplyFrom.supplizer.value else: raise TokenError('用户不存在') data = parameter_required(('netitle', 'netext', 'items', 'source')) neid = str(uuid.uuid1()) items = data.get('items') # ['item1', 'item2'] mainpic = data.get('nemainpic') coupon = data.get('coupon') # ['coid1', 'coid2', 'coid3'] product = data.get('product') # ['prid1', 'prid2'] netext = data.get('netext') or [] coupon = json.dumps(coupon) if coupon not in self.empty and isinstance( coupon, list) else None product = json.dumps( product) if product not in self.empty and isinstance( product, list) else None isrecommend = data.get('neisrecommend', 0) isrecommend = True if str(isrecommend) == '1' else False text_list = list() if isinstance(netext, list): for text in netext: if text.get('type') == 'video' and text['content']: text['content']['video'] = self.__verify_set_url([ text.get('content')['video'], ])[0] text['content']['thumbnail'] = self.__verify_set_url([ text.get('content')['thumbnail'], ])[0] text_list.append(text) elif text.get('type') == 'image' and text['content']: if len(text['content']) > 9: raise ParamsError('连续上传图片不允许超过9张,可在视频或文字内容后继续添加图片') text['content'] = self.__verify_set_url(text['content']) text_list.append(text) elif text.get('type') == 'text' and text['content']: text_list.append(text) else: continue if text_list in self.empty: raise ParamsError('请添加内容后发布') netext = json.dumps(text_list) else: raise ParamsError('netext格式错误') if user: isrecommend = False if isrecommend and not mainpic: raise ParamsError("被推荐的资讯必须上传封面图") with self.snews.auto_commit() as s: session_list = [] news_info = News.create({ 'NEid': neid, 'USid': usid, 'NEtitle': data.get('netitle'), 'NEtext': netext, 'NEstatus': NewsStatus.auditing.value, 'NEsource': data.get('source'), 'NEmainpic': mainpic, 'NEisrecommend': isrecommend, 'COid': coupon, 'PRid': product, 'USname': usname, 'USheader': usheader, 'NEfrom': nefrom }) session_list.append(news_info) if items not in self.empty: for item in items: s.query(Items).filter_by_({ 'ITid': item, 'ITtype': ItemType.news.value }).first_('指定标签不存在') news_item_info = NewsTag.create({ 'NTid': str(uuid.uuid1()), 'NEid': neid, 'ITid': item }) session_list.append(news_item_info) s.add_all(session_list) # 添加到审批流 super(CNews, self).create_approval('topublish', usid, neid, nefrom) return Success('添加成功', {'neid': neid})
def get_all_news(self): if is_tourist(): usid = None tourist = 1 elif is_admin(): usid = request.user.id admin = self._check_admin(usid) current_app.logger.info( 'Admin {0} is browsing the list of news'.format(admin.ADname)) tourist = 'admin' elif is_supplizer(): usid = request.user.id sup = self._check_supplizer(usid) current_app.logger.info( 'Supplizer {0} is browsing the list of news'.format( sup.SUname)) tourist = 'supplizer' else: usid = request.user.id user = self.snews.get_user_by_id(usid) current_app.logger.info( 'User {0} is browsing the list of news'.format(user.USname)) tourist = 0 args = parameter_required(('page_num', 'page_size')) itid = args.get('itid') kw = args.get('kw', '').split() or [''] # 关键词 nestatus = args.get('nestatus') or 'usual' nestatus = getattr(NewsStatus, nestatus).value userid = None isrecommend = None if str(itid) == 'mynews': if not usid: raise TokenError('未登录') userid = usid itid = None nestatus = None elif is_supplizer(): userid = usid elif str(itid) == 'isrecommend': isrecommend = True itid = None news_list = self.snews.get_news_list([ or_(and_(*[News.NEtitle.contains(x) for x in kw]), ), # todo 暂更改为只匹配标题 NewsTag.ITid == itid, News.NEstatus == nestatus, News.USid == userid, News.NEisrecommend == isrecommend, ]) for news in news_list: news.fields = ['NEid', 'NEtitle', 'NEpageviews', 'createtime'] # 添加发布者信息 auther = news.USname or '' if news.NEfrom == ApplyFrom.platform.value: news.fill('authername', '{} (管理员)'.format(auther)) elif news.NEfrom == ApplyFrom.supplizer.value: news.fill('authername', '{} (供应商)'.format(auther)) else: news.fill('authername', '{} (用户)'.format(auther)) if news.NEstatus == NewsStatus.usual.value and not ( is_admin() or is_supplizer()): self.snews.update_pageviews(news.NEid) # 增加浏览量 # 显示点赞状态 if usid: is_favorite = self.snews.news_is_favorite(news.NEid, usid) favorite = 1 if is_favorite else 0 is_own = 1 if news.USid == usid else 0 else: favorite = 0 is_own = 0 news.fill('is_favorite', favorite) news.fill('is_own', is_own) # 显示审核状态 if userid or is_admin(): news.fill('zh_nestatus', NewsStatus(news.NEstatus).zh_value) news.fill('nestatus', NewsStatus(news.NEstatus).name) if news.NEstatus == NewsStatus.refuse.value: reason = news.NErefusereason or '因内容不符合规定,审核未通过,建议修改后重新发布' news.fill('refuse_info', reason) # 点赞数 评论数 commentnumber = self.snews.get_news_comment_count(news.NEid) news.fill('commentnumber', commentnumber) favoritnumber = self.snews.get_news_favorite_count(news.NEid) news.fill('favoritnumber', favoritnumber) # 获取内容 new_content = news.NEtext try: new_content = json.loads(new_content) except Exception as e: current_app.logger.error( '内容转换json失败 NEid: {} ; ERROR >>> {} '.format(news.NEid, e)) continue video_index, image_index, text_index = list(), list(), list() for index, item in enumerate(new_content): if item.get('type') == 'video': video_index.append(index) elif item.get('type') == 'image': image_index.append(index) elif item.get('type') == 'text': text_index.append(index) if news.NEmainpic: showtype = 'picture' news.fill('mainpic', news['NEmainpic']) elif len(video_index): showtype = 'video' video_url = new_content[video_index[0]].get('content')['video'] video_url = self.__verify_get_url([ video_url, ])[0] news.fill('video', video_url) thumbnail_url = new_content[video_index[0]].get( 'content')['thumbnail'] thumbnail_url = self.__verify_get_url([ thumbnail_url, ])[0] news.fill('videothumbnail', thumbnail_url) news.fill( 'videoduration', new_content[video_index[0]].get('content')['duration']) elif len(image_index): showtype = 'picture' pic_url = new_content[image_index[0]].get('content')[0] pic_url = self.__verify_get_url([ pic_url, ])[0] news.fill('mainpic', pic_url) else: showtype = 'text' news.fill( 'netext', new_content[text_index[0]].get('content')[:100] + ' ...') news.fill('showtype', showtype) # 作者信息 if news.USheader: usheader = news['USheader'] else: usinfo = self.fill_user_info(news.USid) usheader = usinfo['USheader'] news.fill('usheader', usheader) # 增加搜索记录 if kw not in self.empty and usid: with self.snews.auto_commit() as s: instance = UserSearchHistory.create({ 'USHid': str(uuid.uuid4()), 'USid': request.user.id, 'USHname': ' '.join(kw), 'USHtype': 10 }) s.add(instance) return Success(data=news_list).get_body(istourst=tourist)
def travelrecord_list(self): """时光记录(个人中心)列表""" args = request.args.to_dict() usid, date, area, trtype = args.get('usid'), args.get( 'date'), args.get('area'), args.get('trtype') option = args.get('option') if usid: ucl_list = [usid] counts = self._my_home_page_count(usid) top = self._init_top_dict(counts) elif common_user(): ucl_list = db.session.query( UserCollectionLog.UCLcollection).filter( UserCollectionLog.UCLcoType == CollectionType.user.value, UserCollectionLog.isdelete == false(), UserCollectionLog.UCLcollector == getattr( request, 'user').id).all() ucl_list = [ucl[0] for ucl in ucl_list] counts = self._my_home_page_count(getattr(request, 'user').id) top = self._init_top_dict(counts) elif is_admin(): ucl_list = top = None else: # return Success(data={'top': {'followed': 0, 'fens': 0, 'published': 0, # 'usname': None, 'usheader': None, 'usminilevel': None, 'concerned': False}, # 'travelrecord': []}) raise TokenError('请重新登录') base_filter = [TravelRecord.isdelete == false()] if not (common_user() and option == 'my') and not is_admin(): base_filter.append(TravelRecord.AuthorID.in_(ucl_list)) base_filter.append( TravelRecord.TRstatus == TravelRecordStatus.published.value) trecords_query = TravelRecord.query.filter(*base_filter) if date: if not re.match(r'^\d{4}-\d{2}$', date): raise ParamsError('查询日期格式错误') year, month = str(date).split('-') trecords_query = trecords_query.filter( extract('month', TravelRecord.createtime) == month, extract('year', TravelRecord.createtime) == year) if trtype or str(trtype) == '0': if not re.match(r'^[012]$', str(trtype)): raise ParamsError('trtype 参数错误') trecords_query = trecords_query.filter( TravelRecord.TRtype == trtype) if area: scenicspots = db.session.query(ScenicSpot.SSPname).filter( ScenicSpot.isdelete == false(), ScenicSpot.SSParea.ilike('%{}%'.format(area))).all() ssname = [ss[0] for ss in scenicspots] trecords_query = trecords_query.filter( or_(*map( lambda x: TravelRecord.TRlocation.ilike('%{}%'.format(x)), ssname))) if common_user() and option == 'my': trecords_query = trecords_query.filter( TravelRecord.AuthorID == getattr(request, 'user').id) trecords = trecords_query.order_by( TravelRecord.createtime.desc()).all_with_page() [self._fill_travelrecord(x) for x in trecords] return Success(data={'top': top, 'travelrecord': trecords})