Upstream/public/js/screens/reports.js
jvanvik 931f59e11e Phase 3: trade/end-game client, bot simulator, first balance pass
Built:
- Client: trade screen, world/end-game screen (landing sites, shipping, node build, final ranking), report sharing + alliance reports tab, alert describers for all notification types, error-code strings (en+nb) for every server CODE.
- tools/bot.js (+ tools/bot/): 50 headless bots against the real server in-process with a fake clock; resource/unit conservation ledger, exit 1 on broken invariants. docs/BALANCE.md has method and every run behind a number.
- Balance changes (evidence in docs/BALANCE.md): secondQueueCoreLevel 10 -> 3, TRANSPORT.capacityPerLink 500 -> 1000 (end game was shipping-limited in bot runs).
- Server fixes: POST /reports/:id/share 500 without a pending reportCleanup; bounced link shipments were silent about cargo overflow.

Tested: npm test 207/207 (new: bot determinism + invariants, client alerts/world/i18n over CODES, two regression tests that failed before their fix); openapi check up to date. Real-browser scratch runs (not in repo): WebSocket push shows an incoming-attack banner ~214 ms after launch, polling fallback ~52 s, 15 scripted flows, 71 screenshots.

NOT tested: Playwright suite (e2e/ still empty), real devices/Safari, nginx proxy websockets, throttled networks, HTTP-level bot load. NOT claimed: balance. Bots are not humans; open balance items (loot waste, escrow refund clipping, no garrisons at landing sites, end game not scaling with world speed) are listed in docs/BALANCE.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-11 20:24:41 +02:00

425 lines
27 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/*
* Reports: newest first, cursor-paginated (GET /reports?after=<last id>), unread highlighted, a detail sheet per report
* (GET /reports/:id, then POST /reports/:id/read). Detail layouts exist for battle (raid/attack/takeover), landing (an attack on a backbone
* landing site), scan (also of a landing site), scan_detected, incumbent, settle, reinforce and movement_failed; coordinates are links that
* jump to the map. `data` differs by report type AND by the recipient's role (attacker / defender / reinforcer / sender / target).
* Alliance folder: a report can be shared with your alliance (POST /reports/:id/share) and the "Alliance" tab lists the folder
* (GET /alliances/:id/reports). Shared reports have no recipient role and no read flag: they are told from nobody's side ("attacker won").
*/
(function () {
const { h, clear, icon, toast, openSheet } = UI;
const D = UpstreamData;
const Mil = UpstreamMil;
const mil = () => App.mil;
const num = (n) => App.fmt.num(n);
const PAGE = 25;
let box, listEl, moreBtn, statusEl, items = [], next = null, loading = false, visible = false, offAgo = null;
let tabsEl, markBtn, mode = 'mine'; // 'mine' | 'alliance' (the shared folder)
const folder = { items: [], next: null, loaded: false };
const allianceId = () => (App.state.operator ? App.state.operator.allianceId : null);
const curItems = () => (mode === 'alliance' ? folder.items : items);
const curNext = () => (mode === 'alliance' ? folder.next : next);
// ------------------------------------------------------------------ list rows
const nameOf = (o) => (o && o.name) || '?';
const townOf = (t) => (t ? t.name : '?');
// { icon, title, sub, tone } for the list
function describe(it) {
const s = it.summary || {};
const sharedItem = !it.role; // alliance folder: nobody's side
switch (it.type) {
case 'raid': case 'attack': case 'takeover': {
if (sharedItem) {
return { icon: Mil.TYPE_ICON[it.type], title: mil().reportTypeLabel(it.type) + ': ' + townOf(s.target), sub: App.t('rep.vs', { a: nameOf(s.attacker), d: nameOf(s.defender) }) + (s.captured ? ' · ' + App.t('rep.captured') : ''), tone: 'neutral', badge: App.t(s.outcome === 'attacker_won' ? 'rep.attackerWon' : 'rep.defenderWon') };
}
const res = Mil.perspective(it.role, s.outcome);
const mine = it.role === 'attacker';
const title = mil().reportTypeLabel(it.type) + ': ' + townOf(s.target);
const sub = mine ? App.t('rep.sub.you_vs', { name: nameOf(s.defender) }) : App.t('rep.sub.by', { name: nameOf(s.attacker) });
return { icon: Mil.TYPE_ICON[it.type], title, sub: sub + (s.captured ? ' · ' + App.t('rep.captured') : ''), tone: res === 'victory' ? 'good' : 'bad', badge: App.t('rep.' + res) };
}
case 'landing': {
const site = s.site || {};
const taken = !!s.taken;
const res = sharedItem ? null : Mil.perspective(it.role, s.outcome);
return { icon: 'b-backbone_node', title: App.t('rep.landing.title', { n: Number.isInteger(site.index) ? site.index + 1 : '?' }), sub: sharedItem ? App.t('rep.by', { name: nameOf(s.attacker) }) + ' · ' + (taken ? App.t('rep.landing.taken') : App.t('rep.landing.held')) : (taken ? App.t('rep.landing.taken') : App.t('rep.landing.held')), tone: res === null ? 'neutral' : (res === 'victory' ? 'good' : 'bad'), badge: res === null ? null : App.t('rep.' + res) };
}
case 'scan': {
const where = s.target ? townOf(s.target) : (s.site ? (s.site.type === 'backbone' ? App.t('wld.site', { n: s.site.index + 1 }) : s.site.x + ', ' + s.site.y) : '?');
return { icon: 'eye', title: App.t('rep.scan.title', { where }), sub: s.success ? App.t('rep.scan.ok') : App.t('rep.scan.failed'), tone: s.success ? 'good' : 'bad' };
}
case 'scan_detected':
return { icon: 'eye', title: App.t('rep.detected.title', { town: townOf(s.target) }), sub: s.identityRevealed && s.by ? App.t('rep.sub.by', { name: nameOf(s.by) }) : App.t('rep.detected.unknown'), tone: 'warn' };
case 'incumbent':
return { icon: 'b-core_router', title: App.t('rep.incumbent.title', { x: s.site ? s.site.x : '?', y: s.site ? s.site.y : '?' }), sub: '', tone: s.outcome === 'attacker_won' ? 'good' : 'bad', badge: s.outcome === 'attacker_won' ? App.t('rep.victory') : App.t('rep.defeat') };
case 'settle':
return { icon: 'flag', title: App.t('rep.settle.title', { name: s.town ? s.town.name : '?' }), sub: '', tone: 'good' };
case 'reinforce':
return { icon: 'shield', title: it.role === 'sender' ? App.t('rep.reinforce.sender', { town: townOf(s.host) }) : App.t('rep.reinforce.target', { town: townOf(s.host) }), sub: mil().unitsText(s.units), tone: 'neutral' };
case 'movement_failed':
return { icon: 'alert', title: App.t('rep.failed.title', { type: mil().typeLabel(s.movementType) }), sub: reasonText(s.reason), tone: 'bad' };
default:
return { icon: 'report', title: mil().reportTypeLabel(it.type), sub: '', tone: 'neutral' };
}
}
function reasonText(code) {
if (!code) return '';
if (UpstreamI18n.strings.en['rep.reason.' + code]) return App.t('rep.reason.' + code);
if (UpstreamI18n.strings.en['err.' + code]) return App.t('err.' + code);
return code;
}
function row(it) {
const d = describe(it);
const unread = it.read === false; // shared items have no read flag
const shared = mode === 'alliance';
return h('li', null, h('button', { class: 'alert rep tone-' + d.tone + (unread ? ' new' : ''), type: 'button', dataset: { id: String(it.id) }, onclick: () => openReport(it.id, shared) },
h('span', { class: 'row-ic' }, icon(d.icon)),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: d.title }), d.badge ? h('span', { class: 'pill ' + (d.tone === 'good' ? 'green' : 'amber'), text: d.badge }) : null, unread ? h('span', { class: 'pill accent', text: App.t('alerts.new') }) : null),
d.sub ? h('span', { class: 'row-sub', text: d.sub }) : null,
shared && it.sharedBy ? h('span', { class: 'row-sub', text: App.t('rep.sharedBy', { name: it.sharedBy.name }) }) : null),
h('span', { class: 'when mono', dataset: { at: String(it.createdAt) }, text: App.fmt.ago(App.now() - it.createdAt) })));
}
function draw() {
clear(listEl);
const list = curItems();
if (mode === 'alliance' && !allianceId()) { listEl.appendChild(h('li', null, h('p', { class: 'empty pad', text: App.t('rep.folder.none') }))); moreBtn.hidden = true; return; }
if (!list.length) { listEl.appendChild(h('li', null, h('p', { class: 'empty pad', text: loading || (mode === 'alliance' && !folder.loaded) ? App.t('common.loading') : App.t(mode === 'alliance' ? 'rep.folder.empty' : 'rep.empty') }))); }
for (const it of list) listEl.appendChild(row(it));
moreBtn.hidden = curNext() === null;
if (markBtn) markBtn.hidden = mode === 'alliance';
drawTabs();
}
function drawTabs() {
if (!tabsEl) return;
tabsEl.hidden = !allianceId();
clear(tabsEl);
for (const k of ['mine', 'alliance']) tabsEl.appendChild(h('button', { class: 'seg-btn', type: 'button', dataset: { tab: k }, 'aria-pressed': String(mode === k), onclick: () => { mode = k; draw(); load(false); } }, App.t(k === 'mine' ? 'rep.tab.mine' : 'rep.tab.alliance')));
}
async function load(more) {
if (loading) return;
if (mode === 'alliance') {
if (!allianceId()) { draw(); return; }
loading = true; statusEl.hidden = true;
try {
const r = await App.api.get('/alliances/' + allianceId() + '/reports', { limit: PAGE, after: more ? folder.next : undefined });
folder.items = more ? folder.items.concat(r.items.filter((x) => !folder.items.some((y) => y.id === x.id))) : r.items;
folder.next = r.next; folder.loaded = true;
} catch (e) { statusEl.textContent = e.code === 'forbidden' ? App.t('rep.folder.forbidden') : App.errMsg(e); statusEl.hidden = false; folder.loaded = true; }
finally { loading = false; }
draw();
return;
}
loading = true; statusEl.hidden = true;
try {
const r = await App.api.get('/reports', { limit: PAGE, after: more ? next : undefined });
items = more ? items.concat(r.items.filter((x) => !items.some((y) => y.id === x.id))) : r.items;
next = r.next;
mil().reportsUnread = r.unread;
App.setBadge('reports', r.unread, 'info');
} catch (e) {
statusEl.textContent = App.errMsg(e); statusEl.hidden = false;
} finally { loading = false; }
draw();
}
async function markAll() {
try {
await App.api.post('/reports/read-all', {}, { intent: 'reports:read-all' });
for (const it of items) it.read = true;
App.setBadge('reports', 0, 'info');
draw();
} catch (e) { toast(App.errMsg(e), 'error'); }
}
// ------------------------------------------------------------------ detail pieces
const sec = (title, ...kids) => h('section', { class: 'rep-sec' }, h('h3', { class: 'sub', text: title }), kids);
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
function unitsTable(sent, lost, survivors) {
const ids = D.UNIT_ORDER.filter((u) => (sent && sent[u]) || (lost && lost[u]) || (survivors && survivors[u]));
if (!ids.length) return h('p', { class: 'empty', text: App.t('rep.noUnits') });
return h('table', { class: 'mil-table' },
h('thead', null, h('tr', null, h('th', { text: '' }), h('th', { text: App.t('rep.sent') }), h('th', { text: App.t('rep.lost') }), h('th', { text: App.t('rep.left') }))),
h('tbody', null, ids.map((u) => h('tr', null,
h('td', { text: mil().unitName(u) }),
h('td', { class: 'mono', text: num((sent && sent[u]) || 0) }),
h('td', { class: 'mono' + (lost && lost[u] ? ' bad' : ''), text: num((lost && lost[u]) || 0) }),
h('td', { class: 'mono', text: num((survivors && survivors[u]) || 0) })))));
}
const party = (label, operator, town) => kv(label, h('span', { class: 'rep-party' },
h('b', { text: operator ? operator.name : '?' }), operator && operator.asNumber ? h('small', { class: 'dimmer', text: ' ' + UpstreamI18n.fmtAs(operator.asNumber) }) : null,
town ? mil().endLink(town) : null));
function verdict(role, outcome) {
if (!role) return h('div', { class: 'rep-verdict neutral' }, icon('report'), h('b', { text: App.t(outcome === 'attacker_won' ? 'rep.attackerWon' : 'rep.defenderWon') })); // shared: nobody's side
const res = Mil.perspective(role, outcome);
return h('div', { class: 'rep-verdict ' + res }, icon(res === 'victory' ? 'check' : 'alert'), h('b', { text: App.t('rep.' + res) }));
}
function combatBody(r) {
const d = r.data, out = [];
out.push(verdict(r.role, d.outcome));
out.push(h('p', { class: 'row-sub', text: App.t('rep.arrived', { t: mil().dayTime(d.arrivedAt) }) + ' · ' + mil().reportTypeLabel(d.type) }));
out.push(party(App.t('rep.attacker'), d.attacker.operator, d.attacker.town));
out.push(party(App.t('rep.defender'), d.defender.operator, d.defender.town));
const p = d.power || {};
out.push(sec(App.t('rep.power'),
kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(p.attack || 0) })),
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(p.defence || 0) })),
p.firewallLevel !== undefined ? kv(App.t('rep.power.firewall'), h('span', { class: 'mono', text: p.firewallLevel + (p.effectiveFirewall !== undefined && p.effectiveFirewall !== p.firewallLevel ? ' → ' + App.fmt.dec(p.effectiveFirewall) : '') })) : null));
out.push(sec(App.t('rep.attackerUnits'), unitsTable(d.attacker.units.sent, d.attacker.units.lost, d.attacker.units.survivors)));
const groups = (d.defender.groups || []);
out.push(sec(App.t('rep.defenderUnits'), groups.length ? groups.map((g) => h('div', { class: 'rep-group' },
h('p', { class: 'row-sub wrap' }, g.ownerTownId === (d.defender.town && d.defender.town.id) ? App.t('rep.group.home') : App.t('rep.group.reinf', { town: '#' + g.ownerTownId }), g.offline ? ' · ' + App.t('rep.group.offline') : ''),
unitsTable(g.sent, g.lost, g.survivors))) : h('p', { class: 'empty', text: App.t('rep.noUnits') })));
if (d.loot && D.RESOURCES.some((x) => d.loot[x])) {
out.push(sec(App.t('rep.loot'), mil().resChips(d.loot, true), d.cacheHidden ? h('p', { class: 'row-sub', text: App.t('rep.cache', { p: Math.round(d.cacheHidden * 100) }) }) : null));
}
if (d.siege) out.push(sec(App.t('rep.siege'), h('p', { text: App.t('rep.siege.line', { name: App.buildingName(d.siege.type), a: d.siege.from, b: d.siege.to }) })));
if (d.takeover) {
const t = d.takeover;
const lines = [];
if (t.blocked) lines.push(h('p', { class: 'reason', text: App.t('rep.takeover.blocked.' + t.blocked) }));
else {
lines.push(kv(App.t('rep.takeover.loyalty'), h('b', { class: 'mono', text: num(t.loyaltyBefore) + ' → ' + num(t.loyaltyAfter) + ' (−' + num(t.drop) + ')' })));
if (t.capital) lines.push(h('p', { class: 'row-sub wrap', text: App.t('rep.takeover.capital') }));
}
if (d.capturedTown) lines.push(h('p', { class: 'good', text: App.t('rep.takeover.captured') }));
out.push(sec(App.t('rep.takeover'), lines));
}
return out;
}
function scanBody(r) {
const d = r.data, out = [];
out.push(h('div', { class: 'rep-verdict ' + (d.success ? 'victory' : 'defeat') }, icon(d.success ? 'eye' : 'alert'), h('b', { text: d.success ? App.t('rep.scan.ok') : App.t('rep.scan.failed') })));
if (d.site) out.push(kv(App.t('rep.site'), mil().coordLink(d.site.x, d.site.y)));
if (d.target) out.push(party(App.t('rep.defender'), d.operator, d.target));
if (d.strength) out.push(kv(App.t('rep.scan.strength'), h('span', { class: 'mono', text: App.fmt.dec(d.strength.attacker) + ' vs ' + App.fmt.dec(d.strength.defender) })));
out.push(sec(App.t('rep.scanners'), unitsTable(d.scanners && d.scanners.sent, d.scanners && d.scanners.lost, d.scanners && d.scanners.survivors)));
const intel = d.intel;
if (!intel) { out.push(h('p', { class: 'reason', text: App.t('rep.scan.noIntel') })); return out; }
if (d.site && d.site.type === 'backbone') { // end game landing site: the static defence is the number to beat
out.push(sec(App.t('rep.intel'),
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(intel.defence) })),
kv(App.t('wld.levelShort'), h('b', { class: 'mono', text: App.t('wld.level', { n: intel.level || 0, max: D.ENDGAME.maxLevel }) })),
kv(App.t('rep.landing.holder'), h('span', { text: intel.holder ? '[' + intel.holder.tag + '] ' + intel.holder.name : App.t('wld.incumbent') })),
intel.build ? kv(App.t('wld.building', { n: intel.build.toLevel }), h('span', { text: mil().dayTime(intel.build.dueAt) })) : null));
return out;
}
if (d.site) { // incumbent site
out.push(sec(App.t('rep.intel'),
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(intel.defence) })),
intel.bonusAvailable ? h('p', { class: 'row-sub wrap', text: App.t('rep.incumbent.bonus', { n: num(intel.hardwareBonus) }) }) : h('p', { class: 'row-sub wrap', text: App.t('rep.incumbent.taken') })));
return out;
}
out.push(sec(App.t('rep.intel.resources'), mil().resChips(intel.resources)));
out.push(sec(App.t('rep.intel.units'),
!intel.online ? h('p', { class: 'reason', text: App.t('rep.intel.offline') }) : null,
unitsTable(intel.units.home, {}, intel.units.home),
(intel.units.stationed || []).map((g) => h('div', { class: 'rep-group' }, h('p', { class: 'row-sub wrap', text: App.t('rep.group.reinf', { town: '#' + g.ownerTownId }) }), h('p', { text: mil().unitsText(g.units) })))));
if (intel.buildings) {
out.push(sec(App.t('rep.intel.buildings'),
h('ul', { class: 'rep-buildings' }, intel.buildings.filter((b) => b.level > 0).map((b) => h('li', null, h('span', { text: App.buildingName(b.type) }), h('b', { class: 'mono', text: String(b.level) }))))));
}
if (intel.loyalty !== undefined) out.push(kv(App.t('pop.loyalty'), h('b', { class: 'mono', text: num(intel.loyalty) })));
if (intel.outgoing && intel.outgoing.length) {
out.push(sec(App.t('rep.intel.outgoing'), h('ul', { class: 'rep-buildings' }, intel.outgoing.map((m) => h('li', null, h('span', { text: mil().typeLabel(m.type) }), mil().coordLink(m.to.x, m.to.y), h('small', { class: 'dimmer', text: mil().clockTime(m.arriveAt) }))))));
}
return out;
}
function detectedBody(r) {
const d = r.data, out = [];
out.push(h('div', { class: 'rep-verdict defeat' }, icon('eye'), h('b', { text: App.t('rep.detected.title', { town: townOf(d.target) }) })));
if (d.target) out.push(kv(App.t('rep.target'), mil().endLink(d.target)));
if (d.identityRevealed && d.by) out.push(party(App.t('rep.scannedBy'), d.by.operator, d.by.town));
else out.push(h('p', { class: 'row-sub wrap', text: App.t('rep.detected.unknown') }));
return out;
}
function incumbentBody(r) {
const d = r.data, out = [];
out.push(verdict(r.role ? 'attacker' : null, d.outcome));
out.push(kv(App.t('rep.site'), mil().coordLink(d.site.x, d.site.y)));
if (d.origin) out.push(kv(App.t('rep.from'), mil().endLink(d.origin)));
out.push(sec(App.t('rep.power'), kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(d.power.attack) })), kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(d.power.defence) }))));
out.push(sec(App.t('rep.attackerUnits'), unitsTable(d.attacker.units.sent, d.attacker.units.lost, d.attacker.units.survivors)));
if (d.bonus) out.push(sec(App.t('rep.incumbent.reward'), mil().resChips({ hardware: d.bonus.hardware }, true), d.bonus.researchSpeedBonus ? h('p', { class: 'row-sub', text: App.t('units.research.speed', { p: Math.round(d.bonus.researchSpeedBonus * 100) }) }) : null));
return out;
}
function landingBody(r) {
const d = r.data, out = [];
const site = d.site || {};
out.push(verdict(r.role, d.outcome));
out.push(h('p', { class: 'row-sub', text: App.t('rep.arrived', { t: mil().dayTime(d.arrivedAt) }) }));
out.push(kv(App.t('rep.site'), h('span', { class: 'rep-party' }, h('b', { text: Number.isInteger(site.index) ? App.t('wld.site', { n: site.index + 1 }) : '?' }), mil().coordLink(site.x, site.y))));
out.push(kv(App.t('rep.landing.holder'), h('span', { text: site.holder ? '[' + site.holder.tag + '] ' + site.holder.name : App.t('wld.incumbent') })));
out.push(kv(App.t('wld.levelShort'), h('b', { class: 'mono', text: App.t('wld.level', { n: site.level || 0, max: D.ENDGAME.maxLevel }) })));
out.push(d.taken ? h('p', { class: 'good', text: App.t('rep.landing.takenLine', { tag: d.attacker && d.attacker.alliance ? '[' + d.attacker.alliance.tag + '] ' + d.attacker.alliance.name : '?' }) }) : h('p', { class: 'row-sub wrap', text: App.t('rep.landing.heldLine') }));
out.push(party(App.t('rep.attacker'), d.attacker.operator, d.origin));
const p = d.power || {};
out.push(sec(App.t('rep.power'), kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(p.attack || 0) })), kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(p.defence || 0) }))));
out.push(sec(App.t('rep.attackerUnits'), unitsTable(d.attacker.units.sent, d.attacker.units.lost, d.attacker.units.survivors)));
out.push(h('button', { class: 'btn wide', type: 'button', 'data-keep': '', onclick: () => { UI.closeSheet(); App.go('world', Number.isInteger(site.index) ? { site: site.index } : null); } }, icon('b-backbone_node'), App.t('map.info.openWorld')));
return out;
}
function settleBody(r, ctl) {
const d = r.data, out = [];
out.push(h('div', { class: 'rep-verdict victory' }, icon('flag'), h('b', { text: App.t('rep.settle.title', { name: d.town.name }) })));
out.push(kv(App.t('rep.site'), mil().coordLink(d.town.x, d.town.y)));
out.push(kv(App.t('rep.settle.wild'), h('span', { text: (d.wild || []).map((w) => App.buildingName(w)).join(', ') })));
if (r.shared) return out;
out.push(h('button', { class: 'btn primary wide', type: 'button', 'data-keep': '', onclick: async () => {
ctl.close();
try { await App.refreshTowns(); } catch (e) { /* the POP list may be stale; setTown below copes */ }
App.setTown(d.town.id); App.go('pop');
} }, icon('pop'), App.t('rep.settle.open')));
out.push(h('p', { class: 'row-sub wrap', text: App.t('rep.settle.hint') }));
return out;
}
function reinforceBody(r) {
const d = r.data, out = [];
out.push(kv(App.t('rep.from'), h('span', null, h('b', { text: nameOf(d.operator) }), mil().endLink(d.from))));
out.push(kv(App.t('rep.host'), h('span', null, h('b', { text: nameOf(d.hostOperator) }), mil().endLink(d.host))));
out.push(sec(App.t('rep.units'), h('p', { text: mil().unitsText(d.units) })));
return out;
}
function failedBody(r) {
const d = r.data, out = [];
out.push(h('div', { class: 'rep-verdict defeat' }, icon('alert'), h('b', { text: App.t('rep.failed.title', { type: mil().typeLabel(d.movementType) }) })));
out.push(h('p', { text: reasonText(d.reason) }));
if (d.to) out.push(kv(App.t('rep.target'), mil().coordLink(d.to.x, d.to.y)));
out.push(sec(App.t('rep.units'), h('p', { text: mil().unitsText(d.units) }), h('p', { class: 'row-sub wrap', text: App.t('rep.failed.home') })));
return out;
}
function genericBody(r) {
return [h('pre', { class: 'rep-raw', text: JSON.stringify(r.summary || {}, null, 1).slice(0, 1500) })];
}
function bodyFor(r, ctl) {
switch (r.type) {
case 'raid': case 'attack': case 'takeover': return combatBody(r);
case 'landing': return landingBody(r);
case 'scan': return scanBody(r);
case 'scan_detected': return detectedBody(r);
case 'incumbent': return incumbentBody(r);
case 'settle': return settleBody(r, ctl);
case 'reinforce': return reinforceBody(r);
case 'movement_failed': return failedBody(r);
default: return genericBody(r);
}
}
// ------------------------------------------------------------------ detail sheet
function shareRow(r) {
const msg = h('p', { class: 'form-error', role: 'alert', hidden: true });
const btn = h('button', { class: 'btn', type: 'button', 'data-act': '' }, icon('users'), App.t('rep.share'));
btn.addEventListener('click', async () => {
btn.disabled = true; msg.hidden = true;
try {
const res = await App.api.post('/reports/' + r.id + '/share', {}, { intent: 'report-share:' + r.id });
toast(App.t(res.changed === false ? 'rep.share.already' : 'rep.share.done'), 'ok');
folder.loaded = false;
} catch (e) {
msg.textContent = e.code === 'forbidden' ? App.t('rep.share.forbidden') : App.errMsg(e); msg.hidden = false; btn.disabled = false;
}
});
return h('div', { class: 'rep-share' }, h('p', { class: 'row-sub wrap', text: App.t('rep.share.hint') }), btn, msg);
}
function unshareRow(r, ctl) {
const msg = h('p', { class: 'form-error', role: 'alert', hidden: true });
const btn = h('button', { class: 'btn danger', type: 'button' }, icon('x'), App.t('rep.unshare'));
btn.addEventListener('click', async () => {
btn.disabled = true; msg.hidden = true;
try {
await App.api.del('/reports/' + r.id + '/share');
toast(App.t('rep.unshare.done'), 'ok');
folder.items = folder.items.filter((x) => x.id !== r.id);
ctl.close(); if (visible) draw();
} catch (e) { msg.textContent = e.code === 'forbidden' ? App.t('rep.unshare.forbidden') : App.errMsg(e); msg.hidden = false; btn.disabled = false; }
});
return h('div', { class: 'rep-share' }, btn, msg);
}
async function openReport(id, shared) {
const body = h('div', { class: 'detail rep-detail' }, h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' })));
const ctl = openSheet({ title: App.t('screen.reports'), icon: 'report', closeLabel: App.t('common.close'), body });
try {
const res = await App.api.get(shared ? '/alliances/' + allianceId() + '/reports/' + id : '/reports/' + id);
const r = res.report;
r.shared = !!shared;
ctl.setTitle(mil().reportTypeLabel(r.type));
clear(body);
body.appendChild(h('p', { class: 'row-sub', text: mil().dayTime(r.createdAt) + ' · ' + (shared ? App.t('rep.sharedBy', { name: r.sharedBy ? r.sharedBy.name : '?' }) : App.t('rep.role.' + r.role)) + ' · ' + App.t('rep.expires', { t: mil().dayTime(r.expiresAt) }) }));
let parts;
try { parts = bodyFor(r, ctl); } catch (e) { parts = genericBody(r); }
for (const p of parts.flat(2)) if (p) body.appendChild(p);
if (shared) body.appendChild(unshareRow(r, ctl));
else if (allianceId()) body.appendChild(shareRow(r));
if (!shared && !r.read) {
App.api.post('/reports/' + id + '/read', {}).then(() => {
const it = items.find((x) => x.id === id); if (it) it.read = true;
if (visible) draw();
App.refreshReportsUnread().catch(() => {});
}).catch(() => {});
}
} catch (e) {
clear(body);
body.appendChild(h('p', { class: 'form-error', text: App.errMsg(e) }));
}
}
// ------------------------------------------------------------------ screen
App.registerScreen({
id: 'reports', titleKey: 'screen.reports', navKey: 'nav.reports', icon: 'report', navGroup: 'more', hud: false,
render(container) {
box = container;
listEl = h('ul', { class: 'alert-list' });
statusEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
moreBtn = h('button', { class: 'btn wide', type: 'button', hidden: true, onclick: () => load(true) }, App.t('rep.older'));
tabsEl = h('div', { class: 'seg rep-tabs', role: 'group', hidden: true });
markBtn = h('button', { class: 'btn small', type: 'button', onclick: markAll }, icon('check'), App.t('rep.markAll'));
box.appendChild(h('div', { class: 'page' },
h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.reports') }),
h('div', { class: 'head-actions' }, markBtn,
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load(false) }, icon('refresh')))),
tabsEl, statusEl, listEl, moreBtn));
App.on('session', () => { items = []; next = null; folder.items = []; folder.next = null; folder.loaded = false; mode = 'mine'; });
App.on('report', () => { if (visible) load(false); });
},
onShow(params) {
visible = true;
box.querySelector('h1').textContent = App.t('screen.reports');
moreBtn.textContent = App.t('rep.older');
markBtn.lastChild.textContent = App.t('rep.markAll');
if (params && params.tab === 'alliance' && allianceId()) mode = 'alliance';
if (mode === 'alliance' && !allianceId()) mode = 'mine';
draw();
load(false);
if (params && params.open) openReport(Number(params.open), false);
if (offAgo) offAgo();
offAgo = App.onTick(() => {
const now = App.now();
for (const el of listEl.querySelectorAll('.when')) { const s = App.fmt.ago(now - Number(el.dataset.at)); if (el.textContent !== s) el.textContent = s; }
});
},
onHide() { visible = false; if (offAgo) offAgo(); offAgo = null; },
});
}());