Commit 3f9e150a by 张立顺

feat 精品和权益首页优化

1 parent e64cc2e3
Showing 105 changed files with 4597 additions and 134 deletions
name: tabIndex tests
on:
push:
paths:
- 'tabIndex/**'
- 'utils/**'
- 'package.json'
- '.github/workflows/tabindex-tests.yml'
pull_request:
paths:
- 'tabIndex/**'
- 'utils/**'
- 'package.json'
- '.github/workflows/tabindex-tests.yml'
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm run test:tabIndex
...@@ -19,7 +19,12 @@ Component({ ...@@ -19,7 +19,12 @@ Component({
} }
} }
}, },
scroll: Boolean scroll: Boolean,
/** 为 true 时 ready / page_show 触发的 setTab 不 emit click,避免子页首屏重复拉数 */
suppressInitialClick: {
type: Boolean,
value: false
}
}, },
/** /**
* 组件的初始数据 * 组件的初始数据
...@@ -29,12 +34,10 @@ Component({ ...@@ -29,12 +34,10 @@ Component({
}, },
lifetimes: { lifetimes: {
ready() { ready() {
// console.log('lifetimes',this.data.tabIndex); this.setTab(this.data.tabIndex, { suppressClick: this.data.suppressInitialClick })
// console.log('lifetimes',this.data.activeIndex);
this.setTab(this.data.tabIndex)
let that = this let that = this
wx.$eventbus.on('page_show', n => { wx.$eventbus.on('page_show', n => {
!that.data.width && that.setTab(that.data.tabIndex) !that.data.width && that.setTab(that.data.tabIndex, { suppressClick: true })
}) })
} }
}, },
...@@ -49,7 +52,13 @@ Component({ ...@@ -49,7 +52,13 @@ Component({
} = e.currentTarget.dataset } = e.currentTarget.dataset
this.setTab(index) this.setTab(index)
}, },
setTab(index = 0) { /**
* 切换内部 tab 下标并更新指示条样式。
* @param {number} [index=0]
* @param {{ suppressClick?: boolean }} [options] - suppressClick 为 true 时不 trigger click(首屏/ page_show 防重复拉数)
*/
setTab(index = 0, options = {}) {
const suppressClick = options.suppressClick === true
let { let {
tabIndex, tabIndex,
} = this.data } = this.data
...@@ -75,7 +84,9 @@ Component({ ...@@ -75,7 +84,9 @@ Component({
to: `to-${index}`, to: `to-${index}`,
width width
}) })
this.triggerEvent('click', index) if (!suppressClick) {
this.triggerEvent('click', index)
}
}, 100) }, 100)
}, this) }, this)
}, this) }, this)
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
import api from '~/pages/tabMine/api' import api from '~/pages/tabMine/api'
const app = getApp() const app = getApp()
import constantData from '../../pages/constant/data' import constantData from '../../pages/constant/data'
import { withTabRefreshInFlight } from '../../packageEquity/services/tabRefreshService.js'
const IMG_URL = 'https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/mine/' const IMG_URL = 'https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/mine/'
Component({ Component({
/** /**
...@@ -16,6 +17,13 @@ Component({ ...@@ -16,6 +17,13 @@ Component({
showCollege: { showCollege: {
type: Boolean, type: Boolean,
value: false value: false
},
/** Tab4 可见性:true 时刷新我的页银行卡/版本信息 */
show: {
type: Boolean,
observer(n) {
if (n) this.refreshOnShow()
}
} }
}, },
...@@ -33,30 +41,43 @@ Component({ ...@@ -33,30 +41,43 @@ Component({
lifetimes: { lifetimes: {
ready() { ready() {
let userInfo = wx.$util.getUserInfo() this.applyMineUserInfo()
this.setData({ }
},
/**
* 组件的方法列表
*/
methods: {
/** 从本地 userInfo 同步展示字段(ready 与每次 Tab 显示时调用) */
applyMineUserInfo() {
const userInfo = wx.$util.getUserInfo()
const payload = {
isForbidden: !wx.$hasPermission?.canSelectMultiStore?.(userInfo), isForbidden: !wx.$hasPermission?.canSelectMultiStore?.(userInfo),
isYqdSuper: app.globalData.isYqdSuper, isYqdSuper: app.globalData.isYqdSuper,
selectedSceneName: constantData?.sceneList?.filter(val => val.sceneType == userInfo?.sceneType)[0]?.sceneName, selectedSceneName: constantData?.sceneList?.filter(val => val.sceneType == userInfo?.sceneType)[0]?.sceneName,
selectedSceneDesc: constantData?.sceneList?.filter(val => val.sceneType == userInfo?.sceneType)[0]?.sceneDesc, selectedSceneDesc: constantData?.sceneList?.filter(val => val.sceneType == userInfo?.sceneType)[0]?.sceneDesc,
userInfo userInfo
}) }
if (userInfo.createdDate) { if (userInfo.createdDate) {
let date = userInfo.createdDate + '' let date = userInfo.createdDate + ''
date = date.replace(/-/g, '/').split(' ')[0] // 日期格式处理 date = date.replace(/-/g, '/').split(' ')[0]
this.setData({ payload['userInfo.createdTime'] = date
['userInfo.createdTime']: date
})
} }
this.getStaffBankList() this.setData(payload)
this.getVersionInfo() },
} /**
}, * Tab 切到我的时的统一入口;合并同 tick 并发。
* @returns {Promise<void>}
/** */
* 组件的方法列表 refreshOnShow() {
*/ return withTabRefreshInFlight('mine', () => this.refreshMineTab())
methods: { },
/** 刷新用户信息展示 + getStaffBankList + getVersionInfo */
async refreshMineTab() {
this.applyMineUserInfo()
await Promise.all([this.getStaffBankList(), this.getVersionInfo()])
},
/**跳转至银行卡 */ /**跳转至银行卡 */
toAddBankAccount(e) { toAddBankAccount(e) {
const { const {
......
...@@ -15,6 +15,9 @@ ...@@ -15,6 +15,9 @@
"prettier-plugin-mp": "^2.5.0" "prettier-plugin-mp": "^2.5.0"
}, },
"scripts": { "scripts": {
"test": "node --test packageDynamicForm/tests/**/*.test.mjs" "test": "node --test packageDynamicForm/tests/**/*.test.mjs tabIndex/tests/**/*.test.mjs packageEquity/tests/**/*.test.mjs",
"test:tabIndex": "node --test tabIndex/tests/**/*.test.mjs",
"test:equity": "node --test packageEquity/tests/**/*.test.mjs",
"test:dynamicForm": "node --test packageDynamicForm/tests/**/*.test.mjs"
} }
} }
# 路由与首页菜单 # 路由与首页菜单
## 精品首页 Menu 架构(tabIndex)
详细文档:[`tabIndex/docs/MENU-ARCHITECTURE.md`](../../tabIndex/docs/MENU-ARCHITECTURE.md)、变更记录 [`tabIndex/docs/DEVLOG.md`](../../tabIndex/docs/DEVLOG.md)。
实现目录:[`tabIndex/menu/`](../../tabIndex/menu/)
| 模块 | 职责 |
|------|------|
| `registry.js` | 单一数据源:`id` + `label` + `visible` + `action` + `section` |
| `buildMenus.js` | 同步管道 `buildTabIndexMenusSync` + 异步 `buildTabIndexMenusAsync` |
| `asyncProviders.js` | 话术核验 / 工资申诉 / 接待缺失报备 / 客户线索 / 工资绩效 / 驻店目标 / 动态表单 |
| `jumpHandlers.js` | `createMenuJumpHandler`:按 `action.type` 分发跳转 |
| `policies.js` | 可组合权限谓词,供 `visible(ctx)` 使用 |
页面调用链:`index.js` → `rebuildMenus()` → `buildTabIndexMenusAsync` → 单次 `setData`。`onShow` 通过 `getMenuFingerprint` 脏标记避免重复全量重建;切换门店调用 `invalidateMenuCache()` 后强制重建。
菜单项稳定主键为 `id`(如 `pending_approval`),WXML 仍读 `name`(由 `label` 映射)。`section: main` → `menu`,`section: secondary` → `newMenu`。
单测:`npm run test:tabIndex` → [`tabIndex/tests/tabIndexMenu.test.mjs`](../../tabIndex/tests/tabIndexMenu.test.mjs)(用例前缀 `IT-MENU-*` / `IT-MENU-SNAP-*` / `IT-MENU-JUMP-*`)。
## 全站 Menu 契约表(稳定 id)
| id | 文案 | 精品 tabIndex | 权益 packageEquity | 跳转 |
|----|------|---------------|-------------------|------|
| `create_order` | 新建工单 | ✅ 驻店 | ✅ 员工 | `tabWorkOrder.createOrder` / 弹窗 |
| `defeat_order` | 战败下单 | ✅ | ✅ mode=1 | `packageEquity.createDeafeatOrderBefore` |
| `repair_order` | 施工单 | ✅ 技师仅此项 | — | switchTab |
| `staff_daily_report` | 驻店日报 | ✅ | ✅ | `tabWorkOrder.staffDaily` |
| `staff_daily_report_new` | 驻店日报-新 | ✅ 动态表单 | ✅ 动态表单 | navigateToUrl 分包 |
| `store_daily_report` | 门店日报 | ✅ 动态表单 | ✅ 动态表单 | navigateToUrl 分包 |
| `negotiation_detail` | 洽谈明细 | ✅ 动态表单 | ✅ 动态表单 | navigateToUrl 分包 |
| `bi_report` | BI报表 | ✅ 督导+ | ✅ 督导+ | `tabOperating.index` |
| `pending_approval` | 待审批 | ✅ 区域运营 | ✅ 区域运营 | `tabWorkOrder.refundOperationList` |
| `recruit_manage` | 招聘管理 | ✅ | ✅ | `packageEquity.recruitManage` |
| `salary_appeal` | 工资申诉 | ✅ 异步 | ✅ 异步 | `packageEquity.salaryAppeal` |
| `missing_reception` | 接待缺失报备 | ✅ 异步 | ✅ 异步 | `packageEquity.missingReception` |
| `scene_market` | 场景集市 | ✅ | ✅ | navigateToUrl |
| `work_daily_report` | 工作日报 | — | ✅ 基座 | workReport → 督导日报模版 |
| `work_weekly_report` | 工作周报 | — | ✅ | 同上 |
| `work_monthly_report` | 工作月报 | — | ✅ | 同上 |
| `salary_performance_super` | 工资绩效 | ✅ newMenu 超管 | — | `packageEquity.collegeScene` |
| `salary_performance_api` | 工资绩效 | ✅ 异步驻店 | — | 同上 |
旧入口「驻店日报」(`tabWorkOrder.staffDaily`) 与「驻店日报-新」(动态表单分包) 并存;权益首页工作日报三件套由 `EQUITY_MENU_REGISTRY` 同步基座输出。
权益构建:[`packageEquity/menu/`](../../packageEquity/menu/)(`buildEquityMenusAsync` + `createEquityMenuJumpHandler`)+ 页面 [`rebuildEquityMenus`](../../packageEquity/pages/index/index.js);动态表单仍走 [`appendDynamicFormEquityMenusAsync`](../../utils/dynamicFormMenus.js)。文档:[`MENU-ARCHITECTURE.md`](../../packageEquity/docs/MENU-ARCHITECTURE.md)、[`ADD-MENU-GUIDE-EQUITY.md`](../../packageEquity/docs/ADD-MENU-GUIDE-EQUITY.md)。**不可**引用 `tabIndex/menu/`(分包隔离)。
单测:`npm run test:equity` → [`packageEquity/tests/equityMenu.test.mjs`](../../packageEquity/tests/equityMenu.test.mjs)(用例前缀 `IT-EQ-MENU-*`)。
## 分包页面 ## 分包页面
| TEST-ID | navigateToUrl | 标题 | | TEST-ID | navigateToUrl | 标题 |
...@@ -66,9 +115,9 @@ CDN 需按页面名上传对应 png(精品 `upgrade/`、权益 `crowdFunding/` ...@@ -66,9 +115,9 @@ CDN 需按页面名上传对应 png(精品 `upgrade/`、权益 `crowdFunding/`
| 门店日报 | `store_daily_report_page` | 同上 | | 门店日报 | `store_daily_report_page` | 同上 |
| 驻店日报-新 | `staff_daily_report_page` | 同上 | | 驻店日报-新 | `staff_daily_report_page` | 同上 |
触发位置:`tabIndex/pages/index/index.js`(精品 `jump`)、`packageEquity/pages/index/index.js`(权益 `navGo`)的 `item.navigateToUrl` 分支,在 `wx.navigateTo` 之前调用。其它 `navigateToUrl`(如场景集市)不打上述 eventCode。 触发位置:[`tabIndex/menu/jumpHandlers.js`](../../tabIndex/menu/jumpHandlers.js)(精品 `navigate` action)、`packageEquity/pages/index/index.js`(权益 `navGo`)的 `item.navigateToUrl` 分支,在 `wx.navigateTo` 之前调用。其它 `navigateToUrl`(如场景集市)不打上述 eventCode。
单测:`tests/dynamicFormMenus.test.mjs`(`IT-TRACK-001`~`004`)。 单测:`packageDynamicForm/tests/dynamicFormMenus.test.mjs`(`IT-TRACK-001`~`004`)、`tabIndex/tests/tabIndexMenu.test.mjs`。
## Schema 模版(配置中心) ## Schema 模版(配置中心)
......
/** 权益首页产值看板静态配置 */
export const EQUITY_ITEM_DATA_LIST = [
{
label: '客户成交',
value: 'totalSuccessCount',
icon: 'icon_1',
waitlabel: '推荐量',
waitValue: 'totalQuotationCount',
index: 1
},
{
label: '成交',
value: 'totalSuccessOrderCount',
icon: 'icon_7',
waitlabel: '报价单量',
waitValue: 'totalOrderCount',
index: 2
},
{
label: '融合客单价',
value: 'avgPrice',
icon: 'icon_12',
unit: true
},
{
label: '权益客单价',
value: 'avgQuotationPrice',
icon: 'icon_11',
unit: true
}
]
export const EQUITY_STATIC_DATA_LIST = [
{
label: '今日营业额',
value: 'todayTurnover',
tipsLabel: '今日成交量',
tipsValue: 'todayOrderNumber'
},
{
label: '本月营业额',
value: 'monthTurnover',
tipsLabel: '本月成交量',
tipsValue: 'monthOrderNumber'
},
{
label: '累计营业额',
value: 'totalTurnover',
tipsLabel: '累计成交量',
tipsValue: 'totalOrderNumber'
}
]
/** swiper index → dataActive */
export const SWIPER_INDEX_TO_ACTIVE = ['today', 'month', 'total']
# 权益首页新增菜单维护指南
面向 **packageEquity 权益首页**([`packageEquity/pages/index`](../pages/index/index.js) Component)。精品首页见 [`tabIndex/docs/ADD-MENU-GUIDE.md`](../../tabIndex/docs/ADD-MENU-GUIDE.md)。**不可**引用 `tabIndex/menu/`(分包隔离)。
相关架构:[`MENU-ARCHITECTURE.md`](./MENU-ARCHITECTURE.md) · 字段 JSDoc:[`registry.js`](../menu/registry.js) 顶部
---
## 1. 数据流(一句话)
菜单定义在注册表 → 管道组装 → 页面单次 `setData({ menuList })` → WXML 渲染 → 点击按 `action.type` 跳转。**不要在 `index.js` 里 `push` 菜单项。**
```mermaid
flowchart LR
registry["registry.js"]
build["buildMenus.js"]
page["index.js rebuildEquityMenus"]
wxml["index.wxml"]
jump["jumpHandlers.js"]
registry --> build --> page --> wxml
wxml -->|bindtap navGo| jump
```
| 概念 | 说明 |
|------|------|
| 稳定主键 | `id`(snake_case) |
| 展示文案 | `label` → view model 的 `menuText` |
| 场景 | `sceneType: 0`;动态表单 `appendDynamicFormEquityMenusAsync` |
| mode | `properties.mode` 控制 `defeat_order`;observer → `rebuildEquityMenus({ force: true })` |
---
## 2. 先判断:要改哪些文件?
| 场景 | 改动的文件 |
|------|------------|
| **A** 同步 + 权限显隐 + 已有 `action.type` | 仅 [`EQUITY_MENU_REGISTRY`](../menu/registry.js) |
| **B** 接口决定显隐 | `ASYNC_MENU_REGISTRY` + [`asyncProviders.js`](../menu/asyncProviders.js) |
| **C** 动态表单三入口 | [`utils/dynamicFormMenus.js`](../../utils/dynamicFormMenus.js)(已有 `dynamicForm` provider) |
| **D** 全新跳转方式 | [`jumpHandlers.js`](../menu/jumpHandlers.js) + registry `action.type` |
| **E** 角标需接口刷新 | [`badgeProviders.js`](../menu/badgeProviders.js) 按 `id` 扩展 |
| **F** 新权限谓词 | [`policies.js`](../menu/policies.js) + registry `visible` |
跨首页契约:[`packageDynamicForm/docs/routes-and-menus.md`](../../packageDynamicForm/docs/routes-and-menus.md)
---
## 3. 示例 A — 同步 router(员工可见)
```javascript
{
id: 'my_feature',
label: '我的功能',
icon: 'my_icon',
section: MENU_SECTION.MAIN,
sortVal: 20,
action: { type: 'router', target: 'packageEquity.myPage' },
visible: ({ isStaff }) => isStaff
}
```
`defeat_order` 需同时判断 `mode`:
```javascript
visible: ({ isStaff, policies }) =>
isStaff && policies.hasDefeatOrderMode()
```
---
## 4. 示例 B — 异步 provider
**registry.js** `ASYNC_MENU_REGISTRY`:
```javascript
{
id: 'my_async_menu',
label: '异步入口',
icon: 'async_icon',
section: MENU_SECTION.MAIN,
sortVal: 21,
action: { type: 'router', target: 'packageEquity.myPage' },
provider: 'myAsyncMenu'
}
```
**asyncProviders.js**:
```javascript
async function resolveMyAsyncMenu(ctx, commonApi) {
const res = await commonApi.someApi({})
return { myAsyncMenu: { visible: !!res?.data } }
}
// resolveAsyncMenuProviders 的 providers 数组中注册
```
- `packageEquity.extract` / `salaryAppeal` / `missingReception` 路由 toViewModel 会自动写 `path`
---
## 5. 示例 C — 角标(待审批模式)
在 `badgeProviders.js` 的 `applyEquityMenuBadges` 中按 `id` 查找下标并 `setData`:
```javascript
const index = menuList.findIndex(e => e.id === 'my_menu')
if (index > -1) {
someApi().then(res => {
page.setData({ [`menuList[${index}].tipsNum`]: res.data.count })
})
}
```
registry 可设 `tipsNum: 0` 初值。
---
## 6. 权益特有 action.type
| type | 行为 |
|------|------|
| `createOrderPrompt` | 校验链 + `showPromptDialog` |
| `defeatOrder` | 鸿蒙智行品牌判断 + 校验 + `scene: 0` |
| `workReport` | 工作日报/周报/月报模版弹窗 |
| `salaryPerformance` | `collegeScene` reLaunch |
| `residentTarget` | 带 `taskId` |
---
## 7. 检查清单
- [ ] `id` 为 snake_case(`IT-EQ-MENU-GUIDE-001`)
- [ ] 未在 `index.js` 内联 `menuList.push`
- [ ] `mode` 相关项用 `policies.hasDefeatOrderMode()` 或 `ctx.mode`
- [ ] 双首页都要上:另改 `tabIndex/menu/` + 更新 `routes-and-menus.md`
- [ ] 补 `packageEquity/tests/equityMenu.test.mjs` 用例
- [ ] `npm run test:equity` 全绿
---
## 8. 单测模板
```javascript
it('IT-EQ-MENU-SYNC-XXX: my_menu visible for staff', () => {
const menuList = buildEquityMenusSync(
createEquityMenuContext({
userInfo: { loginRole: 4 },
isStaff: true,
mode: 1
})
)
assert.ok(menuList.some(i => i.id === 'my_feature'))
})
```
```bash
npm run test:equity
```
用例文件:[`equityMenu.test.mjs`](../tests/equityMenu.test.mjs)、[`equityMenuJump.test.mjs`](../tests/equityMenuJump.test.mjs)
---
## 9. 四步速记
1. 判断场景(第 2 节)→ 确定改哪些文件
2. 在 `registry.js`(或 async provider)加条目
3. 补 `equityMenu.test.mjs` 用例
4. `npm run test:equity` + 真机点一遍(含 `mode` 切换)
# 权益分包变更记录
## 2026-06 — 权益首页 Menu 架构重构
- 新增 `packageEquity/menu/`:与精品 `tabIndex/menu/` 同构,分包内独立维护
- `packageEquity/pages/index/index.js`:`rebuildEquityMenus` + `createEquityMenuJumpHandler`,移除内联 `menuList.push`
- 文档:[`MENU-ARCHITECTURE.md`](./MENU-ARCHITECTURE.md)、[`ADD-MENU-GUIDE-EQUITY.md`](./ADD-MENU-GUIDE-EQUITY.md)
- 单测:`npm run test:equity`(`IT-EQ-MENU-*`,37 用例)
## 2026-06 — 修复 asyncProviders dynamic import 403
- 移除 `asyncProviders.js` 运行时 `import()`;API 改由 `index.js` `deps` 注入
- `buildMenus.js` 异步失败时回退同步 `menuList`
## 2026-06 — 权益首页非菜单优化
- 新增 `packageEquity/services/`:`dashboardService`、`todoService`、`receptionListService`
- `index.js`:`refreshEquityHome` 编排;修复 `isWait` 时 `fetchStaffRemindList` 未调用
- 子组件:`statistics-swiper`、`todo-panel`、`reception-timeline`
- 文档:[`HOMEPAGE-INDEX.md`](./HOMEPAGE-INDEX.md)
## 2026-06 — 权益 TabBar 接口治理与统一刷新
- **Tab0 看板**:`homeRefreshService` in-flight;`initList` 不再刷 home;`onShow` 补子页返回路径
- **Tab1–4 子页**:`pageShow[N]` 懒挂载 + `hide` 保活;`show` → `refreshOnShow` + `tabRefreshService`
- **父页去重**:`getMerchant4SMode` 仅 `onLoad`;`checkStaffOrderStatus` 仅 Tab0 + `staffOrderValidService`
- **tab-bar**:`suppressInitialClick` 避免工单/权益列表首屏三入口
- 详录:[`TAB-REFRESH-CHANGELOG.md`](./TAB-REFRESH-CHANGELOG.md)
- 单测:`IT-EQ-HOME-*`、`IT-EQ-TAB-*`、`IT-EQ-STAFF-*`(`npm run test:equity` 68 用例)
# 权益首页 index 组件职责地图
[`packageEquity/pages/index/index.js`](../pages/index/index.js) 在 Menu 抽离后的非菜单区块边界(对标 [`tabIndex/docs/HOMEPAGE-INDEX.md`](../../tabIndex/docs/HOMEPAGE-INDEX.md))。
> TabBar 接口治理与刷新策略完整变更记录见 [`TAB-REFRESH-CHANGELOG.md`](./TAB-REFRESH-CHANGELOG.md)。
## Menu(已抽离)
| 入口 | 模块 |
|------|------|
| `rebuildEquityMenus()` | [`menu/buildMenus.js`](../menu/buildMenus.js) |
| `navGo` | [`menu/jumpHandlers.js`](../menu/jumpHandlers.js) |
| `onReportPopupSelect` | [`menu/workReportHandler.js`](../menu/workReportHandler.js) |
| `promptHandleConfirm` | [`menu/orderPromptHandler.js`](../menu/orderPromptHandler.js) |
架构见 [`MENU-ARCHITECTURE.md`](./MENU-ARCHITECTURE.md)。
## 看板(services)
| 方法 | 模块 |
|------|------|
| `refreshDashboard` / `onSwiperChange` | [`services/dashboardService.js`](../services/dashboardService.js) |
| `refreshQuotationTotal` | 同上 `normalizeQuotationStatistics` |
| 静态 `itemDataList` | [`config/dashboardConfig.js`](../config/dashboardConfig.js) |
子组件:[`statistics-swiper`](../pages/index/components/statistics-swiper/statistics-swiper.wxml)
## 待办(services)
| 方法 | 模块 |
|------|------|
| `fetchStaffRemindList` | `buildEquityStaffRemindParams`(**scene: 0**) |
| `onTodoClose` | `buildEquityShutDownTaskParams` |
| `onTodoGoto` | `resolveTodoGotoAction` |
子组件:[`todo-panel`](../pages/index/components/todo-panel/todo-panel.wxml)
**注意**:权益 `merchantId` 取 `default4SStoreInfo.merchantId`,与精品 `shopMerchantId` + scene 1 不同。
## 接待列表(services)
| 方法 | 模块 |
|------|------|
| `getReceptionParams` | `buildReceptionQueryParams` |
| `getReceptionList` | `normalizeReceptionDateSections` |
| `getReceptionRecordDetailInfo` | `mergeReceptionDetails` / `computeReceptionHasMore` |
| `maybeRefreshReceptionList` | `buildReceptionFingerprint`(Tab 切回脏标记) |
子组件:[`reception-timeline`](../pages/index/components/reception-timeline/reception-timeline.wxml)
筛选弹层仍通过 `wx.$router.getPageInstance()` 与父页 `equityPage` 联动,本次未搬迁。
## 父子页职责(与 equityPage 协同)
| 职责 | equityPage(父页) | home(本组件) |
|------|-------------------|----------------|
| 公告角标/弹窗 | `checkServiceNotice`(仅 Tab0 + [`serviceCenterNoticeService`](../services/serviceCenterNoticeService.js) 缓存) | 只读 `serviceCenterUnreadNum` |
| 门店 mode | `equityPage.onLoad` 单次 `getMerchant4SMode` 下发 `mode`(初始 `null`) | `scheduleInitialMenuBuild` 等 mode 就绪后建菜单 |
| 菜单异步 API | 不调用 | `rebuildEquityMenus` 唯一入口 |
| 看板/待办/接待 | `initList` 不刷新看板、不触发 home `onLoad` | `onLoad` / `show` → `refreshEquityHome`([`homeRefreshService`](../services/homeRefreshService.js) in-flight) |
| 开单预警 | `checkStaffOrderStatus` 仅 Tab0;[`staffOrderValidService`](../services/staffOrderValidService.js) 当日缓存 | 不调用 |
## 生命周期
```
attached → onLoad
→ ensureMentorFlag
→ refreshDashboard + refreshQuotationTotal + fetchStaffRemindList(isWait)
→ scheduleInitialMenuBuild(mode 就绪后单次 rebuild;3s fallback)
→ _homeReady = true
properties.mode → 首次非 null:_buildInitialMenusOnce;后续变化:rebuildEquityMenus(指纹)
rebuildEquityMenus → getMenuFingerprint;hasPerformanceConfig / getTargetCheck → menuApiCache
refreshEquityHome → buildHomeRefreshFingerprint + withHomeRefreshDedup(仅 in-flight,每次切回 Tab0 都刷)
Tab 切回时各子页 `show` observer → `refreshOnShow`([`tabRefreshService`](../services/tabRefreshService.js) in-flight):
Tab0 home → refreshEquityHome
Tab1 quotation-list → refreshQuotationTab(page + statistics + merchant.info)
Tab2 equity-list → refreshEquityTab(statics + page)
Tab3 makert-material → refreshMaterialsTab(materialListApi)
Tab4 tab-mine → refreshMineTab(银行卡 + 版本)
子页返回权益页(Tab 0)→ equityPage.onShow → refreshEquityHome skipMenu
equityPage.onLoad → getMerchant4SMode(仅首屏)
equityPage.initList(tab 0)→ checkStaffOrderStatus / checkAbnormalOrderLocal / checkServiceNotice
equityPage.initList(tab 1–4)→ 不打 order.staff.valid;不调用子页 onLoad
Tab 1/2 内部 tab-bar → suppressInitialClick 避免 ready 重复 tabClick
```
## 测试
```bash
npm run test:equity
```
用例前缀:`IT-EQ-DASH-*`、`IT-EQ-TODO-*`、`IT-EQ-REC-*`、`IT-EQ-MENU-*`、`IT-EQ-CACHE-*`、`IT-EQ-HOME-*`、`IT-EQ-TAB-*`、`IT-EQ-STAFF-*`、`IT-EQ-NOTICE-*`
## 不在本组件范围
- [`equityPage.js`](../pages/TabBar/equityPage.js):Tab、弹窗队列、`initList`、服务中心公告
- [`receptionScreen`](../pages/index/components/receptionScreen/receptionScreen.js):筛选 UI
# 权益首页 Menu 架构
## 新增菜单(维护者入口)
新增/修改权益首页菜单项,请先阅读 **[`ADD-MENU-GUIDE-EQUITY.md`](./ADD-MENU-GUIDE-EQUITY.md)**:含决策流程、示例、检查清单与单测模板。字段细节以本文与 [`registry.js`](../menu/registry.js) JSDoc 为准。
精品首页对照:[`tabIndex/docs/MENU-ARCHITECTURE.md`](../../tabIndex/docs/MENU-ARCHITECTURE.md)(**不可** cross-import `tabIndex/menu/`)。
## 数据流
```mermaid
flowchart TD
registry["EQUITY_MENU_REGISTRY / ASYNC_MENU_REGISTRY"]
ctx["createEquityMenuContext"]
sync["buildEquityMenusSync"]
async["resolveAsyncMenuProviders"]
merge["dedupe + sort"]
page["index.js rebuildEquityMenus → setData menuList"]
jump["createEquityMenuJumpHandler → action.type"]
registry --> sync
ctx --> sync
ctx --> async
sync --> merge
async --> merge
merge --> page
page --> jump
```
## 模块职责
| 文件 | 导出 | 职责 |
|------|------|------|
| [`constants.js`](../menu/constants.js) | `SCENE_TYPE`, `MENU_SECTION` | 权益场景常量(`sceneType: 0`) |
| [`policies.js`](../menu/policies.js) | `createPolicies` | 从 `userInfo` / `mentorFlag` / `mode` 派生权限谓词 |
| [`context.js`](../menu/context.js) | `createEquityMenuContext`, `getMenuFingerprint` | 构建管道上下文;脏标记指纹(含 `mode`) |
| [`registry.js`](../menu/registry.js) | `EQUITY_MENU_REGISTRY`, `ASYNC_MENU_REGISTRY`, `DYNAMIC_FORM_MENU_IDS` | 菜单单一数据源 |
| [`toViewModel.js`](../menu/toViewModel.js) | `registryItemToViewModel` | `label`→`menuText`,`action`→`path`/`navigateToUrl` |
| [`buildMenus.js`](../menu/buildMenus.js) | `buildEquityMenusSync`, `buildEquityMenusAsync` | 同步过滤 + 异步合并 |
| [`asyncProviders.js`](../menu/asyncProviders.js) | `resolveAsyncMenuProviders`, `resolveCustomerClue` | 并行拉接口决定显隐 |
| [`resolveActionType.js`](../menu/resolveActionType.js) | `resolveActionType` | 从 view model 解析 `action.type` |
| [`jumpHandlers.js`](../menu/jumpHandlers.js) | `createEquityMenuJumpHandler` | 点击跳转分发 |
| [`badgeProviders.js`](../menu/badgeProviders.js) | `applyEquityMenuBadges` | 待审批/招聘/客户线索角标 |
| [`workReportHandler.js`](../menu/workReportHandler.js) | `openWorkReportTemp`, `onWorkReportPopupSelect` | 工作日报/周报/月报模版 |
## WXML 与 view model
首页 [`index.wxml`](../pages/index/index.wxml) 单列表 `menuList`:
| 字段 | WXML 绑定 | 说明 |
|------|-----------|------|
| `menuText` | `{{ item.menuText }}` | 由 `label` 映射 |
| `icon` | `crowdFunding/{{ item.icon }}.png` | 权益固定 `crowdFunding/` 前缀 |
| `tipsNum` | 角标数字 | registry 初值 + `applyEquityMenuBadges` |
| `noRead` | `bubble_icon` | 驻店目标未读 |
## 注册表字段
字段定义源码:[`registry.js` 顶部 `EquityMenuRegistryEntry` / `EquityMenuAction`](../menu/registry.js)。
### 同步条目(EQUITY_MENU_REGISTRY)
| 字段 | 必填 | 消费方 | 说明 |
|------|------|--------|------|
| `id` | 是 | `buildMenus` 去重、`applyEquityMenuBadges`、`jumpHandlers` | 稳定主键 |
| `label` | 是 | `toViewModel` → `menuText` | WXML 展示文案 |
| `icon` | 是 | `index.wxml` | `crowdFunding/{icon}.png` |
| `section` | 是 | 文档/契约 | 权益统一进 `menuList` |
| `action` | 是 | `toViewModel`、`jumpHandlers` | 跳转指令 |
| `visible` | 是 | `buildEquityMenusSync` | `(ctx) => boolean` |
| `sortVal` | 建议 | `buildMenus` sort | 升序 |
### action.type 一览(权益)
| type | 消费方 | 行为 |
|------|--------|------|
| `router` | `jumpHandlers.router` | `wx.$router.go`,默认 `scene: 0` |
| `navigate` | `jumpHandlers.navigate` | `wx.navigateTo` + 动态表单/场景集市埋点 |
| `workReport` | `jumpHandlers.workReport` | `openWorkReportTemp`(工作日报三件套) |
| `createOrderPrompt` | `jumpHandlers.createOrderPrompt` | 校验链 + `showPromptDialog` |
| `defeatOrder` | `jumpHandlers.defeatOrder` | 品牌判断 path + 校验 + 跳转 |
| `salaryPerformance` | `jumpHandlers.salaryPerformance` | `collegeScene` reLaunch |
| `residentTarget` | `jumpHandlers.residentTarget` | 驻店目标,带 `taskId` |
### 跳转副作用(shutDownTaskApi)
| 菜单 id | taskId | scene | 触发位置 |
|---------|--------|-------|----------|
| `training_materials` | 5 | 0 | `jumpHandlers` `SHUTDOWN_TASK_BY_ID` |
### resolveActionType 回退链
1. `reportTypeAttr` 或 `path === 'tabWorkOrder.supervisorDaily'` → `workReport`
2. `navigateToUrl` → `navigate`
3. 无 `path` 且 `menuText === '工资绩效'` → `salaryPerformance`
4. 无 `path` 且 `id === 'create_order'` → `createOrderPrompt`
5. 默认 → `router`
## 异步 Provider
| provider key | 菜单 id | 角色 / 前置条件 | 接口 / 显隐逻辑 |
|--------------|---------|-----------------|-----------------|
| `salaryAppeal` | `salary_appeal` | — | 超管直显;否则 `hasPerformanceConfig` 且 (`canViewRecruit` \| `isStaff` \| `loginRole==4`) |
| `missingReception` | `missing_reception` | `isStaff` \| `canSelectMultiStoreForStaffDaily` | `checkMerchantDirect(scene:0)` + `checkMissingReception` → `missingRecordTodoList` |
| `scriptExtract` | `script_extract` | — | `canViewViolation` \| `canViewRecruit` \| `mentorFlag` |
| `scriptVerify` | `script_verify` | — | `extractCheck`;(超管 \| 接口 true) |
| `aiFunPractice` | `ai_fun_practice` | `isNotMentor` | 同步谓词 |
| `customerClue` | `customer_clue` | — | `getYqStoreConfig.customerExchangeFlag === 'Y'` |
| `salaryPerformance` | `salary_performance_api` | — | `getBusinessSchoolScene` 有结果则显 |
| `residentTarget` | `resident_target` | `isStaff`、非 `canSelectMultiStore` | `getStaffTargetTaskApi(sceneType:0)` + task 弹窗 sideEffects |
| `receptionRecords` | `reception_records` | 门店在质检列表 \| 多店督导;且 `isNotMentor` | `selectrecmerchantList` |
| `illegalRecording` | `illegal_recording` | 同上(无导师限制) | 同上 |
| `mentorFlag` | — | 非多店督导 | `getStaffMentorFlag` → `sideEffects.mentorFlag` 触发二次重建 |
| `dynamicForm` | 三入口 id | `sceneType:0` + 角色门禁 | `appendDynamicFormEquityMenusAsync` |
Provider 返回:`{ [key]: { visible, extras?, sideEffects? } }`;`dynamicForm` 另返回 `items[]`。
## 页面集成(Component)
**约束**:`packageEquity/menu/asyncProviders.js` **禁止**运行时 `import()`(微信分包会 403)。API 须在页面层 **静态 import** 后通过 `deps` 注入 `buildEquityMenusAsync`。
```js
// packageEquity/pages/index/index.js
import commonApi from '~/api/api'
import aiApi from '../../aiApi'
import carLifeApi from '../../carEquityApi'
import { checkMerchantDirect, checkMissingReception } from '../../receptionRecordsApi'
import {
buildEquityMenusAsync,
createEquityMenuJumpHandler,
applyEquityMenuBadges
} from '../../menu/index.js'
async rebuildEquityMenus() {
const result = await buildEquityMenusAsync({
userInfo, isStaff, mentorFlag, mode,
deps: {
commonApi,
aiApi,
carLifeApi,
receptionRecordsApi: { checkMerchantDirect, checkMissingReception },
getBusinessSchoolScene
}
})
this.setData({ menuList: result.menuList })
}
// mode 变化
properties.mode.observer() { this.rebuildEquityMenus({ force: true }) }
```
`buildEquityMenusAsync` 在异步 provider 异常时会 **回退同步菜单**(`syncItems`),避免整页空白。
## 测试
```bash
npm run test:equity
```
用例前缀:`IT-EQ-MENU-*`([`equityMenu.test.mjs`](../tests/equityMenu.test.mjs)、[`equityMenuJump.test.mjs`](../tests/equityMenuJump.test.mjs))。
Mock:测试顶部 `setupWxMock`;异步用 `createDefaultEquityAsyncDeps` 注入 API。
相关文档:[`packageDynamicForm/docs/routes-and-menus.md`](../../packageDynamicForm/docs/routes-and-menus.md)。
# 权益 TabBar 接口治理与刷新策略变更记录
> 记录 2026-06 权益页 `equityPage` 及子 Tab 的接口去重、刷新策略统一改造。
> 架构总览见 [`HOMEPAGE-INDEX.md`](./HOMEPAGE-INDEX.md)。
## 一、问题背景
| 现象 | 根因 |
|------|------|
| Tab 切回首页,看板/待办接口成对重复 | `initList` 与 home `show` observer 双触发 `refreshEquityHome` |
| Tab 切工单管理,列表/统计/merchant.info 重复 | `attached→onLoad` + `initList→onLoad` + `tab-bar ready→tabClick` 三重入口 |
| 任意 Tab 切换都打 `order.staff.valid` | `initList` 无条件 `checkStaffOrderStatus`;且无预警时不写 `dateStaffPop` |
| 任意 Tab 切换都打 `merchant.mode` | `initList` 每次调用 `getMerchant4SMode` |
| 切回子 Tab 不刷新数据 | `_tabReady` 仅首进刷新,与「切 Tab 应刷」产品诉求冲突 |
## 二、目标架构
```
equityPage.changeTabBar
→ setData tabIndex + pageShow[N]
→ initList(仅父页弹窗/交付目标,Tab0 才含开单预警/异常单/公告)
→ 子组件 properties.show=true → refreshOnShow / refreshEquityHome
子页挂载:pageShow[N] 懒挂载 + hide 保活(不 wx:if 销毁)
并发去重:tabRefreshService / homeRefreshService 仅 in-flight,无 TTL 跳过
```
## 三、分阶段改动清单
### 3.1 首页看板/待办(Tab 0)
**文件**:[`pages/index/index.js`](../pages/index/index.js)、[`services/homeRefreshService.js`](../services/homeRefreshService.js)、[`pages/TabBar/equityPage.js`](../pages/TabBar/equityPage.js)
| 改动 | 说明 |
|------|------|
| 移除 `initList` 内 `home.refreshEquityHome` | Tab 切回 0 仅由 `show` observer 刷新 |
| `equityPage.onShow` 补 `refreshEquityHome` | 子页返回且仍在 Tab0 时 `show` 不变,observer 不触发 |
| `refreshEquityHome` + `withHomeRefreshDedup` | 指纹合并同 tick 并发;**每次切回都刷**(已去掉 60s TTL) |
| 涉及 API | `outputValueStatistics`、`quotation.statistics`、`staff.reminder.list` |
### 3.2 门店 mode(父页)
**文件**:[`equityPage.js`](../pages/TabBar/equityPage.js)
| 改动 | 说明 |
|------|------|
| `getMerchant4SMode` 从 `initList` 移到 `onLoad` | 仅首屏请求 `merchant.mode` |
| Tab 切换不再打 mode 接口 | |
### 3.3 开单预警(父页 Tab0)
**文件**:[`equityPage.js`](../pages/TabBar/equityPage.js)、[`services/staffOrderValidService.js`](../services/staffOrderValidService.js)
| 改动 | 说明 |
|------|------|
| `checkStaffOrderStatus` 仅 `tabIndex===0` | Tab 1–4 切换不再打 `order.staff.valid` |
| API 成功后无论是否弹窗写 `dateStaffPop` | 修复无预警时每次 initList 都请求 |
| 读写键统一 `[sceneType][merchantId]` | 修复原先写死 `0` 键 |
### 3.4 子 Tab 保活与刷新(Tab 1–4)
**文件**:[`equityPage.wxml`](../pages/TabBar/equityPage.wxml)、各子组件
| Tab | 组件 | 刷新函数 | API |
|-----|------|----------|-----|
| 1 | `quotation-list` | `refreshQuotationTab` | `quotation.page`、`order.status.statistics`、`merchant.info` |
| 2 | `equity-list` | `refreshEquityTab` | `equityOrder.statics`、`equityOrder.page` |
| 3 | `makert-material` | `refreshMaterialsTab` | `materialListApi` |
| 4 | `tab-mine` | `refreshMineTab` | `getStaffBankList`、`getVersionInfo` |
**公共**:
- `wx:if="{{ pageShow[N] }}"` + `hide` + `show="{{ tabIndex==N }}"`
- `initList` **不再** `selectComponent('#page-N').onLoad()`
- [`tabRefreshService.js`](../services/tabRefreshService.js):`withTabRefreshInFlight` 防同 tick 双触发
### 3.5 工单/权益列表内 tab-bar
**文件**:[`components/TabBar/TabBar.js`](../../components/TabBar/TabBar.js)、子组件 wxml
| 改动 | 说明 |
|------|------|
| `suppressInitialClick` | ready / `page_show` 时 `setTab` 不 emit `click`,避免首屏多打列表 |
| `tabClick` 去掉末尾重复 `getOrderStatistics` | `search()` 已含统计 |
## 四、刷新入口职责表(现行)
| 场景 | 入口 | 是否打业务 API |
|------|------|----------------|
| 冷启动 Tab0 | home `onLoad` | 看板/待办 1 次 |
| Tab 切到 0 | home `show` observer → `refreshEquityHome` | 看板/待办 1 次 |
| 子页返回权益页 Tab0 | `equityPage.onShow` → `refreshEquityHome` | 看板/待办 1 次(in-flight 与 observer 合并) |
| Tab 切到 1–4 | 子组件 `show` → `refreshOnShow` | 各 Tab 业务 API 各 1 次 |
| Tab 切换(任意) | `initList` | 仅 `checkDeliveryTarget`;Tab0 加弹窗链 |
| 首屏 | `equityPage.onLoad` | `getMerchant4SMode` 1 次 |
## 五、新增/变更服务模块
| 模块 | 职责 |
|------|------|
| [`homeRefreshService.js`](../services/homeRefreshService.js) | Tab0 `refreshEquityHome` in-flight |
| [`tabRefreshService.js`](../services/tabRefreshService.js) | Tab1–4 `refreshOnShow` in-flight |
| [`staffOrderValidService.js`](../services/staffOrderValidService.js) | 开单预警 `dateStaffPop` 读写 |
| [`serviceCenterNoticeService.js`](../services/serviceCenterNoticeService.js) | 公告角标/弹窗(既有) |
## 六、单测
```bash
npm run test:equity
```
| 前缀 | 覆盖 |
|------|------|
| `IT-EQ-HOME-*` | 首页刷新指纹、in-flight、顺序刷新 |
| `IT-EQ-TAB-*` | 子 Tab in-flight、key 隔离 |
| `IT-EQ-STAFF-*` | 开单预警当日缓存 |
## 七、Network 自检清单
1. Tab0→1→0 往返:看板三接口每次进 Tab0 各 1 次,无成对重复
2. Tab0→1:工单三接口各 1 次;**无** `order.staff.valid`
3. Tab1→2→3→4:仅对应 Tab 业务接口;**无** `merchant.mode` / `order.staff.valid`
4. 同日 Tab0 多次:`order.staff.valid` 至多 1 次
## 八、源码 JSDoc 索引
各关键函数已补充 JSDoc / 行内注释,便于对照上文改动:
| 文件 | 函数 / 属性 |
|------|-------------|
| [`equityPage.js`](../pages/TabBar/equityPage.js) | `onLoad`、`onShow`、`initList`、`changeTabBar`、`getMerchant4SMode`、`checkStaffOrderStatus` |
| [`index/index.js`](../pages/index/index.js) | `properties.show`、`refreshEquityHome` |
| [`homeRefreshService.js`](../services/homeRefreshService.js) | `buildHomeRefreshFingerprint`、`withHomeRefreshDedup`、`clearHomeRefreshState` |
| [`tabRefreshService.js`](../services/tabRefreshService.js) | `withTabRefreshInFlight`、`clearTabRefreshState` |
| [`staffOrderValidService.js`](../services/staffOrderValidService.js) | `shouldSkipStaffOrderValid`、`markStaffOrderValidChecked` |
| [`carQuotation/index/index.js`](../pages/carQuotation/index/index.js) | `show`、`refreshOnShow`、`refreshQuotationTab` |
| [`EquityList.js`](../pages/carEquity/components/EquityList/EquityList.js) | `show`、`refreshOnShow`、`refreshEquityTab` |
| [`materials.js`](../pages/trainingMaterials/components/Materials/materials.js) | `show`、`refreshOnShow`、`refreshMaterialsTab`、`bootstrapMaterialsTab` |
| [`TabMine.js`](../../components/TabMine/TabMine.js) | `show`、`applyMineUserInfo`、`refreshOnShow`、`refreshMineTab` |
| [`TabBar.js`](../../components/TabBar/TabBar.js) | `suppressInitialClick`、`setTab` |
/**
* 权益首页异步菜单 Provider
*
* 各 provider 并行执行,返回 `{ [providerKey]: { visible, extras?, sideEffects? } }`
* 由 buildEquityMenusAsync 合并进最终 menuList。单测通过 deps 注入 mock API。
*
* **微信小程序约束**:禁止使用运行时 `import()`(会 403);API 须由页面 `deps` 静态 import 后注入(见 index.js rebuildEquityMenus)。
* Provider 表见 packageEquity/docs/MENU-ARCHITECTURE.md
*/
import dayjs from 'dayjs'
import {
appendDynamicFormEquityMenusAsync,
stripDynamicFormEquityMenus,
DYNAMIC_FORM_EQUITY_MENUS
} from '../../utils/dynamicFormMenus.js'
import { SCENE_TYPE } from './constants.js'
import { registryItemToViewModel } from './toViewModel.js'
import {
cachedHasPerformanceConfig,
cachedGetStaffTargetTask
} from './menuApiCache.js'
/**
* 并行解析所有异步菜单 provider
*
* @param {Object} ctx - createEquityMenuContext 返回值
* @param {Object} [deps]
* @param {Object} [deps.commonApi] - api/api.js 方法集
* @param {Object} [deps.aiApi] - packageEquity/aiApi.js
* @param {Object} [deps.carLifeApi] - packageEquity/carEquityApi.js
* @param {Object} [deps.receptionRecordsApi] - checkMerchantDirect / checkMissingReception
* @param {Function} [deps.getBusinessSchoolScene] - 工资绩效显隐
* @returns {Promise<Record<string, { visible: boolean, extras?: Object, sideEffects?: Object, items?: Array }>>}
*/
export async function resolveAsyncMenuProviders(ctx, deps = {}) {
const { isStaff } = ctx
const policies = ctx.policies
const resolvedCommonApi = deps.commonApi
const resolvedAiApi = deps.aiApi
const resolvedCarLifeApi = deps.carLifeApi
const resolvedReceptionApi = deps.receptionRecordsApi
if (
!resolvedCommonApi ||
!resolvedAiApi ||
!resolvedCarLifeApi ||
!resolvedReceptionApi
) {
throw new Error(
'resolveAsyncMenuProviders requires deps.commonApi, aiApi, carLifeApi, receptionRecordsApi (see index.js rebuildEquityMenus)'
)
}
const providers = [
resolveSalaryAppeal(ctx, resolvedCommonApi, isStaff),
resolveMissingReception(ctx, resolvedReceptionApi, isStaff, policies),
resolveScriptExtract(ctx, policies),
resolveScriptVerify(ctx, resolvedAiApi, policies),
resolveAiFunPractice(ctx, policies),
resolveCustomerClue(ctx, resolvedCommonApi, deps),
resolveSalaryPerformance(ctx, deps.getBusinessSchoolScene),
resolveResidentTarget(ctx, resolvedCommonApi, policies, isStaff),
resolveReceptionMenus(ctx, resolvedCarLifeApi, policies),
resolveDynamicForm(ctx)
]
const results = await Promise.all(providers)
return Object.assign({}, ...results)
}
/** 工资申诉:超管直显;否则 hasPerformanceConfig + 角色门禁。 @see MENU-ARCHITECTURE.md */
async function resolveSalaryAppeal(ctx, commonApi, isStaff) {
const { userInfo } = ctx
const policies = ctx.policies
if (policies.isSuper()) {
return { salaryAppeal: { visible: true } }
}
const mayNeedSalaryAppeal =
policies.canViewRecruit() || isStaff || userInfo?.loginRole == 4
if (!mayNeedSalaryAppeal) {
return { salaryAppeal: { visible: false } }
}
try {
const res = await cachedHasPerformanceConfig(
commonApi,
userInfo.shopMerchantId || ''
)
const visible = !!res?.data
return { salaryAppeal: { visible } }
} catch {
return { salaryAppeal: { visible: false } }
}
}
/** 接待缺失报备:scene 0;写入 sideEffects.missingRecordTodoList。 @see MENU-ARCHITECTURE.md */
async function resolveMissingReception(ctx, receptionApi, isStaff, policies) {
const { userInfo } = ctx
if (!(isStaff || policies.canSelectMultiStoreForStaffDaily())) {
return {
missingReception: {
visible: false,
sideEffects: { missingRecordTodoList: [] }
}
}
}
try {
const res = await receptionApi.checkMerchantDirect({
merchantId: userInfo.shopMerchantId,
scene: SCENE_TYPE
})
if (!res?.data) {
return {
missingReception: {
visible: false,
sideEffects: { missingRecordTodoList: [] }
}
}
}
const { uuid, merchantId, shopMerchantId } = userInfo
let missingRecordTodoList = []
try {
const result = await receptionApi.checkMissingReception({
merchantId: shopMerchantId,
yqMerchantId: merchantId,
staffUuid: uuid,
sceneType: SCENE_TYPE,
reportStartDate: dayjs().subtract(6, 'day').format('YYYY-MM-DD'),
reportEndDate: dayjs().format('YYYY-MM-DD')
})
if (result.code == 0) {
result.data.reverse().forEach(e => {
if (
e.missingReceptionRecord &&
!e.hasReceptionReport &&
!missingRecordTodoList.length
) {
missingRecordTodoList.push(e)
}
})
}
} catch {
// ignore
}
return {
missingReception: {
visible: true,
sideEffects: { missingRecordTodoList }
}
}
} catch {
return {
missingReception: {
visible: false,
sideEffects: { missingRecordTodoList: [] }
}
}
}
}
async function resolveScriptExtract(ctx, policies) {
const { mentorFlag } = ctx
return {
scriptExtract: {
visible:
policies.canViewViolation() ||
policies.canViewRecruit() ||
mentorFlag
}
}
}
async function resolveScriptVerify(ctx, aiApi, policies) {
try {
const res = await aiApi.extractCheck({})
const visible = policies.isSuper() || !!res?.data
return { scriptVerify: { visible } }
} catch {
return { scriptVerify: { visible: policies.isSuper() } }
}
}
async function resolveAiFunPractice(ctx, policies) {
return {
aiFunPractice: {
visible: policies.isNotMentor()
}
}
}
/**
* 客户线索:getYqStoreConfig.customerExchangeFlag === 'Y' 时显隐
* @param {Object} ctx
* @param {Object} commonApi
* @param {Object} [deps]
*/
export async function resolveCustomerClue(ctx, commonApi, deps = {}) {
const { userInfo } = ctx
try {
const { merchantId: yqMerchantId } = userInfo
const res = await (deps.getYqStoreConfig || commonApi.getYqStoreConfig)({
yqMerchantId
})
const data = res?.data
if (!data || data.customerExchangeFlag != 'Y') {
return { customerClue: { visible: false } }
}
return { customerClue: { visible: true, extras: { tipsNum: 0 } } }
} catch {
return { customerClue: { visible: false } }
}
}
async function resolveSalaryPerformance(ctx, getBusinessSchoolScene) {
if (!getBusinessSchoolScene) {
return { salaryPerformance: { visible: false } }
}
try {
const res = await getBusinessSchoolScene({})
return { salaryPerformance: { visible: !!res } }
} catch {
return { salaryPerformance: { visible: false } }
}
}
async function resolveResidentTarget(ctx, commonApi, policies, isStaff) {
const { userInfo } = ctx
if (policies.canSelectMultiStore() || !isStaff) {
return { residentTarget: { visible: false } }
}
const merchantId = userInfo?.default4SStoreInfo?.merchantId
if (!merchantId) {
return { residentTarget: { visible: false } }
}
try {
const res = await cachedGetStaffTargetTask(commonApi, {
sceneType: SCENE_TYPE,
merchantId
})
const { code, data } = res
if (code != 0 || !data?.length) {
return { residentTarget: { visible: false } }
}
const sideEffects = {
taskId: data[0]?.id,
taskInfo: data[0],
showTaskDialog: data[0]?.promptFlag == 'N'
}
return {
residentTarget: {
visible: true,
extras: { noRead: data[0]?.readFlag == 'N' },
sideEffects
}
}
} catch {
return { residentTarget: { visible: false } }
}
}
async function resolveReceptionMenus(ctx, carLifeApi, policies) {
const { userInfo } = ctx
try {
const res = await carLifeApi.selectrecmerchantList({})
if (res.code != 0) {
return {
receptionRecords: { visible: false },
illegalRecording: { visible: false },
sideEffects: { storeRangeList: null, showReceive: false }
}
}
const data = res.data || []
const index = data.findIndex(
v => v.merchantNo == userInfo?.default4SStoreInfo?.merchantId
)
const hasAccess =
policies.canSelectMultiStore() || index > -1
return {
receptionRecords: {
visible: hasAccess && policies.isNotMentor()
},
illegalRecording: {
visible: hasAccess
},
sideEffects: {
storeRangeList: hasAccess ? data : null,
showReceive: hasAccess
}
}
} catch {
return {
receptionRecords: { visible: false },
illegalRecording: { visible: false }
}
}
}
async function resolveDynamicForm(ctx) {
const { userInfo } = ctx
const menuList = []
stripDynamicFormEquityMenus(menuList)
await appendDynamicFormEquityMenusAsync(menuList, userInfo)
const items = menuList.map(item => {
const label = item.menuText || item.name
const id =
label === '洽谈明细'
? 'negotiation_detail'
: label === '门店日报'
? 'store_daily_report'
: 'staff_daily_report_new'
return registryItemToViewModel(
{
id,
label,
icon: item.icon,
sortVal: item.sortVal,
action: { type: 'navigate', target: item.navigateToUrl },
noCheckdailyReport: item.noCheckdailyReport,
recordId: item.recordId
},
{
navigateToUrl: item.navigateToUrl,
trackEventCode: item.trackEventCode
}
)
})
return { dynamicForm: { visible: items.length > 0, items } }
}
/**
* 权益首页菜单角标拉取(按 id 定位 menuList 下标后 setData)
*/
import {
getWaitAuditCountAPI,
waitstaffstateAPI
} from '~/api/api'
import commonApi from '../../api/api.js'
/**
* 菜单重建后按 id 拉取角标
* @param {Object} page - index Component 实例
* @param {Object} userInfo
* @param {Array} [menuList] - 当前 menuList
*/
export function applyEquityMenuBadges(page, userInfo, menuList = page.data.menuList) {
const approvalIndex = menuList.findIndex(e => e.id === 'pending_approval')
const recruitIndex = menuList.findIndex(e => e.id === 'recruit_manage')
const clueIndex = menuList.findIndex(e => e.id === 'customer_clue')
if (approvalIndex > -1) {
getWaitAuditCountAPI({ sceneType: userInfo?.sceneType }).then(res => {
if (res.code == 0) {
page.setData({
[`menuList[${approvalIndex}].tipsNum`]: res.data.waiteForAuditNum
})
}
})
}
if (recruitIndex > -1) {
waitstaffstateAPI().then(result => {
if (result.code == 0) {
page.setData({
[`menuList[${recruitIndex}].tipsNum`]: result.data.waitProcessCount
})
}
})
}
if (clueIndex > -1) {
applyCustomerClueBadge(page, clueIndex)
}
}
/**
* 客户线索角标
* @param {Object} page
* @param {number} [index] - menuList 下标,省略则按 id 查找
*/
export async function applyCustomerClueBadge(page, index) {
const { sceneType, shopMerchantId: merchantId } = wx.$util.getUserInfo()
const clueIndex =
index ?? page.data.menuList.findIndex(e => e.id === 'customer_clue')
if (clueIndex < 0) return
const { data, code } = await commonApi.getCustomerClueRemind({
sceneType,
merchantId: [merchantId]
})
if (code == 0) {
page.setData({
[`menuList[${clueIndex}].tipsNum`]: data
})
}
}
import { createEquityMenuContext } from './context.js'
import { EQUITY_MENU_REGISTRY, ASYNC_MENU_REGISTRY } from './registry.js'
import { registryItemToViewModel } from './toViewModel.js'
import { resolveAsyncMenuProviders } from './asyncProviders.js'
/** 按 id 去重,保留先出现的条目 */
function dedupeById(items) {
const seen = new Set()
const result = []
for (const item of items) {
if (seen.has(item.id)) continue
seen.add(item.id)
result.push(item)
}
return result
}
/** 按 sortVal 升序;无 sortVal 的排到末尾 */
function sortBySortVal(items) {
return [...items].sort((a, b) => (a.sortVal ?? 999) - (b.sortVal ?? 999))
}
/**
* 同步管道:根据 registry.visible 过滤并输出 menuList(不含异步入口)
*
* @param {Object} ctx - createEquityMenuContext 返回值
* @returns {Array} view model 列表,可直接 setData 为 menuList
*/
export function buildEquityMenusSync(ctx) {
const visibleEntries = EQUITY_MENU_REGISTRY.filter(entry => {
if (typeof entry.visible !== 'function') return false
return entry.visible(ctx)
})
const viewModels = visibleEntries.map(entry => registryItemToViewModel(entry))
return sortBySortVal(dedupeById(viewModels))
}
/**
* 完整构建:同步管道 + 并行异步 provider,合并后单次输出 menuList
*
* @param {Object} [options] - 同 createEquityMenuContext 参数
* @param {Object} [options.deps] - 注入 API(单测用),见 asyncProviders
* @returns {Promise<{ menuList: Array, sideEffects: Object }>}
*/
export async function buildEquityMenusAsync(options = {}) {
const ctx = createEquityMenuContext(options)
const syncItems = buildEquityMenusSync(ctx)
let apiResults = {}
try {
apiResults = await resolveAsyncMenuProviders(ctx, options.deps || {})
} catch (err) {
console.error('[buildEquityMenusAsync] async providers failed:', err)
return { menuList: syncItems, sideEffects: {} }
}
ctx.apiResults = apiResults
const asyncEntries = ASYNC_MENU_REGISTRY.filter(entry => {
const providerResult = apiResults[entry.provider]
return providerResult?.visible
})
const asyncViewModels = asyncEntries.map(entry => {
const extras = apiResults[entry.provider]?.extras || {}
return registryItemToViewModel(entry, extras)
})
const dynamicItems = apiResults.dynamicForm?.items || []
const menuList = sortBySortVal(
dedupeById([...syncItems, ...asyncViewModels, ...dynamicItems])
)
const sideEffects = {}
if (apiResults.sideEffects) {
Object.assign(sideEffects, apiResults.sideEffects)
}
for (const key of Object.keys(apiResults)) {
if (apiResults[key]?.sideEffects) {
Object.assign(sideEffects, apiResults[key].sideEffects)
}
}
return { menuList, sideEffects }
}
/** 权益首页场景类型(`userInfo.sceneType`、接口入参 scene) */
export const SCENE_TYPE = 0
/**
* 菜单分区标记(与精品契约对齐;权益首页统一写入 `data.menuList`)
* @type {{ MAIN: 'main', SECONDARY: 'secondary' }}
*/
export const MENU_SECTION = {
MAIN: 'main',
SECONDARY: 'secondary'
}
import { createPolicies } from './policies.js'
/**
* 构建权益首页菜单管道上下文
* @param {Object} [options]
* @param {Object} [options.userInfo]
* @param {boolean} [options.isStaff]
* @param {boolean} [options.mentorFlag]
* @param {number} [options.mode] - Component `properties.mode`,控制 defeat_order
* @param {Array} [options.merchantBrand] - 门店品牌列表,defeatOrder 跳转用
* @param {Object} [options.apiResults]
*/
export function createEquityMenuContext({
userInfo,
isStaff = false,
mentorFlag = false,
mode = 0,
merchantBrand = [],
apiResults = {}
} = {}) {
const app = typeof getApp === 'function' ? getApp() : null
const resolvedIsStaff = isStaff ?? !!app?.globalData?.isStaff
return {
userInfo: userInfo || {},
isStaff: resolvedIsStaff,
mentorFlag: !!mentorFlag,
mode: mode ?? 0,
merchantBrand: merchantBrand || [],
apiResults,
get policies() {
return createPolicies(this)
}
}
}
/**
* 菜单重建指纹(含 mode / mentorFlag / isStaff,供 onShow 脏标记扩展)
* @param {Object} [userInfo]
* @param {Object} [extra]
* @param {boolean} [extra.mentorFlag]
* @param {boolean} [extra.isStaff]
* @param {number} [extra.mode]
*/
export function getMenuFingerprint(userInfo = {}, extra = {}) {
const app = typeof getApp === 'function' ? getApp() : null
const isStaff =
extra.isStaff !== undefined
? extra.isStaff
: !!app?.globalData?.isStaff
const mentorFlag = extra.mentorFlag ? '1' : '0'
const mode = extra.mode !== undefined ? String(extra.mode) : '0'
return [
userInfo.uuid,
userInfo.shopMerchantId,
userInfo.merchantId,
userInfo.loginRole,
userInfo.loginRoleOnSelectMerchant,
userInfo.subLoginUser?.loginRole,
userInfo.subLoginUser?.channelType,
userInfo.isSuper,
isStaff ? '1' : '0',
mentorFlag,
mode
].join('|')
}
/**
* 权益首页 Menu 模块统一导出
*
* 架构说明见 packageEquity/docs/MENU-ARCHITECTURE.md
* 新增菜单见 packageEquity/docs/ADD-MENU-GUIDE-EQUITY.md
*
* @module packageEquity/menu
*/
export { SCENE_TYPE, MENU_SECTION } from './constants.js'
export { createEquityMenuContext, getMenuFingerprint } from './context.js'
export { createPolicies } from './policies.js'
export {
EQUITY_MENU_REGISTRY,
ASYNC_MENU_REGISTRY,
DYNAMIC_FORM_MENU_IDS
} from './registry.js'
export { applyEquityMenuBadges, applyCustomerClueBadge } from './badgeProviders.js'
export { openWorkReportTemp, onWorkReportPopupSelect } from './workReportHandler.js'
export { registryItemToViewModel } from './toViewModel.js'
export { buildEquityMenusSync, buildEquityMenusAsync } from './buildMenus.js'
export { resolveActionType } from './resolveActionType.js'
export { resolveAsyncMenuProviders, resolveCustomerClue } from './asyncProviders.js'
export { createEquityMenuJumpHandler } from './jumpHandlers.js'
/**
* 权益首页菜单跳转 Command Dispatcher(按 item.id / action.type)
*
* 点击时 shutDownTaskApi 副作用:
*
* | 触发方式 | 菜单 id | taskId | scene |
* |----------|---------|--------|-------|
* | `SHUTDOWN_TASK_BY_ID` | `training_materials` | 5 | 0 |
*
* 详见 packageEquity/docs/MENU-ARCHITECTURE.md「跳转副作用」。
*/
import commonApi from '../../api/api.js'
import {
checkDailyReport,
checkStudyTask,
checkAbnormalOrder
} from '../../store/ModalToQueueControl.js'
import { trackDynamicFormMenuEntry } from '../../utils/dynamicFormMenus.js'
import { SCENE_TYPE } from './constants.js'
import { resolveActionType } from './resolveActionType.js'
import { openWorkReportTemp } from './workReportHandler.js'
export { resolveActionType }
const SHUTDOWN_TASK_BY_ID = {
training_materials: 5
}
async function runStaffOrderChecks() {
let staffCheck = await checkDailyReport(true)
if (staffCheck) return true
let staffStudyTask = await checkStudyTask()
if (staffStudyTask) return true
let abnormalOrderCheck = await checkAbnormalOrder()
if (abnormalOrderCheck) return true
return false
}
/**
* 创建页面绑定的菜单点击处理器
* @param {Object} page - packageEquity/pages/index Component 实例(需含 taskId、mentorFlag、merchantBrand)
* @returns {Function} 供 `navGo` 委托的 async dispatch 函数
*/
export function createEquityMenuJumpHandler(page) {
const handlers = {
workReport: async (item, ctx) => {
const { userInfo, mentorFlag } = ctx
if (
wx.$hasPermission?.canViewMentorship?.(userInfo) ||
mentorFlag
) {
wx.$track.setTrackData(0, 'supervisor_daily_page', {}, '', 0)
}
openWorkReportTemp(page, item)
},
navigate: async (item, ctx) => {
const { userInfo } = ctx
const code = item.trackEventCode || item.action?.trackEventCode
if (code === 'scenario_marketplace') {
wx.$track.setTrackData(0, 'scenario_marketplace', {}, '', 0)
}
const url = item.navigateToUrl || item.action?.target
trackDynamicFormMenuEntry(
url,
userInfo?.sceneType ?? SCENE_TYPE,
item.trackEventCode
)
return wx.navigateTo({ url })
},
salaryPerformance: async () => {
return wx.$router.go('packageEquity.collegeScene', {
reLaunchPath: 'packageEquity.equityPage',
tabIndex: 0
})
},
residentTarget: async (item, ctx) => {
return wx.$router.go(item.path || item.action?.target, {
id: ctx.taskId
})
},
createOrderPrompt: async (item, ctx) => {
if (await runStaffOrderChecks()) return
if (
item.beforeClick &&
(await wx.$globalDataFunction[item.beforeClick]())
) {
return
}
page.setData({ showPromptDialog: true })
},
defeatOrder: async (item, ctx) => {
const { merchantBrand } = ctx
let target = item.path || item.action?.target
if (
merchantBrand?.findIndex(i => ['鸿蒙智行'].includes(i.name)) == -1
) {
target = 'packageEquity.createDeafeatOrder'
}
if (await runStaffOrderChecks()) return
wx.$router.go(target, {
scene: SCENE_TYPE,
params: item.params || item.action?.params || {}
})
},
router: async (item, ctx) => {
const { userInfo } = ctx
const target = item.path || item.action?.target
const routerParams = item.params || item.action?.params || {}
if (item.id === 'customer_clue' || target === 'packageEquity.clueList') {
wx.$track.setTrackData(0, 'leads_page', {}, '', 0)
}
if (target === 'packageEquity.start') {
wx.$track.setTrackData(0, 'aiCheck_page', {}, '', 0)
}
if (target === 'tabWorkOrder.mentorshipManage' &&
wx.$hasPermission?.canViewMentorship?.(userInfo)) {
wx.$track.setTrackData(0, 'mentorship_page', {}, '', 0)
}
if (target === 'packageEquity.receptionRecords') {
wx.$track.setTrackData(0, 'reception_records', {}, '', 0)
}
const shutdownTaskId = SHUTDOWN_TASK_BY_ID[item.id]
if (shutdownTaskId) {
commonApi.shutDownTaskApi({
merchantId: userInfo?.default4SStoreInfo?.merchantId,
staffUuid: userInfo?.uuid,
scene: SCENE_TYPE,
taskId: shutdownTaskId
})
}
if (item.id === 'pending_approval') {
return wx.$router.go(target)
}
if (
['packageEquity.extract', 'packageEquity.salaryAppeal', 'packageEquity.missingReception'].includes(
target
) ||
item.params
) {
return wx.$router.go(target, { params: routerParams })
}
return wx.$router.go(target, {
scene: SCENE_TYPE,
params: routerParams
})
}
}
return async function dispatchEquityMenuJump(e) {
const { item } = e.currentTarget.dataset
const { userInfo, taskId, mentorFlag, merchantBrand } = page.data
const ctx = { userInfo, taskId, mentorFlag, merchantBrand }
const actionType = resolveActionType(item)
const handler = handlers[actionType] || handlers.router
return handler(item, ctx)
}
}
/**
* 权益菜单异步 provider 用 API 缓存(in-flight + TTL)
*/
const CACHE_TTL_MS = 60 * 1000
const cache = new Map()
const pending = new Map()
export function clearMenuApiCache() {
cache.clear()
pending.clear()
}
function cacheKey(prefix, id) {
return `${prefix}:${id == null ? '' : String(id)}`
}
function readCache(key) {
const entry = cache.get(key)
if (!entry) return null
if (Date.now() - entry.ts > CACHE_TTL_MS) {
cache.delete(key)
return null
}
return entry.value
}
function writeCache(key, value) {
cache.set(key, { value, ts: Date.now() })
}
async function cachedCall(key, fn) {
const cached = readCache(key)
if (cached !== null) return cached
if (pending.has(key)) return pending.get(key)
const promise = Promise.resolve()
.then(fn)
.then(res => {
writeCache(key, res)
return res
})
.finally(() => {
pending.delete(key)
})
pending.set(key, promise)
return promise
}
export function cachedHasPerformanceConfig(commonApi, merchantId) {
const key = cacheKey('hasPerformanceConfig', merchantId || '')
return cachedCall(key, () =>
commonApi.hasPerformanceConfig({ merchantId: merchantId || '' })
)
}
export function cachedGetStaffTargetTask(commonApi, params) {
const key = cacheKey(
'getStaffTargetTask',
`${params?.merchantId || ''}|${params?.sceneType ?? ''}`
)
return cachedCall(key, () => commonApi.getStaffTargetTaskApi(params))
}
/**
* 新建工单弹窗确认/取消(与 jumpHandlers create_order 对称)
*/
/**
* @param {Object} pageCtx - index Component 实例
* @param {Object} detail - order-prompt-popup confirm 事件 detail
*/
export function handleOrderPromptConfirm(pageCtx, detail = {}) {
const { payFlag, payType } = detail
const { mode } = pageCtx.data
const thisPage = wx.$router.getPageInstance()
const paymentMethod = payFlag != 2 ? 1 : payType
if (payFlag == 1 || payType == 3 || payType == 4 || payType == 6) {
wx.$router.go(mode ? 'createOrderCarQuotationSimple' : 'createOrderCarQuotation', {
paymentMethod
})
} else {
thisPage.tipsEvent && thisPage.tipsEvent()
}
thisPage.setData({ paymentMethod })
}
/** @param {Object} pageCtx */
export function handleOrderPromptCancel(pageCtx) {
pageCtx.setData({ showPromptDialog: false })
}
const perm = () => wx?.$hasPermission || {}
/**
* 从 EquityMenuContext 派生可组合权限谓词,供 registry `visible(ctx)` 使用
*
* @param {Object} ctx - createEquityMenuContext 返回值
* @returns {Record<string, () => boolean>}
*/
export function createPolicies(ctx) {
const { userInfo, isStaff, mentorFlag, mode } = ctx
const p = perm()
return {
/** 超管 */
isSuper: () => p.isSuper?.(userInfo),
/** 非飞行督导 */
isNotMentor: () => p.isNotMentor?.(userInfo),
/** 可多选门店(督导/超管等) */
canSelectMultiStore: () => p.canSelectMultiStore?.(userInfo),
/** 驻店日报相关权限 */
canSelectMultiStoreForStaffDaily: () =>
p.canSelectMultiStoreForStaffDaily?.(userInfo),
canViewMentorship: () => p.canViewMentorship?.(userInfo),
canViewRecruit: () => p.canViewRecruit?.(userInfo),
canViewViolation: () => p.canViewViolation?.(userInfo),
/** 员工或具备驻店日报督导权限 */
staffOrMultiStoreDaily: () =>
isStaff || p.canSelectMultiStoreForStaffDaily?.(userInfo),
/** 非冀联园区 channelType!=9 */
notJiLianChannel: () => userInfo?.subLoginUser?.channelType != 9,
/** 违规查看权限或导师标记 */
mentorOrViolation: () =>
p.canViewViolation?.(userInfo) || mentorFlag,
/** 驻店负责人(loginRoleOnSelectMerchant==4)且为员工 */
isDeliveryTargetRole: () =>
isStaff && userInfo?.loginRoleOnSelectMerchant == 4,
/** properties.mode 为真时展示战败下单 */
hasDefeatOrderMode: () => !!mode
}
}
/**
* 从 view model 解析 action.type(权益首页,按 id / 结构字段,不用 menuText 推断跳转)
*
* 回退链(`item.action?.type` 不存在时依次判断):
* 1. `reportTypeAttr` 或 `path === 'tabWorkOrder.supervisorDaily'` → `workReport`
* 2. `navigateToUrl` → `navigate`
* 3. 无 `path` 且 `menuText === '工资绩效'` → `salaryPerformance`
* 4. 无 `path` 且 `id === 'create_order'` → `createOrderPrompt`
* 5. 默认 → `router`
*
* @param {Object} [item] - WXML dataset 菜单项(view model)
* @returns {string}
*/
export function resolveActionType(item = {}) {
if (item.action?.type) return item.action.type
if (item.reportTypeAttr || item.path === 'tabWorkOrder.supervisorDaily') {
return 'workReport'
}
if (item.navigateToUrl) return 'navigate'
if (!item.path && item.menuText === '工资绩效') return 'salaryPerformance'
if (!item.path && item.id === 'create_order') return 'createOrderPrompt'
return 'router'
}
/**
* 将注册表条目转为权益 WXML 兼容的 view model
*
* - `label` 映射为 `menuText`(模板 `item.menuText`)
* - `action` 映射为 `path` / `navigateToUrl` / `params` 等过渡字段
* - `extras` 合并 provider 运行时字段(noRead、tipsNum 等)
*
* router 类型写 `path` 的方式:
* 1. `action.type` 为 `router` / `workReport` / `defeatOrder`
* 2. `action.target` 为 packageEquity.extract / salaryAppeal / missingReception 时硬编码写 path
* 3. `createOrderPrompt` 写空 `path`
*
* @param {Object} entry - registry 条目
* @param {Object} [extras] - provider 附加字段
* @returns {Object} 可直接 setData 的菜单项
*/
export function registryItemToViewModel(entry, extras = {}) {
const {
id,
label,
icon,
section,
sortVal,
action,
...rest
} = entry
const vm = {
id,
menuText: label,
icon,
section,
sortVal,
...rest,
...extras
}
if (action) {
vm.action = action
if (
action.type === 'router' ||
action.type === 'workReport' ||
action.type === 'defeatOrder'
) {
vm.path = action.target
}
if (action.type === 'createOrderPrompt') {
vm.path = ''
}
if (action.type === 'router' && action.params) {
vm.params = action.params
}
if (action.type === 'navigate') {
vm.navigateToUrl = action.target
if (action.trackEventCode) {
vm.trackEventCode = action.trackEventCode
}
}
if (action.type === 'residentTarget') {
vm.path = action.target
}
if (action.type === 'salaryPerformance') {
vm.path = action.target || ''
}
if (
action.type === 'router' &&
['packageEquity.extract', 'packageEquity.salaryAppeal', 'packageEquity.missingReception'].includes(
action.target
)
) {
vm.path = action.target
if (action.params) vm.params = action.params
}
if (action.type === 'router' && action.usePath) {
vm.path = action.target
}
}
return vm
}
/**
* 权益首页工作日报/周报/月报模版选择与跳转
*/
import { getStaffTemplate } from '~/api/api'
const TIP_TXT = {
daily: '暂无可填日报模版,请找总部运营配置',
weekly: '暂无可填周报模版,请找总部运营配置',
monthly: '暂无可填月报模版,请找总部运营配置'
}
/**
* 拉取报表模版并打开选择弹窗
* @param {Object} page - index Component 实例
* @param {Object} targetItem - 菜单 view model(含 reportTypeAttr / reportTypeVal)
*/
export function openWorkReportTemp(page, targetItem) {
getStaffTemplate({ reportType: targetItem.reportTypeVal }).then(res => {
const { code, data } = res
if (!data?.length) {
wx.$util.showToast(TIP_TXT[targetItem.reportTypeAttr])
return
}
if (code == 0) {
page.setData({
showReportPopup: true,
reportTemplateList: data,
currentReportItem: targetItem || null
})
}
})
}
/**
* 报表模版弹窗确认后跳转
* @param {Object} page
* @param {Object} selectedTemplate
*/
export function onWorkReportPopupSelect(page, selectedTemplate) {
page.setData({ showReportPopup: false })
const item = page.data.currentReportItem
if (!item) return
const params = {
reportTypeAttr: item.reportTypeAttr,
...(selectedTemplate || {})
}
if (item.recordId) {
wx.$util.pointRecord(item.recordId)
}
const eventCode = params?.code?.replace(/-/g, '_') + '_click'
wx.$track.setTrackData(0, eventCode, {}, '', 0)
wx.$router.go(item.path, { params })
}
...@@ -51,8 +51,10 @@ ...@@ -51,8 +51,10 @@
style="position: relative;padding-top:{{ navBarHeight }}px;"> style="position: relative;padding-top:{{ navBarHeight }}px;">
<block wx:if="{{ navBarHeight && showPage }}"> <block wx:if="{{ navBarHeight && showPage }}">
<!-- wx:if="{{ tabIndex == 0}}" wx:if="{{ tabIndex == 1}}" --> <!-- wx:if="{{ tabIndex == 0}}" wx:if="{{ tabIndex == 1}}" -->
<quotation-list id="page-1" <quotation-list wx:if="{{ pageShow[1] }}"
class="pagedetail {{ tabIndex == 1?'':'hide' }}" id="page-1"
class="pagedetail {{ tabIndex == 1 ? '' : 'hide' }}"
show="{{ tabIndex == 1 }}"
invoice-order-info="{{ invoiceOrderInfo }}" invoice-order-info="{{ invoiceOrderInfo }}"
mode="{{ mode }}" mode="{{ mode }}"
nav-bar-height="{{ navBarHeight }}" nav-bar-height="{{ navBarHeight }}"
...@@ -65,15 +67,21 @@ ...@@ -65,15 +67,21 @@
serviceCenterUnreadNum="{{ serviceCenterUnreadNum }}" serviceCenterUnreadNum="{{ serviceCenterUnreadNum }}"
show-screen="{{ showScreen }}" show-screen="{{ showScreen }}"
wait-input-count="{{ waitInputCount }}" /> wait-input-count="{{ waitInputCount }}" />
<equity-list id="page-2" <equity-list wx:if="{{ pageShow[2] }}"
class="pagedetail {{ tabIndex == 2?'':'hide' }}" id="page-2"
class="pagedetail {{ tabIndex == 2 ? '' : 'hide' }}"
show="{{ tabIndex == 2 }}"
nav-bar-height="{{ navBarHeight }}" nav-bar-height="{{ navBarHeight }}"
out-tab-index="{{ tabIndex }}" /> out-tab-index="{{ tabIndex }}" />
<makert-material id="page-3" <makert-material wx:if="{{ pageShow[3] }}"
class="pagedetail {{ tabIndex == 3?'':'hide' }}" id="page-3"
class="pagedetail {{ tabIndex == 3 ? '' : 'hide' }}"
show="{{ tabIndex == 3 }}"
nav-bar-height="{{ navBarHeight }}"></makert-material> nav-bar-height="{{ navBarHeight }}"></makert-material>
<tab-mine id="page-4" <tab-mine wx:if="{{ pageShow[4] }}"
class="pagedetail {{ tabIndex == 4?'':'hide' }}" id="page-4"
class="pagedetail {{ tabIndex == 4 ? '' : 'hide' }}"
show="{{ tabIndex == 4 }}"
nav-bar-height="{{ navBarHeight }}" nav-bar-height="{{ navBarHeight }}"
show-college="{{ enableBusinessSchool }}"></tab-mine> show-college="{{ enableBusinessSchool }}"></tab-mine>
</block> </block>
......
...@@ -7,6 +7,7 @@ import { ...@@ -7,6 +7,7 @@ import {
import carLifeApi from '../../../../carEquityApi' import carLifeApi from '../../../../carEquityApi'
import constantData from '../constant/data' import constantData from '../constant/data'
import { ImgUrl } from '~/config' import { ImgUrl } from '~/config'
import { withTabRefreshInFlight } from '../../../../services/tabRefreshService.js'
const IMG_URL = ImgUrl + '/' const IMG_URL = ImgUrl + '/'
const TABLIST = ['全部', '待补单', '提单失败', '已完成'] const TABLIST = ['全部', '待补单', '提单失败', '已完成']
Component({ Component({
...@@ -34,6 +35,13 @@ Component({ ...@@ -34,6 +35,13 @@ Component({
}, 10) }, 10)
} }
} }
},
/** Tab2 可见性:true 时刷新权益列表/统计 */
show: {
type: Boolean,
observer(n) {
if (n) this.refreshOnShow()
}
} }
}, },
...@@ -103,7 +111,6 @@ Component({ ...@@ -103,7 +111,6 @@ Component({
storeInfo: wx.$util.getUserInfo()?.default4SStoreInfo || {}, storeInfo: wx.$util.getUserInfo()?.default4SStoreInfo || {},
userInfo: wx.$util.getUserInfo() || {} userInfo: wx.$util.getUserInfo() || {}
}) })
this.onLoad(true)
} }
}, },
...@@ -111,18 +118,39 @@ Component({ ...@@ -111,18 +118,39 @@ Component({
* 组件的方法列表 * 组件的方法列表
*/ */
methods: { methods: {
onLoad(noGetList) { /**
let userInfo = wx.$util.getUserInfo() || {} * Tab 切到权益列表时的统一入口;合并同 tick 并发。
* @returns {Promise<void>}
*/
refreshOnShow() {
return withTabRefreshInFlight('equityList', () => this.refreshEquityTab())
},
/** 重置分页并拉 equityOrder.statics、equityOrder.page */
refreshEquityTab() {
const userInfo = wx.$util.getUserInfo() || {}
this.setData({ this.setData({
nothing: false, nothing: false,
pageNum: 1, pageNum: 1,
storeInfo: wx.$util.getUserInfo()?.default4SStoreInfo || {}, storeInfo: userInfo?.default4SStoreInfo || {},
isOrder: !( isOrder: !wx.$hasPermission?.canSelectMultiStore?.(userInfo)
wx.$hasPermission?.canSelectMultiStore?.(userInfo)
)
}) })
this.getTotal() this.getTotal()
if (!noGetList) this.getList(true) this.getList(true)
},
/** @deprecated 兼容外部 selectComponent 调用 */
onLoad(noGetList) {
if (noGetList) {
const userInfo = wx.$util.getUserInfo() || {}
this.setData({
nothing: false,
pageNum: 1,
storeInfo: userInfo?.default4SStoreInfo || {},
isOrder: !wx.$hasPermission?.canSelectMultiStore?.(userInfo)
})
this.getTotal()
return
}
return this.refreshEquityTab()
}, },
onBottomRefresh() { onBottomRefresh() {
this.getList() this.getList()
......
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
</block> </block>
</view> </view>
</view> </view>
<tab-bar tabList="{{ tabList }}" bindclick="tabClick" /> <tab-bar tabList="{{ tabList }}" bindclick="tabClick" suppress-initial-click />
</view> </view>
<!-- <view class="total-box"> <!-- <view class="total-box">
总订单 · 总订单 ·
......
...@@ -25,6 +25,7 @@ const IMG_URL = ImgUrl + '/'; ...@@ -25,6 +25,7 @@ const IMG_URL = ImgUrl + '/';
const IMG_URL2 = ImgUrl + '/'; const IMG_URL2 = ImgUrl + '/';
import carLifeApi from "../../../carEquityApi"; import carLifeApi from "../../../carEquityApi";
import commonApi from "~/api/api"; import commonApi from "~/api/api";
import { withTabRefreshInFlight } from "../../../services/tabRefreshService.js";
function getSceneNameForQuotationItem(item) { function getSceneNameForQuotationItem(item) {
if (!item) return ""; if (!item) return "";
...@@ -48,6 +49,13 @@ Component({ ...@@ -48,6 +49,13 @@ Component({
invoiceOrderInfo: { invoiceOrderInfo: {
type: Object, type: Object,
}, },
/** Tab1 可见性:true 时刷新工单列表/统计(经 tabRefreshService 去重) */
show: {
type: Boolean,
observer(n) {
if (n) this.refreshOnShow()
},
},
}, },
/** /**
* 组件的初始数据 * 组件的初始数据
...@@ -233,10 +241,6 @@ Component({ ...@@ -233,10 +241,6 @@ Component({
storeInfo: wx.$util.getUserInfo()?.default4SStoreInfo || {}, storeInfo: wx.$util.getUserInfo()?.default4SStoreInfo || {},
userInfo: wx.$util.getUserInfo() || {}, userInfo: wx.$util.getUserInfo() || {},
}); });
// console.log(this.data.userInfo)
this.onLoad(true);
// this.getMerchant4SMode()
}, },
resize(res) {}, resize(res) {},
}, },
...@@ -273,21 +277,50 @@ Component({ ...@@ -273,21 +277,50 @@ Component({
console.log(orderInfo, "orderInfo"); console.log(orderInfo, "orderInfo");
wx.$router.go("updateOrderInfo", orderInfo.id); wx.$router.go("updateOrderInfo", orderInfo.id);
}, },
// 获取数据 /**
onLoad(noGetList) { * Tab 切到工单管理时的统一入口;合并同 tick 并发。
let userInfo = wx.$util.getUserInfo() || {}; * @returns {Promise<void>}
*/
refreshOnShow() {
return withTabRefreshInFlight("quotation", () => this.refreshQuotationTab())
},
/**
* 重置列表态并拉 quotation.page、order.status.statistics、merchant.info。
* 每次 show=true 都会执行(无 TTL 跳过)。
*/
refreshQuotationTab() {
const userInfo = wx.$util.getUserInfo() || {}
this.setData({ this.setData({
nothing: false, nothing: false,
currentPage: 1, currentPage: 1,
storeInfo: wx.$util.getUserInfo()?.default4SStoreInfo || {}, storeInfo: userInfo?.default4SStoreInfo || {},
isOrder: !wx.$hasPermission?.canSelectMultiStore?.(userInfo), isOrder: !wx.$hasPermission?.canSelectMultiStore?.(userInfo),
list: [], list: [],
}); })
// this.getTotal() this.getList(true)
if (!noGetList) this.getList(true); this.getOrderStatistics()
this.getOrderStatistics(); if (!wx.$hasPermission?.canViewViolation?.(userInfo)) {
if (!wx.$hasPermission?.canViewViolation?.(userInfo)) this.getMerchantCarBrandList(); this.getMerchantCarBrandList()
}
},
/** @deprecated 兼容外部 selectComponent 调用 */
onLoad(noGetList) {
if (noGetList) {
const userInfo = wx.$util.getUserInfo() || {}
this.setData({
nothing: false,
currentPage: 1,
storeInfo: userInfo?.default4SStoreInfo || {},
isOrder: !wx.$hasPermission?.canSelectMultiStore?.(userInfo),
list: [],
})
this.getOrderStatistics()
if (!wx.$hasPermission?.canViewViolation?.(userInfo)) {
this.getMerchantCarBrandList()
}
return
}
return this.refreshQuotationTab()
}, },
async handleClickOrderBtn(e) { async handleClickOrderBtn(e) {
// 校验是否填写昨日日报 // 校验是否填写昨日日报
...@@ -569,7 +602,6 @@ Component({ ...@@ -569,7 +602,6 @@ Component({
zyPayStatus: e.detail == tabList?.length - 1 && !e.zyPayStatus ? 1 : e.zyPayStatus ? e.zyPayStatus : "", zyPayStatus: e.detail == tabList?.length - 1 && !e.zyPayStatus ? 1 : e.zyPayStatus ? e.zyPayStatus : "",
}); });
this.search(); this.search();
this.getOrderStatistics();
}, },
// 按钮 // 按钮
async handleClickBtn(e) { async handleClickBtn(e) {
......
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
</view> </view>
</view> </view>
<view> <view>
<tab-bar tabList="{{ tabList }}" bindclick="tabClick" scroll activeIndex="{{ tabIndex }}" /> <tab-bar tabList="{{ tabList }}" bindclick="tabClick" scroll activeIndex="{{ tabIndex }}" suppress-initial-click />
</view> </view>
</view> </view>
<view wx:if="{{ flag }}" class="order-box"> <view wx:if="{{ flag }}" class="order-box">
......
Component({
properties: {
listData: { type: Array, value: [] },
loaded: { type: Boolean, value: false },
nothing: { type: Boolean, value: false },
showScreen: { type: Boolean, value: false },
isScrollTop: { type: Boolean, value: false },
searchForm: { type: Object, value: {} },
userInfo: { type: Object, value: {} },
showEmployeeName: { type: Boolean, value: false },
isShowDefeatBtn: { type: Boolean, value: true },
recordTabList: { type: Array, value: [] },
IMG_URL: { type: String, value: '' }
},
methods: {
onFilterTap() {
this.triggerEvent('filter')
},
onTabClick(e) {
this.triggerEvent('tab', e.detail)
},
onDetailTap(e) {
this.triggerEvent('detail', { item: e.currentTarget.dataset.item })
},
onMoreTap() {
this.triggerEvent('more')
}
}
})
{
"component": true,
"usingComponents": {
"record-item": "../record-item/recordItem",
"record-tab": "../recordTab/recordTab"
}
}
<wxs src="../../../../index.wxs" module="filter" />
<wxs src="../../../../../utils/permission.wxs" module="perm" />
<view class="receive-list">
<view class="screen-box {{ showScreen ? '' : 'sticky-screen' }} {{ isScrollTop ? 'bg-white' : '' }}">
<view>
<text class="name text-hide">{{ searchForm.merchantNames.length > 1 ? "部分门店" : searchForm.merchantNames.length ? filter.filterMerchantName(searchForm.merchantNames) : !perm.hasPermission.canViewViolation(userInfo) ? userInfo.default4SStoreInfo.merchantName || "全部门店" : "全部门店" }}</text>
</view>
<view bindtap="onFilterTap">
<text class="text">筛选</text><gl-image webp src="/equity/screen-icon.png" />
</view>
</view>
<view class="tab-box">
<record-tab tabList="{{ recordTabList }}" bindclick="onTabClick"></record-tab>
</view>
<view class="list-box">
<block wx:if="{{ filter.isShowEmpty(listData) }}">
<block wx:for="{{ listData }}"
wx:key="date"
wx:if="{{ item.receptionStaticInfoDTOList.length }}">
<view class="date-section {{ showScreen ? '' : 'sticky-date-section' }}">
<text class="date">{{ item.staticDateStr }}</text>
</view>
<block wx:for="{{ item.receptionStaticInfoDTOList }}"
wx:key="time"
wx:for-index="subIndex"
wx:for-item="record">
<view class="record-card"
bindtap="onDetailTap"
data-item="{{ record }}">
<view class="record-card-top">
<text class="round-dot"
style="font-size: {{ subIndex + 1 > 99 ? 'var(--fontSize16)' : 'var(--fontSize20)' }}">{{ subIndex + 1 }}</text>
<view class="card-line"></view>
</view>
<view class="card-item">
<record-item record="{{ record }}"
showEmployeeName="{{ showEmployeeName }}"
isShowDefeatBtn="{{ isShowDefeatBtn }}"
hideScore></record-item>
</view>
</view>
</block>
</block>
</block>
<block wx:if="{{ !filter.isShowEmpty(listData) && loaded }}">
<view class="empty-box">
<image class="no-data-img" src="{{ IMG_URL }}empty_data.png" />
<view class="list-not-text">近七天暂无接待记录数据</view>
</view>
</block>
<block wx:if="{{ nothing }}">
<view class="show-more-btn" bindtap="onMoreTap">查看更多</view>
</block>
<view class="seize-box"></view>
</view>
</view>
/* packageEquity/pages/index/components/reception-timeline/reception-timeline.wxss */
.receive-list {
margin-top: var(--fontSize20);
background: #f7f8fa;
}
.screen-box {
box-sizing: border-box;
background: #f7f8fa;
padding: 0 var(--fontSize28);
width: 100%;
height: var(--fontSize80);
display: flex;
align-items: center;
justify-content: space-between;
}
.screen-box.sticky-screen {
position: sticky;
top: 0;
left: 0;
z-index: 100;
}
.screen-box.bg-white {
background: #ffffff;
}
.screen-box view {
display: flex;
align-items: flex-end;
}
.screen-box .name {
color: #292d33;
font-size: var(--fontSize24);
width: var(--fontSize430);
}
.screen-box .name.text-hide {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.screen-box .text {
font-size: var(--fontSize24);
color: #292d33;
}
.screen-box image {
width: var(--fontSize36);
height: var(--fontSize36);
}
.tab-box {
position: sticky;
top: var(--fontSize80);
left: 0;
z-index: 100;
background: #f7f8fa;
}
.list-box {
padding: 0 var(--fontSize8);
}
.list-box .date-section {
height: var(--fontSize72);
line-height: var(--fontSize70);
padding-left: var(--fontSize32);
background: #f7f8fa;
display: flex;
align-items: center;
}
.list-box .date-section.sticky-date-section {
position: sticky;
top: var(--fontSize168);
left: 0;
z-index: 100;
}
.list-box .date-section .date {
flex-shrink: 0;
width: var(--fontSize146);
font-size: var(--fontSize28);
color: #292d33;
font-weight: 500;
}
.list-box .record-card-top {
display: flex;
flex-flow: column;
align-items: center;
padding-top: var(--fontSize8);
margin-right: var(--fontSize4);
}
.list-box .record-card-top .round-dot {
width: var(--fontSize28);
height: var(--fontSize36);
display: flex;
align-items: center;
justify-content: center;
border-radius: var(--fontSize14);
background: #5a5e66;
color: #ffffff;
}
.list-box .record-card {
display: flex;
margin: var(--fontSize16) 0;
padding: 0 var(--fontSize20) 0 var(--fontSize4);
position: relative;
}
.list-box .record-card .card-line {
position: absolute;
top: var(--fontSize44);
left: var(--fontSize14);
width: var(--fontSize3);
height: var(--fontSize280);
background: repeating-linear-gradient(to bottom, transparent, transparent var(--fontSize10), #dee0e3 var(--fontSize10), #dee0e3 var(--fontSize20));
}
.list-box .record-card .card-item {
width: calc(100% - var(--fontSize27));
}
.list-box .show-more-btn {
margin: var(--fontSize80) auto;
text-align: center;
width: var(--fontSize296);
padding: var(--fontSize8) 0;
border: var(--fontSize1) solid #c3c3c3;
border-radius: var(--fontSize26);
}
.list-box .seize-box {
width: 100%;
height: var(--fontSize1);
}
.list-box .empty-box {
padding-top: var(--fontSize14);
display: flex;
flex-flow: column;
justify-content: center;
align-items: center;
}
.list-box .empty-box .no-data-img {
width: var(--fontSize160);
height: var(--fontSize160);
}
.list-box .empty-box .list-not-text {
margin-top: var(--fontSize10);
font-size: var(--fontSize24);
color: #bec1c7;
}
...@@ -5,33 +5,32 @@ ...@@ -5,33 +5,32 @@
display: flex; display: flex;
box-sizing: border-box; box-sizing: border-box;
padding: 0 var(--fontSize40); padding: 0 var(--fontSize40);
&-item {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
flex-shrink: 0;
color: #5a5e66;
font-size: var(--fontSize28);
font-weight: 700;
text-align: center;
position: relative;
transition: all .15s;
}
.active {
color: #347bff;
&::after {
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
content: '';
width: var(--fontSize64);
height: var(--fontSize4);
border-radius:var(--fontSize2) var(--fontSize2) 0 0;
background: #347bff;
}
}
}
\ No newline at end of file \ No newline at end of file
}
.record-tab-item {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
flex-shrink: 0;
color: #5a5e66;
font-size: var(--fontSize28);
font-weight: 700;
text-align: center;
position: relative;
transition: all 0.15s;
}
.record-tab .active {
color: #347bff;
}
.record-tab .active::after {
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
content: "";
width: var(--fontSize64);
height: var(--fontSize4);
border-radius: var(--fontSize2) var(--fontSize2) 0 0;
background: #347bff;
}
Component({
properties: {
staticData: { type: Object, value: {} },
itemDataList: { type: Array, value: [] },
current: { type: Number, value: 0 },
isStaff: { type: Boolean, value: false },
serviceCenterUnreadNum: { type: Number, value: 0 }
},
methods: {
onSwiperChange(e) {
this.triggerEvent('change', { current: e.detail.current })
},
onServiceCenterTap() {
this.triggerEvent('servicecenter')
}
}
})
<view class="swiper-wrap">
<view wx:if="{{ isStaff }}"
class="server-center-tips-text {{ serviceCenterUnreadNum ? 'has-unread' : '' }}"
bind:tap="onServiceCenterTap">
<view class="wrapper">
<image class="icons" src="/images/server-center-icons.png"></image>
<view class="text">服务中心</view>
</view>
</view>
<swiper bindchange="onSwiperChange">
<block wx:for="{{ 3 }}" wx:key="index">
<swiper-item>
<view class="swiper-item">
<view class="total-wrap">
<view class="item">
<view class="title">
{{ current == 0 ? "今日" : current == 1 ? "本月" : "累计" }}产值
</view>
<view class="number">
<text class="unit">¥</text><text>{{ staticData.totalOutputValue || 0 }}</text>
</view>
</view>
<view class="item">
<view class="title">转化率</view>
<view class="number">
<text>{{ staticData.conversionRate > 100 ? 100 : staticData.conversionRate || 0 }}</text><text class="units">%</text>
</view>
</view>
</view>
<view class="custom-statistic">
<view class="customItem"
wx:for="{{ itemDataList }}"
wx:key="index"
wx:for-index="index">
<block wx:if="{{ item.index == 2 || item.index == 1 }}">
<view class="label">
<text>{{ item.label }}</text><text>/{{ item.waitlabel }}</text>
</view>
<view class="number">
<view class="firstValue">{{ staticData[item.value] || 0 }}</view>
<view class="lastValue">/{{ staticData[item.waitValue] || 0 }}</view>
</view>
</block>
<block wx:else>
<view class="label">{{ item.label }}</view>
<view class="number">
<text class="unit" wx:if="{{ item.unit }}">¥</text>
<view>{{ staticData[item.value] || 0 }}</view>
</view>
</block>
</view>
</view>
</view>
</swiper-item>
</block>
</swiper>
<view class="dots">
<view wx:for="{{ 3 }}"
wx:key="index"
wx:for-index="idx"
class="dot {{ current == idx ? 'active' : '' }}"></view>
</view>
</view>
/* packageEquity/pages/index/components/statistics-swiper/statistics-swiper.wxss */
.swiper-wrap {
margin-bottom: var(--fontSize16);
position: relative;
}
.swiper-wrap .server-center-tips-text {
position: absolute;
right: 16rpx;
top: 8px;
color: #2c66f7;
background-color: white;
font-size: 28rpx;
font-weight: 500;
border-radius: 345px 0 0 345px;
z-index: 2;
}
.swiper-wrap .server-center-tips-text .wrapper {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
padding: 10rpx;
border-radius: 345px 0 0 345px;
background: linear-gradient(90deg, rgba(44, 102, 247, 0.1019607843) 0%, rgba(44, 102, 247, 0) 100%);
}
.swiper-wrap .server-center-tips-text .wrapper .icons {
z-index: 3;
width: 32rpx;
height: 32rpx;
margin-right: 8rpx;
}
.swiper-wrap .server-center-tips-text.has-unread::after {
content: "";
width: 12rpx;
height: 12rpx;
background-color: #f24724;
border-radius: 50%;
position: absolute;
top: 2rpx;
right: -8rpx;
}
.swiper-wrap swiper {
background: #ffffff;
box-shadow: 0 24rpx 24rpx -12rpx rgba(211, 217, 230, 0.5019607843);
border-radius: var(--fontSize20);
height: var(--fontSize392);
margin-bottom: var(--fontSize16);
padding: var(--fontSize16);
box-sizing: border-box;
}
.swiper-wrap .dots {
display: flex;
align-items: center;
justify-content: center;
}
.swiper-wrap .dots .dot {
width: var(--fontSize16);
height: var(--fontSize8);
background: #c9c9c9;
border-radius: var(--fontSize8);
margin-right: var(--fontSize8);
}
.swiper-wrap .dots .active {
width: var(--fontSize32);
background: #2c66f7;
}
.total-wrap {
display: flex;
margin: var(--fontSize16) var(--fontSize56);
align-items: center;
}
.total-wrap .item {
flex: 1;
}
.total-wrap .item .title {
font-weight: 500;
font-size: var(--fontSize28);
color: #292d33;
margin-bottom: var(--fontSize8);
}
.total-wrap .item .number {
font-weight: 700;
font-size: var(--fontSize48);
color: #2c66f7;
white-space: nowrap;
font-family: numberNor;
line-height: var(--fontSize56);
}
.total-wrap .item .unit {
font-size: var(--fontSize28);
color: #2c66f7;
margin-right: var(--fontSize4);
}
.total-wrap .item .units {
font-size: var(--fontSize28);
color: #2c66f7;
margin-left: var(--fontSize4);
}
.custom-statistic {
padding: var(--fontSize20) var(--fontSize56) var(--fontSize4);
display: flex;
flex-wrap: wrap;
background: #f7f8fa;
border-radius: var(--fontSize16);
}
.custom-statistic .customItem {
width: 50%;
padding-bottom: var(--fontSize16);
}
.custom-statistic .customItem .label {
font-weight: 400;
font-size: var(--fontSize24);
color: #999ea8;
line-height: var(--fontSize36);
}
.custom-statistic .customItem .number {
font-weight: 700;
font-size: var(--fontSize36);
white-space: nowrap;
display: flex;
color: #292d33;
align-items: flex-end;
font-family: numberNor;
margin: var(--fontSize4);
}
.custom-statistic .customItem .number .unit {
font-size: var(--fontSize24);
margin-right: var(--fontSize4);
height: var(--fontSize28);
}
.custom-statistic .customItem .number .firstValue {
margin-right: var(--fontSize4);
}
.custom-statistic .customItem .number .lastValue {
height: var(--fontSize28);
font-size: var(--fontSize24);
}
Component({
properties: {
isWait: { type: Boolean, value: false },
todoList: { type: Array, value: [] },
stodoList: { type: Array, value: [] },
missingRecordTodoList: { type: Array, value: [] },
ispopUp: { type: Boolean, value: true },
todos: { type: Object, value: {} },
IMG_URL: { type: String, value: '' }
},
methods: {
onGoto(e) {
this.triggerEvent('goto', { id: e.currentTarget.dataset.id })
},
onClose(e) {
this.triggerEvent('close', { id: e.currentTarget.dataset.id })
},
onPackup() {
this.triggerEvent('packup')
},
onMissing() {
this.triggerEvent('missing')
}
}
})
<block wx:if="{{ isWait && (todoList.length || missingRecordTodoList.length) }}">
<view class="todo-list">
<view class="title">今日待办·{{ todoList.length + missingRecordTodoList.length }}</view>
<view class="todo-items">
<block wx:if="{{ todoList.length }}">
<view class="todo-item"
wx:key="idx"
wx:for="{{ ispopUp ? todoList : stodoList }}"
wx:for-index="idx">
<view class="todo-item-title">
<image src="{{ IMG_URL }}{{ item.taskType == '1' ? 'warn' : 'task' }}.png" />
<text>{{ todos[item.taskId] }}</text>
</view>
<view class="todo-item-info">{{ item.content }}</view>
<view class="todo-item-btn"
wx:if="{{ item.taskId == 2 }}"
bindtap="onGoto"
data-id="{{ item.taskId }}">去开单</view>
<view class="todo-item-btn"
wx:elif="{{ item.taskId == 4 }}"
data-id="{{ item.taskId }}"
bindtap="onGoto">去处理</view>
<view class="todo-item-btn"
wx:elif="{{ item.taskId == 1 }}"
data-id="{{ item.taskId }}"
bindtap="onGoto">去填写</view>
<view class="todo-item-btn"
wx:else
bindtap="onClose"
data-id="{{ item.taskId }}">关闭提醒</view>
</view>
</block>
<block wx:if="{{ missingRecordTodoList.length }}">
<view class="todo-item">
<view class="todo-item-title">
<image src="{{ IMG_URL }}warn.png" /><text>接待缺失报备</text>
</view>
<view class="todo-item-info">请报备缺失接待客户的原因</view>
<view class="todo-item-btn" bindtap="onMissing">去报备</view>
</view>
</block>
</view>
<view class="pack-up {{ !ispopUp ? 'pack-up-active' : '' }}"
wx:if="{{ missingRecordTodoList.length + todoList.length > 2 }}"
bindtap="onPackup">
<image src="{{ IMG_URL }}pack-up.png" />
</view>
</view>
</block>
/* packageEquity/pages/index/components/todo-panel/todo-panel.wxss */
.todo-list {
background: #ffffff;
border-radius: var(--fontSize16);
margin-bottom: var(--fontSize16);
padding: var(--fontSize32) var(--fontSize32) var(--fontSize48) var(--fontSize32);
position: relative;
}
.todo-list .title {
font-weight: 400;
font-size: var(--fontSize28);
color: #999ea8;
margin-bottom: var(--fontSize8);
}
.todo-list .todo-items {
overflow: hidden;
display: flex;
flex-wrap: wrap;
}
.todo-list .todo-items .todo-item {
position: relative;
padding: var(--fontSize24) 0;
box-sizing: border-box;
width: 100%;
}
.todo-list .todo-items .todo-item .todo-item-title {
display: flex;
align-items: center;
margin-bottom: var(--fontSize4);
font-size: var(--fontSize28);
color: #1a1a1a;
}
.todo-list .todo-items .todo-item .todo-item-title image {
width: var(--fontSize32);
height: var(--fontSize32);
margin-right: var(--fontSize11);
}
.todo-list .todo-items .todo-item .todo-item-info {
font-size: var(--fontSize24);
color: #999ea8;
max-width: var(--fontSize500);
margin-left: var(--fontSize43);
}
.todo-list .todo-items .todo-item .todo-item-btn {
padding: var(--fontSize10) var(--fontSize16);
background: #f7f8fa;
border-radius: var(--fontSize28);
font-size: var(--fontSize26);
color: #2c66f7;
position: absolute;
right: 0;
top: var(--fontSize36);
}
.todo-list .pack-up {
width: var(--fontSize32);
height: var(--fontSize32);
position: absolute;
left: 50%;
transform: translateX(-50%);
}
.todo-list .pack-up image {
width: 100%;
}
.todo-list .pack-up-active {
transform: rotate(180deg);
margin-left: -var(--fontSize32);
}
...@@ -2,9 +2,10 @@ ...@@ -2,9 +2,10 @@
"component": true, "component": true,
"usingComponents": { "usingComponents": {
"task-dialog": "/components/TaskDialog/TaskDialog", "task-dialog": "/components/TaskDialog/TaskDialog",
"record-item": "./components/record-item/recordItem",
"record-tab": "./components/recordTab/recordTab",
"order-prompt-popup": "/components/orderPromptPop/orderPromptPop", "order-prompt-popup": "/components/orderPromptPop/orderPromptPop",
"report-template-popup": "/components/report-template-popup/report-template-popup" "report-template-popup": "/components/report-template-popup/report-template-popup",
"statistics-swiper": "./components/statistics-swiper/statistics-swiper",
"todo-panel": "./components/todo-panel/todo-panel",
"reception-timeline": "./components/reception-timeline/reception-timeline"
} }
}
\ No newline at end of file \ No newline at end of file
}
/* packageEquity/pages/index/index.wxss */
.layout_box {
position: relative;
width: 100%;
height: 100%;
padding-top: var(--fontSize6);
}
.content_box {
box-sizing: border-box;
margin: 0 var(--fontSize20);
box-shadow: 0 var(--fontSize24) var(--fontSize24) -var(--fontSize12) rgba(211, 217, 230, 0.5019607843);
border-radius: var(--fontSize20);
}
.menu_box {
display: grid;
grid-template-columns: repeat(4, minmax(var(--fontSize100), 1fr));
justify-content: space-between;
align-items: center;
padding: var(--fontSize16) 0;
background: #ffffff;
border-radius: var(--fontSize16);
}
.menu_box .menu_item {
padding-bottom: var(--fontSize16);
display: flex;
flex-flow: column;
align-items: center;
position: relative;
}
.menu_box .menu_item .icon {
width: var(--fontSize100);
height: var(--fontSize100);
}
.menu_box .menu_item .text {
font-size: var(--fontSize24);
color: #292d33;
}
.hot_icon {
position: absolute;
right: var(--fontSize46);
top: 0;
min-width: var(--fontSize24);
height: var(--fontSize24);
background: #f24724;
border-radius: var(--fontSize16);
color: #ffffff;
font-size: var(--fontSize20);
display: flex;
justify-content: center;
align-items: center;
padding: var(--fontSize2);
border: var(--fontSize2) solid #ffffff;
}
.bubble_icon {
position: absolute;
right: var(--fontSize14);
top: var(--fontSize12);
width: var(--fontSize16);
height: var(--fontSize16);
background: #f24724;
border-radius: var(--fontSize16);
}
.tips {
display: flex;
align-items: center;
justify-content: space-between;
font-size: var(--fontSize28);
color: #ffffff;
margin: 0 40rpx var(--fontSize16) 40rpx;
}
.tips .tips-text {
max-width: 100%;
font-size: var(--fontSize24);
flex-shrink: 0;
}
@media screen and (min-width: 768px) and (orientation: landscape) {
.menu_box {
grid-template-columns: repeat(7, var(--fontSize100)) !important;
}
}
const IMG_URL = 'https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/' const IMG_URL = 'https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/'
import { materialListApi, leavePageTrack } from "../../api/api" import { materialListApi, leavePageTrack } from "../../api/api"
import commonApi from "~/api/api"; import commonApi from "~/api/api";
import { withTabRefreshInFlight } from '../../../../services/tabRefreshService.js'
let currentTabType = 'video'; let currentTabType = 'video';
Component({ Component({
properties: { properties: {
navBarHeight: Number navBarHeight: Number,
/** Tab3 可见性:true 刷新素材列表,false 走 onHide 清理 */
show: {
type: Boolean,
observer(n) {
if (n) {
this.refreshOnShow()
} else {
this.onHide()
}
}
}
},
lifetimes: {
attached() {
this.setData({
userInfo: wx.$util.getUserInfo() || {}
})
}
}, },
data: { data: {
IMG_URL, IMG_URL,
...@@ -31,20 +50,50 @@ Component({ ...@@ -31,20 +50,50 @@ Component({
isNeedFixed: false isNeedFixed: false
}, },
methods: { methods: {
async onLoad() { /**
* Tab 切到培训素材时的统一入口;合并同 tick 并发。
* @returns {Promise<void>}
*/
refreshOnShow() {
return withTabRefreshInFlight('materials', () => this.refreshMaterialsTab())
},
/**
* 每次 show=true 刷新 materialListApi;首进走 bootstrap 动画与埋点。
* @returns {Promise<void>}
*/
async refreshMaterialsTab() {
if (!this._materialsBootstrapped) {
this._materialsBootstrapped = true
return this.bootstrapMaterialsTab()
}
this.setData({
userInfo: wx.$util.getUserInfo() || {}
})
this.getListData()
this.startMaterialsInterval()
},
/** 素材 Tab 首次挂载:关闭提醒、延迟展示、启动 tab 尺寸轮询 */
async bootstrapMaterialsTab() {
this.pdfPageTrack() this.pdfPageTrack()
this.closeRemind() this.closeRemind()
setTimeout(async () => { setTimeout(() => {
this.setData({ this.setData({
showPage: true, showPage: true,
userInfo: wx.$util.getUserInfo() || {} userInfo: wx.$util.getUserInfo() || {}
}) })
// await this.getScroviewHeight()
this.getListData() this.getListData()
}, 300); }, 300)
this.startMaterialsInterval()
},
startMaterialsInterval() {
if (this.intaval) return
this.intaval = setInterval(() => { this.intaval = setInterval(() => {
this.selectComponent('#tabID').resize(); this.selectComponent('#tabID')?.resize()
}, 500); }, 500)
},
/** @deprecated 兼容外部 selectComponent 调用 */
async onLoad() {
return this.refreshMaterialsTab()
}, },
closeRemind() { closeRemind() {
let userInfo = wx.$util.getUserInfo() let userInfo = wx.$util.getUserInfo()
......
/**
* 权益首页产值看板:日期区间与响应格式化
*/
import NP from 'number-precision'
/**
* @param {'today'|'month'|'total'} dataActive
* @param {Date} [now]
*/
export function buildOutputValueDateRange(dataActive = 'today', now = new Date()) {
const todayStr =
typeof now.format === 'function'
? now.format('yyyy-MM-dd')
: now.toISOString().slice(0, 10)
const thisMonth = new Date(new Date(now).setDate(1))
const thisMonthStr =
typeof thisMonth.format === 'function'
? thisMonth.format('yyyy-MM-dd')
: thisMonth.toISOString().slice(0, 10)
const ranges = {
today: {
startTime: `${todayStr} 00:00:00`,
endTime: `${todayStr} 23:59:59`
},
month: {
startTime: `${thisMonthStr} 00:00:00`,
endTime: `${todayStr} 23:59:59`
},
total: {
startTime: '',
endTime: ''
}
}
return ranges[dataActive] || ranges.today
}
/** outputValueStatistics 响应 → staticData */
export function normalizeOutputValueStats(data = {}) {
if (!data || typeof data !== 'object') return {}
const result = { ...data }
result.conversionRate = NP.times(result.conversionRate || 0, 100)
result.avgPrice = NP.round(NP.divide(result.avgPrice || 0, 100), 0)
result.totalOutputValue = NP.round(result.totalOutputValue || 0, 0)
result.avgQuotationPrice = NP.round(result.avgQuotationPrice || 0, 0)
return result
}
/** getQuotationStatistics 响应 → statisticsObj 展示字段 */
export function normalizeQuotationStatistics(raw = {}) {
if (!raw || typeof raw !== 'object') return {}
const splitTurnover = (cents) => {
if (!cents) return { int: '0', decimal: '00' }
const fixed = ((cents / 100).toFixed(2) + '').split('.')
return { int: fixed[0], decimal: fixed[1] }
}
const today = splitTurnover(raw.todayTurnover)
const total = raw.totalTurnover
? { int: String(Math.round(raw.totalTurnover / 100)), decimal: splitTurnover(raw.totalTurnover).decimal }
: { int: '0', decimal: '00' }
const month = splitTurnover(raw.monthTurnover)
return {
...raw,
todayTurnover: today.int,
todayTurDecimal: today.decimal,
totalTurnover: total.int,
totalTurDecimal: total.decimal,
monthTurnover: month.int
}
}
/**
* 权益首页(Tab0)看板/待办刷新去重。
*
* 与 {@link ./tabRefreshService.js} 的区别:
* - 本模块用于 home `refreshEquityHome`,带请求指纹(dataActive + 门店 + isWait)
* - 仅 in-flight 合并同 tick 并发,**不做 TTL 跳过**,保证每次切回 Tab0 都会刷新
*
* @module packageEquity/services/homeRefreshService
*/
/** @type {Promise<void>|null} 进行中的刷新 Promise */
let inFlight = null
/** @type {string|null} 进行中请求对应的指纹 */
let inFlightFingerprint = null
/**
* 清空单测/调试用的 in-flight 状态。
*/
export function clearHomeRefreshState() {
inFlight = null
inFlightFingerprint = null
}
/**
* 构建首页刷新指纹,用于合并同一上下文下的并发 refreshEquityHome。
*
* @param {Object} [ctx]
* @param {string} [ctx.dataActive] - 看板维度:today | month | total
* @param {string|number} [ctx.shopMerchantId] - 当前 4S 门店 ID
* @param {boolean} [ctx.isWait] - 是否单店员工(决定是否拉待办)
* @returns {string}
*/
export function buildHomeRefreshFingerprint(ctx = {}) {
const dataActive = ctx.dataActive ?? 'today'
const merchantId = ctx.shopMerchantId ?? ''
const isWait = ctx.isWait ? '1' : '0'
return `${dataActive}|${merchantId}|${isWait}`
}
/**
* 在 in-flight 去重下执行首页刷新逻辑。
*
* 触发场景:
* - home `properties.show` observer(Tab 切回 0)
* - equityPage `onShow`(子页返回且仍在 Tab0,show 未变化时补刷)
*
* @param {string} fingerprint - {@link buildHomeRefreshFingerprint} 返回值
* @param {{ force?: boolean }} [options] - 保留扩展;当前无 TTL,force 与不 force 行为一致
* @param {() => Promise<void>|void} fn - 实际刷新:看板 + 待办 + 可选菜单/接待
* @returns {Promise<void>}
*/
export async function withHomeRefreshDedup(fingerprint, options, fn) {
if (inFlight && inFlightFingerprint === fingerprint) {
return inFlight
}
const promise = Promise.resolve()
.then(fn)
.finally(() => {
if (inFlight === promise) {
inFlight = null
inFlightFingerprint = null
}
})
inFlight = promise
inFlightFingerprint = fingerprint
return promise
}
/**
* 权益首页接待记录列表:查询参数、合并分页、脏标记
*/
/**
* 构建接待记录查询参数(原 getParams)
* @param {Object} ctx
* @param {Object} ctx.searchForm
* @param {boolean} ctx.isFilterDefeat
* @param {boolean} ctx.isFilterUpgrade
* @param {Array} ctx.storeRangeList
* @param {number} ctx.violationStatus
* @param {Object} ctx.userInfo
* @param {Object} ctx.hasPermission - { isSuper, canSelectMultiStore }
*/
export function buildReceptionQueryParams(ctx = {}) {
const {
searchForm = {},
isFilterDefeat,
isFilterUpgrade,
storeRangeList = [],
violationStatus,
userInfo = {},
hasPermission = {}
} = ctx
const timestamp = Date.now()
const sevenDaysAgoTimestamp = timestamp - 6 * 24 * 60 * 60 * 1000
const sevenDaysAgoDate =
typeof Date.prototype.format === 'function'
? new Date().format('yyyy-MM-dd')
: new Date().toISOString().slice(0, 10)
const orderResult = searchForm.orderResult?.length
? searchForm.orderResult
: (isFilterDefeat ? [2] : []).concat(isFilterUpgrade ? [1] : [])
let merchantNo
if (searchForm.merchantNo?.length) {
merchantNo = searchForm.merchantNo
} else if (hasPermission.isSuper?.(userInfo)) {
merchantNo = storeRangeList.map(v => v.merchantNo).filter(Boolean)
} else if (hasPermission.canSelectMultiStore?.(userInfo)) {
merchantNo = ''
} else {
merchantNo = [userInfo?.default4SStoreInfo?.merchantId]
}
return {
violationStatus,
startDateTime:
searchForm.startDateTime ||
new Date(sevenDaysAgoTimestamp).format?.('yyyy-MM-dd') ||
new Date(sevenDaysAgoTimestamp).toISOString().slice(0, 10),
endDateTime: searchForm.endDateTime || sevenDaysAgoDate,
customerName: searchForm.customerName || '',
phoneNumber: searchForm.customerName || '',
qualityCheckScoreBegin: searchForm.qualityCheckScoreBegin,
qualityCheckScoreEnd: searchForm.qualityCheckScoreEnd,
customerTypes: searchForm.customerTypes,
carModels: searchForm.carModels,
orderResult,
merchantNo,
staffUuids: hasPermission.canSelectMultiStore?.(userInfo)
? searchForm.staffUuids
: [userInfo.uuid]
}
}
/** 接待日期分组初始化 */
export function normalizeReceptionDateSections(data = []) {
return (data || []).map(val => ({
...val,
receptionStaticInfoDTOList: [],
staticDateStr: `${new Date(val.staticDate).getMonth() + 1}月${new Date(val.staticDate).getDate()}日`
}))
}
/** 合并详情分页到日期分组(返回新 listData 引用) */
export function mergeReceptionDetails(listData = [], pageList = []) {
const next = listData.map(section => ({
...section,
receptionStaticInfoDTOList: [...(section.receptionStaticInfoDTOList || [])]
}))
next.forEach(val => {
pageList.forEach(subV => {
if (
val.staticDate === subV.staticDate &&
val.receptionStaticInfoDTOList.findIndex(v => v.fileUrl === subV.fileUrl) < 0
) {
val.receptionStaticInfoDTOList.push(subV)
}
})
})
return next
}
/** 是否已加载全部(原 nothing 字段) */
export function computeReceptionHasMore(listData = [], pageNum, pages, total) {
const loadedCount = listData.reduce(
(acc, curr) => acc + (curr?.receptionStaticInfoDTOList?.length || 0),
0
)
return pageNum === pages || total === loadedCount
}
/** 接待列表脏标记指纹 */
export function buildReceptionFingerprint(ctx = {}) {
const { userInfo = {}, violationStatus, searchForm = {} } = ctx
const merchantId = userInfo?.default4SStoreInfo?.merchantId || ''
const key = JSON.stringify({
violationStatus,
startDateTime: searchForm.startDateTime,
endDateTime: searchForm.endDateTime,
merchantNo: searchForm.merchantNo,
staffUuids: searchForm.staffUuids,
orderResult: searchForm.orderResult
})
return `${merchantId}|${key}`
}
/**
* 权益首页服务中心公告:角标拉取(TTL + in-flight)与弹窗候选分离
*/
import { noticeSort } from '../../utils/enum/serviceCenter.js'
const CACHE_TTL_MS = 60 * 1000
let unreadCache = { value: null, ts: 0, pending: null }
let popupProbeCache = { value: null, ts: 0, pending: null }
let listApiOverride = null
/** 单测注入 mock */
export function __setListApiForTest(fn) {
listApiOverride = fn
}
export function clearServiceCenterNoticeCache() {
unreadCache = { value: null, ts: 0, pending: null }
popupProbeCache = { value: null, ts: 0, pending: null }
}
function getListApi() {
if (listApiOverride) return listApiOverride
const mod = require('~/api/serviceCenter/index')
return mod.getCompanyNoticeList
}
function readCacheEntry(entry) {
if (entry.value === null) return null
if (Date.now() - entry.ts > CACHE_TTL_MS) {
entry.value = null
entry.ts = 0
return null
}
return entry.value
}
async function probeNoticeLists() {
const cached = readCacheEntry(popupProbeCache)
if (cached) return cached
if (popupProbeCache.pending) return popupProbeCache.pending
const getCompanyNoticeList = getListApi()
popupProbeCache.pending = (async () => {
const probes = []
for (const moduleType of noticeSort) {
const { data } = await getCompanyNoticeList({
pageNum: 1,
pageSize: 3,
createdTimeSortType: 0,
moduleType,
status: 0
})
const list = data?.list || []
probes.push({ moduleType, list, unreadCount: list.length })
if (list.length > 0) break
}
popupProbeCache.value = probes
popupProbeCache.ts = Date.now()
return probes
})()
try {
return await popupProbeCache.pending
} finally {
popupProbeCache.pending = null
}
}
/**
* 拉取服务中心未读角标数(带缓存)
* @returns {Promise<number>}
*/
export async function fetchServiceCenterUnread() {
const cached = readCacheEntry(unreadCache)
if (cached !== null) return cached
if (unreadCache.pending) return unreadCache.pending
unreadCache.pending = (async () => {
const probes = await probeNoticeLists()
let count = 0
for (const p of probes) {
if (p.unreadCount > 0) {
count = p.unreadCount
break
}
}
unreadCache.value = count
unreadCache.ts = Date.now()
return count
})()
try {
return await unreadCache.pending
} finally {
unreadCache.pending = null
}
}
function getPopupStorageKey() {
return `equityServiceNoticePop_${new Date().format('yyyy-MM-dd')}`
}
function wasPopupShownToday(moduleType) {
const stored = wx.$storage?.get?.(getPopupStorageKey()) || {}
return !!stored[moduleType]
}
function markPopupShownToday(moduleType) {
const key = getPopupStorageKey()
const stored = wx.$storage?.get?.(key) || {}
wx.$storage?.set?.(key, { ...stored, [moduleType]: true })
}
/**
* 返回今日尚未弹过的首条未读公告(无则 null)
* @returns {Promise<{ moduleType: number, noticeItem: Object }|null>}
*/
export async function resolveServiceNoticePopupCandidate() {
const probes = await probeNoticeLists()
for (const { moduleType, list } of probes) {
if (!list?.length) continue
if (wasPopupShownToday(moduleType)) continue
return { moduleType, noticeItem: list[0] }
}
return null
}
/** 弹窗展示后标记,避免同日重复弹 */
export function markServiceNoticePopupShown(moduleType) {
markPopupShownToday(moduleType)
}
/**
* 权益页开单预警(`order.staff.valid`)当日缓存。
*
* 由 equityPage `checkStaffOrderStatus` 使用:
* - 仅 Tab0 的 `initList` 调用
* - API 成功返回后无论是否弹窗,均写入 `dateStaffPop`,避免无预警时重复请求
*
* @module packageEquity/services/staffOrderValidService
*/
/**
* @param {Date} [now]
* @returns {string} yyyy-MM-dd
*/
function todayDateString(now = new Date()) {
if (typeof now.format === 'function') {
return now.format('yyyy-MM-dd')
}
return now.toISOString().slice(0, 10)
}
/**
* 是否应跳过开单预警接口(当日当前门店已查询过)。
*
* @param {Object} storage - wx.$storage `dateStaffPop`
* @param {Object} userInfo - 含 sceneType、default4SStoreInfo.merchantId
* @returns {boolean}
*/
export function shouldSkipStaffOrderValid(storage = {}, userInfo = {}) {
const nowDate = todayDateString()
const sceneType = userInfo.sceneType
const merchantId = userInfo?.default4SStoreInfo?.merchantId
const dayBoolean =
storage?.date && nowDate === String(storage.date).slice(0, 10)
const flag = storage?.[sceneType]?.[merchantId]
return !!(dayBoolean && flag)
}
/**
* 合并写入当日已查询标记(保留同 scene 下其它门店标记)。
*
* @param {Object} storage - 现有 dateStaffPop
* @param {Object} userInfo
* @returns {Object} 可直接 wx.$storage.set('dateStaffPop', ...)
*/
export function markStaffOrderValidChecked(storage = {}, userInfo = {}) {
const sceneType = userInfo.sceneType
const merchantId = userInfo?.default4SStoreInfo?.merchantId
return {
date: todayDateString(),
[sceneType]: {
[merchantId]: true,
...(storage?.[sceneType] || {})
}
}
}
/**
* 权益 Tab 子页(Tab1–4)刷新 in-flight 合并。
*
* 设计原则:
* - **每次** `show=true` 都会执行刷新(与 Tab0 对齐)
* - 仅合并同一 key 下同一 tick 的并发调用(如 observer + 其它入口叠加)
* - **不做 TTL**,切走再切回应重新请求
*
* @module packageEquity/services/tabRefreshService
*/
/** @type {Map<string, Promise<void>>} key → 进行中的刷新 */
const inFlightByKey = new Map()
/**
* 清空单测/调试用的 in-flight 状态。
*/
export function clearTabRefreshState() {
inFlightByKey.clear()
}
/**
* 在 in-flight 去重下执行子 Tab 刷新。
*
* @param {'quotation'|'equityList'|'materials'|'mine'} key - Tab 业务隔离键
* @param {() => Promise<void>|void} fn - 实际刷新函数(如 refreshQuotationTab)
* @returns {Promise<void>}
*/
export async function withTabRefreshInFlight(key, fn) {
if (inFlightByKey.has(key)) {
return inFlightByKey.get(key)
}
const promise = Promise.resolve()
.then(fn)
.finally(() => {
if (inFlightByKey.get(key) === promise) {
inFlightByKey.delete(key)
}
})
inFlightByKey.set(key, promise)
return promise
}
/**
* 权益首页待办(scene: 0,与精品 scene: 1 独立)
*/
/** 昨日日期 yyyy-MM-dd(与页面 goto 原逻辑一致,补偿时区) */
export function getYesterdayReportDate(now = new Date()) {
const previousDate = new Date(now)
previousDate.setDate(now.getDate() - 1)
const hour = previousDate.getHours() + 8
previousDate.setHours(hour)
return previousDate.toISOString().split('T')[0]
}
/** 待办列表预览切片 */
export function sliceTodoPreview(list = [], previewSize = 2) {
const safe = list || []
return {
todoList: safe,
stodoList: safe.slice(0, previewSize)
}
}
/** 权益员工待办请求参数 */
export function buildEquityStaffRemindParams(userInfo = {}) {
return {
merchantId: userInfo?.default4SStoreInfo?.merchantId,
staffUuid: userInfo?.uuid,
scene: 0
}
}
/** 关闭待办请求参数 */
export function buildEquityShutDownTaskParams(userInfo = {}, taskId) {
return {
merchantId: userInfo?.default4SStoreInfo?.merchantId,
staffUuid: userInfo?.uuid,
scene: 0,
taskId
}
}
/**
* 待办按钮动作(页面负责 wx.$router / setData)
* @returns {{ type: 'navigate'|'showPromptDialog'|'noop', route?: string, params?: Object }}
*/
export function resolveTodoGotoAction(taskId, ctx = {}) {
const id = Number(taskId)
switch (id) {
case 1:
return {
type: 'navigate',
route: 'tabWorkOrder.staffDaily',
params: { reportDate: getYesterdayReportDate() }
}
case 2: {
const isHarmony =
ctx.merchantBrand?.findIndex(i => ['鸿蒙智行'].includes(i.name)) !== -1
if (isHarmony) {
return {
type: 'navigate',
route: 'beforeCreate',
params: { mode: ctx.mode }
}
}
return { type: 'showPromptDialog' }
}
case 4:
return { type: 'noop' }
default:
return { type: 'noop' }
}
}
/**
* IT-EQ-DASH-* 权益首页看板 service 单测
*/
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import {
buildOutputValueDateRange,
normalizeOutputValueStats,
normalizeQuotationStatistics
} from '../services/dashboardService.js'
describe('dashboardService', () => {
it('IT-EQ-DASH-001: buildOutputValueDateRange today', () => {
const now = new Date('2026-06-09T12:00:00')
now.format = () => '2026-06-09'
const range = buildOutputValueDateRange('today', now)
assert.equal(range.startTime, '2026-06-09 00:00:00')
assert.equal(range.endTime, '2026-06-09 23:59:59')
})
it('IT-EQ-DASH-002: buildOutputValueDateRange month', () => {
const now = new Date('2026-06-09T12:00:00')
now.format = () => '2026-06-09'
const range = buildOutputValueDateRange('month', now)
assert.match(range.startTime, /2026-06-01 00:00:00/)
assert.equal(range.endTime, '2026-06-09 23:59:59')
})
it('IT-EQ-DASH-003: buildOutputValueDateRange total empty', () => {
const range = buildOutputValueDateRange('total')
assert.equal(range.startTime, '')
assert.equal(range.endTime, '')
})
it('IT-EQ-DASH-004: normalizeOutputValueStats scales conversionRate', () => {
const out = normalizeOutputValueStats({
conversionRate: 0.12,
avgPrice: 5000,
totalOutputValue: 12345.6,
avgQuotationPrice: 9999.4
})
assert.equal(out.conversionRate, 12)
assert.equal(out.avgPrice, 50)
assert.equal(out.totalOutputValue, 12346)
})
it('IT-EQ-DASH-005: normalizeQuotationStatistics splits cents', () => {
const out = normalizeQuotationStatistics({
todayTurnover: 12345,
monthTurnover: 99999,
totalTurnover: 10000050
})
assert.equal(out.todayTurnover, '123')
assert.equal(out.todayTurDecimal, '45')
assert.equal(out.monthTurnover, '999')
assert.equal(out.totalTurnover, '100001')
})
})
/**
* 权益首页 jumpHandlers 单元测试(IT-EQ-MENU-JUMP-*)
*/
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { setupWxMock } from './menuTestHelpers.mjs'
const globalRef = globalThis
describe('equityMenuJump', async () => {
setupWxMock(globalRef)
const { resolveActionType } = await import('../menu/resolveActionType.js')
it('IT-EQ-MENU-JUMP-001: resolveActionType prefers action.type', () => {
assert.equal(
resolveActionType({ action: { type: 'defeatOrder' } }),
'defeatOrder'
)
assert.equal(
resolveActionType({ action: { type: 'createOrderPrompt' } }),
'createOrderPrompt'
)
})
it('IT-EQ-MENU-JUMP-002: workReport from reportTypeAttr', () => {
assert.equal(
resolveActionType({
reportTypeAttr: 'weekly',
path: 'tabWorkOrder.supervisorDaily'
}),
'workReport'
)
})
it('IT-EQ-MENU-JUMP-003: navigate from navigateToUrl', () => {
assert.equal(
resolveActionType({
navigateToUrl: '/packageEquity/pages/sceneMarket/index/index'
}),
'navigate'
)
})
it('IT-EQ-MENU-JUMP-004: createOrderPrompt from id without path', () => {
assert.equal(
resolveActionType({ id: 'create_order', path: '' }),
'createOrderPrompt'
)
})
it('IT-EQ-MENU-JUMP-005: salaryPerformance from empty path menuText', () => {
assert.equal(
resolveActionType({ menuText: '工资绩效', path: '' }),
'salaryPerformance'
)
})
it('IT-EQ-MENU-JUMP-006: router fallback', () => {
assert.equal(
resolveActionType({
id: 'training_materials',
path: 'packageEquity.trainingMaterials'
}),
'router'
)
})
})
import { describe, it, beforeEach } from 'node:test'
import assert from 'node:assert/strict'
import {
buildHomeRefreshFingerprint,
withHomeRefreshDedup,
clearHomeRefreshState
} from '../services/homeRefreshService.js'
describe('homeRefreshService', () => {
beforeEach(() => {
clearHomeRefreshState()
})
it('IT-EQ-HOME-001: buildHomeRefreshFingerprint includes dataActive merchant isWait', () => {
const fp = buildHomeRefreshFingerprint({
dataActive: 'month',
shopMerchantId: 'store-1',
isWait: true
})
assert.equal(fp, 'month|store-1|1')
})
it('IT-EQ-HOME-002: withHomeRefreshDedup dedupes concurrent calls', async () => {
let runs = 0
const fp = buildHomeRefreshFingerprint({
dataActive: 'today',
shopMerchantId: 'm1',
isWait: false
})
const task = () =>
withHomeRefreshDedup(fp, {}, async () => {
runs++
await new Promise(r => setTimeout(r, 10))
})
await Promise.all([task(), task()])
assert.equal(runs, 1)
})
it('IT-EQ-HOME-003: withHomeRefreshDedup allows sequential tab refresh', async () => {
let runs = 0
const fp = buildHomeRefreshFingerprint({
dataActive: 'today',
shopMerchantId: 'm1',
isWait: true
})
await withHomeRefreshDedup(fp, {}, async () => {
runs++
})
await withHomeRefreshDedup(fp, {}, async () => {
runs++
})
assert.equal(runs, 2)
})
})
import { describe, it, beforeEach, afterEach } from 'node:test'
import assert from 'node:assert/strict'
import {
cachedHasPerformanceConfig,
cachedGetStaffTargetTask,
clearMenuApiCache
} from '../menu/menuApiCache.js'
describe('menuApiCache', () => {
beforeEach(() => {
clearMenuApiCache()
})
afterEach(() => {
clearMenuApiCache()
})
it('IT-EQ-CACHE-001: hasPerformanceConfig dedupes concurrent calls', async () => {
let calls = 0
const commonApi = {
hasPerformanceConfig: async () => {
calls++
await new Promise(r => setTimeout(r, 10))
return { data: true }
}
}
const [a, b] = await Promise.all([
cachedHasPerformanceConfig(commonApi, 'm1'),
cachedHasPerformanceConfig(commonApi, 'm1')
])
assert.equal(calls, 1)
assert.equal(a.data, true)
assert.equal(b.data, true)
})
it('IT-EQ-CACHE-002: getStaffTargetTask uses TTL cache', async () => {
let calls = 0
const commonApi = {
getStaffTargetTaskApi: async () => {
calls++
return { code: 0, data: [] }
}
}
await cachedGetStaffTargetTask(commonApi, {
merchantId: 'store-1',
sceneType: 0
})
await cachedGetStaffTargetTask(commonApi, {
merchantId: 'store-1',
sceneType: 0
})
assert.equal(calls, 1)
})
})
/**
* packageEquity Menu 单测公共 mock(对齐 tabIndex/tests/menuTestHelpers.mjs)
*/
export function setupWxMock(globalRef = globalThis) {
globalRef.wx = {
getAccountInfoSync: () => ({ miniProgram: { envVersion: 'release' } }),
getSystemInfoSync: () => ({}),
$hasPermission: {
isSuper: u => !!u?.isSuper,
isNotMentor: u => u?.loginRole !== 6,
canSelectMultiStore: u =>
!!u?.isSuper || [3, 5, 6, 8].includes(u?.loginRole),
canSelectMultiStoreForStaffDaily: u =>
!!u?.isSuper || [3, 5, 8].includes(u?.loginRole),
canViewMentorship: u => !!u?.isSuper || u?.loginRole === 6,
canViewRecruit: u => [3, 8].includes(u?.loginRole),
canViewViolation: u =>
!!u?.isSuper || [3, 6, 8].includes(u?.loginRole)
}
}
return globalRef.wx
}
/** 默认异步 deps,各用例可按需覆盖 */
export function createDefaultEquityAsyncDeps(overrides = {}) {
return {
commonApi: {
hasPerformanceConfig: async () => ({ data: false }),
getStaffTargetTaskApi: async () => ({ code: 0, data: [] }),
getYqStoreConfig: async () => ({ data: { customerExchangeFlag: 'N' } }),
getStaffMentorFlag: async () => ({ code: 0 }),
...overrides.commonApi
},
aiApi: {
extractCheck: async () => ({ data: false }),
...overrides.aiApi
},
carLifeApi: {
selectrecmerchantList: async () => ({ code: 0, data: [] }),
...overrides.carLifeApi
},
receptionRecordsApi: {
checkMerchantDirect: async () => ({ data: false }),
checkMissingReception: async () => ({ code: 0, data: [] }),
...overrides.receptionRecordsApi
},
getBusinessSchoolScene: async () => false,
...overrides
}
}
/**
* IT-EQ-REC-* 权益首页接待列表 service 单测
*/
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import {
buildReceptionQueryParams,
normalizeReceptionDateSections,
mergeReceptionDetails,
computeReceptionHasMore,
buildReceptionFingerprint
} from '../services/receptionListService.js'
const hasPermission = {
isSuper: () => false,
canSelectMultiStore: () => false
}
describe('receptionListService', () => {
it('IT-EQ-REC-001: buildReceptionQueryParams staff single store', () => {
const params = buildReceptionQueryParams({
violationStatus: 1,
userInfo: {
uuid: 'u1',
default4SStoreInfo: { merchantId: 'mid1' }
},
hasPermission,
searchForm: {},
storeRangeList: []
})
assert.equal(params.violationStatus, 1)
assert.deepEqual(params.merchantNo, ['mid1'])
assert.deepEqual(params.staffUuids, ['u1'])
})
it('IT-EQ-REC-002: buildReceptionQueryParams orderResult filters', () => {
const params = buildReceptionQueryParams({
isFilterDefeat: true,
isFilterUpgrade: true,
violationStatus: 0,
userInfo: { uuid: 'u1' },
hasPermission: { isSuper: () => false, canSelectMultiStore: () => true },
searchForm: {}
})
assert.deepEqual(params.orderResult, [2, 1])
})
it('IT-EQ-REC-003: normalizeReceptionDateSections', () => {
const out = normalizeReceptionDateSections([
{ staticDate: '2026-06-09' }
])
assert.equal(out[0].staticDateStr, '6月9日')
assert.deepEqual(out[0].receptionStaticInfoDTOList, [])
})
it('IT-EQ-REC-004: mergeReceptionDetails dedupes by fileUrl', () => {
const listData = [
{
staticDate: '2026-06-09',
receptionStaticInfoDTOList: [{ fileUrl: 'a' }]
}
]
const merged = mergeReceptionDetails(listData, [
{ staticDate: '2026-06-09', fileUrl: 'b' },
{ staticDate: '2026-06-09', fileUrl: 'a' }
])
assert.equal(merged[0].receptionStaticInfoDTOList.length, 2)
})
it('IT-EQ-REC-005: computeReceptionHasMore when pages reached', () => {
const listData = [{ receptionStaticInfoDTOList: [{}, {}] }]
assert.equal(computeReceptionHasMore(listData, 2, 2, 10), true)
})
it('IT-EQ-REC-006: buildReceptionFingerprint changes on violationStatus', () => {
const ctx = {
userInfo: { default4SStoreInfo: { merchantId: 'm1' } },
violationStatus: 1,
searchForm: {}
}
const a = buildReceptionFingerprint(ctx)
const b = buildReceptionFingerprint({ ...ctx, violationStatus: 0 })
assert.notEqual(a, b)
})
})
import { describe, it, beforeEach, afterEach } from 'node:test'
import assert from 'node:assert/strict'
describe('serviceCenterNoticeService', async () => {
const {
fetchServiceCenterUnread,
resolveServiceNoticePopupCandidate,
markServiceNoticePopupShown,
__setListApiForTest,
clearServiceCenterNoticeCache
} = await import('../services/serviceCenterNoticeService.js')
let apiCalls
const storage = {}
beforeEach(() => {
apiCalls = []
clearServiceCenterNoticeCache()
if (!Date.prototype.format) {
Date.prototype.format = function () {
return '2026-06-09'
}
}
globalThis.wx = {
$storage: {
get: key => storage[key],
set: (key, val) => {
storage[key] = val
}
}
}
__setListApiForTest(async params => {
apiCalls.push(params.moduleType)
if (params.moduleType === 6) {
return { data: { list: [{ id: 1, msgTitle: '课程', reminderType: 1 }] } }
}
return { data: { list: [] } }
})
})
afterEach(() => {
__setListApiForTest(null)
clearServiceCenterNoticeCache()
})
it('IT-EQ-NOTICE-001: fetchServiceCenterUnread caches within session', async () => {
const a = await fetchServiceCenterUnread()
const b = await fetchServiceCenterUnread()
assert.equal(a, 1)
assert.equal(b, 1)
assert.equal(apiCalls.length, 1)
})
it('IT-EQ-NOTICE-002: popup candidate respects daily mark', async () => {
const first = await resolveServiceNoticePopupCandidate()
assert.ok(first)
markServiceNoticePopupShown(first.moduleType)
clearServiceCenterNoticeCache()
__setListApiForTest(async params => {
apiCalls.push(params.moduleType)
return {
data: {
list: [{ id: 1, msgTitle: '课程', reminderType: 1 }]
}
}
})
const second = await resolveServiceNoticePopupCandidate()
assert.equal(second, null)
})
})
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import {
shouldSkipStaffOrderValid,
markStaffOrderValidChecked
} from '../services/staffOrderValidService.js'
describe('staffOrderValidService', () => {
const userInfo = {
sceneType: 0,
default4SStoreInfo: { merchantId: 'store-1' }
}
it('IT-EQ-STAFF-001: shouldSkipStaffOrderValid when same day flagged', () => {
const storage = markStaffOrderValidChecked({}, userInfo)
assert.equal(shouldSkipStaffOrderValid(storage, userInfo), true)
})
it('IT-EQ-STAFF-002: shouldSkipStaffOrderValid false when no cache', () => {
assert.equal(shouldSkipStaffOrderValid({}, userInfo), false)
})
it('IT-EQ-STAFF-003: markStaffOrderValidChecked uses sceneType key', () => {
const marked = markStaffOrderValidChecked({}, userInfo)
assert.equal(marked[0]['store-1'], true)
assert.match(marked.date, /^\d{4}-\d{2}-\d{2}$/)
})
})
import { describe, it, beforeEach } from 'node:test'
import assert from 'node:assert/strict'
import {
withTabRefreshInFlight,
clearTabRefreshState
} from '../services/tabRefreshService.js'
describe('tabRefreshService', () => {
beforeEach(() => {
clearTabRefreshState()
})
it('IT-EQ-TAB-001: withTabRefreshInFlight dedupes concurrent calls', async () => {
let runs = 0
const task = () =>
withTabRefreshInFlight('quotation', async () => {
runs++
await new Promise(r => setTimeout(r, 10))
})
await Promise.all([task(), task()])
assert.equal(runs, 1)
})
it('IT-EQ-TAB-002: withTabRefreshInFlight allows sequential refresh', async () => {
let runs = 0
await withTabRefreshInFlight('equityList', async () => {
runs++
})
await withTabRefreshInFlight('equityList', async () => {
runs++
})
assert.equal(runs, 2)
})
it('IT-EQ-TAB-003: withTabRefreshInFlight isolates keys', async () => {
let a = 0
let b = 0
await Promise.all([
withTabRefreshInFlight('materials', async () => {
a++
await new Promise(r => setTimeout(r, 10))
}),
withTabRefreshInFlight('mine', async () => {
b++
})
])
assert.equal(a, 1)
assert.equal(b, 1)
})
})
/**
* IT-EQ-TODO-* 权益首页待办 service 单测
*/
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import {
buildEquityStaffRemindParams,
buildEquityShutDownTaskParams,
sliceTodoPreview,
resolveTodoGotoAction,
getYesterdayReportDate
} from '../services/todoService.js'
describe('todoService', () => {
it('IT-EQ-TODO-001: buildEquityStaffRemindParams scene 0', () => {
const params = buildEquityStaffRemindParams({
uuid: 'u1',
default4SStoreInfo: { merchantId: 'm1' }
})
assert.deepEqual(params, {
merchantId: 'm1',
staffUuid: 'u1',
scene: 0
})
})
it('IT-EQ-TODO-002: buildEquityShutDownTaskParams', () => {
const params = buildEquityShutDownTaskParams(
{ uuid: 'u1', default4SStoreInfo: { merchantId: 'm1' } },
5
)
assert.equal(params.taskId, 5)
assert.equal(params.scene, 0)
})
it('IT-EQ-TODO-003: sliceTodoPreview', () => {
const list = [1, 2, 3, 4]
const { todoList, stodoList } = sliceTodoPreview(list, 2)
assert.deepEqual(todoList, list)
assert.deepEqual(stodoList, [1, 2])
})
it('IT-EQ-TODO-004: resolveTodoGotoAction daily report', () => {
const action = resolveTodoGotoAction(1)
assert.equal(action.type, 'navigate')
assert.equal(action.route, 'tabWorkOrder.staffDaily')
assert.ok(action.params.reportDate)
})
it('IT-EQ-TODO-005: resolveTodoGotoAction order prompt', () => {
const action = resolveTodoGotoAction(2, { mode: 1, merchantBrand: [] })
assert.equal(action.type, 'showPromptDialog')
})
it('IT-EQ-TODO-006: resolveTodoGotoAction harmony brand', () => {
const action = resolveTodoGotoAction(2, {
mode: 0,
merchantBrand: [{ name: '鸿蒙智行' }]
})
assert.equal(action.type, 'navigate')
assert.equal(action.route, 'beforeCreate')
})
it('IT-EQ-TODO-007: getYesterdayReportDate format', () => {
const d = getYesterdayReportDate(new Date('2026-06-09T12:00:00'))
assert.match(d, /^\d{4}-\d{2}-\d{2}$/)
})
})
...@@ -197,42 +197,37 @@ export const setConfigInfo = globalData => { ...@@ -197,42 +197,37 @@ export const setConfigInfo = globalData => {
}) })
} }
let _pendingBusinessSchoolScene = null
export const getBusinessSchoolScene = () => { export const getBusinessSchoolScene = () => {
const app = getApp() const app = getApp()
return new Promise((resolve, reject) => { if (
// 如果有 直接返回 app.globalData.businessSchoolScene != '' &&
if ( app.globalData.businessSchoolScene != null
app.globalData.businessSchoolScene != '' && ) {
app.globalData.businessSchoolScene != null return Promise.resolve(app.globalData.businessSchoolScene)
) { }
// debugger if (_pendingBusinessSchoolScene) {
return resolve(app.globalData.businessSchoolScene) return _pendingBusinessSchoolScene
} else { }
// let userInfo = wx.$util.getUserInfo() _pendingBusinessSchoolScene = api
// if (!userInfo) this.login(true) .isBusinessSchoolEnableCurrentUser({})
// let { merchantId, merchantName } = userInfo.subLoginUser .then(res => {
// wx.$util.showLoading() const { code, data } = res
// debugger if (code == 0) {
api app.globalData.businessSchoolScene = data
.isBusinessSchoolEnableCurrentUser({ return app.globalData.businessSchoolScene
// merchantId, }
// merchantName return null
}) })
.then(res => { .catch(error => {
// console.log(res) console.log(error)
// wx.$util.hideLoading() return null
let { code, data } = res })
if (code == 0) { .finally(() => {
app.globalData.businessSchoolScene = data _pendingBusinessSchoolScene = null
// this.checkSeverType(userInfo) })
resolve(app.globalData.businessSchoolScene) return _pendingBusinessSchoolScene
}
})
.catch(error => {
console.log(error)
})
}
})
} }
// 扫码进来的处理 // 扫码进来的处理
......
/**
* 首页看板 / 表格静态配置(自 index_mixins 抽离)
*/
export const STATIC_DATA_LIST = [
{ label: '今日营业额', valueObj: 'merchantTodayTotal', tipsLabel: '今日成交量' },
{ label: '本月营业额', valueObj: 'merchantMonthTotal', tipsLabel: '本月成交量' },
{ label: '累计营业额', valueObj: 'merchantTotal', tipsLabel: '累计成交量' }
]
export const TOTAL_TABLE_SUM = [
{ name: 'filmTimesTotalSum' },
{ name: 'usedTotalSum' },
{ name: 'experienceTotalSum' },
{ name: 'upgradeTotalSum' },
{ name: 'orderMoneyTotalSum' },
{ name: 'customerUnitMoneySum' },
{ name: 'upgradeRateSum' }
]
export const TABLE_OBJ = [
{ name: '贴膜', unit: '/台', key: 'filmTimes', width: 'var(--fontSize110)' },
{ name: '核销', unit: '/张', key: 'usedTotal', width: 'var(--fontSize110)' },
{ name: '体验', unit: '/位', key: 'experienceTotal', width: 'var(--fontSize110)' },
{ name: '转化', unit: '/单', key: 'upgradeTotal', width: 'var(--fontSize110)' },
{ name: '营业额', unit: '', key: 'orderMoneyTotal', sort: false, width: 'var(--fontSize110)' },
{ name: '客单价', unit: '', key: 'customerUnitMoney', width: 'var(--fontSize110)' },
{ name: '转化率', unit: '', key: 'upgradeRate', width: 'var(--fontSize110)' }
]
export const ORDER_BY_TYPE_ENUM = {
true: [1, 3, 13, 5, 7, 9, 11],
false: [2, 4, 14, 6, 8, 10, 12]
}
export const WIDE_SUM_COLUMNS = ['orderMoneyTotalSum', 'customerUnitMoneySum']
export const CHANGE_BTN_DATA = [
{ label: '本日', valueObj: 'staffTodayTotal', valueFn: 'merchantTodayTotal' },
{ label: '本月', valueObj: 'staffMonthTotal', valueFn: 'merchantMonthTotal' },
{ label: '累计', valueObj: 'staffTotal', valueFn: 'merchantTotal' }
]
export const DEFAULT_TOTAL_LIST = [
{
name: '已预约',
itemName: 'totalInvited',
index: 2,
url: 'pages.tabDateIndex',
icon: 'icon_14',
activeIndex: 1,
waitname: '待预约客户',
waititemName: 'totalWaitToInvited',
waiturl: 'pages.tabDateIndex',
activeWIndex: 2
},
{
name: '转化订单',
itemName: 'totalUpgrade',
index: 4,
url: 'pages.index',
icon: 'icon_17',
activeIndex: 2
},
{
name: '战败订单',
itemName: 'totalNotUpgrade',
index: 5,
url: 'pages.index',
icon: 'icon_16',
activeIndex: 3
},
{
name: '客单价',
itemName: 'customerUnitPrice',
unit: '¥',
icon: 'icon_7',
index: 6,
url: 'tabOperating.index'
}
]
export const TECHNICIAN_TOTAL_LIST = [
{
name: '窗膜(本月/累计)',
itemName: 'currentMonthSunroofCount',
waititemName: 'totalSunroofCount'
},
{
name: '车衣(本月/累计)',
itemName: 'currentMonthCarSeatCount',
waititemName: 'totalCarSeatCount'
},
{
name: '精品(本月/累计)',
itemName: 'currentMonthPremiumCount',
waititemName: 'totalPremiumCount'
}
]
export const TABLE_BTN = [
{ text: '今日', type: 'today', active: true },
{ text: '本月', type: 'month' },
{ text: '自定义', type: 'date' }
]
export const LOGIN_ROLE_LABEL = {
1: '超管',
2: '商户管理员',
3: '区域运营',
4: '驻店负责人',
5: '广联销售',
6: '飞行督导',
7: '技师',
8: '技师督导'
}
/** 深拷贝看板表格配置(避免运行时 mutate 污染模块常量) */
export function cloneDashboardTableConfig() {
return {
staticDataList: STATIC_DATA_LIST.map(x => ({ ...x })),
totalTableSum: TOTAL_TABLE_SUM.map(x => ({ ...x })),
tableObj: TABLE_OBJ.map(x => ({ ...x })),
orderByTypeEnum: { ...ORDER_BY_TYPE_ENUM },
changeBtnData: CHANGE_BTN_DATA.map(x => ({ ...x })),
totalList: DEFAULT_TOTAL_LIST.map(x => ({ ...x })),
technicianTotalList: TECHNICIAN_TOTAL_LIST.map(x => ({ ...x })),
tableBtn: TABLE_BTN.map(x => ({ ...x })),
loginRoleLabel: { ...LOGIN_ROLE_LABEL }
}
}
/**
* 根据合计列动态计算表格宽度
*/
export function computeTableWidth(totalTableSum = [], tableObj = []) {
let sumWidth = 0
totalTableSum.forEach((element, index) => {
if (WIDE_SUM_COLUMNS.includes(element.name)) {
const length = element.total?.toString().length || 0
const labelWidth = length > 5 ? length * 20 : 118
if (tableObj[index]) tableObj[index].width = labelWidth + 'rpx'
sumWidth += labelWidth
}
})
return 118 * 5 + 232 + 30 + sumWidth
}
/**
* 产值完成率(百分比数值)
*/
export function computeRatePercent(outputValue = 0, targetValue = 0, round = (n, d) => n) {
if (!targetValue) return 0
const rate = round((outputValue / targetValue) * 100, 2)
return rate
}
# DEVLOG — tabIndex 精品首页
## 2026-06-09 — 首页 Menu 架构重构
### 背景
原 `index.js` 中 `customerOnReady()` 约 400 行、49 处 `menu.every(name)` 去重,`jump()` 约 200 行按中文 `name` 分支;菜单定义散落在 `index_mixins.js` 与运行时 `push`,异步 API 回调多次 `setData`,存在竞态与重复逻辑。
### 变更摘要
| 项 | 旧实现 | 新实现 |
|----|--------|--------|
| 菜单定义 | `index_mixins.js` + `customerOnReady` push | [`tabIndex/menu/registry.js`](../menu/registry.js) 单一注册表 |
| 组装 | 过程式 if + push | `buildTabIndexMenusSync` / `buildTabIndexMenusAsync` 管道 |
| 异步入口 | 散落 Promise 回调 | `asyncProviders.js` 并行 `Promise.all` 后单次 merge |
| 跳转 | `jump()` name/url 分支 | `createMenuJumpHandler` 按 `action.type` 分发 |
| 标识 | 中文 `name` | 稳定 `id`(WXML 仍读 `name` = `label`) |
| 生命周期 | `onReady` + `onShow` 均全量重建 | `getMenuFingerprint` 脏标记,仅变化时重建 |
| 工资绩效 | 超管 `newMenu` + `getIsBusinessSchoolEnableCurrentUser` 再 push `menu` | 超管仅 `newMenu`;非超管走 API provider |
| 接待缺失报备 | `menu.splice` 返回值误赋给 `menu`(潜在 bug) | provider 控制显隐,不再 splice 赋值 |
### 新增文件
- `tabIndex/menu/constants.js` — 技师菜单、特殊账号白名单、`MENU_SECTION`
- `tabIndex/menu/policies.js` — 可组合权限谓词
- `tabIndex/menu/context.js` — `createMenuContext`、`getMenuFingerprint`
- `tabIndex/menu/registry.js` — `MENU_REGISTRY`、`ASYNC_MENU_REGISTRY`
- `tabIndex/menu/toViewModel.js` — 注册表 → WXML view model
- `tabIndex/menu/buildMenus.js` — 同步/异步构建管道
- `tabIndex/menu/asyncProviders.js` — 7 个异步 provider
- `tabIndex/menu/jumpHandlers.js` — 跳转 Command Dispatcher
- `tabIndex/menu/index.js` — 统一导出
- `tabIndex/tests/tabIndexMenu.test.mjs` — 单元测试
- `tabIndex/docs/MENU-ARCHITECTURE.md` — 架构与 API 说明
### 修改文件
- `tabIndex/pages/index/index.js` — 接入 `rebuildMenus`,删除旧 `customerOnReady` 拼装与 `jump` 分支
- `tabIndex/pages/index/index_mixins.js` — `menu` / `newMenu` 初始化为 `[]`
- `packageDynamicForm/docs/routes-and-menus.md` — 补充精品 Menu 架构章节
- `package.json` — `test` 脚本纳入 `tabIndex/tests`
### 页面侧 API(`index.js`)
| 方法 | 说明 |
|------|------|
| `rebuildMenus(options)` | 调用 `buildTabIndexMenusAsync` 并 `setData`;`includeCustomerClue` 控制客户线索 provider |
| `customerOnReady(force)` | 脏标记门禁后委托 `rebuildMenus`;`onReady` 传 `force=true` |
| `invalidateMenuCache()` | 切换门店 / 导师标记变化时清除指纹缓存 |
| `_shouldRefreshMenus(userInfo)` | 比较 `getMenuFingerprint` 决定是否跳过重建 |
| `_updateMenuBadges(userInfo, menu)` | 按 `id` 更新待审批、招聘、客户线索角标 |
### 单测
运行:`npm run test:tabIndex` 或 `npm test`(含 packageDynamicForm)。
用例前缀:`IT-MENU-*`,详见 [`tabIndex/tests/tabIndexMenu.test.mjs`](../tests/tabIndexMenu.test.mjs)。
### 新增菜单(后续开发)
完整流程、示例与检查清单见 **[`ADD-MENU-GUIDE.md`](./ADD-MENU-GUIDE.md)**。速记:
1. 在 `registry.js` 增加条目(`id`、`label`、`visible`、`action`、`section`、`sortVal`)
2. 若依赖接口 → `asyncProviders.js` + `ASYNC_MENU_REGISTRY`
3. 若跳转方式特殊 → `jumpHandlers.js` 增加 `action.type` handler
4. 补充 `tabIndexMenu.test.mjs` 用例;权益首页另维护,见指南第 10 节
---
## 2026-06-09 — 文档对齐与权益回退后续
### 背景
Menu 重构后 JSDoc / 架构文档需与实现对齐;`packageEquity` 分包不可跨引 `tabIndex/menu/`,权益 registry 方案已回退。
### 文档对齐(注释 vs 实现)
| 项 | 修补内容 |
|----|----------|
| `registry.js` | 移除过时 `buildEquityMenusAsync` 引用;`MenuViewModelExtras` 仅对应 `buildTabIndexMenusAsync` |
| `asyncProviders.js` | 各 `resolve*` 补 `@description` 与 MENU-ARCHITECTURE Provider 表交叉引用 |
| `resolveActionType.js` | 补完整回退链 JSDoc |
| `constants.js` | 注明技师短路菜单与 `repair_order` 注册表项并行、图标差异 |
| `jumpHandlers.js` | 补 `shutDownTaskApi` 副作用表(`training_materials:5`、`marketing_materials:6`) |
| `MENU-ARCHITECTURE.md` | 补 `resolveActionType` 模块行、技师短路、Provider 前置条件、跳转副作用、action.type 回退 |
| `HOMEPAGE-INDEX.md` | `shutDownTask` → `closeRemind`;看板区分已接入 / 预留导出 |
| `TODO-SERVICE.md` | 区分已接入与待页面接入的导出函数 |
| `modalQueueService.js` | 注明 `page` 为预留参数 |
### 权益回退(分包隔离)
- 删除 `tabIndex/menu/buildEquityMenus.js`、`equityRegistry.js`、`toEquityViewModel.js`
- `packageEquity/pages/index/index.js` 恢复内联 `menuList` + `appendDynamicFormEquityMenusAsync`
- `ROADMAP.md` 标记权益 registry 化「已回退」
### 非 Menu 服务(同期落地)
- `tabIndex/services/todoService.js` — P1 待办(部分函数待页面接入)
- `tabIndex/services/modalQueueService.js` — P2 弹窗队列(已接入)
- `tabIndex/services/dashboardService.js` — P3 看板(仅 `computeTableWidth` 已接入)
- `tabIndex/menu/resolveActionType.js` — 从 jumpHandlers 抽离 action.type 解析
### 单测补充
- `IT-MENU-REG-003`:注册表必填字段 schema 校验
- `IT-MENU-JUMP-*`:`resolveActionType` 回退链
- `IT-TODO-*` / `permissionSync.test.mjs`
# 精品首页 index.js 职责地图
`tabIndex/pages/index/index.js` 在 Menu 抽离后约 1500 行,各区块边界如下。
## Menu(已抽离)
| 入口 | 模块 | 说明 |
|------|------|------|
| `rebuildMenus()` | `tabIndex/menu/buildMenus.js` | 同步 + 异步管道,单次 setData |
| `jump()` | `tabIndex/menu/jumpHandlers.js` | `createMenuJumpHandler` |
| `customerOnReady()` | `getMenuFingerprint` | onShow 脏标记 |
| `_updateMenuBadges()` | `menu/badgeProviders.js` | 按 `id` 拉取角标 |
## 待办(P1)
| 方法 | 服务 |
|------|------|
| `getStaffRemindList` | `todoService.sliceTodoPreview` / `buildStaffRemindParams` |
| `closeRemind` | `buildShutDownTaskParams` + `shutDownTaskApi` |
| `checkDailyRecport` | `dailyCheckService.runDailyChecks` |
| `openWorkReportTemp` / `onReportPopupSelect` | `menu/workReportHandler.js` |
| `rebuildMenusForStaffTarget` | 原 `getStaffTargetTask`,onLoad 驻店重建菜单 |
详见 [`TODO-SERVICE.md`](./TODO-SERVICE.md)。
## 弹窗队列(P2)
| 方法 | 服务 |
|------|------|
| `addModalToQueue` | `modalQueueService.add` |
| `showNextModal` | `modalQueueService.showNext` |
| `onLoad` | `createModalQueueService(this)` |
与 menu `sideEffects.showTaskDialog` 对接:菜单重建后由页面触发弹窗。
## 看板(P3)
| 方法 | 模块 | 接入状态 |
|------|------|----------|
| `getMerchantCouponList` | `computeTableWidth` + `mergeTablePage` | ✅ 已接入 |
| `getUserStat` | `capDisplayOrderMoney` | ✅ 已接入 |
| `totalList` / 看板静态配置 | `dashboardConfig.js`(经 `index_mixins` clone) | ✅ 单一数据源 |
## 权限(P4)
WXML 通过 `permission.wxs`;JS 通过 `rolePermission.js`。同步校验:`tabIndex/tests/permissionSync.test.mjs`。
## 生命周期职责
```
onLoad → modalQueue 初始化、门店/日期初始化
onShow → customerOnReady(指纹)→ 待办/弹窗/看板刷新
切换门店 → invalidateMenuCache + rebuildMenus
```
# 首页重构路线图
本文档为 [`首页重构剩余路线图`](../../.cursor/plans) 的持久化版本,跟踪 Menu 与非 Menu 分期落地状态。
## Menu 渐进路径
| 阶段 | 状态 | 说明 |
|------|------|------|
| Phase 0 止血 | ✅ 已落地 | splice / early return / onShow 去重 |
| Phase 1 注册表 | ✅ 已落地 | `MENU_REGISTRY` + `buildTabIndexMenus` |
| Phase 2 异步 Provider | ✅ 已落地 | `asyncProviders.js` 7 个 provider |
| Phase 3 Command 化 | ✅ 已落地 | `resolveActionType` + `jumpHandlers`,无 name 回退 |
| Phase 4 测试文档 | ✅ 已落地 | `IT-MENU-*` / `IT-MENU-JUMP-*` / 角色快照 |
### Menu 剩余可选项
| 项 | 优先级 | 说明 |
|----|--------|------|
| sections 模型 | 低 | `menu` + `newMenu` → `menuSections` |
| 配置外置 | 低 | 白名单迁入远程配置 |
| 权益 menu registry 化 | 已回退 | 因 `packageEquity` 分包不可跨引 `tabIndex/menu/`;权益保持内联 `menuList` + `appendDynamicFormEquityMenusAsync` |
| 权益 navGo Command 化 | 低 | 若要做,共享代码须放主包 `utils/menu/equity/` |
## 非 Menu 首页优化
| 分期 | 模块 | 状态 |
|------|------|------|
| P1 待办 | `tabIndex/services/todoService.js` | ✅ 已抽离 + `IT-TODO-*` |
| P2 弹窗队列 | `tabIndex/services/modalQueueService.js` | ✅ 已接入 `index.js` |
| P3 看板 | `dashboardService.js` + `dashboardConfig.js` | ✅ 宽度计算已接入 |
| P4 权限双实现 | `permissionSync.test.mjs` | ✅ CI 对照 JS/WXS |
| P5 死代码清理 | getIsMentor 注释 / jump 调试 log | ✅ 已清理 |
## 执行顺序(已完成)
1. Phase 3 收尾 + WXML/角标 id 化
2. 指纹补全 + jump 单测
3. 非 Menu P1 待办服务
4. 非 Menu P2 弹窗队列
5. ~~权益首页 menu 对齐~~(已回退,分包隔离)
6. 非 Menu P3 看板抽离
7. 文档 + 权限同步测试
## 相关文档
- [`ADD-MENU-GUIDE.md`](./ADD-MENU-GUIDE.md) — 新增菜单流程与示例
- [`MENU-ARCHITECTURE.md`](./MENU-ARCHITECTURE.md)
- [`HOMEPAGE-INDEX.md`](./HOMEPAGE-INDEX.md)
- [`TODO-SERVICE.md`](./TODO-SERVICE.md)
- [`DEVLOG.md`](./DEVLOG.md)
# 待办服务契约(todoService)
模块:`tabIndex/services/todoService.js`
## 导出函数
| 函数 | 用途 | 页面接入 |
|------|------|----------|
| `sliceTodoPreview(list, previewSize?)` | 待办全量 + 首页预览切片 | ✅ `getStaffRemindList` |
| `buildStaffRemindParams(userInfo)` | `getStaffRemindList` 请求体(scene 固定 1) | ✅ `getStaffRemindList` |
| `buildShutDownTaskParams(userInfo, taskId)` | 关闭待办请求体 | ✅ `closeRemind` |
| `shouldSkipOrderStaffPop(storage, userInfo)` | 开单预警当日已弹 | ✅ `dailyCheckService.checkStaffOrderStatus` |
| `shouldSkipAbnormalOrderPop(storage, userInfo)` | 异常订单当日已弹 | ✅ `dailyCheckService.checkAbnormalOrderLocal` |
| `pickFirstMissingReceptionTodo(data)` | 接待缺失待办首条(与 `asyncProviders` 逻辑一致) | ⏳ 仅单测,待页面接入 |
## 页面接入点(已接入)
```javascript
import {
sliceTodoPreview,
buildStaffRemindParams,
buildShutDownTaskParams
} from '../../services/todoService.js'
getStaffRemindList() {
commonApi.getStaffRemindList(buildStaffRemindParams(userInfo))
.then(result => this.setData(sliceTodoPreview(result.data)))
}
```
## 单测
`npm run test:tabIndex` → `tabIndex/tests/tabIndexTodoService.test.mjs`(`IT-TODO-*`)
/**
* 精品首页异步菜单 Provider
*
* 各 provider 并行执行,返回 `{ [providerKey]: { visible, extras?, sideEffects? } }`
* 由 buildTabIndexMenusAsync 合并进最终 menu。单测通过 deps 注入 mock API。
*/
import dayjs from 'dayjs'
import {
appendDynamicFormTabIndexMenusAsync,
stripDynamicFormTabIndexMenus,
DYNAMIC_FORM_TAB_INDEX_MENUS
} from '../../utils/dynamicFormMenus.js'
import { registryItemToViewModel } from './toViewModel.js'
/**
* 并行解析所有异步菜单 provider
*
* @param {Object} ctx - createMenuContext 返回值
* @param {Object} [deps]
* @param {Object} [deps.tabIndexApi] - tabIndex/api.js 方法集
* @param {Object} [deps.commonApi] - api/api.js 方法集
* @param {Function} [deps.getBusinessSchoolScene] - 工资绩效显隐
* @param {boolean} [deps.includeCustomerClue] - 是否解析客户线索(园区配置)
* @returns {Promise<Record<string, { visible: boolean, extras?: Object, sideEffects?: Object }>>}
*/
export async function resolveAsyncMenuProviders(ctx, deps = {}) {
const { userInfo, isStaff } = ctx
const policies = ctx.policies
const tabIndexApi =
deps.tabIndexApi ||
((await import('../api.js')).default ?? (await import('../api.js')))
const commonApiModule = deps.commonApi
? { default: deps.commonApi }
: await import('../../api/api.js')
const commonApi = commonApiModule.default ?? commonApiModule
const providers = []
if (!policies.isTechnician()) {
providers.push(
resolveScriptVerify(ctx, tabIndexApi),
resolveSalaryAppeal(ctx, tabIndexApi, isStaff),
resolveMissingReception(ctx, tabIndexApi),
resolveDynamicForm(ctx),
resolveSalaryPerformance(ctx, deps.getBusinessSchoolScene),
resolveResidentTarget(ctx, commonApi, policies)
)
}
if (deps.includeCustomerClue) {
providers.push(resolveCustomerClue(ctx, commonApi, deps))
}
const results = await Promise.all(providers)
return Object.assign({}, ...results)
}
/**
* 话术核验:非技师;`extractCheck` 返回 true 或超管可见;接口异常时仅超管可见。
* @see tabIndex/docs/MENU-ARCHITECTURE.md 异步 Provider 表
*/
async function resolveScriptVerify(ctx, tabIndexApi) {
const { userInfo } = ctx
const policies = ctx.policies
if (policies.isTechnician()) {
return { scriptVerify: { visible: false } }
}
try {
const res = await tabIndexApi.extractCheck({})
const visible =
(policies.isSuper() || !!res) && policies.notTechnician()
return { scriptVerify: { visible } }
} catch {
return { scriptVerify: { visible: policies.isSuper() } }
}
}
/**
* 工资申诉:超管直显;否则 `hasPerformanceConfig` 且(`canViewRecruit` 或 `isStaff` 或 `loginRole==4`)。
* @see tabIndex/docs/MENU-ARCHITECTURE.md 异步 Provider 表
*/
async function resolveSalaryAppeal(ctx, tabIndexApi, isStaff) {
const { userInfo } = ctx
const policies = ctx.policies
if (policies.isTechnician()) {
return { salaryAppeal: { visible: false } }
}
if (policies.isSuper()) {
return { salaryAppeal: { visible: true } }
}
try {
const res = await tabIndexApi.hasPerformanceConfig({
merchantId: userInfo.shopMerchantId || userInfo.merchantId
})
const visible =
!!res?.data &&
(policies.canViewRecruit() ||
isStaff ||
userInfo?.loginRole == 4)
return { salaryAppeal: { visible } }
} catch {
return { salaryAppeal: { visible: false } }
}
}
/**
* 接待缺失报备:需 `isStaff` 或 `canSelectMultiStoreForStaffDaily`;再 `checkMerchantDirect`;
* 通过则 `checkMissingReception` 写入 `sideEffects.missingRecordTodoList`。
* @see tabIndex/docs/MENU-ARCHITECTURE.md 异步 Provider 表
*/
async function resolveMissingReception(ctx, tabIndexApi) {
const { userInfo, isStaff } = ctx
const policies = ctx.policies
if (
policies.isTechnician() ||
!(isStaff || policies.canSelectMultiStoreForStaffDaily())
) {
return {
missingReception: {
visible: false,
sideEffects: { missingRecordTodoList: [] }
}
}
}
try {
const res = await tabIndexApi.checkMerchantDirect({
merchantId: userInfo.shopMerchantId,
scene: 1
})
if (!res?.data) {
return {
missingReception: {
visible: false,
sideEffects: { missingRecordTodoList: [] }
}
}
}
const { uuid, merchantId, shopMerchantId } = userInfo
let missingRecordTodoList = []
try {
const result = await tabIndexApi.checkMissingReception({
merchantId: shopMerchantId,
yqMerchantId: merchantId,
staffUuid: uuid,
sceneType: 1,
reportStartDate: dayjs().subtract(6, 'day').format('YYYY-MM-DD'),
reportEndDate: dayjs().format('YYYY-MM-DD')
})
if (result.code == 0) {
result.data.reverse().forEach(e => {
if (
e.missingReceptionRecord &&
!e.hasReceptionReport &&
!missingRecordTodoList.length
) {
missingRecordTodoList.push(e)
}
})
}
} catch {
// ignore
}
return {
missingReception: {
visible: policies.notTechnician(),
sideEffects: { missingRecordTodoList }
}
}
} catch {
return {
missingReception: {
visible: false,
sideEffects: { missingRecordTodoList: [] }
}
}
}
}
/**
* 动态表单三入口:角色门禁 + isNeed 后由 `appendDynamicFormTabIndexMenusAsync` 注入 items。
* 返回 `{ visible, items }`,items 不经 ASYNC_MENU_REGISTRY 登记。
* @see tabIndex/docs/MENU-ARCHITECTURE.md 异步 Provider 表
*/
async function resolveDynamicForm(ctx) {
const { userInfo } = ctx
const menu = []
const newMenu = []
stripDynamicFormTabIndexMenus(menu, newMenu)
await appendDynamicFormTabIndexMenusAsync(menu, newMenu, userInfo)
const items = menu.map(item => {
const registryLike = DYNAMIC_FORM_TAB_INDEX_MENUS.find(m => m.name === item.name)
return registryItemToViewModel(
{
id:
item.name === '洽谈明细'
? 'negotiation_detail'
: item.name === '门店日报'
? 'store_daily_report'
: 'staff_daily_report_new',
label: item.name,
icon: item.icon,
sortVal: item.sortVal,
action: { type: 'navigate', target: item.navigateToUrl },
noCheckdailyReport: item.noCheckdailyReport,
recordId: item.recordId
},
{
navigateToUrl: item.navigateToUrl,
trackEventCode: item.trackEventCode
}
)
})
return { dynamicForm: { visible: items.length > 0, items } }
}
/**
* 工资绩效(异步项):排除技师与超管(超管走同步 `salary_performance_super`);`getBusinessSchoolScene` 有结果则显。
* @see tabIndex/docs/MENU-ARCHITECTURE.md 异步 Provider 表
*/
async function resolveSalaryPerformance(ctx, getBusinessSchoolScene) {
const { userInfo } = ctx
const policies = ctx.policies
if (policies.isTechnician() || policies.isSuper()) {
return { salaryPerformance: { visible: false } }
}
if (!getBusinessSchoolScene) {
return { salaryPerformance: { visible: false } }
}
const fetchScene = getBusinessSchoolScene
try {
const res = await fetchScene({})
return { salaryPerformance: { visible: !!res } }
} catch {
return { salaryPerformance: { visible: false } }
}
}
/**
* 驻店目标:需 `isStaff`、非 `canSelectMultiStore`、`default4SStoreInfo.merchantId` 存在;
* `getStaffTargetTaskApi` 有数据则显,并可能注入 `noRead` 与 `showTaskDialog` sideEffects。
* @see tabIndex/docs/MENU-ARCHITECTURE.md 异步 Provider 表
*/
async function resolveResidentTarget(ctx, commonApi, policies) {
const { userInfo, isStaff } = ctx
if (
policies.isTechnician() ||
policies.canSelectMultiStore() ||
!isStaff
) {
return { residentTarget: { visible: false } }
}
const merchantId = userInfo?.default4SStoreInfo?.merchantId
if (!merchantId) {
return { residentTarget: { visible: false } }
}
try {
const res = await commonApi.getStaffTargetTaskApi({
sceneType: 1,
merchantId
})
const { code, data } = res
if (code != 0 || !data?.length) {
return { residentTarget: { visible: false } }
}
const sideEffects = {
taskId: data[0]?.id,
taskInfo: data[0],
showTaskDialog: data[0]?.promptFlag == 'N'
}
return {
residentTarget: {
visible: true,
extras: { noRead: data[0]?.readFlag == 'N' },
sideEffects
}
}
} catch {
return { residentTarget: { visible: false } }
}
}
/**
* 客户线索入口:园区 getYqStoreConfig.customerExchangeFlag === 'Y' 时显隐
* @param {Object} ctx
* @param {Object} commonApi
* @param {Object} [deps]
*/
export async function resolveCustomerClue(ctx, commonApi, deps = {}) {
const { userInfo } = ctx
const policies = ctx.policies
if (policies.isTechnician()) {
return { customerClue: { visible: false } }
}
try {
const { merchantId: yqMerchantId } = userInfo
const res = await (deps.getYqStoreConfig || commonApi.getYqStoreConfig)({
yqMerchantId
})
const data = res?.data
if (!data || data.customerExchangeFlag != 'Y') {
return { customerClue: { visible: false } }
}
return { customerClue: { visible: true, tipsNum: 0 } }
} catch {
return { customerClue: { visible: false } }
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!