storage_facility.py 38 KB

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