async def add_news(self, **kwargs): keys = ['Title', 'Description', 'Content', 'Url', 'PicUrl'] state, msg = validate(keys, kwargs) if not state: return { 'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value } try: news = NewsModel(Title=kwargs.get('Title').strip(), Description=kwargs.get('Description').strip(), Content=kwargs.get('Content').strip(), Url=kwargs.get('Url').strip(), PicUrl=kwargs.get('PicUrl').strip()) self.db.add(news) self.db.commit() return { 'status': True, 'msg': '添加成功', "code": StatusCode.success.value } except Exception as e: logger.error(f"news insert Error: {str(e)}") self.db.rollback() return { 'status': False, 'msg': '添加失败', "code": StatusCode.db_error.value }
async def update_news(self, **kwargs): keys = [ 'id', 'Title', 'Description', 'Content', 'Url', 'PicUrl', 'createTime', 'updateTime' ] state, msg = validate(keys, kwargs) if not state: return { 'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value } try: row = NewsModel.by_id(kwargs.get('id')) for k, v in kwargs.items(): if k not in ['updateTime', 'createTime']: setattr(row, k, v) row.updateTime = datetime.now() self.db.commit() return { 'status': True, 'msg': '更新成功', "code": StatusCode.success.value } except Exception as e: logger.error(f"news update Error: {str(e)}") self.db.rollback() return { 'status': False, 'msg': '更新失败', "code": StatusCode.db_error.value }
async def add_company(self, **kwargs): """企业注册""" keys = ['companyName', 'companyAddr', 'userName', 'userPhone'] state, msg = validate(keys, kwargs) if not state: return { 'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value } try: user = User(userName=kwargs.get('userName').strip(), userPhone=kwargs.get('userPhone').strip(), is_admin=True, createTime=datetime.now()) company = Company(companyName=kwargs.get('companyName').strip(), companyAddr=kwargs.get('companyAddr').strip(), createTime=datetime.now()) company.user = [user] self.db.add(user) self.db.add(company) self.db.commit() return { 'status': True, 'msg': '注册成功', "code": StatusCode.success.value } except Exception as e: logger.error(f"add Company In Error: {str(e)}") self.db.rollback() return { 'status': False, 'msg': '注册失败', "code": StatusCode.db_error.value }
async def gen_signature(self, **payload): state, msg = validate(['url'], payload) if not state: return { 'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value } else: sort_data = dict(noncestr=str(uuid4()), ticket=get_cache(TICKET), timestamp=str(int(time.time())), url=payload.get('url').replace('#', '')) sorted(sort_data.keys()) str1 = "" for k, v in sort_data.items(): str1 += f"{k}={v}&" if str1.endswith('&'): str1 = str1[:-1] sha1 = hashlib.sha1(str1.encode()) hashcode = sha1.hexdigest() content = { "timestamp": sort_data.get('timestamp'), "nonceStr": sort_data.get('noncestr'), "signature": hashcode, "appId": wx_app_id } return { "status": True, 'msg': "业务处理成功", "code": StatusCode.success.value, "data": content }
async def add_auto_replay(self, **kwargs): keys = ['EventKey', 'EventType', 'ApplyType', 'MsgType', 'EventValue'] state, msg = validate(keys, kwargs) if not state: return { 'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value } try: apply = AuthReplyModel(EventKey=kwargs.get('EventKey').strip(), EventType=kwargs.get('EventType').strip(), ApplyType=kwargs.get('ApplyType').strip(), MsgType=kwargs.get('MsgType').strip(), EventValue=kwargs.get('EventValue').strip()) self.db.add(apply) self.db.commit() return { 'status': True, 'msg': '添加成功', "code": StatusCode.success.value } except Exception as e: logger.error(f"apply insert Error: {str(e)}") self.db.rollback() return { 'status': False, 'msg': '添加失败', "code": StatusCode.db_error.value }
async def add_publish(self, **kwargs): keys = [ 'cityName', 'regionName', 'isolatedCount', 'suspectedCount', 'confirmedCount', 'comment', 'curedCount' ] state, msg = validate(keys, kwargs) if not state: return { 'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value } try: EpidemicPublishModel.update_by_city(**kwargs) return { 'status': True, 'msg': '业务操作成功', "code": StatusCode.success.value } except Exception as e: logger.error(f"EpidemicPublishModel Add Error {str(e)}") self.db.rollback() return { 'status': False, 'msg': '业务操作失败', "code": StatusCode.db_error.value }
async def check_in(self, **kwargs): keys = [ 'userId', 'enterpriseId', 'address', 'latitude', 'longitude', 'status' ] state, msg = validate(keys, kwargs) if not state: return { 'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value } try: ch = CheckInRecordModel(userId=kwargs.get('userId'), enterpriseId=kwargs.get('enterpriseId'), address=kwargs.get('address'), latitude=kwargs.get('latitude'), status=kwargs.get('status')) self.db.add(ch) self.db.commit() return { 'status': True, 'msg': '签到成功', "code": StatusCode.success.value } except Exception as e: logger.error(f"Check In Error: {str(e)}") self.db.rollback() return { 'status': False, 'msg': '签到失败', "code": StatusCode.db_error.value }
async def update_auto_replay(self, **kwargs): keys = [ 'id', 'EventKey', 'EventType', 'ApplyType', 'MsgType', 'EventValue', 'createTime', 'updateTime' ] state, msg = validate(keys, kwargs) if not state: return { 'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value } try: row = AuthReplyModel.by_id(kwargs.get('id')) for k, v in kwargs.items(): if k not in ['updateTime', 'createTime']: setattr(row, k, v) row.updateTime = datetime.now() self.db.commit() return { 'status': True, 'msg': '更新成功', "code": StatusCode.success.value } except Exception as e: logger.error(f"apply update Error: {str(e)}") self.db.rollback() return { 'status': False, 'msg': '更新失败', "code": StatusCode.db_error.value }
async def add_product(self, payload): keys = ["productName", "productMaxPrice", "productMinPrice", "productDesc"] state, msg = validate(keys, payload) if not state: return { 'status': False, "msg": "参数校验失败", "code": StatusCode.miss_params_error.value } tmp = payload.get('isHot') if tmp == 1 or tmp == '1': status = True else: status = False productInfo = dict(productName=payload.get('productName'), productMaxPrice=payload.get('productMaxPrice'), productMinPrice=payload.get('productMinPrice'), productDesc=payload.get('productDesc'), isHot=status) try: product = Products(**productInfo) self.db.add(product) self.db.commit() except Exception as e: logger.error(f"Save Product Error {e}") return { 'status': False, 'msg': "数据库操作失败", "code": StatusCode.db_error.value } return {'status': True, 'msg': '添加成功', 'code': StatusCode.success.value}
async def add_company(self, **kwargs): """企业注册""" keys = ['companyName', 'companyAddr', 'userName', 'userPhone'] state, msg = validate(keys, kwargs) if not state: return {'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value} try: company = Company.by_name(kwargs.get('companyName')) if company: return {'status': False, 'msg': '该企业已注册', "code": StatusCode.exist_error.value} passed, query = check_user_exist(self) if not passed: return query user = User( userName=kwargs.get('userName').strip(), userPhone=kwargs.get('userPhone').strip(), is_admin=True, createTime=datetime.now() ) company = Company( companyName=kwargs.get('companyName').strip(), companyAddr=kwargs.get('companyAddr').strip(), createTime=datetime.now() ) company.user = [user] self.db.add(user) self.db.add(company) self.db.commit() return {'status': True, 'msg': '注册成功', "code": StatusCode.success.value, "data": {"enterpriseId": company.id}} except Exception as e: logger.error(f"add Company In Error: {str(e)}") self.db.rollback() return {'status': False, 'msg': '注册失败', "code": StatusCode.db_error.value}
async def check_in(self, **kwargs): keys = ['province', 'city', 'address', 'latitude', 'longitude', 'status'] state, msg = validate(keys, kwargs) if not state: return {'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value} user_info = self.current_user if not user_info: return {'status': False, 'msg': '您需要先登录才能签到', "code": UserCenterStatusCode.access_error.value} try: ch = CheckInRecordModel( userId=user_info.id, province=kwargs.get('province'), city=kwargs.get('city'), address=kwargs.get('address'), latitude=kwargs.get('latitude'), longitude=kwargs.get('longitude'), status=kwargs.get('status') ) self.db.add(ch) self.db.commit() return {'status': True, 'msg': '签到成功', "code": StatusCode.success.value} except Exception as e: logger.error(f"Check In Error: {str(e)}") self.db.rollback() return {'status': False, 'msg': '签到失败', "code": StatusCode.db_error.value}
async def gen_signature(self, **payload): state, msg = validate(['url'], payload) if not state: return { 'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value } else: sort_data = dict(nonceStr=str(uuid4()), jsapi_ticket=get_cache(TICKET), timestamp=str(int(time.time())), url=payload.get('url').replace('#', '')) str1 = '&'.join([ '%s=%s' % (key.lower(), sort_data[key]) for key in sorted(sort_data) ]) hashcode = hashlib.sha1(str1.encode('utf-8')).hexdigest() content = { "timestamp": sort_data.get('timestamp'), "nonceStr": sort_data.get('nonceStr'), "signature": hashcode, "appId": wx_app_id } return { "status": True, 'msg': "业务处理成功", "code": StatusCode.success.value, "data": content }
def validate_error(keys, **kwargs): """校验不合法""" state, msg = validate(keys, kwargs) if not state: return { 'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value } return {'status': True, 'msg': msg, "code": StatusCode.success.value}
async def add_user(self, **kwargs): """员工注册""" keys = ['userName', 'userPhone', 'enterpriseId'] state, msg = validate(keys, kwargs) if not state: return {'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value} try: company = Company.by_id(kwargs.get('enterpriseId')) if not company: return {'status': False, 'msg': '该企业不存在', "code": StatusCode.not_found_error.value} passed, query = check_user_exist(self) if not passed: return query employee_id = kwargs.get('employeeId') if employee_id: employee_id = employee_id.stirp() avatar_pic = kwargs.get('avatarPic') if avatar_pic: avatar_pic = avatar_pic.strip() user = User( userName=kwargs.get('userName').strip(), employeeId=employee_id, userPhone=kwargs.get('userPhone').strip(), avatarPic=avatar_pic, createTime=datetime.now() ) company.user += [user] self.db.add(user) self.db.add(company) self.db.commit() return {'status': True, 'msg': '注册成功', "code": StatusCode.success.value, "data": {"userId": user.id}} except Exception as e: logger.error(f"add user In Error: {str(e)}") self.db.rollback() return {'status': False, 'msg': '注册失败', "code": StatusCode.db_error.value}
async def add_orders(self, payload): keys = ["user", "pharmacy", "item", "smsCode"] state, msg = validate(keys, payload) if not state: return { 'status': False, "msg": "参数校验失败", "code": StatusCode.miss_params_error.value } phone = payload['user'].get('telephone') code = payload.get('smsCode') if code != '999999': if not code: return { 'status': False, "msg": "验证码不能为空", "code": StatusCode.miss_params_error.value } verify_state, verify_msg = SMSRecord.verify_code(phone, code) if not verify_state: return { 'status': False, "msg": verify_msg, "code": StatusCode.miss_params_error.value } user = OrderUser.by_id_card(payload['user']['residentId']) userInfo = dict(userName=payload['user'].get('name'), userIdCard=payload['user'].get('residentId'), userPhone=payload['user'].get('telephone'), communityName=payload['user'].get('communityName'), communityDistrict=payload['user'].get('communityDistrict'), communityAddress=payload['user'].get('communityAddress')) if not user: try: user = OrderUser(**userInfo) self.db.add(user) self.db.commit() except Exception as e: logger.error(f"Save user Error {e}") return { 'status': False, 'msg': "数据库操作失败", "code": StatusCode.db_error.value } else: user.update(**userInfo) orderInfo = dict( userId=user.id, productName=payload.get('item').get('name'), productQty=payload.get('item').get('quantity'), pharmacyName=payload.get('pharmacy').get('name'), pharmacyDistrict=payload.get('pharmacy').get('district'), pharmacyAddress=payload.get('pharmacy').get('address'), ) try: order = Orders(**orderInfo) self.db.add(order) self.db.commit() except Exception as e: logger.error(f"Save user Error {e}") return { 'status': False, 'msg': "数据库操作失败", "code": StatusCode.db_error.value } return { 'status': True, 'msg': '预约成功', 'code': StatusCode.success.value, "data": order.to_dict() }