classification.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from fastapi import APIRouter, Request, Depends, Query, HTTPException, status,WebSocket,WebSocketDisconnect
  4. from common.security import valid_access_token,valid_websocket_token
  5. from fastapi.responses import JSONResponse
  6. from sqlalchemy.orm import Session
  7. from sqlalchemy.sql import func
  8. from common.auth_user import *
  9. from sqlalchemy import text
  10. from pydantic import BaseModel
  11. from common.BigDataCenterAPI import *
  12. from database import get_db
  13. from typing import List
  14. from models import *
  15. from utils import *
  16. from utils.spatial import *
  17. from utils.ry_system_util import *
  18. from common.websocketManager import *
  19. from openpyxl import load_workbook
  20. from PIL import Image
  21. import io
  22. import json
  23. import xlrd,os
  24. import traceback
  25. router = APIRouter()
  26. def classification_id_get_classification_info(db,id):
  27. query = db.query(TpPatternClassification)
  28. query = query.filter_by(classification_id = id,del_flag = '0')
  29. return query.first()
  30. def template_id_get_classification_list(db,id):
  31. query = db.query(TpPatternClassification)
  32. query = query.filter_by(template_id = id,del_flag = '0')
  33. query = query.order_by(TpPatternClassification.order_num.asc())
  34. return query.all()
  35. def template_id_get_template_info(db,id):
  36. query = db.query(TpPatternTemplate)
  37. query = query.filter_by(template_id = id,del_flag = '0')
  38. return query.first()
  39. def read_save_excel_img(file_path):
  40. wb = load_workbook(file_path)
  41. ws = wb.active
  42. data={}
  43. for drawing in ws._images:
  44. img_bytes = drawing._data()
  45. anchor = drawing.anchor
  46. # 锚点给出的是“起始行列”和“终止行列”
  47. col0, row0 = anchor._from.col, anchor._from.row
  48. img = Image.open(io.BytesIO(img_bytes))
  49. w, h = img.size # 像素宽高
  50. # print(f'第1张图片:宽={w}px, 高={h}px')
  51. name = new_guid()
  52. img.save(f'/data/upload/mergefile/uploads/{name}.png')
  53. data[f'{col0}-{row0}']={"size":[h, w],"image":f'{name}.png'}
  54. return data
  55. @router.post('/createImport')
  56. async def create_contact(
  57. request: Request,
  58. db: Session = Depends(get_db),
  59. body=Depends(remove_xss_json),
  60. auth_user: AuthUser = Depends(find_auth_user),
  61. user_id=Depends(valid_access_token)
  62. ):
  63. try:
  64. # 提取请求数据
  65. filename = body['filename']
  66. # file_name_desc = body['file_name_desc']
  67. template_id = body['template_id']
  68. if len(filename) == 0:
  69. raise Exception()
  70. file_path = f'/data/upload/mergefile/uploads/{filename}'
  71. # 检查文件是否存在
  72. if not os.path.isfile(file_path):
  73. return JSONResponse(status_code=404, content={
  74. 'errcode': 404,
  75. 'errmsg': f'{filename}不存在'
  76. })
  77. msg = '成功'
  78. code =200
  79. try:
  80. book = xlrd.open_workbook(file_path)
  81. sheet = book.sheet_by_index(0)
  82. img_list = read_save_excel_img(file_path)
  83. if sheet.nrows-1 != len(img_list):
  84. msg = f'\n文件图片缺失,请核实图片个数是否为 {sheet.nrows-1}'
  85. code = 500
  86. return JSONResponse(status_code=code, content={
  87. "code": code,
  88. "msg": msg,
  89. "data": None
  90. })
  91. except Exception as e:
  92. traceback.print_exc()
  93. msg = f'\n文件打开失败,请核实文件格式为xlsx/xlx>{str(e)}'
  94. code = 500
  95. return JSONResponse(status_code=code, content={
  96. "code": code,
  97. "msg": msg,
  98. "data": None
  99. })
  100. data = []
  101. import_status = True
  102. for row in range(1, sheet.nrows):
  103. name = sheet.cell(row, 0).value
  104. if name == '' or name==0:
  105. import_status = False
  106. msg = f'\n行<{row + 1}>分类名称不能为空<{name}>'
  107. code = 500
  108. value = 'marker'
  109. # value = sheet.cell(row, 1).value
  110. # if value == '':
  111. # import_status = False
  112. # msg = f'\n行<{row + 1}>分类值不能为空<{value}>'
  113. # code = 500
  114. try:
  115. img_data=img_list[f'1-{row}']
  116. except:
  117. import_status = False
  118. msg = f'\n行<{row + 1}>图片不能为空<{name}>'
  119. code = 500
  120. return JSONResponse(status_code=code, content={
  121. "code": code,
  122. "msg": msg,
  123. "data": None
  124. })
  125. new_classification = TpPatternClassification(
  126. classification_id=new_guid(),
  127. template_id=template_id,
  128. name=name,
  129. value=value,
  130. order_num=999,
  131. visible='1',
  132. image=img_data['image'],
  133. icon=value,
  134. size=img_data['size'],
  135. create_by=user_id
  136. )
  137. data.append(new_classification)
  138. if import_status:
  139. db.add_all(data)
  140. db.commit()
  141. except Exception as e:
  142. traceback.print_exc()
  143. # 处理异常
  144. db.rollback()
  145. code = 500
  146. msg = str(e)
  147. return JSONResponse(status_code=code, content={
  148. "code": code,
  149. "msg": msg,
  150. "data": None
  151. })
  152. @router.post("/create")
  153. async def create_pattern(
  154. user_id=Depends(valid_access_token),
  155. body = Depends(remove_xss_json),
  156. db: Session = Depends(get_db)
  157. ):
  158. try:
  159. if 'order_num' in body:
  160. order_num=body['order_num']
  161. else:
  162. info = db.query(func.max(TpPatternClassification.order_num).label('max_value')).filter_by(template_id=body['template_id']).first()
  163. if info.max_value:
  164. order_num=info.max_value+1
  165. else:
  166. order_num=1
  167. if 'visible'in body:
  168. visible=body['visible']
  169. else:
  170. visible='1'
  171. new_classification = TpPatternClassification(
  172. classification_id=new_guid(),
  173. template_id=body['template_id'],
  174. name=body['name'],
  175. value=body['value'],
  176. order_num = order_num,
  177. visible=visible,
  178. image=body['image'],
  179. icon=body['icon'],
  180. size=body['size'],
  181. create_by = user_id
  182. )
  183. db.add(new_classification)
  184. db.commit()
  185. return {"code": 200, "msg": "创建成功", "data": None}
  186. except Exception as e:
  187. traceback.print_exc()
  188. raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  189. @router.put("/update/{id}")
  190. async def update_classification(
  191. id :str ,
  192. user_id=Depends(valid_access_token),
  193. body=Depends(remove_xss_json),
  194. db: Session = Depends(get_db)
  195. ):
  196. try:
  197. update_classification = classification_id_get_classification_info(db,id)
  198. if not update_classification:
  199. return JSONResponse(status_code=404,content={"code":404,"msg":"classification not found"})
  200. update_classification.template_id = body['template_id']
  201. update_classification.name = body['name']
  202. update_classification.value=body['value']
  203. update_classification.order_num=body['order_num']
  204. update_classification.visible=body['visible']
  205. update_classification.image=body['image']
  206. update_classification.icon=body['icon']
  207. update_classification.size=body['size']
  208. update_classification.update_by = user_id
  209. db.commit()
  210. return {"code": 200, "msg": "更新成功"}
  211. except Exception as e:
  212. traceback.print_exc()
  213. raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  214. @router.get("/info/{id}")
  215. async def get_pattern_info(
  216. id: str,
  217. db: Session = Depends(get_db)
  218. ):
  219. try:
  220. info = classification_id_get_classification_info(db,id)
  221. if not info:
  222. return JSONResponse(status_code=404,content={"code":404,"msg":"classification not found"})
  223. template_info = template_id_get_template_info(db,info.template_id)
  224. data = {"classification_id": info.classification_id,
  225. "template_id": info.template_id,
  226. "template_name":template_info.name,
  227. "name": info.name,
  228. "value": info.value,
  229. "order_num": info.order_num,
  230. "visible": info.visible,
  231. "image": info.image,
  232. "icon": info.icon,
  233. "size": info.size,
  234. "create_time": info.create_time}
  235. return {"code": 200, "msg": "获取成功", "data": data}
  236. except Exception as e:
  237. traceback.print_exc()
  238. raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  239. @router.get("/list")
  240. async def get_pattern_list(
  241. name: str = Query(None, description='名称'),
  242. page: int = Query(1, gt=0, description='页码'),
  243. pageSize: int = Query(None, gt=0, description='每页条目数量'),
  244. db: Session = Depends(get_db)
  245. ):
  246. try:
  247. query = db.query(TpPatternClassification)
  248. query = query.filter_by(del_flag='0')
  249. if name:
  250. query = query.filter(TpPatternClassification.name.like(f'%{name}%'))
  251. total_items = query.count()
  252. # 排序
  253. if pageSize is None:
  254. pageSize=total_items
  255. query = query.order_by(TpPatternClassification.order_num.asc())
  256. # 执行分页查询
  257. lists = query.offset((page - 1) * pageSize).limit(pageSize).all()
  258. data = [ ]
  259. for info in lists:
  260. template_info = template_id_get_template_info(db, info.template_id)
  261. data.append({"classification_id": info.classification_id,
  262. "template_id": info.template_id,
  263. "template_name":template_info.name,
  264. "name": info.name,
  265. "value": info.value,
  266. "order_num": info.order_num,
  267. "visible": info.visible,
  268. "image": info.image,
  269. "icon": info.icon,
  270. "size": info.size,
  271. "create_time": info.create_time})
  272. return {"code": 200, "msg": "查询成功", "data": data,
  273. "total": total_items,
  274. "page": page,
  275. "pageSize": pageSize,
  276. "totalPages": (total_items + pageSize - 1) // pageSize
  277. }
  278. except Exception as e:
  279. traceback.print_exc()
  280. raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  281. @router.delete("/delete/{id}")
  282. async def delete_pattern(
  283. id: str,
  284. db: Session = Depends(get_db)
  285. ):
  286. try:
  287. # 检查图案是否存在
  288. info = classification_id_get_classification_info(db, id)
  289. if not info:
  290. return JSONResponse(status_code=404, content={"code": 404, "msg": "classification not found"})
  291. info.del_flag='2'
  292. db.commit()
  293. return {"code": 200, "msg": "删除成功"}
  294. except Exception as e:
  295. traceback.print_exc()
  296. raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  297. @router.put('/changeVisible')
  298. async def change_classification_visible(
  299. db: Session = Depends(get_db),
  300. body=Depends(remove_xss_json),
  301. user_id=Depends(valid_access_token)
  302. ):
  303. try:
  304. classification_id = body['classification_id']
  305. visible = body['visible']
  306. info = classification_id_get_classification_info(db, classification_id)
  307. if not info:
  308. return JSONResponse(status_code=404, content={"code": 404, "msg": "classification not found"})
  309. info.visible= visible
  310. info.update_by=user_id
  311. db.commit()
  312. return {
  313. "code": 200,
  314. "msg": "操作成功"
  315. }
  316. except Exception as e:
  317. # 处理异常
  318. traceback.print_exc()
  319. raise HTTPException(status_code=500, detail=str(e))
  320. @router.get("/templateTree")
  321. async def get_pattern_list(
  322. visible: str = Query(None, description='是否显示'),
  323. # page: int = Query(1, gt=0, description='页码'),
  324. # pageSize: int = Query(None, gt=0, description='每页条目数量'),
  325. db: Session = Depends(get_db)
  326. ):
  327. try:
  328. query = db.query(TpPatternTemplate)
  329. query = query.filter_by(del_flag='0')
  330. if visible is not None:
  331. query = query.filter_by(visible=visible)
  332. # if name:
  333. # query = query.filter(TpPatternTemplate.name.like(f'%{name}%'))
  334. # total_items = query.count()
  335. # # 排序
  336. # if pageSize is None:
  337. # pageSize=total_items
  338. query = query.order_by(TpPatternTemplate.order_num.asc())
  339. # 执行分页查询
  340. lists = query.all() # .offset((page - 1) * pageSize).limit(pageSize)
  341. data = []
  342. for info in lists:
  343. # print(1111)
  344. query1 = db.query(TpPatternClassification)
  345. query1 = query1.filter_by(template_id=info.template_id, del_flag='0')
  346. if visible is not None:
  347. query1 = query1.filter_by(visible=visible)
  348. query1 = query1.order_by(TpPatternClassification.order_num.asc())
  349. classification_list = query1.all()
  350. # =template_id_get_classification_list(db,info.template_id)
  351. template_info = {"template_id": info.template_id,
  352. "name": info.name,
  353. "value": info.value,
  354. "order_num": info.order_num,
  355. "visible": info.visible,
  356. "create_time": info.create_time}
  357. if classification_list:
  358. template_info['children']=[{"classification_id": classification.classification_id,
  359. "name": classification.name,
  360. "value": classification.value,
  361. "order_num": classification.order_num,
  362. "visible": classification.visible,
  363. "image": classification.image,
  364. "icon": classification.icon,
  365. "size": classification.size,
  366. "create_time": classification.create_time} for classification in classification_list]
  367. data.append(template_info)
  368. return {"code": 200, "msg": "查询成功", "data": data}
  369. except Exception as e:
  370. traceback.print_exc()
  371. raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")