parse.py 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577
  1. from typing import Dict, Any
  2. from app import db
  3. from datetime import datetime
  4. import os
  5. import boto3
  6. from botocore.config import Config
  7. import logging
  8. import requests
  9. import json
  10. import re
  11. import uuid
  12. from PIL import Image
  13. from io import BytesIO
  14. import pytesseract
  15. import base64
  16. from openai import OpenAI
  17. from app.config.config import DevelopmentConfig, ProductionConfig
  18. # 测试用的解析数据接口。没有实际使用。
  19. def parse_data(data: Dict[str, Any]) -> Dict[str, Any]:
  20. """
  21. 解析数据的主函数
  22. Args:
  23. data: 要解析的数据
  24. Returns:
  25. 解析后的数据
  26. """
  27. # TODO: 实现数据解析逻辑
  28. return {
  29. 'code': 200,
  30. 'status': 'success',
  31. 'message': 'Data parsed successfully',
  32. 'data': data
  33. }
  34. # 名片解析数据模型
  35. class BusinessCard(db.Model):
  36. __tablename__ = 'business_cards'
  37. id = db.Column(db.Integer, primary_key=True, autoincrement=True)
  38. name_zh = db.Column(db.String(100), nullable=False)
  39. name_en = db.Column(db.String(100))
  40. title_zh = db.Column(db.String(100))
  41. title_en = db.Column(db.String(100))
  42. mobile = db.Column(db.String(50))
  43. phone = db.Column(db.String(50))
  44. email = db.Column(db.String(100))
  45. hotel_zh = db.Column(db.String(200))
  46. hotel_en = db.Column(db.String(200))
  47. address_zh = db.Column(db.Text)
  48. address_en = db.Column(db.Text)
  49. postal_code_zh = db.Column(db.String(20))
  50. postal_code_en = db.Column(db.String(20))
  51. brand_zh = db.Column(db.String(100))
  52. brand_en = db.Column(db.String(100))
  53. affiliation_zh = db.Column(db.String(200))
  54. affiliation_en = db.Column(db.String(200))
  55. image_path = db.Column(db.String(255)) # MinIO中存储的路径
  56. career_path = db.Column(db.JSON) # 职业轨迹,JSON格式
  57. brand_group = db.Column(db.String(200)) # 品牌组合
  58. created_at = db.Column(db.DateTime, default=datetime.now, nullable=False)
  59. updated_at = db.Column(db.DateTime, onupdate=datetime.now)
  60. updated_by = db.Column(db.String(50))
  61. status = db.Column(db.String(20), default='active')
  62. def to_dict(self):
  63. return {
  64. 'id': self.id,
  65. 'name_zh': self.name_zh,
  66. 'name_en': self.name_en,
  67. 'title_zh': self.title_zh,
  68. 'title_en': self.title_en,
  69. 'mobile': self.mobile,
  70. 'phone': self.phone,
  71. 'email': self.email,
  72. 'hotel_zh': self.hotel_zh,
  73. 'hotel_en': self.hotel_en,
  74. 'address_zh': self.address_zh,
  75. 'address_en': self.address_en,
  76. 'postal_code_zh': self.postal_code_zh,
  77. 'postal_code_en': self.postal_code_en,
  78. 'brand_zh': self.brand_zh,
  79. 'brand_en': self.brand_en,
  80. 'affiliation_zh': self.affiliation_zh,
  81. 'affiliation_en': self.affiliation_en,
  82. 'image_path': self.image_path,
  83. 'career_path': self.career_path,
  84. 'brand_group': self.brand_group,
  85. 'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
  86. 'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None,
  87. 'updated_by': self.updated_by,
  88. 'status': self.status
  89. }
  90. # 名片解析功能模块
  91. # DeepSeek API配置
  92. DEEPSEEK_API_KEY = os.environ.get('DEEPSEEK_API_KEY', 'sk-2aea6e8b159b448aa3c1e29acd6f4349')
  93. DEEPSEEK_API_URL = os.environ.get('DEEPSEEK_API_URL', 'https://api.deepseek.com/v1/chat/completions')
  94. # 备用API端点
  95. DEEPSEEK_API_URL_BACKUP = 'https://api.deepseek.com/v1/completions'
  96. # OCR配置
  97. # 设置pytesseract路径(如果需要)
  98. # pytesseract.pytesseract.tesseract_cmd = r'/path/to/tesseract'
  99. # OCR语言设置,支持多语言
  100. OCR_LANG = os.environ.get('OCR_LANG', 'chi_sim+eng')
  101. # 根据环境选择配置
  102. """
  103. if os.environ.get('FLASK_ENV') == 'production':
  104. config = ProductionConfig()
  105. else:
  106. config = DevelopmentConfig()
  107. """
  108. # 使用配置变量,缺省认为在生产环境运行
  109. config = ProductionConfig()
  110. # 使用配置变量
  111. minio_url = f"{'https' if config.MINIO_SECURE else 'http'}://{config.MINIO_HOST}"
  112. minio_access_key = config.MINIO_USER
  113. minio_secret_key = config.MINIO_PASSWORD
  114. minio_bucket = config.MINIO_BUCKET
  115. use_ssl = config.MINIO_SECURE
  116. def get_minio_client():
  117. """获取MinIO客户端连接"""
  118. try:
  119. # 使用全局配置变量
  120. global minio_url, minio_access_key, minio_secret_key, minio_bucket, use_ssl
  121. logging.info(f"尝试连接MinIO服务器: {minio_url}")
  122. minio_client = boto3.client(
  123. 's3',
  124. endpoint_url=minio_url,
  125. aws_access_key_id=minio_access_key,
  126. aws_secret_access_key=minio_secret_key,
  127. config=Config(
  128. signature_version='s3v4',
  129. retries={'max_attempts': 3, 'mode': 'standard'},
  130. connect_timeout=10,
  131. read_timeout=30
  132. )
  133. )
  134. # 确保存储桶存在
  135. buckets = minio_client.list_buckets()
  136. bucket_names = [bucket['Name'] for bucket in buckets.get('Buckets', [])]
  137. logging.info(f"成功连接到MinIO服务器,现有存储桶: {bucket_names}")
  138. if minio_bucket not in bucket_names:
  139. logging.info(f"创建存储桶: {minio_bucket}")
  140. minio_client.create_bucket(Bucket=minio_bucket)
  141. return minio_client
  142. except Exception as e:
  143. logging.error(f"MinIO连接错误: {str(e)}")
  144. return None
  145. def extract_text_from_image(image_data):
  146. """
  147. 使用OCR从图像中提取文本,然后通过DeepSeek API解析名片信息
  148. Args:
  149. image_data (bytes): 图像的二进制数据
  150. Returns:
  151. dict: 提取的信息(姓名、职位、公司等)
  152. Raises:
  153. Exception: 当OCR或API调用失败或配置错误时抛出异常
  154. """
  155. try:
  156. # 步骤1: 使用OCR从图像中提取文本
  157. ocr_text = ocr_extract_text(image_data)
  158. if not ocr_text or ocr_text.strip() == "":
  159. error_msg = "OCR无法从图像中提取文本"
  160. logging.error(error_msg)
  161. raise Exception(error_msg)
  162. logging.info(f"OCR提取的文本: {ocr_text[:200]}..." if len(ocr_text) > 200 else ocr_text)
  163. # 步骤2: 使用DeepSeek API解析文本中的信息
  164. return parse_text_with_deepseek(ocr_text)
  165. except Exception as e:
  166. error_msg = f"从图像中提取和解析文本失败: {str(e)}"
  167. logging.error(error_msg, exc_info=True)
  168. raise Exception(error_msg)
  169. def ocr_extract_text(image_data):
  170. """
  171. 使用OCR从图像中提取文本
  172. Args:
  173. image_data (bytes): 图像的二进制数据
  174. Returns:
  175. str: 提取的文本
  176. """
  177. try:
  178. # 将二进制数据转换为PIL图像
  179. image = Image.open(BytesIO(image_data))
  180. # 使用pytesseract进行OCR文本提取
  181. text = pytesseract.image_to_string(image, lang=OCR_LANG)
  182. # 清理提取的文本
  183. text = text.strip()
  184. logging.info(f"OCR成功从图像中提取文本,长度: {len(text)}")
  185. print(text)
  186. return text
  187. except Exception as e:
  188. error_msg = f"OCR提取文本失败: {str(e)}"
  189. logging.error(error_msg, exc_info=True)
  190. raise Exception(error_msg)
  191. def parse_text_with_deepseek(text):
  192. """
  193. 使用DeepSeek API解析文本中的名片信息
  194. Args:
  195. text (str): 要解析的文本
  196. Returns:
  197. dict: 解析的名片信息
  198. """
  199. # 准备请求DeepSeek API
  200. if not DEEPSEEK_API_KEY:
  201. error_msg = "未配置DeepSeek API密钥"
  202. logging.error(error_msg)
  203. raise Exception(error_msg)
  204. # 构建API请求的基本信息
  205. headers = {
  206. "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
  207. "Content-Type": "application/json"
  208. }
  209. # 构建提示语,包含OCR提取的文本
  210. prompt = f"""请从以下名片文本中提取详细信息,需分别识别中英文内容。
  211. 以JSON格式返回,包含以下字段:
  212. - name_zh: 中文姓名
  213. - name_en: 英文姓名
  214. - title_zh: 中文职位/头衔
  215. - title_en: 英文职位/头衔
  216. - hotel_zh: 中文酒店/公司名称
  217. - hotel_en: 英文酒店/公司名称
  218. - mobile: 手机号码
  219. - phone: 固定电话
  220. - email: 电子邮箱
  221. - address_zh: 中文地址
  222. - address_en: 英文地址
  223. - brand_group: 品牌组合(如有多个品牌,以逗号分隔)
  224. - career_path: 职业轨迹(如果能从文本中推断出,以JSON数组格式返回,包含公司名称和职位)
  225. 名片文本:
  226. {text}
  227. """
  228. # 使用模型名称
  229. model_name = 'deepseek-chat'
  230. try:
  231. # 尝试调用DeepSeek API
  232. logging.info(f"尝试通过DeepSeek API解析文本")
  233. payload = {
  234. "model": model_name,
  235. "messages": [
  236. {"role": "system", "content": "你是一个专业的名片信息提取助手。请用JSON格式返回结果,不要有多余的文字说明。"},
  237. {"role": "user", "content": prompt}
  238. ],
  239. "temperature": 0.1
  240. }
  241. logging.info(f"向DeepSeek API发送请求")
  242. response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload, timeout=30)
  243. # 检查响应状态
  244. response.raise_for_status()
  245. # 解析API响应
  246. result = response.json()
  247. content = result.get("choices", [{}])[0].get("message", {}).get("content", "{}")
  248. # 尝试解析JSON内容
  249. try:
  250. # 找到内容中的JSON部分(有时模型会在JSON前后添加额外文本)
  251. json_content = extract_json_from_text(content)
  252. extracted_data = json.loads(json_content)
  253. logging.info(f"成功解析DeepSeek API返回的JSON")
  254. except json.JSONDecodeError:
  255. logging.warning(f"无法解析JSON,尝试直接从文本提取信息")
  256. # 如果无法解析JSON,尝试直接从文本中提取关键信息
  257. extracted_data = extract_fields_from_text(content)
  258. # 确保所有必要的字段都存在
  259. required_fields = ['name', 'title', 'company', 'phone', 'email', 'address', 'brand_group', 'career_path']
  260. for field in required_fields:
  261. if field not in extracted_data:
  262. extracted_data[field] = "" if field != 'career_path' else []
  263. logging.info(f"成功从DeepSeek API获取解析结果")
  264. return extracted_data
  265. except requests.exceptions.HTTPError as e:
  266. error_msg = f"DeepSeek API调用失败: {str(e)}"
  267. logging.error(error_msg)
  268. if hasattr(e, 'response') and e.response:
  269. logging.error(f"错误状态码: {e.response.status_code}")
  270. logging.error(f"错误内容: {e.response.text}")
  271. raise Exception(error_msg)
  272. except Exception as e:
  273. error_msg = f"解析文本过程中发生错误: {str(e)}"
  274. logging.error(error_msg, exc_info=True)
  275. raise Exception(error_msg)
  276. def extract_json_from_text(text):
  277. """
  278. 从文本中提取JSON部分
  279. Args:
  280. text (str): 包含JSON的文本
  281. Returns:
  282. str: 提取的JSON字符串
  283. """
  284. # 尝试找到最外层的花括号对
  285. start_idx = text.find('{')
  286. if start_idx == -1:
  287. return "{}"
  288. # 使用简单的括号匹配算法找到对应的闭合括号
  289. count = 0
  290. for i in range(start_idx, len(text)):
  291. if text[i] == '{':
  292. count += 1
  293. elif text[i] == '}':
  294. count -= 1
  295. if count == 0:
  296. return text[start_idx:i+1]
  297. # 如果没有找到闭合括号,返回从开始位置到文本结尾
  298. return text[start_idx:]
  299. def extract_fields_from_text(text):
  300. """
  301. 从文本中直接提取名片字段信息
  302. Args:
  303. text (str): 要分析的文本
  304. Returns:
  305. dict: 提取的字段
  306. """
  307. # 初始化结果字典
  308. result = {
  309. 'name_zh': '',
  310. 'name_en': '',
  311. 'title_zh': '',
  312. 'title_en': '',
  313. 'mobile': '',
  314. 'phone': '',
  315. 'email': '',
  316. 'hotel_zh': '',
  317. 'hotel_en': '',
  318. 'address_zh': '',
  319. 'address_en': '',
  320. 'postal_code_zh': '',
  321. 'postal_code_en': '',
  322. 'brand_zh': '',
  323. 'brand_en': '',
  324. 'affiliation_zh': '',
  325. 'affiliation_en': ''
  326. }
  327. # 提取中文姓名
  328. name_zh_match = re.search(r'["\'](姓名)["\'][\s\{:]*["\']?(中文)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  329. if name_zh_match:
  330. result['name_zh'] = name_zh_match.group(3)
  331. # 提取英文姓名
  332. name_en_match = re.search(r'["\'](姓名)["\'][\s\{:]*["\']?(英文)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  333. if name_en_match:
  334. result['name_en'] = name_en_match.group(3)
  335. # 提取中文头衔
  336. title_zh_match = re.search(r'["\'](头衔|职位)["\'][\s\{:]*["\']?(中文)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  337. if title_zh_match:
  338. result['title_zh'] = title_zh_match.group(3)
  339. # 提取英文头衔
  340. title_en_match = re.search(r'["\'](头衔|职位)["\'][\s\{:]*["\']?(英文)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  341. if title_en_match:
  342. result['title_en'] = title_en_match.group(3)
  343. # 提取手机
  344. mobile_match = re.search(r'["\'](手机)["\'][\s:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  345. if mobile_match:
  346. result['mobile'] = mobile_match.group(2)
  347. # 提取电话
  348. phone_match = re.search(r'["\'](电话)["\'][\s:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  349. if phone_match:
  350. result['phone'] = phone_match.group(2)
  351. # 提取邮箱
  352. email_match = re.search(r'["\'](邮箱)["\'][\s:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  353. if email_match:
  354. result['email'] = email_match.group(2)
  355. # 提取中文酒店名称
  356. hotel_zh_match = re.search(r'["\'](地址)["\'][\s\{:]*["\']?(中文)["\']?[\s\{:]*["\']?(酒店名称)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  357. if hotel_zh_match:
  358. result['hotel_zh'] = hotel_zh_match.group(4)
  359. # 提取英文酒店名称
  360. hotel_en_match = re.search(r'["\'](地址)["\'][\s\{:]*["\']?(英文)["\']?[\s\{:]*["\']?(酒店名称)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  361. if hotel_en_match:
  362. result['hotel_en'] = hotel_en_match.group(4)
  363. # 提取中文详细地址
  364. address_zh_match = re.search(r'["\'](地址)["\'][\s\{:]*["\']?(中文)["\']?[\s\{:]*["\']?(详细地址)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  365. if address_zh_match:
  366. result['address_zh'] = address_zh_match.group(4)
  367. # 提取英文详细地址
  368. address_en_match = re.search(r'["\'](地址)["\'][\s\{:]*["\']?(英文)["\']?[\s\{:]*["\']?(详细地址)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  369. if address_en_match:
  370. result['address_en'] = address_en_match.group(4)
  371. # 提取中文邮政编码
  372. postal_code_zh_match = re.search(r'["\'](地址)["\'][\s\{:]*["\']?(中文)["\']?[\s\{:]*["\']?(邮政编码)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  373. if postal_code_zh_match:
  374. result['postal_code_zh'] = postal_code_zh_match.group(4)
  375. # 提取英文邮政编码
  376. postal_code_en_match = re.search(r'["\'](地址)["\'][\s\{:]*["\']?(英文)["\']?[\s\{:]*["\']?(邮政编码)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  377. if postal_code_en_match:
  378. result['postal_code_en'] = postal_code_en_match.group(4)
  379. # 提取中文品牌名称
  380. brand_zh_match = re.search(r'["\'](公司)["\'][\s\{:]*["\']?(中文)["\']?[\s\{:]*["\']?(品牌名称)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  381. if brand_zh_match:
  382. result['brand_zh'] = brand_zh_match.group(4)
  383. # 提取英文品牌名称
  384. brand_en_match = re.search(r'["\'](公司)["\'][\s\{:]*["\']?(英文)["\']?[\s\{:]*["\']?(品牌名称)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  385. if brand_en_match:
  386. result['brand_en'] = brand_en_match.group(4)
  387. # 提取中文隶属关系
  388. affiliation_zh_match = re.search(r'["\'](公司)["\'][\s\{:]*["\']?(中文)["\']?[\s\{:]*["\']?(隶属关系)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  389. if affiliation_zh_match:
  390. result['affiliation_zh'] = affiliation_zh_match.group(4)
  391. # 提取英文隶属关系
  392. affiliation_en_match = re.search(r'["\'](公司)["\'][\s\{:]*["\']?(英文)["\']?[\s\{:]*["\']?(隶属关系)["\']?[\s\}:]*["\']([^"\']+)["\']', text, re.IGNORECASE)
  393. if affiliation_en_match:
  394. result['affiliation_en'] = affiliation_en_match.group(4)
  395. return result
  396. def parse_text_with_qwen25VLplus(image_data):
  397. """
  398. 使用阿里云的 Qwen VL Max 模型解析图像中的名片信息
  399. Args:
  400. image_data (bytes): 图像的二进制数据
  401. Returns:
  402. dict: 解析的名片信息
  403. """
  404. # 阿里云 Qwen API 配置
  405. QWEN_API_KEY = os.environ.get('QWEN_API_KEY', 'sk-8f2320dafc9e4076968accdd8eebd8e9')
  406. try:
  407. # 将图片数据转为 base64 编码
  408. base64_image = base64.b64encode(image_data).decode('utf-8')
  409. # 初始化 OpenAI 客户端,配置为阿里云 API
  410. client = OpenAI(
  411. api_key=QWEN_API_KEY,
  412. base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
  413. )
  414. # 构建优化后的提示语
  415. prompt = """你是企业名片的信息提取专家。请仔细分析提供的图片,精确提取名片信息。
  416. ## 提取要求
  417. - 区分中英文内容,分别提取
  418. - 保持提取信息的原始格式(如大小写、标点)
  419. - 对于无法识别或名片中不存在的信息,返回空字符串
  420. - 名片中没有的信息,请不要猜测
  421. ## 需提取的字段
  422. 1. 中文姓名 (name_zh)
  423. 2. 英文姓名 (name_en)
  424. 3. 中文职位/头衔 (title_zh)
  425. 4. 英文职位/头衔 (title_en)
  426. 5. 中文酒店/公司名称 (hotel_zh)
  427. 6. 英文酒店/公司名称 (hotel_en)
  428. 7. 手机号码 (mobile) - 如有多个,使用逗号分隔
  429. 8. 固定电话 (phone) - 如有多个,使用逗号分隔
  430. 9. 电子邮箱 (email)
  431. 10. 中文地址 (address_zh)
  432. 11. 英文地址 (address_en)
  433. 12. 中文邮政编码 (postal_code_zh)
  434. 13. 英文邮政编码 (postal_code_en)
  435. 14. 品牌组合 (brand_group) - 如有多个品牌,使用逗号分隔
  436. 15. 职业轨迹 (career_path) - 如能从名片中推断,以JSON数组格式返回,包含当前日期,公司名称和职位。自动生成当前日期。
  437. 16. 隶属关系 (affiliation) - 如能从名片中推断,以JSON数组格式返回,包含公司名称和隶属集团名称
  438. ## 输出格式
  439. 请以严格的JSON格式返回结果,不要添加任何额外解释文字。JSON格式如下:
  440. ```json
  441. {
  442. "name_zh": "",
  443. "name_en": "",
  444. "title_zh": "",
  445. "title_en": "",
  446. "hotel_zh": "",
  447. "hotel_en": "",
  448. "mobile": "",
  449. "phone": "",
  450. "email": "",
  451. "address_zh": "",
  452. "address_en": "",
  453. "postal_code_zh": "",
  454. "postal_code_en": "",
  455. "brand_group": "",
  456. "career_path": [],
  457. "affiliation": []
  458. }
  459. ```"""
  460. # 调用 Qwen VL Max API
  461. logging.info("发送请求到 Qwen VL Max 模型")
  462. completion = client.chat.completions.create(
  463. # model="qwen-vl-plus",
  464. model="qwen-vl-max-latest",
  465. messages=[
  466. {
  467. "role": "user",
  468. "content": [
  469. {"type": "text", "text": prompt},
  470. {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
  471. ]
  472. }
  473. ],
  474. temperature=0.1, # 降低温度增加精确性
  475. response_format={"type": "json_object"} # 要求输出JSON格式
  476. )
  477. # 解析响应
  478. response_content = completion.choices[0].message.content
  479. logging.info(f"成功从 Qwen 模型获取响应: {response_content}")
  480. # 尝试从响应中提取 JSON
  481. try:
  482. json_content = extract_json_from_text(response_content)
  483. extracted_data = json.loads(json_content)
  484. logging.info("成功解析 Qwen 响应中的 JSON")
  485. except json.JSONDecodeError:
  486. logging.warning("无法解析 JSON,尝试从文本中提取信息")
  487. extracted_data = extract_fields_from_text(response_content)
  488. # 确保所有必要字段存在
  489. required_fields = [
  490. 'name_zh', 'name_en', 'title_zh', 'title_en',
  491. 'hotel_zh', 'hotel_en', 'mobile', 'phone',
  492. 'email', 'address_zh', 'address_en',
  493. 'postal_code_zh', 'postal_code_en', 'brand_group', 'career_path'
  494. ]
  495. for field in required_fields:
  496. if field not in extracted_data:
  497. extracted_data[field] = [] if field == 'career_path' else ""
  498. return extracted_data
  499. except Exception as e:
  500. error_msg = f"Qwen VL Max 模型解析失败: {str(e)}"
  501. logging.error(error_msg, exc_info=True)
  502. raise Exception(error_msg)
  503. def process_business_card(image_file):
  504. """
  505. 处理名片图片并提取信息
  506. Args:
  507. image_file (FileStorage): 上传的名片图片文件
  508. Returns:
  509. dict: 处理结果,包含提取的信息和状态
  510. """
  511. minio_path = None
  512. try:
  513. # 读取图片数据
  514. image_data = image_file.read()
  515. image_file.seek(0) # 重置文件指针以便后续读取
  516. try:
  517. # 优先使用 Qwen 2.5 VL Plus 模型直接从图像提取信息
  518. try:
  519. logging.info("尝试使用 Qwen 2.5 VL Plus 模型解析名片")
  520. extracted_data = parse_text_with_qwen25VLplus(image_data)
  521. logging.info("成功使用 Qwen 2.5 VL Plus 模型解析名片")
  522. except Exception as qwen_error:
  523. logging.warning(f"Qwen 模型解析失败,错误原因: {str(qwen_error)}")
  524. # extracted_data = extract_text_from_image(image_data)
  525. except Exception as e:
  526. return {
  527. 'code': 500,
  528. 'success': False,
  529. 'message': f"名片解析失败: {str(e)}",
  530. 'data': None
  531. }
  532. try:
  533. # 生成唯一的文件名
  534. file_ext = os.path.splitext(image_file.filename)[1].lower()
  535. if not file_ext:
  536. file_ext = '.jpg' # 默认扩展名
  537. unique_filename = f"{uuid.uuid4().hex}{file_ext}"
  538. minio_path = f"{unique_filename}"
  539. # 尝试上传到MinIO
  540. minio_client = get_minio_client()
  541. if minio_client:
  542. try:
  543. # 上传文件
  544. logging.info(f"上传文件到MinIO: {minio_path}")
  545. minio_client.put_object(
  546. Bucket=minio_bucket,
  547. Key=minio_path,
  548. Body=image_file,
  549. ContentType=image_file.content_type
  550. )
  551. logging.info(f"图片已上传到MinIO: {minio_path}")
  552. except Exception as upload_err:
  553. logging.error(f"上传文件到MinIO时出错: {str(upload_err)}")
  554. # 即使上传失败,仍继续处理,但路径为None
  555. minio_path = None
  556. else:
  557. minio_path = None
  558. logging.warning("MinIO客户端未初始化,图片未上传")
  559. except Exception as e:
  560. logging.error(f"上传图片到MinIO失败: {str(e)}", exc_info=True)
  561. minio_path = None
  562. try:
  563. # 保存到数据库
  564. business_card = BusinessCard(
  565. name_zh=extracted_data.get('name_zh', ''),
  566. name_en=extracted_data.get('name_en', ''),
  567. title_zh=extracted_data.get('title_zh', ''),
  568. title_en=extracted_data.get('title_en', ''),
  569. mobile=extracted_data.get('mobile', ''),
  570. phone=extracted_data.get('phone', ''),
  571. email=extracted_data.get('email', ''),
  572. hotel_zh=extracted_data.get('hotel_zh', ''),
  573. hotel_en=extracted_data.get('hotel_en', ''),
  574. address_zh=extracted_data.get('address_zh', ''),
  575. address_en=extracted_data.get('address_en', ''),
  576. postal_code_zh=extracted_data.get('postal_code_zh', ''),
  577. postal_code_en=extracted_data.get('postal_code_en', ''),
  578. brand_zh=extracted_data.get('brand_zh', ''),
  579. brand_en=extracted_data.get('brand_en', ''),
  580. affiliation_zh=extracted_data.get('affiliation_zh', ''),
  581. affiliation_en=extracted_data.get('affiliation_en', ''),
  582. image_path=minio_path, # 存储相对路径
  583. career_path=extracted_data.get('career_path', []), # 添加职业轨迹
  584. brand_group=extracted_data.get('brand_group', ''), # 添加品牌组合
  585. status='active',
  586. updated_by='system'
  587. )
  588. db.session.add(business_card)
  589. db.session.commit()
  590. logging.info(f"名片信息已保存到数据库,ID: {business_card.id}")
  591. return {
  592. 'code': 200,
  593. 'success': True,
  594. 'message': '名片解析成功',
  595. 'data': business_card.to_dict()
  596. }
  597. except Exception as e:
  598. db.session.rollback()
  599. error_msg = f"保存名片信息到数据库失败: {str(e)}"
  600. logging.error(error_msg, exc_info=True)
  601. # 即使数据库操作失败,仍返回提取的信息
  602. return {
  603. 'code': 500,
  604. 'success': False,
  605. 'message': error_msg,
  606. 'data': {
  607. 'id': None,
  608. 'name_zh': extracted_data.get('name_zh', ''),
  609. 'name_en': extracted_data.get('name_en', ''),
  610. 'title_zh': extracted_data.get('title_zh', ''),
  611. 'title_en': extracted_data.get('title_en', ''),
  612. 'mobile': extracted_data.get('mobile', ''),
  613. 'phone': extracted_data.get('phone', ''),
  614. 'email': extracted_data.get('email', ''),
  615. 'hotel_zh': extracted_data.get('hotel_zh', ''),
  616. 'hotel_en': extracted_data.get('hotel_en', ''),
  617. 'address_zh': extracted_data.get('address_zh', ''),
  618. 'address_en': extracted_data.get('address_en', ''),
  619. 'postal_code_zh': extracted_data.get('postal_code_zh', ''),
  620. 'postal_code_en': extracted_data.get('postal_code_en', ''),
  621. 'brand_zh': extracted_data.get('brand_zh', ''),
  622. 'brand_en': extracted_data.get('brand_en', ''),
  623. 'affiliation_zh': extracted_data.get('affiliation_zh', ''),
  624. 'affiliation_en': extracted_data.get('affiliation_en', ''),
  625. 'image_path': minio_path, # 返回相对路径
  626. 'career_path': extracted_data.get('career_path', []), # 添加职业轨迹
  627. 'brand_group': extracted_data.get('brand_group', ''), # 添加品牌组合
  628. 'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  629. 'updated_at': None,
  630. 'updated_by': 'system',
  631. 'status': 'active'
  632. }
  633. }
  634. except Exception as e:
  635. db.session.rollback()
  636. error_msg = f"名片处理失败: {str(e)}"
  637. logging.error(error_msg, exc_info=True)
  638. return {
  639. 'code': 500,
  640. 'success': False,
  641. 'message': error_msg,
  642. 'data': None
  643. }
  644. def update_business_card(card_id, data):
  645. """
  646. 更新名片信息
  647. Args:
  648. card_id (int): 名片记录ID
  649. data (dict): 包含要更新的字段的字典
  650. Returns:
  651. dict: 包含操作结果和更新后的名片信息
  652. """
  653. try:
  654. # 查找要更新的名片记录
  655. card = BusinessCard.query.get(card_id)
  656. if not card:
  657. return {
  658. 'code': 500,
  659. 'success': False,
  660. 'message': f'未找到ID为{card_id}的名片记录',
  661. 'data': None
  662. }
  663. # 更新名片信息
  664. card.name_zh = data.get('name_zh', card.name_zh)
  665. card.name_en = data.get('name_en', card.name_en)
  666. card.title_zh = data.get('title_zh', card.title_zh)
  667. card.title_en = data.get('title_en', card.title_en)
  668. card.mobile = data.get('mobile', card.mobile)
  669. card.phone = data.get('phone', card.phone)
  670. card.email = data.get('email', card.email)
  671. card.hotel_zh = data.get('hotel_zh', card.hotel_zh)
  672. card.hotel_en = data.get('hotel_en', card.hotel_en)
  673. card.address_zh = data.get('address_zh', card.address_zh)
  674. card.address_en = data.get('address_en', card.address_en)
  675. card.postal_code_zh = data.get('postal_code_zh', card.postal_code_zh)
  676. card.postal_code_en = data.get('postal_code_en', card.postal_code_en)
  677. card.brand_zh = data.get('brand_zh', card.brand_zh)
  678. card.brand_en = data.get('brand_en', card.brand_en)
  679. card.affiliation_zh = data.get('affiliation_zh', card.affiliation_zh)
  680. card.affiliation_en = data.get('affiliation_en', card.affiliation_en)
  681. card.career_path = data.get('career_path', card.career_path) # 更新职业轨迹
  682. card.brand_group = data.get('brand_group', card.brand_group) # 更新品牌组合
  683. card.updated_by = data.get('updated_by', 'user') # 可以根据实际情况修改为当前用户
  684. # 保存更新
  685. db.session.commit()
  686. # 更新成功后,更新Neo4j图数据库中的人才-酒店关系
  687. try:
  688. from app.services.neo4j_driver import neo4j_driver
  689. from app.core.graph.graph_operations import create_or_get_node
  690. # 获取当前时间
  691. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  692. # 创建或更新人才节点
  693. talent_properties = {
  694. 'pg_id': card_id, # PostgreSQL数据库中的ID
  695. 'name_zh': card.name_zh, # 中文姓名
  696. 'name_en': card.name_en, # 英文姓名
  697. 'mobile': card.mobile, # 手机号码
  698. 'email': card.email, # 电子邮箱
  699. 'updated_at': current_time # 更新时间
  700. }
  701. talent_node_id = create_or_get_node('talent', **talent_properties)
  702. # 如果有酒店信息,创建或更新酒店节点
  703. if card.hotel_zh or card.hotel_en:
  704. hotel_properties = {
  705. 'hotel_zh': card.hotel_zh, # 酒店中文名称
  706. 'hotel_en': card.hotel_en, # 酒店英文名称
  707. 'updated_at': current_time # 更新时间
  708. }
  709. hotel_node_id = create_or_get_node('hotel', **hotel_properties)
  710. # 创建或更新人才与酒店之间的WORK_FOR关系
  711. if talent_node_id and hotel_node_id:
  712. # 构建Cypher查询以创建或更新关系
  713. cypher_query = """
  714. MATCH (t:talent), (h:hotel)
  715. WHERE id(t) = $talent_id AND id(h) = $hotel_id
  716. MERGE (t)-[r:WORKS_FOR]->(h)
  717. SET r.title_zh = $title_zh,
  718. r.title_en = $title_en,
  719. r.updated_at = $updated_at
  720. RETURN r
  721. """
  722. with neo4j_driver.get_session() as session:
  723. session.run(
  724. cypher_query,
  725. talent_id=talent_node_id,
  726. hotel_id=hotel_node_id,
  727. title_zh=card.title_zh,
  728. title_en=card.title_en,
  729. updated_at=current_time
  730. )
  731. logging.info(f"已成功更新人才(ID:{talent_node_id})与酒店(ID:{hotel_node_id})的WORK_FOR关系")
  732. logging.info(f"Neo4j图数据库关系更新成功")
  733. except Exception as e:
  734. logging.error(f"更新Neo4j图数据库关系失败: {str(e)}", exc_info=True)
  735. # 不因为图数据库更新失败而影响PostgreSQL数据库的更新结果
  736. return {
  737. 'code': 200,
  738. 'success': True,
  739. 'message': '名片信息已更新',
  740. 'data': card.to_dict()
  741. }
  742. except Exception as e:
  743. db.session.rollback()
  744. error_msg = f"更新名片信息失败: {str(e)}"
  745. logging.error(error_msg, exc_info=True)
  746. return {
  747. 'code': 500,
  748. 'success': False,
  749. 'message': error_msg,
  750. 'data': None
  751. }
  752. def get_business_cards():
  753. """
  754. 获取所有名片记录列表
  755. Returns:
  756. dict: 包含操作结果和名片列表
  757. """
  758. try:
  759. # 查询所有名片记录
  760. cards = BusinessCard.query.all()
  761. # 将所有记录转换为字典格式
  762. cards_data = [card.to_dict() for card in cards]
  763. return {
  764. 'code': 200,
  765. 'success': True,
  766. 'message': '获取名片列表成功',
  767. 'data': cards_data
  768. }
  769. except Exception as e:
  770. error_msg = f"获取名片列表失败: {str(e)}"
  771. logging.error(error_msg, exc_info=True)
  772. return {
  773. 'code': 500,
  774. 'success': False,
  775. 'message': error_msg,
  776. 'data': []
  777. }
  778. def update_business_card_status(card_id, status):
  779. """
  780. 更新名片状态(激活/禁用)
  781. Args:
  782. card_id (int): 名片记录ID
  783. status (str): 新状态,'active'或'inactive'
  784. Returns:
  785. dict: 包含操作结果和更新后的名片信息
  786. """
  787. try:
  788. # 查找要更新的名片记录
  789. card = BusinessCard.query.get(card_id)
  790. if not card:
  791. return {
  792. 'code': 500,
  793. 'success': False,
  794. 'message': f'未找到ID为{card_id}的名片记录',
  795. 'data': None
  796. }
  797. # 验证状态值
  798. if status not in ['active', 'inactive']:
  799. return {
  800. 'code': 500,
  801. 'success': False,
  802. 'message': f'无效的状态值: {status},必须为 active 或 inactive',
  803. 'data': None
  804. }
  805. # 更新状态
  806. card.status = status
  807. card.updated_at = datetime.now()
  808. card.updated_by = 'system' # 可以根据实际情况修改为当前用户
  809. # 保存更新
  810. db.session.commit()
  811. return {
  812. 'code': 200,
  813. 'success': True,
  814. 'message': f'名片状态已更新为: {status}',
  815. 'data': card.to_dict()
  816. }
  817. except Exception as e:
  818. db.session.rollback()
  819. error_msg = f"更新名片状态失败: {str(e)}"
  820. logging.error(error_msg, exc_info=True)
  821. return {
  822. 'code': 500,
  823. 'success': False,
  824. 'message': error_msg,
  825. 'data': None
  826. }
  827. def create_talent_tag(tag_data):
  828. """
  829. 创建人才标签节点
  830. Args:
  831. tag_data: 包含标签信息的字典,包括:
  832. - name: 标签名称
  833. - category: 标签分类
  834. - description: 标签描述
  835. - status: 启用状态
  836. Returns:
  837. dict: 操作结果字典
  838. """
  839. try:
  840. from app.services.neo4j_driver import neo4j_driver
  841. # 验证必要参数存在
  842. if not tag_data or 'name' not in tag_data or not tag_data['name']:
  843. return {
  844. 'code': 400,
  845. 'success': False,
  846. 'message': '标签名称为必填项',
  847. 'data': None
  848. }
  849. # 准备节点属性
  850. tag_properties = {
  851. 'name': tag_data.get('name'),
  852. 'category': tag_data.get('category', '未分类'),
  853. 'describe': tag_data.get('description', ''), # 使用describe与现有系统保持一致
  854. 'status': tag_data.get('status', 'active'),
  855. 'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  856. }
  857. # 生成标签的英文名(可选)
  858. from app.core.graph.graph_operations import create_or_get_node
  859. # 如果提供了名称,尝试获取英文翻译
  860. if 'name' in tag_data and tag_data['name']:
  861. try:
  862. from app.api.data_interface.routes import translate_and_parse
  863. en_name = translate_and_parse(tag_data['name'])
  864. tag_properties['en_name'] = en_name[0] if en_name and isinstance(en_name, list) else ''
  865. except Exception as e:
  866. logging.warning(f"获取标签英文名失败: {str(e)}")
  867. tag_properties['en_name'] = ''
  868. # 创建节点
  869. node_id = create_or_get_node('data_label', **tag_properties)
  870. if node_id:
  871. return {
  872. 'code': 200,
  873. 'success': True,
  874. 'message': '人才标签创建成功',
  875. 'data': {
  876. 'id': node_id,
  877. **tag_properties
  878. }
  879. }
  880. else:
  881. return {
  882. 'code': 500,
  883. 'success': False,
  884. 'message': '人才标签创建失败',
  885. 'data': None
  886. }
  887. except Exception as e:
  888. logging.error(f"创建人才标签失败: {str(e)}", exc_info=True)
  889. return {
  890. 'code': 500,
  891. 'success': False,
  892. 'message': f'创建人才标签失败: {str(e)}',
  893. 'data': None
  894. }
  895. def get_talent_tag_list():
  896. """
  897. 从Neo4j图数据库获取人才标签列表
  898. Returns:
  899. dict: 包含操作结果和标签列表的字典
  900. """
  901. try:
  902. from app.services.neo4j_driver import neo4j_driver
  903. # 构建Cypher查询语句,获取分类为talent的标签
  904. query = """
  905. MATCH (n:data_label)
  906. WHERE n.category CONTAINS 'talent' OR n.category CONTAINS '人才'
  907. RETURN id(n) as id, n.name as name, n.en_name as en_name,
  908. n.category as category, n.describe as description,
  909. n.status as status, n.time as time
  910. ORDER BY n.time DESC
  911. """
  912. # 执行查询
  913. tags = []
  914. with neo4j_driver.get_session() as session:
  915. result = session.run(query)
  916. # 处理查询结果
  917. for record in result:
  918. tag = {
  919. 'id': record['id'],
  920. 'name': record['name'],
  921. 'en_name': record['en_name'],
  922. 'category': record['category'],
  923. 'description': record['description'],
  924. 'status': record['status'],
  925. 'time': record['time']
  926. }
  927. tags.append(tag)
  928. return {
  929. 'code': 200,
  930. 'success': True,
  931. 'message': '获取人才标签列表成功',
  932. 'data': tags
  933. }
  934. except Exception as e:
  935. error_msg = f"获取人才标签列表失败: {str(e)}"
  936. logging.error(error_msg, exc_info=True)
  937. return {
  938. 'code': 500,
  939. 'success': False,
  940. 'message': error_msg,
  941. 'data': []
  942. }
  943. def update_talent_tag(tag_id, tag_data):
  944. """
  945. 更新人才标签节点属性
  946. Args:
  947. tag_id: 标签节点ID
  948. tag_data: 包含更新信息的字典,可能包括:
  949. - name: 标签名称
  950. - category: 标签分类
  951. - description: 标签描述
  952. - status: 启用状态
  953. Returns:
  954. dict: 操作结果字典
  955. """
  956. try:
  957. from app.services.neo4j_driver import neo4j_driver
  958. # 准备要更新的属性
  959. update_properties = {}
  960. # 检查并添加需要更新的属性
  961. if 'name' in tag_data and tag_data['name']:
  962. update_properties['name'] = tag_data['name']
  963. # 如果名称更新了,尝试更新英文名称
  964. try:
  965. from app.api.data_interface.routes import translate_and_parse
  966. en_name = translate_and_parse(tag_data['name'])
  967. update_properties['en_name'] = en_name[0] if en_name and isinstance(en_name, list) else ''
  968. except Exception as e:
  969. logging.warning(f"更新标签英文名失败: {str(e)}")
  970. if 'category' in tag_data and tag_data['category']:
  971. update_properties['category'] = tag_data['category']
  972. if 'description' in tag_data:
  973. update_properties['describe'] = tag_data['description']
  974. if 'status' in tag_data:
  975. update_properties['status'] = tag_data['status']
  976. # 添加更新时间
  977. update_properties['time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  978. # 如果没有可更新的属性,返回错误
  979. if not update_properties:
  980. return {
  981. 'code': 400,
  982. 'success': False,
  983. 'message': '未提供任何可更新的属性',
  984. 'data': None
  985. }
  986. # 构建更新的Cypher查询
  987. set_clauses = []
  988. params = {'nodeId': tag_id}
  989. for key, value in update_properties.items():
  990. param_name = f"param_{key}"
  991. set_clauses.append(f"n.{key} = ${param_name}")
  992. params[param_name] = value
  993. set_clause = ", ".join(set_clauses)
  994. query = f"""
  995. MATCH (n:data_label)
  996. WHERE id(n) = $nodeId
  997. SET {set_clause}
  998. RETURN id(n) as id, n.name as name, n.en_name as en_name,
  999. n.category as category, n.describe as description,
  1000. n.status as status, n.time as time
  1001. """
  1002. # 执行更新查询
  1003. with neo4j_driver.get_session() as session:
  1004. result = session.run(query, **params)
  1005. record = result.single()
  1006. if not record:
  1007. return {
  1008. 'code': 404,
  1009. 'success': False,
  1010. 'message': f'未找到ID为{tag_id}的标签',
  1011. 'data': None
  1012. }
  1013. # 提取更新后的标签信息
  1014. updated_tag = {
  1015. 'id': record['id'],
  1016. 'name': record['name'],
  1017. 'en_name': record['en_name'],
  1018. 'category': record['category'],
  1019. 'description': record['description'],
  1020. 'status': record['status'],
  1021. 'time': record['time']
  1022. }
  1023. return {
  1024. 'code': 200,
  1025. 'success': True,
  1026. 'message': '人才标签更新成功',
  1027. 'data': updated_tag
  1028. }
  1029. except Exception as e:
  1030. error_msg = f"更新人才标签失败: {str(e)}"
  1031. logging.error(error_msg, exc_info=True)
  1032. return {
  1033. 'code': 500,
  1034. 'success': False,
  1035. 'message': error_msg,
  1036. 'data': None
  1037. }
  1038. def delete_talent_tag(tag_id):
  1039. """
  1040. 删除人才标签节点及其相关关系
  1041. Args:
  1042. tag_id: 标签节点ID
  1043. Returns:
  1044. dict: 操作结果字典
  1045. """
  1046. try:
  1047. from app.services.neo4j_driver import neo4j_driver
  1048. # 首先获取要删除的标签信息,以便在成功后返回
  1049. get_query = """
  1050. MATCH (n:data_label)
  1051. WHERE id(n) = $nodeId
  1052. RETURN id(n) as id, n.name as name, n.en_name as en_name,
  1053. n.category as category, n.describe as description,
  1054. n.status as status, n.time as time
  1055. """
  1056. # 构建删除节点和关系的Cypher查询
  1057. delete_query = """
  1058. MATCH (n:data_label)
  1059. WHERE id(n) = $nodeId
  1060. OPTIONAL MATCH (n)-[r]-()
  1061. DELETE r, n
  1062. RETURN count(n) AS deleted
  1063. """
  1064. # 执行查询
  1065. tag_info = None
  1066. with neo4j_driver.get_session() as session:
  1067. # 先获取标签信息
  1068. result = session.run(get_query, nodeId=tag_id)
  1069. record = result.single()
  1070. if not record:
  1071. return {
  1072. 'code': 404,
  1073. 'success': False,
  1074. 'message': f'未找到ID为{tag_id}的标签',
  1075. 'data': None
  1076. }
  1077. # 保存标签信息用于返回
  1078. tag_info = {
  1079. 'id': record['id'],
  1080. 'name': record['name'],
  1081. 'en_name': record['en_name'],
  1082. 'category': record['category'],
  1083. 'description': record['description'],
  1084. 'status': record['status'],
  1085. 'time': record['time']
  1086. }
  1087. # 执行删除操作
  1088. delete_result = session.run(delete_query, nodeId=tag_id)
  1089. deleted = delete_result.single()['deleted']
  1090. if deleted > 0:
  1091. return {
  1092. 'code': 200,
  1093. 'success': True,
  1094. 'message': '人才标签删除成功',
  1095. 'data': tag_info
  1096. }
  1097. else:
  1098. return {
  1099. 'code': 404,
  1100. 'success': False,
  1101. 'message': f'未能删除ID为{tag_id}的标签',
  1102. 'data': None
  1103. }
  1104. except Exception as e:
  1105. error_msg = f"删除人才标签失败: {str(e)}"
  1106. logging.error(error_msg, exc_info=True)
  1107. return {
  1108. 'code': 500,
  1109. 'success': False,
  1110. 'message': error_msg,
  1111. 'data': None
  1112. }
  1113. def query_neo4j_graph(query_requirement):
  1114. """
  1115. 查询Neo4j图数据库,通过Deepseek API生成Cypher脚本
  1116. Args:
  1117. query_requirement (str): 查询需求描述
  1118. Returns:
  1119. dict: 包含查询结果的字典,JSON格式
  1120. """
  1121. try:
  1122. # 导入必要的模块
  1123. from app.services.neo4j_driver import neo4j_driver
  1124. import requests
  1125. import json
  1126. # Deepseek API配置
  1127. api_key = DEEPSEEK_API_KEY
  1128. api_url = DEEPSEEK_API_URL
  1129. # 步骤1: 从Neo4j获取所有标签列表
  1130. logging.info("第一步:从Neo4j获取人才类别的标签列表")
  1131. all_labels_query = """
  1132. MATCH (dl:data_label)
  1133. WHERE dl.category CONTAINS '人才' OR dl.category CONTAINS 'talent'
  1134. RETURN dl.name as name
  1135. """
  1136. all_labels = []
  1137. with neo4j_driver.get_session() as session:
  1138. result = session.run(all_labels_query)
  1139. for record in result:
  1140. all_labels.append(record['name'])
  1141. logging.info(f"获取到{len(all_labels)}个人才标签: {all_labels}")
  1142. # 步骤2: 使用Deepseek判断查询需求中的关键信息与标签的对应关系
  1143. logging.info("第二步:调用Deepseek API匹配查询需求与标签")
  1144. # 构建所有标签的JSON字符串
  1145. labels_json = json.dumps(all_labels, ensure_ascii=False)
  1146. # 构建匹配标签的提示语
  1147. matching_prompt = f"""
  1148. 请分析以下查询需求,并从标签列表中找出与查询需求相关的标签。
  1149. ## 查询需求
  1150. {query_requirement}
  1151. ## 可用标签列表
  1152. {labels_json}
  1153. ## 输出要求
  1154. 1. 请以JSON数组格式返回匹配的标签名称列表,格式如: ["标签1", "标签2", "标签3"]
  1155. 2. 只返回标签名称数组,不要包含任何解释或其他文本
  1156. 3. 如果没有找到匹配的标签,请返回空数组 []
  1157. """
  1158. # 调用Deepseek API匹配标签
  1159. headers = {
  1160. "Authorization": f"Bearer {api_key}",
  1161. "Content-Type": "application/json"
  1162. }
  1163. payload = {
  1164. "model": "deepseek-chat",
  1165. "messages": [
  1166. {"role": "system", "content": "你是一个专业的文本分析和匹配专家。"},
  1167. {"role": "user", "content": matching_prompt}
  1168. ],
  1169. "temperature": 0.1,
  1170. "response_format": {"type": "json_object"}
  1171. }
  1172. logging.info("发送请求到Deepseek API匹配标签:"+matching_prompt)
  1173. response = requests.post(api_url, headers=headers, json=payload, timeout=30)
  1174. response.raise_for_status()
  1175. # 解析API响应
  1176. result = response.json()
  1177. matching_content = result.get("choices", [{}])[0].get("message", {}).get("content", "[]")
  1178. # 提取JSON数组
  1179. try:
  1180. # 尝试直接解析返回结果,预期格式为 ["新开酒店经验", "五星级酒店", "总经理"]
  1181. logging.info(f"Deepseek返回的匹配内容: {matching_content}")
  1182. # 如果返回的是JSON字符串,先去除可能的前后缀文本
  1183. if isinstance(matching_content, str):
  1184. # 查找JSON数组的开始和结束位置
  1185. start_idx = matching_content.find('[')
  1186. end_idx = matching_content.rfind(']') + 1
  1187. if start_idx >= 0 and end_idx > start_idx:
  1188. json_str = matching_content[start_idx:end_idx]
  1189. matched_labels = json.loads(json_str)
  1190. else:
  1191. matched_labels = []
  1192. else:
  1193. matched_labels = []
  1194. # 确保结果是字符串列表
  1195. if matched_labels and all(isinstance(item, str) for item in matched_labels):
  1196. logging.info(f"成功解析到标签列表: {matched_labels}")
  1197. else:
  1198. logging.warning("解析结果不是预期的字符串列表格式,将使用空列表")
  1199. matched_labels = []
  1200. except json.JSONDecodeError as e:
  1201. logging.error(f"JSON解析错误: {str(e)}")
  1202. matched_labels = []
  1203. except Exception as e:
  1204. logging.error(f"解析匹配标签时出错: {str(e)}")
  1205. matched_labels = []
  1206. logging.info(f"匹配到的标签: {matched_labels}")
  1207. # 如果没有匹配到标签,返回空结果
  1208. if not matched_labels:
  1209. return {
  1210. 'code': 200,
  1211. 'success': True,
  1212. 'message': '未找到与查询需求匹配的标签',
  1213. 'query': '',
  1214. 'data': []
  1215. }
  1216. # 步骤3: 构建Cypher生成提示文本
  1217. logging.info("第三步:构建提示文本生成Cypher查询语句")
  1218. # 将匹配的标签转换为字符串
  1219. matched_labels_str = ", ".join([f"'{label}'" for label in matched_labels])
  1220. # 构建生成Cypher的提示语
  1221. cypher_prompt = f"""
  1222. 请根据以下Neo4j图数据库结构和已匹配的标签,生成一个Cypher查询脚本。
  1223. ## 图数据库结构
  1224. ### 节点
  1225. 1. talent - 人才节点
  1226. 属性: pg_id(PostgreSQL数据库ID), name_zh(中文姓名), name_en(英文姓名),
  1227. mobile(手机号码), email(电子邮箱), updated_at(更新时间)
  1228. 2. data_label - 人才标签节点
  1229. ### 关系
  1230. BELONGS_TO - 从属关系
  1231. (talent)-[BELONGS_TO]->(data_label) - 人才属于某标签
  1232. ## 匹配的标签列表
  1233. [{matched_labels_str}]
  1234. ## 查询需求
  1235. {query_requirement}
  1236. ## 输出要求
  1237. 1. 只输出有效的Cypher查询语句,不要包含任何解释或注释
  1238. 2. 确保return语句中包含talent节点属性
  1239. 3. 尽量利用图数据库的特性来优化查询效率
  1240. 4. 使用WITH子句和COLLECT函数收集标签,确保查询到同时拥有所有标签的人才
  1241. 注意:请直接返回Cypher查询语句,无需任何其他文本。
  1242. 以下是一个示例:
  1243. 假设匹配的标签是 ['五星级酒店', '新开酒店经验', '总经理']
  1244. 生成的Cypher查询语句应该是:
  1245. MATCH (t:talent)-[:BELONGS_TO]->(dl:data_label)
  1246. WHERE dl.name IN ['五星级酒店', '新开酒店经验', '总经理']
  1247. WITH t, COLLECT(DISTINCT dl.name) AS labels
  1248. WHERE size(labels) = 3
  1249. RETURN t.pg_id as pg_id, t.name_zh as name_zh, t.name_en as name_en, t.mobile as mobile, t.email as email, t.updated_at as updated_at
  1250. """
  1251. # 调用Deepseek API生成Cypher脚本
  1252. payload = {
  1253. "model": "deepseek-chat",
  1254. "messages": [
  1255. {"role": "system", "content": "你是一个专业的Neo4j Cypher查询专家。"},
  1256. {"role": "user", "content": cypher_prompt}
  1257. ],
  1258. "temperature": 0.1
  1259. }
  1260. logging.info("发送请求到Deepseek API生成Cypher脚本")
  1261. response = requests.post(api_url, headers=headers, json=payload, timeout=30)
  1262. response.raise_for_status()
  1263. # 解析API响应
  1264. result = response.json()
  1265. cypher_script = result.get("choices", [{}])[0].get("message", {}).get("content", "")
  1266. # 清理Cypher脚本,移除不必要的markdown格式或注释
  1267. cypher_script = cypher_script.strip()
  1268. if cypher_script.startswith("```cypher"):
  1269. cypher_script = cypher_script[9:]
  1270. elif cypher_script.startswith("```"):
  1271. cypher_script = cypher_script[3:]
  1272. if cypher_script.endswith("```"):
  1273. cypher_script = cypher_script[:-3]
  1274. cypher_script = cypher_script.strip()
  1275. logging.info(f"生成的Cypher脚本: {cypher_script}")
  1276. # 步骤4: 执行Cypher脚本
  1277. logging.info("第四步:执行Cypher脚本并返回结果")
  1278. with neo4j_driver.get_session() as session:
  1279. result = session.run(cypher_script)
  1280. records = [record.data() for record in result]
  1281. # 构建查询结果
  1282. response_data = {
  1283. 'code': 200,
  1284. 'success': True,
  1285. 'message': '查询成功执行',
  1286. 'query': cypher_script,
  1287. 'matched_labels': matched_labels,
  1288. 'data': records
  1289. }
  1290. return response_data
  1291. except requests.exceptions.HTTPError as e:
  1292. error_msg = f"调用Deepseek API失败: {str(e)}"
  1293. logging.error(error_msg)
  1294. if hasattr(e, 'response') and e.response:
  1295. logging.error(f"错误状态码: {e.response.status_code}")
  1296. logging.error(f"错误内容: {e.response.text}")
  1297. return {
  1298. 'code': 500,
  1299. 'success': False,
  1300. 'message': error_msg,
  1301. 'data': []
  1302. }
  1303. except Exception as e:
  1304. error_msg = f"查询Neo4j图数据库失败: {str(e)}"
  1305. logging.error(error_msg, exc_info=True)
  1306. return {
  1307. 'code': 500,
  1308. 'success': False,
  1309. 'message': error_msg,
  1310. 'data': []
  1311. }
  1312. def talent_get_tags(talent_id):
  1313. """
  1314. 根据talent ID获取人才节点关联的标签
  1315. Args:
  1316. talent_id (int): 人才节点pg_id
  1317. Returns:
  1318. dict: 包含人才ID和关联标签的字典,JSON格式
  1319. """
  1320. try:
  1321. # 导入必要的模块
  1322. from app.services.neo4j_driver import neo4j_driver
  1323. # 准备查询返回数据
  1324. response_data = {
  1325. 'code': 200,
  1326. 'success': True,
  1327. 'message': '获取人才标签成功',
  1328. 'data': []
  1329. }
  1330. # 构建Cypher查询语句,获取人才节点关联的标签
  1331. cypher_query = """
  1332. MATCH (t:talent)-[r:BELONGS_TO]->(tag:data_label)
  1333. WHERE t.pg_id = $talent_id
  1334. RETURN t.pg_id as talent_id, tag.name as tag_name
  1335. """
  1336. # 执行查询
  1337. with neo4j_driver.get_session() as session:
  1338. result = session.run(cypher_query, talent_id=int(talent_id))
  1339. records = list(result)
  1340. # 如果没有查询到标签,返回空数组
  1341. if not records:
  1342. response_data['message'] = f'人才pg_id {talent_id} 没有关联的标签'
  1343. return response_data
  1344. # 处理查询结果
  1345. for record in records:
  1346. talent_tag = {
  1347. 'talent': record['talent_id'],
  1348. 'tag': record['tag_name']
  1349. }
  1350. response_data['data'].append(talent_tag)
  1351. return response_data
  1352. except Exception as e:
  1353. error_msg = f"获取人才标签失败: {str(e)}"
  1354. logging.error(error_msg, exc_info=True)
  1355. return {
  1356. 'code': 500,
  1357. 'success': False,
  1358. 'message': error_msg,
  1359. 'data': []
  1360. }
  1361. def talent_update_tags(data):
  1362. """
  1363. 根据传入的JSON数据为人才节点创建与标签的BELONGS_TO关系
  1364. Args:
  1365. data (list): 包含talent和tag字段的对象列表
  1366. 例如: [
  1367. {"talent": 12345, "tag": "市场营销"},
  1368. {"talent": 12345, "tag": "酒店管理"}
  1369. ]
  1370. Returns:
  1371. dict: 操作结果和状态信息
  1372. """
  1373. try:
  1374. # 导入必要的模块
  1375. from app.services.neo4j_driver import neo4j_driver
  1376. # 验证输入参数
  1377. if not isinstance(data, list):
  1378. return {
  1379. 'code': 400,
  1380. 'success': False,
  1381. 'message': '参数格式错误,需要JSON数组',
  1382. 'data': None
  1383. }
  1384. if len(data) == 0:
  1385. return {
  1386. 'code': 400,
  1387. 'success': False,
  1388. 'message': '数据列表为空',
  1389. 'data': None
  1390. }
  1391. # 获取当前时间
  1392. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  1393. # 成功和失败计数
  1394. success_count = 0
  1395. failed_items = []
  1396. # 按talent分组处理数据
  1397. talent_tags = {}
  1398. for item in data:
  1399. # 验证每个项目的格式
  1400. if not isinstance(item, dict) or 'talent' not in item or 'tag' not in item:
  1401. failed_items.append(item)
  1402. continue
  1403. talent_id = item.get('talent')
  1404. tag_name = item.get('tag')
  1405. # 验证talent_id和tag_name的值
  1406. if not talent_id or not tag_name or not isinstance(tag_name, str):
  1407. failed_items.append(item)
  1408. continue
  1409. # 按talent_id分组
  1410. if talent_id not in talent_tags:
  1411. talent_tags[talent_id] = []
  1412. talent_tags[talent_id].append(tag_name)
  1413. with neo4j_driver.get_session() as session:
  1414. # 处理每个talent及其标签
  1415. for talent_id, tags in talent_tags.items():
  1416. # 首先验证talent节点是否存在
  1417. check_talent_query = """
  1418. MATCH (t:talent)
  1419. WHERE t.pg_id = $talent_id
  1420. RETURN t
  1421. """
  1422. talent_result = session.run(check_talent_query, talent_id=int(talent_id))
  1423. if not talent_result.single():
  1424. # 该talent不存在,记录失败项并继续下一个talent
  1425. for tag in tags:
  1426. failed_items.append({'talent_pg_id': talent_id, 'tag': tag})
  1427. continue
  1428. # 首先清除所有现有的BELONGS_TO关系
  1429. clear_relations_query = """
  1430. MATCH (t:talent)-[r:BELONGS_TO]->(:data_label)
  1431. WHERE t.pg_id = $talent_id
  1432. DELETE r
  1433. RETURN count(r) as deleted_count
  1434. """
  1435. clear_result = session.run(clear_relations_query, talent_id=int(talent_id))
  1436. deleted_count = clear_result.single()['deleted_count']
  1437. logging.info(f"已删除talent_id={talent_id}的{deleted_count}个已有标签关系")
  1438. # 处理每个标签
  1439. for tag_name in tags:
  1440. try:
  1441. # 1. 查找或创建标签节点
  1442. # 先查找是否存在该标签
  1443. find_tag_query = """
  1444. MATCH (tag:data_label)
  1445. WHERE tag.name = $tag_name
  1446. RETURN id(tag) as tag_id
  1447. """
  1448. tag_result = session.run(find_tag_query, tag_name=tag_name)
  1449. tag_record = tag_result.single()
  1450. if tag_record:
  1451. tag_id = tag_record['tag_id']
  1452. else:
  1453. # 创建新标签
  1454. create_tag_query = """
  1455. CREATE (tag:data_label {name: $name, category: $category, updated_at: $updated_at})
  1456. RETURN id(tag) as tag_id
  1457. """
  1458. tag_result = session.run(
  1459. create_tag_query,
  1460. name=tag_name,
  1461. category='talent',
  1462. updated_at=current_time
  1463. )
  1464. tag_record = tag_result.single()
  1465. tag_id = tag_record['tag_id']
  1466. # 2. 创建人才与标签的BELONGS_TO关系
  1467. create_relation_query = """
  1468. MATCH (t:talent), (tag:data_label)
  1469. WHERE t.pg_id = $talent_id AND tag.name = $tag_name
  1470. CREATE (t)-[r:BELONGS_TO]->(tag)
  1471. SET r.created_at = $current_time
  1472. RETURN r
  1473. """
  1474. relation_result = session.run(
  1475. create_relation_query,
  1476. talent_id=int(talent_id),
  1477. tag_name=tag_name,
  1478. current_time=current_time
  1479. )
  1480. if relation_result.single():
  1481. success_count += 1
  1482. else:
  1483. failed_items.append({'talent_pg_id': talent_id, 'tag': tag_name})
  1484. except Exception as tag_error:
  1485. logging.error(f"为标签 {tag_name} 创建关系时出错: {str(tag_error)}")
  1486. failed_items.append({'talent_pg_id': talent_id, 'tag': tag_name})
  1487. # 返回结果
  1488. total_items = len(data)
  1489. if success_count == total_items:
  1490. return {
  1491. 'code': 200,
  1492. 'success': True,
  1493. 'message': f'成功创建或更新了 {success_count} 个标签关系',
  1494. 'data': {
  1495. 'success_count': success_count,
  1496. 'total_count': total_items,
  1497. 'failed_items': []
  1498. }
  1499. }
  1500. elif success_count > 0:
  1501. return {
  1502. 'code': 206, # Partial Content
  1503. 'success': True,
  1504. 'message': f'部分成功: 创建或更新了 {success_count}/{total_items} 个标签关系',
  1505. 'data': {
  1506. 'success_count': success_count,
  1507. 'total_count': total_items,
  1508. 'failed_items': failed_items
  1509. }
  1510. }
  1511. else:
  1512. return {
  1513. 'code': 500,
  1514. 'success': False,
  1515. 'message': '无法创建任何标签关系',
  1516. 'data': {
  1517. 'success_count': 0,
  1518. 'total_count': total_items,
  1519. 'failed_items': failed_items
  1520. }
  1521. }
  1522. except Exception as e:
  1523. error_msg = f"更新人才标签关系失败: {str(e)}"
  1524. logging.error(error_msg, exc_info=True)
  1525. return {
  1526. 'code': 500,
  1527. 'success': False,
  1528. 'message': error_msg,
  1529. 'data': None
  1530. }
  1531. def get_business_card(card_id):
  1532. """
  1533. 根据ID从PostgreSQL数据库中获取名片记录
  1534. Args:
  1535. card_id (int): 名片记录ID
  1536. Returns:
  1537. dict: 包含操作结果和名片信息的字典
  1538. """
  1539. try:
  1540. # 查询指定ID的名片记录
  1541. card = BusinessCard.query.get(card_id)
  1542. if not card:
  1543. return {
  1544. 'code': 404,
  1545. 'success': False,
  1546. 'message': f'未找到ID为{card_id}的名片记录',
  1547. 'data': None
  1548. }
  1549. # 将记录转换为字典格式返回
  1550. return {
  1551. 'code': 200,
  1552. 'success': True,
  1553. 'message': '获取名片记录成功',
  1554. 'data': card.to_dict()
  1555. }
  1556. except Exception as e:
  1557. error_msg = f"获取名片记录失败: {str(e)}"
  1558. logging.error(error_msg, exc_info=True)
  1559. return {
  1560. 'code': 500,
  1561. 'success': False,
  1562. 'message': error_msg,
  1563. 'data': None
  1564. }
  1565. # 酒店职位数据模型
  1566. class HotelPosition(db.Model):
  1567. __tablename__ = 'hotel_positions'
  1568. id = db.Column(db.Integer, primary_key=True, autoincrement=True)
  1569. department_zh = db.Column(db.String(10), nullable=False)
  1570. department_en = db.Column(db.String(50), nullable=False)
  1571. position_zh = db.Column(db.String(20), nullable=False)
  1572. position_en = db.Column(db.String(100), nullable=False)
  1573. position_abbr = db.Column(db.String(20), nullable=True)
  1574. level_zh = db.Column(db.String(10), nullable=False)
  1575. level_en = db.Column(db.String(30), nullable=False)
  1576. created_at = db.Column(db.DateTime, default=datetime.now, nullable=False)
  1577. updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
  1578. created_by = db.Column(db.String(50), default='system')
  1579. updated_by = db.Column(db.String(50), default='system')
  1580. status = db.Column(db.String(20), default='active')
  1581. def to_dict(self):
  1582. return {
  1583. 'id': self.id,
  1584. 'department_zh': self.department_zh,
  1585. 'department_en': self.department_en,
  1586. 'position_zh': self.position_zh,
  1587. 'position_en': self.position_en,
  1588. 'position_abbr': self.position_abbr,
  1589. 'level_zh': self.level_zh,
  1590. 'level_en': self.level_en,
  1591. 'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
  1592. 'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None,
  1593. 'created_by': self.created_by,
  1594. 'updated_by': self.updated_by,
  1595. 'status': self.status
  1596. }
  1597. def get_hotel_positions_list():
  1598. """
  1599. 获取酒店职位数据表的全部记录
  1600. Returns:
  1601. dict: 包含操作结果和酒店职位列表的字典
  1602. """
  1603. try:
  1604. # 查询所有酒店职位记录,按部门和职位排序
  1605. positions = HotelPosition.query.order_by(
  1606. HotelPosition.department_zh,
  1607. HotelPosition.position_zh
  1608. ).all()
  1609. # 将所有记录转换为字典格式
  1610. positions_data = [position.to_dict() for position in positions]
  1611. return {
  1612. 'code': 200,
  1613. 'success': True,
  1614. 'message': '获取酒店职位列表成功',
  1615. 'data': positions_data,
  1616. 'count': len(positions_data)
  1617. }
  1618. except Exception as e:
  1619. error_msg = f"获取酒店职位列表失败: {str(e)}"
  1620. logging.error(error_msg, exc_info=True)
  1621. return {
  1622. 'code': 500,
  1623. 'success': False,
  1624. 'message': error_msg,
  1625. 'data': [],
  1626. 'count': 0
  1627. }
  1628. def add_hotel_positions(position_data):
  1629. """
  1630. 新增酒店职位数据表记录
  1631. Args:
  1632. position_data (dict): 包含职位信息的字典,包括:
  1633. - department_zh: 部门中文名称 (必填)
  1634. - department_en: 部门英文名称 (必填)
  1635. - position_zh: 职位中文名称 (必填)
  1636. - position_en: 职位英文名称 (必填)
  1637. - position_abbr: 职位英文缩写 (可选)
  1638. - level_zh: 职级中文名称 (必填)
  1639. - level_en: 职级英文名称 (必填)
  1640. - created_by: 创建者 (可选,默认为'system')
  1641. - updated_by: 更新者 (可选,默认为'system')
  1642. - status: 状态 (可选,默认为'active')
  1643. Returns:
  1644. dict: 包含操作结果和创建的职位信息的字典
  1645. """
  1646. try:
  1647. # 验证必填字段
  1648. required_fields = ['department_zh', 'department_en', 'position_zh', 'position_en', 'level_zh', 'level_en']
  1649. missing_fields = []
  1650. for field in required_fields:
  1651. if field not in position_data or not position_data[field] or not position_data[field].strip():
  1652. missing_fields.append(field)
  1653. if missing_fields:
  1654. return {
  1655. 'code': 400,
  1656. 'success': False,
  1657. 'message': f'缺少必填字段: {", ".join(missing_fields)}',
  1658. 'data': None
  1659. }
  1660. # 检查是否已存在相同的职位记录(基于部门和职位的中文名称)
  1661. existing_position = HotelPosition.query.filter_by(
  1662. department_zh=position_data['department_zh'].strip(),
  1663. position_zh=position_data['position_zh'].strip()
  1664. ).first()
  1665. if existing_position:
  1666. return {
  1667. 'code': 409,
  1668. 'success': False,
  1669. 'message': f'职位记录已存在:{position_data["department_zh"]} - {position_data["position_zh"]}',
  1670. 'data': existing_position.to_dict()
  1671. }
  1672. # 创建新的职位记录
  1673. new_position = HotelPosition(
  1674. department_zh=position_data['department_zh'].strip(),
  1675. department_en=position_data['department_en'].strip(),
  1676. position_zh=position_data['position_zh'].strip(),
  1677. position_en=position_data['position_en'].strip(),
  1678. position_abbr=position_data.get('position_abbr', '').strip() if position_data.get('position_abbr') else None,
  1679. level_zh=position_data['level_zh'].strip(),
  1680. level_en=position_data['level_en'].strip(),
  1681. created_by=position_data.get('created_by', 'system'),
  1682. updated_by=position_data.get('updated_by', 'system'),
  1683. status=position_data.get('status', 'active')
  1684. )
  1685. # 保存到数据库
  1686. db.session.add(new_position)
  1687. db.session.commit()
  1688. logging.info(f"成功创建酒店职位记录,ID: {new_position.id}")
  1689. return {
  1690. 'code': 200,
  1691. 'success': True,
  1692. 'message': '酒店职位记录创建成功',
  1693. 'data': new_position.to_dict()
  1694. }
  1695. except Exception as e:
  1696. db.session.rollback()
  1697. error_msg = f"创建酒店职位记录失败: {str(e)}"
  1698. logging.error(error_msg, exc_info=True)
  1699. return {
  1700. 'code': 500,
  1701. 'success': False,
  1702. 'message': error_msg,
  1703. 'data': None
  1704. }
  1705. def update_hotel_positions(position_id, position_data):
  1706. """
  1707. 修改酒店职位数据表记录
  1708. Args:
  1709. position_id (int): 职位记录ID
  1710. position_data (dict): 包含要更新的职位信息的字典,可能包括:
  1711. - department_zh: 部门中文名称
  1712. - department_en: 部门英文名称
  1713. - position_zh: 职位中文名称
  1714. - position_en: 职位英文名称
  1715. - position_abbr: 职位英文缩写
  1716. - level_zh: 职级中文名称
  1717. - level_en: 职级英文名称
  1718. - updated_by: 更新者
  1719. - status: 状态
  1720. Returns:
  1721. dict: 包含操作结果和更新后的职位信息的字典
  1722. """
  1723. try:
  1724. # 查找要更新的职位记录
  1725. position = HotelPosition.query.get(position_id)
  1726. if not position:
  1727. return {
  1728. 'code': 404,
  1729. 'success': False,
  1730. 'message': f'未找到ID为{position_id}的职位记录',
  1731. 'data': None
  1732. }
  1733. # 检查是否有数据需要更新
  1734. if not position_data:
  1735. return {
  1736. 'code': 400,
  1737. 'success': False,
  1738. 'message': '请求数据为空',
  1739. 'data': None
  1740. }
  1741. # 如果要更新部门和职位名称,检查是否会与其他记录冲突
  1742. new_department_zh = position_data.get('department_zh', position.department_zh).strip() if position_data.get('department_zh') else position.department_zh
  1743. new_position_zh = position_data.get('position_zh', position.position_zh).strip() if position_data.get('position_zh') else position.position_zh
  1744. # 查找是否存在相同的职位记录(排除当前记录)
  1745. existing_position = HotelPosition.query.filter(
  1746. HotelPosition.id != position_id,
  1747. HotelPosition.department_zh == new_department_zh,
  1748. HotelPosition.position_zh == new_position_zh
  1749. ).first()
  1750. if existing_position:
  1751. return {
  1752. 'code': 409,
  1753. 'success': False,
  1754. 'message': f'职位记录已存在:{new_department_zh} - {new_position_zh}',
  1755. 'data': existing_position.to_dict()
  1756. }
  1757. # 更新职位信息
  1758. if 'department_zh' in position_data and position_data['department_zh']:
  1759. position.department_zh = position_data['department_zh'].strip()
  1760. if 'department_en' in position_data and position_data['department_en']:
  1761. position.department_en = position_data['department_en'].strip()
  1762. if 'position_zh' in position_data and position_data['position_zh']:
  1763. position.position_zh = position_data['position_zh'].strip()
  1764. if 'position_en' in position_data and position_data['position_en']:
  1765. position.position_en = position_data['position_en'].strip()
  1766. if 'position_abbr' in position_data:
  1767. # 处理position_abbr,可能为空字符串或None
  1768. if position_data['position_abbr'] and position_data['position_abbr'].strip():
  1769. position.position_abbr = position_data['position_abbr'].strip()
  1770. else:
  1771. position.position_abbr = None
  1772. if 'level_zh' in position_data and position_data['level_zh']:
  1773. position.level_zh = position_data['level_zh'].strip()
  1774. if 'level_en' in position_data and position_data['level_en']:
  1775. position.level_en = position_data['level_en'].strip()
  1776. if 'updated_by' in position_data:
  1777. position.updated_by = position_data['updated_by'] or 'system'
  1778. if 'status' in position_data:
  1779. position.status = position_data['status'] or 'active'
  1780. # 更新时间会自动设置(onupdate=datetime.now)
  1781. # 保存更新
  1782. db.session.commit()
  1783. logging.info(f"成功更新酒店职位记录,ID: {position.id}")
  1784. return {
  1785. 'code': 200,
  1786. 'success': True,
  1787. 'message': '酒店职位记录更新成功',
  1788. 'data': position.to_dict()
  1789. }
  1790. except Exception as e:
  1791. db.session.rollback()
  1792. error_msg = f"更新酒店职位记录失败: {str(e)}"
  1793. logging.error(error_msg, exc_info=True)
  1794. return {
  1795. 'code': 500,
  1796. 'success': False,
  1797. 'message': error_msg,
  1798. 'data': None
  1799. }
  1800. def query_hotel_positions(position_id):
  1801. """
  1802. 查找指定ID的酒店职位数据表记录
  1803. Args:
  1804. position_id (int): 职位记录ID
  1805. Returns:
  1806. dict: 包含操作结果和职位信息的字典
  1807. """
  1808. try:
  1809. # 根据ID查找职位记录
  1810. position = HotelPosition.query.get(position_id)
  1811. if not position:
  1812. return {
  1813. 'code': 404,
  1814. 'success': False,
  1815. 'message': f'未找到ID为{position_id}的职位记录',
  1816. 'data': None
  1817. }
  1818. # 返回找到的记录
  1819. return {
  1820. 'code': 200,
  1821. 'success': True,
  1822. 'message': '查找职位记录成功',
  1823. 'data': position.to_dict()
  1824. }
  1825. except Exception as e:
  1826. error_msg = f"查找职位记录失败: {str(e)}"
  1827. logging.error(error_msg, exc_info=True)
  1828. return {
  1829. 'code': 500,
  1830. 'success': False,
  1831. 'message': error_msg,
  1832. 'data': None
  1833. }
  1834. def delete_hotel_positions(position_id):
  1835. """
  1836. 删除指定ID的酒店职位数据表记录
  1837. Args:
  1838. position_id (int): 职位记录ID
  1839. Returns:
  1840. dict: 包含操作结果的字典
  1841. """
  1842. try:
  1843. # 根据ID查找要删除的职位记录
  1844. position = HotelPosition.query.get(position_id)
  1845. if not position:
  1846. return {
  1847. 'code': 404,
  1848. 'success': False,
  1849. 'message': f'未找到ID为{position_id}的职位记录',
  1850. 'data': None
  1851. }
  1852. # 保存被删除记录的信息,用于返回
  1853. deleted_position_info = position.to_dict()
  1854. # 执行删除操作
  1855. db.session.delete(position)
  1856. db.session.commit()
  1857. logging.info(f"成功删除酒店职位记录,ID: {position_id}")
  1858. return {
  1859. 'code': 200,
  1860. 'success': True,
  1861. 'message': '职位记录删除成功',
  1862. 'data': deleted_position_info
  1863. }
  1864. except Exception as e:
  1865. db.session.rollback()
  1866. error_msg = f"删除职位记录失败: {str(e)}"
  1867. logging.error(error_msg, exc_info=True)
  1868. return {
  1869. 'code': 500,
  1870. 'success': False,
  1871. 'message': error_msg,
  1872. 'data': None
  1873. }
  1874. # 酒店集团子品牌数据模型
  1875. class HotelGroupBrands(db.Model):
  1876. __tablename__ = 'hotel_group_brands'
  1877. id = db.Column(db.Integer, primary_key=True, autoincrement=True)
  1878. group_name_en = db.Column(db.String(60), nullable=False)
  1879. group_name_zh = db.Column(db.String(20), nullable=False)
  1880. brand_name_en = db.Column(db.String(40), nullable=False)
  1881. brand_name_zh = db.Column(db.String(40), nullable=False)
  1882. positioning_level_en = db.Column(db.String(20), nullable=False)
  1883. positioning_level_zh = db.Column(db.String(5), nullable=False)
  1884. created_at = db.Column(db.DateTime, default=datetime.now, nullable=False)
  1885. updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
  1886. created_by = db.Column(db.String(50), default='system')
  1887. updated_by = db.Column(db.String(50), default='system')
  1888. status = db.Column(db.String(20), default='active')
  1889. def to_dict(self):
  1890. return {
  1891. 'id': self.id,
  1892. 'group_name_en': self.group_name_en,
  1893. 'group_name_zh': self.group_name_zh,
  1894. 'brand_name_en': self.brand_name_en,
  1895. 'brand_name_zh': self.brand_name_zh,
  1896. 'positioning_level_en': self.positioning_level_en,
  1897. 'positioning_level_zh': self.positioning_level_zh,
  1898. 'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
  1899. 'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None,
  1900. 'created_by': self.created_by,
  1901. 'updated_by': self.updated_by,
  1902. 'status': self.status
  1903. }
  1904. def get_hotel_group_brands_list():
  1905. """
  1906. 获取酒店集团子品牌数据表的全部记录
  1907. Returns:
  1908. dict: 包含操作结果和酒店集团品牌列表的字典
  1909. """
  1910. try:
  1911. # 查询所有酒店集团品牌记录,按集团和品牌排序
  1912. brands = HotelGroupBrands.query.order_by(
  1913. HotelGroupBrands.group_name_zh,
  1914. HotelGroupBrands.brand_name_zh
  1915. ).all()
  1916. # 将所有记录转换为字典格式
  1917. brands_data = [brand.to_dict() for brand in brands]
  1918. return {
  1919. 'code': 200,
  1920. 'success': True,
  1921. 'message': '获取酒店集团品牌列表成功',
  1922. 'data': brands_data,
  1923. 'count': len(brands_data)
  1924. }
  1925. except Exception as e:
  1926. error_msg = f"获取酒店集团品牌列表失败: {str(e)}"
  1927. logging.error(error_msg, exc_info=True)
  1928. return {
  1929. 'code': 500,
  1930. 'success': False,
  1931. 'message': error_msg,
  1932. 'data': [],
  1933. 'count': 0
  1934. }
  1935. def add_hotel_group_brands(brand_data):
  1936. """
  1937. 新增酒店集团子品牌数据表记录
  1938. Args:
  1939. brand_data (dict): 包含品牌信息的字典,包括:
  1940. - group_name_en: 集团英文名称 (必填)
  1941. - group_name_zh: 集团中文名称 (必填)
  1942. - brand_name_en: 品牌英文名称 (必填)
  1943. - brand_name_zh: 品牌中文名称 (必填)
  1944. - positioning_level_en: 定位级别英文名称 (必填)
  1945. - positioning_level_zh: 定位级别中文名称 (必填)
  1946. - created_by: 创建者 (可选,默认为'system')
  1947. - updated_by: 更新者 (可选,默认为'system')
  1948. - status: 状态 (可选,默认为'active')
  1949. Returns:
  1950. dict: 包含操作结果和创建的品牌信息的字典
  1951. """
  1952. try:
  1953. # 验证必填字段
  1954. required_fields = ['group_name_en', 'group_name_zh', 'brand_name_en', 'brand_name_zh', 'positioning_level_en', 'positioning_level_zh']
  1955. missing_fields = []
  1956. for field in required_fields:
  1957. if field not in brand_data or not brand_data[field] or not brand_data[field].strip():
  1958. missing_fields.append(field)
  1959. if missing_fields:
  1960. return {
  1961. 'code': 400,
  1962. 'success': False,
  1963. 'message': f'缺少必填字段: {", ".join(missing_fields)}',
  1964. 'data': None
  1965. }
  1966. # 检查是否已存在相同的品牌记录(基于集团和品牌的中文名称)
  1967. existing_brand = HotelGroupBrands.query.filter_by(
  1968. group_name_zh=brand_data['group_name_zh'].strip(),
  1969. brand_name_zh=brand_data['brand_name_zh'].strip()
  1970. ).first()
  1971. if existing_brand:
  1972. return {
  1973. 'code': 409,
  1974. 'success': False,
  1975. 'message': f'品牌记录已存在:{brand_data["group_name_zh"]} - {brand_data["brand_name_zh"]}',
  1976. 'data': existing_brand.to_dict()
  1977. }
  1978. # 创建新的品牌记录
  1979. new_brand = HotelGroupBrands(
  1980. group_name_en=brand_data['group_name_en'].strip(),
  1981. group_name_zh=brand_data['group_name_zh'].strip(),
  1982. brand_name_en=brand_data['brand_name_en'].strip(),
  1983. brand_name_zh=brand_data['brand_name_zh'].strip(),
  1984. positioning_level_en=brand_data['positioning_level_en'].strip(),
  1985. positioning_level_zh=brand_data['positioning_level_zh'].strip(),
  1986. created_by=brand_data.get('created_by', 'system'),
  1987. updated_by=brand_data.get('updated_by', 'system'),
  1988. status=brand_data.get('status', 'active')
  1989. )
  1990. # 保存到数据库
  1991. db.session.add(new_brand)
  1992. db.session.commit()
  1993. logging.info(f"成功创建酒店集团品牌记录,ID: {new_brand.id}")
  1994. return {
  1995. 'code': 200,
  1996. 'success': True,
  1997. 'message': '酒店集团品牌记录创建成功',
  1998. 'data': new_brand.to_dict()
  1999. }
  2000. except Exception as e:
  2001. db.session.rollback()
  2002. error_msg = f"创建酒店集团品牌记录失败: {str(e)}"
  2003. logging.error(error_msg, exc_info=True)
  2004. return {
  2005. 'code': 500,
  2006. 'success': False,
  2007. 'message': error_msg,
  2008. 'data': None
  2009. }
  2010. def update_hotel_group_brands(brand_id, brand_data):
  2011. """
  2012. 修改酒店集团子品牌数据表记录
  2013. Args:
  2014. brand_id (int): 品牌记录ID
  2015. brand_data (dict): 包含要更新的品牌信息的字典,可能包括:
  2016. - group_name_en: 集团英文名称
  2017. - group_name_zh: 集团中文名称
  2018. - brand_name_en: 品牌英文名称
  2019. - brand_name_zh: 品牌中文名称
  2020. - positioning_level_en: 定位级别英文名称
  2021. - positioning_level_zh: 定位级别中文名称
  2022. - updated_by: 更新者
  2023. - status: 状态
  2024. Returns:
  2025. dict: 包含操作结果和更新后的品牌信息的字典
  2026. """
  2027. try:
  2028. # 查找要更新的品牌记录
  2029. brand = HotelGroupBrands.query.get(brand_id)
  2030. if not brand:
  2031. return {
  2032. 'code': 404,
  2033. 'success': False,
  2034. 'message': f'未找到ID为{brand_id}的品牌记录',
  2035. 'data': None
  2036. }
  2037. # 检查是否有数据需要更新
  2038. if not brand_data:
  2039. return {
  2040. 'code': 400,
  2041. 'success': False,
  2042. 'message': '请求数据为空',
  2043. 'data': None
  2044. }
  2045. # 如果要更新集团和品牌名称,检查是否会与其他记录冲突
  2046. new_group_name_zh = brand_data.get('group_name_zh', brand.group_name_zh).strip() if brand_data.get('group_name_zh') else brand.group_name_zh
  2047. new_brand_name_zh = brand_data.get('brand_name_zh', brand.brand_name_zh).strip() if brand_data.get('brand_name_zh') else brand.brand_name_zh
  2048. # 查找是否存在相同的品牌记录(排除当前记录)
  2049. existing_brand = HotelGroupBrands.query.filter(
  2050. HotelGroupBrands.id != brand_id,
  2051. HotelGroupBrands.group_name_zh == new_group_name_zh,
  2052. HotelGroupBrands.brand_name_zh == new_brand_name_zh
  2053. ).first()
  2054. if existing_brand:
  2055. return {
  2056. 'code': 409,
  2057. 'success': False,
  2058. 'message': f'品牌记录已存在:{new_group_name_zh} - {new_brand_name_zh}',
  2059. 'data': existing_brand.to_dict()
  2060. }
  2061. # 更新品牌信息
  2062. if 'group_name_en' in brand_data and brand_data['group_name_en']:
  2063. brand.group_name_en = brand_data['group_name_en'].strip()
  2064. if 'group_name_zh' in brand_data and brand_data['group_name_zh']:
  2065. brand.group_name_zh = brand_data['group_name_zh'].strip()
  2066. if 'brand_name_en' in brand_data and brand_data['brand_name_en']:
  2067. brand.brand_name_en = brand_data['brand_name_en'].strip()
  2068. if 'brand_name_zh' in brand_data and brand_data['brand_name_zh']:
  2069. brand.brand_name_zh = brand_data['brand_name_zh'].strip()
  2070. if 'positioning_level_en' in brand_data and brand_data['positioning_level_en']:
  2071. brand.positioning_level_en = brand_data['positioning_level_en'].strip()
  2072. if 'positioning_level_zh' in brand_data and brand_data['positioning_level_zh']:
  2073. brand.positioning_level_zh = brand_data['positioning_level_zh'].strip()
  2074. if 'updated_by' in brand_data:
  2075. brand.updated_by = brand_data['updated_by'] or 'system'
  2076. if 'status' in brand_data:
  2077. brand.status = brand_data['status'] or 'active'
  2078. # 更新时间会自动设置(onupdate=datetime.now)
  2079. # 保存更新
  2080. db.session.commit()
  2081. logging.info(f"成功更新酒店集团品牌记录,ID: {brand.id}")
  2082. return {
  2083. 'code': 200,
  2084. 'success': True,
  2085. 'message': '酒店集团品牌记录更新成功',
  2086. 'data': brand.to_dict()
  2087. }
  2088. except Exception as e:
  2089. db.session.rollback()
  2090. error_msg = f"更新酒店集团品牌记录失败: {str(e)}"
  2091. logging.error(error_msg, exc_info=True)
  2092. return {
  2093. 'code': 500,
  2094. 'success': False,
  2095. 'message': error_msg,
  2096. 'data': None
  2097. }
  2098. def query_hotel_group_brands(brand_id):
  2099. """
  2100. 查找指定ID的酒店集团子品牌数据表记录
  2101. Args:
  2102. brand_id (int): 品牌记录ID
  2103. Returns:
  2104. dict: 包含操作结果和品牌信息的字典
  2105. """
  2106. try:
  2107. # 根据ID查找品牌记录
  2108. brand = HotelGroupBrands.query.get(brand_id)
  2109. if not brand:
  2110. return {
  2111. 'code': 404,
  2112. 'success': False,
  2113. 'message': f'未找到ID为{brand_id}的品牌记录',
  2114. 'data': None
  2115. }
  2116. # 返回找到的记录
  2117. return {
  2118. 'code': 200,
  2119. 'success': True,
  2120. 'message': '查找品牌记录成功',
  2121. 'data': brand.to_dict()
  2122. }
  2123. except Exception as e:
  2124. error_msg = f"查找品牌记录失败: {str(e)}"
  2125. logging.error(error_msg, exc_info=True)
  2126. return {
  2127. 'code': 500,
  2128. 'success': False,
  2129. 'message': error_msg,
  2130. 'data': None
  2131. }
  2132. def delete_hotel_group_brands(brand_id):
  2133. """
  2134. 删除指定ID的酒店集团子品牌数据表记录
  2135. Args:
  2136. brand_id (int): 品牌记录ID
  2137. Returns:
  2138. dict: 包含操作结果的字典
  2139. """
  2140. try:
  2141. # 根据ID查找要删除的品牌记录
  2142. brand = HotelGroupBrands.query.get(brand_id)
  2143. if not brand:
  2144. return {
  2145. 'code': 404,
  2146. 'success': False,
  2147. 'message': f'未找到ID为{brand_id}的品牌记录',
  2148. 'data': None
  2149. }
  2150. # 保存被删除记录的信息,用于返回
  2151. deleted_brand_info = brand.to_dict()
  2152. # 执行删除操作
  2153. db.session.delete(brand)
  2154. db.session.commit()
  2155. logging.info(f"成功删除酒店集团品牌记录,ID: {brand_id}")
  2156. return {
  2157. 'code': 200,
  2158. 'success': True,
  2159. 'message': '品牌记录删除成功',
  2160. 'data': deleted_brand_info
  2161. }
  2162. except Exception as e:
  2163. db.session.rollback()
  2164. error_msg = f"删除品牌记录失败: {str(e)}"
  2165. logging.error(error_msg, exc_info=True)
  2166. return {
  2167. 'code': 500,
  2168. 'success': False,
  2169. 'message': error_msg,
  2170. 'data': None
  2171. }