feat(小程序): 新增仓库管理内嵌面板与授权
首页 Tab 内嵌仓库管理面板:批次/可用/成本价/报告/入库时间 默认仅看可用,顶部统计库存批次、可用总量、可用货值 批量上传按 Web 流程:上传→识别→候选→人工确认,编辑可直传 新增权限码 warehouse_manage,默认赋予仓管,不映射 Web 菜单 6 条移动端薄路由,全部复用 Web 同一批 service 修复首页未转发 onReachBottom 导致内嵌列表只有第 1 页 修复录单员获授权后点仓库管理回弹(漏传 permissions)
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
# 小程序「仓库管理」:首页一级 Tab(库存批次 + 批量上传报告)
|
||||
|
||||
- 日期:2026-10-23
|
||||
- 需求(开发者原话):
|
||||
1. 「仓库管理放的就是和我们 web 的效果类似,展示入库的那些批次的库存、成本价、商品名,还能看到那些批次没有报告,小程序上就好进行批量上传」
|
||||
2. 「默认给仓管人员,但是其他成员也可以得到这个权限,相当于就是一个按钮」
|
||||
3. 「不影响 web,按理说上传修改这些相关接口、执行函数肯定是一样的,但是就是接口入口不一样而已,本质上就是将 web 界面的操作让小程序上也能执行操作」
|
||||
4. 「注意和其他模块一样,别给我整什么二级界面,规范一点,都统一在一级界面」
|
||||
- 状态:**已实施**(迁移 + 后端薄路由 + 小程序面板 + 测试)
|
||||
|
||||
## 1. 现状(改前代码事实)
|
||||
|
||||
| # | 事实 |
|
||||
|---|---|
|
||||
| F1 | 小程序首页模块可见性 = **先角色、再权限(AND)**(`modules/registry.js` `isModuleVisible`) |
|
||||
| F2 | 仓库侧原有 3 个入口(订单入库 / 库存入库 / 加工)都锁 `warehouse/inspector`,页面、面板、接口三层都拦角色 |
|
||||
| F3 | 小程序**没有**库存批次列表,也没有列表接口 |
|
||||
| F4 | Web 的执行函数都在 service 层可直接复用:`listInventoryForManagement` / `createInventoryBatchReportsForInventory` / `listReportsForInventory` / `deleteInventoryBatchReport` / `updateInventoryBatchAttributes` / `adjustInventoryAvailableQty` |
|
||||
| F5 | 小程序已有报告文件上传:`uploadQualityReportStorageFile()` → `POST /storage/quality-reports/upload` |
|
||||
| F6 | 小程序会话已带 `permissions`(登录 / 切角色刷新),首页放入 `pageData.permissions` |
|
||||
| F7 | 首页每个模块都是「首页一级 Tab 内嵌面板 + 一个薄页面」,例:`processing` → `<processing-panel embedded>` + `pages/processing/processing` |
|
||||
|
||||
## 2. 方案(已落地)
|
||||
|
||||
```
|
||||
首页一级 Tab(与 加工 / 库存入库 同一套规矩)
|
||||
└─「仓库管理」→ <warehouse-panel embedded>(components/warehouse-panel)
|
||||
├─ 顶部绿卡:库存批次 | 可用总量 | 可用货值(与列表同筛选口径,面板上报)
|
||||
├─ 搜索:品名 / 编码 / 批次号
|
||||
├─ 筛选行:仅有可用 · 缺报告(矩形选择框) | 共 N 批 | [批量上传报告]
|
||||
├─ 表格(表头 + 列对齐):商品(含批次/分类/入库时间小字) | 可用 | 成本价 | 报告
|
||||
│ 行点击 → 直接弹「修改」弹窗(可用数量 + 成本价 + 报告入口)
|
||||
├─ 弹层:批量上传报告(选文件 → 上传并识别 → 候选批次 → 确认匹配)
|
||||
├─ 弹层:修改(居中卡片,本批次可用数量 / 成本价 / 批次报告上传)
|
||||
└─ 弹层:批次报告(该批次报告列表 + 上传 + 逐条删除)
|
||||
```
|
||||
|
||||
- **不做二级页**:界面与逻辑都在面板组件里;`pages/warehouse/warehouse` 只是薄壳(`selectComponent` 转发下拉刷新/触底),供深链打开。
|
||||
- **入口授权**:新权限码 `warehouse_manage`;仓管默认有,其他角色在「角色权限 → 库存 → 仓库管理」勾选。
|
||||
- **Web 完全不受影响**:`warehouse_manage` 不映射任何 Web 菜单;Web 路由权限、页面一行未动。
|
||||
- **执行函数唯一**:移动端只加薄路由,内部调用与 Web 相同的 service。
|
||||
|
||||
## 3. 后端
|
||||
|
||||
### 3.1 迁移 `20261082_warehouse_manage_permission.sql`
|
||||
|
||||
- `permissions` 新增 `warehouse_manage`(`module='inventory'`),默认授予 `warehouse`(另含 `admin` / `super_admin`,与既有权限种子写法一致);
|
||||
- 不写 `PERMISSION_COVERS` ⇒ 勾它不会打开 Web 的「库存」「验收与加工」菜单。
|
||||
|
||||
### 3.2 移动端薄路由(`routes/mobile/mobileInventoryRoutes.ts`)
|
||||
|
||||
统一守卫 `requireWarehouseManageAccess(req)`(`mobileShared.ts`):角色命中(warehouse / inspector / admin)**或** 持 `warehouse_manage`(`inventory_manage` 等同放行)。
|
||||
|
||||
| 方法 & 路径 | 复用 service |
|
||||
|---|---|
|
||||
| `GET /mobile/inventory/batches` | `listInventoryForManagement`(分页/搜索/仅可用;返回精简字段) |
|
||||
| `GET /mobile/inventory/batches/:id/reports` | `listReportsForInventory` |
|
||||
| `POST /mobile/inventory/batches/:id/reports` | `createInventoryBatchReportsForInventory` |
|
||||
| `DELETE /mobile/inventory/batch-reports/:reportId` | `deleteInventoryBatchReport` |
|
||||
| `POST /mobile/inventory/batches/:id/cost-price` | `updateInventoryBatchAttributes`(成本改动仍由服务端重算未结算订单) |
|
||||
| `POST /mobile/inventory/batches/:id/available-qty` | `adjustInventoryAvailableQty`(双日志 + 审计口径不变) |
|
||||
|
||||
### 3.3 权限目录(Web「角色权限」页)
|
||||
|
||||
`src/config/permissionCatalog.ts` 新增 `warehouse_manage: { kind: 'menu', mobile: ['小程序仓库管理'], note: … }`
|
||||
⇒ 「可访问功能」与角色预览的「小程序功能」自动出现,**Web 菜单不出**。
|
||||
|
||||
## 4. 小程序
|
||||
|
||||
### 4.1 注册表与可见性
|
||||
|
||||
```js
|
||||
{
|
||||
id: 'warehouse',
|
||||
title: '仓库管理',
|
||||
subtitle: '库存批次、成本价与报告状态,可批量上传报告',
|
||||
page: '/pages/warehouse/warehouse',
|
||||
roles: ['warehouse'], // 默认可见
|
||||
grantable: true, // 角色不命中时,权限命中也可见
|
||||
permissionKey: 'warehouse_manage',
|
||||
handler: 'goWarehouse',
|
||||
homeEmbed: 'warehouse-panel',
|
||||
}
|
||||
```
|
||||
|
||||
- `isModuleVisible`:`grantable` 模块按「角色 或 权限」;其它模块保持原「AND」语义(零影响)。
|
||||
- `isHomeWorkspaceModule(mod, roles, fallbackRole, permissions)`:被授权用户同样把仓库管理当**一级 Tab**。
|
||||
⚠️ `pages/home/home.js` 的 `refreshMenuModules()` **必须把 `this.data.permissions` 传进去**(2026-10-25 修复:
|
||||
漏传时录单员点「仓库管理」会先切过去、再被退回到默认模块,表现为「回弹」);
|
||||
`notifyHomePanelShow` 也要登记 `warehouse → #warehouseHomePanel`,否则重复点同一 Tab 不刷新。
|
||||
- `pages/home/home.js`:`activateHomeModule` / `navigateToModule` 在被授权但角色不匹配时**不切角色**,直接内嵌 / 直链。
|
||||
- 页面守卫 `requireWarehouseModuleRole()`(`utils/roleGuard.js`):角色命中或 `session.permissions` 含 `warehouse_manage`。
|
||||
|
||||
### 4.2 交互细节
|
||||
|
||||
- **分页(2026-10-25 开发者提醒)**:每页固定 **20** 条(`PAGE_SIZE`),服务端 `LIMIT/OFFSET`(`clampManagementPage`),
|
||||
小程序按 `hasMore` 追加。⚠️ 首页内嵌面板不会自己收到页面触底事件 —— `pages/home/home.js` 必须把
|
||||
`onReachBottom` 转给当前模块面板(`HOME_PANEL_SELECTORS`),否则只能看到第 1 页(表现为「没做分页」)。
|
||||
- **筛选与批量上传同一行**(开发者:「能否整齐的排列成为一行」「用方形选择框 而不是这种椭圆形」):
|
||||
`仅有可用 / 缺报告` 两个**矩形圆角选择框**(高度 60rpx、圆角 10rpx,不再是 999rpx 糖丸)在左,`共 N 批` 靠右,
|
||||
「批量上传报告」是最右侧的**矩形按钮**(同高度 / 同圆角);窄屏时只截断总数,不把按钮挤出屏幕。
|
||||
**一进面板默认勾选「仅有可用」**(2026-10-25 开发者:「仅有可用这个是默认选择的 一进去」),
|
||||
因此列表与顶部统计卡都只含可用批次;取消勾选后才会带出 0 库存批次。
|
||||
- **顶部统计卡(开发者:「顶部这块展示 库存批次数量 可用总量 可用货值」)**:
|
||||
面板 `loadPage` 成功后 `triggerEvent('statschange')`,首页把它们渲染成绿色三格卡,取代原来的「仓库管理」标题卡
|
||||
(`showWarehouseStats` 计入 `hasDedicatedProgress`,标题卡自动不显)。
|
||||
三个数**全部来自服务端同一 `where` 的 `stats`**(搜索 / 仅有可用一致):批次数量取 `total`、
|
||||
`total_available_qty`、`total_value = Σ(available_qty × cost_price)`,小程序侧只做千位分隔与两位小数,不另算。
|
||||
- **列表是表格布局**(开发者:「布局优化一下要像表格一样才行」):表头 `商品 | 可用 | 成本价 | 报告` 与行内列对齐,
|
||||
商品列三行(名 + `批次号 · 分类` 小字 + `入库 YYYY-MM-DD` 小字);「报告」列本身仍可直接点开该批次报告。
|
||||
入库时间与 Web 同一字段 `inbound_at`(该批次**最早一次**入库流水 `stock_in / inspection_in`),
|
||||
移动端薄路由只负责把它映射出来,不改查询口径;无流水的旧批次显示 `入库 —`。
|
||||
- **点行直接弹「修改」弹窗**(开发者:「点击了某一个商品应该是直接展示一个修改弹窗……而不是我还得二次的进行选择」):
|
||||
弹窗一次给出 `可用数量(本批次)`、`成本价(本批次)` 与「批次报告 ›」入口;保存时**只提交真正改过的字段**
|
||||
(数量走 `/available-qty`、成本价走 `/cost-price`,两条写路径各自带审计/流水),都没改则提示「没有改动」。
|
||||
形态是**居中卡片**(与 Web 库存调整弹窗同形,`max-width: 660rpx`),不再用 `wx.showActionSheet`(原生菜单贴物理底边、且要多点一步)。
|
||||
- **弹层必须放在 `<root-portal>` 里**(开发者:「弹窗不能随着界面的滚动而滚动」「弹窗不应该是直接覆盖了底部的选择栏吗」):
|
||||
首页 `.home-*-embed` 的 `transform` 会把 `position: fixed` 困在容器内 ⇒ 弹层跟随页面滚动、且被底部 tab 栏压住。
|
||||
**每个弹层各自包一个 `root-portal`(单子节点)** —— 一个 portal 里塞多个弹层会让 portal 不生效(与加工 / 分拣面板同款做法);
|
||||
`z-index: 10000`(底部 tab 是 100),遮罩四边显式写 `top/right/bottom/left: 0` + `catchtouchmove` 吃掉滚动。
|
||||
弹层按「头 / 体 / 脚」三段:头部与按钮行固定,只有 `scroll-view` 的 body 内部滚动(长列表不把按钮推出屏幕),
|
||||
`max-height: 82vh`,底部留 `env(safe-area-inset-bottom)`(旧基础库用 `constant()` 兜底)。
|
||||
- **编辑弹窗里可直接上传该批次报告**(开发者:「编辑这里可以上传批次报告的」):
|
||||
「批次报告」行右侧加「上传」,报告弹窗顶部也有「上传报告」——都是**单批次直传**
|
||||
(`chooseMedia/chooseMessageFile` → `uploadQualityReportStorageFile` → `POST /mobile/inventory/batches/:id/reports`,
|
||||
与 Web「修改」弹窗同一条 service);上传后刷新报告列表、编辑弹窗里的 `N 个 / 缺少` 与表格的报告列。
|
||||
- **批量上传 = 上传 → 识别 → 匹配 → 确认(与 Web 同流程)**(开发者:「他是上传了去匹配 而不是自己勾选哪些商品再去上传」):
|
||||
`wx.chooseMedia`(拍照/相册)或 `wx.chooseMessageFile`(PDF 等)选文件 → 逐个 `uploadQualityReportStorageFile` →
|
||||
`POST /mobile/inventory/batch-reports/parse` 由服务端 OCR 并按「商品名 + 生产日期」给出候选批次 →
|
||||
**`unique` 自动勾选、其余人工确认** → `POST /mobile/inventory/batch-reports/:reportId/confirm` 逐份绑定 → 刷新列表。
|
||||
列表页**不再有行勾选 / 全选**(勾选态已整体移除)。
|
||||
- 报告:点「报告 N 个 / 缺少批次报告」→ 弹层列出该批次报告(类型 / 编号 / 上传时间),逐条删除(二次确认)。
|
||||
- 「缺报告」为本地筛选(服务端列表口径不动),分页 `hasMore` 按原始条数判断,避免筛完误判到底。
|
||||
|
||||
## 5. 改动清单(已落地)
|
||||
|
||||
| 层 | 文件 |
|
||||
|---|---|
|
||||
| 数据 | `migrations/20261082_warehouse_manage_permission.sql`(新增) |
|
||||
| 后端 | `server/src/modules/businessModules.ts`、`server/src/routes/mobile/mobileShared.ts`、`server/src/routes/mobile/mobileInventoryRoutes.ts` |
|
||||
| 后端测试 | `server/tests/mobileWarehouseManage.test.ts`(新增,9 条) |
|
||||
| 前端 | `src/config/permissionCatalog.ts` |
|
||||
| 小程序 | `miniprogram/modules/registry.js`、`miniprogram/utils/roleGuard.js`、`miniprogram/utils/request.js`、`miniprogram/pages/home/{home.js,home.wxml,home.json}`、`miniprogram/app.json` |
|
||||
| 小程序(新) | `miniprogram/components/warehouse-panel/*`(面板)、`miniprogram/pages/warehouse/*`(薄壳)、`warehouse.contract.test.js`(11 条) |
|
||||
|
||||
## 6. 已确认的口径
|
||||
|
||||
1. 批量上传 = **一份报告挂多个批次**(每批次一条记录、共用同一组文件);
|
||||
2. 报告类型默认 **批次报告**(类型字典已内置,后续要选类型再加);
|
||||
3. 第一批即含**行内改成本价 / 改可用数量**;
|
||||
4. 默认授予 `warehouse`(系统里没有「验收员」角色;`inspector` 是历史角色码,守卫仍兼容,不单独授权)。
|
||||
|
||||
## 7. 风险与冻结
|
||||
|
||||
- 鉴权面:新权限码 + 新路由守卫属 `platform-freeze` 范围,已按「角色或权限」最小化放开,未动 `ALLOWED_TABLES/DENY_WRITE_TABLES`;
|
||||
- 写路径:报告绑定/删除、成本价、可用数量全部复用原 service,入库/验收/加工状态链一行未动;
|
||||
- 成本价可见性:被授权角色同样能看到成本价(与 Web 库存管理一致);若后续只允许仓管看成本,再加独立开关;
|
||||
- 回滚:删 registry 条目与面板/页面、迁移删权限行即可;Web 侧无需回滚。
|
||||
|
||||
## 8. 证据
|
||||
|
||||
- 后端契约 `server/tests/mobileWarehouseManage.test.ts` **9 条全绿**:6 条薄路由、复用 6 个 service、每条都挂守卫、
|
||||
可用数量按 `inventoryId`、守卫放行口径、权限码进模块注册表 + 迁移默认授予、批量上传与 Web 同流程(解析 → 候选 → 确认)、
|
||||
列表透出 `inbound_at`(入库时间与 Web 同字段)、分页(每页 20 + 服务端 LIMIT/OFFSET)。
|
||||
- 小程序契约 `miniprogram/components/warehouse-panel/warehouse.contract.test.js` **11 条全绿**:一级 Tab 内嵌(页面无状态)、
|
||||
grantable 可见性 + 不切角色、**表格布局(表头/列宽)**、列表字段(含入库时间、默认仅有可用)、
|
||||
**顶部统计卡(批次 / 可用总量 / 可用货值,面板上报)**、**分页(每页 20 + 首页触底转发)**、批量上传编排(不含行勾选)、
|
||||
**点行直接弹修改弹窗(双字段 + **单批次上传报告** + 安全区留白 + 三个弹层各一个 `root-portal` 固定视口)**、
|
||||
纯改价/改量(只提交改动字段)、报告查看删除;
|
||||
另钉住**录单员回弹回归**:`refreshMenuModules` 必须传 `permissions`、`notifyHomePanelShow` 必须登记 `warehouse`。
|
||||
- `npx tsc --noEmit`(server)与前端 typecheck 通过;`node --check` 覆盖全部改动的小程序 JS。
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,15 @@
|
||||
-- 小程序「仓库管理」:库存批次查看 + 批量上传/删除批次报告 + 改成本价/可用数量
|
||||
-- 2026-10-23 开发者:仓库管理是基础功能,默认给仓管人员;其他成员可在「角色权限」勾选获得。
|
||||
-- 说明:本权限**不映射任何 Web 菜单**,Web 侧菜单与路由权限均不变。
|
||||
|
||||
INSERT INTO permissions (permission_code, permission_name, module, description)
|
||||
SELECT 'warehouse_manage', '仓库管理', 'inventory',
|
||||
'小程序「仓库管理」:库存批次查看、批量上传/删除批次报告、改成本价与可用数量。默认授予仓管。'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE permission_code = 'warehouse_manage');
|
||||
|
||||
INSERT INTO role_permissions (role, permission_id)
|
||||
SELECT r.role, p.id
|
||||
FROM (VALUES ('warehouse'), ('admin'), ('super_admin')) AS r(role)
|
||||
CROSS JOIN permissions p
|
||||
WHERE p.permission_code = 'warehouse_manage'
|
||||
ON CONFLICT (role, permission_id) DO NOTHING;
|
||||
@@ -25,7 +25,8 @@
|
||||
"pages/order-entry/order-entry",
|
||||
"pages/cost-management/cost-management",
|
||||
"pages/order-detail/order-detail",
|
||||
"pages/trace/trace"
|
||||
"pages/trace/trace",
|
||||
"pages/warehouse/warehouse"
|
||||
],
|
||||
"window": {
|
||||
"navigationBarTitleText": "鲜配达",
|
||||
|
||||
@@ -0,0 +1,647 @@
|
||||
/**
|
||||
* 小程序「仓库管理」面板(2026-10-23 开发者):
|
||||
* 与 Web 库存管理同一套能力与执行函数 —— 批次库存、成本价、商品名、报告状态,
|
||||
* 支持**批量上传报告**、行内改成本价 / 可用数量、按批次查看与删除报告。
|
||||
*
|
||||
* 交互与其它模块一致:作为首页一级 Tab 内嵌(`embedded`),需要独立打开时由 `pages/warehouse` 包一层。
|
||||
* 权限:默认仓管可见;其他角色在 Web「角色权限」勾 `warehouse_manage` 后同样可用。
|
||||
*/
|
||||
const { requireWarehouseModuleRole } = require('../../utils/roleGuard');
|
||||
const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate');
|
||||
const {
|
||||
fetchInventoryBatches,
|
||||
fetchInventoryBatchReports,
|
||||
uploadInventoryBatchReports,
|
||||
parseInventoryBatchReports,
|
||||
confirmInventoryBatchReportMatches,
|
||||
deleteInventoryBatchReport,
|
||||
updateInventoryBatchCostPrice,
|
||||
updateInventoryBatchAvailableQty,
|
||||
uploadQualityReportStorageFile,
|
||||
} = require('../../utils/request');
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
const REPORT_TYPE_LABELS = {
|
||||
batch: '批次报告',
|
||||
pesticide: '农残报告',
|
||||
quarantine: '检疫报告',
|
||||
annual: '年度报告',
|
||||
};
|
||||
|
||||
function roundQty(value) {
|
||||
const num = Number(value);
|
||||
if (!Number.isFinite(num)) return 0;
|
||||
return Math.round(num * 1000) / 1000;
|
||||
}
|
||||
|
||||
function formatQty(value) {
|
||||
return String(roundQty(value));
|
||||
}
|
||||
|
||||
function formatMoney(value) {
|
||||
const num = Number(value);
|
||||
if (!Number.isFinite(num)) return '';
|
||||
return num.toFixed(2);
|
||||
}
|
||||
|
||||
/** 千位分隔(列表统计卡用):1234567.5 → 1,234,567.5 */
|
||||
function withThousands(text) {
|
||||
const [intPart, decPart] = String(text).split('.');
|
||||
const grouped = String(intPart).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
||||
return decPart == null ? grouped : `${grouped}.${decPart}`;
|
||||
}
|
||||
|
||||
/** 合计数量:千位分隔,最多 3 位小数,去尾零 */
|
||||
function formatQtyTotal(value) {
|
||||
const text = roundQty(value)
|
||||
.toFixed(3)
|
||||
.replace(/\.?0+$/, '');
|
||||
return withThousands(text || '0');
|
||||
}
|
||||
|
||||
/** 合计货值:千位分隔 + 固定两位小数 */
|
||||
function formatMoneyTotal(value) {
|
||||
const num = Number(value);
|
||||
return withThousands((Number.isFinite(num) ? num : 0).toFixed(2));
|
||||
}
|
||||
|
||||
function toRow(row) {
|
||||
const reportCount = Number(row.batch_report_count) || 0;
|
||||
const cost = row.cost_price == null ? null : Number(row.cost_price);
|
||||
return {
|
||||
id: String(row.id || ''),
|
||||
sku_name: String(row.sku_name || row.sku_code || ''),
|
||||
category_name: String(row.category_name || ''),
|
||||
batch_no: String(row.batch_no || ''),
|
||||
available_text: formatQty(row.available_qty),
|
||||
cost_text: cost == null ? '' : formatMoney(cost),
|
||||
cost_missing: cost == null || cost <= 0,
|
||||
storage_zone: String(row.storage_zone || ''),
|
||||
production_date: row.production_date ? String(row.production_date).slice(0, 10) : '',
|
||||
expiry_date: row.expiry_date ? String(row.expiry_date).slice(0, 10) : '',
|
||||
/** 入库时间 = 该批次最早一次入库流水(后端已出 'YYYY-MM-DD';无流水为空串) */
|
||||
inbound_at: row.inbound_at ? String(row.inbound_at).slice(0, 10) : '',
|
||||
report_count: reportCount,
|
||||
report_missing: reportCount <= 0,
|
||||
};
|
||||
}
|
||||
|
||||
function totalLabel(count) {
|
||||
const n = Number(count) || 0;
|
||||
return `共 ${n} 批`;
|
||||
}
|
||||
|
||||
Component({
|
||||
options: { addGlobalClass: true },
|
||||
|
||||
properties: {
|
||||
embedded: { type: Boolean, value: false },
|
||||
homeTabFilter: { type: String, value: '' },
|
||||
},
|
||||
|
||||
data: {
|
||||
loading: false,
|
||||
loadingMore: false,
|
||||
rows: [],
|
||||
totalText: '共 0 批',
|
||||
page: 1,
|
||||
hasMore: true,
|
||||
search: '',
|
||||
// 进入面板默认只看有可用库存的批次(2026-10-25 开发者)
|
||||
onlyAvailable: true,
|
||||
onlyMissingReport: false,
|
||||
uploading: false,
|
||||
uploadText: '',
|
||||
// 批量上传报告:上传 → 解析 → 人工确认匹配(与 Web 同流程)
|
||||
uploadOpen: false,
|
||||
uploadFiles: [],
|
||||
uploadParsing: false,
|
||||
uploadConfirming: false,
|
||||
uploadReports: [],
|
||||
uploadSelectedCount: 0,
|
||||
// 修改弹窗(点行直接弹出:可用数量 + 成本价 + 报告入口)
|
||||
editItem: null,
|
||||
editAvailable: '',
|
||||
editCost: '',
|
||||
editSaving: false,
|
||||
// 批次报告
|
||||
reportItem: null,
|
||||
reports: [],
|
||||
reportsLoading: false,
|
||||
},
|
||||
|
||||
lifetimes: {
|
||||
attached() {
|
||||
this.onPanelShow();
|
||||
},
|
||||
},
|
||||
|
||||
pageLifetimes: {
|
||||
show() {
|
||||
this.onPanelShow();
|
||||
},
|
||||
},
|
||||
|
||||
methods: {
|
||||
onPanelShow() {
|
||||
if (!beginPanelShow(this)) return;
|
||||
try {
|
||||
if (!requireWarehouseModuleRole()) return;
|
||||
if (!this._panelReady) {
|
||||
this._panelReady = true;
|
||||
this.reload();
|
||||
return;
|
||||
}
|
||||
// 再次切回本 Tab 时刷新;但选图/编辑/报告弹层进行中不打断
|
||||
if (this.data.uploading || this.data.editSaving || this.data.editItem || this.data.reportItem) {
|
||||
return;
|
||||
}
|
||||
this.reload();
|
||||
} finally {
|
||||
endPanelShow(this);
|
||||
}
|
||||
},
|
||||
|
||||
onPullDownRefresh() {
|
||||
this.reload().then(() => wx.stopPullDownRefresh());
|
||||
},
|
||||
|
||||
onReachBottom() {
|
||||
if (!this.data.hasMore || this.data.loading || this.data.loadingMore) return;
|
||||
this.loadPage(this.data.page + 1, true);
|
||||
},
|
||||
|
||||
reload() {
|
||||
this.setData({ page: 1, hasMore: true });
|
||||
return this.loadPage(1, false);
|
||||
},
|
||||
|
||||
async loadPage(page, append) {
|
||||
if (append) this.setData({ loadingMore: true });
|
||||
else this.setData({ loading: true });
|
||||
try {
|
||||
const res = await fetchInventoryBatches({
|
||||
page,
|
||||
page_size: PAGE_SIZE,
|
||||
search: String(this.data.search || '').trim() || undefined,
|
||||
only_available: this.data.onlyAvailable === true,
|
||||
});
|
||||
const rawRows = ((res && res.data) || []).map(toRow);
|
||||
// 「缺报告」是本地筛选(服务端列表口径不动):hasMore 按**原始条数**判断,避免筛完误判到底
|
||||
const rows = this.data.onlyMissingReport
|
||||
? rawRows.filter((row) => row.report_missing)
|
||||
: rawRows;
|
||||
const nextRows = append ? (this.data.rows || []).concat(rows) : rows;
|
||||
this.setData({
|
||||
rows: nextRows,
|
||||
totalText: totalLabel(res && res.total),
|
||||
page,
|
||||
hasMore: rawRows.length >= PAGE_SIZE,
|
||||
});
|
||||
// 顶部统计卡(与列表同一筛选口径,服务端已算好):批次数量 / 可用总量 / 可用货值
|
||||
const stats = (res && res.stats) || {};
|
||||
this.triggerEvent('statschange', {
|
||||
batches: Number(res && res.total) || 0,
|
||||
availableQtyText: formatQtyTotal(stats.total_available_qty),
|
||||
availableValueText: formatMoneyTotal(stats.total_value),
|
||||
});
|
||||
} catch (err) {
|
||||
wx.showToast({ title: (err && err.message) || '加载失败', icon: 'none' });
|
||||
} finally {
|
||||
this.setData({ loading: false, loadingMore: false });
|
||||
}
|
||||
},
|
||||
|
||||
noop() {},
|
||||
|
||||
onSearchInput(e) {
|
||||
const value = String((e && e.detail && e.detail.value) || '');
|
||||
this.setData({ search: value });
|
||||
clearTimeout(this._searchTimer);
|
||||
this._searchTimer = setTimeout(() => this.reload(), 400);
|
||||
},
|
||||
|
||||
onSearchConfirm() {
|
||||
this.reload();
|
||||
},
|
||||
|
||||
toggleOnlyAvailable() {
|
||||
this.setData({ onlyAvailable: !this.data.onlyAvailable }, () => this.reload());
|
||||
},
|
||||
|
||||
toggleOnlyMissingReport() {
|
||||
this.setData({ onlyMissingReport: !this.data.onlyMissingReport }, () => this.reload());
|
||||
},
|
||||
|
||||
// ── 批量上传报告:上传 → 解析 → 人工确认匹配(与 Web 同流程) ──
|
||||
openUploadSheet() {
|
||||
this.setData({
|
||||
uploadOpen: true,
|
||||
uploadFiles: [],
|
||||
uploadParsing: false,
|
||||
uploadConfirming: false,
|
||||
uploadReports: [],
|
||||
uploadSelectedCount: 0,
|
||||
});
|
||||
},
|
||||
|
||||
closeUploadSheet() {
|
||||
if (this.data.uploadParsing || this.data.uploadConfirming) return;
|
||||
this.setData({ uploadOpen: false });
|
||||
},
|
||||
|
||||
async pickUploadFiles() {
|
||||
if (this.data.uploadParsing || this.data.uploadConfirming) return;
|
||||
const files = await this.chooseReportFiles();
|
||||
if (!files || !files.length) return;
|
||||
const next = (this.data.uploadFiles || []).concat(files).slice(0, 9);
|
||||
this.setData({ uploadFiles: next });
|
||||
},
|
||||
|
||||
removeUploadFile(e) {
|
||||
const index = Number(e.currentTarget.dataset.index);
|
||||
if (!Number.isInteger(index) || index < 0) return;
|
||||
const next = (this.data.uploadFiles || []).filter((_, i) => i !== index);
|
||||
this.setData({ uploadFiles: next });
|
||||
},
|
||||
|
||||
/** 上传并识别:服务端 OCR + 匹配候选批次(同一 service,与 Web 页级上传一致) */
|
||||
async parseUploadFiles() {
|
||||
if (this.data.uploadParsing || this.data.uploadConfirming) return;
|
||||
const files = this.data.uploadFiles || [];
|
||||
if (!files.length) {
|
||||
wx.showToast({ title: '请先选择报告文件', icon: 'none' });
|
||||
return;
|
||||
}
|
||||
this.setData({ uploadParsing: true, uploadText: '上传识别中…' });
|
||||
try {
|
||||
const paths = [];
|
||||
for (let i = 0; i < files.length; i += 1) {
|
||||
this.setData({ uploadText: `上传文件 ${i + 1}/${files.length}…` });
|
||||
const res = await uploadQualityReportStorageFile(files[i].path, files[i].name);
|
||||
const key =
|
||||
typeof res === 'string'
|
||||
? res
|
||||
: (res && (res.path || res.key || res.file || res.url)) || '';
|
||||
if (key) paths.push(String(key));
|
||||
}
|
||||
if (!paths.length) {
|
||||
wx.showToast({ title: '上传文件失败', icon: 'none' });
|
||||
return;
|
||||
}
|
||||
const res = await parseInventoryBatchReports({ files: paths, report_type: 'batch' });
|
||||
const reports = (res && res.data) || [];
|
||||
let selectedCount = 0;
|
||||
const mapped = reports.map((report) => ({
|
||||
id: report.id,
|
||||
title: REPORT_TYPE_LABELS[report.report_type] || '报告',
|
||||
report_no: report.report_no || '',
|
||||
matches: (report.matches || []).map((match) => ({
|
||||
product_name: match.product_name || '',
|
||||
status: match.status,
|
||||
status_text:
|
||||
match.status === 'unique'
|
||||
? '唯一匹配'
|
||||
: match.status === 'multi'
|
||||
? '多个候选'
|
||||
: '未匹配',
|
||||
candidates: (match.candidates || []).map((candidate) => {
|
||||
// 唯一命中自动勾上(与 Web 一致),其余交给人工确认
|
||||
const selected = match.status === 'unique';
|
||||
if (selected) selectedCount += 1;
|
||||
return {
|
||||
key: `${report.id}::${candidate.inventory_id}`,
|
||||
report_id: report.id,
|
||||
inventory_id: candidate.inventory_id,
|
||||
label: `${candidate.sku_name || candidate.sku_code || '未命名'} · ${candidate.batch_no || ''}`,
|
||||
meta: [
|
||||
candidate.available_qty != null ? `可用 ${candidate.available_qty}` : '',
|
||||
candidate.unit || '',
|
||||
candidate.production_date ? `生产 ${String(candidate.production_date).slice(0, 10)}` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
selected,
|
||||
};
|
||||
}),
|
||||
})),
|
||||
}));
|
||||
this.setData({
|
||||
uploadReports: mapped,
|
||||
uploadSelectedCount: selectedCount,
|
||||
});
|
||||
if (!reports.length) {
|
||||
wx.showToast({ title: '未识别到报告内容,可重拍后重试', icon: 'none' });
|
||||
}
|
||||
} catch (err) {
|
||||
wx.showToast({ title: (err && err.message) || '识别失败', icon: 'none' });
|
||||
} finally {
|
||||
this.setData({ uploadParsing: false, uploadText: '' });
|
||||
}
|
||||
},
|
||||
|
||||
toggleUploadCandidate(e) {
|
||||
if (this.data.uploadConfirming) return;
|
||||
const key = String((e.currentTarget.dataset && e.currentTarget.dataset.key) || '');
|
||||
if (!key) return;
|
||||
let selectedCount = 0;
|
||||
const reports = (this.data.uploadReports || []).map((report) => ({
|
||||
...report,
|
||||
matches: (report.matches || []).map((match) => ({
|
||||
...match,
|
||||
candidates: (match.candidates || []).map((candidate) => {
|
||||
const selected = candidate.key === key ? !candidate.selected : candidate.selected;
|
||||
if (selected) selectedCount += 1;
|
||||
return { ...candidate, selected };
|
||||
}),
|
||||
})),
|
||||
}));
|
||||
this.setData({ uploadReports: reports, uploadSelectedCount: selectedCount });
|
||||
},
|
||||
|
||||
async confirmUploadMatches() {
|
||||
if (this.data.uploadConfirming) return;
|
||||
const reports = this.data.uploadReports || [];
|
||||
const payloads = reports
|
||||
.map((report) => ({
|
||||
reportId: report.id,
|
||||
matches: (report.matches || []).flatMap((match) =>
|
||||
(match.candidates || [])
|
||||
.filter((candidate) => candidate.selected)
|
||||
.map((candidate) => ({
|
||||
inventory_id: candidate.inventory_id,
|
||||
product_name: match.product_name,
|
||||
}))
|
||||
),
|
||||
}))
|
||||
.filter((row) => row.matches.length);
|
||||
if (!payloads.length) {
|
||||
wx.showToast({ title: '请至少选择一条入库批次', icon: 'none' });
|
||||
return;
|
||||
}
|
||||
this.setData({ uploadConfirming: true, uploadText: '确认中…' });
|
||||
try {
|
||||
for (let i = 0; i < payloads.length; i += 1) {
|
||||
this.setData({ uploadText: `确认匹配 ${i + 1}/${payloads.length}…` });
|
||||
await confirmInventoryBatchReportMatches(payloads[i].reportId, payloads[i].matches);
|
||||
}
|
||||
wx.showToast({ title: '报告已匹配并绑定', icon: 'success' });
|
||||
this.setData({ uploadOpen: false, uploadReports: [], uploadFiles: [] });
|
||||
await this.reload();
|
||||
} catch (err) {
|
||||
wx.showToast({ title: (err && err.message) || '确认失败', icon: 'none' });
|
||||
} finally {
|
||||
this.setData({ uploadConfirming: false, uploadText: '' });
|
||||
}
|
||||
},
|
||||
|
||||
chooseReportFiles() {
|
||||
return new Promise((resolve) => {
|
||||
wx.showActionSheet({
|
||||
itemList: ['拍照 / 相册', '微信文件(PDF 等)'],
|
||||
success: (tap) => {
|
||||
if (tap.tapIndex === 0) {
|
||||
wx.chooseMedia({
|
||||
count: 9,
|
||||
mediaType: ['image'],
|
||||
sourceType: ['album', 'camera'],
|
||||
success: (res) => {
|
||||
resolve(
|
||||
(res.tempFiles || []).map((file, index) => ({
|
||||
path: file.tempFilePath,
|
||||
name: file.name || `photo-${Date.now()}-${index}.jpg`,
|
||||
}))
|
||||
);
|
||||
},
|
||||
fail: () => resolve([]),
|
||||
});
|
||||
return;
|
||||
}
|
||||
wx.chooseMessageFile({
|
||||
count: 9,
|
||||
type: 'all',
|
||||
success: (res) => {
|
||||
resolve(
|
||||
(res.tempFiles || [])
|
||||
.map((file) => ({ path: file.path, name: file.name || '' }))
|
||||
.filter((file) => /\.(pdf|jpe?g|png|webp)$/i.test(String(file.name || file.path)))
|
||||
);
|
||||
},
|
||||
fail: () => resolve([]),
|
||||
});
|
||||
},
|
||||
fail: () => resolve([]),
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
// ── 行点击:表格行太窄,操作用底部 actionSheet 收口 ─────────
|
||||
/** 点行 → 直接弹「修改」弹窗(不再先出选择菜单,2026-10-23 开发者) */
|
||||
onRowTap(e) {
|
||||
this.openEditSheetById(String((e.currentTarget.dataset && e.currentTarget.dataset.id) || ''));
|
||||
},
|
||||
|
||||
// ── 修改弹窗:可用数量 + 成本价一次改完 ───────────────────
|
||||
openEditSheetById(id) {
|
||||
const row = (this.data.rows || []).find((item) => item.id === id);
|
||||
if (!row) return;
|
||||
this.setData({
|
||||
editItem: {
|
||||
id: row.id,
|
||||
sku_name: row.sku_name,
|
||||
batch_no: row.batch_no,
|
||||
category_name: row.category_name,
|
||||
storage_zone: row.storage_zone,
|
||||
report_count: row.report_count,
|
||||
report_missing: row.report_missing,
|
||||
available: row.available_text,
|
||||
cost: row.cost_missing ? '' : row.cost_text,
|
||||
},
|
||||
editAvailable: row.available_text,
|
||||
editCost: row.cost_missing ? '' : row.cost_text,
|
||||
});
|
||||
},
|
||||
|
||||
onEditAvailableInput(e) {
|
||||
this.setData({ editAvailable: String((e && e.detail && e.detail.value) || '') });
|
||||
},
|
||||
|
||||
onEditCostInput(e) {
|
||||
this.setData({ editCost: String((e && e.detail && e.detail.value) || '') });
|
||||
},
|
||||
|
||||
closeEdit() {
|
||||
if (this.data.editSaving) return;
|
||||
this.setData({ editItem: null, editAvailable: '', editCost: '' });
|
||||
},
|
||||
|
||||
/** 从修改弹窗跳到该批次报告(弹窗关闭,避免叠层) */
|
||||
openReportsFromEdit() {
|
||||
const id = this.data.editItem && this.data.editItem.id;
|
||||
if (!id) return;
|
||||
this.setData({ editItem: null, editAvailable: '', editCost: '' });
|
||||
void this.openReportsById(String(id));
|
||||
},
|
||||
|
||||
async submitEditSheet() {
|
||||
const item = this.data.editItem;
|
||||
if (!item || this.data.editSaving) return;
|
||||
const qtyText = String(this.data.editAvailable || '').trim();
|
||||
const costText = String(this.data.editCost || '').trim();
|
||||
const nextQty = qtyText === '' ? Number.NaN : Number(qtyText);
|
||||
if (!Number.isFinite(nextQty) || nextQty < 0) {
|
||||
wx.showToast({ title: '可用数量须为不小于 0 的数字', icon: 'none' });
|
||||
return;
|
||||
}
|
||||
const nextCost = costText === '' ? null : Number(costText);
|
||||
if (nextCost != null && (!Number.isFinite(nextCost) || nextCost < 0)) {
|
||||
wx.showToast({ title: '成本价须为不小于 0 的数字', icon: 'none' });
|
||||
return;
|
||||
}
|
||||
const prevQty = Number(item.available);
|
||||
const prevCost = item.cost === '' ? null : Number(item.cost);
|
||||
const qtyChanged = Math.abs(nextQty - prevQty) > 1e-9;
|
||||
const costChanged = (prevCost == null ? null : prevCost) !== nextCost;
|
||||
if (!qtyChanged && !costChanged) {
|
||||
wx.showToast({ title: '没有改动', icon: 'none' });
|
||||
return;
|
||||
}
|
||||
this.setData({ editSaving: true });
|
||||
try {
|
||||
// 只提交真正改过的字段:两条写路径与 Web 完全一致(各带自己的审计/流水)
|
||||
if (qtyChanged) await updateInventoryBatchAvailableQty(item.id, nextQty);
|
||||
if (costChanged) await updateInventoryBatchCostPrice(item.id, nextCost);
|
||||
this.setData({ editItem: null, editAvailable: '', editCost: '' });
|
||||
wx.showToast({ title: '已保存', icon: 'success' });
|
||||
await this.reload();
|
||||
} catch (err) {
|
||||
wx.showToast({ title: (err && err.message) || '保存失败', icon: 'none' });
|
||||
} finally {
|
||||
this.setData({ editSaving: false });
|
||||
}
|
||||
},
|
||||
|
||||
// ── 批次报告:查看 / 删除 ───────────────────────────────
|
||||
openReports(e) {
|
||||
void this.openReportsById(String((e.currentTarget.dataset && e.currentTarget.dataset.id) || ''));
|
||||
},
|
||||
|
||||
/** 报告行 → 展示结构(列表/弹窗共用) */
|
||||
mapReportRows(rows) {
|
||||
return (Array.isArray(rows) ? rows : []).map((report) => ({
|
||||
id: report.id,
|
||||
type_label: REPORT_TYPE_LABELS[report.report_type] || report.report_type || '报告',
|
||||
report_no: report.report_no || '',
|
||||
uploaded_at: report.uploaded_at || '',
|
||||
}));
|
||||
},
|
||||
|
||||
/**
|
||||
* 单批次上传报告(编辑弹窗 / 报告弹窗共用):
|
||||
* 选文件 → 上传一次 → 绑定到该批次 → 刷新报告列表与表格里的报告列。
|
||||
*/
|
||||
async uploadReportsForBatch(inventoryId) {
|
||||
const id = String(inventoryId || '');
|
||||
if (!id || this.data.uploading) return;
|
||||
const files = await this.chooseReportFiles();
|
||||
if (!files || !files.length) return;
|
||||
this.setData({ uploading: true, uploadText: '上传中…' });
|
||||
try {
|
||||
const paths = [];
|
||||
for (let i = 0; i < files.length; i += 1) {
|
||||
const res = await uploadQualityReportStorageFile(files[i].path, files[i].name);
|
||||
const key =
|
||||
typeof res === 'string'
|
||||
? res
|
||||
: (res && (res.path || res.key || res.file || res.url)) || '';
|
||||
if (key) paths.push(String(key));
|
||||
}
|
||||
if (!paths.length) {
|
||||
wx.showToast({ title: '上传文件失败', icon: 'none' });
|
||||
return;
|
||||
}
|
||||
await uploadInventoryBatchReports(id, { files: paths, report_type: 'batch' });
|
||||
wx.showToast({ title: '报告已上传', icon: 'success' });
|
||||
await this.refreshBatchReports(id);
|
||||
} catch (err) {
|
||||
wx.showToast({ title: (err && err.message) || '上传失败', icon: 'none' });
|
||||
} finally {
|
||||
this.setData({ uploading: false, uploadText: '' });
|
||||
}
|
||||
},
|
||||
|
||||
/** 上传/删除后刷新:报告弹窗列表 + 编辑弹窗的报告状态 + 表格报告列 */
|
||||
async refreshBatchReports(inventoryId) {
|
||||
try {
|
||||
const res = await fetchInventoryBatchReports(inventoryId);
|
||||
const list = this.mapReportRows(res && res.data);
|
||||
const patch = {};
|
||||
if (this.data.reportItem && this.data.reportItem.id === inventoryId) {
|
||||
patch.reports = list;
|
||||
}
|
||||
if (this.data.editItem && this.data.editItem.id === inventoryId) {
|
||||
patch['editItem.report_count'] = list.length;
|
||||
patch['editItem.report_missing'] = list.length <= 0;
|
||||
}
|
||||
if (Object.keys(patch).length) this.setData(patch);
|
||||
} catch {
|
||||
// 刷新失败不影响已完成的绑定
|
||||
}
|
||||
// 表格里的「报告」列同步(不重置已选)
|
||||
await this.loadPage(1, false);
|
||||
},
|
||||
|
||||
onUploadFromEdit() {
|
||||
const id = this.data.editItem && this.data.editItem.id;
|
||||
if (!id) return;
|
||||
void this.uploadReportsForBatch(id);
|
||||
},
|
||||
|
||||
onUploadFromReports() {
|
||||
const id = this.data.reportItem && this.data.reportItem.id;
|
||||
if (!id) return;
|
||||
void this.uploadReportsForBatch(id);
|
||||
},
|
||||
|
||||
async openReportsById(id) {
|
||||
const row = (this.data.rows || []).find((item) => item.id === id);
|
||||
if (!row) return;
|
||||
this.setData({ reportItem: row, reports: [], reportsLoading: true });
|
||||
try {
|
||||
const res = await fetchInventoryBatchReports(id);
|
||||
this.setData({ reports: this.mapReportRows(res && res.data) });
|
||||
} catch (err) {
|
||||
wx.showToast({ title: (err && err.message) || '加载报告失败', icon: 'none' });
|
||||
} finally {
|
||||
this.setData({ reportsLoading: false });
|
||||
}
|
||||
},
|
||||
|
||||
closeReports() {
|
||||
this.setData({ reportItem: null, reports: [] });
|
||||
},
|
||||
|
||||
async onDeleteReport(e) {
|
||||
const reportId = String((e.currentTarget.dataset && e.currentTarget.dataset.id) || '');
|
||||
const batchId = this.data.reportItem && this.data.reportItem.id;
|
||||
if (!reportId) return;
|
||||
const confirm = await new Promise((resolve) => {
|
||||
wx.showModal({
|
||||
title: '删除报告',
|
||||
content: '删除后该批次会显示「缺少批次报告」,确定删除吗?',
|
||||
success: (res) => resolve(res.confirm === true),
|
||||
fail: () => resolve(false),
|
||||
});
|
||||
});
|
||||
if (!confirm) return;
|
||||
try {
|
||||
await deleteInventoryBatchReport(reportId);
|
||||
wx.showToast({ title: '已删除', icon: 'success' });
|
||||
if (batchId) await this.refreshBatchReports(String(batchId));
|
||||
else await this.reload();
|
||||
} catch (err) {
|
||||
wx.showToast({ title: (err && err.message) || '删除失败', icon: 'none' });
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"component": true,
|
||||
"usingComponents": {}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
<view class="warehouse-panel {{embedded ? 'is-embedded' : ''}}">
|
||||
<!-- 搜索 -->
|
||||
<view class="toolbar">
|
||||
<input
|
||||
class="search-input"
|
||||
placeholder="搜索商品名 / 编码 / 批次号"
|
||||
value="{{search}}"
|
||||
bindinput="onSearchInput"
|
||||
bindconfirm="onSearchConfirm"
|
||||
confirm-type="search"
|
||||
/>
|
||||
</view>
|
||||
|
||||
<!-- 筛选 + 批量上传:同一行(条件在左、总数靠右、操作在最右) -->
|
||||
<view class="filter-row">
|
||||
<view class="chips">
|
||||
<view class="chip {{onlyAvailable ? 'is-on' : ''}}" catchtap="toggleOnlyAvailable">仅有可用</view>
|
||||
<view class="chip {{onlyMissingReport ? 'is-on' : ''}}" catchtap="toggleOnlyMissingReport">缺报告</view>
|
||||
</view>
|
||||
<text class="total">{{totalText}}</text>
|
||||
<button
|
||||
class="upload-btn {{uploading ? 'is-disabled' : ''}}"
|
||||
loading="{{uploading}}"
|
||||
bindtap="openUploadSheet"
|
||||
>批量上传报告</button>
|
||||
</view>
|
||||
|
||||
<!-- 表格:表头 + 行(列对齐) -->
|
||||
<view class="table">
|
||||
<view class="tr thead">
|
||||
<view class="td td-product">商品</view>
|
||||
<view class="td td-qty">可用</view>
|
||||
<view class="td td-cost">成本价</view>
|
||||
<view class="td td-report">报告</view>
|
||||
</view>
|
||||
|
||||
<view wx:if="{{loading}}" class="table-hint">加载中…</view>
|
||||
<view wx:elif="{{!rows.length}}" class="table-hint">没有符合条件的批次</view>
|
||||
|
||||
<view
|
||||
wx:for="{{rows}}"
|
||||
wx:key="id"
|
||||
class="tr"
|
||||
bindtap="onRowTap"
|
||||
data-id="{{item.id}}"
|
||||
>
|
||||
<view class="td td-product">
|
||||
<text class="name {{item.report_missing ? 'is-missing' : ''}}">{{item.sku_name}}</text>
|
||||
<text class="sub">{{item.batch_no}}{{item.category_name ? ' · ' + item.category_name : ''}}</text>
|
||||
<text class="sub">入库 {{item.inbound_at || '—'}}</text>
|
||||
</view>
|
||||
<view class="td td-qty">{{item.available_text}}</view>
|
||||
<view class="td td-cost {{item.cost_missing ? 'is-missing' : ''}}">{{item.cost_missing ? '未设置' : '¥' + item.cost_text}}</view>
|
||||
<view class="td td-report" catchtap="openReports" data-id="{{item.id}}">
|
||||
<text class="{{item.report_missing ? 'is-missing' : 'is-ok'}}">{{item.report_missing ? '缺少' : item.report_count + ' 个'}}</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view wx:if="{{loadingMore}}" class="hint">加载更多…</view>
|
||||
<view wx:elif="{{rows.length && !hasMore}}" class="hint">没有更多了</view>
|
||||
<view wx:else class="hint">点行可改成本价 / 可用数量 · 点报告列看该批次报告</view>
|
||||
</view>
|
||||
|
||||
<!-- 弹层必须 root-portal:首页 .home-*-embed 的 transform 会困住 position:fixed,
|
||||
弹层会跟着页面滚动、也盖不住底部 tab 栏。
|
||||
每个弹层单独一个 root-portal(单子节点)——一个 portal 塞多个弹层会让 portal 不生效,
|
||||
与加工 / 分拣面板同款做法。 -->
|
||||
|
||||
<!-- 批量上传报告:上传 → 识别 → 匹配 → 确认 -->
|
||||
<root-portal enable="{{true}}">
|
||||
<view wx:if="{{uploadOpen}}" class="sheet-mask" catchtouchmove="noop" bindtap="closeUploadSheet">
|
||||
<view class="sheet" catchtap="noop">
|
||||
<view class="sheet-head">
|
||||
<view class="sheet-head-text">
|
||||
<view class="sheet-title">批量上传报告</view>
|
||||
</view>
|
||||
<view class="sheet-close" catchtap="closeUploadSheet">×</view>
|
||||
</view>
|
||||
|
||||
<scroll-view scroll-y class="sheet-body" show-scrollbar="{{false}}">
|
||||
<view class="upload-files">
|
||||
<view wx:for="{{uploadFiles}}" wx:key="path" class="upload-file">
|
||||
<text class="upload-file-name">{{item.name}}</text>
|
||||
<text class="upload-file-del" catchtap="removeUploadFile" data-index="{{index}}">×</text>
|
||||
</view>
|
||||
<view class="upload-chip" catchtap="pickUploadFiles">{{uploadFiles.length ? '继续添加' : '选择文件'}}</view>
|
||||
</view>
|
||||
|
||||
<view class="upload-primary {{uploadParsing ? 'is-disabled' : ''}}" catchtap="parseUploadFiles">{{uploadParsing ? (uploadText || '识别中…') : '上传并识别'}}</view>
|
||||
|
||||
<view wx:for="{{uploadReports}}" wx:key="id" wx:for-item="report" class="match-group">
|
||||
<view class="match-title">{{report.title}}{{report.report_no ? ' · ' + report.report_no : ''}}</view>
|
||||
<view wx:for="{{report.matches}}" wx:key="product_name" wx:for-item="match" class="match-item">
|
||||
<view class="match-product">
|
||||
<text class="match-name">{{match.product_name || '未识别商品名'}}</text>
|
||||
<text class="match-status {{match.status === 'none' ? 'is-missing' : ''}}">{{match.status_text}}</text>
|
||||
</view>
|
||||
<view wx:for="{{match.candidates}}" wx:key="key" wx:for-item="can" class="match-candidate {{can.selected ? 'is-on' : ''}}" catchtap="toggleUploadCandidate" data-key="{{can.key}}">
|
||||
<view class="check {{can.selected ? 'is-on' : ''}}"></view>
|
||||
<view class="match-candidate-text">
|
||||
<text class="match-candidate-label">{{can.label}}</text>
|
||||
<text class="match-candidate-meta">{{can.meta}}</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
|
||||
<view class="sheet-actions">
|
||||
<view class="btn ghost" catchtap="closeUploadSheet">取消</view>
|
||||
<view class="btn primary {{uploadConfirming || !uploadSelectedCount ? 'is-disabled' : ''}}" catchtap="confirmUploadMatches">{{uploadConfirming ? '确认中…' : '确认匹配(' + uploadSelectedCount + ')'}}</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</root-portal>
|
||||
|
||||
<!-- 修改弹窗:点行直接弹,可用数量 / 成本价一次改完 + 报告入口 -->
|
||||
<root-portal enable="{{true}}">
|
||||
<view wx:if="{{editItem}}" class="sheet-mask is-center" catchtouchmove="noop" bindtap="closeEdit">
|
||||
<view class="sheet is-center" catchtap="noop">
|
||||
<view class="sheet-head">
|
||||
<view class="sheet-head-text">
|
||||
<view class="sheet-title">{{editItem.sku_name}}</view>
|
||||
<view class="sheet-sub">{{editItem.batch_no}}{{editItem.category_name ? ' · ' + editItem.category_name : ''}}{{editItem.storage_zone ? ' · 区域 ' + editItem.storage_zone : ''}}</view>
|
||||
</view>
|
||||
<view class="sheet-close" catchtap="closeEdit">×</view>
|
||||
</view>
|
||||
|
||||
<view class="sheet-body">
|
||||
<view class="sheet-field">
|
||||
<text class="sheet-label">可用数量(本批次)</text>
|
||||
<input class="sheet-input" type="digit" value="{{editAvailable}}" bindinput="onEditAvailableInput" />
|
||||
</view>
|
||||
|
||||
<view class="sheet-field">
|
||||
<text class="sheet-label">成本价(本批次)</text>
|
||||
<input class="sheet-input" type="digit" value="{{editCost}}" bindinput="onEditCostInput" />
|
||||
</view>
|
||||
|
||||
<view class="sheet-link">
|
||||
<view class="sheet-link-main" catchtap="openReportsFromEdit">
|
||||
<text class="sheet-link-label">批次报告</text>
|
||||
<text class="sheet-link-value {{editItem.report_missing ? 'is-missing' : 'is-ok'}}">{{editItem.report_missing ? '缺少' : editItem.report_count + ' 个'}} ›</text>
|
||||
</view>
|
||||
<view class="upload-chip {{uploading ? 'is-disabled' : ''}}" catchtap="onUploadFromEdit">{{uploading ? '上传中…' : '上传'}}</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view class="sheet-actions">
|
||||
<view class="btn ghost" catchtap="closeEdit">取消</view>
|
||||
<view class="btn primary {{editSaving ? 'is-disabled' : ''}}" catchtap="submitEditSheet">{{editSaving ? '保存中…' : '保存'}}</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</root-portal>
|
||||
|
||||
<!-- 批次报告列表 -->
|
||||
<root-portal enable="{{true}}">
|
||||
<view wx:if="{{reportItem}}" class="sheet-mask" catchtouchmove="noop" bindtap="closeReports">
|
||||
<view class="sheet" catchtap="noop">
|
||||
<view class="sheet-head">
|
||||
<view class="sheet-head-text">
|
||||
<view class="sheet-title">批次报告</view>
|
||||
<view class="sheet-sub">{{reportItem.sku_name}} · {{reportItem.batch_no}}</view>
|
||||
</view>
|
||||
<view class="sheet-close" catchtap="closeReports">×</view>
|
||||
</view>
|
||||
|
||||
<view class="report-toolbar">
|
||||
<text class="report-toolbar-hint">本批次报告</text>
|
||||
<view class="upload-chip {{uploading ? 'is-disabled' : ''}}" catchtap="onUploadFromReports">{{uploading ? '上传中…' : '上传报告'}}</view>
|
||||
</view>
|
||||
|
||||
<scroll-view scroll-y class="sheet-body" show-scrollbar="{{false}}">
|
||||
<view wx:if="{{reportsLoading}}" class="sheet-empty">加载中…</view>
|
||||
<view wx:elif="{{!reports.length}}" class="sheet-empty">该批次还没有报告</view>
|
||||
<view wx:else class="report-list">
|
||||
<view wx:for="{{reports}}" wx:key="id" class="report-row">
|
||||
<view class="report-info">
|
||||
<text class="report-type">{{item.type_label}}</text>
|
||||
<text class="report-meta">{{item.report_no ? item.report_no + ' · ' : ''}}{{item.uploaded_at}}</text>
|
||||
</view>
|
||||
<text class="report-delete" catchtap="onDeleteReport" data-id="{{item.id}}">删除</text>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
|
||||
<view class="sheet-actions">
|
||||
<view class="btn ghost" catchtap="closeReports">关闭</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</root-portal>
|
||||
@@ -0,0 +1,611 @@
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.warehouse-panel {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.warehouse-panel.is-embedded {
|
||||
padding: 0 0 8rpx;
|
||||
}
|
||||
|
||||
/* 搜索 */
|
||||
.toolbar {
|
||||
margin-bottom: 16rpx;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
width: 100%;
|
||||
height: 76rpx;
|
||||
padding: 0 24rpx;
|
||||
border-radius: 16rpx;
|
||||
border: 1px solid #e2e8f0;
|
||||
background: #ffffff;
|
||||
font-size: 28rpx;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* 筛选 + 批量上传:同一行(条件在左、总数靠右、操作在最右) */
|
||||
.filter-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12rpx;
|
||||
margin-bottom: 16rpx;
|
||||
}
|
||||
|
||||
.chips {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12rpx;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
/* 方形选择框(不是糖丸):高度固定,圆角 10rpx */
|
||||
.chip {
|
||||
flex: none;
|
||||
height: 60rpx;
|
||||
line-height: 60rpx;
|
||||
padding: 0 18rpx;
|
||||
border-radius: 10rpx;
|
||||
border: 1px solid #d4d4d8;
|
||||
background: #ffffff;
|
||||
color: #475569;
|
||||
font-size: 22rpx;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.chip.is-on {
|
||||
border-color: #10b981;
|
||||
background: #ecfdf5;
|
||||
color: #047857;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.total {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
margin-left: auto;
|
||||
color: #94a3b8;
|
||||
font-size: 22rpx;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.upload-btn {
|
||||
flex: none;
|
||||
margin: 0;
|
||||
padding: 0 20rpx;
|
||||
height: 60rpx;
|
||||
line-height: 60rpx;
|
||||
border-radius: 10rpx;
|
||||
background: #059669;
|
||||
color: #ffffff;
|
||||
font-size: 22rpx;
|
||||
font-weight: 500;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.upload-btn::after {
|
||||
border: none;
|
||||
}
|
||||
|
||||
.upload-btn.is-disabled {
|
||||
background: #cbd5e1;
|
||||
color: #ffffff;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* ── 表格 ───────────────────────────────────────────── */
|
||||
.table {
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 16rpx;
|
||||
background: #ffffff;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.tr {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
border-bottom: 1px solid #f1f5f9;
|
||||
}
|
||||
|
||||
.tr:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.tr.is-selected {
|
||||
background: #f6fefb;
|
||||
}
|
||||
|
||||
.thead {
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.td {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 16rpx 12rpx;
|
||||
font-size: 24rpx;
|
||||
color: #334155;
|
||||
box-sizing: border-box;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.thead .td {
|
||||
font-size: 22rpx;
|
||||
font-weight: 600;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.td-product {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 4rpx;
|
||||
}
|
||||
|
||||
.td-qty {
|
||||
width: 96rpx;
|
||||
flex: none;
|
||||
justify-content: flex-end;
|
||||
font-weight: 600;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.td-cost {
|
||||
width: 124rpx;
|
||||
flex: none;
|
||||
justify-content: flex-end;
|
||||
font-weight: 600;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.td-report {
|
||||
width: 104rpx;
|
||||
flex: none;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.check {
|
||||
width: 34rpx;
|
||||
height: 34rpx;
|
||||
flex: none;
|
||||
border-radius: 8rpx;
|
||||
border: 2rpx solid #cbd5e1;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.check.is-on {
|
||||
border-color: #10b981;
|
||||
background: #10b981;
|
||||
}
|
||||
|
||||
.name {
|
||||
max-width: 100%;
|
||||
font-size: 26rpx;
|
||||
font-weight: 600;
|
||||
color: #0f172a;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.name.is-missing {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
.sub {
|
||||
max-width: 100%;
|
||||
font-size: 20rpx;
|
||||
color: #94a3b8;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.is-missing {
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.is-ok {
|
||||
color: #047857;
|
||||
}
|
||||
|
||||
.table-hint {
|
||||
padding: 32rpx 0;
|
||||
text-align: center;
|
||||
color: #94a3b8;
|
||||
font-size: 24rpx;
|
||||
}
|
||||
|
||||
.hint {
|
||||
padding: 20rpx 0;
|
||||
text-align: center;
|
||||
color: #94a3b8;
|
||||
font-size: 20rpx;
|
||||
}
|
||||
|
||||
.link.is-danger {
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
/* 弹层(root-portal 内:固定视口、盖住底部 tab)
|
||||
四边显式写全,不依赖 inset 简写;z-index 必须高于 .tab-bar(100)。 */
|
||||
.sheet-mask {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: center;
|
||||
background: rgba(15, 23, 42, 0.48);
|
||||
}
|
||||
|
||||
/* 头 / 体 / 脚三段:头脚固定,只有 body 内部滚动(长列表不把按钮推出去) */
|
||||
.sheet {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
max-height: 82vh;
|
||||
padding: 28rpx 32rpx calc(24rpx + constant(safe-area-inset-bottom));
|
||||
padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
|
||||
border-radius: 28rpx 28rpx 0 0;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 -16rpx 48rpx rgba(15, 23, 42, 0.16);
|
||||
box-sizing: border-box;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* 修改弹窗:居中卡片(与 Web 库存调整弹窗同形),不贴底、不横向满屏 */
|
||||
.sheet-mask.is-center {
|
||||
align-items: center;
|
||||
padding: 0 48rpx;
|
||||
}
|
||||
|
||||
.sheet.is-center {
|
||||
max-width: 660rpx;
|
||||
border-radius: 24rpx;
|
||||
padding: 32rpx;
|
||||
box-shadow: 0 24rpx 64rpx rgba(15, 23, 42, 0.24);
|
||||
}
|
||||
|
||||
.sheet-head {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 20rpx;
|
||||
}
|
||||
|
||||
.sheet-head-text {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.sheet-title {
|
||||
font-size: 32rpx;
|
||||
font-weight: 600;
|
||||
color: #0f172a;
|
||||
line-height: 1.3;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.sheet-sub {
|
||||
margin-top: 8rpx;
|
||||
font-size: 22rpx;
|
||||
color: #94a3b8;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.sheet-close {
|
||||
flex: none;
|
||||
width: 56rpx;
|
||||
height: 56rpx;
|
||||
line-height: 52rpx;
|
||||
text-align: center;
|
||||
font-size: 40rpx;
|
||||
color: #94a3b8;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.sheet-body {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
max-height: 56vh;
|
||||
margin-top: 24rpx;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.sheet-field + .sheet-field {
|
||||
margin-top: 24rpx;
|
||||
}
|
||||
|
||||
.sheet-label {
|
||||
display: block;
|
||||
margin-bottom: 10rpx;
|
||||
font-size: 24rpx;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.sheet-input {
|
||||
width: 100%;
|
||||
height: 84rpx;
|
||||
padding: 0 24rpx;
|
||||
border-radius: 16rpx;
|
||||
border: 1px solid #e2e8f0;
|
||||
background: #f8fafc;
|
||||
font-size: 30rpx;
|
||||
font-weight: 600;
|
||||
color: #0f172a;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.sheet-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 20rpx;
|
||||
margin-top: 24rpx;
|
||||
padding: 24rpx 0;
|
||||
border-top: 1px dashed #e2e8f0;
|
||||
border-bottom: 1px dashed #e2e8f0;
|
||||
}
|
||||
|
||||
.sheet-link-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 16rpx;
|
||||
}
|
||||
|
||||
.sheet-link-label {
|
||||
flex: none;
|
||||
font-size: 26rpx;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.sheet-link-value {
|
||||
flex: none;
|
||||
font-size: 26rpx;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* 单批次上传报告(编辑弹窗 / 报告弹窗共用):矩形圆角,与筛选项 / 上传按钮一致 */
|
||||
.upload-chip {
|
||||
flex: none;
|
||||
padding: 12rpx 22rpx;
|
||||
border-radius: 10rpx;
|
||||
border: 1px solid #10b981;
|
||||
background: #ecfdf5;
|
||||
color: #047857;
|
||||
font-size: 24rpx;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.upload-chip.is-disabled {
|
||||
border-color: #cbd5e1;
|
||||
background: #f1f5f9;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.report-toolbar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16rpx;
|
||||
margin-top: 20rpx;
|
||||
padding-bottom: 12rpx;
|
||||
}
|
||||
|
||||
.report-toolbar-hint {
|
||||
font-size: 22rpx;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.sheet-empty {
|
||||
padding: 24rpx 0;
|
||||
text-align: center;
|
||||
font-size: 24rpx;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.sheet-actions {
|
||||
flex: none;
|
||||
display: flex;
|
||||
gap: 20rpx;
|
||||
margin-top: 24rpx;
|
||||
}
|
||||
|
||||
.btn {
|
||||
flex: 1;
|
||||
height: 88rpx;
|
||||
line-height: 88rpx;
|
||||
text-align: center;
|
||||
border-radius: 18rpx;
|
||||
font-size: 30rpx;
|
||||
}
|
||||
|
||||
.btn.ghost {
|
||||
background: #f1f5f9;
|
||||
color: #475569;
|
||||
}
|
||||
|
||||
.btn.primary {
|
||||
background: #059669;
|
||||
color: #ffffff;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn.is-disabled {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.report-list {
|
||||
margin-top: 4rpx;
|
||||
}
|
||||
|
||||
.report-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16rpx;
|
||||
padding: 20rpx 0;
|
||||
border-bottom: 1px solid #f1f5f9;
|
||||
}
|
||||
|
||||
.report-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6rpx;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.report-type {
|
||||
font-size: 26rpx;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.report-meta {
|
||||
font-size: 22rpx;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.report-delete {
|
||||
flex: none;
|
||||
font-size: 24rpx;
|
||||
color: #dc2626;
|
||||
}
|
||||
/* ── 批量上传:文件 + 解析匹配 ─────────────────────────── */
|
||||
.upload-files {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12rpx;
|
||||
margin-bottom: 16rpx;
|
||||
}
|
||||
|
||||
.upload-file {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10rpx;
|
||||
max-width: 100%;
|
||||
padding: 8rpx 14rpx;
|
||||
border-radius: 12rpx;
|
||||
background: #f1f5f9;
|
||||
font-size: 22rpx;
|
||||
color: #475569;
|
||||
}
|
||||
|
||||
.upload-file-name {
|
||||
max-width: 380rpx;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.upload-file-del {
|
||||
flex: none;
|
||||
color: #94a3b8;
|
||||
font-size: 26rpx;
|
||||
}
|
||||
|
||||
.upload-primary {
|
||||
height: 76rpx;
|
||||
line-height: 76rpx;
|
||||
text-align: center;
|
||||
border-radius: 16rpx;
|
||||
background: #ecfdf5;
|
||||
border: 1px solid #10b981;
|
||||
color: #047857;
|
||||
font-size: 26rpx;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.upload-primary.is-disabled {
|
||||
border-color: #cbd5e1;
|
||||
background: #f1f5f9;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.match-group {
|
||||
margin-top: 24rpx;
|
||||
padding-top: 20rpx;
|
||||
border-top: 1px dashed #e2e8f0;
|
||||
}
|
||||
|
||||
.match-title {
|
||||
font-size: 24rpx;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.match-item {
|
||||
margin-top: 12rpx;
|
||||
}
|
||||
|
||||
.match-product {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12rpx;
|
||||
}
|
||||
|
||||
.match-name {
|
||||
font-size: 26rpx;
|
||||
font-weight: 600;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.match-status {
|
||||
flex: none;
|
||||
font-size: 22rpx;
|
||||
color: #047857;
|
||||
}
|
||||
|
||||
.match-status.is-missing {
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.match-candidate {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12rpx;
|
||||
margin-top: 10rpx;
|
||||
padding: 14rpx;
|
||||
border-radius: 12rpx;
|
||||
border: 1px solid #e2e8f0;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.match-candidate.is-on {
|
||||
border-color: #10b981;
|
||||
background: #f6fefb;
|
||||
}
|
||||
|
||||
.match-candidate-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4rpx;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.match-candidate-label {
|
||||
font-size: 24rpx;
|
||||
color: #0f172a;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.match-candidate-meta {
|
||||
font-size: 20rpx;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* 小程序「仓库管理」面板契约(2026-10-23 开发者):
|
||||
* · 与其它模块一致:作为**首页一级 Tab 内嵌面板**,不是另开二级列表页;
|
||||
* · 列表字段对齐 Web 库存管理:商品名 / 批次 / 可用数量 / 成本价 / 报告状态;
|
||||
* · 支持**批量上传报告**、行内改成本价 / 可用数量、按批次查看与删除报告;
|
||||
* · 默认仓管可见,其他角色由 `warehouse_manage` 授权(注册表 grantable)。
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const assert = require('assert');
|
||||
|
||||
const read = (rel) => fs.readFileSync(path.join(__dirname, rel), 'utf8');
|
||||
|
||||
const panelJs = read('index.js');
|
||||
const panelWxml = read('index.wxml');
|
||||
const registry = read('../../modules/registry.js');
|
||||
const homeJs = read('../../pages/home/home.js');
|
||||
const homeWxml = read('../../pages/home/home.wxml');
|
||||
const homeJson = read('../../pages/home/home.json');
|
||||
const guard = read('../../utils/roleGuard.js');
|
||||
const api = read('../../utils/request.js');
|
||||
const pageJs = read('../../pages/warehouse/warehouse.js');
|
||||
const wxss = read('index.wxss');
|
||||
|
||||
let failed = 0;
|
||||
function it(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
console.log(' ✓', name);
|
||||
} catch (err) {
|
||||
failed += 1;
|
||||
console.log(' ✗', name, '→', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
it('是一级界面:首页内嵌面板(与加工/库存入库同规矩),页面只是薄壳', () => {
|
||||
assert.ok(registry.includes("homeEmbed: 'warehouse-panel'"), '注册表必须声明 homeEmbed');
|
||||
assert.ok(homeJson.includes('"warehouse-panel": "/components/warehouse-panel/index"'));
|
||||
assert.ok(homeWxml.includes("activeHomeModuleId === 'warehouse'"));
|
||||
assert.ok(homeWxml.includes('<warehouse-panel'));
|
||||
// 页面不承载界面:只 selectComponent 转发下拉刷新/触底
|
||||
assert.ok(pageJs.includes("selectComponent('#warehousePanel')"));
|
||||
assert.ok(!pageJs.includes('setData('), '页面不应承载列表状态');
|
||||
});
|
||||
|
||||
it('默认仓管可见,其他角色可授权(grantable + 不切角色)', () => {
|
||||
assert.ok(registry.includes("permissionKey: 'warehouse_manage'"));
|
||||
assert.ok(registry.includes('grantable: true'));
|
||||
// 可见性:角色命中 或 权限命中
|
||||
assert.ok(registry.includes('if (!roleHit && !permissionHit) return false;'));
|
||||
// 首页内嵌判定也支持权限兜底
|
||||
assert.ok(registry.includes('function isHomeWorkspaceModule(mod, availableRoles, fallbackRole, permissions)'));
|
||||
assert.ok(registry.includes('return perms.includes(mod.permissionKey);'));
|
||||
// 激活/跳转:被授权但角色不匹配时不切角色
|
||||
assert.ok(homeJs.includes('const grantedOnly ='));
|
||||
assert.ok(homeJs.includes('const ok = grantedOnly ? true : await ensureMobileRole(roles, ensureOpts);'));
|
||||
// 回弹回归(2026-10-25 录单员反馈):重算一级 Tab 时必须带权限,否则切过去又被退回默认模块
|
||||
assert.ok(
|
||||
homeJs.includes(
|
||||
'isHomeWorkspaceModule(mod, roleValues, this.data.roleType, this.data.permissions)'
|
||||
),
|
||||
'refreshMenuModules 必须把 permissions 传给 isHomeWorkspaceModule'
|
||||
);
|
||||
assert.ok(homeJs.includes("warehouse: '#warehouseHomePanel'"), '切回同一 Tab 时能刷新面板');
|
||||
assert.ok(homeJs.includes('wx.navigateTo({ url });'));
|
||||
// 页面守卫
|
||||
assert.ok(guard.includes('function hasWarehouseModuleAccess(session)'));
|
||||
assert.ok(guard.includes("perms.includes('warehouse_manage')"));
|
||||
assert.ok(guard.includes('function requireWarehouseModuleRole()'));
|
||||
assert.ok(panelJs.includes('requireWarehouseModuleRole()'));
|
||||
});
|
||||
|
||||
it('列表是表格布局:表头 + 列对齐(不是卡片堆叠)', () => {
|
||||
assert.ok(panelWxml.includes('class="table"'), '必须用表格容器');
|
||||
assert.ok(panelWxml.includes('tr thead'), '必须有表头行');
|
||||
assert.ok(panelWxml.includes('td-product'));
|
||||
assert.ok(panelWxml.includes('td-qty'));
|
||||
assert.ok(panelWxml.includes('td-cost'));
|
||||
assert.ok(panelWxml.includes('td-report'));
|
||||
// 行点击 → **直接弹修改弹窗**(不再先出选择菜单)
|
||||
assert.ok(panelJs.includes('onRowTap(e)'));
|
||||
assert.ok(panelJs.includes('this.openEditSheetById('));
|
||||
assert.ok(!panelJs.includes('报告(查看/删除)'), '行点击不得再弹 actionSheet');
|
||||
assert.ok(panelWxml.includes('bindtap="onRowTap"'));
|
||||
// 弹窗一次给出可用数量 + 成本价 + 报告入口
|
||||
assert.ok(panelWxml.includes('onEditAvailableInput'));
|
||||
assert.ok(panelWxml.includes('onEditCostInput'));
|
||||
assert.ok(panelWxml.includes('catchtap="openReportsFromEdit"'));
|
||||
assert.ok(panelJs.includes('async submitEditSheet()'));
|
||||
// 从安全区底部升起(home 指示条留白)
|
||||
assert.ok(wxss.includes('env(safe-area-inset-bottom)'));
|
||||
assert.ok(wxss.includes('constant(safe-area-inset-bottom)'));
|
||||
// 表格样式:flex 行 + 固定列宽,保证上下对齐
|
||||
assert.ok(wxss.includes('.tr {'));
|
||||
assert.ok(wxss.includes('.td-qty {'));
|
||||
assert.ok(wxss.includes('.td-cost {'));
|
||||
assert.ok(wxss.includes('.td-report {'));
|
||||
});
|
||||
|
||||
it('列表字段对齐 Web 库存管理(商品名/批次/可用/成本/报告状态)', () => {
|
||||
assert.ok(api.includes('function fetchInventoryBatches('));
|
||||
assert.ok(api.includes('/mobile/inventory/batches'));
|
||||
assert.ok(panelJs.includes('available_text'));
|
||||
assert.ok(panelJs.includes('cost_missing'));
|
||||
assert.ok(panelJs.includes('report_missing'));
|
||||
assert.ok(panelWxml.includes('{{item.sku_name}}'));
|
||||
assert.ok(panelWxml.includes('{{item.batch_no}}'));
|
||||
assert.ok(panelWxml.includes('可用数量'));
|
||||
assert.ok(panelWxml.includes('成本价'));
|
||||
assert.ok(panelWxml.includes('缺少')); // 表格列窄,缺报告在报告列显示「缺少」
|
||||
// 入库时间(2026-10-25 开发者:列表缺少入库时间)——口径同 Web:批次最早一条入库流水
|
||||
assert.ok(panelJs.includes('inbound_at: row.inbound_at'), '列表行必须带 inbound_at');
|
||||
assert.ok(panelWxml.includes('入库 {{item.inbound_at'), '商品列必须展示入库时间');
|
||||
// 一进面板默认只看可用(2026-10-25 开发者:「仅有可用这个是默认选择的 一进去」)
|
||||
assert.ok(panelJs.includes('onlyAvailable: true'), '默认必须勾选「仅有可用」');
|
||||
assert.ok(panelWxml.includes("chip {{onlyAvailable ? 'is-on' : ''}}"), '筛选项选中态绑定不变');
|
||||
});
|
||||
|
||||
it('顶部统计卡:库存批次 / 可用总量 / 可用货值(与列表同筛选口径)', () => {
|
||||
// 数据来自服务端同一 where 的 stats,不在小程序侧另算
|
||||
assert.ok(panelJs.includes("this.triggerEvent('statschange'"));
|
||||
assert.ok(panelJs.includes('stats.total_available_qty'));
|
||||
assert.ok(panelJs.includes('stats.total_value'));
|
||||
// 首页:面板上报 → 顶部绿卡(无数据时归零)
|
||||
assert.ok(homeWxml.includes('bind:statschange="onWarehouseStatsChange"'));
|
||||
assert.ok(homeJs.includes('onWarehouseStatsChange(e)'));
|
||||
assert.ok(homeWxml.includes('wx:if="{{showWarehouseStats}}"'));
|
||||
assert.ok(homeWxml.includes('库存批次'));
|
||||
assert.ok(homeWxml.includes('可用总量'));
|
||||
assert.ok(homeWxml.includes('可用货值'));
|
||||
// 布局:文字在上、数字在下(2026-10-25 开发者)
|
||||
const labelIdx = homeWxml.indexOf('>库存批次<');
|
||||
const numIdx = homeWxml.indexOf('{{warehouseBatchCount}}');
|
||||
assert.ok(labelIdx > -1 && numIdx > labelIdx, '统计卡必须文字在上、数字在下');
|
||||
// 有统计卡时不再另外渲染单纯的模块标题卡
|
||||
assert.ok(homeJs.includes('showWarehouseStats;'), '必须计入 hasDedicatedProgress');
|
||||
});
|
||||
|
||||
it('列表分页:每页 20,首页触底转发给内嵌面板', () => {
|
||||
assert.ok(panelJs.includes('const PAGE_SIZE = 20;'), '每页固定 20 条');
|
||||
assert.ok(panelJs.includes('this.loadPage(this.data.page + 1, true)'), '触底加载下一页(追加)');
|
||||
assert.ok(panelJs.includes('if (!this.data.hasMore || this.data.loading || this.data.loadingMore) return;'));
|
||||
// 首页内嵌面板必须收到页面触底事件,否则只能看到第 1 页
|
||||
assert.ok(homeJs.includes('onReachBottom()'), '首页必须有 onReachBottom');
|
||||
assert.ok(
|
||||
homeJs.includes('HOME_PANEL_SELECTORS[this.data.activeHomeModuleId]'),
|
||||
'触底必须转给当前模块面板'
|
||||
);
|
||||
assert.ok(homeJs.includes("warehouse: '#warehouseHomePanel'"));
|
||||
});
|
||||
|
||||
it('批量上传:上传 → 识别 → 匹配候选 → 人工确认(与 Web 同流程)', () => {
|
||||
// 入口:不是先勾选行,而是打开上传弹层
|
||||
assert.ok(panelWxml.includes('bindtap="openUploadSheet"'));
|
||||
assert.ok(!panelJs.includes('toggleSelectAll'), '不应再有「勾选商品再上传」');
|
||||
assert.ok(!panelJs.includes('selectedIds'), '不应再有行勾选状态');
|
||||
// 上传文件 + 服务端解析(返回候选批次)
|
||||
assert.ok(panelJs.includes('uploadQualityReportStorageFile('));
|
||||
assert.ok(panelJs.includes("await parseInventoryBatchReports({ files: paths, report_type: 'batch' })"));
|
||||
assert.ok(api.includes('function parseInventoryBatchReports('));
|
||||
assert.ok(api.includes('/mobile/inventory/batch-reports/parse'));
|
||||
// 唯一命中自动勾选,其余人工确认
|
||||
assert.ok(panelJs.includes("const selected = match.status === 'unique';"));
|
||||
assert.ok(panelWxml.includes('catchtap="toggleUploadCandidate"'));
|
||||
// 确认匹配(逐个报告提交)
|
||||
assert.ok(panelJs.includes('await confirmInventoryBatchReportMatches(payloads[i].reportId, payloads[i].matches);'));
|
||||
assert.ok(api.includes('function confirmInventoryBatchReportMatches('));
|
||||
assert.ok(panelWxml.includes('确认匹配('));
|
||||
// 工具栏:筛选 + 总数 + 批量上传都在同一行(方形选择框,不用椭圆)
|
||||
const filterStart = panelWxml.indexOf('class="filter-row"');
|
||||
const uploadIdx = panelWxml.indexOf('class="upload-btn');
|
||||
assert.ok(filterStart > -1, '必须有筛选行');
|
||||
assert.ok(uploadIdx > filterStart, '批量上传按钮必须在筛选行内(同一行)');
|
||||
assert.ok(!panelWxml.includes('class="action-row"'), '不得再有单独的操作行');
|
||||
assert.ok(wxss.includes('.filter-row {'));
|
||||
assert.ok(wxss.includes('.upload-btn::after'));
|
||||
// 筛选项 / 上传按钮都用矩形圆角(10rpx),不得回到 999rpx 糖丸
|
||||
const chipBlock = wxss.slice(wxss.indexOf('.chip {'), wxss.indexOf('.chip.is-on'));
|
||||
assert.ok(chipBlock.includes('border-radius: 10rpx'), '筛选项必须是方形圆角');
|
||||
assert.ok(!chipBlock.includes('999rpx'), '筛选项不得用椭圆');
|
||||
const btnBlock = wxss.slice(wxss.indexOf('.upload-btn {'), wxss.indexOf('.upload-btn::after'));
|
||||
assert.ok(btnBlock.includes('border-radius: 10rpx'), '上传按钮必须是矩形圆角');
|
||||
assert.ok(!btnBlock.includes('999rpx'), '上传按钮不得用椭圆');
|
||||
});
|
||||
|
||||
it('行内改成本价 / 可用数量(按本批次 inventoryId)', () => {
|
||||
assert.ok(api.includes('function updateInventoryBatchCostPrice('));
|
||||
assert.ok(api.includes('function updateInventoryBatchAvailableQty('));
|
||||
assert.ok(api.includes('/cost-price'));
|
||||
assert.ok(api.includes('/available-qty'));
|
||||
assert.ok(panelJs.includes('await updateInventoryBatchCostPrice(item.id, nextCost)'));
|
||||
assert.ok(panelJs.includes('await updateInventoryBatchAvailableQty(item.id, nextQty)'));
|
||||
// 只提交真正改过的字段(两条写路径各带自己的审计/流水)
|
||||
assert.ok(panelJs.includes('if (qtyChanged) await updateInventoryBatchAvailableQty'));
|
||||
assert.ok(panelJs.includes('if (costChanged) await updateInventoryBatchCostPrice'));
|
||||
assert.ok(!panelJs.includes('sku_code: '), '改数量必须按批次 id,不得按 SKU');
|
||||
});
|
||||
|
||||
it('弹层走 root-portal:固定视口、不跟页面滚、盖住底部 tab', () => {
|
||||
// 每个弹层单独一个 root-portal:一个 portal 塞多个弹层会让 portal 不生效
|
||||
// (弹层会跟着页面滚动、且被底部 tab 栏盖住)——与加工/分拣面板同款做法。
|
||||
const portalCount = panelWxml.split('<root-portal').length - 1;
|
||||
const maskCount = (panelWxml.match(/class="sheet-mask/g) || []).length;
|
||||
assert.ok(portalCount === 3, `必须三个弹层三个 root-portal,实际 ${portalCount}`);
|
||||
assert.ok(maskCount === 3, `弹层遮罩数量应为 3,实际 ${maskCount}`);
|
||||
assert.ok(panelWxml.includes('<root-portal enable="{{true}}">'));
|
||||
assert.ok(panelWxml.includes('</root-portal>'));
|
||||
const portalStart = panelWxml.indexOf('<root-portal');
|
||||
assert.ok(panelWxml.indexOf('sheet-mask', portalStart) > portalStart, '弹层必须在 portal 内');
|
||||
assert.ok(panelWxml.indexOf('catchtouchmove="noop"', portalStart) > portalStart, '遮罩要吃掉滚动');
|
||||
assert.ok(wxss.includes('z-index: 10000'), '必须压过底部 tab(z-index 100)');
|
||||
assert.ok(wxss.includes('max-height: 82vh'), '弹层超高时可内部滚动');
|
||||
// 固定视口四边显式写全(不依赖 inset 简写)
|
||||
assert.ok(wxss.includes('top: 0;') && wxss.includes('bottom: 0;'), '遮罩必须铺满视口');
|
||||
// 头/脚固定,只有 body 滚动(长列表不把按钮推出屏幕)
|
||||
assert.ok(panelWxml.includes('<scroll-view scroll-y class="sheet-body"'), 'body 用 scroll-view 内部滚动');
|
||||
assert.ok(/\.sheet-actions \{[\s\S]{0,40}flex: none;/.test(wxss), '按钮行不得被滚动区撑开');
|
||||
});
|
||||
|
||||
it('编辑弹窗里也能上传该批次报告(单批次直传)', () => {
|
||||
// 编辑弹窗的「批次报告」行有「上传」
|
||||
assert.ok(panelWxml.includes('catchtap="onUploadFromEdit"'));
|
||||
assert.ok(panelWxml.includes('upload-chip'));
|
||||
// 报告弹窗顶部也有「上传报告」
|
||||
assert.ok(panelWxml.includes('catchtap="onUploadFromReports"'));
|
||||
// 单批次上传同样走「文件上传一次 → 绑定该批次」的既有通道
|
||||
assert.ok(panelJs.includes('async uploadReportsForBatch(inventoryId)'));
|
||||
assert.ok(panelJs.includes('await uploadInventoryBatchReports(id, { files: paths, report_type: \'batch\' });'));
|
||||
// 上传后刷新:报告列表 + 编辑弹窗状态 + 表格报告列
|
||||
assert.ok(panelJs.includes('async refreshBatchReports(inventoryId)'));
|
||||
assert.ok(panelJs.includes("patch['editItem.report_count'] = list.length"));
|
||||
assert.ok(panelJs.includes('await this.loadPage(1, false);'));
|
||||
});
|
||||
|
||||
it('报告:按批次查看 + 删除确认', () => {
|
||||
assert.ok(api.includes('function fetchInventoryBatchReports('));
|
||||
assert.ok(api.includes('function deleteInventoryBatchReport('));
|
||||
assert.ok(panelJs.includes('await deleteInventoryBatchReport(reportId)'));
|
||||
assert.ok(panelJs.includes("title: '删除报告'"));
|
||||
assert.ok(panelWxml.includes('批次报告'));
|
||||
});
|
||||
|
||||
if (failed) {
|
||||
console.error(`\n ${failed} 条失败`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('\n 全部通过');
|
||||
@@ -172,6 +172,19 @@ const MOBILE_MODULES = [
|
||||
homeEmbed: 'processing-panel',
|
||||
badgeKey: 'processingPendingCount',
|
||||
},
|
||||
{
|
||||
id: 'warehouse',
|
||||
title: '仓库管理',
|
||||
subtitle: '库存批次、成本价与报告状态,可批量上传报告',
|
||||
page: '/pages/warehouse/warehouse',
|
||||
// 默认给仓管;其他角色由管理员在「角色权限」勾 warehouse_manage 后可用(grantable)
|
||||
roles: ['warehouse'],
|
||||
grantable: true,
|
||||
permissionKey: 'warehouse_manage',
|
||||
handler: 'goWarehouse',
|
||||
// 与其它模块一致:作为首页一级 Tab 内嵌同一套面板
|
||||
homeEmbed: 'warehouse-panel',
|
||||
},
|
||||
{
|
||||
id: 'order-entry',
|
||||
title: '录单',
|
||||
@@ -219,6 +232,7 @@ const MODULE_SORT_ORDER = [
|
||||
'inspection',
|
||||
'stock-inbound',
|
||||
'processing',
|
||||
'warehouse',
|
||||
'picking',
|
||||
'supplier-status',
|
||||
'preparation',
|
||||
@@ -233,15 +247,19 @@ function isModuleVisible(mod, pageData) {
|
||||
if (mod.id === 'quality-reports') return false;
|
||||
const roleType = pageData.roleType;
|
||||
const currentRole = pageData.currentRoleType || roleType;
|
||||
if (mod.currentRoleOnly) {
|
||||
if (mod.roles && !mod.roles.includes(currentRole)) return false;
|
||||
const perms = pageData.permissions || [];
|
||||
const permissionHit =
|
||||
Boolean(mod.permissionKey) && (pageData.isSuperAdmin === true || perms.includes(mod.permissionKey));
|
||||
const roleHit = mod.currentRoleOnly
|
||||
? !mod.roles || mod.roles.includes(currentRole)
|
||||
: (!mod.roleOnly || mod.roleOnly === roleType) && (!mod.roles || mod.roles.includes(roleType));
|
||||
if (mod.grantable) {
|
||||
// 可授权模块(2026-10-23 仓库管理):角色命中 **或** 权限命中即可见;
|
||||
// 其它模块保持原来的「角色 AND 权限」语义,行为不变。
|
||||
if (!roleHit && !permissionHit) return false;
|
||||
} else {
|
||||
if (mod.roleOnly && mod.roleOnly !== roleType) return false;
|
||||
if (mod.roles && !mod.roles.includes(roleType)) return false;
|
||||
}
|
||||
if (mod.permissionKey) {
|
||||
const perms = pageData.permissions || [];
|
||||
if (!pageData.isSuperAdmin && !perms.includes(mod.permissionKey)) return false;
|
||||
if (!roleHit) return false;
|
||||
if (mod.permissionKey && !permissionHit) return false;
|
||||
}
|
||||
if (mod.featureFlag === 'supplierStatusEnabled' && !pageData.supplierStatusEnabled) return false;
|
||||
if (mod.featureFlag === 'pickingEnabled') {
|
||||
@@ -402,11 +420,17 @@ function filterModulesForHomeGrid(modules, availableRoles, fallbackRole) {
|
||||
}
|
||||
|
||||
/** 带 homeEmbed 且当前账号角色与模块 roles 有交集时,点击走首页底部切换 */
|
||||
function isHomeWorkspaceModule(mod, availableRoles, fallbackRole) {
|
||||
function isHomeWorkspaceModule(mod, availableRoles, fallbackRole, permissions) {
|
||||
if (!mod || !mod.homeEmbed) return false;
|
||||
const roles = new Set(normalizeRoleList(availableRoles, fallbackRole));
|
||||
const embedRoles = Array.isArray(mod.homeEmbedRoles) ? mod.homeEmbedRoles : mod.roles;
|
||||
return Array.isArray(embedRoles) && embedRoles.some((role) => roles.has(role));
|
||||
if (Array.isArray(embedRoles) && embedRoles.some((role) => roles.has(role))) return true;
|
||||
// 可授权模块(仓库管理):角色不命中但持入口权限 ⇒ 同样作为首页一级 Tab
|
||||
if (mod.grantable === true && mod.permissionKey) {
|
||||
const perms = Array.isArray(permissions) ? permissions : [];
|
||||
return perms.includes(mod.permissionKey);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -20,6 +20,27 @@ const HOME_MODULE_STORAGE_KEY = 'mp_home_active_module';
|
||||
|
||||
const MODULE_GRID_TITLE_SIZE = '26rpx';
|
||||
|
||||
/** 首页内嵌面板的组件选择器(切模块刷新 / 触底加载共用) */
|
||||
const HOME_PANEL_SELECTORS = {
|
||||
purchase: '#purchaseHomePanel',
|
||||
delivery: '#deliveryHomePanel',
|
||||
preparation: '#preparationHomePanel',
|
||||
'prep-history': '#prepHistoryHomePanel',
|
||||
'prep-price-amend': '#prepPriceAmendHomePanel',
|
||||
bid: '#bidHomePanel',
|
||||
'quality-reports': '#qualityReportsHomePanel',
|
||||
inspection: '#inspectionHomePanel',
|
||||
'stock-inbound': '#stockInboundHomePanel',
|
||||
processing: '#processingHomePanel',
|
||||
warehouse: '#warehouseHomePanel',
|
||||
picking: '#pickingHomePanel',
|
||||
'order-manage': '#orderManageHomePanel',
|
||||
'admin-preparations': '#adminPreparationsHomePanel',
|
||||
'admin-purchase': '#adminPurchaseHomePanel',
|
||||
'prep-amend-review': '#prepAmendHomePanel',
|
||||
'order-entry': '#orderEntryHomePanel',
|
||||
};
|
||||
|
||||
function pxToRpx(px, windowWidth) {
|
||||
const w = Number(windowWidth) || 375;
|
||||
return `${Math.round((Number(px) * 750) / w)}rpx`;
|
||||
@@ -232,6 +253,11 @@ function buildLoggedOutHomeData() {
|
||||
pickingPickedCount: 0,
|
||||
pickingPendingCount: 0,
|
||||
pickingPendingTaskCount: 0,
|
||||
// 仓库管理:库存批次 / 可用总量 / 可用货值(面板上报,与列表同筛选口径)
|
||||
showWarehouseStats: false,
|
||||
warehouseBatchCount: 0,
|
||||
warehouseAvailableQtyText: '0',
|
||||
warehouseAvailableValueText: '0.00',
|
||||
orderPendingCount: 0,
|
||||
orderProcessingCount: 0,
|
||||
orderCompletedCount: 0,
|
||||
@@ -613,6 +639,16 @@ Page({
|
||||
});
|
||||
},
|
||||
|
||||
/** 仓库管理面板上报统计(批次数量 / 可用总量 / 可用货值) */
|
||||
onWarehouseStatsChange(e) {
|
||||
const detail = (e && e.detail) || {};
|
||||
this.setData({
|
||||
warehouseBatchCount: Number(detail.batches) || 0,
|
||||
warehouseAvailableQtyText: String(detail.availableQtyText || '0'),
|
||||
warehouseAvailableValueText: String(detail.availableValueText || '0.00'),
|
||||
});
|
||||
},
|
||||
|
||||
onPickingBadgeChange(e) {
|
||||
const count = Number(e && e.detail && e.detail.count);
|
||||
if (Number.isFinite(count)) {
|
||||
@@ -673,7 +709,9 @@ Page({
|
||||
const menuBase = buildUnionModules(this.data, roleValues);
|
||||
const gridBase = filterModulesForHomeGrid(menuBase, roleValues, this.data.roleType);
|
||||
const workspaceMods = gridBase.filter((mod) =>
|
||||
isHomeWorkspaceModule(mod, roleValues, this.data.roleType)
|
||||
// 必须带 permissions:被授权但角色不命中的模块(仓库管理)也要算一级 Tab,
|
||||
// 否则点进去后 refreshMenuModules 会把 activeHomeModuleId 退回默认模块(回弹)。
|
||||
isHomeWorkspaceModule(mod, roleValues, this.data.roleType, this.data.permissions)
|
||||
);
|
||||
const showHomeWorkspace = workspaceMods.length > 0;
|
||||
const workspaceIds = new Set(workspaceMods.map((mod) => mod.id));
|
||||
@@ -749,6 +787,11 @@ Page({
|
||||
const showInspectionProgress = exclusive.showInspectionProgress;
|
||||
const showProcessingProgress = exclusive.showProcessingProgress;
|
||||
const showPickingProgress = exclusive.showPickingProgress;
|
||||
// 仓库管理:顶部换成「库存批次 / 可用总量 / 可用货值」三格(不再显示単纯标题卡)
|
||||
const showWarehouseStats =
|
||||
showHomeWorkspace &&
|
||||
activeHomeModuleId === 'warehouse' &&
|
||||
workspaceIds.has('warehouse');
|
||||
const showOrderProgressExclusive = exclusive.showOrderProgress;
|
||||
const showAdminPrepProgressExclusive = exclusive.showAdminPrepProgress;
|
||||
const showPrepAmendProgressExclusive = exclusive.showPrepAmendProgress;
|
||||
@@ -761,7 +804,8 @@ Page({
|
||||
showPreparationProgress ||
|
||||
showInspectionProgress ||
|
||||
showProcessingProgress ||
|
||||
showPickingProgress;
|
||||
showPickingProgress ||
|
||||
showWarehouseStats;
|
||||
const activeWorkspaceMod = workspaceMods.find((mod) => mod.id === activeHomeModuleId);
|
||||
const homeModuleTitle = String(activeWorkspaceMod?.title || '').trim();
|
||||
const showModuleTitleBar = Boolean(showHomeWorkspace && !hasDedicatedProgress && homeModuleTitle);
|
||||
@@ -781,6 +825,7 @@ Page({
|
||||
showInspectionProgress,
|
||||
showProcessingProgress,
|
||||
showPickingProgress,
|
||||
showWarehouseStats,
|
||||
showOrderProgress: showOrderProgressExclusive,
|
||||
showAdminPrepProgress: showAdminPrepProgressExclusive,
|
||||
showPrepAmendProgress: showPrepAmendProgressExclusive,
|
||||
@@ -824,6 +869,13 @@ Page({
|
||||
pickingPickedCount: 0,
|
||||
pickingPendingCount: 0,
|
||||
}),
|
||||
...(showWarehouseStats
|
||||
? {}
|
||||
: {
|
||||
warehouseBatchCount: 0,
|
||||
warehouseAvailableQtyText: '0',
|
||||
warehouseAvailableValueText: '0.00',
|
||||
}),
|
||||
...(showOrderProgressExclusive ? {} : orderProgressPatch(0, 0, 0)),
|
||||
...(showAdminPrepProgressExclusive
|
||||
? {}
|
||||
@@ -890,7 +942,12 @@ Page({
|
||||
if (!target) return;
|
||||
if (
|
||||
this.data.showHomeWorkspace &&
|
||||
isHomeWorkspaceModule(target, this.data.availableRoleValues, this.data.roleType)
|
||||
isHomeWorkspaceModule(
|
||||
target,
|
||||
this.data.availableRoleValues,
|
||||
this.data.roleType,
|
||||
(getSession() || {}).permissions || []
|
||||
)
|
||||
) {
|
||||
this.activateHomeModule(target);
|
||||
return;
|
||||
@@ -1004,6 +1061,18 @@ Page({
|
||||
this.setData({ navigatingModule: true });
|
||||
try {
|
||||
const ensureOpts = target.id === 'picking' ? { prefer: 'picker' } : {};
|
||||
// 可授权模块(仓库管理):角色不命中但持有入口权限 ⇒ 不切角色,直接进
|
||||
const session = getSession() || {};
|
||||
const perms = Array.isArray(session.permissions) ? session.permissions : [];
|
||||
const grantedOnly =
|
||||
target.grantable === true &&
|
||||
Boolean(target.permissionKey) &&
|
||||
perms.includes(target.permissionKey) &&
|
||||
!roles.includes(session.role_type);
|
||||
if (grantedOnly) {
|
||||
wx.navigateTo({ url });
|
||||
return;
|
||||
}
|
||||
await ensureRoleThenNavigate(roles, url, ensureOpts);
|
||||
} finally {
|
||||
this.setData({ navigatingModule: false });
|
||||
@@ -1027,7 +1096,15 @@ Page({
|
||||
this.setData({ navigatingModule: true });
|
||||
try {
|
||||
const ensureOpts = target.id === 'picking' ? { prefer: 'picker' } : {};
|
||||
const ok = await ensureMobileRole(roles, ensureOpts);
|
||||
// 可授权模块(仓库管理):角色不命中但持入口权限 ⇒ 不切角色,直接内嵌展示
|
||||
const session = getSession() || {};
|
||||
const perms = Array.isArray(session.permissions) ? session.permissions : [];
|
||||
const grantedOnly =
|
||||
target.grantable === true &&
|
||||
Boolean(target.permissionKey) &&
|
||||
perms.includes(target.permissionKey) &&
|
||||
!roles.includes(session.role_type);
|
||||
const ok = grantedOnly ? true : await ensureMobileRole(roles, ensureOpts);
|
||||
if (!ok) return;
|
||||
persistHomeModule(target.id);
|
||||
const sessionNow = getSession() || {};
|
||||
@@ -1057,25 +1134,7 @@ Page({
|
||||
},
|
||||
|
||||
notifyHomePanelShow(moduleId) {
|
||||
const selectors = {
|
||||
purchase: '#purchaseHomePanel',
|
||||
delivery: '#deliveryHomePanel',
|
||||
preparation: '#preparationHomePanel',
|
||||
'prep-history': '#prepHistoryHomePanel',
|
||||
'prep-price-amend': '#prepPriceAmendHomePanel',
|
||||
bid: '#bidHomePanel',
|
||||
'quality-reports': '#qualityReportsHomePanel',
|
||||
inspection: '#inspectionHomePanel',
|
||||
'stock-inbound': '#stockInboundHomePanel',
|
||||
processing: '#processingHomePanel',
|
||||
picking: '#pickingHomePanel',
|
||||
'order-manage': '#orderManageHomePanel',
|
||||
'admin-preparations': '#adminPreparationsHomePanel',
|
||||
'admin-purchase': '#adminPurchaseHomePanel',
|
||||
'prep-amend-review': '#prepAmendHomePanel',
|
||||
'order-entry': '#orderEntryHomePanel',
|
||||
};
|
||||
const selector = selectors[moduleId];
|
||||
const selector = HOME_PANEL_SELECTORS[moduleId];
|
||||
if (!selector) return;
|
||||
wx.nextTick(() => {
|
||||
const tryNotify = (left) => {
|
||||
@@ -1092,6 +1151,15 @@ Page({
|
||||
});
|
||||
},
|
||||
|
||||
onReachBottom() {
|
||||
// 内嵌面板在首页里是子组件,页面的触底事件不会自动传到组件:
|
||||
// 这里转给当前模块面板(只有带 onReachBottom 的列表面板会接,其它面板零影响)。
|
||||
const selector = HOME_PANEL_SELECTORS[this.data.activeHomeModuleId];
|
||||
if (!selector) return;
|
||||
const panel = this.selectComponent(selector);
|
||||
if (panel && typeof panel.onReachBottom === 'function') panel.onReachBottom();
|
||||
},
|
||||
|
||||
async onModuleTap(e) {
|
||||
if (this.data.needLogin) {
|
||||
this.goLogin();
|
||||
@@ -1104,7 +1172,12 @@ Page({
|
||||
(this.data.menuModules || []).find((item) => item.id === id || item.page === page);
|
||||
if (
|
||||
this.data.showHomeWorkspace &&
|
||||
isHomeWorkspaceModule(mod, this.data.availableRoleValues, this.data.roleType)
|
||||
isHomeWorkspaceModule(
|
||||
mod,
|
||||
this.data.availableRoleValues,
|
||||
this.data.roleType,
|
||||
(getSession() || {}).permissions || []
|
||||
)
|
||||
) {
|
||||
await this.activateHomeModule(mod);
|
||||
return;
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
"inspection-panel": "/components/inspection-panel/index",
|
||||
"stock-inbound-panel": "/components/stock-inbound-panel/index",
|
||||
"processing-panel": "/components/processing-panel/index",
|
||||
"warehouse-panel": "/components/warehouse-panel/index",
|
||||
"picking-panel": "/components/picking-panel/index",
|
||||
"order-manage-panel": "/components/order-manage-panel/index",
|
||||
"admin-preparations-panel": "/components/admin-preparations-panel/index",
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
<view class="home-atmosphere" aria-hidden="true"></view>
|
||||
|
||||
<view
|
||||
wx:if="{{!needLogin && (kpiVisible || showPurchaseProgress || showPreparationProgress || showOrderProgress || showAdminPrepProgress || showPrepAmendProgress || showInspectionProgress || showProcessingProgress || showPickingProgress || showDeliveryProgress || showModuleTitleBar || gridModules.length)}}"
|
||||
wx:if="{{!needLogin && (kpiVisible || showPurchaseProgress || showPreparationProgress || showOrderProgress || showAdminPrepProgress || showPrepAmendProgress || showInspectionProgress || showProcessingProgress || showPickingProgress || showDeliveryProgress || showWarehouseStats || showModuleTitleBar || gridModules.length)}}"
|
||||
id="homeTopDock"
|
||||
class="home-progress-sticky"
|
||||
>
|
||||
<view
|
||||
wx:if="{{kpiVisible || showPurchaseProgress || showPreparationProgress || showOrderProgress || showAdminPrepProgress || showPrepAmendProgress || showInspectionProgress || showProcessingProgress || showPickingProgress || showDeliveryProgress || showModuleTitleBar}}"
|
||||
wx:if="{{kpiVisible || showPurchaseProgress || showPreparationProgress || showOrderProgress || showAdminPrepProgress || showPrepAmendProgress || showInspectionProgress || showProcessingProgress || showPickingProgress || showDeliveryProgress || showWarehouseStats || showModuleTitleBar}}"
|
||||
class="home-progress-dock xd-home-topbar"
|
||||
>
|
||||
<!-- 非采购内嵌:保留原首页 KPI(如供应商待供货 / 管理员改价待审) -->
|
||||
@@ -63,6 +63,23 @@
|
||||
>{{item.name}}</view>
|
||||
</view>
|
||||
</view>
|
||||
<!-- 仓库管理:库存批次 / 可用总量 / 可用货值(文字在上、数字在下) -->
|
||||
<view wx:if="{{showWarehouseStats}}" class="delivery-progress-card warehouse-stats-card">
|
||||
<view class="kpi-cell">
|
||||
<text class="kpi-label">库存批次</text>
|
||||
<text class="kpi-num xd-num">{{warehouseBatchCount}}</text>
|
||||
</view>
|
||||
<view class="kpi-divider"></view>
|
||||
<view class="kpi-cell">
|
||||
<text class="kpi-label">可用总量</text>
|
||||
<text class="kpi-num xd-num">{{warehouseAvailableQtyText}}</text>
|
||||
</view>
|
||||
<view class="kpi-divider"></view>
|
||||
<view class="kpi-cell">
|
||||
<text class="kpi-label">可用货值</text>
|
||||
<text class="kpi-num xd-num">¥{{warehouseAvailableValueText}}</text>
|
||||
</view>
|
||||
</view>
|
||||
<view wx:if="{{showModuleTitleBar}}" class="delivery-progress-card module-title-card">
|
||||
<text class="module-title-text">{{homeModuleTitle}}</text>
|
||||
</view>
|
||||
@@ -263,7 +280,7 @@
|
||||
</view>
|
||||
</view>
|
||||
<view
|
||||
wx:if="{{!needLogin && (kpiVisible || showPurchaseProgress || showPreparationProgress || showOrderProgress || showAdminPrepProgress || showPrepAmendProgress || showInspectionProgress || showProcessingProgress || showPickingProgress || showDeliveryProgress || showModuleTitleBar || gridModules.length)}}"
|
||||
wx:if="{{!needLogin && (kpiVisible || showPurchaseProgress || showPreparationProgress || showOrderProgress || showAdminPrepProgress || showPrepAmendProgress || showInspectionProgress || showProcessingProgress || showPickingProgress || showDeliveryProgress || showWarehouseStats || showModuleTitleBar || gridModules.length)}}"
|
||||
class="home-top-dock-spacer"
|
||||
style="height: {{homeTopDockHeightPx}}px;"
|
||||
/>
|
||||
@@ -369,6 +386,12 @@
|
||||
bind:badgechange="onProcessingBadgeChange"
|
||||
bind:tabchange="onProcessingTabChange"
|
||||
/>
|
||||
<warehouse-panel
|
||||
wx:if="{{activeHomeModuleId === 'warehouse'}}"
|
||||
id="warehouseHomePanel"
|
||||
embedded="{{true}}"
|
||||
bind:statschange="onWarehouseStatsChange"
|
||||
/>
|
||||
<picking-panel
|
||||
wx:if="{{activeHomeModuleId === 'picking'}}"
|
||||
id="pickingHomePanel"
|
||||
|
||||
@@ -225,6 +225,20 @@
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
/* 仓库管理统计卡:可用货值会比较长,数字单行不换行,溢出才截断 */
|
||||
.warehouse-stats-card .kpi-cell {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.warehouse-stats-card .kpi-num {
|
||||
font-size: 30rpx;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.kpi-label {
|
||||
font-size: 18rpx;
|
||||
opacity: 0.9;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 仓库管理:页面只做薄壳,界面与逻辑都在 `components/warehouse-panel`(首页一级 Tab 内嵌同一套)。
|
||||
*/
|
||||
Page({
|
||||
onPullDownRefresh() {
|
||||
const panel = this.selectComponent('#warehousePanel');
|
||||
if (panel && panel.reload) {
|
||||
panel.reload().then(() => wx.stopPullDownRefresh());
|
||||
return;
|
||||
}
|
||||
wx.stopPullDownRefresh();
|
||||
},
|
||||
|
||||
onReachBottom() {
|
||||
const panel = this.selectComponent('#warehousePanel');
|
||||
if (panel && panel.onReachBottom) panel.onReachBottom();
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"navigationBarTitleText": "仓库管理",
|
||||
"navigationBarBackgroundColor": "#047857",
|
||||
"navigationBarTextStyle": "white",
|
||||
"backgroundColor": "#f3faf6",
|
||||
"enablePullDownRefresh": true,
|
||||
"usingComponents": {
|
||||
"warehouse-panel": "/components/warehouse-panel/index"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
<view class="page">
|
||||
<warehouse-panel id="warehousePanel" />
|
||||
</view>
|
||||
@@ -0,0 +1,6 @@
|
||||
.page {
|
||||
min-height: 100vh;
|
||||
padding: 24rpx;
|
||||
box-sizing: border-box;
|
||||
background: #f8fafc;
|
||||
}
|
||||
@@ -581,6 +581,79 @@ function analyzeInspectionQuality(payload) {
|
||||
});
|
||||
}
|
||||
|
||||
// ── 仓库管理(2026-10-23):库存批次 / 批次报告 / 改价改量,与 Web 同一套 service ──
|
||||
function fetchInventoryBatches(params = {}) {
|
||||
const parts = [];
|
||||
if (params.page) parts.push(`page=${encodeURIComponent(params.page)}`);
|
||||
if (params.page_size) parts.push(`page_size=${encodeURIComponent(params.page_size)}`);
|
||||
if (params.search) parts.push(`search=${encodeURIComponent(params.search)}`);
|
||||
if (params.only_available) parts.push('only_available=true');
|
||||
if (params.without_cost) parts.push('without_cost=true');
|
||||
const qs = parts.length ? `?${parts.join('&')}` : '';
|
||||
return request(`/mobile/inventory/batches${qs}`);
|
||||
}
|
||||
|
||||
function fetchInventoryBatchReports(inventoryId) {
|
||||
return request(`/mobile/inventory/batches/${encodeURIComponent(inventoryId)}/reports`);
|
||||
}
|
||||
|
||||
function uploadInventoryBatchReports(inventoryId, payload = {}) {
|
||||
return request(`/mobile/inventory/batches/${encodeURIComponent(inventoryId)}/reports`, {
|
||||
method: 'POST',
|
||||
data: {
|
||||
files: payload.files || [],
|
||||
report_type: payload.report_type || undefined,
|
||||
report_no: payload.report_no || undefined,
|
||||
},
|
||||
timeout: 120000,
|
||||
});
|
||||
}
|
||||
|
||||
/** 批量上传报告:上传 + 解析,返回候选批次(与 Web 页级「上传报告」同一 service) */
|
||||
function parseInventoryBatchReports(payload = {}) {
|
||||
return request('/mobile/inventory/batch-reports/parse', {
|
||||
method: 'POST',
|
||||
data: {
|
||||
files: payload.files || [],
|
||||
report_type: payload.report_type || undefined,
|
||||
report_no: payload.report_no || undefined,
|
||||
},
|
||||
timeout: 120000,
|
||||
});
|
||||
}
|
||||
|
||||
/** 确认报告要绑定到哪些入库批次 */
|
||||
function confirmInventoryBatchReportMatches(reportId, matches) {
|
||||
return request(
|
||||
`/mobile/inventory/batch-reports/${encodeURIComponent(reportId)}/confirm`,
|
||||
{
|
||||
method: 'POST',
|
||||
data: { matches: Array.isArray(matches) ? matches : [] },
|
||||
timeout: 60000,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function deleteInventoryBatchReport(reportId) {
|
||||
return request(`/mobile/inventory/batch-reports/${encodeURIComponent(reportId)}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
}
|
||||
|
||||
function updateInventoryBatchCostPrice(inventoryId, costPrice) {
|
||||
return request(`/mobile/inventory/batches/${encodeURIComponent(inventoryId)}/cost-price`, {
|
||||
method: 'POST',
|
||||
data: { cost_price: costPrice },
|
||||
});
|
||||
}
|
||||
|
||||
function updateInventoryBatchAvailableQty(inventoryId, availableQty) {
|
||||
return request(`/mobile/inventory/batches/${encodeURIComponent(inventoryId)}/available-qty`, {
|
||||
method: 'POST',
|
||||
data: { available_qty: availableQty },
|
||||
});
|
||||
}
|
||||
|
||||
function fetchStockInboundCategories() {
|
||||
return request('/mobile/inventory/categories');
|
||||
}
|
||||
@@ -1409,6 +1482,15 @@ module.exports = {
|
||||
recognizeStockInboundCatalog,
|
||||
fetchStockInboundSkuSimilar,
|
||||
fetchStockInboundSkuOptions,
|
||||
// 仓库管理(小程序)
|
||||
fetchInventoryBatches,
|
||||
fetchInventoryBatchReports,
|
||||
uploadInventoryBatchReports,
|
||||
parseInventoryBatchReports,
|
||||
confirmInventoryBatchReportMatches,
|
||||
deleteInventoryBatchReport,
|
||||
updateInventoryBatchCostPrice,
|
||||
updateInventoryBatchAvailableQty,
|
||||
createStockInboundProduct,
|
||||
submitStockInbound,
|
||||
recognizeStockInboundLines,
|
||||
|
||||
@@ -31,6 +31,41 @@ function requireMobileRole(expectedRole, options = {}) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 小程序「仓库管理」(2026-10-23):默认给仓管,其他角色在 Web「角色权限」勾 `warehouse_manage` 后同样可用。
|
||||
* 判定口径 = 角色命中(warehouse;inspector 为历史角色码)**或** 会话权限含 `warehouse_manage`。
|
||||
*/
|
||||
function hasWarehouseModuleAccess(session) {
|
||||
const role = String((session && session.role_type) || '');
|
||||
if (role === 'warehouse' || role === 'inspector') return true;
|
||||
const perms = Array.isArray(session && session.permissions) ? session.permissions : [];
|
||||
return perms.includes('warehouse_manage');
|
||||
}
|
||||
|
||||
/** 仓库管理页专用:无 token 去登录,无权限弹提示并返回首页 */
|
||||
function requireWarehouseModuleRole() {
|
||||
const session = getSession();
|
||||
if (!session?.access_token) {
|
||||
wx.navigateTo({
|
||||
url: '/pages/login/login',
|
||||
fail: () => wx.reLaunch({ url: '/pages/login/login' }),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
if (hasWarehouseModuleAccess(session)) return true;
|
||||
wx.showModal({
|
||||
title: '无权访问',
|
||||
content: '当前账号未开通「仓库管理」权限,请联系管理员在「角色权限」中勾选',
|
||||
showCancel: false,
|
||||
success: () => {
|
||||
wx.navigateBack({
|
||||
fail: () => goHome(),
|
||||
});
|
||||
},
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
function normalizeAvailableRoles(session) {
|
||||
return (session?.available_roles || [])
|
||||
.map((item) => (typeof item === 'string' ? item : item && item.role_type))
|
||||
@@ -147,6 +182,8 @@ async function ensureRoleThenNavigate(targetRoles, url, options = {}) {
|
||||
|
||||
module.exports = {
|
||||
requireMobileRole,
|
||||
hasWarehouseModuleAccess,
|
||||
requireWarehouseModuleRole,
|
||||
ensureMobileRole,
|
||||
ensureRoleThenNavigate,
|
||||
pickSwitchRole,
|
||||
|
||||
@@ -163,7 +163,8 @@ export const supplierModule: BusinessModuleDescriptor = {
|
||||
export const inventoryModule: BusinessModuleDescriptor = {
|
||||
id: 'inventory',
|
||||
name: '库存',
|
||||
permissions: ['inventory_manage'],
|
||||
// warehouse_manage = 小程序「仓库管理」入口(不映射 Web 菜单,2026-10-23)
|
||||
permissions: ['inventory_manage', 'warehouse_manage'],
|
||||
// 本模块同时挂载 /inventory/* 与 /trace/*(商品溯源在前端也归属 inventory 模块的 menuKeys),
|
||||
// 但主前缀应为本模块的主路由 /inventory —— 原值 '/trace' 是溯源路由,属填错。
|
||||
workflowApiPrefix: '/inventory',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Router, Response } from 'express';
|
||||
import { authMiddleware, type AuthRequest } from '../../middleware/auth';
|
||||
import { loadTenantContext } from '../../services/tenantScope';
|
||||
import { requireStockInboundRole } from './mobileShared';
|
||||
import { requireStockInboundRole, requireWarehouseManageAccess } from './mobileShared';
|
||||
import { pool } from '../../db';
|
||||
import { recognizeCatalogForInbound } from '../../services/weighStationService';
|
||||
import {
|
||||
@@ -15,7 +15,17 @@ import {
|
||||
listSimilarSkusForInbound,
|
||||
} from '../../services/skuProvisioningService';
|
||||
import { inboundFromWeigh, normalizeArchive } from '../../services/stockInboundService';
|
||||
import { parseBatchReportForInbound } from '../../services/inventoryBatchReportService';
|
||||
import {
|
||||
confirmInventoryBatchReportMatches,
|
||||
createInventoryBatchReports,
|
||||
createInventoryBatchReportsForInventory,
|
||||
deleteInventoryBatchReport,
|
||||
listReportsForInventory,
|
||||
parseBatchReportForInbound,
|
||||
} from '../../services/inventoryBatchReportService';
|
||||
import { listInventoryForManagement } from '../../services/inventoryQueryService';
|
||||
import { updateInventoryBatchAttributes } from '../../services/inventoryBatchEditService';
|
||||
import { adjustInventoryAvailableQty } from '../../services/inventoryAdjustService';
|
||||
import { createQuickCatalogCategory } from '../../services/categoryCatalogService';
|
||||
|
||||
const router = Router();
|
||||
@@ -301,4 +311,245 @@ router.post('/inventory/stock-in-batch', authMiddleware, async (req: AuthRequest
|
||||
}
|
||||
});
|
||||
|
||||
/** 小程序「仓库管理」列表行:只透出移动端需要的字段(与 Web 库存管理同一份 service 结果) */
|
||||
function mapMobileBatchRow(row: Record<string, unknown>) {
|
||||
return {
|
||||
id: String(row.id || ''),
|
||||
sku_code: String(row.sku_code || ''),
|
||||
sku_name: String(row.sku_name || row.sku_code || ''),
|
||||
category_name: row.category_name ? String(row.category_name) : '',
|
||||
batch_no: String(row.batch_no || ''),
|
||||
available_qty: Number(row.available_qty) || 0,
|
||||
cost_price: row.cost_price == null ? null : Number(row.cost_price),
|
||||
storage_zone: row.storage_zone ? String(row.storage_zone) : '',
|
||||
batch_report_count: Number(row.batch_report_count) || 0,
|
||||
production_date: row.production_date ? String(row.production_date) : null,
|
||||
expiry_date: row.expiry_date ? String(row.expiry_date) : null,
|
||||
// 入库时间 = 该批次最早一次入库流水(与 Web 库存列表同一字段、同一表达式)
|
||||
inbound_at: row.inbound_at ? String(row.inbound_at) : null,
|
||||
};
|
||||
}
|
||||
|
||||
function readBranch(ctx: { branchCode?: string | null } | null, req: AuthRequest): string {
|
||||
return String(ctx?.branchCode || req.body?.operating_branch_code || req.query?.operating_branch_code || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 小程序「仓库管理」:库存批次列表(2026-10-23 开发者:与 Web 库存管理效果一致)。
|
||||
* 与 Web 共用 `listInventoryForManagement` —— 只多一个入口,不改任何口径/写路径。
|
||||
*/
|
||||
router.get('/inventory/batches', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
await requireWarehouseManageAccess(req);
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
const operating =
|
||||
typeof req.query?.operating_branch_code === 'string' ? req.query.operating_branch_code : null;
|
||||
const data = await listInventoryForManagement(ctx, operating, {
|
||||
page: Number(req.query?.page) || 1,
|
||||
pageSize: Number(req.query?.page_size) || 20,
|
||||
search: typeof req.query?.search === 'string' ? req.query.search : null,
|
||||
onlyAvailable: req.query?.only_available === 'true' || req.query?.only_available === '1',
|
||||
withoutCost: req.query?.without_cost === 'true' || req.query?.without_cost === '1',
|
||||
sortField: 'expiry_date',
|
||||
sortOrder: 'asc',
|
||||
});
|
||||
const rows = (data.rows || []).map(mapMobileBatchRow);
|
||||
return res.json({ data: rows, total: data.total, zones: data.zones, stats: data.stats });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '加载库存批次失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** 某批次已绑定的报告(小程序列表行内查看/删除) */
|
||||
router.get('/inventory/batches/:inventoryId/reports', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
await requireWarehouseManageAccess(req);
|
||||
const data = await listReportsForInventory({ inventoryId: String(req.params.inventoryId || '') });
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '加载批次报告失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 批量上传报告(2026-10-23 与 Web 对齐):**先上传 + 解析 → 返回候选批次 → 人工确认**。
|
||||
* 与 Web 页级「上传报告」同一个 service(`createInventoryBatchReports`),不新写匹配逻辑。
|
||||
*/
|
||||
router.post('/inventory/batch-reports/parse', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
await requireWarehouseManageAccess(req);
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
const branchCode = readBranch(ctx, req);
|
||||
const files = Array.isArray(req.body?.files)
|
||||
? req.body.files.map((f: unknown) => String(f || '').trim()).filter(Boolean)
|
||||
: [];
|
||||
const reports = await createInventoryBatchReports({
|
||||
files,
|
||||
branchCode,
|
||||
uploadedBy: req.userId || null,
|
||||
reportNo: req.body?.report_no ? String(req.body.report_no) : null,
|
||||
reportType: req.body?.report_type ? String(req.body.report_type) : null,
|
||||
});
|
||||
// 只透出移动端要展示的字段,避免整包转大对象
|
||||
const data = (reports || []).map((report) => ({
|
||||
id: report.id,
|
||||
report_no: report.report_no,
|
||||
report_type: report.report_type,
|
||||
uploaded_at: report.uploaded_at,
|
||||
ai_parsed: report.ai_parsed,
|
||||
matches: (report.matches || []).map((match) => ({
|
||||
product_name: match.product_name,
|
||||
status: match.status,
|
||||
candidates: (match.candidates || []).map((candidate) => ({
|
||||
inventory_id: candidate.inventory_id,
|
||||
sku_code: candidate.sku_code,
|
||||
sku_name: candidate.sku_name,
|
||||
batch_no: candidate.batch_no,
|
||||
available_qty: candidate.available_qty,
|
||||
unit: candidate.unit,
|
||||
production_date: candidate.production_date,
|
||||
match_kind: candidate.match_kind,
|
||||
})),
|
||||
})),
|
||||
}));
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '解析报告失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** 确认报告要绑定到哪些入库批次(与 Web 同一个 `confirmInventoryBatchReportMatches`) */
|
||||
router.post(
|
||||
'/inventory/batch-reports/:reportId/confirm',
|
||||
authMiddleware,
|
||||
async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
await requireWarehouseManageAccess(req);
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
const matches = Array.isArray(req.body?.matches)
|
||||
? req.body.matches
|
||||
.map((row: any) => ({
|
||||
inventoryId: String(row?.inventory_id || '').trim(),
|
||||
productName: row?.product_name ? String(row.product_name) : null,
|
||||
}))
|
||||
.filter((row: { inventoryId: string }) => Boolean(row.inventoryId))
|
||||
: [];
|
||||
const data = await confirmInventoryBatchReportMatches({
|
||||
reportId: String(req.params.reportId || ''),
|
||||
branchCode: readBranch(ctx, req),
|
||||
operatorId: req.userId || null,
|
||||
matches,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '确认匹配失败',
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* 批量上传:一个批次一次调用;小程序端对每个选中批次各调一次(同一组文件路径复用)。
|
||||
* 与 Web「修改」弹窗里的按批次直传是同一个 service(`createInventoryBatchReportsForInventory`)。
|
||||
*/
|
||||
router.post('/inventory/batches/:inventoryId/reports', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
await requireWarehouseManageAccess(req);
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
const branchCode = readBranch(ctx, req);
|
||||
const files = Array.isArray(req.body?.files)
|
||||
? req.body.files.map((f: unknown) => String(f || '').trim()).filter(Boolean)
|
||||
: [];
|
||||
const data = await createInventoryBatchReportsForInventory({
|
||||
inventoryId: String(req.params.inventoryId || ''),
|
||||
files,
|
||||
branchCode,
|
||||
reportType: req.body?.report_type ? String(req.body.report_type) : null,
|
||||
reportNo: req.body?.report_no ? String(req.body.report_no) : null,
|
||||
uploadedBy: req.userId || null,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '上传批次报告失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** 删除报告(行内删除):与 Web 同一个 service,撤下主系统报告的入队逻辑照旧 */
|
||||
router.delete('/inventory/batch-reports/:reportId', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
await requireWarehouseManageAccess(req);
|
||||
const data = await deleteInventoryBatchReport({
|
||||
reportId: String(req.params.reportId || ''),
|
||||
operatorId: req.userId || null,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '删除报告失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** 行内改成本价(批次级):与 Web 库存管理「修改」同一个 service,服务端会照常重算未结算订单 */
|
||||
router.post('/inventory/batches/:inventoryId/cost-price', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
await requireWarehouseManageAccess(req);
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
const raw = req.body?.cost_price;
|
||||
const costPrice = raw === '' || raw === null || raw === undefined ? null : Number(raw);
|
||||
if (costPrice != null && (!Number.isFinite(costPrice) || costPrice < 0)) {
|
||||
return res.status(400).json({ error: 'invalid_cost', error_description: '成本价须为不小于 0 的数字' });
|
||||
}
|
||||
const data = await updateInventoryBatchAttributes({
|
||||
inventoryId: String(req.params.inventoryId || ''),
|
||||
branchCode: readBranch(ctx, req),
|
||||
operatorId: req.userId || null,
|
||||
remark: '',
|
||||
costPrice,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '修改成本价失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** 行内改可用数量(**本批次**):与 Web 同一个 service(双日志 + 审计口径不变) */
|
||||
router.post('/inventory/batches/:inventoryId/available-qty', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
await requireWarehouseManageAccess(req);
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
const data = await adjustInventoryAvailableQty({
|
||||
inventoryId: String(req.params.inventoryId || ''),
|
||||
availableQty: Number(req.body?.available_qty),
|
||||
remark: '',
|
||||
branchCode: readBranch(ctx, req),
|
||||
operatorId: req.userId || null,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '调整可用数量失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -610,6 +610,27 @@ export async function requireStockInboundRole(req: AuthRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 小程序「仓库管理」(2026-10-23):库存批次查看 / 报告批量上传 / 改成本价与可用数量。
|
||||
* 放行口径 = 角色命中(仓管、历史验收员码、管理员)**或** 持有 `warehouse_manage`
|
||||
* (其他角色在「角色权限」勾选后即可用);`inventory_manage` 等同放行,与 Web 库存管理一致。
|
||||
*/
|
||||
export async function requireWarehouseManageAccess(req: AuthRequest) {
|
||||
if (!req.userId) throw Object.assign(new Error('未登录'), { status: 401, code: 'unauthorized' });
|
||||
const roles = await getUserRoleSet(req.userId);
|
||||
if (
|
||||
roles.has('super_admin') ||
|
||||
roles.has('admin') ||
|
||||
roles.has('warehouse') ||
|
||||
roles.has('inspector')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const perms = await getUserPermissionSet(req.userId);
|
||||
if (perms.has('warehouse_manage') || perms.has('inventory_manage')) return;
|
||||
throw Object.assign(new Error('无仓库管理权限'), { status: 403, code: 'forbidden' });
|
||||
}
|
||||
|
||||
export function requireOrderManageRole(req: AuthRequest) {
|
||||
requireMobileRoles(req, ['admin', 'operator']);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 小程序「仓库管理」后端契约(2026-10-23 开发者):
|
||||
* 「仓库管理放的就是和 web 的效果类似……小程序上就好进行批量上传」
|
||||
* 「不影响 web……执行函数肯定是一样的,就是接口入口不一样而已」。
|
||||
*
|
||||
* 约束:
|
||||
* · 新入口必须是**移动端薄路由 + 复用 Web 同一批 service**(不放宽 Web 路由权限);
|
||||
* · 鉴权 = 角色命中(仓管/管理员)**或** 持 `warehouse_manage`(其他角色勾选后可用);
|
||||
* · 不改任何写路径口径(报告绑定/删除、成本价与可用数量调整都走原 service)。
|
||||
*/
|
||||
const routes = readFileSync(
|
||||
new URL('../src/routes/mobile/mobileInventoryRoutes.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const shared = readFileSync(new URL('../src/routes/mobile/mobileShared.ts', import.meta.url), 'utf8');
|
||||
const modules = readFileSync(new URL('../src/modules/businessModules.ts', import.meta.url), 'utf8');
|
||||
const migration = readFileSync(
|
||||
new URL('../../migrations/20261082_warehouse_manage_permission.sql', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
describe('小程序仓库管理 · 移动端路由', () => {
|
||||
it('新增 6 条薄路由(列表 / 报告查传删 / 成本价 / 可用数量)', () => {
|
||||
expect(routes).toContain("router.get('/inventory/batches'");
|
||||
expect(routes).toContain("router.get('/inventory/batches/:inventoryId/reports'");
|
||||
expect(routes).toContain("router.post('/inventory/batches/:inventoryId/reports'");
|
||||
expect(routes).toContain("router.delete('/inventory/batch-reports/:reportId'");
|
||||
expect(routes).toContain("router.post('/inventory/batches/:inventoryId/cost-price'");
|
||||
expect(routes).toContain("router.post('/inventory/batches/:inventoryId/available-qty'");
|
||||
});
|
||||
it('批量上传与 Web 同流程:上传解析 → 返回候选 → 人工确认', () => {
|
||||
expect(routes).toContain('createInventoryBatchReports({');
|
||||
expect(routes).toContain('confirmInventoryBatchReportMatches({');
|
||||
// 解析结果只透出移动端要用的字段(候选批次)
|
||||
expect(routes).toContain('matches: (report.matches || []).map((match) => ({');
|
||||
expect(routes).toContain('candidates: (match.candidates || []).map((candidate) => ({');
|
||||
// 两条新路由都挂仓库管理守卫
|
||||
for (const marker of [
|
||||
"router.post('/inventory/batch-reports/parse'",
|
||||
"'/inventory/batch-reports/:reportId/confirm',",
|
||||
]) {
|
||||
const start = routes.indexOf(marker);
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
const sliced = routes.slice(start, start + 600);
|
||||
expect(sliced).toContain('await requireWarehouseManageAccess(req);');
|
||||
}
|
||||
});
|
||||
|
||||
it('复用 Web 同一批 service(不新写查询/写入逻辑)', () => {
|
||||
expect(routes).toContain('listInventoryForManagement(');
|
||||
expect(routes).toContain('createInventoryBatchReportsForInventory(');
|
||||
expect(routes).toContain('listReportsForInventory(');
|
||||
expect(routes).toContain('deleteInventoryBatchReport(');
|
||||
expect(routes).toContain('updateInventoryBatchAttributes(');
|
||||
expect(routes).toContain('adjustInventoryAvailableQty(');
|
||||
// 不得在小程序侧自造 SQL(薄路由只做映射与鉴权)
|
||||
expect(routes).not.toContain('INSERT INTO inventory');
|
||||
expect(routes).not.toContain('UPDATE inventory');
|
||||
});
|
||||
|
||||
it('每条新路由都挂仓库管理守卫', () => {
|
||||
const indexes = [
|
||||
"router.get('/inventory/batches'",
|
||||
"router.get('/inventory/batches/:inventoryId/reports'",
|
||||
"router.post('/inventory/batches/:inventoryId/reports'",
|
||||
"router.delete('/inventory/batch-reports/:reportId'",
|
||||
"router.post('/inventory/batches/:inventoryId/cost-price'",
|
||||
"router.post('/inventory/batches/:inventoryId/available-qty'",
|
||||
];
|
||||
for (const marker of indexes) {
|
||||
const start = routes.indexOf(marker);
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
const block = routes.slice(start, start + 600);
|
||||
expect(block).toContain('await requireWarehouseManageAccess(req);');
|
||||
}
|
||||
});
|
||||
|
||||
it('列表透出入库时间(与 Web 同一字段 inbound_at)', () => {
|
||||
expect(routes).toContain('inbound_at: row.inbound_at ? String(row.inbound_at) : null');
|
||||
});
|
||||
|
||||
it('列表分页:默认每页 20,服务端 LIMIT/OFFSET(不一口气拉全量)', () => {
|
||||
expect(routes).toContain('pageSize: Number(req.query?.page_size) || 20');
|
||||
const service = readFileSync(
|
||||
new URL('../src/services/inventoryQueryService.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
expect(service).toContain('clampManagementPage(');
|
||||
expect(service).toContain('LIMIT $$');
|
||||
expect(service).toContain('OFFSET $$');
|
||||
});
|
||||
|
||||
it('可用数量按本批次 inventoryId 调整(不是 SKU 级)', () => {
|
||||
const start = routes.indexOf("router.post('/inventory/batches/:inventoryId/available-qty'");
|
||||
const block = routes.slice(start);
|
||||
expect(block).toContain('inventoryId: String(req.params.inventoryId');
|
||||
expect(block).not.toContain('sku_code');
|
||||
});
|
||||
});
|
||||
|
||||
describe('小程序仓库管理 · 鉴权', () => {
|
||||
it('角色命中或持 warehouse_manage 即放行(含 inventory_manage 兼容)', () => {
|
||||
expect(shared).toContain('export async function requireWarehouseManageAccess');
|
||||
const start = shared.indexOf('export async function requireWarehouseManageAccess');
|
||||
const block = shared.slice(start, start + 900);
|
||||
expect(block).toContain("roles.has('warehouse')");
|
||||
expect(block).toContain("perms.has('warehouse_manage')");
|
||||
expect(block).toContain("perms.has('inventory_manage')");
|
||||
expect(block).toContain("code: 'forbidden'");
|
||||
});
|
||||
|
||||
it('权限码进模块注册表(库存模块),迁移里默认授予仓管', () => {
|
||||
expect(modules).toContain("permissions: ['inventory_manage', 'warehouse_manage']");
|
||||
expect(migration).toContain("'warehouse_manage'");
|
||||
expect(migration).toContain("('warehouse')");
|
||||
});
|
||||
});
|
||||
@@ -179,6 +179,13 @@ export const PERMISSION_CATALOG: Record<string, PermissionCatalogEntry> = {
|
||||
},
|
||||
|
||||
inventory_manage: { kind: 'menu', menus: menusByPermission('inventory_manage') },
|
||||
// 2026-10-23:小程序「仓库管理」入口(库存批次 + 批量上传报告 + 改成本价/可用数量)。
|
||||
// 只映射小程序能力,**不映射 Web 菜单**,所以勾它不会打开 Web 的「库存」页面。
|
||||
warehouse_manage: {
|
||||
kind: 'menu',
|
||||
mobile: ['小程序仓库管理'],
|
||||
note: '小程序「仓库管理」:库存批次查看、批量上传/删除批次报告、改成本价与可用数量。默认授予仓管。',
|
||||
},
|
||||
product_trace: {
|
||||
kind: 'menu',
|
||||
menus: menusByPermission('product_trace'),
|
||||
|
||||
Reference in New Issue
Block a user