api.py 33 KB

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