diff --git a/inventory-backend/app/api/v1/warehouse.py b/inventory-backend/app/api/v1/warehouse.py index 27837cc..c027a15 100644 --- a/inventory-backend/app/api/v1/warehouse.py +++ b/inventory-backend/app/api/v1/warehouse.py @@ -290,12 +290,8 @@ def batch_generate_locations(): parent = SysWarehouseLocation.query.get(parent_id) if not parent: return jsonify({'code': 404, 'msg': '父级库位不存在', 'data': None}) - parent_level = parent.level - parent_full_path = parent.full_path or '' current_parents = [parent_id] else: - parent_level = -1 # 顶级的话,第一层.level = 0 - parent_full_path = '' current_parents = [None] # 逐层处理规则 @@ -307,40 +303,38 @@ def batch_generate_locations(): end = rule.get('end', 1) pad = rule.get('pad', 1) - next_parents = [] new_locations = [] for parent_id in current_parents: - # 计算该父级下的 level + # 1. 动态获取当前特定父节点的信息(严禁放循环外面共享!) if parent_id is None: - level = 0 + current_level = 0 + current_parent_path = '' else: p = SysWarehouseLocation.query.get(parent_id) - level = p.level + 1 if p else 0 + current_level = (p.level + 1) if p else 0 + current_parent_path = p.full_path if p and p.full_path else '' + # 2. 生成当前父节点下的专属子节点 for num in range(start, end + 1): name = f"{prefix}{str(num).zfill(pad)}" - full_path = f"{parent_full_path}/{name}" if parent_full_path else name + # 路径由当前特定的 current_parent_path 决定 + full_path = f"{current_parent_path}/{name}" if current_parent_path else name location = SysWarehouseLocation( name=name, parent_id=parent_id, full_path=full_path, - level=level, + level=current_level, is_enabled=True ) db.session.add(location) new_locations.append(location) - # 立即刷新以获取 ID + # 单层循环结束后再 flush 和获取新 ID 列表 db.session.flush() - generated_ids.extend([loc.id for loc in new_locations]) - - # 下一层的父级列表 current_parents = [loc.id for loc in new_locations] - # 更新 full_path 的基准路径(为下一层准备) - if new_locations: - parent_full_path = new_locations[0].full_path + generated_ids.extend(current_parents) db.session.commit()