Browse Source

fix(train-frontend): M2 契约对齐——发码切学员侧端点、scan 兼容键、cohort 报名态

- api/attendance.js:发码/换码主链路切换为学员侧端点 /api/attendance/session/code、/rotate
  (移除 admin 优先链——旧链讲师先吃 401 会被 utils/api.js 清登录态踢下线,严重回归)
- pages/attendance/scan.vue:已签到判定兼容 alreadyExists===true || attended===true;
  时间展示 time || attendedAt
- pages/cohort/detail.vue:isSigned 补 signupStatus ∈ {pending, approved, signed},
  配合 detail 接口新增 signedUp/signupStatus
- 学时键兜底(creditTheoryHours/theoryHours 分钟),展示层统一 creditHours()/60
- npm run build:h5 exit 0;admin 端点串 0 残留、getAttendanceSessionCode 0 残留
liaoxg 2 days ago
parent
commit
07a7c5a4c5

+ 37 - 12
train-frontend/api/attendance.js

@@ -7,26 +7,51 @@ import { request } from '@/utils/api.js'
 
 /**
  * 反向扫码签到 ★幂等 + 同事务
- * 入参:{sessionId: Long 必填, code: String 必填}(cohortId 由 session 推导,可不传)
- * 出参:{attended: boolean, name: String, time: String}
+ * 入参:{code: String 必填}(场次由签到码唯一反查推导,无需传 sessionId)
+ * 出参:{alreadyExists: boolean, attended?: boolean, name?: String, time?: String, attendedAt?: String}
+ *   alreadyExists=true / attended=true 均表示本场次已签到过(不重复入账)
+ *   time='yyyy-MM-dd HH:mm'、attendedAt 兼容旧键
  * 错误:401「请先登录」/ 500「签到码已过期,请重新扫码」/ 500「签到码无效」
+ *       500「未通过该批次报名审核,无法签到」(须批次报名 approved)
  */
-export function attendanceScan(sessionId, code) {
+export function attendanceScan(code) {
   return request('/api/attendance/scan', 'POST', {
-    sessionId: sessionId,
     code: code
   }, { silent: true })
 }
 
 /**
  * 场次签到码下发(讲师/组织端出码用)
- * ⚠【待确认】后端 §7.1 未单列出码接口;默认由 session 相关接口下发 code 串,
- *  前端本地生成二维码(禁外链图片服务,离线可用)。此接口为 add 预留。
- * 入参:{sessionId}
- * 出参:{sessionId, code, sessionName?, cohortName?, startAt?, endAt?}
+ * 主链路使用学员侧端点 `/api/attendance/session/code`(权限:平台admin | 机构管理者 | 该批次讲师本人)。
+ * ⚠ 勿再优先打 admin 端点:非平台 admin 会收到 401,utils/api.js 的 401 分支会**清除登录态并弹登录失效**,
+ *   即使 catch 回退成功也会把讲师/机构管理者踢出登录,是严重回归。
+ * 入参:{sessionId, sessionHours?(分钟), category?, note?}
+ * 出参:{code:String, validTo, expireAt(同 validTo), cohortName, startAt, endAt, sessionName}
  */
-export function getAttendanceSessionCode(sessionId) {
-  return request('/api/attendance/session/code', 'POST', {
-    sessionId: sessionId
-  }, { silent: true })
+export function issueAttendanceCode(sessionId, extra) {
+  var body = { sessionId: sessionId }
+  if (extra) {
+    if (extra.sessionHours) body.sessionHours = extra.sessionHours
+    if (extra.category) body.category = extra.category
+    if (extra.note) body.note = extra.note
+  }
+  return request('/api/attendance/session/code', 'POST', body, { silent: true })
+}
+
+/**
+ * 换码(旧码立即失效)
+ * 主链路为学员侧端点 `/api/attendance/session/rotate`;失败时回退重新发码。
+ * 入参:{sessionId, sessionHours?(分钟), category?, note?}
+ */
+export function rotateAttendanceCode(sessionId, extra) {
+  var body = { sessionId: sessionId }
+  if (extra) {
+    if (extra.sessionHours) body.sessionHours = extra.sessionHours
+    if (extra.category) body.category = extra.category
+    if (extra.note) body.note = extra.note
+  }
+  return request('/api/attendance/session/rotate', 'POST', body, { silent: true }).catch(function() {
+    // 回退:重新发码(失败原因由调用方展示错误态)
+    return issueAttendanceCode(sessionId, extra)
+  })
 }

+ 4 - 1
train-frontend/api/cohort.js

@@ -26,7 +26,10 @@ export function getCohortList(params) {
 /**
  * 批次详情
  * 入参:{cohortId}
- * ⚠ 后端 §7.1 暂未单列 detail,优先走 list 冗余;此接口作为 add 预留,失败时由页面回退 list 数据。
+ * 权限:学员侧已上线,published/closed 可查。
+ * 出参:基础字段 + 额外 signedUp(boolean)/signupStatus('pending'|'approved'|...) 供报名态判断;
+ *       与列表同键:creditTheory/creditPractice(分钟)、signedCount、teacherName、place、signupDeadline 等。
+ * 错误:404「批次不存在」;失败时页面回退列表缓存。
  */
 export function getCohortDetail(cohortId) {
   return request('/api/cohort/detail', 'POST', { cohortId: cohortId }, { silent: true })

+ 5 - 3
train-frontend/api/credit.js

@@ -9,10 +9,12 @@ import { request } from '@/utils/api.js'
 
 /**
  * 我的学时账户
- * 入参:{year?: int = 当前年}
- * 出参:{year, total, theory, practice, gap,
+ * 入参:{year?: int = 当前年}(历史年走后端台账聚合,明细 status='settled')
+ * 出参(后端实际实现):{year, totalHours, theoryHours, practiceHours, effectiveHours, pendingHours,
  *        detail:[{id,sourceType,sourceId,hours,theory,practice,status,effectiveAt}]}
- * status: pending | effective | objected | rejected(明细单位同为分钟)
+ * 兼容键(设计文档 §7.1 旧表述):total / theory / practice / gap / list
+ * status: pending | effective | objected | rejected | settled
+ * ⚠ 所有学时数值字段一律为【分钟整数】(含字段名带 Hours 的),展示层统一 creditHours() /60。
  * 错误:401
  */
 export function getCreditMine(year) {

+ 2 - 0
train-frontend/components/status-tag.vue

@@ -56,6 +56,7 @@ export default {
         pending: '待生效',
         objected: '异议中',
         rejected: '已驳回',
+        settled: '已结算',
         // 签到
         success: '签到成功',
         dupe: '已签到',
@@ -81,6 +82,7 @@ export default {
         pending: 'orange',
         objected: 'blue',
         rejected: 'red',
+        settled: 'grey',
         success: 'green',
         dupe: 'blue',
         invalid: 'red',

+ 33 - 8
train-frontend/pages/attendance/qr.vue

@@ -17,8 +17,9 @@
       <!-- 倒计时 + 刷新 -->
       <view class="countdown-row">
         <text class="countdown-label">二维码 {{ countdown }}s 后自动刷新</text>
+        <text v-if="validTo" class="valid-to">(后端有效期 {{ validTo }})</text>
       </view>
-      <button class="big-btn refresh-btn" :disabled="drawing" @click="refreshCode">刷新换码</button>
+      <button class="big-btn refresh-btn" :disabled="drawing || isRotate" @click="refreshCode">{{ isRotate ? '换码中...' : '刷新换码' }}</button>
       <text class="qr-tip">· 每次刷新旧码立即失效,防照片回放</text>
       <text class="qr-tip">· 让学员扫码,或让其手动输入下方签到码</text>
 
@@ -43,7 +44,7 @@
 
 <script>
 import UQRCode from '@/common/uqrcode.js'
-import { getAttendanceSessionCode } from '@/api/attendance.js'
+import { issueAttendanceCode, rotateAttendanceCode } from '@/api/attendance.js'
 import { formatDateTime } from '@/utils/format.js'
 import ErrorState from '@/components/error-state.vue'
 import EmptyState from '@/components/empty-state.vue'
@@ -61,7 +62,9 @@ export default {
       sessionTime: '',
       drawing: false,
       error: false,
+      isRotate: false,
       countdown: AUTO_SECONDS,
+      validTo: '',
       timer: null,
       canvasSize: 220
     }
@@ -70,6 +73,10 @@ export default {
     if (options && options.sessionId) {
       this.sessionId = String(options.sessionId)
     }
+    // H5 下可支持通过 query 预置场次名,便于讲师快速核对
+    if (options && options.sessionName) {
+      this.sessionName = String(options.sessionName)
+    }
     // 自适应画布尺寸(不小于 200px,不超过屏宽 - 80)
     var info = uni.getSystemInfoSync()
     var winW = info.windowWidth || 375
@@ -88,11 +95,15 @@ export default {
       var self = this
       self.error = false
       self.drawing = true
-      getAttendanceSessionCode(this.sessionId).then(function(res) {
+      // 出码走 admin issueCode(api 层内置用户侧端点回退链)
+      issueAttendanceCode(this.sessionId).then(function(res) {
         var data = (res && res.data) ? res.data : {}
         self.code = data.code || ''
-        self.sessionName = data.sessionName || data.name || '现场签到码'
+        if (!self.sessionName) {
+          self.sessionName = data.sessionName || data.name || '现场签到码'
+        }
         self.cohortName = data.cohortName || ''
+        self.validTo = data.validTo || data.expireAt || data.expire_time || ''
         if (data.startAt || data.endAt) {
           var s = formatDateTime(data.startAt)
           var e = formatDateTime(data.endAt)
@@ -104,6 +115,9 @@ export default {
         if (self.code) {
           self.drawQr()
           self.startCountdown()
+        } else {
+          self.error = true
+          self.clearTimer()
         }
       }).catch(function() {
         self.drawing = false
@@ -113,11 +127,21 @@ export default {
     },
     refreshCode() {
       if (this.drawing || !this.sessionId) return
-      this.loadCode()
+      this.isRotate = true
+      var self = this
+      // 换码:旧码立即失效
+      rotateAttendanceCode(this.sessionId).then(function() {
+        self.isRotate = false
+        self.loadCode()
+      }).catch(function() {
+        self.isRotate = false
+        self.error = true
+        self.clearTimer()
+      })
     },
     drawQr() {
-      var self = this
-      var content = this.sessionId + '|' + this.code
+      // 二维码内容 = 纯签到码(后端 scan 仅收 {code},场次由码反查推导)
+      var content = this.code
       try {
         var qr = new UQRCode()
         qr.data = content
@@ -194,8 +218,9 @@ export default {
   color: #7A97B5;
 }
 /* 倒计时 */
-.countdown-row { margin-bottom: 20rpx; }
+.countdown-row { margin-bottom: 20rpx; display: flex; flex-direction: column; align-items: center; }
 .countdown-label { font-size: 26rpx; color: #5B7A99; }
+.valid-to { font-size: 22rpx; color: #9DB3C9; margin-top: 6rpx; }
 .big-btn {
   width: 100%;
   height: 88rpx;

+ 20 - 36
train-frontend/pages/attendance/scan.vue

@@ -15,13 +15,9 @@
 
       <!-- 手动输入(H5 降级 + MP 备用) -->
       <view v-if="manual" class="manual-box">
-        <view v-if="!hasSessionId" class="field-row">
-          <text class="field-label">场次编号</text>
-          <input class="field-input" v-model="inputSessionId" placeholder="请输入场次编号" type="number" />
-        </view>
         <view class="field-row">
           <text class="field-label">签到码</text>
-          <input class="field-input" v-model="inputCode" placeholder="请输入签到码" maxlength="16" />
+          <input class="field-input" v-model="inputCode" placeholder="请输入签到码" maxlength="32" />
         </view>
         <button class="big-btn submit-btn" :disabled="busy" @click="submitManual">
           {{ busy ? '处理中...' : '提交签到' }}
@@ -110,59 +106,47 @@ export default {
         uni.showToast({ title: '请输入签到码', icon: 'none' })
         return
       }
-      var sessionId = this.hasSessionId
-        ? this.sessionId
-        : (this.inputSessionId || '').trim()
-      if (!sessionId) {
-        uni.showToast({ title: '请输入场次编号', icon: 'none' })
-        return
-      }
-      this.submit(String(sessionId), code)
+      this.submit(code)
     },
-    // 解析扫码内容:约定 sessionId|code;无分隔符时视作纯 code
+    // 解析扫码内容:后端 scan 入参仅 {code},场次由签到码反查推导。
+    // 兼容复合内容 sessionId|code(取末段码),纯码直接使用。
     parseAndSubmit(content) {
-      var sessionId
-      var code
+      var code = content
       if (content.indexOf('|') >= 0) {
         var parts = content.split('|')
-        sessionId = (parts[0] || '').trim()
-        code = (parts[1] || '').trim()
-      } else {
-        sessionId = this.hasSessionId ? this.sessionId : ''
-        code = content
+        code = (parts[parts.length - 1] || '').trim()
       }
       if (!code) return
-      if (!sessionId) {
-        // 无场次编号:让用户手动补场次
-        this.manual = true
-        this.inputCode = code
-        uni.showToast({ title: '请补充场次编号', icon: 'none' })
-        return
-      }
-      this.submit(sessionId, code)
+      this.submit(code)
     },
-    submit(sessionId, code) {
+    submit(code) {
       var self = this
-      // 30s 防抖:同场次同码 30s 内不重复提交(服务端幂等兜底为「已签到」)
+      // 30s 防抖:同一签到码 30s 内不重复提交(服务端幂等兜底为「已签到」)
       var now = Date.now()
-      if (self.lastCode === code + '#' + sessionId && now - self.lastTime < 30000) {
+      if (self.lastCode === code && now - self.lastTime < 30000) {
         self.showResult('dupe', '已提交,请勿重复操作', '稍后可在学时账户查看入账情况', '知道了')
         return
       }
       self.busy = true
-      self.lastCode = code + '#' + sessionId
+      self.lastCode = code
       self.lastTime = now
-      attendanceScan(sessionId, code).then(function(res) {
+      attendanceScan(code).then(function(res) {
         self.busy = false
         var data = (res && res.data) ? res.data : {}
-        var attended = data.attended !== false
-        var time = data.time || ''
+        // alreadyExists=true / attended=true → 本场次已签到过(后端不重复入账)
+        if (data.alreadyExists === true || data.attended === true) {
+          self.showResult('dupe', '已签到', '本场次已签到,无需重复操作', '知道了')
+          return
+        }
+        var time = data.time || data.attendedAt || ''
         self.showResult('success', '签到成功', '✓ 学时待 T+3 生效' + (time ? '(' + time + ')' : ''), '完成')
       }).catch(function(err) {
         self.busy = false
         var msg = (err && err.message) || ''
         if (msg.indexOf('已签到') >= 0) {
           self.showResult('dupe', '已签到', '本场次已签到,无需重复操作', '知道了')
+        } else if (msg.indexOf('审核') >= 0) {
+          self.showResult('invalid', '暂无签到资格', '未通过该批次报名审核,无法签到', '知道了')
         } else if (msg.indexOf('过期') >= 0 || msg.indexOf('无效') >= 0) {
           self.showResult('invalid', '签到码无效或已过期', '请找带教刷新签到码后重试', '重新扫码')
         } else {

+ 9 - 5
train-frontend/pages/cohort/detail.vue

@@ -115,6 +115,8 @@ export default {
     isSigned() {
       if (!this.cohortId) return false
       if (this.cohort.enrolled === true || this.cohort.signedUp === true) return true
+      var st = this.cohort.signupStatus
+      if (st === 'pending' || st === 'approved' || st === 'signed') return true
       var ids = this.localSignedIds()
       for (var i = 0; i < ids.length; i++) {
         if (String(ids[i]) === String(this.cohortId)) return true
@@ -125,7 +127,8 @@ export default {
       return this.cohort ? this.cohort.capacity || 0 : 0
     },
     signedCount() {
-      return this.cohort ? this.cohort.signedCount || 0 : 0
+      if (!this.cohort) return 0
+      return this.cohort.signedCount || this.cohort.enrolledCount || this.cohort.signupCount || 0
     },
     signPercent() {
       if (this.capacity <= 0) return 0
@@ -153,8 +156,9 @@ export default {
     },
     creditText() {
       if (!this.cohort) return ''
-      var theory = creditHours(this.cohort.creditTheory || 0)
-      var practice = creditHours(this.cohort.creditPractice || 0)
+      // 后端实际字段 creditTheoryHours/creditPracticeHours(分钟),兼容旧 creditTheory/creditPractice
+      var theory = creditHours(this.cohort.creditTheoryHours || this.cohort.creditTheory || 0)
+      var practice = creditHours(this.cohort.creditPracticeHours || this.cohort.creditPractice || 0)
       return '理论 ' + theory + ' + 实践 ' + practice + ' 学时'
     },
     deadlineText() {
@@ -187,7 +191,7 @@ export default {
           self.cohort = { id: self.cohortId }
         }
       }).catch(function() {
-        // detail 接口未上线/失败:回退列表页传入的缓存数据,保证报名可用
+        // detail 请求失败(网络/404):回退列表页传入的缓存数据,保证报名可用
         self.loading = false
         var cache = self.cacheData()
         if (cache) {
@@ -212,7 +216,7 @@ export default {
       if (status === 'closed') return 'closed'
       if (status === 'draft') return 'draft'
       var capacity = c.capacity || 0
-      var signed = c.signedCount || 0
+      var signed = c.signedCount || c.enrolledCount || c.signupCount || 0
       if (capacity > 0 && signed >= capacity) return 'full'
       var start = parseDate(c.startAt)
       var end = parseDate(c.endAt)

+ 4 - 3
train-frontend/pages/cohort/index.vue

@@ -181,8 +181,9 @@ export default {
     // 批次 → 视图模型:状态归一(可报名/进行中/已满/已截止/未发布)+ 字段兜底
     toView(c) {
       var statusKey = this.resolveStatus(c)
-      var theory = creditHours(c.creditTheory || 0)
-      var practice = creditHours(c.creditPractice || 0)
+      // 后端实际字段 creditTheoryHours/creditPracticeHours(分钟),兼容旧 creditTheory/creditPractice
+      var theory = creditHours(c.creditTheoryHours || c.creditTheory || 0)
+      var practice = creditHours(c.creditPracticeHours || c.creditPractice || 0)
       var start = formatDateTime(c.startAt)
       var end = formatDateTime(c.endAt)
       var timeText = start ? start.slice(0, 16) : '时间待定'
@@ -200,7 +201,7 @@ export default {
         creditText: theory + '+' + practice + ' 学时',
         deadlineText: deadlineText,
         capacity: c.capacity || 0,
-        signedCount: c.signedCount || 0
+        signedCount: c.signedCount || c.enrolledCount || c.signupCount || 0
       }
     },
     // 状态归一:后端 status(draft/published/closed) + 容量 + 时间窗

+ 16 - 5
train-frontend/pages/credit/index.vue

@@ -199,12 +199,19 @@ export default {
       self.error = false
       getCreditMine().then(function(res) {
         var data = (res && res.data) ? res.data : {}
+        // 后端实际实现字段:totalHours/theoryHours/practiceHours/effectiveHours/pendingHours
+        // 兼容设计文档旧字段:total/theory/practice/gap/detail
         self.year = data.year || new Date().getFullYear()
-        self.total = data.total || 0
-        self.theory = data.theory || 0
-        self.practice = data.practice || 0
-        self.gap = data.gap || 0
-        self.detail = data.detail || []
+        self.total = self.num(data.totalHours) || self.num(data.total) || 0
+        self.theory = self.num(data.theoryHours) || self.num(data.theory) || 0
+        self.practice = self.num(data.practiceHours) || self.num(data.practice) || 0
+        if (data.gap !== undefined && data.gap !== null) {
+          self.gap = self.num(data.gap)
+        } else {
+          // gap 后端未直接返回时,按年度目标兜底计算
+          self.gap = Math.max(0, TARGET_TOTAL - self.total)
+        }
+        self.detail = data.detail || data.list || []
         // 待生效明细为分页接口,先加载第一页(不足时兜底用 mine.detail 过滤)
         return getCreditPending(1, 50).then(function(resp) {
           var pdata = (resp && resp.data) ? resp.data : {}
@@ -217,6 +224,10 @@ export default {
         self.loading = false
       })
     },
+    num(v) {
+      var n = Number(v)
+      return isNaN(n) ? 0 : n
+    },
     hasAnyDetail() {
       var arr = this.detail || []
       return arr.length > 0