dashboard.vue 28 KB

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