feat(lottery-a3): add lottery schema, HWM protection, auto-prune & dual-backend transactions
Browse files- js/db.js +728 -249
- js/engine.js +43 -0
- tools/verify-integrity.mjs +119 -1
js/db.js
CHANGED
|
@@ -3,11 +3,12 @@
|
|
| 3 |
// 1. FirebaseBackend:正式使用(Auth + Firestore)
|
| 4 |
// 2. LocalBackend :firebaseConfig 未填時的本機示範模式(localStorage)
|
| 5 |
// =============================================================
|
| 6 |
-
import { firebaseConfig, STUDENT_EMAIL_DOMAIN, PIN_SUFFIX } from './firebase-config.js?v=
|
| 7 |
-
import { WEEKLY_SCHEDULE } from './config.js?v=
|
| 8 |
-
import { trafficTracker } from './traffic-tracker.js?v=
|
| 9 |
-
import { normalizeWorldBossState } from './world-boss-schedule.js?v=
|
| 10 |
-
import {
|
|
|
|
| 11 |
|
| 12 |
const WEEK_TARGET_MAP = Object.fromEntries(WEEKLY_SCHEDULE.map(w => [w.id, w.target]));
|
| 13 |
function clampWeekCap(weekId, val) {
|
|
@@ -30,6 +31,213 @@ function assertBossAttackable(wb, now = Date.now()) {
|
|
| 30 |
}
|
| 31 |
}
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
// 世界 Boss 討伐令單調高水位守衛(跨母子視窗 localStorage + 記憶體雙重防回退)
|
| 34 |
const BOSS_HWM_MEM = {};
|
| 35 |
const BOSS_HWM_PREFIX = 'idle_boss_hwm_';
|
|
@@ -93,9 +301,12 @@ export function applyBossHighWaterMarkToGame(uid, game) {
|
|
| 93 |
if (!uid || !game || typeof game !== 'object') return game;
|
| 94 |
const hwm = readBossHighWaterMark(uid);
|
| 95 |
const today = todayStr();
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
| 99 |
try {
|
| 100 |
if (typeof localStorage !== 'undefined') {
|
| 101 |
localStorage.setItem(BOSS_HWM_PREFIX + uid, JSON.stringify(hwm));
|
|
@@ -110,6 +321,188 @@ export function applyBossHighWaterMarkToGame(uid, game) {
|
|
| 110 |
return game;
|
| 111 |
}
|
| 112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
const FB_VER = '10.12.2';
|
| 114 |
const FB = `https://www.gstatic.com/firebasejs/${FB_VER}`;
|
| 115 |
|
|
@@ -219,19 +612,28 @@ class FirebaseBackend {
|
|
| 219 |
if (this._stCache && this._stCache.uid === uid) {
|
| 220 |
const data = this._stCache.data;
|
| 221 |
this._stCache = null; // 只用一次,之後一律讀最新資料
|
| 222 |
-
if (data?.game)
|
|
|
|
|
|
|
|
|
|
| 223 |
return { ...data, uid };
|
| 224 |
}
|
| 225 |
const s = await this.F.getDoc(this.d('students', uid));
|
| 226 |
trafficTracker.recordOp({ type: 'read', source: 'getStudent', count: 1, estimatedBytes: 4096, note: `讀取學生資料 (${uid.slice(0, 6)}...)` });
|
| 227 |
if (!s.exists()) return null;
|
| 228 |
const data = s.data();
|
| 229 |
-
if (data?.game)
|
|
|
|
|
|
|
|
|
|
| 230 |
return { ...data, uid };
|
| 231 |
}
|
| 232 |
|
| 233 |
async saveGame(uid, { game, progress, stats }) {
|
| 234 |
-
if (game)
|
|
|
|
|
|
|
|
|
|
| 235 |
await this.F.updateDoc(this.d('students', uid), { game, progress, stats, lastSeen: Date.now() });
|
| 236 |
trafficTracker.recordOp({ type: 'write', source: 'saveGame', count: 1, estimatedBytes: 6144, note: `學生存檔更新 (${uid.slice(0, 6)}...)` });
|
| 237 |
}
|
|
@@ -317,161 +719,28 @@ class FirebaseBackend {
|
|
| 317 |
if (!snap.exists()) throw new DBError('班級資料不存在');
|
| 318 |
const cData = snap.data();
|
| 319 |
// 依當期排程正規化:首位出征者的傷害寫入即完成「饕餮→窮奇」換期落地
|
| 320 |
-
const wb =
|
| 321 |
-
assertBossAttackable(wb);
|
| 322 |
-
if (!wb.damages) wb.damages = {};
|
| 323 |
-
|
| 324 |
-
const isYinYang = wb.bossId === 'qiongqi' || !!splitDmg || typeof wb.yangHp === 'number' || typeof wb.yinHp === 'number';
|
| 325 |
-
let effectiveDmg = 0;
|
| 326 |
-
let newHp = 0;
|
| 327 |
-
let maxHp = wb.maxHp || 500;
|
| 328 |
-
let wasDefeated = false;
|
| 329 |
-
let justDefeated = false;
|
| 330 |
-
let newYangHp = undefined;
|
| 331 |
-
let newYinHp = undefined;
|
| 332 |
-
let yangMaxHp = wb.yangMaxHp || 1200;
|
| 333 |
-
let yinMaxHp = wb.yinMaxHp || 800;
|
| 334 |
-
let effYangDmg = 0;
|
| 335 |
-
let effYinDmg = 0;
|
| 336 |
-
|
| 337 |
-
if (isYinYang) {
|
| 338 |
-
maxHp = yangMaxHp + yinMaxHp;
|
| 339 |
-
const oldYangHp = typeof wb.yangHp === 'number' ? Math.max(0, wb.yangHp) : yangMaxHp;
|
| 340 |
-
const oldYinHp = typeof wb.yinHp === 'number' ? Math.max(0, wb.yinHp) : yinMaxHp;
|
| 341 |
-
wasDefeated = !!wb.defeated || (oldYangHp <= 0 && oldYinHp <= 0);
|
| 342 |
-
const rawYang = splitDmg ? Math.max(0, Number(splitDmg.yangDmg) || 0) : Math.max(0, Number(roundDmg) || 0);
|
| 343 |
-
const rawYin = splitDmg ? Math.max(0, Number(splitDmg.yinDmg) || 0) : 0;
|
| 344 |
-
// 雙生同命:單邊歸零後進入「已鎮壓鎖定」,多出的傷害直接溢出,不自動轉移至另一邊
|
| 345 |
-
effYangDmg = wasDefeated ? 0 : Math.min(rawYang, oldYangHp);
|
| 346 |
-
effYinDmg = wasDefeated ? 0 : Math.min(rawYin, oldYinHp);
|
| 347 |
-
newYangHp = Math.max(0, oldYangHp - effYangDmg);
|
| 348 |
-
newYinHp = Math.max(0, oldYinHp - effYinDmg);
|
| 349 |
-
effectiveDmg = effYangDmg + effYinDmg;
|
| 350 |
-
newHp = newYangHp + newYinHp;
|
| 351 |
-
justDefeated = !wasDefeated && (newYangHp <= 0 && newYinHp <= 0);
|
| 352 |
-
} else {
|
| 353 |
-
const oldHp = typeof wb.curHp === 'number' ? wb.curHp : maxHp;
|
| 354 |
-
wasDefeated = !!wb.defeated || oldHp <= 0;
|
| 355 |
-
effectiveDmg = wasDefeated ? 0 : Math.min(Math.max(0, Number(roundDmg) || 0), oldHp);
|
| 356 |
-
newHp = Math.max(0, oldHp - effectiveDmg);
|
| 357 |
-
justDefeated = !wasDefeated && newHp <= 0;
|
| 358 |
-
}
|
| 359 |
-
|
| 360 |
-
let killer = wb.killer || null;
|
| 361 |
-
if (justDefeated) {
|
| 362 |
-
killer = {
|
| 363 |
-
uid: student.uid,
|
| 364 |
-
name: student.name || `座號${student.seat}`,
|
| 365 |
-
seat: student.seat || '',
|
| 366 |
-
at: Date.now()
|
| 367 |
-
};
|
| 368 |
-
}
|
| 369 |
-
|
| 370 |
-
const dRec = wb.damages[student.uid] || {
|
| 371 |
-
name: student.name || `座號${student.seat}`,
|
| 372 |
-
seat: student.seat || '',
|
| 373 |
-
dmg: 0,
|
| 374 |
-
yangDmg: 0,
|
| 375 |
-
yinDmg: 0,
|
| 376 |
-
attacksCount: 0
|
| 377 |
-
};
|
| 378 |
-
dRec.dmg = (dRec.dmg || 0) + effectiveDmg;
|
| 379 |
-
if (isYinYang) {
|
| 380 |
-
dRec.yangDmg = (dRec.yangDmg || 0) + effYangDmg;
|
| 381 |
-
dRec.yinDmg = (dRec.yinDmg || 0) + effYinDmg;
|
| 382 |
-
}
|
| 383 |
-
dRec.attacksCount = (dRec.attacksCount || 0) + 1;
|
| 384 |
-
const today = todayStr();
|
| 385 |
const sData = (sSnap && sSnap.exists()) ? sSnap.data() : null;
|
| 386 |
-
const
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
0,
|
| 390 |
-
Math.floor(Number(student?.game?.extraBossOrders) || 0),
|
| 391 |
-
(sData?.game?.extraBossOrdersDate === today ? Math.floor(Number(sData?.game?.extraBossOrders) || 0) : 0)
|
| 392 |
-
);
|
| 393 |
-
const maxAllowedToday = 3 + extraOrders;
|
| 394 |
-
let prevDailyUsed = 0;
|
| 395 |
-
if (dRec.dailyUsed && typeof dRec.dailyUsed[today] === 'number') {
|
| 396 |
-
prevDailyUsed = dRec.dailyUsed[today];
|
| 397 |
-
} else if (dRec.lastDate === today) {
|
| 398 |
-
prevDailyUsed = (Number(dRec.attacksCount) || 1) - 1;
|
| 399 |
-
} else if (!dRec.dailyUsed && !dRec.lastDate && typeof wb.openAt === 'number' && new Date(wb.openAt).toLocaleDateString('sv-SE') === today) {
|
| 400 |
-
prevDailyUsed = (Number(dRec.attacksCount) || 1) - 1;
|
| 401 |
-
}
|
| 402 |
-
prevDailyUsed = Math.max(prevDailyUsed, sUsedToday);
|
| 403 |
-
if (prevDailyUsed >= maxAllowedToday) {
|
| 404 |
-
throw new DBError(`今日出征討伐次數已達上限(每日 ${maxAllowedToday} 次),無法重複計入傷害!`);
|
| 405 |
-
}
|
| 406 |
-
const newDailyUsed = prevDailyUsed + 1;
|
| 407 |
-
dRec.lastDate = today;
|
| 408 |
-
dRec.dailyUsed = { ...(dRec.dailyUsed || {}), [today]: newDailyUsed };
|
| 409 |
-
dRec.rounds = Array.isArray(dRec.rounds) ? [...dRec.rounds] : [];
|
| 410 |
-
dRec.rounds.push({
|
| 411 |
-
at: Date.now(),
|
| 412 |
-
date: today,
|
| 413 |
-
dmg: effectiveDmg,
|
| 414 |
-
yangDmg: isYinYang ? effYangDmg : undefined,
|
| 415 |
-
yinDmg: isYinYang ? effYinDmg : undefined
|
| 416 |
-
});
|
| 417 |
-
dRec.lastAt = Date.now();
|
| 418 |
-
|
| 419 |
-
const updatedWb = {
|
| 420 |
-
...wb,
|
| 421 |
-
bossId: wb.bossId || 'taotie',
|
| 422 |
-
name: wb.name || (isYinYang ? '上古・窮奇' : '上古・饕餮'),
|
| 423 |
-
maxHp: maxHp,
|
| 424 |
-
curHp: newHp,
|
| 425 |
-
defeated: wasDefeated || justDefeated,
|
| 426 |
-
defeatedAt: (wasDefeated || justDefeated) ? (wb.defeatedAt || Date.now()) : null,
|
| 427 |
-
killer: killer,
|
| 428 |
-
damages: {
|
| 429 |
-
...wb.damages,
|
| 430 |
-
[student.uid]: dRec
|
| 431 |
-
}
|
| 432 |
-
};
|
| 433 |
-
if (isYinYang) {
|
| 434 |
-
updatedWb.yangMaxHp = yangMaxHp;
|
| 435 |
-
updatedWb.yinMaxHp = yinMaxHp;
|
| 436 |
-
updatedWb.yangHp = newYangHp;
|
| 437 |
-
updatedWb.yinHp = newYinHp;
|
| 438 |
}
|
| 439 |
|
| 440 |
-
tx.update(cRef, { worldBoss: updatedWb });
|
| 441 |
-
const mergedStuBoss = mergeBossObj(sBoss, {
|
| 442 |
-
...(student?.game?.boss || {}),
|
| 443 |
-
date: today,
|
| 444 |
-
used: newDailyUsed,
|
| 445 |
-
totalDmg: dRec.dmg
|
| 446 |
-
});
|
| 447 |
if (sRef && sSnap && sSnap.exists()) {
|
| 448 |
tx.update(sRef, {
|
| 449 |
-
'game.boss': mergedStuBoss,
|
| 450 |
lastSeen: Date.now()
|
| 451 |
});
|
| 452 |
}
|
| 453 |
-
return
|
| 454 |
-
curHp: newHp,
|
| 455 |
-
maxHp: maxHp,
|
| 456 |
-
yangHp: newYangHp,
|
| 457 |
-
yangMaxHp: isYinYang ? yangMaxHp : undefined,
|
| 458 |
-
yinHp: newYinHp,
|
| 459 |
-
yinMaxHp: isYinYang ? yinMaxHp : undefined,
|
| 460 |
-
effYangDmg,
|
| 461 |
-
effYinDmg,
|
| 462 |
-
defeated: updatedWb.defeated,
|
| 463 |
-
isKiller: (killer?.uid === student.uid && justDefeated),
|
| 464 |
-
killer: killer,
|
| 465 |
-
effectiveDmg: effectiveDmg,
|
| 466 |
-
myTotalDmg: dRec.dmg,
|
| 467 |
-
dailyUsedToday: newDailyUsed,
|
| 468 |
-
bossState: mergedStuBoss
|
| 469 |
-
};
|
| 470 |
});
|
| 471 |
-
if (student?.uid && res?.bossState) {
|
| 472 |
recordBossHighWaterMark(student.uid, res.bossState);
|
| 473 |
}
|
| 474 |
-
|
|
|
|
|
|
|
| 475 |
return res;
|
| 476 |
}
|
| 477 |
|
|
@@ -783,6 +1052,155 @@ class FirebaseBackend {
|
|
| 783 |
|
| 784 |
async listAttempts(code) { return this._latestByClass('attempts', code, 100); }
|
| 785 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 786 |
getTrafficStats() { return trafficTracker.getQuotaStatus(); }
|
| 787 |
simulateTraffic(params) { return trafficTracker.simulateLoad(params); }
|
| 788 |
resetTrafficStats() { trafficTracker.reset(); }
|
|
@@ -856,12 +1274,21 @@ class LocalBackend {
|
|
| 856 |
|
| 857 |
async getStudent(uid) {
|
| 858 |
const s = this.load().students[uid];
|
| 859 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 860 |
}
|
| 861 |
|
| 862 |
async saveGame(uid, { game, progress, stats }) {
|
| 863 |
const db = this.load();
|
| 864 |
if (!db.students[uid]) throw new DBError('找不到學生資料');
|
|
|
|
|
|
|
|
|
|
|
|
|
| 865 |
Object.assign(db.students[uid], { game, progress, stats, lastSeen: Date.now() });
|
| 866 |
this.save(db);
|
| 867 |
}
|
|
@@ -931,102 +1358,24 @@ class LocalBackend {
|
|
| 931 |
const db = this.load();
|
| 932 |
const c = db.classes[normCode(classCode)];
|
| 933 |
if (!c) throw new DBError('班級不存在');
|
| 934 |
-
const wb =
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
let effectiveDmg = 0;
|
| 940 |
-
let newHp = 0;
|
| 941 |
-
let maxHp = wb.maxHp || 500;
|
| 942 |
-
let wasDefeated = false;
|
| 943 |
-
let justDefeated = false;
|
| 944 |
-
let newYangHp = undefined;
|
| 945 |
-
let newYinHp = undefined;
|
| 946 |
-
let yangMaxHp = wb.yangMaxHp || 1200;
|
| 947 |
-
let yinMaxHp = wb.yinMaxHp || 800;
|
| 948 |
-
let effYangDmg = 0;
|
| 949 |
-
let effYinDmg = 0;
|
| 950 |
-
|
| 951 |
-
if (isYinYang) {
|
| 952 |
-
maxHp = yangMaxHp + yinMaxHp;
|
| 953 |
-
const oldYangHp = typeof wb.yangHp === 'number' ? Math.max(0, wb.yangHp) : yangMaxHp;
|
| 954 |
-
const oldYinHp = typeof wb.yinHp === 'number' ? Math.max(0, wb.yinHp) : yinMaxHp;
|
| 955 |
-
wasDefeated = !!wb.defeated || (oldYangHp <= 0 && oldYinHp <= 0);
|
| 956 |
-
const rawYang = splitDmg ? Math.max(0, Number(splitDmg.yangDmg) || 0) : Math.max(0, Number(roundDmg) || 0);
|
| 957 |
-
const rawYin = splitDmg ? Math.max(0, Number(splitDmg.yinDmg) || 0) : 0;
|
| 958 |
-
effYangDmg = wasDefeated ? 0 : Math.min(rawYang, oldYangHp);
|
| 959 |
-
effYinDmg = wasDefeated ? 0 : Math.min(rawYin, oldYinHp);
|
| 960 |
-
newYangHp = Math.max(0, oldYangHp - effYangDmg);
|
| 961 |
-
newYinHp = Math.max(0, oldYinHp - effYinDmg);
|
| 962 |
-
effectiveDmg = effYangDmg + effYinDmg;
|
| 963 |
-
newHp = newYangHp + newYinHp;
|
| 964 |
-
justDefeated = !wasDefeated && (newYangHp <= 0 && newYinHp <= 0);
|
| 965 |
-
} else {
|
| 966 |
-
const oldHp = typeof wb.curHp === 'number' ? wb.curHp : maxHp;
|
| 967 |
-
wasDefeated = !!wb.defeated || oldHp <= 0;
|
| 968 |
-
effectiveDmg = wasDefeated ? 0 : Math.min(Math.max(0, Number(roundDmg) || 0), oldHp);
|
| 969 |
-
newHp = Math.max(0, oldHp - effectiveDmg);
|
| 970 |
-
justDefeated = !wasDefeated && newHp <= 0;
|
| 971 |
}
|
| 972 |
|
| 973 |
-
|
| 974 |
-
if (
|
| 975 |
-
|
| 976 |
-
|
| 977 |
-
|
| 978 |
-
seat: student.seat || '',
|
| 979 |
-
at: Date.now()
|
| 980 |
-
};
|
| 981 |
}
|
| 982 |
-
|
| 983 |
-
const dRec = wb.damages[student.uid] || {
|
| 984 |
-
name: student.name || `座號${student.seat}`,
|
| 985 |
-
seat: student.seat || '',
|
| 986 |
-
dmg: 0,
|
| 987 |
-
yangDmg: 0,
|
| 988 |
-
yinDmg: 0,
|
| 989 |
-
attacksCount: 0
|
| 990 |
-
};
|
| 991 |
-
dRec.dmg = (dRec.dmg || 0) + effectiveDmg;
|
| 992 |
-
if (isYinYang) {
|
| 993 |
-
dRec.yangDmg = (dRec.yangDmg || 0) + effYangDmg;
|
| 994 |
-
dRec.yinDmg = (dRec.yinDmg || 0) + effYinDmg;
|
| 995 |
-
}
|
| 996 |
-
dRec.attacksCount = (dRec.attacksCount || 0) + 1;
|
| 997 |
-
dRec.lastAt = Date.now();
|
| 998 |
-
|
| 999 |
-
c.worldBoss = {
|
| 1000 |
-
...wb,
|
| 1001 |
-
bossId: wb.bossId || 'taotie',
|
| 1002 |
-
name: wb.name || (isYinYang ? '上古・窮奇' : '上古・饕餮'),
|
| 1003 |
-
maxHp: maxHp,
|
| 1004 |
-
curHp: newHp,
|
| 1005 |
-
...(isYinYang ? { yangMaxHp, yinMaxHp, yangHp: newYangHp, yinHp: newYinHp } : {}),
|
| 1006 |
-
defeated: wasDefeated || justDefeated,
|
| 1007 |
-
defeatedAt: (wasDefeated || justDefeated) ? (wb.defeatedAt || Date.now()) : null,
|
| 1008 |
-
killer: killer,
|
| 1009 |
-
damages: {
|
| 1010 |
-
...wb.damages,
|
| 1011 |
-
[student.uid]: dRec
|
| 1012 |
-
}
|
| 1013 |
-
};
|
| 1014 |
this.save(db);
|
| 1015 |
-
|
| 1016 |
-
|
| 1017 |
-
|
| 1018 |
-
|
| 1019 |
-
yangMaxHp: isYinYang ? yangMaxHp : undefined,
|
| 1020 |
-
yinHp: newYinHp,
|
| 1021 |
-
yinMaxHp: isYinYang ? yinMaxHp : undefined,
|
| 1022 |
-
effYangDmg,
|
| 1023 |
-
effYinDmg,
|
| 1024 |
-
defeated: c.worldBoss.defeated,
|
| 1025 |
-
isKiller: (killer?.uid === student.uid && justDefeated),
|
| 1026 |
-
killer: killer,
|
| 1027 |
-
effectiveDmg: effectiveDmg,
|
| 1028 |
-
myTotalDmg: dRec.dmg
|
| 1029 |
-
};
|
| 1030 |
}
|
| 1031 |
|
| 1032 |
async resetClassBoss(classCode, maxHp = 500, bossId = null) {
|
|
@@ -1293,6 +1642,136 @@ class LocalBackend {
|
|
| 1293 |
return this.load().attempts.filter((a) => a.classCode === normCode(code)).sort((a, b) => b.at - a.at);
|
| 1294 |
}
|
| 1295 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1296 |
getTrafficStats() { return trafficTracker.getQuotaStatus(); }
|
| 1297 |
simulateTraffic(params) { return trafficTracker.simulateLoad(params); }
|
| 1298 |
resetTrafficStats() { trafficTracker.reset(); }
|
|
@@ -1314,4 +1793,4 @@ export async function getDB() {
|
|
| 1314 |
return _db;
|
| 1315 |
}
|
| 1316 |
|
| 1317 |
-
export { trafficTracker };
|
|
|
|
| 3 |
// 1. FirebaseBackend:正式使用(Auth + Firestore)
|
| 4 |
// 2. LocalBackend :firebaseConfig 未填時的本機示範模式(localStorage)
|
| 5 |
// =============================================================
|
| 6 |
+
import { firebaseConfig, STUDENT_EMAIL_DOMAIN, PIN_SUFFIX } from './firebase-config.js?v=20261114_v2';
|
| 7 |
+
import { WEEKLY_SCHEDULE } from './config.js?v=20261114_v2';
|
| 8 |
+
import { trafficTracker } from './traffic-tracker.js?v=20261114_v2';
|
| 9 |
+
import { normalizeWorldBossState } from './world-boss-schedule.js?v=20261114_v2';
|
| 10 |
+
import { scoreLotteryAnswer } from './lottery-core.js?v=20261114_v2';
|
| 11 |
+
import { todayStr } from './util.js?v=20261114_v2';
|
| 12 |
|
| 13 |
const WEEK_TARGET_MAP = Object.fromEntries(WEEKLY_SCHEDULE.map(w => [w.id, w.target]));
|
| 14 |
function clampWeekCap(weekId, val) {
|
|
|
|
| 31 |
}
|
| 32 |
}
|
| 33 |
|
| 34 |
+
/**
|
| 35 |
+
* 純函數:世界 Boss 單場傷害與每日討伐次數原子結算(共用 Firestore Transaction 與 LocalBackend)
|
| 36 |
+
* - 雙邊對齊每日上限(3 + 當日 extraBossOrdersDate === today 額外次數)
|
| 37 |
+
* - 移除累計 attacksCount 跨週誤推,避免換期/跨日後錯鎖每日次數
|
| 38 |
+
* - 伺服器端單場上限校正(窮奇 50 HP / 饕餮 25 HP),防禦異常高傷或前端篡改
|
| 39 |
+
* - 若進房前 Boss 已被同袍先步擊破 (wasDefeated),回傳 orderConsumed: false 且不扣討伐令
|
| 40 |
+
*/
|
| 41 |
+
export function settleBossDamageRecord(wbInput, student, roundDmg, splitDmg = null, sData = null, today = todayStr()) {
|
| 42 |
+
const wb = { ...(wbInput || defaultBossState()) };
|
| 43 |
+
assertBossAttackable(wb);
|
| 44 |
+
if (!wb.damages) wb.damages = {};
|
| 45 |
+
|
| 46 |
+
const isYinYang = wb.bossId === 'qiongqi' || !!splitDmg || typeof wb.yangHp === 'number' || typeof wb.yinHp === 'number';
|
| 47 |
+
const maxRoundDmg = isYinYang ? 50 : 25;
|
| 48 |
+
let maxHp = wb.maxHp || 500;
|
| 49 |
+
const yangMaxHp = wb.yangMaxHp || 1200;
|
| 50 |
+
const yinMaxHp = wb.yinMaxHp || 800;
|
| 51 |
+
|
| 52 |
+
let wasDefeated = false;
|
| 53 |
+
let oldHp = typeof wb.curHp === 'number' ? wb.curHp : maxHp;
|
| 54 |
+
let oldYangHp = yangMaxHp;
|
| 55 |
+
let oldYinHp = yinMaxHp;
|
| 56 |
+
|
| 57 |
+
if (isYinYang) {
|
| 58 |
+
maxHp = yangMaxHp + yinMaxHp;
|
| 59 |
+
oldYangHp = typeof wb.yangHp === 'number' ? Math.max(0, wb.yangHp) : yangMaxHp;
|
| 60 |
+
oldYinHp = typeof wb.yinHp === 'number' ? Math.max(0, wb.yinHp) : yinMaxHp;
|
| 61 |
+
oldHp = oldYangHp + oldYinHp;
|
| 62 |
+
wasDefeated = !!wb.defeated || (oldYangHp <= 0 && oldYinHp <= 0);
|
| 63 |
+
} else {
|
| 64 |
+
wasDefeated = !!wb.defeated || oldHp <= 0;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
const prevRec = wb.damages[student.uid];
|
| 68 |
+
const sBoss = sData?.game?.boss || {};
|
| 69 |
+
const sUsedToday = (sBoss.date === today) ? Math.max(0, Number(sBoss.used) || 0) : 0;
|
| 70 |
+
|
| 71 |
+
// 若在寫入交易瞬間 Boss 已被同袍先一步封印:不寫入廢傷、不消耗玩家今日討伐令
|
| 72 |
+
if (wasDefeated) {
|
| 73 |
+
const curDailyUsed = (prevRec?.dailyUsed && typeof prevRec.dailyUsed[today] === 'number')
|
| 74 |
+
? Math.max(0, Number(prevRec.dailyUsed[today]) || 0)
|
| 75 |
+
: sUsedToday;
|
| 76 |
+
return {
|
| 77 |
+
orderConsumed: false,
|
| 78 |
+
alreadyDefeated: true,
|
| 79 |
+
updatedWb: wb,
|
| 80 |
+
mergedStuBoss: null,
|
| 81 |
+
result: {
|
| 82 |
+
curHp: isYinYang ? 0 : Math.max(0, Number(oldHp) || 0),
|
| 83 |
+
maxHp,
|
| 84 |
+
yangHp: isYinYang ? 0 : undefined,
|
| 85 |
+
yangMaxHp: isYinYang ? yangMaxHp : undefined,
|
| 86 |
+
yinHp: isYinYang ? 0 : undefined,
|
| 87 |
+
yinMaxHp: isYinYang ? yinMaxHp : undefined,
|
| 88 |
+
effYangDmg: 0,
|
| 89 |
+
effYinDmg: 0,
|
| 90 |
+
defeated: true,
|
| 91 |
+
isKiller: false,
|
| 92 |
+
killer: wb.killer || null,
|
| 93 |
+
effectiveDmg: 0,
|
| 94 |
+
myTotalDmg: Number(prevRec?.dmg) || 0,
|
| 95 |
+
orderConsumed: false,
|
| 96 |
+
alreadyDefeated: true,
|
| 97 |
+
dailyUsedToday: curDailyUsed,
|
| 98 |
+
bossState: mergeBossObj(sBoss, student?.game?.boss || null)
|
| 99 |
+
}
|
| 100 |
+
};
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
// 先檢查今日出征次數上限(絕不退回累計 attacksCount)
|
| 104 |
+
const extraOrders = Math.max(
|
| 105 |
+
0,
|
| 106 |
+
(student?.game?.extraBossOrdersDate === today ? Math.floor(Number(student?.game?.extraBossOrders) || 0) : 0),
|
| 107 |
+
(sData?.game?.extraBossOrdersDate === today ? Math.floor(Number(sData?.game?.extraBossOrders) || 0) : 0)
|
| 108 |
+
);
|
| 109 |
+
const maxAllowedToday = 3 + extraOrders;
|
| 110 |
+
let prevDailyUsed = 0;
|
| 111 |
+
if (prevRec?.dailyUsed && typeof prevRec.dailyUsed[today] === 'number') {
|
| 112 |
+
prevDailyUsed = Math.max(0, Number(prevRec.dailyUsed[today]) || 0);
|
| 113 |
+
} else if (prevRec?.lastDate === today && typeof prevRec.todayCount === 'number') {
|
| 114 |
+
prevDailyUsed = Math.max(0, Number(prevRec.todayCount) || 0);
|
| 115 |
+
}
|
| 116 |
+
prevDailyUsed = Math.max(prevDailyUsed, sUsedToday);
|
| 117 |
+
if (prevDailyUsed >= maxAllowedToday) {
|
| 118 |
+
throw new DBError(`今日出征討伐次數已達上限(每日 ${maxAllowedToday} 次),無法重複計入傷害!`);
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
let effectiveDmg = 0;
|
| 122 |
+
let newHp = 0;
|
| 123 |
+
let justDefeated = false;
|
| 124 |
+
let newYangHp = undefined;
|
| 125 |
+
let newYinHp = undefined;
|
| 126 |
+
let effYangDmg = 0;
|
| 127 |
+
let effYinDmg = 0;
|
| 128 |
+
|
| 129 |
+
if (isYinYang) {
|
| 130 |
+
const rawYang = splitDmg ? Math.max(0, Math.floor(Number(splitDmg.yangDmg) || 0)) : Math.max(0, Math.floor(Number(roundDmg) || 0));
|
| 131 |
+
const rawYin = splitDmg ? Math.max(0, Math.floor(Number(splitDmg.yinDmg) || 0)) : 0;
|
| 132 |
+
const capYang = Math.min(rawYang, maxRoundDmg);
|
| 133 |
+
const capYin = Math.min(rawYin, Math.max(0, maxRoundDmg - capYang));
|
| 134 |
+
// 雙生同命:單邊歸零後進入「已鎮壓鎖定」,多出的傷害直接溢出,不自動轉移至另一邊
|
| 135 |
+
effYangDmg = Math.min(capYang, oldYangHp);
|
| 136 |
+
effYinDmg = Math.min(capYin, oldYinHp);
|
| 137 |
+
newYangHp = Math.max(0, oldYangHp - effYangDmg);
|
| 138 |
+
newYinHp = Math.max(0, oldYinHp - effYinDmg);
|
| 139 |
+
effectiveDmg = effYangDmg + effYinDmg;
|
| 140 |
+
newHp = newYangHp + newYinHp;
|
| 141 |
+
justDefeated = newYangHp <= 0 && newYinHp <= 0;
|
| 142 |
+
} else {
|
| 143 |
+
const capRound = Math.min(Math.max(0, Math.floor(Number(roundDmg) || 0)), maxRoundDmg);
|
| 144 |
+
effectiveDmg = Math.min(capRound, oldHp);
|
| 145 |
+
newHp = Math.max(0, oldHp - effectiveDmg);
|
| 146 |
+
justDefeated = newHp <= 0;
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
let killer = wb.killer || null;
|
| 150 |
+
if (justDefeated) {
|
| 151 |
+
killer = {
|
| 152 |
+
uid: student.uid,
|
| 153 |
+
name: student.name || `座號${student.seat}`,
|
| 154 |
+
seat: student.seat || '',
|
| 155 |
+
at: Date.now()
|
| 156 |
+
};
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
const dRec = {
|
| 160 |
+
name: student.name || prevRec?.name || `座號${student.seat}`,
|
| 161 |
+
seat: student.seat || prevRec?.seat || '',
|
| 162 |
+
dmg: (Number(prevRec?.dmg) || 0) + effectiveDmg,
|
| 163 |
+
yangDmg: Number(prevRec?.yangDmg) || 0,
|
| 164 |
+
yinDmg: Number(prevRec?.yinDmg) || 0,
|
| 165 |
+
attacksCount: (Number(prevRec?.attacksCount) || 0) + 1,
|
| 166 |
+
...(prevRec?.dailyUsed ? { dailyUsed: { ...prevRec.dailyUsed } } : {}),
|
| 167 |
+
...(Array.isArray(prevRec?.rounds) ? { rounds: [...prevRec.rounds] } : {})
|
| 168 |
+
};
|
| 169 |
+
if (isYinYang) {
|
| 170 |
+
dRec.yangDmg += effYangDmg;
|
| 171 |
+
dRec.yinDmg += effYinDmg;
|
| 172 |
+
}
|
| 173 |
+
const newDailyUsed = prevDailyUsed + 1;
|
| 174 |
+
dRec.lastDate = today;
|
| 175 |
+
dRec.todayCount = newDailyUsed;
|
| 176 |
+
dRec.dailyUsed = { ...(dRec.dailyUsed || {}), [today]: newDailyUsed };
|
| 177 |
+
dRec.rounds = Array.isArray(dRec.rounds) ? dRec.rounds : [];
|
| 178 |
+
const roundEntry = { at: Date.now(), date: today, dmg: effectiveDmg };
|
| 179 |
+
if (isYinYang) {
|
| 180 |
+
roundEntry.yangDmg = effYangDmg;
|
| 181 |
+
roundEntry.yinDmg = effYinDmg;
|
| 182 |
+
}
|
| 183 |
+
dRec.rounds.push(roundEntry);
|
| 184 |
+
dRec.lastAt = Date.now();
|
| 185 |
+
|
| 186 |
+
const updatedWb = {
|
| 187 |
+
...wb,
|
| 188 |
+
bossId: wb.bossId || (isYinYang ? 'qiongqi' : 'taotie'),
|
| 189 |
+
name: wb.name || (isYinYang ? '上古・窮奇' : '上古・饕餮'),
|
| 190 |
+
maxHp,
|
| 191 |
+
curHp: newHp,
|
| 192 |
+
defeated: justDefeated,
|
| 193 |
+
defeatedAt: justDefeated ? (wb.defeatedAt || Date.now()) : null,
|
| 194 |
+
killer,
|
| 195 |
+
damages: {
|
| 196 |
+
...wb.damages,
|
| 197 |
+
[student.uid]: dRec
|
| 198 |
+
}
|
| 199 |
+
};
|
| 200 |
+
if (isYinYang) {
|
| 201 |
+
updatedWb.yangMaxHp = yangMaxHp;
|
| 202 |
+
updatedWb.yinMaxHp = yinMaxHp;
|
| 203 |
+
updatedWb.yangHp = newYangHp;
|
| 204 |
+
updatedWb.yinHp = newYinHp;
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
const mergedStuBoss = mergeBossObj(sBoss, {
|
| 208 |
+
...(student?.game?.boss || {}),
|
| 209 |
+
date: today,
|
| 210 |
+
used: newDailyUsed,
|
| 211 |
+
totalDmg: dRec.dmg
|
| 212 |
+
});
|
| 213 |
+
|
| 214 |
+
return {
|
| 215 |
+
orderConsumed: true,
|
| 216 |
+
alreadyDefeated: false,
|
| 217 |
+
updatedWb,
|
| 218 |
+
mergedStuBoss,
|
| 219 |
+
result: {
|
| 220 |
+
curHp: newHp,
|
| 221 |
+
maxHp,
|
| 222 |
+
yangHp: newYangHp,
|
| 223 |
+
yangMaxHp: isYinYang ? yangMaxHp : undefined,
|
| 224 |
+
yinHp: newYinHp,
|
| 225 |
+
yinMaxHp: isYinYang ? yinMaxHp : undefined,
|
| 226 |
+
effYangDmg,
|
| 227 |
+
effYinDmg,
|
| 228 |
+
defeated: updatedWb.defeated,
|
| 229 |
+
isKiller: (killer?.uid === student.uid && justDefeated),
|
| 230 |
+
killer,
|
| 231 |
+
effectiveDmg,
|
| 232 |
+
myTotalDmg: dRec.dmg,
|
| 233 |
+
orderConsumed: true,
|
| 234 |
+
alreadyDefeated: false,
|
| 235 |
+
dailyUsedToday: newDailyUsed,
|
| 236 |
+
bossState: mergedStuBoss
|
| 237 |
+
}
|
| 238 |
+
};
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
// 世界 Boss 討伐令單調高水位守衛(跨母子視窗 localStorage + 記憶體雙重防回退)
|
| 242 |
const BOSS_HWM_MEM = {};
|
| 243 |
const BOSS_HWM_PREFIX = 'idle_boss_hwm_';
|
|
|
|
| 301 |
if (!uid || !game || typeof game !== 'object') return game;
|
| 302 |
const hwm = readBossHighWaterMark(uid);
|
| 303 |
const today = todayStr();
|
| 304 |
+
const extraOrders = (game?.extraBossOrdersDate === today) ? Math.max(0, Number(game?.extraBossOrders) || 0) : 0;
|
| 305 |
+
const maxAllowed = 3 + extraOrders;
|
| 306 |
+
const curUsed = (game?.boss?.date === today) ? Math.max(0, Number(game?.boss?.used) || 0) : 0;
|
| 307 |
+
// 🛡️ 防污染校準:若本地 hwm.used 異常 > maxAllowed 且 game.boss 今日正常(<= maxAllowed),清理被歷史 bug 污染的本地快取
|
| 308 |
+
if (hwm && hwm.date === today && Number(hwm.used) > maxAllowed && curUsed <= maxAllowed) {
|
| 309 |
+
hwm.used = curUsed;
|
| 310 |
try {
|
| 311 |
if (typeof localStorage !== 'undefined') {
|
| 312 |
localStorage.setItem(BOSS_HWM_PREFIX + uid, JSON.stringify(hwm));
|
|
|
|
| 321 |
return game;
|
| 322 |
}
|
| 323 |
|
| 324 |
+
// =============================================================
|
| 325 |
+
// 錯題樂透交易純函數與 HWM 防覆寫守衛(雙後端同構)
|
| 326 |
+
// =============================================================
|
| 327 |
+
const LOTTERY_HWM_PREFIX = 'idle_lottery_hwm_';
|
| 328 |
+
const LOTTERY_HWM_MEM = Object.create(null);
|
| 329 |
+
|
| 330 |
+
function mergeLotteryCycles(a = {}, b = {}) {
|
| 331 |
+
const out = {};
|
| 332 |
+
const keys = new Set([...Object.keys(a || {}), ...Object.keys(b || {})]);
|
| 333 |
+
for (const cid of keys) {
|
| 334 |
+
const ca = a?.[cid] || {};
|
| 335 |
+
const cb = b?.[cid] || {};
|
| 336 |
+
const reg = Math.max(Math.max(0, Number(ca.regularBalls) || 0), Math.max(0, Number(cb.regularBalls) || 0));
|
| 337 |
+
const gold = Math.max(Math.max(0, Number(ca.goldenBalls) || 0), Math.max(0, Number(cb.goldenBalls) || 0));
|
| 338 |
+
const dailyUsed = {};
|
| 339 |
+
for (const d of new Set([...Object.keys(ca.dailyUsed || {}), ...Object.keys(cb.dailyUsed || {})])) {
|
| 340 |
+
dailyUsed[d] = Math.max(Number(ca.dailyUsed?.[d]) || 0, Number(cb.dailyUsed?.[d]) || 0);
|
| 341 |
+
}
|
| 342 |
+
const seenQuestionKeysByDay = {};
|
| 343 |
+
for (const d of new Set([...Object.keys(ca.seenQuestionKeysByDay || {}), ...Object.keys(cb.seenQuestionKeysByDay || {})])) {
|
| 344 |
+
seenQuestionKeysByDay[d] = Array.from(new Set([...(ca.seenQuestionKeysByDay?.[d] || []), ...(cb.seenQuestionKeysByDay?.[d] || [])]));
|
| 345 |
+
}
|
| 346 |
+
out[cid] = {
|
| 347 |
+
regularBalls: reg,
|
| 348 |
+
goldenBalls: gold,
|
| 349 |
+
weight: Math.max(reg + gold * 2, Number(ca.weight) || 0, Number(cb.weight) || 0),
|
| 350 |
+
dailyUsed,
|
| 351 |
+
seenQuestionKeysByDay,
|
| 352 |
+
claimed: Boolean(ca.claimed || cb.claimed),
|
| 353 |
+
lastRoundAt: Math.max(Number(ca.lastRoundAt) || 0, Number(cb.lastRoundAt) || 0),
|
| 354 |
+
};
|
| 355 |
+
}
|
| 356 |
+
return out;
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
function readLotteryHighWaterMark(uid) {
|
| 360 |
+
let lsData = null;
|
| 361 |
+
try {
|
| 362 |
+
if (typeof localStorage !== 'undefined') {
|
| 363 |
+
const raw = localStorage.getItem(LOTTERY_HWM_PREFIX + uid);
|
| 364 |
+
if (raw) lsData = JSON.parse(raw);
|
| 365 |
+
}
|
| 366 |
+
} catch (e) {}
|
| 367 |
+
return mergeLotteryCycles(LOTTERY_HWM_MEM[uid]?.cycles, lsData?.cycles);
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
export function recordLotteryHighWaterMark(uid, lotteryObj) {
|
| 371 |
+
if (!uid || !lotteryObj || typeof lotteryObj !== 'object') return;
|
| 372 |
+
const mergedCycles = mergeLotteryCycles(readLotteryHighWaterMark(uid), lotteryObj.cycles);
|
| 373 |
+
LOTTERY_HWM_MEM[uid] = { cycles: mergedCycles };
|
| 374 |
+
try {
|
| 375 |
+
if (typeof localStorage !== 'undefined') {
|
| 376 |
+
localStorage.setItem(LOTTERY_HWM_PREFIX + uid, JSON.stringify({ cycles: mergedCycles }));
|
| 377 |
+
}
|
| 378 |
+
} catch (e) {}
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
export function applyLotteryHighWaterMarkToGame(uid, game) {
|
| 382 |
+
if (!uid || !game || typeof game !== 'object') return game;
|
| 383 |
+
const hwmCycles = readLotteryHighWaterMark(uid);
|
| 384 |
+
const curCycles = game?.lottery?.cycles || {};
|
| 385 |
+
const merged = mergeLotteryCycles(curCycles, hwmCycles);
|
| 386 |
+
if (Object.keys(merged).length > 0) {
|
| 387 |
+
game.lottery = { cycles: merged };
|
| 388 |
+
recordLotteryHighWaterMark(uid, game.lottery);
|
| 389 |
+
}
|
| 390 |
+
return game;
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
export function settleLotteryRoundRecord(classData, studentData, studentMeta, cycleId, payload = {}) {
|
| 394 |
+
const uid = studentMeta?.uid || studentData?.uid;
|
| 395 |
+
if (!uid || !cycleId) throw new DBError('缺少學生帳號或樂透期別參數');
|
| 396 |
+
const cycle = classData?.lotteryCycles?.[cycleId];
|
| 397 |
+
if (!cycle) throw new DBError(`找不到該期錯題樂透 (${cycleId})`);
|
| 398 |
+
if (cycle.status === 'locked') throw new DBError('本期樂透箱已封箱準備開獎,無法再投入新球!');
|
| 399 |
+
if (cycle.status !== 'open') throw new DBError(`本期錯題樂透目前已關閉 (${cycle.status})`);
|
| 400 |
+
|
| 401 |
+
const today = String(payload.today || todayStr());
|
| 402 |
+
const now = Number(payload.now) || Date.now();
|
| 403 |
+
const maxDailyRounds = Math.max(1, Number(payload.maxDailyRounds ?? cycle.maxDailyRounds ?? 2));
|
| 404 |
+
const roundSize = Math.max(1, Number(payload.roundSize ?? 5));
|
| 405 |
+
|
| 406 |
+
const stuGame = (studentData?.game && typeof studentData.game === 'object') ? studentData.game : {};
|
| 407 |
+
const stuLottery = (stuGame.lottery && typeof stuGame.lottery === 'object') ? stuGame.lottery : { cycles: {} };
|
| 408 |
+
const stuCycle = stuLottery.cycles?.[cycleId] || {};
|
| 409 |
+
const clsEntry = cycle.entries?.[uid] || {};
|
| 410 |
+
|
| 411 |
+
const prevUsedToday = Math.max(
|
| 412 |
+
Number(stuCycle.dailyUsed?.[today]) || 0,
|
| 413 |
+
Number(clsEntry.dailyUsed?.[today]) || 0
|
| 414 |
+
);
|
| 415 |
+
if (prevUsedToday >= maxDailyRounds) {
|
| 416 |
+
throw new DBError(`今日已達錯題樂透投球次數上限 (${maxDailyRounds} 輪)!`);
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
const seenSet = new Set([
|
| 420 |
+
...(Array.isArray(stuCycle.seenQuestionKeysByDay?.[today]) ? stuCycle.seenQuestionKeysByDay[today] : []),
|
| 421 |
+
...(Array.isArray(clsEntry.seenTodayKeys) && clsEntry.seenTodayDate === today ? clsEntry.seenTodayKeys : []),
|
| 422 |
+
]);
|
| 423 |
+
|
| 424 |
+
let addedReg = 0;
|
| 425 |
+
let addedGold = 0;
|
| 426 |
+
const outcomes = Array.isArray(payload.roundOutcomes) ? payload.roundOutcomes : [];
|
| 427 |
+
for (const outItem of outcomes) {
|
| 428 |
+
const sc = scoreLotteryAnswer({
|
| 429 |
+
q: { _qKey: outItem?.qKey },
|
| 430 |
+
isCorrect: !!outItem?.isCorrect,
|
| 431 |
+
curRevCount: Number(outItem?.curRevCount) || 0,
|
| 432 |
+
questionIndex: Number(outItem?.questionIndex) || 0,
|
| 433 |
+
roundSize,
|
| 434 |
+
seenKeysSet: seenSet,
|
| 435 |
+
});
|
| 436 |
+
addedReg += sc.awardedRegular;
|
| 437 |
+
addedGold += sc.awardedGold;
|
| 438 |
+
if (outItem?.isCorrect && outItem?.qKey) {
|
| 439 |
+
seenSet.add(String(outItem.qKey));
|
| 440 |
+
}
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
const prevReg = Math.max(Number(stuCycle.regularBalls) || 0, Number(clsEntry.regularBalls) || 0);
|
| 444 |
+
const prevGold = Math.max(Number(stuCycle.goldenBalls) || 0, Number(clsEntry.goldenBalls) || 0);
|
| 445 |
+
const regularBalls = prevReg + addedReg;
|
| 446 |
+
const goldenBalls = prevGold + addedGold;
|
| 447 |
+
const weight = regularBalls + goldenBalls * 2;
|
| 448 |
+
const roundsToday = prevUsedToday + 1;
|
| 449 |
+
const roundsPlayed = Math.max(Number(clsEntry.roundsPlayed) || 0, 0) + 1;
|
| 450 |
+
|
| 451 |
+
const seenArr = Array.from(seenSet);
|
| 452 |
+
const nextDailyUsed = { ...(stuCycle.dailyUsed || {}), ...(clsEntry.dailyUsed || {}), [today]: roundsToday };
|
| 453 |
+
const nextStuSeenByDay = { ...(stuCycle.seenQuestionKeysByDay || {}), [today]: seenArr };
|
| 454 |
+
|
| 455 |
+
const nextClsEntry = {
|
| 456 |
+
uid,
|
| 457 |
+
seat: String(studentMeta?.seat ?? studentData?.seat ?? clsEntry.seat ?? ''),
|
| 458 |
+
name: String(studentMeta?.name ?? studentData?.name ?? clsEntry.name ?? '勇士'),
|
| 459 |
+
regularBalls,
|
| 460 |
+
goldenBalls,
|
| 461 |
+
weight,
|
| 462 |
+
roundsPlayed,
|
| 463 |
+
dailyUsed: nextDailyUsed,
|
| 464 |
+
seenTodayDate: today,
|
| 465 |
+
seenTodayKeys: seenArr,
|
| 466 |
+
lastAt: now,
|
| 467 |
+
};
|
| 468 |
+
|
| 469 |
+
const nextCycle = {
|
| 470 |
+
...cycle,
|
| 471 |
+
entries: { ...(cycle.entries || {}), [uid]: nextClsEntry },
|
| 472 |
+
updatedAt: now,
|
| 473 |
+
};
|
| 474 |
+
|
| 475 |
+
const nextStuCycle = {
|
| 476 |
+
regularBalls,
|
| 477 |
+
goldenBalls,
|
| 478 |
+
weight,
|
| 479 |
+
dailyUsed: nextDailyUsed,
|
| 480 |
+
seenQuestionKeysByDay: nextStuSeenByDay,
|
| 481 |
+
claimed: Boolean(stuCycle.claimed),
|
| 482 |
+
lastRoundAt: now,
|
| 483 |
+
};
|
| 484 |
+
|
| 485 |
+
const nextStudentLottery = {
|
| 486 |
+
cycles: { ...(stuLottery.cycles || {}), [cycleId]: nextStuCycle },
|
| 487 |
+
};
|
| 488 |
+
|
| 489 |
+
return {
|
| 490 |
+
nextCycle,
|
| 491 |
+
nextStudentLottery,
|
| 492 |
+
result: {
|
| 493 |
+
ok: true,
|
| 494 |
+
cycleId,
|
| 495 |
+
regularBalls,
|
| 496 |
+
goldenBalls,
|
| 497 |
+
weight,
|
| 498 |
+
roundsToday,
|
| 499 |
+
roundsPlayed,
|
| 500 |
+
addedReg,
|
| 501 |
+
addedGold,
|
| 502 |
+
},
|
| 503 |
+
};
|
| 504 |
+
}
|
| 505 |
+
|
| 506 |
const FB_VER = '10.12.2';
|
| 507 |
const FB = `https://www.gstatic.com/firebasejs/${FB_VER}`;
|
| 508 |
|
|
|
|
| 612 |
if (this._stCache && this._stCache.uid === uid) {
|
| 613 |
const data = this._stCache.data;
|
| 614 |
this._stCache = null; // 只用一次,之後一律讀最新資料
|
| 615 |
+
if (data?.game) {
|
| 616 |
+
applyBossHighWaterMarkToGame(uid, data.game);
|
| 617 |
+
applyLotteryHighWaterMarkToGame(uid, data.game);
|
| 618 |
+
}
|
| 619 |
return { ...data, uid };
|
| 620 |
}
|
| 621 |
const s = await this.F.getDoc(this.d('students', uid));
|
| 622 |
trafficTracker.recordOp({ type: 'read', source: 'getStudent', count: 1, estimatedBytes: 4096, note: `讀取學生資料 (${uid.slice(0, 6)}...)` });
|
| 623 |
if (!s.exists()) return null;
|
| 624 |
const data = s.data();
|
| 625 |
+
if (data?.game) {
|
| 626 |
+
applyBossHighWaterMarkToGame(uid, data.game);
|
| 627 |
+
applyLotteryHighWaterMarkToGame(uid, data.game);
|
| 628 |
+
}
|
| 629 |
return { ...data, uid };
|
| 630 |
}
|
| 631 |
|
| 632 |
async saveGame(uid, { game, progress, stats }) {
|
| 633 |
+
if (game) {
|
| 634 |
+
applyBossHighWaterMarkToGame(uid, game);
|
| 635 |
+
applyLotteryHighWaterMarkToGame(uid, game);
|
| 636 |
+
}
|
| 637 |
await this.F.updateDoc(this.d('students', uid), { game, progress, stats, lastSeen: Date.now() });
|
| 638 |
trafficTracker.recordOp({ type: 'write', source: 'saveGame', count: 1, estimatedBytes: 6144, note: `學生存檔更新 (${uid.slice(0, 6)}...)` });
|
| 639 |
}
|
|
|
|
| 719 |
if (!snap.exists()) throw new DBError('班級資料不存在');
|
| 720 |
const cData = snap.data();
|
| 721 |
// 依當期排程正規化:首位出征者的傷害寫入即完成「饕餮→窮奇」換期落地
|
| 722 |
+
const wb = normalizeWorldBossState(cData.worldBoss || defaultBossState()) || defaultBossState();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 723 |
const sData = (sSnap && sSnap.exists()) ? sSnap.data() : null;
|
| 724 |
+
const settled = settleBossDamageRecord(wb, student, roundDmg, splitDmg, sData, todayStr());
|
| 725 |
+
if (settled.alreadyDefeated) {
|
| 726 |
+
return settled.result;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 727 |
}
|
| 728 |
|
| 729 |
+
tx.update(cRef, { worldBoss: settled.updatedWb });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 730 |
if (sRef && sSnap && sSnap.exists()) {
|
| 731 |
tx.update(sRef, {
|
| 732 |
+
'game.boss': settled.mergedStuBoss,
|
| 733 |
lastSeen: Date.now()
|
| 734 |
});
|
| 735 |
}
|
| 736 |
+
return settled.result;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 737 |
});
|
| 738 |
+
if (student?.uid && res?.bossState && res?.orderConsumed !== false) {
|
| 739 |
recordBossHighWaterMark(student.uid, res.bossState);
|
| 740 |
}
|
| 741 |
+
if (res?.orderConsumed !== false) {
|
| 742 |
+
trafficTracker.recordOp({ type: 'write', source: 'recordBossDamage', count: 2, estimatedBytes: 3072, note: `討伐Boss傷害與次數原子同步 (+${res?.effectiveDmg ?? roundDmg})` });
|
| 743 |
+
}
|
| 744 |
return res;
|
| 745 |
}
|
| 746 |
|
|
|
|
| 1052 |
|
| 1053 |
async listAttempts(code) { return this._latestByClass('attempts', code, 100); }
|
| 1054 |
|
| 1055 |
+
async recordLotteryRound(classCode, studentMeta, cycleId, payload = {}) {
|
| 1056 |
+
const cCode = normCode(classCode);
|
| 1057 |
+
const uid = studentMeta?.uid;
|
| 1058 |
+
if (!cCode || !uid || !cycleId) throw new DBError('缺少樂透寫入必要參數');
|
| 1059 |
+
const clsRef = this.d('classes', cCode);
|
| 1060 |
+
const stuRef = this.d('students', uid);
|
| 1061 |
+
const txRes = await this.F.runTransaction(this.db, async (tx) => {
|
| 1062 |
+
const [clsSnap, stuSnap] = await Promise.all([tx.get(clsRef), tx.get(stuRef)]);
|
| 1063 |
+
if (!clsSnap.exists()) throw new DBError('班級資料不存在');
|
| 1064 |
+
const clsData = clsSnap.data() || {};
|
| 1065 |
+
const stuData = stuSnap.exists() ? (stuSnap.data() || {}) : {};
|
| 1066 |
+
const settled = settleLotteryRoundRecord(clsData, stuData, { ...studentMeta, uid }, cycleId, payload);
|
| 1067 |
+
tx.update(clsRef, {
|
| 1068 |
+
[`lotteryCycles.${cycleId}`]: settled.nextCycle,
|
| 1069 |
+
updatedAt: Date.now(),
|
| 1070 |
+
});
|
| 1071 |
+
if (stuSnap.exists()) {
|
| 1072 |
+
const nextGame = { ...(stuData.game || {}), lottery: settled.nextStudentLottery };
|
| 1073 |
+
tx.update(stuRef, { game: nextGame, lastSeen: Date.now() });
|
| 1074 |
+
}
|
| 1075 |
+
return settled;
|
| 1076 |
+
});
|
| 1077 |
+
recordLotteryHighWaterMark(uid, txRes.nextStudentLottery);
|
| 1078 |
+
trafficTracker.recordOp({ type: 'write', source: 'recordLotteryRound', count: 2, estimatedBytes: 4096, note: `錯題樂透投球原子入庫 (${cycleId})` });
|
| 1079 |
+
return txRes.result;
|
| 1080 |
+
}
|
| 1081 |
+
|
| 1082 |
+
async saveWeeklySpotlight(classCode, spotlight, cycleInitDoc = null) {
|
| 1083 |
+
const cCode = normCode(classCode);
|
| 1084 |
+
if (!cCode || !spotlight) throw new DBError('缺少主打活動設定參數');
|
| 1085 |
+
const clsRef = this.d('classes', cCode);
|
| 1086 |
+
await this.F.runTransaction(this.db, async (tx) => {
|
| 1087 |
+
const snap = await tx.get(clsRef);
|
| 1088 |
+
const clsData = snap.exists() ? (snap.data() || {}) : {};
|
| 1089 |
+
const patch = { weeklySpotlight: { ...spotlight, updatedAt: Date.now() }, updatedAt: Date.now() };
|
| 1090 |
+
if (cycleInitDoc && cycleInitDoc.cycleId) {
|
| 1091 |
+
const existing = clsData.lotteryCycles?.[cycleInitDoc.cycleId];
|
| 1092 |
+
patch[`lotteryCycles.${cycleInitDoc.cycleId}`] = existing
|
| 1093 |
+
? { ...existing, openAt: cycleInitDoc.openAt ?? existing.openAt, endAt: cycleInitDoc.endAt ?? existing.endAt, milestones: cycleInitDoc.milestones ?? existing.milestones, prizeMode: cycleInitDoc.prizeMode ?? existing.prizeMode, status: existing.status === 'settled' ? 'settled' : (cycleInitDoc.status || existing.status), updatedAt: Date.now() }
|
| 1094 |
+
: cycleInitDoc;
|
| 1095 |
+
}
|
| 1096 |
+
tx.update(clsRef, patch);
|
| 1097 |
+
});
|
| 1098 |
+
trafficTracker.recordOp({ type: 'write', source: 'saveWeeklySpotlight', count: 1, estimatedBytes: 2048, note: `切換週期主打活動 (${spotlight.eventId})` });
|
| 1099 |
+
}
|
| 1100 |
+
|
| 1101 |
+
async setLotteryBoxStatus(classCode, cycleId, status) {
|
| 1102 |
+
const cCode = normCode(classCode);
|
| 1103 |
+
if (!cCode || !cycleId || !status) throw new DBError('缺少樂透封箱參數');
|
| 1104 |
+
await this.F.updateDoc(this.d('classes', cCode), {
|
| 1105 |
+
[`lotteryCycles.${cycleId}.status`]: status,
|
| 1106 |
+
[`lotteryCycles.${cycleId}.updatedAt`]: Date.now(),
|
| 1107 |
+
...(status === 'locked' ? { [`lotteryCycles.${cycleId}.lockedAt`]: Date.now() } : {}),
|
| 1108 |
+
});
|
| 1109 |
+
trafficTracker.recordOp({ type: 'write', source: 'setLotteryBoxStatus', count: 1, estimatedBytes: 1024, note: `切換樂透箱狀態 → ${status}` });
|
| 1110 |
+
}
|
| 1111 |
+
|
| 1112 |
+
async extendLotteryPilotToFriday(classCode, oldCycleId = 'lotto_pilot_20261119', mode = 'keep', fridayEndAt) {
|
| 1113 |
+
const cCode = normCode(classCode);
|
| 1114 |
+
const endTs = Number(fridayEndAt) || Date.parse('2026-11-20T23:59:59+08:00');
|
| 1115 |
+
const clsRef = this.d('classes', cCode);
|
| 1116 |
+
const res = await this.F.runTransaction(this.db, async (tx) => {
|
| 1117 |
+
const snap = await tx.get(clsRef);
|
| 1118 |
+
if (!snap.exists()) throw new DBError('班級資料不存在');
|
| 1119 |
+
const clsData = snap.data() || {};
|
| 1120 |
+
const oldCycle = clsData.lotteryCycles?.[oldCycleId];
|
| 1121 |
+
if (!oldCycle) throw new DBError(`找不到期別 ${oldCycleId}`);
|
| 1122 |
+
const now = Date.now();
|
| 1123 |
+
if (mode === 'void_and_restart') {
|
| 1124 |
+
const newCycleId = 'lotto_pilot_20261120';
|
| 1125 |
+
const openTs = Math.min(now, Date.parse('2026-11-20T07:00:00+08:00'));
|
| 1126 |
+
const newCycle = {
|
| 1127 |
+
cycleId: newCycleId,
|
| 1128 |
+
title: '週五快閃重測(週四場次已作廢重開)',
|
| 1129 |
+
status: 'open',
|
| 1130 |
+
prizeMode: oldCycle.prizeMode || 'pilot',
|
| 1131 |
+
themeId: oldCycle.themeId || 'pilot_flash',
|
| 1132 |
+
questionMode: oldCycle.questionMode || 'mixed',
|
| 1133 |
+
maxDailyRounds: oldCycle.maxDailyRounds || 2,
|
| 1134 |
+
milestones: Array.isArray(oldCycle.milestones) ? [...oldCycle.milestones] : [45, 90, 140],
|
| 1135 |
+
openAt: openTs,
|
| 1136 |
+
endAt: endTs,
|
| 1137 |
+
entries: {},
|
| 1138 |
+
drawResult: null,
|
| 1139 |
+
updatedAt: now,
|
| 1140 |
+
};
|
| 1141 |
+
tx.update(clsRef, {
|
| 1142 |
+
[`lotteryCycles.${oldCycleId}.status`]: 'voided',
|
| 1143 |
+
[`lotteryCycles.${oldCycleId}.updatedAt`]: now,
|
| 1144 |
+
[`lotteryCycles.${newCycleId}`]: newCycle,
|
| 1145 |
+
weeklySpotlight: { ...(clsData.weeklySpotlight || {}), eventId: 'lottery', cycleId: newCycleId, openAt: openTs, endAt: endTs, allowDuringCaravan: true, updatedAt: now },
|
| 1146 |
+
updatedAt: now,
|
| 1147 |
+
});
|
| 1148 |
+
return { mode, cycleId: newCycleId, endAt: endTs };
|
| 1149 |
+
}
|
| 1150 |
+
tx.update(clsRef, {
|
| 1151 |
+
[`lotteryCycles.${oldCycleId}.status`]: 'open',
|
| 1152 |
+
[`lotteryCycles.${oldCycleId}.endAt`]: endTs,
|
| 1153 |
+
[`lotteryCycles.${oldCycleId}.updatedAt`]: now,
|
| 1154 |
+
'weeklySpotlight.endAt': endTs,
|
| 1155 |
+
'weeklySpotlight.updatedAt': now,
|
| 1156 |
+
updatedAt: now,
|
| 1157 |
+
});
|
| 1158 |
+
return { mode: 'keep', cycleId: oldCycleId, endAt: endTs };
|
| 1159 |
+
});
|
| 1160 |
+
trafficTracker.recordOp({ type: 'write', source: 'extendLotteryPilotToFriday', count: 1, estimatedBytes: 2048, note: `快閃延長至週五 (${res.mode})` });
|
| 1161 |
+
return res;
|
| 1162 |
+
}
|
| 1163 |
+
|
| 1164 |
+
async settleLotteryDraw(classCode, cycleId, drawResult, giftItems = [], logMeta = {}) {
|
| 1165 |
+
const cCode = normCode(classCode);
|
| 1166 |
+
if (!cCode || !cycleId) throw new DBError('缺少開獎結算參數');
|
| 1167 |
+
const clsRef = this.d('classes', cCode);
|
| 1168 |
+
const now = Date.now();
|
| 1169 |
+
await this.F.runTransaction(this.db, async (tx) => {
|
| 1170 |
+
const snap = await tx.get(clsRef);
|
| 1171 |
+
if (!snap.exists()) throw new DBError('班級資料不存在');
|
| 1172 |
+
const cycle = snap.data()?.lotteryCycles?.[cycleId];
|
| 1173 |
+
if (!cycle) throw new DBError(`找不到期別 ${cycleId}`);
|
| 1174 |
+
if (cycle.status === 'settled') throw new DBError('此期錯題樂透已結算過(settled),禁止重複發信!');
|
| 1175 |
+
tx.update(clsRef, {
|
| 1176 |
+
[`lotteryCycles.${cycleId}.status`]: 'settled',
|
| 1177 |
+
[`lotteryCycles.${cycleId}.drawResult`]: { ...(drawResult || {}), settledAt: now },
|
| 1178 |
+
[`lotteryCycles.${cycleId}.updatedAt`]: now,
|
| 1179 |
+
updatedAt: now,
|
| 1180 |
+
});
|
| 1181 |
+
});
|
| 1182 |
+
if (Array.isArray(giftItems) && giftItems.length > 0) {
|
| 1183 |
+
await this.sendGiftsPersonalized(giftItems, {
|
| 1184 |
+
kind: 'lottery_settle',
|
| 1185 |
+
lotteryCycleId: cycleId,
|
| 1186 |
+
reason: logMeta.reason || `🎰 錯題樂透開獎結算 (${cycleId})`,
|
| 1187 |
+
...logMeta,
|
| 1188 |
+
});
|
| 1189 |
+
}
|
| 1190 |
+
trafficTracker.recordOp({ type: 'write', source: 'settleLotteryDraw', count: 1, estimatedBytes: 2048, note: `錯題樂透開獎封存 (${cycleId})` });
|
| 1191 |
+
}
|
| 1192 |
+
|
| 1193 |
+
async markLegacyBossCleared(classCode, ts = Date.now()) {
|
| 1194 |
+
const cCode = normCode(classCode);
|
| 1195 |
+
await this.F.updateDoc(this.d('classes', cCode), {
|
| 1196 |
+
legacyBossClearedAt: ts,
|
| 1197 |
+
'worldBoss.hidden': true,
|
| 1198 |
+
'worldBoss.phaseMode': 'closed',
|
| 1199 |
+
updatedAt: Date.now(),
|
| 1200 |
+
});
|
| 1201 |
+
trafficTracker.recordOp({ type: 'write', source: 'markLegacyBossCleared', count: 1, estimatedBytes: 1024, note: '確認舊版窮奇全員領完並全面收起' });
|
| 1202 |
+
}
|
| 1203 |
+
|
| 1204 |
getTrafficStats() { return trafficTracker.getQuotaStatus(); }
|
| 1205 |
simulateTraffic(params) { return trafficTracker.simulateLoad(params); }
|
| 1206 |
resetTrafficStats() { trafficTracker.reset(); }
|
|
|
|
| 1274 |
|
| 1275 |
async getStudent(uid) {
|
| 1276 |
const s = this.load().students[uid];
|
| 1277 |
+
if (!s) return null;
|
| 1278 |
+
if (s.game) {
|
| 1279 |
+
applyBossHighWaterMarkToGame(uid, s.game);
|
| 1280 |
+
applyLotteryHighWaterMarkToGame(uid, s.game);
|
| 1281 |
+
}
|
| 1282 |
+
return { uid, ...s };
|
| 1283 |
}
|
| 1284 |
|
| 1285 |
async saveGame(uid, { game, progress, stats }) {
|
| 1286 |
const db = this.load();
|
| 1287 |
if (!db.students[uid]) throw new DBError('找不到學生資料');
|
| 1288 |
+
if (game) {
|
| 1289 |
+
applyBossHighWaterMarkToGame(uid, game);
|
| 1290 |
+
applyLotteryHighWaterMarkToGame(uid, game);
|
| 1291 |
+
}
|
| 1292 |
Object.assign(db.students[uid], { game, progress, stats, lastSeen: Date.now() });
|
| 1293 |
this.save(db);
|
| 1294 |
}
|
|
|
|
| 1358 |
const db = this.load();
|
| 1359 |
const c = db.classes[normCode(classCode)];
|
| 1360 |
if (!c) throw new DBError('班級不存在');
|
| 1361 |
+
const wb = normalizeWorldBossState(c.worldBoss || defaultBossState()) || defaultBossState();
|
| 1362 |
+
const sData = (student?.uid && db.students?.[student.uid]) ? db.students[student.uid] : null;
|
| 1363 |
+
const settled = settleBossDamageRecord(wb, student, roundDmg, splitDmg, sData, todayStr());
|
| 1364 |
+
if (settled.alreadyDefeated) {
|
| 1365 |
+
return settled.result;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1366 |
}
|
| 1367 |
|
| 1368 |
+
c.worldBoss = settled.updatedWb;
|
| 1369 |
+
if (sData && settled.mergedStuBoss) {
|
| 1370 |
+
sData.game = sData.game || {};
|
| 1371 |
+
sData.game.boss = settled.mergedStuBoss;
|
| 1372 |
+
sData.lastSeen = Date.now();
|
|
|
|
|
|
|
|
|
|
| 1373 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1374 |
this.save(db);
|
| 1375 |
+
if (student?.uid && settled.result?.bossState && settled.result?.orderConsumed !== false) {
|
| 1376 |
+
recordBossHighWaterMark(student.uid, settled.result.bossState);
|
| 1377 |
+
}
|
| 1378 |
+
return settled.result;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1379 |
}
|
| 1380 |
|
| 1381 |
async resetClassBoss(classCode, maxHp = 500, bossId = null) {
|
|
|
|
| 1642 |
return this.load().attempts.filter((a) => a.classCode === normCode(code)).sort((a, b) => b.at - a.at);
|
| 1643 |
}
|
| 1644 |
|
| 1645 |
+
async recordLotteryRound(classCode, studentMeta, cycleId, payload = {}) {
|
| 1646 |
+
const cCode = normCode(classCode);
|
| 1647 |
+
const uid = studentMeta?.uid;
|
| 1648 |
+
if (!cCode || !uid || !cycleId) throw new DBError('缺少樂透寫入必要參數');
|
| 1649 |
+
const db = this.load();
|
| 1650 |
+
const clsData = db.classes[cCode];
|
| 1651 |
+
if (!clsData) throw new DBError('班級資料不存在');
|
| 1652 |
+
const stuData = db.students[uid] || {};
|
| 1653 |
+
const settled = settleLotteryRoundRecord(clsData, stuData, { ...studentMeta, uid }, cycleId, payload);
|
| 1654 |
+
clsData.lotteryCycles = { ...(clsData.lotteryCycles || {}), [cycleId]: settled.nextCycle };
|
| 1655 |
+
clsData.updatedAt = Date.now();
|
| 1656 |
+
if (db.students[uid]) {
|
| 1657 |
+
db.students[uid].game = { ...(db.students[uid].game || {}), lottery: settled.nextStudentLottery };
|
| 1658 |
+
db.students[uid].lastSeen = Date.now();
|
| 1659 |
+
}
|
| 1660 |
+
this.save(db);
|
| 1661 |
+
recordLotteryHighWaterMark(uid, settled.nextStudentLottery);
|
| 1662 |
+
return settled.result;
|
| 1663 |
+
}
|
| 1664 |
+
|
| 1665 |
+
async saveWeeklySpotlight(classCode, spotlight, cycleInitDoc = null) {
|
| 1666 |
+
const cCode = normCode(classCode);
|
| 1667 |
+
if (!cCode || !spotlight) throw new DBError('缺少主打活動設定參數');
|
| 1668 |
+
const db = this.load();
|
| 1669 |
+
const c = db.classes[cCode];
|
| 1670 |
+
if (!c) throw new DBError('班級不存在');
|
| 1671 |
+
c.weeklySpotlight = { ...spotlight, updatedAt: Date.now() };
|
| 1672 |
+
if (cycleInitDoc && cycleInitDoc.cycleId) {
|
| 1673 |
+
c.lotteryCycles = c.lotteryCycles || {};
|
| 1674 |
+
const existing = c.lotteryCycles[cycleInitDoc.cycleId];
|
| 1675 |
+
c.lotteryCycles[cycleInitDoc.cycleId] = existing
|
| 1676 |
+
? { ...existing, openAt: cycleInitDoc.openAt ?? existing.openAt, endAt: cycleInitDoc.endAt ?? existing.endAt, milestones: cycleInitDoc.milestones ?? existing.milestones, prizeMode: cycleInitDoc.prizeMode ?? existing.prizeMode, status: existing.status === 'settled' ? 'settled' : (cycleInitDoc.status || existing.status), updatedAt: Date.now() }
|
| 1677 |
+
: cycleInitDoc;
|
| 1678 |
+
}
|
| 1679 |
+
c.updatedAt = Date.now();
|
| 1680 |
+
this.save(db);
|
| 1681 |
+
}
|
| 1682 |
+
|
| 1683 |
+
async setLotteryBoxStatus(classCode, cycleId, status) {
|
| 1684 |
+
const cCode = normCode(classCode);
|
| 1685 |
+
const db = this.load();
|
| 1686 |
+
const c = db.classes[cCode];
|
| 1687 |
+
if (!c || !c.lotteryCycles?.[cycleId]) throw new DBError('找不到該期樂透');
|
| 1688 |
+
c.lotteryCycles[cycleId].status = status;
|
| 1689 |
+
c.lotteryCycles[cycleId].updatedAt = Date.now();
|
| 1690 |
+
if (status === 'locked') c.lotteryCycles[cycleId].lockedAt = Date.now();
|
| 1691 |
+
c.updatedAt = Date.now();
|
| 1692 |
+
this.save(db);
|
| 1693 |
+
}
|
| 1694 |
+
|
| 1695 |
+
async extendLotteryPilotToFriday(classCode, oldCycleId = 'lotto_pilot_20261119', mode = 'keep', fridayEndAt) {
|
| 1696 |
+
const cCode = normCode(classCode);
|
| 1697 |
+
const endTs = Number(fridayEndAt) || Date.parse('2026-11-20T23:59:59+08:00');
|
| 1698 |
+
const db = this.load();
|
| 1699 |
+
const clsData = db.classes[cCode];
|
| 1700 |
+
if (!clsData) throw new DBError('班級不存在');
|
| 1701 |
+
const oldCycle = clsData.lotteryCycles?.[oldCycleId];
|
| 1702 |
+
if (!oldCycle) throw new DBError(`找不到期別 ${oldCycleId}`);
|
| 1703 |
+
const now = Date.now();
|
| 1704 |
+
if (mode === 'void_and_restart') {
|
| 1705 |
+
const newCycleId = 'lotto_pilot_20261120';
|
| 1706 |
+
const openTs = Math.min(now, Date.parse('2026-11-20T07:00:00+08:00'));
|
| 1707 |
+
oldCycle.status = 'voided';
|
| 1708 |
+
oldCycle.updatedAt = now;
|
| 1709 |
+
clsData.lotteryCycles[newCycleId] = {
|
| 1710 |
+
cycleId: newCycleId,
|
| 1711 |
+
title: '週五快閃重測(週四場次已作廢重開)',
|
| 1712 |
+
status: 'open',
|
| 1713 |
+
prizeMode: oldCycle.prizeMode || 'pilot',
|
| 1714 |
+
themeId: oldCycle.themeId || 'pilot_flash',
|
| 1715 |
+
questionMode: oldCycle.questionMode || 'mixed',
|
| 1716 |
+
maxDailyRounds: oldCycle.maxDailyRounds || 2,
|
| 1717 |
+
milestones: Array.isArray(oldCycle.milestones) ? [...oldCycle.milestones] : [45, 90, 140],
|
| 1718 |
+
openAt: openTs,
|
| 1719 |
+
endAt: endTs,
|
| 1720 |
+
entries: {},
|
| 1721 |
+
drawResult: null,
|
| 1722 |
+
updatedAt: now,
|
| 1723 |
+
};
|
| 1724 |
+
clsData.weeklySpotlight = { ...(clsData.weeklySpotlight || {}), eventId: 'lottery', cycleId: newCycleId, openAt: openTs, endAt: endTs, allowDuringCaravan: true, updatedAt: now };
|
| 1725 |
+
clsData.updatedAt = now;
|
| 1726 |
+
this.save(db);
|
| 1727 |
+
return { mode, cycleId: newCycleId, endAt: endTs };
|
| 1728 |
+
}
|
| 1729 |
+
oldCycle.status = 'open';
|
| 1730 |
+
oldCycle.endAt = endTs;
|
| 1731 |
+
oldCycle.updatedAt = now;
|
| 1732 |
+
clsData.weeklySpotlight = { ...(clsData.weeklySpotlight || {}), endAt: endTs, updatedAt: now };
|
| 1733 |
+
clsData.updatedAt = now;
|
| 1734 |
+
this.save(db);
|
| 1735 |
+
return { mode: 'keep', cycleId: oldCycleId, endAt: endTs };
|
| 1736 |
+
}
|
| 1737 |
+
|
| 1738 |
+
async settleLotteryDraw(classCode, cycleId, drawResult, giftItems = [], logMeta = {}) {
|
| 1739 |
+
const cCode = normCode(classCode);
|
| 1740 |
+
const db = this.load();
|
| 1741 |
+
const clsData = db.classes[cCode];
|
| 1742 |
+
const cycle = clsData?.lotteryCycles?.[cycleId];
|
| 1743 |
+
if (!cycle) throw new DBError(`找不到期別 ${cycleId}`);
|
| 1744 |
+
if (cycle.status === 'settled') throw new DBError('此期錯題樂透已結算過(settled),禁止重複發信!');
|
| 1745 |
+
const now = Date.now();
|
| 1746 |
+
cycle.status = 'settled';
|
| 1747 |
+
cycle.drawResult = { ...(drawResult || {}), settledAt: now };
|
| 1748 |
+
cycle.updatedAt = now;
|
| 1749 |
+
clsData.updatedAt = now;
|
| 1750 |
+
this.save(db);
|
| 1751 |
+
if (Array.isArray(giftItems) && giftItems.length > 0) {
|
| 1752 |
+
await this.sendGiftsPersonalized(giftItems, {
|
| 1753 |
+
kind: 'lottery_settle',
|
| 1754 |
+
lotteryCycleId: cycleId,
|
| 1755 |
+
reason: logMeta.reason || `🎰 錯題樂透開獎結算 (${cycleId})`,
|
| 1756 |
+
...logMeta,
|
| 1757 |
+
});
|
| 1758 |
+
}
|
| 1759 |
+
}
|
| 1760 |
+
|
| 1761 |
+
async markLegacyBossCleared(classCode, ts = Date.now()) {
|
| 1762 |
+
const cCode = normCode(classCode);
|
| 1763 |
+
const db = this.load();
|
| 1764 |
+
const clsData = db.classes[cCode];
|
| 1765 |
+
if (!clsData) throw new DBError('班級不存在');
|
| 1766 |
+
clsData.legacyBossClearedAt = ts;
|
| 1767 |
+
if (clsData.worldBoss) {
|
| 1768 |
+
clsData.worldBoss.hidden = true;
|
| 1769 |
+
clsData.worldBoss.phaseMode = 'closed';
|
| 1770 |
+
}
|
| 1771 |
+
clsData.updatedAt = Date.now();
|
| 1772 |
+
this.save(db);
|
| 1773 |
+
}
|
| 1774 |
+
|
| 1775 |
getTrafficStats() { return trafficTracker.getQuotaStatus(); }
|
| 1776 |
simulateTraffic(params) { return trafficTracker.simulateLoad(params); }
|
| 1777 |
resetTrafficStats() { trafficTracker.reset(); }
|
|
|
|
| 1793 |
return _db;
|
| 1794 |
}
|
| 1795 |
|
| 1796 |
+
export { trafficTracker, LocalBackend };
|
js/engine.js
CHANGED
|
@@ -52,6 +52,7 @@ export function newGame() {
|
|
| 52 |
extraBossOrders: 0,
|
| 53 |
extraBossOrdersDate: null,
|
| 54 |
boss: { date: null, used: 0, rewardClaimed: false, claimed: {} },
|
|
|
|
| 55 |
buildings,
|
| 56 |
peakBuildings: {},
|
| 57 |
peakProd: 0,
|
|
@@ -280,6 +281,48 @@ export function normalizeGame(g) {
|
|
| 280 |
out.stats = { ...(g.stats || {}) };
|
| 281 |
out.extraBossOrdersDate = g.extraBossOrdersDate || g.boss?.date || null;
|
| 282 |
out.extraBossOrders = (out.extraBossOrdersDate === today) ? Math.max(0, Number(g.extraBossOrders) || 0) : 0;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
out.lastTick = Number(out.lastTick) || Date.now();
|
| 284 |
return out;
|
| 285 |
}
|
|
|
|
| 52 |
extraBossOrders: 0,
|
| 53 |
extraBossOrdersDate: null,
|
| 54 |
boss: { date: null, used: 0, rewardClaimed: false, claimed: {} },
|
| 55 |
+
lottery: { cycles: {} },
|
| 56 |
buildings,
|
| 57 |
peakBuildings: {},
|
| 58 |
peakProd: 0,
|
|
|
|
| 281 |
out.stats = { ...(g.stats || {}) };
|
| 282 |
out.extraBossOrdersDate = g.extraBossOrdersDate || g.boss?.date || null;
|
| 283 |
out.extraBossOrders = (out.extraBossOrdersDate === today) ? Math.max(0, Number(g.extraBossOrders) || 0) : 0;
|
| 284 |
+
|
| 285 |
+
// 錯題樂透正規化+自動裁剪 7 日以前題鍵明細(保留近 3 期完整明細)
|
| 286 |
+
const rawLotCycles = (g.lottery && typeof g.lottery.cycles === 'object' && g.lottery.cycles) ? g.lottery.cycles : {};
|
| 287 |
+
const todayMidMs = Date.parse(`${today}T12:00:00+08:00`);
|
| 288 |
+
const cycleEntries = Object.entries(rawLotCycles);
|
| 289 |
+
cycleEntries.sort((a, b) => (Number(b[1]?.lastRoundAt) || 0) - (Number(a[1]?.lastRoundAt) || 0));
|
| 290 |
+
const prunedCycles = {};
|
| 291 |
+
cycleEntries.forEach(([cid, cData], idx) => {
|
| 292 |
+
if (!cData || typeof cData !== 'object') return;
|
| 293 |
+
const reg = Math.max(0, Math.floor(Number(cData.regularBalls) || 0));
|
| 294 |
+
const gold = Math.max(0, Math.floor(Number(cData.goldenBalls) || 0));
|
| 295 |
+
const weight = Math.max(reg + gold * 2, Math.floor(Number(cData.weight) || 0));
|
| 296 |
+
const dailyUsed = {};
|
| 297 |
+
if (cData.dailyUsed && typeof cData.dailyUsed === 'object') {
|
| 298 |
+
for (const [dKey, cnt] of Object.entries(cData.dailyUsed)) {
|
| 299 |
+
const dMs = Date.parse(`${dKey}T12:00:00+08:00`);
|
| 300 |
+
if (idx < 3 || !Number.isFinite(dMs) || !Number.isFinite(todayMidMs) || (todayMidMs - dMs) <= 14 * 86400 * 1000) {
|
| 301 |
+
dailyUsed[dKey] = Math.max(0, Math.floor(Number(cnt) || 0));
|
| 302 |
+
}
|
| 303 |
+
}
|
| 304 |
+
}
|
| 305 |
+
const seenQuestionKeysByDay = {};
|
| 306 |
+
if (idx < 3 && cData.seenQuestionKeysByDay && typeof cData.seenQuestionKeysByDay === 'object') {
|
| 307 |
+
for (const [dKey, arr] of Object.entries(cData.seenQuestionKeysByDay)) {
|
| 308 |
+
const dMs = Date.parse(`${dKey}T12:00:00+08:00`);
|
| 309 |
+
if (Number.isFinite(dMs) && Number.isFinite(todayMidMs) && (todayMidMs - dMs) <= 7 * 86400 * 1000 && Array.isArray(arr)) {
|
| 310 |
+
seenQuestionKeysByDay[dKey] = Array.from(new Set(arr.map(String)));
|
| 311 |
+
}
|
| 312 |
+
}
|
| 313 |
+
}
|
| 314 |
+
prunedCycles[cid] = {
|
| 315 |
+
regularBalls: reg,
|
| 316 |
+
goldenBalls: gold,
|
| 317 |
+
weight,
|
| 318 |
+
dailyUsed,
|
| 319 |
+
seenQuestionKeysByDay,
|
| 320 |
+
claimed: Boolean(cData.claimed),
|
| 321 |
+
lastRoundAt: Number(cData.lastRoundAt) || 0,
|
| 322 |
+
};
|
| 323 |
+
});
|
| 324 |
+
out.lottery = { cycles: prunedCycles };
|
| 325 |
+
|
| 326 |
out.lastTick = Number(out.lastTick) || Date.now();
|
| 327 |
return out;
|
| 328 |
}
|
tools/verify-integrity.mjs
CHANGED
|
@@ -78,7 +78,7 @@ import {
|
|
| 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';
|
| 82 |
import { computeStudentAudit, cumStarCost } from '../.agents/skills/student-resource-audit/scripts/audit-student.js';
|
| 83 |
|
| 84 |
const ROOT = process.cwd();
|
|
@@ -1376,4 +1376,122 @@ ok('可插拔活動排程、週四快閃並列與舊窮奇領完才隱藏檢驗
|
|
| 1376 |
}
|
| 1377 |
ok('錯題樂透純函數核心(r2->r1->r0、金球+幸運球、升級遞補與智慧里程碑)100% 通過');
|
| 1378 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1379 |
console.log(`\n🎉 全部 ${passedChecks} 大項工程防呆檢驗 100% 通過!可安全部署上線。`);
|
|
|
|
| 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, settleLotteryRoundRecord, applyLotteryHighWaterMarkToGame, recordLotteryHighWaterMark } from '../js/db.js';
|
| 82 |
import { computeStudentAudit, cumStarCost } from '../.agents/skills/student-resource-audit/scripts/audit-student.js';
|
| 83 |
|
| 84 |
const ROOT = process.cwd();
|
|
|
|
| 1376 |
}
|
| 1377 |
ok('錯題樂透純函數核心(r2->r1->r0、金球+幸運球、升級遞補與智慧里程碑)100% 通過');
|
| 1378 |
|
| 1379 |
+
// ----------------------------------------------------------------------------
|
| 1380 |
+
// 19. 樂透存檔 Schema、HWM 守衛、同構交易與週四→週五雙模式延展檢驗 (Task A3)
|
| 1381 |
+
// ----------------------------------------------------------------------------
|
| 1382 |
+
{
|
| 1383 |
+
// 19.1 Schema、normalizeGame 保真與 7 日外 seenQuestionKeysByDay 自動裁剪
|
| 1384 |
+
const g0 = newGame();
|
| 1385 |
+
assert.ok(g0.lottery && typeof g0.lottery.cycles === 'object', 'newGame() 必須初始化 game.lottery.cycles');
|
| 1386 |
+
g0.lottery.cycles.lotto_pilot_20261119 = {
|
| 1387 |
+
regularBalls: 4,
|
| 1388 |
+
goldenBalls: 1,
|
| 1389 |
+
weight: 6,
|
| 1390 |
+
dailyUsed: { '2026-11-19': 1 },
|
| 1391 |
+
seenQuestionKeysByDay: { '2020-01-01': ['old_1'], [todayStr()]: ['fresh_1'] },
|
| 1392 |
+
claimed: false,
|
| 1393 |
+
};
|
| 1394 |
+
const gNorm = normalizeGame(g0);
|
| 1395 |
+
assert.equal(gNorm.lottery.cycles.lotto_pilot_20261119.weight, 6, 'normalizeGame 必須保留當期彩球與籤權');
|
| 1396 |
+
assert.equal(gNorm.lottery.cycles.lotto_pilot_20261119.seenQuestionKeysByDay['2020-01-01'], undefined, '逾 7 天歷史題鍵明細應自動清理');
|
| 1397 |
+
assert.deepEqual(gNorm.lottery.cycles.lotto_pilot_20261119.seenQuestionKeysByDay[todayStr()], ['fresh_1'], '今日題鍵應保留去重');
|
| 1398 |
+
|
| 1399 |
+
// 19.2 LocalBackend 原子交易(同日去重、2輪上限鎖、封箱擋單、HWM、延長/作廢週五、防重結算)
|
| 1400 |
+
const pilotSetup = buildPilotLotterySpotlightPreset();
|
| 1401 |
+
const mockLocalStorageStore = {};
|
| 1402 |
+
const origLS = globalThis.localStorage;
|
| 1403 |
+
globalThis.localStorage = {
|
| 1404 |
+
getItem: (k) => (k in mockLocalStorageStore ? mockLocalStorageStore[k] : null),
|
| 1405 |
+
setItem: (k, v) => { mockLocalStorageStore[k] = String(v); },
|
| 1406 |
+
removeItem: (k) => { delete mockLocalStorageStore[k]; },
|
| 1407 |
+
};
|
| 1408 |
+
try {
|
| 1409 |
+
const lb = new LocalBackend();
|
| 1410 |
+
await lb.init();
|
| 1411 |
+
const dbState = lb.load();
|
| 1412 |
+
dbState.classes['test101'] = { name: '測試班', bank: 'wiring', worldBoss: { bossId: 'qiongqi', hidden: true } };
|
| 1413 |
+
dbState.students['stu_a'] = { uid: 'stu_a', classCode: 'test101', seat: '1', name: '甲生', role: 'student', game: newGame(), progress: {}, stats: {} };
|
| 1414 |
+
lb.save(dbState);
|
| 1415 |
+
|
| 1416 |
+
await lb.saveWeeklySpotlight('test101', pilotSetup.weeklySpotlight, pilotSetup.lotteryCycle);
|
| 1417 |
+
|
| 1418 |
+
// 第 1 輪:全對,其中 q5 為畢業金球(+1金+1幸運銀 = +3權重),其餘 4 銀 -> 共 5銀 + 1金 = 7權重
|
| 1419 |
+
const r1 = await lb.recordLotteryRound('test101', { uid: 'stu_a', seat: '1', name: '甲生' }, 'lotto_pilot_20261119', {
|
| 1420 |
+
today: '2026-11-19',
|
| 1421 |
+
maxDailyRounds: 2,
|
| 1422 |
+
roundOutcomes: [
|
| 1423 |
+
{ qKey: 'w_1', isCorrect: true, curRevCount: 0, questionIndex: 0 },
|
| 1424 |
+
{ qKey: 'w_2', isCorrect: true, curRevCount: 1, questionIndex: 1 },
|
| 1425 |
+
{ qKey: 'w_3', isCorrect: true, curRevCount: 0, questionIndex: 2 },
|
| 1426 |
+
{ qKey: 'w_4', isCorrect: true, curRevCount: 1, questionIndex: 3 },
|
| 1427 |
+
{ qKey: 'w_5', isCorrect: true, curRevCount: 2, questionIndex: 4 },
|
| 1428 |
+
],
|
| 1429 |
+
});
|
| 1430 |
+
assert.equal(r1.regularBalls, 5, '5銀球(含Q5幸運銀球)');
|
| 1431 |
+
assert.equal(r1.goldenBalls, 1, '1金球(Q5精熟畢業)');
|
| 1432 |
+
assert.equal(r1.weight, 7);
|
| 1433 |
+
assert.equal(r1.roundsToday, 1);
|
| 1434 |
+
|
| 1435 |
+
// 第 2 輪:夾帶今日已出現過的 w_1(伺服器應去重僅算新題 w_6 -> 僅 +1 銀)
|
| 1436 |
+
const r2 = await lb.recordLotteryRound('test101', { uid: 'stu_a', seat: '1', name: '甲生' }, 'lotto_pilot_20261119', {
|
| 1437 |
+
today: '2026-11-19',
|
| 1438 |
+
maxDailyRounds: 2,
|
| 1439 |
+
roundOutcomes: [
|
| 1440 |
+
{ qKey: 'w_1', isCorrect: true, curRevCount: 1, questionIndex: 0 },
|
| 1441 |
+
{ qKey: 'w_6', isCorrect: true, curRevCount: 0, questionIndex: 1 },
|
| 1442 |
+
],
|
| 1443 |
+
});
|
| 1444 |
+
assert.equal(r2.regularBalls, 6, '交易內同日 w_1 應自動去重,僅加算新題 w_6');
|
| 1445 |
+
assert.equal(r2.roundsToday, 2);
|
| 1446 |
+
|
| 1447 |
+
// 第 3 輪超過當日上限 2 輪必須拒絕
|
| 1448 |
+
await assert.rejects(
|
| 1449 |
+
() => lb.recordLotteryRound('test101', { uid: 'stu_a', seat: '1', name: '甲生' }, 'lotto_pilot_20261119', { today: '2026-11-19', maxDailyRounds: 2, roundOutcomes: [] }),
|
| 1450 |
+
/上限|今日已/,
|
| 1451 |
+
'當日第 3 輪必須遭交易層拒絕'
|
| 1452 |
+
);
|
| 1453 |
+
|
| 1454 |
+
// HWM 保護:過時 saveGame() 不可洗掉剛入帳的球數與輪次
|
| 1455 |
+
recordLotteryHighWaterMark('stu_a', lb.load().students['stu_a'].game.lottery);
|
| 1456 |
+
const staleGame = newGame();
|
| 1457 |
+
await lb.saveGame('stu_a', { game: staleGame, progress: {}, stats: {} });
|
| 1458 |
+
assert.equal(lb.load().students['stu_a'].game.lottery.cycles.lotto_pilot_20261119.weight, 8, 'saveGame HWM 守衛必須保留已入袋 8 籤權');
|
| 1459 |
+
|
| 1460 |
+
// 封箱後拒絕新日投球;解除封箱後可恢復
|
| 1461 |
+
await lb.setLotteryBoxStatus('test101', 'lotto_pilot_20261119', 'locked');
|
| 1462 |
+
await assert.rejects(
|
| 1463 |
+
() => lb.recordLotteryRound('test101', { uid: 'stu_a', seat: '1', name: '甲生' }, 'lotto_pilot_20261119', { today: '2026-11-20', maxDailyRounds: 2, roundOutcomes: [] }),
|
| 1464 |
+
/封箱/,
|
| 1465 |
+
'封箱狀態必須拒絕投球'
|
| 1466 |
+
);
|
| 1467 |
+
await lb.setLotteryBoxStatus('test101', 'lotto_pilot_20261119', 'open');
|
| 1468 |
+
|
| 1469 |
+
// 延長週五選項 (a) keep:延長 endAt 至週五,保留原週四 8 籤權
|
| 1470 |
+
const friEndTs = new Date('2026-11-20T23:59:59+08:00').getTime();
|
| 1471 |
+
await lb.extendLotteryPilotToFriday('test101', 'lotto_pilot_20261119', 'keep', friEndTs);
|
| 1472 |
+
assert.equal(lb.load().classes['test101'].lotteryCycles.lotto_pilot_20261119.entries.stu_a.weight, 8);
|
| 1473 |
+
assert.equal(lb.load().classes['test101'].weeklySpotlight.endAt, friEndTs);
|
| 1474 |
+
|
| 1475 |
+
// 延長週五選項 (b) void_and_restart:作廢舊期並開啟 lotto_pilot_20261120,徹底隔離舊 HWM 與次數
|
| 1476 |
+
await lb.extendLotteryPilotToFriday('test101', 'lotto_pilot_20261119', 'void_and_restart', friEndTs);
|
| 1477 |
+
const afterVoidCls = lb.load().classes['test101'];
|
| 1478 |
+
assert.equal(afterVoidCls.lotteryCycles.lotto_pilot_20261119.status, 'voided', '週四舊期應封存標記為 voided');
|
| 1479 |
+
assert.equal(afterVoidCls.weeklySpotlight.cycleId, 'lotto_pilot_20261120', '應切換至全新週五獨立期別');
|
| 1480 |
+
assert.deepEqual(afterVoidCls.lotteryCycles.lotto_pilot_20261120.entries, {}, '新期別彩球應清空從零開始');
|
| 1481 |
+
|
| 1482 |
+
// 在週五新期別結算發獎+防重複結算鎖
|
| 1483 |
+
const drawRes = { winners: [{ uid: 'stu_a', tierKey: 'head', bp: 6 }], totalWeight: 10, settledAt: Date.now() };
|
| 1484 |
+
await lb.settleLotteryDraw('test101', 'lotto_pilot_20261120', drawRes, [{ student: { uid: 'stu_a', seat: '1', name: '甲生' }, uid: 'stu_a', gift: { bp: 6, lotteryCycleId: 'lotto_pilot_20261120', kind: 'lottery_settle' } }], { reason: '週五開獎測試' });
|
| 1485 |
+
assert.equal(lb.load().classes['test101'].lotteryCycles.lotto_pilot_20261120.status, 'settled');
|
| 1486 |
+
assert.equal(Object.values(lb.load().gifts['stu_a'] || {}).some(g => g.lotteryCycleId === 'lotto_pilot_20261120' && g.bp === 6), true);
|
| 1487 |
+
await assert.rejects(
|
| 1488 |
+
() => lb.settleLotteryDraw('test101', 'lotto_pilot_20261120', drawRes, [], {}),
|
| 1489 |
+
/已結算|settled/
|
| 1490 |
+
);
|
| 1491 |
+
} finally {
|
| 1492 |
+
globalThis.localStorage = origLS;
|
| 1493 |
+
}
|
| 1494 |
+
}
|
| 1495 |
+
ok('樂透存檔 Schema、HWM 守衛、同構交易與週四→週五雙模式延展檢驗 100% 通過');
|
| 1496 |
+
|
| 1497 |
console.log(`\n🎉 全部 ${passedChecks} 大項工程防呆檢驗 100% 通過!可安全部署上線。`);
|