- La Carte du jour: one zoomed card shared by all players each Paris day, six guesses with collection and rarity hints, a fixed stardust reward and an emoji result to share. - The Guilde des Veilleurs lists the quests, with a menu entry, a home banner and an admin section for quest settings. - The section menu folds into a dropdown below 960 px; the home pairs the guild with the best pull and moves the opening reserve under the menu. - The shop pack share moves to the shop collection admin page, which recalls where the pack draws its cards. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
230 lines
15 KiB
JavaScript
230 lines
15 KiB
JavaScript
// Rôle : vérifie les règles, le service et l'API de la Carte du jour de Sokko TCG.
|
|
import assert from "node:assert/strict";
|
|
import { readFile } from "node:fs/promises";
|
|
import { resolve } from "node:path";
|
|
import { Readable } from "node:stream";
|
|
import { test } from "node:test";
|
|
import { createCardsApiHandler } from "../services/cards/api.js";
|
|
import { buildPublishedCatalog, prepareVersionedCatalog } from "../services/cards/catalog.js";
|
|
import { computeStreak, dailyCandidates, dailyDayKey, dailyZoom, drawDailyPuzzle, guessHint, MAX_DAILY_GUESSES, nextDailyAt, shiftDayKey } from "../services/cards/daily.js";
|
|
import { CardsDatabase } from "../services/cards/database.js";
|
|
import { CardsService } from "../services/cards/service.js";
|
|
|
|
const baseCatalog = prepareVersionedCatalog(JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8")));
|
|
const ACTIVE_STATES = [{ collectionId: "primordial-nebula", active: true }, { collectionId: "dream-arcade", active: false }];
|
|
const catalog = buildPublishedCatalog(baseCatalog, { variations: [], collectionStates: ACTIVE_STATES, dropRates: [{ collectionId: "primordial-nebula", rarityWeights: { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 } }] });
|
|
const standardRarity = (cardId) => catalog.editions.find((edition) => edition.cardId === cardId && edition.rarity !== "mythic" && !edition.promotional).rarity;
|
|
|
|
test("the daily day changes at midnight in Paris, in winter and in summer", () => {
|
|
assert.equal(dailyDayKey(Date.parse("2026-11-13T22:59:59Z")), "2026-11-13");
|
|
assert.equal(dailyDayKey(Date.parse("2026-11-13T23:00:00Z")), "2026-11-14");
|
|
assert.equal(dailyDayKey(Date.parse("2026-07-01T21:59:59Z")), "2026-07-01");
|
|
assert.equal(dailyDayKey(Date.parse("2026-07-01T22:00:00Z")), "2026-07-02");
|
|
assert.equal(nextDailyAt(Date.parse("2026-11-13T12:00:00Z")), Date.parse("2026-11-13T23:00:00Z"));
|
|
// Passage à l'heure d'été le 29 mars 2026 : le minuit suivant est à 22 h UTC.
|
|
assert.equal(nextDailyAt(Date.parse("2026-03-29T12:00:00Z")), Date.parse("2026-03-29T22:00:00Z"));
|
|
assert.equal(nextDailyAt(Date.parse("2026-10-25T12:00:00Z")), Date.parse("2026-10-25T23:00:00Z"));
|
|
assert.equal(shiftDayKey("2026-03-01", -1), "2026-02-28");
|
|
assert.equal(shiftDayKey("2026-12-31", 1), "2027-01-01");
|
|
});
|
|
|
|
test("the daily streak counts consecutive won days up to today or yesterday", () => {
|
|
assert.equal(computeStreak([], "2026-11-13"), 0);
|
|
assert.equal(computeStreak(["2026-11-11", "2026-11-12", "2026-11-13"], "2026-11-13"), 3);
|
|
assert.equal(computeStreak(["2026-11-11", "2026-11-12"], "2026-11-13"), 2);
|
|
assert.equal(computeStreak(["2026-11-10", "2026-11-12"], "2026-11-13"), 1);
|
|
assert.equal(computeStreak(["2026-11-11"], "2026-11-13"), 0);
|
|
});
|
|
|
|
test("the daily card comes from an open collection and avoids recent cards", () => {
|
|
const candidates = dailyCandidates(catalog);
|
|
assert.ok(candidates.length > 0);
|
|
assert.ok(candidates.every((item) => item.collectionId === "primordial-nebula"));
|
|
const first = drawDailyPuzzle(catalog, [], () => 0);
|
|
assert.equal(first.cardId, candidates[0].id);
|
|
assert.deepEqual([first.focusX, first.focusY], [20, 20]);
|
|
const last = drawDailyPuzzle(catalog, [], (max) => max - 1);
|
|
assert.deepEqual([last.focusX, last.focusY], [80, 80]);
|
|
assert.equal(drawDailyPuzzle(catalog, [candidates[0].id], () => 0).cardId, candidates[1].id);
|
|
// Quand toutes les cartes sont récentes, le tirage reprend sur toute la liste.
|
|
assert.equal(drawDailyPuzzle(catalog, candidates.map((item) => item.id), () => 0).cardId, candidates[0].id);
|
|
assert.equal(drawDailyPuzzle({ ...catalog, collections: catalog.collections.map((item) => ({ ...item, active: false })) }, [], () => 0), null);
|
|
// Une carte encore sans illustration n'est jamais tirée.
|
|
const withoutImage = { ...catalog, cards: catalog.cards.map((item) => item.id === candidates[0].id ? { ...item, image: null } : item) };
|
|
assert.ok(!dailyCandidates(withoutImage).some((item) => item.id === candidates[0].id));
|
|
});
|
|
|
|
test("a daily guess tells the collection and how the answer rarity compares", () => {
|
|
const nebula = catalog.cards.filter((item) => item.collectionId === "primordial-nebula");
|
|
const legendary = nebula.find((item) => standardRarity(item.id) === "legendary");
|
|
const common = nebula.find((item) => standardRarity(item.id) === "common");
|
|
const arcadeCommon = catalog.cards.find((item) => item.collectionId === "dream-arcade" && standardRarity(item.id) === "common");
|
|
assert.deepEqual(guessHint(catalog, legendary.id, common.id), { cardId: common.id, correct: false, sameCollection: true, rarity: "higher" });
|
|
assert.deepEqual(guessHint(catalog, common.id, legendary.id), { cardId: legendary.id, correct: false, sameCollection: true, rarity: "lower" });
|
|
assert.deepEqual(guessHint(catalog, common.id, arcadeCommon.id), { cardId: arcadeCommon.id, correct: false, sameCollection: false, rarity: "equal" });
|
|
assert.equal(guessHint(catalog, common.id, common.id).correct, true);
|
|
assert.equal(dailyZoom(0, false), 6);
|
|
assert.equal(dailyZoom(5, false), 1.15);
|
|
assert.equal(dailyZoom(9, false), 1.15);
|
|
assert.equal(dailyZoom(2, true), 1);
|
|
});
|
|
|
|
function dailyService(start = Date.parse("2026-11-13T09:00:00Z")) {
|
|
const clock = { now: start };
|
|
const database = new CardsDatabase(":memory:");
|
|
const service = new CardsService({ database, catalog: baseCatalog, now: () => clock.now, random: () => 0 });
|
|
const admin = service.upsertPlayer({ discordId: "daily-admin", displayName: "Admin", isAdmin: true });
|
|
const player = service.upsertPlayer({ discordId: "daily-player", displayName: "Player" });
|
|
const wrongCards = () => {
|
|
const answer = service.todayPuzzle().cardId;
|
|
return service.catalog.cards.filter((item) => item.collectionId === "primordial-nebula" && item.id !== answer).map((item) => item.id);
|
|
};
|
|
return { clock, database, service, admin, player, wrongCards };
|
|
}
|
|
|
|
test("every player gets the same daily card and the answer stays hidden while playing", () => {
|
|
const { service, admin, player, database } = dailyService();
|
|
const daily = service.getDaily(player.id);
|
|
assert.equal(daily.day, "2026-11-13");
|
|
assert.equal(daily.number, 1);
|
|
assert.equal(daily.status, "playing");
|
|
assert.equal(daily.zoom, 6);
|
|
assert.equal(daily.maxGuesses, MAX_DAILY_GUESSES);
|
|
assert.equal(daily.reward, 10);
|
|
assert.equal(daily.answerCardId, null);
|
|
assert.ok(!JSON.stringify(daily).includes(service.todayPuzzle().cardId));
|
|
assert.deepEqual(daily.focus, { x: 20, y: 20 });
|
|
assert.equal(daily.nextAt, Date.parse("2026-11-13T23:00:00Z"));
|
|
assert.ok(daily.collectionIds.includes("primordial-nebula"));
|
|
assert.ok(!daily.collectionIds.includes("dream-arcade"));
|
|
assert.equal(service.getDaily(admin.id).day, daily.day);
|
|
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM daily_puzzles").get().count, 1);
|
|
assert.equal(service.getState(player.id).daily.status, "playing");
|
|
});
|
|
|
|
test("wrong daily guesses unzoom the card until the player runs out of guesses", () => {
|
|
const { service, player, wrongCards } = dailyService();
|
|
const [first, ...others] = wrongCards();
|
|
const { daily, state } = service.guessDaily(player.id, { day: "2026-11-13", cardId: first });
|
|
assert.deepEqual({ status: state.daily.status, guessCount: state.daily.guessCount }, { status: "playing", guessCount: 1 });
|
|
assert.equal(daily.guesses.length, 1);
|
|
assert.equal(daily.guesses[0].correct, false);
|
|
assert.equal(daily.guesses[0].sameCollection, true);
|
|
assert.equal(daily.zoom, 4.2);
|
|
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: first }), (error) => error.code === "DAILY_GUESS_REPEATED");
|
|
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: "unknown-card" }), (error) => error.code === "DAILY_GUESS_INVALID");
|
|
const closedCard = service.catalog.cards.find((item) => item.collectionId === "dream-arcade");
|
|
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: closedCard.id }), (error) => error.code === "DAILY_GUESS_INVALID");
|
|
assert.throws(() => service.guessDaily(player.id, { day: "13/11/2026", cardId: others[0] }), (error) => error.code === "DAILY_GUESS_INVALID");
|
|
let last;
|
|
for (const cardId of others.slice(0, MAX_DAILY_GUESSES - 1)) last = service.guessDaily(player.id, { day: "2026-11-13", cardId }).daily;
|
|
assert.equal(last.status, "lost");
|
|
assert.equal(last.zoom, 1);
|
|
assert.equal(last.earned, 0);
|
|
assert.equal(last.answerCardId, service.todayPuzzle().cardId);
|
|
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: others.at(-1) }), (error) => error.code === "DAILY_FINISHED");
|
|
assert.equal(service.getState(player.id).wallet.stardust, 0);
|
|
});
|
|
|
|
test("finding the daily card credits the reward once and records it in the player history", () => {
|
|
const { service, admin, player, wrongCards } = dailyService();
|
|
service.updateShopSetting(admin.id, { ...service.shopSetting, dailyReward: 25 });
|
|
const answer = service.todayPuzzle().cardId;
|
|
service.guessDaily(player.id, { day: "2026-11-13", cardId: wrongCards()[0] });
|
|
const { daily, state } = service.guessDaily(player.id, { day: "2026-11-13", cardId: answer });
|
|
assert.equal(daily.status, "won");
|
|
assert.equal(daily.earned, 25);
|
|
assert.equal(daily.streak, 1);
|
|
assert.equal(daily.zoom, 1);
|
|
assert.equal(daily.answerCardId, answer);
|
|
assert.equal(state.wallet.stardust, 25);
|
|
assert.deepEqual(state.history.find((entry) => entry.type === "daily_won"), { type: "daily_won", entityId: "2026-11-13", details: { number: 1, cardId: answer, guesses: 2, stardust: 25 }, createdAt: Date.parse("2026-11-13T09:00:00Z") });
|
|
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: answer }), (error) => error.code === "DAILY_FINISHED");
|
|
assert.equal(service.getState(player.id).wallet.stardust, 25);
|
|
assert.deepEqual(service.getAdminDashboard(admin.id).daily, { day: "2026-11-13", number: 1, cardId: answer, players: 1, winners: 1 });
|
|
// La récompense de la Carte du jour n'est pas une action d'administration.
|
|
assert.ok(!service.getAdminHistory(admin.id).entries.some((entry) => entry.type === "daily_won"));
|
|
assert.throws(() => service.updateShopSetting(admin.id, { ...service.shopSetting, dailyReward: -1 }), /Carte du jour/);
|
|
});
|
|
|
|
test("a new daily card arrives at midnight in Paris and the streak continues", () => {
|
|
const { clock, service, player } = dailyService();
|
|
const firstAnswer = service.todayPuzzle().cardId;
|
|
service.guessDaily(player.id, { day: "2026-11-13", cardId: firstAnswer });
|
|
clock.now = Date.parse("2026-11-13T23:00:00Z");
|
|
assert.throws(() => service.guessDaily(player.id, { day: "2026-11-13", cardId: firstAnswer }), (error) => error.code === "DAILY_EXPIRED");
|
|
const daily = service.getDaily(player.id);
|
|
assert.equal(daily.day, "2026-11-14");
|
|
assert.equal(daily.number, 2);
|
|
assert.equal(daily.status, "playing");
|
|
assert.equal(daily.streak, 1);
|
|
const secondAnswer = service.todayPuzzle().cardId;
|
|
assert.notEqual(secondAnswer, firstAnswer);
|
|
assert.equal(service.guessDaily(player.id, { day: "2026-11-14", cardId: secondAnswer }).daily.streak, 2);
|
|
});
|
|
|
|
test("deleting an account erases its daily games", () => {
|
|
const { service, player, database } = dailyService();
|
|
service.guessDaily(player.id, { day: "2026-11-13", cardId: service.todayPuzzle().cardId });
|
|
service.deleteAccount(player.id);
|
|
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM daily_attempts WHERE player_id = ?").get(player.id).count, 0);
|
|
});
|
|
|
|
function mockRequest({ method = "GET", path, body, headers = {} }) {
|
|
const req = Readable.from(body == null ? [] : [Buffer.from(JSON.stringify(body))]);
|
|
req.method = method;
|
|
req.url = path;
|
|
req.headers = { host: "localhost:5173", ...headers };
|
|
req.socket = { remoteAddress: "127.0.0.1" };
|
|
return req;
|
|
}
|
|
|
|
async function call(handler, options) {
|
|
const response = { status: 0, headers: {}, chunks: [] };
|
|
const res = {
|
|
setHeader(name, value) { response.headers[name.toLowerCase()] = value; },
|
|
writeHead(status, headers = {}) {
|
|
response.status = status;
|
|
for (const [name, value] of Object.entries(headers)) response.headers[name.toLowerCase()] = value;
|
|
},
|
|
end(value = "") { response.chunks.push(Buffer.from(value)); }
|
|
};
|
|
await handler(mockRequest(options), res);
|
|
response.raw = Buffer.concat(response.chunks);
|
|
response.json = response.headers["content-type"]?.startsWith("application/json") && response.raw.length ? JSON.parse(response.raw.toString("utf8")) : null;
|
|
return response;
|
|
}
|
|
|
|
test("the daily API requires a session, protects guesses and serves the image without revealing the card", async (t) => {
|
|
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 });
|
|
t.after(() => handler.close());
|
|
for (const path of ["/api/cards/daily", "/api/cards/daily/image"]) assert.equal((await call(handler, { path })).status, 401);
|
|
assert.equal((await call(handler, { method: "POST", path: "/api/cards/daily/guesses", body: {} })).status, 401);
|
|
|
|
const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} });
|
|
const cookie = login.headers["set-cookie"].split(";")[0];
|
|
const csrf = login.json.csrfToken;
|
|
const daily = await call(handler, { path: "/api/cards/daily", headers: { cookie } });
|
|
assert.equal(daily.status, 200);
|
|
assert.equal(daily.json.answerCardId, null);
|
|
|
|
const image = await call(handler, { path: "/api/cards/daily/image", headers: { cookie } });
|
|
assert.equal(image.status, 200);
|
|
assert.equal(image.headers["content-type"], "image/webp");
|
|
assert.equal(image.headers["cache-control"], "private, no-store");
|
|
assert.equal(image.headers["content-disposition"], undefined);
|
|
assert.equal(image.raw.subarray(8, 12).toString("ascii"), "WEBP");
|
|
const answer = handler.service.todayPuzzle().cardId;
|
|
assert.ok(!JSON.stringify(image.headers).includes(answer));
|
|
assert.deepEqual(image.raw, await readFile(resolve("website/public", `.${handler.service.index.cards.get(answer).image}`)));
|
|
|
|
const unprotected = await call(handler, { method: "POST", path: "/api/cards/daily/guesses", headers: { cookie }, body: { day: daily.json.day, cardId: answer } });
|
|
assert.equal(unprotected.status, 403);
|
|
const won = await call(handler, { method: "POST", path: "/api/cards/daily/guesses", headers: { cookie, "x-csrf-token": csrf }, body: { day: daily.json.day, cardId: answer } });
|
|
assert.equal(won.status, 200);
|
|
assert.equal(won.json.daily.status, "won");
|
|
assert.ok(won.json.state.history.some((entry) => entry.type === "daily_won"));
|
|
const again = await call(handler, { method: "POST", path: "/api/cards/daily/guesses", headers: { cookie, "x-csrf-token": csrf }, body: { day: daily.json.day, cardId: answer } });
|
|
assert.equal(again.status, 409);
|
|
assert.equal(again.json.error.code, "DAILY_FINISHED");
|
|
});
|