mirror of
https://github.com/db9979/tidefront.git
synced 2026-12-06 04:44:09 +01:00
Merge branch 'worktree-agent-a0114651eaf12747e'
This commit is contained in:
commit
d7bdfd08b0
31 files changed
+1328
-62
No files matched your search
@@ -101,7 +101,7 @@ export async function disablePush(): Promise<void> {
|
||||
await sub.unsubscribe().catch(() => {});
|
||||
}
|
||||
|
||||
export type OpenTarget = { tab?: "basis" | "karte" | "truppen" | "berichte" | "boerse"; view?: "settings" | "admin"; /** Mehrere Häfen: diesen Hafen aktiv machen. */ base?: number };
|
||||
export type OpenTarget = { tab?: "basis" | "karte" | "truppen" | "berichte" | "boerse"; view?: "settings" | "admin"; /** Mehrere Häfen: diesen Hafen aktiv machen. */ base?: number; /** E-Mail-Link: diesen Bericht öffnen. */ report?: number };
|
||||
|
||||
/** Ziel aus einer App-Adresse (Benachrichtigung): ?tab=berichte, ?view=admin, ?base=12 (Hafen). */
|
||||
export function parseOpenUrl(url: string): OpenTarget {
|
||||
@@ -112,5 +112,14 @@ export function parseOpenUrl(url: string): OpenTarget {
|
||||
tab: tab && ["basis", "karte", "truppen", "berichte", "boerse"].includes(tab) ? (tab as OpenTarget["tab"]) : undefined,
|
||||
view: view === "admin" || view === "settings" ? view : undefined,
|
||||
base: /^\d{1,9}$/.test(q.get("base") ?? "") ? Number(q.get("base")) : undefined,
|
||||
report: /^\d{1,9}$/.test(q.get("bericht") ?? "") ? Number(q.get("bericht")) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/** Bericht aus dem Start-Link (?bericht=ID, z. B. aus einer E-Mail); wird einmal abgeholt. */
|
||||
let openReport: number | undefined = typeof location !== "undefined" ? parseOpenUrl(location.href).report : undefined;
|
||||
export function takeOpenReport(): number | null {
|
||||
const id = openReport ?? null;
|
||||
openReport = undefined;
|
||||
return id;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { BattleLog, type Battle } from "../components/BattleLog.tsx";
|
||||
import { RepeatButton } from "../components/Repeat.tsx";
|
||||
import { WorldEventReportNote } from "../components/WorldEvents.tsx";
|
||||
import { useBackLayer } from "../lib/back.ts";
|
||||
import { takeOpenReport } from "../lib/push.ts";
|
||||
import { SabotageReport, SpyReport } from "../components/Intel.tsx";
|
||||
import { AdmiralReport } from "../components/Admirals.tsx"; // Admirale
|
||||
import { AllianceOpsReport } from "../components/AllianceOps.tsx"; // Allianz-Ops
|
||||
@@ -53,7 +54,7 @@ function roleText(role: string, kind: string): string {
|
||||
}
|
||||
|
||||
export function ReportsScreen() {
|
||||
const [open, setOpen] = useState<number | null>(null);
|
||||
const [open, setOpen] = useState<number | null>(() => takeOpenReport()); // E-Mail-Link ?bericht=ID
|
||||
const [filter, setFilter] = useState<Filter>("alle");
|
||||
const [limit, setLimit] = useState(PAGE);
|
||||
const list = useQuery(trpc.report.list.queryOptions());
|
||||
|
||||
@@ -280,6 +280,8 @@ export async function flushAchievementNotices(engine: Engine, limit = 200): Prom
|
||||
jobs.push({ playerId: r.playerId, notice: {
|
||||
kind: "report", url: "/?tab=berichte", tag: `erfolg-${r.achievementId}`,
|
||||
title: `Erfolg: ${a.title} (${TIER_NAMES[r.tier - 1]})`, body: `${tierText(a, r.tier)}. Belohnung abholen unter Meldungen → Erfolge.`,
|
||||
facts: [["Erfolg", a.title], ["Stufe", TIER_NAMES[r.tier - 1] ?? String(r.tier)], ["Erreicht", tierText(a, r.tier)]], // E-Mail
|
||||
mail: { subject: `Erfolg freigeschaltet: ${a.title} (${TIER_NAMES[r.tier - 1]})` },
|
||||
} });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -271,7 +271,7 @@ export const raidArrive: Handler = async (tx, ev, due) => {
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const mine = sum(shares[i]) > 0 ? resText(shares[i]) : "keine";
|
||||
await tx.insert(tables.message).values({ fromPlayerId: null, toPlayerId: parts[i].playerId, subject: "Sammelangriff: Ergebnis", body: `${head} Dein Beitrag ${pct[i]} %, deine Beute: ${mine}.`, createdAt: new Date(due) });
|
||||
push.push({ playerId: parts[i].playerId, notice: { kind: "report", title: `Kampfbericht: ${fight?.title ?? raid.targetName}`, body: `Dein Beitrag ${pct[i]} %, Beute: ${mine}.`, url: "/?tab=meldungen", tag: `raid-${raid.id}` } });
|
||||
push.push({ playerId: parts[i].playerId, notice: { kind: "report", title: `Kampfbericht: ${fight?.title ?? raid.targetName}`, body: `Dein Beitrag ${pct[i]} %, Beute: ${mine}.`, url: "/?tab=meldungen", tag: `raid-${raid.id}`, ...(reportId !== null ? { reportId } : {}) } });
|
||||
}
|
||||
notes.push([ids, "messages"], [ids, "reports"], [ids, "missions"], [await memberIds(tx, raid.allianceId), "alliance"]);
|
||||
return { notify: [...notify, ...notes], push };
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Balance, market } from "@tidefront/game-core";
|
||||
import type { Db } from "@tidefront/db";
|
||||
import type { MailBlock } from "./mail-blocks.ts";
|
||||
import balanceJson from "../../balance/v1/balance.json" with { type: "json" };
|
||||
|
||||
export const balance = balanceJson as unknown as Balance;
|
||||
@@ -26,6 +27,10 @@ export interface Notice {
|
||||
url?: string;
|
||||
tag?: string;
|
||||
facts?: [string, string][];
|
||||
/** Zugehöriger Bericht: die E-Mail zeigt ihn ausführlich (mail-reports.ts) und verlinkt direkt darauf. */
|
||||
reportId?: number;
|
||||
/** Nur für die E-Mail: aussagekräftiger Betreff und ausführlicher Inhalt (Bausteine aus mail-blocks.ts). */
|
||||
mail?: { subject?: string; lead?: string; blocks?: MailBlock[] };
|
||||
}
|
||||
|
||||
export interface NoticeJob {
|
||||
|
||||
@@ -186,12 +186,12 @@ export const spyArrive: Handler = async (tx, ev, due) => {
|
||||
winner: "defender", seed: spy.seed, atMs: due, report: { spy: dice, battle },
|
||||
});
|
||||
await tx.update(tables.mission).set({ status: "done", returning: {}, cargoHome: {}, reportId }).where(eq(tables.mission.id, m.id));
|
||||
push.push({ playerId: pid, notice: { kind: "report", url: "/?tab=meldungen", tag: `spy-${m.id}`, title: "Spion enttarnt", body: `Dein Spion wurde in ${targetName} enttarnt (Wurf ${roll.roll}, nötig ≤ ${roll.threshold}). Er ist verloren.` } });
|
||||
push.push({ playerId: pid, notice: { kind: "report", url: "/?tab=meldungen", tag: `spy-${m.id}`, reportId, title: "Spion enttarnt", body: `Dein Spion wurde in ${targetName} enttarnt (Wurf ${roll.roll}, nötig ≤ ${roll.threshold}). Er ist verloren.` } });
|
||||
if (target) {
|
||||
const what = KIND_TITLE[spy.kind] + (spy.building ? ` (${SABOTAGE_TEXT[spy.building] ?? spy.building})` : "");
|
||||
await systemMessage(tx, [target.playerId], `Fremder Spion enttarnt – Absender ${senderName}`,
|
||||
`In ${target.name} wurde ein Spion von ${senderName} enttarnt. Auftrag: ${what}. Der Spion ist ausgeschaltet; der Wurf steht im Bericht.`, due);
|
||||
push.push({ playerId: target.playerId, notice: { kind: "attack", url: "/?tab=meldungen", tag: `spy-def-${m.id}`, title: "Fremder Spion enttarnt", body: `Absender: ${senderName}. Auftrag: ${what}.` } });
|
||||
push.push({ playerId: target.playerId, notice: { kind: "attack", url: "/?tab=meldungen", tag: `spy-def-${m.id}`, reportId, title: "Fremder Spion enttarnt", body: `Absender: ${senderName}. Auftrag: ${what}.` } });
|
||||
notify.push([[target.playerId], "reports"], [[target.playerId], "messages"]);
|
||||
}
|
||||
return { notify, push };
|
||||
@@ -212,12 +212,12 @@ export const spyArrive: Handler = async (tx, ev, due) => {
|
||||
const name = SABOTAGE_TEXT[spy.building] ?? spy.building;
|
||||
const effect = spy.building === "bauschlange" ? `Der Ausbau verzögert sich um ${espionageOf(balance)!.sabotage.delayHours} Stunden.` : `${name} fällt aus bis ${clock(r.sabotage.untilMs)} Uhr (UTC).`;
|
||||
detail = { sabotage: { ...r.sabotage, effect } };
|
||||
await insertReport(tx, {
|
||||
const sabotageReportId = await insertReport(tx, {
|
||||
kind: "sabotage", title: `Sabotage in ${target.name}: ${name}`, attackerPlayerId: null, defenderPlayerId: target.playerId,
|
||||
attackerBaseId: null, defenderBaseId: target.id, winner: null, seed: null, atMs: due,
|
||||
report: { sabotage: { ...r.sabotage, effect }, targetName: target.name },
|
||||
});
|
||||
push.push({ playerId: target.playerId, notice: { kind: "attack", url: "/?tab=basis", tag: `sabotage-${target.id}`, title: `Sabotage: ${name}`, body: effect } });
|
||||
push.push({ playerId: target.playerId, notice: { kind: "attack", url: "/?tab=basis", tag: `sabotage-${target.id}`, reportId: sabotageReportId, title: `Sabotage: ${name}`, body: effect } });
|
||||
notify.push([[target.playerId], "base"], [[target.playerId], "reports"]);
|
||||
}
|
||||
} else if (spy.kind === "desinformation" && target && origin) {
|
||||
@@ -239,7 +239,7 @@ export const spyArrive: Handler = async (tx, ev, due) => {
|
||||
await back(reportId, true);
|
||||
// Tagesbefehl „erkundung“: erfolgreiche Erkundung (Hafen oder Kartell).
|
||||
if (spy.kind === "erkunden" || spy.kind === "kartell") await trackProgress(tx, pid, "erkundung", 1, { atMs: due });
|
||||
push.push({ playerId: pid, notice: { kind: "report", url: "/?tab=meldungen", tag: `spy-${m.id}`, title: `Spionagebericht: ${KIND_TITLE[spy.kind]}`, body: `Auftrag gegen ${targetName} gelungen (Wurf ${roll.roll}, nötig ≤ ${roll.threshold}).` } });
|
||||
push.push({ playerId: pid, notice: { kind: "report", url: "/?tab=meldungen", tag: `spy-${m.id}`, reportId, title: `Spionagebericht: ${KIND_TITLE[spy.kind]}`, body: `Auftrag gegen ${targetName} gelungen (Wurf ${roll.roll}, nötig ≤ ${roll.threshold}).` } });
|
||||
return { notify, push };
|
||||
};
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import { ADMIRAL_RETURN_TYPE, lockBase, readBase, scheduleEvent } from "./store.
|
||||
import { amounts, clock, fmtInt, minutesText, nameOf } from "./names.ts";
|
||||
import { modsOf } from "./modifiers.ts";
|
||||
import { detectedAtOf, isDetected, markDetected, warnFactor } from "./radar.ts";
|
||||
import { attackWarningMail } from "./mail-notices.ts"; // E-Mail: Lage und empfohlene Schritte
|
||||
|
||||
export type Snapshot =
|
||||
| { kind: "build"; order: BuildOrder | null }
|
||||
@@ -60,12 +61,13 @@ async function reportNotices(tx: Tx, reportId: number): Promise<NoticeJob[]> {
|
||||
const loot = amounts(data.battle?.loot);
|
||||
const url = "/?tab=berichte";
|
||||
const tag = `report-${r.id}`;
|
||||
// E-Mail: reportId (Parameter) zeigt den Bericht ausführlich.
|
||||
const out: NoticeJob[] = [];
|
||||
if (r.kind === "ueberfall" || r.kind === "kartell") {
|
||||
if (r.attackerPlayerId !== null) {
|
||||
const won = r.winner === "attacker";
|
||||
out.push({ playerId: r.attackerPlayerId, notice: {
|
||||
kind: "report", url, tag, title: `Kampfbericht: ${r.title}`,
|
||||
kind: "report", url, tag, reportId, title: `Kampfbericht: ${r.title}`,
|
||||
body: won ? `Sieg. Beute: ${loot}.` : "Der Angriff ist gescheitert.",
|
||||
facts: [["Ergebnis", won ? "Sieg" : "Niederlage"], ["Beute", loot]],
|
||||
} });
|
||||
@@ -74,18 +76,18 @@ async function reportNotices(tx: Tx, reportId: number): Promise<NoticeJob[]> {
|
||||
const held = r.winner === "defender";
|
||||
const attacker = r.kind === "kartell" ? "Freibeuter-Kartell" : (data.attackerName ?? "Ein Gegner");
|
||||
out.push({ playerId: r.defenderPlayerId, notice: {
|
||||
kind: "report", url, tag, title: `Kampfbericht: ${data.targetName ?? "Dein Hafen"} angegriffen`,
|
||||
kind: "report", url, tag, reportId, title: `Kampfbericht: ${data.targetName ?? "Dein Hafen"} angegriffen`,
|
||||
body: held ? `${attacker} wurde abgewehrt.` : `${attacker} hat ${(await harborName(tx, r.defenderPlayerId, r.defenderBaseId)) ?? "deinen Hafen"} überwunden. Verlust: ${loot}.`,
|
||||
facts: [["Angreifer", attacker], ["Ergebnis", held ? "Abgewehrt" : "Verloren"], ["Beute des Gegners", loot]],
|
||||
} });
|
||||
}
|
||||
} else if (r.kind === "aufklaerung" || r.kind === "leer") {
|
||||
if (r.attackerPlayerId !== null) {
|
||||
out.push({ playerId: r.attackerPlayerId, notice: { kind: "report", url, tag, title: r.title, body: "Der Bericht liegt vor." } });
|
||||
out.push({ playerId: r.attackerPlayerId, notice: { kind: "report", url, tag, reportId, title: r.title, body: "Der Bericht liegt vor." } });
|
||||
}
|
||||
} else if (r.kind === "transport" && r.defenderPlayerId !== null) {
|
||||
out.push({ playerId: r.defenderPlayerId, notice: {
|
||||
kind: "delivery", url: "/?tab=basis", tag, title: "Transport angekommen",
|
||||
kind: "delivery", url: "/?tab=basis", tag, reportId, title: "Transport angekommen",
|
||||
body: `${data.from ?? "Ein Mitspieler"} hat Ladung geliefert.`,
|
||||
} });
|
||||
}
|
||||
@@ -224,12 +226,14 @@ export const attackWarning: Handler = async (tx, ev, due) => {
|
||||
}
|
||||
const arrive = m.arriveAt.getTime();
|
||||
const left = minutesText(arrive - due);
|
||||
const units = (m.plan as { units?: Record<string, number> } | null)?.units ?? {};
|
||||
const mail = attackWarningMail({ attacker, targetName: b.name, arriveAtMs: arrive, nowMs: due, units, kartell: m.playerId === null, state: b.state, mods: await modsOf(tx, b, due) });
|
||||
return {
|
||||
notify: [[[b.playerId], "missions"]],
|
||||
push: [{ playerId: b.playerId, notice: {
|
||||
kind: "attack", url: "/?tab=basis", tag: `attack-${m.id}`, title: "Angriff erkannt",
|
||||
body: `${attacker} greift ${b.name} an. Ankunft in ${left} (${clock(arrive)} Uhr).`,
|
||||
facts: [["Angreifer", attacker], ["Ziel", b.name], ["Ankunft in", left], ["Ankunft", `${clock(arrive)} Uhr`]],
|
||||
facts: [["Angreifer", attacker], ["Ziel", b.name], ["Ankunft in", left], ["Ankunft", `${clock(arrive)} Uhr`]], mail,
|
||||
} }],
|
||||
};
|
||||
};
|
||||
@@ -58,7 +58,7 @@ async function foundingArrive(tx: Tx, m: MissionRowLike, plan: Mission, due: num
|
||||
report: { founding: { col: at.col, row: at.row, ok: false, code: blocker, units: plan.units, cargo: plan.cargo } },
|
||||
});
|
||||
await sendHome(tx, m, plan, activeCounts(plan.units), plan.cargo ?? {}, reportId, due);
|
||||
push.push(pushNotice(pid, "report", title, "Das Kolonieschiff kehrt mit seiner Ladung heim.", "berichte"));
|
||||
push.push(pushNotice(pid, "report", title, "Das Kolonieschiff kehrt mit seiner Ladung heim.", "berichte", reportId));
|
||||
return { notify, push };
|
||||
}
|
||||
await scheduleEvent(tx, "raid_launch", due + (e!.firstRaidAfterHours * HOUR_MS), {}, baseId);
|
||||
@@ -79,7 +79,7 @@ async function foundingArrive(tx: Tx, m: MissionRowLike, plan: Mission, due: num
|
||||
await tx.update(tables.mission).set({ status: "done", returning: {}, cargoHome: {}, reportId, returnAt: new Date(due) }).where(eq(tables.mission.id, m.id));
|
||||
}
|
||||
await recordAchievement(tx, pid, "kolonien", 1, { atMs: due }); // Erfolg „Kolonist“
|
||||
push.push(pushNotice(pid, "report", title, "Dein neuer Hafen steht unter Gründungsschutz.", "berichte"));
|
||||
push.push(pushNotice(pid, "report", title, "Dein neuer Hafen steht unter Gründungsschutz.", "berichte", reportId));
|
||||
notify.push([null, "map"]);
|
||||
return { notify, push };
|
||||
}
|
||||
|
||||
@@ -254,13 +254,13 @@ export async function fieldArrive(tx: Tx, m: MissionRowLike, plan: Mission, orig
|
||||
} else {
|
||||
await sendHome(tx, m, plan, survivors, {}, reportId, due);
|
||||
}
|
||||
push.push(pushNotice(pid, "report", title, outcome === "captured" ? "Deine Besatzung hält das Feld." : "Der Verband kehrt heim.", "berichte"));
|
||||
push.push(pushNotice(pid, "report", title, outcome === "captured" ? "Deine Besatzung hält das Feld." : "Der Verband kehrt heim.", "berichte", reportId));
|
||||
if (prevOwner !== null) {
|
||||
const lost = destroyed;
|
||||
await systemMessage(tx, notify, [prevOwner], lost ? `${name} verloren` : `${name} gehalten`,
|
||||
lost ? `${attackerName} hat deine Besatzung auf ${name} geschlagen.${outcome === "captured" ? " Das Feld gehört jetzt ihm." : " Das Feld ist wieder neutral."}`
|
||||
: `Deine Besatzung auf ${name} hat den Angriff von ${attackerName} abgewiesen.`);
|
||||
push.push(pushNotice(prevOwner, "attack", lost ? `${name} verloren` : `${name} gehalten`, `Angreifer: ${attackerName}.`, "berichte"));
|
||||
push.push(pushNotice(prevOwner, "attack", lost ? `${name} verloren` : `${name} gehalten`, `Angreifer: ${attackerName}.`, "berichte", reportId));
|
||||
notify.push([[prevOwner], "reports"], [[prevOwner], "missions"], [[prevOwner], "base"]);
|
||||
}
|
||||
notify.push([null, "map"], [[pid], "reports"]);
|
||||
|
||||
@@ -49,7 +49,7 @@ export async function reinforceArrive(tx: Tx, m: MissionRowLike, plan: Mission,
|
||||
report: { field: { id: field.id, kind: field.kind, tier: field.tier, refused: refused ?? "field_lost" } },
|
||||
});
|
||||
await sendHome(tx, m, plan, units, {}, reportId, due);
|
||||
push.push(pushNotice(pid, "report", `Verstärkung für ${name} kehrt um`, refused === "field_has_admiral" ? "Die Besatzung hat schon einen Admiral." : "Das Feld wird nicht mehr von dir gehalten.", "berichte"));
|
||||
push.push(pushNotice(pid, "report", `Verstärkung für ${name} kehrt um`, refused === "field_has_admiral" ? "Die Besatzung hat schon einen Admiral." : "Das Feld wird nicht mehr von dir gehalten.", "berichte", reportId));
|
||||
notify.push([[pid], "reports"], [[pid], "missions"]);
|
||||
return;
|
||||
}
|
||||
@@ -83,6 +83,6 @@ export async function reinforceArrive(tx: Tx, m: MissionRowLike, plan: Mission,
|
||||
report: { field: { id: field.id, kind: field.kind, tier: field.tier, outcome: "reinforced", units, garrison } },
|
||||
});
|
||||
await tx.update(tables.mission).set({ status: "done", returning: {}, cargoHome: {}, reportId, returnAt: new Date(due) }).where(eq(tables.mission.id, m.id));
|
||||
push.push(pushNotice(pid, "report", `Verstärkung auf ${name} eingetroffen`, "Die Schiffe gehören jetzt zur Besatzung.", "berichte"));
|
||||
push.push(pushNotice(pid, "report", `Verstärkung auf ${name} eingetroffen`, "Die Schiffe gehören jetzt zur Besatzung.", "berichte", reportId));
|
||||
notify.push([[pid], "reports"], [[pid], "missions"], [[pid], "base"]);
|
||||
}
|
||||
@@ -165,12 +165,12 @@ async function fieldRaid(tx: Tx, payload: Record<string, unknown>, due: number):
|
||||
await tx.insert(tables.wreck).values({ col: f.col, row: f.row, stahl: report.wreck.stahl ?? 0, elektronik: report.wreck.elektronik ?? 0, createdAt: new Date(due) });
|
||||
}
|
||||
const title = destroyed ? `${name} an das Kartell verloren` : `Kartell vor ${name} abgewehrt`;
|
||||
await storeNavalReport(tx, {
|
||||
const reportId = await storeNavalReport(tx, {
|
||||
kind: "feld", title, attackerPlayerId: null, defenderPlayerId: owner, defenderBaseId: f.baseId, winner: destroyed ? "attacker" : "defender", seed, atMs: due,
|
||||
report: { field: { id: f.id, kind: f.kind, tier: f.tier, outcome: destroyed ? "cartel" : "held" }, battle: { ...report, loot: {} }, attackerName: "Freibeuter-Kartell", defenderName: "Besatzung", targetName: name, attacker: { units }, ...(admirals ? { admirals } : {}) },
|
||||
});
|
||||
await systemMessage(tx, notify, [owner], title, destroyed ? `Das Kartell hat deine Besatzung auf ${name} geschlagen. Das Feld ist wieder neutral.` : `Deine Besatzung auf ${name} hat den Kartellverband zurückgeschlagen.`);
|
||||
return { notify, push: [pushNotice(owner, "attack", title, destroyed ? "Das Feld ist wieder neutral." : "Das Feld bleibt deins.", "berichte")] };
|
||||
return { notify, push: [pushNotice(owner, "attack", title, destroyed ? "Das Feld ist wieder neutral." : "Das Feld bleibt deins.", "berichte", reportId)] };
|
||||
}
|
||||
|
||||
export const FIELD_HANDLERS: Record<string, (tx: Tx, ev: { payload: Record<string, unknown> }, due: number) => Promise<HandlerResult>> = {
|
||||
|
||||
@@ -19,6 +19,9 @@ export * from "./ops.ts";
|
||||
export * from "./push.ts";
|
||||
export * from "./mail.ts";
|
||||
export * from "./mail-templates.ts";
|
||||
// Ausführliche E-Mails: je Berichtsart ein Abschnitt (registerReportSection), Standard für unbekannte Arten
|
||||
export { genericBlocks, registerReportSection, reportMailFor, reportMailParts, type ReportMailParts, type ReportSection, type ReportView } from "./mail-reports.ts";
|
||||
export { attackWarningMail, defaultNoticeBlocks, digestBlocks } from "./mail-notices.ts";
|
||||
export * from "./notices.ts";
|
||||
export * from "./settings.ts";
|
||||
export * from "./invite.ts";
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
// Bausteine für ausführliche E-Mails: Ergebnis-Banner, Kennzahlen-Kacheln, Abschnittstitel, Tabellen, Listen.
|
||||
// Jeder Baustein hat eine HTML-Form (Tabellen-Layout, Inline-Styles, Klassen für Dunkelmodus) und eine Textform.
|
||||
import type { MailTheme } from "./mail-templates.ts";
|
||||
|
||||
/** Färbung: Sieg (grün), Niederlage (siegelrot), Warnung (bernstein), Hinweis (tinte). */
|
||||
export type Tone = "win" | "loss" | "warn" | "info";
|
||||
|
||||
/** Zelle einer Tabelle: Text oder Text mit Färbung/Hervorhebung. */
|
||||
export type Cell = string | { v: string; tone?: Tone; bold?: boolean; muted?: boolean };
|
||||
|
||||
export type MailBlock =
|
||||
| { type: "banner"; tone: Tone; kicker?: string; title: string; sub?: string }
|
||||
| { type: "tiles"; tiles: { label: string; value: string; tone?: Tone }[] }
|
||||
| { type: "section"; title: string }
|
||||
| {
|
||||
type: "table";
|
||||
head: string[];
|
||||
rows: Cell[][];
|
||||
/** Ausrichtung je Spalte; Vorgabe: erste links, übrige rechts. */
|
||||
align?: ("left" | "right")[];
|
||||
/** Summenzeile (abgesetzt). */
|
||||
foot?: Cell[];
|
||||
/** Höchstzahl Zeilen (Vorgabe 20); weitere werden gekürzt und mit Hinweis erwähnt. */
|
||||
maxRows?: number;
|
||||
caption?: string;
|
||||
}
|
||||
| { type: "facts"; facts: [string, string][] }
|
||||
| { type: "list"; items: string[] }
|
||||
| { type: "text"; text: string; tone?: "muted" | Tone };
|
||||
|
||||
export const MAX_TABLE_ROWS = 20;
|
||||
|
||||
const escHtml = (s: string) =>
|
||||
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
||||
|
||||
const cellText = (c: Cell): string => (typeof c === "string" ? c : c.v);
|
||||
|
||||
function toneColors(t: MailTheme, tone: Tone): { fg: string; bg: string } {
|
||||
switch (tone) {
|
||||
case "win": return { fg: t.win, bg: t.winBg };
|
||||
case "loss": return { fg: t.loss, bg: t.lossBg };
|
||||
case "warn": return { fg: t.warn, bg: t.warnBg };
|
||||
default: return { fg: t.text, bg: t.infoBg };
|
||||
}
|
||||
}
|
||||
|
||||
/** Zusätzliche Regeln im <style>-Block für den Dunkelmodus der Bausteine. */
|
||||
export function blockDarkCss(t: MailTheme): string {
|
||||
return [
|
||||
`.tf-tone-win{background:${t.darkWinBg}!important;border-color:${t.darkWin}!important;} .tf-c-win{color:${t.darkWin}!important;}`,
|
||||
`.tf-tone-loss{background:${t.darkLossBg}!important;border-color:${t.darkLoss}!important;} .tf-c-loss{color:${t.darkLoss}!important;}`,
|
||||
`.tf-tone-warn{background:${t.darkWarnBg}!important;border-color:${t.darkWarn}!important;} .tf-c-warn{color:${t.darkWarn}!important;}`,
|
||||
`.tf-tone-info{background:${t.darkInfoBg}!important;border-color:${t.darkLine}!important;} .tf-c-info{color:${t.darkText}!important;}`,
|
||||
`.tf-tile{background:${t.darkFactBg}!important;border-color:${t.darkLine}!important;}`,
|
||||
`.tf-row-alt td{background:${t.darkStripe}!important;} .tf-tbl,.tf-tbl td,.tf-tbl th{border-color:${t.darkLine}!important;}`,
|
||||
`.tf-th{color:${t.darkMuted}!important;} .tf-foot td{background:${t.darkFactBg}!important;} .tf-rule{border-color:${t.darkLine}!important;}`,
|
||||
].join("\n ");
|
||||
}
|
||||
|
||||
function renderTable(b: Extract<MailBlock, { type: "table" }>, t: MailTheme): string {
|
||||
const max = b.maxRows ?? MAX_TABLE_ROWS;
|
||||
const rows = b.rows.slice(0, max);
|
||||
const cut = b.rows.length - rows.length;
|
||||
const align = (i: number) => b.align?.[i] ?? (i === 0 ? "left" : "right");
|
||||
const td = (c: Cell, i: number, extra = "") => {
|
||||
const o = typeof c === "string" ? { v: c } : c;
|
||||
const right = align(i) === "right";
|
||||
const color = o.tone ? toneColors(t, o.tone).fg : o.muted ? t.muted : t.text;
|
||||
const cls = o.tone ? `tf-c-${o.tone}` : o.muted ? "tf-muted" : "tf-text";
|
||||
const font = right ? "font-family:'IBM Plex Mono',Menlo,Consolas,monospace;font-size:14px;" : "font-size:14px;";
|
||||
return `<td class="${cls}" align="${right ? "right" : "left"}" valign="top" style="padding:7px 8px;${font}line-height:19px;color:${color};border-top:1px solid ${t.line};${o.bold ? "font-weight:700;" : ""}${right ? "white-space:nowrap;" : ""}${extra}">${escHtml(o.v)}</td>`;
|
||||
};
|
||||
const head = b.head.length
|
||||
? `<tr>${b.head.map((h, i) => `<th class="tf-th" align="${align(i) === "right" ? "right" : "left"}" style="padding:6px 8px;font-size:11px;line-height:14px;letter-spacing:1px;text-transform:uppercase;font-weight:600;color:${t.muted};">${escHtml(h)}</th>`).join("")}</tr>`
|
||||
: "";
|
||||
const body = rows.map((r, k) => `<tr${k % 2 ? ` class="tf-row-alt"` : ""}>${r.map((c, i) => td(c, i, k % 2 ? `background:${t.stripe};` : "")).join("")}</tr>`).join("\n");
|
||||
const foot = b.foot ? `<tr class="tf-foot">${b.foot.map((c, i) => td(typeof c === "string" ? { v: c, bold: true } : { bold: true, ...c }, i, `background:${t.factBg};`)).join("")}</tr>` : "";
|
||||
const more = cut > 0
|
||||
? `<tr><td colspan="${Math.max(1, b.head.length || (b.rows[0]?.length ?? 1))}" class="tf-muted" style="padding:7px 8px;font-size:12px;color:${t.muted};border-top:1px solid ${t.line};">… und ${cut} weitere ${cut === 1 ? "Zeile" : "Zeilen"} – vollständig im Spiel.</td></tr>`
|
||||
: "";
|
||||
const caption = b.caption ? `<div class="tf-muted" style="font-size:12px;line-height:17px;color:${t.muted};margin:0 0 4px 0;">${escHtml(b.caption)}</div>` : "";
|
||||
return `${caption}<table role="presentation" width="100%" cellpadding="0" cellspacing="0" class="tf-tbl" style="margin:0 0 16px 0;border:1px solid ${t.line};border-radius:${t.radius};border-collapse:separate;font-family:${t.font};">
|
||||
${head}
|
||||
${body}
|
||||
${foot}${more}
|
||||
</table>`;
|
||||
}
|
||||
|
||||
function renderTiles(b: Extract<MailBlock, { type: "tiles" }>, t: MailTheme): string {
|
||||
const per = b.tiles.length === 4 ? 2 : Math.min(3, b.tiles.length);
|
||||
const rows: (typeof b.tiles)[] = [];
|
||||
for (let i = 0; i < b.tiles.length; i += per) rows.push(b.tiles.slice(i, i + per));
|
||||
const width = `${Math.floor(100 / per)}%`;
|
||||
const cell = (x: (typeof b.tiles)[number], last: boolean) => {
|
||||
const color = x.tone ? toneColors(t, x.tone).fg : t.text;
|
||||
return `<td width="${width}" valign="top" style="padding:0 ${last ? 0 : 8}px 8px 0;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" class="tf-tile" style="background:${t.factBg};border:1px solid ${t.line};border-radius:${t.radius};border-collapse:separate;"><tr><td style="padding:10px 12px;">
|
||||
<div class="tf-muted" style="font-size:11px;line-height:14px;letter-spacing:1px;text-transform:uppercase;color:${t.muted};">${escHtml(x.label)}</div>
|
||||
<div class="${x.tone ? `tf-c-${x.tone}` : "tf-text"}" style="margin-top:3px;font-family:'IBM Plex Mono',Menlo,Consolas,monospace;font-size:18px;line-height:23px;font-weight:700;color:${color};">${escHtml(x.value)}</div>
|
||||
</td></tr></table></td>`;
|
||||
};
|
||||
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 10px 0;">
|
||||
${rows.map((r) => `<tr>${r.map((x, i) => cell(x, i === r.length - 1)).join("")}${r.length < per ? `<td width="${width}"></td>`.repeat(per - r.length) : ""}</tr>`).join("\n")}
|
||||
</table>`;
|
||||
}
|
||||
|
||||
/** HTML eines Bausteins. */
|
||||
export function blockHtml(b: MailBlock, t: MailTheme): string {
|
||||
switch (b.type) {
|
||||
case "banner": {
|
||||
const c = toneColors(t, b.tone);
|
||||
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" class="tf-tone-${b.tone}" style="margin:0 0 16px 0;background:${c.bg};border-left:5px solid ${c.fg};border-radius:${t.radius};"><tr><td style="padding:14px 16px;font-family:${t.font};">
|
||||
${b.kicker ? `<div class="tf-c-${b.tone}" style="font-size:11px;line-height:14px;letter-spacing:2px;text-transform:uppercase;font-weight:700;color:${c.fg};">${escHtml(b.kicker)}</div>` : ""}
|
||||
<div class="tf-c-${b.tone}" style="font-family:${t.headingFont};font-size:28px;line-height:33px;font-weight:600;color:${c.fg};margin-top:2px;">${escHtml(b.title)}</div>
|
||||
${b.sub ? `<div class="tf-text" style="font-size:14px;line-height:20px;color:${t.text};margin-top:4px;">${escHtml(b.sub)}</div>` : ""}
|
||||
</td></tr></table>`;
|
||||
}
|
||||
case "tiles":
|
||||
return b.tiles.length ? renderTiles(b, t) : "";
|
||||
case "section":
|
||||
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:10px 0 8px 0;"><tr><td class="tf-text tf-rule" style="padding:0 0 5px 0;border-bottom:1px solid ${t.line};font-family:${t.headingFont};font-size:18px;line-height:23px;font-weight:600;color:${t.text};"><span class="tf-seal" style="color:${t.seal};font-size:12px;">◆</span> ${escHtml(b.title)}</td></tr></table>`;
|
||||
case "table":
|
||||
return renderTable(b, t);
|
||||
case "facts":
|
||||
return b.facts.length
|
||||
? `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" class="tf-facts" style="margin:0 0 16px 0;background:${t.factBg};border:1px solid ${t.line};border-radius:${t.radius};border-collapse:separate;">
|
||||
${b.facts.map(([k, v], i) => `<tr><td class="tf-muted" style="padding:8px 12px;font-size:13px;line-height:18px;color:${t.muted};${i ? `border-top:1px solid ${t.line};` : ""}">${escHtml(k)}</td><td class="tf-text" align="right" style="padding:8px 12px;font-size:14px;line-height:19px;font-weight:600;color:${t.text};${i ? `border-top:1px solid ${t.line};` : ""}">${escHtml(v)}</td></tr>`).join("\n")}
|
||||
</table>`
|
||||
: "";
|
||||
case "list":
|
||||
return b.items.length
|
||||
? `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 16px 0;">
|
||||
${b.items.map((s) => `<tr><td width="18" valign="top" class="tf-seal" style="padding:4px 0;color:${t.seal};font-size:12px;line-height:21px;">◆</td><td class="tf-text" style="padding:4px 0;font-size:15px;line-height:21px;color:${t.text};">${escHtml(s)}</td></tr>`).join("\n")}
|
||||
</table>`
|
||||
: "";
|
||||
case "text": {
|
||||
const tone = b.tone && b.tone !== "muted" ? b.tone : null;
|
||||
const color = tone ? toneColors(t, tone).fg : b.tone === "muted" ? t.muted : t.text;
|
||||
const cls = tone ? `tf-c-${tone}` : b.tone === "muted" ? "tf-muted" : "tf-text";
|
||||
const size = b.tone === "muted" ? "13px;line-height:19px" : "15px;line-height:22px";
|
||||
return `<p class="${cls}" style="margin:0 0 12px 0;font-size:${size};color:${color};">${escHtml(b.text)}</p>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Spalten auf gleiche Breite auffüllen (Textversion). */
|
||||
function textTable(head: string[], rows: string[][], align: (i: number) => "left" | "right"): string[] {
|
||||
const all = head.length ? [head, ...rows] : rows;
|
||||
const w = all.reduce<number[]>((acc, r) => r.map((c, i) => Math.max(acc[i] ?? 0, c.length)), []);
|
||||
const line = (r: string[]) => r.map((c, i) => (align(i) === "right" ? c.padStart(w[i]) : c.padEnd(w[i]))).join(" ").trimEnd();
|
||||
return [...(head.length ? [line(head), w.map((n) => "-".repeat(n)).join(" ")] : []), ...rows.map(line)];
|
||||
}
|
||||
|
||||
/** Textform eines Bausteins (Zeilen). */
|
||||
export function blockText(b: MailBlock): string[] {
|
||||
switch (b.type) {
|
||||
case "banner":
|
||||
return [`${b.kicker ? `${b.kicker} – ` : ""}${b.title}`, ...(b.sub ? [b.sub] : []), ""];
|
||||
case "tiles":
|
||||
return [...b.tiles.map((x) => `${x.label}: ${x.value}`), ""];
|
||||
case "section":
|
||||
return [b.title, "-".repeat(Math.min(40, b.title.length))];
|
||||
case "table": {
|
||||
const max = b.maxRows ?? MAX_TABLE_ROWS;
|
||||
const rows = b.rows.slice(0, max).map((r) => r.map(cellText));
|
||||
if (b.foot) rows.push(b.foot.map(cellText));
|
||||
const align = (i: number) => b.align?.[i] ?? (i === 0 ? "left" : "right");
|
||||
const cut = b.rows.length - Math.min(b.rows.length, max);
|
||||
return [
|
||||
...(b.caption ? [b.caption] : []),
|
||||
...textTable(b.head, rows, align),
|
||||
...(cut > 0 ? [`… und ${cut} weitere ${cut === 1 ? "Zeile" : "Zeilen"} – vollständig im Spiel.`] : []),
|
||||
"",
|
||||
];
|
||||
}
|
||||
case "facts":
|
||||
return [...b.facts.map(([k, v]) => `${k}: ${v}`), ""];
|
||||
case "list":
|
||||
return [...b.items.map((s) => `- ${s}`), ""];
|
||||
case "text":
|
||||
return [b.text, ""];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// E-Mails zu Benachrichtigungen ohne eigenen Bericht: Angriffswarnung mit empfohlenen Schritten, allgemeine
|
||||
// Meldungen (Kennzahlen als Kacheln) und gebündelte Meldungen (Tabelle mit Zeit). Inhalte nur aus dem, was der
|
||||
// Spieler im Spiel auch sieht.
|
||||
import {
|
||||
bunkerProtection, fleetSize, protectionStatus, settle, visibleUnitCount,
|
||||
type BaseState, type Counts, type Modifiers,
|
||||
} from "@tidefront/game-core";
|
||||
import { balance, type Notice } from "./context.ts";
|
||||
import type { MailBlock } from "./mail-blocks.ts";
|
||||
import { dateTime, int, sum, unitRows } from "./mail-report-kit.ts";
|
||||
import { clock, minutesText } from "./names.ts";
|
||||
|
||||
const SIZE_TEXT: Record<string, string> = { klein: "klein", mittel: "mittel", gross: "groß" };
|
||||
const PROTECTION_TEXT: Record<string, string> = {
|
||||
anfaengerschutz: "Anfängerschutz", gruendungsschutz: "Gründungsschutz", niederlage: "Schutz nach Niederlage", nachtschild: "Nachtschild",
|
||||
};
|
||||
|
||||
/**
|
||||
* Inhalt der Angriffswarnung (Notice.mail): Ankunft, Angreifer, Größenklasse (wie das Radar sie zeigt), Lage im Hafen
|
||||
* und empfohlene Schritte. Kartellverbände zeigt das Spiel genau, Spielerverbände nur als Größenklasse.
|
||||
*/
|
||||
export function attackWarningMail(input: {
|
||||
attacker: string; targetName: string; arriveAtMs: number; nowMs: number; units: Counts; kartell: boolean;
|
||||
state: BaseState; mods?: Modifiers;
|
||||
}): NonNullable<Notice["mail"]> {
|
||||
const s = settle(input.state, input.nowMs, balance, input.mods);
|
||||
const left = minutesText(input.arriveAtMs - input.nowMs);
|
||||
const ib = balance.intel;
|
||||
const size = ib ? SIZE_TEXT[fleetSize(visibleUnitCount(input.units, balance.units), ib)] : null;
|
||||
const shield = protectionStatus(s.protection, input.arriveAtMs, balance);
|
||||
const home = sum(s.units);
|
||||
const away = sum(s.unitsAway);
|
||||
const defs = sum(s.defenses);
|
||||
const prot = bunkerProtection(s, balance, input.mods);
|
||||
const exposed = Object.fromEntries(Object.entries(s.resources).map(([k, v]) => [k, Math.max(0, Math.floor(v) - prot)]));
|
||||
const steps: string[] = [];
|
||||
if (shield.protected) {
|
||||
steps.push(`Dein ${PROTECTION_TEXT[shield.reason ?? ""] ?? "Schutz"} gilt bei Ankunft – der Verband dreht voraussichtlich ohne Kampf ab.`);
|
||||
} else {
|
||||
steps.push(home > 0 ? `Truppen daheim lassen: ${int(home)} Einheiten und ${int(defs)} Anlagen verteidigen ${input.targetName}.` : `Keine Einheiten daheim – nur ${int(defs)} Anlagen verteidigen. Verbände zurückrufen oder neue ausbilden.`);
|
||||
if (away > 0) steps.push(`${int(away)} Einheiten sind unterwegs – zurückrufen, wenn sie vor ${clock(input.arriveAtMs)} Uhr heimkommen.`);
|
||||
if (sum(exposed) > 0) steps.push(`Vorräte über dem Bunkerschutz (${int(prot)} je Ressource) ausgeben oder verschicken – nur sie können geplündert werden.`);
|
||||
steps.push("Verbündete um Stationierung im Hafen bitten (Allianz).");
|
||||
if (s.protection.nightShieldStartHour === null) steps.push(`Nachtschild einrichten – wirkt erst nach ${balance.protection.nightShieldChangeHours} Std. Vorlauf, also für künftige Nächte.`);
|
||||
}
|
||||
const blocks: MailBlock[] = [
|
||||
{ type: "banner", tone: "warn", kicker: "Radar-Warnung", title: `Ankunft in ${left}`, sub: `${input.attacker} greift ${input.targetName} an · ${clock(input.arriveAtMs)} Uhr` },
|
||||
{ type: "tiles", tiles: [
|
||||
{ label: "Ankunft", value: clock(input.arriveAtMs), tone: "warn" },
|
||||
{ label: "Größe", value: size ?? "unbekannt" },
|
||||
{ label: "Schutz", value: shield.protected ? "aktiv" : "keiner", tone: shield.protected ? "win" : "loss" },
|
||||
] },
|
||||
{ type: "section", title: "Lage" },
|
||||
{ type: "facts", facts: [
|
||||
["Angreifer", input.attacker],
|
||||
["Ziel", input.targetName],
|
||||
["Ankunft", dateTime(input.arriveAtMs)],
|
||||
["Größenklasse (Radar)", size ?? "unbekannt"],
|
||||
["Einheiten daheim", int(home)],
|
||||
["Anlagen", int(defs)],
|
||||
["Bunkerschutz", `${int(prot)} je Ressource`],
|
||||
] },
|
||||
];
|
||||
if (input.kartell && sum(input.units) > 0) {
|
||||
blocks.push({ type: "section", title: "Kartellverband" }, { type: "table", head: ["Einheit", "Anzahl"], rows: unitRows(input.units) });
|
||||
}
|
||||
blocks.push({ type: "section", title: "Empfohlene Schritte" }, { type: "list", items: steps });
|
||||
return { subject: `⚠︎ Angriff auf ${input.targetName} in ${left}`, lead: `${input.attacker} greift ${input.targetName} an. Ankunft um ${clock(input.arriveAtMs)} Uhr.`, blocks };
|
||||
}
|
||||
|
||||
/** Standardinhalt einer Meldung: Kennzahlen als Kacheln (bis drei kurze), sonst als Liste. */
|
||||
export function defaultNoticeBlocks(n: Notice): MailBlock[] {
|
||||
const facts = n.facts ?? [];
|
||||
if (!facts.length) return [];
|
||||
const short = facts.length <= 3 && facts.every(([, v]) => v.length <= 14);
|
||||
return short ? [{ type: "tiles", tiles: facts.map(([label, value]) => ({ label, value })) }] : [{ type: "facts", facts }];
|
||||
}
|
||||
|
||||
const KIND_TEXT: Record<string, string> = {
|
||||
attack: "Angriff", report: "Bericht", build: "Ausbau", training: "Ausbildung", fleet: "Verband", delivery: "Lieferung", ops: "Betrieb", market: "Börse", test: "Test",
|
||||
};
|
||||
|
||||
/** Gebündelte Meldungen als Tabelle (Zeit | Art | Meldung), neueste zuletzt; Länge begrenzt die Tabelle selbst. */
|
||||
export function digestBlocks(rows: { kind: string; title: string; body: string; createdAt: Date }[]): MailBlock[] {
|
||||
const counts = new Map<string, number>();
|
||||
for (const r of rows) counts.set(r.kind, (counts.get(r.kind) ?? 0) + 1);
|
||||
return [
|
||||
{ type: "tiles", tiles: [...counts].slice(0, 3).map(([k, n]) => ({ label: KIND_TEXT[k] ?? k, value: String(n) })) },
|
||||
{ type: "table", head: ["Zeit", "Meldung"], align: ["left", "left"], rows: rows.map((r) => [{ v: clock(r.createdAt.getTime()), muted: true }, `${r.title}: ${r.body}`]) },
|
||||
];
|
||||
}
|
||||
|
||||
/** Kurzer Betreffteil der Bündelung: die häufigsten Titel, z. B. „Ausbau fertig (3), Lieferung angekommen“. */
|
||||
export function digestSubject(rows: { title: string }[]): string {
|
||||
const n = new Map<string, number>();
|
||||
for (const r of rows) n.set(r.title, (n.get(r.title) ?? 0) + 1);
|
||||
const top = [...n].sort((a, b) => b[1] - a[1]);
|
||||
const shown = top.slice(0, 2).map(([t, k]) => (k > 1 ? `${t} (${k})` : t));
|
||||
return top.length > 2 ? `${shown.join(", ")} u. a.` : shown.join(", ");
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// Kampfbericht in der E-Mail: Ergebnis-Banner, Kurzfazit, Kennzahlen, Verbände beider Seiten (Start → Verlust →
|
||||
// übrig), Beute, Wetter und Admirale. Gilt für jede Berichtsart mit Kampfdaten (Überfall, Kartell, Nest, Feld,
|
||||
// Weltereignis, See, Sammelangriff …) – auch für künftige Arten, solange sie `battle` mitliefern.
|
||||
import type { Cell, MailBlock } from "./mail-blocks.ts";
|
||||
import {
|
||||
counts, dateTime, int, kindLabel, num, pct, registerReportSection, resText, resourceRows, str, sum, unitLabel,
|
||||
type Counts, type ReportCtx, type ReportView,
|
||||
} from "./mail-report-kit.ts";
|
||||
import { nameOf } from "./names.ts";
|
||||
|
||||
interface Outcome { before?: Counts; losses?: Counts; returned?: Counts; final?: Counts; survivors?: Counts }
|
||||
interface Battle {
|
||||
winner?: string;
|
||||
airSuperiority?: string | null;
|
||||
landed?: boolean;
|
||||
attacker?: Outcome;
|
||||
defender?: Outcome;
|
||||
loot?: Counts;
|
||||
wreck?: Counts;
|
||||
weather?: { air: number; strike: number; wind: number; clouds: number; storm: boolean };
|
||||
phases?: { phase: string; skipped: boolean }[];
|
||||
}
|
||||
interface AdmiralSide { name?: string; rankName?: string; xpGain?: number; xp?: number; promoted?: string | null; lossShare?: number; roll?: number | null; fate?: string; until?: number | null }
|
||||
|
||||
const FATE: Record<string, string> = { unversehrt: "unversehrt", verwundet: "verwundet", gefangen: "in Gefangenschaft geraten", gefallen: "gefallen" };
|
||||
|
||||
const side = (o: Outcome | undefined) => {
|
||||
const before = counts(o?.before);
|
||||
const final = o?.final ? counts(o.final) : null;
|
||||
const losses = o?.losses ? counts(o.losses) : null;
|
||||
// Endgültiger Verlust: Start − übrig (Rückkehrer aus Lazarett/Reparatur zählen nicht als verloren).
|
||||
const lost = (id: string) => (final ? Math.max(0, (before[id] ?? 0) - (final[id] ?? 0)) : losses?.[id] ?? 0);
|
||||
const left = (id: string) => final?.[id] ?? Math.max(0, (before[id] ?? 0) - lost(id));
|
||||
return { before, lost, left, returned: counts(o?.returned) };
|
||||
};
|
||||
|
||||
/** Tabelle eines Verbands: Einheit | Start | Verlust | übrig, mit Summenzeile. */
|
||||
function forceTable(title: string, o: Outcome | undefined, vets: Record<string, string>): MailBlock[] {
|
||||
const s = side(o);
|
||||
const ids = Object.keys(s.before).filter((id) => (s.before[id] ?? 0) > 0).sort((a, b) => s.before[b] - s.before[a]);
|
||||
if (!ids.length) return [{ type: "section", title }, { type: "text", text: "Keine Einheiten im Kampf.", tone: "muted" }];
|
||||
const rows: Cell[][] = ids.map((id) => {
|
||||
const lost = s.lost(id);
|
||||
return [vets[id] ? `${unitLabel(id)} · ${vets[id]}` : unitLabel(id), int(s.before[id]), lost > 0 ? { v: `−${int(lost)}`, tone: "loss" } : { v: "±0", muted: true }, int(s.left(id))];
|
||||
});
|
||||
const totalLost = ids.reduce((n, id) => n + s.lost(id), 0);
|
||||
const totalLeft = ids.reduce((n, id) => n + s.left(id), 0);
|
||||
const back = sum(s.returned);
|
||||
return [
|
||||
{ type: "section", title },
|
||||
{
|
||||
type: "table", head: ["Einheit", "Start", "Verlust", "Übrig"], rows,
|
||||
foot: ids.length > 1 ? ["Gesamt", int(sum(s.before)), totalLost > 0 ? { v: `−${int(totalLost)}`, tone: "loss" } : "±0", int(totalLeft)] : undefined,
|
||||
caption: back > 0 ? `Zurück aus Lazarett/Reparatur (in „Übrig“ enthalten): ${resText(s.returned, "–", 6)}` : undefined,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const weatherText = (w: Battle["weather"]) =>
|
||||
!w ? null : `${w.storm ? "Sturm" : `Wind ${Math.round(w.wind * 100)} %`}, Wolken ${Math.round(w.clouds * 100)} %${w.air < 0.995 || w.strike < 0.995 ? ` – Flugzeuge ×${w.air.toFixed(2)}, Luftschlag ×${(w.air * w.strike).toFixed(2)}` : " – ohne Einfluss"}`;
|
||||
|
||||
function admiralLines(who: string, a: AdmiralSide | undefined): string[] {
|
||||
if (!a) return [];
|
||||
const parts = [`${who}: ${str(a.rankName)} ${str(a.name)}`.trim()];
|
||||
parts.push((a.xpGain ?? 0) > 0 ? `Erfahrung +${int(a.xpGain!)} (jetzt ${int(a.xp ?? 0)})` : "keine Erfahrung");
|
||||
if (a.promoted) parts.push(`befördert zum ${a.promoted}`);
|
||||
if (a.roll !== null && a.roll !== undefined) parts.push(`Schicksal: ${FATE[a.fate ?? ""] ?? str(a.fate, "?")}${a.until ? ` bis ${dateTime(a.until)}` : ""}`);
|
||||
else parts.push(FATE[a.fate ?? ""] ?? "unversehrt");
|
||||
return [parts.join(" · ")];
|
||||
}
|
||||
|
||||
/** Eigene Sicht: Sieg/Niederlage, Verlustanteil, Beute bzw. Plünderung. */
|
||||
export function battleSummary(r: ReportView) {
|
||||
const b = r.data.battle as Battle;
|
||||
const mine: "attacker" | "defender" = r.role === "defender" ? "defender" : "attacker";
|
||||
const theirs = mine === "attacker" ? "defender" : "attacker";
|
||||
const won = (b.winner === "attacker") === (mine === "attacker");
|
||||
const own = side(b[mine]);
|
||||
const foe = side(b[theirs]);
|
||||
const ownBefore = sum(own.before);
|
||||
const ownLost = Object.keys(own.before).reduce((n, id) => n + own.lost(id), 0);
|
||||
const foeBefore = sum(foe.before);
|
||||
const foeLost = Object.keys(foe.before).reduce((n, id) => n + foe.lost(id), 0);
|
||||
return { b, mine, won, ownBefore, ownLost, foeBefore, foeLost, loot: counts(b.loot) };
|
||||
}
|
||||
|
||||
function renderBattle(r: ReportView, ctx: ReportCtx) {
|
||||
const d = r.data;
|
||||
const { b, mine, won, ownBefore, ownLost, foeBefore, foeLost, loot } = battleSummary(r);
|
||||
const names = [str(d.attackerName, "Angreifer"), str(d.defenderName, "Verteidiger")];
|
||||
const target = str(d.targetName, r.title);
|
||||
const lootSum = sum(loot);
|
||||
const gain = mine === "attacker";
|
||||
const lossShare = pct(ownLost, ownBefore);
|
||||
const fazit = gain
|
||||
? won ? `Gewonnen mit ${lossShare} Verlust${lootSum > 0 ? `, Beute ${resText(loot)}` : ""}.` : `Verloren – ${lossShare} der eigenen Einheiten sind gefallen.`
|
||||
: won ? `${names[0]} abgewehrt, eigene Verluste ${lossShare}.` : `${target} verloren – ${lootSum > 0 ? `${resText(loot)} geplündert` : "nichts geplündert"}, eigene Verluste ${lossShare}.`;
|
||||
const subject = gain
|
||||
? won ? `Sieg bei ${target}${lootSum > 0 ? ` – Beute ${resText(loot, "", 2)}` : ""}` : `Niederlage bei ${target} – ${lossShare} Verlust`
|
||||
: won ? `${target} gehalten – ${names[0]} abgewehrt` : `${target} überwunden${lootSum > 0 ? ` – ${resText(loot, "", 2)} geplündert` : ""}`;
|
||||
|
||||
const blocks: MailBlock[] = [
|
||||
{ type: "banner", tone: won ? "win" : "loss", kicker: `Kampfbericht · ${kindLabel(r.kind)}`, title: won ? (gain ? "Sieg" : "Abgewehrt") : gain ? "Niederlage" : "Verloren", sub: `${names[0]} gegen ${names[1]} · ${target} · ${dateTime(r.atMs)}` },
|
||||
{ type: "text", text: fazit },
|
||||
{
|
||||
type: "tiles", tiles: [
|
||||
{ label: "Verluste", value: `${lossShare}`, tone: ownLost > 0 ? "loss" : "win" },
|
||||
{ label: "Gegner", value: pct(foeLost, foeBefore), tone: foeLost > 0 ? "win" : undefined },
|
||||
{ label: gain ? "Beute" : "Geplündert", value: lootSum > 0 ? `${gain ? "+" : "−"}${int(lootSum)}` : "0", tone: lootSum > 0 ? (gain ? "win" : "loss") : undefined },
|
||||
],
|
||||
},
|
||||
];
|
||||
const vets = (who: "attacker" | "defender") => (who === mine ? ctx.veterans : {});
|
||||
blocks.push(...forceTable(`Verband ${names[0]}${mine === "attacker" ? " (du)" : ""}`, b.attacker, vets("attacker")));
|
||||
blocks.push(...forceTable(`${mine === "defender" ? "Verteidigung" : "Gegner"} ${names[1]}${mine === "defender" ? " (du)" : ""}`, b.defender, vets("defender")));
|
||||
|
||||
blocks.push({ type: "section", title: gain ? "Beute" : "Plünderung" });
|
||||
const lootRows = resourceRows(loot, gain ? "+" : "−").map((row) => [row[0], { v: row[1] as string, tone: gain ? "win" : "loss" }] as Cell[]);
|
||||
if (lootRows.length) blocks.push({ type: "table", head: ["Ressource", "Menge"], rows: lootRows, foot: lootRows.length > 1 ? ["Gesamt", `${gain ? "+" : "−"}${int(lootSum)}`] : undefined });
|
||||
else blocks.push({ type: "text", text: gain ? "Keine Beute." : "Nichts geplündert.", tone: "muted" });
|
||||
const facts: [string, string][] = [];
|
||||
const salvage = counts(d.salvage);
|
||||
if (gain && sum(salvage) > 0) facts.push(["Zusätzlich geborgen (Wrackgut)", resText(salvage)]);
|
||||
const prot = num(d.protectedPerResource);
|
||||
if (prot !== null) facts.push([`Bunkerschutz ${names[1]}`, `${int(prot)} je Ressource`]);
|
||||
facts.push(["Neues Wrackfeld am Kampfort", resText(counts(b.wreck), "keins")]);
|
||||
|
||||
facts.push(["Luftüberlegenheit", b.airSuperiority === "attacker" ? names[0] : b.airSuperiority === "defender" ? names[1] : "keine"]);
|
||||
facts.push(["Landung", b.landed ? "ja" : "nein"]);
|
||||
const w = weatherText(b.weather);
|
||||
if (w) facts.push(["Wetter", w]);
|
||||
const phases = (b.phases ?? []).filter((p) => !p.skipped).map((p) => nameOf(p.phase));
|
||||
if (phases.length) facts.push(["Phasen", phases.join(" → ")]);
|
||||
blocks.push({ type: "section", title: "Lage" }, { type: "facts", facts });
|
||||
|
||||
const adm = d.admirals as { attacker?: AdmiralSide; defender?: AdmiralSide } | undefined;
|
||||
const admLines = adm ? [...admiralLines(names[0], adm.attacker), ...admiralLines(names[1], adm.defender)] : [];
|
||||
if (admLines.length) blocks.push({ type: "section", title: "Admirale" }, { type: "list", items: admLines });
|
||||
return { blocks, subject, lead: fazit };
|
||||
}
|
||||
|
||||
registerReportSection({ id: "battle", applies: (r) => !!r.data.battle && r.kind !== "spionage", render: renderBattle });
|
||||
@@ -0,0 +1,183 @@
|
||||
// Aufklärung, Spionage und Felder in der E-Mail: Lagebild des Ziels genau so, wie der Bericht es im Spiel zeigt
|
||||
// (inklusive Unsicherheit bei Nebel; Desinformation ist für den Leser nicht erkennbar und bleibt es auch hier).
|
||||
import type { Cell, MailBlock } from "./mail-blocks.ts";
|
||||
import {
|
||||
counts, dateTime, int, nOf, num, registerReportSection, resText, resourceRows, str, sum, unitTable,
|
||||
type Counts, type ReportView,
|
||||
} from "./mail-report-kit.ts";
|
||||
import { nameOf } from "./names.ts";
|
||||
|
||||
interface Scout { resources?: Counts; units?: Counts; defenses?: Counts; buildings?: Counts; protectedPerResource?: number; uncertain?: { fog: number; heavy: boolean } }
|
||||
|
||||
/** Lagebild eines Hafens: Kennzahlen, Bestände, Einheiten, Anlagen, Gebäude. */
|
||||
export function scoutBlocks(s: Scout, opts: { atMs?: number } = {}): MailBlock[] {
|
||||
const units = counts(s.units);
|
||||
const defs = counts(s.defenses);
|
||||
const res = counts(s.resources);
|
||||
const blocks: MailBlock[] = [
|
||||
{ type: "tiles", tiles: [
|
||||
{ label: "Einheiten", value: int(sum(units)) },
|
||||
{ label: "Anlagen", value: int(sum(defs)) },
|
||||
{ label: "Bestände", value: int(sum(res)) },
|
||||
] },
|
||||
];
|
||||
if (s.uncertain) {
|
||||
blocks.push({ type: "text", tone: "warn", text: `Sichtung unsicher – Nebel am Ziel (${Math.round(s.uncertain.fog * 100)} %): Bestände, Einheiten und Anlagen nur ${s.uncertain.heavy ? "grob " : ""}gerundet, Gebäude genau.` });
|
||||
}
|
||||
blocks.push({ type: "section", title: "Bestände" });
|
||||
const rows = resourceRows(res);
|
||||
blocks.push(rows.length ? { type: "table", head: ["Ressource", "Menge"], rows } : { type: "text", text: "Keine Vorräte.", tone: "muted" });
|
||||
const prot = num(s.protectedPerResource);
|
||||
if (prot !== null) blocks.push({ type: "text", tone: "muted", text: `Bunkerschutz: ${int(prot)} je Ressource – davon ist nichts zu erbeuten.` });
|
||||
blocks.push(...unitTable("Einheiten", units), ...unitTable("Anlagen", defs, ["Anlage", "Anzahl"]));
|
||||
const b = Object.entries(counts(s.buildings)).filter(([, l]) => l > 0).sort((a, c) => c[1] - a[1]);
|
||||
if (b.length) blocks.push({ type: "section", title: "Gebäude" }, { type: "table", head: ["Gebäude", "Stufe"], rows: b.map(([id, l]) => [nameOf(id), String(l)]) });
|
||||
if (opts.atMs) blocks.push({ type: "text", tone: "muted", text: `Stand der Sichtung: ${dateTime(opts.atMs)}.` });
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function renderScout(r: ReportView) {
|
||||
const d = r.data;
|
||||
const s = d.scout as Scout;
|
||||
const target = str(d.targetName, r.title.replace(/^Aufklärung: /, ""));
|
||||
const owner = str(d.owner);
|
||||
const units = sum(counts(s.units));
|
||||
const defs = sum(counts(s.defenses));
|
||||
const lead = `Lagebild von ${target}${owner ? ` (${owner})` : ""}: ${nOf(units, "Einheit", "Einheiten")}, ${nOf(defs, "Anlage", "Anlagen")}, Vorräte ${resText(counts(s.resources), "keine", 2)}`.replace(/\.?$/, ".");
|
||||
return {
|
||||
subject: `Aufklärung: ${target} – ${nOf(units, "Einheit", "Einheiten")}, ${nOf(defs, "Anlage", "Anlagen")}${s.uncertain ? " (unsicher)" : ""}`,
|
||||
lead,
|
||||
blocks: [
|
||||
{ type: "banner", tone: "info", kicker: "Aufklärung", title: target, sub: `${owner ? `${owner} · ` : ""}${dateTime(r.atMs)}` } as MailBlock,
|
||||
...scoutBlocks(s),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function renderNest(r: ReportView) {
|
||||
const n = r.data.nest as { level?: number; empty?: boolean; garrison?: { units?: Counts; defenses?: Counts; loot?: Counts } | null };
|
||||
const level = num(n.level);
|
||||
const title = `Piratennest${level !== null ? ` Stufe ${level}` : ""}`;
|
||||
const banner: MailBlock = { type: "banner", tone: "info", kicker: "Aufklärung", title, sub: dateTime(r.atMs) };
|
||||
if (n.empty || !n.garrison) return { subject: `Aufklärung: ${title} – verlassen`, lead: "Das Nest ist verlassen.", blocks: [banner, { type: "text", text: "Das Nest ist verlassen." } as MailBlock] };
|
||||
const g = n.garrison;
|
||||
const loot = counts(g.loot);
|
||||
return {
|
||||
subject: `Aufklärung: ${title} – ${int(sum(counts(g.units)))} Mann, Beute ${resText(loot, "keine", 1)}`,
|
||||
lead: `Besatzung ${nOf(sum(counts(g.units)), "Einheit", "Einheiten")}, ${nOf(sum(counts(g.defenses)), "Anlage", "Anlagen")}, Beute ${resText(loot)}`.replace(/\.?$/, "."),
|
||||
blocks: [
|
||||
banner,
|
||||
{ type: "tiles", tiles: [
|
||||
{ label: "Besatzung", value: int(sum(counts(g.units))) },
|
||||
{ label: "Anlagen", value: int(sum(counts(g.defenses))) },
|
||||
{ label: "Beute", value: int(sum(loot)), tone: "win" },
|
||||
] } as MailBlock,
|
||||
...unitTable("Besatzung", counts(g.units)),
|
||||
...unitTable("Anlagen", counts(g.defenses), ["Anlage", "Anzahl"]),
|
||||
{ type: "section", title: "Mögliche Beute" } as MailBlock,
|
||||
{ type: "table", head: ["Ressource", "Menge"], rows: resourceRows(loot) } as MailBlock,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const FIELD_KIND: Record<string, string> = { oelfeld: "Ölfeld", erzbucht: "Erzbucht", fischgrund: "Fischgrund", elektronikwrack: "Elektronik-Wrack" };
|
||||
const OUTCOME_TEXT: Record<string, string> = {
|
||||
captured: "Feld besetzt – deine Besatzung hält es, der Rest des Verbands fährt heim.",
|
||||
cleared: "Wache bzw. Besatzung geschlagen, aber die Überlebenden reichen nicht für eine Besatzung. Das Feld ist neutral.",
|
||||
limit: "Feld freigekämpft, aber die Höchstzahl deiner Felder ist erreicht. Das Feld ist neutral.",
|
||||
held: "Der Angriff wurde abgewiesen.",
|
||||
cartel: "Das Kartell hat die Besatzung geschlagen. Das Feld ist wieder neutral.",
|
||||
reinforced: "Die Verstärkung ist eingetroffen und gehört jetzt zur Besatzung.",
|
||||
};
|
||||
const REFUSED: Record<string, string> = {
|
||||
own_field: "das Feld gehört dir schon", fleet_lost: "keine Schiffe mehr im Verband", field_lost: "das Feld wird nicht mehr von dir gehalten",
|
||||
};
|
||||
|
||||
function renderField(r: ReportView) {
|
||||
const f = r.data.field as { kind?: string; tier?: number; owner?: string | null; units?: Counts; garrison?: Counts; outcome?: string; refused?: string; gone?: boolean };
|
||||
if (f.gone) return { blocks: [{ type: "text", text: "Das Feld gibt es nicht mehr (Saisonwechsel oder neu verteilt). Der Verband kehrt um." } as MailBlock] };
|
||||
const name = `${FIELD_KIND[f.kind ?? ""] ?? "Rohstofffeld"}${f.tier ? ` (Stufe ${f.tier})` : ""}`;
|
||||
const blocks: MailBlock[] = [];
|
||||
const scouting = r.kind === "aufklaerung";
|
||||
if (scouting) blocks.push({ type: "banner", tone: "info", kicker: "Feld-Aufklärung", title: name, sub: `${f.owner ? `Besatzung von ${f.owner}` : "Kartell-Wache"} · ${dateTime(r.atMs)}` });
|
||||
if (f.refused) blocks.push({ type: "text", text: `Nicht besetzt: ${REFUSED[f.refused] ?? "Verbündete und Paktpartner greift man nicht an"}.` });
|
||||
if (f.outcome && OUTCOME_TEXT[f.outcome]) blocks.push({ type: "text", text: OUTCOME_TEXT[f.outcome] });
|
||||
if (f.outcome === "reinforced" && f.garrison) blocks.push(...unitTable("Besatzung jetzt", counts(f.garrison)));
|
||||
const units = f.units ? counts(f.units) : null;
|
||||
if (units && !r.data.battle) blocks.push(...unitTable(f.outcome === "reinforced" ? "Verstärkung" : f.owner ? `Besatzung von ${f.owner}` : "Kartell-Wache", units));
|
||||
if (scouting && units) {
|
||||
const n = sum(units);
|
||||
return {
|
||||
subject: `Aufklärung: ${name} – ${n ? `${f.owner ? "Besatzung" : "Wache"} ${nOf(n, "Einheit", "Einheiten")}` : "unbewacht"}`,
|
||||
lead: `${name}: ${n ? `${f.owner ? `Besatzung von ${f.owner}` : "Kartell-Wache"} mit ${nOf(n, "Einheit", "Einheiten")}` : "keine Wache"}.`,
|
||||
blocks,
|
||||
};
|
||||
}
|
||||
return { blocks };
|
||||
}
|
||||
|
||||
interface SpyData { kind?: string; building?: string | null; spies?: number; targetName?: string; owner?: string; from?: string; roll?: number; die?: number; threshold?: number; success?: boolean; aborted?: string }
|
||||
const SPY_KIND: Record<string, string> = { erkunden: "Erkunden", sabotage: "Sabotage", desinformation: "Desinformation", kartell: "Kartell-Aufklärung" };
|
||||
|
||||
function renderSpy(r: ReportView) {
|
||||
const d = r.data;
|
||||
const s = d.spy as SpyData;
|
||||
const what = `${SPY_KIND[s.kind ?? ""] ?? "Spionage"}${s.building ? ` (${nameOf(s.building)})` : ""}`;
|
||||
const spies = `${int(s.spies ?? 0)} ${s.spies === 1 ? "Spion" : "Spione"}`;
|
||||
const blocks: MailBlock[] = [];
|
||||
if (r.role === "defender") {
|
||||
blocks.push(
|
||||
{ type: "banner", tone: "win", kicker: "Spionageabwehr", title: "Fremder Spion enttarnt", sub: `Absender ${str(s.from, "?")} · ${dateTime(r.atMs)}` },
|
||||
{ type: "facts", facts: [["Absender", str(s.from, "?")], ["Auftrag", what], ["Ausgeschaltet", spies]] },
|
||||
);
|
||||
return { subject: `Fremder Spion enttarnt – Absender ${str(s.from, "?")}`, lead: `${str(s.from, "?")} wollte ${what}. ${spies} ausgeschaltet.`, blocks };
|
||||
}
|
||||
const ok = !s.aborted && !!s.success;
|
||||
const result = s.aborted ?? (ok ? "Der Auftrag ist gelungen; das Ziel hat nichts bemerkt." : `Enttarnt – ${s.spies === 1 ? "der Spion ist" : "die Spione sind"} verloren${s.kind === "kartell" ? "." : ", das Ziel kennt jetzt deinen Namen."}`);
|
||||
blocks.push(
|
||||
{ type: "banner", tone: s.aborted ? "info" : ok ? "win" : "loss", kicker: `Spionage · ${what}`, title: s.aborted ? "Abgebrochen" : ok ? "Gelungen" : "Enttarnt", sub: `${str(s.targetName, "?")}${s.owner && s.kind !== "kartell" ? ` (${s.owner})` : ""} · ${dateTime(r.atMs)}` },
|
||||
{ type: "text", text: result },
|
||||
);
|
||||
if (s.roll !== undefined) blocks.push({ type: "facts", facts: [["Wurf", `W${s.die ?? 20}: ${s.roll} ${ok ? "≤" : ">"} Zielzahl ${s.threshold ?? "?"}`], ["Eingesetzt", spies]] });
|
||||
const dossier = d.dossier as { scout?: Scout; research?: { order?: { name: string; targetLevel: number; finishesAt: number } | null } | null; buildQueue?: { buildingId: string; targetLevel: number; finishesAt: number }[]; trainingQueue?: { id: string; count: number; finishesAt: number }[]; veterans?: { id: string; rankName: string }[] } | undefined;
|
||||
if (dossier?.scout) {
|
||||
blocks.push({ type: "section", title: "Dossier" }, ...scoutBlocks(dossier.scout));
|
||||
const queue: Cell[][] = [
|
||||
...(dossier.buildQueue ?? []).map((o) => [`Ausbau ${nameOf(o.buildingId)} ${o.targetLevel}`, dateTime(o.finishesAt)] as Cell[]),
|
||||
...(dossier.trainingQueue ?? []).map((o) => [`${int(o.count)} × ${nameOf(o.id)}`, dateTime(o.finishesAt)] as Cell[]),
|
||||
...(dossier.research?.order ? [[`Forschung ${dossier.research.order.name} ${dossier.research.order.targetLevel}`, dateTime(dossier.research.order.finishesAt)] as Cell[]] : []),
|
||||
];
|
||||
if (queue.length) blocks.push({ type: "section", title: "Aufträge des Ziels" }, { type: "table", head: ["Auftrag", "fertig"], rows: queue });
|
||||
if (dossier.veterans?.length) blocks.push({ type: "list", items: [`Veteranen: ${dossier.veterans.map((v) => `${nameOf(v.id)}: ${v.rankName}`).join(", ")}`] });
|
||||
}
|
||||
if (d.sabotage) blocks.push({ type: "section", title: "Sabotage" }, { type: "text", text: str((d.sabotage as { effect?: string }).effect) });
|
||||
if (d.disinfo) {
|
||||
const x = d.disinfo as { untilMs: number; forceFactor: number };
|
||||
blocks.push({ type: "section", title: "Desinformation ausgelegt" }, { type: "text", text: `Bis ${dateTime(x.untilMs)} sieht ${str(s.targetName, "das Ziel")} im nächsten Lagebild über dich etwa ${(x.forceFactor ?? 1).toLocaleString("de-DE", { maximumFractionDigits: 1 })}-mal so viele Truppen und Anlagen und nur einen Bruchteil deiner Vorräte.` });
|
||||
}
|
||||
const cartel = d.cartel as { next?: { atMs: number; kind: string | null } | null; events?: { name: string; position: { col: number; row: number }; endsAtMs: number; units: Counts }[] } | undefined;
|
||||
if (cartel) {
|
||||
blocks.push({ type: "section", title: "Aus dem Kartell" }, { type: "text", text: cartel.next ? `Nächstes Unternehmen: ${cartel.next.kind ? nameOf(cartel.next.kind) : "unbekannt"} um ${dateTime(cartel.next.atMs)}.` : "Kein weiteres Unternehmen geplant." });
|
||||
if (cartel.events?.length) blocks.push({ type: "table", head: ["Ereignis", "Feld", "Stärke", "endet"], align: ["left", "right", "right", "right"], rows: cartel.events.map((e) => [e.name, `${e.position.col}/${e.position.row}`, int(sum(e.units)), dateTime(e.endsAtMs)]) });
|
||||
}
|
||||
return { subject: `Spionage: ${what} gegen ${str(s.targetName, "?")} – ${s.aborted ? "abgebrochen" : ok ? "gelungen" : "enttarnt"}`, lead: result, blocks };
|
||||
}
|
||||
|
||||
function renderSabotageVictim(r: ReportView) {
|
||||
const s = r.data.sabotage as { target?: string; untilMs?: number; effect?: string };
|
||||
return {
|
||||
subject: `Sabotage: ${nameOf(str(s.target, "?"))}`,
|
||||
lead: str(s.effect),
|
||||
blocks: [
|
||||
{ type: "banner", tone: "loss", kicker: "Sabotage", title: nameOf(str(s.target, "?")), sub: dateTime(r.atMs) } as MailBlock,
|
||||
{ type: "text", text: `${str(s.effect)} Der Täter ist unbekannt.` } as MailBlock,
|
||||
...(s.untilMs ? [{ type: "facts", facts: [["Wirkt bis", dateTime(s.untilMs)]] } as MailBlock] : []),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
registerReportSection({ id: "scout", applies: (r) => !!r.data.scout && r.kind !== "spionage", render: renderScout });
|
||||
registerReportSection({ id: "nest", applies: (r) => !!r.data.nest, render: renderNest });
|
||||
registerReportSection({ id: "field", applies: (r) => !!r.data.field, render: renderField });
|
||||
registerReportSection({ id: "spy", applies: (r) => r.kind === "spionage" && !!r.data.spy, render: renderSpy });
|
||||
registerReportSection({ id: "sabotage", applies: (r) => r.kind === "sabotage" && !!r.data.sabotage, render: renderSabotageVictim });
|
||||
@@ -0,0 +1,144 @@
|
||||
// Werkzeug für ausführliche Bericht-Mails: Abschnitts-Register (je Berichtsart bzw. Datenteil ein Renderer),
|
||||
// Formatierung von Zahlen, Zeiten, Einheiten (mit Textsymbol) und Ressourcen. Neue Berichtsarten melden hier
|
||||
// einen eigenen Abschnitt an (registerReportSection); ohne eigenen Abschnitt greift der Standard in mail-reports.ts.
|
||||
import { balance } from "./context.ts";
|
||||
import type { Cell, MailBlock } from "./mail-blocks.ts";
|
||||
import { fmtInt, nameOf } from "./names.ts";
|
||||
|
||||
export type Counts = Record<string, number>;
|
||||
|
||||
/** Bericht aus Sicht des Lesers – dieselben Daten, die das Spiel ihm zeigt (views.reportGet). */
|
||||
export interface ReportView {
|
||||
id: number;
|
||||
kind: string;
|
||||
title: string;
|
||||
atMs: number;
|
||||
role: "attacker" | "defender" | "recipient";
|
||||
winner: string | null;
|
||||
data: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Zusatzwissen des Lesers: Veteranenränge der eigenen Einheiten (wie im Spiel unter Truppen). */
|
||||
export interface ReportCtx {
|
||||
veterans: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface SectionOut {
|
||||
blocks: MailBlock[];
|
||||
/** Betreff ohne Spielnamen; der erste Abschnitt mit Betreff gewinnt. */
|
||||
subject?: string;
|
||||
/** Kurzer Satz unter der Überschrift (und Vorschauzeile). */
|
||||
lead?: string;
|
||||
}
|
||||
|
||||
export interface ReportSection {
|
||||
id: string;
|
||||
applies: (r: ReportView) => boolean;
|
||||
render: (r: ReportView, ctx: ReportCtx) => SectionOut | null;
|
||||
}
|
||||
|
||||
const sections: ReportSection[] = [];
|
||||
|
||||
/** Meldet einen Abschnitt an; gleiche id ersetzt den alten (Reihenfolge bleibt). */
|
||||
export function registerReportSection(s: ReportSection): void {
|
||||
const i = sections.findIndex((x) => x.id === s.id);
|
||||
if (i >= 0) sections[i] = s;
|
||||
else sections.push(s);
|
||||
}
|
||||
|
||||
export function reportSections(): readonly ReportSection[] {
|
||||
return sections;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Formatierung
|
||||
|
||||
export const isCounts = (v: unknown): v is Counts =>
|
||||
!!v && typeof v === "object" && !Array.isArray(v) && Object.values(v as object).every((x) => typeof x === "number");
|
||||
|
||||
export const counts = (v: unknown): Counts => (isCounts(v) ? v : {});
|
||||
|
||||
export function sum(c: Counts | null | undefined): number {
|
||||
let n = 0;
|
||||
for (const v of Object.values(c ?? {})) if (Number.isFinite(v) && v > 0) n += v;
|
||||
return n;
|
||||
}
|
||||
|
||||
export const str = (v: unknown, fallback = ""): string => (typeof v === "string" && v ? v : typeof v === "number" && Number.isFinite(v) ? String(v) : fallback);
|
||||
|
||||
export const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
|
||||
|
||||
export const int = (n: number) => fmtInt(Number.isFinite(n) ? n : 0);
|
||||
|
||||
/** „1 Anlage“ / „3 Anlagen“. */
|
||||
export const nOf = (n: number, one: string, many: string) => `${int(n)} ${n === 1 ? one : many}`;
|
||||
|
||||
export const pct = (part: number, whole: number) => (whole > 0 ? `${Math.round((part / whole) * 100)} %` : "0 %");
|
||||
|
||||
const TZ = () => process.env.TZ || "Europe/Berlin";
|
||||
|
||||
/** „Fr., 27.11., 14:05 Uhr“ in der Zeitzone des Servers. */
|
||||
export function dateTime(ms: number): string {
|
||||
try {
|
||||
return `${new Date(ms).toLocaleString("de-DE", { weekday: "short", day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: TZ() })} Uhr`;
|
||||
} catch {
|
||||
return new Date(ms).toISOString().slice(0, 16).replace("T", " ");
|
||||
}
|
||||
}
|
||||
|
||||
/** Textsymbole statt Bilder (keine externen Abrufe; ︎ erzwingt die Textdarstellung statt Emoji). */
|
||||
const BRANCH_SYMBOL: Record<string, string> = { see: "⚓︎", luft: "✈︎", land: "♞︎" };
|
||||
const DEFENSE_SYMBOL = "▣";
|
||||
|
||||
/** Einheiten außerhalb von balance.units (Kartell). */
|
||||
const EXTRA_BRANCH: Record<string, string> = { piratenmiliz: "land", schnellboot: "see" };
|
||||
|
||||
export function unitSymbol(id: string): string {
|
||||
const u = (balance.units as Record<string, { branch?: string } | undefined>)[id] ?? (EXTRA_BRANCH[id] ? { branch: EXTRA_BRANCH[id] } : undefined);
|
||||
if (u?.branch) return BRANCH_SYMBOL[u.branch] ?? "◆";
|
||||
if ((balance.defenses as Record<string, unknown> | undefined)?.[id]) return DEFENSE_SYMBOL;
|
||||
return "◆";
|
||||
}
|
||||
|
||||
export const unitLabel = (id: string) => `${unitSymbol(id)} ${nameOf(id)}`;
|
||||
|
||||
export const isResource = (id: string) => (balance.resources as readonly string[]).includes(id);
|
||||
|
||||
/** „1.240 Stahl, 300 Treibstoff“ oder fallback. */
|
||||
export function resText(c: Counts | null | undefined, fallback = "nichts", limit = 4): string {
|
||||
const parts = Object.entries(c ?? {}).filter(([, v]) => v >= 1).sort((a, b) => b[1] - a[1]);
|
||||
if (!parts.length) return fallback;
|
||||
const shown = parts.slice(0, limit).map(([k, v]) => `${int(v)} ${nameOf(k)}`);
|
||||
return parts.length > limit ? `${shown.join(", ")} u. a.` : shown.join(", ");
|
||||
}
|
||||
|
||||
/** Zeilen „Ressource | Menge“ in der Reihenfolge des Spiels; null ohne Inhalt. */
|
||||
export function resourceRows(c: Counts | null | undefined, sign = ""): Cell[][] {
|
||||
const order = [...(balance.resources as readonly string[]), ...Object.keys(c ?? {}).filter((k) => !isResource(k))];
|
||||
return order.filter((k) => (c?.[k] ?? 0) >= 1).map((k) => [nameOf(k), `${sign}${int(c![k])}`]);
|
||||
}
|
||||
|
||||
/** Einheiten-Tabelle „Einheit | Anzahl“ (z. B. Lagebild), Anlagen nach Einheiten. */
|
||||
export function unitRows(c: Counts, vets: Record<string, string> = {}): Cell[][] {
|
||||
return Object.entries(c)
|
||||
.filter(([, n]) => n > 0)
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([id, n]) => [vets[id] ? `${unitLabel(id)} · ${vets[id]}` : unitLabel(id), int(n)]);
|
||||
}
|
||||
|
||||
export function unitTable(title: string | null, c: Counts, head = ["Einheit", "Anzahl"], caption?: string): MailBlock[] {
|
||||
const rows = unitRows(c);
|
||||
if (!rows.length) return title ? [{ type: "section", title }, { type: "text", text: "Keine.", tone: "muted" }] : [];
|
||||
return [...(title ? [{ type: "section", title } as MailBlock] : []), { type: "table", head, rows, caption, foot: rows.length > 1 ? ["Gesamt", int(sum(c))] : undefined }];
|
||||
}
|
||||
|
||||
/** Bezeichnung einer Berichtsart für Kopfzeilen. */
|
||||
const KIND_LABEL: Record<string, string> = {
|
||||
ueberfall: "Überfall", kartell: "Kartell-Überfall", aufklaerung: "Aufklärung", transport: "Lieferung", leer: "Piratennest",
|
||||
abgewiesen: "Kartell abgewiesen", weltereignis: "Weltereignis", weltereignis_leer: "Weltereignis", spionage: "Spionage",
|
||||
sabotage: "Sabotage", sammelangriff: "Sammelangriff", minen: "Minen", blockade: "Seeblockade", blockadekampf: "Blockadekampf",
|
||||
konvoi: "Konvoi", feld: "Rohstofffeld", gruendung: "Gründung", verlegung: "Verlegung",
|
||||
};
|
||||
|
||||
export function kindLabel(kind: string): string {
|
||||
return KIND_LABEL[kind] ?? nameOf(kind.replace(/_/g, " "));
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// Weitere Berichtsteile in der E-Mail: Lieferung, See (Minen, Blockade, Konvoi), verlassenes Nest, abgewiesener
|
||||
// Kartellverband, Weltereignis und Sammelangriff/stationierte Verteidiger der Allianz.
|
||||
import type { Cell, MailBlock } from "./mail-blocks.ts";
|
||||
import {
|
||||
counts, dateTime, int, num, registerReportSection, resText, resourceRows, str, sum, unitTable,
|
||||
type Counts, type ReportView,
|
||||
} from "./mail-report-kit.ts";
|
||||
import { nameOf } from "./names.ts";
|
||||
|
||||
function renderTransport(r: ReportView) {
|
||||
const cargo = counts(r.data.cargo);
|
||||
const from = str(r.data.from, "?");
|
||||
const to = str(r.data.to, "?");
|
||||
const incoming = r.role === "recipient";
|
||||
const rows = resourceRows(cargo, incoming ? "+" : "");
|
||||
return {
|
||||
subject: incoming ? `Lieferung von ${from}: ${resText(cargo, "leer", 3)}` : `Transport an ${to} zugestellt: ${resText(cargo, "leer", 3)}`,
|
||||
lead: incoming ? `${from} hat deinem Hafen ${to} ${resText(cargo)} geliefert.` : `Von ${from} an ${to}: ${resText(cargo)}.`,
|
||||
blocks: [
|
||||
{ type: "banner", tone: "win", kicker: incoming ? "Lieferung erhalten" : "Transport", title: incoming ? `Von ${from}` : `An ${to}`, sub: dateTime(r.atMs) } as MailBlock,
|
||||
{ type: "section", title: "Ladung" } as MailBlock,
|
||||
rows.length
|
||||
? ({ type: "table", head: ["Ressource", "Menge"], rows: rows.map((x) => [x[0], { v: x[1] as string, tone: incoming ? "win" : undefined }] as Cell[]), foot: rows.length > 1 ? ["Gesamt", int(sum(cargo))] : undefined } as MailBlock)
|
||||
: ({ type: "text", text: "Keine Ladung.", tone: "muted" } as MailBlock),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function renderMines(r: ReportView) {
|
||||
const m = r.data.mines as { action?: string; leg?: string; strength?: number; swept?: { owner: string; before: number; after: number }[]; hits?: { owner: string; strength: number; losses: Counts; share?: number }[]; before?: Counts; after?: Counts; refused?: string; lost?: Counts; cargoLeft?: Counts };
|
||||
const blocks: MailBlock[] = [];
|
||||
if (m.action === "legen") blocks.push({ type: "text", text: m.refused ? "Nicht gelegt: Höchstzahl an Feldern erreicht." : `Das Feld hat jetzt Stärke ${int(m.strength ?? 0)}. Fremde Schiffe, die hindurchfahren, sinken.` });
|
||||
if (m.action === "raeumen") {
|
||||
blocks.push(m.swept?.length
|
||||
? { type: "table", head: ["Minenfeld von", "vorher", "nachher"], rows: m.swept.map((s) => [s.owner, int(s.before), int(s.after)]) }
|
||||
: { type: "text", text: "Keine Minen gefunden." });
|
||||
}
|
||||
if (m.action === "konvoi" || m.action === "durchfahrt") {
|
||||
if (m.hits?.length) {
|
||||
blocks.push({ type: "table", head: ["Minenfeld von", "Stärke", m.action === "konvoi" ? "Ladung" : "Verluste"], rows: m.hits.map((h) => [h.owner, int(h.strength), m.action === "konvoi" ? { v: `−${Math.round((h.share ?? 0) * 1000) / 10} %`, tone: "loss" } : { v: `−${int(sum(h.losses))}`, tone: "loss" }]) });
|
||||
}
|
||||
if (m.action === "konvoi") blocks.push({ type: "facts", facts: [["Versenkt", resText(counts(m.lost))], ["Ladung danach", resText(counts(m.cargoLeft))]] });
|
||||
else blocks.push(...unitTable("Verband danach", counts(m.after)));
|
||||
}
|
||||
return { blocks };
|
||||
}
|
||||
|
||||
function renderBlockade(r: ReportView) {
|
||||
const b = r.data.blockade as { targetName?: string; attackerName?: string; endsAtMs?: number; refused?: string; factor?: number };
|
||||
const text = b.refused
|
||||
? `Die Blockade vor ${str(b.targetName, "?")} begann nicht (${b.refused === "fleet_lost" ? "Verband verloren" : nameOf(b.refused)}).`
|
||||
: `${str(b.attackerName, "?")} blockiert ${str(b.targetName, "?")} bis ${dateTime(b.endsAtMs ?? 0)}: Produktion −${Math.round((1 - (b.factor ?? 1)) * 100)} %, Lieferungen zurückgehalten, Börsenverkäufe gesperrt.`;
|
||||
return { lead: text, blocks: [{ type: "text", text } as MailBlock] };
|
||||
}
|
||||
|
||||
function renderConvoy(r: ReportView) {
|
||||
const c = r.data.convoy as { by?: string; held?: boolean | null; lost?: Counts; loot?: Counts; cargoLeft?: Counts; missed?: boolean; force?: Counts };
|
||||
if (c.missed) return { blocks: [{ type: "text", text: "Der Konvoi war schon eingelaufen." } as MailBlock] };
|
||||
const held = c.held === true ? "Der Geleitschutz hat gehalten – nichts verloren." : c.held === false ? "Der Geleitschutz unterlag." : "Ohne Geleitschutz.";
|
||||
const blocks: MailBlock[] = [{ type: "text", text: held }];
|
||||
if (c.by === "kartell" && c.force) blocks.push(...unitTable("Kartellverband", counts(c.force)));
|
||||
const facts: [string, string][] = [];
|
||||
if (c.held !== true) facts.push(["Verlust", resText(counts(c.lost))]);
|
||||
if (c.loot && sum(counts(c.loot)) > 0) facts.push(["Davon erbeutet", resText(counts(c.loot))]);
|
||||
facts.push(["Ladung danach", resText(counts(c.cargoLeft))]);
|
||||
blocks.push({ type: "facts", facts });
|
||||
return { lead: held, blocks };
|
||||
}
|
||||
|
||||
function renderWorldEvent(r: ReportView) {
|
||||
if (r.kind === "weltereignis_leer") {
|
||||
const t = str(r.data.text, "Bei Ankunft war niemand mehr da.");
|
||||
return { lead: t, blocks: [{ type: "text", text: `${t} Der Verband kehrt um.` } as MailBlock] };
|
||||
}
|
||||
const we = r.data.worldEvent as { destroyed?: boolean; destroyedHp?: number; initialHp?: number; remaining?: Counts };
|
||||
const blocks: MailBlock[] = [{ type: "section", title: "Weltereignis" }];
|
||||
blocks.push({ type: "text", text: we.destroyed ? "Der Kartellverband ist vernichtet." : sum(counts(we.remaining)) > 0 ? `Verbleibend: ${resText(counts(we.remaining), "–", 6)}.` : "Der Kartellverband ist noch da." });
|
||||
const hp = num(we.destroyedHp);
|
||||
if (hp !== null) blocks.push({ type: "facts", facts: [["Dein Schaden", `${int(hp)} Lebenspunkte${we.initialHp ? ` (${Math.round((hp / we.initialHp) * 100)} % der Anfangsstärke)` : ""}`]] });
|
||||
return { blocks };
|
||||
}
|
||||
|
||||
interface Part { name: string; share: number; outcome: { losses: Counts }; loot: Counts }
|
||||
function renderAlliance(r: ReportView) {
|
||||
const raid = r.data.allianceRaid as { tag: string; participants: Part[] } | undefined;
|
||||
const guests = Array.isArray(r.data.guests) ? (r.data.guests as { name: string; losses: Counts }[]) : [];
|
||||
const blocks: MailBlock[] = [];
|
||||
if (raid?.participants?.length) {
|
||||
blocks.push(
|
||||
{ type: "section", title: `Sammelangriff [${raid.tag}]` },
|
||||
{ type: "table", head: ["Teilnehmer", "Beitrag", "Verluste", "Beute"], rows: raid.participants.map((p) => [p.name, `${(p.share ?? 0).toLocaleString("de-DE", { maximumFractionDigits: 1 })} %`, int(sum(p.outcome?.losses)), int(sum(p.loot))]) },
|
||||
);
|
||||
}
|
||||
if (guests.length) blocks.push({ type: "section", title: "Stationierte Verteidiger" }, { type: "table", head: ["Verbündeter", "Verluste"], rows: guests.map((g) => [g.name, int(sum(g.losses))]) });
|
||||
return blocks.length ? { blocks } : null;
|
||||
}
|
||||
|
||||
registerReportSection({ id: "transport", applies: (r) => r.kind === "transport", render: renderTransport });
|
||||
registerReportSection({ id: "mines", applies: (r) => !!r.data.mines, render: renderMines });
|
||||
registerReportSection({ id: "blockade", applies: (r) => !!r.data.blockade, render: renderBlockade });
|
||||
registerReportSection({ id: "convoy", applies: (r) => !!r.data.convoy, render: renderConvoy });
|
||||
registerReportSection({ id: "worldEvent", applies: (r) => r.kind.startsWith("weltereignis") && (!!r.data.worldEvent || r.kind === "weltereignis_leer"), render: renderWorldEvent });
|
||||
registerReportSection({ id: "alliance", applies: (r) => !!r.data.allianceRaid || Array.isArray(r.data.guests), render: renderAlliance });
|
||||
registerReportSection({ id: "leer", applies: (r) => r.kind === "leer", render: () => ({ subject: undefined, blocks: [{ type: "text", text: "Das Nest war bei Ankunft verlassen. Der Verband kehrt um." }] }) });
|
||||
registerReportSection({
|
||||
id: "abgewiesen",
|
||||
applies: (r) => r.kind === "abgewiesen",
|
||||
render: (r) => ({ blocks: [{ type: "text", text: `Ein Verband des Kartells erreichte deinen Hafen, traf aber auf deinen Schutz (${nameOf(str(r.data.reason, "nachtschild"))}) und drehte ohne Kampf ab.` }] }),
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
// Ausführliche E-Mail zu einem Bericht: lädt den Bericht aus Sicht des Lesers (dieselben Daten wie im Spiel,
|
||||
// views.reportGet) und setzt die angemeldeten Abschnitte zusammen. Für unbekannte Berichtsarten (z. B. neue Arten
|
||||
// anderer Ausbaustufen) entsteht ein Standard aus Banner und den Zahlen des Berichts.
|
||||
import { eq } from "drizzle-orm";
|
||||
import { tables } from "@tidefront/db";
|
||||
import type { BaseState } from "@tidefront/game-core";
|
||||
import type { Engine } from "./context.ts";
|
||||
import type { MailBlock } from "./mail-blocks.ts";
|
||||
import {
|
||||
dateTime, isCounts, isResource, kindLabel, reportSections, resourceRows, unitRows,
|
||||
type ReportCtx, type ReportView,
|
||||
} from "./mail-report-kit.ts";
|
||||
import "./mail-report-battle.ts";
|
||||
import "./mail-report-intel.ts";
|
||||
import "./mail-report-misc.ts";
|
||||
import { nameOf } from "./names.ts";
|
||||
import { veteranView } from "./veterans.ts";
|
||||
import { reportGet } from "./views.ts";
|
||||
|
||||
export { registerReportSection, type ReportSection, type ReportView } from "./mail-report-kit.ts";
|
||||
|
||||
export interface ReportMailParts {
|
||||
subject: string;
|
||||
heading: string;
|
||||
lead: string;
|
||||
blocks: MailBlock[];
|
||||
}
|
||||
|
||||
const SKIP_KEYS = /(^id$|Id$|^seed$|Ms$|^at$)/;
|
||||
|
||||
/** Standard für unbekannte Teile: Zahlenlisten als Tabellen, einfache Werte als Kennzahlen (eine Ebene tief). */
|
||||
export function genericBlocks(data: Record<string, unknown>, depth = 0): MailBlock[] {
|
||||
const blocks: MailBlock[] = [];
|
||||
const facts: [string, string][] = [];
|
||||
for (const [k, v] of Object.entries(data)) {
|
||||
if (SKIP_KEYS.test(k) || v === null || v === undefined) continue;
|
||||
if (typeof v === "string" && v.length <= 200) facts.push([nameOf(k), v]);
|
||||
else if (typeof v === "number" && Number.isFinite(v)) facts.push([nameOf(k), v.toLocaleString("de-DE", { maximumFractionDigits: 2 })]);
|
||||
else if (typeof v === "boolean") facts.push([nameOf(k), v ? "ja" : "nein"]);
|
||||
else if (isCounts(v)) {
|
||||
const keys = Object.keys(v);
|
||||
if (!keys.some((x) => v[x] > 0)) continue;
|
||||
const res = keys.every(isResource);
|
||||
blocks.push({ type: "section", title: nameOf(k) }, { type: "table", head: res ? ["Ressource", "Menge"] : ["Einheit", "Anzahl"], rows: res ? resourceRows(v) : unitRows(v) });
|
||||
} else if (depth === 0 && typeof v === "object" && !Array.isArray(v)) {
|
||||
blocks.push(...genericBlocks(v as Record<string, unknown>, 1));
|
||||
}
|
||||
}
|
||||
return [...(facts.length ? [{ type: "facts", facts } as MailBlock] : []), ...blocks];
|
||||
}
|
||||
|
||||
/** Bericht → Betreff, Überschrift, Kurzsatz und Bausteine. Reine Funktion (testbar ohne Datenbank). */
|
||||
export function reportMailParts(r: ReportView, ctx: ReportCtx = { veterans: {} }): ReportMailParts {
|
||||
const outs = reportSections().filter((s) => s.applies(r)).map((s) => s.render(r, ctx)).filter((o) => o !== null);
|
||||
const blocks = outs.flatMap((o) => o.blocks);
|
||||
if (outs.length === 0) blocks.push(...genericBlocks(r.data));
|
||||
const bi = blocks.findIndex((b) => b.type === "banner");
|
||||
if (bi > 0) blocks.unshift(...blocks.splice(bi, 1));
|
||||
else if (bi < 0) blocks.unshift({ type: "banner", tone: r.winner === null ? "info" : (r.winner === "attacker") === (r.role === "attacker") ? "win" : "loss", kicker: kindLabel(r.kind), title: r.title, sub: dateTime(r.atMs) });
|
||||
const lead = outs.find((o) => o.lead)?.lead;
|
||||
// Kurzsatz direkt unter dem Banner, sofern der Abschnitt dort keinen eigenen Text setzt.
|
||||
if (lead && blocks[1]?.type !== "text") blocks.splice(1, 0, { type: "text", text: lead });
|
||||
if (blocks.length === 1) blocks.push({ type: "text", text: "Der Bericht liegt im Spiel vor.", tone: "muted" });
|
||||
const subject = outs.find((o) => o.subject)?.subject ?? r.title;
|
||||
return { subject, heading: r.title, lead: lead ?? `${kindLabel(r.kind)} vom ${dateTime(r.atMs)}.`, blocks };
|
||||
}
|
||||
|
||||
/** Veteranenränge der eigenen Einheiten im beteiligten Hafen (wie unter Truppen); nur bei Kämpfen. */
|
||||
async function readerCtx(engine: Engine, playerId: number, reportId: number, r: ReportView): Promise<ReportCtx> {
|
||||
if (!r.data.battle) return { veterans: {} };
|
||||
const [row] = await engine.db
|
||||
.select({ a: tables.battleReport.attackerBaseId, d: tables.battleReport.defenderBaseId })
|
||||
.from(tables.battleReport)
|
||||
.where(eq(tables.battleReport.id, reportId));
|
||||
const baseId = r.role === "defender" ? row?.d : row?.a;
|
||||
if (!baseId) return { veterans: {} };
|
||||
const [b] = await engine.db.select({ playerId: tables.base.playerId, state: tables.base.state }).from(tables.base).where(eq(tables.base.id, baseId));
|
||||
if (!b || b.playerId !== playerId) return { veterans: {} };
|
||||
const veterans: Record<string, string> = {};
|
||||
for (const v of veteranView(b.state as BaseState)) if (v.rank !== "rekrut") veterans[v.id] = v.rankName;
|
||||
return { veterans };
|
||||
}
|
||||
|
||||
/** Bericht für einen Spieler laden und aufbereiten; null, wenn er ihn nicht sehen darf oder es ihn nicht gibt. */
|
||||
export async function reportMailFor(engine: Engine, playerId: number, reportId: number): Promise<(ReportMailParts & { reportId: number }) | null> {
|
||||
const r = await reportGet(engine, playerId, reportId);
|
||||
if (!r) return null;
|
||||
const view: ReportView = { id: r.id, kind: r.kind, title: r.title, atMs: r.atMs, role: r.role as ReportView["role"], winner: r.winner, data: r.data ?? {} };
|
||||
const ctx = await readerCtx(engine, playerId, reportId, view).catch(() => ({ veterans: {} }));
|
||||
return { ...reportMailParts(view, ctx), reportId: r.id };
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// E-Mail-Vorlagen: tabellenbasiert mit Inline-CSS, hell und dunkel, mit Textversion.
|
||||
// Das Erscheinungsbild hängt nur an MAIL_THEME; ein neues Design ändert hier Farben und Schrift.
|
||||
import { blockDarkCss, blockHtml, blockText, type MailBlock } from "./mail-blocks.ts";
|
||||
export type { Cell, MailBlock, Tone } from "./mail-blocks.ts";
|
||||
|
||||
export const MAIL_THEME = {
|
||||
brand: "TIDEFRONT",
|
||||
@@ -33,6 +35,24 @@ export const MAIL_THEME = {
|
||||
darkAccent: "#ede6d6",
|
||||
darkAccentText: "#11161d",
|
||||
darkSeal: "#e58a73",
|
||||
/** Ergebnisfarben (Banner, Kacheln, Zellen): Schrift kräftig, Grund hell getönt; dunkel umgekehrt. */
|
||||
win: "#2d6a3a",
|
||||
winBg: "#e5efe1",
|
||||
loss: "#a8331f",
|
||||
lossBg: "#f7e3dd",
|
||||
warn: "#8a5800",
|
||||
warnBg: "#f8ecd0",
|
||||
infoBg: "#ebeee9",
|
||||
/** Abgesetzte Tabellenzeilen. */
|
||||
stripe: "#faf6ed",
|
||||
darkWin: "#9fd3a8",
|
||||
darkWinBg: "#142619",
|
||||
darkLoss: "#f0a08c",
|
||||
darkLossBg: "#2d1612",
|
||||
darkWarn: "#e8c27a",
|
||||
darkWarnBg: "#2a2110",
|
||||
darkInfoBg: "#1a2430",
|
||||
darkStripe: "#1d2733",
|
||||
};
|
||||
|
||||
export type MailTheme = typeof MAIL_THEME;
|
||||
@@ -47,6 +67,10 @@ export interface MailContent {
|
||||
facts?: [string, string][];
|
||||
/** Aufzählung (z. B. gebündelte Meldungen). */
|
||||
items?: string[];
|
||||
/** Ausführlicher Inhalt (Banner, Kacheln, Tabellen …), steht nach den Absätzen und vor facts/items. */
|
||||
blocks?: MailBlock[];
|
||||
/** Vorschauzeile im Posteingang; Vorgabe: erster Absatz bzw. Überschrift. */
|
||||
preheader?: string;
|
||||
button?: { label: string; url: string };
|
||||
/** Abmeldelink in der Fußzeile; fehlt er, steht dort nur der Hinweis. */
|
||||
unsubscribeUrl?: string;
|
||||
@@ -80,6 +104,7 @@ ${(c.facts ?? []).map(([k, v], i) => `<tr><td class="tf-muted" style="padding:10
|
||||
${(c.items ?? []).map((s) => `<tr><td width="18" valign="top" class="tf-seal" style="padding:4px 0;color:${t.seal};font-size:13px;line-height:22px;">◆</td><td class="tf-text" style="padding:4px 0;font-size:15px;line-height:22px;color:${t.text};">${esc(s)}</td></tr>`).join("\n")}
|
||||
</table>`
|
||||
: "";
|
||||
const blocks = (c.blocks ?? []).map((b) => blockHtml(b, t)).filter(Boolean).join("\n");
|
||||
const button = c.button
|
||||
? `<table role="presentation" cellpadding="0" cellspacing="0" style="margin:8px 0 6px 0;"><tr><td class="tf-btn" style="border-radius:${t.radius};background:${t.accent};">
|
||||
<a href="${esc(c.button.url)}" class="tf-btn-a" style="display:inline-block;padding:14px 26px;font-size:14px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:${t.accentText};text-decoration:none;border-radius:${t.radius};font-family:${t.font};">${esc(c.button.label)}</a>
|
||||
@@ -102,22 +127,25 @@ ${(c.items ?? []).map((s) => `<tr><td width="18" valign="top" class="tf-seal" st
|
||||
.tf-facts{background:${t.darkFactBg}!important;border-color:${t.darkLine}!important;} .tf-facts td{border-color:${t.darkLine}!important;}
|
||||
.tf-btn{background:${t.darkAccent}!important;} .tf-btn-a{color:${t.darkAccentText}!important;} .tf-seal{color:${t.darkSeal}!important;}
|
||||
.tf-panel{border-color:${t.darkLine}!important;}
|
||||
${blockDarkCss(t)}
|
||||
}
|
||||
@media only screen and (max-width:620px){ .tf-wrap{width:100%!important;} .tf-pad{padding:20px 18px!important;} }
|
||||
@media only screen and (max-width:620px){ .tf-wrap{width:100%!important;} .tf-pad{padding:20px 16px!important;} .tf-h1{font-size:22px!important;line-height:28px!important;} }
|
||||
@media only screen and (max-width:480px){ .tf-tag{display:none!important;} }
|
||||
</style></head>
|
||||
<body class="tf-page" style="margin:0;padding:0;background:${t.page};font-family:${t.font};">
|
||||
<div style="display:none;max-height:0;overflow:hidden;opacity:0;">${esc(c.paragraphs[0] ?? c.heading)}</div>
|
||||
<div style="display:none;max-height:0;overflow:hidden;opacity:0;">${esc(c.preheader ?? c.paragraphs[0] ?? c.heading)}</div>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" class="tf-page" style="background:${t.page};">
|
||||
<tr><td align="center" style="padding:24px 12px;">
|
||||
<table role="presentation" width="600" cellpadding="0" cellspacing="0" class="tf-wrap" style="width:600px;max-width:600px;">
|
||||
<tr><td style="background:${t.header};border-radius:${t.radius} ${t.radius} 0 0;padding:18px 28px;font-family:${t.font};">
|
||||
<span style="font-family:${t.headingFont};font-size:19px;font-weight:600;letter-spacing:5px;color:${t.headerText};">${esc(t.brand)}</span>
|
||||
<span style="font-size:12px;color:${t.headerMuted};padding-left:10px;">${esc(t.tagline)}</span>
|
||||
<span class="tf-tag" style="font-size:12px;color:${t.headerMuted};padding-left:10px;">${esc(t.tagline)}</span>
|
||||
</td></tr>
|
||||
<tr><td style="background:${t.header};padding:0 28px 12px 28px;font-size:0;line-height:0;"><div style="border-top:3px double ${t.headerText};opacity:0.55;"> </div></td></tr>
|
||||
<tr><td class="tf-panel tf-pad" style="background:${t.panel};padding:28px;border:1px solid ${t.line};border-top:0;border-left:4px solid ${t.seal};border-radius:0 0 ${t.radius} ${t.radius};font-family:${t.font};">
|
||||
<h1 class="tf-text" style="margin:0 0 14px 0;font-family:${t.headingFont};font-size:25px;line-height:31px;font-weight:600;color:${t.text};">${esc(c.heading)}</h1>
|
||||
<h1 class="tf-text tf-h1" style="margin:0 0 14px 0;font-family:${t.headingFont};font-size:25px;line-height:31px;font-weight:600;color:${t.text};">${esc(c.heading)}</h1>
|
||||
${c.paragraphs.map(p).join("\n")}
|
||||
${blocks}
|
||||
${facts}
|
||||
${items}
|
||||
${button}
|
||||
@@ -133,6 +161,7 @@ ${button}
|
||||
c.heading,
|
||||
"",
|
||||
...c.paragraphs.flatMap((s) => [s, ""]),
|
||||
...(c.blocks ?? []).flatMap((b) => blockText(b)),
|
||||
...(c.facts ?? []).map(([k, v]) => `${k}: ${v}`),
|
||||
...((c.facts ?? []).length ? [""] : []),
|
||||
...(c.items ?? []).map((s) => `- ${s}`),
|
||||
|
||||
@@ -6,6 +6,8 @@ import { and, eq, gt, inArray, isNotNull, isNull, lt, or, sql } from "drizzle-or
|
||||
import { tables, type Db } from "@tidefront/db";
|
||||
import { type Engine, type Notice, type NoticeKind } from "./context.ts";
|
||||
import { renderMail, type MailContent } from "./mail-templates.ts";
|
||||
import { defaultNoticeBlocks, digestBlocks, digestSubject } from "./mail-notices.ts";
|
||||
import { reportMailFor } from "./mail-reports.ts";
|
||||
import { cleanPrefs, wants, type Prefs } from "./push.ts";
|
||||
import { decryptSecret, encryptSecret, getSetting, getSettings, publicUrl, secretAvailable, setSetting, sha256 } from "./settings.ts";
|
||||
|
||||
@@ -183,14 +185,32 @@ export async function sendMail(
|
||||
|
||||
const unsubUrl = (token: string) => `${publicUrl()}/api/mail/unsubscribe?t=${token}`;
|
||||
|
||||
function noticeMail(n: Notice, unsubscribeToken: string): MailContent {
|
||||
/** Inhalt einer Benachrichtigungs-Mail: mit Bericht ausführlich (mail-reports.ts), sonst aus Notice.mail bzw. facts. */
|
||||
export async function noticeMail(engine: Engine, playerId: number, n: Notice, unsubscribeToken: string): Promise<MailContent> {
|
||||
const unsubscribeUrl = unsubUrl(unsubscribeToken);
|
||||
if (n.reportId !== undefined) {
|
||||
const r = await reportMailFor(engine, playerId, n.reportId).catch((err) => {
|
||||
engine.log("report mail", String(err));
|
||||
return null;
|
||||
});
|
||||
if (r) {
|
||||
return {
|
||||
subject: r.subject, heading: r.heading, paragraphs: [], preheader: r.lead, blocks: r.blocks,
|
||||
button: { label: "Im Spiel öffnen", url: `${publicUrl()}/?tab=berichte&bericht=${r.reportId}` },
|
||||
unsubscribeUrl,
|
||||
};
|
||||
}
|
||||
}
|
||||
// Mit eigenem Banner steht der Kurzsatz dort; dann nur als Vorschauzeile.
|
||||
const banner = n.mail?.blocks?.some((b) => b.type === "banner") ?? false;
|
||||
return {
|
||||
subject: n.title,
|
||||
subject: n.mail?.subject ?? n.title,
|
||||
heading: n.title,
|
||||
paragraphs: [n.body],
|
||||
facts: n.facts,
|
||||
paragraphs: banner ? [] : [n.mail?.lead ?? n.body],
|
||||
preheader: n.mail?.lead ?? n.body,
|
||||
blocks: n.mail?.blocks ?? defaultNoticeBlocks(n),
|
||||
button: { label: "Im Spiel öffnen", url: `${publicUrl()}${n.url ?? "/"}` },
|
||||
unsubscribeUrl: unsubUrl(unsubscribeToken),
|
||||
unsubscribeUrl,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -205,7 +225,7 @@ export async function mailNotice(engine: Engine, playerId: number, n: Notice): P
|
||||
return "queued";
|
||||
}
|
||||
if (!(await mailReady(engine.db))) return "skipped";
|
||||
const r = await sendMail(engine, pe.email, noticeMail(n, pe.unsubscribeToken));
|
||||
const r = await sendMail(engine, pe.email, await noticeMail(engine, playerId, n, pe.unsubscribeToken));
|
||||
return r.ok ? "sent" : "failed";
|
||||
}
|
||||
|
||||
@@ -238,12 +258,12 @@ export async function flushMailDigests(engine: Engine, nowMs: number): Promise<n
|
||||
const [nb] = await engine.db.select({ n: sql<number>`count(*)::int` }).from(tables.base).where(eq(tables.base.playerId, p.playerId));
|
||||
const harbor = (nb?.n ?? 1) > 1 ? "deinen Häfen" : "deinem Hafen";
|
||||
const content: MailContent = rows.length === 1
|
||||
? noticeMail({ kind: rows[0].kind as NoticeKind, title: rows[0].title, body: rows[0].body }, p.token)
|
||||
? await noticeMail(engine, p.playerId, { kind: rows[0].kind as NoticeKind, title: rows[0].title, body: rows[0].body }, p.token)
|
||||
: {
|
||||
subject: `${rows.length} Meldungen aus ${harbor}`,
|
||||
subject: `${rows.length} Meldungen aus ${harbor}: ${digestSubject(rows)}`,
|
||||
heading: `Neues aus ${harbor}`,
|
||||
paragraphs: ["Seit der letzten Nachricht ist Folgendes passiert:"],
|
||||
items: rows.map((r) => `${r.title}: ${r.body}`),
|
||||
blocks: digestBlocks(rows),
|
||||
button: { label: "Im Spiel öffnen", url: `${publicUrl()}/` },
|
||||
unsubscribeUrl: unsubUrl(p.token),
|
||||
};
|
||||
|
||||
@@ -9,6 +9,12 @@ const NAMES: Record<string, string> = {
|
||||
schnellboot: "Schnellboot", piratenmiliz: "Piratenmiliz", kuestenbatterie: "Küstenbatterie", flakstellung: "Flakstellung",
|
||||
bunkerlinie: "Bunkerlinie", minensperre: "Minensperre",
|
||||
stahl: "Stahl", treibstoff: "Treibstoff", elektronik: "Elektronik", proviant: "Proviant", credits: "Kredite",
|
||||
// Für ausführliche E-Mails (wie apps/web/src/lib/names.ts)
|
||||
windpark: "Windpark", solarfeld: "Solarfeld", speicherwerk: "Speicherwerk", forschungsamt: "Forschungsamt",
|
||||
minenleger: "Minenleger", minenraeumer: "Minenräumer", kolonieschiff: "Kolonieschiff", spion: "Spion", anlagen: "Anlagen",
|
||||
luftkampf: "Luftkampf", luftschlag: "Luftschlag", ubootangriff: "U-Boot-Angriff", seegefecht: "Seegefecht", landung: "Landung",
|
||||
nachtschild: "Nachtschild", anfaengerschutz: "Anfängerschutz", niederlage: "Schutz nach Niederlage", gruendungsschutz: "Gründungsschutz",
|
||||
bauschlange: "Bauschlange", oelfeld: "Ölfeld", erzbucht: "Erzbucht", fischgrund: "Fischgrund", elektronikwrack: "Elektronik-Wrack",
|
||||
};
|
||||
|
||||
export function nameOf(id: string): string {
|
||||
|
||||
@@ -144,14 +144,14 @@ export async function blockadeArrive(tx: Tx, m: MissionRowLike, plan: Mission &
|
||||
await tx.update(tables.mission).set({ status: "holding", returning: activeUnits(units), returnAt: new Date(endsAt + travel) }).where(eq(tables.mission.id, m.id));
|
||||
await scheduleEvent(tx, "blockade_end", endsAt, { blockadeId: b.id }, null);
|
||||
const who = await playerName(tx, pid);
|
||||
await storeNavalReport(tx, {
|
||||
const reportId = await storeNavalReport(tx, {
|
||||
kind: "blockade", title: `Blockade vor ${target.name} bis ${fmtClock(endsAt)}`, attackerPlayerId: pid, defenderPlayerId: target.playerId,
|
||||
attackerBaseId: m.baseId, defenderBaseId: target.id,
|
||||
report: { blockade: { id: b.id, targetName: target.name, attackerName: who, units: activeUnits(units), endsAtMs: endsAt, factor: blockadeProductionFactor(balance) } }, atMs: due,
|
||||
});
|
||||
await systemMessage(tx, [target.playerId], `Seeblockade vor ${target.name}`,
|
||||
`${who} blockiert deinen Hafen ${target.name} bis ${fmtClock(endsAt)}. Produktion −${Math.round((1 - blockadeProductionFactor(balance)) * 100)} %, eingehende Lieferungen werden zurückgehalten, Börsenverkäufe sind gesperrt. Greife den Blockadeverband auf der Karte an, um die Blockade zu brechen.`, due);
|
||||
push.push(pushNotice(target.playerId, "attack", `Seeblockade vor ${target.name}`, `${who} blockiert deinen Hafen ${target.name} bis ${fmtClock(endsAt)}.`));
|
||||
push.push(pushNotice(target.playerId, "attack", `Seeblockade vor ${target.name}`, `${who} blockiert deinen Hafen ${target.name} bis ${fmtClock(endsAt)}.`, "karte", reportId));
|
||||
notify.push([[target.playerId], "base"], [[target.playerId], "messages"], [[target.playerId], "reports"], [null, "map"]);
|
||||
}
|
||||
|
||||
@@ -263,8 +263,8 @@ export async function blockadeAttackArrive(tx: Tx, m: MissionRowLike, plan: Miss
|
||||
atMs: due,
|
||||
});
|
||||
if (destroyed) await endBlockade(tx, { ...b, units: left }, "broken", due, notify);
|
||||
push.push(pushNotice(b.attackerId, "attack", destroyed ? "Blockade gebrochen" : "Blockade angegriffen", `${attackerName} hat deinen Blockadeverband angegriffen.`, "berichte"));
|
||||
if (b.targetPlayerId !== pid) push.push(pushNotice(b.targetPlayerId, "report", title, `${attackerName} hat den Blockadeverband angegriffen.`, "berichte"));
|
||||
push.push(pushNotice(b.attackerId, "attack", destroyed ? "Blockade gebrochen" : "Blockade angegriffen", `${attackerName} hat deinen Blockadeverband angegriffen.`, "berichte", reportId));
|
||||
if (b.targetPlayerId !== pid) push.push(pushNotice(b.targetPlayerId, "report", title, `${attackerName} hat den Blockadeverband angegriffen.`, "berichte", reportId));
|
||||
notify.push([[b.attackerId], "reports"], [[b.attackerId], "missions"], [null, "map"]);
|
||||
await sendHome(tx, m, plan, activeUnits(raw.attacker.final), {}, reportId, due);
|
||||
}
|
||||
|
||||
@@ -131,8 +131,8 @@ export function hasShips(units: Counts): boolean {
|
||||
return Object.entries(units).some(([id, n]) => n > 0 && balance.units[id]?.branch === "see");
|
||||
}
|
||||
|
||||
export function pushNotice(playerId: number, kind: NoticeJob["notice"]["kind"], title: string, body: string, tab = "karte"): NoticeJob {
|
||||
return { playerId, notice: { kind, title, body, url: `/?tab=${tab}`, tag: `see-${kind}` } };
|
||||
export function pushNotice(playerId: number, kind: NoticeJob["notice"]["kind"], title: string, body: string, tab = "karte", reportId?: number): NoticeJob {
|
||||
return { playerId, notice: { kind, title, body, url: `/?tab=${tab}`, tag: `see-${kind}`, ...(reportId !== undefined ? { reportId } : {}) } }; // reportId: ausführliche E-Mail
|
||||
}
|
||||
|
||||
export function fmtClock(ms: number): string {
|
||||
|
||||
@@ -230,12 +230,12 @@ export async function convoyRaidHandler(tx: Tx, payload: Record<string, unknown>
|
||||
await addEvent(tx, c, { atMs: due, by: "kartell", name: "Freibeuter-Kartell", lost, escortHeld: held });
|
||||
const victim = victimOf(c);
|
||||
const title = held === true ? "Konvoi: Geleitschutz schlägt das Kartell zurück" : `Konvoi vom Kartell abgefangen – ${resText(lost)} verloren`;
|
||||
await storeNavalReport(tx, {
|
||||
const reportId = await storeNavalReport(tx, {
|
||||
kind: "konvoi", title, attackerPlayerId: null, defenderPlayerId: victim, defenderBaseId: c.recipientBaseId, winner: held === null ? null : held ? "defender" : "attacker", seed,
|
||||
report: { convoy: { id: c.id, kind: c.kind, by: "kartell", force, escort, held, lost, cargoLeft: c.cargo }, ...(battle ? { battle, attackerName: "Freibeuter-Kartell", defenderName: "Geleitschutz", targetName: "Konvoi" } : {}) },
|
||||
atMs: due,
|
||||
});
|
||||
push.push(pushNotice(victim, "delivery", title, held === true ? "Die Ladung ist sicher." : `Verlust: ${resText(lost)}.`, "berichte"));
|
||||
push.push(pushNotice(victim, "delivery", title, held === true ? "Die Ladung ist sicher." : `Verlust: ${resText(lost)}.`, "berichte", reportId));
|
||||
notify.push([[victim], "reports"], [[victim], "base"], [[victim], "market"]);
|
||||
return { notify, push };
|
||||
}
|
||||
@@ -319,7 +319,7 @@ export async function interceptArrive(tx: Tx, m: MissionRowLike, plan: Mission,
|
||||
report: { convoy: { id: c.id, kind: c.kind, by: "spieler", escort, held, lost, loot, cargoLeft: c.cargo }, ...(battle ? { battle, attackerName: name, defenderName: "Geleitschutz", targetName: "Konvoi" } : {}) },
|
||||
atMs: due,
|
||||
});
|
||||
push.push(pushNotice(victim, "attack", `Konvoi von ${name} abgefangen`, held === true ? "Der Geleitschutz hat gehalten." : `Verlust: ${resText(lost)}.`, "berichte"));
|
||||
push.push(pushNotice(victim, "attack", `Konvoi von ${name} abgefangen`, held === true ? "Der Geleitschutz hat gehalten." : `Verlust: ${resText(lost)}.`, "berichte", reportId));
|
||||
notify.push([[victim], "reports"], [[victim], "base"], [[victim], "market"], [null, "map"]);
|
||||
await sendHome(tx, m, plan, activeCounts(returning), loot, reportId, due);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { Counts, ResourceMap } from "@tidefront/game-core";
|
||||
import type { PgColumn } from "drizzle-orm/pg-core";
|
||||
import { tables, type Db, type DbOrTx } from "@tidefront/db";
|
||||
import type { Engine } from "./context.ts";
|
||||
import type { MailContent } from "./mail-templates.ts";
|
||||
import type { MailBlock, MailContent } from "./mail-templates.ts";
|
||||
import { mailReady, sendMail } from "./mail.ts";
|
||||
import { pushToPlayer } from "./push.ts";
|
||||
import { publicUrl } from "./settings.ts";
|
||||
@@ -186,17 +186,33 @@ export function summaryMail(d: SummaryData, name: string, timeZone: string, unsu
|
||||
facts.push(["Neue Nachrichten", d.messages.unread > d.messages.received ? `${d.messages.received} (${d.messages.unread} ungelesen)` : String(d.messages.received)]);
|
||||
if (d.rank) facts.push(["Rang in der Saison", `${d.rank.rank} von ${d.rank.of} · ${fmtInt(d.rank.total)} Punkte`]);
|
||||
|
||||
const timed: [number, string][] = [];
|
||||
for (const b of d.battles) {
|
||||
const res = b.role === "attacker" ? (b.won ? `Sieg, Beute ${amounts(b.loot)}` : "Niederlage") : b.won ? "abgewehrt" : `verloren, geplündert ${amounts(b.loot)}`;
|
||||
timed.push([b.atMs, `${clockIn(b.atMs, timeZone)} ${b.role === "attacker" ? b.title : `Angriff auf dich: ${b.title}`} – ${res}`]);
|
||||
// Ausführlich: Kacheln, Lage, Kämpfe als Tabelle, Aufträge/Lieferungen und Zusatzabschnitte als Listen.
|
||||
const lootSum = Object.values(d.lootGained).reduce((n, v) => n + Math.max(0, v), 0);
|
||||
const done = d.entries.filter((e) => e.kind !== "delivery").length + d.entries.filter((e) => e.kind === "delivery").length;
|
||||
const blocks: MailBlock[] = [
|
||||
{ type: "tiles", tiles: [
|
||||
{ label: "Siege", value: d.battles.length ? `${won}/${d.battles.length}` : "–", tone: !d.battles.length ? undefined : won === d.battles.length ? "win" : won === 0 ? "loss" : undefined },
|
||||
{ label: "Beute", value: lootSum > 0 ? `+${fmtInt(lootSum)}` : "0", tone: lootSum > 0 ? "win" : undefined },
|
||||
{ label: "Erledigt", value: String(done) },
|
||||
] },
|
||||
{ type: "section", title: "Lage" },
|
||||
{ type: "facts", facts },
|
||||
];
|
||||
if (d.battles.length) {
|
||||
blocks.push({ type: "section", title: "Kämpfe" }, {
|
||||
type: "table", head: ["Zeit", "Ereignis", "Ergebnis"], align: ["left", "left", "left"], maxRows: MAX_ITEMS,
|
||||
rows: [...d.battles].sort((a, b) => a.atMs - b.atMs).map((b) => [
|
||||
{ v: clockIn(b.atMs, timeZone), muted: true },
|
||||
b.role === "attacker" ? b.title : `Angriff auf dich: ${b.title}`,
|
||||
{ v: b.role === "attacker" ? (b.won ? `Sieg${Object.values(b.loot).some((v) => v >= 1) ? `, Beute ${amounts(b.loot)}` : ""}` : "Niederlage") : b.won ? "abgewehrt" : `verloren, geplündert ${amounts(b.loot)}`, tone: b.won ? "win" : "loss" },
|
||||
]),
|
||||
});
|
||||
}
|
||||
for (const e of d.entries) timed.push([e.atMs, `${clockIn(e.atMs, timeZone)} ${e.title}: ${e.body}`]);
|
||||
timed.sort((a, b) => a[0] - b[0]);
|
||||
const items = timed.map(([, s]) => s);
|
||||
const items = d.entries.map((e) => `${clockIn(e.atMs, timeZone)} ${e.title}: ${e.body}`);
|
||||
if (d.scouts > 0) items.push(`${d.scouts} ${d.scouts === 1 ? "Aufklärungsbericht liegt" : "Aufklärungsberichte liegen"} vor.`);
|
||||
const shown = items.length > MAX_ITEMS ? [...items.slice(0, MAX_ITEMS), `… und ${items.length - MAX_ITEMS} weitere Meldungen`] : items;
|
||||
for (const s of d.extra) for (const l of s.lines.slice(0, 10)) shown.push(`${s.title}: ${l}`);
|
||||
if (shown.length) blocks.push({ type: "section", title: "Aufträge und Meldungen" }, { type: "list", items: shown });
|
||||
for (const s of d.extra) blocks.push({ type: "section", title: s.title }, { type: "list", items: s.lines.slice(0, 10) });
|
||||
|
||||
return {
|
||||
subject: `Morgenbericht ${new Date(d.nowMs).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", timeZone })}`,
|
||||
@@ -205,8 +221,7 @@ export function summaryMail(d: SummaryData, name: string, timeZone: string, unsu
|
||||
`Lage seit ${new Date(d.sinceMs).toLocaleString("de-DE", { weekday: "short", hour: "2-digit", minute: "2-digit", timeZone })} Uhr: ${summaryLine(d)}`,
|
||||
`Dein Bericht für ${day}.`,
|
||||
],
|
||||
facts,
|
||||
items: shown,
|
||||
blocks,
|
||||
button: { label: "Hafen öffnen", url: `${publicUrl()}/?tab=basis` },
|
||||
unsubscribeUrl,
|
||||
footerNote: "Du erhältst den Morgenbericht, weil du ihn in den Einstellungen eingeschaltet hast. Abschalten: Einstellungen → Morgenbericht.",
|
||||
|
||||
@@ -255,7 +255,7 @@ export async function eventMissionArrive(
|
||||
} else {
|
||||
notify.push([null, "map"]);
|
||||
}
|
||||
push.push(notice(pid, "report", `Kampfbericht: ${title}`, sumLoot(loot) > 0 ? `Beute: ${resText(loot)}.` : "Keine Beute."));
|
||||
push.push(notice(pid, "report", `Kampfbericht: ${title}`, sumLoot(loot) > 0 ? `Beute: ${resText(loot)}.` : "Keine Beute.", r.id));
|
||||
return { returning, cargoHome: loot, reportId: r.id, notify, push };
|
||||
}
|
||||
|
||||
|
||||
@@ -107,18 +107,18 @@ const worldEventAttack: Handler = async (tx, ev, due) => {
|
||||
await tx.insert(tables.wreck).values({ col: b.col, row: b.row, stahl: report.wreck.stahl ?? 0, elektronik: report.wreck.elektronik ?? 0, createdAt: new Date(due) });
|
||||
}
|
||||
const [p] = await tx.select({ name: tables.player.name }).from(tables.player).where(eq(tables.player.id, b.playerId));
|
||||
await tx.insert(tables.battleReport).values({
|
||||
const [rep] = await tx.insert(tables.battleReport).values({
|
||||
kind: "weltereignis", title: `Großflotte greift ${b.name} an`, attackerPlayerId: null, defenderPlayerId: b.playerId,
|
||||
attackerBaseId: null, defenderBaseId: b.id, nestId: null, winner: report.winner, seed, balanceVersion: balance.version,
|
||||
createdAt: new Date(due),
|
||||
report: { battle: report, attackerName: "Großflotte des Kartells", defenderName: p?.name ?? "?", targetName: b.name, attacker, worldEvent: { id: e.id, kind: e.kind } },
|
||||
});
|
||||
}).returning({ id: tables.battleReport.id });
|
||||
units = activeUnits(report.attacker.final);
|
||||
pool = addRes(pool, report.loot);
|
||||
pos = { col: b.col, row: b.row };
|
||||
targets[index] = { ...target, status: "attacked", winner: report.winner };
|
||||
const won = report.winner === "defender";
|
||||
push.push(notice(b.playerId, "attack", `Großflotte greift ${b.name} an`, won ? "Dein Hafen hat die Großflotte abgewehrt." : `Die Großflotte hat ${resText(report.loot)} erbeutet.`));
|
||||
push.push(notice(b.playerId, "attack", `Großflotte greift ${b.name} an`, won ? "Dein Hafen hat die Großflotte abgewehrt." : `Die Großflotte hat ${resText(report.loot)} erbeutet.`, rep.id));
|
||||
notify.push([[b.playerId], "base"], [[b.playerId], "reports"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,8 +97,8 @@ export async function systemMessage(tx: Tx, playerIds: number[], subject: string
|
||||
}
|
||||
|
||||
/** Push- bzw. E-Mail-Auftrag (nach dem Commit verschickt). */
|
||||
export function notice(playerId: number, kind: Notice["kind"], title: string, body: string): NoticeJob {
|
||||
return { playerId, notice: { kind, title, body, url: "/?tab=karte", tag: `weltereignis-${kind}` } };
|
||||
export function notice(playerId: number, kind: Notice["kind"], title: string, body: string, reportId?: number): NoticeJob {
|
||||
return { playerId, notice: { kind, title, body, url: "/?tab=karte", tag: `weltereignis-${kind}`, ...(reportId !== undefined ? { reportId } : {}) } }; // reportId: ausführliche E-Mail
|
||||
}
|
||||
|
||||
/** Alle Spieler mit Hafen (Empfänger von Ankündigungen), je Spieler einmal mit seinem Heimathafen. */
|
||||
|
||||
@@ -235,14 +235,14 @@ test("Morgenbericht: genau einmal je Tag, Inhalt korrekt, Abmelden schaltet ab",
|
||||
assert.ok(m.text.includes("Guten Morgen, Emil"));
|
||||
assert.ok(m.text.includes("Kämpfe: 1 (1 gewonnen, 0 verloren)"), m.text);
|
||||
assert.ok(m.text.includes(`Beute: ${loot.stahl.toLocaleString("de-DE")} Stahl`), m.text);
|
||||
assert.ok(m.text.includes("Überfall auf Piratennest Stufe 1 – Sieg"));
|
||||
assert.match(m.text, /Überfall auf Piratennest Stufe 1 +Sieg, Beute/, "Kampf als Tabellenzeile");
|
||||
assert.ok(m.text.includes("Fertige Aufträge: 1"));
|
||||
assert.ok(m.text.includes("Lieferungen: 1"));
|
||||
assert.ok(m.text.includes("Ausbau fertig: Werft ist jetzt auf Stufe 2."));
|
||||
assert.ok(m.text.includes("Neue Nachrichten: 1"));
|
||||
assert.match(m.text, /Rang in der Saison: \d+ von 2/);
|
||||
assert.ok(m.text.includes("Aufklärungsbericht liegt vor"));
|
||||
assert.ok(m.text.includes("Tagesbefehl: Drei Korvetten bauen"));
|
||||
assert.ok(m.text.includes("Tagesbefehl\n----------") && m.text.includes("- Drei Korvetten bauen"), "Zusatzabschnitt mit Titel");
|
||||
assert.ok(!m.text.includes("zählt nicht"));
|
||||
assert.ok(m.html.includes("Morgenbericht") && m.html.includes("Guten Morgen, Emil"));
|
||||
assert.ok(m.headers?.["List-Unsubscribe"]);
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
// Ausführliche E-Mails aus echten Berichten gegen ein echtes PostgreSQL (TEST_DATABASE_URL, wird geleert):
|
||||
// Kampf (Nest, Spielerhafen aus beiden Sichten), Aufklärung (Hafen, Nest, Feld), Spionage, Angriffswarnung,
|
||||
// Bündelung, Erfolg und der Standard für unbekannte Berichtsarten. Mit MAIL_PREVIEW_DIR werden die Mails als
|
||||
// .html/.txt abgelegt (für Bildschirmfotos).
|
||||
import { after, before, test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { createDb, migrateDb, tables } from "@tidefront/db";
|
||||
import { nestSites, isCoast, COLS, ROWS } from "@tidefront/world";
|
||||
import { spyRollOf, type BaseState, type SpyMission } from "@tidefront/game-core";
|
||||
import {
|
||||
chooseBase, deliverNotices, ensureFieldPlanner, fieldsView, flushMailDigests, launchMission, mailNotice, processDue, register,
|
||||
renderMail, reportMailParts, saveSmtp, seed, setMailSender, spyLaunch, type Engine, type NoticeJob, type OutgoingMail,
|
||||
} from "../src/index.ts";
|
||||
|
||||
const url = process.env.TEST_DATABASE_URL;
|
||||
const { db, client } = createDb(url ?? "postgres://invalid", 10);
|
||||
const pending: NoticeJob[] = [];
|
||||
const engine: Engine = { db, notify: () => {}, log: () => {}, push: (jobs) => { pending.push(...jobs); } };
|
||||
const mails: OutgoingMail[] = [];
|
||||
const PREVIEW = process.env.MAIL_PREVIEW_DIR;
|
||||
let keyN = 0;
|
||||
const key = () => `m${++keyN}-${Date.now()}`;
|
||||
const SEED_OK = (() => { let s = 1; while (spyRollOf(s, 20) !== 1) s++; return s; })();
|
||||
|
||||
function freeCoast(skip: number): { col: number; row: number } {
|
||||
const nests = new Set(nestSites().map((n) => `${n.col},${n.row}`));
|
||||
let k = 0;
|
||||
for (let row = 10; row < ROWS; row++) for (let col = 0; col < COLS; col++) {
|
||||
if (isCoast(col, row) && !nests.has(`${col},${row}`) && k++ === skip) return { col, row };
|
||||
}
|
||||
throw new Error("no coast");
|
||||
}
|
||||
|
||||
async function newPlayer(name: string, field: number) {
|
||||
const p = await register(db, { inviteCode: "TEST", name, password: "geheim123" });
|
||||
const f = freeCoast(field);
|
||||
const r = await chooseBase(engine, p.playerId, key(), { ...f, name: `Hafen ${name}`, nightShieldStartHour: null, tzOffsetMinutes: 0 });
|
||||
assert.equal(r.ok, true, JSON.stringify(r));
|
||||
const email = `${name.toLowerCase()}@example.org`;
|
||||
await db.insert(tables.playerEmail).values({ playerId: p.playerId, email, verifiedAt: new Date(), unsubscribeToken: (name.slice(0, 2).toLowerCase().replace(/[^a-f]/g, "a") + "0".repeat(46)).slice(0, 48) });
|
||||
return { playerId: p.playerId, baseId: (r as { baseId: number }).baseId, email, ...f };
|
||||
}
|
||||
|
||||
async function patchBase(baseId: number, patch: (s: BaseState) => void) {
|
||||
const [b] = await db.select().from(tables.base).where(eq(tables.base.id, baseId));
|
||||
const s = b.state as BaseState;
|
||||
patch(s);
|
||||
await db.update(tables.base).set({ state: s }).where(eq(tables.base.id, baseId));
|
||||
}
|
||||
|
||||
/** Ereignisse bis `ms` abarbeiten und die Benachrichtigungen (Push, E-Mail) zustellen. */
|
||||
async function runTo(ms: number) {
|
||||
await processDue(engine, ms);
|
||||
await deliverNotices(engine, pending.splice(0));
|
||||
}
|
||||
|
||||
/** Prüft eine Mail auf saubere Werte und legt sie für Bildschirmfotos ab. */
|
||||
function check(name: string, m: OutgoingMail | undefined, must: (string | RegExp)[]): OutgoingMail {
|
||||
assert.ok(m, `Mail ${name} fehlt`);
|
||||
for (const bad of ["undefined", "NaN", "[object Object]", "Infinity"]) {
|
||||
assert.ok(!m.html.includes(bad), `${name}: HTML enthält ${bad}`);
|
||||
assert.ok(!m.text.includes(bad), `${name}: Text enthält ${bad}`);
|
||||
assert.ok(!m.subject.includes(bad), `${name}: Betreff enthält ${bad}`);
|
||||
}
|
||||
assert.ok(m.text.length > 200, `${name}: Textversion vorhanden`);
|
||||
assert.ok(m.html.includes("prefers-color-scheme: dark") && m.html.includes("Im Spiel öffnen"));
|
||||
assert.ok(m.text.includes("abbestellen") || m.text.includes("Abbestellen"), `${name}: Abmeldelink im Text`);
|
||||
for (const x of must) {
|
||||
if (typeof x === "string") assert.ok(m.text.includes(x) && m.html.includes(x.replace(/&/g, "&")), `${name}: „${x}“ fehlt\n${m.text}`);
|
||||
else assert.match(m.text, x, name);
|
||||
}
|
||||
if (PREVIEW) {
|
||||
mkdirSync(PREVIEW, { recursive: true });
|
||||
writeFileSync(join(PREVIEW, `${name}.html`), m.html);
|
||||
writeFileSync(join(PREVIEW, `${name}.txt`), `Betreff: ${m.subject}\n\n${m.text}`);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
const lastTo = (to: string) => mails.filter((m) => m.to === to).at(-1);
|
||||
|
||||
let A: Awaited<ReturnType<typeof newPlayer>>;
|
||||
let B: Awaited<ReturnType<typeof newPlayer>>;
|
||||
|
||||
before(async () => {
|
||||
if (!url) throw new Error("TEST_DATABASE_URL fehlt");
|
||||
await db.execute(sql`drop schema if exists public cascade; drop schema if exists drizzle cascade; create schema public;`);
|
||||
await migrateDb(db);
|
||||
await seed(db, "TEST:100");
|
||||
process.env.APP_SECRET = "test-geheimnis-0123456789abcdef";
|
||||
setMailSender(async (_cfg, mail) => { mails.push(mail); });
|
||||
assert.equal((await saveSmtp(db, { enabled: true, provider: "custom", host: "smtp.test", port: 25, security: "none", user: "", password: "", fromName: "TIDEFRONT", fromAddress: "tf@x.test" })).ok, true);
|
||||
A = await newPlayer("Anna", 5);
|
||||
B = await newPlayer("Bert", 14);
|
||||
await patchBase(A.baseId, (s) => {
|
||||
s.units = { korvette: 8, zerstoerer: 4, landungsschiff: 6, schuetzen: 400, kampfpanzer: 30, jagdbomber: 6, spion: 4 };
|
||||
s.resources.treibstoff = 200000; s.resources.proviant = 200000;
|
||||
s.buildings.kommandozentrale = 10; s.buildings.nachrichtendienst = 4; s.buildings.hafenkommandantur = 6; s.buildings.lagerkomplex = 8;
|
||||
s.veterancy = { korvette: 500, schuetzen: 80 };
|
||||
});
|
||||
await patchBase(B.baseId, (s) => {
|
||||
s.protection.createdAtMs = 0;
|
||||
s.units = { schuetzen: 40, korvette: 2 };
|
||||
s.defenses = { kuestenbatterie: 2, flakstellung: 1 };
|
||||
s.resources.stahl = 20000; s.resources.proviant = 50000;
|
||||
s.buildings.kraftwerk = 3; s.buildings.stahlwerk = 3; s.buildings.lagerkomplex = 8; s.buildings.radarstation = 4;
|
||||
});
|
||||
// Keine Kartell-Überfälle zwischendurch (sie würden Schutz nach Niederlage auslösen).
|
||||
await db.delete(tables.gameEvent).where(eq(tables.gameEvent.type, "raid_launch"));
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
setMailSender(null);
|
||||
await client.end();
|
||||
});
|
||||
|
||||
test("Kampfbericht Nest: Sieg, Verbände als Tabelle, Beute, Kurzfazit, Betreff mit Beute, Direktlink", async () => {
|
||||
const nests = await db.select().from(tables.nest).where(eq(tables.nest.level, 1));
|
||||
const near = nests.map((n) => ({ n, d: Math.hypot(n.col - A.col, n.row - A.row) })).sort((x, y) => x.d - y.d)[0].n;
|
||||
const m = await launchMission(engine, A.playerId, key(), { type: "ueberfall", units: { korvette: 4, landungsschiff: 4, schuetzen: 200 }, col: near.col, row: near.row });
|
||||
assert.equal(m.ok, true, JSON.stringify(m));
|
||||
const [mission] = await db.select().from(tables.mission).where(eq(tables.mission.id, (m as { missionId: number }).missionId));
|
||||
await runTo(mission.arriveAt.getTime() + 1);
|
||||
const [arrived] = await db.select().from(tables.mission).where(eq(tables.mission.id, mission.id));
|
||||
const mail = check("kampf-nest-sieg", lastTo(A.email), ["Kampfbericht", "Einheit", "Start", "Verlust", "Übrig", "Beute", "Gewonnen mit"]);
|
||||
assert.match(mail.subject, /^TIDEFRONT: Sieg bei Piratennest Stufe 1 – Beute [\d.]+ /, mail.subject);
|
||||
assert.ok(mail.html.includes(`?tab=berichte&bericht=${arrived.reportId}`), "Knopf öffnet den Bericht");
|
||||
assert.ok(mail.text.includes("Korvette · "), "Veteranenrang der eigenen Einheit");
|
||||
assert.ok(mail.text.includes("Piratenmiliz") || mail.text.includes("Schnellboot"), "Gegner mit Namen");
|
||||
await runTo(arrived.returnAt!.getTime() + 1);
|
||||
});
|
||||
|
||||
test("Aufklärung: Spielerhafen mit Lagebild, Piratennest Stufe 2, Rohstofffeld", async () => {
|
||||
const scout = await launchMission(engine, A.playerId, key(), { type: "aufklaerung", units: { korvette: 1 }, col: B.col, row: B.row });
|
||||
assert.equal(scout.ok, true, JSON.stringify(scout));
|
||||
await runTo((scout as { arriveAtMs: number }).arriveAtMs + 1);
|
||||
const m = check("aufklaerung-hafen", lastTo(A.email), ["Lagebild von Hafen Bert", "Bestände", "Schützen", "Küstenbatterie", "Gebäude", "Bunkerschutz"]);
|
||||
assert.match(m.subject, /Aufklärung: Hafen Bert – \d+ Einheiten, 3 Anlagen/, m.subject);
|
||||
|
||||
const nest2 = (await db.select().from(tables.nest).where(eq(tables.nest.level, 2)))
|
||||
.map((n) => ({ n, d: Math.hypot(n.col - A.col, n.row - A.row) })).sort((x, y) => x.d - y.d)[0].n;
|
||||
const ns = await launchMission(engine, A.playerId, key(), { type: "aufklaerung", units: { korvette: 1 }, col: nest2.col, row: nest2.row });
|
||||
assert.equal(ns.ok, true, JSON.stringify(ns));
|
||||
await runTo((ns as { arriveAtMs: number }).arriveAtMs + 1);
|
||||
const nm = check("aufklaerung-nest", lastTo(A.email), ["Piratennest Stufe 2", "Besatzung", "Mögliche Beute"]);
|
||||
assert.match(nm.subject, /Aufklärung: Piratennest Stufe 2/);
|
||||
|
||||
await ensureFieldPlanner(db, Date.now());
|
||||
const view = (await fieldsView(engine, A.playerId))!;
|
||||
const target = [...view.fields].sort((x, y) => Math.hypot(x.col - A.col, x.row - A.row) - Math.hypot(y.col - A.col, y.row - A.row))[0];
|
||||
const fs = await launchMission(engine, A.playerId, key(), { type: "aufklaerung", units: { korvette: 1 }, col: target.col, row: target.row, fieldId: target.id });
|
||||
assert.equal(fs.ok, true, JSON.stringify(fs));
|
||||
await runTo((fs as { arriveAtMs: number }).arriveAtMs + 1);
|
||||
const fm = check("aufklaerung-feld", lastTo(A.email), ["Feld-Aufklärung", "Kartell-Wache", "Stufe"]);
|
||||
assert.match(fm.subject, /Aufklärung: .+ \(Stufe \d\) – Wache \d+ Einheit/, fm.subject);
|
||||
});
|
||||
|
||||
test("Angriff auf Spielerhafen: Warnung mit Schritten, Kampfbericht für beide Seiten", async () => {
|
||||
const m = await launchMission(engine, A.playerId, key(), { type: "ueberfall", units: { korvette: 3, zerstoerer: 4, landungsschiff: 4, schuetzen: 150, kampfpanzer: 20 }, col: B.col, row: B.row });
|
||||
assert.equal(m.ok, true, JSON.stringify(m));
|
||||
const id = (m as { missionId: number }).missionId;
|
||||
const [warn] = await db.select().from(tables.gameEvent).where(and(eq(tables.gameEvent.type, "attack_warning"), sql`${tables.gameEvent.payload}->>'missionId' = ${String(id)}`));
|
||||
assert.ok(warn, "Warnung geplant");
|
||||
const [mission] = await db.select().from(tables.mission).where(eq(tables.mission.id, id));
|
||||
assert.ok(warn.dueAt.getTime() < mission.arriveAt.getTime() - 60000, "Radar warnt vor der Ankunft");
|
||||
await runTo(warn.dueAt.getTime() + 1);
|
||||
const w = check("angriffswarnung", lastTo(B.email), ["Ankunft in", "Empfohlene Schritte", "Truppen daheim lassen", "Bunkerschutz", "Größenklasse"]);
|
||||
assert.match(w.subject, /^TIDEFRONT: ⚠︎ Angriff auf Hafen Bert in /, w.subject);
|
||||
await runTo(mission.arriveAt.getTime() + 1);
|
||||
const att = check("kampf-hafen-angreifer", lastTo(A.email), ["Verband Anna (du)", "Gegner Bert", "Bunkerschutz Bert"]);
|
||||
assert.match(att.subject, /(Sieg|Niederlage) bei Hafen Bert/);
|
||||
const def = check("kampf-hafen-verteidiger", lastTo(B.email), ["Verteidigung Bert (du)", "Plünderung"]);
|
||||
assert.match(def.subject, /Hafen Bert (gehalten|überwunden)/, def.subject);
|
||||
});
|
||||
|
||||
test("Spionage: Dossier für den Absender", async () => {
|
||||
const r = await spyLaunch(engine, A.playerId, key(), { kind: "erkunden", col: B.col, row: B.row });
|
||||
assert.equal(r.ok, true, JSON.stringify(r));
|
||||
const [m0] = await db.select().from(tables.mission).where(eq(tables.mission.id, (r as { missionId: number }).missionId));
|
||||
const plan = m0.plan as SpyMission;
|
||||
await db.update(tables.mission).set({ plan: { ...plan, spy: { ...plan.spy, seed: SEED_OK } } }).where(eq(tables.mission.id, m0.id));
|
||||
await runTo(plan.arriveAtMs + 1000);
|
||||
const s = check("spionage", lastTo(A.email), ["Gelungen", "Dossier", "Wurf"]);
|
||||
assert.match(s.subject, /Spionage: Erkunden gegen Hafen Bert – gelungen/, s.subject);
|
||||
});
|
||||
|
||||
test("Bündelung und Erfolg: Tabelle mit Zeiten, Kennzahlen als Kacheln", async () => {
|
||||
await db.update(tables.playerEmail).set({ prefs: { build: true, training: true } }).where(eq(tables.playerEmail.playerId, B.playerId));
|
||||
assert.equal(await mailNotice(engine, B.playerId, { kind: "build", title: "Ausbau fertig", body: "Werft ist jetzt auf Stufe 3.", facts: [["Gebäude", "Werft"], ["Stufe", "3"]] }), "queued");
|
||||
assert.equal(await mailNotice(engine, B.playerId, { kind: "build", title: "Ausbau fertig", body: "Kaserne ist jetzt auf Stufe 4." }), "queued");
|
||||
assert.equal(await mailNotice(engine, B.playerId, { kind: "training", title: "Ausbildung fertig", body: "Bereit: 25 Schützen." }), "queued");
|
||||
assert.equal(await flushMailDigests(engine, Date.now()), 1);
|
||||
const d = check("buendelung", lastTo(B.email), ["Werft ist jetzt auf Stufe 3.", "Bereit: 25 Schützen.", "Meldung"]);
|
||||
assert.match(d.subject, /3 Meldungen aus deinem Hafen: Ausbau fertig \(2\), Ausbildung fertig/, d.subject);
|
||||
|
||||
assert.equal(await mailNotice(engine, B.playerId, {
|
||||
kind: "report", title: "Erfolg: Seebär (Silber)", body: "10 Kämpfe gewonnen. Belohnung abholen unter Meldungen → Erfolge.",
|
||||
facts: [["Erfolg", "Seebär"], ["Stufe", "Silber"], ["Erreicht", "10 Siege"]], mail: { subject: "Erfolg freigeschaltet: Seebär (Silber)" },
|
||||
}), "sent");
|
||||
const e = check("erfolg", lastTo(B.email), ["Seebär", "Silber"]);
|
||||
assert.equal(e.subject, "TIDEFRONT: Erfolg freigeschaltet: Seebär (Silber)");
|
||||
});
|
||||
|
||||
test("Standard für unbekannte Berichtsarten, Kürzung langer Tabellen, HTML maskiert", () => {
|
||||
const units: Record<string, number> = {};
|
||||
for (let i = 0; i < 26; i++) units[`einheit${i}`] = 26 - i;
|
||||
const parts = reportMailParts({
|
||||
id: 1, kind: "patrouille", title: "Patrouille <Nordmeer> & Co", atMs: Date.UTC(2026, 10, 27, 13, 5), role: "attacker", winner: null,
|
||||
data: { sector: "Nordmeer", sichtungen: 3, gesichtet: units, sicht: { radius: 120, fremd: { korvette: 2 } } },
|
||||
});
|
||||
assert.equal(parts.blocks[0].type, "banner");
|
||||
const m = renderMail({ subject: parts.subject, heading: parts.heading, paragraphs: [], preheader: parts.lead, blocks: parts.blocks, button: { label: "Im Spiel öffnen", url: "https://x.test/?tab=berichte&bericht=1" }, unsubscribeUrl: "https://x.test/u" });
|
||||
check("unbekannte-art", { to: "x", ...m }, ["Nordmeer", "Sichtungen", "Korvette", "6 weitere Zeilen"]);
|
||||
assert.ok(m.html.includes("Patrouille <Nordmeer> & Co") && !m.html.includes("<Nordmeer>"), "maskiert");
|
||||
assert.ok(m.text.includes("Patrouille <Nordmeer> & Co"), "Text unmaskiert");
|
||||
});
|
||||
Reference in new issue
Block a user