const { ROLE_LABELS } = require('../../utils/constants'); const { getSession, setSession, clearSession } = require('../../utils/auth'); const { fetchMobileRoles, fetchMe, fetchOrdersManagement } = require('../../utils/request'); const { buildUnionModules, findModuleById, normalizeRoleList, resolveDisplayMobileRoles, filterModulesForHomeGrid, isHomeWorkspaceModule, } = require('../../modules/registry'); const { buildMergedFeaturePatch, mergeRoleFeatureBlobs } = require('../../utils/roleFeatures'); const { ensureRoleThenNavigate, ensureMobileRole } = require('../../utils/roleGuard'); const badgeCenter = require('../../utils/badgeCenter'); const { goLogin } = require('../../utils/nav'); const { clearUnitDictionaryCache } = require('../../utils/units'); /** 记住首页当前工作模块,避免拍照/选图触发 onShow 后回退到订单入库 */ const HOME_MODULE_STORAGE_KEY = 'mp_home_active_module'; const MODULE_GRID_TITLE_SIZE = '26rpx'; function pxToRpx(px, windowWidth) { const w = Number(windowWidth) || 375; return `${Math.round((Number(px) * 750) / w)}rpx`; } /** 宫格标题固定 26rpx;窄屏只收缝和边距 */ function computeModuleGridMetrics() { try { const info = wx.getSystemInfoSync() || {}; const w = Number(info.windowWidth) || 375; const sidePx = w < 340 ? 6 : 8; const gapPx = w < 330 ? 4 : w < 360 ? 6 : 8; return { moduleGridSize: MODULE_GRID_TITLE_SIZE, moduleGridGap: pxToRpx(gapPx, w), moduleGridPad: pxToRpx(gapPx / 2, w), moduleGridSide: pxToRpx(sidePx, w), }; } catch (error) { return { moduleGridSize: MODULE_GRID_TITLE_SIZE, moduleGridGap: '8rpx', moduleGridPad: '4rpx', moduleGridSide: '8rpx', }; } } function readStoredHomeModule() { try { const raw = String(wx.getStorageSync(HOME_MODULE_STORAGE_KEY) || '').trim(); if ( raw === 'purchaser-order-add' || raw === 'purchaser-order-remove' || raw === 'purchaser-order-items' ) { return 'purchase'; } return raw; } catch { return ''; } } function persistHomeModule(id) { const next = String(id || '').trim(); if (!next) return; try { wx.setStorageSync(HOME_MODULE_STORAGE_KEY, next); } catch { // 存储不可用时忽略,下次仍走默认模块 } } function clearStoredHomeModule() { try { wx.removeStorageSync(HOME_MODULE_STORAGE_KEY); } catch { // 存储不可用时忽略 } } function orderProgressPatch(pending, processing, completed) { const pendingCount = Number(pending) || 0; const processingCount = Number(processing) || 0; const completedCount = Number(completed) || 0; return { orderPendingCount: pendingCount, orderProcessingCount: processingCount, orderCompletedCount: completedCount, }; } /** 首页顶栏互斥:按优先级只保留第一条,避免管理员并集角色叠出两张绿卡 */ function pickExclusiveHomeProgress(flags) { const keys = [ 'showOrderProgress', 'showAdminPrepProgress', 'showPrepAmendProgress', 'showPurchaseProgress', 'showDeliveryProgress', 'showPreparationProgress', 'showInspectionProgress', 'showProcessingProgress', 'showPickingProgress', ]; const picked = keys.find((key) => flags[key]); const next = {}; keys.forEach((key) => { next[key] = key === picked; }); return next; } function pickDefaultHomeModule(workspaceIds, workspaceMods) { const order = [ 'purchase', 'admin-purchase', 'delivery', 'preparation', 'order-manage', 'admin-preparations', 'inspection', 'stock-inbound', 'processing', 'picking', ]; const hit = order.find((id) => workspaceIds.has(id)); return hit || (workspaceMods[0] && workspaceMods[0].id) || 'purchase'; } /** 工作台模块图标(Vant icon name + 色调),仅影响展示 */ const MODULE_ICONS = { 'order-manage': { name: 'orders-o', tone: 'emerald' }, 'admin-preparations': { name: 'bag-o', tone: 'teal' }, 'admin-purchase': { name: 'shopping-cart-o', tone: 'orange' }, delivery: { name: 'logistics', tone: 'sky' }, picking: { name: 'completed', tone: 'lime' }, purchase: { name: 'shopping-cart-o', tone: 'orange' }, 'supplier-status': { name: 'chart-trending-o', tone: 'violet' }, 'prep-amend-review': { name: 'edit', tone: 'amber' }, preparation: { name: 'shop-o', tone: 'lime' }, 'prep-history': { name: 'records', tone: 'teal' }, 'prep-price-amend': { name: 'edit', tone: 'amber' }, bid: { name: 'gold-coin-o', tone: 'amber' }, 'quality-reports': { name: 'description', tone: 'sky' }, inspection: { name: 'photo-o', tone: 'teal' }, 'stock-inbound': { name: 'add-square', tone: 'lime' }, processing: { name: 'cluster-o', tone: 'orange' }, 'order-entry': { name: 'phone-o', tone: 'violet' }, 'cost-management': { name: 'balance-list-o', tone: 'rose' }, 'product-trace': { name: 'search', tone: 'sky' }, }; function mapRoleOptions(roles) { return (roles || []).map((item) => { if (typeof item === 'string') { return { value: item, label: ROLE_LABELS[item] || item }; } return { value: item.role_type, label: item.label || ROLE_LABELS[item.role_type] || item.role_type, }; }); } function buildSupplierCategoryDisplay(profile, roleType) { if (roleType !== 'supplier') { return { supplierCategoryLabels: [] }; } const raw = profile?.supplier?.categories; const list = Array.isArray(raw) ? raw : []; const supplierCategoryLabels = list .map((row) => { const name = String(row?.category_name || row?.category_code || '').trim(); if (!name) return null; return { name, primary: row?.is_primary === true || row?.is_primary === 1 || row?.is_primary === 't', }; }) .filter(Boolean); return { supplierCategoryLabels }; } function buildLoggedOutHomeData() { return { needLogin: true, roleType: '', roleLabel: '工作台', availableRoles: [], availableRoleValues: [], canSwitchRole: false, menuModules: [], gridModules: [], listModules: [], showHomeWorkspace: false, showPurchaseProgress: false, showDeliveryProgress: false, showPreparationProgress: false, supplierCategoryLabels: [], showInspectionProgress: false, showProcessingProgress: false, showPickingProgress: false, showOrderProgress: false, showAdminPrepProgress: false, showPrepAmendProgress: false, showAdminPurchaseProgress: false, showModuleTitleBar: false, homeTopDockHeightPx: 0, homeModuleTitle: '', activeHomeModuleId: 'purchase', purchasePendingBadgeCount: 0, adminPurchasePendingBadgeCount: 0, prepHeroDate: '今天', prepCompletedCount: 0, prepTotalCount: 0, deliveryTaskCount: 0, deliveryTaskLabel: '今日任务', deliveryDeliveringCount: 0, deliveryCompletedCount: 0, deliveryPendingBadgeCount: 0, inspectionPendingCount: 0, inspectionDoneCount: 0, inspectionPhotoRequiredCount: 0, inspectionPendingBadgeCount: 0, inspectionSourceFilter: 'all', processingTabFilter: 'work', pickingTaskCount: 0, pickingPickedCount: 0, pickingPendingCount: 0, pickingPendingTaskCount: 0, orderPendingCount: 0, orderProcessingCount: 0, orderCompletedCount: 0, orderPickingPendingCount: 0, orderStatusGroup: 'pending', adminPrepPendingCount: 0, adminPrepPreparingCount: 0, adminPrepCompletedCount: 0, adminPrepExceptionCount: 0, adminPrepPendingBadgeCount: 0, adminPrepStatusFilter: '10', adminPurchaseStatusGroup: 'pending', adminPurchasePendingCount: 0, adminPurchaseCompletedCount: 0, preparationTaskCount: 0, prepPriceAmendCount: 0, prepAmendPendingCount: 0, prepAmendReviewedTodayCount: 0, prepAmendStatusGroup: 'pending', bidPendingQuoteCount: 0, qualityReportPendingCount: 0, processingPendingCount: 0, supplierStatusEnabled: false, photoInspectionEnabled: false, pickingEnabled: false, deliveryEnabled: true, bidEnabled: false, oneClickSupplierInspectionEnabled: false, permissions: [], isSuperAdmin: false, kpiVisible: false, }; } function buildKpi(data) { const roles = data.availableRoleValues || []; const roleSet = new Set(roles.length ? roles : [data.roleType].filter(Boolean)); // 采购员 / 配送员 / 供应商 / 仓管首页:顶部留给角色进度条,其它 KPI 隐藏 if ( (roleSet.has('purchaser') || roleSet.has('delivery') || roleSet.has('supplier') || roleSet.has('warehouse') || roleSet.has('inspector') || roleSet.has('picker')) && data.showHomeWorkspace ) { return { kpiVisible: false, kpiMainLabel: '', kpiMainValue: 0, kpiMainUnit: '', kpiSide1Label: '', kpiSide1Value: '', kpiSide2Label: '', kpiSide2Value: '', }; } if (roleSet.has('supplier') && data.preparationTaskCount > 0) { return { kpiVisible: true, kpiMainLabel: '今日待供货', kpiMainValue: data.preparationTaskCount || 0, kpiMainUnit: '项', kpiSide1Label: '', kpiSide1Value: '', kpiSide2Label: '', kpiSide2Value: '', }; } if ( (roleSet.has('admin') || roleSet.has('operator')) && data.prepAmendPendingCount > 0 ) { return { kpiVisible: true, kpiMainLabel: '改价待审', kpiMainValue: data.prepAmendPendingCount || 0, kpiMainUnit: '项', kpiSide1Label: '', kpiSide1Value: '', kpiSide2Label: '', kpiSide2Value: '', }; } return { kpiVisible: false, kpiMainLabel: '', kpiMainValue: 0, kpiMainUnit: '', kpiSide1Label: '', kpiSide1Value: '', kpiSide2Label: '', kpiSide2Value: '', }; } function decorateModules(mods, activeId) { return (mods || []).map((mod) => { const meta = MODULE_ICONS[mod.id] || { name: 'label-o', tone: 'emerald' }; return { ...mod, icon: meta.name, iconTone: meta.tone, isActive: Boolean(activeId && mod.id === activeId), }; }); } function sessionDisplay(session) { return resolveDisplayMobileRoles(session?.available_roles, session?.role_type, session); } Page({ data: { ...buildLoggedOutHomeData(), navigatingModule: false, ...computeModuleGridMetrics(), }, applyModuleGridMetrics() { this.setData(computeModuleGridMetrics(), () => this.syncHomeTopDockSpacer()); }, syncHomeTopDockSpacer() { const run = () => { wx.createSelectorQuery() .in(this) .select('#homeTopDock') .boundingClientRect((rect) => { const h = rect && Number(rect.height) > 0 ? Math.ceil(rect.height) : 0; if (h !== Number(this.data.homeTopDockHeightPx || 0)) { this.setData({ homeTopDockHeightPx: h }); } }) .exec(); }; if (typeof wx.nextTick === 'function') wx.nextTick(run); else setTimeout(run, 16); }, onLoad(options) { this.applyModuleGridMetrics(); const moduleId = String(options?.module || '').trim(); if (moduleId) this._pendingHomeModuleId = moduleId; }, onResize() { this.applyModuleGridMetrics(); }, onShow() { this._sessionNotifyDone = false; const session = getSession(); if (!session?.access_token) { clearStoredHomeModule(); this.setData(buildLoggedOutHomeData()); return; } this.setData({ needLogin: false }); this.refreshFromSession(session); this.refreshSupplierProfileIfNeeded(session); this.loadRoleOptions(session).finally(() => { this.refreshHomeBadges(); this.loadOrderProgressStats(); }); }, async refreshSupplierProfileIfNeeded(session) { const roleType = sessionDisplay(session).roleType; if (roleType !== 'supplier') return; try { const me = await fetchMe(); if (!me?.profile) return; const nextSession = { ...(getSession() || session), profile: me.profile, role_type: me.role_type || session.role_type, }; if (Array.isArray(me.available_roles)) { nextSession.available_roles = normalizeRoleList( me.available_roles, nextSession.role_type ); } setSession(nextSession); this.refreshFromSession(nextSession); } catch { // 保留本地 session 档案 } }, refreshHomeBadges(modules) { let list = Array.isArray(modules) && modules.length ? modules : this.data.menuModules || []; if (!list.length) { const roleValues = this.data.availableRoleValues || this.data.availableRoles; list = buildUnionModules(this.data, roleValues); } badgeCenter.refreshBadges(this, list.filter((mod) => mod && mod.badgeKey)); }, refreshBadgeForModule(moduleId) { const id = String(moduleId || '').trim(); if (!id || id === 'quality-reports') return; const mod = findModuleById(id) || (this.data.menuModules || []).find((item) => item.id === id); if (!mod) return; badgeCenter.refreshBadgeForModule(this, mod); }, onPurchaseProgressChange(e) { const detail = e.detail || {}; this.setData({ purchaseHeroDate: detail.heroDate || '今天', purchaseCompletedCount: Number(detail.completedCount) || 0, purchaseTotalCount: Number(detail.totalCount) || 0, }); }, onPurchaseBadgeChange(e) { const badgeKey = String((e && e.detail && e.detail.badgeKey) || 'purchasePendingBadgeCount'); const count = Number(e && e.detail && e.detail.count); if (Number.isFinite(count)) { badgeCenter.setBadgeCount(this, badgeKey, count); return; } this.refreshBadgeForModule( badgeKey === 'adminPurchasePendingBadgeCount' ? 'admin-purchase' : 'purchase' ); }, onDeliveryProgressChange(e) { const detail = e.detail || {}; this.setData({ deliveryTaskCount: Number(detail.taskCount) || 0, deliveryTaskLabel: detail.taskLabel || '今日任务', deliveryDeliveringCount: Number(detail.deliveringCount) || 0, deliveryCompletedCount: Number(detail.completedCount) || 0, }); }, onDeliveryBadgeChange() { this.refreshBadgeForModule('delivery'); }, onPreparationProgressChange(e) { const detail = e.detail || {}; this.setData({ prepHeroDate: detail.heroDate || '今天', prepCompletedCount: Number(detail.completedCount) || 0, prepTotalCount: Number(detail.totalCount) || 0, }); }, onPreparationBadgeChange(e) { const key = String((e && e.detail && e.detail.badgeKey) || 'preparationTaskCount'); if (key !== 'preparationTaskCount') return; const count = Number(e && e.detail && e.detail.count); if (Number.isFinite(count)) { badgeCenter.setBadgeCount(this, 'preparationTaskCount', count); return; } this.refreshBadgeForModule('preparation'); }, onPrepPriceAmendBadgeChange(e) { const key = String((e && e.detail && e.detail.badgeKey) || 'prepPriceAmendCount'); if (key !== 'prepPriceAmendCount') return; const count = Number(e && e.detail && e.detail.count); if (Number.isFinite(count)) { badgeCenter.setBadgeCount(this, 'prepPriceAmendCount', count); return; } this.refreshBadgeForModule('prep-price-amend'); }, onBidBadgeChange(e) { const count = Number(e && e.detail && e.detail.count); if (Number.isFinite(count)) { badgeCenter.setBadgeCount(this, 'bidPendingQuoteCount', count); return; } this.refreshBadgeForModule('bid'); }, onPrepAmendBadgeChange(e) { const count = Number(e && e.detail && e.detail.count); if (Number.isFinite(count)) { badgeCenter.setBadgeCount(this, 'prepAmendPendingCount', count); this.setData({ prepAmendPendingCount: count }); return; } this.refreshBadgeForModule('prep-amend-review'); }, onPrepAmendProgressChange(e) { const detail = e.detail || {}; this.setData({ prepAmendPendingCount: Number(detail.pendingCount) || 0, prepAmendReviewedTodayCount: Number(detail.reviewedCount) || 0, }); }, onPrepAmendStatusTap(e) { const value = String(e.currentTarget.dataset.value || 'pending'); if (value !== 'pending' && value !== 'reviewed') return; const alreadyOn = this.data.activeHomeModuleId === 'prep-amend-review'; if (alreadyOn && this.data.prepAmendStatusGroup === value) return; this.setData({ prepAmendStatusGroup: value }); if (!alreadyOn) { this.activateHomeModule({ id: 'prep-amend-review' }); } }, onOrderManageBadgeChange(e) { const count = Number(e && e.detail && e.detail.count); if (Number.isFinite(count)) { badgeCenter.setBadgeCount(this, 'orderPickingPendingCount', count); return; } this.refreshBadgeForModule('order-manage'); }, onInspectionProgressChange(e) { const detail = e.detail || {}; this.setData({ inspectionPendingCount: Number(detail.pendingCount) || 0, inspectionDoneCount: Number(detail.doneCount) || 0, inspectionPhotoRequiredCount: Number(detail.photoRequiredCount) || 0, }); }, onInspectionBadgeChange(e) { const count = Number(e && e.detail && e.detail.count); if (Number.isFinite(count)) { badgeCenter.setBadgeCount(this, 'inspectionPendingBadgeCount', count); return; } this.refreshBadgeForModule('inspection'); }, onQualityReportsBadgeChange() {}, onInspectionSourceTap(e) { const value = String(e.currentTarget.dataset.value || 'all'); const alreadyOnInspection = this.data.activeHomeModuleId === 'inspection'; if (alreadyOnInspection && this.data.inspectionSourceFilter === value) return; this.setData({ inspectionSourceFilter: value }); if (!alreadyOnInspection) { this.activateHomeModule({ id: 'inspection' }); } }, onProcessingTabTap(e) { const value = String(e.currentTarget.dataset.value || 'work'); const alreadyOnProcessing = this.data.activeHomeModuleId === 'processing'; if (alreadyOnProcessing && this.data.processingTabFilter === value) return; this.setData({ processingTabFilter: value }); if (!alreadyOnProcessing) { this.activateHomeModule({ id: 'processing' }); } }, onProcessingTabChange(e) { const tab = String(e.detail?.tab || '').trim(); if (!tab || tab === this.data.processingTabFilter) return; this.setData({ processingTabFilter: tab }); }, onPickingProgressChange(e) { const detail = e.detail || {}; this.setData({ pickingTaskCount: Number(detail.taskCount) || 0, pickingPickedCount: Number(detail.pickedCount) || 0, pickingPendingCount: Number(detail.pendingCount) || 0, }); }, onPickingBadgeChange(e) { const count = Number(e && e.detail && e.detail.count); if (Number.isFinite(count)) { badgeCenter.setBadgeCount(this, 'pickingPendingTaskCount', count); return; } this.refreshBadgeForModule('picking'); }, onOrderProgressChange(e) { const detail = e.detail || {}; this.setData( orderProgressPatch(detail.pendingCount, detail.processingCount, detail.completedCount) ); }, onOrderStatusTap(e) { const value = String(e.currentTarget.dataset.value || 'pending'); const alreadyOnOrders = this.data.activeHomeModuleId === 'order-manage'; if (alreadyOnOrders && this.data.orderStatusGroup === value) return; this.setData({ orderStatusGroup: value }); if (!alreadyOnOrders) { this.activateHomeModule({ id: 'order-manage' }); } }, onAdminPrepProgressChange(e) { const detail = e.detail || {}; this.setData({ adminPrepPendingCount: Number(detail.pendingCount) || 0, adminPrepPreparingCount: Number(detail.preparingCount) || 0, adminPrepCompletedCount: Number(detail.completedCount) || 0, adminPrepExceptionCount: Number(detail.exceptionCount) || 0, }); }, onAdminPrepBadgeChange(e) { const count = Number(e && e.detail && e.detail.count); if (Number.isFinite(count)) { badgeCenter.setBadgeCount(this, 'adminPrepPendingBadgeCount', count); return; } this.refreshBadgeForModule('admin-preparations'); }, onAdminPrepStatusTap(e) { const value = String(e.currentTarget.dataset.value || '10'); const alreadyOnPrep = this.data.activeHomeModuleId === 'admin-preparations'; if (alreadyOnPrep && this.data.adminPrepStatusFilter === value) return; this.setData({ adminPrepStatusFilter: value }); if (!alreadyOnPrep) { this.activateHomeModule({ id: 'admin-preparations' }); } }, refreshMenuModules() { const roleValues = this.data.availableRoleValues || this.data.availableRoles; 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) ); const showHomeWorkspace = workspaceMods.length > 0; const workspaceIds = new Set(workspaceMods.map((mod) => mod.id)); const roleSet = new Set(normalizeRoleList(roleValues, this.data.roleType)); let activeHomeModuleId = this.data.activeHomeModuleId; if (showHomeWorkspace) { if (!activeHomeModuleId || !workspaceIds.has(activeHomeModuleId)) { const stored = readStoredHomeModule(); activeHomeModuleId = stored && workspaceIds.has(stored) ? stored : pickDefaultHomeModule(workspaceIds, workspaceMods); } persistHomeModule(activeHomeModuleId); } const showOrderProgress = showHomeWorkspace && activeHomeModuleId === 'order-manage' && (roleSet.has('admin') || roleSet.has('operator')) && workspaceIds.has('order-manage'); const showAdminPrepProgress = showHomeWorkspace && activeHomeModuleId === 'admin-preparations' && (roleSet.has('admin') || roleSet.has('operator')) && workspaceIds.has('admin-preparations'); const showPrepAmendProgress = showHomeWorkspace && activeHomeModuleId === 'prep-amend-review' && workspaceIds.has('prep-amend-review'); const roleProgressLocked = showOrderProgress || showAdminPrepProgress; const exclusive = pickExclusiveHomeProgress({ showOrderProgress, showAdminPrepProgress, showPrepAmendProgress, showPurchaseProgress: !roleProgressLocked && showHomeWorkspace && ((roleSet.has('purchaser') && workspaceIds.has('purchase') && activeHomeModuleId === 'purchase') || ((roleSet.has('admin') || roleSet.has('operator')) && workspaceIds.has('admin-purchase') && activeHomeModuleId === 'admin-purchase')), showDeliveryProgress: !roleProgressLocked && showHomeWorkspace && roleSet.has('delivery') && workspaceIds.has('delivery') && activeHomeModuleId === 'delivery', showPreparationProgress: !roleProgressLocked && showHomeWorkspace && roleSet.has('supplier') && workspaceIds.has('preparation') && activeHomeModuleId === 'preparation', showInspectionProgress: showHomeWorkspace && activeHomeModuleId === 'inspection' && workspaceIds.has('inspection'), showProcessingProgress: showHomeWorkspace && activeHomeModuleId === 'processing' && workspaceIds.has('processing'), showPickingProgress: showHomeWorkspace && activeHomeModuleId === 'picking' && roleSet.has('picker') && workspaceIds.has('picking'), }); const showPurchaseProgress = exclusive.showPurchaseProgress; const showDeliveryProgress = exclusive.showDeliveryProgress; const showPreparationProgress = exclusive.showPreparationProgress; const showInspectionProgress = exclusive.showInspectionProgress; const showProcessingProgress = exclusive.showProcessingProgress; const showPickingProgress = exclusive.showPickingProgress; const showOrderProgressExclusive = exclusive.showOrderProgress; const showAdminPrepProgressExclusive = exclusive.showAdminPrepProgress; const showPrepAmendProgressExclusive = exclusive.showPrepAmendProgress; const hasDedicatedProgress = showOrderProgressExclusive || showAdminPrepProgressExclusive || showPrepAmendProgressExclusive || showPurchaseProgress || showDeliveryProgress || showPreparationProgress || showInspectionProgress || showProcessingProgress || showPickingProgress; const activeWorkspaceMod = workspaceMods.find((mod) => mod.id === activeHomeModuleId); const homeModuleTitle = String(activeWorkspaceMod?.title || '').trim(); const showModuleTitleBar = Boolean(showHomeWorkspace && !hasDedicatedProgress && homeModuleTitle); const menuModules = decorateModules(menuBase, ''); const gridModules = decorateModules( gridBase, showHomeWorkspace ? activeHomeModuleId : '' ); this.setData({ menuModules, gridModules, listModules: [], showHomeWorkspace, showPurchaseProgress, showDeliveryProgress, showPreparationProgress, showInspectionProgress, showProcessingProgress, showPickingProgress, showOrderProgress: showOrderProgressExclusive, showAdminPrepProgress: showAdminPrepProgressExclusive, showPrepAmendProgress: showPrepAmendProgressExclusive, showAdminPurchaseProgress: false, showModuleTitleBar, homeModuleTitle, activeHomeModuleId, ...(showPurchaseProgress ? {} : { purchaseHeroDate: '今天', purchaseCompletedCount: 0, purchaseTotalCount: 0, }), ...(showDeliveryProgress ? {} : { deliveryTaskCount: 0, deliveryTaskLabel: '今日任务', deliveryDeliveringCount: 0, deliveryCompletedCount: 0, }), ...(showPreparationProgress ? {} : { prepHeroDate: '今天', prepCompletedCount: 0, prepTotalCount: 0, }), ...(showInspectionProgress ? {} : { inspectionPendingCount: 0, inspectionDoneCount: 0, inspectionPhotoRequiredCount: 0, }), ...(showPickingProgress ? {} : { pickingTaskCount: 0, pickingPickedCount: 0, pickingPendingCount: 0, }), ...(showOrderProgressExclusive ? {} : orderProgressPatch(0, 0, 0)), ...(showAdminPrepProgressExclusive ? {} : { adminPrepPendingCount: 0, adminPrepPreparingCount: 0, adminPrepCompletedCount: 0, adminPrepExceptionCount: 0, }), ...(showPrepAmendProgressExclusive ? {} : { prepAmendReviewedTodayCount: 0, }), ...(hasDedicatedProgress || showModuleTitleBar ? { kpiVisible: false, kpiMainLabel: '', kpiMainValue: 0, kpiMainUnit: '', kpiSide1Label: '', kpiSide1Value: '', kpiSide2Label: '', kpiSide2Value: '', } : buildKpi({ ...this.data, menuModules, showHomeWorkspace })), }, () => this.syncHomeTopDockSpacer()); }, refreshFromSession(session) { const display = sessionDisplay(session); const roleType = display.roleType; const roleValues = display.roles; const roleOptions = mapRoleOptions(roleValues); const patch = { roleType, roleLabel: ROLE_LABELS[roleType] || '移动端', ...buildSupplierCategoryDisplay(session.profile || {}, roleType), availableRoles: roleOptions, availableRoleValues: roleValues, canSwitchRole: false, permissions: session.permissions || [], isSuperAdmin: session.is_super_admin === true || session.isSuperAdmin === true, ...buildMergedFeaturePatch(roleValues, session, roleType), }; this.setData(patch, () => { this.refreshMenuModules(); const alreadyNotified = this._sessionNotifyDone; this._sessionNotifyDone = true; if (this._pendingHomeModuleId) { this.applyPendingHomeModule(); return; } if (alreadyNotified) return; this.notifyHomePanelShow(this.data.activeHomeModuleId); }); }, applyPendingHomeModule() { const id = String(this._pendingHomeModuleId || '').trim(); if (!id) return; this._pendingHomeModuleId = ''; const target = findModuleById(id) || (this.data.menuModules || []).find((mod) => mod.id === id); if (!target) return; if ( this.data.showHomeWorkspace && isHomeWorkspaceModule(target, this.data.availableRoleValues, this.data.roleType) ) { this.activateHomeModule(target); return; } this.navigateToModule(target); }, async loadOrderProgressStats() { const currentRole = String((getSession() || {}).role_type || '').trim(); if (currentRole !== 'admin' && currentRole !== 'operator') { this.setData(orderProgressPatch(0, 0, 0)); return; } try { const result = await fetchOrdersManagement({ page: 1, page_size: 1, date_range: 'today', date_field: 'delivery_date', }); const stats = result.stats || {}; this.setData( orderProgressPatch(stats.pending, stats.processing, stats.completed) ); } catch { this.setData(orderProgressPatch(0, 0, 0)); } }, onProcessingBadgeChange(e) { const count = Number(e && e.detail && e.detail.count); if (Number.isFinite(count)) { badgeCenter.setBadgeCount(this, 'processingPendingCount', count); return; } this.refreshBadgeForModule('processing'); }, async loadRoleOptions(session) { let roles = session.available_roles; try { const result = await fetchMobileRoles(); roles = result.available_roles != null ? result.available_roles : roles || []; const storedRoleValues = normalizeRoleList(roles, result.current_role || session.role_type); const nextSession = mergeRoleFeatureBlobs( { ...getSession(), available_roles: storedRoleValues, permissions: result.permissions || [], is_super_admin: result.is_super_admin === true, }, result ); if (result.current_role) { nextSession.role_type = result.current_role; } setSession(nextSession); const display = sessionDisplay(nextSession); const roleValues = display.roles; const roleOptions = mapRoleOptions(roleValues); const featurePatch = buildMergedFeaturePatch(roleValues, nextSession, display.roleType); this.setData( { roleType: display.roleType, roleLabel: ROLE_LABELS[display.roleType] || '移动端', availableRoles: roleOptions, availableRoleValues: roleValues, canSwitchRole: false, permissions: result.permissions || [], isSuperAdmin: result.is_super_admin === true, ...featurePatch, }, () => { this.refreshFromSession(nextSession); this.refreshMenuModules(); } ); } catch { const stored = getSession() || {}; const display = sessionDisplay({ ...stored, available_roles: roles, role_type: stored.role_type || this.data.roleType, }); const roleValues = display.roles; const roleOptions = mapRoleOptions(roleValues); this.setData( { roleType: display.roleType, roleLabel: ROLE_LABELS[display.roleType] || '移动端', availableRoles: roleOptions, availableRoleValues: roleValues, canSwitchRole: false, ...buildMergedFeaturePatch(roleValues, stored, display.roleType), }, () => this.refreshMenuModules() ); } }, async navigateToModule(mod) { if (!mod) return; if (this.data.navigatingModule) return; const target = findModuleById(mod.id) || mod; const roles = target.roleOnly ? [target.roleOnly] : target.roles || []; const url = target.page; if (!url || !roles.length) { wx.showToast({ title: '入口不可用', icon: 'none' }); return; } this.setData({ navigatingModule: true }); try { const ensureOpts = target.id === 'picking' ? { prefer: 'picker' } : {}; await ensureRoleThenNavigate(roles, url, ensureOpts); } finally { this.setData({ navigatingModule: false }); } }, async activateHomeModule(mod) { if (!mod) return; if (this.data.navigatingModule) return; const target = findModuleById(mod.id) || mod; const roles = target.roleOnly ? [target.roleOnly] : target.roles || []; if (!roles.length) { wx.showToast({ title: '入口不可用', icon: 'none' }); return; } if (this.data.activeHomeModuleId === target.id) { this.notifyHomePanelShow(target.id); this.refreshBadgeForModule(target.id); return; } this.setData({ navigatingModule: true }); try { const ensureOpts = target.id === 'picking' ? { prefer: 'picker' } : {}; const ok = await ensureMobileRole(roles, ensureOpts); if (!ok) return; persistHomeModule(target.id); const sessionNow = getSession() || {}; const display = sessionDisplay(sessionNow); const patch = { activeHomeModuleId: target.id, ...buildMergedFeaturePatch(display.roles, sessionNow, display.roleType), }; if (target.id === 'order-manage' && !this.data.orderStatusGroup) { patch.orderStatusGroup = 'pending'; } if (target.id === 'admin-preparations' && !this.data.adminPrepStatusFilter) { patch.adminPrepStatusFilter = '10'; } if (target.id === 'prep-amend-review' && !this.data.prepAmendStatusGroup) { patch.prepAmendStatusGroup = 'pending'; } this.setData(patch, () => { this.refreshMenuModules(); this.notifyHomePanelShow(target.id); this.refreshBadgeForModule(target.id); if (target.id === 'order-manage') this.loadOrderProgressStats(); }); } finally { this.setData({ navigatingModule: false }); } }, 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]; if (!selector) return; wx.nextTick(() => { const tryNotify = (left) => { const panel = this.selectComponent(selector); if (panel && typeof panel.onPanelShow === 'function') { panel.onPanelShow(); return; } if (left > 0) { setTimeout(() => tryNotify(left - 1), 50); } }; tryNotify(8); }); }, async onModuleTap(e) { if (this.data.needLogin) { this.goLogin(); return; } const id = e.currentTarget.dataset.id; const page = e.currentTarget.dataset.page; const mod = findModuleById(id) || (this.data.menuModules || []).find((item) => item.id === id || item.page === page); if ( this.data.showHomeWorkspace && isHomeWorkspaceModule(mod, this.data.availableRoleValues, this.data.roleType) ) { await this.activateHomeModule(mod); return; } await this.navigateToModule(mod); }, onLogout() { clearUnitDictionaryCache(); clearStoredHomeModule(); clearSession(); this.setData(buildLoggedOutHomeData()); wx.showToast({ title: '已退出', icon: 'success', duration: 1200 }); setTimeout(() => { goLogin(); }, 300); }, goLogin() { wx.navigateTo({ url: '/pages/login/login' }); }, });