Lashtw commited on
Commit
bbe2c6f
·
1 Parent(s): 7d1ea3d

feat(lottery-a2): add mistake lottery pure core logic and dynamic milestones

Browse files
Files changed (2) hide show
  1. js/lottery-core.js +621 -0
  2. tools/verify-integrity.mjs +125 -0
js/lottery-core.js ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============================================================================
2
+ // js/lottery-core.js
3
+ // 錯題樂透純函數核心(不依賴 DOM / Firestore)
4
+ // - 三層錯題篩選 + 精熟收割優先序 (r2 -> r1 -> r0) + 防跨科污染
5
+ // - 單發計分、壓軸幸運銀球 + rev 2->3 黃金畢業球計算
6
+ // - 小班名額縮編、不重複加權抽獎與「向上覆蓋升級遞補」演算法
7
+ // - 智慧里程碑試算與可擴充獎勵信箱結算產生器
8
+ // ============================================================================
9
+ import { PASS_SCORE } from './config.js?v=20261114_v2';
10
+ import { getQuestionKey, calcDynamicWorldBossBalance } from './engine.js?v=20261114_v2';
11
+
12
+ export const MAX_DAILY_LOTTERY_ROUNDS = 2;
13
+ export const LOTTERY_ROUND_SIZE = 5;
14
+ export const LOTTERY_PARTICIPATION_MIN_WEIGHT = 3;
15
+ export const LOTTERY_PILOT_PARTICIPATION_MIN_WEIGHT = 2;
16
+ export const LOTTERY_DEFAULT_MILESTONES = [150, 280, 420];
17
+ export const LOTTERY_PILOT_MILESTONES = [45, 90, 140];
18
+
19
+ /** 正式週完整獎池模板 */
20
+ export const LOTTERY_DEFAULT_PRIZES = {
21
+ mode: 'standard',
22
+ participationMinWeight: LOTTERY_PARTICIPATION_MIN_WEIGHT,
23
+ tiers: [
24
+ { tierKey: 'head', label: '👑 頭獎', quota: 1, bp: 12, m1BonusBp: 2, hours: 6, peek: 2, eliminate: 2, titles: ['九州錦鯉', '天選歐皇'] },
25
+ { tierKey: 't1', label: '🥇 一獎', quota: 1, bp: 8, hours: 4, peek: 1, eliminate: 1, titles: ['鴻運先鋒'] },
26
+ { tierKey: 't2', label: '🥈 二獎', quota: 2, m2ExtraQuota: 1, bp: 5, hours: 2, peek: 1, eliminate: 0, titles: [] },
27
+ { tierKey: 't3', label: '🥉 三獎', quota: 3, bp: 3, hours: 1, peek: 0, eliminate: 1, titles: [] },
28
+ ],
29
+ participation: { bp: 1, hours: 1, peek: 0, eliminate: 0, m3BonusBp: 1, m3BonusPeek: 1 },
30
+ effort: { title: '錯題終結者', peek: 1, eliminate: 1 },
31
+ };
32
+
33
+ /** 週四快閃測試縮小版獎池模板(避免 1 日短活動過早膨脹經濟) */
34
+ export const LOTTERY_PILOT_PRIZES = {
35
+ mode: 'pilot',
36
+ participationMinWeight: LOTTERY_PILOT_PARTICIPATION_MIN_WEIGHT,
37
+ tiers: [
38
+ { tierKey: 'head', label: '👑 頭獎', quota: 1, bp: 6, m1BonusBp: 1, hours: 3, peek: 1, eliminate: 1, titles: ['九州錦鯉', '天選歐皇'] },
39
+ { tierKey: 't1', label: '🥇 一獎', quota: 1, bp: 4, hours: 2, peek: 1, eliminate: 0, titles: ['鴻運先鋒'] },
40
+ { tierKey: 't2', label: '🥈 二獎', quota: 2, m2ExtraQuota: 1, bp: 3, hours: 1, peek: 0, eliminate: 1, titles: [] },
41
+ { tierKey: 't3', label: '🥉 三獎', quota: 3, bp: 2, hours: 1, peek: 0, eliminate: 0, titles: [] },
42
+ ],
43
+ participation: { bp: 1, hours: 1, peek: 0, eliminate: 0, m3BonusBp: 0, m3BonusHours: 1, m3BonusPeek: 1 },
44
+ effort: { title: '錯題終結者', peek: 1, eliminate: 1 },
45
+ };
46
+
47
+ const TIER_RANK = { head: 4, t1: 3, t2: 2, t3: 1 };
48
+
49
+ export function getLotteryPrizeTemplate(prizeMode = 'standard') {
50
+ return prizeMode === 'pilot' ? LOTTERY_PILOT_PRIZES : LOTTERY_DEFAULT_PRIZES;
51
+ }
52
+
53
+ /** 強制歸一化題庫鍵值:英文題庫一律強制賦予 bank='english' 與 english_${n} */
54
+ export function normalizeLotteryQuestionKey(q, fallbackBank = 'wiring') {
55
+ if (!q || typeof q !== 'object') return '';
56
+ if (q.bank === 'english' || String(q.id || '').startsWith('english_')) {
57
+ const suffix = q.n ?? q.word ?? '';
58
+ if (q.id && String(q.id).startsWith('english_')) return String(q.id);
59
+ if (suffix !== '') return `english_${suffix}`;
60
+ }
61
+ if (q.id) return String(q.id);
62
+ if (q.bank || fallbackBank) {
63
+ const b = q.bank || fallbackBank;
64
+ if (q.n !== undefined && q.n !== null && q.n !== '') return `${b}_${q.n}`;
65
+ }
66
+ return getQuestionKey(q);
67
+ }
68
+
69
+ export function calcLotteryBallStats(entry) {
70
+ const regularBalls = Math.max(0, Math.floor(Number(entry?.regularBalls) || 0));
71
+ const goldenBalls = Math.max(0, Math.floor(Number(entry?.goldenBalls) || 0));
72
+ return {
73
+ regularBalls,
74
+ goldenBalls,
75
+ weight: regularBalls + goldenBalls * 2,
76
+ };
77
+ }
78
+
79
+ export function calcLotteryMilestonesProgress(entriesMap = {}, milestones = LOTTERY_DEFAULT_MILESTONES) {
80
+ const ms = Array.isArray(milestones) && milestones.length >= 3
81
+ ? milestones.map(n => Math.max(1, Number(n) || 1))
82
+ : [...LOTTERY_DEFAULT_MILESTONES];
83
+
84
+ let totalRegular = 0;
85
+ let totalGolden = 0;
86
+ let totalWeight = 0;
87
+ for (const raw of Object.values(entriesMap || {})) {
88
+ const st = calcLotteryBallStats(raw);
89
+ totalRegular += st.regularBalls;
90
+ totalGolden += st.goldenBalls;
91
+ totalWeight += st.weight;
92
+ }
93
+ const reachedLevels = [];
94
+ ms.forEach((m, idx) => {
95
+ if (totalWeight >= m) reachedLevels.push(idx + 1);
96
+ });
97
+ const nextMilestone = ms.find(m => totalWeight < m) || null;
98
+ return {
99
+ totalRegular,
100
+ totalGolden,
101
+ totalWeight,
102
+ milestones: ms,
103
+ reachedLevels,
104
+ nextMilestone,
105
+ };
106
+ }
107
+
108
+ function shuffleInPlace(arr, rng = Math.random) {
109
+ for (let i = arr.length - 1; i > 0; i--) {
110
+ const j = Math.floor(rng() * (i + 1));
111
+ [arr[i], arr[j]] = [arr[j], arr[i]];
112
+ }
113
+ return arr;
114
+ }
115
+
116
+ function matchesSubjectAndMode(m, { myBankId, questionMode, validVocQSet, validLaborQSet }) {
117
+ if (!m || !m.q || !Array.isArray(m.o)) return false;
118
+ const isEng = m.bank === 'english' || String(m.id || '').startsWith('english_');
119
+ if (questionMode === 'english') return isEng;
120
+ if (questionMode === 'vocational') {
121
+ if (isEng) return false;
122
+ }
123
+ if (isEng) return true;
124
+ if (m.bank === 'labor') {
125
+ return validLaborQSet.size > 0 ? validLaborQSet.has(m.q) : true;
126
+ }
127
+ if (m.bank && m.bank !== myBankId && m.bank !== 'default') return false;
128
+ if (validVocQSet.size > 0) return validVocQSet.has(m.q);
129
+ return true;
130
+ }
131
+
132
+ /**
133
+ * 三層防污染挑題核心(個人未精熟 r2->r1->r0 ➔ 同科同袍救援 ➔ 班級已開放題庫)
134
+ */
135
+ export function pickLotteryRoundQuestions({
136
+ game = {},
137
+ classInfo = {},
138
+ students = [],
139
+ questionPools = { vocational: [], english: [], labor: [] },
140
+ questionMode = 'mixed',
141
+ seenToday = new Set(),
142
+ count = LOTTERY_ROUND_SIZE,
143
+ studentUid = null,
144
+ rng = Math.random,
145
+ } = {}) {
146
+ const myBankId = classInfo?.bank || classInfo?.bankId || 'wiring';
147
+ const vocRaw = Array.isArray(questionPools?.vocational) ? questionPools.vocational : [];
148
+ const laborRaw = Array.isArray(questionPools?.labor) ? questionPools.labor : [];
149
+ const engRaw = Array.isArray(questionPools?.english) ? questionPools.english : [];
150
+
151
+ const validVocQSet = new Set(vocRaw.map(q => q.q).filter(Boolean));
152
+ const validLaborQSet = new Set(laborRaw.map(q => q.q).filter(Boolean));
153
+ const seenSet = seenToday instanceof Set ? seenToday : new Set(Array.isArray(seenToday) ? seenToday : []);
154
+
155
+ const isUnmastered = (m) => m && !m.mastered && (Number(m.reviewCorrectCount) || 0) < 3;
156
+
157
+ // 1. 第一層:個人未精熟錯題,嚴格按 rev=2 -> rev=1 -> rev=0 排序收割
158
+ const myCandidates = Object.values(game?.mistakes || {})
159
+ .filter(m => isUnmastered(m) && matchesSubjectAndMode(m, { myBankId, questionMode, validVocQSet, validLaborQSet }))
160
+ .map(m => {
161
+ const normalizedBank = m.bank === 'english' ? 'english' : (m.bank === 'labor' ? 'labor' : myBankId);
162
+ const qKey = normalizeLotteryQuestionKey({ ...m, bank: normalizedBank }, myBankId);
163
+ const rev = Math.max(0, Math.min(2, Number(m.reviewCorrectCount) || 0));
164
+ return {
165
+ ...m,
166
+ bank: normalizedBank,
167
+ _qKey: qKey,
168
+ _revCount: rev,
169
+ _layer: 'my',
170
+ _tag: rev === 2 ? '✨ 精熟收割 r2(答對掉金球)' : `🎯 個人錯題 r${rev}`,
171
+ _tieSort: rng(),
172
+ };
173
+ });
174
+
175
+ // 未見過同日題號優先,同階層依 rev 降序 (r2 -> r1 -> r0)
176
+ myCandidates.sort((a, b) => {
177
+ const aSeen = seenSet.has(a._qKey) ? 1 : 0;
178
+ const bSeen = seenSet.has(b._qKey) ? 1 : 0;
179
+ if (aSeen !== bSeen) return aSeen - bSeen;
180
+ if (b._revCount !== a._revCount) return b._revCount - a._revCount;
181
+ return a._tieSort - b._tieSort;
182
+ });
183
+
184
+ const picked = [];
185
+ const usedKeys = new Set();
186
+ const tryPush = (item) => {
187
+ if (picked.length >= count) return;
188
+ if (!item || !item._qKey) return;
189
+ if (usedKeys.has(item._qKey)) return;
190
+ usedKeys.add(item._qKey);
191
+ picked.push(item);
192
+ };
193
+
194
+ // 先抽未在 seenSet 中的個人錯題
195
+ for (const item of myCandidates) {
196
+ if (seenSet.has(item._qKey)) continue;
197
+ tryPush(item);
198
+ }
199
+
200
+ // 2. 第二層:同袍未精熟錯題(排除教師與 20 號測試號)
201
+ if (picked.length < count && Array.isArray(students)) {
202
+ const peerPool = [];
203
+ for (const s of students) {
204
+ if (!s || s.role === 'teacher' || Number(s.seat) === 20) continue;
205
+ if (studentUid && s.uid === studentUid) continue;
206
+ const sBank = s.bankId || s.bank || myBankId;
207
+ for (const sm of Object.values(s.game?.mistakes || {})) {
208
+ if (!isUnmastered(sm)) continue;
209
+ const isEng = sm.bank === 'english' || String(sm.id || '').startsWith('english_');
210
+ if (!isEng && sm.bank !== 'labor' && sBank !== myBankId) continue;
211
+ if (!matchesSubjectAndMode(sm, { myBankId, questionMode, validVocQSet, validLaborQSet })) continue;
212
+ const normalizedBank = isEng ? 'english' : (sm.bank === 'labor' ? 'labor' : myBankId);
213
+ const qKey = normalizeLotteryQuestionKey({ ...sm, bank: normalizedBank }, myBankId);
214
+ if (seenSet.has(qKey) || usedKeys.has(qKey)) continue;
215
+ peerPool.push({
216
+ ...sm,
217
+ bank: normalizedBank,
218
+ _qKey: qKey,
219
+ _revCount: Math.max(0, Math.min(2, Number(sm.reviewCorrectCount) || 0)),
220
+ _layer: 'peer',
221
+ _donorSeat: s.seat || '',
222
+ _donorName: s.name || `座號${s.seat || ''}`,
223
+ _tag: `🤝 同袍座號 ${s.seat || '?'} 錯題救援`,
224
+ });
225
+ }
226
+ }
227
+ shuffleInPlace(peerPool, rng);
228
+ for (const item of peerPool) tryPush(item);
229
+ }
230
+
231
+ // 3. 第三層:已開放單元標準題庫
232
+ if (picked.length < count) {
233
+ const stdPool = [];
234
+ if (questionMode !== 'english') {
235
+ for (const vq of [...vocRaw, ...laborRaw]) {
236
+ const bank = vq.bank || myBankId;
237
+ const qKey = normalizeLotteryQuestionKey({ ...vq, bank }, myBankId);
238
+ stdPool.push({
239
+ ...vq,
240
+ bank,
241
+ _qKey: qKey,
242
+ _revCount: Math.max(0, Math.min(2, Number(game?.mistakes?.[qKey]?.reviewCorrectCount) || 0)),
243
+ _layer: 'bank',
244
+ _tag: '📘 基礎複習題庫',
245
+ });
246
+ }
247
+ }
248
+ if (questionMode !== 'vocational') {
249
+ for (const eq of engRaw) {
250
+ const qKey = normalizeLotteryQuestionKey({ ...eq, bank: 'english' }, 'english');
251
+ stdPool.push({
252
+ ...eq,
253
+ bank: 'english',
254
+ _qKey: qKey,
255
+ _revCount: Math.max(0, Math.min(2, Number(game?.mistakes?.[qKey]?.reviewCorrectCount) || 0)),
256
+ _layer: 'bank',
257
+ _tag: '❄️ 西域單字複習',
258
+ });
259
+ }
260
+ }
261
+ shuffleInPlace(stdPool, rng);
262
+ for (const item of stdPool) {
263
+ if (seenSet.has(item._qKey)) continue;
264
+ tryPush(item);
265
+ }
266
+ // 極端備援:題庫小到不足時才允許納入剩餘個人/題庫候補
267
+ if (picked.length < count) {
268
+ for (const item of [...myCandidates, ...stdPool]) {
269
+ tryPush(item);
270
+ }
271
+ }
272
+ }
273
+
274
+ return picked.slice(0, count);
275
+ }
276
+
277
+ /**
278
+ * 單發計分純函數:
279
+ * - 答錯 → 0 球
280
+ * - 同日同題重做 → 0 球(duplicateSkipped: true)
281
+ * - 一般答對 → +1 銀球;若 curRevCount === 2(精熟 2->3 畢業)→ 改以 +1 金球取代銀球
282
+ * - 若為壓軸第 5 題 (questionIndex === roundSize - 1) → 額外加贈 +1 幸運銀球(故剛好畢業時回傳 1 金 + 1 銀)
283
+ */
284
+ export function scoreLotteryAnswer({
285
+ q,
286
+ isCorrect,
287
+ curRevCount = 0,
288
+ questionIndex = 0,
289
+ roundSize = LOTTERY_ROUND_SIZE,
290
+ seenKeysSet = new Set(),
291
+ } = {}) {
292
+ const qKey = q?._qKey || normalizeLotteryQuestionKey(q);
293
+ if (!isCorrect) {
294
+ return {
295
+ awardedRegular: 0,
296
+ awardedGold: 0,
297
+ triggeredGraduationGold: false,
298
+ awardedLuckyBonus: false,
299
+ duplicateSkipped: false,
300
+ };
301
+ }
302
+ if (qKey && seenKeysSet?.has?.(qKey)) {
303
+ return {
304
+ awardedRegular: 0,
305
+ awardedGold: 0,
306
+ triggeredGraduationGold: false,
307
+ awardedLuckyBonus: false,
308
+ duplicateSkipped: true,
309
+ };
310
+ }
311
+ const triggeredGraduationGold = Number(curRevCount) === 2;
312
+ const awardedLuckyBonus = Number(questionIndex) === (Number(roundSize) - 1);
313
+ const awardedGold = triggeredGraduationGold ? 1 : 0;
314
+ const awardedRegular = (triggeredGraduationGold ? 0 : 1) + (awardedLuckyBonus ? 1 : 0);
315
+ return {
316
+ awardedRegular,
317
+ awardedGold,
318
+ triggeredGraduationGold,
319
+ awardedLuckyBonus,
320
+ duplicateSkipped: false,
321
+ };
322
+ }
323
+
324
+ function roundToNearest5(val) {
325
+ return Math.max(10, Math.round((Number(val) || 0) / 5) * 5);
326
+ }
327
+
328
+ /**
329
+ * 共用班級錯題水位掃描,試算樂透推薦三階里程碑與預估清題率
330
+ */
331
+ export function calcDynamicLotteryBalance(students = [], { targetDays = 5, prizeMode = 'standard' } = {}) {
332
+ const scan = calcDynamicWorldBossBalance(students, { targetDays });
333
+ const activeCount = Math.max(1, Number(scan.studentCount) || 1);
334
+ const days = Math.max(1, Number(targetDays) || 1);
335
+ const attendance = Number(scan.attendanceRate) || 0.8;
336
+
337
+ // 每位實到學生每日約產出 10 籤權(8 題答對+第5題幸運球+畢業金球加成)
338
+ const effectiveDays = days <= 2 ? days : Math.min(days, 4.5);
339
+ const expectedTotalWeight = activeCount * attendance * effectiveDays * 10;
340
+
341
+ let recommendedMilestones;
342
+ if (days <= 2 || prizeMode === 'pilot') {
343
+ recommendedMilestones = [
344
+ roundToNearest5(expectedTotalWeight * 0.40),
345
+ roundToNearest5(expectedTotalWeight * 0.80),
346
+ roundToNearest5(expectedTotalWeight * 1.25),
347
+ ];
348
+ } else {
349
+ recommendedMilestones = [
350
+ roundToNearest5(expectedTotalWeight * 0.30),
351
+ roundToNearest5(expectedTotalWeight * 0.56),
352
+ roundToNearest5(expectedTotalWeight * 0.835),
353
+ ];
354
+ }
355
+
356
+ const avgMistakes = Number(scan.avgVocMistakes || 0) + Number(scan.avgEngMistakes || 0);
357
+ const totalReviewsNeeded = (Number(scan.totalVocReviewsNeeded) || 0) + (Number(scan.totalEngReviewsNeeded) || 0);
358
+ const avgReviewsPerStudent = totalReviewsNeeded / activeCount;
359
+ const expectedCorrectInWindow = effectiveDays * 10 * 0.8;
360
+ const estimatedClearancePct = avgMistakes > 0
361
+ ? Math.min(99, Math.round((Math.min(avgReviewsPerStudent, expectedCorrectInWindow) / Math.max(1, avgReviewsPerStudent)) * 100))
362
+ : 100;
363
+
364
+ return {
365
+ studentCount: scan.studentCount,
366
+ attendanceRate: attendance,
367
+ targetDays: days,
368
+ totalVocMistakes: scan.totalVocMistakes,
369
+ totalEngMistakes: scan.totalEngMistakes,
370
+ totalMistakes: scan.totalMistakes,
371
+ totalVocReviewsNeeded: scan.totalVocReviewsNeeded,
372
+ totalEngReviewsNeeded: scan.totalEngReviewsNeeded,
373
+ totalReviewsNeeded,
374
+ avgMistakes: Math.round(avgMistakes * 10) / 10,
375
+ estimatedClearancePct,
376
+ expectedTotalWeightLow: Math.round(expectedTotalWeight * 0.85),
377
+ expectedTotalWeightHigh: Math.round(expectedTotalWeight * 1.15),
378
+ recommendedMilestones,
379
+ };
380
+ }
381
+
382
+ /** 若參加人數少於主要獎項總名額,等比縮編(優先保住頭獎與高階名額,防無窮迴圈) */
383
+ export function shrinkTierQuotas(prizeTemplate = LOTTERY_DEFAULT_PRIZES, eligibleCount = 0) {
384
+ const tiers = (prizeTemplate?.tiers || []).map(t => ({ ...t }));
385
+ const cap = Math.max(0, Math.floor(Number(eligibleCount) || 0));
386
+ const totalWanted = tiers.reduce((s, t) => s + t.quota, 0);
387
+ if (cap >= totalWanted) return tiers;
388
+ if (cap === 0) return tiers.map(t => ({ ...t, quota: 0 }));
389
+
390
+ // 先從低階 t3 -> t2 -> t1 -> head 縮減到為止
391
+ let remaining = totalWanted;
392
+ for (let pass = 0; pass < 10 && remaining > cap; pass++) {
393
+ for (let i = tiers.length - 1; i >= 0 && remaining > cap; i--) {
394
+ if (tiers[i].quota > (pass === 0 ? 1 : 0)) {
395
+ tiers[i].quota -= 1;
396
+ remaining -= 1;
397
+ }
398
+ }
399
+ }
400
+ return tiers;
401
+ }
402
+
403
+ export function createLotteryDrawState(prizeTemplate = LOTTERY_DEFAULT_PRIZES, eligibleEntries = [], reachedMilestones = []) {
404
+ const list = Array.isArray(eligibleEntries) ? eligibleEntries : Object.values(eligibleEntries || {});
405
+ const validPool = list
406
+ .map(e => ({ ...e, ...calcLotteryBallStats(e) }))
407
+ .filter(e => e.uid && e.weight > 0);
408
+
409
+ const m2Hit = Array.isArray(reachedMilestones) && reachedMilestones.includes(2);
410
+ const rawTemplate = {
411
+ ...prizeTemplate,
412
+ tiers: (prizeTemplate?.tiers || []).map(t => ({
413
+ ...t,
414
+ quota: t.tierKey === 't2' && m2Hit ? t.quota + (Number(t.m2ExtraQuota) || 0) : t.quota,
415
+ })),
416
+ };
417
+
418
+ const shrunkTiers = shrinkTierQuotas(rawTemplate, validPool.length);
419
+ const holdersByTier = {};
420
+ for (const t of shrunkTiers) holdersByTier[t.tierKey] = [];
421
+
422
+ return {
423
+ prizeMode: prizeTemplate?.mode || 'standard',
424
+ prizeTiers: shrunkTiers,
425
+ holdersByTier,
426
+ uidToTier: {},
427
+ eligiblePool: validPool,
428
+ extraDrawsByTier: {},
429
+ extraBonusesByUid: {},
430
+ };
431
+ }
432
+
433
+ /** 依加權籤數抽出一位未被排除之得主,並附帶 2 位「差一點」名單供動畫呈現 */
434
+ export function drawWeightedWinner(eligiblePool = [], excludeUids = new Set(), rng = Math.random) {
435
+ const excl = excludeUids instanceof Set ? excludeUids : new Set(excludeUids || []);
436
+ const pool = (eligiblePool || []).filter(e => e && e.uid && e.weight > 0 && !excl.has(e.uid));
437
+ const totalW = pool.reduce((s, e) => s + e.weight, 0);
438
+ if (pool.length === 0 || totalW <= 0) return { winner: null, nearMisses: [] };
439
+
440
+ let r = rng() * totalW;
441
+ let winner = pool[pool.length - 1];
442
+ for (const item of pool) {
443
+ r -= item.weight;
444
+ if (r <= 0) {
445
+ winner = item;
446
+ break;
447
+ }
448
+ }
449
+ const others = pool.filter(e => e.uid !== winner.uid);
450
+ const nearMisses = [];
451
+ for (let i = 0; i < Math.min(2, others.length); i++) {
452
+ nearMisses.push(others[Math.floor(rng() * others.length)]);
453
+ }
454
+ return { winner, nearMisses };
455
+ }
456
+
457
+ /**
458
+ * 將抽中候選人寫入指定獎階,支援「先中三獎、後中頭獎 → 升級並自動空出原三獎重抽遞補」
459
+ */
460
+ export function applyTierDrawWithUpgrade({ state, tierKey, candidateUid }) {
461
+ if (!state || !tierKey || !candidateUid) {
462
+ return { state, action: 'noop', upgradedFromTier: null, vacatedTier: null, holdersByTier: state?.holdersByTier || {} };
463
+ }
464
+ const nextHolders = {};
465
+ for (const k of Object.keys(state.holdersByTier || {})) {
466
+ nextHolders[k] = [...state.holdersByTier[k]];
467
+ }
468
+ const nextUidToTier = { ...(state.uidToTier || {}) };
469
+ const prevTier = nextUidToTier[candidateUid] || null;
470
+ const newRank = TIER_RANK[tierKey] || 0;
471
+ const prevRank = prevTier ? (TIER_RANK[prevTier] || 0) : 0;
472
+
473
+ if (prevTier && prevRank >= newRank) {
474
+ return { state, action: 'noop', upgradedFromTier: null, vacatedTier: null, holdersByTier: nextHolders };
475
+ }
476
+
477
+ let upgradedFromTier = null;
478
+ let vacatedTier = null;
479
+ if (prevTier) {
480
+ upgradedFromTier = prevTier;
481
+ vacatedTier = prevTier;
482
+ nextHolders[prevTier] = (nextHolders[prevTier] || []).filter(id => id !== candidateUid);
483
+ }
484
+ nextHolders[tierKey] = [...(nextHolders[tierKey] || []), candidateUid];
485
+ nextUidToTier[candidateUid] = tierKey;
486
+
487
+ const nextState = {
488
+ ...state,
489
+ holdersByTier: nextHolders,
490
+ uidToTier: nextUidToTier,
491
+ };
492
+ return {
493
+ state: nextState,
494
+ action: upgradedFromTier ? 'upgraded' : 'assigned',
495
+ upgradedFromTier,
496
+ vacatedTier,
497
+ holdersByTier: nextHolders,
498
+ };
499
+ }
500
+
501
+ /** 產出完整開獎結算報表與個人化信箱禮物清單(含全班里程碑與奇蹟骰加碼上限防爆) */
502
+ export function buildLotterySettlement({ cycle = {}, drawState = {}, extraBonuses = {} } = {}) {
503
+ const entries = cycle?.entries || {};
504
+ const prizeTemplate = getLotteryPrizeTemplate(cycle?.prizeMode || drawState?.prizeMode || 'standard');
505
+ const milestoneProg = calcLotteryMilestonesProgress(entries, cycle?.milestones);
506
+ const m1Hit = milestoneProg.reachedLevels.includes(1);
507
+ const m2Hit = milestoneProg.reachedLevels.includes(2);
508
+ const m3Hit = milestoneProg.reachedLevels.includes(3);
509
+
510
+ const winners = [];
511
+ const giftItems = [];
512
+ const mainWinnerUids = new Set();
513
+
514
+ for (const tier of (drawState?.prizeTiers || prizeTemplate.tiers)) {
515
+ const uids = drawState?.holdersByTier?.[tier.tierKey] || [];
516
+ for (const uid of uids) {
517
+ mainWinnerUids.add(uid);
518
+ const entry = entries[uid] || { uid, name: '幸運勇士', seat: '' };
519
+ const bonusBpRaw = Number(extraBonuses?.[uid] ?? drawState?.extraBonusesByUid?.[uid]) || 0;
520
+ const clampedBonusBp = Math.max(0, Math.min(3, Math.floor(bonusBpRaw)));
521
+ const milestoneBp = tier.tierKey === 'head' && m1Hit ? (Number(tier.m1BonusBp) || 0) : 0;
522
+ const totalBp = (Number(tier.bp) || 0) + milestoneBp + clampedBonusBp;
523
+
524
+ const reason = `🎰 錯題樂透【${cycle?.title || cycle?.cycleId}】${tier.label}得主`;
525
+ const gift = {
526
+ coins: 0,
527
+ hours: Number(tier.hours) || 0,
528
+ bp: totalBp,
529
+ peek: Number(tier.peek) || 0,
530
+ eliminate: Number(tier.eliminate) || 0,
531
+ titles: [...(tier.titles || [])],
532
+ futureRewards: {},
533
+ kind: 'lottery_settle',
534
+ lotteryCycleId: cycle?.cycleId || '',
535
+ tierKey: tier.tierKey,
536
+ detail: [
537
+ `${tier.label}(總籤權 ${calcLotteryBallStats(entry).weight},含銀球 ${entry.regularBalls || 0} + 金球 ${entry.goldenBalls || 0})`,
538
+ milestoneBp > 0 ? `🌟 全班達成里程碑加碼 +${milestoneBp} 兵符!` : '',
539
+ clampedBonusBp > 0 ? `🎲 教師現場奇蹟骰加碼 +${clampedBonusBp} 兵符!` : '',
540
+ ].filter(Boolean),
541
+ reason,
542
+ };
543
+ winners.push({
544
+ uid,
545
+ seat: entry.seat || '',
546
+ name: entry.name || '勇士',
547
+ tierKey: tier.tierKey,
548
+ tierLabel: tier.label,
549
+ bp: totalBp,
550
+ giftPayload: gift,
551
+ });
552
+ giftItems.push({ student: { uid, seat: entry.seat, name: entry.name }, uid, gift });
553
+ }
554
+ }
555
+
556
+ // 努力苦勞慰勞獎(非主要得主中總籤權最高者,需 weight >= 參加門檻)
557
+ const minWeight = prizeTemplate.participationMinWeight ?? LOTTERY_PARTICIPATION_MIN_WEIGHT;
558
+ const nonMainEligible = Object.values(entries)
559
+ .map(e => ({ ...e, ...calcLotteryBallStats(e) }))
560
+ .filter(e => e.uid && !mainWinnerUids.has(e.uid) && e.weight >= minWeight)
561
+ .sort((a, b) => b.weight - a.weight);
562
+
563
+ const effortWinnerUid = nonMainEligible[0]?.uid || null;
564
+ const partCfg = prizeTemplate.participation || {};
565
+
566
+ for (const e of nonMainEligible) {
567
+ const isEffort = e.uid === effortWinnerUid;
568
+ const partBp = (Number(partCfg.bp) || 1) + (m3Hit ? (Number(partCfg.m3BonusBp) || 0) : 0);
569
+ const partHours = (Number(partCfg.hours) || 1) + (m3Hit ? (Number(partCfg.m3BonusHours) || 0) : 0);
570
+ const partPeek = (Number(partCfg.peek) || 0) + (m3Hit ? (Number(partCfg.m3BonusPeek) || 0) : 0) + (isEffort ? (Number(prizeTemplate.effort?.peek) || 0) : 0);
571
+ const partElim = (Number(partCfg.eliminate) || 0) + (isEffort ? (Number(prizeTemplate.effort?.eliminate) || 0) : 0);
572
+ const titles = isEffort && prizeTemplate.effort?.title ? [prizeTemplate.effort.title] : [];
573
+
574
+ const gift = {
575
+ coins: 0,
576
+ hours: partHours,
577
+ bp: partBp,
578
+ peek: partPeek,
579
+ eliminate: partElim,
580
+ titles,
581
+ futureRewards: {},
582
+ kind: 'lottery_settle',
583
+ lotteryCycleId: cycle?.cycleId || '',
584
+ tierKey: isEffort ? 'effort' : 'participation',
585
+ detail: [
586
+ isEffort
587
+ ? `⚡ 全班未中大獎中總籤權最高(${e.weight} 籤),榮獲【${prizeTemplate.effort?.title || '錯題終結者'}】紀念獎勵!`
588
+ : `🎁 達成錯題樂透參與門檻(${e.weight} 籤),獲頒參加獎!`,
589
+ m3Hit ? '🚩 全班突破第 3 階集氣里程碑,全體參與者同步獲得加碼福利!' : '',
590
+ ].filter(Boolean),
591
+ reason: isEffort ? `⚡ 錯題樂透・錯題終結者特別獎` : `🎁 錯題樂透・參加獎`,
592
+ };
593
+ winners.push({
594
+ uid: e.uid,
595
+ seat: e.seat || '',
596
+ name: e.name || '勇士',
597
+ tierKey: isEffort ? 'effort' : 'participation',
598
+ tierLabel: isEffort ? '⚡ 錯題終結者' : '🎁 參加獎',
599
+ bp: partBp,
600
+ giftPayload: gift,
601
+ });
602
+ giftItems.push({ student: { uid: e.uid, seat: e.seat, name: e.name }, uid: e.uid, gift });
603
+ }
604
+
605
+ return {
606
+ summary: {
607
+ cycleId: cycle?.cycleId || '',
608
+ totalRegular: milestoneProg.totalRegular,
609
+ totalGolden: milestoneProg.totalGolden,
610
+ totalWeight: milestoneProg.totalWeight,
611
+ reachedMilestones: milestoneProg.reachedLevels,
612
+ m1Hit,
613
+ m2Hit,
614
+ m3Hit,
615
+ totalWinnersCount: winners.length,
616
+ totalBpDistributed: giftItems.reduce((s, item) => s + (Number(item.gift.bp) || 0), 0),
617
+ },
618
+ winners,
619
+ giftItems,
620
+ };
621
+ }
tools/verify-integrity.mjs CHANGED
@@ -59,6 +59,23 @@ import {
59
  buildOddWeekSpotlightPreset,
60
  findUnclaimedLegacyBossStudents,
61
  } from '../js/event-schedule.js';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  import { renderRichQuizText, todayStr } from '../js/util.js';
63
  import { rollChestRewards, evaluateChestRhythm, CHEST_RHYTHM_CFG } from '../js/tianji.js';
64
  import { LocalBackend, settleBossDamageRecord, applyBossHighWaterMarkToGame } from '../js/db.js';
@@ -1251,4 +1268,112 @@ ok('學生兵符對帳輔助腳本(建城/升星★6+/二紀元重置/4卷池
1251
  }
1252
  ok('可插拔活動排程、週四快閃並列與舊窮奇領完才隱藏檢驗 100% 通過');
1253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1254
  console.log(`\n🎉 全部 ${passedChecks} 大項工程防呆檢驗 100% 通過!可安全部署上線。`);
 
59
  buildOddWeekSpotlightPreset,
60
  findUnclaimedLegacyBossStudents,
61
  } from '../js/event-schedule.js';
62
+ import {
63
+ MAX_DAILY_LOTTERY_ROUNDS,
64
+ LOTTERY_ROUND_SIZE,
65
+ LOTTERY_DEFAULT_PRIZES,
66
+ LOTTERY_PILOT_PRIZES,
67
+ LOTTERY_DEFAULT_MILESTONES,
68
+ LOTTERY_PILOT_MILESTONES,
69
+ pickLotteryRoundQuestions,
70
+ scoreLotteryAnswer,
71
+ calcDynamicLotteryBalance,
72
+ calcLotteryMilestonesProgress,
73
+ shrinkTierQuotas,
74
+ createLotteryDrawState,
75
+ drawWeightedWinner,
76
+ applyTierDrawWithUpgrade,
77
+ buildLotterySettlement,
78
+ } from '../js/lottery-core.js';
79
  import { renderRichQuizText, todayStr } from '../js/util.js';
80
  import { rollChestRewards, evaluateChestRhythm, CHEST_RHYTHM_CFG } from '../js/tianji.js';
81
  import { LocalBackend, settleBossDamageRecord, applyBossHighWaterMarkToGame } from '../js/db.js';
 
1268
  }
1269
  ok('可插拔活動排程、週四快閃並列與舊窮奇領完才隱藏檢驗 100% 通過');
1270
 
1271
+ // ----------------------------------------------------------------------------
1272
+ // 18. 錯題樂透純函數核心(r2->r1->r0、金球+幸運球、縮編、升級遞補與智慧里程碑)(Task A2)
1273
+ // ----------------------------------------------------------------------------
1274
+ {
1275
+ // 18.1 精熟收割優先序 r2 -> r1 -> r0 + 英文題鍵歸一 + 跨科過濾 + 同日去重
1276
+ const gPick = newGame();
1277
+ gPick.mistakes = {
1278
+ wiring_1: { q: 'w1', o: ['a', 'b', 'c', 'd'], a: 0, bank: 'wiring', n: 1, wrongCount: 3, reviewCorrectCount: 0, mastered: false },
1279
+ wiring_2: { q: 'w2', o: ['a', 'b', 'c', 'd'], a: 0, bank: 'wiring', n: 2, wrongCount: 1, reviewCorrectCount: 2, mastered: false },
1280
+ wiring_3: { q: 'w3', o: ['a', 'b', 'c', 'd'], a: 0, bank: 'wiring', n: 3, wrongCount: 2, reviewCorrectCount: 1, mastered: false },
1281
+ plumbing_9: { q: 'p9', o: ['a', 'b', 'c', 'd'], a: 0, bank: 'plumbing', n: 9, wrongCount: 5, reviewCorrectCount: 2, mastered: false }, // 異科不可出給 wiring
1282
+ english_15: { id: 'english_15', q: 'apple', o: ['蘋果', '香蕉', '橘子', '梨'], a: 0, bank: 'english', n: 15, wrongCount: 2, reviewCorrectCount: 2, mastered: false },
1283
+ };
1284
+ const pickedVoc = pickLotteryRoundQuestions({
1285
+ game: gPick,
1286
+ classInfo: { bank: 'wiring' },
1287
+ students: [],
1288
+ questionPools: { vocational: [], english: [] },
1289
+ questionMode: 'vocational',
1290
+ seenToday: new Set(),
1291
+ count: 3,
1292
+ });
1293
+ assert.deepEqual(pickedVoc.map(x => x._qKey), ['wiring_2', 'wiring_3', 'wiring_1'], '個人錯題應嚴格依 r2 -> r1 -> r0 優先,並排除異科 plumbing');
1294
+
1295
+ const pickedEngDedup = pickLotteryRoundQuestions({
1296
+ game: gPick,
1297
+ classInfo: { bank: 'wiring' },
1298
+ students: [
1299
+ { uid: 'peer1', seat: '3', role: 'student', bankId: 'wiring', game: { mistakes: { english_22: { q: 'banana', o: ['香','蘋','橘','瓜'], a: 0, bank: 'english', n: 22, reviewCorrectCount: 1, mastered: false } } } },
1300
+ { uid: 'tester20', seat: '20', role: 'student', bankId: 'wiring', game: { mistakes: { english_99: { q: 'test20', o: ['a','b','c','d'], a: 0, bank: 'english', n: 99, reviewCorrectCount: 2, mastered: false } } } },
1301
+ ],
1302
+ questionPools: { vocational: [], english: [{ n: 30, q: 'cat', o: ['貓', '狗', '魚', '鳥'], a: 0 }] },
1303
+ questionMode: 'english',
1304
+ seenToday: new Set(['english_15']),
1305
+ count: 3,
1306
+ });
1307
+ assert.equal(pickedEngDedup[0]._qKey, 'english_22', '同日見過 english_15 時應順延改抽未重複之同袍英文題,且排除 20 號測試號');
1308
+ assert.ok(!pickedEngDedup.some(q => q._qKey === 'english_99'), '不可抽入 seat=20 之錯題');
1309
+
1310
+ // 18.2 單發計分 + 第 5 題幸運加碼 + rev 2->3 金球取代原銀球(+1金 +1銀)+ 同日重複 0 球
1311
+ const scWrong = scoreLotteryAnswer({ q: { _qKey: 'wiring_2' }, isCorrect: false, curRevCount: 2, questionIndex: 4, seenKeysSet: new Set() });
1312
+ assert.deepEqual(scWrong, { awardedRegular: 0, awardedGold: 0, triggeredGraduationGold: false, awardedLuckyBonus: false, duplicateSkipped: false });
1313
+
1314
+ const scQ5Grad = scoreLotteryAnswer({ q: { _qKey: 'wiring_2' }, isCorrect: true, curRevCount: 2, questionIndex: LOTTERY_ROUND_SIZE - 1, seenKeysSet: new Set() });
1315
+ assert.deepEqual(scQ5Grad, { awardedRegular: 1, awardedGold: 1, triggeredGraduationGold: true, awardedLuckyBonus: true, duplicateSkipped: false }, '第5題剛好精熟畢業應獲得 1 金球(取代本題銀球)+ 1 幸運銀球(合計+3籤權)');
1316
+
1317
+ const scDup = scoreLotteryAnswer({ q: { _qKey: 'wiring_2' }, isCorrect: true, curRevCount: 2, questionIndex: 0, seenKeysSet: new Set(['wiring_2']) });
1318
+ assert.equal(scDup.duplicateSkipped, true);
1319
+ assert.equal(scDup.awardedRegular + scDup.awardedGold, 0, '同日重複題應給 0 球');
1320
+
1321
+ // 18.3 小班縮編 + 升級遞補契約一致驗證
1322
+ const shrunk2 = shrinkTierQuotas(LOTTERY_PILOT_PRIZES, 2);
1323
+ assert.equal(shrunk2.reduce((s, t) => s + t.quota, 0), 2, '僅 2 名參與者時主要獎額總和應縮編為 2');
1324
+ let drawSt = createLotteryDrawState(LOTTERY_PILOT_PRIZES, [
1325
+ { uid: 'u1', seat: '1', name: '一號', regularBalls: 4, goldenBalls: 2, weight: 8 },
1326
+ { uid: 'u2', seat: '2', name: '二號', regularBalls: 3, goldenBalls: 0, weight: 3 },
1327
+ { uid: 'u3', seat: '3', name: '三號', regularBalls: 2, goldenBalls: 0, weight: 2 },
1328
+ ]);
1329
+ const rAssign = applyTierDrawWithUpgrade({ state: drawSt, tierKey: 't3', candidateUid: 'u1' });
1330
+ assert.equal(rAssign.action, 'assigned');
1331
+ drawSt = rAssign.state;
1332
+ const rUpg = applyTierDrawWithUpgrade({ state: drawSt, tierKey: 'head', candidateUid: 'u1' });
1333
+ assert.equal(rUpg.action, 'upgraded');
1334
+ assert.equal(rUpg.upgradedFromTier, 't3');
1335
+ assert.equal(rUpg.vacatedTier, 't3');
1336
+ assert.deepEqual(rUpg.holdersByTier.head, ['u1']);
1337
+ assert.deepEqual(rUpg.holdersByTier.t3, [], 'u1 升級頭獎後,原本三獎名單應即時空出等待遞補');
1338
+
1339
+ const settledPilot = buildLotterySettlement({
1340
+ cycle: {
1341
+ cycleId: 'lotto_pilot_20261119',
1342
+ title: '週四快閃',
1343
+ prizeMode: 'pilot',
1344
+ milestones: [45, 90, 140],
1345
+ entries: {
1346
+ u1: { uid: 'u1', seat: '1', name: '一號', regularBalls: 4, goldenBalls: 2, weight: 8 },
1347
+ u2: { uid: 'u2', seat: '2', name: '二號', regularBalls: 3, goldenBalls: 0, weight: 3 },
1348
+ u3: { uid: 'u3', seat: '3', name: '三號', regularBalls: 20, goldenBalls: 15, weight: 50 },
1349
+ },
1350
+ },
1351
+ drawState: rUpg.state,
1352
+ });
1353
+ const u1Gift = settledPilot.giftItems.find(x => x.uid === 'u1');
1354
+ const u3Gift = settledPilot.giftItems.find(x => x.uid === 'u3');
1355
+ assert.equal(u1Gift.gift.bp, 7, '快閃縮小版頭獎 6 兵符 + 第1階里程碑達標(>=45)加碼 1 ➔ 7 兵符');
1356
+ assert.ok(u3Gift.gift.titles.includes('錯題終結者'), '未中主要獎最高總籤權者應獲得錯題終結者稱號');
1357
+ assert.equal(settledPilot.giftItems.some(x => x.uid === 'u2' && x.gift.bp === 1 && !x.gift.titles?.includes('九州錦鯉')), true, 'u2 達 fast pilot weight>=2 門檻應獲參加獎 1 兵符');
1358
+
1359
+ // 18.4 智慧平衡引擎:14 人 1 天快閃 vs 5 天正式週區間斷言
1360
+ const mock14 = Array.from({ length: 14 }, (_, i) => ({
1361
+ uid: `s${i + 1}`,
1362
+ seat: String(i + 1),
1363
+ role: 'student',
1364
+ game: {
1365
+ mistakes: Object.fromEntries(
1366
+ Array.from({ length: 10 }, (__, k) => [`w_${i}_${k}`, { bank: k < 7 ? 'wiring' : 'english', mastered: false, reviewCorrectCount: k % 3 }])
1367
+ ),
1368
+ },
1369
+ }));
1370
+ const bal1d = calcDynamicLotteryBalance(mock14, { targetDays: 1, prizeMode: 'pilot' });
1371
+ assert.ok(bal1d.recommendedMilestones[0] >= 35 && bal1d.recommendedMilestones[0] <= 65, '1日快閃第1階應落於 35~65');
1372
+ assert.ok(bal1d.recommendedMilestones[1] >= 70 && bal1d.recommendedMilestones[1] <= 120, '1日快閃第2階應落於 70~120');
1373
+ assert.ok(bal1d.recommendedMilestones[2] >= 110 && bal1d.recommendedMilestones[2] <= 180, '1日快閃第3階應落於 110~180');
1374
+ const bal5d = calcDynamicLotteryBalance(mock14, { targetDays: 5, prizeMode: 'standard' });
1375
+ assert.ok(bal5d.recommendedMilestones[2] >= 360 && bal5d.recommendedMilestones[2] <= 500, '5日正式週第3階應對齊 ~420 區間');
1376
+ }
1377
+ ok('錯題樂透純函數核心(r2->r1->r0、金球+幸運球、升級遞補與智慧里程碑)100% 通過');
1378
+
1379
  console.log(`\n🎉 全部 ${passedChecks} 大項工程防呆檢驗 100% 通過!可安全部署上線。`);