api.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. from re import search
  2. from natsort.natsort import order_by_index
  3. from sqlalchemy import func
  4. from models import *
  5. import requests
  6. import json
  7. from logger import logger
  8. from serial.tools import list_ports
  9. from model import PhotoRecord
  10. import settings, datetime
  11. import pandas as pd
  12. from utils.hlm_http_request import forward_request
  13. from utils.utils_func import check_path
  14. from sockets.socket_client import socket_manager
  15. from mcu.DeviceControl import DeviceControl
  16. import time, shutil, os
  17. from sqlalchemy import and_, asc, desc
  18. from functools import partial
  19. from service.deal_image import DealImage
  20. from databases import DeviceConfig, SysConfigs, SqlQuery, CRUD, select, DeviceConfigTabs
  21. from service.run_main import RunMain
  22. import importlib
  23. from service.auto_deal_pics.upload_pic import UploadPic
  24. from service.OnePicTest import OnePicTest
  25. from service.base import check_move_goods_art_no_folder
  26. import win32api, win32gui, win32con
  27. from win32gui import EnumWindows, GetWindowText
  28. from service.online_request.module_online_data import OnlineDataRequest
  29. from concurrent.futures import ThreadPoolExecutor
  30. from functools import partial
  31. @app.get("/")
  32. async def index():
  33. # await socket_manager.send_message(msg="测试")
  34. return {"message": "Hello World"}
  35. @app.get("/scan_serials", description="扫描可用的设备端口")
  36. async def scanSerials():
  37. """扫描串口"""
  38. ports = list_ports.comports()
  39. print("Scanning", ports)
  40. return {"message": "Hello World"}
  41. @app.api_route(
  42. "/forward_request", methods=["GET", "POST"], description="代理转发hlm项目得请求"
  43. )
  44. async def forwardRequest(request: HlmForwardRequest):
  45. """
  46. 转发HTTP请求到目标URL
  47. :param request: FastAPI Request对象
  48. :return: 目标接口的响应
  49. """
  50. try:
  51. if request.method == "GET":
  52. params = request.query_params
  53. elif request.method == "POST":
  54. params = json.dump(request.query_params)
  55. else:
  56. raise UnicornException("仅支持GET和POST方法")
  57. target_url = request.target_url
  58. method = request.method.upper()
  59. headers = request.headers
  60. if not target_url:
  61. raise UnicornException("目标url地址不能为空")
  62. # 调用 hlm_http_request 中的 forward_request 函数
  63. response = forward_request(
  64. target_url, params=params, method=method, headers=headers
  65. )
  66. return response
  67. except requests.RequestException as e:
  68. raise UnicornException(e)
  69. except Exception as e:
  70. raise UnicornException(e)
  71. async def fromExcelHandler(params: HandlerDetail):
  72. excel_path = params.excel_path
  73. token = "Bearer " + params.token
  74. uuid = params.uuid
  75. excel_df = pd.read_excel(excel_path, sheet_name=0, header=0)
  76. handler_result = []
  77. handler_result_folder = ""
  78. if "文件夹名称" not in excel_df.columns:
  79. raise UnicornException("缺失 [文件夹名称] 列")
  80. if "商品货号" not in excel_df.columns:
  81. raise UnicornException("缺失 [商品货号] 列")
  82. if "款号" not in excel_df.columns:
  83. raise UnicornException("缺失 [款号] 列")
  84. goods_art_dirs = excel_df.groupby(excel_df["款号"])
  85. obj = None
  86. run_main = RunMain(obj, token, uuid)
  87. temp_class = {}
  88. # 可用模板列表-需要导包
  89. temp_name_list = []
  90. for tempItem in params.temp_list:
  91. temp_class[tempItem.template_id] = tempItem.template_local_classes
  92. temp_name_list.append(tempItem.template_id)
  93. # 抠图时用到的货号列表,与生成详情图有所区别
  94. goods_art_no_arrays = []
  95. # # 详情图生成需要对同款商品进行分组,保证详情图可以生成多个色
  96. goods_art_no_group_arrays = []
  97. for _, goods_row in excel_df.iterrows():
  98. goods_art_no = str(goods_row["商品货号"])
  99. goods_art_no_arrays.append(goods_art_no)
  100. goods_no = str(goods_row["款号"])
  101. a001_df = goods_art_dirs.get_group(goods_no)
  102. goods_art_groups = a001_df["商品货号"].tolist()
  103. if goods_art_groups in goods_art_no_group_arrays:
  104. continue
  105. goods_art_no_group_arrays.append(goods_art_groups)
  106. limit_path = "output/{}".format(
  107. time.strftime("%Y-%m-%d", time.localtime(time.time()))
  108. )
  109. # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  110. move_folder_array = check_move_goods_art_no_folder(
  111. "output", goods_art_no_arrays, limit_path
  112. )
  113. for index, row in excel_df.iterrows():
  114. goods_art_no_image_dir = str(row["文件夹名称"])
  115. goods_art_no = str(row["商品货号"])
  116. print("货号数据", goods_art_no)
  117. if not goods_art_no:
  118. raise UnicornException("货号不能为空")
  119. session = SqlQuery()
  120. pr = CRUD(PhotoRecord)
  121. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  122. if not images:
  123. raise UnicornException("没有可用货号数据")
  124. # 货号目录不存在再去进行移动和创建操作
  125. if move_folder_array.get(goods_art_no) == None:
  126. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  127. check_path(image_dir)
  128. for idx, itemImg in enumerate(images):
  129. if itemImg.image_path == "" or itemImg.image_path == None:
  130. raise UnicornException(
  131. f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  132. )
  133. new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  134. if not os.path.exists(
  135. image_dir + "/" + os.path.basename(new_file_name)
  136. ):
  137. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  138. dealImage = DealImage(image_dir)
  139. resFlag, path = dealImage.dealMoveImage(
  140. image_dir=image_dir,
  141. callback_func=None,
  142. goods_art_no=goods_art_no_image_dir,
  143. )
  144. if not resFlag:
  145. raise UnicornException(path)
  146. shutil.rmtree(image_dir)
  147. # path = os.path.dirname(path)
  148. cutOutMode = (
  149. '0'
  150. if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图") == "普通抠图"
  151. else '1'
  152. )
  153. config_data = {
  154. "image_dir": limit_path, # 这个目录作为本次生成的图片目录非常重要 例:./output/当前日期
  155. "image_order": params.template_image_order,
  156. "goods_art_no": goods_art_no,
  157. "goods_art_nos": goods_art_no_arrays,
  158. "is_check_number": False,
  159. "resize_image_view": "后跟",
  160. "cutout_mode": cutOutMode,
  161. "logo_path": params.logo_path,
  162. "special_goods_art_no_folder_line": "",
  163. "is_use_excel": (False if params.excel_path == "" else True), # 是否使用excel
  164. "excel_path": params.excel_path, # excel路径
  165. "is_check_color_is_all": False,
  166. "cutout_is_pass": True,
  167. "assigned_page_dict": {},
  168. "detail_is_pass": True,
  169. "upload_is_pass": False,
  170. "upload_is_enable": False,
  171. "is_filter": False,
  172. "temp_class": temp_class,
  173. "temp_name": params.temp_name,
  174. "temp_name_list": temp_name_list,
  175. "target_error_folder": f"{limit_path}/软件-生成详情错误",
  176. "success_handler": [],
  177. }
  178. # 动态导入类
  179. temp_class_dict = {}
  180. for key, class_path in config_data["temp_class"].items():
  181. module_path, class_name = class_path.rsplit(".", 1)
  182. module = importlib.import_module(module_path)
  183. cls = getattr(module, class_name)
  184. temp_class_dict[key] = cls
  185. config_data["temp_class"] = temp_class_dict
  186. executor = ThreadPoolExecutor(max_workers=4)
  187. # 此处对抠图进行批量处理,保证所有的图片在生成详情图之前已经完成抠图,以保证详情图生成的效率
  188. return_data = run_main.check_before_cutout(config_data)
  189. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  190. check_for_detail_first_res = None
  191. try:
  192. if cutout_res:
  193. return_data_check_before_detail = run_main.check_before_detail(config_data)
  194. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  195. return_data_check_before_detail
  196. )
  197. if isinstance(check_for_detail_first_res, partial):
  198. result = check_for_detail_first_res()
  199. try:
  200. config_data = result["config_data"]
  201. except:
  202. config_data = result
  203. if config_data["sign_text"] == "已结束详情处理":
  204. print("config_data", config_data)
  205. if config_data["upload_is_enable"]:
  206. to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  207. check_path(to_deal_dir)
  208. print("to_deal_dir", to_deal_dir)
  209. if os.path.exists(to_deal_dir):
  210. upload_pic = UploadPic(
  211. windows=None,
  212. to_deal_dir=to_deal_dir,
  213. config_data=config_data,
  214. token=token,
  215. )
  216. upload_pic.run()
  217. out_put_dir = config_data.get("out_put_dir")
  218. if out_put_dir == None:
  219. handler_result_folder = ""
  220. if len(config_data["success_handler"]) > 0:
  221. for good_art in config_data["success_handler"]:
  222. handler_result.append(good_art)
  223. else:
  224. for good_art in goods_art_no_arrays:
  225. handler_result.append(
  226. {
  227. "goods_art_no": good_art,
  228. "success": False,
  229. "info": "处理失败",
  230. }
  231. )
  232. else:
  233. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  234. "\\", "/"
  235. )
  236. handler_result_folder = os.path.dirname(out_put_dir_path)
  237. if len(config_data["success_handler"]) == 0:
  238. for good_art in goods_art_no_arrays:
  239. handler_result.append(
  240. {
  241. "goods_art_no": good_art,
  242. "success": False,
  243. "info": "处理失败",
  244. }
  245. )
  246. else:
  247. handler_result = config_data["success_handler"]
  248. else:
  249. for good_art in goods_art_no_arrays:
  250. handler_result.append(
  251. {"goods_art_no": good_art, "success": False, "info": "处理失败"}
  252. )
  253. except Exception as e:
  254. for good_art in goods_art_no_arrays:
  255. handler_result.append(
  256. {"goods_art_no": good_art, "success": False, "info": str(e)}
  257. )
  258. handler_result_folder = "/".join(handler_result_folder.split("/")[:-1])
  259. return {
  260. "code": 0,
  261. "msg": "",
  262. "data": {"output_folder": handler_result_folder, "list": handler_result},
  263. }
  264. def group_by_style_number(data):
  265. result = {}
  266. for goods_id, info in data.items():
  267. style_number = info["款号"]
  268. if style_number not in result:
  269. result[style_number] = []
  270. result[style_number].append(goods_id)
  271. return result
  272. @app.post("/handle_detail")
  273. async def handle_detail(request: Request, params: HandlerDetail):
  274. obj = None
  275. token = "Bearer " + params.token
  276. uuid = params.uuid
  277. run_main = RunMain(obj, token, uuid)
  278. onlineData = OnlineDataRequest(token)
  279. goods_art_no_arrays = params.goods_art_no
  280. is_only_cutout = params.is_only_cutout
  281. online_stores = params.online_stores
  282. handler_result = []
  283. handler_result_folder = ""
  284. if is_only_cutout == 1:
  285. # 如果是仅抠图模式,避免进入到excel模式
  286. params.excel_path = ""
  287. if params.excel_path != "" and params.excel_path != None:
  288. return await fromExcelHandler(params)
  289. path = ""
  290. limit_path = "output/{}".format(
  291. time.strftime("%Y-%m-%d", time.localtime(time.time()))
  292. )
  293. check_path(limit_path)
  294. # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  295. move_folder_array = check_move_goods_art_no_folder(
  296. "output", goods_art_no_arrays, limit_path
  297. )
  298. for goods_art_no in goods_art_no_arrays:
  299. if not goods_art_no:
  300. raise UnicornException("货号不能为空")
  301. session = SqlQuery()
  302. pr = CRUD(PhotoRecord)
  303. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  304. if not images:
  305. raise UnicornException("没有可用货号数据")
  306. if is_only_cutout != 1:
  307. detail_counts = len(params.template_image_order.split(","))
  308. image_counts = len(images)
  309. if image_counts < detail_counts:
  310. raise UnicornException(
  311. f"货号:[{goods_art_no}],实际照片数量:{image_counts}张,小于详情图要求数量:{detail_counts}张"
  312. )
  313. if move_folder_array.get(goods_art_no) == None:
  314. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  315. check_path(image_dir)
  316. for idx, itemImg in enumerate(images):
  317. if itemImg.image_path == "" or itemImg.image_path == None:
  318. raise UnicornException(
  319. f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  320. )
  321. new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  322. if not os.path.exists(
  323. image_dir + "/" + os.path.basename(new_file_name)
  324. ):
  325. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  326. dealImage = DealImage(image_dir)
  327. resFlag, path = dealImage.dealMoveImage(
  328. image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  329. )
  330. if not resFlag:
  331. raise UnicornException(path)
  332. # try:
  333. temp_class = {}
  334. temp_name_list = []
  335. for tempItem in params.temp_list:
  336. temp_class[tempItem.template_id] = tempItem.template_local_classes
  337. temp_name_list.append(tempItem.template_id)
  338. cutOutMode = (
  339. '1'
  340. if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图")
  341. == "普通抠图"
  342. else '2'
  343. )
  344. config_data = {
  345. "image_dir": limit_path,
  346. "image_order": (
  347. "俯视,侧视,后跟,鞋底,内里"
  348. if params.template_image_order == None or params.template_image_order == ""
  349. else params.template_image_order
  350. ),
  351. "goods_art_no": "",
  352. "goods_art_nos": goods_art_no_arrays,
  353. "is_check_number": False,
  354. "resize_image_view": "后跟",
  355. "cutout_mode": cutOutMode,
  356. "logo_path": params.logo_path,
  357. "special_goods_art_no_folder_line": "",
  358. "is_use_excel": False, # 是否使用excel
  359. "excel_path": "", # excel路径
  360. "is_check_color_is_all": False,
  361. "cutout_is_pass": True,
  362. "assigned_page_dict": {},
  363. "detail_is_pass": True,
  364. "upload_is_pass": False,
  365. "upload_is_enable": settings.IS_UPLOAD_HLM, # 是否上传到惠利玛商品库,通过config.ini得is_upload开启
  366. "is_filter": False,
  367. "temp_class": temp_class,
  368. "temp_name": params.temp_name,
  369. "temp_name_list": temp_name_list,
  370. "target_error_folder": f"{limit_path}/软件-生成详情错误",
  371. "success_handler": [],
  372. }
  373. print("image_dir=====>>>>>", config_data["image_dir"])
  374. # 动态导入类
  375. temp_class_dict = {}
  376. for key, class_path in config_data["temp_class"].items():
  377. module_path, class_name = class_path.rsplit(".", 1)
  378. module = importlib.import_module(module_path)
  379. cls = getattr(module, class_name)
  380. temp_class_dict[key] = cls
  381. config_data["temp_class"] = temp_class_dict
  382. return_data = run_main.check_before_cutout(config_data)
  383. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  384. check_for_detail_first_res = None
  385. if cutout_res == True:
  386. sys_path = format(os.getcwd()).replace("\\", "/")
  387. handler_result_folder = f"{sys_path}/{limit_path}"
  388. for goods_art_item in goods_art_no_arrays:
  389. handler_result.append(
  390. {
  391. "goods_art_no": goods_art_item,
  392. "success": True,
  393. "info": "处理成功",
  394. }
  395. )
  396. if is_only_cutout == 1:
  397. return {
  398. "code": 0,
  399. "msg": "",
  400. "data": {"output_folder": handler_result_folder, "list": handler_result},
  401. }
  402. handler_result = []
  403. try:
  404. return_data_check_before_detail = run_main.check_before_detail(config_data)
  405. check_for_detail_first_res = await run_main.check_for_detail_first_call_back(
  406. return_data_check_before_detail
  407. )
  408. if isinstance(check_for_detail_first_res, partial):
  409. result = check_for_detail_first_res()
  410. try:
  411. config_data = result["config_data"]
  412. except:
  413. config_data = result
  414. if config_data["sign_text"] == "已结束详情处理":
  415. print("config_data", config_data)
  416. out_put_dir = config_data.get("out_put_dir")
  417. if out_put_dir == None:
  418. handler_result_folder = ""
  419. if len(config_data["success_handler"]) > 0:
  420. for good_art in config_data["success_handler"]:
  421. handler_result.append(good_art)
  422. else:
  423. for good_art in goods_art_no_arrays:
  424. handler_result.append(
  425. {
  426. "goods_art_no": good_art,
  427. "success": False,
  428. "info": "处理失败",
  429. }
  430. )
  431. else:
  432. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  433. "\\", "/"
  434. )
  435. handler_result_folder = os.path.dirname(out_put_dir_path)
  436. if len(config_data["success_handler"]) == 0:
  437. for good_art in goods_art_no_arrays:
  438. handler_result.append(
  439. {
  440. "goods_art_no": good_art,
  441. "success": False,
  442. "info": "处理失败",
  443. }
  444. )
  445. else:
  446. if len(online_stores) >0:
  447. result_goods_no_dict = return_data_check_before_detail["data"][
  448. "goods_no_dict"
  449. ]
  450. for goods_idx,goods_no_dict in enumerate(result_goods_no_dict.keys()):
  451. all_detail_path_list = config_data["all_detail_path_list"]
  452. for detail_path in all_detail_path_list:
  453. if goods_no_dict in detail_path:
  454. detail_path_replace = detail_path.replace(
  455. "\\", "/"
  456. )
  457. result_goods_no_dict[goods_no_dict][
  458. "detail_path"
  459. ] = f"{detail_path_replace}/详情页.jpg"
  460. onlineData.uploadGoods2ThirdParty(
  461. result_goods_no_dict, online_stores=online_stores
  462. )
  463. handler_result = config_data["success_handler"]
  464. else:
  465. handler_result.append(
  466. {"goods_art_no": "", "success": False, "info": "处理失败"}
  467. )
  468. except UnicornException as e:
  469. handler_result_folder = ""
  470. handler_result = e.msg
  471. # except Exception as e:
  472. # handler_result_folder = ""
  473. # handler_result.append({"goods_art_no": "", "success": False, "info": str(e)})
  474. return {
  475. "code": 0,
  476. "msg": "",
  477. "data": {"output_folder": handler_result_folder, "list": handler_result},
  478. }
  479. @app.get("/get_device_tabs", description="获取可执行程序命令列表")
  480. def get_device_tabs(type: int):
  481. session = SqlQuery()
  482. statement = (
  483. select(DeviceConfigTabs)
  484. .where(DeviceConfigTabs.mode_type == type)
  485. .order_by(asc("id"))
  486. )
  487. result = session.exec(statement).all()
  488. session.close()
  489. sys = CRUD(SysConfigs)
  490. action_configs = sys.read(session, conditions={"key": "action_configs"})
  491. session.close()
  492. return {
  493. "code": 0,
  494. "msg": "",
  495. "data": {"tabs": result, "select_configs": json.loads(action_configs.value)},
  496. }
  497. @app.post("/update_tab_name", description="更改tab名称")
  498. def update_tab_name(params: DeviceConfigTabsReq):
  499. if params.mode_name == "":
  500. return {"code": 1, "msg": "名称不能为空", "data": {}}
  501. session = SqlQuery()
  502. tabModel = CRUD(DeviceConfigTabs)
  503. kwargs = {"mode_name": params.mode_name}
  504. tabModel.updateConditions(session, conditions={"id": params.id}, **kwargs)
  505. session.close()
  506. return {
  507. "code": 0,
  508. "msg": "",
  509. "data": None,
  510. }
  511. @app.post("/get_device_configs", description="获取可执行程序命令列表")
  512. def get_device_configs(params: ModelGetDeviceConfig):
  513. tab_id = params.tab_id
  514. session = SqlQuery()
  515. configModel = CRUD(DeviceConfig)
  516. configList = configModel.read_all(
  517. session,
  518. conditions={"tab_id": tab_id},
  519. order_by="action_index",
  520. ascending=True,
  521. )
  522. return {
  523. "code": 0,
  524. "msg": "",
  525. "data": {"list": configList},
  526. }
  527. @app.post("/device_config_detail", description="获取可执行程序详情")
  528. def device_config_detail(params: ModelGetDeviceConfigDetail):
  529. action_id = params.id
  530. session = SqlQuery()
  531. configModel = CRUD(DeviceConfig)
  532. model = configModel.read(session, conditions={"id": action_id})
  533. if model == None:
  534. return {"code": 1, "msg": "数据不存在", "data": None}
  535. return {"code": 0, "msg": "", "data": model}
  536. @app.post("/device_config_detail_query", description="通过条件获取可执行程序详情")
  537. def device_config_detail_query():
  538. # tab_id = params.tab_id
  539. # action_name = params.action_name
  540. session = SqlQuery()
  541. sys = CRUD(SysConfigs)
  542. action_configs = sys.read(session, conditions={"key": "action_configs"})
  543. action_configs_value = json.loads(action_configs.value)
  544. left_config = action_configs_value.get("left")
  545. configModel = CRUD(DeviceConfig)
  546. model = configModel.read(
  547. session, conditions={"tab_id": left_config, "action_name": "侧视"}
  548. )
  549. if model == None:
  550. model = configModel.read(session, conditions={"tab_id": left_config})
  551. return {"code": 0, "msg": "", "data": model}
  552. @app.post("/remove_config", description="删除一条可执行命令")
  553. def get_device_configs(params: ModelGetDeviceConfigDetail):
  554. action_id = params.id
  555. session = SqlQuery()
  556. configModel = CRUD(DeviceConfig)
  557. model = configModel.read(session, conditions={"id": action_id})
  558. if model == None:
  559. return {"code": 1, "msg": "数据不存在", "data": None}
  560. if model.is_system == True:
  561. return {"code": 1, "msg": "系统配置不允许删除", "data": None}
  562. configArray = configModel.read_all(session, conditions={"tab_id": model.tab_id})
  563. if len(configArray) == 1:
  564. return {"code": 1, "msg": "请至少保留一个配置", "data": None}
  565. configModel.delete(session, obj_id=action_id)
  566. return {"code": 0, "msg": "删除成功", "data": None}
  567. @app.post("/save_device_config", description="创建或修改一条可执行命令")
  568. def save_device_config(params: SaveDeviceConfig):
  569. action_id = params.id
  570. session = SqlQuery()
  571. deviceConfig = CRUD(DeviceConfig)
  572. if action_id == None or action_id == 0:
  573. # 走新增逻辑
  574. params.id = None
  575. save_device_config = deviceConfig.create(session, obj_in=params)
  576. else:
  577. model = deviceConfig.read(session, conditions={"id": action_id})
  578. if model == None:
  579. return {"code": 1, "msg": "数据不存在", "data": None}
  580. # 走编辑逻辑
  581. kwargs = params.__dict__
  582. save_device_config = deviceConfig.update(session, obj_id=action_id, **kwargs)
  583. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  584. @app.post("/reset_config", description="创建或修改一条可执行命令")
  585. def reset_config(params: ModelGetDeviceConfig):
  586. tab_id = params.tab_id
  587. if tab_id == None or tab_id == "":
  588. return {"code": 1, "msg": "参数错误", "data": None}
  589. session = SqlQuery()
  590. deviceConfig = CRUD(DeviceConfig)
  591. first_config = deviceConfig.read(session, conditions={"tab_id": tab_id})
  592. res = deviceConfig.deleteConditions(session, conditions={"tab_id": tab_id})
  593. if res is False:
  594. return {"code": 1, "msg": "操作失败", "data": None}
  595. actions = json.load(open("action.json", encoding="utf-8"))
  596. for data in actions:
  597. data["tab_id"] = tab_id
  598. data["is_system"] = first_config.is_system
  599. device_config = DeviceConfig(**data)
  600. session.add(device_config)
  601. session.commit()
  602. # session.close()
  603. return {"code": 0, "msg": "操作成功", "data": None}
  604. @app.get("/get_photo_records", description="获取拍照记录")
  605. def get_photo_records(page: int = 1, size: int = 5):
  606. session = SqlQuery()
  607. # photos = CRUD(PhotoRecord)
  608. print("准备查询拍摄记录", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  609. statement = (
  610. select(PhotoRecord)
  611. .offset((page - 1) * size)
  612. .limit(size)
  613. .order_by(desc("id"))
  614. .group_by("goods_art_no")
  615. )
  616. list = []
  617. result = session.exec(statement).all()
  618. print("group 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  619. join_conditions = [
  620. {
  621. "model": DeviceConfig,
  622. "on": PhotoRecord.action_id == DeviceConfig.id,
  623. "is_outer": False, # 可选,默认False,设为True则为LEFT JOIN
  624. }
  625. ]
  626. for item in result:
  627. query = (
  628. select(PhotoRecord, DeviceConfig.action_name)
  629. .where(PhotoRecord.goods_art_no == item.goods_art_no)
  630. .join(DeviceConfig, PhotoRecord.action_id == DeviceConfig.id)
  631. )
  632. list_item = session.exec(query).mappings().all()
  633. list.append(
  634. {
  635. "goods_art_no": item.goods_art_no,
  636. "action_time": item.create_time,
  637. "items": list_item,
  638. }
  639. )
  640. # session.close()
  641. print("循环查询 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  642. return {
  643. "code": 0,
  644. "msg": "",
  645. "data": {"list": list, "page": page, "size": size},
  646. }
  647. @app.get("/get_last_photo_record", description="获取最后一条拍照记录")
  648. def get_last_photo_record():
  649. session = SqlQuery()
  650. statement = (
  651. select(PhotoRecord)
  652. .where(PhotoRecord.image_path != None)
  653. .order_by(desc("photo_create_time"))
  654. )
  655. result = session.exec(statement).first()
  656. # session.close()
  657. return {
  658. "code": 0,
  659. "msg": "",
  660. "data": result,
  661. }
  662. @app.get("/get_photo_record_detail", description="通过货号获取拍照记录详情")
  663. def get_photo_record_detail(goods_art_no: str = None):
  664. if goods_art_no == None:
  665. return {"code": 1, "msg": "参数错误", "data": None}
  666. session = SqlQuery()
  667. photos = CRUD(PhotoRecord)
  668. items = photos.read_all(session, conditions={"goods_art_no": goods_art_no})
  669. # session.close()
  670. return {
  671. "code": 0,
  672. "msg": "",
  673. "data": {"list": items},
  674. }
  675. @app.post("/delect_goods_arts", description="通过货号删除记录")
  676. def delect_goods_arts(params: PhotoRecordDelete):
  677. session = SqlQuery()
  678. photos = CRUD(PhotoRecord)
  679. for item in params.goods_art_nos:
  680. photos.deleteConditions(session, conditions={"goods_art_no": item})
  681. # session.close()
  682. return {
  683. "code": 0,
  684. "msg": "操作成功",
  685. "data": None,
  686. }
  687. def query_config_by_key(key_name):
  688. """
  689. 在sys_configs.json格式的数据中查询指定的key,如果匹配则返回整个对象
  690. Args:
  691. key_name (str): 要查询的key名称
  692. Returns:
  693. dict or None: 匹配的对象或None(如果没有找到)
  694. """
  695. try:
  696. # 获取所有配置数据
  697. configs = json.load(open("sys_configs.json", encoding="utf-8"))
  698. # 遍历配置数据查找匹配的key
  699. for config in configs:
  700. if config.get("key") == key_name:
  701. return config
  702. return None
  703. except Exception as e:
  704. print(f"查询配置时出错: {e}")
  705. return None
  706. @app.get("/get_sys_config", description="查询系统配置")
  707. def get_sys_config(key: str = None):
  708. if key == None:
  709. return {"code": 1, "msg": "参数错误", "data": None}
  710. session = SqlQuery()
  711. photos = CRUD(SysConfigs)
  712. item = photos.read(session, conditions={"key": key})
  713. search_data = None if item == None else json.loads(item.value)
  714. if search_data == None:
  715. sys_config_json = query_config_by_key(key)
  716. if sys_config_json != None:
  717. config = SysConfigs(**sys_config_json)
  718. session.add(config)
  719. session.commit() # 合并事务提交
  720. search_data = json.loads(sys_config_json.get("value"))
  721. return {
  722. "code": 0,
  723. "msg": "",
  724. "data": search_data,
  725. }
  726. @app.post("/update_left_right_config", description="更新左右脚配置")
  727. def update_left_right_config(params: LeftRightParams):
  728. session = SqlQuery()
  729. sysConfig = CRUD(SysConfigs)
  730. model = sysConfig.read(session, conditions={"key": "action_configs"})
  731. if model == None:
  732. return {"code": 1, "msg": "配置不存在", "data": None}
  733. config_value = json.loads(model.value)
  734. config_value[params.type] = params.id
  735. update_value = json.dumps(config_value)
  736. # 走编辑逻辑
  737. kwargs = {"key": "action_configs", "value": update_value}
  738. save_device_config = sysConfig.updateConditions(
  739. session, conditions={"key": "action_configs"}, **kwargs
  740. )
  741. return {"code": 0, "msg": "操作成功", "data": None}
  742. @app.post("/update_record", description="更新拍照记录")
  743. def update_record(params: RecordUpdate):
  744. session = SqlQuery()
  745. photoRecord = CRUD(PhotoRecord)
  746. model = photoRecord.read(session, conditions={"id": params.id})
  747. if model == None:
  748. return {"code": 1, "msg": "记录不存在", "data": None}
  749. kwargs = params.__dict__
  750. save_device_config = photoRecord.update(session, obj_id=params.id, **kwargs)
  751. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  752. @app.post("/update_sys_configs", description="创建或修改系统配置")
  753. def save_sys_configs(params: SysConfigParams):
  754. session = SqlQuery()
  755. sysConfig = CRUD(SysConfigs)
  756. model = sysConfig.read(session, conditions={"key": params.key})
  757. if model == None:
  758. return {"code": 1, "msg": "配置不存在", "data": None}
  759. # 走编辑逻辑
  760. kwargs = params.__dict__
  761. save_device_config = sysConfig.updateConditions(
  762. session, conditions={"key": params.key}, **kwargs
  763. )
  764. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  765. @app.post("/create_main_image", description="创建主图测试")
  766. def create_main_image(params: MaineImageTest):
  767. file_path = params.file_path
  768. onePic = OnePicTest(pic_path=file_path)
  769. main_out_path = onePic.HandlerMainImage()
  770. return {"code": 0, "msg": "操作成功", "data": {"main_out_path": main_out_path}}
  771. def insertEmptyLogoList(session):
  772. """插入空logo列表"""
  773. data = {"key": "logo_configs", "value": "[]"}
  774. config = SysConfigs(**data)
  775. session.add(config)
  776. session.commit()
  777. session.close()
  778. item = SysConfigs()
  779. item.key = "logo_configs"
  780. item.value = "[]"
  781. return item
  782. @app.get("/logo_list", description="logo列表")
  783. def logo_list():
  784. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  785. check_path(logo_dir)
  786. logo_files = os.listdir(logo_dir)
  787. logo_list = []
  788. for logoItem in logo_files:
  789. logo_list.append(f"{logo_dir}{logoItem}")
  790. return {"code": 0, "msg": "操作成功", "data": logo_list}
  791. @app.post("/add_logo", description="添加logo")
  792. def add_logo(params: LogoParams):
  793. logo_path = params.logo_path.replace("\\", "/")
  794. session = SqlQuery()
  795. sysConfig = CRUD(SysConfigs)
  796. item = sysConfig.read(session, conditions={"key": "logo_configs"})
  797. if item == None:
  798. item = insertEmptyLogoList(session)
  799. if os.path.isfile(logo_path) == False:
  800. return {"code": 1, "msg": "logo文件不存在", "data": None}
  801. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  802. check_path(logo_dir)
  803. fpath, fname = os.path.split(logo_path)
  804. logo_path_info = logo_dir + fname
  805. shutil.copy(logo_path, logo_path_info) # 复制文件
  806. logo_files = os.listdir(logo_dir)
  807. logo_list = []
  808. for logoItem in logo_files:
  809. logo_list.append(f"{logo_dir}{logoItem}")
  810. return {
  811. "code": 0,
  812. "msg": "",
  813. "data": {"logo": logo_path_info},
  814. }
  815. @app.post("/delete_logo", description="删除logo")
  816. def delete_logo(params: LogoParamsupdate):
  817. logo_path = params.path
  818. if os.path.isfile(logo_path) == False:
  819. return {"code": 1, "msg": "logo文件不存在", "data": None}
  820. os.remove(logo_path)
  821. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  822. check_path(logo_dir)
  823. logo_files = os.listdir(logo_dir)
  824. logo_list = []
  825. for logoItem in logo_files:
  826. logo_list.append(f"{logo_dir}{logoItem}")
  827. return {"code": 0, "msg": "操作成功", "data": logo_list}
  828. @app.post("/close_other_window", description="关闭窗口")
  829. def close_other_window():
  830. hwnd_list = []
  831. def callback(hwnd, _):
  832. title = GetWindowText(hwnd)
  833. if title == "digiCamControl by Duka Istvan":
  834. hwnd_list.append(hwnd)
  835. EnumWindows(callback, None)
  836. if hwnd_list:
  837. hwnd = hwnd_list[0]
  838. win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
  839. return {"code": 0, "msg": "关闭成功", "data": {"status": True}}
  840. return {"code": 0, "msg": "关闭失败", "data": {"status": False}}