dashboard.vue 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. <template>
  2. <div class="wms-home">
  3. <main class="main">
  4. <home-overview v-if="view === 'home'" :summary="summary" :options="options" :warehouse-id="warehouseId" :updated-at="updatedAt" :error="error" @open="open" @refresh="refresh" @business="business" @warehouse="setWarehouse" @navigate="navigate" />
  5. <section v-else-if="businessComponent" class="view active dashboard-business"><nav class="crumb"><a href="#" class="back" @click.prevent="open('home')">‹ 返回首页</a><span>仓储管理系统</span> / <b>{{ businessTitle }}</b></nav><div class="drill-head"><h2>{{ businessTitle }}</h2></div><div v-if="receiveQueue.length" class="receive-progress">批量收货:正在核对第 {{ preparedReceipts.length + 1 }} / {{ receiveQueue.length }} 单。请核对仓库、产品明细及包装后确认。<el-button @click="cancelReceive">取消批量收货</el-button></div><div v-if="!receiveQueue.length && preparedReceipts.length" class="receive-progress">有 {{ preparedReceipts.length }} 单待重试。<el-button :loading="receiving" @click="submitReceipts">重试收货</el-button></div><component :is="businessComponent" :key="view + ($route.query.inId || '')" :batch-prepare="receiveQueue.length > 0" @batch-receive="startReceive" @prepared="prepareReceipt" @cancelled="cancelReceive" /></section>
  6. <dashboard-detail v-else :key="view" :view="view" :filters="filters" :options="options" :result="result" :summary="summary" :loading="loading" :error="error" :exporting="exporting" :stagnant-days="stagnantDays" @back="open('home')" @navigate="open" @search="search" @retry="loadDetail" @export="exportRows" @business="business" />
  7. </main>
  8. <dashboard-actions ref="actions" :options="options" :filters="filters" :alert-rows="alertRows" @success="refresh" @business="business" />
  9. <!-- 首屏遮罩:看板要等 home-options + 13 项首页指标请求都回来才展示结果,之前是空卡片逐步填充,
  10. 用户看到的是「没有数据」。这里盖住内容,加载完再显示;失败也会撤掉遮罩,露出 HomeOverview 的错误条与「重试」。
  11. 只管首屏一次,不是每次 refresh 都盖(15 分钟定时刷新和筛选项切换不该闪遮罩)。 -->
  12. <div v-if="homeLoading && view === 'home'" class="home-loading" role="status" aria-live="polite">
  13. <i class="home-loading__spinner" aria-hidden="true"></i>
  14. <span>正在加载首页数据…</span>
  15. </div>
  16. </div>
  17. </template>
  18. <script>
  19. import HomeOverview from './components/HomeOverview.vue';
  20. import DashboardDetail from './detail.vue';
  21. import DashboardActions from './components/DashboardActions.vue';
  22. import { homeOptions, homeSummaryMetric, homeDetail, dashboardAction } from '@/api/warehouseManagement/dashboard';
  23. import { getResourcesTree } from '@/api/layout';
  24. import { getCurrentUser } from '@/utils/token-util';
  25. import { monthRange, cleanQuery, findPortalEntry, homeLog, homeWarn } from './dashboard-utils';
  26. import { screens } from './dashboard-screens';
  27. const businessViews = {
  28. addin: () => import('../stockManagement/add.vue'), addout: () => import('../outgoingManagement/add.vue'),
  29. ioapp: () => import('../inboundRequests/index.vue'), inapp: () => import('../warehouseApplication/index.vue')
  30. };
  31. const filterKeys = ['warehouseId','factoryId','categoryId','startTime','endTime','keyword','type','direction','stockBatchId','age','level','inspection','status','page'];
  32. const metricKeys = {
  33. B1: ['pendingInbound','overdueInbound'],
  34. B2: ['pendingOutbound','overdueOutbound'],
  35. B3: ['pendingInventory'],
  36. B4: ['pendingApproval','overdueApproval','approvalReason'],
  37. // C1/C2 都要带 ledgerInventoryReason:两张卡共用同一句台账口径说明,漏在任一组都会让另一组刷新后被清空。
  38. C1: ['inventoryQuantity','inventoryBatchCount','inventoryReason','weekOverWeekQuantity','comparisonReason','comparisonBaseAt','historyUnattributed','ledgerInventoryQuantity','ledgerInventoryReason'],
  39. C2: ['pricedValuation','unpricedBatchCount','valuationCoverage','inventoryValue','valuationReason','inventoryValueChangeRate','inventoryValueBase','inventoryValueComparisonReason','comparisonBaseAt','ledgerInventoryValue','ledgerInventoryReason'],
  40. C3: ['turnoverDays','turnoverAsOf','turnoverStatus','turnoverReason','turnoverChange','turnoverChangeReason','turnoverTargetDays','turnoverWarnDays'],
  41. C4: ['stagnantDays','stagnantRate','stagnantReason','stagnantLevel','stagnantBatchCount','stagnantKnownBatchCount','stagnantUnknownBatchCount','stagnantChange','stagnantChangeReason','stagnantBaseDate'],
  42. C6: ['qualityPassRate','qualityChange','qualityCoverage','qualityReason','qualityChangeReason','qualityInspectedCount','qualityPassedCount','qualityConcessionCount'],
  43. D1: ['trend','trendReason'],
  44. D2: ['categories','categoryReason'],
  45. E1: ['aging','agingReason','averageAgeDays','averageAgeChange','averageAgeChangeReason','ageCoverage'],
  46. E3: ['activities'],
  47. F1: ['alerts','alertCount','alertUnknownCount','alertGapAmount','alertGapAmountReason','alertWorkOrderCount','alertWorkOrderCountReason']
  48. };
  49. export default {
  50. name: 'WmsHome',
  51. components: { HomeOverview, DashboardDetail, DashboardActions },
  52. data() { return {
  53. view: 'home', warehouseId: '', filters: {}, homeFilters: null, options: {}, summary: {}, result: {}, updatedAt: '', error: '', loading: false, exporting: false, portalRoots: [], optionsLoaded: false, receiveQueue: [], preparedReceipts: [], receiving: false, homeLoading: true
  54. }; },
  55. computed: {
  56. // 呆滞阈值向下透传:优先用首页 C4 指标返回的 stagnantDays(不额外发请求),
  57. // 缺失/非正数时传 null,由 detail.vue 回落默认 180 天并在口径条标明是默认值,绝不把「后端没给」显示成仓库配置。
  58. // 字段名与后端契约保持一致(stagnantDays),避免排查时被误读成另一个概念。
  59. stagnantDays() {
  60. const days = this.summary && this.summary.stagnantDays;
  61. if (days == null || days === '') return null;
  62. const number = Number(days);
  63. return Number.isFinite(number) && number > 0 ? number : null;
  64. },
  65. // 预警行全集:超储行发起调拨时要从「缺口最大的缺料行」推目标仓库。
  66. // summary.alerts 只有 TOP5(口径契约第 6 条),拿它推会把第 6 名之后的缺料当成不存在;
  67. // 已经在 alerts 视图里时明细列表才是全集,优先用它,缺数据时再退回首页 TOP5。
  68. alertRows() {
  69. const records = this.view === 'alerts' && this.result && Array.isArray(this.result.records) ? this.result.records : null;
  70. if (records && records.length) return records;
  71. return Array.isArray(this.summary && this.summary.alerts) ? this.summary.alerts : [];
  72. },
  73. businessComponent() { return businessViews[this.view] || null; },
  74. businessTitle() { return { addin:'新增入库单',addout:'新增出库单',ioapp:'出入库申请',inapp:'入总库申请' }[this.view]; }
  75. },
  76. watch: { '$route.query': { deep: true, handler() { this.readRoute(); this.refresh(); } } },
  77. async created() {
  78. this.active = true; this.generation = 0; this.requests = {}; this.timers = [];
  79. // 看板打开期间给 body 打标:让业务页 filter 弹层(el-select/el-date-picker 默认挂 body、无 popper-class)走深色主题。
  80. // 用组件生命周期而非路由 query 判断:离开看板(跳转/页签/keep-alive 停用)必然走 deactivated/beforeDestroy,不会残留。
  81. document.body.classList.add('wms-dashboard-open');
  82. this.readRoute();
  83. await this.refresh();
  84. // 首屏数据(筛选项 + 汇总)已经落定或失败,撤掉遮罩;失败时由 HomeOverview 的错误条 + 重试接手。
  85. this.homeLoading = false;
  86. this.startTimers();
  87. },
  88. // 2026-10-30 恢复 body class(wms-dashboard-open):业务页弹层默认挂 body 又没有 popper-class,
  89. // 只能由 body 标记接管。与旧方案的区别:旧方案靠 $route.query.dashboard 判断会残留到下钻业务页;
  90. // 现在挂在组件生命周期上,离开看板必然走 deactivated/beforeDestroy,可靠摘除。
  91. activated() { document.body.classList.add('wms-dashboard-open'); const resumed = !this.active; this.active = true; this.startTimers(); if (resumed) this.refresh(); },
  92. deactivated() { document.body.classList.remove('wms-dashboard-open'); this.stop(); },
  93. beforeDestroy() { document.body.classList.remove('wms-dashboard-open'); this.stop(); },
  94. methods: {
  95. readRoute() {
  96. const query = this.$route.query;
  97. const previousWarehouseId = this.warehouseId;
  98. const knownView = screens[query.dashboardView] || businessViews[query.dashboardView] || query.dashboardView === 'home';
  99. this.view = knownView ? query.dashboardView : 'home';
  100. const blanks = { warehouseId:'', factoryId:'', categoryId:'', keyword:'', type:'', direction:'', stockBatchId:'', age:'', level:'', inspection:'', status:'' };
  101. this.filters = filterKeys.reduce((r,key) => { if (query[key] != null) r[key] = query[key]; return r; }, { ...blanks, ...monthRange(), page: 1 });
  102. this.warehouseId = this.filters.warehouseId || '';
  103. if (previousWarehouseId !== this.warehouseId) {
  104. this.summary = {}; this.updatedAt = ''; this.options = {}; this.optionsLoaded = false;
  105. }
  106. // 首页筛选快照只保留仓库:单位维度随后端契约一起删除,不再有默认单位兜底。
  107. if (this.view === 'home') this.homeFilters = { warehouseId: this.filters.warehouseId || '' };
  108. },
  109. route(view, filters, replace = false) {
  110. const query = cleanQuery({ ...filters, dashboard: '1', dashboardView: view });
  111. if (this.$route.query.dashboardView === view && JSON.stringify(query) === JSON.stringify(this.$route.query)) return;
  112. this.$router[replace ? 'replace' : 'push']({ path: this.$route.path, query }).catch((e) => { if (e.name !== 'NavigationDuplicated') this.$message.error(e.message); });
  113. },
  114. open(view, extra = {}) {
  115. // 台账首屏沿用首页仓库;分类下钻额外带 categoryLevelId。
  116. // path 保持 /warehouseManagement/stockLedger 不变(既有入口断言依赖它);cleanQuery 丢弃 null/'',
  117. // 没有 extra 时 query 是 {},与改动前的「只跳转不过滤」完全等价。
  118. // 顺手吞掉 NavigationDuplicated:重复点击「查看台账」不应该弹错误提示。
  119. if (view === 'stockLedger') return this.$router.push({ path: '/warehouseManagement/stockLedger', query: cleanQuery({ warehouseId: this.warehouseId, ...extra }) }).catch((e) => { if (e.name !== 'NavigationDuplicated') this.$message.error(e.message); });
  120. const base = view === 'home' ? (this.homeFilters || this.filters) : this.filters;
  121. const filters = { ...base, page: 1, ...extra };
  122. if (view !== this.view) ['stockBatchId','age','level','inspection','type','direction'].forEach((key) => { if (!(key in extra)) delete filters[key]; });
  123. if (view === 'ioapp' && !filters.direction) filters.direction = 'in';
  124. if (['ioapp','inapp'].includes(view)) {
  125. filters.status = Object.prototype.hasOwnProperty.call(extra,'status') ? extra.status : '0';
  126. delete filters.categoryId; Object.assign(filters,monthRange());
  127. }
  128. this.route(view, filters);
  129. },
  130. // 首页只按仓库筛选;仓库变更后 readRoute 清空旧仓库统计。
  131. setWarehouse(warehouseId) { this.route('home', { ...this.filters, warehouseId, page: 1 }); },
  132. search(filters) {
  133. const query = cleanQuery({ ...filters, dashboard: '1', dashboardView: this.view });
  134. if (this.$route.query.dashboardView === this.view && JSON.stringify(query) === JSON.stringify(this.$route.query)) return this.refresh();
  135. this.route(this.view, filters);
  136. },
  137. parameters(extra = {}) { return cleanQuery({ ...this.filters, ...extra }); },
  138. async refresh() {
  139. // 全量刷新入口:路由切换、手动重试、15 分钟定时器都会走到这里,先记录触发上下文。
  140. homeLog('refresh 触发整页刷新', { view: this.view, warehouseId: this.warehouseId });
  141. if (!this.active) return;
  142. this.generation++; this.requests = {}; this.error = ''; this.loading = false;
  143. const generation = this.generation;
  144. if (!this.optionsLoaded) {
  145. try {
  146. const options = await homeOptions({ warehouseId:this.warehouseId });
  147. if (!this.active || generation !== this.generation) return;
  148. this.options = options; this.optionsLoaded = true;
  149. } catch (e) {
  150. if (this.active && generation === this.generation) this.error = e.message || '筛选项加载失败,请重试';
  151. return;
  152. }
  153. }
  154. await Promise.allSettled([this.loadSummary(), this.businessComponent || this.view === 'home' ? Promise.resolve() : this.loadDetail()]);
  155. },
  156. async loadSummary() {
  157. const generation = this.generation; const seq = (this.requests.summary || 0) + 1; this.requests.summary = seq;
  158. const params = this.parameters();
  159. const queue = Object.keys(metricKeys).filter(metric => metric !== 'C6' || this.view === 'qc');
  160. const worker = async () => { while (queue.length) {
  161. const metric = queue.shift();
  162. const metricSeq = (this.requests[metric] || 0) + 1; this.requests[metric] = metricSeq;
  163. try {
  164. const data = await homeSummaryMetric(metric, params);
  165. if (!this.active || generation !== this.generation || seq !== this.requests.summary) return;
  166. if (metricSeq !== this.requests[metric]) continue;
  167. const patch = metricKeys[metric].reduce((acc, key) => { acc[key] = data && data[key] != null ? data[key] : null; return acc; }, {});
  168. if (patch.comparisonBaseAt == null) delete patch.comparisonBaseAt;
  169. this.summary = { ...this.summary, ...patch, capturedAt: data && data.capturedAt };
  170. this.updatedAt = new Date().toLocaleTimeString('zh-CN', { hour12: false });
  171. homeLog('首页指标请求成功', { metric });
  172. } catch (e) {
  173. homeWarn('首页指标请求失败', { metric, reason: e && e.message });
  174. if (this.active && generation === this.generation && seq === this.requests.summary && metricSeq === this.requests[metric])
  175. this.error = (this.error ? this.error + ';' : '') + metric + ':' + (e.message || '加载失败');
  176. }
  177. } };
  178. await Promise.allSettled(Array.from({ length: Math.min(4, queue.length) }, () => worker()));
  179. },
  180. async fetchDetail(filters = this.filters, page = filters.page || 1, limit = 20) {
  181. return homeDetail(cleanQuery({ ...filters, view: this.view, page, limit }));
  182. },
  183. async loadDetail() {
  184. const generation = this.generation; const seq = (this.requests.detail || 0) + 1; this.requests.detail = seq;
  185. this.loading = true; this.result = {};
  186. try { const data = await this.fetchDetail(); if (this.active && generation === this.generation && seq === this.requests.detail) this.result = data || {}; }
  187. catch (e) { if (this.active && generation === this.generation) this.error = e.message || '明细加载失败,请重试'; }
  188. finally { if (this.active && generation === this.generation && seq === this.requests.detail) this.loading = false; }
  189. },
  190. async refreshPart(metric) {
  191. if (!this.active || this.view !== 'home') return;
  192. const generation = this.generation; const seq = (this.requests[metric] || 0) + 1; this.requests[metric] = seq;
  193. const params = this.parameters(); const startedAt = Date.now();
  194. homeLog('refreshPart 请求开始', { metric, params });
  195. try {
  196. const data = await homeSummaryMetric(metric, params);
  197. const rows = metric === 'F1' ? data && data.alerts : data && data.activities;
  198. homeLog('refreshPart 请求成功', { metric, costMs: Date.now() - startedAt, rows: Array.isArray(rows) ? rows.length : 0 });
  199. if (!this.active || generation !== this.generation || seq !== this.requests[metric]) return;
  200. const patch = metricKeys[metric].reduce((acc, key) => { acc[key] = data && data[key] != null ? data[key] : null; return acc; }, {});
  201. patch[metric === 'F1' ? 'alertReason' : 'activityReason'] = null;
  202. this.summary = { ...this.summary, ...patch };
  203. } catch (e) {
  204. homeWarn('refreshPart 请求失败', { metric, costMs: Date.now() - startedAt, reason: e && e.message });
  205. if (this.active && generation === this.generation && seq === this.requests[metric]) this.$set(this.summary, metric === 'F1' ? 'alertReason' : 'activityReason', e.message || '刷新失败,请手动重试');
  206. }
  207. },
  208. startTimers() {
  209. if (!this.active || this.timers && this.timers.length) return;
  210. homeLog('startTimers 启动定时刷新', { pageRefreshMs: 15*60*1000, alertsMs: 5*60*1000, activitiesMs: 30*1000 });
  211. this.timers = [
  212. setInterval(() => { homeLog('15 分钟整页刷新触发', { at: new Date().toLocaleTimeString('zh-CN', { hour12: false }) }); this.refresh(); }, 15*60*1000),
  213. setInterval(() => this.refreshPart('F1'),5*60*1000),
  214. setInterval(() => this.refreshPart('E3'),30*1000)
  215. ];
  216. },
  217. stop() { this.active = false; this.generation++; (this.timers || []).forEach(clearInterval); this.timers = []; },
  218. async exportRows() {
  219. this.exporting = true; const generation = this.generation; const filters = { ...this.filters }; const view = this.view;
  220. try {
  221. const rows = []; let page = 1; let total;
  222. do { const data = await this.fetchDetail(filters,page++,200); if (!this.active || generation !== this.generation || view !== this.view) return; rows.push(...(data.records || [])); total = Number(data.total || 0); if (!(data.records || []).length) break; } while (rows.length < total);
  223. const XLSX = await import('xlsx'); const columns = screens[view].columns;
  224. const output = rows.map((row) => columns.reduce((r,c) => { r[c.name] = c.key.split('.').reduce((v,k) => v == null ? null : v[k],row); return r; },{}));
  225. const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook,XLSX.utils.json_to_sheet(output),'明细'); XLSX.writeFile(workbook,screens[view].title + '-' + new Date().toISOString().slice(0,10) + '.xlsx');
  226. } catch (e) { this.$message.error(e.message || '导出失败,请重试'); } finally { this.exporting = false; }
  227. },
  228. // 下钻到系统原有业务页(详情、批次)时只带目标页真正需要的参数:
  229. // 不再带 dashboard=1(该参数只服务看板自身的内部视图:tgTable 批量收货勾选、warehouseApplication 批量审批),
  230. // 也不再整包透传首页筛选(startTime/endTime/page/categoryId/warehouseId 详情页一个都不认,
  231. // 只会把 URL 撑长、让人误以为详情被筛过)。unknown/null 参数由 cleanQuery 丢弃,缺 planId 的旧链接
  232. // 仍由 PlanServiceImpl#getOrderInfoByPlanId 反查兼容。
  233. // 同时吞掉 NavigationDuplicated:重复点同一行不该弹错误提示。
  234. navigate(path, query = {}) { this.$router.push({ path, query: cleanQuery({ ...query }) }).catch((e) => { if (e.name !== 'NavigationDuplicated') this.$message.error(e.message); }); },
  235. async portal(predicate, query) {
  236. try {
  237. if (!this.portalRoots.length) { const user = getCurrentUser(); this.portalRoots = await getResourcesTree({ groupId:user.currentGroupId,roleId:user.currentRoleId }); }
  238. const path = findPortalEntry(this.portalRoots,predicate);
  239. if (!path) return this.$message.warning('当前账号未获得对应业务入口,请联系管理员配置菜单权限');
  240. const params = new URLSearchParams(cleanQuery(query)); window.history.pushState(null,'',path + (params.toString() ? '?' + params : ''));
  241. } catch (e) { this.$message.error(e.message || '授权入口加载失败'); }
  242. },
  243. business(kind,row) {
  244. // 待我审批下钻不再传 month:后端按全部未处理统计(当前经办人 + 入库/出库/调拨 + 授权仓库范围),
  245. // 前端再叠当月过滤会造成月份与卡片数字分叉。
  246. // dashboard:'1' 必须保留:目标页只有收到它才会切到仓储口径(warehouseScope=true),
  247. // 去掉就等于跳到一个未按仓储范围过滤的全量待办列表。
  248. if (kind === 'approval-todo') {
  249. return this.portal((n) => /bpm\/todo|流程待办/.test((n.component || '') + (n.title || n.name || '') + (n.path || '')),
  250. { dashboard: '1', warehouseId: this.warehouseId });
  251. }
  252. if (kind === 'todo' && row.type === 'inventory')
  253. return this.navigate('/warehouseManagement/stocktaking/work/details', { id: row.id, planId: row.planId });
  254. if (['purchase','threshold','disposal','disposal-list','finance','transfer'].includes(kind)) return this.$refs.actions.open(kind,row);
  255. if (kind === 'dead') return this.$refs.actions.open('disposal',row);
  256. // 预警行动作按状态分流:超储行的闭环是「发起调拨」(把超储量调到缺料仓库),不是补货也不是跳库存台账;
  257. // 缺料/偏低/未知行才走补货弹层,默认采购数量取该行缺口量 gapQuantity。
  258. // 原来超储行直接 open('stockLedger') 会把这一行的 gapQuantity/gapAmount/status 全丢掉,用户还得在台账里重新找行。
  259. if (kind === 'alerts') {
  260. const target = row && row.status === 'excess' ? 'transfer' : 'purchase';
  261. homeLog('alerts 行动作分流', { status:row && row.status, action:target, warehouseId:row && row.warehouseId, categoryId:row && row.categoryId, gapQuantity:row && row.gapQuantity, purchaseRequestCode:(row && row.purchaseRequestCode) || null });
  262. return this.$refs.actions.open(target,row);
  263. }
  264. // 打开采购需求:savedPurchase 是刚存下的需求(id 就是需求主键),而预警行只有后端台账回传的
  265. // purchaseRequestCode(business_code)。只带单号时不能拿 row.id(那是预警行主键)冒充 requirementId,
  266. // 否则会打开另一张需求单;此时只透传单号,让采购需求页按单号自行定位。
  267. if (kind === 'purchase-document') {
  268. const requirementId = row.purchaseRequestId || row.requirementId || (row.purchaseRequestCode ? '' : row.id);
  269. homeLog('打开采购需求', { requirementId:requirementId || null, purchaseRequestCode:row.purchaseRequestCode || null, hasId:!!requirementId });
  270. return this.portal((n) => /purchasingManage\/purchaseNeedManage/.test((n.component || '') + (n.path || '')), { requirementId, requirementCode:row.purchaseRequestCode || row.requirementCode, code:row.purchaseRequestCode, dashboard:'1' });
  271. }
  272. if (kind === 'qc') return this.portal((n) => /inspectionWork|检验工作台|质检报告/.test((n.component || '') + (n.title || n.name || '')), { stockBatchId:row.stockBatchId || row.id,systemBatchNo:row.systemBatchNo,warehouseId:row.warehouseId,dashboard:'1' });
  273. // 盘点工单详情同时要 planOrderId(=id) 与 planId:只带 id 时详情页拿不到计划信息(服务端虽能由工单反查,
  274. // 但 URL 与列表页入口不一致,排查时两套地址对不上)。planId 由首页 detail/recentActivities 的查询列下发。
  275. if (kind === 'io' && row.activityType === 'inventory') return this.navigate('/warehouseManagement/stocktaking/work/details',{ id:row.orderId, planId:row.planId });
  276. if (kind === 'io' && row.activityType === 'transfer') return this.open('io',{ warehouseId:row.warehouseId,keyword:row.orderNo });
  277. if (kind === 'io') return row.orderId ? this.navigate(String(row.direction) === '1' ? '/warehouseManagement/stockManagement/details' : '/warehouseManagement/outgoingManagement/details',{ id:row.orderId }) : this.$message.warning('该流水缺少来源单据身份,请先核实');
  278. if (kind === 'turnover') return this.open('stockLedger');
  279. if (['batch','age'].includes(kind)) return this.navigate('/warehouseManagement/stockLedger/batchDetails',{ id:row.categoryId,batchNo:row.batchNo,systemBatchNo:row.systemBatchNo,stockBatchId:row.stockBatchId || row.id,warehouseId:row.warehouseId });
  280. if (kind === 'disposal-document') return this.navigate(row.documentType === 'ALLOT' ? '/warehouseManagement/inventoryAllocation/details' : '/warehouseManagement/outgoingManagement/details',{ id:row.documentId });
  281. },
  282. async startReceive(rows) {
  283. if (this.receiving || this.receiveQueue.length) return;
  284. if (this.preparedReceipts.length) return this.$message.warning('请先重试未完成的收货');
  285. this.receiveQueue = rows.slice(); this.preparedReceipts = []; this.nextReceipt();
  286. },
  287. nextReceipt() {
  288. const row = this.receiveQueue[this.preparedReceipts.length];
  289. if (!row) return this.submitReceipts();
  290. this.route('addin',{ ...this.filters,code:row.code,inId:row.id,type:'1',sourceType:row.sourceType,name:'inboundRequests',batchReceive:'1' },true);
  291. },
  292. prepareReceipt(request) {
  293. if (!this.receiveQueue.length || this.receiving) return;
  294. const row = this.receiveQueue[this.preparedReceipts.length];
  295. // 路由切换完成前旧表单仍可能发出确认事件,不能准备到下一张申请。
  296. if (!row || String(this.$route.query.inId) !== String(row.id)) return;
  297. this.preparedReceipts.push({ requestKey:'wms-receive-' + row.id + '-' + Date.now(),request }); this.nextReceipt();
  298. },
  299. async cancelReceive() {
  300. try { await this.$confirm('取消本次批量收货?尚未提交的收货信息将清除。','取消确认'); this.receiveQueue = []; this.preparedReceipts = []; this.route('ioapp',{ ...this.filters,direction:'in',status:'0' },true); } catch (e) { /* 取消确认后继续核对。 */ }
  301. },
  302. async submitReceipts() {
  303. if (this.receiving || !this.preparedReceipts.length) return;
  304. this.receiving = true;
  305. try {
  306. await this.$confirm('已核对 ' + this.preparedReceipts.length + ' 单,确认保存并提交原审批或质检?','批量收货确认');
  307. const results = await dashboardAction('batch-receive',{ items:this.preparedReceipts });
  308. const succeeded = new Set(results.filter((r) => r.success).map((r) => String(r.key)));
  309. this.preparedReceipts = this.preparedReceipts.filter((r) => !succeeded.has(String(r.requestKey))); this.receiveQueue = [];
  310. this.route('ioapp',{ ...this.filters,direction:'in',status:'0' },true); this.$refs.actions.showResults(results,'成功表示已保存并提交原审批或质检;库存是否增加取决于原流程的执行结果。'); this.refresh();
  311. } catch (e) { if (e !== 'cancel' && e !== 'close') this.$message.error(e.message || '收货失败,保留原信息供重试'); this.receiveQueue = []; this.route('ioapp',{ ...this.filters,direction:'in',status:'0' },true); }
  312. finally { this.receiving = false; }
  313. }
  314. }
  315. };
  316. </script>
  317. <style lang="scss" src="./dashboard-theme.scss"></style>
  318. <style lang="scss" src="./dashboard-layout.scss"></style>