api.py 33 KB

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