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