mirror of
https://github.com/db9979/wibosim.git
synced 2026-12-06 21:44:09 +01:00
Mit gültigem Einladungscode (/e/CODE) brach inviteHeadHtml mit „ReferenceError: art is not defined“ ab, die Willkommenskarte erschien nicht. Neuer Test client-imports.test.js prüft statisch, dass jede aufgerufene exportierte Funktion eines anderen Client-Moduls auch importiert ist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
266 lines
16 KiB
JavaScript
266 lines
16 KiB
JavaScript
// Freunde einladen: Einladungscode aus dem Link (/e/CODE → /?einladung=CODE) merken, Willkommenskarte,
|
||
// Karte „Freunde einladen“ (Community und Profil), Teilen (navigator.share), Link kopieren (mit Rückfall für http),
|
||
// QR-Code (eigener Encoder, ohne Netz), Einladung per E-Mail und „Meine Einladungen“.
|
||
import { art, emptyArt } from './art.js';
|
||
import { S, sub, changed, loggedIn } from './state.js';
|
||
import { api, on, getToken } from './net.js';
|
||
import { toast, openModal } from './ui.js';
|
||
import { esc, int, dateY, player } from './util.js';
|
||
import { icon } from './icons.js';
|
||
import { drawQr } from './qr.js';
|
||
import { openAuth } from './account.js';
|
||
|
||
const KEY = 'wibo.einladung';
|
||
const MSG_MAX = 300;
|
||
|
||
// ---------------------------------------------------------------- Code merken (übersteht Neuladen und späteres Registrieren)
|
||
export function pendingInvite() {
|
||
try { return sessionStorage.getItem(KEY) || localStorage.getItem(KEY) || ''; } catch { return ''; }
|
||
}
|
||
function rememberInvite(code) {
|
||
const c = String(code ?? '').trim().slice(0, 40);
|
||
if (!c) return;
|
||
try { sessionStorage.setItem(KEY, c); localStorage.setItem(KEY, c); } catch { /* privater Modus */ }
|
||
}
|
||
export function clearInvite() {
|
||
try { sessionStorage.removeItem(KEY); localStorage.removeItem(KEY); } catch { /* egal */ }
|
||
}
|
||
|
||
/** Einladungslink geöffnet? Willkommenskarte mit geöffneter Registrierung. Liefert true, wenn ein Dialog offen ist. */
|
||
export async function inviteLanding(open = (invite) => openAuth('register', '', { invite })) {
|
||
let fromUrl = null;
|
||
try {
|
||
const url = new URL(location.href);
|
||
fromUrl = url.searchParams.get('einladung');
|
||
if (fromUrl !== null) {
|
||
url.searchParams.delete('einladung');
|
||
history.replaceState(null, '', `${url.pathname}${url.search}${url.hash}`);
|
||
}
|
||
} catch { /* egal */ }
|
||
if (fromUrl) rememberInvite(fromUrl);
|
||
if (!fromUrl) return false;
|
||
if (getToken()) {
|
||
clearInvite();
|
||
toast('Du bist schon angemeldet – Einladungscodes gelten nur für neue Konten. Teile gern deinen eigenen Link unter Community → Freunde einladen.', 'info', { title: 'Einladung', ms: 8000 });
|
||
return false;
|
||
}
|
||
let info;
|
||
try { info = await api(`/api/invite/${encodeURIComponent(fromUrl)}`, { auth: false }); } catch (e) { info = { ok: false, error: e.message }; }
|
||
if (!info.ok) clearInvite();
|
||
open({ code: info.ok ? fromUrl : '', ...info });
|
||
return true;
|
||
}
|
||
|
||
/** Kopf der Anmeldeseite bei einer Einladung (Willkommenskarte bzw. verständliche Fehlermeldung) */
|
||
export function inviteHeadHtml(inv) {
|
||
const only = S.info?.invites?.inviteOnly;
|
||
if (!inv) return '';
|
||
if (!inv.ok) {
|
||
return `<p class="banner-in down-b" role="alert"><b>Einladung ungültig:</b> ${esc(inv.error ?? 'unbekannter Code')}. ${only ? 'Registrierung ist derzeit nur mit gültiger Einladung möglich – frag nach einem neuen Link.' : 'Du kannst dich trotzdem registrieren.'}</p>`;
|
||
}
|
||
const who = inv.inviter;
|
||
const cash = S.info?.startCash ? `${int(S.info.startCash)}\u00a0€` : '100.000\u00a0€';
|
||
return `<div class="invite-hero">
|
||
<div class="dlg-art">${art('users', { cls: 'dlg-art-i' })}</div>
|
||
<div class="kicker">Einladung</div>
|
||
<h2>${who ? `${esc(who)} lädt dich zu WiBoSim ein` : 'Du bist zu WiBoSim eingeladen'}</h2>
|
||
<ul class="invite-points">
|
||
<li>${icon('chart-up')} Eine fiktive Börse mit erfundenen Unternehmen – du startest mit ${esc(cash)} Spielgeld.</li>
|
||
<li>${icon('parliament')} Ein Parlament stimmt über Gesetze ab, die die Kurse bewegen – du stimmst mit.</li>
|
||
<li>${icon('swords')} Battles: ${who ? `Fordere ${esc(who)} zum` : 'Fordere Freunde zum'} Depot-Duell heraus.</li>
|
||
</ul>
|
||
${who ? `<p class="muted small">Nach der Registrierung seid ihr automatisch befreundet. Beim ersten Handel bekommt ihr beide XP.</p>` : ''}
|
||
</div>`;
|
||
}
|
||
|
||
/** Nach der Registrierung: Ergebnis der Einladung anzeigen */
|
||
export function afterRegister(inv) {
|
||
clearInvite();
|
||
if (!inv) return;
|
||
if (!inv.ok) { toast(inv.error, 'warn', { title: 'Einladung', ms: 9000 }); return; }
|
||
if (inv.kind === 'setup') { toast('Du bist jetzt Admin dieses Servers. Den Admin-Bereich findest du unter Profil → Admin-Bereich.', 'gold', { title: 'Einrichtung', ms: 9000 }); return; }
|
||
if (inv.inviter) {
|
||
toast(`Du und ${esc(inv.inviter)} seid jetzt befreundet. <button type="button" class="linkish" data-act="challengeName" data-name="${esc(inv.inviter)}">Fordere ${esc(inv.inviter)} zu einem ersten Battle heraus</button>`,
|
||
'gold', { title: 'Einladung angenommen', html: true, ms: 15_000 });
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Daten
|
||
let loading = null;
|
||
export function loadInvites() {
|
||
if (!loggedIn() || !S.info?.invites?.enabled) return Promise.resolve(null);
|
||
loading ??= api('/api/invites').then((r) => { S.invites = r; changed('invites'); return r; }).catch(() => null).finally(() => { loading = null; });
|
||
return loading;
|
||
}
|
||
const linkOf = (v) => v?.link || (v?.code ? `${location.origin}/e/${v.code}` : location.origin);
|
||
async function data() { return S.invites ?? (await loadInvites()); }
|
||
|
||
// ---------------------------------------------------------------- Teilen & Kopieren
|
||
export async function copyText(text) {
|
||
try {
|
||
if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(text); return true; }
|
||
} catch { /* Rückfall unten */ }
|
||
// http im Heimnetz: keine Clipboard-API → unsichtbares Textfeld markieren und kopieren (auch iOS Safari)
|
||
const ta = document.createElement('textarea');
|
||
ta.value = text;
|
||
ta.setAttribute('readonly', '');
|
||
ta.style.position = 'fixed'; ta.style.top = '0'; ta.style.left = '0'; ta.style.opacity = '0';
|
||
document.body.append(ta);
|
||
ta.focus(); ta.select(); ta.setSelectionRange(0, text.length);
|
||
let ok = false;
|
||
try { ok = document.execCommand('copy'); } catch { ok = false; }
|
||
ta.remove();
|
||
return ok;
|
||
}
|
||
|
||
async function copyLink() {
|
||
const v = await data();
|
||
const link = linkOf(v);
|
||
if (await copyText(link)) toast('Link kopiert – füge ihn in deine Nachricht ein.', 'ok', { ms: 3000 });
|
||
else {
|
||
const inp = document.querySelector('#invLink');
|
||
inp?.focus(); inp?.select();
|
||
toast('Kopieren ist hier nicht erlaubt – der Link ist markiert, bitte manuell kopieren.', 'warn');
|
||
}
|
||
}
|
||
|
||
async function share() {
|
||
const v = await data();
|
||
const link = linkOf(v);
|
||
const text = `${S.profile?.name ?? 'Ich'} lädt dich zu WiBoSim ein – Börsenspiel mit Spielgeld, Politik und Battles. Mein Code: ${v?.code ?? ''}`;
|
||
if (navigator.share) {
|
||
try { await navigator.share({ title: 'WiBoSim – Einladung', text, url: link }); return; } catch (e) { if (e?.name === 'AbortError') return; }
|
||
}
|
||
if (await copyText(`${text}\n${link}`)) toast('Teilen wird hier nicht unterstützt – Einladungstext mit Link kopiert.', 'ok', { ms: 4500 });
|
||
else openQr();
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Dialoge
|
||
async function openQr() {
|
||
const v = await data();
|
||
const link = linkOf(v);
|
||
const { el } = openModal(`<h2>Einladen per QR-Code</h2>
|
||
<p class="muted small">Mit der Handykamera scannen – öffnet die Einladung mit deinem Code.</p>
|
||
<div class="qr-box"><canvas id="invQr" role="img" aria-label="QR-Code mit deinem Einladungslink"></canvas></div>
|
||
<p class="qr-link"><code>${esc(link)}</code></p>
|
||
<p class="muted small">Dein Code: <b class="code">${esc(v?.code ?? '')}</b></p>
|
||
<div class="dlg-actions"><a class="btn ghost" id="invQrSave" download="wibosim-einladung.png">Als Bild speichern</a>
|
||
<button type="button" class="btn ghost" data-act="inviteCopy">Link kopieren</button><button type="button" class="btn" data-act="inviteShare">Teilen</button></div>`, { label: 'QR-Code', cls: 'invite-modal' });
|
||
const cv = el.querySelector('#invQr');
|
||
try { drawQr(cv, link, { px: 232 }); el.querySelector('#invQrSave').href = cv.toDataURL('image/png'); } catch (e) { cv.replaceWith(Object.assign(document.createElement('p'), { textContent: e.message })); }
|
||
}
|
||
|
||
function openMail() {
|
||
const v = S.invites;
|
||
const m = v?.mail ?? { enabled: false };
|
||
if (!m.enabled) {
|
||
openModal(`<h2>Einladung per E-Mail</h2><p>Auf diesem Server ist kein Mailversand eingerichtet${m.limit === 0 ? ' bzw. abgeschaltet' : ''}. Link kopieren, Teilen und QR-Code funktionieren trotzdem.</p>
|
||
<div class="dlg-actions"><button type="button" class="btn ghost" data-act="inviteQr">QR-Code</button><button type="button" class="btn" data-act="inviteShare">Teilen</button></div>`, { label: 'Einladung per E-Mail' });
|
||
return;
|
||
}
|
||
const { el, close } = openModal(`<h2>Einladung per E-Mail</h2>
|
||
<form id="inviteMailForm" novalidate>
|
||
<div class="field"><label for="imTo">E-Mail-Adresse deiner Freundin / deines Freundes</label><input id="imTo" type="email" inputmode="email" autocomplete="off" autocapitalize="off" spellcheck="false" maxlength="200" required autofocus></div>
|
||
<div class="field"><label for="imMsg">Persönliche Nachricht <span class="muted">(optional)</span></label><textarea id="imMsg" maxlength="${MSG_MAX}" rows="3" placeholder="z. B. Lust auf ein Depot-Duell? Ich wette, ich schlag dich."></textarea>
|
||
<small class="muted block" id="imCount">0 / ${MSG_MAX}</small></div>
|
||
<p class="muted small">Heute noch <b id="imLeft">${int(m.left)}</b> von ${int(m.limit)} Einladungen. Jede Adresse bekommt höchstens eine Einladung pro Woche, Abmeldung per Link in der Mail.
|
||
Die Adresse wird nicht gespeichert – nur ein Prüfwert für Sperre und Abmeldung.</p>
|
||
<p class="err-line" id="imErr" role="alert"></p>
|
||
<div class="dlg-actions"><button type="submit" class="btn" ${m.left > 0 ? '' : 'disabled'}>Einladung senden</button></div>
|
||
</form>`, { label: 'Einladung per E-Mail', cls: 'invite-modal' });
|
||
const msg = el.querySelector('#imMsg');
|
||
msg.addEventListener('input', () => { el.querySelector('#imCount').textContent = `${msg.value.length} / ${MSG_MAX}`; });
|
||
el.querySelector('#inviteMailForm').addEventListener('submit', async (e) => {
|
||
e.preventDefault();
|
||
const to = el.querySelector('#imTo').value.trim();
|
||
const err = el.querySelector('#imErr');
|
||
err.textContent = '';
|
||
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(to)) { err.textContent = 'Bitte eine gültige E-Mail-Adresse eingeben.'; return; }
|
||
try {
|
||
const r = await api('/api/invites/mail', { method: 'POST', body: { to, message: msg.value } });
|
||
S.invites = r.invites; changed('invites');
|
||
toast(r.text ?? 'Einladung verschickt.', 'ok', { title: 'Einladung' });
|
||
close();
|
||
} catch (ex) { err.textContent = ex.message; }
|
||
});
|
||
}
|
||
|
||
const CHANNEL = { link: ['link', 'Link'], mail: ['mail', 'E-Mail'], code: ['ticket', 'Code'] };
|
||
function statusHtml(x) {
|
||
const steps = [];
|
||
if (x.channel === 'mail') steps.push(['verschickt', true]);
|
||
steps.push([x.name ? `registriert · ${player(x.name)}` : 'registriert', x.status !== 'verschickt']);
|
||
steps.push(['aktiv', x.status === 'aktiv']);
|
||
return `<span class="inv-steps">${steps.map(([t, on]) => `<span class="inv-step ${on ? 'on' : ''}">${t.includes('<') ? t : esc(t)}</span>`).join('<span class="inv-arrow" aria-hidden="true">→</span>')}</span>`;
|
||
}
|
||
|
||
function countsHtml(c) {
|
||
return `<div class="kpis invite-kpis"><div><small>Verschickt</small><b>${int(c?.sent ?? 0)}</b></div><div><small>Registriert</small><b>${int(c?.registered ?? 0)}</b></div><div><small>Aktiv</small><b>${int(c?.active ?? 0)}</b></div></div>`;
|
||
}
|
||
|
||
export function invitesListHtml(v) {
|
||
const list = v?.list ?? [];
|
||
if (!list.length) return emptyArt('users', 'Noch keine Einladungen. Teile deinen Link – sobald sich jemand registriert, erscheint er hier.', { size: 'sm' });
|
||
return `<div class="scroll-x"><table class="invite-list"><thead><tr><th scope="col">Kanal</th><th scope="col">Datum</th><th scope="col">Status</th></tr></thead><tbody>
|
||
${list.map((x) => { const [ic, t] = CHANNEL[x.channel] ?? ['info', x.channel]; return `<tr><td>${icon(ic)} ${esc(t)}${x.hint ? ` <small class="muted">an ${esc(x.hint)}</small>` : ''}</td><td>${dateY(x.ts)}</td><td>${statusHtml(x)}</td></tr>`; }).join('')}
|
||
</tbody></table></div>`;
|
||
}
|
||
|
||
async function openList() {
|
||
const v = await loadInvites() ?? S.invites;
|
||
openModal(`<h2>Meine Einladungen</h2>${countsHtml(v?.counts)}${invitesListHtml(v)}
|
||
<p class="muted small">„Aktiv“ heißt: erster Handel gemacht – dann bekommst du ${int(v?.xp?.inviter ?? 150)} XP und dein Freund ${int(v?.xp?.invitee ?? 75)} XP (einmal je neuem Konto, nicht vom selben Anschluss).
|
||
Bei E-Mail-Einladungen zeigen wir die Adresse nur gekürzt.</p>`, { label: 'Meine Einladungen', wide: true, cls: 'invite-modal' });
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Karten
|
||
export function inviteCardHtml() {
|
||
if (!loggedIn() || !S.info?.invites?.enabled) return '';
|
||
const v = S.invites;
|
||
if (!v) return '<div class="card invite-card"><h2 class="card-h">Freunde einladen</h2><div class="body"><p class="muted">Lade …</p></div></div>';
|
||
const link = linkOf(v);
|
||
return `<div class="card invite-card"><h2 class="card-h">Freunde einladen <span class="muted small">${int(v.counts.registered)} dabei</span></h2><div class="body">
|
||
<p>Spielt zusammen! Wer über deinen Link mitmacht, ist automatisch mit dir befreundet. Beim ersten Handel bekommt ihr beide XP.</p>
|
||
<div class="invite-link"><label class="sr" for="invLink">Dein Einladungslink</label><input id="invLink" readonly value="${esc(link)}" data-nofeedback>
|
||
<button type="button" class="btn ghost" data-act="inviteCopy">Link kopieren</button></div>
|
||
<p class="muted small">Dein Code: <b class="code">${esc(v.code)}</b></p>
|
||
<div class="row-actions invite-actions">
|
||
<button type="button" class="btn" data-act="inviteShare">Einladen</button>
|
||
<button type="button" class="btn ghost" data-act="inviteQr">QR-Code</button>
|
||
${v.mail.enabled ? '<button type="button" class="btn ghost" data-act="inviteMail">Per E-Mail</button>' : ''}
|
||
<button type="button" class="btn ghost" data-act="inviteList">Meine Einladungen</button>
|
||
</div>
|
||
${v.mail.enabled ? '' : '<p class="muted small">Einladung per E-Mail ist auf diesem Server nicht eingerichtet – Link, Teilen und QR-Code gehen trotzdem.</p>'}
|
||
${countsHtml(v.counts)}
|
||
</div></div>`;
|
||
}
|
||
|
||
/** kompakter Block für Profil & Einstellungen */
|
||
export function inviteFieldsetHtml() {
|
||
if (!loggedIn() || !S.info?.invites?.enabled) return '';
|
||
const v = S.invites;
|
||
return `<fieldset class="invite-fs"><legend>Freunde einladen</legend>
|
||
<p class="muted small">${v ? `Dein Code: <b class="code">${esc(v.code)}</b> · ${int(v.counts.registered)} registriert · ${int(v.counts.active)} aktiv` : 'Persönlicher Link, QR-Code oder E-Mail – ihr seid danach automatisch befreundet.'}</p>
|
||
<div class="row-actions"><button type="button" class="btn small" data-act="inviteShare">Einladen</button><button type="button" class="btn ghost small" data-act="inviteCopy">Link kopieren</button>
|
||
<button type="button" class="btn ghost small" data-act="inviteQr">QR-Code</button>${v?.mail?.enabled ? '<button type="button" class="btn ghost small" data-act="inviteMail">Per E-Mail</button>' : ''}
|
||
<button type="button" class="btn ghost small" data-act="inviteList">Meine Einladungen</button></div></fieldset>`;
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Init
|
||
export function initInvite() {
|
||
document.addEventListener('click', async (e) => {
|
||
const a = e.target.closest('[data-act]');
|
||
if (!a) return;
|
||
const act = a.dataset.act;
|
||
if (!act.startsWith('invite')) return;
|
||
if (!loggedIn()) { openAuth(); return; }
|
||
if (act === 'inviteCopy') copyLink();
|
||
else if (act === 'inviteShare') share();
|
||
else if (act === 'inviteQr') openQr();
|
||
else if (act === 'inviteMail') { await data(); openMail(); }
|
||
else if (act === 'inviteList') openList();
|
||
});
|
||
sub('profile', () => { if (loggedIn() && !S.invites) loadInvites(); if (!loggedIn()) S.invites = null; });
|
||
on('inbox', (m) => { if (m.item?.kind === 'social' && S.invites) loadInvites(); });
|
||
}
|