aboutsummaryrefslogtreecommitdiff
path: root/174bg/manager/public/index.html
blob: 9f537c4fc480a581ea802498e0473c8344497120 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      html {
        font-family: monospace;
        font-size: 16px;
      }

      #preferences table {
        border-collapse: collapse;
        min-width: 16rem;
      }

      #preferences thead th {
        text-align: left;
        padding: 0.4rem 0.75rem;
        border-bottom: 2px solid #555;
        font-size: 0.75rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #888;
      }

      #preferences tbody tr:nth-child(even) {
        background: rgba(0, 0, 0, 0.04);
      }

      #preferences tbody td {
        padding: 0.4rem 0.75rem;
        border-bottom: 1px solid #e0e0e0;
      }

      #preferences tbody td:last-child {
        text-align: center;
        width: 2.5rem;
      }

      #ledger table {
        border-collapse: collapse;
        min-width: 16rem;
      }

      #ledger thead th {
        text-align: left;
        padding: 0.4rem 0.75rem;
        border-bottom: 2px solid #555;
        font-size: 0.75rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #888;
      }

      #ledger tbody tr:nth-child(even) {
        background: rgba(0, 0, 0, 0.04);
      }

      #ledger tbody td {
        padding: 0.4rem 0.75rem;
        border-bottom: 1px solid #e0e0e0;
      }

      #ledger td.uec {
        text-align: right;
        font-variant-numeric: tabular-nums;
      }

      #ledger .empty {
        margin: 0;
        font-size: 0.85rem;
        color: #888;
      }

      #profile-warning {
        margin-top: 0.75rem;
        padding: 0.6rem 0.9rem;
        background: #fdd;
        border: 1px solid #c00;
        border-radius: 4px;
        color: #900;
        font-weight: bold;
      }

      #welcome {
        display: flex;
        align-items: center;
        gap: 0.75rem;
      }

      #welcome-avatar {
        width: 3rem;
        height: 3rem;
        border-radius: 50%;
        object-fit: cover;
      }

      #welcome-text {
        font-size: 1.25rem;
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <h1>174th Battle Group: Manager</h1>

    <section id="anonymous">
      <p>You are not logged in. Please log in to access this site:</p>
      <button id="login">Login with Discord</button>
    </section>

    <p id="oauth-status" style="font-size: 0.9rem"></p>

    <section
      id="authed"
      style="display: none; flex-direction: column; gap: 1em"
    >
      <div id="welcome">
        <img id="welcome-avatar" src="" alt="" />
        <span id="welcome-text"></span>
      </div>
      <div id="required-info" style="display: flex; flex-direction: column">
        <h2 style="margin-bottom: 0">Required Information</h2>
        <div><b>174BG ID:</b> <span id="174bg-id"></span></div>
        <div>
          <b>UEE Citizen Record ID:</b> <span id="uee-citizen-record-id"></span>
        </div>
        <div><b>RSI Display Name:</b> <span id="rsi-display-name"></span></div>
        <div><b>RSI Handle:</b> <span id="rsi-handle"></span></div>
        <div>
          <b>Joined RSI Organisation:</b> <span id="joined-rsi-org"></span>
        </div>
        <div><b>Email:</b> <span id="user-email"></span></div>
        <div><b>Branch:</b> <span id="174bg-branch"></span></div>
        <div><b>Rank Number:</b> <span id="174bg-rank-number"></span></div>
        <div><b>Rank Name:</b> <span id="174bg-rank-name"></span></div>
        <div id="profile-warning" hidden>
          ⚠️ Your profile is incomplete. Message an officer ASAP!
        </div>
      </div>
      <div id="preferences"></div>
      <div id="ledger"></div>
      <div>
        <button id="logout">Logout</button>
      </div>
    </section>
  </body>
  <script type="module">
    import PocketBase from "https://esm.sh/pocketbase@0.27.0";

    const pb = new PocketBase("https://db.174bg.net");

    function populateWelcome() {
      const record = pb.authStore.record ?? {};
      const avatarEl = document.getElementById("welcome-avatar");
      const textEl = document.getElementById("welcome-text");

      const name = record["RSI_Handle"] || record["name"] || "Pilot";
      textEl.textContent = `Welcome back, ${name}!`;

      // PocketBase avatar URL pattern
      const avatarFile = record["avatar"];
      if (avatarFile) {
        avatarEl.src = `https://db.174bg.net/api/files/${record.collectionId}/${record.id}/${avatarFile}`;
        avatarEl.alt = name;
        avatarEl.hidden = false;
      } else {
        avatarEl.hidden = true;
      }
    }

    // ---------------------------------------------------------------------------
    // Required-info field definitions — map span IDs to PocketBase field names
    // ---------------------------------------------------------------------------
    const REQUIRED_INFO_FIELDS = [
      { id: "174bg-id", field: "id" },
      { id: "uee-citizen-record-id", field: "UEE_Citizen_Record_ID" },
      { id: "rsi-display-name", field: "RSI_Display_Name" },
      { id: "rsi-handle", field: "RSI_Handle" },
      { id: "joined-rsi-org", field: "joined_rsi_org" },
      { id: "user-email", field: "email" },
      { id: "174bg-branch", field: "Branch" },
      { id: "174bg-rank-number", field: "Rank_Number" },
    ];

    const RANK_NAMES = {
      Naval: [
        "Cadet",
        "Ensign",
        "Lieutenant",
        "Captain",
        "Commodore",
        "Admiral",
      ],
      Marine: [
        "Private",
        "Corporal",
        "Sergeant",
        "Major",
        "Commander",
        "General",
      ],
      Auxiliary: [
        "Trainee",
        "Technician",
        "Specialist",
        "Supervisor",
        "Chief",
        "Marshal",
      ],
    };

    function populateRequiredInfo() {
      const record = pb.authStore.record ?? {};
      let anyMissing = false;

      for (const { id, field } of REQUIRED_INFO_FIELDS) {
        const span = document.getElementById(id);
        const value = record[field];
        if (value) {
          span.textContent = value;
          span.style.color = "";
        } else {
          span.textContent = "MISSING";
          span.style.color = "red";
          anyMissing = true;
        }
      }

      // Derive rank name from branch + rank number
      const rankSpan = document.getElementById("174bg-rank-name");
      const branch = record["Branch"];
      const rankNumber = record["Rank_Number"];
      const rankName = RANK_NAMES[branch]?.[rankNumber];
      if (rankName) {
        rankSpan.textContent = rankName;
        rankSpan.style.color = "";
      } else {
        rankSpan.textContent = "MISSING";
        rankSpan.style.color = "red";
        anyMissing = true;
      }

      if (anyMissing) {
        document.getElementById("profile-warning").hidden = false;
      } else {
        document.getElementById("profile-warning").hidden = true;
      }
    }

    // Role options are fetched from the collection schema after auth
    let ROLES = [];

    async function fetchRoles() {
      ROLES = [
        {
          branch: "Naval",
          value: "Ship Captain",
          text: "Ship Captain",
          link: "https://handbook.174bg.net/#ship-captain",
        },
        {
          branch: "Naval",
          value: "Pilot",
          text: "Pilot",
          link: "https://handbook.174bg.net/#pilot",
        },
        {
          branch: "Naval",
          value: "Helmsman",
          text: "Helmsman",
          link: "https://handbook.174bg.net/#helmsman",
        },
        {
          branch: "Naval",
          value: "Gunner",
          text: "Gunner",
          link: "https://handbook.174bg.net/#gunner",
        },
        {
          branch: "Marine",
          value: "Tactical Marine",
          text: "Tactical Marine",
          link: "https://handbook.174bg.net/#tactical-marine",
        },
        {
          branch: "Marine",
          value: "Heavy Marine",
          text: "Heavy Marine",
          link: "https://handbook.174bg.net/#heavy-marine",
        },
        {
          branch: "Marine",
          value: "Scout Marine",
          text: "Scout Marine",
          link: "https://handbook.174bg.net/#scout-marine",
        },
        {
          branch: "Marine",
          value: "Combat Medic",
          text: "Combat Medic",
          link: "https://handbook.174bg.net/#combat-medic",
        },
        {
          branch: "Marine",
          value: "Combat Engineer",
          text: "Combat Engineer",
          link: "https://handbook.174bg.net/#combat-engineer",
        },
        {
          branch: "Marine",
          value: "Warden",
          text: "Warden",
          link: "https://handbook.174bg.net/#warden",
        },
        {
          branch: "Auxiliary",
          value: "Engineer",
          text: "Engineer",
          link: "https://handbook.174bg.net/#engineer",
        },
        {
          branch: "Auxiliary",
          value: "Hazardous Materials Specialist",
          text: "Hazardous Materials Specialist",
          link: "https://handbook.174bg.net/#hazardous-materials-specialist",
        },
        {
          branch: "Auxiliary",
          value: "Medical Doctor",
          text: "Medical Doctor",
          link: "https://handbook.174bg.net/#medical-doctor",
        },
        {
          branch: "Auxiliary",
          value: "Quartermaster",
          text: "Quartermaster",
          link: "https://handbook.174bg.net/#quartermaster",
        },
        {
          branch: "Auxiliary",
          value: "Cargo Technician",
          text: "Cargo Technician",
          link: "https://handbook.174bg.net/#cargo-technician",
        },
        {
          branch: "Auxiliary",
          value: "Craftsman",
          text: "Craftsman",
          link: "https://handbook.174bg.net/#craftsman",
        },
        {
          branch: "Auxiliary",
          value: "Mining Technician",
          text: "Mining Technician",
          link: "https://handbook.174bg.net/#mining-technician",
        },
        {
          branch: "Auxiliary",
          value: "Salvage Operator",
          text: "Salvage Operator",
          link: "https://handbook.174bg.net/#salvage-operator",
        },
        {
          branch: "Auxiliary",
          value: "Expeditionary Analyst",
          text: "Expeditionary Analyst",
          link: "https://handbook.174bg.net/#expeditionary-analyst",
        },
        {
          branch: "Auxiliary",
          value: "Intelligence Agent",
          text: "Intelligence Agent",
          link: "https://handbook.174bg.net/#intelligence-agent",
        },
      ];
    }

    let rolesEditing = false;
    let rolesTbody;
    let rolesEditBtn;
    let rolesCancelBtn;
    let rolesStatus;

    function renderRoles(saved, editMode) {
      rolesTbody.querySelectorAll("tr:not([data-separator])").forEach((tr) => {
        const td = tr.querySelectorAll("td")[1];
        if (editMode) {
          const cb = document.createElement("input");
          cb.type = "checkbox";
          cb.checked = saved.includes(tr.dataset.roleValue);
          td.replaceChildren(cb);
        } else {
          td.textContent = saved.includes(tr.dataset.roleValue) ? "✅" : "❌";
        }
      });
    }

    function buildRolesSection() {
      const container = document.getElementById("preferences");
      container.innerHTML = "";

      const heading = document.createElement("div");
      const title = document.createElement("b");
      title.textContent = "Role Preferences";
      rolesEditBtn = document.createElement("button");
      rolesEditBtn.type = "button";
      rolesEditBtn.textContent = "✏️ Edit";
      rolesCancelBtn = document.createElement("button");
      rolesCancelBtn.type = "button";
      rolesCancelBtn.textContent = "❌ Cancel";
      rolesCancelBtn.hidden = true;
      heading.append(title, " ", rolesEditBtn, " ", rolesCancelBtn);

      const table = document.createElement("table");
      const thead = document.createElement("thead");
      const headerRow = document.createElement("tr");
      for (const text of ["Role", ""]) {
        const th = document.createElement("th");
        th.textContent = text;
        headerRow.appendChild(th);
      }
      thead.appendChild(headerRow);

      rolesTbody = document.createElement("tbody");
      let lastBranch = null;
      for (const role of ROLES) {
        if (role.branch !== lastBranch) {
          lastBranch = role.branch;
          const sep = document.createElement("tr");
          sep.dataset.separator = "true";
          const tdSep = document.createElement("td");
          tdSep.colSpan = 2;
          tdSep.textContent = role.branch ?? "";
          tdSep.style.cssText =
            "font-weight:600; padding-top:0.75rem; padding-bottom:0.25rem; border-bottom:none; opacity:0.6; font-size:0.8rem; text-transform:uppercase; letter-spacing:0.05em";
          sep.appendChild(tdSep);
          rolesTbody.appendChild(sep);
        }
        const tr = document.createElement("tr");
        tr.dataset.roleValue = role.value;
        const tdName = document.createElement("td");
        if (role.link) {
          const a = document.createElement("a");
          a.href = role.link;
          a.textContent = role.text;
          a.target = "_blank";
          a.rel = "noopener noreferrer";
          tdName.appendChild(a);
        } else {
          tdName.textContent = role.text;
        }
        const tdCheck = document.createElement("td");
        tr.append(tdName, tdCheck);
        rolesTbody.appendChild(tr);
      }

      table.append(thead, rolesTbody);
      rolesStatus = document.createElement("p");
      rolesStatus.style.cssText = "margin:0; font-size:0.85rem";
      container.append(heading, table, rolesStatus);
    }

    function loadRoles() {
      rolesEditing = false;
      rolesEditBtn.textContent = "✏️ Edit";
      rolesCancelBtn.hidden = true;
      renderRoles(pb.authStore.record?.RolePreferencesSelect ?? [], false);
    }

    function memberLabel(record, id) {
      const m = record?.expand?.[id];
      return m ? m.RSI_Handle || m.name || m.id : (record?.[id] ?? "—");
    }

    async function loadLedger() {
      const container = document.getElementById("ledger");
      container.innerHTML = "";

      const heading = document.createElement("div");
      const title = document.createElement("b");
      title.textContent = "Ledger";
      heading.appendChild(title);
      container.appendChild(heading);

      const userId = pb.authStore.record?.id;
      if (!userId) return;

      let records;
      try {
        records = await pb.collection("ledger").getFullList({
          expand: "sender,recipient",
          sort: "-created",
          requestKey: null,
          cache: "no-store",
        });
      } catch (err) {
        console.error("Failed to load ledger:", err);
        const p = document.createElement("p");
        p.className = "empty";
        p.style.color = "red";
        p.textContent = `Failed to load ledger: ${err?.message ?? String(err)}`;
        container.appendChild(p);
        return;
      }

      if (records.length === 0) {
        const p = document.createElement("p");
        p.className = "empty";
        p.textContent = "No ledger entries.";
        container.appendChild(p);
        return;
      }

      const table = document.createElement("table");
      const thead = document.createElement("thead");
      const headerRow = document.createElement("tr");
      for (const text of ["Date", "Sender", "Recipient", "UEC", "Note"]) {
        const th = document.createElement("th");
        th.textContent = text;
        headerRow.appendChild(th);
      }
      thead.appendChild(headerRow);

      const tbody = document.createElement("tbody");
      for (const rec of records) {
        const tr = document.createElement("tr");

        const tdDate = document.createElement("td");
        tdDate.textContent = rec.created
          ? new Date(rec.created).toLocaleString()
          : "—";

        const tdSender = document.createElement("td");
        tdSender.textContent = memberLabel(rec, "sender");

        const tdRecipient = document.createElement("td");
        tdRecipient.textContent = memberLabel(rec, "recipient");

        const tdUec = document.createElement("td");
        tdUec.className = "uec";
        tdUec.textContent = Number(rec.uec ?? 0).toLocaleString();

        const tdNote = document.createElement("td");
        tdNote.textContent = rec.note ?? "";

        tr.append(tdDate, tdSender, tdRecipient, tdUec, tdNote);
        tbody.appendChild(tr);
      }

      table.append(thead, tbody);
      container.appendChild(table);
    }

    const loginBtn = document.getElementById("login");
    const logoutBtn = document.getElementById("logout");
    const anonymousSection = document.getElementById("anonymous");
    const authedSection = document.getElementById("authed");

    function updateAuthUI() {
      const loggedIn = pb.authStore.isValid;
      anonymousSection.style.display = loggedIn ? "none" : "";
      authedSection.style.display = loggedIn ? "flex" : "none";
    }

    // Verify the stored session is still valid server-side
    if (pb.authStore.isValid) {
      try {
        await pb.collection("members").authRefresh();
      } catch {
        pb.authStore.clear();
      }
    }

    // Complete OAuth redirect if returning from Discord
    const oauthParams = new URLSearchParams(window.location.search);
    const storedProvider = localStorage.getItem("pb_oauth_provider");
    const oauthStatus = document.getElementById("oauth-status");

    if (oauthParams.has("code") && oauthParams.has("state")) {
      if (!storedProvider) {
        oauthStatus.textContent =
          "Login error: OAuth state lost (localStorage empty). Please try again.";
        oauthStatus.style.color = "red";
        window.history.replaceState({}, "", window.location.pathname);
      } else {
        oauthStatus.textContent = "Completing login...";
        const provider = JSON.parse(storedProvider);
        localStorage.removeItem("pb_oauth_provider");
        const redirectUrl = window.location.origin + window.location.pathname;
        try {
          await pb
            .collection("members")
            .authWithOAuth2Code(
              provider.name,
              oauthParams.get("code"),
              provider.codeVerifier,
              redirectUrl,
            );
          oauthStatus.style.cssText =
            "color:green; background:#dfd; border:1px solid #080; border-radius:4px; padding:0.5rem";
          oauthStatus.textContent = "✅ Login successful!";
          window.history.replaceState({}, "", window.location.pathname);
          await fetchRoles();
          buildRolesSection();
          updateAuthUI();
          populateWelcome();
          populateRequiredInfo();
          loadRoles();
          loadLedger();
        } catch (err) {
          console.error("OAuth callback failed:", err);
          const detail = [
            err?.message,
            err?.response ? JSON.stringify(err.response) : null,
            `code=${oauthParams.get("code")?.slice(0, 8)}…`,
            `state=${oauthParams.get("state")?.slice(0, 8)}…`,
            `redirect=${redirectUrl}`,
            `provider=${provider.name}`,
          ]
            .filter(Boolean)
            .join(" | ");
          oauthStatus.style.cssText =
            "color:red; background:#fdd; border:1px solid #c00; border-radius:4px; padding:0.5rem; font-family:monospace; font-size:0.8rem; white-space:pre-wrap; word-break:break-all";
          oauthStatus.textContent = `Login error — send this to your admin:\n${detail}`;
          window.history.replaceState({}, "", window.location.pathname);
        }
      }
    }

    updateAuthUI();
    if (pb.authStore.isValid) {
      await fetchRoles();
      buildRolesSection();
      populateWelcome();
      populateRequiredInfo();
      loadRoles();
      loadLedger();
    }

    loginBtn.addEventListener("click", async () => {
      loginBtn.disabled = true;
      try {
        const methods = await pb.collection("members").listAuthMethods();
        const provider = methods.oauth2.providers.find(
          (p) => p.name === "discord",
        );
        if (!provider) throw new Error("Discord provider not found");
        const redirectUrl = window.location.origin + window.location.pathname;
        localStorage.setItem("pb_oauth_provider", JSON.stringify(provider));
        window.location.href =
          provider.authUrl + encodeURIComponent(redirectUrl);
      } catch (err) {
        console.error("Login failed:", err);
        loginBtn.disabled = false;
      }
    });

    logoutBtn.addEventListener("click", () => {
      pb.authStore.clear();
      updateAuthUI();
    });

    rolesEditBtn.addEventListener("click", async () => {
      if (!rolesEditing) {
        rolesEditing = true;
        rolesEditBtn.textContent = "💾 Save";
        rolesCancelBtn.hidden = false;
        renderRoles(pb.authStore.record?.RolePreferencesSelect ?? [], true);
      } else {
        const selected = [
          ...rolesTbody.querySelectorAll("input[type=checkbox]:checked"),
        ].map((cb) => cb.closest("tr").dataset.roleValue);
        rolesEditBtn.disabled = true;
        rolesCancelBtn.disabled = true;
        try {
          const prefs = selected;
          await pb
            .collection("members")
            .update(pb.authStore.record.id, { RolePreferencesSelect: prefs });
          pb.authStore.record.RolePreferencesSelect = prefs;
          rolesEditing = false;
          rolesEditBtn.textContent = "✏️ Edit";
          rolesCancelBtn.hidden = true;
          rolesStatus.textContent = "";
          renderRoles(selected, false);
        } catch (err) {
          console.error("Failed to save role preferences:", err);
          const msg = err?.response
            ? JSON.stringify(err.response)
            : (err?.message ?? String(err));
          rolesStatus.style.color = "red";
          rolesStatus.textContent = `Save failed: ${msg}`;
        } finally {
          rolesEditBtn.disabled = false;
          rolesCancelBtn.disabled = false;
        }
      }
    });

    rolesCancelBtn.addEventListener("click", () => {
      rolesEditing = false;
      rolesEditBtn.textContent = "✏️ Edit";
      rolesCancelBtn.hidden = true;
      renderRoles(pb.authStore.record?.RolePreferencesSelect ?? [], false);
    });
  </script>
</html>