idle / js /db.js
Lashtw's picture
fix(assets): clean up cutout background & internal holes for era2 b3 and b10 (20261129_v1)
e58357c
Raw History Blame Contribute Delete
105 kB
// ============================================================= // 資料層:同一組 API,兩種後端 // 1. FirebaseBackend:正式使用(Auth + Firestore) // 2. LocalBackend :firebaseConfig 未填時的本機示範模式(localStorage) // ============================================================= import { firebaseConfig, STUDENT_EMAIL_DOMAIN, PIN_SUFFIX } from './firebase-config.js?v=20261129_v1'; import { WEEKLY_SCHEDULE, BAZAAR_CONFIG } from './config.js?v=20261129_v1'; import { trafficTracker } from './traffic-tracker.js?v=20261129_v1'; import { normalizeWorldBossState } from './world-boss-schedule.js?v=20261129_v1'; import { LOTTERY_ROUND_SIZE, scoreLotteryAnswer } from './lottery-core.js?v=20261129_v1'; import { grantTally } from './engine.js?v=20261129_v1'; import { todayStr } from './util.js?v=20261129_v1'; const WEEK_TARGET_MAP = Object.fromEntries(WEEKLY_SCHEDULE.map(w => [w.id, w.target])); function clampWeekCap(weekId, val) { const num = Math.max(0, Number(val) || 0); const cap = WEEK_TARGET_MAP[weekId]; return (typeof cap === 'number' && cap > 0) ? Math.min(num, cap) : num; } // 讀取班級資料時,依世界 Boss 當期排程正規化 worldBoss(饕餮→窮奇自動換期、預告→封印倒數) function withScheduledBoss(cls) { if (!cls || typeof cls !== 'object') return cls; const wb = normalizeWorldBossState(cls.worldBoss); return (wb && wb !== cls.worldBoss) ? { ...cls, worldBoss: wb } : cls; } // 世界 Boss 寫入傷害前的防線:封印倒數期間一律拒絕(防止直連 boss.html 提前偷打) function assertBossAttackable(wb, now = Date.now()) { if (wb?.phaseMode === 'scheduled' && Number(wb.openAt) > now) { throw new DBError('世界 Boss 尚在封印倒數中,破印時間到才能出征!'); } } /** * 純函數:世界 Boss 單場傷害與每日討伐次數原子結算(共用 Firestore Transaction 與 LocalBackend) * - 雙邊對齊每日上限(3 + 當日 extraBossOrdersDate === today 額外次數) * - 移除累計 attacksCount 跨週誤推,避免換期/跨日後錯鎖每日次數 * - 伺服器端單場上限校正(窮奇 50 HP / 饕餮 25 HP),防禦異常高傷或前端篡改 * - 若進房前 Boss 已被同袍先步擊破 (wasDefeated),回傳 orderConsumed: false 且不扣討伐令 */ export function settleBossDamageRecord(wbInput, student, roundDmg, splitDmg = null, sData = null, today = todayStr()) { const wb = { ...(wbInput || defaultBossState()) }; assertBossAttackable(wb); if (!wb.damages) wb.damages = {}; const isYinYang = wb.bossId === 'qiongqi' || !!splitDmg || typeof wb.yangHp === 'number' || typeof wb.yinHp === 'number'; const maxRoundDmg = isYinYang ? 50 : 25; let maxHp = wb.maxHp || 500; const yangMaxHp = wb.yangMaxHp || 1200; const yinMaxHp = wb.yinMaxHp || 800; let wasDefeated = false; let oldHp = typeof wb.curHp === 'number' ? wb.curHp : maxHp; let oldYangHp = yangMaxHp; let oldYinHp = yinMaxHp; if (isYinYang) { maxHp = yangMaxHp + yinMaxHp; oldYangHp = typeof wb.yangHp === 'number' ? Math.max(0, wb.yangHp) : yangMaxHp; oldYinHp = typeof wb.yinHp === 'number' ? Math.max(0, wb.yinHp) : yinMaxHp; oldHp = oldYangHp + oldYinHp; wasDefeated = !!wb.defeated || (oldYangHp <= 0 && oldYinHp <= 0); } else { wasDefeated = !!wb.defeated || oldHp <= 0; } const prevRec = wb.damages[student.uid]; const sBoss = sData?.game?.boss || {}; const sUsedToday = (sBoss.date === today) ? Math.max(0, Number(sBoss.used) || 0) : 0; // 若在寫入交易瞬間 Boss 已被同袍先一步封印:不寫入廢傷、不消耗玩家今日討伐令 if (wasDefeated) { const curDailyUsed = (prevRec?.dailyUsed && typeof prevRec.dailyUsed[today] === 'number') ? Math.max(0, Number(prevRec.dailyUsed[today]) || 0) : sUsedToday; return { orderConsumed: false, alreadyDefeated: true, updatedWb: wb, mergedStuBoss: null, result: { curHp: isYinYang ? 0 : Math.max(0, Number(oldHp) || 0), maxHp, yangHp: isYinYang ? 0 : undefined, yangMaxHp: isYinYang ? yangMaxHp : undefined, yinHp: isYinYang ? 0 : undefined, yinMaxHp: isYinYang ? yinMaxHp : undefined, effYangDmg: 0, effYinDmg: 0, defeated: true, isKiller: false, killer: wb.killer || null, effectiveDmg: 0, myTotalDmg: Number(prevRec?.dmg) || 0, orderConsumed: false, alreadyDefeated: true, dailyUsedToday: curDailyUsed, bossState: mergeBossObj(sBoss, student?.game?.boss || null) } }; } // 先檢查今日出征次數上限(絕不退回累計 attacksCount) const extraOrders = Math.max( 0, (student?.game?.extraBossOrdersDate === today ? Math.floor(Number(student?.game?.extraBossOrders) || 0) : 0), (sData?.game?.extraBossOrdersDate === today ? Math.floor(Number(sData?.game?.extraBossOrders) || 0) : 0) ); const maxAllowedToday = 3 + extraOrders; let prevDailyUsed = 0; if (prevRec?.dailyUsed && typeof prevRec.dailyUsed[today] === 'number') { prevDailyUsed = Math.max(0, Number(prevRec.dailyUsed[today]) || 0); } else if (prevRec?.lastDate === today && typeof prevRec.todayCount === 'number') { prevDailyUsed = Math.max(0, Number(prevRec.todayCount) || 0); } prevDailyUsed = Math.max(prevDailyUsed, sUsedToday); if (prevDailyUsed >= maxAllowedToday) { throw new DBError(`今日出征討伐次數已達上限(每日 ${maxAllowedToday} 次),無法重複計入傷害!`); } let effectiveDmg = 0; let newHp = 0; let justDefeated = false; let newYangHp = undefined; let newYinHp = undefined; let effYangDmg = 0; let effYinDmg = 0; if (isYinYang) { const rawYang = splitDmg ? Math.max(0, Math.floor(Number(splitDmg.yangDmg) || 0)) : Math.max(0, Math.floor(Number(roundDmg) || 0)); const rawYin = splitDmg ? Math.max(0, Math.floor(Number(splitDmg.yinDmg) || 0)) : 0; const capYang = Math.min(rawYang, maxRoundDmg); const capYin = Math.min(rawYin, Math.max(0, maxRoundDmg - capYang)); // 雙生同命:單邊歸零後進入「已鎮壓鎖定」,多出的傷害直接溢出,不自動轉移至另一邊 effYangDmg = Math.min(capYang, oldYangHp); effYinDmg = Math.min(capYin, oldYinHp); newYangHp = Math.max(0, oldYangHp - effYangDmg); newYinHp = Math.max(0, oldYinHp - effYinDmg); effectiveDmg = effYangDmg + effYinDmg; newHp = newYangHp + newYinHp; justDefeated = newYangHp <= 0 && newYinHp <= 0; } else { const capRound = Math.min(Math.max(0, Math.floor(Number(roundDmg) || 0)), maxRoundDmg); effectiveDmg = Math.min(capRound, oldHp); newHp = Math.max(0, oldHp - effectiveDmg); justDefeated = newHp <= 0; } let killer = wb.killer || null; if (justDefeated) { killer = { uid: student.uid, name: student.name || `座號${student.seat}`, seat: student.seat || '', at: Date.now() }; } const dRec = { name: student.name || prevRec?.name || `座號${student.seat}`, seat: student.seat || prevRec?.seat || '', dmg: (Number(prevRec?.dmg) || 0) + effectiveDmg, yangDmg: Number(prevRec?.yangDmg) || 0, yinDmg: Number(prevRec?.yinDmg) || 0, attacksCount: (Number(prevRec?.attacksCount) || 0) + 1, ...(prevRec?.dailyUsed ? { dailyUsed: { ...prevRec.dailyUsed } } : {}), ...(Array.isArray(prevRec?.rounds) ? { rounds: [...prevRec.rounds] } : {}) }; if (isYinYang) { dRec.yangDmg += effYangDmg; dRec.yinDmg += effYinDmg; } const newDailyUsed = prevDailyUsed + 1; dRec.lastDate = today; dRec.todayCount = newDailyUsed; dRec.dailyUsed = { ...(dRec.dailyUsed || {}), [today]: newDailyUsed }; dRec.rounds = Array.isArray(dRec.rounds) ? dRec.rounds : []; const roundEntry = { at: Date.now(), date: today, dmg: effectiveDmg }; if (isYinYang) { roundEntry.yangDmg = effYangDmg; roundEntry.yinDmg = effYinDmg; } dRec.rounds.push(roundEntry); dRec.lastAt = Date.now(); const updatedWb = { ...wb, bossId: wb.bossId || (isYinYang ? 'qiongqi' : 'taotie'), name: wb.name || (isYinYang ? '上古・窮奇' : '上古・饕餮'), maxHp, curHp: newHp, defeated: justDefeated, defeatedAt: justDefeated ? (wb.defeatedAt || Date.now()) : null, killer, damages: { ...wb.damages, [student.uid]: dRec } }; if (isYinYang) { updatedWb.yangMaxHp = yangMaxHp; updatedWb.yinMaxHp = yinMaxHp; updatedWb.yangHp = newYangHp; updatedWb.yinHp = newYinHp; } const mergedStuBoss = mergeBossObj(sBoss, { ...(student?.game?.boss || {}), date: today, used: newDailyUsed, totalDmg: dRec.dmg }); return { orderConsumed: true, alreadyDefeated: false, updatedWb, mergedStuBoss, result: { curHp: newHp, maxHp, yangHp: newYangHp, yangMaxHp: isYinYang ? yangMaxHp : undefined, yinHp: newYinHp, yinMaxHp: isYinYang ? yinMaxHp : undefined, effYangDmg, effYinDmg, defeated: updatedWb.defeated, isKiller: (killer?.uid === student.uid && justDefeated), killer, effectiveDmg, myTotalDmg: dRec.dmg, orderConsumed: true, alreadyDefeated: false, dailyUsedToday: newDailyUsed, bossState: mergedStuBoss } }; } // 世界 Boss 討伐令單調高水位守衛(跨母子視窗 localStorage + 記憶體雙重防回退) const BOSS_HWM_MEM = {}; const BOSS_HWM_PREFIX = 'idle_boss_hwm_'; export function mergeBossObj(a, b) { if (!a && !b) return null; if (!a) return { ...b, claimed: { ...(b.claimed || {}) } }; if (!b) return { ...a, claimed: { ...(a.claimed || {}) } }; const dateA = String(a.date || ''); const dateB = String(b.date || ''); const claimed = { ...(a.claimed || {}), ...(b.claimed || {}) }; const totalDmg = Math.max(Number(a.totalDmg) || 0, Number(b.totalDmg) || 0); if (dateA === dateB) { return { ...a, ...b, date: dateA, used: Math.max(Number(a.used) || 0, Number(b.used) || 0), totalDmg, claimed }; } const newer = dateB > dateA ? b : a; return { ...a, ...b, date: newer.date, used: Math.max(0, Number(newer.used) || 0), totalDmg, claimed }; } export function readBossHighWaterMark(uid) { if (!uid) return null; const mem = BOSS_HWM_MEM[uid] || null; let loc = null; try { if (typeof localStorage !== 'undefined') { const raw = localStorage.getItem(BOSS_HWM_PREFIX + uid); if (raw) loc = JSON.parse(raw); } } catch (e) { } return mergeBossObj(mem, loc); } export function recordBossHighWaterMark(uid, bossObj) { if (!uid || !bossObj || typeof bossObj !== 'object' || !bossObj.date) return; const cur = readBossHighWaterMark(uid); const merged = mergeBossObj(cur, bossObj); if (!merged) return; BOSS_HWM_MEM[uid] = merged; try { if (typeof localStorage !== 'undefined') { localStorage.setItem(BOSS_HWM_PREFIX + uid, JSON.stringify(merged)); } } catch (e) { } } export function applyBossHighWaterMarkToGame(uid, game) { if (!uid || !game || typeof game !== 'object') return game; const hwm = readBossHighWaterMark(uid); const today = todayStr(); const extraOrders = (game?.extraBossOrdersDate === today) ? Math.max(0, Number(game?.extraBossOrders) || 0) : 0; const maxAllowed = 3 + extraOrders; const curUsed = (game?.boss?.date === today) ? Math.max(0, Number(game?.boss?.used) || 0) : 0; // 🛡️ 防污染校準:若本地 hwm.used 異常 > maxAllowed 且 game.boss 今日正常(<= maxAllowed),清理被歷史 bug 污染的本地快取 if (hwm && hwm.date === today && Number(hwm.used) > maxAllowed && curUsed <= maxAllowed) { hwm.used = curUsed; try { if (typeof localStorage !== 'undefined') { localStorage.setItem(BOSS_HWM_PREFIX + uid, JSON.stringify(hwm)); } } catch (e) { } } const merged = mergeBossObj(game.boss, hwm); if (merged) { game.boss = merged; recordBossHighWaterMark(uid, merged); } return game; } // ============================================================= // 錯題樂透交易純函數與 HWM 防覆寫守衛(雙後端同構) // ============================================================= const LOTTERY_HWM_PREFIX = 'idle_lottery_hwm_'; const LOTTERY_HWM_MEM = Object.create(null); function mergeLotteryCycles(a = {}, b = {}) { const out = {}; const keys = new Set([...Object.keys(a || {}), ...Object.keys(b || {})]); for (const cid of keys) { const ca = a?.[cid] || {}; const cb = b?.[cid] || {}; const reg = Math.max(Math.max(0, Number(ca.regularBalls) || 0), Math.max(0, Number(cb.regularBalls) || 0)); const gold = Math.max(Math.max(0, Number(ca.goldenBalls) || 0), Math.max(0, Number(cb.goldenBalls) || 0)); const dailyUsed = {}; for (const d of new Set([...Object.keys(ca.dailyUsed || {}), ...Object.keys(cb.dailyUsed || {})])) { dailyUsed[d] = Math.max(Number(ca.dailyUsed?.[d]) || 0, Number(cb.dailyUsed?.[d]) || 0); } const seenQuestionKeysByDay = {}; for (const d of new Set([...Object.keys(ca.seenQuestionKeysByDay || {}), ...Object.keys(cb.seenQuestionKeysByDay || {})])) { seenQuestionKeysByDay[d] = Array.from(new Set([...(ca.seenQuestionKeysByDay?.[d] || []), ...(cb.seenQuestionKeysByDay?.[d] || [])])); } out[cid] = { regularBalls: reg, goldenBalls: gold, weight: Math.max(reg + gold * 2, Number(ca.weight) || 0, Number(cb.weight) || 0), dailyUsed, seenQuestionKeysByDay, claimed: Boolean(ca.claimed || cb.claimed), lastRoundAt: Math.max(Number(ca.lastRoundAt) || 0, Number(cb.lastRoundAt) || 0), }; } return out; } function readLotteryHighWaterMark(uid) { let lsData = null; try { if (typeof localStorage !== 'undefined') { const raw = localStorage.getItem(LOTTERY_HWM_PREFIX + uid); if (raw) lsData = JSON.parse(raw); } } catch (e) { } return mergeLotteryCycles(LOTTERY_HWM_MEM[uid]?.cycles, lsData?.cycles); } export function recordLotteryHighWaterMark(uid, lotteryObj) { if (!uid || !lotteryObj || typeof lotteryObj !== 'object') return; const mergedCycles = mergeLotteryCycles(readLotteryHighWaterMark(uid), lotteryObj.cycles); LOTTERY_HWM_MEM[uid] = { cycles: mergedCycles }; try { if (typeof localStorage !== 'undefined') { localStorage.setItem(LOTTERY_HWM_PREFIX + uid, JSON.stringify({ cycles: mergedCycles })); } } catch (e) { } } export function applyLotteryHighWaterMarkToGame(uid, game) { if (!uid || !game || typeof game !== 'object') return game; const hwmCycles = readLotteryHighWaterMark(uid); const curCycles = game?.lottery?.cycles || {}; const merged = mergeLotteryCycles(curCycles, hwmCycles); if (Object.keys(merged).length > 0) { game.lottery = { cycles: merged }; recordLotteryHighWaterMark(uid, game.lottery); } return game; } export function settleLotteryRoundRecord(classData, studentData, studentMeta, cycleId, payload = {}) { const uid = studentMeta?.uid || studentData?.uid; if (!uid || !cycleId) throw new DBError('缺少學生帳號或樂透期別參數'); const cycle = classData?.lotteryCycles?.[cycleId]; if (!cycle) throw new DBError(`找不到該期錯題樂透 (${cycleId})`); if (cycle.status === 'locked') throw new DBError('本期樂透箱已封箱準備開獎,無法再投入新球!'); if (cycle.status !== 'open') throw new DBError(`本期錯題樂透目前已關閉 (${cycle.status})`); const today = String(payload.today || todayStr()); const now = Number(payload.now) || Date.now(); const openTs = Number(cycle.openAt); if (Number.isFinite(openTs) && openTs > 0 && now < openTs) { throw new DBError('本期錯題樂透尚未到開放時間,請於開放後再來投球!'); } if (cycle.endAt !== null && cycle.endAt !== undefined) { const endTs = Number(cycle.endAt); if (Number.isFinite(endTs) && endTs > 0 && now > endTs) { throw new DBError('本期錯題樂透已超過投球截止時間!'); } } const maxDailyRounds = Math.max(1, Number(payload.maxDailyRounds ?? cycle.maxDailyRounds ?? 2)); const roundSize = Math.max(1, Number(payload.roundSize ?? LOTTERY_ROUND_SIZE)); const stuGame = (studentData?.game && typeof studentData.game === 'object') ? studentData.game : {}; const stuLottery = (stuGame.lottery && typeof stuGame.lottery === 'object') ? stuGame.lottery : { cycles: {} }; const stuCycle = stuLottery.cycles?.[cycleId] || {}; const clsEntry = cycle.entries?.[uid] || {}; const prevUsedToday = Math.max( Number(stuCycle.dailyUsed?.[today]) || 0, Number(clsEntry.dailyUsed?.[today]) || 0 ); if (prevUsedToday >= maxDailyRounds) { throw new DBError(`今日已達錯題樂透投球次數上限 (${maxDailyRounds} 輪)!`); } const seenSet = new Set([ ...(Array.isArray(stuCycle.seenQuestionKeysByDay?.[today]) ? stuCycle.seenQuestionKeysByDay[today] : []), ...(Array.isArray(clsEntry.seenTodayKeys) && clsEntry.seenTodayDate === today ? clsEntry.seenTodayKeys : []), ]); let addedReg = 0; let addedGold = 0; const failedKeysInRound = new Set(); let retriedCorrectCount = 0; const outcomes = Array.isArray(payload.roundOutcomes) ? payload.roundOutcomes : []; for (const outItem of outcomes) { const qKeyStr = outItem?.qKey ? String(outItem.qKey) : ''; const isCorrect = !!outItem?.isCorrect; if (!isCorrect) { if (qKeyStr) failedKeysInRound.add(qKeyStr); continue; } const isAlreadySeen = qKeyStr ? seenSet.has(qKeyStr) : false; const isRetried = Boolean(outItem?.isRetried) || (qKeyStr ? failedKeysInRound.has(qKeyStr) : false); if (isRetried && !isAlreadySeen) { retriedCorrectCount += 1; } const sc = scoreLotteryAnswer({ q: { _qKey: qKeyStr }, isCorrect: true, curRevCount: Number(outItem?.curRevCount) || 0, questionIndex: Number(outItem?.questionIndex) || 0, roundSize, seenKeysSet: seenSet, isRetried, retriedCorrectIndex: isRetried ? retriedCorrectCount : 0, isCrit: Boolean(outItem?.isCrit), }); addedReg += sc.awardedRegular; addedGold += sc.awardedGold; if (qKeyStr) { seenSet.add(qKeyStr); } } const prevReg = Math.max(Number(stuCycle.regularBalls) || 0, Number(clsEntry.regularBalls) || 0); const prevGold = Math.max(Number(stuCycle.goldenBalls) || 0, Number(clsEntry.goldenBalls) || 0); const regularBalls = prevReg + addedReg; const goldenBalls = prevGold + addedGold; const weight = regularBalls + goldenBalls * 2; const roundsToday = prevUsedToday + 1; const roundsPlayed = Math.max(Number(clsEntry.roundsPlayed) || 0, 0) + 1; const seenArr = Array.from(seenSet); const nextDailyUsed = { ...(stuCycle.dailyUsed || {}), ...(clsEntry.dailyUsed || {}), [today]: roundsToday }; const nextStuSeenByDay = { ...(stuCycle.seenQuestionKeysByDay || {}), [today]: seenArr }; const nextClsEntry = { uid, seat: String(studentMeta?.seat ?? studentData?.seat ?? clsEntry.seat ?? ''), name: String(studentMeta?.name ?? studentData?.name ?? clsEntry.name ?? '勇士'), regularBalls, goldenBalls, weight, roundsPlayed, dailyUsed: nextDailyUsed, seenTodayDate: today, seenTodayKeys: seenArr, lastAt: now, }; const nextCycle = { ...cycle, entries: { ...(cycle.entries || {}), [uid]: nextClsEntry }, updatedAt: now, }; const nextStuCycle = { regularBalls, goldenBalls, weight, dailyUsed: nextDailyUsed, seenQuestionKeysByDay: nextStuSeenByDay, claimed: Boolean(stuCycle.claimed), lastRoundAt: now, }; const nextStudentLottery = { cycles: { ...(stuLottery.cycles || {}), [cycleId]: nextStuCycle }, }; return { nextCycle, nextStudentLottery, result: { ok: true, cycleId, regularBalls, goldenBalls, weight, roundsToday, roundsPlayed, addedReg, addedGold, }, }; } // ============================================================= // 西域萬國大市集交易純函數與 HWM 防覆寫守衛(雙後端同構) // ============================================================= const BAZAAR_HWM_PREFIX = 'idle_bazaar_hwm_'; const BAZAAR_HWM_MEM = Object.create(null); function mergeBazaarBoolMap(a = {}, b = {}) { const out = {}; for (const src of [a, b]) { if (!src || typeof src !== 'object') continue; for (const [k, v] of Object.entries(src)) { if (v) out[String(k)] = true; } } return out; } function mergeBazaarCycles(a = {}, b = {}) { const out = {}; const keys = new Set([...Object.keys(a || {}), ...Object.keys(b || {})]); for (const cid of keys) { const ca = (a?.[cid] && typeof a[cid] === 'object') ? a[cid] : {}; const cb = (b?.[cid] && typeof b[cid] === 'object') ? b[cid] : {}; const ua = Math.max(0, Number(ca.updatedAt) || 0); const ub = Math.max(0, Number(cb.updatedAt) || 0); const newer = ub > ua ? cb : (ua > ub ? ca : (cb.lastNpc ? cb : ca)); const dailyMerged = mergeDailyDateCount(ca.dailyLitDate, ca.dailyLitCount, cb.dailyLitDate, cb.dailyLitCount); out[cid] = { litWords: mergeBazaarBoolMap(ca.litWords, cb.litWords), claimedLines: mergeBazaarBoolMap(ca.claimedLines, cb.claimedLines), firstBloodWon: mergeBazaarBoolMap(ca.firstBloodWon, cb.firstBloodWon), dailyLitDate: dailyMerged.date || '', dailyLitCount: dailyMerged.count, clearedMistakes: Math.max(Math.max(0, Number(ca.clearedMistakes) || 0), Math.max(0, Number(cb.clearedMistakes) || 0)), encounters: Math.max(Math.max(0, Number(ca.encounters) || 0), Math.max(0, Number(cb.encounters) || 0)), lastNpc: (typeof newer.lastNpc === 'string' && newer.lastNpc) ? newer.lastNpc : null, lastNpcStreak: Math.max(0, Math.floor(Number(newer.lastNpcStreak) || 0)), updatedAt: Math.max(ua, ub), }; } return out; } function readBazaarHighWaterMark(uid) { let lsData = null; try { if (typeof localStorage !== 'undefined') { const raw = localStorage.getItem(BAZAAR_HWM_PREFIX + uid); if (raw) lsData = JSON.parse(raw); } } catch (e) { } return mergeBazaarCycles(BAZAAR_HWM_MEM[uid]?.cycles, lsData?.cycles); } export function recordBazaarHighWaterMark(uid, bazaarObj) { if (!uid || !bazaarObj || typeof bazaarObj !== 'object') return; const mergedCycles = mergeBazaarCycles(readBazaarHighWaterMark(uid), bazaarObj.cycles); BAZAAR_HWM_MEM[uid] = { cycles: mergedCycles }; try { if (typeof localStorage !== 'undefined') { localStorage.setItem(BAZAAR_HWM_PREFIX + uid, JSON.stringify({ cycles: mergedCycles })); } } catch (e) { } } export function applyBazaarHighWaterMarkToGame(uid, game, { recordBack = true } = {}) { if (!uid || !game || typeof game !== 'object') return game; const hwmCycles = readBazaarHighWaterMark(uid); const curCycles = game?.bazaar?.cycles || {}; const merged = mergeBazaarCycles(curCycles, hwmCycles); if (Object.keys(merged).length > 0) { game.bazaar = { cycles: merged }; if (recordBack) recordBazaarHighWaterMark(uid, game.bazaar); } return game; } function mergeBazaarMistakesMap(remoteMistakes = {}, localMistakes = {}) { const out = {}; const keys = new Set([...Object.keys(remoteMistakes || {}), ...Object.keys(localMistakes || {})]); for (const k of keys) { const rm = remoteMistakes?.[k]; const lm = localMistakes?.[k]; if (!rm) { out[k] = JSON.parse(JSON.stringify(lm)); continue; } if (!lm) { out[k] = JSON.parse(JSON.stringify(rm)); continue; } const rw = Math.max(0, Number(rm.wrongCount) || 0); const lw = Math.max(0, Number(lm.wrongCount) || 0); if (lw > rw) { out[k] = JSON.parse(JSON.stringify(lm)); } else if (rw > lw) { out[k] = JSON.parse(JSON.stringify(rm)); } else { const rr = Math.max(0, Number(rm.reviewCorrectCount) || 0); const lr = Math.max(0, Number(lm.reviewCorrectCount) || 0); out[k] = JSON.parse(JSON.stringify(lr >= rr ? lm : rm)); out[k].mastered = Boolean(rm.mastered || lm.mastered); } } return out; } function mergeMerchantBuyRecord(ra, rb) { if (ra === undefined || ra === null) return rb && typeof rb === 'object' ? { ...rb } : rb; if (rb === undefined || rb === null) return ra && typeof ra === 'object' ? { ...ra } : ra; if (typeof ra !== 'object' && typeof rb !== 'object') { return Math.max(Number(ra) || 0, Number(rb) || 0); } const normObj = (x) => (typeof x === 'object' ? { count: Math.max(0, Number(x.count) || 0), week: Math.max(0, Number(x.week) || 0), total: Math.max(0, Number(x.total) || 0) } : { count: Math.max(0, Number(x) || 0), week: 0, total: Math.max(0, Number(x) || 0) }); const oa = normObj(ra); const ob = normObj(rb); const week = Math.max(oa.week, ob.week); const count = oa.week === ob.week ? Math.max(oa.count, ob.count) : (ob.week > oa.week ? ob.count : oa.count); return { count, week, total: Math.max(oa.total, ob.total), }; } function mergeBazaarMerchantObj(rm = {}, lm = {}) { const rDate = String(rm?.day || rm?.dayDate || ''); const lDate = String(lm?.day || lm?.dayDate || ''); const sameDay = rDate === lDate; const base = lDate >= rDate ? { ...rm, ...lm } : { ...lm, ...rm }; if (lDate || rDate) { base.day = lDate >= rDate ? lDate : rDate; } delete base.dayDate; base.gold = Math.max(Number(rm?.gold) || 0, Number(lm?.gold) || 0); base.exp = Math.max(Number(rm?.exp) || 0, Number(lm?.exp) || 0); base.coupons = Math.max(Number(rm?.coupons) || 0, Number(lm?.coupons) || 0); const buys = {}; for (const k of new Set([...Object.keys(rm?.buys || {}), ...Object.keys(lm?.buys || {})])) { buys[k] = mergeMerchantBuyRecord(rm?.buys?.[k], lm?.buys?.[k]); } base.buys = buys; const stats = {}; for (const k of new Set([...Object.keys(rm?.stats || {}), ...Object.keys(lm?.stats || {})])) { const sa = rm?.stats?.[k]; const sb = lm?.stats?.[k]; if (!sa) { stats[k] = { ...sb }; continue; } if (!sb) { stats[k] = { ...sa }; continue; } stats[k] = { ...sa, ...sb, c: Math.max(Number(sa.c) || 0, Number(sb.c) || 0), w: Math.max(Number(sa.w) || 0, Number(sb.w) || 0), lastAt: Math.max(Number(sa.lastAt) || 0, Number(sb.lastAt) || 0), }; } base.stats = stats; if (sameDay) { base.dayCount = Math.max(Number(rm?.dayCount) || 0, Number(lm?.dayCount) || 0); base.dayCoins = Math.max(Number(rm?.dayCoins) || 0, Number(lm?.dayCoins) || 0); base.dayRewWordIds = Array.from(new Set([...(Array.isArray(rm?.dayRewWordIds) ? rm.dayRewWordIds : []), ...(Array.isArray(lm?.dayRewWordIds) ? lm.dayRewWordIds : [])])); base.marketUnlocked = Boolean(rm?.marketUnlocked || lm?.marketUnlocked); base.weekendRewarded = Boolean(rm?.weekendRewarded || lm?.weekendRewarded); const mults = [rm?.todayMult, lm?.todayMult].filter(v => v !== null && v !== undefined && Number.isFinite(Number(v))).map(Number); if (mults.length > 0) { const bestMult = Math.min(...mults); base.todayMult = bestMult; if (lm?.todayMult === bestMult && lm?.todayDiscount !== undefined) { base.todayDiscount = lm.todayDiscount; base.todayDiscountLabel = lm.todayDiscountLabel ?? base.todayDiscountLabel; } else if (rm?.todayMult === bestMult && rm?.todayDiscount !== undefined) { base.todayDiscount = rm.todayDiscount; base.todayDiscountLabel = rm.todayDiscountLabel ?? base.todayDiscountLabel; } } } return base; } function mergeBuildingsAndPeaks(remote = {}, local = {}) { const buildings = {}; const peakBuildings = {}; const ids = new Set([ ...Object.keys(remote.buildings || {}), ...Object.keys(local.buildings || {}), ...Object.keys(remote.peakBuildings || {}), ...Object.keys(local.peakBuildings || {}), ]); for (const id of ids) { const rb = remote.buildings?.[id] || {}; const lb = local.buildings?.[id] || {}; const rp = remote.peakBuildings?.[id] || {}; const lp = local.peakBuildings?.[id] || {}; const rEra2 = !!(rb.era2 || rp.era2); const lEra2 = !!(lb.era2 || lp.era2); const lv = Math.max(Number(rb.lv) || 0, Number(lb.lv) || 0); const maxLv = Math.max(Number(rp.maxLv) || 0, Number(lp.maxLv) || 0, lv); let era2 = false; let star = 0; let maxStar = 0; if (rEra2 && !lEra2) { // 遠端已飛升第二紀元:保留遠端第二紀元專屬星級軌道,嚴禁混入本地第一紀元 5 星 era2 = true; star = Math.max(0, Number(rb.star) || 0); maxStar = Math.max(Number(rp.maxStar) || 0, star); } else if (lEra2 && !rEra2) { // 本地已飛升第二紀元:保留本地第二紀元專屬星級軌道,嚴禁混入遠端第一紀元 5 星 era2 = true; star = Math.max(0, Number(lb.star) || 0); maxStar = Math.max(Number(lp.maxStar) || 0, star); } else { era2 = rEra2 || lEra2; star = Math.max(Number(rb.star) || 0, Number(lb.star) || 0); maxStar = Math.max(Number(rp.maxStar) || 0, Number(lp.maxStar) || 0, star); } buildings[id] = { lv, star, era2 }; peakBuildings[id] = { maxLv, maxStar, ...(era2 ? { era2: true } : {}) }; } return { buildings, peakBuildings }; } function mergeDailyDateCount(rDate, rCount, lDate, lCount) { const rd = String(rDate || ''); const ld = String(lDate || ''); if (rd === ld) { return { date: rd || null, count: Math.max(Number(rCount) || 0, Number(lCount) || 0) }; } return ld > rd ? { date: ld || null, count: Math.max(0, Number(lCount) || 0) } : { date: rd || null, count: Math.max(0, Number(rCount) || 0) }; } function mergeBazaarLocalAndRemoteGame(uid, remoteGame, localGame) { const remote = (remoteGame && typeof remoteGame === 'object') ? JSON.parse(JSON.stringify(remoteGame)) : {}; if (!localGame || typeof localGame !== 'object') { const bossHwm = readBossHighWaterMark(uid); const mergedBoss = mergeBossObj(remote.boss, bossHwm); if (mergedBoss) remote.boss = mergedBoss; const lotHwm = readLotteryHighWaterMark(uid); const mergedLot = mergeLotteryCycles(remote.lottery?.cycles, lotHwm); if (Object.keys(mergedLot).length > 0) remote.lottery = { cycles: mergedLot }; applyBazaarHighWaterMarkToGame(uid, remote, { recordBack: false }); return remote; } const local = JSON.parse(JSON.stringify(localGame)); const merged = { ...local, ...remote }; const { buildings, peakBuildings } = mergeBuildingsAndPeaks(remote, local); if (Object.keys(buildings).length > 0 || remote.buildings || local.buildings) merged.buildings = buildings; if (Object.keys(peakBuildings).length > 0 || remote.peakBuildings || local.peakBuildings) merged.peakBuildings = peakBuildings; merged.peakProd = Math.max(Number(remote.peakProd) || 0, Number(local.peakProd) || 0); for (const k of ['coins', 'totalEarned', 'blueprints', 'donated', 'donatedCoins', 'clicks']) { merged[k] = Math.max(Number(remote[k]) || 0, Number(local[k]) || 0); } const weeklyDonated = {}; for (const k of new Set([...Object.keys(remote.weeklyDonated || {}), ...Object.keys(local.weeklyDonated || {})])) { weeklyDonated[k] = Math.max(Number(remote.weeklyDonated?.[k]) || 0, Number(local.weeklyDonated?.[k]) || 0); } merged.weeklyDonated = weeklyDonated; merged.era2Unlocked = Boolean(remote.era2Unlocked || local.era2Unlocked); merged.seenEra2Intro = Boolean(remote.seenEra2Intro || local.seenEra2Intro); merged.hasDragonFrame = Boolean(remote.hasDragonFrame || local.hasDragonFrame); const seenStages = []; for (const s of [...(Array.isArray(remote.seenClassStages) ? remote.seenClassStages : []), ...(Array.isArray(local.seenClassStages) ? local.seenClassStages : [])]) { if (s !== undefined && s !== null && !seenStages.includes(s)) seenStages.push(s); } merged.seenClassStages = seenStages; const merchantBuffs = {}; for (const k of new Set([...Object.keys(remote.merchantBuffs || {}), ...Object.keys(local.merchantBuffs || {})])) { const rv = remote.merchantBuffs?.[k]; const lv = local.merchantBuffs?.[k]; if (typeof rv === 'boolean' || typeof lv === 'boolean') { merchantBuffs[k] = Boolean(rv || lv); } else if (typeof rv === 'number' || typeof lv === 'number') { merchantBuffs[k] = Math.max(Number(rv) || 0, Number(lv) || 0); } else { merchantBuffs[k] = lv ?? rv; } } merged.merchantBuffs = merchantBuffs; const mergedBoss = mergeBossObj(mergeBossObj(remote.boss, local.boss), readBossHighWaterMark(uid)); if (mergedBoss) merged.boss = mergedBoss; const mergedLot = mergeLotteryCycles(mergeLotteryCycles(remote.lottery?.cycles, local.lottery?.cycles), readLotteryHighWaterMark(uid)); if (Object.keys(mergedLot).length > 0 || remote.lottery || local.lottery) { merged.lottery = { cycles: mergedLot }; } const tianji = mergeDailyDateCount(remote.tianjiDate, remote.tianjiPlayed, local.tianjiDate, local.tianjiPlayed); if (tianji.date !== null || remote.tianjiDate || local.tianjiDate) { merged.tianjiDate = tianji.date; merged.tianjiPlayed = tianji.count; } const extraOrders = mergeDailyDateCount(remote.extraBossOrdersDate, remote.extraBossOrders, local.extraBossOrdersDate, local.extraBossOrders); if (extraOrders.date !== null || remote.extraBossOrdersDate || local.extraBossOrdersDate) { merged.extraBossOrdersDate = extraOrders.date; merged.extraBossOrders = extraOrders.count; } const workClicks = mergeDailyDateCount(remote.workClicksDate, remote.workClicksToday, local.workClicksDate, local.workClicksToday); if (workClicks.date !== null || remote.workClicksDate || local.workClicksDate) { merged.workClicksDate = workClicks.date; merged.workClicksToday = workClicks.count; } merged.merchant = mergeBazaarMerchantObj(remote.merchant || {}, local.merchant || {}); merged.mistakes = mergeBazaarMistakesMap(remote.mistakes || {}, local.mistakes || {}); const titles = []; for (const t of [...(Array.isArray(remote.titles) ? remote.titles : []), ...(Array.isArray(local.titles) ? local.titles : [])]) { if (t && !titles.includes(t)) titles.push(t); } merged.titles = titles; merged.curTitle = local.curTitle || remote.curTitle || null; if (remote.items || local.items) { merged.items = { ...(remote.items || {}), ...(local.items || {}), peek: Math.max(Number(remote.items?.peek) || 0, Number(local.items?.peek) || 0), eliminate: Math.max(Number(remote.items?.eliminate) || 0, Number(local.items?.eliminate) || 0), }; } if (remote.stats || local.stats) { merged.stats = { ...(remote.stats || {}), ...(local.stats || {}), perfectCount: Math.max(Number(remote.stats?.perfectCount) || 0, Number(local.stats?.perfectCount) || 0), }; } merged.lastTick = Math.max(Number(remote.lastTick) || 0, Number(local.lastTick) || 0); merged.bazaar = { cycles: mergeBazaarCycles(remote.bazaar?.cycles, local.bazaar?.cycles) }; applyBazaarHighWaterMarkToGame(uid, merged, { recordBack: false }); return merged; } export function settleBazaarClassRecord(classData = {}, studentData = {}, studentMeta = {}, cycleId, payload = {}) { if (!cycleId) throw new DBError('缺少西域大市集期別參數'); const nowMs = (payload.nowMs !== undefined && payload.nowMs !== null && Number.isFinite(Number(payload.nowMs))) ? Number(payload.nowMs) : Date.now(); const openAtMs = Number(payload.openAtMs) || 0; if (!payload.isForcedOpen && openAtMs && nowMs < openAtMs) { throw new Error('西域大市集尚未開市(週一 07:00 準時開張)'); } const effRole = studentMeta?.role ?? studentData?.role; const effSeat = studentMeta?.seat ?? studentData?.seat; const effUid = studentMeta?.uid || studentData?.uid; const effName = studentMeta?.name ?? studentData?.name; const isExcluded = effRole === 'teacher' || String(effSeat) === '20'; if (!isExcluded && !effUid) throw new DBError('缺少學生帳號參數'); const nextBazaarCycles = JSON.parse(JSON.stringify(classData?.bazaarCycles || {})); const curClsCycle = (nextBazaarCycles[cycleId] && typeof nextBazaarCycles[cycleId] === 'object') ? nextBazaarCycles[cycleId] : {}; nextBazaarCycles[cycleId] = { ...curClsCycle, firstMilestones: (curClsCycle.firstMilestones && typeof curClsCycle.firstMilestones === 'object') ? curClsCycle.firstMilestones : {}, entries: (curClsCycle.entries && typeof curClsCycle.entries === 'object') ? curClsCycle.entries : {}, }; const nextStudentGame = JSON.parse(JSON.stringify(studentData?.game || {})); if (!nextStudentGame.bazaar || typeof nextStudentGame.bazaar !== 'object') nextStudentGame.bazaar = { cycles: {} }; if (!nextStudentGame.bazaar.cycles || typeof nextStudentGame.bazaar.cycles !== 'object') nextStudentGame.bazaar.cycles = {}; const curStuCycle = nextStudentGame.bazaar.cycles[cycleId]; if (!curStuCycle || typeof curStuCycle !== 'object') { nextStudentGame.bazaar.cycles[cycleId] = { litWords: {}, claimedLines: {}, firstBloodWon: {}, dailyLitDate: '', dailyLitCount: 0, clearedMistakes: 0, encounters: 0, lastNpc: null, lastNpcStreak: 0, updatedAt: 0, }; } else { if (!curStuCycle.litWords || typeof curStuCycle.litWords !== 'object') curStuCycle.litWords = {}; if (!curStuCycle.claimedLines || typeof curStuCycle.claimedLines !== 'object') curStuCycle.claimedLines = {}; if (!curStuCycle.firstBloodWon || typeof curStuCycle.firstBloodWon !== 'object') curStuCycle.firstBloodWon = {}; if (typeof curStuCycle.dailyLitDate !== 'string') curStuCycle.dailyLitDate = ''; curStuCycle.dailyLitCount = Math.max(0, Math.floor(Number(curStuCycle.dailyLitCount) || 0)); } const stuCycle = nextStudentGame.bazaar.cycles[cycleId]; if (isExcluded) { return { nextBazaarCycles, nextStudentGame, newlyWonMilestones: [], tallyAwarded: 0, excludedFromClassBoard: true, firstMilestones: nextBazaarCycles[cycleId].firstMilestones, leaderboardEntries: nextBazaarCycles[cycleId].entries, }; } const totalLines = Math.max(0, Number(payload.totalLines) || 0); const newlyWonMilestones = []; let tallyAwarded = 0; for (const m of (BAZAAR_CONFIG.firstBloodLines || [])) { const mk = String(m); if (totalLines >= m && !nextBazaarCycles[cycleId].firstMilestones[mk]) { nextBazaarCycles[cycleId].firstMilestones[mk] = { uid: effUid, seat: effSeat ?? null, name: effName || '無名小將', at: nowMs, }; if (!stuCycle.firstBloodWon[mk]) { stuCycle.firstBloodWon[mk] = true; grantTally(nextStudentGame, 1); newlyWonMilestones.push(m); tallyAwarded += 1; } } } stuCycle.updatedAt = Math.max(Number(stuCycle.updatedAt) || 0, nowMs); const prev = nextBazaarCycles[cycleId].entries[effUid]; nextBazaarCycles[cycleId].entries[effUid] = { uid: effUid, seat: effSeat ?? prev?.seat ?? null, name: effName || prev?.name || '', lines: Math.max(Number(prev?.lines) || 0, totalLines), litCount: Math.max(Number(prev?.litCount) || 0, Number(payload.litCount) || 0), clearedMistakes: Math.max(Number(prev?.clearedMistakes) || 0, Number(payload.clearedMistakes) || 0), title: payload.title || prev?.title || '', updatedAt: Math.max(Number(prev?.updatedAt) || 0, nowMs), }; return { nextBazaarCycles, nextStudentGame, newlyWonMilestones, tallyAwarded, excludedFromClassBoard: false, firstMilestones: nextBazaarCycles[cycleId].firstMilestones, leaderboardEntries: nextBazaarCycles[cycleId].entries, }; } const FB_VER = '10.12.2'; const FB = `https://www.gstatic.com/firebasejs/${FB_VER}`; export function normCode(code) { return String(code || '').trim().toLowerCase().replace(/[^a-z0-9]/g, ''); } export function normSeat(seat) { return String(parseInt(seat, 10) || '').trim(); } export function studentEmail(code, seat) { return `${normCode(code)}-${normSeat(seat)}@${STUDENT_EMAIL_DOMAIN}`; } export function pinToPassword(pin) { return String(pin || '').trim() + PIN_SUFFIX; } function friendlyError(e) { const c = e?.code || ''; if (c.includes('invalid-credential') || c.includes('wrong-password') || c.includes('user-not-found') || c.includes('invalid-login')) return '帳號或密碼錯誤'; if (c.includes('too-many-requests')) return '嘗試太多次,請稍後再試'; if (c.includes('network')) return '網路連線失敗'; if (c.includes('permission-denied')) return '權限不足(請確認 Firestore 規則與教師權限)'; if (c.includes('email-already-in-use')) return '這個座號帳號已存在'; return e?.message || String(e); } export class DBError extends Error { } export function defaultBossState() { return { bossId: 'taotie', name: '上古・饕餮', maxHp: 500, curHp: 500, defeated: false, defeatedAt: null, killer: null, damages: {} }; } // ------------------------------------------------------------- // Firebase // ------------------------------------------------------------- class FirebaseBackend { constructor() { this.mode = 'firebase'; this.user = null; } async init() { const [appMod, authMod, fsMod] = await Promise.all([ import(`${FB}/firebase-app.js`), import(`${FB}/firebase-auth.js`), import(`${FB}/firebase-firestore.js`), ]); this.A = authMod; this.F = fsMod; this.appMod = appMod; this.app = appMod.initializeApp(firebaseConfig); this.auth = authMod.getAuth(this.app); this.db = fsMod.getFirestore(this.app); await authMod.setPersistence(this.auth, authMod.browserLocalPersistence); } // 第二個 app 實例:老師建立/管理學生帳號時,不會把自己登出 async secondaryAuth() { if (!this._sec) { const app2 = this.appMod.initializeApp(firebaseConfig, 'secondary'); const a2 = this.A.getAuth(app2); await this.A.setPersistence(a2, this.A.inMemoryPersistence); this._sec = a2; } return this._sec; } d(...path) { return this.F.doc(this.db, ...path); } c(...path) { return this.F.collection(this.db, ...path); } onAuth(cb) { return this.A.onAuthStateChanged(this.auth, async (u) => { if (!u) { this.user = null; cb(null); return; } try { let role = 'unknown'; const adm = await this.F.getDoc(this.d('admins', u.uid)).catch(() => null); trafficTracker.recordOp({ type: 'read', source: 'authCheck', count: 1, estimatedBytes: 1024, note: '管理員權限驗證' }); if (adm && adm.exists()) role = 'teacher'; else { const st = await this.F.getDoc(this.d('students', u.uid)).catch(() => null); trafficTracker.recordOp({ type: 'read', source: 'authCheck', count: 1, estimatedBytes: 2048, note: '學生帳號驗證' }); if (st && st.exists()) { role = 'student'; this._stCache = { uid: u.uid, data: st.data() }; // 給 getStudent 用,省一次讀取 } } this.user = { uid: u.uid, email: u.email, role }; cb(this.user); } catch (e) { console.error('[auth] role check failed', e); this.user = { uid: u.uid, email: u.email, role: 'unknown' }; cb(this.user); } }); } async studentLogin(code, seat, pin) { try { await this.A.signInWithEmailAndPassword(this.auth, studentEmail(code, seat), pinToPassword(pin)); } catch (e) { throw new DBError(friendlyError(e)); } } async teacherLogin(email, pw) { try { await this.A.signInWithEmailAndPassword(this.auth, email.trim(), pw); } catch (e) { throw new DBError(friendlyError(e)); } } async logout() { await this.A.signOut(this.auth); } // ----- 學生 ----- async getStudent(uid) { if (this._stCache && this._stCache.uid === uid) { const data = this._stCache.data; this._stCache = null; // 只用一次,之後一律讀最新資料 if (data?.game) { applyBossHighWaterMarkToGame(uid, data.game); applyLotteryHighWaterMarkToGame(uid, data.game); applyBazaarHighWaterMarkToGame(uid, data.game); } return { ...data, uid }; } const s = await this.F.getDoc(this.d('students', uid)); trafficTracker.recordOp({ type: 'read', source: 'getStudent', count: 1, estimatedBytes: 4096, note: `讀取學生資料 (${uid.slice(0, 6)}...)` }); if (!s.exists()) return null; const data = s.data(); if (data?.game) { applyBossHighWaterMarkToGame(uid, data.game); applyLotteryHighWaterMarkToGame(uid, data.game); applyBazaarHighWaterMarkToGame(uid, data.game); } return { ...data, uid }; } async saveGame(uid, { game, progress, stats }) { if (game) { applyBossHighWaterMarkToGame(uid, game); applyLotteryHighWaterMarkToGame(uid, game); applyBazaarHighWaterMarkToGame(uid, game); } await this.F.updateDoc(this.d('students', uid), { game, progress, stats, lastSeen: Date.now() }); trafficTracker.recordOp({ type: 'write', source: 'saveGame', count: 1, estimatedBytes: 6144, note: `學生存檔更新 (${uid.slice(0, 6)}...)` }); } async addAttempt(att) { await this.F.addDoc(this.c('attempts'), { ...att, at: Date.now() }); trafficTracker.recordOp({ type: 'write', source: 'addAttempt', count: 1, estimatedBytes: 1024, note: `測驗紀錄寫入 (${att.seat}號 ${att.score}分)` }); } async listMyGifts(uid) { const q = this.F.query(this.c('students', uid, 'gifts'), this.F.where('claimed', '==', false)); const snap = await this.F.getDocs(q); trafficTracker.recordOp({ type: 'read', source: 'listMyGifts', count: Math.max(1, snap.docs.length), estimatedBytes: 1024 * Math.max(1, snap.docs.length), note: '讀取未領取禮物' }); return snap.docs.map((x) => ({ id: x.id, ...x.data() })).sort((a, b) => a.at - b.at); } async claimGift(uid, gid) { const ref = this.d('students', uid, 'gifts', gid); return this.F.runTransaction(this.db, async (tx) => { const s = await tx.get(ref); if (!s.exists() || s.data().claimed) throw new DBError('禮物已領取或不存在'); tx.update(ref, { claimed: true, claimedAt: Date.now() }); trafficTracker.recordOp({ type: 'write', source: 'claimGift', count: 1, estimatedBytes: 1536, note: '領取禮物入庫' }); return { id: gid, ...s.data() }; }); } async getClass(code) { const s = await this.F.getDoc(this.d('classes', normCode(code))); trafficTracker.recordOp({ type: 'read', source: 'getClass', count: 1, estimatedBytes: 2048, note: `讀取班級目標 (${code})` }); return s.exists() ? withScheduledBoss({ code: s.id, ...s.data() }) : null; } async donate(code, amount) { await this.F.updateDoc(this.d('classes', normCode(code)), { donated: this.F.increment(amount), updatedAt: Date.now(), }); trafficTracker.recordOp({ type: 'write', source: 'donate', count: 1, estimatedBytes: 1024, note: `軍餉捐獻 (+${amount})` }); } async updateClassFirstConquer(code, townId, record) { const ref = this.d('classes', normCode(code)); await this.F.setDoc(ref, { firstConquers: { [townId]: record } }, { merge: true }); trafficTracker.recordOp({ type: 'write', source: 'updateClassFirstConquer', count: 1, estimatedBytes: 512, note: `首破城池紀錄 (${townId})` }); } // ----- 世界 Boss (World Boss) ----- async getWorldBoss(classCode) { const cRef = this.d('classes', normCode(classCode)); const s = await this.F.getDoc(cRef); trafficTracker.recordOp({ type: 'read', source: 'getWorldBoss', count: 1, estimatedBytes: 2048, note: `讀取世界Boss狀態 (${classCode})` }); if (!s.exists()) return defaultBossState(); const data = s.data(); return normalizeWorldBossState(data.worldBoss || defaultBossState()); } onWorldBoss(classCode, callback) { const cRef = this.d('classes', normCode(classCode)); return this.F.onSnapshot(cRef, (snap) => { if (!snap.exists()) { callback(defaultBossState()); return; } const data = snap.data(); callback(normalizeWorldBossState(data.worldBoss || defaultBossState())); }, (err) => { console.warn('[onWorldBoss] 監聽失敗,切換至單次讀取備援', err); this.getWorldBoss(classCode).then((wb) => callback(wb)).catch(() => { }); }); } async recordBossDamage(classCode, student, roundDmg, splitDmg = null) { classCode = normCode(classCode); const cRef = this.d('classes', classCode); const sRef = student?.uid ? this.d('students', student.uid) : null; const res = await this.F.runTransaction(this.db, async (tx) => { const [snap, sSnap] = await Promise.all([ tx.get(cRef), sRef ? tx.get(sRef) : Promise.resolve(null) ]); if (!snap.exists()) throw new DBError('班級資料不存在'); const cData = snap.data(); // 依當期排程正規化:首位出征者的傷害寫入即完成「饕餮→窮奇」換期落地 const wb = normalizeWorldBossState(cData.worldBoss || defaultBossState()) || defaultBossState(); const sData = (sSnap && sSnap.exists()) ? sSnap.data() : null; const settled = settleBossDamageRecord(wb, student, roundDmg, splitDmg, sData, todayStr()); if (settled.alreadyDefeated) { return settled.result; } tx.update(cRef, { worldBoss: settled.updatedWb }); if (sRef && sSnap && sSnap.exists()) { tx.update(sRef, { 'game.boss': settled.mergedStuBoss, lastSeen: Date.now() }); } return settled.result; }); if (student?.uid && res?.bossState && res?.orderConsumed !== false) { recordBossHighWaterMark(student.uid, res.bossState); } if (res?.orderConsumed !== false) { trafficTracker.recordOp({ type: 'write', source: 'recordBossDamage', count: 2, estimatedBytes: 3072, note: `討伐Boss傷害與次數原子同步 (+${res?.effectiveDmg ?? roundDmg})` }); } return res; } async resetClassBoss(classCode, maxHp = 500, bossId = null) { classCode = normCode(classCode); const cRef = this.d('classes', classCode); const isQiongqi = bossId === 'qiongqi' || maxHp === 2000; const newBoss = { bossId: isQiongqi ? 'qiongqi' : 'taotie', name: isQiongqi ? '上古・窮奇' : '上古・饕餮', maxHp: isQiongqi ? 2000 : maxHp, curHp: isQiongqi ? 2000 : maxHp, ...(isQiongqi ? { yangMaxHp: 1200, yangHp: 1200, yinMaxHp: 800, yinHp: 800 } : {}), defeated: false, defeatedAt: null, killer: null, damages: {}, resetAt: Date.now() }; await this.F.updateDoc(cRef, { worldBoss: newBoss }); trafficTracker.recordOp({ type: 'write', source: 'resetClassBoss', count: 1, estimatedBytes: 1024, note: `重設世界Boss (${classCode})` }); return newBoss; } // ----- 教師 ----- async listClasses() { const snap = await this.F.getDocs(this.c('classes')); trafficTracker.recordOp({ type: 'read', source: 'listClasses', count: Math.max(1, snap.docs.length), estimatedBytes: 2048 * Math.max(1, snap.docs.length), note: '讀取所有班級清單' }); return snap.docs.map((x) => withScheduledBoss({ code: x.id, ...x.data() })); } async createClass(code, name) { code = normCode(code); if (!code) throw new DBError('班級代碼只能用英文小寫與數字'); const ref = this.d('classes', code); const ex = await this.F.getDoc(ref); trafficTracker.recordOp({ type: 'read', source: 'createClassCheck', count: 1, estimatedBytes: 1024, note: '檢查班級代碼重複' }); if (ex.exists()) throw new DBError('班級代碼已存在'); await this.F.setDoc(ref, { name: name || code, donated: 0, openAll: false, openRanges: [], constructionPause: { routineEnabled: true }, createdAt: Date.now() }); trafficTracker.recordOp({ type: 'write', source: 'createClass', count: 1, estimatedBytes: 2048, note: `建立新班級 (${code})` }); return code; } async updateClass(code, data) { await this.F.updateDoc(this.d('classes', normCode(code)), data); trafficTracker.recordOp({ type: 'write', source: 'updateClass', count: 1, estimatedBytes: 2048, note: `更新班級設定 (${code})` }); } async donate(code, amount) { code = normCode(code); const ref = this.d('classes', code); await this.F.updateDoc(ref, { donated: this.F.increment(amount) }); trafficTracker.recordOp({ type: 'write', source: 'donate', count: 1, estimatedBytes: 1024, note: `班級軍餉捐獻 (${code})` }); } async aidDonate(classCode, donor, targetUid, targetGame, realDonate, weekId, aidAmt, aidDetails = null) { classCode = normCode(classCode); const ref = this.d('classes', classCode); const classUpdate = { donated: this.F.increment(realDonate), [`peerAid.${targetUid}.lastAidAt`]: Date.now(), [`peerAid.${targetUid}.donorName`]: donor.name || `座號${donor.seat}`, [`peerAid.${targetUid}.donorSeat`]: donor.seat || '' }; // 將被代捐同袍該週累積總額直接對齊並夾限於當週上限,避免多人併發 increment 導致超過上限 const targetWd = targetGame?.weeklyDonated || {}; if (aidDetails && typeof aidDetails === 'object') { for (const [w, amt] of Object.entries(aidDetails)) { if (amt > 0) { const finalVal = clampWeekCap(w, targetWd[w] !== undefined ? targetWd[w] : amt); classUpdate[`peerAid.${targetUid}.weeks.${w}`] = finalVal; } } } else if (weekId && aidAmt > 0) { const finalVal = clampWeekCap(weekId, targetWd[weekId] !== undefined ? targetWd[weekId] : aidAmt); classUpdate[`peerAid.${targetUid}.weeks.${weekId}`] = finalVal; } await this.F.updateDoc(ref, classUpdate); try { const studentDocRef = this.d('students', targetUid); if (aidDetails && typeof aidDetails === 'object' && Object.keys(aidDetails).length > 0) { const studentUpdates = {}; for (const [w, amt] of Object.entries(aidDetails)) { if (amt > 0) { const finalVal = clampWeekCap(w, targetWd[w] !== undefined ? targetWd[w] : amt); studentUpdates[`game.weeklyDonated.${w}`] = finalVal; } } await this.F.updateDoc(studentDocRef, studentUpdates); } else if (weekId && aidAmt > 0) { const finalVal = clampWeekCap(weekId, targetWd[weekId] !== undefined ? targetWd[weekId] : aidAmt); await this.F.updateDoc(studentDocRef, { [`game.weeklyDonated.${weekId}`]: finalVal }); } else { await this.updateStudent(targetUid, { game: targetGame }); } } catch (e) { console.warn('嘗試直接更新被代捐同袍文檔受規則限制,已同步至班級協同池', e); } trafficTracker.recordOp({ type: 'write', source: 'aidDonate', count: 2, estimatedBytes: 3072, note: `同袍代捐軍餉 (${donor.seat || ''}號 -> ${targetUid.slice(0, 6)})` }); } async deleteClass(code) { await this.F.deleteDoc(this.d('classes', normCode(code))); trafficTracker.recordOp({ type: 'delete', source: 'deleteClass', count: 1, estimatedBytes: 1024, note: `刪除班級 (${code})` }); } async listStudents(code) { try { const q = this.F.query(this.c('students'), this.F.where('classCode', '==', normCode(code))); const snap = await this.F.getDocs(q); trafficTracker.recordOp({ type: 'read', source: 'listStudents', count: Math.max(1, snap.docs.length), estimatedBytes: 4096 * Math.max(1, snap.docs.length), note: `讀取班級學生清單 (${code}, ${snap.docs.length}生)` }); return snap.docs.map((x) => ({ ...x.data(), uid: x.id })).sort((a, b) => Number(a.seat) - Number(b.seat)); } catch (e) { throw new DBError(friendlyError(e)); } } async createStudent({ classCode, seat, name, pin, bankId }) { classCode = normCode(classCode); seat = normSeat(seat); if (!classCode || !seat) throw new DBError('班級代碼或座號錯誤'); if (String(pin || '').trim().length < 1) throw new DBError('請設定密碼'); const sec = await this.secondaryAuth(); const email = studentEmail(classCode, seat); let uid; try { const cred = await this.A.createUserWithEmailAndPassword(sec, email, pinToPassword(pin)); uid = cred.user.uid; } catch (e) { if ((e.code || '').includes('email-already-in-use')) { try { const cred = await this.A.signInWithEmailAndPassword(sec, email, pinToPassword(pin)); uid = cred.user.uid; } catch (e2) { throw new DBError(`座號 ${seat} 帳號已存在且密碼不同,請先在名單中刪除該生,或到 Firebase Console 刪除帳號`); } } else throw new DBError(friendlyError(e)); } finally { await this.A.signOut(sec).catch(() => { }); } await this.F.setDoc(this.d('students', uid), { classCode, seat, name: name || `座號${seat}`, pin: String(pin).trim(), bankId: bankId || '', createdAt: Date.now(), lastSeen: null, game: null, progress: {}, stats: {}, }, { merge: true }); trafficTracker.recordOp({ type: 'write', source: 'createStudent', count: 1, estimatedBytes: 4096, note: `建立學生資料 (${seat}號)` }); return uid; } async updateStudent(uid, data) { await this.F.updateDoc(this.d('students', uid), data); trafficTracker.recordOp({ type: 'write', source: 'updateStudent', count: 1, estimatedBytes: 2048, note: `更新學生資料 (${uid.slice(0, 6)}...)` }); } async resetPin(student, newPin) { const sec = await this.secondaryAuth(); try { const cred = await this.A.signInWithEmailAndPassword(sec, studentEmail(student.classCode, student.seat), pinToPassword(student.pin)); await this.A.updatePassword(cred.user, pinToPassword(newPin)); } catch (e) { throw new DBError('重設失敗:' + friendlyError(e)); } finally { await this.A.signOut(sec).catch(() => { }); } await this.updateStudent(student.uid, { pin: String(newPin).trim() }); } async deleteStudent(student) { const sec = await this.secondaryAuth(); try { const cred = await this.A.signInWithEmailAndPassword(sec, studentEmail(student.classCode, student.seat), pinToPassword(student.pin)); await this.A.deleteUser(cred.user); } catch (e) { console.warn('[deleteStudent] auth 帳號刪除失敗,只刪除資料', e); } finally { await this.A.signOut(sec).catch(() => { }); } await this.F.deleteDoc(this.d('students', student.uid)); trafficTracker.recordOp({ type: 'delete', source: 'deleteStudent', count: 1, estimatedBytes: 1024, note: `刪除學生 (${student.seat}號)` }); } async sendGift(students, gift) { const batch = this.F.writeBatch(this.db); const at = Date.now(); students.forEach((s) => { const ref = this.F.doc(this.c('students', s.uid, 'gifts')); batch.set(ref, { ...gift, claimed: false, at }); }); const logRef = this.F.doc(this.c('giftLog')); batch.set(logRef, { ...gift, classCode: students[0]?.classCode || '', to: students.map((s) => `${s.seat} ${s.name}`), at }); await batch.commit(); trafficTracker.recordOp({ type: 'write', source: 'sendGift', count: students.length + 1, estimatedBytes: 1024 * (students.length + 1), note: `批量發送禮物至 ${students.length} 生` }); } // 個人化批量發信:items = [{ student, gift, giftId? }],每位學生收到各自內容的信件(世界 Boss / 錯題樂透結算用) async sendGiftsPersonalized(items, logMeta = {}) { const at = Date.now(); const CHUNK = 400; for (let i = 0; i < items.length; i += CHUNK) { const batch = this.F.writeBatch(this.db); items.slice(i, i + CHUNK).forEach(({ student, gift, giftId }) => { const ref = giftId ? this.d('students', student.uid, 'gifts', String(giftId)) : this.F.doc(this.c('students', student.uid, 'gifts')); batch.set(ref, { ...gift, claimed: false, at }); }); await batch.commit(); } const logId = logMeta.logId ? String(logMeta.logId) : null; const logRef = logId ? this.d('giftLog', logId) : this.F.doc(this.c('giftLog')); await this.F.setDoc(logRef, { ...logMeta, reason: logMeta.reason || '個人化批量發信', classCode: normCode(items[0]?.student?.classCode || logMeta.classCode || ''), to: items.map(({ student }) => `${student.seat} ${student.name}`), at }); trafficTracker.recordOp({ type: 'write', source: 'sendGiftsPersonalized', count: items.length + 1, estimatedBytes: 1024 * (items.length + 1), note: `個人化批量發信 ${items.length} 生` }); } // 教師直接收回/扣減學生現有資源 (兵符、糧草、錦囊道具) async reclaimResources(students, { blueprints = 0, coins = 0, peek = 0, eliminate = 0, reason = '' }) { const at = Date.now(); const results = []; for (const s of students) { const docRef = this.d('students', s.uid); const snap = await this.F.getDoc(docRef); if (!snap.exists()) continue; const data = snap.data(); const g = data.game || {}; const curBp = Number(g.blueprints) || 0; const curCoins = Number(g.coins) || 0; const curPeek = Number(g.items?.peek) || 0; const curEliminate = Number(g.items?.eliminate) || 0; const newBp = Math.max(0, curBp - (Number(blueprints) || 0)); const newCoins = Math.max(0, curCoins - (Number(coins) || 0)); const newPeek = Math.max(0, curPeek - (Number(peek) || 0)); const newEliminate = Math.max(0, curEliminate - (Number(eliminate) || 0)); g.blueprints = newBp; g.coins = newCoins; g.items = g.items || {}; g.items.peek = newPeek; g.items.eliminate = newEliminate; await this.F.updateDoc(docRef, { 'game.blueprints': newBp, 'game.coins': newCoins, 'game.items': g.items, lastAdminOp: { type: 'reclaim', at, reason, deducted: { blueprints: curBp - newBp, coins: curCoins - newCoins, peek: curPeek - newPeek, eliminate: curEliminate - newEliminate } } }); results.push({ uid: s.uid, name: s.name, seat: s.seat, before: { bp: curBp, coins: curCoins, peek: curPeek, eliminate: curEliminate }, after: { bp: newBp, coins: newCoins, peek: newPeek, eliminate: newEliminate } }); } if (results.length > 0) { const logRef = this.F.doc(this.c('giftLog')); await this.F.setDoc(logRef, { type: 'reclaim', isReclaim: true, reason: reason || '教師手動收回/扣減資源', blueprints: Number(blueprints) || 0, coins: Number(coins) || 0, peek: Number(peek) || 0, eliminate: Number(eliminate) || 0, classCode: students[0]?.classCode || '', to: students.map(s => `${s.seat} ${s.name}`), results, at }); trafficTracker.recordOp({ type: 'write', source: 'reclaimResources', count: results.length + 1, estimatedBytes: 2048 * (results.length + 1), note: `批量收回 ${results.length} 生資源` }); } return results; } // 只取最新 N 筆(每筆文件 = 1 次讀取)。需要複合索引 classCode(↑) + at(↓); // 第一次執行時 Console 會印出建立索引的連結,點一下即可。索引建好前暫時退回舊查詢。 async _latestByClass(col, code, n) { const F = this.F; try { const q = F.query(this.c(col), F.where('classCode', '==', normCode(code)), F.orderBy('at', 'desc'), F.limit(n)); const snap = await F.getDocs(q); trafficTracker.recordOp({ type: 'read', source: col, count: Math.max(1, snap.docs.length), estimatedBytes: 1024 * Math.max(1, snap.docs.length), note: `分頁查詢 ${col} (${snap.docs.length}筆)` }); return snap.docs.map((x) => ({ id: x.id, ...x.data() })); } catch (e) { if ((e?.code || '').includes('failed-precondition')) { console.error(`[db] ${col} 需要建立複合索引才能省讀取額度,請點下方連結建立:`, e.message); const snap = await F.getDocs(F.query(this.c(col), F.where('classCode', '==', normCode(code)))); trafficTracker.recordOp({ type: 'read', source: col, count: Math.max(1, snap.docs.length), estimatedBytes: 1024 * Math.max(1, snap.docs.length), note: `全量降級查詢 ${col} (${snap.docs.length}筆)` }); return snap.docs.map((x) => ({ id: x.id, ...x.data() })).sort((a, b) => b.at - a.at).slice(0, n); } throw e; } } async listGiftLog(code) { return this._latestByClass('giftLog', code, 100); } async listAttempts(code) { return this._latestByClass('attempts', code, 100); } async recordLotteryRound(classCode, studentMeta, cycleId, payload = {}) { const cCode = normCode(classCode); const uid = studentMeta?.uid; if (!cCode || !uid || !cycleId) throw new DBError('缺少樂透寫入必要參數'); const clsRef = this.d('classes', cCode); const stuRef = this.d('students', uid); const txRes = await this.F.runTransaction(this.db, async (tx) => { const [clsSnap, stuSnap] = await Promise.all([tx.get(clsRef), tx.get(stuRef)]); if (!clsSnap.exists()) throw new DBError('班級資料不存在'); const clsData = clsSnap.data() || {}; const stuData = stuSnap.exists() ? (stuSnap.data() || {}) : {}; const settled = settleLotteryRoundRecord(clsData, stuData, { ...studentMeta, uid }, cycleId, payload); tx.update(clsRef, { [`lotteryCycles.${cycleId}`]: settled.nextCycle, updatedAt: Date.now(), }); if (stuSnap.exists()) { const nextGame = { ...(stuData.game || {}), lottery: settled.nextStudentLottery }; tx.update(stuRef, { game: nextGame, lastSeen: Date.now() }); } return settled; }); recordLotteryHighWaterMark(uid, txRes.nextStudentLottery); trafficTracker.recordOp({ type: 'write', source: 'recordLotteryRound', count: 2, estimatedBytes: 4096, note: `錯題樂透投球原子入庫 (${cycleId})` }); return txRes.result; } async recordBazaarProgress(classCode, studentMeta, cycleId, payload = {}) { const cCode = normCode(classCode); const uid = studentMeta?.uid; if (!cCode || !uid || !cycleId) throw new DBError('缺少西域大市集寫入必要參數'); const clsRef = this.d('classes', cCode); const stuRef = this.d('students', uid); const txRes = await this.F.runTransaction(this.db, async (tx) => { const [clsSnap, stuSnap] = await Promise.all([tx.get(clsRef), tx.get(stuRef)]); if (!clsSnap.exists()) throw new DBError('班級資料不存在'); const clsData = clsSnap.data() || {}; const stuData = stuSnap.exists() ? (stuSnap.data() || {}) : {}; const mergedGame = mergeBazaarLocalAndRemoteGame(uid, stuData.game, payload.localGame); const settled = settleBazaarClassRecord(clsData, { ...stuData, game: mergedGame }, { ...studentMeta, uid }, cycleId, payload); const now = Date.now(); if (!settled.excludedFromClassBoard) { tx.set(clsRef, { bazaarCycles: settled.nextBazaarCycles, updatedAt: now, }, { merge: true }); } if (stuSnap.exists()) { tx.set(stuRef, { game: settled.nextStudentGame, lastSeen: now, updatedAt: now, }, { merge: true }); } return settled; }); recordBazaarHighWaterMark(uid, txRes.nextStudentGame?.bazaar); trafficTracker.recordOp({ type: 'write', source: 'recordBazaarProgress', count: txRes.excludedFromClassBoard ? 1 : 2, estimatedBytes: 4096, note: `西域大市集進度與首破原子入庫 (${cycleId})` }); return txRes; } async saveWeeklySpotlight(classCode, spotlight, cycleInitDoc = null) { const cCode = normCode(classCode); if (!cCode || !spotlight) throw new DBError('缺少主打活動設定參數'); const clsRef = this.d('classes', cCode); await this.F.runTransaction(this.db, async (tx) => { const snap = await tx.get(clsRef); const clsData = snap.exists() ? (snap.data() || {}) : {}; const patch = { weeklySpotlight: { ...spotlight, updatedAt: Date.now() }, updatedAt: Date.now() }; if (cycleInitDoc && cycleInitDoc.cycleId) { const existing = clsData.lotteryCycles?.[cycleInitDoc.cycleId]; patch[`lotteryCycles.${cycleInitDoc.cycleId}`] = existing ? { ...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() } : cycleInitDoc; } tx.update(clsRef, patch); }); trafficTracker.recordOp({ type: 'write', source: 'saveWeeklySpotlight', count: 1, estimatedBytes: 2048, note: `切換週期主打活動 (${spotlight.eventId})` }); } async setLotteryBoxStatus(classCode, cycleId, status) { const cCode = normCode(classCode); if (!cCode || !cycleId || !status) throw new DBError('缺少樂透封箱參數'); await this.F.updateDoc(this.d('classes', cCode), { [`lotteryCycles.${cycleId}.status`]: status, [`lotteryCycles.${cycleId}.updatedAt`]: Date.now(), ...(status === 'locked' ? { [`lotteryCycles.${cycleId}.lockedAt`]: Date.now() } : {}), }); trafficTracker.recordOp({ type: 'write', source: 'setLotteryBoxStatus', count: 1, estimatedBytes: 1024, note: `切換樂透箱狀態 → ${status}` }); } async extendLotteryPilotToFriday(classCode, oldCycleId = 'lotto_pilot_20261119', mode = 'keep', fridayEndAt) { const cCode = normCode(classCode); const endTs = Number(fridayEndAt) || Date.parse('2026-11-20T23:59:59+08:00'); const clsRef = this.d('classes', cCode); const res = await this.F.runTransaction(this.db, async (tx) => { const snap = await tx.get(clsRef); if (!snap.exists()) throw new DBError('班級資料不存在'); const clsData = snap.data() || {}; const oldCycle = clsData.lotteryCycles?.[oldCycleId]; if (!oldCycle) throw new DBError(`找不到期別 ${oldCycleId}`); const now = Date.now(); if (mode === 'void_and_restart') { const newCycleId = 'lotto_pilot_20261120'; const openTs = Math.min(now, Date.parse('2026-11-20T07:00:00+08:00')); const newCycle = { cycleId: newCycleId, title: '週五快閃重測(週四場次已作廢重開)', status: 'open', prizeMode: oldCycle.prizeMode || 'pilot', themeId: oldCycle.themeId || 'pilot_flash', questionMode: oldCycle.questionMode || 'mixed', maxDailyRounds: oldCycle.maxDailyRounds || 2, milestones: Array.isArray(oldCycle.milestones) ? [...oldCycle.milestones] : [40, 80, 120], openAt: openTs, endAt: endTs, entries: {}, drawResult: null, updatedAt: now, }; tx.update(clsRef, { [`lotteryCycles.${oldCycleId}.status`]: 'voided', [`lotteryCycles.${oldCycleId}.updatedAt`]: now, [`lotteryCycles.${newCycleId}`]: newCycle, weeklySpotlight: { ...(clsData.weeklySpotlight || {}), eventId: 'lottery', cycleId: newCycleId, openAt: openTs, endAt: endTs, allowDuringCaravan: true, updatedAt: now }, updatedAt: now, }); return { mode, cycleId: newCycleId, endAt: endTs }; } tx.update(clsRef, { [`lotteryCycles.${oldCycleId}.status`]: 'open', [`lotteryCycles.${oldCycleId}.endAt`]: endTs, [`lotteryCycles.${oldCycleId}.updatedAt`]: now, 'weeklySpotlight.endAt': endTs, 'weeklySpotlight.updatedAt': now, updatedAt: now, }); return { mode: 'keep', cycleId: oldCycleId, endAt: endTs }; }); trafficTracker.recordOp({ type: 'write', source: 'extendLotteryPilotToFriday', count: 1, estimatedBytes: 2048, note: `快閃延長至週五 (${res.mode})` }); return res; } async settleLotteryDraw(classCode, cycleId, drawResult, giftItems = [], logMeta = {}) { const cCode = normCode(classCode); if (!cCode || !cycleId) throw new DBError('缺少開獎結算參數'); const clsRef = this.d('classes', cCode); const now = Date.now(); const hasGifts = Array.isArray(giftItems) && giftItems.length > 0; await this.F.runTransaction(this.db, async (tx) => { const snap = await tx.get(clsRef); if (!snap.exists()) throw new DBError('班級資料不存在'); const cycle = snap.data()?.lotteryCycles?.[cycleId]; if (!cycle) throw new DBError(`找不到期別 ${cycleId}`); if (cycle.status === 'settled' && cycle.drawResult?.giftsDispatched !== false) { throw new DBError('此期錯題樂透已結算過(settled),禁止重複發信!'); } tx.update(clsRef, { [`lotteryCycles.${cycleId}.status`]: 'settled', [`lotteryCycles.${cycleId}.drawResult`]: { ...(drawResult || {}), settledAt: cycle.drawResult?.settledAt || now, giftsDispatched: !hasGifts, }, [`lotteryCycles.${cycleId}.updatedAt`]: now, updatedAt: now, }); }); if (hasGifts) { const taggedItems = giftItems.map(item => ({ ...item, giftId: item.giftId || `lottery_${cycleId}`, })); await this.sendGiftsPersonalized(taggedItems, { kind: 'lottery_settle', classCode: cCode, lotteryCycleId: cycleId, logId: `lottery_settle_${cCode}_${cycleId}`, reason: logMeta.reason || `🎰 錯題樂透開獎結算 (${cycleId})`, ...logMeta, }); await this.F.updateDoc(clsRef, { [`lotteryCycles.${cycleId}.drawResult.giftsDispatched`]: true, [`lotteryCycles.${cycleId}.drawResult.giftsDispatchedAt`]: Date.now(), [`lotteryCycles.${cycleId}.drawResult.giftsDispatchedCount`]: taggedItems.length, updatedAt: Date.now(), }); } trafficTracker.recordOp({ type: 'write', source: 'settleLotteryDraw', count: 1, estimatedBytes: 2048, note: `錯題樂透開獎封存 (${cycleId})` }); } async markLegacyBossCleared(classCode, ts = Date.now()) { const cCode = normCode(classCode); await this.F.updateDoc(this.d('classes', cCode), { legacyBossClearedAt: ts, 'worldBoss.hidden': true, 'worldBoss.phaseMode': 'closed', updatedAt: Date.now(), }); trafficTracker.recordOp({ type: 'write', source: 'markLegacyBossCleared', count: 1, estimatedBytes: 1024, note: '確認舊版窮奇全員領完並全面收起' }); } getTrafficStats() { return trafficTracker.getQuotaStatus(); } simulateTraffic(params) { return trafficTracker.simulateLoad(params); } resetTrafficStats() { trafficTracker.reset(); } } // ------------------------------------------------------------- // 本機示範模式(localStorage) // ------------------------------------------------------------- const LS_KEY = 'idle_demo_db_v1'; const SS_AUTH = 'idle_demo_auth'; class LocalBackend { constructor() { this.mode = 'local'; this.user = null; this.listeners = []; } async init() { const db = this.load(); if (!db.seeded || !db.classes?.demo?.lotteryCycles) { db.seeded = true; const now = Date.now(); const demoOpenAt = now - 3600 * 1000; const demoEndAt = now + 2 * 86400 * 1000; db.classes.demo = { ...(db.classes.demo || {}), name: '示範測試班', bank: 'wiring', donated: db.classes.demo?.donated || 0, openAll: true, openRanges: [], createdAt: db.classes.demo?.createdAt || now, weeklySpotlight: { weekKey: 'demo_pilot', eventId: 'lottery', cycleId: 'lotto_demo_pilot', subId: null, allowDuringCaravan: true, prizeMode: 'pilot', questionMode: 'mixed', openAt: demoOpenAt, endAt: demoEndAt, closedAt: null, updatedAt: now, }, lotteryCycles: { lotto_demo_pilot: { cycleId: 'lotto_demo_pilot', title: '本機體驗快閃樂透(Demo 模擬全班投球)', status: 'open', prizeMode: 'pilot', themeId: 'pilot_flash', questionMode: 'mixed', maxDailyRounds: 2, milestones: [40, 80, 120], openAt: demoOpenAt, endAt: demoEndAt, entries: { 'demo-2': { uid: 'demo-2', seat: '2', name: '張無忌', regularBalls: 9, goldenBalls: 2, weight: 13, roundsPlayed: 2, lastAt: now - 300000 }, 'demo-3': { uid: 'demo-3', seat: '3', name: '趙敏', regularBalls: 7, goldenBalls: 3, weight: 13, roundsPlayed: 2, lastAt: now - 250000 }, 'demo-4': { uid: 'demo-4', seat: '4', name: '黃蓉', regularBalls: 10, goldenBalls: 1, weight: 12, roundsPlayed: 2, lastAt: now - 200000 }, 'demo-5': { uid: 'demo-5', seat: '5', name: '郭靖', regularBalls: 6, goldenBalls: 2, weight: 10, roundsPlayed: 2, lastAt: now - 150000 }, 'demo-6': { uid: 'demo-6', seat: '6', name: '楊過', regularBalls: 6, goldenBalls: 0, weight: 6, roundsPlayed: 1, lastAt: now - 100000 }, }, drawResult: null, updatedAt: now, }, }, }; const uid = 'demo-1'; db.users[studentEmail('demo', 1)] = { uid, pw: pinToPassword('1234') }; const existingStu = db.students[uid]; const seedMistakes = { wiring_1: { id: 'wiring_1', bank: 'wiring', n: 1, q: '電工儀表上交直流兩用之符號為', o: ['<img src="data/banks/img/wiring/image001.gif" alt="圖">', '<img src="data/banks/img/wiring/image002.jpg" alt="圖">', '<img src="data/banks/img/wiring/image003.gif" alt="圖">', '<img src="data/banks/img/wiring/image004.gif" alt="圖">'], a: 'C', wrongCount: 1, reviewCorrectCount: 2, mastered: false, }, wiring_2: { id: 'wiring_2', bank: 'wiring', n: 2, q: '屋內配線設計圖無熔線開關之符號為', o: ['<img src="data/banks/img/wiring/image006.jpg" alt="圖">', '<img src="data/banks/img/wiring/image007.jpg" alt="圖">', '<img src="data/banks/img/wiring/image008.jpg" alt="圖">', '<img src="data/banks/img/wiring/image009.jpg" alt="圖">'], a: 'C', wrongCount: 2, reviewCorrectCount: 1, mastered: false, }, english_1: { id: 'english_1', bank: 'english', n: 1, q: '請問英文單字【person】(名) 的意思是?', o: ['人', '動物', '房子', '樹'], a: 'A', wrongCount: 1, reviewCorrectCount: 2, mastered: false, }, }; db.students[uid] = existingStu ? { ...existingStu, game: { ...(existingStu.game || {}), mistakes: { ...seedMistakes, ...(existingStu.game?.mistakes || {}) } } } : { classCode: 'demo', seat: '1', name: '示範學生', pin: '1234', bankId: 'wiring', role: 'student', createdAt: now, lastSeen: null, game: { mistakes: seedMistakes, buildings: {}, blueprints: 5, coins: 100, lottery: { cycles: {} } }, progress: { u1: { passed: true, best: 100 } }, stats: {}, }; const peers = [ { uid: 'demo-2', seat: '2', name: '張無忌' }, { uid: 'demo-3', seat: '3', name: '趙敏' }, { uid: 'demo-4', seat: '4', name: '黃蓉' }, { uid: 'demo-5', seat: '5', name: '郭靖' }, { uid: 'demo-6', seat: '6', name: '楊過' }, ]; for (const p of peers) { db.users[studentEmail('demo', p.seat)] = db.users[studentEmail('demo', p.seat)] || { uid: p.uid, pw: pinToPassword('1234') }; if (!db.students[p.uid]) { db.students[p.uid] = { classCode: 'demo', seat: p.seat, name: p.name, pin: '1234', bankId: 'wiring', role: 'student', createdAt: now, lastSeen: now, game: { mistakes: {}, buildings: {}, blueprints: 3, coins: 50, lottery: { cycles: {} } }, progress: { u1: { passed: true, best: 90 } }, stats: {}, }; } } this.save(db); } const curDemoDb = this.load(); const demoPilot = curDemoDb?.classes?.demo?.lotteryCycles?.lotto_demo_pilot; if (demoPilot && Array.isArray(demoPilot.milestones) && demoPilot.milestones.join(',') === '45,90,140') { demoPilot.milestones = [40, 80, 120]; this.save(curDemoDb); } const raw = sessionStorage.getItem(SS_AUTH); this.user = raw ? JSON.parse(raw) : null; } load() { try { const d = JSON.parse(localStorage.getItem(LS_KEY)); if (d && d.users) return d; } catch (e) { console.warn('[local] 讀取失敗,重建', e); } return { users: {}, admins: {}, classes: {}, students: {}, gifts: {}, attempts: [], giftLog: [], seeded: false }; } save(db) { localStorage.setItem(LS_KEY, JSON.stringify(db)); } uid() { return 'u' + Math.random().toString(36).slice(2, 10); } setUser(u) { this.user = u; if (u) sessionStorage.setItem(SS_AUTH, JSON.stringify(u)); else sessionStorage.removeItem(SS_AUTH); this.listeners.forEach((cb) => cb(u)); } onAuth(cb) { this.listeners.push(cb); setTimeout(() => cb(this.user), 0); return () => { this.listeners = this.listeners.filter((x) => x !== cb); }; } async studentLogin(code, seat, pin) { const db = this.load(); const u = db.users[studentEmail(code, seat)]; if (!u || u.pw !== pinToPassword(pin)) throw new DBError('帳號或密碼錯誤'); this.setUser({ uid: u.uid, email: studentEmail(code, seat), role: 'student' }); } async teacherLogin(email, pw) { // 示範模式:任何 email + 密碼 demo1234 都可以當老師 if (pw !== 'demo1234') throw new DBError('示範模式教師密碼為 demo1234'); const db = this.load(); const uid = 't-' + email.trim().toLowerCase(); db.admins[uid] = true; this.save(db); this.setUser({ uid, email, role: 'teacher' }); } async logout() { this.setUser(null); } async getStudent(uid) { const s = this.load().students[uid]; if (!s) return null; if (s.game) { applyBossHighWaterMarkToGame(uid, s.game); applyLotteryHighWaterMarkToGame(uid, s.game); applyBazaarHighWaterMarkToGame(uid, s.game); } return { uid, ...s }; } async saveGame(uid, { game, progress, stats }) { const db = this.load(); if (!db.students[uid]) throw new DBError('找不到學生資料'); if (game) { applyBossHighWaterMarkToGame(uid, game); applyLotteryHighWaterMarkToGame(uid, game); applyBazaarHighWaterMarkToGame(uid, game); } Object.assign(db.students[uid], { game, progress, stats, lastSeen: Date.now() }); this.save(db); } async addAttempt(att) { const db = this.load(); db.attempts.push({ id: this.uid(), ...att, at: Date.now() }); this.save(db); } async listMyGifts(uid) { const g = this.load().gifts[uid] || {}; return Object.entries(g).filter(([, v]) => !v.claimed).map(([id, v]) => ({ id, ...v })).sort((a, b) => a.at - b.at); } async claimGift(uid, gid) { const db = this.load(); const g = db.gifts[uid]?.[gid]; if (!g || g.claimed) throw new DBError('禮物已領取或不存在'); g.claimed = true; g.claimedAt = Date.now(); this.save(db); return { id: gid, ...g }; } async getClass(code) { const c = this.load().classes[normCode(code)]; return c ? withScheduledBoss({ code: normCode(code), ...c }) : null; } async donate(code, amount) { const db = this.load(); const c = db.classes[normCode(code)]; if (!c) throw new DBError('班級不存在'); c.donated = (c.donated || 0) + amount; c.updatedAt = Date.now(); this.save(db); } async updateClassFirstConquer(code, townId, record) { const db = this.load(); const c = db.classes[normCode(code)]; if (c) { c.firstConquers = c.firstConquers || {}; if (!c.firstConquers[townId]) { c.firstConquers[townId] = record; this.save(db); } } } // ----- 世界 Boss (World Boss) ----- async getWorldBoss(classCode) { const c = this.load().classes[normCode(classCode)]; return normalizeWorldBossState((c && c.worldBoss) ? c.worldBoss : defaultBossState()); } onWorldBoss(classCode, callback) { const check = () => { const c = this.load().classes[normCode(classCode)]; callback(normalizeWorldBossState((c && c.worldBoss) ? c.worldBoss : defaultBossState())); }; check(); const interval = setInterval(check, 1500); return () => clearInterval(interval); } async recordBossDamage(classCode, student, roundDmg, splitDmg = null) { const db = this.load(); const c = db.classes[normCode(classCode)]; if (!c) throw new DBError('班級不存在'); const wb = normalizeWorldBossState(c.worldBoss || defaultBossState()) || defaultBossState(); const sData = (student?.uid && db.students?.[student.uid]) ? db.students[student.uid] : null; const settled = settleBossDamageRecord(wb, student, roundDmg, splitDmg, sData, todayStr()); if (settled.alreadyDefeated) { return settled.result; } c.worldBoss = settled.updatedWb; if (sData && settled.mergedStuBoss) { sData.game = sData.game || {}; sData.game.boss = settled.mergedStuBoss; sData.lastSeen = Date.now(); } this.save(db); if (student?.uid && settled.result?.bossState && settled.result?.orderConsumed !== false) { recordBossHighWaterMark(student.uid, settled.result.bossState); } return settled.result; } async resetClassBoss(classCode, maxHp = 500, bossId = null) { const db = this.load(); const c = db.classes[normCode(classCode)]; if (!c) throw new DBError('班級不存在'); const isQiongqi = bossId === 'qiongqi' || maxHp === 2000; c.worldBoss = { bossId: isQiongqi ? 'qiongqi' : 'taotie', name: isQiongqi ? '上古・窮奇' : '上古・饕餮', maxHp: isQiongqi ? 2000 : maxHp, curHp: isQiongqi ? 2000 : maxHp, ...(isQiongqi ? { yangMaxHp: 1200, yangHp: 1200, yinMaxHp: 800, yinHp: 800 } : {}), defeated: false, defeatedAt: null, killer: null, damages: {}, resetAt: Date.now() }; this.save(db); return c.worldBoss; } async listClasses() { return Object.entries(this.load().classes).map(([code, v]) => withScheduledBoss({ code, ...v })); } async createClass(code, name) { code = normCode(code); if (!code) throw new DBError('班級代碼只能用英文小寫與數字'); const db = this.load(); if (db.classes[code]) throw new DBError('班級代碼已存在'); db.classes[code] = { name: name || code, donated: 0, openAll: false, openRanges: [], createdAt: Date.now() }; this.save(db); return code; } async updateClass(code, data) { const db = this.load(); Object.assign(db.classes[normCode(code)], data); this.save(db); } async donate(code, amount) { const db = this.load(); const c = db.classes[normCode(code)] || { donated: 0 }; c.donated = (c.donated || 0) + amount; db.classes[normCode(code)] = c; this.save(db); } async aidDonate(classCode, donor, targetUid, targetGame, realDonate, weekId, aidAmt, aidDetails = null) { const db = this.load(); const c = db.classes[normCode(classCode)] || { donated: 0 }; c.donated = (c.donated || 0) + realDonate; c.peerAid = c.peerAid || {}; c.peerAid[targetUid] = c.peerAid[targetUid] || {}; c.peerAid[targetUid].lastAidAt = Date.now(); c.peerAid[targetUid].donorName = donor.name || `座號${donor.seat}`; c.peerAid[targetUid].donorSeat = donor.seat || ''; c.peerAid[targetUid].weeks = c.peerAid[targetUid].weeks || {}; const targetWd = targetGame?.weeklyDonated || {}; if (aidDetails && typeof aidDetails === 'object') { for (const [w, amt] of Object.entries(aidDetails)) { if (amt > 0) { const nextVal = targetWd[w] !== undefined ? targetWd[w] : ((c.peerAid[targetUid].weeks[w] || 0) + amt); c.peerAid[targetUid].weeks[w] = clampWeekCap(w, nextVal); } } } else if (weekId && aidAmt) { const nextVal = targetWd[weekId] !== undefined ? targetWd[weekId] : ((c.peerAid[targetUid].weeks[weekId] || 0) + aidAmt); c.peerAid[targetUid].weeks[weekId] = clampWeekCap(weekId, nextVal); } db.classes[normCode(classCode)] = c; if (db.students[targetUid]) { db.students[targetUid].game = targetGame; } this.save(db); } async deleteClass(code) { const db = this.load(); delete db.classes[normCode(code)]; this.save(db); } ensureDemoStudents(db) { const demoRoster = [ { seat: '1', name: '示範學生', wPct: 0.5, sloth: false }, { seat: '2', name: '趙子龍', wPct: 1.0, sloth: false }, { seat: '3', name: '諸葛孔明', wPct: 1.0, sloth: false }, { seat: '4', name: '關雲長', wPct: 1.0, sloth: false }, { seat: '5', name: '張翼德', wPct: 0.75, sloth: false }, { seat: '6', name: '周公瑾', wPct: 0.85, sloth: false }, { seat: '7', name: '陸伯言', wPct: 0.50, sloth: false }, { seat: '8', name: '黃漢升', wPct: 0.30, sloth: false }, { seat: '9', name: '馬孟起', wPct: 0.20, sloth: false }, { seat: '10', name: '龐士元', wPct: 1.0, sloth: false }, { seat: '11', name: '司馬仲達', wPct: 0.60, sloth: false }, { seat: '12', name: '郭奉孝', wPct: 0.15, sloth: true, shortfall: 25000 }, { seat: '13', name: '荀文若', wPct: 1.0, sloth: false }, { seat: '14', name: '姜伯約', wPct: 0.0, sloth: true, shortfall: 50000 }, ]; let changed = false; for (const r of demoRoster) { const uid = 'demo-' + r.seat; if (!db.students[uid]) { changed = true; const email = studentEmail('demo', r.seat); db.users[email] = { uid, pw: pinToPassword('1234') }; const goal = 100000; const don = Math.round(goal * r.wPct); db.students[uid] = { classCode: 'demo', seat: r.seat, name: r.name, pin: '1234', bankId: 'wiring', createdAt: Date.now(), lastSeen: Date.now() - Math.floor(Math.random() * 86400000), game: { coins: Math.round(don * 1.5 + 50000), totalEarned: don * 3, donated: Math.round(Math.sqrt(Math.max(1, don)) * 5), donatedCoins: don, weeklyDonated: { w1: don }, buildings: { b1: { lv: 10, star: 0 } }, conquered: { b1: true }, blueprints: 5, clicks: 25, lastTick: Date.now() }, progress: { u1: { score: 90, passed: true } }, stats: {} }; } } if (changed) this.save(db); } async listStudents(code) { const db = this.load(); if (normCode(code) === 'demo') { this.ensureDemoStudents(db); } return Object.entries(db.students).filter(([, s]) => s.classCode === normCode(code)) .map(([uid, s]) => ({ ...s, uid })).sort((a, b) => Number(a.seat) - Number(b.seat)); } async createStudent({ classCode, seat, name, pin, bankId }) { classCode = normCode(classCode); seat = normSeat(seat); if (!classCode || !seat) throw new DBError('班級代碼或座號錯誤'); if (!String(pin || '').trim()) throw new DBError('請設定密碼'); const db = this.load(); const email = studentEmail(classCode, seat); if (db.users[email]) throw new DBError(`座號 ${seat} 已存在`); const uid = this.uid(); db.users[email] = { uid, pw: pinToPassword(pin) }; db.students[uid] = { classCode, seat, name: name || `座號${seat}`, pin: String(pin).trim(), bankId: bankId || '', createdAt: Date.now(), lastSeen: null, game: null, progress: {}, stats: {}, }; this.save(db); return uid; } async updateStudent(uid, data) { const db = this.load(); Object.assign(db.students[uid], data); this.save(db); } async resetPin(student, newPin) { const db = this.load(); db.users[studentEmail(student.classCode, student.seat)].pw = pinToPassword(newPin); db.students[student.uid].pin = String(newPin).trim(); this.save(db); } async deleteStudent(student) { const db = this.load(); delete db.users[studentEmail(student.classCode, student.seat)]; delete db.students[student.uid]; delete db.gifts[student.uid]; this.save(db); } async sendGiftsPersonalized(items, logMeta = {}) { const db = this.load(); const at = Date.now(); items.forEach(({ student, gift, giftId }) => { db.gifts[student.uid] = db.gifts[student.uid] || {}; const gid = giftId ? String(giftId) : this.uid(); db.gifts[student.uid][gid] = { ...gift, claimed: false, at }; }); const logId = logMeta.logId ? String(logMeta.logId) : this.uid(); const existingLogIdx = db.giftLog.findIndex(l => l && l.id === logId); const logEntry = { id: logId, ...logMeta, classCode: normCode(items[0]?.student?.classCode || logMeta.classCode || ''), to: items.map(({ student }) => `${student.seat} ${student.name}`), at }; if (existingLogIdx >= 0) db.giftLog[existingLogIdx] = logEntry; else db.giftLog.push(logEntry); this.save(db); } async sendGift(students, gift) { const db = this.load(); const at = Date.now(); students.forEach((s) => { db.gifts[s.uid] = db.gifts[s.uid] || {}; db.gifts[s.uid][this.uid()] = { ...gift, claimed: false, at }; }); db.giftLog.push({ id: this.uid(), ...gift, classCode: students[0]?.classCode || '', to: students.map((s) => `${s.seat} ${s.name}`), at }); this.save(db); } async reclaimResources(students, { blueprints = 0, coins = 0, peek = 0, eliminate = 0, reason = '' }) { const db = this.load(); const at = Date.now(); const results = []; for (const st of students) { const s = db.students[st.uid]; if (!s) continue; const g = s.game || {}; const curBp = Number(g.blueprints) || 0; const curCoins = Number(g.coins) || 0; const curPeek = Number(g.items?.peek) || 0; const curEliminate = Number(g.items?.eliminate) || 0; const newBp = Math.max(0, curBp - (Number(blueprints) || 0)); const newCoins = Math.max(0, curCoins - (Number(coins) || 0)); const newPeek = Math.max(0, curPeek - (Number(peek) || 0)); const newEliminate = Math.max(0, curEliminate - (Number(eliminate) || 0)); g.blueprints = newBp; g.coins = newCoins; g.items = g.items || {}; g.items.peek = newPeek; g.items.eliminate = newEliminate; s.game = g; results.push({ uid: st.uid, name: s.name, seat: s.seat, before: { bp: curBp, coins: curCoins, peek: curPeek, eliminate: curEliminate }, after: { bp: newBp, coins: newCoins, peek: newPeek, eliminate: newEliminate } }); } db.giftLog = db.giftLog || []; db.giftLog.push({ id: this.uid(), type: 'reclaim', isReclaim: true, reason: reason || '教師手動收回/扣減資源', blueprints: Number(blueprints) || 0, coins: Number(coins) || 0, peek: Number(peek) || 0, eliminate: Number(eliminate) || 0, classCode: students[0]?.classCode || '', to: students.map(s => `${s.seat} ${s.name}`), results, at }); this.save(db); return results; } async listGiftLog(code) { return this.load().giftLog.filter((g) => g.classCode === normCode(code)).sort((a, b) => b.at - a.at); } async listAttempts(code) { return this.load().attempts.filter((a) => a.classCode === normCode(code)).sort((a, b) => b.at - a.at); } async recordLotteryRound(classCode, studentMeta, cycleId, payload = {}) { const cCode = normCode(classCode); const uid = studentMeta?.uid; if (!cCode || !uid || !cycleId) throw new DBError('缺少樂透寫入必要參數'); const db = this.load(); const clsData = db.classes[cCode]; if (!clsData) throw new DBError('班級資料不存在'); const stuData = db.students[uid] || {}; const settled = settleLotteryRoundRecord(clsData, stuData, { ...studentMeta, uid }, cycleId, payload); clsData.lotteryCycles = { ...(clsData.lotteryCycles || {}), [cycleId]: settled.nextCycle }; clsData.updatedAt = Date.now(); if (db.students[uid]) { db.students[uid].game = { ...(db.students[uid].game || {}), lottery: settled.nextStudentLottery }; db.students[uid].lastSeen = Date.now(); } this.save(db); recordLotteryHighWaterMark(uid, settled.nextStudentLottery); return settled.result; } async recordBazaarProgress(classCode, studentMeta, cycleId, payload = {}) { const cCode = normCode(classCode); const uid = studentMeta?.uid; if (!cCode || !uid || !cycleId) throw new DBError('缺少西域大市集寫入必要參數'); const db = this.load(); const clsData = db.classes[cCode]; if (!clsData) throw new DBError('班級資料不存在'); const stuData = db.students[uid] || {}; const mergedGame = mergeBazaarLocalAndRemoteGame(uid, stuData.game, payload.localGame); const settled = settleBazaarClassRecord(clsData, { ...stuData, game: mergedGame }, { ...studentMeta, uid }, cycleId, payload); const now = Date.now(); if (!settled.excludedFromClassBoard) { clsData.bazaarCycles = settled.nextBazaarCycles; clsData.updatedAt = now; } if (db.students[uid]) { db.students[uid].game = settled.nextStudentGame; db.students[uid].lastSeen = now; db.students[uid].updatedAt = now; } this.save(db); recordBazaarHighWaterMark(uid, settled.nextStudentGame?.bazaar); return settled; } async saveWeeklySpotlight(classCode, spotlight, cycleInitDoc = null) { const cCode = normCode(classCode); if (!cCode || !spotlight) throw new DBError('缺少主打活動設定參數'); const db = this.load(); const c = db.classes[cCode]; if (!c) throw new DBError('班級不存在'); c.weeklySpotlight = { ...spotlight, updatedAt: Date.now() }; if (cycleInitDoc && cycleInitDoc.cycleId) { c.lotteryCycles = c.lotteryCycles || {}; const existing = c.lotteryCycles[cycleInitDoc.cycleId]; c.lotteryCycles[cycleInitDoc.cycleId] = existing ? { ...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() } : cycleInitDoc; } c.updatedAt = Date.now(); this.save(db); } async setLotteryBoxStatus(classCode, cycleId, status) { const cCode = normCode(classCode); const db = this.load(); const c = db.classes[cCode]; if (!c || !c.lotteryCycles?.[cycleId]) throw new DBError('找不到該期樂透'); c.lotteryCycles[cycleId].status = status; c.lotteryCycles[cycleId].updatedAt = Date.now(); if (status === 'locked') c.lotteryCycles[cycleId].lockedAt = Date.now(); c.updatedAt = Date.now(); this.save(db); } async extendLotteryPilotToFriday(classCode, oldCycleId = 'lotto_pilot_20261119', mode = 'keep', fridayEndAt) { const cCode = normCode(classCode); const endTs = Number(fridayEndAt) || Date.parse('2026-11-20T23:59:59+08:00'); const db = this.load(); const clsData = db.classes[cCode]; if (!clsData) throw new DBError('班級不存在'); const oldCycle = clsData.lotteryCycles?.[oldCycleId]; if (!oldCycle) throw new DBError(`找不到期別 ${oldCycleId}`); const now = Date.now(); if (mode === 'void_and_restart') { const newCycleId = 'lotto_pilot_20261120'; const openTs = Math.min(now, Date.parse('2026-11-20T07:00:00+08:00')); oldCycle.status = 'voided'; oldCycle.updatedAt = now; clsData.lotteryCycles[newCycleId] = { cycleId: newCycleId, title: '週五快閃重測(週四場次已作廢重開)', status: 'open', prizeMode: oldCycle.prizeMode || 'pilot', themeId: oldCycle.themeId || 'pilot_flash', questionMode: oldCycle.questionMode || 'mixed', maxDailyRounds: oldCycle.maxDailyRounds || 2, milestones: Array.isArray(oldCycle.milestones) ? [...oldCycle.milestones] : [40, 80, 120], openAt: openTs, endAt: endTs, entries: {}, drawResult: null, updatedAt: now, }; clsData.weeklySpotlight = { ...(clsData.weeklySpotlight || {}), eventId: 'lottery', cycleId: newCycleId, openAt: openTs, endAt: endTs, allowDuringCaravan: true, updatedAt: now }; clsData.updatedAt = now; this.save(db); return { mode, cycleId: newCycleId, endAt: endTs }; } oldCycle.status = 'open'; oldCycle.endAt = endTs; oldCycle.updatedAt = now; clsData.weeklySpotlight = { ...(clsData.weeklySpotlight || {}), endAt: endTs, updatedAt: now }; clsData.updatedAt = now; this.save(db); return { mode: 'keep', cycleId: oldCycleId, endAt: endTs }; } async settleLotteryDraw(classCode, cycleId, drawResult, giftItems = [], logMeta = {}) { const cCode = normCode(classCode); const db = this.load(); const clsData = db.classes[cCode]; const cycle = clsData?.lotteryCycles?.[cycleId]; if (!cycle) throw new DBError(`找不到期別 ${cycleId}`); if (cycle.status === 'settled' && cycle.drawResult?.giftsDispatched !== false) { throw new DBError('此期錯題樂透已結算過(settled),禁止重複發信!'); } const now = Date.now(); const hasGifts = Array.isArray(giftItems) && giftItems.length > 0; cycle.status = 'settled'; cycle.drawResult = { ...(drawResult || {}), settledAt: cycle.drawResult?.settledAt || now, giftsDispatched: !hasGifts, }; cycle.updatedAt = now; clsData.updatedAt = now; this.save(db); if (hasGifts) { const taggedItems = giftItems.map(item => ({ ...item, giftId: item.giftId || `lottery_${cycleId}`, })); await this.sendGiftsPersonalized(taggedItems, { kind: 'lottery_settle', classCode: cCode, lotteryCycleId: cycleId, logId: `lottery_settle_${cCode}_${cycleId}`, reason: logMeta.reason || `🎰 錯題樂透開獎結算 (${cycleId})`, ...logMeta, }); const dbAfter = this.load(); const afterCyc = dbAfter.classes[cCode]?.lotteryCycles?.[cycleId]; if (afterCyc?.drawResult) { afterCyc.drawResult.giftsDispatched = true; afterCyc.drawResult.giftsDispatchedAt = Date.now(); afterCyc.drawResult.giftsDispatchedCount = taggedItems.length; dbAfter.classes[cCode].updatedAt = Date.now(); this.save(dbAfter); } } } async markLegacyBossCleared(classCode, ts = Date.now()) { const cCode = normCode(classCode); const db = this.load(); const clsData = db.classes[cCode]; if (!clsData) throw new DBError('班級不存在'); clsData.legacyBossClearedAt = ts; if (clsData.worldBoss) { clsData.worldBoss.hidden = true; clsData.worldBoss.phaseMode = 'closed'; } clsData.updatedAt = Date.now(); this.save(db); } getTrafficStats() { return trafficTracker.getQuotaStatus(); } simulateTraffic(params) { return trafficTracker.simulateLoad(params); } resetTrafficStats() { trafficTracker.reset(); } } let _db = null; export async function getDB() { if (_db) return _db; const isDemoParam = typeof location !== 'undefined' && new URLSearchParams(location.search).has('demo'); const useFirebase = !!(firebaseConfig && firebaseConfig.apiKey) && !isDemoParam; const backend = useFirebase ? new FirebaseBackend() : new LocalBackend(); try { await backend.init(); } catch (e) { console.error('[db] 初始化失敗', e); throw new DBError('資料庫初始化失敗:' + (e.message || e)); } _db = backend; return _db; } export { trafficTracker, LocalBackend };
// =============================================================
// 資料層:同一組 API,兩種後端
// 1. FirebaseBackend:正式使用(Auth + Firestore)
// 2. LocalBackend :firebaseConfig 未填時的本機示範模式(localStorage)
// =============================================================
import { firebaseConfig, STUDENT_EMAIL_DOMAIN, PIN_SUFFIX } from './firebase-config.js?v=20261129_v1';
import { WEEKLY_SCHEDULE, BAZAAR_CONFIG } from './config.js?v=20261129_v1';
import { trafficTracker } from './traffic-tracker.js?v=20261129_v1';
import { normalizeWorldBossState } from './world-boss-schedule.js?v=20261129_v1';
import { LOTTERY_ROUND_SIZE, scoreLotteryAnswer } from './lottery-core.js?v=20261129_v1';
import { grantTally } from './engine.js?v=20261129_v1';
import { todayStr } from './util.js?v=20261129_v1';
const WEEK_TARGET_MAP = Object.fromEntries(WEEKLY_SCHEDULE.map(w => [w.id, w.target]));
function clampWeekCap(weekId, val) {
const num = Math.max(0, Number(val) || 0);
const cap = WEEK_TARGET_MAP[weekId];
return (typeof cap === 'number' && cap > 0) ? Math.min(num, cap) : num;
}
// 讀取班級資料時,依世界 Boss 當期排程正規化 worldBoss(饕餮→窮奇自動換期、預告→封印倒數)
function withScheduledBoss(cls) {
if (!cls || typeof cls !== 'object') return cls;
const wb = normalizeWorldBossState(cls.worldBoss);
return (wb && wb !== cls.worldBoss) ? { ...cls, worldBoss: wb } : cls;
}
// 世界 Boss 寫入傷害前的防線:封印倒數期間一律拒絕(防止直連 boss.html 提前偷打)
function assertBossAttackable(wb, now = Date.now()) {
if (wb?.phaseMode === 'scheduled' && Number(wb.openAt) > now) {
throw new DBError('世界 Boss 尚在封印倒數中,破印時間到才能出征!');
}
}
/**
* 純函數:世界 Boss 單場傷害與每日討伐次數原子結算(共用 Firestore Transaction 與 LocalBackend)
* - 雙邊對齊每日上限(3 + 當日 extraBossOrdersDate === today 額外次數)
* - 移除累計 attacksCount 跨週誤推,避免換期/跨日後錯鎖每日次數
* - 伺服器端單場上限校正(窮奇 50 HP / 饕餮 25 HP),防禦異常高傷或前端篡改
* - 若進房前 Boss 已被同袍先步擊破 (wasDefeated),回傳 orderConsumed: false 且不扣討伐令
*/
export function settleBossDamageRecord(wbInput, student, roundDmg, splitDmg = null, sData = null, today = todayStr()) {
const wb = { ...(wbInput || defaultBossState()) };
assertBossAttackable(wb);
if (!wb.damages) wb.damages = {};
const isYinYang = wb.bossId === 'qiongqi' || !!splitDmg || typeof wb.yangHp === 'number' || typeof wb.yinHp === 'number';
const maxRoundDmg = isYinYang ? 50 : 25;
let maxHp = wb.maxHp || 500;
const yangMaxHp = wb.yangMaxHp || 1200;
const yinMaxHp = wb.yinMaxHp || 800;
let wasDefeated = false;
let oldHp = typeof wb.curHp === 'number' ? wb.curHp : maxHp;
let oldYangHp = yangMaxHp;
let oldYinHp = yinMaxHp;
if (isYinYang) {
maxHp = yangMaxHp + yinMaxHp;
oldYangHp = typeof wb.yangHp === 'number' ? Math.max(0, wb.yangHp) : yangMaxHp;
oldYinHp = typeof wb.yinHp === 'number' ? Math.max(0, wb.yinHp) : yinMaxHp;
oldHp = oldYangHp + oldYinHp;
wasDefeated = !!wb.defeated || (oldYangHp <= 0 && oldYinHp <= 0);
} else {
wasDefeated = !!wb.defeated || oldHp <= 0;
}
const prevRec = wb.damages[student.uid];
const sBoss = sData?.game?.boss || {};
const sUsedToday = (sBoss.date === today) ? Math.max(0, Number(sBoss.used) || 0) : 0;
// 若在寫入交易瞬間 Boss 已被同袍先一步封印:不寫入廢傷、不消耗玩家今日討伐令
if (wasDefeated) {
const curDailyUsed = (prevRec?.dailyUsed && typeof prevRec.dailyUsed[today] === 'number')
? Math.max(0, Number(prevRec.dailyUsed[today]) || 0)
: sUsedToday;
return {
orderConsumed: false,
alreadyDefeated: true,
updatedWb: wb,
mergedStuBoss: null,
result: {
curHp: isYinYang ? 0 : Math.max(0, Number(oldHp) || 0),
maxHp,
yangHp: isYinYang ? 0 : undefined,
yangMaxHp: isYinYang ? yangMaxHp : undefined,
yinHp: isYinYang ? 0 : undefined,
yinMaxHp: isYinYang ? yinMaxHp : undefined,
effYangDmg: 0,
effYinDmg: 0,
defeated: true,
isKiller: false,
killer: wb.killer || null,
effectiveDmg: 0,
myTotalDmg: Number(prevRec?.dmg) || 0,
orderConsumed: false,
alreadyDefeated: true,
dailyUsedToday: curDailyUsed,
bossState: mergeBossObj(sBoss, student?.game?.boss || null)
}