storage_facility.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. """存储设施(树结构)+ 小格 CRUD(biz_storage_facility / biz_storage_facility_slot)"""
  2. from __future__ import annotations
  3. from datetime import datetime
  4. import re
  5. from typing import Any, Dict, List, Optional
  6. from sqlalchemy import and_, case, false, func, or_
  7. from sqlalchemy.orm import Session
  8. from app.core.utils import generate_uuid
  9. from app.models.models import BizStorageFacility, BizStorageFacilitySlot
  10. from app.services.storage_facility_code import (
  11. assert_sibling_node_code_unique,
  12. build_full_slot_code,
  13. build_node_code_path,
  14. cascade_refresh_slot_name_snapshots_for_nodes,
  15. cascade_refresh_slot_name_snapshots_for_slots,
  16. decode_slot_layout_order,
  17. encode_slot_layout_order,
  18. load_facility_ancestor_map,
  19. load_facility_map,
  20. validate_node_code,
  21. )
  22. # ---------------------------------------------------------------------------
  23. # Facility node helpers
  24. # ---------------------------------------------------------------------------
  25. def _row_to_dict(f: BizStorageFacility) -> Dict[str, Any]:
  26. return {
  27. "id": f.id,
  28. "parentId": f.parent_id,
  29. "nodeName": f.node_name,
  30. "nodeCode": f.node_code or "",
  31. "nodeType": f.node_type or "",
  32. "isLeaf": 1 if f.is_leaf else 0,
  33. "tenantNo": f.tenant_no,
  34. "orderNum": f.order_num if f.order_num is not None else 0,
  35. "remark": f.remark or "",
  36. "createTime": f.create_time.strftime("%Y-%m-%d %H:%M:%S") if f.create_time else "",
  37. "updateTime": f.update_time.strftime("%Y-%m-%d %H:%M:%S") if f.update_time else "",
  38. }
  39. def list_all_facilities(
  40. db: Session,
  41. *,
  42. tenant_no: str,
  43. keyword: Optional[str] = None,
  44. ) -> List[Dict[str, Any]]:
  45. """Return FLAT list of all non-deleted facility nodes (no pagination, no tree building)."""
  46. q = db.query(BizStorageFacility).filter(BizStorageFacility.del_flag == 0)
  47. if tenant_no:
  48. q = q.filter(BizStorageFacility.tenant_no == tenant_no)
  49. kw = (keyword or "").strip()
  50. if kw:
  51. like = f"%{kw}%"
  52. q = q.filter(
  53. or_(
  54. BizStorageFacility.node_name.like(like),
  55. BizStorageFacility.node_code.like(like),
  56. )
  57. )
  58. rows = q.order_by(BizStorageFacility.order_num.asc(), BizStorageFacility.create_time.asc()).all()
  59. return [_row_to_dict(x) for x in rows]
  60. def get_facility(db: Session, node_id: str, tenant_no: Optional[str] = None) -> Optional[BizStorageFacility]:
  61. q = db.query(BizStorageFacility).filter(
  62. and_(BizStorageFacility.id == node_id, BizStorageFacility.del_flag == 0)
  63. )
  64. if tenant_no:
  65. q = q.filter(BizStorageFacility.tenant_no == tenant_no)
  66. return q.first()
  67. def get_children(db: Session, parent_id: str, tenant_no: str) -> List[BizStorageFacility]:
  68. """Direct children of a node."""
  69. return (
  70. db.query(BizStorageFacility)
  71. .filter(
  72. and_(
  73. BizStorageFacility.parent_id == parent_id,
  74. BizStorageFacility.del_flag == 0,
  75. BizStorageFacility.tenant_no == tenant_no,
  76. )
  77. )
  78. .order_by(BizStorageFacility.order_num.asc(), BizStorageFacility.create_time.asc())
  79. .all()
  80. )
  81. def collect_descendant_ids(db: Session, node_id: str, tenant_no: str) -> List[str]:
  82. """Iteratively collect ALL descendant node IDs (stack-based, no recursion)."""
  83. ids: List[str] = []
  84. stack: List[str] = [node_id]
  85. while stack:
  86. current = stack.pop()
  87. children = get_children(db, current, tenant_no)
  88. for child in children:
  89. ids.append(child.id)
  90. stack.append(child.id)
  91. return ids
  92. def create_facility(
  93. db: Session,
  94. *,
  95. parent_id: str = "0",
  96. node_name: str,
  97. node_code: str,
  98. node_type: Optional[str] = None,
  99. is_leaf: int = 0,
  100. tenant_no: str = "zkxw",
  101. order_num: Optional[int] = None,
  102. remark: Optional[str] = None,
  103. user_id: Optional[str] = None,
  104. ) -> BizStorageFacility:
  105. name = (node_name or "").strip()
  106. if not name:
  107. raise ValueError("节点名称不能为空")
  108. code = validate_node_code(node_code)
  109. pid = parent_id or "0"
  110. assert_sibling_node_code_unique(
  111. db, parent_id=pid, node_code=code, tenant_no=tenant_no
  112. )
  113. obj = BizStorageFacility(
  114. id=generate_uuid(),
  115. parent_id=pid,
  116. node_name=name,
  117. node_code=code,
  118. node_type=(node_type or "").strip() or None,
  119. is_leaf=is_leaf,
  120. tenant_no=tenant_no,
  121. order_num=order_num if order_num is not None else 0,
  122. remark=(remark or "").strip() or None,
  123. create_by=user_id,
  124. create_dept_id="",
  125. create_time=datetime.now(),
  126. update_by=user_id,
  127. update_time=datetime.now(),
  128. del_flag=0,
  129. )
  130. db.add(obj)
  131. db.commit()
  132. db.refresh(obj)
  133. return obj
  134. def _format_seq(num: int, pad_width: int) -> str:
  135. s = str(num)
  136. width = int(pad_width or 0)
  137. if width <= 0:
  138. return s
  139. return s.zfill(width)
  140. def batch_create_facilities(
  141. db: Session,
  142. *,
  143. parent_id: str = "0",
  144. name_prefix: str = "",
  145. name_suffix: str = "",
  146. start_num: int,
  147. end_num: int,
  148. pad_width: int = 0,
  149. code_prefix: str = "",
  150. code_suffix: str = "",
  151. node_type: Optional[str] = None,
  152. is_leaf: int = 0,
  153. tenant_no: str = "zkxw",
  154. remark: Optional[str] = None,
  155. user_id: Optional[str] = None,
  156. ) -> List[Dict[str, Any]]:
  157. """按「前缀 + 序号 + 后缀」批量创建同级子节点。"""
  158. if start_num < 0 or end_num < 0:
  159. raise ValueError("序号不能为负数")
  160. if end_num < start_num:
  161. raise ValueError("结束序号不能小于起始序号")
  162. count = end_num - start_num + 1
  163. if count > 200:
  164. raise ValueError("单次最多创建 200 个子节点")
  165. if pad_width < 0 or pad_width > 8:
  166. raise ValueError("位数补零须在 0~8 之间")
  167. pid = (parent_id or "0").strip() or "0"
  168. if pid != "0":
  169. parent = get_facility(db, pid, tenant_no=tenant_no)
  170. if not parent:
  171. raise ValueError("上级节点不存在")
  172. name_prefix = name_prefix or ""
  173. name_suffix = name_suffix or ""
  174. code_prefix = code_prefix or ""
  175. code_suffix = code_suffix or ""
  176. node_type_val = (node_type or "").strip() or None
  177. remark_val = (remark or "").strip() or None
  178. leaf_val = 1 if int(is_leaf or 0) == 1 else 0
  179. now = datetime.now()
  180. planned: List[tuple[str, str, int]] = []
  181. seen_codes: set[str] = set()
  182. for num in range(start_num, end_num + 1):
  183. seq = _format_seq(num, pad_width)
  184. name = f"{name_prefix}{seq}{name_suffix}".strip()
  185. if not name:
  186. raise ValueError("节点名称不能为空,请填写前缀或后缀")
  187. # 前缀、后缀都空时,节点编号 = 序号(含补零)
  188. code = validate_node_code(f"{code_prefix}{seq}{code_suffix}")
  189. if not code:
  190. raise ValueError("节点编号不能为空")
  191. if code in seen_codes:
  192. raise ValueError(f"批次内节点编号重复:{code}")
  193. seen_codes.add(code)
  194. assert_sibling_node_code_unique(
  195. db, parent_id=pid, node_code=code, tenant_no=tenant_no
  196. )
  197. planned.append((name, code, num))
  198. objs: List[BizStorageFacility] = []
  199. for name, code, num in planned:
  200. obj = BizStorageFacility(
  201. id=generate_uuid(),
  202. parent_id=pid,
  203. node_name=name,
  204. node_code=code,
  205. node_type=node_type_val,
  206. is_leaf=leaf_val,
  207. tenant_no=tenant_no,
  208. order_num=num,
  209. remark=remark_val,
  210. create_by=user_id,
  211. create_dept_id="",
  212. create_time=now,
  213. update_by=user_id,
  214. update_time=now,
  215. del_flag=0,
  216. )
  217. db.add(obj)
  218. objs.append(obj)
  219. db.commit()
  220. for obj in objs:
  221. db.refresh(obj)
  222. return [_row_to_dict(obj) for obj in objs]
  223. def update_facility(
  224. db: Session,
  225. node_id: str,
  226. *,
  227. node_name: Optional[str] = None,
  228. node_code: Optional[str] = None,
  229. node_type: Optional[str] = None,
  230. is_leaf: Optional[int] = None,
  231. order_num: Optional[int] = None,
  232. remark: Optional[str] = None,
  233. user_id: Optional[str] = None,
  234. tenant_no: Optional[str] = None,
  235. ) -> BizStorageFacility:
  236. obj = get_facility(db, node_id, tenant_no=tenant_no)
  237. if not obj:
  238. raise ValueError("存储设施节点不存在")
  239. old_node_code = (obj.node_code or "").strip()
  240. if node_name is not None:
  241. name = (node_name or "").strip()
  242. if not name:
  243. raise ValueError("节点名称不能为空")
  244. obj.node_name = name
  245. if node_code is not None:
  246. code = validate_node_code(node_code)
  247. assert_sibling_node_code_unique(
  248. db,
  249. parent_id=obj.parent_id or "0",
  250. node_code=code,
  251. tenant_no=obj.tenant_no,
  252. exclude_id=obj.id,
  253. )
  254. obj.node_code = code
  255. if node_type is not None:
  256. obj.node_type = (node_type or "").strip() or None
  257. if is_leaf is not None:
  258. obj.is_leaf = is_leaf
  259. if order_num is not None:
  260. obj.order_num = order_num
  261. if remark is not None:
  262. obj.remark = (remark or "").strip() or None
  263. obj.update_by = user_id
  264. obj.update_time = datetime.now()
  265. db.add(obj)
  266. node_code_changed = node_code is not None and (obj.node_code or "").strip() != old_node_code
  267. if node_code_changed:
  268. cascade_refresh_slot_name_snapshots_for_nodes(
  269. db,
  270. [node_id],
  271. obj.tenant_no,
  272. collect_descendant_ids_fn=collect_descendant_ids,
  273. )
  274. db.commit()
  275. db.refresh(obj)
  276. return obj
  277. def soft_delete_facility(db: Session, node_id: str, tenant_no: Optional[str] = None) -> None:
  278. """Cascade soft-delete: node + all descendants + their slots."""
  279. node = get_facility(db, node_id, tenant_no=tenant_no)
  280. if not node:
  281. raise ValueError("存储设施节点不存在")
  282. # Collect all descendant IDs
  283. all_ids = [node_id] + collect_descendant_ids(db, node_id, node.tenant_no)
  284. now = datetime.now()
  285. # Soft-delete all slots belonging to these nodes
  286. db.query(BizStorageFacilitySlot).filter(
  287. BizStorageFacilitySlot.facility_node_id.in_(all_ids),
  288. BizStorageFacilitySlot.del_flag == 0,
  289. ).update({"del_flag": 1, "update_time": now}, synchronize_session=False)
  290. # Soft-delete all facility nodes
  291. db.query(BizStorageFacility).filter(
  292. BizStorageFacility.id.in_(all_ids),
  293. BizStorageFacility.del_flag == 0,
  294. ).update({"del_flag": 1, "update_time": now}, synchronize_session=False)
  295. db.commit()
  296. # ---------------------------------------------------------------------------
  297. # Slot helpers
  298. # ---------------------------------------------------------------------------
  299. def _slot_to_dict(
  300. s: BizStorageFacilitySlot,
  301. facility_by_id: Optional[Dict[str, BizStorageFacility]] = None,
  302. ) -> Dict[str, Any]:
  303. occupied_count = s.occupied_count if s.occupied_count is not None else 0
  304. full_slot_code = ""
  305. if facility_by_id is not None:
  306. full_slot_code = build_full_slot_code(s.facility_node_id, s.slot_code, facility_by_id)
  307. return {
  308. "id": s.id,
  309. "facilityNodeId": s.facility_node_id,
  310. "slotCode": s.slot_code or "",
  311. "fullSlotCode": full_slot_code,
  312. "slotStatus": s.slot_status or "",
  313. "occupiedCount": int(occupied_count),
  314. "tenantNo": s.tenant_no,
  315. "orderNum": s.order_num if s.order_num is not None else 0,
  316. "remark": s.remark or "",
  317. "createTime": s.create_time.strftime("%Y-%m-%d %H:%M:%S") if s.create_time else "",
  318. "updateTime": s.update_time.strftime("%Y-%m-%d %H:%M:%S") if s.update_time else "",
  319. }
  320. def aggregate_slot_stats_by_facility(*, query) -> List[Dict[str, Any]]:
  321. """按设施叶子节点聚合格子总数与占用数(单次 GROUP BY,供树节点徽章展示)。"""
  322. rows = (
  323. query.with_entities(
  324. BizStorageFacilitySlot.facility_node_id,
  325. func.count(BizStorageFacilitySlot.id).label("total"),
  326. func.sum(
  327. case((BizStorageFacilitySlot.slot_status == "占用", 1), else_=0)
  328. ).label("occupied"),
  329. )
  330. .group_by(BizStorageFacilitySlot.facility_node_id)
  331. .all()
  332. )
  333. result: List[Dict[str, Any]] = []
  334. for facility_node_id, total, occupied in rows:
  335. total_int = int(total or 0)
  336. occupied_int = int(occupied or 0)
  337. result.append(
  338. {
  339. "facilityNodeId": facility_node_id,
  340. "total": total_int,
  341. "occupied": occupied_int,
  342. "empty": total_int - occupied_int,
  343. }
  344. )
  345. return result
  346. def list_slots(
  347. db: Session,
  348. *,
  349. facility_node_id: str,
  350. tenant_no: Optional[str] = None,
  351. ) -> List[Dict[str, Any]]:
  352. q = db.query(BizStorageFacilitySlot).filter(
  353. and_(
  354. BizStorageFacilitySlot.facility_node_id == facility_node_id,
  355. BizStorageFacilitySlot.del_flag == 0,
  356. )
  357. )
  358. if tenant_no:
  359. q = q.filter(BizStorageFacilitySlot.tenant_no == tenant_no)
  360. rows = q.order_by(BizStorageFacilitySlot.order_num.asc(), BizStorageFacilitySlot.create_time.asc()).all()
  361. facility_by_id = load_facility_map(db, tenant_no or "") if tenant_no else {}
  362. items = [_slot_to_dict(x, facility_by_id) for x in rows]
  363. if tenant_no:
  364. from app.crud import storage_occupancy as occupancy_svc
  365. items = occupancy_svc.enrich_slots_with_stored_cell_products(db, tenant_no, items)
  366. return items
  367. def _is_slot_available_row(row: Dict[str, Any]) -> bool:
  368. status = row.get("slotStatus") or ""
  369. occupied = int(row.get("occupiedCount") or 0)
  370. return status == "空" or occupied == 0
  371. def _slot_select_display_name(row: Dict[str, Any]) -> str:
  372. full = (row.get("fullSlotCode") or "").strip()
  373. code = (row.get("slotCode") or "").strip()
  374. return full or code or str(row.get("id") or "")
  375. def _slot_available_filter():
  376. """空格子:状态为「空」或 occupied_count 为 0 / NULL。"""
  377. return or_(
  378. BizStorageFacilitySlot.slot_status == "空",
  379. BizStorageFacilitySlot.occupied_count == 0,
  380. BizStorageFacilitySlot.occupied_count.is_(None),
  381. )
  382. def _facility_node_ids_matching_keyword(
  383. db: Session,
  384. tenant_no: str,
  385. keyword: str,
  386. ) -> set[str]:
  387. like = f"%{keyword.strip()}%"
  388. return {
  389. row[0]
  390. for row in db.query(BizStorageFacility.id)
  391. .filter(
  392. BizStorageFacility.tenant_no == tenant_no,
  393. BizStorageFacility.del_flag == 0,
  394. or_(
  395. BizStorageFacility.node_name.like(like),
  396. BizStorageFacility.node_code.like(like),
  397. ),
  398. )
  399. .all()
  400. }
  401. def _slot_matches_select_keyword(
  402. slot: BizStorageFacilitySlot,
  403. keyword: str,
  404. facility_by_id: Dict[str, BizStorageFacility],
  405. matching_node_ids: set[str],
  406. ) -> bool:
  407. """下拉关键词:完整 fullSlotCode 子串 + 备注 + 设施节点名/编号。"""
  408. kw = keyword.strip().lower()
  409. if not kw:
  410. return True
  411. row = _slot_to_dict(slot, facility_by_id)
  412. display = _slot_select_display_name(row).lower()
  413. if kw in display:
  414. return True
  415. remark = (row.get("remark") or "").lower()
  416. if kw in remark:
  417. return True
  418. if slot.facility_node_id in matching_node_ids:
  419. return True
  420. return False
  421. def _leaf_node_ids_for_path_prefix(
  422. facility_by_id: Dict[str, BizStorageFacility],
  423. path_prefix: str,
  424. ) -> set[str]:
  425. """按设施 node_code 路径前缀/子串匹配叶子节点(储物格挂在节点上)。"""
  426. prefix = (path_prefix or "").strip().lower()
  427. if not prefix:
  428. return set()
  429. result: set[str] = set()
  430. for node_id in facility_by_id:
  431. path = build_node_code_path(node_id, facility_by_id).lower()
  432. if not path:
  433. continue
  434. if (
  435. prefix in path
  436. or path in prefix
  437. or path.startswith(f"{prefix}-")
  438. or prefix.startswith(f"{path}-")
  439. ):
  440. result.add(node_id)
  441. return result
  442. def _build_node_path_cache(
  443. facility_by_id: Dict[str, BizStorageFacility],
  444. ) -> Dict[str, str]:
  445. return {
  446. node_id: build_node_code_path(node_id, facility_by_id)
  447. for node_id in facility_by_id
  448. }
  449. def _exact_node_ids_for_path(
  450. path_cache: Dict[str, str],
  451. path: str,
  452. ) -> List[str]:
  453. target = (path or "").strip().lower()
  454. if not target:
  455. return []
  456. return [
  457. node_id
  458. for node_id, node_path in path_cache.items()
  459. if (node_path or "").strip().lower() == target
  460. ]
  461. def _collect_slot_host_node_ids(
  462. path_cache: Dict[str, str],
  463. facility_by_id: Dict[str, BizStorageFacility],
  464. path: str,
  465. ) -> List[str]:
  466. """储物格只挂在叶子节点;路径命中非叶子(如 1-1 架子)时展开其下全部叶子层。"""
  467. target = (path or "").strip().lower()
  468. if not target:
  469. return []
  470. anchor_ids = _exact_node_ids_for_path(path_cache, path)
  471. if not anchor_ids:
  472. return []
  473. host_ids: List[str] = []
  474. seen: set[str] = set()
  475. child_prefix = f"{target}-"
  476. for anchor_id in anchor_ids:
  477. anchor = facility_by_id.get(anchor_id)
  478. if anchor and int(getattr(anchor, "is_leaf", 0) or 0) == 1:
  479. if anchor_id not in seen:
  480. seen.add(anchor_id)
  481. host_ids.append(anchor_id)
  482. continue
  483. for node_id, node_path in path_cache.items():
  484. if node_id in seen:
  485. continue
  486. node = facility_by_id.get(node_id)
  487. if not node or int(getattr(node, "is_leaf", 0) or 0) != 1:
  488. continue
  489. np = (node_path or "").strip().lower()
  490. if np.startswith(child_prefix):
  491. seen.add(node_id)
  492. host_ids.append(node_id)
  493. return host_ids
  494. def _resolve_path_keyword(
  495. path_cache: Dict[str, str],
  496. keyword: str,
  497. ) -> tuple[Optional[str], Optional[str]]:
  498. """
  499. 解析路径型储物格编号关键词。
  500. - '1-1-2-' -> ('1-1-2', None) 整盒
  501. - '1-1-2-1' -> ('1-1-2', '1') 精确格位
  502. - '1-1-2' -> ('1-1-2', None) 若存在该节点路径
  503. """
  504. kw = (keyword or "").strip()
  505. if not kw or "-" not in kw:
  506. return None, None
  507. if kw.endswith("-"):
  508. path = kw.rstrip("-").strip()
  509. if path and _exact_node_ids_for_path(path_cache, path):
  510. return path, None
  511. return None, None
  512. known_paths = {
  513. (path or "").strip().lower()
  514. for path in path_cache.values()
  515. if (path or "").strip()
  516. }
  517. parts = kw.split("-")
  518. for i in range(len(parts), 0, -1):
  519. candidate = "-".join(parts[:i]).strip()
  520. if not candidate:
  521. continue
  522. if candidate.lower() not in known_paths:
  523. continue
  524. slot_part = "-".join(parts[i:]).strip() if i < len(parts) else ""
  525. return candidate, slot_part or None
  526. return None, None
  527. def _build_slot_keyword_sql_filters(
  528. db: Session,
  529. tenant_no: str,
  530. keyword: str,
  531. facility_by_id: Dict[str, BizStorageFacility],
  532. matching_node_ids: set[str],
  533. ):
  534. """SQL 预筛:slot_code / remark / 设施节点 + 路径型关键词分段,缩小 Python 校验范围。"""
  535. kw = keyword.strip()
  536. like = f"%{kw}%"
  537. filters = [
  538. BizStorageFacilitySlot.slot_code.like(like),
  539. BizStorageFacilitySlot.remark.like(like),
  540. ]
  541. if matching_node_ids:
  542. filters.append(BizStorageFacilitySlot.facility_node_id.in_(list(matching_node_ids)))
  543. path_cache = _build_node_path_cache(facility_by_id)
  544. path_prefix, slot_part = _resolve_path_keyword(path_cache, kw)
  545. if path_prefix:
  546. host_nodes = _collect_slot_host_node_ids(path_cache, facility_by_id, path_prefix)
  547. if host_nodes:
  548. filters.append(BizStorageFacilitySlot.facility_node_id.in_(host_nodes))
  549. if slot_part:
  550. filters.append(BizStorageFacilitySlot.slot_code.like(f"{slot_part}%"))
  551. elif "-" in kw:
  552. prefix, loose_slot_part = kw.rsplit("-", 1)
  553. prefix = prefix.strip()
  554. loose_slot_part = loose_slot_part.strip()
  555. if loose_slot_part:
  556. filters.append(BizStorageFacilitySlot.slot_code.like(f"%{loose_slot_part}%"))
  557. if prefix:
  558. path_node_ids = _leaf_node_ids_for_path_prefix(facility_by_id, prefix)
  559. if path_node_ids:
  560. filters.append(BizStorageFacilitySlot.facility_node_id.in_(list(path_node_ids)))
  561. return filters
  562. # ---------------------------------------------------------------------------
  563. # Slot select options (remote dropdown)
  564. # ---------------------------------------------------------------------------
  565. SLOT_SELECT_DEFAULT_PAGE_SIZE = 20
  566. SLOT_SELECT_MAX_PAGE_SIZE = 50
  567. SLOT_SELECT_KEYWORD_SCAN_LIMIT = 120
  568. def _apply_slot_select_base_filters(
  569. query,
  570. *,
  571. available_only: bool = False,
  572. include_slot_ids: Optional[List[str]] = None,
  573. ):
  574. include_set = {
  575. str(x).strip()
  576. for x in (include_slot_ids or [])
  577. if str(x).strip()
  578. }
  579. filtered = query
  580. if available_only:
  581. availability = _slot_available_filter()
  582. if include_set:
  583. filtered = filtered.filter(
  584. or_(BizStorageFacilitySlot.id.in_(list(include_set)), availability)
  585. )
  586. else:
  587. filtered = filtered.filter(availability)
  588. return filtered
  589. def _search_slot_select_matched_ids(
  590. db: Session,
  591. filtered,
  592. tenant_no: str,
  593. keyword: str,
  594. *,
  595. max_results: int,
  596. ) -> List[str]:
  597. """关键词匹配储物格 ID(限量扫描,路径型编码优先精确匹配)。"""
  598. kw = (keyword or "").strip()
  599. if not kw or max_results <= 0:
  600. return []
  601. facility_by_id = load_facility_map(db, tenant_no)
  602. path_cache = _build_node_path_cache(facility_by_id)
  603. matching_node_ids = _facility_node_ids_matching_keyword(db, tenant_no, kw)
  604. matched_ids: List[str] = []
  605. seen: set[str] = set()
  606. def collect(rows: List[BizStorageFacilitySlot]) -> bool:
  607. for slot in rows:
  608. sid = slot.id
  609. if sid in seen:
  610. continue
  611. if _slot_matches_select_keyword(slot, kw, facility_by_id, matching_node_ids):
  612. seen.add(sid)
  613. matched_ids.append(sid)
  614. if len(matched_ids) >= max_results:
  615. return True
  616. return False
  617. order_clause = (
  618. BizStorageFacilitySlot.order_num.asc(),
  619. BizStorageFacilitySlot.create_time.asc(),
  620. )
  621. # 快路径:路径型编码 1-1-2- / 1-1-2 / 1-1-2-1 → 设施路径 + 可选格位前缀(非叶子展开子层)
  622. path_prefix, slot_part = _resolve_path_keyword(path_cache, kw)
  623. if path_prefix:
  624. host_nodes = _collect_slot_host_node_ids(path_cache, facility_by_id, path_prefix)
  625. if host_nodes:
  626. exact_q = filtered.filter(
  627. BizStorageFacilitySlot.facility_node_id.in_(host_nodes)
  628. )
  629. if slot_part:
  630. exact_q = exact_q.filter(
  631. BizStorageFacilitySlot.slot_code.like(f"{slot_part}%")
  632. )
  633. exact_rows = (
  634. exact_q.order_by(*order_clause)
  635. .limit(max(max_results * 2, 10))
  636. .all()
  637. )
  638. if collect(exact_rows):
  639. return matched_ids
  640. if matched_ids:
  641. return matched_ids
  642. keyword_filters = _build_slot_keyword_sql_filters(
  643. db, tenant_no, kw, facility_by_id, matching_node_ids
  644. )
  645. sql_q = filtered.filter(or_(*keyword_filters)).order_by(*order_clause)
  646. offset = 0
  647. batch_size = 40
  648. while len(matched_ids) < max_results and offset < SLOT_SELECT_KEYWORD_SCAN_LIMIT:
  649. rows = sql_q.offset(offset).limit(batch_size).all()
  650. if not rows:
  651. break
  652. if collect(rows):
  653. return matched_ids
  654. offset += batch_size
  655. return matched_ids
  656. def _apply_slot_select_query_filters(
  657. db: Session,
  658. query,
  659. *,
  660. tenant_no: str,
  661. keyword: Optional[str] = None,
  662. available_only: bool = False,
  663. include_slot_ids: Optional[List[str]] = None,
  664. ):
  665. """兼容旧调用:无关键词时等同 base;有关键词时返回 ID 过滤后的 query。"""
  666. filtered = _apply_slot_select_base_filters(
  667. query,
  668. available_only=available_only,
  669. include_slot_ids=include_slot_ids,
  670. )
  671. kw = (keyword or "").strip()
  672. if not kw:
  673. return filtered
  674. matched_ids = _search_slot_select_matched_ids(
  675. db,
  676. filtered,
  677. tenant_no,
  678. kw,
  679. max_results=SLOT_SELECT_KEYWORD_SCAN_LIMIT,
  680. )
  681. if not matched_ids:
  682. return filtered.filter(false())
  683. return filtered.filter(BizStorageFacilitySlot.id.in_(matched_ids))
  684. def _load_slot_select_include_rows(query, include_slot_ids: Optional[List[str]]):
  685. """按传入顺序加载需强制保留的储物格(编辑态当前选中格)。"""
  686. include_ids = [
  687. str(x).strip()
  688. for x in (include_slot_ids or [])
  689. if str(x).strip()
  690. ]
  691. if not include_ids:
  692. return []
  693. rows_by_id = {
  694. row.id: row
  695. for row in query.filter(BizStorageFacilitySlot.id.in_(include_ids)).all()
  696. }
  697. return [rows_by_id[sid] for sid in include_ids if sid in rows_by_id]
  698. def _merge_slot_select_rows_with_includes(
  699. page_rows: List[BizStorageFacilitySlot],
  700. include_rows: List[BizStorageFacilitySlot],
  701. ) -> List[BizStorageFacilitySlot]:
  702. """将 include 格置顶合并进当前页,避免分页把当前选中格挤出导致下拉显示 id。"""
  703. merged: List[BizStorageFacilitySlot] = []
  704. seen: set[str] = set()
  705. for row in list(include_rows or []) + list(page_rows or []):
  706. sid = row.id
  707. if not sid or sid in seen:
  708. continue
  709. seen.add(sid)
  710. merged.append(row)
  711. return merged
  712. def list_slot_select_options(
  713. db: Session,
  714. *,
  715. query,
  716. tenant_no: str,
  717. keyword: Optional[str] = None,
  718. available_only: bool = False,
  719. include_slot_ids: Optional[List[str]] = None,
  720. page: int = 1,
  721. page_size: int = SLOT_SELECT_DEFAULT_PAGE_SIZE,
  722. ) -> tuple[List[Dict[str, Any]], int]:
  723. """储物格下拉远程选项:默认 20 条;关键词检索限量扫描 + 路径快路径。"""
  724. page = max(int(page or 1), 1)
  725. page_size = max(
  726. min(int(page_size or SLOT_SELECT_DEFAULT_PAGE_SIZE), SLOT_SELECT_MAX_PAGE_SIZE),
  727. 1,
  728. )
  729. need_count = page * page_size
  730. include_rows = _load_slot_select_include_rows(query, include_slot_ids)
  731. filtered = _apply_slot_select_base_filters(
  732. query,
  733. available_only=available_only,
  734. include_slot_ids=include_slot_ids,
  735. )
  736. kw = (keyword or "").strip()
  737. order_clause = (
  738. BizStorageFacilitySlot.order_num.asc(),
  739. BizStorageFacilitySlot.create_time.asc(),
  740. )
  741. if kw:
  742. matched_ids = _search_slot_select_matched_ids(
  743. db,
  744. filtered,
  745. tenant_no,
  746. kw,
  747. max_results=need_count,
  748. )
  749. total = len(matched_ids)
  750. page_ids = matched_ids[(page - 1) * page_size : page * page_size]
  751. rows_by_id = {
  752. row.id: row
  753. for row in (
  754. filtered.filter(BizStorageFacilitySlot.id.in_(page_ids)).all()
  755. if page_ids
  756. else []
  757. )
  758. }
  759. rows = [rows_by_id[sid] for sid in page_ids if sid in rows_by_id]
  760. else:
  761. total = (
  762. filtered.order_by(None)
  763. .with_entities(func.count(BizStorageFacilitySlot.id))
  764. .scalar()
  765. or 0
  766. )
  767. rows = (
  768. filtered.order_by(*order_clause)
  769. .offset((page - 1) * page_size)
  770. .limit(page_size)
  771. .all()
  772. )
  773. rows = _merge_slot_select_rows_with_includes(rows, include_rows)
  774. if not rows:
  775. return [], int(total)
  776. facility_by_id = load_facility_map(db, tenant_no)
  777. result_list = []
  778. for slot_row in rows:
  779. row = _slot_to_dict(slot_row, facility_by_id)
  780. result_list.append(
  781. {
  782. "id": row.get("id"),
  783. "name": _slot_select_display_name(row),
  784. "fullSlotCode": row.get("fullSlotCode") or "",
  785. "slotCode": row.get("slotCode") or "",
  786. "facilityNodeId": row.get("facilityNodeId") or "",
  787. "slotStatus": row.get("slotStatus") or "",
  788. "occupiedCount": int(row.get("occupiedCount") or 0),
  789. }
  790. )
  791. return result_list, int(total)
  792. def get_slot(db: Session, slot_id: str, tenant_no: Optional[str] = None) -> Optional[BizStorageFacilitySlot]:
  793. q = db.query(BizStorageFacilitySlot).filter(
  794. and_(BizStorageFacilitySlot.id == slot_id, BizStorageFacilitySlot.del_flag == 0)
  795. )
  796. if tenant_no:
  797. q = q.filter(BizStorageFacilitySlot.tenant_no == tenant_no)
  798. return q.first()
  799. def _slot_to_dict_for_row(db: Session, s: BizStorageFacilitySlot) -> Dict[str, Any]:
  800. facility_by_id = load_facility_map(db, s.tenant_no)
  801. return _slot_to_dict(s, facility_by_id)
  802. def create_slot(
  803. db: Session,
  804. *,
  805. facility_node_id: str,
  806. slot_code: Optional[str] = None,
  807. slot_status: Optional[str] = None,
  808. tenant_no: str = "zkxw",
  809. order_num: Optional[int] = None,
  810. remark: Optional[str] = None,
  811. user_id: Optional[str] = None,
  812. at_row_num: Optional[int] = None,
  813. ) -> BizStorageFacilitySlot:
  814. fid = (facility_node_id or "").strip()
  815. if not fid:
  816. raise ValueError("所属设施节点不能为空")
  817. if at_row_num is not None:
  818. return insert_slot_at_row_end(
  819. db,
  820. facility_node_id=fid,
  821. row_num=at_row_num,
  822. slot_status=slot_status,
  823. tenant_no=tenant_no,
  824. remark=remark,
  825. user_id=user_id,
  826. )
  827. obj = BizStorageFacilitySlot(
  828. id=generate_uuid(),
  829. facility_node_id=fid,
  830. slot_code=(slot_code or "").strip() or None,
  831. slot_status=(slot_status or "").strip() or None,
  832. tenant_no=tenant_no,
  833. order_num=order_num if order_num is not None else 0,
  834. remark=(remark or "").strip() or None,
  835. create_by=user_id,
  836. create_dept_id="",
  837. create_time=datetime.now(),
  838. update_by=user_id,
  839. update_time=datetime.now(),
  840. del_flag=0,
  841. )
  842. db.add(obj)
  843. db.commit()
  844. db.refresh(obj)
  845. return obj
  846. def insert_slot_at_row_end(
  847. db: Session,
  848. *,
  849. facility_node_id: str,
  850. row_num: int,
  851. slot_status: Optional[str] = None,
  852. tenant_no: str = "zkxw",
  853. remark: Optional[str] = None,
  854. user_id: Optional[str] = None,
  855. ) -> BizStorageFacilitySlot:
  856. fid = (facility_node_id or "").strip()
  857. row = int(row_num)
  858. if row < 1:
  859. raise ValueError("行号参数不合法")
  860. node = db.query(BizStorageFacility).filter(
  861. and_(BizStorageFacility.id == fid, BizStorageFacility.del_flag == 0)
  862. ).first()
  863. if not node:
  864. raise ValueError("所属设施节点不存在")
  865. if not node.is_leaf:
  866. raise ValueError("只能为叶子节点创建格子")
  867. max_col = 0
  868. for slot in _list_facility_slots(db, fid, tenant_no):
  869. slot_row, slot_col = _resolve_slot_layout_position(slot)
  870. if slot_row == row:
  871. max_col = max(max_col, slot_col)
  872. _ensure_slot_layout_order(slot, user_id=user_id)
  873. now = datetime.now()
  874. obj = BizStorageFacilitySlot(
  875. id=generate_uuid(),
  876. facility_node_id=fid,
  877. slot_code=None,
  878. slot_status=(slot_status or "空").strip() or "空",
  879. tenant_no=tenant_no,
  880. order_num=encode_slot_layout_order(row, max_col + 1),
  881. remark=(remark or "").strip() or None,
  882. create_by=user_id,
  883. create_dept_id="",
  884. create_time=now,
  885. update_by=user_id,
  886. update_time=now,
  887. del_flag=0,
  888. )
  889. db.add(obj)
  890. db.commit()
  891. db.refresh(obj)
  892. return obj
  893. def update_slot(
  894. db: Session,
  895. slot_id: str,
  896. *,
  897. slot_code: Optional[str] = None,
  898. slot_status: Optional[str] = None,
  899. order_num: Optional[int] = None,
  900. remark: Optional[str] = None,
  901. user_id: Optional[str] = None,
  902. tenant_no: Optional[str] = None,
  903. ) -> BizStorageFacilitySlot:
  904. obj = get_slot(db, slot_id, tenant_no=tenant_no)
  905. if not obj:
  906. raise ValueError("存储设施小格不存在")
  907. old_slot_code = (obj.slot_code or "").strip()
  908. if slot_code is not None:
  909. obj.slot_code = (slot_code or "").strip() or None
  910. if slot_status is not None:
  911. obj.slot_status = (slot_status or "").strip() or None
  912. if order_num is not None:
  913. obj.order_num = order_num
  914. if remark is not None:
  915. obj.remark = (remark or "").strip() or None
  916. obj.update_by = user_id
  917. obj.update_time = datetime.now()
  918. db.add(obj)
  919. slot_code_changed = slot_code is not None and (obj.slot_code or "").strip() != old_slot_code
  920. if slot_code_changed:
  921. cascade_refresh_slot_name_snapshots_for_slots(db, [slot_id], obj.tenant_no)
  922. db.commit()
  923. db.refresh(obj)
  924. return obj
  925. def soft_delete_slot(db: Session, slot_id: str, tenant_no: Optional[str] = None, user_id: Optional[str] = None) -> None:
  926. obj = get_slot(db, slot_id, tenant_no=tenant_no)
  927. if not obj:
  928. raise ValueError("存储设施小格不存在")
  929. obj.del_flag = 1
  930. obj.update_time = datetime.now()
  931. obj.update_by = user_id
  932. db.add(obj)
  933. db.commit()
  934. def clear_slots_by_facility_node(
  935. db: Session,
  936. *,
  937. facility_node_id: str,
  938. tenant_no: str,
  939. user_id: Optional[str] = None,
  940. ) -> int:
  941. fid = (facility_node_id or "").strip()
  942. if not fid:
  943. raise ValueError("所属设施节点不能为空")
  944. node = db.query(BizStorageFacility).filter(
  945. and_(
  946. BizStorageFacility.id == fid,
  947. BizStorageFacility.del_flag == 0,
  948. BizStorageFacility.tenant_no == tenant_no,
  949. )
  950. ).first()
  951. if not node:
  952. raise ValueError("所属设施节点不存在")
  953. now = datetime.now()
  954. updated = db.query(BizStorageFacilitySlot).filter(
  955. BizStorageFacilitySlot.facility_node_id == fid,
  956. BizStorageFacilitySlot.del_flag == 0,
  957. BizStorageFacilitySlot.tenant_no == tenant_no,
  958. ).update(
  959. {"del_flag": 1, "update_time": now, "update_by": user_id},
  960. synchronize_session=False
  961. )
  962. db.commit()
  963. return int(updated or 0)
  964. # ---------------------------------------------------------------------------
  965. # Slot layout & sequential code helpers
  966. # ---------------------------------------------------------------------------
  967. def _resolve_slot_layout_position(slot: BizStorageFacilitySlot) -> tuple[int, int]:
  968. order = int(slot.order_num or 0)
  969. row, col = decode_slot_layout_order(order)
  970. if row > 0:
  971. return row, col
  972. match = re.match(r"^(.*?)(\d+)-(\d+)$", (slot.slot_code or "").strip())
  973. if match:
  974. return int(match.group(2)), int(match.group(3))
  975. return 0, 0
  976. def _ensure_slot_layout_order(
  977. slot: BizStorageFacilitySlot,
  978. *,
  979. user_id: Optional[str] = None,
  980. ) -> tuple[int, int]:
  981. row, col = _resolve_slot_layout_position(slot)
  982. if row > 0:
  983. expected = encode_slot_layout_order(row, col)
  984. if int(slot.order_num or 0) != expected:
  985. slot.order_num = expected
  986. if user_id:
  987. slot.update_by = user_id
  988. slot.update_time = datetime.now()
  989. return row, col
  990. return 0, 0
  991. def _list_facility_slots(
  992. db: Session,
  993. facility_node_id: str,
  994. tenant_no: str,
  995. ) -> List[BizStorageFacilitySlot]:
  996. return (
  997. db.query(BizStorageFacilitySlot)
  998. .filter(
  999. BizStorageFacilitySlot.facility_node_id == facility_node_id,
  1000. BizStorageFacilitySlot.del_flag == 0,
  1001. BizStorageFacilitySlot.tenant_no == tenant_no,
  1002. )
  1003. .order_by(
  1004. BizStorageFacilitySlot.order_num.asc(),
  1005. BizStorageFacilitySlot.create_time.asc(),
  1006. )
  1007. .all()
  1008. )
  1009. def batch_create_slots(
  1010. db: Session,
  1011. *,
  1012. facility_node_id: str,
  1013. rows: int,
  1014. cols: int,
  1015. tenant_no: str = "zkxw",
  1016. user_id: Optional[str] = None,
  1017. ) -> List[Dict[str, Any]]:
  1018. fid = (facility_node_id or "").strip()
  1019. if not fid:
  1020. raise ValueError("所属设施节点不能为空")
  1021. if rows < 1 or cols < 1:
  1022. raise ValueError("行数和列数必须大于 0")
  1023. if rows > 50 or cols > 50:
  1024. raise ValueError("单次最多生成 50×50 = 2500 个格子")
  1025. node = db.query(BizStorageFacility).filter(
  1026. and_(BizStorageFacility.id == fid, BizStorageFacility.del_flag == 0)
  1027. ).first()
  1028. if not node:
  1029. raise ValueError("所属设施节点不存在")
  1030. if not node.is_leaf:
  1031. raise ValueError("只能为叶子节点创建格子")
  1032. now = datetime.now()
  1033. slots: List[BizStorageFacilitySlot] = []
  1034. seq = 0
  1035. for r in range(1, rows + 1):
  1036. for c in range(1, cols + 1):
  1037. seq += 1
  1038. obj = BizStorageFacilitySlot(
  1039. id=generate_uuid(),
  1040. facility_node_id=fid,
  1041. slot_code=str(seq),
  1042. slot_status="空",
  1043. tenant_no=tenant_no,
  1044. order_num=encode_slot_layout_order(r, c),
  1045. remark=None,
  1046. create_by=user_id,
  1047. create_dept_id="",
  1048. create_time=now,
  1049. update_by=user_id,
  1050. update_time=now,
  1051. del_flag=0,
  1052. )
  1053. db.add(obj)
  1054. slots.append(obj)
  1055. db.commit()
  1056. facility_by_id = load_facility_map(db, tenant_no)
  1057. for s in slots:
  1058. db.refresh(s)
  1059. return [_slot_to_dict(s, facility_by_id) for s in slots]
  1060. def insert_row_and_shift_slots(
  1061. db: Session,
  1062. *,
  1063. facility_node_id: str,
  1064. after_row_num: int,
  1065. cols: int,
  1066. tenant_no: str = "zkxw",
  1067. user_id: Optional[str] = None,
  1068. ) -> Dict[str, int]:
  1069. fid = (facility_node_id or "").strip()
  1070. if not fid:
  1071. raise ValueError("所属设施节点不能为空")
  1072. if after_row_num < 0:
  1073. raise ValueError("插入行号参数不合法")
  1074. if cols < 1:
  1075. raise ValueError("列数必须大于 0")
  1076. node = db.query(BizStorageFacility).filter(
  1077. and_(
  1078. BizStorageFacility.id == fid,
  1079. BizStorageFacility.del_flag == 0,
  1080. BizStorageFacility.tenant_no == tenant_no,
  1081. )
  1082. ).first()
  1083. if not node:
  1084. raise ValueError("所属设施节点不存在")
  1085. if not node.is_leaf:
  1086. raise ValueError("只能为叶子节点新增格子行")
  1087. slots = _list_facility_slots(db, fid, tenant_no)
  1088. now = datetime.now()
  1089. shifted_count = 0
  1090. for slot in slots:
  1091. row_no, col_no = _ensure_slot_layout_order(slot, user_id=user_id)
  1092. if row_no <= 0:
  1093. continue
  1094. if row_no > after_row_num:
  1095. slot.order_num = encode_slot_layout_order(row_no + 1, col_no)
  1096. slot.update_by = user_id
  1097. slot.update_time = now
  1098. shifted_count += 1
  1099. insert_row_num = after_row_num + 1
  1100. created_slots: List[BizStorageFacilitySlot] = []
  1101. for col in range(1, cols + 1):
  1102. created_slots.append(
  1103. BizStorageFacilitySlot(
  1104. id=generate_uuid(),
  1105. facility_node_id=fid,
  1106. slot_code=None,
  1107. slot_status="空",
  1108. tenant_no=tenant_no,
  1109. order_num=encode_slot_layout_order(insert_row_num, col),
  1110. remark=None,
  1111. create_by=user_id,
  1112. create_dept_id="",
  1113. create_time=now,
  1114. update_by=user_id,
  1115. update_time=now,
  1116. del_flag=0,
  1117. )
  1118. )
  1119. if created_slots:
  1120. db.add_all(created_slots)
  1121. db.commit()
  1122. return {"shiftedCount": shifted_count, "createdCount": len(created_slots)}