File size: 5,094 Bytes
187ef74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
(() => {
  "use strict";
  const shell = document.querySelector("[data-organization-id]");
  if (!shell) return;
  const organizationId = shell.dataset.organizationId;
  const csrf = shell.dataset.csrf;
  const outcome = document.querySelector("[data-workspace-outcome]");
  let organizationVersion = Number(shell.dataset.organizationVersion || "1");

  const key = (resource, operation, id) => {
    if (globalThis.crypto && globalThis.crypto.randomUUID) return `${resource}:${operation}:${globalThis.crypto.randomUUID()}`;
    return `${resource}:${operation}:${id || "new"}:${Date.now()}`;
  };
  const show = (message, failed = false) => {
    if (!outcome) return;
    outcome.textContent = message;
    outcome.style.background = failed ? "#fde8e7" : "#e8f5ee";
    outcome.style.color = failed ? "#b3261e" : "#287d4f";
  };
  const send = async (path, payload, idempotencyKey) => {
    const response = await fetch(path, {
      method: "POST",
      headers: {"Content-Type": "application/json", "X-CSRF-Token": csrf, "Idempotency-Key": idempotencyKey},
      body: JSON.stringify(payload),
    });
    const body = await response.json().catch(() => ({message: "The response could not be read."}));
    if (!response.ok) throw new Error(body.message || body.error || "The command was rejected.");
    return body;
  };

  document.querySelectorAll("[data-workspace-create]").forEach((form) => {
    form.addEventListener("submit", async (event) => {
      event.preventDefault();
      const resource = form.dataset.workspaceCreate;
      const payload = Object.fromEntries(new FormData(form).entries());
      for (const input of form.querySelectorAll("input[type=number]")) payload[input.name] = Number(input.value || "0");
      const idem = key(resource, "create");
      try {
        show("Saving…");
        const body = await send(`/api/v3/organizations/${organizationId}/${resource}`, {...payload, expected_version: organizationVersion}, idem);
        if (body.organization_version) organizationVersion = Number(body.organization_version);
        show("Saved locally. No remote effect occurred.");
        globalThis.setTimeout(() => globalThis.location.reload(), 250);
      } catch (error) { show(error.message, true); }
    });
  });

  document.querySelectorAll("[data-workspace-transition]").forEach((button) => {
    button.addEventListener("click", async () => {
      const {resource, id, version, outcome: next} = button.dataset;
      try {
        show("Updating…");
        await send(`/api/v3/organizations/${organizationId}/${resource}/${id}`, {expected_version: Number(version), outcome: next}, key(resource, next, id));
        show("Updated locally. No remote effect occurred.");
        globalThis.setTimeout(() => globalThis.location.reload(), 250);
      } catch (error) { show(error.message, true); }
    });
  });

  document.querySelectorAll("[data-workspace-checkin]").forEach((button) => {
    button.addEventListener("click", async () => {
      const {attendeeId, version, operation} = button.dataset;
      try {
        show("Updating attendee…");
        await send(`/api/v3/organizations/${organizationId}/check-ins`, {attendee_id: attendeeId, operation, expected_version: Number(version)}, key("check-ins", operation, attendeeId));
        show("Attendee updated.");
        globalThis.setTimeout(() => globalThis.location.reload(), 250);
      } catch (error) { show(error.message, true); }
    });
  });

  document.querySelectorAll("[data-copy-code]").forEach((button) => {
    button.addEventListener("click", async () => {
      const code = button.dataset.copyCode;
      const scanner = document.querySelector('[data-workspace-scan] input[name="scan_code"]');
      if (scanner) scanner.value = code;
      if (globalThis.navigator.clipboard) {
        await globalThis.navigator.clipboard.writeText(code).catch(() => {});
      }
      show("Local attendee code copied into the scanner.");
    });
  });

  document.querySelectorAll("[data-workspace-scan]").forEach((form) => {
    form.addEventListener("submit", async (event) => {
      event.preventDefault();
      const scanCode = String(new FormData(form).get("scan_code") || "").trim();
      const parts = scanCode.split(".");
      const attendeeId = parts.length === 4 ? parts[2] : "";
      const row = Array.from(document.querySelectorAll("[data-attendee-row]")).find(
        (item) => item.dataset.attendeeId === attendeeId
      );
      if (!row) {
        show("That code does not match an attendee in this organization.", true);
        return;
      }
      try {
        show("Checking in attendee…");
        await send(
          `/api/v3/organizations/${organizationId}/check-ins`,
          {scan_code: scanCode, operation: "check-in", expected_version: Number(row.dataset.attendeeVersion)},
          key("check-ins", "scan", attendeeId)
        );
        show("Attendee checked in from the local code.");
        globalThis.setTimeout(() => globalThis.location.reload(), 250);
      } catch (error) { show(error.message, true); }
    });
  });
})();