api.py 33 KB

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