Просмотр исходного кода

Merge branch 'ui-refactor-phase-2' of guanli/ngfrontend into develop

bill001 2 недель назад
Родитель
Сommit
c5a4f12f63

+ 4 - 3
docs/refactor/signup-welcome-pack.md

@@ -1,7 +1,8 @@
 # 注册页 Welcome Pack 功能迁移
 # 注册页 Welcome Pack 功能迁移
 
 
 创建日期:2026-10-09  
 创建日期:2026-10-09  
-更新日期:2026-10-14  
+更新日期:2026-10-28
+
 状态:注册 UI 已迁移,已接入游客查询 / 报单与站内 Paystack V2 弹窗;真实后端、订单确认和支付待联调。
 状态:注册 UI 已迁移,已接入游客查询 / 报单与站内 Paystack V2 弹窗;真实后端、订单确认和支付待联调。
 
 
 第 1~6 节描述当前源码,第 7 节保留最初迁移时的验证记录,第 8 节说明本次文档核对范围。早期会员报单、删除订单、成功倒计时等行为不能继续作为当前游客注册页的实现说明。
 第 1~6 节描述当前源码,第 7 节保留最初迁移时的验证记录,第 8 节说明本次文档核对范围。早期会员报单、删除订单、成功倒计时等行为不能继续作为当前游客注册页的实现说明。
@@ -65,7 +66,7 @@
 7. 提交使用 `POST /v1/user/guest-dec`。在原业务字段之外,将 `draftId` 与 `accessToken` 放在请求体最外层,不嵌套为 `draft`。两项缺失时阻止提交;草稿只保存在页面内存,不写入会员缓存。
 7. 提交使用 `POST /v1/user/guest-dec`。在原业务字段之外,将 `draftId` 与 `accessToken` 放在请求体最外层,不嵌套为 `draft`。两项缺失时阻止提交;草稿只保存在页面内存,不写入会员缓存。
 8. 提交响应按 `response.data || response` 读取订单,包含 `orderSn`、`amount`、`currency`、`reference`、`accessCode` 等支付信息;缺少 `accessCode` 或 `reference` 时显示错误。`authorizationUrl` 即使返回,当前也不用于整页跳转。
 8. 提交响应按 `response.data || response` 读取订单,包含 `orderSn`、`amount`、`currency`、`reference`、`accessCode` 等支付信息;缺少 `accessCode` 或 `reference` 时显示错误。`authorizationUrl` 即使返回,当前也不用于整页跳转。
 9. 当前支付由 `GuestPaystack` 加载 `https://js.paystack.co/v2/inline.js`,调用 `resumeTransaction(accessCode)`。金额用于展示,不由前端重新创建交易或按旧流程乘 100 初始化扣款;交易金额与币种由服务端交易决定。
 9. 当前支付由 `GuestPaystack` 加载 `https://js.paystack.co/v2/inline.js`,调用 `resumeTransaction(accessCode)`。金额用于展示,不由前端重新创建交易或按旧流程乘 100 初始化扣款;交易金额与币种由服务端交易决定。
-10. 关闭弹窗仅隐藏,不删除订单。每次有效点击 Continue Payment 都重新校验当前表单并调用 `POST /v1/user/guest-dec`,成功后使用本次返回的支付信息打开弹窗;请求中阻止重复点击,失败或缺少交易标识时不打开旧支付信息。是否复用已有后台订单由接口决定。SDK 内仍防止重复打开,支付回调的 `reference` 必须与最新订单一致;随后停留注册页等待确认,不跳转 `/shop/member-order`,也没有成功倒计时。
+10. 关闭弹窗仅隐藏,不删除订单。每次有效点击 Continue Payment 都重新校验当前表单并调用 `POST /v1/user/guest-dec`,成功后使用本次返回的支付信息打开弹窗;请求中阻止重复点击,失败或缺少交易标识时不打开旧支付信息。是否复用已有后台订单由接口决定。SDK 内仍防止重复打开,支付回调的 `reference` 必须与最新订单一致;随后立即使用 `replace` 跳转 `/login`,保留原查询参数,不再停留注册页,也没有成功倒计时。取消支付、请求失败或回调不匹配时不跳转。
 11. `paymentComplete` 后按钮显示 Payment submitted 并禁用;这只表示前端收到了匹配回调,不代表服务端已确认注册或付款成功。
 11. `paymentComplete` 后按钮显示 Payment submitted 并禁用;这只表示前端收到了匹配回调,不代表服务端已确认注册或付款成功。
 
 
 邀请链接形如 `/#/login?ref=会员ID`,登录页 Register 已透传查询参数。注册页创建时读取单个字符串 `ref`,去掉首尾空格后同时作为 `form.recUserName` 和 `form.conUserName` 的默认值;没有有效 `ref` 时留空,不猜测推荐人。初始化不触发推荐人查询或其他接口,也不反复覆盖手动修改;两项始终可编辑。手动更改推荐人仍会清空实际推荐人,需要重新填写并确认关系。Save 和 Continue Payment 都传递用户当前填写的两项。
 邀请链接形如 `/#/login?ref=会员ID`,登录页 Register 已透传查询参数。注册页创建时读取单个字符串 `ref`,去掉首尾空格后同时作为 `form.recUserName` 和 `form.conUserName` 的默认值;没有有效 `ref` 时留空,不猜测推荐人。初始化不触发推荐人查询或其他接口,也不反复覆盖手动修改;两项始终可编辑。手动更改推荐人仍会清空实际推荐人,需要重新填写并确认关系。Save 和 Continue Payment 都传递用户当前填写的两项。
@@ -88,7 +89,7 @@
 | 项目 | 已确认事实 / 待确认 |
 | 项目 | 已确认事实 / 待确认 |
 |---|---|
 |---|---|
 | 匿名接口 | **已接入、待联调**:游客专用 GET / POST 和推荐人接口已由前端调用;服务端匿名授权、草稿有效期与异常响应仍需在授权环境验证 |
 | 匿名接口 | **已接入、待联调**:游客专用 GET / POST 和推荐人接口已由前端调用;服务端匿名授权、草稿有效期与异常响应仍需在授权环境验证 |
-| 支付完成 | **已确认**:匹配回调后留在注册页等待订单确认;前端没有服务端确认查询或独立完成页,不能把 SDK 回调当成最终付款凭证 |
+| 支付完成 | **已确认(2026-10-28)**:匹配回调后立即返回登录页并保留原查询参数;前端没有服务端确认查询或独立完成页,不能把 SDK 回调当成最终付款凭证 |
 | 配送参数 | **已确认**:旧页提交参数没有 `way` 字段;本轮保持同一 payload。UI 切换仍改变地址禁用状态,没有擅自增加接口字段 |
 | 配送参数 | **已确认**:旧页提交参数没有 `way` 字段;本轮保持同一 payload。UI 切换仍改变地址禁用状态,没有擅自增加接口字段 |
 | 密码初始值 | **已确认**:当前仍有预设登录 / 支付密码;当前控件未配置 `type="password"` 或 `show-password`。清空默认值、调整控件及新增校验均未在本次文档任务中实施 |
 | 密码初始值 | **已确认**:当前仍有预设登录 / 支付密码;当前控件未配置 `type="password"` 或 `show-password`。清空默认值、调整控件及新增校验均未在本次文档任务中实施 |
 | 计价 | **已确认**:显示销售价与市场价,实际汇总和提交前余额校验仍按市场价计算;是否调整价格规则不属于本轮 UI 改造 |
 | 计价 | **已确认**:显示销售价与市场价,实际汇总和提交前余额校验仍按市场价计算;是否调整价格规则不属于本轮 UI 改造 |

+ 1 - 0
src/ui-refactor/views/signup/components/welcomePackRegistration.js

@@ -417,6 +417,7 @@ export default {
         message: 'Payment submitted. Please wait for order confirmation.',
         message: 'Payment submitted. Please wait for order confirmation.',
         type: 'success'
         type: 'success'
       })
       })
+      this.$router.replace(this.loginRoute)
     },
     },
     // 已选择商品
     // 已选择商品
     selectProduct() {
     selectProduct() {

+ 29 - 0
src/ui-refactor/views/welcome-pack/MemberWelcomePack.vue

@@ -82,6 +82,7 @@ import Legacy from '@/views/user/welcome-pack.vue?vue&type=script&lang=js'
 import { fetchWelcomePack } from '@/api/user'
 import { fetchWelcomePack } from '@/api/user'
 import { deleteApproachOrder } from '@/api/shop'
 import { deleteApproachOrder } from '@/api/shop'
 import { getLanguages } from '@/api/setting'
 import { getLanguages } from '@/api/setting'
+import tool from '@/utils/tool'
 import usersInfo from '@/utils/usersInfo'
 import usersInfo from '@/utils/usersInfo'
 import UiSectionCard from '@/components/ui/UiSectionCard.vue'
 import UiSectionCard from '@/components/ui/UiSectionCard.vue'
 import SignupProducts from '../signup/components/SignupProducts.vue'
 import SignupProducts from '../signup/components/SignupProducts.vue'
@@ -227,6 +228,34 @@ export default {
       this.$set(this.storeNums, index, value)
       this.$set(this.storeNums, index, value)
       this.handleInputNumber(value, row)
       this.handleInputNumber(value, row)
     },
     },
+    // 新会员报单使用登录后的会员价,与商品卡片和余额校验保持一致。
+    handleSureChange() {
+      let subtotal = 0
+      let bv = 0
+      let tax = 0
+      this.multipleSelection.forEach(item => {
+        subtotal += Number(item.SELL_PRICE) * Number(item.goodsNum)
+        bv += Number(item.PRICE_PV) * Number(item.goodsNum)
+        tax += tool.calculateTax(Number(item.SELL_PRICE), Number(item.TAX_RATE), Number(item.goodsNum))
+      })
+      this.sellPriceSum = tool.formatPrice(subtotal)
+      this.pricePvSum = tool.formatPrice(bv)
+      this.taxSum = tool.formatPrice(tax)
+    },
+    selectProduct() {
+      this.form.goodsId = []
+      this.form.goodsNum = []
+      this.payAmount = 0
+      this.multipleSelection.forEach(item => {
+        this.form.goodsId.push(item.ID)
+        this.form.goodsNum.push(item.goodsNum)
+        this.payAmount += Number(item.SELL_PRICE) * Number(item.goodsNum)
+      })
+    },
+    handleProduct(row) {
+      this.product = { ...row, taxAmount: tool.calculateTax(Number(row.SELL_PRICE), Number(row.TAX_RATE)) }
+      this.visibleProduct = true
+    },
     onSubmit() {
     onSubmit() {
       if (this.busy || !this.initialized) return
       if (this.busy || !this.initialized) return
       if (!this.isCurrent()) {
       if (!this.isCurrent()) {

+ 25 - 1
src/ui-refactor/views/welcome-pack/README.md

@@ -1,5 +1,29 @@
 # Member Welcome Pack
 # Member Welcome Pack
 
 
+## 2026-10-28 会员报单价格修正验收
+
+- 用户要求沿用登录前后的价格区别:未登录注册继续使用 `MARKET_PRICE`;已登录的新 Member Welcome Pack 按 `SELL_PRICE` 计算商品小计、含税税额、付款摘要、商品详情税额及余额校验。截图中的单件商品应统一为 NGN 199,000,税额为 NGN 13,883.72,而非 NGN 299,900。
+- 验证数量 1–10、数字与字符串价格、零价格、多商品与移除清空,以及余额不足/刚好足够/介于销售价与市场价之间的情况。BV 算法保持原样。
+- 只在新页面覆盖旧脚本的相关方法,保留旧页、游客注册、接口请求体、服务端返回的 `ORDER_AMOUNT` 和 Paystack 金额换算。用新旧请求对比、SDK 参数及导航回归检查这些边界。
+- 本轮使用已有 Node、Jest、ESLint 和隔离预览;不新增依赖、配置或提交,不进行真实报单/扣款。金额风险集中在混用单价、数量更新遗漏、错误余额判断以及覆盖后端金额,通过上述用例和定向故障注入检查。
+- `spec approval: not obtained (autonomous run)`:用户已明确价格方向,具体测试清单未单独审批。
+
+复验命令:`node src/ui-refactor/views/welcome-pack/__tests__/verifyPricing.cjs`。使用当前 Node 24.14.0、Vue 2.7.16、Jest 24.9.0;每次创建新的临时证据目录,记录日志、JSON 及构建输出,并在故障注入后核对源码还原。
+
+| 2026-10-28 检查 | 结果与对应证据 |
+| --- | --- |
+| 修复前复现 | 8 个会员价用例均在金额断言失败;截图样例原先显示 199,000,但汇总 299,900 |
+| 价格、数量、清空、余额及详情 | `MemberWelcomePack.spec.js` 35 项通过;`uses member price` 枚举 4 种价格 × 1–10 件,`matches the member card` 对照截图金额,`accepts cash balance` 检查刚好足够及低于市场价的余额,`recalculates multiple member` 检查多商品及清空 |
+| 接口、SDK、旧页及成功去向 | 同文件保留新旧请求体对比、服务端金额 ×100 和旧页 MARKET_PRICE 用例;`WelcomePackNavigation.spec.js` 12 项通过,两文件共 47 项 |
+| 金额故障注入 | 分别将小计、税额、余额检查、详情税额退回 MARKET_PRICE,4/4 被上述价格用例捕获;校验器拒绝“测试通过”和“runner 崩溃”两个负对照 |
+| 全量回归 | 修改前 509 通过、18 项失败及 2 个组件编译器版本错误;修改后 517 通过,失败名称和编译器错误完全相同。复验脚本严格比较基线,不接受新增失败 |
+| lint / 构建 | 修改的页面、测试及复验脚本 0 错误/警告;完整生产构建成功,输出临时目录,保留既有体积和浏览器数据过期提示 |
+| 隔离页面实跑 | 会员价 38,000 的样例添加 1 件、键盘增至 2 件后,小计及付款摘要为 76,000,税额 5,302.33,详情单件税额 2,651.16;320/375/768/1024/1440px 和 375×480 均无横向溢出,金额一致。未提交报单或调用真实 SDK |
+| 补跑检查 | 保留工作区同时产生的 `WelcomePackFields.vue` 单选框样式修改。一次补跑发现既有收货方式用例依赖 `$children[0]` 顺序而定位失败,已改为真实姓名输入与 Pickup 单选操作,原业务断言保持不变,再运行完整复验 |
+| 边界与未执行项 | 未改变 API、旧页、游客注册、全局样式、依赖或环境文件;根目录环境与 lockfile 哈希不变。动态 SFC 加载不支持可靠的源码覆盖率,本轮不声明覆盖率;用枚举金额不变量替代新增属性测试依赖。Jest 24 无现成随机顺序选项,未声称随机化验证;未进行真实报单、服务端重新计价或扣款联调 |
+
+最终页面 SHA-256:`962718b187e7c3db2bb25e4f864a6983bb7748d14dd0510f95d173c9a6be788e`。此前 MARKET_PRICE 金额验证记录描述旧行为,新页面自本节起使用会员价;旧页面仍保持原样。
+
 ## 本轮范围与验收
 ## 本轮范围与验收
 
 
 - 新页面沿用 SignupPage 的分组表单、SignupProducts 和现有公开布局;旧 Welcome Pack、游客注册和认证逻辑保留。
 - 新页面沿用 SignupPage 的分组表单、SignupProducts 和现有公开布局;旧 Welcome Pack、游客注册和认证逻辑保留。
@@ -8,7 +32,7 @@
 - Country 使用登录缓存 `baseData.COUNTRY_ID`,只读;新会员编号继续取会员 `GET /v1/user/dec` 的 `userName`。
 - Country 使用登录缓存 `baseData.COUNTRY_ID`,只读;新会员编号继续取会员 `GET /v1/user/dec` 的 `userName`。
 - Reporting Center ID 按旧 `isDec` 规则处理:普通会员可编辑且必填;stockist 默认填当前报单中心账号并禁用编辑。加载或提交期间沿用外层表单的禁用状态,原提交字段保留。
 - Reporting Center ID 按旧 `isDec` 规则处理:普通会员可编辑且必填;stockist 默认填当前报单中心账号并禁用编辑。加载或提交期间沿用外层表单的禁用状态,原提交字段保留。
 - 国家/语言列表使用现有接口;产品、等级、地区、银行、余额及支付方式取登录后的 Welcome Pack 接口。
 - 国家/语言列表使用现有接口;产品、等级、地区、银行、余额及支付方式取登录后的 Welcome Pack 接口。
-- 提交保持旧 `POST /v1/user/dec` 字段、MARKET_PRICE 计价、BV/含税算法与自动安置;余额或 Paystack 支付成功后立即打开本次订单详情(`/guest-order?order=<SN>`)。保留银行信息,配送方式不额外加入旧请求体。
+- 提交保持旧 `POST /v1/user/dec` 字段、BV/含税算法与自动安置;新页面按 `SELL_PRICE` 计价(2026-10-28 起)。余额或 Paystack 支付成功后立即打开本次订单详情(`/guest-order?order=<SN>`)。保留银行信息,配送方式不额外加入旧请求体。
 - 支付展示按截图区分 Paystack 和 Account Balance,金额及余额来自实际状态,不移植演示数值或游客 accessCode 协议。
 - 支付展示按截图区分 Paystack 和 Account Balance,金额及余额来自实际状态,不移植演示数值或游客 accessCode 协议。
 - 请求中阻止重复提交和修改表单;失败恢复可操作。取消 Paystack 仍先确认并调用旧取消接口,使用本次响应中的 `payForm.orderSn`;取消失败保留支付窗口。
 - 请求中阻止重复提交和修改表单;失败恢复可操作。取消 Paystack 仍先确认并调用旧取消接口,使用本次响应中的 `payForm.orderSn`;取消失败保留支付窗口。
 - 测试覆盖身份/国家初始化、旧请求体等价、数量/金额、余额不足、缺失商品/等级/报单中心、两种支付成功/失败/取消以及入口。
 - 测试覆盖身份/国家初始化、旧请求体等价、数量/金额、余额不足、缺失商品/等级/报单中心、两种支付成功/失败/取消以及入口。

+ 7 - 6
src/ui-refactor/views/welcome-pack/WelcomePackFields.vue

@@ -264,12 +264,13 @@ export default {
 //  gap: 12px;
 //  gap: 12px;
 //}
 //}
 //
 //
-//.ng-welcome-fields ::v-deep .el-radio {
-//  height: auto;
-//  margin: 0;
-//  line-height: 1.5;
-//  white-space: normal;
-//}
+.ng-welcome-fields ::v-deep .el-radio {
+  height: auto;
+  min-height: 40px;
+  margin: 0;
+  white-space: normal;
+  line-height: 1.5;
+}
 
 
 @media (max-width: 767px) {
 @media (max-width: 767px) {
   .ng-welcome-grid {
   .ng-welcome-grid {

+ 91 - 8
src/ui-refactor/views/welcome-pack/__tests__/MemberWelcomePack.spec.js

@@ -136,35 +136,118 @@ it.each(['cash', 'pay_stack'])('keeps the exact legacy %s request and payment re
   }
   }
 })
 })
 
 
-it('keeps MARKET_PRICE totals, BV and legacy tax for a range of stock quantities', async() => {
+it.each([0, '0', 100, '100.25'])('uses member price %s for totals, BV and inclusive tax across stock quantities', async price => {
+  user.fetchWelcomePack.mockImplementation(async() => {
+    const response = settings()
+    response.data.allGoods[0].SELL_PRICE = price
+    return response
+  })
   const vm = await order()
   const vm = await order()
   for (let quantity = 1; quantity <= 10; quantity++) {
   for (let quantity = 1; quantity <= 10; quantity++) {
     vm.changeProductQuantity({ row: vm.tableData[0], index: 0, value: quantity })
     vm.changeProductQuantity({ row: vm.tableData[0], index: 0, value: quantity })
     vm.selectProduct()
     vm.selectProduct()
     expect(vm.form.goodsNum).toEqual([quantity])
     expect(vm.form.goodsNum).toEqual([quantity])
-    expect(Number(vm.sellPriceSum)).toBe(120 * quantity)
+    expect(Number(vm.sellPriceSum)).toBe(Number(price) * quantity)
     expect(Number(vm.pricePvSum)).toBe(60 * quantity)
     expect(Number(vm.pricePvSum)).toBe(60 * quantity)
-    expect(vm.payAmount).toBe(120 * quantity)
-    expect(Number(vm.taxSum)).toBe(Number((120 * quantity * 7.5 / 107.5).toFixed(2)))
+    expect(vm.payAmount).toBe(Number(price) * quantity)
+    expect(Number(vm.taxSum)).toBe(Number((Number(price) * quantity * 7.5 / 107.5).toFixed(2)))
   }
   }
 })
 })
 
 
+it('matches the member card price with subtotal, tax, payment summary and product details', async() => {
+  user.fetchWelcomePack.mockImplementation(async() => {
+    const response = settings()
+    response.data.allGoods[0] = { ...product, SELL_PRICE: '199000.00', MARKET_PRICE: '299900.00', PRICE_PV: '70' }
+    response.data.userBalance.cash = 250000
+    return response
+  })
+  const vm = await order()
+  vm.form.payType = 'cash'
+  await settle()
+  expect(vm.$el.querySelector('.ng-signup-product-price strong').textContent).toBe('NGN 199,000')
+  const totals = vm.$el.querySelector('.ng-signup-totals').textContent
+  expect(totals).toContain('NGN 199,000')
+  expect(totals).toContain('NGN 13,883.72')
+  const payment = vm.$el.querySelector('.ng-payment-methods-detail').textContent
+  expect(payment).toContain('NGN 199,000')
+  expect(payment).toContain('NGN 51,000')
+  expect(payment).not.toContain('not enough to cover this order')
+  vm.$el.querySelector('.ng-signup-product-view').click()
+  await settle()
+  expect(vm.product.taxAmount).toBe(13883.72)
+  expect(document.body.querySelector('.ng-product-details-dialog').textContent).toContain('NGN 13,883.72')
+  expect(vm.tableData[0]).toMatchObject({ SELL_PRICE: '199000.00', MARKET_PRICE: '299900.00' })
+  vm.onSubmit()
+  expect(vm.payAmount).toBe(199000)
+  expect(user.createWelcomePack).toHaveBeenCalledTimes(1)
+})
+
+it.each([100, 119])('accepts cash balance %s when it covers the member price but not the market price', async balance => {
+  const vm = await order()
+  vm.userBalance.cash = balance
+  vm.form.payType = 'cash'
+  await settle()
+  expect(vm.$el.textContent).not.toContain('not enough to cover this order')
+  vm.onSubmit()
+  expect(vm.payAmount).toBe(100)
+  expect(user.createWelcomePack).toHaveBeenCalledTimes(1)
+  expect(vm.userBalance.cash).toBe(balance)
+})
+
+it('recalculates multiple member products and clears all totals when they are removed', async() => {
+  user.fetchWelcomePack.mockImplementation(async() => {
+    const response = settings()
+    response.data.allGoods.push({ ...product, ID: 'P2', SELL_PRICE: '73.40', MARKET_PRICE: '99.90', PRICE_PV: '28.4' })
+    return response
+  })
+  const vm = await order()
+  vm.toggleProduct(vm.tableData[1])
+  vm.changeProductQuantity({ row: vm.tableData[0], index: 0, value: 3 })
+  vm.changeProductQuantity({ row: vm.tableData[1], index: 1, value: 2 })
+  vm.selectProduct()
+  expect(Number(vm.sellPriceSum)).toBe(446.8)
+  expect(vm.payAmount).toBe(446.8)
+  expect(Number(vm.pricePvSum)).toBe(236.8)
+  expect(Number(vm.taxSum)).toBe(31.17)
+  expect(vm.form.goodsId).toEqual(['P1', 'P2'])
+  expect(vm.form.goodsNum).toEqual([3, 2])
+  vm.tableData.slice().forEach(row => vm.toggleProduct(row))
+  vm.selectProduct()
+  expect(Number(vm.sellPriceSum)).toBe(0)
+  expect(Number(vm.pricePvSum)).toBe(0)
+  expect(Number(vm.taxSum)).toBe(0)
+  expect(vm.payAmount).toBe(0)
+  expect(vm.form.goodsId).toEqual([])
+  expect(vm.form.goodsNum).toEqual([])
+})
+
+it('preserves the old page market-price calculations', () => {
+  const vm = mount({ ...Legacy, created: undefined, render: h => h('div') })
+  vm.multipleSelection = [{ ...product, goodsNum: 1 }]
+  vm.handleSureChange()
+  vm.selectProduct()
+  expect(Number(vm.sellPriceSum)).toBe(120)
+  expect(vm.payAmount).toBe(120)
+})
+
 it('shows balance shortage without changing the original balance or submitting', async() => {
 it('shows balance shortage without changing the original balance or submitting', async() => {
   const vm = await order()
   const vm = await order()
-  vm.userBalance.cash = 119
+  vm.userBalance.cash = 99
   vm.form.payType = 'cash'
   vm.form.payType = 'cash'
   await settle()
   await settle()
   expect(vm.$el.textContent).toContain('not enough to cover this order')
   expect(vm.$el.textContent).toContain('not enough to cover this order')
   expect(vm.$el.textContent).toContain('Balance after payment')
   expect(vm.$el.textContent).toContain('Balance after payment')
   vm.onSubmit()
   vm.onSubmit()
   expect(user.createWelcomePack).not.toHaveBeenCalled()
   expect(user.createWelcomePack).not.toHaveBeenCalled()
-  expect(vm.userBalance.cash).toBe(119)
+  expect(vm.userBalance.cash).toBe(99)
 })
 })
 
 
 it('keeps editable fields and pickup events connected without changing the legacy request fields', async() => {
 it('keeps editable fields and pickup events connected without changing the legacy request fields', async() => {
   const vm = await order()
   const vm = await order()
-  const fields = vm.$children[0].$children.find(child => child.$options.name === 'WelcomePackFields')
-  fields.$emit('change', { realName: 'Updated member', way: 'pickup' })
+  const name = vm.$el.querySelector('#ng-welcome-realName')
+  name.value = 'Updated member'
+  name.dispatchEvent(new Event('input', { bubbles: true }))
+  vm.$el.querySelector('input[type="radio"][value="pickup"]').click()
   await settle()
   await settle()
   expect(vm.form.realName).toBe('Updated member')
   expect(vm.form.realName).toBe('Updated member')
   expect(vm.areaDisabled).toBe(true)
   expect(vm.areaDisabled).toBe(true)

+ 76 - 0
src/ui-refactor/views/welcome-pack/__tests__/verifyPricing.cjs

@@ -0,0 +1,76 @@
+/* eslint-env node */
+const fs = require('fs')
+const os = require('os')
+const path = require('path')
+const assert = require('assert')
+const crypto = require('crypto')
+const { spawnSync } = require('child_process')
+const output = fs.mkdtempSync(path.join(os.tmpdir(), 'ng-welcome-pricing-'))
+const target = path.resolve(__dirname, '../MemberWelcomePack.vue')
+const original = fs.readFileSync(target, 'utf8')
+const jest = 'node_modules/jest/bin/jest.js'
+const pricingTests = 'uses member price|matches the member card|accepts cash balance|recalculates multiple member'
+function run(args, name) {
+  const result = spawnSync(process.execPath, args, {
+    encoding: 'utf8', env: { ...process.env, NODE_OPTIONS: '--openssl-legacy-provider' }
+  })
+  fs.writeFileSync(path.join(output, name + '.log'), (result.stdout || '') + (result.stderr || ''))
+  assert(!result.error && result.status !== null, 'Runner failed: ' + name)
+  return result
+}
+function assertKilled(result, report) {
+  assert.strictEqual(result.status, 1, 'Mutation did not fail')
+  assert(report.numFailedTests > 0 && report.numRuntimeErrorTestSuites === 0, 'Expected test assertions, not runner errors')
+}
+assert.throws(() => assertKilled({ status: 0 }, { numFailedTests: 0 }))
+assert.throws(() => assertKilled({ status: 1 }, { numFailedTests: 0, numRuntimeErrorTestSuites: 1 }))
+const mutations = [
+  ['subtotal', 'subtotal += Number(item.SELL_PRICE)', 'subtotal += Number(item.MARKET_PRICE)'],
+  ['tax', 'tax += tool.calculateTax(Number(item.SELL_PRICE)', 'tax += tool.calculateTax(Number(item.MARKET_PRICE)'],
+  ['balance', 'this.payAmount += Number(item.SELL_PRICE)', 'this.payAmount += Number(item.MARKET_PRICE)'],
+  ['details', 'tool.calculateTax(Number(row.SELL_PRICE)', 'tool.calculateTax(Number(row.MARKET_PRICE)']
+]
+for (const [name, from, to] of mutations) {
+  assert.strictEqual(original.split(from).length, 2, 'Mutation target must be unique: ' + name)
+  const report = path.join(output, name + '.json')
+  try {
+    fs.writeFileSync(target, original.replace(from, to))
+    const result = run([jest, '--runInBand', '--testMatch', '**/welcome-pack/__tests__/MemberWelcomePack.spec.js', '--testNamePattern', pricingTests, '--json', '--outputFile=' + report], name)
+    assertKilled(result, JSON.parse(fs.readFileSync(report, 'utf8')))
+    console.log('Killed: ' + name)
+  } finally {
+    fs.writeFileSync(target, original)
+    assert.strictEqual(fs.readFileSync(target, 'utf8'), original)
+  }
+}
+const baseline = [
+  ...['repeat-purchase', 'member-repurchase', 'member-auto-maintenance', 'member-upgrade'].map(name => name + ' shows checkout product prices and BV using the existing purchase rules'),
+  ...['repeat-purchase', 'member-repurchase', 'member-auto-maintenance', 'member-upgrade'].map(name => 'keeps the order list fallback when ' + name + ' returns no order number'),
+  'renders the confirmed order/goods response with an empty goods list and missing address',
+  'Profile UI preserves existing account, password and address behavior preserves edit row mapping, ID and default string values without changing other card actions',
+  'inherits each old page without replacing its state, requests, downloads or amount filters',
+  'loads only the selected endpoint and displays multiple orders, all details and products',
+  'keeps separate pagination when switching categories and does not duplicate requests on return',
+  'summarizes each order separately using the existing displayed quantity, price, BV and tax',
+  'Sponsor Network UI reuses both original network scripts keeps the original untrimmed username, unrestricted depth and period query on form submission',
+  'AccountBalances preserves the existing account logic resets page size to the original 5 and repeats the same request',
+  'Team inquiry UI and its account shortcut opens Repeat Purchase from Browse products while preserving the current query',
+  'new page theme preserves Element UI and legacy pages retains control geometry and confines table styles to new pages'
+].sort()
+const checkFailures = failures => assert.deepStrictEqual(failures.slice().sort(), baseline, 'Failures changed from the recorded pre-change baseline')
+assert.throws(() => checkFailures(baseline.concat('Unexpected failure')))
+const report = path.join(output, 'regression.json')
+const regression = run(['--max-old-space-size=8192', jest, '--runInBand', '--testMatch', '**/__tests__/*.spec.js', '**/tests/unit/**/*.spec.js', '--json', '--outputFile=' + report, '--silent'], 'regression')
+assert.strictEqual(regression.status, 1)
+const tests = JSON.parse(fs.readFileSync(report, 'utf8'))
+const failures = tests.testResults.flatMap(suite => suite.assertionResults.filter(test => test.status === 'failed').map(test => test.fullName))
+checkFailures(failures)
+const suiteErrors = tests.testResults.filter(suite => suite.status === 'failed' && !suite.assertionResults.length)
+assert.deepStrictEqual(suiteErrors.map(suite => path.relative(process.cwd(), suite.name).replace(/\\/g, '/')).sort(), ['tests/unit/components/Hamburger.spec.js', 'tests/unit/components/SvgIcon.spec.js'])
+assert(suiteErrors.every(suite => suite.message.includes('Vue packages version mismatch')))
+assert.strictEqual(run(['node_modules/eslint/bin/eslint.js', '--max-warnings=0', target, path.join(__dirname, 'MemberWelcomePack.spec.js'), __filename], 'lint').status, 0)
+assert.strictEqual(run(['node_modules/@vue/cli-service/bin/vue-cli-service.js', 'build', '--dest', path.join(output, 'build'), '--no-clean'], 'build').status, 0)
+assert.strictEqual(fs.readFileSync(target, 'utf8'), original)
+const result = { passed: tests.numPassedTests, existingFailures: failures.length, existingCompilerErrors: suiteErrors.length, mutationsKilled: mutations.length, lint: 'passed', build: 'passed', sourceHash: crypto.createHash('sha256').update(original).digest('hex'), output }
+fs.writeFileSync(path.join(output, 'result.json'), JSON.stringify(result, null, 2))
+console.log(JSON.stringify(result, null, 2))

+ 14 - 3
tests/unit/ui-refactor/signup.spec.js

@@ -3,7 +3,7 @@ import Vue from 'vue'
 import ElementUI from 'element-ui'
 import ElementUI from 'element-ui'
 import path from 'path'
 import path from 'path'
 import registration from '@/ui-refactor/views/signup/components/welcomePackRegistration'
 import registration from '@/ui-refactor/views/signup/components/welcomePackRegistration'
-import { load } from '@/ui-refactor/views/purchase/__tests__/loadComponent'
+import { load } from './loadGuestComponent'
 import { getLanguages } from '@/api/setting'
 import { getLanguages } from '@/api/setting'
 import request from '@/utils/request'
 import request from '@/utils/request'
 
 
@@ -13,13 +13,16 @@ jest.mock('@/utils/request', () => jest.fn())
 
 
 Vue.use(ElementUI)
 Vue.use(ElementUI)
 const PaymentMethods = load(path.resolve('src/ui-refactor/components/PaymentMethods.vue'))
 const PaymentMethods = load(path.resolve('src/ui-refactor/components/PaymentMethods.vue'))
+const SignupPage = load(path.resolve('src/ui-refactor/views/signup/SignupPage.vue'))
 
 
 function instance() {
 function instance() {
   const vm = registration.data()
   const vm = registration.data()
   vm.$message = jest.fn()
   vm.$message = jest.fn()
   vm.$message.error = jest.fn()
   vm.$message.error = jest.fn()
   vm.$t = key => key
   vm.$t = key => key
-  vm.$router = { push: jest.fn() }
+  vm.$route = { query: {}}
+  vm.$router = { push: jest.fn(), replace: jest.fn() }
+  Object.defineProperty(vm, 'loginRoute', { get: () => SignupPage.computed.loginRoute.call(vm) })
   Object.keys(registration.methods).forEach(key => {
   Object.keys(registration.methods).forEach(key => {
     vm[key] = registration.methods[key].bind(vm)
     vm[key] = registration.methods[key].bind(vm)
   })
   })
@@ -365,6 +368,7 @@ describe('Signup welcome-pack compatibility', () => {
     expect(vm.$message).not.toHaveBeenCalled()
     expect(vm.$message).not.toHaveBeenCalled()
     jest.advanceTimersByTime(6000)
     jest.advanceTimersByTime(6000)
     expect(vm.$router.push).not.toHaveBeenCalled()
     expect(vm.$router.push).not.toHaveBeenCalled()
+    expect(vm.$router.replace).not.toHaveBeenCalled()
     expect(window.location.assign).not.toHaveBeenCalled()
     expect(window.location.assign).not.toHaveBeenCalled()
   })
   })
 
 
@@ -399,6 +403,7 @@ describe('Signup welcome-pack compatibility', () => {
     await settle()
     await settle()
     expect(vm.submitButtonStat).toBe(false)
     expect(vm.submitButtonStat).toBe(false)
     expect(vm.$message).toHaveBeenCalledWith({ message: 'Test submit failure', type: 'error' })
     expect(vm.$message).toHaveBeenCalledWith({ message: 'Test submit failure', type: 'error' })
+    expect(vm.$router.replace).not.toHaveBeenCalled()
   })
   })
 
 
   it.each([
   it.each([
@@ -420,6 +425,7 @@ describe('Signup welcome-pack compatibility', () => {
     expect(window.location.assign).not.toHaveBeenCalled()
     expect(window.location.assign).not.toHaveBeenCalled()
     expect(vm.$router.push).not.toHaveBeenCalled()
     expect(vm.$router.push).not.toHaveBeenCalled()
     expect(vm.$message).toHaveBeenCalledWith({ message: expect.any(String), type: 'error' })
     expect(vm.$message).toHaveBeenCalledWith({ message: expect.any(String), type: 'error' })
+    expect(vm.$router.replace).not.toHaveBeenCalled()
   })
   })
 
 
   it('refreshes payment details on every continuation using the current form and prevents concurrent requests', async() => {
   it('refreshes payment details on every continuation using the current form and prevents concurrent requests', async() => {
@@ -464,6 +470,7 @@ describe('Signup welcome-pack compatibility', () => {
     expect(vm.submitButtonStat).toBe(false)
     expect(vm.submitButtonStat).toBe(false)
     expect(window.location.assign).not.toHaveBeenCalled()
     expect(window.location.assign).not.toHaveBeenCalled()
     expect(vm.$router.push).not.toHaveBeenCalled()
     expect(vm.$router.push).not.toHaveBeenCalled()
+    expect(vm.$router.replace).not.toHaveBeenCalled()
   })
   })
 
 
   it.each([false, true])('does not reopen cached payment after a failed or incomplete refresh: %s', async(incomplete) => {
   it.each([false, true])('does not reopen cached payment after a failed or incomplete refresh: %s', async(incomplete) => {
@@ -494,8 +501,9 @@ describe('Signup welcome-pack compatibility', () => {
     expect(vm.$message).toHaveBeenCalledWith({ message: 'profile.selectLevel', type: 'error' })
     expect(vm.$message).toHaveBeenCalledWith({ message: 'profile.selectLevel', type: 'error' })
   })
   })
 
 
-  it('stays on signup after the payment callback and prevents another submission', () => {
+  it.each([{}, { ref: 'test-inviter', redirect: '/dashboard/repeat-purchase' }])('returns to login immediately after the matching payment callback with query %j and prevents another submission', query => {
     const vm = instance()
     const vm = instance()
+    vm.$route.query = query
     vm.paymentOrder = { accessCode: 'test-access-code', reference: 'test-reference' }
     vm.paymentOrder = { accessCode: 'test-access-code', reference: 'test-reference' }
     vm.visible = true
     vm.visible = true
     vm.processPayment({ reference: 'test-reference' })
     vm.processPayment({ reference: 'test-reference' })
@@ -504,6 +512,8 @@ describe('Signup welcome-pack compatibility', () => {
     expect(vm.$message).toHaveBeenCalledWith({
     expect(vm.$message).toHaveBeenCalledWith({
       message: 'Payment submitted. Please wait for order confirmation.', type: 'success'
       message: 'Payment submitted. Please wait for order confirmation.', type: 'success'
     })
     })
+    expect(vm.$router.replace).toHaveBeenCalledTimes(1)
+    expect(vm.$router.replace).toHaveBeenCalledWith({ path: '/login', query })
     vm.onSubmit()
     vm.onSubmit()
     jest.advanceTimersByTime(6000)
     jest.advanceTimersByTime(6000)
     expect(request).not.toHaveBeenCalled()
     expect(request).not.toHaveBeenCalled()
@@ -518,5 +528,6 @@ describe('Signup welcome-pack compatibility', () => {
     expect(vm.paymentComplete).toBe(false)
     expect(vm.paymentComplete).toBe(false)
     expect(vm.$message.error).toHaveBeenCalledWith('Payment reference does not match the current order.')
     expect(vm.$message.error).toHaveBeenCalledWith('Payment reference does not match the current order.')
     expect(vm.$router.push).not.toHaveBeenCalled()
     expect(vm.$router.push).not.toHaveBeenCalled()
+    expect(vm.$router.replace).not.toHaveBeenCalled()
   })
   })
 })
 })