Browse Source

fix(shop): 修复结算页优惠券丢失——地址返回后重同步券抵扣额+区分业务/瞬时失败不清券+tasks透传修正

Bug(用户反馈):「用了优惠券,选地址再回来提交订单,显示为未用优惠券的价格」

根因(前端展示层,后端无责):
1. checkout.vue applyCouponDiscount() catch 原为无条件清空已选券,而 utils/api.js 对网络/超时等瞬时失败也 reject → 券被静默丢弃,提交时 couponId=null,后端按未用券价格建单
2. checkout.vue onShow() 从地址/编辑页返回时只重拉地址,从不向服务端重新确认已选券抵扣额,异步竞态下券价丢失后不会被纠正

修复(+14/-3,仅 checkout.vue):
- onShow() 返回分支:selectedCoupon 存在且非特价禁用券时重新调 applyCouponDiscount() 向服务端确认抵扣额(不重选未选券,_couponDismissed 语义保留)
- applyCouponDiscount() catch:仅服务端明确判定不可用(业务响应带 code)才清空已选券并归零抵扣额;瞬时失败保留券,交由下单时服务端权威裁决
- onSubmit() setTimeout 回调内 this.taskId → that.taskId(闭包修正,购买任务打卡透传)

测试:__tests__/pages/shop/checkout.couponAfterAddressReturn.spec.js(16 条源码契约,红→绿,4 项变异测试全部 RED 验证可抓缺陷);__tests__/pages/shop/ 24/24 绿,全仓基线无恶化(48 suites/703 passed 与修复前基线一致)
Agnes Agent 5 hours ago
parent
commit
0fad1a8770

+ 224 - 0
cfc-frontend/__tests__/pages/shop/checkout.couponAfterAddressReturn.spec.js

@@ -0,0 +1,224 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:shop.checkout.couponAfterAddressReturn (BUGFIX-2026-11-25)
+// 溯源·需求:主理人派单「小程序结算页优惠券丢失」——用户反馈:
+//   「选不了地址」「用了优惠券,选地址再回来提交订单,显示为未用券价格」
+// 溯源·实现:cfc-frontend/pages/shop/checkout/checkout.vue
+//   + pages/shop/address/address.vue(selectMode=1,选中写 checkoutSelectedAddressId 兜底)
+//
+// 说明:源读取契约(与既有 checkout.couponAutoSelect / order-detail.refundAndBuyAgain 同风格)。
+// 红线思维:先写能暴露缺陷的断言(RED),再修复源码(GREEN)。
+//   - RED 点 A:地址选择/编辑返回(onShow 非首次)后必须重新向服务端确认已选券抵扣额,
+//     防止「返回结算页再提交显示未用券价」。此断言已锚定「返回(else)分支」,而非只认
+//     onShow 体内出现过调用,防止被误挪到首次进入(if)分支而假绿。
+//   - RED 点 B:applyCouponDiscount 失败分支不得无条件清空已选券——仅服务端明确判定
+//     "不可用"(业务码 code 存在)才清空;瞬时失败(网络/超时)保留,交由下单权威裁决。
+//   - RED 点 C:支付页金额透传 taskId 必须用闭包变量 that(setTimeout 回调内 this 非组件实例)。
+
+const CHECKOUT_VUE = resolve(__dirname, '../../../pages/shop/checkout/checkout.vue')
+const PAYMENT_VUE = resolve(__dirname, '../../../pages/shop/payment/payment.vue')
+const source = readFileSync(CHECKOUT_VUE, 'utf8')
+
+// ---- 通用:用「括号配平」从源码中切出方法体,容忍任意缩进/换行/async 前缀 ----
+// 返回不含最外层大括号的方法体;找不到返回 ''。跳过字符串字面量与注释,防止误配平。
+function extractMethodBody(src, name) {
+  const re = new RegExp('(^|\\n)[ \\t]*(?:async\\s+)?' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*\\(')
+  const start = src.search(re)
+  if (start < 0) return ''
+  const braceIdx = src.indexOf('{', start)
+  if (braceIdx < 0) return ''
+  let depth = 0
+  let inStr = null
+  let inLineComment = false
+  let inBlockComment = false
+  let bodyStart = -1
+  for (let i = braceIdx; i < src.length; i++) {
+    const ch = src[i]
+    const next = src[i + 1]
+    if (inLineComment) {
+      if (ch === '\n') inLineComment = false
+      continue
+    }
+    if (inBlockComment) {
+      if (ch === '*' && next === '/') { inBlockComment = false; i++ }
+      continue
+    }
+    if (inStr) {
+      if (ch === '\\') { i++; continue }
+      if (ch === inStr) inStr = null
+      continue
+    }
+    if (ch === '/' && next === '/') { inLineComment = true; i++; continue }
+    if (ch === '/' && next === '*') { inBlockComment = true; i++; continue }
+    if (ch === '"' || ch === "'" || ch === '`') { inStr = ch; continue }
+    if (ch === '{') {
+      if (depth === 0) bodyStart = i + 1
+      depth++
+      continue
+    }
+    if (ch === '}') {
+      depth--
+      if (depth === 0) return src.slice(bodyStart, i)
+    }
+  }
+  return ''
+}
+
+const onShowBody = extractMethodBody(source, 'onShow')
+const applyCatchBody = extractMethodBody(source, 'applyCouponDiscount')
+const loadAddrBody = extractMethodBody(source, 'loadDefaultAddress')
+
+// onShow 体按 `} else {` 切出「首次进入(if)」与「返回(else)」两个分支
+const onShowElseIdx = onShowBody.search(/\}\s*else\s*\{/)
+const onShowIfBranch = onShowElseIdx >= 0 ? onShowBody.slice(0, onShowElseIdx) : ''
+const onShowReturnBranch = onShowElseIdx >= 0
+  ? onShowBody.slice(onShowBody.indexOf('{', onShowElseIdx) + 1)
+  : ''
+
+// 从 src 的 fromIdx 起,取下一个 `{` 开始、括号配平的块内内容(跳过字符串/注释)
+function balancedBlock(src, fromIdx) {
+  const braceIdx = src.indexOf('{', fromIdx)
+  if (braceIdx < 0) return ''
+  let depth = 0
+  let inStr = null
+  let inLineComment = false
+  let inBlockComment = false
+  let bodyStart = -1
+  for (let i = braceIdx; i < src.length; i++) {
+    const ch = src[i]
+    const next = src[i + 1]
+    if (inLineComment) {
+      if (ch === '\n') inLineComment = false
+      continue
+    }
+    if (inBlockComment) {
+      if (ch === '*' && next === '/') { inBlockComment = false; i++ }
+      continue
+    }
+    if (inStr) {
+      if (ch === '\\') { i++; continue }
+      if (ch === inStr) inStr = null
+      continue
+    }
+    if (ch === '/' && next === '/') { inLineComment = true; i++; continue }
+    if (ch === '/' && next === '*') { inBlockComment = true; i++; continue }
+    if (ch === '"' || ch === "'" || ch === '`') { inStr = ch; continue }
+    if (ch === '{') {
+      if (depth === 0) bodyStart = i + 1
+      depth++
+      continue
+    }
+    if (ch === '}') {
+      depth--
+      if (depth === 0) return src.slice(bodyStart, i)
+    }
+  }
+  return ''
+}
+
+// setTimeout 回调体(url 拼接所在上下文),用于精准断言 taskId 闭包取值
+const setTimeoutBody = (() => {
+  const idx = source.indexOf('setTimeout')
+  if (idx < 0) return ''
+  // setTimeout(function() { ... }):取 function 后首个 `{` 的配平块
+  return balancedBlock(source, idx)
+})()
+// 支付页跳转 url 行(仅限 setTimeout 回调内;找不到则回退全文件)
+function paymentUrlLines(scope) {
+  return scope.split('\n').filter(l => /url\s*:\s*['"`]\/?pages\/shop\/payment\/payment/.test(l))
+}
+let urlLines = paymentUrlLines(setTimeoutBody || source)
+if (urlLines.length === 0) urlLines = paymentUrlLines(source)
+
+// RED-B:catch 块必须存在「对业务码 code 的存在性判断」——容忍等价写法
+const hasCodeExistenceGuard = [
+  /e\s*&&\s*e\.code/,                                   // e && e.code(短路守卫)
+  /e\.code\s*!=\s*null/,
+  /e\.code\s*!==\s*null/,
+  /e\.code\s*!=\s*undefined/,
+  /e\.code\s*!==\s*undefined/,
+  /typeof\s+e\.code\s*!==?\s*['"`]undefined['"`]/,      // typeof e.code !== 'undefined'
+  /['"`]code['"`]\s*in\s*e/                              // 'code' in e
+].some(re => re.test(applyCatchBody))
+
+describe('checkout.vue 选地址返回后优惠券不丢失(BUGFIX-2026-11-25)', () => {
+  // ---- RED-A:返回分支必须重同步券抵扣 ----
+  test('RED-A:onShow 返回(else)分支重新向服务端确认已选券抵扣额', () => {
+    expect(onShowReturnBranch).toMatch(/applyCouponDiscount\s*\(\s*\)/)
+  })
+
+  test('RED-A-防漂移:首次进入(if)分支不得触发券重同步', () => {
+    // 若被误挪到首次分支,onShow 首次进入就会重复调 /api/coupon/apply(双请求)
+    expect(onShowIfBranch).not.toMatch(/applyCouponDiscount\s*\(\s*\)/)
+  })
+
+  test('RED-A-返回路径仍刷新地址:返回分支须调用 loadDefaultAddress()', () => {
+    expect(onShowReturnBranch).toMatch(/loadDefaultAddress\s*\(\s*\)/)
+  })
+
+  test('RED-A-守卫:onShow 返回路径不得清空已选券或抵扣额', () => {
+    expect(onShowReturnBranch).not.toMatch(/selectedCoupon\s*=\s*null/)
+    expect(onShowReturnBranch).not.toMatch(/couponDiscount\s*=\s*0/)
+  })
+
+  test('RED-A-条件:返回重同步须同时满足「已选券」与「非特价禁用券」', () => {
+    // 防止漂移成无条件调用(每次返回都打一次接口)——特价禁用券/已取消券都不应重同步
+    expect(onShowReturnBranch).toMatch(/this\.selectedCoupon\s*&&/)
+    expect(onShowReturnBranch).toMatch(/!this\.isSpecialCouponDisabled/)
+  })
+
+  // ---- RED-B:失败分支不得无条件清空已选券 ----
+  test('RED-B:applyCouponDiscount 失败分支须校验业务码 code 的存在性(容忍等价写法)', () => {
+    expect(hasCodeExistenceGuard).toBe(true)
+  })
+
+  test('RED-B-守卫:业务性不可用仍要清空已选券并归零抵扣额(展示与提交一致)', () => {
+    expect(applyCatchBody).toMatch(/selectedCoupon\s*=\s*null/)
+    expect(applyCatchBody).toMatch(/couponDiscount\s*=\s*0/)
+  })
+
+  test('RED-B-受控清空:清空动作必须位于「业务码判断」之后(不得先清后判)', () => {
+    const guardIdx = applyCatchBody.search(/e\.code/)
+    const clearIdx = applyCatchBody.indexOf('selectedCoupon = null')
+    expect(guardIdx).toBeGreaterThanOrEqual(0)
+    expect(clearIdx).toBeGreaterThanOrEqual(0)
+    expect(clearIdx).toBeGreaterThan(guardIdx)
+  })
+
+  // ---- 提交与支付契约 ----
+  test('提交订单透传 couponId(已选券 id,未选为 null)', () => {
+    expect(source).toMatch(/couponId\s*:\s*that\.selectedCoupon\s*\?\s*that\.selectedCoupon\.id\s*:\s*null/)
+  })
+
+  test('支付页金额来源:优先后端权威 moneyAmount,兜底 totalAmount', () => {
+    expect(source).toMatch(/order\.moneyAmount\s*!=\s*null\s*\?\s*order\.moneyAmount\s*:\s*order\.totalAmount/)
+  })
+
+  test('支付页跳转:taskId 透传用闭包变量 that(setTimeout 回调内 this 非组件实例)', () => {
+    expect(urlLines.length).toBeGreaterThan(0)
+    expect(urlLines.some(l => /that\.taskId\s*\?\s*['"`]&taskId=['"`]\s*\+\s*that\.taskId/.test(l))).toBe(true)
+  })
+
+  test('支付页跳转:taskId 取值不得误用 this(this.taskId 在 URL 拼接语境即缺陷)', () => {
+    expect(urlLines.some(l => /this\.taskId/.test(l))).toBe(false)
+  })
+
+  // ---- 地址兜底(症状1):读取 + 一次性消费 ----
+  test('地址兜底-读:loadDefaultAddress 读取 checkoutSelectedAddressId', () => {
+    expect(loadAddrBody).toMatch(/getStorageSync\s*\(\s*['"`]checkoutSelectedAddressId['"`]\s*\)/)
+  })
+
+  test('地址兜底-消费:loadDefaultAddress 一次性 removeStorageSync(防止旧值复用于下次)', () => {
+    expect(loadAddrBody).toMatch(/removeStorageSync\s*\(\s*['"`]checkoutSelectedAddressId['"`]\s*\)/)
+  })
+
+  test('地址选中兜底:结算页与地址页共用 checkoutSelectedAddressId 契约', () => {
+    expect(source).toMatch(/checkoutSelectedAddressId/)
+  })
+
+  test('支付页直接展示 amount 参数(不透传原始商品总额)', () => {
+    const paymentSource = readFileSync(PAYMENT_VUE, 'utf8')
+    expect(paymentSource).toMatch(/parseFloat\(options\.amount\)/)
+  })
+})

+ 14 - 3
cfc-frontend/pages/shop/checkout/checkout.vue

@@ -703,6 +703,13 @@ export default {
       this._onLoadFired = false
     } else {
       this.loadDefaultAddress()
+      // 地址选择/编辑返回后重新向服务端确认已选券的抵扣额:
+      // 防止异步竞态下 selectedCoupon/couponDiscount 被丢弃或未同步,
+      // 导致「返回结算页再提交订单显示为未用券价格」(优惠静默丢失)。
+      // 仅当已选中券且非特价禁用券时重同步;未选券(_couponDismissed)不重选。
+      if (this.selectedCoupon && !this.isSpecialCouponDisabled) {
+        this.applyCouponDiscount()
+      }
     }
   },
   methods: {
@@ -894,8 +901,11 @@ export default {
         }
         this.couponDiscount = (res && res.data && res.data.discount) || 0
       } catch (e) {
-        if (this.selectedCoupon && this.selectedCoupon.id === applyingCouponId) {
-          // 服务端判定不可用(request 已提示 message),本地同步清空避免错误展示
+        // 仅「服务端明确判定不可用」才清空已选券(业务响应带 code/message,request 已提示 message);
+        // 瞬时失败(网络中断/超时,e.code 为空)保留已选券,交由下单时服务端权威裁决。
+        // 否则会出现「选券 → 选地址返回 → 提交订单」时券被静默清空、订单按未用券价格创建的回归。
+        if (this.selectedCoupon && this.selectedCoupon.id === applyingCouponId
+            && e && e.code != null) {
           this.selectedCoupon = null
           this.couponDiscount = 0
         }
@@ -1252,8 +1262,9 @@ export default {
             var moneyAmount = order.moneyAmount != null ? order.moneyAmount : order.totalAmount
             var pointsUsed = order.pointsUsed || 0
             setTimeout(function() {
+              // setTimeout 回调内 this 非组件实例,taskId 必须经闭包 that 取,否则购买任务打卡透传丢失
               uni.navigateTo({
-                url: '/pages/shop/payment/payment?orderNo=' + order.orderNo + '&amount=' + moneyAmount + '&pointsUsed=' + pointsUsed + (this.taskId ? '&taskId=' + this.taskId : '')
+                url: '/pages/shop/payment/payment?orderNo=' + order.orderNo + '&amount=' + moneyAmount + '&pointsUsed=' + pointsUsed + (that.taskId ? '&taskId=' + that.taskId : '')
               })
             }, 1000)
           } else {