Compare commits
491
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78dd903b2d | ||
|
|
716d47242a | ||
|
|
8a930d07c6 | ||
|
|
390b80e56e | ||
|
|
4952e2cb0f | ||
|
|
9d585c94aa | ||
|
|
0cc72aaaad | ||
|
|
6db2f439b4 | ||
|
|
28603f2301 | ||
|
|
ee799dec98 | ||
|
|
0312767d75 | ||
|
|
46e8c15602 | ||
|
|
f1d6234800 | ||
|
|
a286f8abce | ||
|
|
d985a4c853 | ||
|
|
eb4e44a735 | ||
|
|
3bcde954fb | ||
|
|
328b2ce11a | ||
|
|
f4955bee9d | ||
|
|
570f2dda5a | ||
|
|
19709c2c75 | ||
|
|
f3f6dc8f7a | ||
|
|
0d7e6b52d2 | ||
|
|
2479cbbd0a | ||
|
|
c8d46ef2d9 | ||
|
|
ee65ff358c | ||
|
|
b207d17db8 | ||
|
|
92869d2683 | ||
|
|
d61b3e5978 | ||
|
|
1eeaf4d94f | ||
|
|
e9e9b5a97f | ||
|
|
350ab9f4e8 | ||
|
|
90a98a4306 | ||
|
|
53e15fdd69 | ||
|
|
a0ab22fbf3 | ||
|
|
52099c310d | ||
|
|
61a64cf339 | ||
|
|
afaccf79d1 | ||
|
|
38ebce24ab | ||
|
|
e8853cf0c8 | ||
|
|
c442fe0d42 | ||
|
|
f174285711 | ||
|
|
47f346b0a6 | ||
|
|
1ef1af64b7 | ||
|
|
243021c81e | ||
|
|
a800d448f4 | ||
|
|
0ab0ca9fa0 | ||
|
|
897b27cc42 | ||
|
|
2bb5580e10 | ||
|
|
015495ab56 | ||
|
|
9dc2fa8af4 | ||
|
|
4cbfcddfbd | ||
|
|
fbf9d3553d | ||
|
|
e78534328e | ||
|
|
6bb80f75d1 | ||
|
|
5ab755cc63 | ||
|
|
6a5aa29494 | ||
|
|
ca7a14bcf8 | ||
|
|
545880fdc7 | ||
|
|
01f9a3eeac | ||
|
|
53797e4447 | ||
|
|
a345b3c824 | ||
|
|
aca6f7728d | ||
|
|
9dda0d1851 | ||
|
|
c018772ded | ||
|
|
aabf3cbe07 | ||
|
|
cebfe52be5 | ||
|
|
40fa8b2dba | ||
|
|
8d7269a1e2 | ||
|
|
d33284b1ec | ||
|
|
391baa0d67 | ||
|
|
b58123adab | ||
|
|
abd2c36e97 | ||
|
|
3f59164ab2 | ||
|
|
57b3c41067 | ||
|
|
fa48e3bb24 | ||
|
|
edd3ee6e76 | ||
|
|
b41dbab667 | ||
|
|
76f17ab0e9 | ||
|
|
50639088b2 | ||
|
|
d53eba29ea | ||
|
|
72edb4da30 | ||
|
|
d74af96f1d | ||
|
|
6e64e64bff | ||
|
|
db214a1013 | ||
|
|
ba121118ea | ||
|
|
4924d1ed76 | ||
|
|
d4f54f2cc8 | ||
|
|
cbdc7ad10a | ||
|
|
20d53b79f1 | ||
|
|
dbec47aae3 | ||
|
|
838a6b3c3d | ||
|
|
0f915d345d | ||
|
|
792b5b291b | ||
|
|
839a56ddbd | ||
|
|
0e4a251c9a | ||
|
|
558c433b8f | ||
|
|
82e8f9cd62 | ||
|
|
d31ffdce0c | ||
|
|
20d43b63c2 | ||
|
|
044a113af5 | ||
|
|
68c6559136 | ||
|
|
7b20ffbe08 | ||
|
|
23ff8dd31f | ||
|
|
3b5ba6b9c6 | ||
|
|
ba351be029 | ||
|
|
1bc236ddd1 | ||
|
|
165e4d14f0 | ||
|
|
d1452c6645 | ||
|
|
11a90e572e | ||
|
|
237cd89f6a | ||
|
|
fe6034f10f | ||
|
|
91fa42ba5f | ||
|
|
50205c03f0 | ||
|
|
fb36e9c8ac | ||
|
|
de08f057ad | ||
|
|
a7a9382a93 | ||
|
|
7eb6f99e97 | ||
|
|
5a3bfa1100 | ||
|
|
4fa0d831d8 | ||
|
|
af43b72c04 | ||
|
|
684560119f | ||
|
|
0498ee1854 | ||
|
|
a387570098 | ||
|
|
c1fc8628d3 | ||
|
|
d1927cd334 | ||
|
|
96b9b8c23f | ||
|
|
006c4db02f | ||
|
|
4a7f75a8ec | ||
|
|
a564436f3b | ||
|
|
3e2895a9ce | ||
|
|
d74c37f5b3 | ||
|
|
fa9da3dc06 | ||
|
|
0044eec881 | ||
|
|
2b8f39b4e7 | ||
|
|
81e6aeb7c2 | ||
|
|
d5580cf9f0 | ||
|
|
a630b1ccc6 | ||
|
|
bee209faf2 | ||
|
|
91047bcde2 | ||
|
|
1b7adcf7fe | ||
|
|
6816e8bc67 | ||
|
|
440c43e530 | ||
|
|
310684a563 | ||
|
|
966fa256b6 | ||
|
|
6b3c55902e | ||
|
|
7e736d8d41 | ||
|
|
ea0f0cc7ca | ||
|
|
fbf8b6199c | ||
|
|
b6c16a7ec4 | ||
|
|
b5c1224b76 | ||
|
|
43bbdbc405 | ||
|
|
b9a886fc52 | ||
|
|
9548efdb45 | ||
|
|
eac21f3860 | ||
|
|
ed1feed59d | ||
|
|
2b78193b35 | ||
|
|
0bfa86bd06 | ||
|
|
0f099b71f4 | ||
|
|
7b00eb7c99 | ||
|
|
35e58592db | ||
|
|
ac5581a6f9 | ||
|
|
ecb375ecf5 | ||
|
|
a4bdbf8412 | ||
|
|
434784ecbc | ||
|
|
adb6e11000 | ||
|
|
aa79168660 | ||
|
|
51dc908630 | ||
|
|
50e0cbe62d | ||
|
|
e66d39f6ff | ||
|
|
8ec5dcefb9 | ||
|
|
cf7d00bdf3 | ||
|
|
24cd604b43 | ||
|
|
bc8021cde0 | ||
|
|
e221d83ff8 | ||
|
|
164c74e5dd | ||
|
|
6bdf33b0e5 | ||
|
|
7148051896 | ||
|
|
ddf5290bbd | ||
|
|
1b5a967acf | ||
|
|
ae0458bf8f | ||
|
|
443b73773d | ||
|
|
a9baa3b127 | ||
|
|
44af96c0ee | ||
|
|
d6d7cdf56d | ||
|
|
6bc7a7ec22 | ||
|
|
e11c3caaab | ||
|
|
4166096706 | ||
|
|
a9f13a1b0a | ||
|
|
a4fc2c0a88 | ||
|
|
4515fde7aa | ||
|
|
2f550bc9e8 | ||
|
|
b6a0d49c5c | ||
|
|
f9de6b84ee | ||
|
|
115dbb177f | ||
|
|
b28434f2e2 | ||
|
|
2ed9f4bbc1 | ||
|
|
116a2ce4b4 | ||
|
|
193cf4267a | ||
|
|
f8a567615c | ||
|
|
fd1cbb3239 | ||
|
|
2ac2ec36e0 | ||
|
|
ab4152960b | ||
|
|
eff2cb108b | ||
|
|
7e8eeaa7a5 | ||
|
|
e138d4811d | ||
|
|
388ba26c33 | ||
|
|
07f5dc1969 | ||
|
|
8e63639713 | ||
|
|
3bbaacbac1 | ||
|
|
4f40ef195f | ||
|
|
c2034fd523 | ||
|
|
b33936eac0 | ||
|
|
f37ec5c8ef | ||
|
|
c777515025 | ||
|
|
a238e7fc22 | ||
|
|
0367e0ca6d | ||
|
|
afe1e25cde | ||
|
|
3091783bdd | ||
|
|
a47c04e4a4 | ||
|
|
2ca48a3d06 | ||
|
|
e16c7ee09d | ||
|
|
b2b126068a | ||
|
|
95401baff7 | ||
|
|
b495fb8d36 | ||
|
|
d1d6c90821 | ||
|
|
1adf6e426d | ||
|
|
1fe9048aa2 | ||
|
|
51ad8f0bb0 | ||
|
|
ff98a6fdfd | ||
|
|
b67f40c2df | ||
|
|
9960c4e938 | ||
|
|
e07d62a125 | ||
|
|
7e4b657f41 | ||
|
|
8146628627 | ||
|
|
11528d2239 | ||
|
|
9ac63e2406 | ||
|
|
6907bc3bd3 | ||
|
|
7f5e31461a | ||
|
|
91cb7ddc6f | ||
|
|
34f9e96e4e | ||
|
|
04be99b930 | ||
|
|
3201397f2c | ||
|
|
18f35ceeb3 | ||
|
|
f03b766b6e | ||
|
|
8654473679 | ||
|
|
d0589de592 | ||
|
|
39ba82d63b | ||
|
|
569824a75d | ||
|
|
eeb929d931 | ||
|
|
966cf5eb1c | ||
|
|
2064ba2e42 | ||
|
|
67730d3eb0 | ||
|
|
4c58b9457a | ||
|
|
fcb7a00121 | ||
|
|
e91a538ced | ||
|
|
c9785efa7e | ||
|
|
228719ef96 | ||
|
|
1fc5e44183 | ||
|
|
15e9b6faf0 | ||
|
|
2116d727b9 | ||
|
|
608f3ccec5 | ||
|
|
c0ed63a885 | ||
|
|
e368be4dce | ||
|
|
f6d19a596e | ||
|
|
c207ea417a | ||
|
|
abf9ca714d | ||
|
|
e22566bdeb | ||
|
|
6a8bc6f9dd | ||
|
|
dd6fe949b7 | ||
|
|
3f12efc1d4 | ||
|
|
60d522c3a9 | ||
|
|
0c10bda057 | ||
|
|
f4b358e5c8 | ||
|
|
623c85ccc5 | ||
|
|
65986342b3 | ||
|
|
da461bbc96 | ||
|
|
bcd3de94b4 | ||
|
|
49c379a13e | ||
|
|
896d533736 | ||
|
|
0ae5afabd4 | ||
|
|
6fb1866f41 | ||
|
|
92903e35d8 | ||
|
|
866b340a4e | ||
|
|
2dff048d12 | ||
|
|
c4c18140ed | ||
|
|
6c555525c7 | ||
|
|
b2a7996e6d | ||
|
|
a6387ba79b | ||
|
|
eadd9a8329 | ||
|
|
0aabc03fe6 | ||
|
|
88f3014750 | ||
|
|
ebd3e1f951 | ||
|
|
c98545b5e4 | ||
|
|
3bc9704769 | ||
|
|
3369794097 | ||
|
|
44d18cbdd6 | ||
|
|
454868a6bf | ||
|
|
f84d57a5b4 | ||
|
|
5805a65d3b | ||
|
|
0368b7ee86 | ||
|
|
a7954837f0 | ||
|
|
2c2acc49e4 | ||
|
|
a513f893d0 | ||
|
|
125c2e7f53 | ||
|
|
981056a045 | ||
|
|
268781d610 | ||
|
|
2a8e8c7c11 | ||
|
|
988b23ec73 | ||
|
|
9bf2fb594c | ||
|
|
f0313cd346 | ||
|
|
8270fa2cc3 | ||
|
|
6725005c86 | ||
|
|
7eb3744ec5 | ||
|
|
1d8f5616c8 | ||
|
|
724424246c | ||
|
|
fc9e6e1277 | ||
|
|
056a1ba4af | ||
|
|
f341cc1d06 | ||
|
|
c6628e8a80 | ||
|
|
2c12c42c3f | ||
|
|
22e0edca38 | ||
|
|
6caf6794fb | ||
|
|
8360a78026 | ||
|
|
5ee1880339 | ||
|
|
d03a5f1493 | ||
|
|
f2728892b4 | ||
|
|
b21e7857d0 | ||
|
|
dc4d2fff41 | ||
|
|
5024ab7241 | ||
|
|
9e8244bb71 | ||
|
|
700b220906 | ||
|
|
789f59760b | ||
|
|
114ba6af6e | ||
|
|
5ad0a3d8e3 | ||
|
|
9ab446e409 | ||
|
|
f263f418b7 | ||
|
|
3ee3667886 | ||
|
|
832a2c579e | ||
|
|
d1d417f294 | ||
|
|
c28cdb28f8 | ||
|
|
1bd976f863 | ||
|
|
5bc7019863 | ||
|
|
bd7e5e8e0e | ||
|
|
6b958884d6 | ||
|
|
996e0a2d89 | ||
|
|
904b674378 | ||
|
|
141dce60ee | ||
|
|
b82de64d4d | ||
|
|
204a4268b6 | ||
|
|
1c3045b43f | ||
|
|
6a6f56f377 | ||
|
|
dff83d47af | ||
|
|
9bdd3250bf | ||
|
|
4a2e6ba01b | ||
|
|
a6549bc032 | ||
|
|
ab2260db1f | ||
|
|
35f61a8ffb | ||
|
|
c40542dafd | ||
|
|
e280c7fab5 | ||
|
|
4e5faff617 | ||
|
|
ae7dbf457c | ||
|
|
c5b0032e1d | ||
|
|
50c6c61afb | ||
|
|
736d17caff | ||
|
|
123fb288b1 | ||
|
|
a13b443ab7 | ||
|
|
f55353ecc6 | ||
|
|
03b79972e6 | ||
|
|
1f42f35835 | ||
|
|
a357dea50f | ||
|
|
66a0dc99bf | ||
|
|
0968fb02be | ||
|
|
efcac8b2c2 | ||
|
|
38b53f3195 | ||
|
|
7dcb1a83e0 | ||
|
|
3f3a8cad66 | ||
|
|
12832dea67 | ||
|
|
ba79f25571 | ||
|
|
a21f12ae3c | ||
|
|
c06e12b7d9 | ||
|
|
05043379d9 | ||
|
|
d6c99657a2 | ||
|
|
abf7883490 | ||
|
|
84ae0dbc55 | ||
|
|
2cf4aa79a1 | ||
|
|
0c9676a466 | ||
|
|
97c5c4cc6a | ||
|
|
af39a25695 | ||
|
|
08995d9882 | ||
|
|
d892a0d153 | ||
|
|
1a33f510f2 | ||
|
|
40880434f2 | ||
|
|
24679ed6ac | ||
|
|
3e7ddcbe62 | ||
|
|
9aa1dd6a69 | ||
|
|
d9dedd935a | ||
|
|
4a9ba8fec8 | ||
|
|
568a437069 | ||
|
|
47bc861487 | ||
|
|
5a83849549 | ||
|
|
00db2261fb | ||
|
|
aeda6f3b4d | ||
|
|
1e50285e95 | ||
|
|
80e9595540 | ||
|
|
7a47b141f8 | ||
|
|
c845c7cf0f | ||
|
|
cf549d440a | ||
|
|
91070e791b | ||
|
|
f15a035c9f | ||
|
|
b8c76c776f | ||
|
|
2d8db65622 | ||
|
|
797440669f | ||
|
|
a95a7785eb | ||
|
|
874c58762a | ||
|
|
1b369fc5c3 | ||
|
|
72e9ffd42a | ||
|
|
56ed3c6da7 | ||
|
|
3df92ffd00 | ||
|
|
4b4c7a44a0 | ||
|
|
2cc6667378 | ||
|
|
90ed1d073f | ||
|
|
cc17459117 | ||
|
|
a6de39a08a | ||
|
|
4d9e6a5107 | ||
|
|
c465c96d95 | ||
|
|
7ff9565f92 | ||
|
|
12ba1f945f | ||
|
|
43bf37aa5c | ||
|
|
393ca2551e | ||
|
|
145f8a2801 | ||
|
|
705eba37d2 | ||
|
|
5d8896ecc2 | ||
|
|
c80e8d3436 | ||
|
|
2be398bdc0 | ||
|
|
9ee76af63e | ||
|
|
5ac74859c6 | ||
|
|
e3c837e8b3 | ||
|
|
d4d7b9df98 | ||
|
|
d8e2316f63 | ||
|
|
0ac5017204 | ||
|
|
fccf220039 | ||
|
|
ef2c82ad7e | ||
|
|
3ae9c9b964 | ||
|
|
87b3bff214 | ||
|
|
520a1ae167 | ||
|
|
8e957d6401 | ||
|
|
49ee8682d8 | ||
|
|
49e28c15bf | ||
|
|
f08959e306 | ||
|
|
5c2e29ed1b | ||
|
|
d715a45e22 | ||
|
|
a6cec9d8bc | ||
|
|
bdb8993914 | ||
|
|
8b3a0ced9f | ||
|
|
d858c7fcf5 | ||
|
|
c0f43c0e4c | ||
|
|
2434a7ffbd | ||
|
|
144aee9d54 | ||
|
|
98f85e1465 | ||
|
|
f7ec9b1ca1 | ||
|
|
8e38e2faf6 | ||
|
|
ce80eb0829 | ||
|
|
6cf8c336d7 | ||
|
|
aaa2108824 | ||
|
|
f57aea17bb | ||
|
|
6af60c739e | ||
|
|
d9fa08b383 | ||
|
|
a916274a9d | ||
|
|
1f82202776 | ||
|
|
734b344ddf | ||
|
|
803d605da4 | ||
|
|
d64c0a9fea | ||
|
|
8cc6e58875 | ||
|
|
4f895b85b3 | ||
|
|
f6dcf3a479 | ||
|
|
fea9136382 | ||
|
|
bff568475c | ||
|
|
3a4ff57188 | ||
|
|
6860db60c9 | ||
|
|
2ef0cc1bb3 | ||
|
|
c89ed74fea | ||
|
|
14465fee66 | ||
|
|
a6ac97309e | ||
|
|
05666e2ab3 | ||
|
|
3632f67d8b | ||
|
|
719e2df867 | ||
|
|
9ed988d774 | ||
|
|
7146f5cf77 | ||
|
|
fc60671dd8 | ||
|
|
fdd2d241b4 |
@@ -25,3 +25,4 @@ npm-debug.log*
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
temp/
|
||||
|
||||
+88
-1
@@ -2,7 +2,94 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## Unreleased
|
||||
## events@2.4.0, contracts@1.4.0 - unreleased
|
||||
|
||||
Phase 2 (docs/EVENTS-2.4-PLAN.md): protocol v2, Linked products, the event feed and
|
||||
`packages/seo`. With Hub 2.2.0 (events-hub). Not tagged yet: the e2e run and the VM test come first.
|
||||
|
||||
### Events (2.4.0)
|
||||
|
||||
- Protocol v2 with the site's own Ed25519 key, Settings → Linked products with Connect, the public
|
||||
event feed (`/api/feed/v1/events`) and `event.changed`, and events from linked products on the
|
||||
public pages. Details in `apps/events/CHANGELOG.md`.
|
||||
|
||||
### Contracts (1.4.0)
|
||||
|
||||
- `crosscode.link/1` (`link.connect`, `link.connected`, `link.disconnect`) with `signLink` /
|
||||
`verifyLink`, PEM helpers, link secrets and nonces; `LINK_PATHS`, `FEED_PATHS`.
|
||||
- The v2 heartbeat can carry `publicKey`; the reply's `publicKeyStatus` (`saved` / `matches` /
|
||||
`mismatch`).
|
||||
- `typesVersions` for `@crosscode/contracts/signing` (older `moduleResolution`).
|
||||
|
||||
### packages/seo (new)
|
||||
|
||||
- `eventJsonLd`, `churchJsonLd`, `canonicalUrl`, `pageMeta`, `jsonLdString` (ROADMAP-v3 §11).
|
||||
|
||||
### Scripts
|
||||
|
||||
- `crosscode` (Events): installs and builds the shared packages Events uses before it.
|
||||
|
||||
## events@2.3.1 - 2026-11-18
|
||||
|
||||
- Next.js 16.4.6 (security advisories for 16.2.0–16.4.4; Events wasn't exposed). Also brings
|
||||
`apps/events/package.json` up to the release (it was left at 2.2.0). Details in
|
||||
`apps/events/CHANGELOG.md`.
|
||||
|
||||
## agent@1.0.1 - 2026-11-18
|
||||
|
||||
- A `status` job on the central server is answered by the agent itself (its stats, frps and
|
||||
the agent version). It used to run `crosscode status`, which central servers don't have, and
|
||||
failed with `spawn /usr/local/bin/crosscode ENOENT`.
|
||||
|
||||
## events@2.3.0, contracts@1.3.0, agent@1.0.0 - 2026-11-17
|
||||
|
||||
Phase 1c (authenticator-app sign-in) and phase 1d (docs/AGENT-1.0-PLAN.md): installs, updates and
|
||||
uninstalls from the Hub (Hub 2.1.0) through the agent. Tested end to end on a VM (church server +
|
||||
central server + Hub, AGENT-1.0-PLAN §13 and EVENTS-2.2-PLAN §6).
|
||||
|
||||
### Events (2.3.0)
|
||||
|
||||
- Two-factor with an authenticator app, and recovery codes. The env template, the church export
|
||||
and registering by itself from `HUB_LICENCE_KEY` for installs from the Hub. Details in
|
||||
`apps/events/CHANGELOG.md`.
|
||||
|
||||
### Contracts (1.3.0)
|
||||
|
||||
- `crosscode.agent-job/1` (fixed job types, strict arguments), `crosscode.agent-report/1`,
|
||||
`crosscode.script-report/1`, `crosscode.agent-stats/1`, the agent join / poll requests,
|
||||
`crosscode.env-template/1` and `crosscode.church-export/1`.
|
||||
- `@crosscode/contracts/signing`: Ed25519 jobs (over canonical JSON) and agent requests, config
|
||||
sealed to a server (X25519 + HKDF + AES-256-GCM), export encryption.
|
||||
|
||||
### Agent (1.0.0)
|
||||
|
||||
- `apps/agent`: polls the Hub, checks every job (pinned key, server, time window, replays, type,
|
||||
arguments) and runs the crosscode script for it; stats every minute; listens on nothing.
|
||||
Install script, systemd unit, self-update with automatic revert.
|
||||
|
||||
### crosscode script
|
||||
|
||||
- `--json` reports and `--config` on every command; `.env` files from each release's env template
|
||||
(appended to, never rewritten, on deploy); `install --frp` with Hub-given ports, a database on
|
||||
another server, and clean-up on failure; frpc.ini blocks; `restart`, `export`, `uninstall`, `purge`.
|
||||
- Fixed in the VM test: `adopt` applies a release's new migrations in the switch-over; a failed
|
||||
migration is marked rolled back so later deploys aren't blocked; frpc is restarted once when its
|
||||
admin lines are first added; a site's PM2 always runs under its own systemd unit (`pm2-<user>`),
|
||||
so restarting or updating the agent never stops a site; tags are fetched with `--force`.
|
||||
|
||||
## events@2.2.0, contracts@1.2.0 - 2026-11-17
|
||||
|
||||
### Events
|
||||
|
||||
- **Cross Events 2.2.0**, the first release from this repo (`apps/events`, ROADMAP-v3 phase 1b):
|
||||
moved in with its history, npm workspaces with one root lockfile, and the `crosscode` script
|
||||
(`deploy`, `status`, `install`, `adopt`) in `scripts/`. Also AI use shown in tokens instead of
|
||||
rand, and everything the backend serves under `/api`. Details in `apps/events/CHANGELOG.md`.
|
||||
|
||||
### Contracts
|
||||
|
||||
- AI status (Hub protocol §3b): optional `usedInputTokens`, `usedOutputTokens`, `capInputTokens`,
|
||||
`capOutputTokens` (Hub 2.0.1). Churches see tokens; the cents stay for the Hub and older installs.
|
||||
|
||||
### Docs
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Cross Code server agent
|
||||
|
||||
Runs on every server (docs/AGENT-1.0-PLAN.md). It polls Cross Code Hub every 30 seconds for
|
||||
signed jobs, runs the `crosscode` script for them, sends the results, and sends the server's
|
||||
stats every 60 seconds. **It listens on nothing**: no port, no URL; every request goes out to the Hub.
|
||||
|
||||
## Joining a server
|
||||
|
||||
Hub → Servers → **Add server** shows a command with a one-time token (valid an hour):
|
||||
|
||||
```bash
|
||||
curl -fsSL https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/apps/agent/deploy/install.sh \
|
||||
| sudo bash -s -- --hub https://hub.crosscode.co.za --token <token>
|
||||
```
|
||||
|
||||
Add `--central` on the central (FastPanel) server: there the agent is read-only and only runs
|
||||
`check-ports` and `status`. The script installs Node 24 if needed, the agent in
|
||||
`/opt/crosscode/agent/releases/<version>` (with `current` pointing at it), the `crosscode` script in
|
||||
`/opt/crosscode/tools` (church servers), makes the server's two key pairs, joins, and starts
|
||||
`crosscode-agent.service`.
|
||||
|
||||
## On the server
|
||||
|
||||
| What | Where |
|
||||
|------|-------|
|
||||
| Config (Hub address, server id, the Hub's pinned job key) | `/etc/crosscode/agent.json` |
|
||||
| Private keys (never leave the server) | `/etc/crosscode/agent-ed25519.pem`, `agent-x25519.pem` |
|
||||
| Seen job ids (90 days), unsent reports, exports in progress | `/var/lib/crosscode-agent/` |
|
||||
| A job's opened config, only while it runs | `/run/crosscode-agent/` |
|
||||
| Logs | `journalctl -u crosscode-agent` |
|
||||
|
||||
## Security
|
||||
|
||||
- **Jobs are signed** by the Hub's job key (Ed25519, pinned when joining). The agent refuses a
|
||||
job that's unsigned, for another server, outside its time window, already seen, of an unknown
|
||||
type, or with an argument outside its schema. Refusals are reported to the Hub.
|
||||
- **Only the `crosscode` script runs**, with arguments built from the checked job (an array,
|
||||
never a shell). There's no "run this command" job.
|
||||
- **Config** (database admin, server settings) arrives sealed to this server's X25519 key. It's
|
||||
opened into a root-only file for the job and removed straight after.
|
||||
- **Log lines** sent with a report are filtered for passwords, tokens, keys and licence keys.
|
||||
- **Exports** are encrypted on the server with a new key; the key travels in the job's report
|
||||
so the Hub can email the download link, and the Hub doesn't store it.
|
||||
|
||||
## Updates
|
||||
|
||||
An `update-agent` job builds the new release next to the running one, switches `current`, and
|
||||
restarts. If the new agent hasn't polled the Hub within 150 seconds, `revert.sh` switches back.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
npm run build -w apps/agent # dist/cli.js: one file, everything bundled
|
||||
npm test -w apps/agent # the no-listening-socket test runs on Linux, after a build
|
||||
```
|
||||
@@ -0,0 +1,23 @@
|
||||
# The Cross Code server agent (docs/AGENT-1.0-PLAN.md §3). Root, because the crosscode script it
|
||||
# runs needs root (PostgreSQL, PM2 for each app user, frpc). It listens on nothing.
|
||||
[Unit]
|
||||
Description=Cross Code server agent
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/bin/node /opt/crosscode/agent/current/apps/agent/dist/cli.js run
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
RuntimeDirectory=crosscode-agent
|
||||
RuntimeDirectoryMode=0700
|
||||
StateDirectory=crosscode-agent
|
||||
StateDirectoryMode=0700
|
||||
Environment=NODE_ENV=production
|
||||
# Logs: journalctl -u crosscode-agent
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env bash
|
||||
# Installs the Cross Code server agent and joins this server to the Hub
|
||||
# (docs/AGENT-1.0-PLAN.md §3). Hub → Servers → Add server shows the command, with a one-time token:
|
||||
#
|
||||
# curl -fsSL https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/apps/agent/deploy/install.sh \
|
||||
# | sudo bash -s -- --hub https://hub.crosscode.co.za --token <token> [--central]
|
||||
#
|
||||
# Church servers also get the crosscode script (/opt/crosscode/tools, linked as
|
||||
# /usr/local/bin/crosscode). The central server (--central) only gets the agent, which is
|
||||
# read-only there. Running it again updates nothing that's there already; use --force to join again.
|
||||
set -Eeuo pipefail
|
||||
|
||||
REPO="${CROSSCODE_REPO:-https://c-git.crosscode.co.za/joshua/crosscode-platform.git}"
|
||||
ROOT=/opt/crosscode/agent
|
||||
TOOLS=/opt/crosscode/tools
|
||||
HUB="" TOKEN="" MODE=church VERSION="" FORCE=""
|
||||
|
||||
die() { printf '!!> %s\n' "$*" >&2; exit 1; }
|
||||
step() { printf '==> %s\n' "$*"; }
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--hub) HUB="$2"; shift 2 ;;
|
||||
--token) TOKEN="$2"; shift 2 ;;
|
||||
--central) MODE=central; shift ;;
|
||||
--version) VERSION="$2"; shift 2 ;;
|
||||
--force) FORCE=--force; shift ;;
|
||||
*) die "Unknown option $1" ;;
|
||||
esac
|
||||
done
|
||||
[ "$(id -u)" = 0 ] || die "Run as root (sudo bash -s -- …)."
|
||||
[[ "$HUB" =~ ^https?:// ]] || die "--hub <url> is required."
|
||||
[[ "$TOKEN" =~ ^[A-Za-z0-9_-]{32,128}$ ]] || die "--token is required (Hub → Servers → Add server)."
|
||||
[ -z "$VERSION" ] || [[ "$VERSION" =~ ^agent@[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "--version: expected agent@x.y.z."
|
||||
|
||||
step "System packages"
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update -q
|
||||
apt-get install -y -q git curl ca-certificates
|
||||
if ! command -v node >/dev/null || [ "$(node -p 'process.versions.node.split(".")[0]')" -lt 24 ]; then
|
||||
step "Node.js 24"
|
||||
curl -fsSL https://deb.nodesource.com/setup_24.x | bash -
|
||||
apt-get install -y -q nodejs
|
||||
fi
|
||||
|
||||
if [ -z "$VERSION" ]; then
|
||||
VERSION="$(git ls-remote --tags --refs "$REPO" 'agent@*' | sed 's#.*refs/tags/##' | sort -t@ -k2 -V | tail -n 1)"
|
||||
[ -n "$VERSION" ] || die "No agent@x.y.z release yet."
|
||||
fi
|
||||
DIR="$ROOT/releases/${VERSION#agent@}"
|
||||
|
||||
step "Agent $VERSION in $DIR"
|
||||
mkdir -p "$ROOT/releases"
|
||||
chmod 755 /opt/crosscode "$ROOT" 2>/dev/null || true
|
||||
if [ ! -d "$DIR/.git" ]; then
|
||||
git clone --quiet --depth 1 --branch "$VERSION" "$REPO" "$DIR"
|
||||
fi
|
||||
(
|
||||
cd "$DIR"
|
||||
NODE_ENV=development npm ci --no-audit --no-fund --include=dev --include-workspace-root -w packages/contracts -w apps/agent
|
||||
npm run build -w packages/contracts
|
||||
npm run build -w apps/agent
|
||||
)
|
||||
[ "$(node "$DIR/apps/agent/dist/cli.js" version)" = "${VERSION#agent@}" ] || die "The build doesn't report $VERSION."
|
||||
ln -sfn "$DIR" "$ROOT/current"
|
||||
install -m 755 "$DIR/apps/agent/deploy/revert.sh" "$ROOT/revert.sh"
|
||||
|
||||
if [ "$MODE" = church ]; then
|
||||
step "The crosscode script ($TOOLS)"
|
||||
[ -d "$TOOLS/.git" ] || git clone --quiet "$REPO" "$TOOLS"
|
||||
ln -sfn "$TOOLS/scripts/crosscode" /usr/local/bin/crosscode
|
||||
fi
|
||||
|
||||
step "Joining the Hub ($HUB)"
|
||||
mkdir -p /etc/crosscode /var/lib/crosscode-agent
|
||||
chmod 700 /etc/crosscode /var/lib/crosscode-agent
|
||||
args=(join --hub "$HUB" --token "$TOKEN")
|
||||
[ "$MODE" = central ] && args+=(--central)
|
||||
[ -n "$FORCE" ] && args+=("$FORCE")
|
||||
if [ -f /etc/crosscode/agent.json ] && [ -z "$FORCE" ]; then
|
||||
echo " Already joined (/etc/crosscode/agent.json); keeping it."
|
||||
else
|
||||
node "$ROOT/current/apps/agent/dist/cli.js" "${args[@]}"
|
||||
fi
|
||||
|
||||
step "systemd"
|
||||
install -m 644 "$DIR/apps/agent/deploy/crosscode-agent.service" /etc/systemd/system/crosscode-agent.service
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now crosscode-agent
|
||||
systemctl restart crosscode-agent
|
||||
step "Done: the server shows on Hub → Servers within a minute (journalctl -u crosscode-agent)."
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
# Started by a one-shot systemd timer after an agent update (src/update.ts). If the new agent
|
||||
# hasn't polled the Hub by now, update-pending.json is still there: switch back to the previous
|
||||
# release and restart. Copied to /opt/crosscode/agent/revert.sh by install.sh.
|
||||
set -euo pipefail
|
||||
ROOT=/opt/crosscode/agent
|
||||
PENDING=/var/lib/crosscode-agent/update-pending.json
|
||||
[ -f "$PENDING" ] || exit 0
|
||||
[ -L "$ROOT/previous" ] || { echo "crosscode-agent revert: no previous release" >&2; exit 1; }
|
||||
ln -sfn "$(readlink "$ROOT/previous")" "$ROOT/current.tmp"
|
||||
mv -T "$ROOT/current.tmp" "$ROOT/current"
|
||||
rm -f "$PENDING"
|
||||
systemctl restart crosscode-agent
|
||||
echo "crosscode-agent revert: the new agent didn't poll in time; back on $(readlink "$ROOT/current")" >&2
|
||||
@@ -0,0 +1,7 @@
|
||||
module.exports = {
|
||||
testEnvironment: "node",
|
||||
testMatch: ["<rootDir>/tests/**/*.test.ts"],
|
||||
transform: { "^.+\\.ts$": ["ts-jest", { tsconfig: { module: "commonjs", moduleResolution: "node", isolatedModules: true } }] },
|
||||
moduleFileExtensions: ["ts", "js", "json"],
|
||||
modulePathIgnorePatterns: ["<rootDir>/dist/"],
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "@crosscode/agent",
|
||||
"version": "1.0.1",
|
||||
"private": true,
|
||||
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
|
||||
"license": "UNLICENSED",
|
||||
"bin": { "crosscode-agent": "./dist/cli.js" },
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "jest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"engines": { "node": ">=24" }
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
* The central server (AGENT-1.0-PLAN §6): read-only checks of frps for `check-ports`. Nothing on
|
||||
* the central server is ever changed: no frps edits, no firewall, no FastPanel.
|
||||
*/
|
||||
|
||||
export interface FrpsSettings {
|
||||
proxyBindAddr: string | null;
|
||||
allowPorts: string | null;
|
||||
}
|
||||
|
||||
/** frps.ini's [common] proxy_bind_addr and allow_ports (null when not set or no file). */
|
||||
export function parseFrpsIni(text: string): FrpsSettings {
|
||||
let inCommon = false;
|
||||
const out: FrpsSettings = { proxyBindAddr: null, allowPorts: null };
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (/^\[.*\]$/.test(line)) { inCommon = line === "[common]"; continue; }
|
||||
if (!inCommon || line.startsWith("#") || line.startsWith(";")) continue;
|
||||
const m = /^([a-z_]+)\s*=\s*(.*)$/.exec(line);
|
||||
if (!m) continue;
|
||||
if (m[1] === "proxy_bind_addr") out.proxyBindAddr = m[2]!.trim() || null;
|
||||
if (m[1] === "allow_ports") out.allowPorts = m[2]!.trim() || null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function readFrps(file = paths.frpsIni): FrpsSettings | null {
|
||||
try {
|
||||
return parseFrpsIni(fs.readFileSync(file, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a port is inside allow_ports ("2000-3000,3001,4000-5000"); no allow_ports allows all. */
|
||||
export function portAllowed(port: number, allowPorts: string | null): boolean {
|
||||
if (!allowPorts) return true;
|
||||
return allowPorts.split(",").map((s) => s.trim()).filter(Boolean).some((range) => {
|
||||
const [a, b] = range.split("-").map((n) => Number(n.trim()));
|
||||
if (!Number.isFinite(a)) return false;
|
||||
return b === undefined ? port === a : Number.isFinite(b) && port >= a! && port <= b;
|
||||
});
|
||||
}
|
||||
|
||||
/** Listening TCP sockets from `ss -ltnH`: port → local addresses. */
|
||||
export function parseSs(text: string): Map<number, string[]> {
|
||||
const out = new Map<number, string[]>();
|
||||
for (const line of text.split("\n")) {
|
||||
const cols = line.trim().split(/\s+/);
|
||||
const local = cols[3];
|
||||
if (!local) continue;
|
||||
const i = local.lastIndexOf(":");
|
||||
const port = Number(local.slice(i + 1));
|
||||
const addr = local.slice(0, i).replace(/^\[|\]$/g, "").replace(/%.*$/, "");
|
||||
if (!Number.isFinite(port)) continue;
|
||||
out.set(port, [...(out.get(port) ?? []), addr]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
|
||||
|
||||
export interface PortCheck {
|
||||
port: number;
|
||||
allowed: boolean;
|
||||
listening: boolean;
|
||||
loopbackOnly: boolean;
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export function checkPorts(ports: number[], frps: FrpsSettings | null, listening: Map<number, string[]>): { ports: PortCheck[]; proxyBindAddr: string | null; warnings: string[] } {
|
||||
const warnings: string[] = [];
|
||||
if (!frps) warnings.push(`No frps.ini at ${paths.frpsIni}.`);
|
||||
const bind = frps?.proxyBindAddr ?? null;
|
||||
if (frps && (!bind || !LOOPBACK.has(bind))) warnings.push(`proxy_bind_addr is ${bind ? `"${bind}"` : "not set"}: tunnels can be reached straight from the internet. Set proxy_bind_addr = 127.0.0.1 in frps.ini.`);
|
||||
const results = ports.map((port) => {
|
||||
const addrs = listening.get(port) ?? [];
|
||||
const allowed = portAllowed(port, frps?.allowPorts ?? null);
|
||||
const loopbackOnly = addrs.length > 0 && addrs.every((a) => LOOPBACK.has(a));
|
||||
return { port, allowed, listening: addrs.length > 0, loopbackOnly, ok: allowed && addrs.length > 0 && loopbackOnly };
|
||||
});
|
||||
for (const r of results) {
|
||||
if (!r.allowed) warnings.push(`Port ${r.port} isn't in allow_ports.`);
|
||||
else if (!r.listening) warnings.push(`Port ${r.port} isn't open in frps (is the church server's frpc connected?).`);
|
||||
else if (!r.loopbackOnly) warnings.push(`Port ${r.port} is open on more than 127.0.0.1.`);
|
||||
}
|
||||
return { ports: results, proxyBindAddr: bind, warnings };
|
||||
}
|
||||
|
||||
export function listeningNow(): Promise<Map<number, string[]>> {
|
||||
return new Promise((resolve) => {
|
||||
execFile("ss", ["-ltnH"], { timeout: 10_000 }, (err, stdout) => resolve(err ? new Map() : parseSs(String(stdout))));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { generateEd25519, generateX25519 } from "@crosscode/contracts/signing";
|
||||
import { configFile, ed25519File, loadConfig, saveConfig, writePrivate, x25519File } from "./config";
|
||||
import { hubClient, postUnsigned } from "./hub";
|
||||
import { Agent } from "./loop";
|
||||
import { AGENT_VERSION } from "./stats";
|
||||
|
||||
/**
|
||||
* crosscode-agent (AGENT-1.0-PLAN §3)
|
||||
* crosscode-agent join --hub https://hub.crosscode.co.za --token <one-time token> [--central]
|
||||
* crosscode-agent run what systemd runs (crosscode-agent.service)
|
||||
* crosscode-agent version
|
||||
*/
|
||||
|
||||
const USAGE = `crosscode-agent ${AGENT_VERSION}
|
||||
|
||||
crosscode-agent join --hub <url> --token <token> [--central] [--force]
|
||||
Join this server to the Hub with a one-time token (Hub → Servers → Add server).
|
||||
Makes the server's key pairs; the private keys never leave it.
|
||||
crosscode-agent run poll the Hub for jobs and send stats (run by systemd)
|
||||
crosscode-agent version
|
||||
`;
|
||||
|
||||
function flag(args: string[], name: string): string | undefined {
|
||||
const i = args.indexOf(name);
|
||||
return i >= 0 ? args[i + 1] : undefined;
|
||||
}
|
||||
|
||||
export async function join(args: string[]): Promise<void> {
|
||||
const hub = flag(args, "--hub");
|
||||
const token = flag(args, "--token");
|
||||
const mode: agent.AgentMode = args.includes("--central") ? "central" : "church";
|
||||
if (!hub || !/^https?:\/\//.test(hub)) throw new Error("--hub <url> is required (https://hub.crosscode.co.za).");
|
||||
if (!token) throw new Error("--token <token> is required (Hub → Servers → Add server).");
|
||||
if (fs.existsSync(configFile()) && !args.includes("--force")) {
|
||||
throw new Error(`This server has already joined (${configFile()}). Use --force to join again (the Hub then sees a new server).`);
|
||||
}
|
||||
const ed = generateEd25519();
|
||||
const x = generateX25519();
|
||||
const reply = agent.joinResponseSchema.parse(await postUnsigned(hub, "/api/agent/v1/join", {
|
||||
agentApiVersion: agent.AGENT_API_VERSION,
|
||||
token,
|
||||
mode,
|
||||
hostname: os.hostname().slice(0, 253),
|
||||
agentVersion: AGENT_VERSION,
|
||||
publicKeys: { ed25519: ed.publicKey, x25519: x.publicKey },
|
||||
}));
|
||||
writePrivate(ed25519File(), ed.privateKeyPem);
|
||||
writePrivate(x25519File(), x.privateKeyPem);
|
||||
saveConfig({ hubUrl: hub, serverId: reply.serverId, mode, hubJobKey: reply.hubJobKey, pollSeconds: reply.pollSeconds, statsSeconds: reply.statsSeconds, joinedAt: new Date().toISOString() });
|
||||
console.log(`Joined the Hub as ${reply.serverId} (${mode}). Start the agent: systemctl enable --now crosscode-agent`);
|
||||
}
|
||||
|
||||
export async function main(argv = process.argv.slice(2)): Promise<void> {
|
||||
const [command, ...args] = argv;
|
||||
switch (command) {
|
||||
case "version":
|
||||
case "--version":
|
||||
console.log(AGENT_VERSION);
|
||||
return;
|
||||
case "join":
|
||||
await join(args);
|
||||
return;
|
||||
case "run": {
|
||||
if (process.getuid && process.getuid() !== 0 && !process.env.CROSSCODE_AGENT_ALLOW_NON_ROOT) {
|
||||
throw new Error("Run the agent as root (it runs crosscode, which needs root).");
|
||||
}
|
||||
const { config, keys } = loadConfig();
|
||||
const a = new Agent({ config, keys, hub: hubClient(config, keys) });
|
||||
for (const sig of ["SIGTERM", "SIGINT"] as const) process.on(sig, () => { a.stop(); setTimeout(() => process.exit(0), 1000).unref(); });
|
||||
await a.start();
|
||||
return;
|
||||
}
|
||||
default:
|
||||
process.stdout.write(USAGE);
|
||||
if (command && command !== "help" && command !== "--help") process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((e) => {
|
||||
console.error(`crosscode-agent: ${(e as Error).message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { agent } from "@crosscode/contracts";
|
||||
|
||||
/**
|
||||
* The `crosscode` arguments for a job (AGENT-1.0-PLAN §4): built from the checked arguments only,
|
||||
* as an array passed straight to the process (never through a shell). Jobs the agent handles
|
||||
* itself (update-agent, check-ports) have none.
|
||||
*
|
||||
* `--config <file>` is added by the runner when the job brings config; `--json` always.
|
||||
*/
|
||||
export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string } = {}): string[] | null {
|
||||
switch (job.type) {
|
||||
case "install": {
|
||||
const a = job.args;
|
||||
if (a.products.length !== 1 || a.products[0] !== "events") throw new Error("This agent can only install Events so far.");
|
||||
const domain = a.domains.events;
|
||||
const ports = a.ports.events;
|
||||
if (!domain || !ports) throw new Error("An Events install needs its domain and ports.");
|
||||
// The church's address: the Events domain without "events." (crosscode uses it for the
|
||||
// church.env ADDRESS; the domain itself goes in --events-domain).
|
||||
const address = domain.startsWith("events.") ? domain.slice("events.".length) : domain;
|
||||
const out = ["install", a.church, "--products", "events", "--domain", address, "--events-domain", domain,
|
||||
"--api-port", String(ports.api), "--web-port", String(ports.web), "--frp"];
|
||||
const v = a.versions?.events;
|
||||
if (v) out.push("--version", v);
|
||||
return out;
|
||||
}
|
||||
case "add-product":
|
||||
return ["add", job.args.church, job.args.product];
|
||||
case "deploy": {
|
||||
const out = ["deploy", job.args.church, ...job.args.products];
|
||||
for (const v of job.args.versions ?? []) out.push("--version", v);
|
||||
if (job.args.check) out.push("--check");
|
||||
return out;
|
||||
}
|
||||
case "adopt": {
|
||||
const out = ["adopt", job.args.church, "--events-dir", job.args.eventsDir];
|
||||
if (job.args.version) out.push("--version", job.args.version);
|
||||
if (job.args.address) out.push("--address", job.args.address);
|
||||
return out;
|
||||
}
|
||||
case "adopt-undo":
|
||||
return ["adopt", job.args.church, "--undo"];
|
||||
case "restart":
|
||||
return ["restart", job.args.church, ...(job.args.product ? [job.args.product] : [])];
|
||||
case "export":
|
||||
if (!opts.exportFile) throw new Error("export needs a file to write");
|
||||
return ["export", job.args.church, "--out", opts.exportFile];
|
||||
case "uninstall":
|
||||
return ["uninstall", job.args.church, "--confirm", job.args.church];
|
||||
case "purge":
|
||||
return ["purge", job.args.church, "--confirm", job.args.church];
|
||||
case "status":
|
||||
return ["status", ...(job.args.church ? [job.args.church] : []), "--no-fetch"];
|
||||
case "update-agent":
|
||||
case "check-ports":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { z } from "zod";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { publicKeyOf } from "@crosscode/contracts/signing";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/** /etc/crosscode/agent.json, written by `crosscode-agent join`. No secrets: the keys are files next to it. */
|
||||
export const agentConfigSchema = z.object({
|
||||
hubUrl: z.url({ protocol: /^https?$/ }),
|
||||
serverId: z.string().regex(/^srv_[A-Za-z0-9_-]{8,64}$/),
|
||||
mode: agent.agentModeSchema,
|
||||
/** The Hub's job-signing key, pinned when joining. */
|
||||
hubJobKey: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
|
||||
pollSeconds: z.int().min(5).max(600).default(30),
|
||||
statsSeconds: z.int().min(15).max(3600).default(60),
|
||||
joinedAt: z.string(),
|
||||
});
|
||||
export type AgentConfig = z.infer<typeof agentConfigSchema>;
|
||||
|
||||
export interface Keys {
|
||||
ed25519Pem: string;
|
||||
x25519Pem: string;
|
||||
}
|
||||
|
||||
export const configFile = () => path.join(paths.configDir, "agent.json");
|
||||
export const ed25519File = () => path.join(paths.configDir, "agent-ed25519.pem");
|
||||
export const x25519File = () => path.join(paths.configDir, "agent-x25519.pem");
|
||||
|
||||
/** Writes a file only root can read, atomically. */
|
||||
export function writePrivate(file: string, text: string): void {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
||||
const tmp = `${file}.tmp-${process.pid}`;
|
||||
fs.writeFileSync(tmp, text, { mode: 0o600 });
|
||||
fs.renameSync(tmp, file);
|
||||
}
|
||||
|
||||
export function loadConfig(): { config: AgentConfig; keys: Keys } {
|
||||
const config = agentConfigSchema.parse(JSON.parse(fs.readFileSync(configFile(), "utf8")));
|
||||
const keys = { ed25519Pem: fs.readFileSync(ed25519File(), "utf8"), x25519Pem: fs.readFileSync(x25519File(), "utf8") };
|
||||
// A broken pair would sign requests the Hub can't check; better to stop at start.
|
||||
publicKeyOf(keys.ed25519Pem);
|
||||
publicKeyOf(keys.x25519Pem);
|
||||
return { config, keys };
|
||||
}
|
||||
|
||||
export function saveConfig(config: AgentConfig): void {
|
||||
writePrivate(configFile(), `${JSON.stringify(config, null, 2)}\n`);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { signAgentRequest } from "@crosscode/contracts/signing";
|
||||
import type { AgentConfig, Keys } from "./config";
|
||||
|
||||
/**
|
||||
* Requests to the Hub. The agent only ever makes outgoing requests (it listens on nothing,
|
||||
* AGENT-1.0-PLAN §2 rule 1); every one after joining is signed with the server's Ed25519 key.
|
||||
*/
|
||||
|
||||
export class HubRequestError extends Error {
|
||||
constructor(message: string, readonly status: number, readonly code: string | null) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export type Fetch = typeof fetch;
|
||||
|
||||
export interface HubClient {
|
||||
post(path: string, body: unknown): Promise<unknown>;
|
||||
put(path: string, body: Uint8Array, contentType: string): Promise<unknown>;
|
||||
}
|
||||
|
||||
const TIMEOUT_MS = 30_000;
|
||||
const UPLOAD_TIMEOUT_MS = 10 * 60_000;
|
||||
|
||||
async function send(fetcher: Fetch, url: string, init: RequestInit, timeoutMs: number): Promise<unknown> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetcher(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
||||
} catch (e) {
|
||||
throw new HubRequestError(`The Hub can't be reached: ${(e as Error).message}`, 0, "HUB_UNREACHABLE");
|
||||
}
|
||||
if (res.status === 204) return null;
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await res.json();
|
||||
} catch {
|
||||
body = null;
|
||||
}
|
||||
if (!res.ok) {
|
||||
const b = (body ?? {}) as { message?: string; code?: string };
|
||||
throw new HubRequestError(b.message || `The Hub answered ${res.status}`, res.status, b.code ?? null);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/** An unsigned request (only `join`, where the one-time token is the proof). */
|
||||
export function postUnsigned(hubUrl: string, path: string, body: unknown, fetcher: Fetch = fetch): Promise<unknown> {
|
||||
return send(fetcher, `${hubUrl.replace(/\/$/, "")}${path}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", "user-agent": "crosscode-agent" },
|
||||
body: JSON.stringify(body),
|
||||
}, TIMEOUT_MS);
|
||||
}
|
||||
|
||||
export function hubClient(config: AgentConfig, keys: Keys, fetcher: Fetch = fetch): HubClient {
|
||||
const base = config.hubUrl.replace(/\/$/, "");
|
||||
const signed = (raw: string | Uint8Array) => signAgentRequest({ serverId: config.serverId, privateKeyPem: keys.ed25519Pem, rawBody: raw });
|
||||
return {
|
||||
post(path, body) {
|
||||
const raw = JSON.stringify(body);
|
||||
return send(fetcher, `${base}${path}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", "user-agent": "crosscode-agent", ...signed(raw) },
|
||||
body: raw,
|
||||
}, TIMEOUT_MS);
|
||||
},
|
||||
put(path, body, contentType) {
|
||||
return send(fetcher, `${base}${path}`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": contentType, "user-agent": "crosscode-agent", ...signed(body) },
|
||||
body,
|
||||
}, UPLOAD_TIMEOUT_MS);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { encryptExport } from "@crosscode/contracts/signing";
|
||||
import { checkPorts, listeningNow, readFrps } from "./central";
|
||||
import { crosscodeArgs } from "./command";
|
||||
import type { AgentConfig, Keys } from "./config";
|
||||
import { type HubClient, HubRequestError } from "./hub";
|
||||
import { paths } from "./paths";
|
||||
import { runCrosscode, type RunResult } from "./runner";
|
||||
import { AGENT_VERSION, collectStats } from "./stats";
|
||||
import { confirmUpdate, updateAgent } from "./update";
|
||||
import { checkJob, SeenJobs } from "./verify";
|
||||
|
||||
/**
|
||||
* The agent's life: poll the Hub every 30 s for jobs due, send stats every 60 s, run one job at a
|
||||
* time and send each result. Reports that can't be sent are kept in an outbox and sent later, so
|
||||
* a Hub outage never loses a job's result. Nothing here listens: every request goes out.
|
||||
*/
|
||||
|
||||
const log = (...a: unknown[]) => console.log(new Date().toISOString(), ...a);
|
||||
|
||||
export interface AgentDeps {
|
||||
config: AgentConfig;
|
||||
keys: Keys;
|
||||
hub: HubClient;
|
||||
seen?: SeenJobs;
|
||||
/** For tests: replaces running crosscode and the stats. */
|
||||
run?: (args: string[], job: agent.AgentJob) => Promise<RunResult>;
|
||||
stats?: () => Promise<agent.AgentStats>;
|
||||
now?: () => Date;
|
||||
}
|
||||
|
||||
const outboxDir = () => path.join(paths.stateDir, "outbox");
|
||||
|
||||
function report(job: { id: string; type: agent.JobType }, serverId: string, r: Omit<RunResult, "log"> & { log?: string[] }): agent.AgentReport {
|
||||
return {
|
||||
schema: "crosscode.agent-report/1",
|
||||
jobId: job.id,
|
||||
serverId,
|
||||
type: job.type,
|
||||
status: r.status,
|
||||
startedAt: r.startedAt,
|
||||
finishedAt: r.finishedAt,
|
||||
steps: r.steps.slice(0, 200),
|
||||
result: r.result,
|
||||
...(r.message ? { message: r.message.slice(0, 2000) } : {}),
|
||||
log: (r.log ?? []).slice(-200),
|
||||
};
|
||||
}
|
||||
|
||||
export class Agent {
|
||||
private seen: SeenJobs;
|
||||
private stopped = false;
|
||||
private confirmed = false;
|
||||
private failures = 0;
|
||||
|
||||
constructor(private deps: AgentDeps) {
|
||||
this.seen = deps.seen ?? new SeenJobs();
|
||||
}
|
||||
|
||||
private now(): Date {
|
||||
return this.deps.now?.() ?? new Date();
|
||||
}
|
||||
|
||||
/** Sends a report, or keeps it in the outbox to send later. */
|
||||
async send(r: agent.AgentReport): Promise<void> {
|
||||
try {
|
||||
await this.deps.hub.post("/api/agent/v1/report", r);
|
||||
} catch (e) {
|
||||
log(`[report] ${r.jobId}: couldn't send (${(e as Error).message}); kept to send later.`);
|
||||
fs.mkdirSync(outboxDir(), { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(path.join(outboxDir(), `${r.jobId}.json`), JSON.stringify(r), { mode: 0o600 });
|
||||
}
|
||||
}
|
||||
|
||||
async flushOutbox(): Promise<void> {
|
||||
let files: string[];
|
||||
try { files = fs.readdirSync(outboxDir()).filter((f) => f.endsWith(".json")); } catch { return; }
|
||||
for (const f of files) {
|
||||
const file = path.join(outboxDir(), f);
|
||||
try {
|
||||
await this.deps.hub.post("/api/agent/v1/report", JSON.parse(fs.readFileSync(file, "utf8")));
|
||||
fs.rmSync(file, { force: true });
|
||||
} catch (e) {
|
||||
// A report the Hub refuses outright (4xx) would never go: drop it rather than retry forever.
|
||||
if (e instanceof HubRequestError && e.status >= 400 && e.status < 500) fs.rmSync(file, { force: true });
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One poll: fetch the jobs due and run them, one after the other. Returns the next delay (s). */
|
||||
async pollOnce(): Promise<number> {
|
||||
const { config } = this.deps;
|
||||
let reply: { jobs: unknown[]; pollSeconds: number };
|
||||
try {
|
||||
reply = agent.pollResponseSchema.parse(await this.deps.hub.post("/api/agent/v1/poll", {
|
||||
agentApiVersion: agent.AGENT_API_VERSION, agentVersion: AGENT_VERSION, mode: config.mode, runningJobId: null,
|
||||
}));
|
||||
} catch (e) {
|
||||
this.failures++;
|
||||
const delay = Math.min(300, config.pollSeconds * 2 ** Math.min(this.failures, 4));
|
||||
log(`[poll] ${(e as Error).message}; next try in ${delay}s.`);
|
||||
return delay;
|
||||
}
|
||||
this.failures = 0;
|
||||
if (!this.confirmed) {
|
||||
confirmUpdate();
|
||||
this.confirmed = true;
|
||||
}
|
||||
await this.flushOutbox();
|
||||
for (const raw of reply.jobs) {
|
||||
if (this.stopped) break;
|
||||
await this.handle(raw);
|
||||
}
|
||||
return reply.pollSeconds || config.pollSeconds;
|
||||
}
|
||||
|
||||
async handle(raw: unknown): Promise<void> {
|
||||
const { config } = this.deps;
|
||||
const verdict = checkJob(raw, config, this.seen, this.now());
|
||||
const at = this.now().toISOString();
|
||||
if (!verdict.ok) {
|
||||
log(`[job] ${verdict.id ?? "(no id)"} ${verdict.status}: ${verdict.message}`);
|
||||
if (verdict.id && verdict.type && !this.seen.has(verdict.id)) {
|
||||
this.seen.add(verdict.id);
|
||||
await this.send(report({ id: verdict.id, type: verdict.type }, config.serverId, { status: verdict.status, steps: [], result: {}, message: verdict.message, startedAt: at, finishedAt: at }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const job = verdict.job;
|
||||
// Seen before it runs, so a crash part-way can never run it twice.
|
||||
this.seen.add(job.id);
|
||||
log(`[job] ${job.id} ${job.type} ${JSON.stringify(job.args)}`);
|
||||
const result = await this.execute(job);
|
||||
log(`[job] ${job.id} ${result.status}${result.message ? `: ${result.message}` : ""}`);
|
||||
await this.send(report(job, config.serverId, result));
|
||||
if ((result as RunResult & { restart?: boolean }).restart) {
|
||||
log("[agent] Exiting so systemd starts the new version.");
|
||||
this.stopped = true;
|
||||
setTimeout(() => process.exit(0), 500);
|
||||
}
|
||||
}
|
||||
|
||||
private async execute(job: agent.AgentJob): Promise<RunResult & { restart?: boolean }> {
|
||||
const startedAt = this.now().toISOString();
|
||||
const limit = agent.JOB_TIME_LIMIT_MINUTES[job.type];
|
||||
try {
|
||||
switch (job.type) {
|
||||
case "update-agent": {
|
||||
const u = await updateAgent(job.args.version, AGENT_VERSION);
|
||||
return { status: u.status, steps: u.steps, result: u.result, message: u.message, log: [], startedAt, finishedAt: new Date().toISOString(), restart: u.restart };
|
||||
}
|
||||
case "check-ports": {
|
||||
const res = checkPorts(job.args.ports, readFrps(), await listeningNow());
|
||||
const ok = res.ports.every((p) => p.ok) && res.warnings.length === 0;
|
||||
return { status: ok ? "succeeded" : "failed", steps: [], result: res as unknown as Record<string, unknown>, message: res.warnings.join(" ") || undefined, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
case "export":
|
||||
return await this.runExport(job, limit);
|
||||
case "status":
|
||||
// The central server has no crosscode script (install.sh --central): its status is the
|
||||
// agent's own stats, with frps.
|
||||
if (this.deps.config.mode === "central") {
|
||||
const stats = await (this.deps.stats ?? (() => collectStats("central")))();
|
||||
const warning = stats.central && !stats.central.frpsRunning ? "frps isn't running." : undefined;
|
||||
return { status: "succeeded", steps: [], result: { stats } as unknown as Record<string, unknown>, message: warning, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
return await this.run(crosscodeArgs(job)!, job, limit);
|
||||
default: {
|
||||
const args = crosscodeArgs(job);
|
||||
if (!args) throw new Error(`No command for ${job.type}`);
|
||||
return await this.run(args, job, limit);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
return { status: "failed", steps: [], result: {}, message: (e as Error).message, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
}
|
||||
|
||||
private run(args: string[], job: agent.AgentJob, limit: number): Promise<RunResult> {
|
||||
if (this.deps.run) return this.deps.run(args, job);
|
||||
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit });
|
||||
}
|
||||
|
||||
/**
|
||||
* export: crosscode writes the ZIP, the agent encrypts it with a fresh key and uploads it. The
|
||||
* key goes to the Hub only in this job's report, so it can email the download link; the Hub
|
||||
* doesn't keep it (AGENT-1.0-PLAN §9).
|
||||
*/
|
||||
private async runExport(job: Extract<agent.AgentJob, { type: "export" }>, limit: number): Promise<RunResult> {
|
||||
const dir = path.join(paths.stateDir, "exports");
|
||||
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
const zip = path.join(dir, `${job.args.exportId}.zip`);
|
||||
fs.rmSync(zip, { force: true });
|
||||
try {
|
||||
const r = await this.run(crosscodeArgs(job, { exportFile: zip })!, job, limit);
|
||||
if (r.status !== "succeeded") return r;
|
||||
const { key, file } = encryptExport(fs.readFileSync(zip));
|
||||
await this.deps.hub.put(`/api/agent/v1/exports/${job.args.exportId}`, file, "application/octet-stream");
|
||||
return { ...r, result: { ...r.result, file: undefined, encryptedBytes: file.length, key } };
|
||||
} finally {
|
||||
fs.rmSync(zip, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async statsOnce(): Promise<void> {
|
||||
try {
|
||||
const stats = await (this.deps.stats ?? (() => collectStats(this.deps.config.mode)))();
|
||||
await this.deps.hub.post("/api/agent/v1/stats", stats);
|
||||
} catch (e) {
|
||||
log(`[stats] ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs until stopped: polls and stats on their own timers, never at the same time as a job. */
|
||||
async start(): Promise<void> {
|
||||
log(`[agent] ${AGENT_VERSION} (${this.deps.config.mode}) for ${this.deps.config.serverId}, Hub ${this.deps.config.hubUrl}`);
|
||||
let nextStats = 0;
|
||||
while (!this.stopped) {
|
||||
if (Date.now() >= nextStats) {
|
||||
await this.statsOnce();
|
||||
nextStats = Date.now() + this.deps.config.statsSeconds * 1000;
|
||||
}
|
||||
const delay = await this.pollOnce();
|
||||
await new Promise((r) => setTimeout(r, Math.max(5, Math.min(delay, this.deps.config.statsSeconds)) * 1000));
|
||||
}
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Where the agent keeps things on a server (docs/AGENT-1.0-PLAN.md §3). Each can be moved with an
|
||||
* environment variable, which the tests use.
|
||||
*/
|
||||
const env = (name: string, fallback: string): string => process.env[name] || fallback;
|
||||
|
||||
export const paths = {
|
||||
/** agent.json and the two private keys, root only (mode 600). */
|
||||
get configDir() { return env("CROSSCODE_AGENT_CONFIG_DIR", "/etc/crosscode"); },
|
||||
/** Seen job ids (replay protection) and exports waiting to upload. */
|
||||
get stateDir() { return env("CROSSCODE_AGENT_STATE_DIR", "/var/lib/crosscode-agent"); },
|
||||
/** A job's opened config, only while the job runs (tmpfs). */
|
||||
get runDir() { return env("CROSSCODE_AGENT_RUN_DIR", "/run/crosscode-agent"); },
|
||||
/** The crosscode script (a checkout of the monorepo in /opt/crosscode/tools). */
|
||||
get crosscode() { return env("CROSSCODE_BIN", "/usr/local/bin/crosscode"); },
|
||||
/** Agent releases: releases/<version>/ (checkouts), current → the running one, previous. */
|
||||
get agentRoot() { return env("CROSSCODE_AGENT_ROOT", "/opt/crosscode/agent"); },
|
||||
/** frps.ini on the central server. */
|
||||
get frpsIni() { return env("CROSSCODE_FRPS_INI", "/etc/frp/frps.ini"); },
|
||||
/** The churches on a church server. */
|
||||
get sites() { return env("CROSSCODE_SITES", "/var/www/sites"); },
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Log lines are filtered for anything that looks like a secret before they leave the server
|
||||
* (AGENT-1.0-PLAN §4, rule 7). The crosscode script never prints .env values, but tools it runs
|
||||
* (npm, Prisma, git) might print a URL with a password or a token in an error.
|
||||
*/
|
||||
|
||||
const RULES: [RegExp, string][] = [
|
||||
// user:password@ in any URL (postgresql://, https://).
|
||||
[/([a-z][a-z0-9+.-]*:\/\/[^\s:/@]+:)[^\s@/]+@/gi, "$1***@"],
|
||||
// KEY=value and KEY: value for keys that hold secrets.
|
||||
[/\b([A-Z0-9_]*(SECRET|PASSWORD|PASSWD|TOKEN|API_KEY|PRIVATE_KEY|DSN|LICENCE_KEY|LICENSE_KEY)[A-Z0-9_]*)(\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/g, "$1$3***"],
|
||||
// Authorization headers and bearer tokens.
|
||||
[/\b(authorization\s*:\s*)(bearer|basic)\s+\S+/gi, "$1$2 ***"],
|
||||
[/\bbearer\s+[A-Za-z0-9._~+/=-]{16,}/gi, "Bearer ***"],
|
||||
// PEM blocks.
|
||||
[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "[private key]"],
|
||||
// Cross Code licence keys (CEH-7K2M-…).
|
||||
[/\b(CEH|CCA|CCW|CCP)-[A-Z0-9]{4}(-[A-Z0-9]{4}){3}\b/g, "$1-****"],
|
||||
// Long random-looking strings (hex or base64 of 32+ characters): likely keys or tokens.
|
||||
[/\b[A-Fa-f0-9]{40,}\b/g, "***"],
|
||||
[/\b[A-Za-z0-9+/_-]{48,}={0,2}/g, "***"],
|
||||
];
|
||||
|
||||
export function redact(line: string): string {
|
||||
let out = line;
|
||||
for (const [re, to] of RULES) out = out.replace(re, to);
|
||||
return out.length > 1000 ? `${out.slice(0, 997)}...` : out;
|
||||
}
|
||||
|
||||
/** Keeps the last `max` lines of output, redacted, without holding all of it in memory. */
|
||||
export class LogTail {
|
||||
private lines: string[] = [];
|
||||
private partial = "";
|
||||
constructor(private max = 200) {}
|
||||
push(chunk: string): void {
|
||||
const parts = (this.partial + chunk).split(/\r?\n/);
|
||||
this.partial = parts.pop() ?? "";
|
||||
for (const p of parts) this.add(p);
|
||||
}
|
||||
private add(line: string): void {
|
||||
this.lines.push(redact(line));
|
||||
if (this.lines.length > this.max) this.lines.shift();
|
||||
}
|
||||
end(): string[] {
|
||||
if (this.partial) {
|
||||
this.add(this.partial);
|
||||
this.partial = "";
|
||||
}
|
||||
return [...this.lines];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { openConfig } from "@crosscode/contracts/signing";
|
||||
import { paths } from "./paths";
|
||||
import { LogTail, redact } from "./redact";
|
||||
|
||||
/**
|
||||
* Runs `crosscode … --json` for a job: argument array (no shell), the job's config opened to a
|
||||
* file only root can read and removed as soon as the job ends, a time limit per type (the whole
|
||||
* process group is stopped past it), and the last 200 log lines, redacted.
|
||||
*/
|
||||
|
||||
export interface RunResult {
|
||||
status: agent.JobStatus;
|
||||
steps: agent.ReportStep[];
|
||||
result: Record<string, unknown>;
|
||||
message?: string;
|
||||
log: string[];
|
||||
startedAt: string;
|
||||
finishedAt: string;
|
||||
}
|
||||
|
||||
export interface RunOptions {
|
||||
args: string[];
|
||||
sealedConfig?: agent.Sealed | null;
|
||||
x25519Pem: string;
|
||||
timeLimitMinutes: number;
|
||||
/** For tests. */
|
||||
bin?: string;
|
||||
}
|
||||
|
||||
const iso = (d = new Date()) => d.toISOString();
|
||||
|
||||
function writeConfig(sealed: agent.Sealed, x25519Pem: string): string {
|
||||
const opened = agent.jobConfigSchema.parse(openConfig(sealed, x25519Pem));
|
||||
fs.mkdirSync(paths.runDir, { recursive: true, mode: 0o700 });
|
||||
const file = path.join(paths.runDir, `config-${process.pid}-${Date.now()}.json`);
|
||||
fs.writeFileSync(file, JSON.stringify(opened), { mode: 0o600 });
|
||||
return file;
|
||||
}
|
||||
|
||||
export async function runCrosscode(opts: RunOptions): Promise<RunResult> {
|
||||
const startedAt = iso();
|
||||
let configFile: string | null = null;
|
||||
try {
|
||||
if (opts.sealedConfig) {
|
||||
try {
|
||||
configFile = writeConfig(opts.sealedConfig, opts.x25519Pem);
|
||||
} catch (e) {
|
||||
return { status: "refused", steps: [], result: {}, message: `The job's config couldn't be opened with this server's key: ${(e as Error).message}`, log: [], startedAt, finishedAt: iso() };
|
||||
}
|
||||
}
|
||||
const args = [...opts.args, "--json", ...(configFile ? ["--config", configFile] : [])];
|
||||
return await new Promise<RunResult>((resolve) => {
|
||||
const tail = new LogTail(200);
|
||||
let stdout = "";
|
||||
const child = spawn(opts.bin ?? paths.crosscode, args, {
|
||||
detached: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: { ...process.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
|
||||
});
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
try { process.kill(-child.pid!, "SIGTERM"); } catch { /* already gone */ }
|
||||
setTimeout(() => { try { process.kill(-child.pid!, "SIGKILL"); } catch { /* gone */ } }, 10_000).unref();
|
||||
}, opts.timeLimitMinutes * 60_000);
|
||||
child.stdout.setEncoding("utf8").on("data", (d: string) => { stdout += d; if (stdout.length > 5_000_000) stdout = stdout.slice(-1_000_000); });
|
||||
child.stderr.setEncoding("utf8").on("data", (d: string) => tail.push(d));
|
||||
child.on("error", (e) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ status: "failed", steps: [], result: {}, message: `crosscode couldn't be started: ${e.message}`, log: tail.end(), startedAt, finishedAt: iso() });
|
||||
});
|
||||
child.on("close", (code) => {
|
||||
clearTimeout(timer);
|
||||
const log = tail.end();
|
||||
const report = parseReport(stdout);
|
||||
if (timedOut) {
|
||||
resolve({ status: "failed", steps: report?.steps ?? [], result: report?.result ?? {}, message: `Stopped after the time limit (${opts.timeLimitMinutes} minutes).`, log, startedAt, finishedAt: iso() });
|
||||
return;
|
||||
}
|
||||
if (!report) {
|
||||
resolve({ status: code === 0 ? "succeeded" : "failed", steps: [], result: {}, message: code === 0 ? undefined : `crosscode ended with code ${code} without a report.`, log, startedAt, finishedAt: iso() });
|
||||
return;
|
||||
}
|
||||
resolve({
|
||||
status: report.status,
|
||||
steps: report.steps,
|
||||
result: report.result,
|
||||
message: report.message ? redact(report.message) : undefined,
|
||||
log,
|
||||
startedAt: report.startedAt,
|
||||
finishedAt: report.finishedAt,
|
||||
});
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
if (configFile) fs.rmSync(configFile, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** The last line of stdout that's a valid script report. */
|
||||
export function parseReport(stdout: string): agent.ScriptReport | null {
|
||||
const lines = stdout.trim().split("\n").reverse();
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const parsed = agent.scriptReportSchema.safeParse(JSON.parse(line));
|
||||
if (parsed.success) return parsed.data;
|
||||
} catch {
|
||||
// not JSON
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { execFile, execFileSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { agent } from "@crosscode/contracts";
|
||||
import { readFrps } from "./central";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
* The server's stats every 60 s (AGENT-1.0-PLAN §10, crosscode.agent-stats/1): RAM, CPU, disks,
|
||||
* uptime, versions, frpc, and each PM2 process with its church and product. Read from /proc and
|
||||
* the tools that are there; anything missing is null rather than an error.
|
||||
*/
|
||||
|
||||
export const AGENT_VERSION = "1.0.1";
|
||||
|
||||
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
execFile(cmd, args, { timeout: timeoutMs, maxBuffer: 10_000_000 }, (err, stdout) => resolve(err ? null : String(stdout)));
|
||||
});
|
||||
}
|
||||
|
||||
export function parseMeminfo(text: string): agent.AgentStats["ram"] {
|
||||
const kb = (key: string) => Number(new RegExp(`^${key}:\\s+(\\d+)`, "m").exec(text)?.[1] ?? 0) * 1024;
|
||||
const total = kb("MemTotal");
|
||||
const available = kb("MemAvailable");
|
||||
return { totalBytes: total, usedBytes: Math.max(0, total - available), availableBytes: available, swapTotalBytes: kb("SwapTotal"), swapUsedBytes: Math.max(0, kb("SwapTotal") - kb("SwapFree")) };
|
||||
}
|
||||
|
||||
/** CPU busy % between two /proc/stat readings. */
|
||||
export function cpuPercent(a: string, b: string): number {
|
||||
const parse = (t: string) => {
|
||||
const f = (/^cpu\s+(.+)$/m.exec(t)?.[1] ?? "").trim().split(/\s+/).map(Number);
|
||||
const idle = (f[3] ?? 0) + (f[4] ?? 0);
|
||||
return { idle, total: f.reduce((s, n) => s + (Number.isFinite(n) ? n : 0), 0) };
|
||||
};
|
||||
const x = parse(a), y = parse(b);
|
||||
const total = y.total - x.total;
|
||||
if (total <= 0) return 0;
|
||||
return Math.min(100, Math.max(0, Math.round(((total - (y.idle - x.idle)) / total) * 1000) / 10));
|
||||
}
|
||||
|
||||
async function disks(): Promise<agent.AgentStats["disks"]> {
|
||||
const out = await run("df", ["-P", "-B1", "-x", "tmpfs", "-x", "devtmpfs", "-x", "squashfs", "-x", "overlay"]);
|
||||
if (!out) return [];
|
||||
return out.trim().split("\n").slice(1).map((l) => l.trim().split(/\s+/)).filter((c) => c.length >= 6 && c[5]!.startsWith("/"))
|
||||
.slice(0, 30).map((c) => ({ mount: c[5]!, totalBytes: Number(c[1]), usedBytes: Number(c[2]), freeBytes: Number(c[3]) }));
|
||||
}
|
||||
|
||||
function osName(): string {
|
||||
try {
|
||||
const t = fs.readFileSync("/etc/os-release", "utf8");
|
||||
return /^PRETTY_NAME="?([^"\n]+)"?/m.exec(t)?.[1] ?? `${os.type()} ${os.release()}`;
|
||||
} catch {
|
||||
return `${os.type()} ${os.release()}`;
|
||||
}
|
||||
}
|
||||
|
||||
const versionIn = (text: string | null) => (text ? /(\d+\.\d+(\.\d+)?)/.exec(text)?.[1] ?? null : null);
|
||||
|
||||
/** church.env → { app user → [{ church, product, names }] }, read as data like the script does. */
|
||||
export function churchProcesses(sitesDir = paths.sites): Map<string, { church: string; product: agent.AgentStats["processes"][number]["product"]; names: string[] }[]> {
|
||||
const byUser = new Map<string, { church: string; product: "events" | "accounts" | "website" | "app"; names: string[] }[]>();
|
||||
let entries: string[];
|
||||
try { entries = fs.readdirSync(sitesDir); } catch { return byUser; }
|
||||
for (const church of entries) {
|
||||
if (!/^[a-z][a-z0-9-]{0,39}$/.test(church)) continue;
|
||||
let text: string;
|
||||
try { text = fs.readFileSync(path.join(sitesDir, church, "church.env"), "utf8"); } catch { continue; }
|
||||
const vars = new Map<string, string>();
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const m = /^([A-Z][A-Z0-9_]*)=("([^"]*)"|'([^']*)'|([^#\s]*))/.exec(line);
|
||||
if (m) vars.set(m[1]!, m[3] ?? m[4] ?? m[5] ?? "");
|
||||
}
|
||||
for (const product of ["accounts", "events", "website", "app"] as const) {
|
||||
const p = product.toUpperCase();
|
||||
const user = vars.get(`${p}_USER`);
|
||||
const names = (vars.get(`${p}_PM2`) ?? "").split(/\s+/).filter(Boolean);
|
||||
if (!user || !names.length || !/^[a-z_][a-z0-9_-]{0,31}$/.test(user)) continue;
|
||||
const list = byUser.get(user) ?? [];
|
||||
list.push({ church, product, names });
|
||||
byUser.set(user, list);
|
||||
}
|
||||
}
|
||||
return byUser;
|
||||
}
|
||||
|
||||
interface Pm2Proc { name?: string; monit?: { memory?: number; cpu?: number }; pm2_env?: { status?: string; restart_time?: number; pm_uptime?: number } }
|
||||
|
||||
function pm2Running(user: string): boolean {
|
||||
try {
|
||||
const home = execFileSync("getent", ["passwd", user], { encoding: "utf8" }).split(":")[5];
|
||||
const pid = Number(fs.readFileSync(`${home}/.pm2/pm2.pid`, "utf8").trim());
|
||||
if (!pid) return false;
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function pm2Processes(): Promise<agent.AgentStats["processes"]> {
|
||||
const out: agent.AgentStats["processes"] = [];
|
||||
for (const [user, installs] of churchProcesses()) {
|
||||
// Only ask a daemon that's running: `pm2 jlist` would otherwise start an empty one inside this
|
||||
// agent's service, which dies with the agent (found in the VM test).
|
||||
if (!pm2Running(user)) continue;
|
||||
const json = await run("sudo", ["-n", "-u", user, "-H", "--", "pm2", "jlist"]);
|
||||
let list: Pm2Proc[];
|
||||
try { list = JSON.parse(json ?? "[]") as Pm2Proc[]; } catch { list = []; }
|
||||
for (const p of list) {
|
||||
const owner = installs.find((i) => i.names.includes(p.name ?? ""));
|
||||
out.push({
|
||||
name: String(p.name ?? "?").slice(0, 100),
|
||||
church: owner?.church ?? null,
|
||||
product: owner?.product ?? null,
|
||||
status: String(p.pm2_env?.status ?? "unknown").slice(0, 40),
|
||||
memoryBytes: Number(p.monit?.memory ?? 0),
|
||||
cpuPercent: Number(p.monit?.cpu ?? 0),
|
||||
restarts: Math.max(0, Math.trunc(Number(p.pm2_env?.restart_time ?? 0))),
|
||||
uptimeSeconds: p.pm2_env?.pm_uptime ? Math.max(0, (Date.now() - p.pm2_env.pm_uptime) / 1000) : 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
return out.slice(0, 200);
|
||||
}
|
||||
|
||||
/** A systemd unit is active; null when there's no systemctl. (is-active exits non-zero when inactive.) */
|
||||
function active(unit: string): Promise<boolean | null> {
|
||||
return new Promise((resolve) => {
|
||||
execFile("systemctl", ["is-active", unit], { timeout: 10_000 }, (err, stdout) => {
|
||||
if (err && (err as NodeJS.ErrnoException).code === "ENOENT") resolve(null);
|
||||
else resolve(String(stdout).trim() === "active");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function collectStats(mode: agent.AgentMode): Promise<agent.AgentStats> {
|
||||
const read = (f: string) => { try { return fs.readFileSync(f, "utf8"); } catch { return ""; } };
|
||||
const stat1 = read("/proc/stat");
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
const stat2 = read("/proc/stat");
|
||||
const [load1, load5, load15] = os.loadavg();
|
||||
const [diskList, postgres, frpc, processes, frpcRunning] = await Promise.all([
|
||||
disks(),
|
||||
run("psql", ["--version"]),
|
||||
run("frpc", ["-v"]),
|
||||
mode === "church" ? pm2Processes() : Promise.resolve([]),
|
||||
mode === "church" ? active("frpc") : Promise.resolve(null),
|
||||
]);
|
||||
const stats: agent.AgentStats = {
|
||||
schema: "crosscode.agent-stats/1",
|
||||
at: new Date().toISOString(),
|
||||
ram: parseMeminfo(read("/proc/meminfo")),
|
||||
cpu: { percent: cpuPercent(stat1, stat2), load1: load1 ?? 0, load5: load5 ?? 0, load15: load15 ?? 0, cores: Math.max(1, os.cpus().length) },
|
||||
disks: diskList,
|
||||
uptimeSeconds: os.uptime(),
|
||||
versions: { os: osName().slice(0, 200), node: process.versions.node, postgres: versionIn(postgres), frpc: versionIn(frpc), agent: AGENT_VERSION },
|
||||
frpcRunning,
|
||||
processes,
|
||||
};
|
||||
if (mode === "central") {
|
||||
const frps = readFrps();
|
||||
stats.central = { proxyBindAddr: frps?.proxyBindAddr ?? null, allowPorts: frps?.allowPorts ?? null, frpsRunning: await active("frps") };
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import type { agent } from "@crosscode/contracts";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
* update-agent (AGENT-1.0-PLAN §3): the newest agent@x.y.z is checked out and built next to the
|
||||
* running copy, `current` is switched to it and the agent exits, so systemd starts the new one.
|
||||
* A one-shot systemd timer switches back to `previous` unless the new agent clears
|
||||
* update-pending.json by polling the Hub within 150 seconds.
|
||||
*
|
||||
* /opt/crosscode/agent/releases/<version>/ checkouts of the monorepo at agent@<version>
|
||||
* /opt/crosscode/agent/current, previous symlinks to releases
|
||||
* /opt/crosscode/agent/revert.sh written by the install script
|
||||
*/
|
||||
|
||||
const REPO = process.env.CROSSCODE_REPO || "https://c-git.crosscode.co.za/joshua/crosscode-platform.git";
|
||||
const CONFIRM_SECONDS = 150;
|
||||
|
||||
const pendingFile = () => path.join(paths.stateDir, "update-pending.json");
|
||||
|
||||
function exec(cmd: string, args: string[], cwd?: string, timeoutMs = 15 * 60_000): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(cmd, args, { cwd, timeout: timeoutMs, maxBuffer: 20_000_000, env: { ...process.env, NODE_ENV: "development" } }, (err, stdout, stderr) => {
|
||||
if (err) reject(new Error(`${cmd} ${args.join(" ")}: ${String(stderr).trim().split("\n").slice(-3).join(" ") || err.message}`));
|
||||
else resolve(String(stdout));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export interface UpdateOutcome {
|
||||
status: agent.JobStatus;
|
||||
message: string;
|
||||
steps: agent.ReportStep[];
|
||||
result: Record<string, unknown>;
|
||||
/** Exit after reporting, so systemd starts the new version. */
|
||||
restart: boolean;
|
||||
}
|
||||
|
||||
export async function updateAgent(tag: string, currentVersion: string): Promise<UpdateOutcome> {
|
||||
const version = tag.replace(/^agent@/, "");
|
||||
const steps: agent.ReportStep[] = [];
|
||||
const step = async (name: string, fn: () => Promise<void>) => {
|
||||
const s: agent.ReportStep = { name, startedAt: new Date().toISOString(), finishedAt: null, outcome: "ok" };
|
||||
steps.push(s);
|
||||
try {
|
||||
await fn();
|
||||
} catch (e) {
|
||||
s.outcome = "failed";
|
||||
s.detail = (e as Error).message.slice(0, 2000);
|
||||
throw e;
|
||||
} finally {
|
||||
s.finishedAt = new Date().toISOString();
|
||||
}
|
||||
};
|
||||
if (version === currentVersion) return { status: "succeeded", message: `Already on ${tag}.`, steps, result: { version }, restart: false };
|
||||
|
||||
const root = paths.agentRoot;
|
||||
const dir = path.join(root, "releases", version);
|
||||
try {
|
||||
await step(`Checking out ${tag}`, async () => {
|
||||
if (!fs.existsSync(path.join(dir, ".git"))) {
|
||||
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
||||
await exec("git", ["clone", "--quiet", "--depth", "1", "--branch", tag, REPO, dir]);
|
||||
}
|
||||
});
|
||||
await step("Installing and building", async () => {
|
||||
await exec("npm", ["ci", "--no-audit", "--no-fund", "--include=dev", "--include-workspace-root", "-w", "packages/contracts", "-w", "apps/agent"], dir);
|
||||
await exec("npm", ["run", "build", "-w", "packages/contracts"], dir);
|
||||
await exec("npm", ["run", "build", "-w", "apps/agent"], dir);
|
||||
});
|
||||
await step("Checking the new build", async () => {
|
||||
const out = await exec(process.execPath, [path.join(dir, "apps/agent/dist/cli.js"), "version"], dir, 30_000);
|
||||
if (out.trim() !== version) throw new Error(`The new build says it's ${out.trim()}, not ${version}.`);
|
||||
});
|
||||
await step("Switching over", async () => {
|
||||
const current = path.join(root, "current");
|
||||
const previous = path.join(root, "previous");
|
||||
const old = fs.readlinkSync(current);
|
||||
fs.writeFileSync(pendingFile(), JSON.stringify({ from: currentVersion, to: version, at: new Date().toISOString() }), { mode: 0o600 });
|
||||
replaceLink(previous, old);
|
||||
replaceLink(current, dir);
|
||||
// If the new agent doesn't poll within CONFIRM_SECONDS, revert.sh puts `previous` back.
|
||||
await exec("systemd-run", [`--on-active=${CONFIRM_SECONDS}`, `--unit=crosscode-agent-revert-${Date.now()}`, path.join(root, "revert.sh")]);
|
||||
});
|
||||
} catch (e) {
|
||||
return { status: "failed", message: `The agent wasn't updated: ${(e as Error).message}`, steps, result: { from: currentVersion, to: version }, restart: false };
|
||||
}
|
||||
return { status: "succeeded", message: `Switching to ${tag}; it confirms by polling within ${CONFIRM_SECONDS} seconds.`, steps, result: { from: currentVersion, to: version }, restart: true };
|
||||
}
|
||||
|
||||
function replaceLink(link: string, target: string): void {
|
||||
const tmp = `${link}.tmp-${process.pid}`;
|
||||
fs.rmSync(tmp, { force: true });
|
||||
fs.symlinkSync(target, tmp);
|
||||
fs.renameSync(tmp, link);
|
||||
}
|
||||
|
||||
/** Called after the first successful poll: this version works, so it stays. */
|
||||
export function confirmUpdate(): void {
|
||||
fs.rmSync(pendingFile(), { force: true });
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { verifyJob } from "@crosscode/contracts/signing";
|
||||
import type { AgentConfig } from "./config";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
* Whether to run a job (AGENT-1.0-PLAN §4). Checked in this order, and a job is refused at the
|
||||
* first check it fails:
|
||||
* 1. it's an object with an id and type the agent can report on,
|
||||
* 2. the signature verifies with the Hub key pinned when the server joined,
|
||||
* 3. it's for this server,
|
||||
* 4. it's within notBefore … expiresAt (an expired job is reported as `expired`, never run late),
|
||||
* 5. its id hasn't been seen in the last 90 days (replays),
|
||||
* 6. its type is one this agent runs (a central agent only runs check-ports, status, update-agent),
|
||||
* 7. every argument passes that type's schema (unknown arguments refused).
|
||||
*/
|
||||
|
||||
export type Verdict =
|
||||
| { ok: true; job: agent.AgentJob }
|
||||
| { ok: false; status: "refused" | "expired"; message: string; id: string | null; type: agent.JobType | null };
|
||||
|
||||
const SEEN_DAYS = 90;
|
||||
|
||||
/** Job ids already run or refused, with when (replay protection). */
|
||||
export class SeenJobs {
|
||||
private seen = new Map<string, number>();
|
||||
constructor(private file = path.join(paths.stateDir, "seen-jobs.json")) {
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(this.file, "utf8")) as Record<string, number>;
|
||||
for (const [id, at] of Object.entries(data)) this.seen.set(id, at);
|
||||
} catch {
|
||||
// First run, or an unreadable file: start empty (signatures and expiry still apply).
|
||||
}
|
||||
}
|
||||
has(id: string): boolean {
|
||||
return this.seen.has(id);
|
||||
}
|
||||
add(id: string, now = Date.now()): void {
|
||||
this.seen.set(id, now);
|
||||
const cutoff = now - SEEN_DAYS * 86_400_000;
|
||||
for (const [k, at] of this.seen) if (at < cutoff) this.seen.delete(k);
|
||||
fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
|
||||
const tmp = `${this.file}.tmp-${process.pid}`;
|
||||
fs.writeFileSync(tmp, JSON.stringify(Object.fromEntries(this.seen)), { mode: 0o600 });
|
||||
fs.renameSync(tmp, this.file);
|
||||
}
|
||||
}
|
||||
|
||||
const typeOf = (v: unknown): agent.JobType | null => (agent.jobTypeSchema.safeParse(v).success ? (v as agent.JobType) : null);
|
||||
|
||||
export function checkJob(raw: unknown, config: AgentConfig, seen: SeenJobs, now = new Date()): Verdict {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, status: "refused", message: "Not a job.", id: null, type: null };
|
||||
const j = raw as Record<string, unknown>;
|
||||
const id = typeof j.id === "string" && /^job_[A-Za-z0-9_-]{8,64}$/.test(j.id) ? j.id : null;
|
||||
const type = typeOf(j.type);
|
||||
const refuse = (message: string): Verdict => ({ ok: false, status: "refused", message, id, type });
|
||||
|
||||
if (!id) return refuse("The job has no valid id.");
|
||||
if (!verifyJob(j, config.hubJobKey)) return refuse("The signature doesn't match the Hub's key.");
|
||||
if (j.serverId !== config.serverId) return refuse(`The job is for ${String(j.serverId)}, not this server.`);
|
||||
const notBefore = Date.parse(String(j.notBefore));
|
||||
const expiresAt = Date.parse(String(j.expiresAt));
|
||||
if (!Number.isFinite(notBefore) || !Number.isFinite(expiresAt) || expiresAt <= notBefore) return refuse("The job's times aren't valid.");
|
||||
if (now.getTime() > expiresAt) return { ok: false, status: "expired", message: `The job expired at ${new Date(expiresAt).toISOString()}; it wasn't run.`, id, type };
|
||||
// A minute's leeway for clocks that differ a little.
|
||||
if (now.getTime() < notBefore - 60_000) return refuse(`The job isn't due until ${new Date(notBefore).toISOString()}.`);
|
||||
if (seen.has(id)) return refuse("This job was already received (a replay).");
|
||||
if (!type) return refuse(`Unknown job type ${JSON.stringify(j.type)}.`);
|
||||
if (config.mode === "central" && !agent.CENTRAL_JOB_TYPES.includes(type)) return refuse(`A central agent doesn't run ${type} jobs.`);
|
||||
const parsed = agent.agentJobSchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0];
|
||||
return refuse(`The job's ${issue?.path.join(".") || "content"} isn't valid: ${issue?.message ?? "unknown problem"}.`);
|
||||
}
|
||||
return { ok: true, job: parsed.data };
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { crosscodeArgs } from "../src/command";
|
||||
import { job } from "./helpers";
|
||||
|
||||
const parsed = (over: Record<string, unknown>) => agent.agentJobSchema.parse(job(over));
|
||||
|
||||
describe("crosscode arguments for each job", () => {
|
||||
it("install: behind frp with the Hub's ports and the release", () => {
|
||||
expect(crosscodeArgs(parsed({
|
||||
type: "install",
|
||||
args: { church: "hope", products: ["events"], versions: { events: "events@2.4.1" }, domains: { events: "events.hope.co.za" }, ports: { events: { web: 20010, api: 20011 } } },
|
||||
}))).toEqual(["install", "hope", "--products", "events", "--domain", "hope.co.za", "--events-domain", "events.hope.co.za", "--api-port", "20011", "--web-port", "20010", "--frp", "--version", "events@2.4.1"]);
|
||||
});
|
||||
|
||||
it("deploy, adopt, restart, uninstall, purge, status", () => {
|
||||
expect(crosscodeArgs(parsed({}))).toEqual(["deploy", "hope", "events", "--version", "events@2.4.1"]);
|
||||
expect(crosscodeArgs(parsed({ args: { church: "hope", products: ["events"], check: true } }))).toEqual(["deploy", "hope", "events", "--check"]);
|
||||
expect(crosscodeArgs(parsed({ type: "adopt", args: { church: "hope", eventsDir: "/var/www/hope-events", version: "events@2.2.0" } })))
|
||||
.toEqual(["adopt", "hope", "--events-dir", "/var/www/hope-events", "--version", "events@2.2.0"]);
|
||||
expect(crosscodeArgs(parsed({ type: "adopt-undo", args: { church: "hope" } }))).toEqual(["adopt", "hope", "--undo"]);
|
||||
expect(crosscodeArgs(parsed({ type: "restart", args: { church: "hope" } }))).toEqual(["restart", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope" } }))).toEqual(["uninstall", "hope", "--confirm", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope" } }))).toEqual(["purge", "hope", "--confirm", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "status", args: {} }))).toEqual(["status", "--no-fetch"]);
|
||||
});
|
||||
|
||||
it("export writes to the file the agent gives", () => {
|
||||
const j = parsed({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh" } });
|
||||
expect(crosscodeArgs(j, { exportFile: "/var/lib/crosscode-agent/exports/exp_abcdefgh.zip" })).toEqual(["export", "hope", "--out", "/var/lib/crosscode-agent/exports/exp_abcdefgh.zip"]);
|
||||
});
|
||||
|
||||
it("the agent's own jobs run no crosscode command", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "check-ports", args: { ports: [20010] } }))).toBeNull();
|
||||
expect(crosscodeArgs(parsed({ type: "update-agent", args: { version: "agent@1.0.1" } }))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { generateEd25519, generateX25519, signJob } from "@crosscode/contracts/signing";
|
||||
import type { AgentConfig } from "../src/config";
|
||||
|
||||
export const hubKeys = generateEd25519();
|
||||
export const serverKeys = { ed25519: generateEd25519(), x25519: generateX25519() };
|
||||
|
||||
export const config: AgentConfig = {
|
||||
hubUrl: "https://hub.test",
|
||||
serverId: "srv_test00001",
|
||||
mode: "church",
|
||||
hubJobKey: hubKeys.publicKey,
|
||||
pollSeconds: 30,
|
||||
statsSeconds: 60,
|
||||
joinedAt: "2026-11-20T00:00:00.000Z",
|
||||
};
|
||||
|
||||
export const NOW = new Date("2026-11-20T12:05:00.000Z");
|
||||
|
||||
let n = 0;
|
||||
export function job(over: Record<string, unknown> = {}, key = hubKeys.privateKeyPem) {
|
||||
n++;
|
||||
return signJob({
|
||||
schema: "crosscode.agent-job/1",
|
||||
id: `job_test${String(n).padStart(6, "0")}`,
|
||||
serverId: config.serverId,
|
||||
type: "deploy",
|
||||
args: { church: "hope", products: ["events"], versions: ["events@2.4.1"] },
|
||||
config: null,
|
||||
notBefore: "2026-11-20T12:00:00.000Z",
|
||||
expiresAt: "2026-11-20T12:15:00.000Z",
|
||||
...over,
|
||||
}, key);
|
||||
}
|
||||
|
||||
/** A temporary state folder per test file. */
|
||||
export function tempState(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agent-test-"));
|
||||
process.env.CROSSCODE_AGENT_STATE_DIR = dir;
|
||||
process.env.CROSSCODE_AGENT_RUN_DIR = path.join(dir, "run");
|
||||
return dir;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { decryptExport } from "@crosscode/contracts/signing";
|
||||
import { HubRequestError, type HubClient } from "../src/hub";
|
||||
import { Agent } from "../src/loop";
|
||||
import type { RunResult } from "../src/runner";
|
||||
import { SeenJobs } from "../src/verify";
|
||||
import { config, job, NOW, serverKeys, tempState } from "./helpers";
|
||||
|
||||
const state = tempState();
|
||||
|
||||
function fakeHub(jobs: unknown[]) {
|
||||
const posts: { path: string; body: unknown }[] = [];
|
||||
const puts: { path: string; body: Uint8Array }[] = [];
|
||||
let down = false;
|
||||
const hub: HubClient = {
|
||||
async post(p, body) {
|
||||
if (down) throw new HubRequestError("down", 0, "HUB_UNREACHABLE");
|
||||
posts.push({ path: p, body });
|
||||
if (p === "/api/agent/v1/poll") return { jobs: jobs.splice(0), pollSeconds: 30 };
|
||||
return null;
|
||||
},
|
||||
async put(p, body) {
|
||||
puts.push({ path: p, body });
|
||||
return null;
|
||||
},
|
||||
};
|
||||
return { hub, posts, puts, setDown: (v: boolean) => { down = v; } };
|
||||
}
|
||||
|
||||
const ok = (over: Partial<RunResult> = {}): RunResult => ({ status: "succeeded", steps: [{ name: "x", startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), outcome: "ok" }], result: {}, log: ["==> done"], startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), ...over });
|
||||
|
||||
type Run = (args: string[], job: agent.AgentJob) => Promise<RunResult>;
|
||||
|
||||
function make(jobs: unknown[], run: jest.Mock<ReturnType<Run>, Parameters<Run>> = jest.fn<ReturnType<Run>, Parameters<Run>>(async () => ok())) {
|
||||
const h = fakeHub(jobs);
|
||||
const a = new Agent({ config, keys: { ed25519Pem: serverKeys.ed25519.privateKeyPem, x25519Pem: serverKeys.x25519.privateKeyPem }, hub: h.hub, seen: new SeenJobs(path.join(state, `seen-${Math.random()}.json`)), run, now: () => NOW });
|
||||
return { a, run, ...h };
|
||||
}
|
||||
|
||||
const reports = (posts: { path: string; body: unknown }[]) => posts.filter((p) => p.path === "/api/agent/v1/report").map((p) => p.body as agent.AgentReport);
|
||||
|
||||
describe("the agent loop", () => {
|
||||
it("runs a valid job once and reports it", async () => {
|
||||
const j = job();
|
||||
const { a, run, posts } = make([j, j]);
|
||||
await a.pollOnce();
|
||||
expect(run).toHaveBeenCalledTimes(1);
|
||||
expect(run.mock.calls[0]).toEqual([["deploy", "hope", "events", "--version", "events@2.4.1"], expect.objectContaining({ id: j.id })]);
|
||||
// The second copy is a replay: refused quietly (the first one's report already went).
|
||||
const rs = reports(posts);
|
||||
expect(rs.map((r) => [r.jobId, r.status])).toEqual([[j.id, "succeeded"]]);
|
||||
expect(agent.agentReportSchema.safeParse(rs[0]).success).toBe(true);
|
||||
});
|
||||
|
||||
it("reports refused and expired jobs without running them", async () => {
|
||||
const forged = { ...job(), signature: "A".repeat(86) };
|
||||
const late = job({ expiresAt: "2026-11-20T12:01:00.000Z", notBefore: "2026-11-20T11:00:00.000Z" });
|
||||
const { a, run, posts } = make([forged, late]);
|
||||
await a.pollOnce();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
expect(reports(posts).map((r) => r.status)).toEqual(["refused", "expired"]);
|
||||
});
|
||||
|
||||
it("keeps a report it can't send and sends it on the next poll", async () => {
|
||||
const j = job();
|
||||
let setDownLater: (v: boolean) => void = () => {};
|
||||
const { a, posts, setDown } = make([j], jest.fn<ReturnType<Run>, Parameters<Run>>(async () => { setDownLater(true); return ok(); }));
|
||||
setDownLater = setDown;
|
||||
await a.pollOnce();
|
||||
expect(reports(posts)).toEqual([]);
|
||||
expect(fs.readdirSync(path.join(state, "outbox"))).toContain(`${j.id}.json`);
|
||||
setDown(false);
|
||||
await a.pollOnce();
|
||||
expect(reports(posts).map((r) => r.jobId)).toEqual([j.id]);
|
||||
expect(fs.readdirSync(path.join(state, "outbox"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("backs off while the Hub is unreachable", async () => {
|
||||
const { a, setDown } = make([]);
|
||||
setDown(true);
|
||||
expect(await a.pollOnce()).toBe(60);
|
||||
expect(await a.pollOnce()).toBe(120);
|
||||
setDown(false);
|
||||
expect(await a.pollOnce()).toBe(30);
|
||||
});
|
||||
|
||||
it("export: encrypts the ZIP, uploads it, and only the report carries the key", async () => {
|
||||
const j = job({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh" } });
|
||||
const run = jest.fn<ReturnType<Run>, Parameters<Run>>(async (args: string[]) => {
|
||||
fs.writeFileSync(args[3]!, "PK zip bytes");
|
||||
return ok({ result: { file: args[3], bytes: 12 } });
|
||||
});
|
||||
const { a, puts, posts } = make([j], run);
|
||||
await a.pollOnce();
|
||||
expect(puts).toHaveLength(1);
|
||||
expect(puts[0]!.path).toBe("/api/agent/v1/exports/exp_abcdefgh");
|
||||
const r = reports(posts)[0]!;
|
||||
expect(r.status).toBe("succeeded");
|
||||
const key = r.result.key as string;
|
||||
expect(decryptExport(puts[0]!.body, key).toString()).toBe("PK zip bytes");
|
||||
expect(Buffer.from(puts[0]!.body).includes(Buffer.from("PK zip"))).toBe(false);
|
||||
expect(fs.readdirSync(path.join(state, "exports"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("status on the central server: its own stats, without crosscode (which isn't installed there)", async () => {
|
||||
const h = fakeHub([job({ type: "status", args: {} })]);
|
||||
const run = jest.fn<ReturnType<Run>, Parameters<Run>>(async () => ok());
|
||||
const stats = { schema: "crosscode.agent-stats/1", central: { proxyBindAddr: "127.0.0.1", allowPorts: null, frpsRunning: true } } as unknown as agent.AgentStats;
|
||||
const a = new Agent({ config: { ...config, mode: "central" }, keys: { ed25519Pem: serverKeys.ed25519.privateKeyPem, x25519Pem: serverKeys.x25519.privateKeyPem }, hub: h.hub, seen: new SeenJobs(path.join(state, `seen-${Math.random()}.json`)), run, stats: async () => stats, now: () => NOW });
|
||||
await a.pollOnce();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
const r = reports(h.posts)[0]!;
|
||||
expect(r).toMatchObject({ type: "status", status: "succeeded", result: { stats } });
|
||||
expect(agent.agentReportSchema.safeParse(r).success).toBe(true);
|
||||
});
|
||||
|
||||
it("status on a church server runs crosscode status", async () => {
|
||||
const { a, run } = make([job({ type: "status", args: {} })]);
|
||||
await a.pollOnce();
|
||||
expect(run.mock.calls[0]![0]).toEqual(["status", "--no-fetch"]);
|
||||
});
|
||||
|
||||
it("a job that throws is reported as failed", async () => {
|
||||
const { a, posts } = make([job()], jest.fn<ReturnType<Run>, Parameters<Run>>(async () => { throw new Error("boom"); }));
|
||||
await a.pollOnce();
|
||||
expect(reports(posts)[0]).toMatchObject({ status: "failed", message: "boom" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { config, serverKeys } from "./helpers";
|
||||
|
||||
/**
|
||||
* AGENT-1.0-PLAN §2 rule 1: the agent listens on nothing. Starts the built agent (dist/cli.js)
|
||||
* against a fake Hub served by this test, lets it poll, then compares the agent's open sockets
|
||||
* with every listening TCP socket the kernel knows (/proc/net/tcp, tcp6). Linux only (the
|
||||
* servers); run `npm run build -w apps/agent` first.
|
||||
*/
|
||||
const cli = path.join(__dirname, "..", "dist", "cli.js");
|
||||
const linux = process.platform === "linux" && fs.existsSync(cli);
|
||||
const maybe = linux ? it : it.skip;
|
||||
|
||||
function listeningInodes(): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const f of ["/proc/net/tcp", "/proc/net/tcp6"]) {
|
||||
let text: string;
|
||||
try { text = fs.readFileSync(f, "utf8"); } catch { continue; }
|
||||
for (const line of text.split("\n").slice(1)) {
|
||||
const cols = line.trim().split(/\s+/);
|
||||
if (cols[3] === "0A") out.add(cols[9]!); // 0A = LISTEN
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function socketInodes(pid: number): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const fd of fs.readdirSync(`/proc/${pid}/fd`)) {
|
||||
try {
|
||||
const m = /^socket:\[(\d+)\]$/.exec(fs.readlinkSync(`/proc/${pid}/fd/${fd}`));
|
||||
if (m) out.add(m[1]!);
|
||||
} catch { /* closed meanwhile */ }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("the running agent", () => {
|
||||
maybe("has no listening socket", async () => {
|
||||
let polls = 0;
|
||||
const hub = http.createServer((req, res) => {
|
||||
if (req.url === "/api/agent/v1/poll") polls++;
|
||||
res.setHeader("content-type", "application/json");
|
||||
res.end(req.url === "/api/agent/v1/poll" ? JSON.stringify({ jobs: [], pollSeconds: 5 }) : "{}");
|
||||
});
|
||||
await new Promise<void>((r) => hub.listen(0, "127.0.0.1", r));
|
||||
const port = (hub.address() as { port: number }).port;
|
||||
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agent-nolisten-"));
|
||||
fs.writeFileSync(path.join(dir, "agent.json"), JSON.stringify({ ...config, hubUrl: `http://127.0.0.1:${port}`, pollSeconds: 5, statsSeconds: 15 }));
|
||||
fs.writeFileSync(path.join(dir, "agent-ed25519.pem"), serverKeys.ed25519.privateKeyPem);
|
||||
fs.writeFileSync(path.join(dir, "agent-x25519.pem"), serverKeys.x25519.privateKeyPem);
|
||||
const child = spawn(process.execPath, [cli, "run"], {
|
||||
env: { ...process.env, CROSSCODE_AGENT_CONFIG_DIR: dir, CROSSCODE_AGENT_STATE_DIR: path.join(dir, "state"), CROSSCODE_AGENT_ALLOW_NON_ROOT: "1", CROSSCODE_SITES: path.join(dir, "sites") },
|
||||
stdio: "ignore",
|
||||
});
|
||||
try {
|
||||
for (let i = 0; i < 40 && polls === 0; i++) await new Promise((r) => setTimeout(r, 250));
|
||||
expect(polls).toBeGreaterThan(0);
|
||||
const listening = listeningInodes();
|
||||
const mine = [...socketInodes(child.pid!)].filter((inode) => listening.has(inode));
|
||||
expect(mine).toEqual([]);
|
||||
} finally {
|
||||
child.kill("SIGTERM");
|
||||
hub.close();
|
||||
}
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { checkPorts, parseFrpsIni, parseSs, portAllowed } from "../src/central";
|
||||
import { LogTail, redact } from "../src/redact";
|
||||
import { churchProcesses, cpuPercent, parseMeminfo } from "../src/stats";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
describe("log lines are redacted before they leave the server", () => {
|
||||
it.each([
|
||||
["Error: connect postgresql://hope_events:Zx81kLmQ@localhost:5432/hope_events", "postgresql://hope_events:***@localhost"],
|
||||
["JWT_SECRET=abcdefghijklmnop", "JWT_SECRET=***"],
|
||||
['DB_PASSWORD: "hunter2 x"', "DB_PASSWORD: ***"],
|
||||
["Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.payload.sig", "Authorization: Bearer ***"],
|
||||
["licence CEH-7K2M-9QXA-P4RT-WD8C refused", "CEH-****"],
|
||||
["token a3f9c1d27b8e4f60a3f9c1d27b8e4f60a3f9c1d2", "token ***"],
|
||||
])("%s", (line, expected) => {
|
||||
const out = redact(line);
|
||||
expect(out).toContain(expected);
|
||||
});
|
||||
|
||||
it("keeps ordinary lines", () => {
|
||||
expect(redact("==> events: migrations")).toBe("==> events: migrations");
|
||||
});
|
||||
|
||||
it("keeps only the last lines", () => {
|
||||
const t = new LogTail(3);
|
||||
t.push("1\n2\n3\n4");
|
||||
t.push("\n5\n");
|
||||
expect(t.end()).toEqual(["3", "4", "5"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("central server checks", () => {
|
||||
const ini = "[common]\nbind_port = 7000\nproxy_bind_addr = 127.0.0.1\nallow_ports = 20000-29999,3000\n\n[web]\nproxy_bind_addr = 0.0.0.0\n";
|
||||
|
||||
it("reads [common] only", () => {
|
||||
expect(parseFrpsIni(ini)).toEqual({ proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3000" });
|
||||
});
|
||||
|
||||
it("allow_ports ranges", () => {
|
||||
expect(portAllowed(20010, "20000-29999,3000")).toBe(true);
|
||||
expect(portAllowed(3000, "20000-29999,3000")).toBe(true);
|
||||
expect(portAllowed(5000, "20000-29999,3000")).toBe(false);
|
||||
expect(portAllowed(5000, null)).toBe(true);
|
||||
});
|
||||
|
||||
it("ports must be allowed, open and bound to 127.0.0.1 only", () => {
|
||||
const ss = "LISTEN 0 4096 127.0.0.1:20010 0.0.0.0:*\nLISTEN 0 4096 0.0.0.0:20011 0.0.0.0:*\nLISTEN 0 4096 [::1]:20012 [::]:*\n";
|
||||
const res = checkPorts([20010, 20011, 20012, 20013], parseFrpsIni(ini), parseSs(ss));
|
||||
expect(res.ports.map((p) => [p.port, p.ok])).toEqual([[20010, true], [20011, false], [20012, true], [20013, false]]);
|
||||
expect(res.warnings.join(" ")).toMatch(/20011 is open on more than 127.0.0.1/);
|
||||
expect(res.warnings.join(" ")).toMatch(/20013 isn't open/);
|
||||
});
|
||||
|
||||
it("warns when proxy_bind_addr is missing", () => {
|
||||
const res = checkPorts([20010], parseFrpsIni("[common]\nbind_port = 7000\n"), parseSs("LISTEN 0 1 127.0.0.1:20010 0.0.0.0:*"));
|
||||
expect(res.warnings.join(" ")).toMatch(/proxy_bind_addr is not set/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("stats", () => {
|
||||
it("RAM from /proc/meminfo", () => {
|
||||
const r = parseMeminfo("MemTotal: 4000000 kB\nMemFree: 100 kB\nMemAvailable: 1000000 kB\nSwapTotal: 2000 kB\nSwapFree: 500 kB\n");
|
||||
expect(r).toEqual({ totalBytes: 4096000000, usedBytes: 3072000000, availableBytes: 1024000000, swapTotalBytes: 2048000, swapUsedBytes: 1536000 });
|
||||
});
|
||||
|
||||
it("CPU % between two readings", () => {
|
||||
expect(cpuPercent("cpu 100 0 100 700 100 0 0 0", "cpu 150 0 150 750 150 0 0 0")).toBe(50);
|
||||
});
|
||||
|
||||
it("PM2 processes are matched to churches through church.env", () => {
|
||||
const sites = fs.mkdtempSync(path.join(os.tmpdir(), "sites-"));
|
||||
fs.mkdirSync(path.join(sites, "hope"));
|
||||
fs.writeFileSync(path.join(sites, "hope", "church.env"), 'CHURCH=hope\nEVENTS_USER=cc-hope\nEVENTS_PM2="hope-events-backend hope-events-frontend"\n');
|
||||
fs.mkdirSync(path.join(sites, "Bad Name"));
|
||||
const map = churchProcesses(sites);
|
||||
expect([...map.entries()]).toEqual([["cc-hope", [{ church: "hope", product: "events", names: ["hope-events-backend", "hope-events-frontend"] }]]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import path from "node:path";
|
||||
import { generateEd25519 } from "@crosscode/contracts/signing";
|
||||
import { checkJob, SeenJobs } from "../src/verify";
|
||||
import { config, job, NOW, tempState } from "./helpers";
|
||||
|
||||
const dir = tempState();
|
||||
const fresh = () => new SeenJobs(path.join(dir, `seen-${Math.random()}.json`));
|
||||
|
||||
describe("checking a job (AGENT-1.0-PLAN §4)", () => {
|
||||
it("accepts a signed job for this server, in its window", () => {
|
||||
expect(checkJob(job(), config, fresh(), NOW)).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("refuses a job signed with another key", () => {
|
||||
expect(checkJob(job({}, generateEd25519().privateKeyPem), config, fresh(), NOW)).toMatchObject({ ok: false, status: "refused", message: expect.stringContaining("signature") });
|
||||
});
|
||||
|
||||
it("refuses a job whose content was changed after signing", () => {
|
||||
const j = job();
|
||||
expect(checkJob({ ...j, args: { ...j.args, church: "other" } }, config, fresh(), NOW)).toMatchObject({ ok: false, status: "refused" });
|
||||
});
|
||||
|
||||
it("refuses a job for another server", () => {
|
||||
expect(checkJob(job({ serverId: "srv_other0001" }), config, fresh(), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("not this server") });
|
||||
});
|
||||
|
||||
it("reports an expired job as expired, and never runs it", () => {
|
||||
expect(checkJob(job(), config, fresh(), new Date("2026-11-20T12:16:00.000Z"))).toMatchObject({ ok: false, status: "expired" });
|
||||
});
|
||||
|
||||
it("refuses a job that isn't due yet (beyond a minute of clock difference)", () => {
|
||||
expect(checkJob(job(), config, fresh(), new Date("2026-11-20T11:58:00.000Z"))).toMatchObject({ ok: false, status: "refused" });
|
||||
expect(checkJob(job(), config, fresh(), new Date("2026-11-20T11:59:30.000Z"))).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("refuses a replayed job, also after a restart", () => {
|
||||
const file = path.join(dir, "seen-replay.json");
|
||||
const seen = new SeenJobs(file);
|
||||
const j = job();
|
||||
expect(checkJob(j, config, seen, NOW)).toMatchObject({ ok: true });
|
||||
seen.add(j.id);
|
||||
expect(checkJob(j, config, seen, NOW)).toMatchObject({ ok: false, message: expect.stringContaining("replay") });
|
||||
expect(checkJob(j, config, new SeenJobs(file), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("replay") });
|
||||
});
|
||||
|
||||
it("refuses an unknown type, and arguments with shell characters", () => {
|
||||
expect(checkJob(job({ type: "shell", args: { command: "id" } }), config, fresh(), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("Unknown job type") });
|
||||
expect(checkJob(job({ args: { church: "hope;reboot", products: ["events"] } }), config, fresh(), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("isn't valid") });
|
||||
expect(checkJob(job({ type: "adopt", args: { church: "hope", eventsDir: "/var/www/$(id)" } }), config, fresh(), NOW)).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it("a central agent only runs check-ports, status and update-agent", () => {
|
||||
const central = { ...config, mode: "central" as const };
|
||||
expect(checkJob(job(), central, fresh(), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("central") });
|
||||
expect(checkJob(job({ type: "check-ports", args: { ports: [20010, 20011] } }), central, fresh(), NOW)).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("refuses things that aren't jobs", () => {
|
||||
for (const raw of [null, "job", [], { id: "nope" }]) expect(checkJob(raw, config, fresh(), NOW)).toMatchObject({ ok: false, status: "refused" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"types": ["node", "jest"],
|
||||
"declaration": false
|
||||
},
|
||||
"include": ["src", "tests", "tsup.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
// One self-contained file (contracts and zod bundled in), so a server needs no node_modules to run
|
||||
// the agent: /opt/crosscode/agent/current/apps/agent/dist/cli.js.
|
||||
export default defineConfig({
|
||||
entry: ["src/cli.ts"],
|
||||
format: ["cjs"],
|
||||
platform: "node",
|
||||
target: "node24",
|
||||
noExternal: [/.*/],
|
||||
clean: true,
|
||||
sourcemap: true,
|
||||
banner: { js: "#!/usr/bin/env node" },
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
# dependencies
|
||||
node_modules/
|
||||
|
||||
# env files (never commit real secrets — .env.example files are fine)
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
# next.js
|
||||
.next/
|
||||
out/
|
||||
|
||||
# build output
|
||||
dist/
|
||||
build/
|
||||
|
||||
# logs
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
*.log
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# this install's PM2 config (made from ecosystem.config.example.js; deploys never touch it)
|
||||
/ecosystem.config.js
|
||||
|
||||
# misc scratch / generated files
|
||||
temp/
|
||||
backend/public/uploads/
|
||||
backend/backups/
|
||||
hope-events-deployment-setup.txt
|
||||
|
||||
# runtime data stores (mutated by the running app, not source)
|
||||
backend/data/scheduled-emails.json
|
||||
backend/data/banner.json
|
||||
# end-to-end tests
|
||||
e2e/.data/
|
||||
e2e/report/
|
||||
e2e/test-results/
|
||||
frontend/.next-e2e/
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,382 @@
|
||||
# Deploying Cross Events behind frp
|
||||
|
||||
This guide is for a server that is **not reachable from the internet directly**: it runs
|
||||
`frpc`, which opens a tunnel to `frps` on a public server (the "VPS"). Visitors reach the VPS,
|
||||
and frp carries the traffic through to this server. The frp client config lives at
|
||||
**`/etc/frp/frpc.ini`**.
|
||||
|
||||
For a server with a public IP, `scripts/install.sh` does everything (see the README). Behind frp
|
||||
it needs a few changes, because:
|
||||
|
||||
- **HTTPS can't be set up by the installer.** DNS points at the VPS, not at this server, so
|
||||
`certbot --nginx` can't work the usual way. HTTPS ends either on the VPS or in `frpc`.
|
||||
- **There are more proxies in the way.** The app must be told which of them to trust, or it sees
|
||||
every visitor as `127.0.0.1` (rate limiting then treats everyone as one person, and PayFast
|
||||
payment notifications fail their IP check).
|
||||
- **The app must know the site is HTTPS** even though nginx on this server only speaks HTTP;
|
||||
otherwise it builds `http://` links (event images, payment return URLs).
|
||||
|
||||
## 1. How the traffic flows
|
||||
|
||||
Pick the setup that matches how your other frp sites get HTTPS.
|
||||
|
||||
**A. HTTPS ends on the VPS** (nginx/Caddy on the VPS holds the certificate) — recommended if the
|
||||
VPS already does this for other sites:
|
||||
|
||||
```
|
||||
visitor ──https──▶ VPS nginx/Caddy ──http──▶ frps (vhost_http_port) ══tunnel══▶ frpc ──▶ nginx :80 ──▶ app
|
||||
```
|
||||
|
||||
**B. HTTPS ends in frpc** (the VPS only runs frps; the certificate lives on this server and
|
||||
frpc's `https2http` plugin uses it):
|
||||
|
||||
```
|
||||
visitor ──https──▶ frps (vhost_https_port) ══tunnel══▶ frpc https2http ──▶ nginx 127.0.0.1:8080 ──▶ app
|
||||
visitor ──http───▶ frps (vhost_http_port) ══tunnel══▶ frpc ──▶ nginx :80 (certificate check + redirect to https)
|
||||
```
|
||||
|
||||
On this server, nginx sends `/api`, `/uploads`, `/health` and `/docs` to the backend (port 5000)
|
||||
and everything else to the Next.js site (port 3000), the same as a normal install.
|
||||
|
||||
### One address, one rule (2.2.0 and later)
|
||||
|
||||
From 2.2.0 everything the backend serves is under **`/api`**: the API (`/api/v2`), the status page
|
||||
(`/api`), health (`/api/health`), the API reference (`/api/docs/v2`) and uploaded files
|
||||
(`/api/uploads/…`). So the site and its API share one address (`events.yourchurch.org`, no
|
||||
separate `events-api.` record), and a web server or panel such as FastPanel needs a single
|
||||
rule:
|
||||
|
||||
| Path | Goes to |
|
||||
|------|---------|
|
||||
| `/api` and everything under it | the backend, `http://127.0.0.1:5000` |
|
||||
| everything else | the frontend, `http://127.0.0.1:3000` |
|
||||
|
||||
Set `BACKEND_URL` (backend `.env`) and `NEXT_PUBLIC_API_URL` (frontend `.env.production`) to the
|
||||
same `https://` address as `FRONTEND_URL`, then rebuild the frontend. The old paths (`/health`,
|
||||
`/docs/v2`, `/uploads/…`) still answer on the backend's port, so a site with a separate API
|
||||
address keeps working unchanged. With only `/api` routed, links made before 2.2.0 that point at
|
||||
`https://<site>/uploads/…` stop working (they aren't stored that way, but could be in an old
|
||||
email); keep the four-path rule above if that matters. Pictures, logos and attachments are all
|
||||
given out as `/api/uploads/…` from 2.2.0.
|
||||
|
||||
## 2. Before you start
|
||||
|
||||
- Ubuntu 22.04 or 24.04 on this server, with `frpc` already installed and connected (it runs as
|
||||
a systemd service, usually `frpc.service`).
|
||||
- The site's DNS record (e.g. `events.yourchurch.org`) points at the **VPS**.
|
||||
- On the VPS, `frps.ini` has `vhost_http_port` set (and `vhost_https_port` for setup B). Note
|
||||
the values; you need them below.
|
||||
- The licence key for this site from the Cross Events Hub.
|
||||
|
||||
## 3. Install the app
|
||||
|
||||
On this server, as root, run the installer **without** its certificate step:
|
||||
|
||||
```bash
|
||||
curl -fsSLO https://c-git.crosscode.co.za/joshua/hope-events/raw/branch/main/scripts/install.sh
|
||||
sudo bash install.sh --domain events.yourchurch.org --no-ssl --version v1.41.2
|
||||
```
|
||||
|
||||
It installs Node 24 LTS, PostgreSQL, PM2 and nginx, creates the database, writes the config, builds
|
||||
and starts the app (in `/opt/hope-events`, run by the `hopeevents` user). Use `--name`, `--dir`,
|
||||
`--web-port` and `--api-port` if other apps already use those names or ports; adjust the ports
|
||||
below to match.
|
||||
|
||||
### Switch the URLs to https
|
||||
|
||||
With `--no-ssl` the installer writes `http://` addresses. Change them to `https://`:
|
||||
|
||||
```bash
|
||||
cd /opt/hope-events
|
||||
sudo sed -i 's#=http://#=https://#' backend/.env frontend/.env.production
|
||||
grep -E 'URL=' backend/.env frontend/.env.production # all should now start with https://
|
||||
```
|
||||
|
||||
While `backend/.env` is open, set which proxies to trust (all of them run on loopback in both
|
||||
setups; see [step 7](#7-check-that-visitor-addresses-come-through) to confirm):
|
||||
|
||||
```bash
|
||||
sudo sed -i 's#^TRUST_PROXY=.*#TRUST_PROXY=loopback#' backend/.env
|
||||
```
|
||||
|
||||
`NEXT_PUBLIC_API_URL` is baked in when the site is built, so rebuild the frontend and restart:
|
||||
|
||||
```bash
|
||||
sudo -u hopeevents -H bash -lc 'cd /opt/hope-events/frontend && npm run build'
|
||||
sudo -u hopeevents -H bash -lc 'cd /opt/hope-events && pm2 reload ecosystem.config.js --update-env'
|
||||
```
|
||||
|
||||
Keep `JWT_SECRET` in `backend/.env` as it is: it also encrypts the secrets stored in the
|
||||
database (SMTP, payment keys).
|
||||
|
||||
## 4. nginx on this server
|
||||
|
||||
The installer wrote `/etc/nginx/sites-available/hope-events`. Replace it with the version for
|
||||
your setup, changing the domain (and the ports if you changed them).
|
||||
|
||||
### Setup A (HTTPS on the VPS)
|
||||
|
||||
```nginx
|
||||
# Shows the forwarded-for chain in the access log (see step 7). Safe to keep.
|
||||
log_format hope_proxy '$remote_addr xff="$http_x_forwarded_for" "$request" $status';
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name events.yourchurch.org;
|
||||
client_max_body_size 25m;
|
||||
access_log /var/log/nginx/hope-events.access.log hope_proxy;
|
||||
|
||||
# Visitors only reach this through the VPS over HTTPS, so tell the app so.
|
||||
location ~ ^/(api|uploads|health|docs)(/|$) {
|
||||
proxy_pass http://127.0.0.1:5000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
}
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The VPS nginx/Caddy must redirect plain HTTP to HTTPS and pass the `Host` header through to frps
|
||||
unchanged (frps picks the site by its host name). For nginx on the VPS, roughly:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name events.yourchurch.org;
|
||||
# ssl_certificate / ssl_certificate_key from certbot on the VPS
|
||||
client_max_body_size 25m;
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8080; # frps vhost_http_port
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Setup B (HTTPS in frpc)
|
||||
|
||||
Port 80 only answers certificate checks and redirects everything else; the real site is on
|
||||
`127.0.0.1:8080`, which only frpc's `https2http` plugin reaches.
|
||||
|
||||
```nginx
|
||||
log_format hope_proxy '$remote_addr xff="$http_x_forwarded_for" "$request" $status';
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name events.yourchurch.org;
|
||||
location /.well-known/acme-challenge/ { root /var/www/certbot; }
|
||||
location / { return 301 https://$host$request_uri; }
|
||||
}
|
||||
|
||||
server {
|
||||
listen 127.0.0.1:8080;
|
||||
server_name events.yourchurch.org;
|
||||
client_max_body_size 25m;
|
||||
access_log /var/log/nginx/hope-events.access.log hope_proxy;
|
||||
|
||||
location ~ ^/(api|uploads|health|docs)(/|$) {
|
||||
proxy_pass http://127.0.0.1:5000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
}
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then, for either setup:
|
||||
|
||||
```bash
|
||||
sudo mkdir -p /var/www/certbot # setup B only
|
||||
sudo nginx -t && sudo systemctl reload nginx
|
||||
```
|
||||
|
||||
## 5. frpc: `/etc/frp/frpc.ini`
|
||||
|
||||
Back it up first, then **add** a section for the site below the existing ones. Leave `[common]`
|
||||
(server address, port, token) and the other sections as they are. Section names must be unique
|
||||
across everything connected to your frps.
|
||||
|
||||
```bash
|
||||
sudo cp /etc/frp/frpc.ini /etc/frp/frpc.ini.bak-$(date +%F)
|
||||
sudo nano /etc/frp/frpc.ini
|
||||
```
|
||||
|
||||
### Setup A
|
||||
|
||||
```ini
|
||||
[hope-events-http]
|
||||
type = http
|
||||
local_ip = 127.0.0.1
|
||||
local_port = 80
|
||||
custom_domains = events.yourchurch.org
|
||||
```
|
||||
|
||||
### Setup B
|
||||
|
||||
```ini
|
||||
# Plain HTTP: certificate checks and the redirect to https
|
||||
[hope-events-http]
|
||||
type = http
|
||||
local_ip = 127.0.0.1
|
||||
local_port = 80
|
||||
custom_domains = events.yourchurch.org
|
||||
|
||||
# HTTPS: frpc holds the certificate and passes plain HTTP to nginx on 127.0.0.1:8080
|
||||
[hope-events-https]
|
||||
type = https
|
||||
custom_domains = events.yourchurch.org
|
||||
plugin = https2http
|
||||
plugin_local_addr = 127.0.0.1:8080
|
||||
plugin_crt_path = /etc/letsencrypt/live/events.yourchurch.org/fullchain.pem
|
||||
plugin_key_path = /etc/letsencrypt/live/events.yourchurch.org/privkey.pem
|
||||
plugin_header_X-Forwarded-Proto = https
|
||||
```
|
||||
|
||||
Restart frpc and check it registered the new sections without errors:
|
||||
|
||||
```bash
|
||||
sudo systemctl restart frpc
|
||||
sudo journalctl -u frpc -n 30 --no-pager # look for "start proxy success" for each section
|
||||
```
|
||||
|
||||
> Newer frp releases (0.52+) prefer `frpc.toml`, but still read `.ini`. Don't mix the two: if
|
||||
> your service already uses `frpc.ini`, keep adding to it.
|
||||
|
||||
### Certificate (setup B only)
|
||||
|
||||
Request it through the tunnel with the webroot method (not `--nginx`, which would rewrite the
|
||||
nginx config), then have renewals restart frpc so it loads the new certificate:
|
||||
|
||||
```bash
|
||||
sudo apt-get install -y certbot
|
||||
sudo certbot certonly --webroot -w /var/www/certbot -d events.yourchurch.org \
|
||||
-m you@yourchurch.org --agree-tos --non-interactive
|
||||
echo 'systemctl restart frpc' | sudo tee /etc/letsencrypt/renewal-hooks/deploy/restart-frpc.sh
|
||||
sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/restart-frpc.sh
|
||||
sudo systemctl restart frpc
|
||||
```
|
||||
|
||||
frpc needs to be able to read the certificate files (it does when it runs as root, the usual
|
||||
setup). If the `[hope-events-https]` section fails to start, check `journalctl -u frpc`.
|
||||
|
||||
## 6. Finish in the browser
|
||||
|
||||
1. Open `https://events.yourchurch.org/api/health` (`/health` before 2.2.0) — it should answer with the version.
|
||||
2. Open `https://events.yourchurch.org/setup`: create the admin account.
|
||||
3. **Site settings → Licence**: enter the licence key to connect to the Hub. The site checks in
|
||||
every 15 minutes from then on (outgoing HTTPS to `events-hub.crosscode.co.za`, which frp
|
||||
doesn't affect).
|
||||
4. Configure SMTP, payments (Yoco/PayFast webhooks use the `https://` `BACKEND_URL`), branding,
|
||||
etc. in Site settings.
|
||||
|
||||
## 7. Check that visitor addresses come through
|
||||
|
||||
Open the site from your phone (on mobile data, so it isn't your own network), then on the
|
||||
server:
|
||||
|
||||
```bash
|
||||
sudo tail -n 5 /var/log/nginx/hope-events.access.log
|
||||
```
|
||||
|
||||
The `xff="…"` part is what the app sees, with nginx's own entry added at the end:
|
||||
|
||||
- `xff="<your phone's IP>, 127.0.0.1"` (only `127.0.0.1` after the real address): good,
|
||||
`TRUST_PROXY=loopback` is right.
|
||||
- `xff="<your phone's IP>, 203.0.113.10"` (a non-local address after it, e.g. the VPS's): add
|
||||
that address: `TRUST_PROXY=loopback,203.0.113.10`, then
|
||||
`pm2 reload ecosystem.config.js --update-env`.
|
||||
- Your phone's IP doesn't appear at all: frp isn't passing the visitor's address on (can happen
|
||||
with setup B on some frp versions). Rate limiting and the PayFast IP check will then misbehave.
|
||||
Fix it by moving TLS to the VPS (setup A), or with frp's `proxy_protocol_version = v2` on the
|
||||
frpc section plus nginx's `listen … proxy_protocol` and `set_real_ip_from 127.0.0.1;
|
||||
real_ip_header proxy_protocol;`.
|
||||
|
||||
The backend logs the setting it uses at startup: `pm2 logs hope-events-backend | grep trust`.
|
||||
|
||||
## 8. Updating
|
||||
|
||||
Nothing about frp changes for updates. On the server:
|
||||
|
||||
```bash
|
||||
cd /opt/hope-events
|
||||
sudo -u hopeevents -H bash scripts/deploy.sh v1.41.2 # or no tag for the latest main
|
||||
```
|
||||
|
||||
It backs up the database, checks out the release, installs, migrates, builds (the backend too,
|
||||
since 1.51.0) and reloads PM2,
|
||||
and goes back to the previous version if anything fails first. `backend/.env`,
|
||||
`frontend/.env.production`, `ecosystem.config.js` and the nginx/frpc configs are not in git, so
|
||||
updates keep your changes from this guide.
|
||||
|
||||
Since 1.52.2 it first checks for files in the install folder that were changed or added by hand
|
||||
(e.g. by a setup wizard run on the server) and stops, listing them, before it backs anything up
|
||||
or checks anything out: they would be built into the release, or block the checkout. Move added
|
||||
files out of the folder and put changed ones back with `git checkout -- <file>`, or deploy anyway
|
||||
with `ALLOW_LOCAL_CHANGES=1`. To check without deploying:
|
||||
|
||||
```bash
|
||||
sudo -u hopeevents -H bash scripts/deploy.sh --check
|
||||
```
|
||||
|
||||
An install still on an older release can run the new check without updating anything — fetch the
|
||||
script on its own and run it from the install folder:
|
||||
|
||||
```bash
|
||||
git fetch -q origin && git show origin/main:scripts/deploy.sh > /tmp/deploy.sh
|
||||
bash /tmp/deploy.sh --check
|
||||
```
|
||||
|
||||
### Upgrading Node
|
||||
|
||||
Node 20 stopped getting security fixes in April 2026; Cross Events runs on Node 24 LTS (supported
|
||||
until April 2028). `deploy.sh` warns when a server is still on an older Node. To upgrade:
|
||||
|
||||
```bash
|
||||
node -v # what you have now
|
||||
curl -fsSL https://deb.nodesource.com/setup_24.x | sudo bash -
|
||||
sudo apt-get install -y nodejs # replaces the old Node
|
||||
sudo npm install -g pm2 # PM2 for the new Node
|
||||
cd /opt/hope-events
|
||||
sudo -u hopeevents -H pm2 update # restart PM2's daemon on the new Node
|
||||
sudo -u hopeevents -H bash scripts/deploy.sh v1.51.4 # reinstall packages and rebuild for Node 24
|
||||
```
|
||||
|
||||
Use the version you're on (or a newer one) in the last line — the deploy reinstalls every package
|
||||
and rebuilds, which a Node upgrade needs.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Likely cause |
|
||||
| --- | --- |
|
||||
| frps shows "404 Not Found" page | The `custom_domains` value doesn't match the address typed, or frpc didn't start that section (`journalctl -u frpc`). |
|
||||
| 502 Bad Gateway | nginx is up but the app isn't: `sudo -u hopeevents pm2 ls` and `pm2 logs`. |
|
||||
| Site loads but login/API calls fail (CORS) | `FRONTEND_URL` in `backend/.env` is still `http://`, or the frontend wasn't rebuilt after changing `NEXT_PUBLIC_API_URL`. |
|
||||
| Images or links use `http://` (browser "mixed content" warnings) | nginx isn't sending `X-Forwarded-Proto https`, or `TRUST_PROXY` isn't set. |
|
||||
| "Too many requests" for everyone at once | All visitors look like one address: see step 7. |
|
||||
| PayFast payments stay pending | Same as above: the PayFast notification's IP check sees the proxy, not PayFast. |
|
||||
| Uploads over ~1 MB fail | `client_max_body_size` missing on this server's nginx or the VPS's. |
|
||||
| Redirect loop (setup B) | The site's `server` block is on port 80 instead of `127.0.0.1:8080`, or `plugin_local_addr` points at port 80. |
|
||||
@@ -0,0 +1,962 @@
|
||||
# Cross Events — Feature Overview
|
||||
|
||||
A complete map of what the platform does, grouped by who uses it. For setup and
|
||||
deployment see [README.md](./README.md); for the API see
|
||||
[backend/API_DOCUMENTATION.md](./backend/API_DOCUMENTATION.md); for setting
|
||||
defaults see [SETTINGS.md](./SETTINGS.md); for history see
|
||||
[CHANGELOG.md](./CHANGELOG.md).
|
||||
|
||||
**Stack:** Next.js (React, Tailwind, shadcn/ui) frontend · Express + Prisma +
|
||||
PostgreSQL backend · Yoco for card payments · SMTP for email · WAWP for
|
||||
WhatsApp · PM2 for process management · optional Sentry for error monitoring.
|
||||
|
||||
---
|
||||
|
||||
## Contents
|
||||
|
||||
1. [Roles](#roles)
|
||||
2. [Public site](#public-site)
|
||||
3. [Events](#events)
|
||||
4. [Registration](#registration)
|
||||
5. [Payments, donations & refunds](#payments-donations--refunds)
|
||||
6. [Tickets & check-in](#tickets--check-in)
|
||||
7. [Attendee forms](#attendee-forms)
|
||||
8. [Messaging & notifications](#messaging--notifications)
|
||||
9. [User dashboard (My Events)](#user-dashboard-my-events)
|
||||
10. [Staff tools](#staff-tools)
|
||||
11. [Supervisor tools](#supervisor-tools)
|
||||
12. [Admin tools](#admin-tools)
|
||||
13. [Cashup & event costs](#cashup--event-costs)
|
||||
14. [Reports](#reports)
|
||||
15. [Site settings & setup wizard](#site-settings--setup-wizard)
|
||||
16. [Event series](#event-series)
|
||||
17. [Multi-campus](#multi-campus)
|
||||
18. [Kids check-in](#kids-check-in)
|
||||
19. [Volunteer rosters](#volunteer-rosters)
|
||||
20. [Accounts & security](#accounts--security)
|
||||
21. [Privacy (POPIA)](#privacy-popia)
|
||||
22. [Accessibility](#accessibility)
|
||||
23. [Help system](#help-system)
|
||||
24. [Background jobs](#background-jobs)
|
||||
25. [Operations](#operations)
|
||||
26. [Page map](#page-map)
|
||||
|
||||
---
|
||||
|
||||
## Roles
|
||||
|
||||
Four roles, each including everything the roles below it can do:
|
||||
|
||||
| Role | Can do |
|
||||
|------|--------|
|
||||
| **User** | Browse events, register, pay, donate, view tickets, fill in forms, manage their own profile |
|
||||
| **Staff** | Scan tickets, view/print event tickets, view registrations and form responses |
|
||||
| **Supervisor** | Create and manage events, record payments/refunds, assign donations, at-the-door desk, manual registration, bulk email/WhatsApp, reports, site banner, self-service kiosk |
|
||||
| **Admin** | Manage users and roles, all registrations, event costs and cashup (close/reopen events), audit log, site settings, WhatsApp connection, backups |
|
||||
|
||||
---
|
||||
|
||||
## Public site
|
||||
|
||||
- **Home page** — hero section with the organisation's name and branding, upcoming
|
||||
and in-progress events, and a "Join Us" button (becomes "My Dashboard" when
|
||||
logged in).
|
||||
- **Events list** (`/events`) — event cards with picture, dates, location,
|
||||
price, and a Register / Sold Out / Contact us button. A diagonal "Early bird"
|
||||
ribbon in the top-right corner while an early-bird tier is running and
|
||||
registration is open.
|
||||
- **Event detail** (`/events/[id]`) — description, ticket options with
|
||||
variant and early-bird pricing, low-stock and sold-out badges, downloadable
|
||||
attachments, embedded Google Map with "Directions" link, and an
|
||||
**Add to calendar** (`.ics`) button.
|
||||
- **Short links** — events can have an alias (e.g. `/camp-2025`) that redirects
|
||||
to the event. Only plausible aliases hit the database, so bot probes are
|
||||
rejected cheaply.
|
||||
- **Contact page** (`/contact`) — organisation email, phone, address and map.
|
||||
- **Legal pages** — Terms of Use and Privacy Policy, filled from Site Settings.
|
||||
- **Site banner** — a site-wide announcement bar set by supervisors.
|
||||
- **Lockdown rules** (`/lockdown-rules`) — static rules page for the youth
|
||||
lockdown event.
|
||||
- **SEO** — `sitemap.xml` (every public page and event), `robots.txt`, and
|
||||
Open Graph/Twitter link-preview metadata.
|
||||
- **Theming** — brand colours, logo and favicon come from Site Settings.
|
||||
|
||||
---
|
||||
|
||||
## Events
|
||||
|
||||
Created and edited by supervisors through a 9-step wizard: **Basic Details →
|
||||
Items & Pricing → Sections → Form → Visibility → Notifications → Attachments →
|
||||
Feedback → Attendance**.
|
||||
|
||||
- **Basic details** — title, description, start/end dates, registration
|
||||
deadline, picture (upload or URL), location (defaults to the org's address),
|
||||
contact person.
|
||||
- **Copy an event** — "Copy" on an event card opens the editor filled in from that
|
||||
event (details, campus, sessions, options, variants, early birds, sections, form,
|
||||
notification recipients, feedback questions, certificates, reminders). Setting
|
||||
the **New start** moves every date with it (end, sessions, registration deadline,
|
||||
early-bird deadlines, feedback date). Allocation groups are copied on save, and
|
||||
for admins the planned costs (matched to options by name). Not copied:
|
||||
registrations, coupons, attachments, the short link, the go-live time, kids
|
||||
check-in and volunteer roles.
|
||||
- **Contact-only events** — for things like baptisms: shown publicly with a
|
||||
"Contact us" popup instead of registration, with no tickets.
|
||||
- **Multi-day events (sessions)** — one event on several dates, e.g. every
|
||||
Wednesday 18:30–20:30 for 5 weeks. A repeat pattern (daily/weekly, every N,
|
||||
chosen weekdays, a number of sessions or an end date) creates the sessions,
|
||||
which can then be edited one by one (label, times, location), added to, or
|
||||
cancelled (kept for history; one with check-ins can't be deleted). People
|
||||
register and pay once and get one ticket. The event page shows the schedule
|
||||
with the next session highlighted; cards show "5 sessions · Wed 4 Nov – Wed
|
||||
2 Dec" and stay listed until the last session. Calendar files get one entry
|
||||
per session. Saving moved or cancelled sessions offers to message attendees.
|
||||
- **Pick sessions** (multi-day) — instead of the whole course, people can choose
|
||||
which sessions to come to (day passes, drop-in classes). Tickets set to "Pick
|
||||
sessions" are priced and bought per session — one line and one ticket per session,
|
||||
bookable until the session starts (staff: until it ends) — alongside optional
|
||||
whole-course tickets. Sessions can have a capacity (picked places plus whole-course
|
||||
tickets); a per-session ticket's stock limit is places per session. Picked tickets
|
||||
only scan on their own session; reminders, the register and certificates follow
|
||||
the sessions each person booked. "All sessions" tickets on such an event also show
|
||||
the sessions: people tick the ones they'll come to and pay the ticket's one price; the
|
||||
ticket scans, reminds and counts towards capacity for those sessions only. The waitlist
|
||||
works per session (a full session shows "Join waitlist"). Bookable from the registration page, Manual registration,
|
||||
At the door (today's session is preselected) and the kiosk. Not available on youth
|
||||
events.
|
||||
- **Late joining** (multi-day) — registration closes when the first session
|
||||
starts, or later (until session N) with late joining on. Late joiners pay
|
||||
full price, a pro-rata price for the sessions left (rounded to the nearest
|
||||
R10), or a fixed late price — main tickets only.
|
||||
- **Completion certificates** — optional per event: four designs (Classic,
|
||||
Modern, Church, Kids), custom wording with placeholders, signature name/role/
|
||||
image, and a completion rule (every session, at least N sessions, or N%).
|
||||
Issued automatically when the event ends; each has a code and QR code checked
|
||||
on a public verify page.
|
||||
- **Ticket options** — multiple options per event (e.g. Adult, Child, Dinner,
|
||||
T-shirt), each with a price and optional **stock limit**. One option is marked
|
||||
as the main ticket, which is what gets checked in at the door.
|
||||
- **Variants** — sub-types of an option (sizes, colours, Adult/Child/VIP), each
|
||||
with an optional price override and its own stock limit.
|
||||
- **Early-bird tiers** — deadline- and/or stock-limited cheaper prices per
|
||||
option or variant. Prices are locked in per purchase ("tranches"), so buying
|
||||
more later doesn't re-price what was already bought.
|
||||
- **Sections** — named scan points (e.g. "Main hall", "Dinner") limited to
|
||||
certain ticket options, so a scanner at that point only accepts those tickets.
|
||||
- **Visibility** — active/inactive, hidden (reachable only by link), scheduled
|
||||
go-live date, require login vs. allow guest registration, or no registration
|
||||
at all.
|
||||
- **Attachments** — downloadable files (maps, schedules, waivers) shown on the
|
||||
event page.
|
||||
- **Notify recipients** — choose which staff get registration/payment alerts and
|
||||
the daily summary for the event.
|
||||
- **Sold-out handling** — an event is sold out when every stock-limited option
|
||||
is exhausted. "X remaining" badges appear at a threshold that scales with
|
||||
capacity.
|
||||
|
||||
---
|
||||
|
||||
## Registration
|
||||
|
||||
- **Online registration** (`/register/[eventId]`) — pick options, variants and
|
||||
quantities; see early-bird prices and stock warnings; fill in the event form.
|
||||
- **Guest registration** — when an event doesn't require login, an inactive
|
||||
account is created and an activation link is sent by email or WhatsApp.
|
||||
- **Statuses** — Pending, Confirmed, Partially Paid, Paid, Cancelled.
|
||||
- **Edit options** — users can add or change items on their registration
|
||||
(not for past or closed events).
|
||||
- **Self-cancellation** — allowed only before any payment; admins can cancel
|
||||
any time.
|
||||
- **Pricing refresh** — when an unpaid registration is viewed or paid, expired
|
||||
early-bird prices are re-evaluated, and the user is warned if the total
|
||||
changed.
|
||||
- **Manual registration** (supervisor) — register someone on their behalf,
|
||||
creating an account if needed. Includes a "Record Payment" tab.
|
||||
- **Duplicate-account protection** — if an email and phone belong to two
|
||||
different accounts, the registration is blocked instead of merging them.
|
||||
- **Group tickets** — on events with "Named attendees" turned on, someone booking
|
||||
several places can name each person (with optional email/phone). Each named person
|
||||
gets their own ticket and their own attendee form; unnamed places share one ticket.
|
||||
Tickets go all to the payer, or each to the person (falling back to the payer).
|
||||
Attendees matching an existing account see their ticket in My Events. Names can be
|
||||
added or changed later from My Events, and attendees can be sent a link to fill in
|
||||
their own form. Available on the registration page, manual registration, At the
|
||||
door and the kiosk.
|
||||
- **Waitlist** — on events with a waitlist, sold-out tickets show "Join waitlist"
|
||||
(on the event page, the register page and the event list). When places free up — a
|
||||
cancellation, a smaller booking or a higher stock limit — the next person is
|
||||
emailed/WhatsApped a claim link and the places are held for them (24 hours by
|
||||
default) so nobody else can buy them. Unclaimed offers expire and move on; people
|
||||
who asked for more than came free can be offered what's free or skipped. Claiming
|
||||
works without logging in. People can leave from My Events. On pick-sessions events
|
||||
people wait for a particular session; offers never run past the session's start.
|
||||
- **Parental consent (youth events)** — on events that require it, every attendee
|
||||
gives a date of birth; for anyone under 18, a parent or guardian gets an email and
|
||||
a WhatsApp with a consent link. They read the event's consent text, optionally give
|
||||
medical info, an emergency contact and photo consent, type their name to sign, and
|
||||
give or decline. Tickets are issued but can't be checked in until consent is given
|
||||
(supervisors can override, audited). Reminders go after 2 days, then every 3 days.
|
||||
Medical details are encrypted and deleted a set number of days after the event.
|
||||
- **Coupon codes** — percentage, fixed-amount or free (comp) codes, entered under
|
||||
"Have a code?" on the registration page, in My Events (for unpaid registrations),
|
||||
manual registration, At the door and the kiosk. Codes can be limited to events,
|
||||
ticket options or variants, dates, total and per-person uses, a minimum quantity,
|
||||
and specific people, roles or an email domain (restricted codes need a login).
|
||||
Early-bird prices either stack or the better price wins. The discount is locked in
|
||||
when applied and shows on invoices, receipts, emails and the Yoco checkout;
|
||||
cancelling frees the use. Managed from Supervisor → Coupon codes.
|
||||
- **Staff price** — a ticket option or variant can have a staff price that Staff and
|
||||
above get automatically, without a code.
|
||||
|
||||
---
|
||||
|
||||
## Payments, donations & refunds
|
||||
|
||||
- **Online card payments via Yoco** — checkout for the full outstanding balance,
|
||||
confirmed by a signed webhook. Keys and the webhook are set up from
|
||||
Site Settings → Payments, where providers are switched on or off and put in order
|
||||
(the first one is the default). Online payments are at least R15; payments are
|
||||
recorded at the full amount and provider fees are dealt with at cashup.
|
||||
- **PayFast** — the second online provider (card, instant EFT…), with sandbox and live
|
||||
modes. When several providers are on, payers choose on the "Pay online" page; a
|
||||
payment of a different amount from the checkout is held for review instead of being
|
||||
recorded. When no provider is on (or the amount is under R15), nothing offers to pay
|
||||
online.
|
||||
- **Payment status checks** — if a provider's notification never arrives, Payments →
|
||||
Reconcile → "Waiting for payment" checks with the provider (PayFast; Yoco's API can't be
|
||||
asked) and records what it finds. A job checks recent PayFast checkouts every 15 minutes.
|
||||
- **Payment links** — supervisors can generate and send a Yoco link for any
|
||||
amount (including partial).
|
||||
- **Manual payments** — cash, card, EFT, voucher or other, recorded by staff.
|
||||
Each payment records **who recorded it** as well as who it's for.
|
||||
- **Refunds** — negative payments against an original payment, netted against
|
||||
the original method.
|
||||
- **Impersonate user** (Admin → Manage users) — an admin with 2FA can view the site as a
|
||||
user, to debug problems.
|
||||
- It needs a reason, lasts at most 30 minutes, and shows a bright "Viewing as" banner
|
||||
on every page.
|
||||
- It is strictly read-only. A server-side guard refuses every write made with the
|
||||
impersonation token before it reaches any route, and pages don't even refresh
|
||||
prices while viewing.
|
||||
- Admins can't be impersonated.
|
||||
- The start, end, reason and every page and API call are in the audit log, with each
|
||||
session's trail.
|
||||
- Optional email to the user (`notify_user_on_impersonation`).
|
||||
- **Registration funnel stats** — first-party and consent-based, with no third-party analytics.
|
||||
- A cookie notice asks once. Only visitors who allow it get a random visit id.
|
||||
- We record event page views and registration starts. Submits and payments come
|
||||
from the registration itself.
|
||||
- Each record holds only the stage, the traffic source (utm_source, or the short-link
|
||||
alias, which short links now pass as `?src=`) and the device type.
|
||||
- The Registration funnel report shows counts and conversion per stage over a date
|
||||
range, a daily trend, and breakdowns by source, device and ticket option.
|
||||
- A "Conversion (past month)" tile on the supervisor/admin dashboards covers live
|
||||
events.
|
||||
- Raw rows are rolled up into daily totals after 90 days.
|
||||
- **Post-event feedback** — a Feedback step in the event wizard.
|
||||
- Questions use the form builder, with new **star rating (1–5)** and **multiple
|
||||
choice** types (also available on attendee forms).
|
||||
- The form goes out at a chosen time to everyone who checked in, or to everyone
|
||||
registered, each with a personal link (`/feedback/<token>`). One reminder goes
|
||||
3 days later to anyone who hasn't answered.
|
||||
- Answers can be anonymous or named. "Send now" is available, and the questions
|
||||
lock once people have answered.
|
||||
- **Feedback page** (Supervisor → Feedback, supervisors and admins): every event's form
|
||||
with answered of asked, response rate, average rating and last reminder; per event the
|
||||
results per question (and the AI summary), each response, and on named forms who was
|
||||
asked and who has answered. **Remind** sends everyone who hasn't answered a fresh link
|
||||
(and the form to anyone eligible who hasn't had it), or one person on a named form;
|
||||
nobody gets the form or a reminder twice within 24 hours. Anonymous forms show no names
|
||||
and no list of who has answered. Opening a named form's answers goes in the access log.
|
||||
- **Sponsor a spot** — per-event setting. A "Sponsor a spot" button on the event page
|
||||
lets anyone, including guests, pay for one or more spots (at the main ticket price)
|
||||
or any amount through Yoco. They can give anonymously or add a name and a message.
|
||||
The money is a donation tagged to the event and goes into its sponsorship pool, which
|
||||
supervisors assign to registrations with the usual donation flow.
|
||||
- An optional public progress bar ("12 of 20 spots sponsored") with an optional goal.
|
||||
- Sponsors get a thank-you receipt, and an Automations thank-you can go to all of an
|
||||
event's sponsors.
|
||||
- The Donations breakdown report shows each pool: received, assigned and remaining.
|
||||
- Who is helped is never shown.
|
||||
- **Donations** — users can donate from their dashboard (`/dashboard/user/donate`).
|
||||
Supervisors can **assign** a donation (fully or partly) to someone's
|
||||
registration and **unassign** it later. Assignments are kept as separate
|
||||
records, so the original donation never changes.
|
||||
- **Online payment reconciliation** — provider (Yoco) transactions can be matched to a
|
||||
registration, recorded as a donation (optionally choosing the donor), or
|
||||
ignored.
|
||||
- **Invoices & receipts** — branded PDFs: an invoice (itemised, early-bird
|
||||
discount, balance due, pay-now link and QR code) and a payment receipt. Sent
|
||||
automatically and re-sendable on demand by email or WhatsApp.
|
||||
- **Method normalisation** — Apple Pay / Google Pay / checkout payments count as
|
||||
"Card" in reports and user views.
|
||||
|
||||
---
|
||||
|
||||
## Tickets & check-in
|
||||
|
||||
- **Automatic tickets** — QR-coded tickets are generated when a registration is
|
||||
fully paid (or free), and sent as a PDF by email and/or WhatsApp.
|
||||
- **Quantity tickets** — one ticket can cover several people and be redeemed
|
||||
partially (e.g. check in 2 of 3).
|
||||
- **Named tickets** — group bookings can give each person their own ticket, shown
|
||||
with their name on the PDF, the scanner and the staff ticket list.
|
||||
- **QR scanner** — works in any mobile browser. A preview checks the ticket is
|
||||
for the selected event/section, then a confirmation screen shows holder, type
|
||||
and remaining quantity.
|
||||
- **Check-in confirmation** — holders get an email/WhatsApp saying how many were
|
||||
checked in and how many remain.
|
||||
- **Per-session check-in** — multi-day tickets are checked in once per session.
|
||||
The scanner uses today's session (or one picked from a list). Check-in is open
|
||||
the whole day of a session, or only from 2 hours before it until it ends, per
|
||||
event. Optional reminders (1 h / 3 h / 1 day before each session) by email
|
||||
and/or WhatsApp.
|
||||
- **Attendance register** — attendees × sessions with ticks, totals per session,
|
||||
completion, filters (completed, missed the last two), Excel/PDF export.
|
||||
Supervisors can tick someone present or absent (audit-logged), and issue,
|
||||
send, download or revoke certificates.
|
||||
- **Scan stats** — recent scans and per-event scan counts.
|
||||
- **Offline scanning** — while online, a staff member locks an event section (or the
|
||||
whole event) to their device and downloads its tickets. They can then keep scanning
|
||||
with no connection; scans are queued on the device and sync automatically when it's
|
||||
back online (never redeeming more than is left). Only one device can hold a section,
|
||||
and while it's locked nobody else can scan it, online or offline. Problems found
|
||||
while syncing go into a report for a supervisor. Supervisors can force-release a
|
||||
lost device. The scanner can be added to the home screen (PWA) and opens offline.
|
||||
- **Printing** — A4 sheets (8 tickets per page) and A6 single tickets.
|
||||
- **Resend** — send tickets to a different email/phone at the door.
|
||||
|
||||
---
|
||||
|
||||
## Attendee forms
|
||||
|
||||
- **Form builder** per event — field types: Yes/No, Text, Paragraph, Number,
|
||||
Date, plus Statement and Heading blocks; required/optional, help text,
|
||||
reordering. The whole form can be marked required.
|
||||
- **Drafts** — partially filled forms are auto-saved.
|
||||
- **Required forms and tickets** — a required form (with at least one question)
|
||||
holds a registration's tickets back until a form is in for each person (a
|
||||
picked-session booking counts each person once). At the door and in Manual
|
||||
registration the form pops up to fill in with the attendee; **Fill in later**
|
||||
(any staff) issues the tickets anyway once it's paid and sends the payer a link
|
||||
to the form. The kiosk asks the visitor for exactly the forms still missing.
|
||||
- **Responses** — view, filter (event, user, past/inactive) and print one
|
||||
response per A4 page. Supervisors can edit responses.
|
||||
|
||||
---
|
||||
|
||||
## Messaging & notifications
|
||||
|
||||
Every user picks a **notification preference**: Email, WhatsApp, or Both.
|
||||
|
||||
**Automatic notifications**
|
||||
|
||||
| Trigger | Goes to |
|
||||
|---------|---------|
|
||||
| Registration created / updated | Registrant (with invoice if unpaid) + event notify recipients |
|
||||
| Payment recorded / donation applied / unassigned | Registrant (with receipt) + admins |
|
||||
| Refund processed | Registrant + admins |
|
||||
| Tickets generated | Registrant (ticket PDF) |
|
||||
| Ticket checked in | Ticket holder |
|
||||
| Daily summary, 07:00, for each live event that hasn't started yet | Registrations inbox + event notify recipients |
|
||||
| Account registered, activation, login, password changed/reset, account closed | The account holder |
|
||||
|
||||
**Bulk messaging** (supervisor)
|
||||
|
||||
- **Email attendees** and **WhatsApp attendees** — filter by status or pick
|
||||
specific attendees, preview, send now or schedule for later.
|
||||
- **Placeholders** — `{{name}}`, `{{event.title}}`, `{{event.link}}`,
|
||||
`{{event.start}}`, `{{balance}}`, and `{{payment.link}}` (a live Yoco link for each recipient's
|
||||
outstanding balance).
|
||||
- **Broadcasts** — ad-hoc email/WhatsApp to any users or addresses, not tied to
|
||||
one event.
|
||||
- **Message type** — Event update or News & announcements; news only reaches people
|
||||
who opted in (see [Privacy](#privacy-popia)).
|
||||
- **Automations** — schedule a sequence of lifecycle emails for an event
|
||||
(pre-event, final reminder, thank-you, promo for another event).
|
||||
- **Manage scheduled** — view, edit or delete queued jobs per channel. Sends
|
||||
run in the background and are purged 24 h after sending.
|
||||
|
||||
**WhatsApp** is connected through the WAWP API: an admin links a number in
|
||||
Site Settings → WhatsApp (QR code or pairing code), with status, restart and
|
||||
logout controls. Disconnected sessions are recovered automatically.
|
||||
|
||||
---
|
||||
|
||||
## User dashboard (My Events)
|
||||
|
||||
- Registrations with status badges, event thumbnails, and Closed/Past/Inactive
|
||||
tags. Past and closed events are hidden by default.
|
||||
- Registration detail: itemised bill (early-bird lines grouped), payments,
|
||||
**Invoice** and **Receipt** buttons, edit, cancel, **Make payment**.
|
||||
- Upcoming events and tickets side by side, with bulk ticket email/WhatsApp.
|
||||
- **Ticket transfer** — offer a ticket to someone else before the event by typing
|
||||
their name and email/phone (no user search, and nothing reveals whether they have an
|
||||
account). They get a link to accept or decline; the ticket only moves once they
|
||||
accept, and the sender can cancel until then (offers expire after 7 days or at the
|
||||
event start). On accepting they get a new ticket and QR code, and an inactive account
|
||||
with an activation link if they're new. The old code stops working, and scanning it says it
|
||||
was transferred, both online and in offline-mode sync reports. One place can be split
|
||||
off a ticket covering several people. Billing stays with the payer. It's not allowed
|
||||
once a ticket has been scanned, and it can be turned off per event (supervisors can
|
||||
always transfer, from At the door → Tickets). On youth events the new holder needs
|
||||
their own parental consent, and the previous holder's form answers are removed.
|
||||
Every transfer is in the audit log.
|
||||
- **Payment history** (`/dashboard/user/payments`) — paginated, with filters by
|
||||
date, method and payment/refund.
|
||||
- **Donate** page.
|
||||
- **Forms** — complete outstanding attendee forms.
|
||||
- **Profile & Security** — edit details and notification preference, change
|
||||
password, see recent account activity (logins, password changes, device),
|
||||
sign out everywhere, deactivate or delete my data.
|
||||
|
||||
---
|
||||
|
||||
## Staff tools
|
||||
|
||||
- **Staff dashboard** — scan stats and quick actions.
|
||||
- **Ticket scanning** (`/dashboard/staff/ticket-scanning`) — camera QR scanner
|
||||
with event and section filters.
|
||||
- **Event tickets & printing** (`/dashboard/staff/event-tickets`) — list, search
|
||||
and print an event's tickets.
|
||||
- **Kids check-in** (`/dashboard/staff/kids`) and the **room screen**
|
||||
(`/dashboard/staff/kids/rooms`) — see [Kids check-in](#kids-check-in).
|
||||
- **Volunteers** (`/dashboard/staff/volunteers`) — today's roster, ticking volunteers in and the
|
||||
check-in QR code — see [Volunteer rosters](#volunteer-rosters).
|
||||
|
||||
---
|
||||
|
||||
## Supervisor tools
|
||||
|
||||
- **Choosing an event** (staff and supervisor pages: scanner, event tickets, at the door, payments,
|
||||
manual registration, email and WhatsApp, forms, attendance, consent, waitlist, allocations,
|
||||
bundles, offline scans, kids and volunteer set-up, manage registrations, kiosk): a searchable
|
||||
picker instead of a long dropdown. It opens on upcoming events, soonest first; **Show past
|
||||
events** lists past ones (latest first), and typing searches every event by name, campus or date.
|
||||
Arrow keys, Enter and Escape work. `components/shared/EventPicker.tsx`.
|
||||
- **Dashboard** — **Today** (each event or session on today: checked in so far
|
||||
against places, children in now, volunteers here; money in today and this
|
||||
week) and **Waiting for you** (unpaid registrations for the next two weeks,
|
||||
parental consent outstanding, waitlists, cover requests, roster gaps; for
|
||||
admins also cashups due, payments to reconcile, privacy requests, failed
|
||||
webhooks — each links to where it's dealt with); then KPIs (active events,
|
||||
revenue, donations, registrations, tickets sold, each vs. the previous month),
|
||||
revenue trend chart, top events, and recent scans. Staff see Today too.
|
||||
- **Command palette (Ctrl K / ⌘K)** — anywhere in the dashboard: pages, settings
|
||||
and reports for the role, actions ("New event", "Scan tickets"…), and search:
|
||||
events; payments by amount ("R450") for supervisors; people and registrations
|
||||
for admins. Follows campus scoping.
|
||||
- **Manage events** — the 9-step event wizard, ticket options, variants,
|
||||
sections, form and attachments.
|
||||
- **At the door** — search by name/phone/ticket ID, walk-in registration,
|
||||
payments, a **Check-In** tab for redeeming main tickets by quantity, and
|
||||
ticket printing/resending.
|
||||
- **Self-service kiosk** (`/self-service`) — a touchscreen page a supervisor
|
||||
unlocks for an event, where visitors register themselves. Existing accounts
|
||||
are matched by email/phone, and any change to their details needs
|
||||
confirmation.
|
||||
- **Manual registration** — register someone on their behalf and record their
|
||||
payment.
|
||||
- **Payments** — tabs for Payment, Refund, Donations (assign/unassign),
|
||||
Reconcile (Yoco transactions), and Payment Link.
|
||||
- **Coupon codes** (`/dashboard/supervisor/coupons`) — create, edit and turn off
|
||||
discount codes, and see who used each one.
|
||||
- **Rooms & groups** (`/dashboard/supervisor/allocations`):
|
||||
- Per event, allocation sets such as "Rooms", "Small groups" or "Buses". Each set
|
||||
has groups with an optional capacity, gender restriction and leader (staff).
|
||||
- A drag-and-drop board, plus auto-allocate: fill evenly, respecting capacity and
|
||||
gender, keeping bookings together or splitting them.
|
||||
- Printable per-group and master lists. On youth events they can include medical
|
||||
details, and viewing those is audited.
|
||||
- The group can show on tickets and in My Events.
|
||||
- Email and WhatsApp attendees can be filtered to one group.
|
||||
- Leaders see their people under Staff → **My groups**.
|
||||
- Works on named attendees. Events can ask each person's gender.
|
||||
- **Offline scanning** (`/dashboard/supervisor/offline-scans`) — devices holding
|
||||
offline locks (with force release) and sync reports to review.
|
||||
- **Waitlist** (`/dashboard/supervisor/waitlist`) — the queue per event: offer a
|
||||
place now, move people up or down, or remove them.
|
||||
- **Parental consent** (`/dashboard/supervisor/consent`) — consent status per
|
||||
attendee on youth events, resend (one or all pending), re-request after the
|
||||
consent text changes, and a printable medical & emergency list (audited).
|
||||
- **Email attendees / WhatsApp attendees** — bulk and scheduled messaging.
|
||||
- **Forms** — view, filter, edit and print form responses.
|
||||
- **Reports** — see [Reports](#reports).
|
||||
- **Site banner** (`/set-banner`) — set the announcement bar.
|
||||
|
||||
---
|
||||
|
||||
## Admin tools
|
||||
|
||||
- **Admin dashboard** — same KPIs as supervisor, plus admin quick actions.
|
||||
- **Manage users** — server-side search and filters (role, active), paging,
|
||||
edit role and notification preference, revoke sessions, delete or
|
||||
**anonymise** personal data.
|
||||
- **Data requests** — POPIA correction and deletion requests (see
|
||||
[Privacy](#privacy-popia)).
|
||||
- **Registrations** — all registrations, with filters (event, status, text),
|
||||
status counts, revenue and outstanding totals, and per-registration options,
|
||||
form answers and payments (with who recorded each one). **Bulk actions** on
|
||||
ticked registrations (or all shown): message (email/WhatsApp), mark paid
|
||||
(records the balance by method), move to another ticket (same tickets and QR
|
||||
codes, repriced), put in a room or group, export to Excel, cancel — each
|
||||
through the same rules as one at a time, with a result per registration.
|
||||
- **Saved filters** — on Manage registrations, Users, Events and Reports: name the
|
||||
current filters, apply one with a click, star one as the default for the page
|
||||
(not applied over a deep link). Per person, on the server.
|
||||
- **Cashup** — see below.
|
||||
- **Corrections** (`/dashboard/admin/corrections`, admins only) — for any event,
|
||||
past and closed ones too: registrations missing tickets, with forms to fill in,
|
||||
or owing money. **Issue all missing tickets** at once (forms left for later),
|
||||
fill in a form, **issue tickets — pay later** (balance still owed), **make it
|
||||
free** (the balance written off as a complimentary discount, so income stays
|
||||
what was paid; not on closed events), and **check people in (or undo) after the
|
||||
event** for any session. Optionally send the tickets. Every correction is in
|
||||
the audit log with the reason given.
|
||||
- **Audit log** (`/dashboard/admin/audit-log`) — who did what and when for
|
||||
refunds, donation assign/unassign, manual registrations, staff
|
||||
cancellations, event create/update/delete, settings changes, and coupon codes
|
||||
(created, edited, turned off, applied or removed by staff), and every later feature's admin
|
||||
actions. Search by person, target or IP; filter by action, role and dates; 50 a page.
|
||||
- **Site settings** — see below.
|
||||
|
||||
---
|
||||
|
||||
## Cashup & event costs
|
||||
|
||||
- **Event costs** — once-off or per-item costs (optionally linked to a ticket
|
||||
option), with a "paid from takings" method so cash on hand is correct.
|
||||
- **Expected vs. actual** — expected takings per method (cash/card/EFT/other)
|
||||
compared with actual amounts, with variance shown.
|
||||
- **Cash denomination counts** — entered per staff member, at any time. The
|
||||
event's actual cash is the sum of these counts.
|
||||
- **Payment accountability by staff member** — what each person recorded, by
|
||||
method, with live cash variance.
|
||||
- **Close / quick close / reopen** an event — closing locks it from further
|
||||
edits and hides it from the kiosk and user actions. Drafts are saved as you
|
||||
go.
|
||||
- **Report tab** — a read-only cashup summary, shown automatically once the
|
||||
event is closed.
|
||||
- **Cashup audit trail** — every close/reopen with totals and who did it.
|
||||
|
||||
---
|
||||
|
||||
## Reports
|
||||
|
||||
A full-width workspace with shared filters (events, searchable, with "Select these N" for the matches; date range with presets,
|
||||
include past/inactive/closed) and a searchable grid of reports, each opening in
|
||||
a viewer with its own filters, stat tiles and bar charts.
|
||||
|
||||
| Category | Reports |
|
||||
|----------|---------|
|
||||
| Financial | Payments between dates · Revenue summary (by method) · Revenue detailed · Finance report (revenue & costs, after discounts) · Profit report · Discounts (coupon codes) |
|
||||
| Registration | Registration funnel (views → started → submitted → paid, daily trend, by source / device / ticket option) · Attendees per event (grouped by option) · Registration type counts · Master orders breakdown · Registration status breakdown (count by registration or ticket quantity) · Parental consent status · Medical & emergency list · Feedback summary (response rate, average ratings, choice breakdowns, comments; compare events) |
|
||||
| Ticketing | Ticket usage summary |
|
||||
| Donations | Donations breakdown (used / unused per event, plus the sponsorship pool) |
|
||||
| Cashup | Cashup reconciliation · Cashup audit trail |
|
||||
| Other | Series: year on year (a series' events side by side — registrations, tickets, income, checked in, attendance rate, change from the one before) |
|
||||
|
||||
**Export:** Print, branded PDF download, styled Excel (`.xlsx`) workbook,
|
||||
Email (to yourself), or WhatsApp (the PDF to your own number). Dashboard tiles
|
||||
deep-link into reports with `?report=&range=`.
|
||||
|
||||
---
|
||||
|
||||
## Site settings & setup wizard
|
||||
|
||||
**Setup wizard** (`/setup`) — on a fresh database, walks through organisation
|
||||
details, the first admin account and branding. No manual seeding needed.
|
||||
|
||||
**Site Settings** (`/dashboard/admin/settings`) — stored in the database and
|
||||
applied without a restart. Secrets are encrypted with AES-256-GCM.
|
||||
|
||||
| Tab | Contains |
|
||||
|-----|----------|
|
||||
| Organisation | Name, tagline, contact email/phone, address (with map link) |
|
||||
| Campuses | Off by default. Turn on, then add, order, archive or delete campuses (name, web address, address, contact, colour, logo, default event location, daily-summary recipients) |
|
||||
| Branding | Primary/secondary/accent colours (with a readability warning and a darker shade offered when the primary is too light), logo, favicon, colours suggested from the logo, live website/email preview on desktop and mobile |
|
||||
| Notifications | Registrations inbox and admin notification emails |
|
||||
| Email | SMTP host/port/TLS/user/password/from, with a "Test connection" button |
|
||||
| Legal | Operator, Information Officer, website, effective date for the Terms/Privacy pages |
|
||||
| WhatsApp | WAWP credentials, connect a number, status/restart/logout |
|
||||
| Payments | Online payment providers: Enabled toggle and order; PayFast merchant ID/key, passphrase and sandbox/live; Yoco's secret key (masked, test/live), webhook secret (generate by registering with Yoco, or enter), list/delete the account's webhooks |
|
||||
| Backups | List, run now, download database backups |
|
||||
|
||||
See [SETTINGS.md](./SETTINGS.md) for the default of every setting.
|
||||
|
||||
---
|
||||
|
||||
## Event series
|
||||
|
||||
Separate events grouped on one page — every year's camp, the monthly men's breakfast (each event
|
||||
keeps its own registrations; for one event on several dates see multi-day events).
|
||||
|
||||
- **Event series** page (supervisors): name, web address (`/series/<slug>`), description, picture;
|
||||
each series lists its events (campus-scoped supervisors see only their campuses' events in it)
|
||||
and its number of followers. Admins can delete a series (its events stay).
|
||||
- **Series box** in the event editor's Basic details. A copied event keeps its series. A series can
|
||||
have events at several campuses.
|
||||
- **Public series page**: upcoming events as cards, then past events. Event pages in a series show
|
||||
"Part of …" and **Next in this series** (the next public event in it).
|
||||
- **Follow a series**: signed-in people follow on the series page; when a new event in it goes live
|
||||
(before it starts) they get one email, sent as News & announcements (opted-in only, with an
|
||||
unsubscribe link). The `series` job runs every 15 minutes.
|
||||
- **Year on year**: Reports → Series: year on year (or **Compare** on the Event series page)
|
||||
compares the series' events — registrations, tickets, income, checked in (average per session on
|
||||
multi-session events), attendance rate — each against the one before.
|
||||
- **Season passes**: on the Event series page, a pass gives a ticket (and variant) at each event
|
||||
ticked, at one price (optional sale end; stops when its first event starts; no youth events,
|
||||
staff-only or per-session tickets). Buyers choose how many on the series page and are registered at
|
||||
every event at once with one payment (or tickets at once when free; "Pay now" later if online
|
||||
payment isn't possible). The price is split over the events in proportion to their normal prices;
|
||||
each event gets its own registration line and payment for its share, so cashups stay per event.
|
||||
Pass registrations aren't repriced, take no codes and can't be edited. Events and price lock once
|
||||
sold.
|
||||
|
||||
## Multi-campus
|
||||
|
||||
For a church with several campuses in one install (Site settings → Campuses, off by
|
||||
default — single-campus churches never see campus fields).
|
||||
|
||||
- **Events** belong to one campus or to **All campuses** (church-wide). Choosing a campus fills in
|
||||
its default location. Moving an event to another campus is in the audit log.
|
||||
- **Public site:** a campus filter on the events page, remembered per visitor and starting on their
|
||||
home campus; a campus shows its own events plus church-wide ones. The campus shows on event cards,
|
||||
the event page and ticket PDFs. Each campus has a page at `/campus/<slug>` (also in the sitemap).
|
||||
- **People** choose a home campus on their profile.
|
||||
- **Reports and dashboards:** a campus filter on Reports (every report and the funnel) and on the
|
||||
admin/supervisor dashboards' month-over-month tiles, with a church-wide total.
|
||||
- **Messages:** "Everyone at a campus" in Email and WhatsApp broadcasts — home campus, plus (ticked)
|
||||
people who registered for its events in the last 12 months. News consent still applies.
|
||||
- **Daily summary:** campus recipients get the summary of their campus's events.
|
||||
- **Turning it off** hides everything campus-related; nothing is deleted. A campus with events can't
|
||||
be deleted, only archived.
|
||||
- **Staff for some campuses** (Admin → Users → "Limit to campuses"): a supervisor or staff member
|
||||
sees only their campuses' events plus events for all campuses — every list, report, dashboard
|
||||
and scanner follows it. For church-wide events they can scan, register people and take payments
|
||||
at the door, but not change, cash up or refund them. The site banner, payment reconciliation and
|
||||
donations not linked to an event are for admins and unscoped supervisors; broadcasts only reach
|
||||
people at their campuses or their events' attendees; coupons only for their campuses' events.
|
||||
Another campus's records answer "not found"; the scanner says which campus a ticket is for.
|
||||
Admins are never limited; limits are ignored while campuses are off.
|
||||
|
||||
---
|
||||
|
||||
## Kids check-in
|
||||
|
||||
Secure check-in and pickup for children's ministry, run from a staff desk and fully digital — no
|
||||
label printers.
|
||||
|
||||
- **Setup** (Supervisor → Kids check-in setup, `/dashboard/supervisor/kids`): per event, a
|
||||
**kids ticket** (a main ticket covering the whole event — "Add a free Kids check-in ticket"
|
||||
makes one) and **rooms** (an allocation set; each room has an age range, capacity and children
|
||||
per leader), then switch it on. Weekly kids church = one event with a session per Sunday.
|
||||
- **Families** are kept between events: parents add their children under My account → **Kids**
|
||||
(`/dashboard/user/kids`) — date of birth, allergies, medical and custody notes — and their
|
||||
**authorised adults** (name, phone, relationship; no account needed). The page shows a family QR
|
||||
code for the desk.
|
||||
- **Desk** (`/dashboard/staff/kids`): find the family (name, phone or family QR) or add one, tick
|
||||
the children (room suggested from the age: the narrowest range that isn't full), check in. The
|
||||
family gets a **4-character pickup code** for the day or session (no 0/O/1/I), sent to the parents
|
||||
by WhatsApp/email and shown on their Kids page with a QR code; it can also go to an authorised
|
||||
adult. A **"write on the sticker"** panel shows first name, room, code and ALLERGY/MEDICAL in
|
||||
large print to copy onto a blank sticker.
|
||||
- **Check-out:** type or scan the code, see the children on it, the parents, the authorised adults
|
||||
and any custody notes, record who collected. Anyone with the code can collect. A **wrong code**
|
||||
is refused, raises an alert on the room screens and is audited; **without the code** needs who
|
||||
and why (audited).
|
||||
- **Room screen** (`/dashboard/staff/kids/rooms`): live cards per room — code, allergies, medical
|
||||
and custody notes, parents and authorised adults — "I'm on duty", counts and full/over-ratio
|
||||
warnings, **Call parent** (WhatsApp/email, shown on the parent's page), move to another room,
|
||||
check out without code, wrong-code alerts.
|
||||
- **Offline desk:** "Get ready for offline" downloads the families and 20 pickup codes reserved for
|
||||
the device. Offline, the desk checks in (no messages) and checks out children it checked in
|
||||
itself; "Sync" uploads everything and says if a family got another code elsewhere.
|
||||
- **Attendance:** each child gets a free place on the kids ticket under the parent the first time
|
||||
(registration, attendee, ticket), and each check-in is a ticket usage — so the attendance
|
||||
register, reports and campus scoping include them.
|
||||
- **Privacy:** allergies, medical and custody notes encrypted, never in messages; custody notes
|
||||
changed only by parents, supervisors and admins (audited); opening the desk/room screens and
|
||||
offline downloads are in the access log; a child's profile is deleted after **6 months** without
|
||||
a check-in (Admin → Privacy → Retention).
|
||||
- **Volunteers in kids rooms:** a serving role linked to a room puts its volunteers on duty there
|
||||
when they check in; the room screen lists who is rostered but not in yet.
|
||||
- The kids ticket is never offered publicly (left out of public event pages, refused on public
|
||||
registration).
|
||||
|
||||
---
|
||||
|
||||
## Volunteer rosters
|
||||
|
||||
Who serves where, for an event or each session.
|
||||
|
||||
- **Roles** (Supervisor → Volunteer rosters, `/dashboard/supervisor/volunteers`): name, people
|
||||
needed, optional shift times (default: the session's or event's times), description, and
|
||||
optionally a kids room. On a multi-session event each role is for one session. A role can't be
|
||||
deleted once someone has checked in for it.
|
||||
- **Volunteering** (My account → Serving, `/dashboard/user/serving`): anyone with an account signs
|
||||
up for a role that isn't full; supervisors can also put people on (beyond the number needed).
|
||||
Nobody can be in two roles whose shifts overlap. `?event=<id>` opens one event (the sign-up link
|
||||
supervisors share, also for hidden events). Volunteers are told when they're put on, taken off,
|
||||
or a role is deleted, and get a **reminder the day before**.
|
||||
- **Swaps:** "Can't make it" asks for cover — the event's other volunteers are told and the request
|
||||
shows on everyone's Serving page; the first to accept takes the place at once (no approval). The
|
||||
event's notification recipients (or its creator) are emailed about every swap and withdrawal.
|
||||
- **Check-in:** volunteers scan the event's **check-in QR code** (Check-in QR tab, or Staff →
|
||||
Volunteers) with their phone camera → `/serve/check-in` → every shift of theirs on that day is
|
||||
checked in. Staff can tick people in by hand (and undo). Check-in opens on the day of the shift
|
||||
and closes when it ends.
|
||||
- **Kids rooms:** checking in for a role linked to a kids room puts the volunteer on duty in that
|
||||
room (counted for the ratio, like "I'm on duty"); undoing the check-in takes them off.
|
||||
- **Volunteer ticket** (off by default): choose a main ticket of the event, or add a free
|
||||
"Volunteer" ticket. Volunteers without a ticket get a free place on it (in My Events); it's
|
||||
cancelled when they leave the roster (unless it was scanned), moves with a swap, and is never
|
||||
offered publicly.
|
||||
- **Reports:** roster sheet (phone numbers, check-in time and how), printable; fill rate per event;
|
||||
**hours served** per person (checked-in shifts × shift length) over all events or one.
|
||||
- **Read-only licence:** new roles and sign-ups are blocked; check-ins, swaps and withdrawals keep
|
||||
working.
|
||||
|
||||
---
|
||||
|
||||
## Accounts & security
|
||||
|
||||
- Register, log in, forgot/reset password, activate account (for accounts
|
||||
created on someone's behalf).
|
||||
- JWT authentication (HS256 pinned) with **session revocation** (token
|
||||
versioning) — users can sign out everywhere, and admins can do it for any user.
|
||||
- **Two-factor authentication** — a 6-digit login code by email or WhatsApp
|
||||
(10-minute expiry, 5 attempts, resend), with "Trust this device for 30 days".
|
||||
**Required for Admins and Supervisors**: their next login sends a code that turns
|
||||
it on, and they can change the channel but not turn it off (skipped only when no
|
||||
email or WhatsApp channel can deliver a code; `TWO_FACTOR_REQUIRED_ROLES=false`
|
||||
is the emergency switch). Optional for everyone else from Profile & Security.
|
||||
Admins can reset it for a locked-out user, and the kiosk asks for the code at
|
||||
setup.
|
||||
- **Login lockout** after repeated failed attempts, plus login rate limiting
|
||||
(`TRUST_PROXY` to read real IPs behind a proxy).
|
||||
- **Security event log** — logins, password changes and resets, with device
|
||||
and IP.
|
||||
- **Account closure** — deactivate, or close and ask for the personal data to be
|
||||
deleted (see [Privacy](#privacy-popia)).
|
||||
- **Upload hardening** — server-generated filenames, and uploads served with a
|
||||
sandbox CSP and `nosniff`.
|
||||
|
||||
---
|
||||
|
||||
## Privacy (POPIA)
|
||||
|
||||
Tools that help a church handle personal information the way POPIA expects. They
|
||||
support compliance; wording and retention choices are for the church's Information
|
||||
Officer.
|
||||
|
||||
**For everyone** — the **Privacy** page (`/dashboard/user/privacy`):
|
||||
|
||||
- **News & announcements** opt-in per channel (email, WhatsApp), with the history of
|
||||
every choice: when, and how (sign-up, privacy page, unsubscribe link, STOP reply…).
|
||||
Sign-up has an unticked opt-in box; accounts that never answered are asked once
|
||||
after logging in.
|
||||
- **Download my data** — readable PDF, or the complete copy as JSON.
|
||||
- **Correct my data** — profile fields directly; anything else as a correction request.
|
||||
- **Delete my account** — closes the account at once and files a deletion request.
|
||||
|
||||
**Bulk messages** are either an **Event update** (about an event the recipients
|
||||
registered for; always sent) or **News & announcements** (only to people who opted in
|
||||
on that channel and haven't unsubscribed). News emails carry an unsubscribe link and
|
||||
one-click `List-Unsubscribe` headers; news WhatsApps end with "Reply STOP" and a link.
|
||||
Event updates say why they were sent and link to the preferences. A STOP reply on
|
||||
WhatsApp turns off WhatsApp news (through WAWP's `message` webhook, checked against a
|
||||
secret in the webhook URL).
|
||||
|
||||
**Privacy notice** (`/legal/privacy`) — edited in **Admin → Privacy (POPIA)**
|
||||
(`/dashboard/admin/privacy`): sections start from the built-in text; drafts, preview,
|
||||
and published, numbered versions (earlier ones stay readable with `?version=N`).
|
||||
Placeholders (`{org}`, `{ioName}`, `{ioEmail}`, `{website}`, `{orgEmail}`,
|
||||
`{medicalRetentionDays}`, `{operators}`) are filled in from Site settings and the
|
||||
operator register. A version marked as a significant change is accepted once by everyone
|
||||
after their next login. People agree to the notice at sign-up and when they activate an account
|
||||
made for them; anyone who never has is asked once after login. When the built-in text changes
|
||||
in an update, a site with its own published version sees what changed in the editor, with each
|
||||
changed section marked (**Use the new text**, **Use all the new text**, **Add** missing sections,
|
||||
**Done — hide this**). The "Change my cookie choice" button shows above the cookie section. The
|
||||
contact page shows the Information Officer.
|
||||
|
||||
**Registers and logs** (same admin page):
|
||||
|
||||
- **Operators** — the services that process personal information (payment, WhatsApp,
|
||||
email, hosting, maps, error monitoring), what each receives and where; those in use
|
||||
are listed in the notice.
|
||||
- **Consent log** — news opt-ins/opt-outs, privacy notice acceptances and parental consent
|
||||
answers, searchable.
|
||||
- **Access log** — every bulk export or view of personal information (reports, attendance
|
||||
registers, certificates, group lists, form answers, consent and medical lists, backups)
|
||||
and every "view as" session, with the number of records. Children's and medical
|
||||
information is flagged (medical lists, and anything about a youth event).
|
||||
- **Retention** — how long each kind of personal information is kept, applied by a nightly
|
||||
job: inactive accounts anonymised after 5 years (warning 30 days before; never staff
|
||||
roles or people with an upcoming registration), form answers deleted 12 months after
|
||||
the event, login history kept 24 months, payer details in payment notifications removed
|
||||
after 24 months, audit/access logs kept 5 years. The notice's `{retention}` placeholder
|
||||
lists them.
|
||||
- **Breaches** — the register of security compromises, with when the Information Regulator
|
||||
and the people affected were told, and drafts of both notifications.
|
||||
- **Readiness** — a scored checklist of what's set up, each item linking to its fix.
|
||||
|
||||
**For admins** — **Data requests** (`/dashboard/admin/data-requests`, searchable, closed ones paged): correction and
|
||||
deletion requests with a 30-day due date, emailed to the Information Officer and
|
||||
admins, reminded daily when due within a week. Completing a deletion anonymises the
|
||||
person: name, contact details, the people they registered, form answers, consent
|
||||
details, sponsor names, login history and payer details in provider notifications are
|
||||
removed; payments, registrations, tickets and check-ins stay as "Deleted User". It
|
||||
waits while they have a registration for an upcoming event. Everything is in the audit
|
||||
log.
|
||||
|
||||
---
|
||||
|
||||
## Accessibility
|
||||
|
||||
Built to WCAG 2.2 AA on the public pages, sign-in, registration, payment, My Events and the
|
||||
self-service kiosk (1.50.0): "Skip to main content" link, visible keyboard focus, labelled fields,
|
||||
named buttons (ticket quantities say "Add one …"), errors announced as they appear, popups that
|
||||
trap focus and close with Escape, readable contrast with underlined in-text links, and "reduce
|
||||
motion" respected. Branding warns when the primary colour is too light for white text and
|
||||
suggests a darker shade. axe-core checks and keyboard tests in the e2e suite
|
||||
(`e2e/accessibility.spec.ts`) keep it that way.
|
||||
|
||||
---
|
||||
|
||||
## Help system
|
||||
|
||||
A floating **"Need help?"** button on every page opens a page-specific guide
|
||||
(tabs, quick links). Every page has dedicated content (`frontend/src/content/help/`),
|
||||
falling back to a general guide.
|
||||
|
||||
---
|
||||
|
||||
## Outbound webhooks
|
||||
|
||||
Site settings → **Webhooks** (admins): send what happens to other systems as it happens.
|
||||
|
||||
- **Endpoints**: name, https address, and the event types to send — registration created / paid /
|
||||
cancelled, payment received / refunded, ticket checked in, account created, event published.
|
||||
Switch off, edit, delete, **Send test**, **New secret**.
|
||||
- **Messages**: JSON `{ id, type, createdAt, data }` (registration with items and totals, payment,
|
||||
check-in with session, person, event); headers `X-CrossEvents-Event`, `X-CrossEvents-Delivery` and
|
||||
`X-CrossEvents-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<body>">` with the endpoint's secret.
|
||||
- **Delivery log** per endpoint (30 days): status, tries, response code or error, the full message,
|
||||
**Resend**; filter by status and **Load older**. Retries after 1 min, 5 min, 30 min, 2 h, 12 h, then failed.
|
||||
- Every path that registers, pays, cancels, refunds or checks in is covered (Prisma client
|
||||
extension); rolled-back changes send nothing. Kids check-in and volunteer tickets are never sent.
|
||||
- https and public addresses only (DNS checked at each send, redirects not followed). Each endpoint
|
||||
is added to the operator register; deliveries are deleted after 30 days and with an account.
|
||||
- **How webhooks work** (1.50.2), a guide on the tab (open until the first webhook is added): the
|
||||
envelope and headers, retries and duplicates, checking the signature (Node.js and PHP examples),
|
||||
Zapier/Make set-up, and a copyable example message for every event type. The examples come from
|
||||
`EVENT_TYPES[].example` in `utils/webhooks.js`; a test keeps them the same shape as what is sent.
|
||||
|
||||
## Background jobs
|
||||
|
||||
Timed jobs run on a job queue in Postgres (pg-boss, `backend/src/jobs/index.js`): each
|
||||
runs once per schedule even with several server processes, every run is recorded,
|
||||
failed runs are retried twice, and a slow run never overlaps the next. Admin → Site
|
||||
Settings → Background jobs shows each job's schedule, next run and last 10 runs, with
|
||||
"Run now". Times are in `APP_TIMEZONE` (default Africa/Johannesburg). Change a schedule
|
||||
with `JOB_SCHEDULE_<NAME>` (cron); `JOBS_ENABLED=false` turns them all off. If the queue
|
||||
can't start, the same jobs run on in-process timers.
|
||||
|
||||
| Job | Schedule |
|
||||
|-----|----------|
|
||||
| Scheduled email/WhatsApp worker | Polls every 30 s (`SCHEDULED_EMAILS_INTERVAL_MS`) and purges sent jobs after 24 h (not on the queue) |
|
||||
| `daily-summary` — daily event summary email | 07:00 daily (`DAILY_SUMMARY_ENABLED=false` to disable) |
|
||||
| `waitlist` — expire unclaimed offers, offer freed places | Every 10 minutes (`WAITLIST_JOB_ENABLED=false`) |
|
||||
| `payment-status` — look up PayFast checkouts (10 min – 3 days old) whose notification never arrived, and record them | Every 15 minutes (`PAYMENT_STATUS_JOB_ENABLED=false`) |
|
||||
| `feedback` — post-event feedback forms and their 3-day reminder | Every 15 minutes (`FEEDBACK_JOB_ENABLED=false`) |
|
||||
| `sessions` — session reminders, and certificates for events that ended in the last 14 days | Every 5 minutes (`SESSION_JOBS_ENABLED=false`) |
|
||||
| `volunteers` — volunteer reminders the day before a shift | Every 15 minutes (`VOLUNTEER_JOBS_ENABLED=false`) |
|
||||
| `series` — email a series' followers when a new event in it goes live | Every 15 minutes (`SERIES_JOBS_ENABLED=false`) |
|
||||
| `webhooks` — send webhook deliveries that are due, retry failures, delete deliveries after 30 days | Every minute (`WEBHOOKS_JOBS_ENABLED=false`) |
|
||||
| `consent` — parental consent reminders, and deleting medical details after events | 09:00 daily (`CONSENT_JOBS_ENABLED=false`) |
|
||||
| `privacy` — remind admins of privacy requests due within a week or overdue | 08:00 daily (`PRIVACY_JOBS_ENABLED=false`) |
|
||||
| `retention` — delete/anonymise personal information past its retention period (Admin → Privacy → Retention) | 03:30 daily (`RETENTION_JOBS_ENABLED=false`) |
|
||||
| `hub-heartbeat` — check in with the Cross Events Hub and pick up licence changes (only once connected) | Every 15 minutes (`HUB_HEARTBEAT_ENABLED=false`) |
|
||||
| `analytics-rollup` — roll raw visit rows older than 90 days into daily totals | 04:15 daily (`ANALYTICS_ROLLUP_ENABLED=false`) |
|
||||
| `backup` — database backup (`pg_dump`, gzipped, 14-day retention) | 02:00 daily (`BACKUP_ENABLED=false`) |
|
||||
| `temp-cleanup` — temp files older than 7 days in `/temp` | 03:00 daily |
|
||||
|
||||
---
|
||||
|
||||
## Operations
|
||||
|
||||
- **Install script** (`scripts/install.sh`) — a fresh Ubuntu server to a running site: Node 20,
|
||||
PostgreSQL, PM2, nginx, HTTPS, configuration, migrations and build; then `/setup`.
|
||||
- **Cross Events Hub** — every install connects with a licence key (`/setup`, or Site settings →
|
||||
Licence) and checks in every 15 minutes with its version, health and totals (no personal
|
||||
information; income as a range). Licences are signed tokens checked on the site, so a Hub outage
|
||||
never switches it off: past the end date there's a grace period (banner for site admins only),
|
||||
then — or when suspended, revoked or not licensed — the site is read-only (events can't be
|
||||
created or edited; no new registrations or payments; tickets still scan, data can be exported).
|
||||
The site checks in 30 seconds after starting and after a licence key is connected. Admins see when an update is available, with
|
||||
**what's new** in each version, and press **Request update**, which tells the provider through the Hub (the site never updates
|
||||
itself). A request can be **withdrawn**; when a newer version comes out after asking, the page shows
|
||||
the version asked for and **Ask for … instead** moves the request on to the newer one. **Not now** hides the update banner until the next version; urgent updates (security or
|
||||
serious bug fixes) can't be put off and show a red banner.
|
||||
- **Notices from the provider** — maintenance and other messages the provider posts in the Hub show as a banner on the dashboard
|
||||
for site admins and supervisors, in their time window; each can be closed (per browser) and stays listed on Site settings →
|
||||
Licence. The provider can email them to the church too.
|
||||
See `docs/hub-protocol.md`.
|
||||
- **`/health`** — status, version, database, background jobs and last backup.
|
||||
- **PM2** (`ecosystem.config.js`) runs backend and frontend, restarting either
|
||||
one above 500 MB of memory.
|
||||
- **Sentry** error monitoring when `SENTRY_DSN` / `NEXT_PUBLIC_SENTRY_DSN` are
|
||||
set.
|
||||
- Unhandled promise rejections are logged and don't crash the server.
|
||||
- Backend status page (`/`); **API v2** (`/api/v2`, 1.51.0 — the only API since 2.0, which removed
|
||||
v1; `/docs` redirects to `/docs/v2`) with one error shape, paged lists and an OpenAPI 3.1 reference at `/docs/v2` (admins). Public
|
||||
events, my account and registrations, registering, cancelling and paying online (1.51.1),
|
||||
signing up, logging in (with the 2FA step), changing my details and checking tickets in (1.51.2;
|
||||
the scanner and at-the-door use it from 1.51.3); the frontend's v2 calls are typed from the
|
||||
OpenAPI document. v1 endpoints with a v2 replacement send `Deprecation` and a `successor-version`
|
||||
link (1.51.3).
|
||||
- **TypeScript backend** (1.51.0): `.ts` files are checked strictly, `.js` compiles as it is;
|
||||
deploys build `dist/`, which `src/index.js` runs.
|
||||
- **Command palette** (Ctrl+K): every page, settings tab, report and quick action for your role.
|
||||
- **Tests** — Jest unit tests in `backend/tests` (`npm test`), and Playwright
|
||||
end-to-end tests in `e2e/` (`npm run test:e2e`) that start their own backend and
|
||||
frontend against a separate, freshly seeded database: public pages, free and paid
|
||||
registration through to check-in and cashup, multi-day check-in, the attendance
|
||||
register and certificates, the event wizard, the kiosk, and the admin jobs page.
|
||||
- **Deploy script** — `scripts/deploy.sh [tag]`, run on the server, backs up the
|
||||
database, checks out the release, migrates, builds and reloads PM2, and goes back to
|
||||
the previous version if a step fails before the reload.
|
||||
- Versioning via git tags and [CHANGELOG.md](./CHANGELOG.md).
|
||||
|
||||
---
|
||||
|
||||
## Page map
|
||||
|
||||
| Path | Who | What |
|
||||
|------|-----|------|
|
||||
| `/` | Public | Home |
|
||||
| `/events`, `/events/[id]` | Public | Event list and detail |
|
||||
| `/campus/[slug]` | Public | A campus's page and its events (while campuses are on) |
|
||||
| `/series/[slug]` | Public | A series' page: upcoming and past events, Follow |
|
||||
| `/[alias]` | Public | Event short link |
|
||||
| `/register/[eventId]` | Public / User | Registration |
|
||||
| `/registration/success` | Public / User | Confirmation, form and pay |
|
||||
| `/pay/[id]` | Public | Pay online: choose a provider, or go on to PayFast |
|
||||
| `/payment/success`, `/payment/failure`, `/payment/cancel` | Public | Return pages after paying online |
|
||||
| `/forms` | Public / User | Attendee forms |
|
||||
| `/contact`, `/legal/terms`, `/legal/privacy`, `/lockdown-rules` | Public | Info pages |
|
||||
| `/login`, `/register`, `/forgot-password`, `/reset-password`, `/activate-account` | Public | Accounts |
|
||||
| `/setup` | First run | Setup wizard |
|
||||
| `/consent/[token]` | Parent/guardian | Give or decline parental consent |
|
||||
| `/waitlist/claim/[token]` | Public | Claim a waitlist place |
|
||||
| `/certificates/verify/[code]` | Public | Check a completion certificate |
|
||||
| `/unsubscribe?t=…` | Public | Unsubscribe from news (link in news emails/WhatsApps) |
|
||||
| `/serve/check-in?code=…` | User (logs in first) | Volunteer check-in (where the event's check-in QR code leads) |
|
||||
| `/self-service` | Supervisor-unlocked | Kiosk |
|
||||
| `/set-banner` | Supervisor | Site banner |
|
||||
| `/dashboard/user` (+ `/payments`, `/donate`, `/forms`, `/profile`, `/privacy`, `/kids`, `/serving`, `/reset-password`) | User | My Events |
|
||||
| `/dashboard/staff` (+ `/ticket-scanning`, `/event-tickets`, `/my-groups`, `/kids`, `/kids/rooms`, `/volunteers`) | Staff | Staff tools |
|
||||
| `/dashboard/supervisor` (+ `/events`, `/event-options`, `/at-the-door`, `/manual`, `/manual-registration`, `/payments`, `/coupons`, `/waitlist`, `/attendance`, `/consent`, `/offline-scans`, `/allocations`, `/kids`, `/volunteers`, `/email-attendees`, `/whatsapp-attendees`, `/forms`, `/reports`) | Supervisor | Supervisor tools |
|
||||
| `/dashboard/admin` (+ `/users`, `/registrations`, `/forms`, `/cashup`, `/cashup/[id]`, `/corrections`, `/audit-log`, `/data-requests`, `/privacy`, `/settings`) | Admin | Admin tools |
|
||||
@@ -0,0 +1,408 @@
|
||||
# Moving to Cross Events 2.0
|
||||
|
||||
Cross Events 2.0 removes version 1 of the API (`/api/…`). Everything the app does has been on
|
||||
version 2 (`/api/v2/…`) since 1.51.16, so **a church that only uses the app has nothing to do** —
|
||||
the update looks the same as any other. This guide is for anyone with their own integration (a
|
||||
script, a website plug-in, a spreadsheet import) that calls the API directly, and for whoever runs
|
||||
the server.
|
||||
|
||||
## What still works without changes
|
||||
|
||||
- **Payment and WhatsApp webhooks.** Yoco, PayFast and WAWP keep posting to the addresses they were
|
||||
registered with: `/api/webhooks/yoco`, `/api/webhooks/payfast`, `/api/webhooks/whatsapp` and the
|
||||
oldest WAWP address, `/api/whatsapp/webhook`. New registrations use `/api/v2/webhooks/…`.
|
||||
- **Links in messages already sent.** "Add to calendar" links (`/api/events/{id}/ics`) and one-click
|
||||
unsubscribe links (`/api/privacy/unsubscribe/{token}/one-click`) answer `308` with their v2
|
||||
address; a mail app's one-click `POST` to the old address is still handled.
|
||||
- **Outbound webhooks** (Site settings → Webhooks) send the same events and payloads as before.
|
||||
- **Pages people open** — event pages, consent forms, ticket transfers, waitlist offers — are app
|
||||
pages, not API addresses, so they were never affected.
|
||||
|
||||
Any other `/api/…` address now answers **`410 Gone`**:
|
||||
|
||||
```json
|
||||
{ "code": "API_V1_REMOVED", "message": "API v1 was removed in Cross Events 2.0. Use /api/v2 — it is described at /docs/v2." }
|
||||
```
|
||||
|
||||
`/docs` (the v1 reference) redirects to `/docs/v2`.
|
||||
|
||||
## How v2 differs
|
||||
|
||||
The full reference is at `/docs/v2` on your site (sign in as an admin), generated from the code so
|
||||
it is always current. The OpenAPI 3.1 document is `GET /api/v2/openapi.json`.
|
||||
|
||||
| | v1 | v2 |
|
||||
|---|---|---|
|
||||
| Answers | whatever each endpoint returned | always `{ "data": … }` |
|
||||
| Lists | plain arrays, some paged | `{ "data": [ … ], "meta": { "page", "limit", "total", "pages" } }`, `?page=` and `?limit=` (most lists up to 100) |
|
||||
| Errors | `{ "message", "code"? }`, often `400` | `{ "error": { "code", "message", "reason"?, "fields"? } }` — `code` is one of a fixed set (`VALIDATION_FAILED`, `UNAUTHENTICATED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`, `READ_ONLY`, `RATE_LIMITED`, `UNAVAILABLE`, `INTERNAL`); v1's `code` is now `reason` |
|
||||
| Input | anything | checked against the documented schema; mistakes are `VALIDATION_FAILED` with `fields` |
|
||||
| Changing a record | mostly `PUT` | `PATCH` for partial changes (events, ticket options, variants, series, users, coupons…) |
|
||||
| Dates | mixed | ISO 8601, UTC |
|
||||
|
||||
Things that behave differently, not just live at a new address:
|
||||
|
||||
- **Signing in:** `POST /api/v2/auth/login` takes `{ identifier, password }` (an email or phone
|
||||
number). If two-step sign-in is on, the answer is `status: "code_sent"` with a `challengeId`;
|
||||
finish with `POST /api/v2/auth/login/code`.
|
||||
- **Signing up:** `POST /api/v2/auth/signup` needs `acceptTerms: true`; the phone number is
|
||||
`phone`. The answer's `data` holds `token` and `user`.
|
||||
- **Checking a ticket in:** `POST /api/v2/checkin/{qrCode}` with `{ people? }` (was `qty`). Every
|
||||
normal result is a `200` with an `outcome` — `checked_in`, `already_used`, `consent_required`,
|
||||
`wrong_event`, … — where v1 used `403`s. Look a ticket up first with `GET /api/v2/checkin/{qrCode}`.
|
||||
- **Paying online:** `POST /api/v2/registrations/{id}/checkout` (the registration is in the path,
|
||||
not the body).
|
||||
- **Cancelling a registration:** `POST /api/v2/registrations/{id}/cancel` (was `DELETE`).
|
||||
- **Staff lists of registrations** are paged (up to 200 a page).
|
||||
- **A suspended or unlicensed site** refuses new events, registrations and payments with
|
||||
`READ_ONLY` / reason `LICENCE_READ_ONLY`.
|
||||
|
||||
## For whoever runs the server
|
||||
|
||||
1. Deploy as usual: `bash scripts/deploy.sh v2.0.0` (it backs up, migrates, builds and rolls back
|
||||
on failure). Run `bash scripts/deploy.sh --check` first if anyone may have changed files by hand.
|
||||
2. Two migrations run: `20261030120000_ai_helpers` (the AI call log) and anything newer listed in the
|
||||
CHANGELOG.
|
||||
3. **AI helpers** need the site connected to the Hub (Site settings → Licence) and a monthly AI cap
|
||||
above R0 on the licence. The Hub must run 1.6.0 or later. With no cap the AI buttons don't show
|
||||
and nothing else changes.
|
||||
4. If something outside Cross Events still calls `/api/…`, it will get `410` after the update — look
|
||||
for those in the nginx access log before updating (`grep -v '/api/v2/' access.log | grep ' /api/'`,
|
||||
leaving out the webhook and link addresses above).
|
||||
5. Passwords are re-hashed with a stronger method the next time each person signs in; nothing to do.
|
||||
|
||||
## Every v1 address and its v2 replacement
|
||||
|
||||
`{id}` is the record's id. `{a|b}` means either. Methods that changed are shown in the v2 column.
|
||||
|
||||
| v1 | v2 |
|
||||
|---|---|
|
||||
| `GET /api/events` | `GET /api/v2/events` |
|
||||
| `GET /api/events/{id}` | `GET /api/v2/events/{id}/full` |
|
||||
| `GET /api/events/{id}/ics` | `GET /api/v2/events/{id}/calendar.ics` |
|
||||
| `GET /api/events/by-alias/{id}` | `GET /api/v2/events/by-alias/{id}` |
|
||||
| `POST /api/events/{id}/options` | `POST /api/v2/events/{id}/ticket-options` |
|
||||
| `PUT /api/events/options/{id}` | `PATCH /api/v2/ticket-options/{id}` |
|
||||
| `DELETE /api/events/options/{id}` | `DELETE /api/v2/ticket-options/{id}` |
|
||||
| `POST /api/events/options/{id}/variants` | `POST /api/v2/ticket-options/{id}/variants` |
|
||||
| `PUT /api/events/variants/{id}` | `PATCH /api/v2/variants/{id}` |
|
||||
| `DELETE /api/events/variants/{id}` | `DELETE /api/v2/variants/{id}` |
|
||||
| `GET /api/events/attachments/status` | `GET /api/v2/attachments/status` |
|
||||
| `POST /api/events/attachments/sync` | `POST /api/v2/attachments/sync` |
|
||||
| `GET /api/events/{id}/attachments` | `GET /api/v2/events/{id}/attachments` |
|
||||
| `POST /api/events/{id}/attachments` | `POST /api/v2/events/{id}/attachments` |
|
||||
| `DELETE /api/events/{id}/attachments/{id2}` | `DELETE /api/v2/events/{id}/attachments/{id2}` |
|
||||
| `GET /api/sections` | `GET /api/v2/sections` |
|
||||
| `POST /api/sections` | `POST /api/v2/sections` |
|
||||
| `PUT /api/sections/{id}` | `PATCH /api/v2/sections/{id}` |
|
||||
| `DELETE /api/sections/{id}` | `DELETE /api/v2/sections/{id}` |
|
||||
| `GET /api/events/{id}/costs` | `GET /api/v2/events/{id}/costs` |
|
||||
| `POST /api/events/{id}/costs` | `POST /api/v2/events/{id}/costs` |
|
||||
| `PUT /api/costs/{id}` | `PATCH /api/v2/costs/{id}` |
|
||||
| `DELETE /api/costs/{id}` | `DELETE /api/v2/costs/{id}` |
|
||||
| `POST /api/uploads/{event-image|logo|favicon}` | `POST /api/v2/uploads/{event-image|logo|favicon}` |
|
||||
| `GET /api/events/all` | `GET /api/v2/events/manage` |
|
||||
| `POST /api/events` | `POST /api/v2/events` |
|
||||
| `PUT /api/events/{id}` | `PATCH /api/v2/events/{id}` |
|
||||
| `DELETE /api/events/{id}` | `DELETE /api/v2/events/{id}` |
|
||||
| `POST /api/events/{id}/copy-from` | `POST /api/v2/events/{id}/copy-from` |
|
||||
| `GET /api/events/{id}/notify-recipients` | `GET /api/v2/events/{id}/notify-recipients` |
|
||||
| `PUT /api/events/{id}/notify-recipients` | `PUT /api/v2/events/{id}/notify-recipients` |
|
||||
| `POST /api/webhooks/{yoco|payfast|whatsapp}` | `POST /api/v2/webhooks/{yoco|payfast|whatsapp}` |
|
||||
| `POST /api/whatsapp/webhook` | `POST /api/v2/webhooks/whatsapp` |
|
||||
| `POST /api/privacy/unsubscribe/{id}/one-click` | `POST /api/v2/unsubscribe/{id}/one-click` |
|
||||
| `GET /api/privacy/me` | `GET /api/v2/me/privacy` |
|
||||
| `PUT /api/privacy/me/news` | `PUT /api/v2/me/privacy/news` |
|
||||
| `GET /api/privacy/me/export` | `GET /api/v2/me/privacy/export` |
|
||||
| `POST /api/privacy/me/requests` | `POST /api/v2/me/privacy/requests` |
|
||||
| `POST /api/privacy/me/notice/accept` | `POST /api/v2/me/privacy/notice/accept` |
|
||||
| `GET /api/privacy/notice` | `GET /api/v2/privacy/notice` |
|
||||
| `GET /api/privacy/unsubscribe/{id}` | `GET /api/v2/unsubscribe/{id}` |
|
||||
| `POST /api/privacy/unsubscribe/{id}` | `POST /api/v2/unsubscribe/{id}` |
|
||||
| `GET /api/privacy/requests` | `GET /api/v2/privacy/requests` |
|
||||
| `POST /api/privacy/requests/{id}/{complete|reject}` | `POST /api/v2/privacy/requests/{id}/{complete|reject}` |
|
||||
| `GET /api/privacy/notice/draft` | `GET /api/v2/privacy/notice/draft` |
|
||||
| `PUT /api/privacy/notice/draft` | `PUT /api/v2/privacy/notice/draft` |
|
||||
| `DELETE /api/privacy/notice/draft` | `DELETE /api/v2/privacy/notice/draft` |
|
||||
| `POST /api/privacy/notice/{publish|builtin-reviewed}` | `POST /api/v2/privacy/notice/{publish|builtin-reviewed}` |
|
||||
| `GET /api/privacy/operators` | `GET /api/v2/privacy/operators` |
|
||||
| `POST /api/privacy/operators` | `POST /api/v2/privacy/operators` |
|
||||
| `PUT /api/privacy/operators/{id}` | `PUT /api/v2/privacy/operators/{id}` |
|
||||
| `DELETE /api/privacy/operators/{id}` | `DELETE /api/v2/privacy/operators/{id}` |
|
||||
| `GET /api/privacy/{consent-log|access-log|readiness|retention|breaches}` | `GET /api/v2/privacy/{consent-log|access-log|readiness|retention|breaches}` |
|
||||
| `PUT /api/privacy/retention` | `PUT /api/v2/privacy/retention` |
|
||||
| `POST /api/privacy/retention/run` | `POST /api/v2/privacy/retention/run` |
|
||||
| `POST /api/privacy/breaches` | `POST /api/v2/privacy/breaches` |
|
||||
| `PUT /api/privacy/breaches/{id}` | `PUT /api/v2/privacy/breaches/{id}` |
|
||||
| `GET /api/admin/{audit-log|jobs|impersonation-sessions}` | `GET /api/v2/admin/{audit-log|jobs|impersonation-sessions}` |
|
||||
| `POST /api/admin/jobs/{id}/run` | `POST /api/v2/admin/jobs/{id}/run` |
|
||||
| `POST /api/admin/impersonate/{end|log}` | `POST /api/v2/me/impersonation/{end|log}` |
|
||||
| `GET /api/admin/impersonate/current` | `GET /api/v2/me/impersonation` |
|
||||
| `POST /api/admin/impersonate/{id}` | `POST /api/v2/admin/impersonate/{id}` |
|
||||
| `GET /api/settings/needs-setup` | `GET /api/v2/setup/needed` |
|
||||
| `GET /api/settings/all` | `GET /api/v2/settings/all` |
|
||||
| `GET /api/settings` | `GET /api/v2/settings` |
|
||||
| `PUT /api/settings` | `PUT /api/v2/settings` |
|
||||
| `POST /api/settings/test-smtp` | `POST /api/v2/settings/test-smtp` |
|
||||
| `POST /api/setup/register` | `POST /api/v2/setup/register` |
|
||||
| `POST /api/setup` | `POST /api/v2/setup` |
|
||||
| `GET /api/hub/{status|notices}` | `GET /api/v2/hub/{status|notices}` |
|
||||
| `POST /api/hub/{connect|heartbeat|update-request|update-snooze}` | `POST /api/v2/hub/{connect|heartbeat|update-request|update-snooze}` |
|
||||
| `POST /api/hub/update-request/cancel` | `POST /api/v2/hub/update-request/cancel` |
|
||||
| `GET /api/outbound-webhooks` | `GET /api/v2/outbound-webhooks` |
|
||||
| `POST /api/outbound-webhooks` | `POST /api/v2/outbound-webhooks` |
|
||||
| `POST /api/outbound-webhooks/deliveries/{id}/resend` | `POST /api/v2/outbound-webhook-deliveries/{id}/resend` |
|
||||
| `PUT /api/outbound-webhooks/{id}` | `PATCH /api/v2/outbound-webhooks/{id}` |
|
||||
| `DELETE /api/outbound-webhooks/{id}` | `DELETE /api/v2/outbound-webhooks/{id}` |
|
||||
| `POST /api/outbound-webhooks/{id}/{rotate-secret|test}` | `POST /api/v2/outbound-webhooks/{id}/{rotate-secret|test}` |
|
||||
| `GET /api/outbound-webhooks/{id}/deliveries` | `GET /api/v2/outbound-webhooks/{id}/deliveries` |
|
||||
| `GET /api/backups` | `GET /api/v2/backups` |
|
||||
| `POST /api/backups/run` | `POST /api/v2/backups/run` |
|
||||
| `GET /api/backups/{id}/download` | `GET /api/v2/backups/{id}/download` |
|
||||
| `GET /api/{yoco|payfast}/config` | `GET /api/v2/payments/{yoco|payfast}/config` |
|
||||
| `PUT /api/{yoco|payfast}/config` | `PUT /api/v2/payments/{yoco|payfast}/config` |
|
||||
| `GET /api/yoco/webhooks` | `GET /api/v2/payments/yoco/webhooks` |
|
||||
| `POST /api/yoco/webhooks` | `POST /api/v2/payments/yoco/webhooks` |
|
||||
| `DELETE /api/yoco/webhooks/{id}` | `DELETE /api/v2/payments/yoco/webhooks/{id}` |
|
||||
| `POST /api/payfast/test` | `POST /api/v2/payments/payfast/test` |
|
||||
| `POST /api/users/login/2fa/resend` | `POST /api/v2/auth/login/code/resend` |
|
||||
| `POST /api/users/forgot` | `POST /api/v2/auth/password/forgot` |
|
||||
| `POST /api/users/reset` | `POST /api/v2/auth/password/reset` |
|
||||
| `POST /api/users/activate` | `POST /api/v2/auth/activate` |
|
||||
| `POST /api/users/revoke-sessions` | `POST /api/v2/me/sessions/revoke` |
|
||||
| `POST /api/users/close-account` | `POST /api/v2/me/close` |
|
||||
| `GET /api/users/activity` | `GET /api/v2/me/activity` |
|
||||
| `POST /api/users/verify-password` | `POST /api/v2/me/verify-password` |
|
||||
| `POST /api/users/2fa/{enable|confirm|disable}` | `POST /api/v2/me/two-factor/{enable|confirm|disable}` |
|
||||
| `GET /api/users/check-exists` | `GET /api/v2/users/exists` |
|
||||
| `POST /api/users/{id}/revoke-sessions` | `POST /api/v2/users/{id}/sessions/revoke` |
|
||||
| `POST /api/users/{id}/anonymize` | `POST /api/v2/users/{id}/anonymize` |
|
||||
| `GET /api/users` | `GET /api/v2/users` |
|
||||
| `GET /api/users/{?!profile$}{id}` | `GET /api/v2/users/{?!profile$}` |
|
||||
| `PUT /api/users/{?!profile$}{id}` | `PATCH /api/v2/users/{?!profile$}` |
|
||||
| `DELETE /api/users/{id}` | `DELETE /api/v2/users/{id}` |
|
||||
| `GET /api/events/admin/all` | `GET /api/v2/admin/events` |
|
||||
| `POST /api/events/{id}/{email|whatsapp}-attendees` | `POST /api/v2/events/{id}/{email|whatsapp}-attendees` |
|
||||
| `POST /api/events/{id}/{email|whatsapp}-attendees/schedule` | `POST /api/v2/events/{id}/{email|whatsapp}-attendees/schedule` |
|
||||
| `POST /api/broadcasts/{preview|send|schedule}` | `POST /api/v2/broadcasts/email/{preview|send|schedule}` |
|
||||
| `POST /api/whatsapp-broadcasts/{preview|send|schedule}` | `POST /api/v2/broadcasts/whatsapp/{preview|send|schedule}` |
|
||||
| `GET /api/scheduled-emails` | `GET /api/v2/scheduled-messages` |
|
||||
| `PATCH /api/scheduled-emails/{id}` | `PATCH /api/v2/scheduled-messages/{id}` |
|
||||
| `DELETE /api/scheduled-emails/{id}` | `DELETE /api/v2/scheduled-messages/{id}` |
|
||||
| `POST /api/automations/schedule` | `POST /api/v2/automations/schedule` |
|
||||
| `GET /api/whatsapp/{config|status|qr}` | `GET /api/v2/whatsapp/{config|status|qr}` |
|
||||
| `POST /api/whatsapp/config` | `GET/PUT /api/v2/whatsapp/config` |
|
||||
| `POST /api/whatsapp/create-instance` | `POST /api/v2/whatsapp/instance` |
|
||||
| `POST /api/whatsapp/delete-instance` | `POST /api/v2/whatsapp/instance` |
|
||||
| `POST /api/whatsapp/{request-code|logout|start|restart}` | `POST /api/v2/whatsapp/{request-code|logout|start|restart}` |
|
||||
| `GET /api/banner` | `GET /api/v2/banner` |
|
||||
| `POST /api/banner` | `GET/PUT /api/v2/banner` |
|
||||
| `GET /api/saved-filters` | `GET /api/v2/saved-filters` |
|
||||
| `POST /api/saved-filters` | `POST /api/v2/saved-filters` |
|
||||
| `PUT /api/saved-filters/{id}` | `PUT /api/v2/saved-filters/{id}` |
|
||||
| `DELETE /api/saved-filters/{id}` | `DELETE /api/v2/saved-filters/{id}` |
|
||||
| `GET /api/dashboard/{today|search}` | `GET /api/v2/dashboard/{today|search}` |
|
||||
| `GET /api/stats/{staff|supervisor|admin|overview}` | `GET /api/v2/stats/{staff|supervisor|admin|overview}` |
|
||||
| `POST /api/analytics/track` | `POST /api/v2/analytics/track` |
|
||||
| `GET /api/analytics/funnel` | `GET /api/v2/analytics/funnel` |
|
||||
| `POST /api/reports/{pdf|excel|email|whatsapp}` | `POST /api/v2/reports/{pdf|excel|email|whatsapp}` |
|
||||
| `GET /api/kids/me` | `GET /api/v2/me/family` |
|
||||
| `POST /api/kids/me` | `POST /api/v2/me/family` |
|
||||
| `PUT /api/kids/me` | `PATCH /api/v2/me/family` |
|
||||
| `DELETE /api/kids/me` | `DELETE /api/v2/me/family` |
|
||||
| `POST /api/kids/me/{children|adults}` | `POST /api/v2/me/family/{children|adults}` |
|
||||
| `PUT /api/kids/me/{children|adults}/{id}` | `PUT /api/v2/me/family/{children|adults}/{id}` |
|
||||
| `DELETE /api/kids/me/{children|adults}/{id}` | `DELETE /api/v2/me/family/{children|adults}/{id}` |
|
||||
| `GET /api/kids/setup-events` | `GET /api/v2/kids/setup-events` |
|
||||
| `GET /api/kids/events` | `GET /api/v2/kids/events` |
|
||||
| `GET /api/kids/events/{id}/{settings|board|families|offline}` | `GET /api/v2/events/{id}/kids/{settings|board|families|offline}` |
|
||||
| `PUT /api/kids/events/{id}/settings` | `PUT /api/v2/events/{id}/kids/settings` |
|
||||
| `POST /api/kids/events/{id}/{families|check-in|check-out|duty|sync}` | `POST /api/v2/events/{id}/kids/{families|check-in|check-out|duty|sync}` |
|
||||
| `GET /api/kids/events/{id}/families/qr/{id2}` | `GET /api/v2/events/{id}/kids/families/qr/{id2}` |
|
||||
| `GET /api/kids/events/{id}/families/{id2}` | `GET /api/v2/events/{id}/kids/families/{id2}` |
|
||||
| `POST /api/kids/events/{id}/families/{id2}/{parents|children|adults}` | `POST /api/v2/events/{id}/kids/families/{id2}/{parents|children|adults}` |
|
||||
| `PUT /api/kids/events/{id}/families/{id2}/children/{id3}` | `PUT /api/v2/events/{id}/kids/families/{id2}/children/{id3}` |
|
||||
| `GET /api/kids/events/{id}/code/{id2}` | `GET /api/v2/events/{id}/kids/code/{id2}` |
|
||||
| `POST /api/kids/check-ins/{id}/{override|page}` | `POST /api/v2/kids/check-ins/{id}/{override|page}` |
|
||||
| `PUT /api/kids/check-ins/{id}/room` | `PUT /api/v2/kids/check-ins/{id}/room` |
|
||||
| `POST /api/kids/alerts/{id}/resolve` | `POST /api/v2/kids/alerts/{id}/resolve` |
|
||||
| `GET /api/volunteers/me` | `GET /api/v2/me/volunteering` |
|
||||
| `GET /api/volunteers/events/{id}` | `GET /api/v2/events/{id}/volunteer-roles` |
|
||||
| `POST /api/volunteers/roles/{id}/sign-up` | `POST /api/v2/volunteer-roles/{id}/sign-up` |
|
||||
| `DELETE /api/volunteers/slots/{id}` | `DELETE /api/v2/volunteer-slots/{id}` |
|
||||
| `POST /api/volunteers/slots/{id}/swap` | `POST /api/v2/volunteer-slots/{id}/swap` |
|
||||
| `DELETE /api/volunteers/swaps/{id}` | `DELETE /api/v2/volunteer-swaps/{id}` |
|
||||
| `POST /api/volunteers/swaps/{id}/accept` | `POST /api/v2/volunteer-swaps/{id}/accept` |
|
||||
| `POST /api/volunteers/check-in` | `POST /api/v2/volunteering/check-in` |
|
||||
| `GET /api/volunteers/manage/events` | `GET /api/v2/volunteering/events` |
|
||||
| `GET /api/volunteers/manage/hours` | `GET /api/v2/volunteering/hours` |
|
||||
| `GET /api/volunteers/manage/events/{id}` | `GET /api/v2/events/{id}/volunteers` |
|
||||
| `GET /api/volunteers/manage/events/{id}/{qr|settings}` | `GET /api/v2/events/{id}/volunteers/{qr|settings}` |
|
||||
| `PUT /api/volunteers/manage/events/{id}/settings` | `PUT /api/v2/events/{id}/volunteers/settings` |
|
||||
| `POST /api/volunteers/manage/events/{id}/roles` | `POST /api/v2/events/{id}/volunteer-roles` |
|
||||
| `PUT /api/volunteers/manage/roles/{id}` | `PATCH /api/v2/volunteer-roles/{id}` |
|
||||
| `DELETE /api/volunteers/manage/roles/{id}` | `DELETE /api/v2/volunteer-roles/{id}` |
|
||||
| `POST /api/volunteers/manage/roles/{id}/assign` | `POST /api/v2/volunteer-roles/{id}/assign` |
|
||||
| `POST /api/volunteers/manage/slots/{id}/check-in` | `POST /api/v2/volunteer-slots/{id}/check-in` |
|
||||
| `DELETE /api/volunteers/manage/slots/{id}` | `POST /api/v2/volunteer-slots/{id}/remove` |
|
||||
| `GET /api/tickets/mytickets` | `GET /api/v2/me/tickets` |
|
||||
| `POST /api/tickets/email` | `POST /api/v2/me/tickets/email` |
|
||||
| `GET /api/tickets/scans/recent` | `GET /api/v2/tickets/scans/recent` |
|
||||
| `GET /api/tickets/scans/stats` | `GET /api/v2/tickets/scans/stats` |
|
||||
| `POST /api/tickets/send-to` | `POST /api/v2/tickets/send` |
|
||||
| `POST /api/tickets/generate` | `POST /api/v2/tickets/generate` |
|
||||
| `PUT /api/tickets/email-sent` | `POST /api/v2/tickets/email-sent` |
|
||||
| `GET /api/tickets/qr/{id}` | `GET /api/v2/tickets/qr/{id}` |
|
||||
| `GET /api/tickets/event/{id}` | `GET /api/v2/events/{id}/tickets` |
|
||||
| `GET /api/tickets/transfer-offer/{id}` | `GET /api/v2/ticket-transfers/{id}` |
|
||||
| `POST /api/tickets/transfer-offer/{id}/{accept|decline}` | `POST /api/v2/ticket-transfers/{id}/{accept|decline}` |
|
||||
| `GET /api/tickets` | `GET /api/v2/tickets` |
|
||||
| `GET /api/tickets/{id}/transfers` | `GET /api/v2/tickets/{id}/transfers` |
|
||||
| `POST /api/tickets/{id}/transfer` | `POST /api/v2/tickets/{id}/transfer` |
|
||||
| `DELETE /api/tickets/{id}/transfer` | `DELETE /api/v2/tickets/{id}/transfer` |
|
||||
| `GET /api/tickets/{id}` | `GET /api/v2/tickets/{id}` |
|
||||
| `GET /api/scan-locks` | `GET /api/v2/scan-locks` |
|
||||
| `POST /api/scan-locks` | `POST /api/v2/scan-locks` |
|
||||
| `GET /api/scan-locks/reports` | `GET /api/v2/scan-locks/reports` |
|
||||
| `POST /api/scan-locks/reports/{id}/review` | `POST /api/v2/scan-locks/reports/{id}/review` |
|
||||
| `GET /api/scan-locks/{id}/snapshot` | `GET /api/v2/scan-locks/{id}/snapshot` |
|
||||
| `POST /api/scan-locks/{id}/{sync|force-release}` | `POST /api/v2/scan-locks/{id}/{sync|force-release}` |
|
||||
| `DELETE /api/scan-locks/{id}` | `DELETE /api/v2/scan-locks/{id}` |
|
||||
| `GET /api/attendance/certificates/verify/{id}` | `GET /api/v2/certificates/verify/{id}` |
|
||||
| `GET /api/attendance/certificates/mine` | `GET /api/v2/me/certificates` |
|
||||
| `POST /api/attendance/certificates/preview` | `POST /api/v2/certificates/preview` |
|
||||
| `GET /api/attendance/certificates/{id}/pdf` | `GET /api/v2/certificates/{id}/pdf` |
|
||||
| `POST /api/attendance/certificates/{id}/revoke` | `POST /api/v2/certificates/{id}/revoke` |
|
||||
| `GET /api/attendance/{id}/export` | `GET /api/v2/events/{id}/attendance/export` |
|
||||
| `POST /api/attendance/{id}/mark` | `POST /api/v2/events/{id}/attendance` |
|
||||
| `POST /api/attendance/{id}/certificates` | `POST /api/v2/events/{id}/certificates` |
|
||||
| `POST /api/attendance/{id}/certificates/send` | `POST /api/v2/events/{id}/certificates/send` |
|
||||
| `GET /api/attendance/{id}/certificates.pdf` | `GET /api/v2/events/{id}/certificates.pdf` |
|
||||
| `GET /api/attendance/{id}` | `GET /api/v2/events/{id}/attendance` |
|
||||
| `GET /api/allocations/my-groups` | `GET /api/v2/me/allocation-groups` |
|
||||
| `GET /api/allocations/event/{id}` | `GET /api/v2/events/{id}/allocations` |
|
||||
| `POST /api/allocations/sets` | `POST /api/v2/allocation-sets` |
|
||||
| `PUT /api/allocations/sets/{id}` | `PATCH /api/v2/allocation-sets/{id}` |
|
||||
| `DELETE /api/allocations/sets/{id}` | `DELETE /api/v2/allocation-sets/{id}` |
|
||||
| `GET /api/allocations/sets/{id}/lists` | `GET /api/v2/allocation-sets/{id}/lists` |
|
||||
| `POST /api/allocations/sets/{id}/{groups|auto}` | `POST /api/v2/allocation-sets/{id}/{groups|auto}` |
|
||||
| `PUT /api/allocations/sets/{id}/assignments` | `PUT /api/v2/allocation-sets/{id}/assignments` |
|
||||
| `DELETE /api/allocations/sets/{id}/assignments` | `DELETE /api/v2/allocation-sets/{id}/assignments` |
|
||||
| `PUT /api/allocations/groups/{id}` | `PATCH /api/v2/allocation-groups/{id}` |
|
||||
| `DELETE /api/allocations/groups/{id}` | `DELETE /api/v2/allocation-groups/{id}` |
|
||||
| `GET /api/payments/providers` | `GET /api/v2/payments/providers` |
|
||||
| `GET /api/payments/providers/settings` | `GET /api/v2/payments/providers/settings` |
|
||||
| `PUT /api/payments/providers/settings` | `PUT /api/v2/payments/providers/settings` |
|
||||
| `GET /api/payments/pay/{id}` | `GET /api/v2/payment-links/{id}` |
|
||||
| `POST /api/payments/pay/{id}` | `POST /api/v2/payment-links/{id}` |
|
||||
| `GET /api/payments/checkouts/open` | `GET /api/v2/payments/open-checkouts` |
|
||||
| `POST /api/payments/checkouts/check` | `POST /api/v2/payments/open-checkouts/check` |
|
||||
| `POST /api/payments/[yoco-]checkout/send` | `POST /api/v2/registrations/{id}/payment-link` |
|
||||
| `GET /api/payments/mypayments` | `GET /api/v2/me/payments` |
|
||||
| `GET /api/payments/admin/stats` | `GET /api/v2/payments/stats` |
|
||||
| `GET /api/payments/registration/{id}` | `GET /api/v2/registrations/{id}/payments` |
|
||||
| `GET /api/payments/event/{id}` | `GET /api/v2/events/{id}/payments` |
|
||||
| `PUT /api/payments/assign-donation` | `POST /api/v2/payments/donations/assign` |
|
||||
| `POST /api/payments/unassign-donation` | `POST /api/v2/payments/donations/unassign` |
|
||||
| `POST /api/payments/refund` | `POST /api/v2/payments/refunds` |
|
||||
| `POST /api/payments/{id}/send-receipt` | `POST /api/v2/payments/{id}/receipt` |
|
||||
| `GET /api/payments` | `GET /api/v2/payments` |
|
||||
| `POST /api/payments` | `POST /api/v2/payments` |
|
||||
| `GET /api/payments/{id}` | `GET /api/v2/payments/{id}` |
|
||||
| `GET /api/cashups/audit` | `GET /api/v2/cashups/audit` |
|
||||
| `GET /api/cashups/event/{id}` | `GET /api/v2/events/{id}/cashup` |
|
||||
| `GET /api/cashups/event/{id}/cash-by-user` | `GET /api/v2/events/{id}/cashup/cash-by-user` |
|
||||
| `PUT /api/cashups/event/{id}/person-cash/{id2}` | `PUT /api/v2/events/{id}/cashup/person-cash/{id2}` |
|
||||
| `PUT /api/cashups/event/{id}/draft` | `PUT /api/v2/events/{id}/cashup/draft` |
|
||||
| `POST /api/cashups/event/{id}/close` | `POST /api/v2/events/{id}/cashup/close` |
|
||||
| `POST /api/cashups/event/{id}/reopen` | `POST /api/v2/events/{id}/cashup/reopen` |
|
||||
| `POST /api/cashups/lines/{id}/pending` | `POST /api/v2/cashup-lines/{id}/pending` |
|
||||
| `GET /api/{provider|yoco}-transactions` | `GET /api/v2/provider-transactions` |
|
||||
| `GET /api/{provider|yoco}-transactions/unreconciled` | `GET /api/v2/provider-transactions/unreconciled` |
|
||||
| `POST /api/{?:provider|yoco}-transactions/{id}/reconcile` | `POST /api/v2/provider-transactions/{?:provider|yoco}/reconcile` |
|
||||
| `POST /api/{?:provider|yoco}-transactions/{id}/ignore` | `POST /api/v2/provider-transactions/{?:provider|yoco}/ignore` |
|
||||
| `POST /api/waitlist` | `POST /api/v2/waitlist` |
|
||||
| `GET /api/waitlist/mine` | `GET /api/v2/me/waitlist` |
|
||||
| `GET /api/waitlist/claim/{id}` | `GET /api/v2/waitlist/claims/{id}` |
|
||||
| `GET /api/waitlist/events/{id}` | `GET /api/v2/events/{id}/waitlist` |
|
||||
| `POST /api/waitlist/{id}/{offer|move|remove}` | `POST /api/v2/waitlist/{id}/{offer|move|remove}` |
|
||||
| `DELETE /api/waitlist/{id}` | `DELETE /api/v2/waitlist/{id}` |
|
||||
| `GET /api/sponsorships/event/{id}` | `GET /api/v2/events/{id}/sponsorship` |
|
||||
| `GET /api/sponsorships/event/{id}/pool` | `GET /api/v2/events/{id}/sponsorship/pool` |
|
||||
| `POST /api/sponsorships/checkout` | `POST /api/v2/sponsorships/checkout` |
|
||||
| `GET /api/consent/events/{id}` | `GET /api/v2/events/{id}/consent` |
|
||||
| `GET /api/consent/events/{id}/medical` | `GET /api/v2/events/{id}/consent/medical` |
|
||||
| `POST /api/consent/events/{id}/{resend-pending|rerequest}` | `POST /api/v2/events/{id}/consent/{resend-pending|rerequest}` |
|
||||
| `POST /api/consent/requests/{id}/resend` | `POST /api/v2/consent-requests/{id}/resend` |
|
||||
| `GET /api/consent/{id}` | `GET /api/v2/consent/{id}` |
|
||||
| `POST /api/consent/{id}` | `POST /api/v2/consent/{id}` |
|
||||
| `GET /api/forms/responses` | `GET /api/v2/form-responses` |
|
||||
| `GET /api/feedback/summary` | `GET /api/v2/feedback/summary` |
|
||||
| `GET /api/feedback/public/{id}` | `GET /api/v2/feedback-forms/{id}` |
|
||||
| `POST /api/feedback/public/{id}` | `POST /api/v2/feedback-forms/{id}` |
|
||||
| `GET /api/feedback/event/{id}` | `GET /api/v2/events/{id}/feedback` |
|
||||
| `PUT /api/feedback/event/{id}` | `PUT /api/v2/events/{id}/feedback` |
|
||||
| `DELETE /api/feedback/event/{id}` | `DELETE /api/v2/events/{id}/feedback` |
|
||||
| `POST /api/feedback/event/{id}/send-now` | `POST /api/v2/events/{id}/feedback/send-now` |
|
||||
| `GET /api/registrations` | `GET /api/v2/registrations` |
|
||||
| `GET /api/registrations/myregistrations` | `GET /api/v2/me/registrations/full` |
|
||||
| `GET /api/registrations/event/{id}` | `GET /api/v2/events/{id}/registrations` |
|
||||
| `POST /api/registrations/manual` | `GET /api/v2/registrations/manual` |
|
||||
| `POST /api/registrations/bulk` | `GET /api/v2/registrations/bulk` |
|
||||
| `PUT /api/registrations/{id}/options` | `PUT /api/v2/registrations/{id}/items` |
|
||||
| `POST /api/registrations/{id}/send-invoice` | `POST /api/v2/registrations/{id}/invoice` |
|
||||
| `POST /api/registrations/{id}/coupon` | `POST /api/v2/registrations/{id}/coupon` |
|
||||
| `DELETE /api/registrations/{id}/coupon` | `DELETE /api/v2/registrations/{id}/coupon` |
|
||||
| `PUT /api/registrations/{id}/attendees` | `PUT /api/v2/registrations/{id}/attendees` |
|
||||
| `POST /api/registrations/{id}/attendees/{id2}/send-form-link` | `POST /api/v2/registrations/{id}/attendees/{id2}/form-link` |
|
||||
| `GET /api/registrations/{id}/forms/draft` | `GET /api/v2/registrations/{id}/form-draft` |
|
||||
| `PUT /api/registrations/{id}/forms/draft` | `PUT /api/v2/registrations/{id}/form-draft` |
|
||||
| `POST /api/registrations/{id}/forms/responses` | `POST /api/v2/registrations/{id}/form-responses` |
|
||||
| `PUT /api/registrations/{id}/forms/responses` | `PUT /api/v2/registrations/{id}/form-responses` |
|
||||
| `GET /api/registrations/{id}` | `GET /api/v2/registrations/{id}/full` |
|
||||
| `PUT /api/registrations/{id}` | `PATCH /api/v2/registrations/{id}/status` |
|
||||
| `GET /api/series` | `GET /api/v2/series` |
|
||||
| `POST /api/series` | `POST /api/v2/series` |
|
||||
| `GET /api/series/by-slug/{id}` | `GET /api/v2/series/by-slug/{id}` |
|
||||
| `GET /api/series/{id}/compare` | `GET /api/v2/series/{id}/compare` |
|
||||
| `POST /api/series/{id}/follow` | `PUT/DELETE /api/v2/series/{id}/follow` |
|
||||
| `DELETE /api/series/{id}/follow` | `DELETE /api/v2/series/{id}/follow` |
|
||||
| `PUT /api/series/{id}` | `PATCH /api/v2/series/{id}` |
|
||||
| `DELETE /api/series/{id}` | `DELETE /api/v2/series/{id}` |
|
||||
| `GET /api/season-passes/mine` | `GET /api/v2/me/season-passes` |
|
||||
| `POST /api/season-passes/purchases/{id}/checkout` | `POST /api/v2/season-pass-purchases/{id}/checkout` |
|
||||
| `POST /api/season-passes/{id}/buy` | `POST /api/v2/season-passes/{id}/buy` |
|
||||
| `GET /api/season-passes` | `GET /api/v2/season-passes` |
|
||||
| `POST /api/season-passes` | `POST /api/v2/season-passes` |
|
||||
| `PUT /api/season-passes/{id}` | `PATCH /api/v2/season-passes/{id}` |
|
||||
| `DELETE /api/season-passes/{id}` | `DELETE /api/v2/season-passes/{id}` |
|
||||
| `POST /api/bundles/quote` | `PATCH/DELETE /api/v2/bundles/quote` |
|
||||
| `GET /api/bundles/event/{id}` | `GET /api/v2/events/{id}/bundles` |
|
||||
| `POST /api/bundles/event/{id}` | `POST /api/v2/events/{id}/bundles` |
|
||||
| `PUT /api/bundles/{id}` | `PATCH /api/v2/bundles/{id}` |
|
||||
| `DELETE /api/bundles/{id}` | `DELETE /api/v2/bundles/{id}` |
|
||||
| `POST /api/coupons/validate` | `GET/PATCH /api/v2/coupons/check` |
|
||||
| `GET /api/coupons/redemptions` | `GET /api/v2/coupons/redemptions` |
|
||||
| `GET /api/coupons` | `GET /api/v2/coupons` |
|
||||
| `POST /api/coupons` | `POST /api/v2/coupons` |
|
||||
| `GET /api/coupons/{id}` | `GET /api/v2/coupons/{id}` |
|
||||
| `PUT /api/coupons/{id}` | `PATCH /api/v2/coupons/{id}` |
|
||||
| `GET /api/campuses` | `GET /api/v2/campuses` |
|
||||
| `GET /api/campuses/admin` | `GET /api/v2/campuses/admin` |
|
||||
| `GET /api/campuses/by-slug/{id}` | `GET /api/v2/campuses/by-slug/{id}` |
|
||||
| `PUT /api/campuses/settings` | `PUT /api/v2/campuses/enabled` |
|
||||
| `PUT /api/campuses/order` | `PUT /api/v2/campuses/order` |
|
||||
| `POST /api/campuses` | `POST /api/v2/campuses` |
|
||||
| `GET /api/campuses/{id}/audience` | `GET /api/v2/campuses/{id}/audience` |
|
||||
| `PUT /api/campuses/{id}` | `PATCH /api/v2/campuses/{id}` |
|
||||
| `DELETE /api/campuses/{id}` | `DELETE /api/v2/campuses/{id}` |
|
||||
| `GET /api/users/profile` | `GET /api/v2/me` |
|
||||
| `PUT /api/users/profile` | `PATCH /api/v2/me` |
|
||||
| `POST /api/users` | `POST /api/v2/auth/signup` |
|
||||
| `POST /api/users/login` | `POST /api/v2/auth/login` |
|
||||
| `POST /api/users/login/2fa` | `POST /api/v2/auth/login/code` |
|
||||
| `POST /api/registrations` | `POST /api/v2/registrations` |
|
||||
| `DELETE /api/registrations/{id}` | `POST /api/v2/registrations/{id}/cancel` |
|
||||
| `POST /api/payments/checkout` | `POST /api/v2/registrations/{id}/checkout` |
|
||||
| `GET /api/tickets/scan-preview/{id}` | `GET /api/v2/checkin/{id}` |
|
||||
| `POST /api/tickets/scan/{id}` | `POST /api/v2/checkin/{id}` |
|
||||
@@ -0,0 +1,252 @@
|
||||
# Cross Events Platform
|
||||
|
||||
Cross Events is a full-stack event management platform that allows users to browse events, register for them, make payments, and manage their tickets.
|
||||
|
||||
## Project Structure
|
||||
|
||||
The project is divided into two main parts:
|
||||
|
||||
- Backend: Node.js + Express + Prisma + PostgreSQL
|
||||
- Frontend: Next.js (React) + Tailwind CSS
|
||||
|
||||
### Backend
|
||||
|
||||
The backend provides a RESTful API for managing users, events, registrations, payments, uploads, and tickets. It includes:
|
||||
|
||||
- JWT-based authentication and role-based authorization
|
||||
- Event and registration management
|
||||
- Payment integration with Yoco (checkout + webhooks)
|
||||
- Ticket generation (PDF + QR) and email delivery
|
||||
- Static uploads for event images
|
||||
|
||||
Documentation: see Backend API Documentation and Backend README for environment setup and endpoints.
|
||||
- API reference: `/api/docs/v2` on the running site (OpenAPI; admin token; `/docs/v2` before 2.2.0) — ./backend/API_DOCUMENTATION.md
|
||||
- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md
|
||||
- Backend README: ./backend/README.md
|
||||
|
||||
### Frontend
|
||||
|
||||
The frontend is a Next.js app that provides:
|
||||
|
||||
- User authentication (login, register)
|
||||
- Browse/search events and view details
|
||||
- Register for events and pay via Yoco
|
||||
- Manage and view tickets
|
||||
|
||||
Documentation: see Frontend README for environment and scripts.
|
||||
- Frontend README: ./frontend/README.md
|
||||
|
||||
## Getting Started (Local Development)
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 18+ (recommended)
|
||||
- npm or yarn
|
||||
- PostgreSQL database
|
||||
|
||||
### 1) Install dependencies
|
||||
|
||||
- Backend
|
||||
- cd backend
|
||||
- npm install
|
||||
|
||||
- Frontend
|
||||
- cd ../frontend
|
||||
- npm install
|
||||
|
||||
### 2) Configure environment variables
|
||||
|
||||
- Backend: create backend/.env and set required variables (see backend/README.md). At minimum:
|
||||
- DATABASE_URL
|
||||
- JWT_SECRET
|
||||
- PORT (optional; defaults to 3000 if not set)
|
||||
- EMAIL_HOST, EMAIL_PORT, EMAIL_USER, EMAIL_PASS, EMAIL_FROM (for ticket emails)
|
||||
- FRONTEND_URL or APP_BASE_URL (used in email links)
|
||||
|
||||
- Frontend: create frontend/.env.local and set
|
||||
- NEXT_PUBLIC_API_URL=http://localhost:<backend-port>
|
||||
Example for default backend: NEXT_PUBLIC_API_URL=http://localhost:5000
|
||||
|
||||
- Organisation name, logo, brand colour, and notification emails are configured via the admin panel (Admin → Site Settings) and do not need to be set in .env files.
|
||||
- Yoco payments are set up in Admin → Site Settings → Payments: paste the secret key, then generate the webhook (or enter its secret). YOCO_SECRET_KEY / YOCO_WEBHOOK_SECRET in backend/.env still work as fallbacks.
|
||||
|
||||
### 3) Run the apps
|
||||
|
||||
- Start backend (development):
|
||||
- cd backend
|
||||
- npm run dev
|
||||
- By default runs at http://localhost:3000 (or the PORT you set)
|
||||
|
||||
- Start frontend (development):
|
||||
- cd ../frontend
|
||||
- npm run dev
|
||||
- Next.js dev server runs at http://localhost:3000 by default; if it conflicts with backend, it will pick another port (e.g., 3001). Ensure NEXT_PUBLIC_API_URL points to the backend port.
|
||||
|
||||
## Tests
|
||||
|
||||
- Backend unit tests: `cd backend && npm test`
|
||||
- End-to-end tests (Playwright), from the repo root:
|
||||
- once: `npm install` and `npx playwright install chromium`
|
||||
- `npm run test:e2e`
|
||||
- They start their own backend (port 5100) and frontend (port 3100) against a separate
|
||||
database — `backend/.env`'s `DATABASE_URL` with `_e2e` added to the name, or
|
||||
`E2E_DATABASE_URL` — which is dropped, recreated and seeded on every run. Your own dev
|
||||
servers and database aren't touched. The database user needs permission to create
|
||||
databases.
|
||||
- There's no CI: run these yourself, plus `npx eslint .` in `frontend/`, before tagging a
|
||||
release (the deploy's `next build` fails on any lint error). Releases are deployed by hand
|
||||
with `scripts/deploy.sh` (see [DEPLOYMENT.md](./DEPLOYMENT.md)).
|
||||
|
||||
## Deployment
|
||||
|
||||
### A new install
|
||||
|
||||
On a fresh Ubuntu 22.04/24.04 server, with the domain's DNS already pointing at it:
|
||||
|
||||
```bash
|
||||
curl -fsSLO https://c-git.crosscode.co.za/joshua/hope-events/raw/branch/main/scripts/install.sh
|
||||
sudo bash install.sh --domain events.yourchurch.org --email you@yourchurch.org [--version v1.41.0]
|
||||
```
|
||||
|
||||
It installs Node 24 LTS, PostgreSQL (with its own database and a random password), PM2, nginx (the
|
||||
API, uploads, `/health` and `/docs` to the backend, everything else to the site) and an HTTPS
|
||||
certificate, writes `backend/.env` and `frontend/.env.production`, migrates, builds and starts the
|
||||
app. Then open `https://<domain>/setup`: create the admin account and enter the **licence key**
|
||||
to connect the site to the Cross Events Hub. Several installs can share a server with different
|
||||
`--name`, `--dir`, `--web-port` and `--api-port`. Run `--help` for all options.
|
||||
|
||||
Behind an frp tunnel (no public IP on the server)? See [DEPLOYMENT.md](DEPLOYMENT.md).
|
||||
|
||||
### Updating
|
||||
|
||||
To update a running install, on the server in the repo folder:
|
||||
|
||||
- `bash scripts/deploy.sh` — the latest `main`
|
||||
- `bash scripts/deploy.sh v1.37.4` — a tagged release
|
||||
|
||||
It backs up the database, checks the version out, installs, migrates, builds and reloads PM2.
|
||||
If anything fails before the reload, it goes back to the previous version (the running app
|
||||
isn't touched).
|
||||
|
||||
PM2 uses the install's own `ecosystem.config.js` (app names, frontend port). It isn't in git,
|
||||
so deploys never change it; the first deploy creates it from `ecosystem.config.example.js` —
|
||||
set names that match your PM2 apps (`pm2 ls`) and the port you use.
|
||||
|
||||
### Backend Deployment
|
||||
|
||||
1. Provision a PostgreSQL database and set DATABASE_URL.
|
||||
2. Set all required environment variables (see backend/README.md).
|
||||
3. Run Prisma migrations (if applicable).
|
||||
4. Start the server with: npm start (or a process manager like PM2).
|
||||
5. Expose the webhook endpoint /api/v2/webhooks/yoco publicly and register it with Yoco (Site settings → Payments → Yoco → Generate does this).
|
||||
6. Ensure the uploads directory public/uploads exists and is writable.
|
||||
|
||||
### Frontend Deployment
|
||||
|
||||
1. Build the frontend:
|
||||
- cd frontend
|
||||
- npm run build
|
||||
2. Run with npm start (Next.js) on your server, or deploy to a platform like Vercel.
|
||||
3. Ensure NEXT_PUBLIC_API_URL points to the public URL of your backend (including port if not 80/443).
|
||||
|
||||
### Ports and URLs
|
||||
|
||||
- Backend default port is 3000 unless overridden by PORT.
|
||||
- Frontend dev server commonly uses 3000; set NEXT_PUBLIC_API_URL to avoid clashes (e.g., backend 3000, frontend 3001).
|
||||
|
||||
## Useful Links
|
||||
|
||||
- API reference: `/api/docs/v2` on the running site (OpenAPI; admin token; `/docs/v2` before 2.2.0) — ./backend/API_DOCUMENTATION.md
|
||||
- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md
|
||||
- Backend README: ./backend/README.md
|
||||
- Frontend README: ./frontend/README.md
|
||||
- Site Settings — defaults reference: ./SETTINGS.md
|
||||
- Feature overview: ./FEATURES.md
|
||||
|
||||
## Recent Changes
|
||||
|
||||
> Older notes, kept for history. The `/api/…` paths they mention are API v1, removed in 2.0 —
|
||||
> MIGRATING-TO-2.md lists each one's v2 replacement. Since 1.33 the changes are in CHANGELOG.md.
|
||||
|
||||
### Sold-out handling, tiered stock warnings & UI polish
|
||||
|
||||
**Backend**
|
||||
- `GET /api/events` now computes and returns `isSoldOut: boolean` per event — true when every option with a stock limit (`stockLimit > 0`) is fully sold out. Events with only unlimited options are never sold out.
|
||||
- `POST /api/settings/test-smtp` error responses now include a `raw` field (the original error message) alongside the human-readable `message`. Error code 530 (Microsoft "Client not authenticated to send mail") is now correctly mapped to the authentication-failure message.
|
||||
|
||||
**Frontend**
|
||||
- **Event listing** (`/events`): `EventCard` shows a disabled "Sold Out" button (red tint) when `isSoldOut` is true, replacing the Register button. Free events now show "Register" without the "- R0.00" suffix.
|
||||
- **Event detail page** (`/events/[id]`): computes sold-out state from returned option `availableCount`; shows a disabled "Sold Out" button instead of the Register link. Options with price `0` display "Free" instead of "R0.00".
|
||||
- **Registration page** (`/register/[eventId]`): shows a red "This event is sold out" banner and replaces the Register button with a disabled "Sold Out" button when all limited options are exhausted.
|
||||
- **Tiered low-stock threshold**: the "X remaining" badge now uses capacity-based percentages — ≤ 50 tickets: 20 %; 51–200: 15 %; 201–1,000: 10 %; 1,000+: 5 %. Changed from `Math.ceil` to `Math.round` to prevent rounding-up inflation of the threshold. Fixed a React rendering bug where `stockLimit && stockLimit > 0 && ...` evaluated to the number `0` (which React renders as visible text) instead of a boolean — this caused "00" to appear next to options with unlimited stock (`stockLimit = 0`).
|
||||
- **Event image upload**: the EventForm (used in the create modal) now shows a file upload button with inline preview alongside the URL input field. Files are uploaded to `POST /api/uploads/event-image` and the returned URL is set automatically.
|
||||
- **Attachments during event creation**: step 6 ("Attachments") of the supervisor create-event wizard now lets you stage files. They are uploaded to `POST /api/events/:id/attachments` immediately after the event record is created, so attachments no longer require a separate edit session.
|
||||
- **SMTP test details**: on failure the "Test connection" result now shows a collapsible "Show technical details" section exposing the raw SMTP error alongside the friendly message. `ApiError` in `src/lib/api.ts` now carries a `data` field with the full JSON response body.
|
||||
|
||||
|
||||
|
||||
### Variants, stock limits, early-bird pricing & cancellation guard
|
||||
|
||||
**Backend**
|
||||
- **`OptionVariant` model**: event options can now have sub-variants (sizes, colours, ticket types — e.g. Adult/Child/VIP under a single "Ticket" option). Variants have an optional `price` override and their own `stockLimit`.
|
||||
- **Stock limits**: `stockLimit` added to `EventOption` and `EarlyBirdTier`. A value of `0` means unlimited. All stock counts exclude cancelled registrations.
|
||||
- **Early-bird concurrency handling**: once a Yoco checkout has been issued at an early-bird price, that price is honoured even if another user simultaneously exhausts the tier's stock. Stock-based forfeiture only applies at registration time (via `resolveOptionPrice`). Deadline expiry at payment time forfeits the price; stock races after the checkout is issued do not.
|
||||
- **Early-bird stock forfeiture**: if a tier's deadline passes after registration but before payment, `refreshPricingForRegistration` (called before every Yoco checkout) re-evaluates the tier and updates `priceSnapshot`. If prices changed, `POST /api/payments/checkout` returns `{ priceUpdated: true, newTotal }` (HTTP 200) so the frontend can show a warning before retrying.
|
||||
- **`priceSnapshot` / `appliedTierId`** on `RegistrationOption`: price and tier are snapshotted at registration creation. `computeRegistrationTotalDue` uses `priceSnapshot` as authoritative when present (legacy rows without a snapshot fall back to deadline-only re-evaluation).
|
||||
- **Cancelled registration tickets**: `GET /api/tickets/mytickets` now excludes tickets from cancelled registrations at the database level.
|
||||
- **Cancellation payment guard**: `DELETE /api/registrations/:id` blocks non-admins from cancelling a registration that has positive payments. Admins can cancel at any time.
|
||||
- **Variant CRUD**: `POST /api/events/options/:id/variants`, `PUT /api/events/variants/:id`, `DELETE /api/events/variants/:id`.
|
||||
- **Testing mode** (`NODE_ENV=testing`): behaves like development (permissive CORS, all debug routes) but validates required env vars (`DATABASE_URL`, `JWT_SECRET`) at startup and enables rate limiting.
|
||||
|
||||
**Frontend**
|
||||
- **Register page** (`/register/[eventId]`): variant picker — when an option has variants, shows each variant with its own qty control, stock badge (sold out / X remaining at ≤ 15 %), and price. Submission payload includes `variantId`. Early-bird notice shown when any active tier is present.
|
||||
- **Event detail page** (`/events/[id]`): ticket section shows variant breakdown with "From R…" pricing, early-bird strikethrough, and sold-out/nearly-out badges.
|
||||
- **User dashboard**: "Cancel registration" button appears in the registration modal when no payments have been made. Inline confirmation before the API call.
|
||||
- **Pay page**: if the backend returns `priceUpdated: true`, an amber warning banner shows the new total and a dismiss button before the user can retry.
|
||||
- **Supervisor events page** (`/dashboard/supervisor/events`): 6-step create/edit modal — "Basic Details", "Items & Pricing", "Sections", "Form", "Visibility", "Attachments". In create mode, step tabs are not clickable (linear navigation only); in edit mode any step can be jumped to. Options in "Items & Pricing" are collapsible cards; Variants and Early-bird tiers are expandable sub-sections within each option. `/dashboard/supervisor/sections` now redirects to the Events page.
|
||||
- **Legal pages**: Terms of Use updated with early-bird pricing terms, partial payment terms, and self-cancellation policy. Privacy Policy updated with data anonymisation details.
|
||||
|
||||
|
||||
|
||||
### Site settings & first-time setup wizard
|
||||
- **Admin → Site Settings** (`/dashboard/admin/settings`): organisation details, branding (colour + logo), notification emails, **SMTP email delivery**, and **legal page content** are stored in the database and editable at runtime.
|
||||
- **Setup wizard** (`/setup`): on a fresh deployment (empty database) the platform automatically shows a wizard — organisation details, admin account creation, and branding. No manual DB seeding required.
|
||||
- **`/api/settings`** (public): exposes public settings (org details, legal keys) for navbar and legal pages.
|
||||
- **`/api/setup`** (public, one-time): creates the first admin account; blocked once any user exists.
|
||||
- **Settings cache** (`settingsCache.js`): in-process 60-second cache with transparent AES-256-GCM decryption for sensitive keys.
|
||||
- **SMTP via admin panel**: host, port, TLS, from address, username, and password are all configurable without touching `.env`. Password is stored AES-256-GCM encrypted (key derived from `JWT_SECRET`).
|
||||
- **Legal pages dynamic**: Terms of Use and Privacy Policy populate org name, contact email, website URL, operator name, Information Officer details, and effective date from the settings DB.
|
||||
- **`ORG_NAME`, `ORG_TAGLINE`, `EMAIL_HEADER_COLOR`, `REGISTRATIONS_EMAIL`, SMTP vars** no longer required in `.env` — all managed via the admin panel (env vars still work as fallbacks).
|
||||
|
||||
### Admin dashboard improvements
|
||||
- **User management** (`/dashboard/admin/users`): filtering (role, active status, text search) is now server-side so page size is always consistent; per-page selector (10/25/50/100); "Delete data" button anonymises a user's personal information via `POST /api/users/:id/anonymize`.
|
||||
- **Registrations** (`/dashboard/admin/registrations`): event dropdown, status, and fuzzy text filters; expandable rows showing ticket options and form responses loaded on demand.
|
||||
|
||||
### Forms page (`/dashboard/supervisor/forms`, `/dashboard/admin/forms`)
|
||||
- **Print** opens a clean popup window (no site chrome) with one form response per A4 page — event name, attendee details, registration ID, and answers in a two-column grid.
|
||||
- **User filter** replaced raw "User ID" text input with a searchable name/email/phone dropdown.
|
||||
- **Event filter** includes "Include past events" and "Include inactive events" checkboxes.
|
||||
- Filters in a responsive grid; dropdowns constrained to `max-w-xs`.
|
||||
|
||||
### Ticket printing
|
||||
- **At-the-door individual print**: individual ticket print now generates a proper A6 ticket with QR code, event title, date, type, holder name, and ID — no longer just a UUID.
|
||||
- **Staff event-tickets page**: A4 print layout matches at-the-door (2 columns × 4 rows, 8 tickets per page).
|
||||
|
||||
### Form builder & events
|
||||
- **Form builder**: up/down reorder buttons; type badge (Text/Number/Date/etc.); separate quick-add buttons for Statement and Heading fields.
|
||||
- **Early-bird tiers**: no manual order number — tiers ordered by list position; labelled Deadline and Price inputs.
|
||||
|
||||
### Bulk messaging dropdowns
|
||||
- Attendee selection dropdown constrained to `max-w-xs` / `w-64` panel on email-attendees and whatsapp-attendees pages.
|
||||
|
||||
### Backend
|
||||
- `GET /api/users` supports server-side `?search=`, `?role=`, `?isActive=` filtering.
|
||||
- `POST /api/users/:id/anonymize` — erases personal data (admin only).
|
||||
- `GET|PUT /api/settings`, `GET /api/settings/needs-setup`, `POST /api/setup` — settings and setup endpoints.
|
||||
- `POST /api/uploads/logo` — logo upload (admin, or unauthenticated during first-time setup).
|
||||
- `backend/src/utils/encryption.js` — AES-256-GCM encrypt/decrypt; key derived from `JWT_SECRET` via scrypt.
|
||||
- SMTP transporter rebuilt dynamically when settings cache detects a config change — no restart required after updating SMTP settings.
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License.
|
||||
@@ -0,0 +1,142 @@
|
||||
# Site Settings — Defaults Reference
|
||||
|
||||
Every setting below is stored as a row in the `AppSetting` key-value table and
|
||||
is editable at runtime via **Admin → Site Settings** (or, for the first few,
|
||||
the `/setup` wizard on a fresh install). None of them are required — this
|
||||
page documents exactly what happens when a given key has never been saved.
|
||||
|
||||
Settings changes take effect within 60 seconds everywhere (the backend's
|
||||
in-process settings cache TTL) without a server restart.
|
||||
|
||||
## Organisation
|
||||
|
||||
| Setting | Default when unset | Notes |
|
||||
|---|---|---|
|
||||
| `org_name` | `"Cross Code"` | Falls back to `ORG_NAME` env var first, then this hardcoded default (the platform vendor's name, used as a neutral placeholder — `org_name` is a required field in the setup wizard, so this fallback is practically unreachable once a site has been set up). Shown in the navbar, email headers/subjects, and WhatsApp messages. |
|
||||
| `org_tagline` | `"Connecting community through events"` | Falls back to `ORG_TAGLINE` env var first. Shown under the org name in the email header. |
|
||||
| `org_email` | *(blank)* | No fallback in most places. **Exception:** the Terms of Use / Privacy Policy pages default to `privacy@example.com` (an obvious placeholder) if unset — see the Legal section below. |
|
||||
| `org_phone` / `org_address` | *(blank)* | No fallback — simply omitted wherever shown if unset. |
|
||||
| `app_base_url` | `APP_BASE_URL` or `FRONTEND_URL` env var, else `http://localhost:3001` | Used to build links in emails (password reset, ticket delivery, etc.). Should always be set in production. |
|
||||
| `APP_TIMEZONE` (env) | `Africa/Johannesburg` | The site's time zone (an IANA name, e.g. `Europe/London`): background job schedules (e.g. the 07:00 daily summary), session dates and printed times. Also sent to the Hub in the heartbeat. Needs a backend restart. |
|
||||
|
||||
## Branding
|
||||
|
||||
| Setting | Default when unset | Notes |
|
||||
|---|---|---|
|
||||
| `primary_color` | Legacy `accent_color` value if present, else `#4F46E5` (indigo) on the website / `#1e3a5f` (navy) in emails | See [Two different fallbacks](#two-different-fallbacks-for-primary_color) below — this is the one setting with a genuine inconsistency worth knowing about. Drives buttons, links, nav highlights, and the email header/CTA. The Branding tab warns when it is under 4.5:1 against white (too light for white text and links) and offers a darker shade (1.50.0). |
|
||||
| `secondary_color` | `210 40% 96.1%` background / near-black text (light gray "wash", shadcn's stock theme) | The Branding tab's color picker *pre-fills* `#8B5CF6` as a suggested starting point, but that's only a UI default — if you never hit Save, the actual site uses the light-gray fallback, not violet. |
|
||||
| `accent_color` | `210 40% 96.1%` background / near-black text (same light gray as Secondary) | Same story as Secondary — the picker pre-fills `#EC4899` (pink) as a suggestion only. |
|
||||
| `logo_url` | Bundled logo (`frontend/src/app/church_logo.jpg`) | Shown in the navbar. This is still the original Hope Family Church artwork checked into the repo — swap the file (or upload a real logo via the Branding tab) before deploying for a different organisation. |
|
||||
| `favicon_url` | `frontend/public/favicon.ico` (the site's original generic favicon) | Shown in the browser tab. |
|
||||
|
||||
### Two different fallbacks for `primary_color`
|
||||
|
||||
If `primary_color` has *never* been saved (no admin has ever used the new
|
||||
3-color Branding tab) **and** there's no legacy `accent_color` value either,
|
||||
the website and outgoing emails currently disagree on what "no color" means:
|
||||
|
||||
- **Website** (`globals.css` / `tailwind.config.js` static defaults): `#4F46E5`, a bright indigo.
|
||||
- **Emails** (`backend/src/utils/email.js` `getOrg()`): `#1e3a5f`, a dark navy — unless overridden by the `EMAIL_HEADER_COLOR` env var.
|
||||
|
||||
In practice this only matters on a brand-new install before the setup wizard
|
||||
or Branding tab has been saved even once — the wizard always writes
|
||||
`primary_color`, so this gap closes itself the moment setup completes.
|
||||
|
||||
## Notifications
|
||||
|
||||
| Setting | Default when unset | Notes |
|
||||
|---|---|---|
|
||||
| `reg_notification_emails` | `REGISTRATIONS_EMAIL` env var, else *(blank)* | If truly blank, no internal notification email is sent for new registrations/payments/donations — it's silently skipped, not an error. |
|
||||
|
||||
## Email delivery (SMTP)
|
||||
|
||||
| Setting | Default when unset | Notes |
|
||||
|---|---|---|
|
||||
| `smtp_host` | `SMTP_HOST`/`EMAIL_HOST` env var, else *(blank)* | If blank, the app **does not send real email** — it uses nodemailer's `jsonTransport`, which just logs the would-be email to the console. This is the single biggest "nothing is configured" gotcha — ticket/payment/password-reset emails silently don't go anywhere until SMTP is set up. |
|
||||
| `smtp_port` | `587` | |
|
||||
| `smtp_secure` | `false` | |
|
||||
| `smtp_user` / `smtp_pass` | *(blank)* | Stored AES-256-GCM encrypted (key derived from `JWT_SECRET`). |
|
||||
| `smtp_from` | *(blank)* | If blank, outgoing mail's `From:` address falls back to the literal `no-reply@crosscode.local`. |
|
||||
|
||||
## Payments
|
||||
|
||||
Managed in the Payments tab (through `/api/v2/payments/providers/settings` and `/api/v2/payments/yoco/config`, not the generic settings endpoints).
|
||||
|
||||
| Setting | Default when unset | Notes |
|
||||
|---|---|---|
|
||||
| `payfast_merchant_id` / `payfast_merchant_key` | `PAYFAST_MERCHANT_ID` / `PAYFAST_MERCHANT_KEY` env vars, else *(blank)* | From the PayFast (or Sandbox) dashboard. Both are needed before PayFast can take payments. The key isn't secret (it's in the payment form), so it's shown in full. Managed through `/api/payfast`. |
|
||||
| `payfast_passphrase` | `PAYFAST_PASSPHRASE` env var, else *(blank)* | Stored encrypted. Must match the dashboard's salt passphrase exactly, or PayFast refuses payments ("signature does not match"). |
|
||||
| `payfast_mode` | `PAYFAST_MODE` env var, else `sandbox` | `sandbox` or `live`: where payers are sent and where notifications are confirmed. |
|
||||
| `payment_providers` | Yoco enabled | JSON `{ order: [...], enabled: { yoco: true } }`: which online payment providers are on, and their order (the first one enabled and set up is the default). Providers not listed yet come last, switched off (Yoco on, as it was the only provider). If none is on and set up, online payments are off. |
|
||||
| `yoco_secret_key` | `YOCO_SECRET_KEY` env var, else *(blank)* | Stored AES-256-GCM encrypted. If blank, online checkouts and sponsorships fail with "online payments are not configured". |
|
||||
| `yoco_webhook_secret` | `YOCO_WEBHOOK_SECRET` env var, else *(blank)* | Stored encrypted. If blank, Yoco webhooks are rejected, so payments aren't confirmed automatically. |
|
||||
| `yoco_webhook_id` | *(blank)* | The Yoco webhook whose secret is stored, set when it's generated from the tab. Used to mark it "Active" and to clear the secret when it's deleted. |
|
||||
|
||||
## Legal (Terms of Use / Privacy Policy)
|
||||
|
||||
| Setting | Default when unset | Notes |
|
||||
|---|---|---|
|
||||
| `legal_operator_name` | `"[operator details not yet configured]"` | Deliberately a generic, obviously-incomplete placeholder rather than any real person's or organisation's name. Unlike `org_name`, these legal fields are optional and can realistically stay unset on a live site — defaulting them to Cross Code's (or anyone else's) real identity would misrepresent who's legally responsible for that deployment. |
|
||||
| `legal_io_name` | `"[not yet configured]"` | Same reasoning as `legal_operator_name`. |
|
||||
| `legal_io_email` | `"io@example.com"` | Rendered as a `mailto:` link, so the placeholder stays a syntactically valid address on the IANA-reserved `example.com` domain rather than a bracketed non-email string that would break the link. |
|
||||
| `legal_website_url` | `"example.com"` | Same reasoning — used to build an `https://` link. |
|
||||
| `legal_effective_date` | `"[not yet set]"` | Plain text only, no link — a bracketed placeholder is fine here. Only used by the built-in privacy notice: once a version is published in Admin → Privacy, its publish date is the effective date. |
|
||||
| `notify_user_on_impersonation` | `"false"` | When `"true"`, a user is emailed (with the reason) whenever an admin views their account with Impersonate. Set under Site Settings → Legal → Support access. |
|
||||
| `consent_medical_retention_days` | `30` | Youth events: medical and emergency details from parental consent forms are deleted this many days after the event ends (daily 09:00 job). The consent record itself — who agreed, when, to which text — is kept. Set under Site Settings → Legal. |
|
||||
| `org_email` (as used on legal pages specifically) | `"privacy@example.com"` | Different fallback than `org_email`'s general default (blank) — also rendered as a `mailto:` link, so it needs to stay a valid-looking address. |
|
||||
|
||||
## Campuses
|
||||
|
||||
| Setting | Default when unset | Notes |
|
||||
|---|---|---|
|
||||
| `campuses_enabled` | `false` | Site settings → Campuses → "Use campuses". Changed only through `PUT /api/v2/campuses/enabled` (audited); hidden from the generic settings endpoints. Off hides campus fields and filters everywhere; campuses and each event's campus are kept. The campuses themselves are in the `Campus` table. |
|
||||
|
||||
## Cross Events Hub (licence)
|
||||
|
||||
| Setting | Default when unset | Notes |
|
||||
|---|---|---|
|
||||
| `HUB_URL` (env) | `https://events-hub.crosscode.co.za` | Where the Hub runs. |
|
||||
| `HUB_PUBLIC_KEY` (env) | The production key built into `backend/src/hub/publicKey.js` | Only for a local or test Hub. Licence tokens are checked with this key. |
|
||||
| `HUB_HEARTBEAT_ENABLED` (env) | `true` | The 15-minute `hub-heartbeat` job (plus one check-in 30 s after starting and after connecting). Off means the licence isn't refreshed — after 30 days the site goes into grace, then read-only. |
|
||||
| `LICENCE_CHECK_DISABLED` (env) | `false` | `true` turns read-only mode off — **ignored when `NODE_ENV=production`**. For the end-to-end tests and local development without a Hub. |
|
||||
| `hub_install_id`, `hub_install_secret` (encrypted), `hub_licence`, `hub_last_heartbeat_at`, `hub_last_error`, `hub_latest_version` | — | Written only by `src/hub/client.js` when connecting and on each heartbeat. Never readable or writable through the generic settings endpoints. Deleting them disconnects the site (it becomes "no licence", which is read-only). The heartbeat deletes the install and licence keys itself when the Hub answers `INSTALL_NOT_FOUND`. |
|
||||
|
||||
## WhatsApp
|
||||
|
||||
| Setting | Default when unset | Notes |
|
||||
|---|---|---|
|
||||
| `WAWP_ACCESS_TOKEN` / `WAWP_INSTANCE_ID` | `WAWP_ACCESS_TOKEN`/`WAWP_INSTANCE_ID` env vars, else *(blank)* | No hardcoded default — WhatsApp sending is simply unavailable until both are configured (Admin → Site Settings → WhatsApp). |
|
||||
| `WAWP_WEBHOOK_SECRET` | Generated (random) the first time the WhatsApp tab is opened | Part of the webhook URL shown in Site Settings → WhatsApp (`/api/v2/webhooks/whatsapp?secret=…`; set-ups from before 1.51.16 use `/api/whatsapp/webhook?secret=…`, which still works). WAWP doesn't sign webhooks, so incoming messages (STOP replies) are only acted on when the secret matches. Not editable in the UI; delete the row to get a new one (then update the URL in WAWP). The URL uses `BACKEND_URL`. |
|
||||
|
||||
## Privacy (POPIA)
|
||||
|
||||
| Setting | Default when unset | Notes |
|
||||
|---|---|---|
|
||||
| `legal_io_email` (Information Officer, Site Settings → Legal) | — | Also where new privacy requests and the daily "requests due" reminder are emailed, together with all admins. The `io@example.com` placeholder is skipped. |
|
||||
| `PRIVACY_JOBS_ENABLED` (env) | `true` | The daily 08:00 `privacy` job that reminds admins of requests due within a week or overdue. |
|
||||
| `retention_policies` | Inactive accounts 60 months (on), form answers 12, login history 24, payment details 24, children at kids check-in (`kids_profiles`) 6, audit/access logs 60 — all on | Admin → Privacy → Retention (JSON `{ policies: { key: { enabled, months } }, reviewedAt, reviewedBy }`). Minimums: inactive accounts and logs 12 months, login history and payment details 3, form answers and kids profiles 1; maximum 240. Saving marks them reviewed (readiness check). |
|
||||
| `retention_last_run` | — | When the `retention` job last ran and what it did (readiness check: within 2 days). |
|
||||
| `VOLUNTEER_JOBS_ENABLED` (env) | `true` | The `volunteers` job (every 15 minutes) that sends volunteer reminders the day before a shift. |
|
||||
| `WEBHOOKS_JOBS_ENABLED` (env) | `true` | The `webhooks` job (every minute): sends deliveries that are due (retries), picks up sends cut off by a restart, deletes deliveries older than 30 days. New events are sent straight away without it. |
|
||||
| `WEBHOOKS_ENABLED` (env) | `true` | `false` stops noticing events for outbound webhooks altogether (nothing new is queued). |
|
||||
| `WEBHOOKS_ALLOW_PRIVATE` (env) | `false` | `true` lets webhook endpoints and linked products use http and private or local addresses — for local testing only (the e2e tests set it). |
|
||||
| `FEED_JOBS_ENABLED` (env) | `true` | The `feed` job (every 5 minutes: publishes what changed in the event feed, e.g. an event going live or selling out, and tells linked products) and `feed-sync` (every 15 minutes: fetches events from the linked products shown here). Off: the feed is still rebuilt when it's asked for. |
|
||||
| `feed_publish` | `true` | Settings → Linked products → **Publish my events**: the public event feed (`/api/feed/v1/events`) for the church's other products. |
|
||||
| `SERIES_JOBS_ENABLED` (env) | `true` | The `series` job (every 15 minutes) that emails a series' followers once when a new event in it goes live (News & announcements: only people opted in to news). |
|
||||
| `RETENTION_JOBS_ENABLED` (env) | `true` | The nightly 03:30 `retention` job. Off means nothing expires automatically. |
|
||||
| `wawp_webhook_last_seen` | — | Set when WAWP's webhook arrives with the right secret; the readiness page uses it to check WhatsApp STOP is set up. |
|
||||
| `privacy_notice_draft` | — | The unpublished draft from Admin → Privacy → Privacy notice (JSON). Published versions are in the `PrivacyNotice` table. With no published version the built-in notice (`backend/src/utils/privacyNotice.js`) is shown. The notice's org name, Information Officer, website, emails and medical retention days come from the settings above when it's shown. |
|
||||
|
||||
People's News & announcements opt-in is per account (`User.newsEmail`, `User.newsWhatsApp`), not a site setting. Unsubscribe links are signed with `JWT_SECRET` and don't expire — changing `JWT_SECRET` breaks links in emails already sent.
|
||||
|
||||
## Backups
|
||||
|
||||
| Setting | Default when unset | Notes |
|
||||
|---|---|---|
|
||||
| `backup_retain_count` | `14` | How many nightly backups to keep on disk (oldest deleted beyond this count). Editable at Admin → Site Settings → Backups. See `BACKUP_ENABLED` (env var) to turn the nightly job off entirely. |
|
||||
|
||||
## Setup state
|
||||
|
||||
| Setting | Default when unset | Notes |
|
||||
|---|---|---|
|
||||
| `setup_complete` | `false` (treated as `"not true"`) | Controls whether `/setup` redirects to `/login` or runs the first-time wizard. Set to `"true"` automatically when the wizard finishes. |
|
||||
@@ -0,0 +1,810 @@
|
||||
# What's new in Cross Events
|
||||
|
||||
What each version changes for the church, in plain language. Churches see these notes on Site
|
||||
settings → Licence before they ask for an update, so they can decide whether they want it.
|
||||
|
||||
<!--
|
||||
How this file is used: the Cross Events Hub reads it from main every 15 minutes, and shows a section
|
||||
only once its version is tagged (so write it before tagging; fixes to old sections show straight away). Each version is a "## 1.2.3" heading; add "— urgent" (or "security") to the heading for a
|
||||
security or serious bug fix, which churches can't put off. Under it, lines starting with "- " show as
|
||||
a list and other lines as paragraphs; **bold**, `code` and links are shown as plain text.
|
||||
Write for church admins, not developers: no environment variables, endpoints or job names. The
|
||||
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||
-->
|
||||
|
||||
## 2.4.0
|
||||
|
||||
- **Ready for the Church Website and App.** When your church has them, your events can show on
|
||||
them and theirs here, with registration and payments still in Cross Events. Nothing changes until
|
||||
you have them: Site settings → Linked products then lists them, with a Connect button.
|
||||
- **Publish my events** (on by default) shares your public events with your connected products,
|
||||
exactly as they appear on your events page. Hidden events and anyone's details are never shared.
|
||||
- **Better search results for your events**: Google gets each event's real dates, place and the
|
||||
price range of its main tickets, from the same data every Cross Code product uses.
|
||||
|
||||
## 2.3.1
|
||||
|
||||
- **Maintenance update.** An update to the framework the site is built on, with its latest security
|
||||
fixes. Nothing changes in how you use Cross Events.
|
||||
|
||||
## 2.3.0
|
||||
|
||||
- **Sign in with an authenticator app.** Two-factor sign-in can now use an app on your phone
|
||||
(Google Authenticator, Microsoft Authenticator, 1Password and others) instead of a code by email
|
||||
or WhatsApp. It's the most secure option and works without signal. Set it up under Profile &
|
||||
Security.
|
||||
- **Recovery codes.** When you turn on two-factor you get 10 single-use recovery codes to keep
|
||||
somewhere safe: if you lose your phone, one of them lets you sign in.
|
||||
- **Admins can see how each person signs in**: the Users page shows whether each account uses an
|
||||
app, email or WhatsApp for its codes.
|
||||
|
||||
## 2.2.0
|
||||
|
||||
- **AI use is now shown in tokens.** Site settings → AI shows how much of this month's AI allowance
|
||||
your team has used, as input tokens (what's sent to the AI) and output tokens (its answers), with
|
||||
an estimate of the whole allowance. The tables of who used it and for what show tokens too.
|
||||
- **Behind the scenes:** Cross Events now lives alongside our other church products, so every
|
||||
product is updated the same way. Your site works as before, and your data and settings stay as
|
||||
they are.
|
||||
|
||||
## 2.1.1
|
||||
|
||||
- **Sending feedback forms and reminders no longer makes you wait.** "Send now" and "Remind" on the
|
||||
Feedback page now answer straight away and the emails go out in the background, so you can carry
|
||||
on working. The page updates itself as they go out.
|
||||
|
||||
## 2.1.0
|
||||
|
||||
- **A Feedback page for supervisors and admins** (Dashboard → Feedback). See every event's feedback
|
||||
in one place: how many people answered, the average star rating, each question's results and
|
||||
every response. On a named form you can also see who was asked and who hasn't answered yet.
|
||||
- **Remind the people who haven't answered.** One button sends everyone who hasn't given feedback
|
||||
a fresh link by email or WhatsApp, or you can remind one person at a time on a named form.
|
||||
Nobody is reminded twice within 24 hours. The automatic reminder after 3 days still goes out.
|
||||
- **Anonymous forms stay anonymous:** the page never shows who gave which answer, or who has and
|
||||
hasn't answered.
|
||||
- Opening the answers to a named form is recorded in the access log.
|
||||
|
||||
## 2.0.2
|
||||
|
||||
- **Licence information sent to Cross Code.** Your site now tells Cross Code which range your event
|
||||
income falls in over the last 12 months (for example "R150 001–R250 000"), which is what your
|
||||
licence tier is based on. Donations and sponsorships aren't counted, and the exact amount never
|
||||
leaves your site. The ranges now go up to over R10 million.
|
||||
- Fixed: a donation that was applied to a registration was counted twice in the income range sent
|
||||
to Cross Code.
|
||||
|
||||
## 2.0.1
|
||||
|
||||
- **Summarise this report on every report.** Reports that list people — payments, attendees,
|
||||
revenue detailed, master orders, the cashup audit trail, parental consent, feedback and the
|
||||
medical list — now have the AI summary button too. Only anonymised totals are sent (for example
|
||||
"40 attendees, 6 with allergies"): no names, contact details, notes, comments or anyone's medical
|
||||
details. Each of these summaries is recorded in the access log.
|
||||
|
||||
## 2.0.0
|
||||
|
||||
- **AI helpers.** Where you already work, a button can now do the first draft for you: describe
|
||||
an event in a sentence and the new-event form is filled in; turn a short note into a friendly
|
||||
email or WhatsApp message; get a plain-language summary under a report or of an event's
|
||||
feedback; or improve, shorten or correct a piece of text. You always see the suggestion first —
|
||||
nothing is saved or sent until you do it. The buttons appear when your licence includes an AI
|
||||
allowance (ask us about it); Site settings → AI shows what's been used this month. Only what a
|
||||
helper needs is sent: email addresses and phone numbers in your text stay on your site, reports
|
||||
are only summarised when they list no people, and feedback goes without names.
|
||||
- **Stronger password protection.** Passwords are now stored with a stronger, modern method. Nobody
|
||||
needs to do anything: each person's password is upgraded the next time they sign in.
|
||||
- **The site banner keeps time.** A banner with start and end times now appears and disappears at
|
||||
those times on pages that are already open.
|
||||
- **For anyone with their own integration** (a script or website plug-in that talks to Cross Events
|
||||
directly): the old version of the connection was retired. Payments, WhatsApp replies and links in
|
||||
emails you've already sent keep working. Whoever looks after your integration can ask us for the
|
||||
migration guide.
|
||||
|
||||
## 1.52.3
|
||||
|
||||
- **A licence check fix.** When a site's licence has run out or isn't connected, the site is
|
||||
meant to go read-only (tickets still scan and all data can still be viewed and exported). Since
|
||||
1.51.15 that wasn't being applied; it is again. Sites with an active licence see no change.
|
||||
|
||||
## 1.52.2
|
||||
|
||||
- **Safer updates.** If files on your server were changed by hand, an update now stops straight
|
||||
away and says which files, instead of failing part-way. Nothing else changes.
|
||||
|
||||
## 1.52.1
|
||||
|
||||
- **Better documentation for developers.** If someone builds on your Cross Events site (for example
|
||||
an integration or a website plug-in), the API reference now explains every part of it in full.
|
||||
Nothing changes in how the site works.
|
||||
|
||||
## 1.52.0 — urgent
|
||||
|
||||
- **Paying at the door always gives people their tickets now.** On events with a required
|
||||
attendee form, people registered at the door or in Manual registration were paid but got no
|
||||
tickets, so they couldn't be checked in. The form now pops up to fill in with them — or tap
|
||||
**Fill in later**: the tickets are issued straight away and they're sent a link to fill in the
|
||||
form afterwards.
|
||||
- **New: Corrections (for admins).** Pick any event, even one that's over, to see who's missing
|
||||
tickets, still has a form to fill in or owes money. Issue all missing tickets in one click, give
|
||||
someone their tickets now and let them pay later, make a ticket free, or check people in after
|
||||
the event.
|
||||
- The self-service kiosk asks for exactly the forms still needed, and shows headings on the form
|
||||
as text instead of an empty box.
|
||||
- People booked on several sessions now fill in one form each, not one per session.
|
||||
|
||||
## 1.51.17 — security update
|
||||
|
||||
- **Better protection for people's accounts.** The forgot-password and sign-in pages no longer
|
||||
let anyone find out whether an email address has an account here.
|
||||
|
||||
## 1.51.16
|
||||
|
||||
- **The move to the new server connection is complete.** Payment confirmations from Yoco and
|
||||
PayFast, WhatsApp messages coming in, and the calendar and unsubscribe links in emails now use
|
||||
the new addresses. Links in emails you've already sent keep working.
|
||||
|
||||
## 1.51.15
|
||||
|
||||
- **The app now talks to the server only through its new version.** Privacy settings, the admin
|
||||
pages, site settings, the Hub, webhooks and backups were the last to move. Everything works just
|
||||
as before.
|
||||
|
||||
## 1.51.14
|
||||
|
||||
- **More groundwork for 2.0.** Accounts, messaging and broadcasts, WhatsApp set-up, the dashboards,
|
||||
saved filters and report files now run on the new version of the server's connection to the
|
||||
app. They work just as before.
|
||||
|
||||
## 1.51.13
|
||||
|
||||
- **More groundwork for 2.0.** Kids check-in and volunteer rosters now run on the new version of
|
||||
the server's connection to the app. They work just as before.
|
||||
|
||||
## 1.51.12
|
||||
|
||||
- **More groundwork for 2.0.** Tickets, ticket transfers, offline scanning, the attendance register,
|
||||
certificates and group allocations now run on the new version of the server's connection to the
|
||||
app. They work just as before.
|
||||
|
||||
## 1.51.11
|
||||
|
||||
- **More groundwork for 2.0.** Payments, cash-ups, the waitlist, sponsorship, consent forms and
|
||||
feedback now run on the new version of the server's connection to the app. They work just as
|
||||
before.
|
||||
|
||||
## 1.51.10
|
||||
|
||||
- **More groundwork for 2.0.** Registrations — at the door, in the dashboards, attendee forms and
|
||||
bulk actions — now run on the new version of the server's connection to the app. They work
|
||||
just as before.
|
||||
|
||||
## 1.51.9
|
||||
|
||||
- **More groundwork for 2.0.** Event series, season passes, bundle deals, coupon codes and campuses
|
||||
now run on the new version of the server's connection to the app. They work just as before.
|
||||
|
||||
## 1.51.8
|
||||
|
||||
- **More groundwork for 2.0.** Event pages, ticket types, scanning sections, attachments, planned
|
||||
costs and picture uploads now run on the new version of the server's connection to the app. They
|
||||
work just as before.
|
||||
|
||||
## 1.51.7
|
||||
|
||||
- **More groundwork for 2.0.** Creating and editing events, and every list of events staff choose
|
||||
from, now run on the new version of the server's connection to the app. They work as before.
|
||||
- The background job runner was updated. Its list of recent runs (Site settings → Background jobs)
|
||||
starts afresh with this version.
|
||||
|
||||
## 1.51.6
|
||||
|
||||
- **Find anything with Ctrl+K.** The search box (Ctrl+K) now lists every report, and pages that
|
||||
were missing: the dashboard, all reports, ticket options, your groups, and your own events,
|
||||
payments, privacy, kids, serving, forms and donations.
|
||||
- Excel downloads use a newer, maintained library. They look the same.
|
||||
|
||||
## 1.51.5
|
||||
|
||||
- **Updated framework.** The site now runs on the latest version of its web framework. Nothing
|
||||
changes in how it works.
|
||||
|
||||
## 1.51.4 — security
|
||||
|
||||
- **Security updates** to the parts the site is built on, including a critical fix in the web
|
||||
framework. Recommended for everyone.
|
||||
|
||||
## 1.51.3
|
||||
|
||||
- **More groundwork for 2.0.** The ticket scanner and check-in at the door now run on the new version
|
||||
of the server's connection to the app, and the server's web framework has been updated. They work
|
||||
just as before.
|
||||
|
||||
## 1.51.2
|
||||
|
||||
- **More groundwork for 2.0.** Logging in, signing up and changing your details now run on the
|
||||
new version of the server's connection to the app. They work just as before.
|
||||
|
||||
## 1.51.1
|
||||
|
||||
- **More groundwork for 2.0.** Registering, paying online and cancelling now run on the new
|
||||
version of the server's connection to the app. They work just as before.
|
||||
|
||||
## 1.51.0
|
||||
|
||||
- **Groundwork for Cross Events 2.0.** Behind the scenes, the server is moving to a newer, safer
|
||||
way of talking to the app, ready for the AI helpers in 2.0. Nothing changes in how you use
|
||||
Cross Events.
|
||||
|
||||
## 1.50.2
|
||||
|
||||
- **Finding an event quickly.** Wherever staff and supervisors choose an event (the scanner, at
|
||||
the door, payments, messages, forms, attendance and more) there is now a search box. The list
|
||||
opens on upcoming events, past ones are one click away, and typing finds any event by name,
|
||||
campus or date. The events list in Reports can be searched too.
|
||||
- **Webhook guide.** Site settings → Webhooks has a "How webhooks work" guide for whoever connects
|
||||
another system: what is sent and when, how to check it came from you, and an example message for
|
||||
every kind of event.
|
||||
|
||||
## 1.50.1
|
||||
|
||||
- **Finding things in long lists.** The audit log can be searched by person, what was changed or
|
||||
IP address, filtered by role, and its action list now includes every kind of action. Data
|
||||
requests can be searched and come a page at a time, and the webhook delivery log can show only
|
||||
failed deliveries and load older ones.
|
||||
- **Fix:** the audit log's "To" date now includes that day.
|
||||
- **Faster Payments page** for churches with a few years of payments behind them.
|
||||
|
||||
## 1.50.0
|
||||
|
||||
- **Easier for everyone to use.** The public pages, registration, payment, My Events and the
|
||||
self-service kiosk now work properly with a keyboard and with screen readers: a "Skip to main
|
||||
content" link, a clear outline showing where you are, popups that can be closed with Escape, and
|
||||
every form field, button and error message read out correctly. Faint grey text is darker and
|
||||
links in sentences are underlined, so they're easier to read.
|
||||
- **Branding check.** If the main colour you pick in Site settings → Branding is too light for
|
||||
white text to be readable, you'll see a warning and can switch to a darker shade with one click.
|
||||
|
||||
## 1.49.2
|
||||
|
||||
- **Saved filters.** On Manage registrations, Users, Events and Reports, save the filters you use
|
||||
under a name and get back to them with one click. Star one and it's ready every time you open the
|
||||
page. They're yours and follow you to any device.
|
||||
|
||||
## 1.49.1
|
||||
|
||||
- **Do many at once.** On Manage registrations, tick the people you want (or select everyone
|
||||
shown after filtering) and send them a message, mark them paid, move them to another ticket, put
|
||||
them in a room or group, export them to Excel, or cancel them.
|
||||
- Moving people to another ticket keeps their tickets and QR codes; the price follows the new
|
||||
ticket, so any difference shows as owing.
|
||||
- You see what happened to each one, and anything that couldn't be done says why.
|
||||
|
||||
## 1.49.0
|
||||
|
||||
- **Today, at a glance.** The dashboard now starts with what's on today: each event with how many
|
||||
people are checked in, children in at kids church, and volunteers here — plus money in today and
|
||||
this week.
|
||||
- **Waiting for you.** One list of what needs someone — unpaid registrations, consent forms still
|
||||
outstanding, waitlists, volunteers asking for cover, events to cash up — each a click away.
|
||||
- **Ctrl K to find anything.** Press Ctrl K anywhere in the dashboard to jump to a page or setting,
|
||||
start "New event", or find an event, a payment by amount ("R450") or a person.
|
||||
|
||||
## 1.48.2
|
||||
|
||||
- No changes for churches in this version — it adds demo data for showing Cross Events to other
|
||||
churches.
|
||||
|
||||
## 1.48.1
|
||||
|
||||
- **Privacy notice brought up to date** with volunteer rosters, event series, season passes and
|
||||
webhooks. If you haven't published your own version, your site shows the new text straight away.
|
||||
- **Published your own version?** Admin → Privacy → Privacy notice now shows what changed in the
|
||||
built-in text, section by section, so you can take the new wording with one click and publish.
|
||||
- **Everyone agrees to the notice once.** People whose account was made for them agree when they
|
||||
activate it, and anyone who never has is asked once after they next log in.
|
||||
|
||||
## 1.48.0
|
||||
|
||||
- **Webhooks.** Connect Cross Events to other systems — ChurchSuite, Planning Center, a Google
|
||||
Sheet through Zapier or Make. Choose what to send (new registrations, payments, check-ins, new
|
||||
accounts, published events) in Site settings → Webhooks, and it goes out as it happens.
|
||||
- Every message is signed so the other system can trust it, failures are tried again
|
||||
automatically, and a delivery log shows what was sent.
|
||||
- Each webhook is added to your operator register for POPIA. Children's details are never sent.
|
||||
|
||||
## 1.47.4
|
||||
|
||||
- **Asked for an update, and a newer one came out?** The Licence page now shows which version you
|
||||
asked for, tells you when a newer one is out, and lets you ask for that one instead with one
|
||||
button.
|
||||
|
||||
## 1.47.3
|
||||
|
||||
- **Season passes.** Sell a ticket for several events in a series at one price — say all of next
|
||||
year's breakfasts. People buy it on the series page, pay once, and get a ticket for each event.
|
||||
- The money is shared out over the events in line with their normal ticket prices, so each event's
|
||||
cashup shows its part.
|
||||
- Set passes up on the Event series page. A pass stops selling when its first event starts.
|
||||
|
||||
## 1.47.2
|
||||
|
||||
- **Compare a series year on year.** A new report puts the events in a series side by side —
|
||||
registrations, tickets, income and how many came — with how much each went up or down from the
|
||||
one before. Open it from Reports, or with **Compare** on the Event series page.
|
||||
|
||||
## 1.47.1
|
||||
|
||||
- **Event series.** Group events that come back — every year's camp, the monthly breakfast — on
|
||||
one page that shows what's coming up and what's been. Each event in a series links to the next one.
|
||||
- **Follow a series.** People can follow a series and get an email when the next event in it is
|
||||
out. It counts as news, so only people who chose to get news and announcements receive it.
|
||||
- A copied event stays in its series, and a series can have events at different campuses.
|
||||
|
||||
## 1.47.0
|
||||
|
||||
- **Copy an event.** Running the same camp, course or breakfast again? Press **Copy** on the event
|
||||
and the editor opens with everything filled in: tickets and prices, early birds, sessions, the
|
||||
form, feedback questions, certificates and groups.
|
||||
- **Pick the new start date** and every other date moves with it — sessions, deadlines and
|
||||
early-bird dates included. Check each step, change what's different this time, and save.
|
||||
- Registrations, coupons, attachments, kids check-in and volunteer roles aren't copied.
|
||||
|
||||
## 1.46.2
|
||||
|
||||
- **See what's new before you update.** When a new version is out, the Licence page lists what it
|
||||
brings, so you can decide whether you want it.
|
||||
- **Changed your mind?** Withdraw an update request, and your provider is told not to update the site.
|
||||
- **Not now:** hide the "update available" reminder until the next version comes out. Updates that
|
||||
fix a security problem or a serious bug are marked in red and can't be put off.
|
||||
- **Notices from your provider**, such as planned maintenance, now show as a banner for site admins
|
||||
and supervisors.
|
||||
|
||||
## 1.46.1
|
||||
|
||||
- Behind-the-scenes maintenance. Nothing changes for you.
|
||||
|
||||
## 1.46.0
|
||||
|
||||
- **Volunteer rosters:** set up serving roles (Welcome, Parking, Kids, Sound…) per event or session.
|
||||
Anyone with an account can sign up under My account → Serving, or supervisors can assign people.
|
||||
- Reminders by WhatsApp or email the day before a shift.
|
||||
- **"Can't make it" swaps:** a volunteer asks for cover, and the first to accept takes the place.
|
||||
- Volunteers check in by scanning the event's QR code; kids-room volunteers count as leaders on duty.
|
||||
- Roster sheet with phone numbers and check-in times, and hours served per person.
|
||||
- Fixed: the free kids check-in ticket was offered on the public event page.
|
||||
|
||||
## 1.45.1
|
||||
|
||||
- The built-in privacy notice and terms of use are brought up to date for kids check-in, sessions,
|
||||
certificates and campuses. If you published your own privacy notice, review it under Admin →
|
||||
Privacy.
|
||||
|
||||
## 1.45.0
|
||||
|
||||
- **Kids check-in:** a secure check-in and pickup for children's ministry, run from a staff desk, with
|
||||
no label printers needed.
|
||||
- Parents keep their children's details (allergies, medical and custody notes) and authorised adults
|
||||
under My account → Kids.
|
||||
- Each check-in gives the family a pickup code by WhatsApp or email; children can only be collected
|
||||
with the code.
|
||||
- Rooms with age ranges, capacity and ratios, live room screens, and an offline desk mode.
|
||||
|
||||
## 1.44.0
|
||||
|
||||
- **Staff for some campuses:** supervisors and staff can be limited to certain campuses (Admin →
|
||||
Users). They then see only those campuses' events, plus events for all campuses, everywhere in the
|
||||
dashboard, reports and the scanner.
|
||||
- The scanner says which campus a ticket is for.
|
||||
|
||||
## 1.43.0
|
||||
|
||||
- **Campuses** for churches with more than one campus (Site settings → Campuses, off by default).
|
||||
- Events belong to one campus or to all campuses; the public events page has a campus filter and
|
||||
each campus gets its own page.
|
||||
- Reports, dashboards, broadcasts and the daily summary can be filtered by campus.
|
||||
- People can choose their home campus on their profile.
|
||||
|
||||
## 1.42.1
|
||||
|
||||
- Behind-the-scenes improvements to licence checking. Nothing changes for you.
|
||||
|
||||
## 1.42.0
|
||||
|
||||
- **Request update:** when a new version is out, press Request update on Site settings → Licence and
|
||||
your provider updates the site for you.
|
||||
|
||||
## 1.41.3
|
||||
|
||||
- The platform is now called **Cross Events**. Nothing else changes, and everyone stays signed in.
|
||||
|
||||
## 1.41.2
|
||||
|
||||
- Fixed: the Background jobs page showed last-run times two hours ahead.
|
||||
|
||||
## 1.41.1
|
||||
|
||||
- A site without a licence is now read-only until a licence key is connected.
|
||||
- Fixed: a site whose licence was released kept showing it as active.
|
||||
|
||||
## 1.41.0
|
||||
|
||||
- **Licences:** the site connects to Cross Events with a licence key (Site settings → Licence) and
|
||||
checks in every 15 minutes with its version and health — never anyone's personal information.
|
||||
- After a licence's end date there's a grace period with a reminder for site admins.
|
||||
- Site admins see when a newer version is available.
|
||||
|
||||
## 1.40.0
|
||||
|
||||
- **POPIA toolkit, part 3:** a privacy readiness checklist with a score, and links to fix each item.
|
||||
- **Retention settings:** choose how long personal information is kept. Inactive accounts are warned
|
||||
and then anonymised after 5 years (on by default).
|
||||
- **Breach register:** record security incidents, with draft messages for the people affected and
|
||||
for the Information Regulator.
|
||||
|
||||
## 1.39.0
|
||||
|
||||
- **POPIA toolkit, part 2:** Admin → Privacy (POPIA).
|
||||
- Edit and publish your own privacy notice, with numbered versions, and ask everyone to accept a new
|
||||
version when it changes significantly.
|
||||
- A register of the outside services that handle personal information, a consent log, and an access
|
||||
log of who downloaded personal information.
|
||||
|
||||
## 1.38.0
|
||||
|
||||
- **POPIA toolkit, part 1:** a Privacy page for everyone (My account → Privacy): choose whether to get
|
||||
news by email or WhatsApp, download your data, ask for a correction or delete your account.
|
||||
- Bulk messages are either **event updates** (to everyone booked) or **news** (only to people who
|
||||
opted in, with an unsubscribe link). Replying STOP on WhatsApp stops news.
|
||||
- Admins handle correction and deletion requests under Admin → Data requests.
|
||||
|
||||
## 1.37.4
|
||||
|
||||
- Behind-the-scenes improvements to updating the site. Nothing changes for you.
|
||||
|
||||
## 1.37.3
|
||||
|
||||
- Behind-the-scenes fix. Nothing changes for you.
|
||||
|
||||
## 1.37.2
|
||||
|
||||
- **Payment status checks:** online payments whose confirmation never arrived from PayFast are found
|
||||
and recorded automatically, with a "Check status" button under Payments → Reconcile.
|
||||
- A "Test connection" button for the PayFast settings.
|
||||
|
||||
## 1.37.1
|
||||
|
||||
- "Pay online" is no longer offered when online payments are off or the amount is under R15; people
|
||||
are told to pay at the event instead.
|
||||
|
||||
## 1.37.0
|
||||
|
||||
- **PayFast:** a second online payment provider (card, instant EFT and more), set up in Site
|
||||
settings → Payments.
|
||||
- When more than one provider is on, people choose how to pay.
|
||||
|
||||
## 1.36.0
|
||||
|
||||
- **Site settings → Payments:** turn online payment providers on or off and choose their order.
|
||||
- Online payments must be at least R15; smaller balances are paid at the door.
|
||||
|
||||
## 1.35.1
|
||||
|
||||
- **Waitlist per session** on events where people pick sessions.
|
||||
- "All sessions" tickets let people choose which sessions they'll come to.
|
||||
- At the door, walk-ins can be booked straight into today's session.
|
||||
- Several fixes for per-session tickets and stock limits.
|
||||
|
||||
## 1.35.0
|
||||
|
||||
- **Pick sessions:** a multi-session event can let people choose which sessions to come to — day
|
||||
passes for a conference, or a weekly drop-in class — with a price per session.
|
||||
- Each session can have its own capacity, and tickets only scan on their own session.
|
||||
|
||||
## 1.34.0
|
||||
|
||||
- **Background jobs page** (Site settings → Background jobs): see every scheduled task, when it last
|
||||
ran, and run it now.
|
||||
- Scheduled tasks (reminders, summaries, backups) are more reliable and run on South African time.
|
||||
- Fixed: at the door, multi-day tickets showed as used up from the second session.
|
||||
|
||||
## 1.33.0
|
||||
|
||||
- **Multi-day events:** an event can run over several sessions (e.g. every Wednesday for 5 weeks);
|
||||
people register and pay once.
|
||||
- Check-in per session, optional reminders before each session, and late joining at a lower price.
|
||||
- **Attendance register** with ticks per session and Excel/PDF export.
|
||||
- **Completion certificates** with four designs, issued automatically, each with a QR code anyone can
|
||||
check.
|
||||
|
||||
## 1.32.0
|
||||
|
||||
- Event cards show an "Early bird" ribbon while early-bird pricing is running.
|
||||
|
||||
## 1.31.1
|
||||
|
||||
- A field for Google Search Console verification (Site settings → Organisation).
|
||||
|
||||
## 1.31.0
|
||||
|
||||
- The registration funnel recognises visits from Facebook, Instagram, Google and other sites without
|
||||
tagged links, and shows shares and QR code scans separately.
|
||||
- Events can appear in Google's event listings with their date, venue and tickets.
|
||||
|
||||
## 1.30.1
|
||||
|
||||
- All tickets — emailed, WhatsApped and printed — share one clean design, with bigger QR codes.
|
||||
|
||||
## 1.30.0
|
||||
|
||||
- People can add an optional **donation** when they register, paid together with their tickets.
|
||||
- Fixed: event pages with a waitlist could crash.
|
||||
|
||||
## 1.29.1
|
||||
|
||||
- The Coupon codes page is easier to use, including on phones, and hides codes that are off, expired
|
||||
or used up.
|
||||
|
||||
## 1.29.0
|
||||
|
||||
- Bundle deals come in four types: an exact set, pick any mix, buy X get Y free, and group discounts.
|
||||
|
||||
## 1.28.3
|
||||
|
||||
- Fixed: the bundle deals form didn't fit on the screen.
|
||||
|
||||
## 1.28.2
|
||||
|
||||
- The Bundle deals page has a new layout that works on phones.
|
||||
|
||||
## 1.28.1
|
||||
|
||||
- Bundle deals work at the door, in manual registration and on the self-service kiosk too.
|
||||
|
||||
## 1.28.0
|
||||
|
||||
- **Bundle deals:** sell a set of tickets together for one price, e.g. 2 adults + 3 kids for R220.
|
||||
They apply automatically, with no code, and the saving shows on invoices and receipts.
|
||||
|
||||
## 1.27.1
|
||||
|
||||
- Behind-the-scenes improvements to the demo data. Nothing changes for you.
|
||||
|
||||
## 1.27.0
|
||||
|
||||
- **Cashups** record where each payment method's money ended up: in the bank, cash on hand, or still
|
||||
pending. Card fees and bank charges can be written off with a reason.
|
||||
- Pending money can be marked received later without reopening the event.
|
||||
- Every dashboard page has the same "Back to dashboard" link.
|
||||
|
||||
## 1.26.1
|
||||
|
||||
- Behind-the-scenes improvements to the demo data. Nothing changes for you.
|
||||
|
||||
## 1.26.0
|
||||
|
||||
- Behind-the-scenes upgrades and security updates.
|
||||
- Fixed: the refund reason didn't show at the door.
|
||||
|
||||
## 1.25.1
|
||||
|
||||
- On phones, the cookie notice and the help button no longer hide each other or the menu.
|
||||
|
||||
## 1.25.0
|
||||
|
||||
- **Yoco settings** in Site settings: enter and check the secret key, and set up payment
|
||||
notifications with one click.
|
||||
|
||||
## 1.24.0
|
||||
|
||||
- **Ticket transfers** now need the new holder to accept, by a link sent to them.
|
||||
- Updated terms of use and privacy policy, with a full cookie policy and a "Cookie settings" link.
|
||||
- Fixed: activating an account didn't sign you in.
|
||||
|
||||
## 1.23.0
|
||||
|
||||
- **View as user:** admins can see the site exactly as someone else does, to help with problems.
|
||||
It's read-only, limited to 30 minutes and recorded in the audit log.
|
||||
|
||||
## 1.22.0
|
||||
|
||||
- **Registration funnel report:** see where people drop off between viewing an event and paying, by
|
||||
traffic source and device. Only visitors who allow it are counted.
|
||||
|
||||
## 1.21.0
|
||||
|
||||
- **Post-event feedback:** send a short survey after an event, with one reminder, and see the results
|
||||
in a Feedback summary report.
|
||||
- New form question types: star ratings and multiple choice.
|
||||
|
||||
## 1.20.0
|
||||
|
||||
- **Sponsor a spot:** people can pay for a place for someone who can't afford it, with an optional
|
||||
goal and progress bar.
|
||||
|
||||
## 1.19.0
|
||||
|
||||
- **Rooms & groups** for camps: put attendees into rooms, cabins, small groups or buses by drag and
|
||||
drop or automatically, with printable lists.
|
||||
- Events can ask each person's gender.
|
||||
|
||||
## 1.18.0
|
||||
|
||||
- **Ticket transfer:** hand a ticket to someone else before the event; the old QR code stops working.
|
||||
|
||||
## 1.17.0
|
||||
|
||||
- **Offline ticket scanning:** download an event's tickets to a device and keep scanning without a
|
||||
connection; scans sync when it's back online.
|
||||
|
||||
## 1.16.0
|
||||
|
||||
- **Waitlists** for sold-out tickets: when a place frees up, the next person is offered it
|
||||
automatically.
|
||||
|
||||
## 1.15.0
|
||||
|
||||
- **Parental consent** for youth events: parents give consent online, with optional medical and
|
||||
emergency details, before their child can be checked in.
|
||||
|
||||
## 1.14.0
|
||||
|
||||
- **Named attendees:** when booking for several people, each person can be named and get their own
|
||||
ticket.
|
||||
|
||||
## 1.13.0
|
||||
|
||||
- **Coupon codes:** percentage, fixed-amount or free codes, with limits on events, dates and uses.
|
||||
- Staff prices for tickets.
|
||||
- A Discounts report.
|
||||
|
||||
## 1.12.0
|
||||
|
||||
- Two-factor login is now required for admins and supervisors.
|
||||
|
||||
## 1.11.0
|
||||
|
||||
- **Two-factor login** for everyone who wants it: a code by email or WhatsApp after the password, and
|
||||
"Trust this device for 30 days".
|
||||
|
||||
## 1.10.6
|
||||
|
||||
- Security updates.
|
||||
|
||||
## 1.10.5
|
||||
|
||||
- Events that have started but not finished stay listed on the home and events pages.
|
||||
|
||||
## 1.10.4
|
||||
|
||||
- Fixed: "Add to calendar" didn't work.
|
||||
|
||||
## 1.10.3
|
||||
|
||||
- More admin actions are written to the audit log.
|
||||
|
||||
## 1.10.2
|
||||
|
||||
- Behind-the-scenes fix to error monitoring. Nothing changes for you.
|
||||
|
||||
## 1.10.1
|
||||
|
||||
- Security fixes for file uploads, and security updates.
|
||||
|
||||
## 1.10.0
|
||||
|
||||
- **Add to calendar** on event pages and in confirmation emails.
|
||||
- Better link previews and search engine listings for events.
|
||||
- **Nightly database backups**, which you can download from Site settings → Backups.
|
||||
- **Audit log** of refunds, donations, manual registrations, cancellations, event changes and
|
||||
settings changes.
|
||||
|
||||
## 1.9.5
|
||||
|
||||
- The site copes better with automated traffic probing for pages that don't exist.
|
||||
|
||||
## 1.9.4
|
||||
|
||||
- Behind-the-scenes server setting. Nothing changes for you.
|
||||
|
||||
## 1.9.3
|
||||
|
||||
- People registered at the door or by staff get their account activation link straight away.
|
||||
- Fixed: the self-service kiosk's "Choose a password" didn't work.
|
||||
|
||||
## 1.9.2
|
||||
|
||||
- Contact-only events no longer get a daily summary email.
|
||||
|
||||
## 1.9.1
|
||||
|
||||
- Fixed: the browser tab and home page showed the default name instead of your church's name.
|
||||
|
||||
## 1.9.0
|
||||
|
||||
- Events have a **location**, with a "Directions" link and a map on the event and contact pages.
|
||||
|
||||
## 1.8.0
|
||||
|
||||
- **Contact-only events** (e.g. baptism) show a "Contact us" button instead of registration.
|
||||
- **Invoices and receipts** as branded PDFs with registration and payment emails, with a "pay now"
|
||||
link and QR code.
|
||||
- Fixed: buying more tickets after early bird ended re-priced the tickets already bought.
|
||||
|
||||
## 1.7.0
|
||||
|
||||
- **Brand colours:** primary, secondary and accent colours across the whole site and emails, a
|
||||
favicon, and a live preview. Colours can be suggested from your logo.
|
||||
|
||||
## 1.6.0
|
||||
|
||||
- Supervisors can unassign a donation that was applied to a registration.
|
||||
- Faster payments and dashboards.
|
||||
|
||||
## 1.5.4
|
||||
|
||||
- The home page shows "My Dashboard" to people who are signed in.
|
||||
|
||||
## 1.5.3
|
||||
|
||||
- Fixed: help popups could be taller than a phone screen.
|
||||
|
||||
## 1.5.2
|
||||
|
||||
- Dashboard tiles and charts fit better on phones.
|
||||
|
||||
## 1.5.1
|
||||
|
||||
- Fixed: scheduled WhatsApp messages were sent as emails.
|
||||
|
||||
## 1.5.0
|
||||
|
||||
- **Site redesign:** a new look across the whole site, new dashboards with trends and top events, and
|
||||
a "Need help?" button with a guide on every page.
|
||||
- A separate Contact page, and recent sign-ins on Profile & Security.
|
||||
|
||||
## 1.4.2
|
||||
|
||||
- Fixes to how refunds and donations are counted in reports and cashups.
|
||||
|
||||
## 1.4.1
|
||||
|
||||
- Reports fit better on phones.
|
||||
|
||||
## 1.4.0
|
||||
|
||||
- **Reports redesigned:** filters that apply to every report, charts, and styled PDF and Excel
|
||||
exports, by email or WhatsApp too.
|
||||
- Cashups show who recorded each payment, with per-person cash counts.
|
||||
- A payment link placeholder for messages to attendees.
|
||||
|
||||
## 1.3.2
|
||||
|
||||
- The self-service kiosk is safer with returning visitors' details, and asks before changing them.
|
||||
|
||||
## 1.3.1
|
||||
|
||||
- The self-service kiosk can find a returning visitor's account.
|
||||
|
||||
## 1.3.0
|
||||
|
||||
- **Check-in at the door** by number of people, without scanning each QR code, and a confirmation
|
||||
message to the ticket holder.
|
||||
|
||||
## 1.2.0
|
||||
|
||||
- "Make payment" goes straight to paying the full balance.
|
||||
- Staff can record a payment straight after a manual registration.
|
||||
|
||||
## 1.1.0
|
||||
|
||||
- A payment history page in My account.
|
||||
- Registration status shows as a coloured badge.
|
||||
|
||||
## 1.0.1
|
||||
|
||||
- Closed and past events are tidied away in My Events.
|
||||
|
||||
## 1.0.0
|
||||
|
||||
- The first release.
|
||||
@@ -0,0 +1,118 @@
|
||||
# ─── Database ────────────────────────────────────────────────────────────────
|
||||
DATABASE_URL="postgresql://username:password@localhost:5432/hope_events"
|
||||
|
||||
# ─── Auth ─────────────────────────────────────────────────────────────────────
|
||||
JWT_SECRET=your_jwt_secret_here_minimum_32_characters
|
||||
|
||||
# Two-factor authentication is required for admins and supervisors whenever
|
||||
# email (SMTP) or WhatsApp can deliver a code. Set to false only as an emergency
|
||||
# switch, e.g. if the mail server is down and admins are locked out.
|
||||
# TWO_FACTOR_REQUIRED_ROLES=true
|
||||
|
||||
# ─── Server ───────────────────────────────────────────────────────────────────
|
||||
PORT=5000
|
||||
NODE_ENV=development
|
||||
|
||||
# Time zone for background job schedules (e.g. the 07:00 daily summary), session dates
|
||||
# and printed times. An IANA name, e.g. Africa/Johannesburg or Europe/London.
|
||||
APP_TIMEZONE=Africa/Johannesburg
|
||||
|
||||
# Set this if the app runs behind a reverse proxy (e.g. nginx on a separate
|
||||
# server) so rate limiting reads the real client IP instead of the proxy's.
|
||||
# Accepts a hop count ("1"), "true"/"false", or comma-separated IP(s)/CIDR(s)
|
||||
# of your trusted proxy (e.g. "10.0.0.5" or "10.0.0.0/8"). Leave unset if the
|
||||
# app is not behind a proxy.
|
||||
# TRUST_PROXY=1
|
||||
|
||||
# ─── CORS ─────────────────────────────────────────────────────────────────────
|
||||
# Comma-separated list of allowed frontend origins
|
||||
FRONTEND_URL=http://localhost:3000
|
||||
|
||||
# ─── Email (SMTP) — optional fallbacks ───────────────────────────────────────
|
||||
# Preferred: configure SMTP via Admin → Site Settings (stored AES-256 encrypted).
|
||||
# These env vars are used as fallbacks if no SMTP settings are saved in the DB.
|
||||
# EMAIL_HOST=smtp.example.com
|
||||
# EMAIL_PORT=587
|
||||
# EMAIL_USER=your_email@example.com
|
||||
# EMAIL_PASS=your_email_password
|
||||
# EMAIL_FROM=no-reply@example.com
|
||||
|
||||
# ─── Payments (Yoco) — optional fallbacks ─────────────────────────────────────
|
||||
# Preferred: set the secret key and generate the webhook in Admin → Site Settings →
|
||||
# Yoco (stored AES-256 encrypted). These are only used if the database has no value.
|
||||
# YOCO_SECRET_KEY=sk_test_...
|
||||
# YOCO_WEBHOOK_SECRET=whsec_...
|
||||
|
||||
# ─── Payments (PayFast) — optional fallbacks ──────────────────────────────────
|
||||
# Preferred: Admin → Site Settings → Payments → PayFast. Only used if the database has no value.
|
||||
# PAYFAST_MERCHANT_ID=
|
||||
# PAYFAST_MERCHANT_KEY=
|
||||
# PAYFAST_PASSPHRASE=
|
||||
# PAYFAST_MODE=sandbox
|
||||
# PayFast notifications (ITNs) must come from a PayFast address. Behind a reverse proxy, set
|
||||
# TRUST_PROXY so the real address is seen. Only for testing through a tunnel:
|
||||
# PAYFAST_SKIP_IP_CHECK=true
|
||||
|
||||
# ─── Public URLs ──────────────────────────────────────────────────────────────
|
||||
# Used to build links in emails (password reset, activation, etc.)
|
||||
APP_BASE_URL=https://your-frontend-domain.com
|
||||
# Used to serve ticket PDFs to WhatsApp (must be publicly reachable)
|
||||
BACKEND_URL=https://your-backend-domain.com
|
||||
|
||||
# ─── WhatsApp (WAWP) — optional, preferred stored via Admin → Site Settings ───
|
||||
# These are env-var fallbacks. Use the admin panel to manage them at runtime.
|
||||
WAWP_ACCESS_TOKEN=your_wawp_access_token
|
||||
WAWP_INSTANCE_ID=your_wawp_instance_id
|
||||
|
||||
# ─── Background workers ───────────────────────────────────────────────────────
|
||||
DAILY_SUMMARY_ENABLED=true
|
||||
SCHEDULED_EMAILS_ENABLED=true
|
||||
SCHEDULED_EMAILS_INTERVAL_MS=30000
|
||||
# Daily 09:00 parental-consent job: reminders, and deleting medical details after events
|
||||
CONSENT_JOBS_ENABLED=true
|
||||
# Waitlist: expire unclaimed offers and offer freed places (every 10 minutes by default)
|
||||
WAITLIST_JOB_ENABLED=true
|
||||
# WAITLIST_JOB_INTERVAL_MS=600000
|
||||
# Payments: every 15 minutes, look up PayFast checkouts whose notification never arrived
|
||||
PAYMENT_STATUS_JOB_ENABLED=true
|
||||
# Volunteer rosters: reminders the day before a shift (every 15 minutes)
|
||||
VOLUNTEER_JOBS_ENABLED=true
|
||||
SERIES_JOBS_ENABLED=true
|
||||
WEBHOOKS_JOBS_ENABLED=true
|
||||
WEBHOOKS_ENABLED=true
|
||||
# Local testing only: lets webhook endpoints and linked products be http:// or on a private network
|
||||
WEBHOOKS_ALLOW_PRIVATE=false
|
||||
# Linked products (2.4.0): publish the event feed every 5 minutes, fetch linked products' events every 15
|
||||
FEED_JOBS_ENABLED=true
|
||||
# Privacy (POPIA): daily 08:00 reminder to admins of data requests due within a week
|
||||
PRIVACY_JOBS_ENABLED=true
|
||||
# Privacy (POPIA): nightly 03:30 retention job (Admin → Privacy → Retention). Note: inactive
|
||||
# accounts are anonymised after 5 years by default (with a warning 30 days before).
|
||||
RETENTION_JOBS_ENABLED=true
|
||||
|
||||
# ─── Cross Events Hub (licence and health) ─────────────────────────────────────
|
||||
# Where the Hub runs. The site checks in every 15 minutes once connected (Site settings → Licence).
|
||||
# HUB_URL=https://events-hub.crosscode.co.za
|
||||
# For a local or test Hub only: its public key (the release has the production key built in).
|
||||
# HUB_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\n…\n-----END PUBLIC KEY-----"
|
||||
HUB_HEARTBEAT_ENABLED=true
|
||||
# Nightly database backup at 02:00 (requires the `pg_dump` binary on this host).
|
||||
# Retention count is set via Admin → Site Settings → Backups (default 14).
|
||||
BACKUP_ENABLED=true
|
||||
|
||||
# ─── Error monitoring (Sentry) — optional ─────────────────────────────────────
|
||||
# Leave unset to disable entirely (a no-op, not an error). Set NEXT_PUBLIC_SENTRY_DSN
|
||||
# in frontend/.env too if you want frontend errors captured.
|
||||
# SENTRY_DSN=https://xxxxx@oxxxxxx.ingest.sentry.io/xxxxx
|
||||
|
||||
# ─── Note ─────────────────────────────────────────────────────────────────────
|
||||
# The following are managed via Admin → Site Settings and stored in the database:
|
||||
# - Organisation name, tagline, contact details, branding colour, logo
|
||||
# - Registration notification emails
|
||||
# - SMTP settings (username and password stored AES-256-GCM encrypted, key
|
||||
# derived from JWT_SECRET — do not change JWT_SECRET after saving SMTP creds)
|
||||
# - Yoco secret key and webhook secret (encrypted the same way)
|
||||
# - Legal page content (operator name, Information Officer, website URL, etc.)
|
||||
# The first-time setup wizard handles initial configuration on fresh deployments.
|
||||
# You no longer need ORG_NAME, ORG_TAGLINE, EMAIL_HEADER_COLOR, REGISTRATIONS_EMAIL,
|
||||
# or SMTP vars in this file (they still work as fallbacks if the DB entry is absent).
|
||||
@@ -0,0 +1,16 @@
|
||||
# Cross Events — API Documentation
|
||||
|
||||
Since 2.0 the API is `/api/v2` only, described by **OpenAPI 3.1** generated from the route
|
||||
declarations (`backend/src/v2/`), so it is never out of date:
|
||||
|
||||
- **Reference:** `/docs/v2` on the running backend (admin token).
|
||||
- **Document:** `GET /api/v2/openapi.json` (admin); the frontend's copy is
|
||||
`frontend/src/lib/api-v2/openapi.json` (regenerate with `npm run api:types` in the repo root).
|
||||
|
||||
Every answer is `{ "data": … }`; lists add `meta: { page, limit, total, pages }` (`?page=&limit=`);
|
||||
errors are `{ "error": { "code", "message", "reason"?, "fields"? } }`. Send the sign-in token as
|
||||
`Authorization: Bearer <token>` (`POST /api/v2/auth/login`).
|
||||
|
||||
Version 1 (`/api/…`) was removed in 2.0 and answers `410 Gone`, except the incoming webhooks and the
|
||||
links in messages already sent. What changed and the full v1 → v2 table are in
|
||||
[MIGRATING-TO-2.md](../MIGRATING-TO-2.md). The old v1 reference is in git history (tag `v1.52.3`).
|
||||
@@ -0,0 +1,204 @@
|
||||
# Demo data
|
||||
|
||||
The demo seeds replace everything in the database with a realistic set of demo data, for
|
||||
showing the platform to other churches. Pick the one that looks like the church you're
|
||||
showing it to:
|
||||
|
||||
| Command (repo root) | For | What's in it |
|
||||
|---|---|---|
|
||||
| `npm run demo:small` | A small church, one congregation | 3 upcoming events (a sold-out breakfast with a waitlist, a family day, free carols), 4 past events with check-ins and cashups. No campuses, kids check-in, rosters, courses or series. |
|
||||
| `npm run demo:events` | Events and conferences (the original demo) | 6 upcoming events (coupons, variants, early birds, a youth camp with consent and cabins, bundles, donations) and 10 past events with every kind of cashup and funnel analytics. |
|
||||
| `npm run demo:ministry` | One campus with weekly ministry | The Alpha Course running now (sessions, attendance, late joining, certificates), a finished Marriage Course with certificates, a 3-day conference sold by day, **Kids Church** with families, children, rooms and check-ins, **volunteer rosters**, a **Men's Breakfast series** with followers and a **season pass**, plus a family day, women's conference and carols. |
|
||||
| `npm run demo:multicampus` | A church with several campuses | **Campuses** Central, North and South (switched on), events per campus and church-wide, home campuses, staff limited to a campus (Anri Botha → North, Daniel Pillay → South), the breakfast series moving between campuses, kids church and rosters at two campuses, and all the events-demo events spread over the campuses. |
|
||||
|
||||
`npm run demo:list` prints the same list. Kids church always has a session **today** with
|
||||
children checked in right now, so the kids desk and room screens have something live to
|
||||
show on any day.
|
||||
|
||||
> **This deletes real data.** Run it only against a database you're happy to wipe, such
|
||||
> as a dedicated demo deployment. It is not something to run on a live church site.
|
||||
|
||||
---
|
||||
|
||||
## Running it
|
||||
|
||||
```bash
|
||||
npm run demo:ministry # (repo root) shows the database it will wipe and asks you to type "demo"
|
||||
npm run demo:ministry -- --yes # no prompt (for scripts)
|
||||
# or in backend/:
|
||||
npm run set-demo -- --profile=ministry --yes # without --profile it seeds "events"
|
||||
```
|
||||
|
||||
The campuses setting is switched on for `multicampus` and off for the others (site settings
|
||||
are otherwise kept). **Restart the backend afterwards** so it picks the setting up.
|
||||
|
||||
The script uses `DATABASE_URL` from `backend/.env`. To point it at another database
|
||||
for one run, set it in the environment first. A value already in the environment wins
|
||||
over `.env`:
|
||||
|
||||
```bash
|
||||
DATABASE_URL="postgresql://user:pass@host:5432/hope_demo" npm run set-demo
|
||||
```
|
||||
|
||||
It takes about five seconds and is safe to re-run as often as you like. Each run wipes the
|
||||
previous demo and creates it again.
|
||||
|
||||
### Before you run it
|
||||
|
||||
- The admin account must already exist. By default that's `joshua@crosscode.co.za`.
|
||||
To keep a different account, set `DEMO_ADMIN_EMAIL`:
|
||||
```bash
|
||||
DEMO_ADMIN_EMAIL="admin@example.org" npm run set-demo
|
||||
```
|
||||
If the account isn't found, the script stops before changing anything.
|
||||
- Migrations must be up to date (`npm run prisma:deploy`).
|
||||
|
||||
---
|
||||
|
||||
## What it keeps and what it clears
|
||||
|
||||
| Kept | Cleared |
|
||||
|---|---|
|
||||
| Site settings (`AppSetting`): org name, branding, SMTP, Yoco, WhatsApp, legal pages | Every event, with its options, variants, early-bird tiers, sections, forms, costs and cash-ups |
|
||||
| The admin account, including its login history, trusted devices and 2FA | Every other user |
|
||||
| Migration history | Registrations, payments, tickets, scans, coupons, waitlists, consents, cabins, feedback, analytics, audit log |
|
||||
| Uploaded files on disk (`public/uploads`) | Queued scheduled emails/WhatsApps (`data/scheduled-emails.json`) |
|
||||
|
||||
The wipe and the new data are written in one database transaction. If that fails,
|
||||
nothing changes. The past events' cashups run straight afterwards, through the same
|
||||
code as the cashup screen. If one of those fails, re-run the script.
|
||||
|
||||
---
|
||||
|
||||
## What it creates
|
||||
|
||||
### Upcoming events
|
||||
|
||||
All dates are worked out from the day you run it, so these events are always upcoming.
|
||||
Registrations are spread over the past month, as if sign-ups have been coming in.
|
||||
The data is generated from a fixed seed, so every run looks the same.
|
||||
|
||||
| When (from today) | Event | Shows off |
|
||||
|---|---|---|
|
||||
| ~1½ weeks, Sat 07:30 | **Men's Breakfast: Built to Last** | **Sold out** (60 places), 5 people on the **waitlist**, card / cash / EFT payments recorded by staff, 2 cancelled registrations |
|
||||
| ~2½ weeks, Sat 10:00 | **Family Fun Day** | Adult and child tickets with a **bundle deal** (Family deal: 2 adults + 3 kids for R220 instead of R280, used by about a third of registrations) and a **pick-any** deal (Lunch for four: any 4 lunch packs for R220), a non-ticket **add-on** (lunch pack), a fixed-amount **coupon** (`FUNDAY20`), entry and food-stall check-in sections |
|
||||
| ~5 weeks, Fri–Sat | **Rooted Women's Conference** | Two **early-bird tiers** (one already expired, one still open) plus a Saturday-only ticket, T-shirt **variants** (S–XXL), a **required sign-up form** (dietary needs, workshop choice, prayer requests), a 20% **group coupon** (`ROOTED20`) used by 4 registrations |
|
||||
| ~7 weeks, Mon–Thu | **Ignite Summer Camp** | **Named attendees** (campers aged 12–17), signed **parental consent**, gender collected, **deposits and part-payments**, campers placed in boys' and girls' **cabins** with staff leaders, **sponsor-a-spot** donations towards a 10-spot goal |
|
||||
| ~8 weeks, Sun 19:00 | **Carols by Candlelight** | A **free event** with group tickets (1–6 people), plus general **donations** |
|
||||
| ~14 weeks, Fri–Sun | **Marriage Enrichment Weekend** | Room-type **variants with limited stock**, early-bird prices per room type, a per-person spa add-on, R1 000 EFT deposits |
|
||||
|
||||
Each event also gets:
|
||||
|
||||
- A cover photo (from Unsplash, which `next.config` already allows) and a contact person.
|
||||
- **Costs**, both once-off and per item, so the profit view and cash-up have figures.
|
||||
- About 30 days of **funnel analytics** (views → started → submitted → paid) by source
|
||||
(WhatsApp, Facebook, Instagram, email, direct) and device.
|
||||
|
||||
Paid registrations have tickets with QR codes, the same way the app issues them once
|
||||
payment is complete. Part-paid and pending ones don't have tickets yet.
|
||||
|
||||
### Past events
|
||||
|
||||
Ten completed events spread over the past year, for showing cashups and the historical
|
||||
reports. Each one has:
|
||||
|
||||
- Online sales in the five weeks before the event, with a few unpaid no-shows.
|
||||
- **Door sales** on the day, recorded by the staff team (cash and card machine).
|
||||
- **Check-ins**: about 90% of tickets scanned, with the odd group arriving short.
|
||||
- **Staff cash counts** with note and coin denominations.
|
||||
|
||||
Some events also have refunds, donations and post-event feedback.
|
||||
|
||||
The cashups cover every path through the cashup screen:
|
||||
|
||||
| When | Event | Cashup to demo |
|
||||
|---|---|---|
|
||||
| ~11 months ago | **Church Family Picnic** | **Quick closed** (no settlement) |
|
||||
| 24 Dec | **Christmas Eve Candlelight Service** | Free event with card and cash **donations**. Card settled net of **Yoco fees**, collection banked |
|
||||
| Easter Sunday | **Easter Sunrise Service & Breakfast** | Cash banked less a **cash deposit fee** (bank charge), card fees, a **refund** |
|
||||
| Mother's Day | **Mother's Day Brunch** | **Closed with R50 cash short → reopened → recounted → closed again.** The history shows all three steps |
|
||||
| ~3½ months ago | **Youth Winter Camp** | Deposits and balances. **EFT pending** (POPs) at close, later **marked received** without reopening |
|
||||
| ~2½ months ago | **Men's Golf Day** | Card-heavy, card fees written off, a refund |
|
||||
| ~2 months ago | **Kids Holiday Club** | Cash-heavy door sales. **R20 cash shortfall written off**, **R500 kept on hand** as float |
|
||||
| ~6 weeks ago | **Women's High Tea** | Closed with **R30 unaccounted**, shown in red |
|
||||
| ~4 weeks ago | **Missions Fundraiser Dinner** | **R2 600 EFT still pending** (POP received, not cleared). Shows "Mark received" / "Write off" |
|
||||
| ~10 days ago | **Worship Night** | **Still open, with the cash already counted.** Use it to do a cashup live in the demo |
|
||||
|
||||
Easter, the Youth Camp, the Holiday Club and the High Tea have **feedback forms** with
|
||||
ratings and comments. Funnel stats older than 90 days are stored as daily totals, the
|
||||
way the app rolls them up overnight, so the funnel report covers the whole year.
|
||||
|
||||
### Totals
|
||||
|
||||
A typical run gives roughly:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Users | 130 (plus the admin) |
|
||||
| Registrations | ~700 (paid, part-paid, pending, cancelled and refunded) |
|
||||
| Payments | ~640, including donations, sponsorships and refunds |
|
||||
| Tickets | ~780, with ~490 check-ins |
|
||||
| Named campers | ~45 |
|
||||
| Feedback responses | ~80 |
|
||||
| Funnel rows | ~4 400 |
|
||||
|
||||
---
|
||||
|
||||
## Logging in
|
||||
|
||||
Every demo account uses the password **`Demo@1234`**.
|
||||
|
||||
| Role | Email | Good for showing |
|
||||
|---|---|---|
|
||||
| Supervisor | `lerato.khumalo@example.com` | Event setup, reports, coupons, viewing cashups |
|
||||
| Staff | `sipho.dlamini@example.com` | At-the-door payments and check-in scanning |
|
||||
| Staff | `anri.botha@example.com` | |
|
||||
| Staff | `daniel.pillay@example.com` | |
|
||||
|
||||
Closing, reopening and settling pending money in a cashup are admin-only, so do the
|
||||
live Worship Night cashup as your own admin account.
|
||||
|
||||
The other 126 people are ordinary members (role `user`), with emails like
|
||||
`thandi.mokoena@example.com`. Log in as one of them to show the member view: their
|
||||
registrations, tickets and payments. Any registrant's email from an event's attendee
|
||||
list works.
|
||||
|
||||
Your own admin account keeps its existing password.
|
||||
|
||||
---
|
||||
|
||||
## Safety
|
||||
|
||||
- **Nothing is sent.** The script writes straight to the database and never calls the
|
||||
email, WhatsApp or Yoco code.
|
||||
- **Nothing can reach a real person later.** Demo people use `@example.com` addresses
|
||||
(a reserved domain that can't receive mail) and have **no phone numbers**, so
|
||||
reminders or broadcasts sent during a demo go nowhere. All parental consents are
|
||||
already signed, so no consent reminders go out.
|
||||
- Card payments have made-up Yoco ids (`demo_…`). They don't exist in Yoco, so leave
|
||||
the demo site's Yoco settings in test mode or empty.
|
||||
|
||||
---
|
||||
|
||||
## Customising
|
||||
|
||||
Everything lives in [`scripts/set-demo.js`](scripts/set-demo.js). There is one
|
||||
`build…()` function per event (`buildMensBreakfast`, `buildYouthCamp`, …), and
|
||||
`main()` decides which ones run. To change an event's name, prices, ticket types or
|
||||
number of registrations, edit its function. To add an event, write a new `build…()`
|
||||
and add it to the list in `main()`. `addBundle(event, { name, price }, [[option, quantity], …])`
|
||||
adds a bundle deal. Registrations added after it get the deal automatically, worked out
|
||||
the same way as the app does it.
|
||||
|
||||
The past events are in `buildPastEvents()`, one spec each: dates, ticket types, costs,
|
||||
how many people bought online and at the door, and a `cashup` that says how it was
|
||||
closed. Supported closes:
|
||||
- `'quick'`
|
||||
- `'full'`, with `lines` saying where the money ended up
|
||||
- `'reclose'`
|
||||
- `'none'`, which leaves the event open
|
||||
|
||||
A full close can add `later` to settle pending money after closing. The helpers
|
||||
`cardLine`, `eftLine` and `cashLine` build the usual settlements: card net of Yoco fees,
|
||||
EFT with an optional pending POP, and cash banked with an optional float, deposit fee or
|
||||
shortfall.
|
||||
@@ -0,0 +1,555 @@
|
||||
# Cross Events — Backend API
|
||||
|
||||
Node.js + Express REST API for the Cross Events platform used by Hope Family Church (`events.hopehenley.co.za`).
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Overview](#overview)
|
||||
2. [Tech Stack](#tech-stack)
|
||||
3. [Prerequisites](#prerequisites)
|
||||
4. [Installation](#installation)
|
||||
5. [Environment Variables](#environment-variables)
|
||||
6. [Database](#database)
|
||||
7. [Running the Server](#running-the-server)
|
||||
8. [Authentication & Roles](#authentication--roles)
|
||||
9. [API Reference](#api-reference)
|
||||
10. [Background Workers](#background-workers)
|
||||
11. [Notification System](#notification-system)
|
||||
12. [WhatsApp Integration](#whatsapp-integration)
|
||||
13. [File Uploads](#file-uploads)
|
||||
14. [Payments (Yoco)](#payments-yoco)
|
||||
15. [Deployment](#deployment)
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Full-stack event management backend handling:
|
||||
- User registration, authentication (JWT), and role-based access control
|
||||
- Event creation, management, and public listings
|
||||
- Attendee registration with optional payment tiers and early-bird pricing
|
||||
- Yoco checkout integration with webhook reconciliation
|
||||
- Ticket generation (PDF + QR code) and email/WhatsApp delivery
|
||||
- Scheduled bulk messaging (email + WhatsApp) for attendees and broadcast lists
|
||||
- Admin WhatsApp instance management via WAWP
|
||||
|
||||
---
|
||||
|
||||
## Tech Stack
|
||||
|
||||
| Layer | Technology |
|
||||
|-------|-----------|
|
||||
| Runtime | Node.js 18+ |
|
||||
| Framework | Express 4 |
|
||||
| Database | PostgreSQL (via Prisma ORM 5) |
|
||||
| Auth | JWT (`jsonwebtoken`), `bcryptjs` |
|
||||
| Email | Nodemailer (any SMTP — configured via Admin → Site Settings, AES-256 encrypted in DB) |
|
||||
| WhatsApp | WAWP REST API (`api.wawp.net/v2`) |
|
||||
| PDF/QR | PDFKit, QRCode |
|
||||
| File Uploads | Multer |
|
||||
| Payments | Yoco |
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 18+
|
||||
- PostgreSQL 14+ (hosted at `database.crosscode.co.za` for production)
|
||||
- npm
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm install # installs deps and runs `prisma generate`
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Create `backend/.env` from `.env.example`. The only variables you must set are:
|
||||
|
||||
| Variable | Required | Description |
|
||||
|----------|----------|-------------|
|
||||
| `DATABASE_URL` | Yes | PostgreSQL connection string |
|
||||
| `JWT_SECRET` | Yes | Secret key for JWTs (32+ random characters). Also used to derive the AES-256 encryption key for sensitive settings (SMTP credentials) stored in the DB — must be set before saving SMTP settings. |
|
||||
| `FRONTEND_URL` | Yes | Comma-separated allowed CORS origins |
|
||||
| `YOCO_SECRET_KEY` | — | Fallback Yoco secret API key (preferred: set via Admin → Site Settings → Yoco) |
|
||||
| `YOCO_WEBHOOK_SECRET` | — | Fallback Yoco webhook secret (preferred: generate or enter it via Admin → Site Settings → Yoco) |
|
||||
| `APP_BASE_URL` | — | Public frontend URL — used in email links (fallback if not set via admin panel) |
|
||||
| `BACKEND_URL` | — | Public backend URL — used to serve ticket PDFs over WhatsApp |
|
||||
| `PORT` | — | Port to listen on (default `3000`) |
|
||||
| `TRUST_PROXY` | — | Set when running behind a reverse proxy (e.g. nginx on a separate server), so `req.ip`/`X-Forwarded-For` are read correctly by rate limiting. Accepts a hop count (`1`), `true`/`false`, or comma-separated trusted proxy IP(s)/CIDR(s). |
|
||||
| `NODE_ENV` | — | `production` or `development` |
|
||||
| `WAWP_ACCESS_TOKEN` | — | WAWP fallback token (preferred: set via Admin → Site Settings) |
|
||||
| `WAWP_INSTANCE_ID` | — | WAWP fallback instance ID (preferred: set via Admin → Site Settings) |
|
||||
| `DAILY_SUMMARY_ENABLED` | — | `false` to disable daily summaries (default `true`) |
|
||||
| `SCHEDULED_EMAILS_ENABLED` | — | `false` to disable scheduled-send worker (default `true`) |
|
||||
| `SCHEDULED_EMAILS_INTERVAL_MS` | — | Polling interval in ms (default `30000`) |
|
||||
| `SMTP_HOST` / `EMAIL_HOST` | — | Fallback SMTP host (preferred: set via Admin → Site Settings) |
|
||||
| `SMTP_PORT` / `EMAIL_PORT` | — | Fallback SMTP port |
|
||||
| `SMTP_USER` / `EMAIL_USER` | — | Fallback SMTP username |
|
||||
| `SMTP_PASS` / `EMAIL_PASS` | — | Fallback SMTP password |
|
||||
| `MAIL_FROM` / `EMAIL_FROM` | — | Fallback from address |
|
||||
|
||||
> **Organisation name, branding colour, logo, registration notification email, SMTP settings, and legal page content** are now managed through the admin panel at **Admin → Site Settings** and stored in the database. You no longer need `ORG_NAME`, `ORG_TAGLINE`, `EMAIL_HEADER_COLOR`, `REGISTRATIONS_EMAIL`, or SMTP vars in `.env` (they still work as fallbacks). On a fresh deployment these are set via the first-time setup wizard.
|
||||
>
|
||||
> **SMTP credentials** (`smtp_user`, `smtp_pass`) and the **Yoco secret key and webhook secret** are stored **AES-256-GCM encrypted** in the database. The encryption key is derived from `JWT_SECRET`. Do not change `JWT_SECRET` after saving them — the stored values will become unreadable.
|
||||
>
|
||||
> To move existing Yoco values from `.env` into the database, run `npm run migrate:env-to-db` (or save them in the Yoco tab).
|
||||
|
||||
---
|
||||
|
||||
## Database
|
||||
|
||||
### Schema summary
|
||||
|
||||
| Model | Purpose |
|
||||
|-------|---------|
|
||||
| `User` | Accounts with roles (`admin`, `supervisor`, `staff`, `user`) |
|
||||
| `Event` | Events with dates, pricing, options, attachments |
|
||||
| `EventOption` | Ticket types / items per event; `stockLimit` (0 = unlimited), `isMainTicket` flag |
|
||||
| `EarlyBirdTier` | Time-limited discounted prices; linked to an `EventOption` (option-level) or an `OptionVariant` (variant-level via nullable `variantId`); `stockLimit` (0 = unlimited) |
|
||||
| `OptionVariant` | Sub-items per option (size, colour, ticket type); optional `price` override; own `stockLimit` |
|
||||
| `Registration` | A user's registration for an event; `status`: pending/confirmed/partial_paid/paid/cancelled |
|
||||
| `RegistrationOption` | Which options (and quantities) a registration includes; `priceSnapshot`, `appliedTierId`, `variantId` |
|
||||
| `Payment` | Payment records (Yoco, manual, donation, refund) |
|
||||
| `Ticket` | QR-code tickets linked to registration options |
|
||||
| `TicketUsage` | Scan log for each ticket redemption |
|
||||
| `PasswordReset` | One-time tokens for password reset flow |
|
||||
| `EventAttachment` | Files attached to events (PDFs, images) |
|
||||
| `EventForm` / `EventFormField` | Per-event custom forms |
|
||||
| `FormResponse` / `FormAnswer` | Submitted form data from attendees |
|
||||
| `FormDraft` | Auto-saved in-progress form data |
|
||||
| `YocoTransaction` | Raw webhook events from Yoco for reconciliation |
|
||||
| `Section` / `SectionOption` | Grouping of event options into sections |
|
||||
| `AppSetting` | Key-value store for runtime config — WAWP credentials, org name, branding, notification emails, SMTP settings (credentials stored AES-256-GCM encrypted), legal page content |
|
||||
|
||||
### Migrations
|
||||
|
||||
```bash
|
||||
# Apply pending migrations (production)
|
||||
npm run prisma:deploy
|
||||
|
||||
# Check migration status
|
||||
npm run prisma:status
|
||||
|
||||
# Regenerate Prisma client after schema changes
|
||||
npm run prisma:generate
|
||||
```
|
||||
|
||||
### Demo data
|
||||
|
||||
`npm run set-demo -- --profile=<small|events|ministry|multicampus>` wipes the database (keeping site settings and the admin account) and stages demo data for that kind of church; from the repo root it's `npm run demo:<name>` (`npm run demo:list` describes them). See [DEMO_DATA.md](DEMO_DATA.md).
|
||||
|
||||
---
|
||||
|
||||
## Running the Server
|
||||
|
||||
```bash
|
||||
# Development (auto-reload; runs the TypeScript in src/ through tsx)
|
||||
npm run dev
|
||||
|
||||
# Production: build once per update, then start (src/index.js runs the build in dist/)
|
||||
npm run build
|
||||
npm start
|
||||
|
||||
# Type-check only
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Since 1.51.0 the backend is partly TypeScript (`allowJs`: `.js` compiles as it is, `.ts` is checked
|
||||
strictly). `src/index.js` is a small launcher: with plain Node it runs `dist/` when `dist/build.json`
|
||||
matches this version, otherwise it compiles on the fly with tsx. The server itself is `src/app.js`.
|
||||
|
||||
Visit `/` for the status page. Visit `/docs?token=<admin-jwt>` for the v1 API documentation and `/docs/v2` for the v2 (OpenAPI) reference — both admin only.
|
||||
|
||||
---
|
||||
|
||||
## Authentication & Roles
|
||||
|
||||
All protected routes require a `Bearer` token in the `Authorization` header:
|
||||
|
||||
```
|
||||
Authorization: Bearer <jwt>
|
||||
```
|
||||
|
||||
Tokens are issued on `POST /api/users/login`. Token version is stored per-user; revoking sessions increments the version and invalidates all existing tokens for that user.
|
||||
|
||||
### Role Hierarchy
|
||||
|
||||
| Role | Description |
|
||||
|------|-------------|
|
||||
| `admin` | Full access — user management, delete operations, WhatsApp admin, payment stats |
|
||||
| `supervisor` | Event/registration/payment management, bulk messaging, reports |
|
||||
| `staff` | Read access to registrations, payments, tickets; ticket scanning |
|
||||
| `user` | Own profile, own registrations, own tickets |
|
||||
|
||||
### Middleware
|
||||
|
||||
| Middleware | Applied when |
|
||||
|-----------|-------------|
|
||||
| `protect` | Any authenticated route |
|
||||
| `admin` | Admin-only actions |
|
||||
| `supervisor` | Supervisor + admin |
|
||||
| `staff` | Staff + supervisor + admin |
|
||||
| `optionalAuth` | Routes that work for guests but enrich responses if authenticated |
|
||||
| `loginLimiter` | Rate-limits login to 15 req/min per IP |
|
||||
|
||||
---
|
||||
|
||||
## API Reference
|
||||
|
||||
Full interactive API docs available at `GET /docs` (requires admin JWT — pass via `?token=<jwt>` query param or `Authorization: Bearer` header).
|
||||
|
||||
### Quick reference by domain
|
||||
|
||||
#### Users — `/api/users`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/` | public | Register a new account |
|
||||
| POST | `/login` | public | Login, returns JWT |
|
||||
| POST | `/forgot` | public | Request password reset email |
|
||||
| POST | `/reset` | public | Reset password with token |
|
||||
| POST | `/activate` | public | Activate account from email link |
|
||||
| GET | `/profile` | user+ | Get own profile |
|
||||
| PUT | `/profile` | user+ | Update own profile |
|
||||
| POST | `/revoke-sessions` | user+ | Revoke own sessions |
|
||||
| POST | `/close-account` | user+ | Deactivate own account |
|
||||
| GET | `/` | supervisor+ | List all users (paginated); supports `?search=`, `?role=`, `?isActive=true\|false`, `?page=`, `?limit=` |
|
||||
| GET | `/:id` | admin | Get user by ID |
|
||||
| PUT | `/:id` | admin | Update user |
|
||||
| DELETE | `/:id` | admin | Deactivate user (sets `isActive: false`) |
|
||||
| POST | `/:id/revoke-sessions` | admin | Revoke all sessions for a user |
|
||||
| POST | `/:id/anonymize` | admin | Erase personal data — sets name to "Deleted User", clears email/phone, deactivates account, revokes all sessions |
|
||||
|
||||
#### Events — `/api/events`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| GET | `/` | public | List public/active upcoming events; response includes `isSoldOut: boolean` per event |
|
||||
| GET | `/all` | staff+ | All events including hidden/past |
|
||||
| GET | `/admin/all` | admin | All events (admin view) |
|
||||
| GET | `/attachments/status` | admin | Attachment manifest sync status |
|
||||
| POST | `/attachments/sync` | admin | Re-sync attachment manifests to DB |
|
||||
| GET | `/:id` | public | Get event by ID |
|
||||
| GET | `/by-alias/:redirectUrl` | public | Get event by redirect alias |
|
||||
| POST | `/` | supervisor+ | Create event |
|
||||
| PUT | `/:id` | supervisor+ | Update event |
|
||||
| DELETE | `/:id` | admin | Delete event |
|
||||
| GET | `/:id/attachments` | public | List event file attachments |
|
||||
| POST | `/:id/attachments` | supervisor+ | Upload attachment |
|
||||
| DELETE | `/:eventId/attachments/:id` | supervisor+ | Delete attachment |
|
||||
| POST | `/:id/email-attendees` | supervisor+ | Bulk email attendees (supports `dryRun`) |
|
||||
| POST | `/:id/email-attendees/schedule` | supervisor+ | Schedule bulk email |
|
||||
| POST | `/:id/whatsapp-attendees` | supervisor+ | Bulk WhatsApp to attendees (supports `dryRun`) |
|
||||
| POST | `/:id/whatsapp-attendees/schedule` | supervisor+ | Schedule bulk WhatsApp |
|
||||
| POST | `/:id/options` | supervisor+ | Add event option |
|
||||
| PUT | `/options/:id` | supervisor+ | Update event option |
|
||||
| DELETE | `/options/:id` | admin | Delete event option |
|
||||
|
||||
#### Registrations — `/api/registrations`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/` | optional | Create registration |
|
||||
| GET | `/myregistrations` | user+ | Own registrations |
|
||||
| PUT | `/:id/options` | user+ | Update registration options |
|
||||
| DELETE | `/:id` | user+ | Cancel registration |
|
||||
| GET | `/:id` | optional | Get registration by ID |
|
||||
| GET | `/:id/forms/draft` | optional | Get form draft |
|
||||
| PUT | `/:id/forms/draft` | optional | Save form draft |
|
||||
| POST | `/:id/forms/responses` | optional | Submit form responses |
|
||||
| PUT | `/:id/forms/responses` | supervisor+ | Replace form responses |
|
||||
| GET | `/` | staff+ | List all registrations |
|
||||
| PUT | `/:id` | staff+ | Update registration status |
|
||||
| GET | `/event/:eventId` | staff+ | Registrations for an event |
|
||||
| POST | `/manual` | supervisor+ | Manual registration |
|
||||
|
||||
#### Payments — `/api/payments`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/` | supervisor+ | Record manual payment |
|
||||
| POST | `/yoco-checkout` | user+ | Initiate Yoco checkout |
|
||||
| GET | `/mypayments` | user+ | Own payments |
|
||||
| GET | `/:id` | user+ | Payment by ID |
|
||||
| GET | `/registration/:registrationId` | user+ | Payments for a registration |
|
||||
| GET | `/` | supervisor+ | All payments |
|
||||
| GET | `/event/:eventId` | staff+ | Payments for an event |
|
||||
| PUT | `/assign-donation` | supervisor+ | Assign donation to registration |
|
||||
| POST | `/refund` | supervisor+ | Create refund |
|
||||
| GET | `/admin/stats` | admin | Payment statistics |
|
||||
|
||||
#### Tickets — `/api/tickets`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| GET | `/mytickets` | user+ | Own tickets |
|
||||
| GET | `/:id` | user+ | Ticket by ID |
|
||||
| POST | `/email` | user+ | Email own tickets |
|
||||
| POST | `/send-to` | staff+ | Send tickets to a specific user |
|
||||
| GET | `/scan-preview/:qrCode` | staff+ | Preview scan (no mark) |
|
||||
| GET | `/qr/:qrCode` | staff+ | Ticket by QR code |
|
||||
| POST | `/scan/:qrCode` | staff+ | Scan/redeem ticket |
|
||||
| GET | `/event/:eventId` | staff+ | All tickets for event |
|
||||
| GET | `/scans/recent` | staff+ | Recent scan activity |
|
||||
| GET | `/scans/stats` | staff+ | Scan statistics |
|
||||
| POST | `/generate` | supervisor+ | Generate tickets for registration |
|
||||
| GET | `/` | supervisor+ | All tickets |
|
||||
| PUT | `/email-sent` | admin | Bulk mark tickets as emailed |
|
||||
|
||||
#### Webhooks — `/api/webhooks`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/yoco` | HMAC | Yoco payment webhook |
|
||||
| POST | `/whatsapp` | — | WAWP inbound webhook |
|
||||
|
||||
#### Broadcasts — `/api/broadcasts` (email)
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/preview` | supervisor+ | Dry-run, returns recipient count/sample |
|
||||
| POST | `/send` | supervisor+ | Send email broadcast |
|
||||
| POST | `/schedule` | supervisor+ | Schedule email broadcast |
|
||||
|
||||
#### WhatsApp Broadcasts — `/api/whatsapp-broadcasts`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/preview` | supervisor+ | Dry-run |
|
||||
| POST | `/send` | supervisor+ | Send WA broadcast |
|
||||
| POST | `/schedule` | supervisor+ | Schedule WA broadcast |
|
||||
|
||||
#### Scheduled Messages — `/api/scheduled-emails`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| GET | `/` | supervisor+ | List all scheduled jobs |
|
||||
| PATCH | `/:id` | supervisor+ | Edit a queued job |
|
||||
| DELETE | `/:id` | supervisor+ | Cancel a queued job |
|
||||
|
||||
#### Automations — `/api/automations`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/schedule` | supervisor+ | Schedule event lifecycle automations |
|
||||
|
||||
#### Reports — `/api/reports`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/pdf` | user+ | Generate and download PDF report |
|
||||
| POST | `/email` | user+ | Email PDF report to current user |
|
||||
|
||||
#### Settings — `/api/settings`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| GET | `/` | public | Public settings (org name, colour, logo, legal keys, etc.) |
|
||||
| GET | `/all` | admin | All settings — `smtp_pass` returned masked (`••••••••`), `smtp_user` decrypted |
|
||||
| GET | `/needs-setup` | public | `{ needsSetup: bool }` — true until setup wizard completes |
|
||||
| PUT | `/` | admin | Upsert settings; `smtp_user` and `smtp_pass` are AES-256-GCM encrypted before storage; sending `••••••••` for `smtp_pass` is a no-op (keeps existing value) |
|
||||
| POST | `/test-smtp` | admin | Test SMTP connection with provided credentials; success returns `{ message }`, failure returns `{ message, raw }` where `message` is human-readable and `raw` is the original SMTP error. The short-lived admin JWT returned by `POST /api/setup/register` also qualifies during the setup wizard. |
|
||||
|
||||
#### Yoco — `/api/yoco`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| GET | `/config` | admin | Yoco settings with secrets masked card-style (`sk_test_***…aba`), the source of each (`db`/`env`/`none`), test/live mode and the default webhook URL |
|
||||
| PUT | `/config` | admin | Save `secretKey` and/or `webhookSecret` (AES-256-GCM encrypted). A new key is checked with Yoco first; `''` clears a value |
|
||||
| GET | `/webhooks` | admin | Webhooks on the Yoco account, flagged `isActive` (its secret is the stored one) and `pointsHere` |
|
||||
| POST | `/webhooks` | admin | Register a webhook at Yoco (`{ name?, url? }`, URL defaults to `BACKEND_URL/api/webhooks/yoco`, must be public https) and store the secret it returns |
|
||||
| DELETE | `/webhooks/:id` | admin | Delete a webhook at Yoco; clears the stored secret if it was the active one |
|
||||
|
||||
#### Setup — `/api/setup`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/register` | public (one-time) | Step 2 of setup wizard — creates the first admin account and returns a short-lived JWT setup token; blocked once any user exists |
|
||||
| POST | `/` | setup token or admin | Final step of setup wizard — saves initial site settings (SMTP, org name, branding); requires setup token from `/register` |
|
||||
|
||||
#### Uploads — `/api/uploads`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/event-image` | supervisor+ | Upload event cover image (`image` field) |
|
||||
| POST | `/logo` | admin (or no-auth during setup) | Upload site logo (`image` field) |
|
||||
|
||||
#### Sections — `/api/sections`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| GET | `/` | staff+ | List sections |
|
||||
| POST | `/` | supervisor+ | Create section |
|
||||
| PUT | `/:id` | supervisor+ | Update section |
|
||||
| DELETE | `/:id` | admin | Delete section |
|
||||
|
||||
#### Banner — `/api/banner`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| GET | `/` | public | Get current site banner |
|
||||
| POST | `/` | supervisor+ | Set site banner |
|
||||
|
||||
#### Forms — `/api/forms`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| GET | `/responses` | staff+ | List all form responses |
|
||||
|
||||
#### Yoco Transactions — `/api/yoco-transactions`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| GET | `/` | supervisor+ | All Yoco webhook transactions |
|
||||
| GET | `/unreconciled` | supervisor+ | Unmatched transactions |
|
||||
| POST | `/:id/reconcile` | supervisor+ | Manually reconcile transaction |
|
||||
| POST | `/:id/ignore` | supervisor+ | Mark transaction as ignored |
|
||||
|
||||
#### WhatsApp Admin — `/api/whatsapp`
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/webhook` | public | WAWP inbound event |
|
||||
| GET | `/config` | admin | Get WAWP credentials |
|
||||
| POST | `/config` | admin | Save WAWP credentials to DB |
|
||||
| POST | `/create-instance` | admin | Create WAWP instance |
|
||||
| POST | `/delete-instance` | admin | Delete WAWP instance |
|
||||
| GET | `/status` | admin | WAWP session status |
|
||||
| GET | `/qr` | admin | QR code for WhatsApp linking |
|
||||
| POST | `/request-code` | admin | Request pairing code |
|
||||
| POST | `/logout` | admin | Logout WAWP session |
|
||||
| POST | `/start` | admin | Start WAWP instance |
|
||||
| POST | `/restart` | admin | Restart WAWP instance |
|
||||
|
||||
#### Static Files
|
||||
| Path | Description |
|
||||
|------|-------------|
|
||||
| `/uploads/*` | Served uploaded files (images, PDFs) |
|
||||
|
||||
---
|
||||
|
||||
## Background Workers
|
||||
|
||||
All workers start automatically with `npm start`.
|
||||
|
||||
### Scheduled Emails Worker
|
||||
Polls every 30 s (configurable via `SCHEDULED_EMAILS_INTERVAL_MS`) for due jobs. Handles attendee emails, attendee WhatsApp, email broadcasts, and WhatsApp broadcasts. Disable with `SCHEDULED_EMAILS_ENABLED=false`.
|
||||
|
||||
### Daily Event Summaries
|
||||
Runs at 07:00 local time. Sends summary emails to supervisors about that day's events. Disable with `DAILY_SUMMARY_ENABLED=false`.
|
||||
|
||||
### Temp File Cleanup
|
||||
Runs at 03:00 local time. Removes files older than 7 days from `public/uploads/tickets-temp/`.
|
||||
|
||||
### Attachment Manifest Sync
|
||||
Runs once on startup. Imports on-disk attachment manifests not yet in the database.
|
||||
|
||||
---
|
||||
|
||||
## Notification System
|
||||
|
||||
Outbound notifications are routed through `src/utils/notify.js`:
|
||||
|
||||
- `shouldEmail(user)` — true if preference is `email` or `both`
|
||||
- `canWhatsApp(user)` — true if preference is `whatsapp` or `both` and user has a phone number
|
||||
- `waText(user, message)` — sends a WhatsApp text
|
||||
- `waPdf(user, pdfPath, caption)` — copies PDF to temp, sends URL to WAWP, cleans up after 5 min
|
||||
|
||||
**Automated notifications**: login, account deletion, ticket delivery, payment confirmation, password reset, daily summaries.
|
||||
|
||||
**Dynamic placeholders** in bulk messages: `{{name}}`, `{{event.title}}`, `{{event.start}}`, `{{event.link}}`, `{{balance}}`, `{{promo.title}}`, `{{promo.link}}`.
|
||||
|
||||
---
|
||||
|
||||
## WhatsApp Integration
|
||||
|
||||
WAWP API (`api.wawp.net/v2`). All calls go through `src/utils/whatsapp.js`.
|
||||
|
||||
Credentials are stored in `AppSetting` (`WAWP_ACCESS_TOKEN`, `WAWP_INSTANCE_ID`), with `.env` as fallback. Cached in memory for 30 s.
|
||||
|
||||
"Session not found" recovery: stale session is deleted and a new one is created automatically, saving the new `instance_id` to `AppSetting`.
|
||||
|
||||
Admin UI: `/dashboard/admin/whatsapp`.
|
||||
|
||||
---
|
||||
|
||||
## File Uploads
|
||||
|
||||
- Event images: `POST /api/uploads/event-image` (field `image`), saved to `public/uploads/`
|
||||
- Event attachments: `POST /api/events/:id/attachments` (field `file`)
|
||||
- Ticket PDFs: generated on demand, temporarily in `public/uploads/tickets-temp/`, auto-deleted after 5 min
|
||||
|
||||
Files are served from `/uploads/*`.
|
||||
|
||||
---
|
||||
|
||||
## Pricing & Cancellation Rules
|
||||
|
||||
### Cancellation
|
||||
|
||||
`DELETE /api/registrations/:id`
|
||||
|
||||
| Actor | Condition | Result |
|
||||
|-------|-----------|--------|
|
||||
| Owner (user) | No positive payments recorded | 200 — status set to `cancelled` |
|
||||
| Owner (user) | Any positive payment exists | 403 — must contact organisation |
|
||||
| Admin | Any state | 200 — always allowed |
|
||||
| Anyone | Already cancelled | 400 |
|
||||
|
||||
Cancelled registrations are excluded from all stock-limit counts (option, variant, and tier stock).
|
||||
|
||||
### Early-bird pricing — two-phase evaluation
|
||||
|
||||
Prices are evaluated in two phases:
|
||||
|
||||
**Phase 1 — Registration time** (`resolveOptionPrice` in `src/utils/pricing.js`)
|
||||
- Selects the cheapest applicable tier, checking **both** the deadline **and** the stock limit.
|
||||
- Result stored as `priceSnapshot` and `appliedTierId` on each `RegistrationOption`.
|
||||
- Tier sort order: cheapest first; earliest deadline breaks ties.
|
||||
|
||||
**Phase 2 — Payment time** (`refreshPricingForRegistration` in `src/utils/pricing.js`)
|
||||
- Called automatically before any Yoco checkout is created or any manual payment is recorded.
|
||||
- Re-runs `resolveOptionPrice` for every `RegistrationOption` that has an `appliedTierId`.
|
||||
- If a tier has since expired **or its stock has been exhausted**, `priceSnapshot` and `appliedTierId` are updated in the DB to reflect the next applicable tier or the base price.
|
||||
- If prices changed, `POST /api/payments/yoco-checkout` returns HTTP 200 with `{ priceUpdated: true, newTotal, message }` instead of proceeding to Yoco. The frontend must present the updated total before the user can retry.
|
||||
- For manual payments (`POST /api/payments`) prices are refreshed silently — no blocking response.
|
||||
|
||||
**`computeRegistrationTotalDue`** (also in `src/utils/pricing.js`)
|
||||
- Uses `priceSnapshot` as the authoritative price when it is set on a `RegistrationOption`.
|
||||
- Falls back to `getEffectiveUnitPrice` (deadline-only re-evaluation) for legacy rows without a snapshot.
|
||||
|
||||
### Variant + tier interaction
|
||||
|
||||
Early-bird tiers can be defined at either the **option level** (no `variantId`) or the **variant level** (`variantId` set). Both are stored as `EarlyBirdTier` records on the `EventOption`.
|
||||
|
||||
| Variant state | Effective price |
|
||||
|---------------|-----------------|
|
||||
| No variant selected | Option-level tiers are evaluated via `resolveOptionPrice` |
|
||||
| Variant selected, variant has its own tier(s) | Variant-level tiers are evaluated first via `resolveVariantTierPrice` |
|
||||
| Variant selected, no variant-level tier | Variant's own `price` is used (or option price if `variant.price` is null) |
|
||||
|
||||
The resolution priority at registration/payment time is: **variant tier → variant price → option tier → option base price**.
|
||||
|
||||
---
|
||||
|
||||
## Payments (Yoco)
|
||||
|
||||
Setup: Admin → Site Settings → **Yoco**. Paste the secret key (checked with Yoco before saving), then **Generate** a webhook — this registers `BACKEND_URL/api/webhooks/yoco` with Yoco and stores the secret Yoco returns (it's only shown once). Or **Enter** the secret of a webhook you registered yourself. The tab also lists the account's webhooks and can delete them.
|
||||
|
||||
1. Frontend calls `POST /api/payments/yoco-checkout`
|
||||
2. Backend calls `refreshPricingForRegistration` — if any early-bird price changed, returns `{ priceUpdated: true, newTotal }` (HTTP 200) and does **not** create a checkout. Frontend shows warning; user retries.
|
||||
3. On the retry (or first attempt when prices are current), backend creates a Yoco checkout and returns `{ redirectUrl }`.
|
||||
4. User pays on Yoco's hosted page.
|
||||
5. Yoco sends webhook to `POST /api/webhooks/yoco`.
|
||||
6. Backend verifies HMAC, creates `Payment` + `YocoTransaction`, updates registration status, generates tickets.
|
||||
7. Unmatched transactions visible at `/api/yoco-transactions/unreconciled`.
|
||||
|
||||
---
|
||||
|
||||
## Deployment
|
||||
|
||||
### PM2 (recommended)
|
||||
```bash
|
||||
npm install -g pm2
|
||||
npm run build
|
||||
pm2 start src/index.js --name hope-events-api
|
||||
pm2 save && pm2 startup
|
||||
```
|
||||
|
||||
### Checklist
|
||||
- [ ] `DATABASE_URL` points to production DB
|
||||
- [ ] `JWT_SECRET` is long (32+ chars) and secret
|
||||
- [ ] `FRONTEND_URL` lists only production origins
|
||||
- [ ] `NODE_ENV=production`
|
||||
- [ ] Yoco secret key saved and webhook generated (Site Settings → Yoco), over HTTPS
|
||||
- [ ] WAWP credentials saved via admin panel
|
||||
- [ ] SMTP credentials correct
|
||||
@@ -0,0 +1,8 @@
|
||||
module.exports = {
|
||||
testEnvironment: 'node',
|
||||
testMatch: ['**/tests/**/*.test.js', '**/tests/**/*.test.ts'],
|
||||
// TypeScript (src/**/*.ts and tests) runs through ts-jest; plain JS is left as it is.
|
||||
transform: { '^.+\\.ts$': ['ts-jest', { tsconfig: 'tsconfig.json' }] },
|
||||
moduleFileExtensions: ['ts', 'js', 'json'],
|
||||
modulePathIgnorePatterns: ['<rootDir>/dist/'],
|
||||
};
|
||||
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "2.3.1",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
"start": "node src/index.js",
|
||||
"dev": "tsx watch src/index.js",
|
||||
"test": "jest",
|
||||
"postinstall": "prisma generate",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:deploy": "prisma migrate deploy && prisma generate",
|
||||
"prisma:status": "prisma migrate status",
|
||||
"prisma:reset": "prisma migrate reset --force",
|
||||
"migrate:env-to-db": "node scripts/migrate-env-to-db.js",
|
||||
"migrate:env-to-db:dry": "node scripts/migrate-env-to-db.js --dry-run",
|
||||
"set-demo": "node scripts/set-demo.js",
|
||||
"build": "tsc -p tsconfig.json && node -e \"require('fs').writeFileSync('dist/build.json', JSON.stringify({ version: require('./package.json').version, builtAt: new Date().toISOString() }))\"",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"openapi": "tsx scripts/openapi.ts",
|
||||
"ai:eval": "tsx scripts/ai-eval.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
"@crosscode/contracts": "*",
|
||||
"@node-rs/argon2": "^2.2.2",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"@sentry/node": "^10.71.0",
|
||||
"axios": "^1.11.0",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"cors": "^2.8.5",
|
||||
"cron-parser": "^5.10.2",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^5.3.0",
|
||||
"express-rate-limit": "^8.6.2",
|
||||
"ics": "^3.12.0",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"multer": "^2.5.0",
|
||||
"nodemailer": "^10.3.0",
|
||||
"pdfkit": "^0.17.1",
|
||||
"pg-boss": "^11.1.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"raw-body": "^3.0.0",
|
||||
"swagger-ui-dist": "^5.34.0",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^5.9.3",
|
||||
"uuid": "^11.1.1",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@crosscode/seo": "*",
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/node": "^20.19.43",
|
||||
"@types/supertest": "^7.2.1",
|
||||
"@types/swagger-ui-dist": "^3.30.6",
|
||||
"jest": "^30.4.2",
|
||||
"prisma": "^7.10.1",
|
||||
"supertest": "^7.3.1",
|
||||
"ts-jest": "^29.4.15"
|
||||
},
|
||||
"overrides": {
|
||||
"uuid": "^11.1.1",
|
||||
"@istanbuljs/load-nyc-config": {
|
||||
"js-yaml": "^4.1.1"
|
||||
},
|
||||
"follow-redirects": "^1.16.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Prisma CLI config (migrate, generate, studio). Prisma 7 no longer reads the
|
||||
// datasource URL from schema.prisma or auto-loads .env, so both happen here.
|
||||
require('dotenv/config');
|
||||
const { defineConfig } = require('prisma/config');
|
||||
|
||||
module.exports = defineConfig({
|
||||
schema: 'prisma/schema.prisma',
|
||||
migrations: {
|
||||
path: 'prisma/migrations',
|
||||
},
|
||||
datasource: {
|
||||
// process.env rather than env() so `prisma generate` still works on a
|
||||
// machine with no DATABASE_URL (generate never connects).
|
||||
url: process.env.DATABASE_URL,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,342 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "UserRole" AS ENUM ('admin', 'supervisor', 'staff', 'user');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "RegistrationStatus" AS ENUM ('pending', 'confirmed', 'partial_paid', 'paid', 'cancelled');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "FormFieldType" AS ENUM ('yes_no', 'text', 'date', 'numeric', 'statement', 'paragraph');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "User" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"password" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
"phoneNumber" TEXT,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"role" "UserRole" NOT NULL DEFAULT 'user',
|
||||
|
||||
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Event" (
|
||||
"id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"startDate" TIMESTAMP(3) NOT NULL,
|
||||
"endDate" TIMESTAMP(3) NOT NULL,
|
||||
"registrationDeadline" TIMESTAMP(3),
|
||||
"goLiveAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"price" DOUBLE PRECISION NOT NULL,
|
||||
"picture" TEXT,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"createdById" TEXT,
|
||||
"redirectUrl" TEXT,
|
||||
|
||||
CONSTRAINT "Event_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventOption" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"price" DOUBLE PRECISION NOT NULL,
|
||||
"isMainTicket" BOOLEAN NOT NULL,
|
||||
|
||||
CONSTRAINT "EventOption_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EarlyBirdTier" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventOptionId" TEXT NOT NULL,
|
||||
"deadline" TIMESTAMP(3) NOT NULL,
|
||||
"price" DOUBLE PRECISION NOT NULL,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "EarlyBirdTier_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Registration" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"status" "RegistrationStatus" NOT NULL DEFAULT 'pending',
|
||||
"checkoutId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Registration_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "RegistrationOption" (
|
||||
"id" TEXT NOT NULL,
|
||||
"registrationId" TEXT NOT NULL,
|
||||
"eventOptionId" TEXT NOT NULL,
|
||||
"quantity" INTEGER NOT NULL DEFAULT 1,
|
||||
|
||||
CONSTRAINT "RegistrationOption_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Payment" (
|
||||
"id" TEXT NOT NULL,
|
||||
"amount" DOUBLE PRECISION NOT NULL,
|
||||
"method" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"registrationId" TEXT,
|
||||
"eventId" TEXT,
|
||||
"isDonation" BOOLEAN NOT NULL DEFAULT false,
|
||||
"externalId" TEXT,
|
||||
"status" TEXT,
|
||||
"originalPaymentId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "Payment_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Ticket" (
|
||||
"id" TEXT NOT NULL,
|
||||
"qrCode" TEXT NOT NULL,
|
||||
"registrationOptionId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"isUsed" BOOLEAN NOT NULL DEFAULT false,
|
||||
"emailSent" BOOLEAN NOT NULL DEFAULT false,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Ticket_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "TicketUsage" (
|
||||
"id" TEXT NOT NULL,
|
||||
"ticketId" TEXT NOT NULL,
|
||||
"scannedById" TEXT NOT NULL,
|
||||
"scannedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "TicketUsage_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "PasswordReset" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"token" TEXT NOT NULL,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"used" BOOLEAN NOT NULL DEFAULT false,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "PasswordReset_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventAttachment" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"originalName" TEXT NOT NULL,
|
||||
"filename" TEXT NOT NULL,
|
||||
"mimeType" TEXT NOT NULL,
|
||||
"size" INTEGER NOT NULL,
|
||||
"url" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "EventAttachment_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventForm" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"isRequired" BOOLEAN NOT NULL DEFAULT false,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "EventForm_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventFormField" (
|
||||
"id" TEXT NOT NULL,
|
||||
"formId" TEXT NOT NULL,
|
||||
"type" "FormFieldType" NOT NULL,
|
||||
"label" TEXT NOT NULL,
|
||||
"isRequired" BOOLEAN NOT NULL DEFAULT false,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"helpText" TEXT,
|
||||
"options" JSONB,
|
||||
|
||||
CONSTRAINT "EventFormField_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "FormResponse" (
|
||||
"id" TEXT NOT NULL,
|
||||
"registrationId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "FormResponse_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "FormAnswer" (
|
||||
"id" TEXT NOT NULL,
|
||||
"responseId" TEXT NOT NULL,
|
||||
"fieldId" TEXT NOT NULL,
|
||||
"value" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "FormAnswer_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "FormDraft" (
|
||||
"id" TEXT NOT NULL,
|
||||
"registrationId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"data" JSONB NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "FormDraft_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "YocoTransaction" (
|
||||
"id" TEXT NOT NULL,
|
||||
"externalId" TEXT NOT NULL,
|
||||
"amount" INTEGER,
|
||||
"currency" TEXT,
|
||||
"createdDate" TIMESTAMP(3),
|
||||
"checkoutId" TEXT,
|
||||
"methodType" TEXT,
|
||||
"reconciled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"ignored" BOOLEAN NOT NULL DEFAULT false,
|
||||
"paymentId" TEXT,
|
||||
"raw" JSONB,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "YocoTransaction_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Event_redirectUrl_key" ON "Event"("redirectUrl");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Event_createdById_idx" ON "Event"("createdById");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EarlyBirdTier_eventOptionId_deadline_idx" ON "EarlyBirdTier"("eventOptionId", "deadline");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Registration_checkoutId_key" ON "Registration"("checkoutId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Payment_externalId_key" ON "Payment"("externalId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Ticket_qrCode_key" ON "Ticket"("qrCode");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "PasswordReset_token_key" ON "PasswordReset"("token");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "EventForm_eventId_key" ON "EventForm"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "FormDraft_registrationId_userId_key" ON "FormDraft"("registrationId", "userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "YocoTransaction_externalId_key" ON "YocoTransaction"("externalId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Event" ADD CONSTRAINT "Event_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventOption" ADD CONSTRAINT "EventOption_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EarlyBirdTier" ADD CONSTRAINT "EarlyBirdTier_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Registration" ADD CONSTRAINT "Registration_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Registration" ADD CONSTRAINT "Registration_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "RegistrationOption" ADD CONSTRAINT "RegistrationOption_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "RegistrationOption" ADD CONSTRAINT "RegistrationOption_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_originalPaymentId_fkey" FOREIGN KEY ("originalPaymentId") REFERENCES "Payment"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Ticket" ADD CONSTRAINT "Ticket_registrationOptionId_fkey" FOREIGN KEY ("registrationOptionId") REFERENCES "RegistrationOption"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Ticket" ADD CONSTRAINT "Ticket_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Ticket" ADD CONSTRAINT "Ticket_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TicketUsage" ADD CONSTRAINT "TicketUsage_ticketId_fkey" FOREIGN KEY ("ticketId") REFERENCES "Ticket"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TicketUsage" ADD CONSTRAINT "TicketUsage_scannedById_fkey" FOREIGN KEY ("scannedById") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PasswordReset" ADD CONSTRAINT "PasswordReset_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventAttachment" ADD CONSTRAINT "EventAttachment_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventForm" ADD CONSTRAINT "EventForm_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventFormField" ADD CONSTRAINT "EventFormField_formId_fkey" FOREIGN KEY ("formId") REFERENCES "EventForm"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FormResponse" ADD CONSTRAINT "FormResponse_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FormAnswer" ADD CONSTRAINT "FormAnswer_responseId_fkey" FOREIGN KEY ("responseId") REFERENCES "FormResponse"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FormAnswer" ADD CONSTRAINT "FormAnswer_fieldId_fkey" FOREIGN KEY ("fieldId") REFERENCES "EventFormField"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FormDraft" ADD CONSTRAINT "FormDraft_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FormDraft" ADD CONSTRAINT "FormDraft_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "YocoTransaction" ADD CONSTRAINT "YocoTransaction_paymentId_fkey" FOREIGN KEY ("paymentId") REFERENCES "Payment"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,34 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "Section" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Section_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SectionOption" (
|
||||
"id" TEXT NOT NULL,
|
||||
"sectionId" TEXT NOT NULL,
|
||||
"eventOptionId" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "SectionOption_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Section_eventId_idx" ON "Section"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "SectionOption_sectionId_eventOptionId_key" ON "SectionOption"("sectionId", "eventOptionId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Section" ADD CONSTRAINT "Section_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "SectionOption" ADD CONSTRAINT "SectionOption_sectionId_fkey" FOREIGN KEY ("sectionId") REFERENCES "Section"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "SectionOption" ADD CONSTRAINT "SectionOption_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "failedAttempts" INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN "lockUntil" TIMESTAMP(3);
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable: add tokenVersion for JWT revocation
|
||||
ALTER TABLE "User" ADD COLUMN "tokenVersion" INTEGER NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Add isHidden and requiresAuth to Event
|
||||
ALTER TABLE "Event" ADD COLUMN "isHidden" BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE "Event" ADD COLUMN "requiresAuth" BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
-- Add quantity to Ticket (1 ticket per option, not per qty unit)
|
||||
ALTER TABLE "Ticket" ADD COLUMN "quantity" INTEGER NOT NULL DEFAULT 1;
|
||||
|
||||
-- Add quantityRedeemed to TicketUsage (for partial redemption)
|
||||
ALTER TABLE "TicketUsage" ADD COLUMN "quantityRedeemed" INTEGER NOT NULL DEFAULT 1;
|
||||
@@ -0,0 +1,8 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- A unique constraint covering the columns `[phoneNumber]` on the table `User` will be added. If there are existing duplicate values, this will fail.
|
||||
|
||||
*/
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_phoneNumber_key" ON "User"("phoneNumber");
|
||||
@@ -0,0 +1,14 @@
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Ticket_eventId_idx" ON "Ticket"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Ticket_userId_idx" ON "Ticket"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "TicketUsage_ticketId_idx" ON "TicketUsage"("ticketId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "TicketUsage_scannedAt_idx" ON "TicketUsage"("scannedAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "TicketUsage_scannedById_scannedAt_idx" ON "TicketUsage"("scannedById", "scannedAt");
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventAttachment_eventId_idx" ON "EventAttachment"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventFormField_formId_idx" ON "EventFormField"("formId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventOption_eventId_idx" ON "EventOption"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "FormAnswer_responseId_idx" ON "FormAnswer"("responseId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "FormAnswer_fieldId_idx" ON "FormAnswer"("fieldId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "FormResponse_registrationId_idx" ON "FormResponse"("registrationId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "PasswordReset_userId_idx" ON "PasswordReset"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Payment_userId_idx" ON "Payment"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Payment_registrationId_idx" ON "Payment"("registrationId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Payment_eventId_idx" ON "Payment"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Payment_createdAt_idx" ON "Payment"("createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Registration_userId_idx" ON "Registration"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Registration_eventId_idx" ON "Registration"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Registration_userId_status_idx" ON "Registration"("userId", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Registration_eventId_status_idx" ON "Registration"("eventId", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "RegistrationOption_registrationId_idx" ON "RegistrationOption"("registrationId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "RegistrationOption_eventOptionId_idx" ON "RegistrationOption"("eventOptionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Ticket_registrationOptionId_idx" ON "Ticket"("registrationOptionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "YocoTransaction_paymentId_idx" ON "YocoTransaction"("paymentId");
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "NotificationPreference" AS ENUM ('email', 'whatsapp', 'both');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "notificationPreference" "NotificationPreference" NOT NULL DEFAULT 'email';
|
||||
@@ -0,0 +1,8 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "AppSetting" (
|
||||
"key" TEXT NOT NULL,
|
||||
"value" TEXT NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "AppSetting_pkey" PRIMARY KEY ("key")
|
||||
);
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
-- Add stockLimit to EventOption
|
||||
ALTER TABLE "EventOption" ADD COLUMN "stockLimit" INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
-- Add stockLimit to EarlyBirdTier
|
||||
ALTER TABLE "EarlyBirdTier" ADD COLUMN "stockLimit" INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
-- CreateTable OptionVariant
|
||||
CREATE TABLE "OptionVariant" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventOptionId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"price" DOUBLE PRECISION,
|
||||
"stockLimit" INTEGER NOT NULL DEFAULT 0,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "OptionVariant_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- Add new columns to RegistrationOption
|
||||
ALTER TABLE "RegistrationOption" ADD COLUMN "variantId" TEXT;
|
||||
ALTER TABLE "RegistrationOption" ADD COLUMN "appliedTierId" TEXT;
|
||||
ALTER TABLE "RegistrationOption" ADD COLUMN "priceSnapshot" DOUBLE PRECISION;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "OptionVariant_eventOptionId_idx" ON "OptionVariant"("eventOptionId");
|
||||
CREATE INDEX "RegistrationOption_variantId_idx" ON "RegistrationOption"("variantId");
|
||||
CREATE INDEX "RegistrationOption_appliedTierId_idx" ON "RegistrationOption"("appliedTierId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "OptionVariant" ADD CONSTRAINT "OptionVariant_eventOptionId_fkey"
|
||||
FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "RegistrationOption" ADD CONSTRAINT "RegistrationOption_variantId_fkey"
|
||||
FOREIGN KEY ("variantId") REFERENCES "OptionVariant"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "RegistrationOption" ADD CONSTRAINT "RegistrationOption_appliedTierId_fkey"
|
||||
FOREIGN KEY ("appliedTierId") REFERENCES "EarlyBirdTier"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "EarlyBirdTier" ADD COLUMN "variantId" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EarlyBirdTier_variantId_idx" ON "EarlyBirdTier"("variantId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EarlyBirdTier" ADD CONSTRAINT "EarlyBirdTier_variantId_fkey" FOREIGN KEY ("variantId") REFERENCES "OptionVariant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,213 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "Ministry" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"image" TEXT,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"leaderId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Ministry_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "TeamMember" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"bio" TEXT,
|
||||
"photo" TEXT,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
"email" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "TeamMember_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ContentBlock" (
|
||||
"id" TEXT NOT NULL,
|
||||
"page" TEXT NOT NULL,
|
||||
"key" TEXT NOT NULL,
|
||||
"value" TEXT NOT NULL,
|
||||
"type" TEXT NOT NULL DEFAULT 'text',
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ContentBlock_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ChurchDocument" (
|
||||
"id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"fileUrl" TEXT NOT NULL,
|
||||
"category" TEXT NOT NULL DEFAULT 'other',
|
||||
"isPublic" BOOLEAN NOT NULL DEFAULT true,
|
||||
"uploadedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ChurchDocument_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "FellowshipGroup" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"leader" TEXT,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "FellowshipGroup_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ChurchMember" (
|
||||
"id" TEXT NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||
"mainName" TEXT NOT NULL,
|
||||
"mainEmail" TEXT NOT NULL,
|
||||
"mainPhone" TEXT,
|
||||
"mainBirthday" TIMESTAMP(3),
|
||||
"mainOccupation" TEXT,
|
||||
"mainEmploymentStatus" TEXT,
|
||||
"mainDateOfSalvation" TIMESTAMP(3),
|
||||
"mainDateOfWaterBaptism" TIMESTAMP(3),
|
||||
"mainHolySpiritBaptism" BOOLEAN NOT NULL DEFAULT false,
|
||||
"spouseName" TEXT,
|
||||
"spouseEmail" TEXT,
|
||||
"spousePhone" TEXT,
|
||||
"spouseBirthday" TIMESTAMP(3),
|
||||
"spouseOccupation" TEXT,
|
||||
"spouseEmploymentStatus" TEXT,
|
||||
"spouseDateOfSalvation" TIMESTAMP(3),
|
||||
"spouseDateOfWaterBaptism" TIMESTAMP(3),
|
||||
"spouseHolySpiritBaptism" BOOLEAN,
|
||||
"homeAddress" TEXT,
|
||||
"inFellowshipGroup" BOOLEAN NOT NULL DEFAULT false,
|
||||
"fellowshipGroupId" TEXT,
|
||||
"membershipConfirmed" BOOLEAN NOT NULL DEFAULT false,
|
||||
"notes" TEXT,
|
||||
"appliedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"approvedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ChurchMember_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ChurchChild" (
|
||||
"id" TEXT NOT NULL,
|
||||
"memberId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"birthday" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "ChurchChild_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "MinistryInterest" (
|
||||
"id" TEXT NOT NULL,
|
||||
"memberId" TEXT NOT NULL,
|
||||
"ministryId" TEXT NOT NULL,
|
||||
"forSpouse" BOOLEAN NOT NULL DEFAULT false,
|
||||
|
||||
CONSTRAINT "MinistryInterest_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Donation" (
|
||||
"id" TEXT NOT NULL,
|
||||
"donorName" TEXT,
|
||||
"donorEmail" TEXT,
|
||||
"donorPhone" TEXT,
|
||||
"amount" DOUBLE PRECISION NOT NULL,
|
||||
"method" TEXT NOT NULL,
|
||||
"reference" TEXT,
|
||||
"note" TEXT,
|
||||
"isAnonymous" BOOLEAN NOT NULL DEFAULT false,
|
||||
"linkedMemberId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Donation_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Ministry_slug_key" ON "Ministry"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Ministry_isActive_order_idx" ON "Ministry"("isActive", "order");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Ministry_leaderId_idx" ON "Ministry"("leaderId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "TeamMember_isActive_order_idx" ON "TeamMember"("isActive", "order");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ContentBlock_page_idx" ON "ContentBlock"("page");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ContentBlock_page_key_key" ON "ContentBlock"("page", "key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "FellowshipGroup_isActive_order_idx" ON "FellowshipGroup"("isActive", "order");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChurchMember_status_idx" ON "ChurchMember"("status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChurchMember_mainEmail_idx" ON "ChurchMember"("mainEmail");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChurchMember_fellowshipGroupId_idx" ON "ChurchMember"("fellowshipGroupId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChurchChild_memberId_idx" ON "ChurchChild"("memberId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "MinistryInterest_memberId_idx" ON "MinistryInterest"("memberId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "MinistryInterest_ministryId_idx" ON "MinistryInterest"("ministryId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "MinistryInterest_memberId_ministryId_forSpouse_key" ON "MinistryInterest"("memberId", "ministryId", "forSpouse");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Donation_linkedMemberId_idx" ON "Donation"("linkedMemberId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Donation_createdAt_idx" ON "Donation"("createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Donation_method_idx" ON "Donation"("method");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Ministry" ADD CONSTRAINT "Ministry_leaderId_fkey" FOREIGN KEY ("leaderId") REFERENCES "TeamMember"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChurchMember" ADD CONSTRAINT "ChurchMember_fellowshipGroupId_fkey" FOREIGN KEY ("fellowshipGroupId") REFERENCES "FellowshipGroup"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChurchChild" ADD CONSTRAINT "ChurchChild_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "ChurchMember"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "MinistryInterest" ADD CONSTRAINT "MinistryInterest_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "ChurchMember"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "MinistryInterest" ADD CONSTRAINT "MinistryInterest_ministryId_fkey" FOREIGN KEY ("ministryId") REFERENCES "Ministry"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Donation" ADD CONSTRAINT "Donation_linkedMemberId_fkey" FOREIGN KEY ("linkedMemberId") REFERENCES "ChurchMember"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- You are about to drop the `ChurchChild` table. If the table is not empty, all the data it contains will be lost.
|
||||
- You are about to drop the `ChurchDocument` table. If the table is not empty, all the data it contains will be lost.
|
||||
- You are about to drop the `ChurchMember` table. If the table is not empty, all the data it contains will be lost.
|
||||
- You are about to drop the `ContentBlock` table. If the table is not empty, all the data it contains will be lost.
|
||||
- You are about to drop the `Donation` table. If the table is not empty, all the data it contains will be lost.
|
||||
- You are about to drop the `FellowshipGroup` table. If the table is not empty, all the data it contains will be lost.
|
||||
- You are about to drop the `Ministry` table. If the table is not empty, all the data it contains will be lost.
|
||||
- You are about to drop the `MinistryInterest` table. If the table is not empty, all the data it contains will be lost.
|
||||
- You are about to drop the `TeamMember` table. If the table is not empty, all the data it contains will be lost.
|
||||
|
||||
*/
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CashupStatus" AS ENUM ('open', 'closed');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CashupAction" AS ENUM ('closed', 'quick_closed', 'reopened');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "EventCostType" AS ENUM ('once_off', 'per_item');
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "ChurchChild" DROP CONSTRAINT "ChurchChild_memberId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "ChurchMember" DROP CONSTRAINT "ChurchMember_fellowshipGroupId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "Donation" DROP CONSTRAINT "Donation_linkedMemberId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "Ministry" DROP CONSTRAINT "Ministry_leaderId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "MinistryInterest" DROP CONSTRAINT "MinistryInterest_memberId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "MinistryInterest" DROP CONSTRAINT "MinistryInterest_ministryId_fkey";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "cashupDraft" JSONB,
|
||||
ADD COLUMN "cashupStatus" "CashupStatus" NOT NULL DEFAULT 'open',
|
||||
ADD COLUMN "closedAt" TIMESTAMP(3),
|
||||
ADD COLUMN "closedById" TEXT,
|
||||
ADD COLUMN "reopenedAt" TIMESTAMP(3),
|
||||
ADD COLUMN "reopenedById" TEXT;
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "ChurchChild";
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "ChurchDocument";
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "ChurchMember";
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "ContentBlock";
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "Donation";
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "FellowshipGroup";
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "Ministry";
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "MinistryInterest";
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "TeamMember";
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventCost" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"eventOptionId" TEXT,
|
||||
"label" TEXT NOT NULL,
|
||||
"costType" "EventCostType" NOT NULL,
|
||||
"amount" DOUBLE PRECISION NOT NULL,
|
||||
"notes" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "EventCost_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventCashup" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"action" "CashupAction" NOT NULL,
|
||||
"donationsWrittenOff" DOUBLE PRECISION NOT NULL DEFAULT 0,
|
||||
"totalCosts" DOUBLE PRECISION NOT NULL DEFAULT 0,
|
||||
"totalExpectedRevenue" DOUBLE PRECISION NOT NULL DEFAULT 0,
|
||||
"totalActualRevenue" DOUBLE PRECISION,
|
||||
"notes" TEXT,
|
||||
"performedById" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "EventCashup_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventCashupLine" (
|
||||
"id" TEXT NOT NULL,
|
||||
"cashupId" TEXT NOT NULL,
|
||||
"method" TEXT NOT NULL,
|
||||
"expectedAmount" DOUBLE PRECISION NOT NULL DEFAULT 0,
|
||||
"actualAmount" DOUBLE PRECISION,
|
||||
"variance" DOUBLE PRECISION,
|
||||
"notes" TEXT,
|
||||
|
||||
CONSTRAINT "EventCashupLine_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventCost_eventId_idx" ON "EventCost"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventCost_eventOptionId_idx" ON "EventCost"("eventOptionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventCashup_eventId_createdAt_idx" ON "EventCashup"("eventId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventCashupLine_cashupId_idx" ON "EventCashupLine"("cashupId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Event_closedById_idx" ON "Event"("closedById");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Event_reopenedById_idx" ON "Event"("reopenedById");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Event" ADD CONSTRAINT "Event_closedById_fkey" FOREIGN KEY ("closedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Event" ADD CONSTRAINT "Event_reopenedById_fkey" FOREIGN KEY ("reopenedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCost" ADD CONSTRAINT "EventCost_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCost" ADD CONSTRAINT "EventCost_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCashup" ADD CONSTRAINT "EventCashup_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCashup" ADD CONSTRAINT "EventCashup_performedById_fkey" FOREIGN KEY ("performedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCashupLine" ADD CONSTRAINT "EventCashupLine_cashupId_fkey" FOREIGN KEY ("cashupId") REFERENCES "EventCashup"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
-- AlterTable: rename donationsWrittenOff -> unallocatedDonationsTotal, preserving existing values
|
||||
ALTER TABLE "EventCashup" RENAME COLUMN "donationsWrittenOff" TO "unallocatedDonationsTotal";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "EventCost" ADD COLUMN "paidFromMethod" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventCashupDenomination" (
|
||||
"id" TEXT NOT NULL,
|
||||
"lineId" TEXT NOT NULL,
|
||||
"value" DOUBLE PRECISION NOT NULL,
|
||||
"count" INTEGER NOT NULL,
|
||||
|
||||
CONSTRAINT "EventCashupDenomination_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventCashupDenomination_lineId_idx" ON "EventCashupDenomination"("lineId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCashupDenomination" ADD CONSTRAINT "EventCashupDenomination_lineId_fkey" FOREIGN KEY ("lineId") REFERENCES "EventCashupLine"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "_EventNotifyRecipients" (
|
||||
"A" TEXT NOT NULL,
|
||||
"B" TEXT NOT NULL
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "_EventNotifyRecipients_AB_unique" ON "_EventNotifyRecipients"("A", "B");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "_EventNotifyRecipients_B_index" ON "_EventNotifyRecipients"("B");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "_EventNotifyRecipients" ADD CONSTRAINT "_EventNotifyRecipients_A_fkey" FOREIGN KEY ("A") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "_EventNotifyRecipients" ADD CONSTRAINT "_EventNotifyRecipients_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Payment" ADD COLUMN "feeAmount" DOUBLE PRECISION,
|
||||
ADD COLUMN "feeChannel" TEXT,
|
||||
ADD COLUMN "feePayer" TEXT,
|
||||
ADD COLUMN "feeRate" DOUBLE PRECISION;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "feePayerOnline" TEXT;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- You are about to drop the column `feePayerOnline` on the `Event` table. All the data in the column will be lost.
|
||||
- You are about to drop the column `feePayer` on the `Payment` table. All the data in the column will be lost.
|
||||
|
||||
*/
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" DROP COLUMN "feePayerOnline";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Payment" DROP COLUMN "feePayer";
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "EventCashupLine" ADD COLUMN "feeAmount" DOUBLE PRECISION;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Payment" ADD COLUMN "recordedById" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Payment_recordedById_idx" ON "Payment"("recordedById");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Payment_originalPaymentId_idx" ON "Payment"("originalPaymentId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_recordedById_fkey" FOREIGN KEY ("recordedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventCashupPersonCount" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"enteredById" TEXT,
|
||||
"notes" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "EventCashupPersonCount_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventCashupPersonCountDenomination" (
|
||||
"id" TEXT NOT NULL,
|
||||
"countId" TEXT NOT NULL,
|
||||
"value" DOUBLE PRECISION NOT NULL,
|
||||
"count" INTEGER NOT NULL,
|
||||
|
||||
CONSTRAINT "EventCashupPersonCountDenomination_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventCashupPersonCount_eventId_idx" ON "EventCashupPersonCount"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "EventCashupPersonCount_eventId_userId_key" ON "EventCashupPersonCount"("eventId", "userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventCashupPersonCountDenomination_countId_idx" ON "EventCashupPersonCountDenomination"("countId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCashupPersonCount" ADD CONSTRAINT "EventCashupPersonCount_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCashupPersonCount" ADD CONSTRAINT "EventCashupPersonCount_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCashupPersonCount" ADD CONSTRAINT "EventCashupPersonCount_enteredById_fkey" FOREIGN KEY ("enteredById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCashupPersonCountDenomination" ADD CONSTRAINT "EventCashupPersonCountDenomination_countId_fkey" FOREIGN KEY ("countId") REFERENCES "EventCashupPersonCount"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "SecurityEventType" AS ENUM ('login', 'password_changed', 'password_reset');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SecurityEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT,
|
||||
"type" "SecurityEventType" NOT NULL,
|
||||
"ip" TEXT,
|
||||
"device" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "SecurityEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "SecurityEvent_userId_createdAt_idx" ON "SecurityEvent"("userId", "createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "SecurityEvent" ADD CONSTRAINT "SecurityEvent_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,11 @@
|
||||
-- DropIndex
|
||||
DROP INDEX "Payment_originalPaymentId_idx";
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Payment_originalPaymentId_isDonation_idx" ON "Payment"("originalPaymentId", "isDonation");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Registration_createdAt_status_idx" ON "Registration"("createdAt", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Ticket_createdAt_idx" ON "Ticket"("createdAt");
|
||||
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- You are about to drop the column `feeAmount` on the `EventCashupLine` table. All the data in the column will be lost.
|
||||
- You are about to drop the column `feeAmount` on the `Payment` table. All the data in the column will be lost.
|
||||
- You are about to drop the column `feeChannel` on the `Payment` table. All the data in the column will be lost.
|
||||
- You are about to drop the column `feeRate` on the `Payment` table. All the data in the column will be lost.
|
||||
|
||||
*/
|
||||
-- AlterTable
|
||||
ALTER TABLE "EventCashupLine" DROP COLUMN "feeAmount";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Payment" DROP COLUMN "feeAmount",
|
||||
DROP COLUMN "feeChannel",
|
||||
DROP COLUMN "feeRate";
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "contactEmail" TEXT,
|
||||
ADD COLUMN "contactName" TEXT,
|
||||
ADD COLUMN "contactPhone" TEXT,
|
||||
ADD COLUMN "requiresRegistration" BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "RegistrationOptionTranche" (
|
||||
"id" TEXT NOT NULL,
|
||||
"registrationOptionId" TEXT NOT NULL,
|
||||
"quantity" INTEGER NOT NULL,
|
||||
"priceSnapshot" DOUBLE PRECISION NOT NULL,
|
||||
"appliedTierId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "RegistrationOptionTranche_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "RegistrationOptionTranche_registrationOptionId_idx" ON "RegistrationOptionTranche"("registrationOptionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "RegistrationOptionTranche_appliedTierId_idx" ON "RegistrationOptionTranche"("appliedTierId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "RegistrationOptionTranche" ADD CONSTRAINT "RegistrationOptionTranche_registrationOptionId_fkey" FOREIGN KEY ("registrationOptionId") REFERENCES "RegistrationOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "RegistrationOptionTranche" ADD CONSTRAINT "RegistrationOptionTranche_appliedTierId_fkey" FOREIGN KEY ("appliedTierId") REFERENCES "EarlyBirdTier"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "location" TEXT;
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "AdminAuditAction" AS ENUM ('refund_created', 'donation_assigned', 'donation_unassigned', 'registration_created_manual', 'registration_cancelled', 'event_created', 'event_updated', 'event_deleted', 'settings_updated');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AdminAuditLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"actorId" TEXT,
|
||||
"actorRole" TEXT NOT NULL,
|
||||
"action" "AdminAuditAction" NOT NULL,
|
||||
"targetType" TEXT NOT NULL,
|
||||
"targetId" TEXT,
|
||||
"metadata" JSONB,
|
||||
"ip" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AdminAuditLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AdminAuditLog_actorId_createdAt_idx" ON "AdminAuditLog"("actorId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AdminAuditLog_action_createdAt_idx" ON "AdminAuditLog"("action", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AdminAuditLog_targetType_targetId_idx" ON "AdminAuditLog"("targetType", "targetId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AdminAuditLog" ADD CONSTRAINT "AdminAuditLog_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,62 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "TwoFactorMethod" AS ENUM ('email', 'whatsapp');
|
||||
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "SecurityEventType" ADD VALUE 'two_factor_enabled';
|
||||
ALTER TYPE "SecurityEventType" ADD VALUE 'two_factor_disabled';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "twoFactorEnabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "twoFactorMethod" "TwoFactorMethod";
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "TwoFactorChallenge" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"purpose" TEXT NOT NULL,
|
||||
"method" "TwoFactorMethod" NOT NULL,
|
||||
"codeHash" TEXT NOT NULL,
|
||||
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||
"lastSentAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"usedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "TwoFactorChallenge_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "TrustedDevice" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"device" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"lastUsedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "TrustedDevice_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "TwoFactorChallenge_userId_idx" ON "TwoFactorChallenge"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "TrustedDevice_tokenHash_key" ON "TrustedDevice"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "TrustedDevice_userId_idx" ON "TrustedDevice"("userId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TwoFactorChallenge" ADD CONSTRAINT "TwoFactorChallenge_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TrustedDevice" ADD CONSTRAINT "TrustedDevice_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CouponType" AS ENUM ('percent', 'fixed', 'comp');
|
||||
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'coupon_created';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'coupon_updated';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'coupon_disabled';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'coupon_applied_manual';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "EventOption" ADD COLUMN "staffPrice" DOUBLE PRECISION;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "OptionVariant" ADD COLUMN "staffPrice" DOUBLE PRECISION;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Registration" ADD COLUMN "discountTotal" DOUBLE PRECISION NOT NULL DEFAULT 0;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Coupon" (
|
||||
"id" TEXT NOT NULL,
|
||||
"code" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"type" "CouponType" NOT NULL,
|
||||
"value" DOUBLE PRECISION NOT NULL DEFAULT 0,
|
||||
"stackEarlyBird" BOOLEAN NOT NULL DEFAULT false,
|
||||
"validFrom" TIMESTAMP(3),
|
||||
"validUntil" TIMESTAMP(3),
|
||||
"maxUses" INTEGER,
|
||||
"maxUsesPerUser" INTEGER DEFAULT 1,
|
||||
"minQuantity" INTEGER,
|
||||
"restrictRoles" "UserRole"[],
|
||||
"restrictDomain" TEXT,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdById" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Coupon_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "CouponEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"couponId" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "CouponEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "CouponOption" (
|
||||
"id" TEXT NOT NULL,
|
||||
"couponId" TEXT NOT NULL,
|
||||
"eventOptionId" TEXT NOT NULL,
|
||||
"variantId" TEXT,
|
||||
|
||||
CONSTRAINT "CouponOption_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "CouponUser" (
|
||||
"id" TEXT NOT NULL,
|
||||
"couponId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "CouponUser_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "CouponRedemption" (
|
||||
"id" TEXT NOT NULL,
|
||||
"couponId" TEXT NOT NULL,
|
||||
"registrationId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"discountAmount" DOUBLE PRECISION NOT NULL,
|
||||
"appliedById" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"releasedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "CouponRedemption_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Coupon_code_key" ON "Coupon"("code");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Coupon_createdById_idx" ON "Coupon"("createdById");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "CouponEvent_eventId_idx" ON "CouponEvent"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "CouponEvent_couponId_eventId_key" ON "CouponEvent"("couponId", "eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "CouponOption_couponId_idx" ON "CouponOption"("couponId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "CouponOption_eventOptionId_idx" ON "CouponOption"("eventOptionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "CouponOption_variantId_idx" ON "CouponOption"("variantId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "CouponUser_userId_idx" ON "CouponUser"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "CouponUser_couponId_userId_key" ON "CouponUser"("couponId", "userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "CouponRedemption_couponId_releasedAt_idx" ON "CouponRedemption"("couponId", "releasedAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "CouponRedemption_registrationId_idx" ON "CouponRedemption"("registrationId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "CouponRedemption_userId_idx" ON "CouponRedemption"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "CouponRedemption_appliedById_idx" ON "CouponRedemption"("appliedById");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Coupon" ADD CONSTRAINT "Coupon_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "CouponEvent" ADD CONSTRAINT "CouponEvent_couponId_fkey" FOREIGN KEY ("couponId") REFERENCES "Coupon"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "CouponEvent" ADD CONSTRAINT "CouponEvent_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "CouponOption" ADD CONSTRAINT "CouponOption_couponId_fkey" FOREIGN KEY ("couponId") REFERENCES "Coupon"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "CouponOption" ADD CONSTRAINT "CouponOption_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "CouponOption" ADD CONSTRAINT "CouponOption_variantId_fkey" FOREIGN KEY ("variantId") REFERENCES "OptionVariant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "CouponUser" ADD CONSTRAINT "CouponUser_couponId_fkey" FOREIGN KEY ("couponId") REFERENCES "Coupon"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "CouponUser" ADD CONSTRAINT "CouponUser_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "CouponRedemption" ADD CONSTRAINT "CouponRedemption_couponId_fkey" FOREIGN KEY ("couponId") REFERENCES "Coupon"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "CouponRedemption" ADD CONSTRAINT "CouponRedemption_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "CouponRedemption" ADD CONSTRAINT "CouponRedemption_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "CouponRedemption" ADD CONSTRAINT "CouponRedemption_appliedById_fkey" FOREIGN KEY ("appliedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "TicketDelivery" AS ENUM ('payer', 'each');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "allowNamedAttendees" BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "FormResponse" ADD COLUMN "attendeeId" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Registration" ADD COLUMN "ticketDelivery" "TicketDelivery" NOT NULL DEFAULT 'payer';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Ticket" ADD COLUMN "attendeeId" TEXT,
|
||||
ADD COLUMN "holderUserId" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Attendee" (
|
||||
"id" TEXT NOT NULL,
|
||||
"registrationId" TEXT NOT NULL,
|
||||
"registrationOptionId" TEXT,
|
||||
"eventOptionId" TEXT NOT NULL,
|
||||
"variantId" TEXT,
|
||||
"name" TEXT NOT NULL,
|
||||
"email" TEXT,
|
||||
"phone" TEXT,
|
||||
"userId" TEXT,
|
||||
"dateOfBirth" TIMESTAMP(3),
|
||||
"gender" TEXT,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Attendee_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Attendee_registrationId_idx" ON "Attendee"("registrationId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Attendee_registrationOptionId_idx" ON "Attendee"("registrationOptionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Attendee_userId_idx" ON "Attendee"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Ticket_attendeeId_key" ON "Ticket"("attendeeId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Ticket_holderUserId_idx" ON "Ticket"("holderUserId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Ticket" ADD CONSTRAINT "Ticket_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "Attendee"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Ticket" ADD CONSTRAINT "Ticket_holderUserId_fkey" FOREIGN KEY ("holderUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FormResponse" ADD CONSTRAINT "FormResponse_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "Attendee"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Attendee" ADD CONSTRAINT "Attendee_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Attendee" ADD CONSTRAINT "Attendee_registrationOptionId_fkey" FOREIGN KEY ("registrationOptionId") REFERENCES "RegistrationOption"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Attendee" ADD CONSTRAINT "Attendee_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ConsentStatus" AS ENUM ('pending', 'given', 'declined');
|
||||
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'consent_override';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'consent_rerequested';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'medical_list_viewed';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Attendee" ADD COLUMN "parentEmail" TEXT,
|
||||
ADD COLUMN "parentName" TEXT,
|
||||
ADD COLUMN "parentPhone" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "consentCollectEmergency" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "consentCollectMedical" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "consentCollectPhoto" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "consentText" TEXT,
|
||||
ADD COLUMN "consentTextVersion" INTEGER NOT NULL DEFAULT 1,
|
||||
ADD COLUMN "requiresParentalConsent" BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ConsentRequest" (
|
||||
"id" TEXT NOT NULL,
|
||||
"attendeeId" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"status" "ConsentStatus" NOT NULL DEFAULT 'pending',
|
||||
"textVersion" INTEGER NOT NULL,
|
||||
"consentText" TEXT NOT NULL,
|
||||
"parentName" TEXT,
|
||||
"parentEmail" TEXT,
|
||||
"parentPhone" TEXT,
|
||||
"signedName" TEXT,
|
||||
"ip" TEXT,
|
||||
"device" TEXT,
|
||||
"medical" TEXT,
|
||||
"emergency" TEXT,
|
||||
"photoConsent" BOOLEAN,
|
||||
"respondedAt" TIMESTAMP(3),
|
||||
"lastSentAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"remindersSent" INTEGER NOT NULL DEFAULT 0,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"medicalPurgedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "ConsentRequest_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ConsentRequest_tokenHash_key" ON "ConsentRequest"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ConsentRequest_attendeeId_createdAt_idx" ON "ConsentRequest"("attendeeId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ConsentRequest_eventId_status_idx" ON "ConsentRequest"("eventId", "status");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ConsentRequest" ADD CONSTRAINT "ConsentRequest_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "Attendee"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ConsentRequest" ADD CONSTRAINT "ConsentRequest_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "WaitlistStatus" AS ENUM ('waiting', 'offered', 'claimed', 'expired', 'removed', 'left');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "waitlistEnabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "waitlistOfferHours" INTEGER NOT NULL DEFAULT 24,
|
||||
ADD COLUMN "waitlistPartialOffers" BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "WaitlistEntry" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"eventOptionId" TEXT NOT NULL,
|
||||
"variantId" TEXT,
|
||||
"userId" TEXT NOT NULL,
|
||||
"quantity" INTEGER NOT NULL,
|
||||
"position" INTEGER NOT NULL,
|
||||
"status" "WaitlistStatus" NOT NULL DEFAULT 'waiting',
|
||||
"offeredQuantity" INTEGER,
|
||||
"offerTokenHash" TEXT,
|
||||
"offeredAt" TIMESTAMP(3),
|
||||
"offerExpiresAt" TIMESTAMP(3),
|
||||
"claimedAt" TIMESTAMP(3),
|
||||
"registrationId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "WaitlistEntry_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "WaitlistEntry_offerTokenHash_key" ON "WaitlistEntry"("offerTokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "WaitlistEntry_eventId_status_position_idx" ON "WaitlistEntry"("eventId", "status", "position");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "WaitlistEntry_eventOptionId_status_idx" ON "WaitlistEntry"("eventOptionId", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "WaitlistEntry_variantId_idx" ON "WaitlistEntry"("variantId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "WaitlistEntry_userId_idx" ON "WaitlistEntry"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "WaitlistEntry_registrationId_idx" ON "WaitlistEntry"("registrationId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "WaitlistEntry" ADD CONSTRAINT "WaitlistEntry_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "WaitlistEntry" ADD CONSTRAINT "WaitlistEntry_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "WaitlistEntry" ADD CONSTRAINT "WaitlistEntry_variantId_fkey" FOREIGN KEY ("variantId") REFERENCES "OptionVariant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "WaitlistEntry" ADD CONSTRAINT "WaitlistEntry_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "WaitlistEntry" ADD CONSTRAINT "WaitlistEntry_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'scan_lock_acquired';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'scan_lock_released';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'scan_lock_force_released';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'offline_sync';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "TicketUsage" ADD COLUMN "clientScanId" TEXT,
|
||||
ADD COLUMN "offline" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "scanLockId" TEXT,
|
||||
ADD COLUMN "syncedAt" TIMESTAMP(3);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ScanLock" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"sectionId" TEXT,
|
||||
"deviceId" TEXT NOT NULL,
|
||||
"deviceName" TEXT,
|
||||
"userId" TEXT NOT NULL,
|
||||
"lockedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"snapshotAt" TIMESTAMP(3),
|
||||
"lastSyncAt" TIMESTAMP(3),
|
||||
"releasedAt" TIMESTAMP(3),
|
||||
"forceReleasedById" TEXT,
|
||||
|
||||
CONSTRAINT "ScanLock_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "OfflineSyncReport" (
|
||||
"id" TEXT NOT NULL,
|
||||
"scanLockId" TEXT NOT NULL,
|
||||
"accepted" INTEGER NOT NULL DEFAULT 0,
|
||||
"duplicates" INTEGER NOT NULL DEFAULT 0,
|
||||
"conflicts" JSONB NOT NULL DEFAULT '[]',
|
||||
"afterForceRelease" BOOLEAN NOT NULL DEFAULT false,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"reviewedAt" TIMESTAMP(3),
|
||||
"reviewedById" TEXT,
|
||||
|
||||
CONSTRAINT "OfflineSyncReport_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ScanLock_eventId_releasedAt_idx" ON "ScanLock"("eventId", "releasedAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ScanLock_userId_idx" ON "ScanLock"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ScanLock_sectionId_idx" ON "ScanLock"("sectionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ScanLock_forceReleasedById_idx" ON "ScanLock"("forceReleasedById");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "OfflineSyncReport_scanLockId_idx" ON "OfflineSyncReport"("scanLockId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "OfflineSyncReport_reviewedById_idx" ON "OfflineSyncReport"("reviewedById");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "TicketUsage_clientScanId_key" ON "TicketUsage"("clientScanId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TicketUsage" ADD CONSTRAINT "TicketUsage_scanLockId_fkey" FOREIGN KEY ("scanLockId") REFERENCES "ScanLock"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ScanLock" ADD CONSTRAINT "ScanLock_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ScanLock" ADD CONSTRAINT "ScanLock_sectionId_fkey" FOREIGN KEY ("sectionId") REFERENCES "Section"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ScanLock" ADD CONSTRAINT "ScanLock_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ScanLock" ADD CONSTRAINT "ScanLock_forceReleasedById_fkey" FOREIGN KEY ("forceReleasedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "OfflineSyncReport" ADD CONSTRAINT "OfflineSyncReport_scanLockId_fkey" FOREIGN KEY ("scanLockId") REFERENCES "ScanLock"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "OfflineSyncReport" ADD CONSTRAINT "OfflineSyncReport_reviewedById_fkey" FOREIGN KEY ("reviewedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'ticket_transferred';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "allowTicketTransfer" BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "TicketTransfer" (
|
||||
"id" TEXT NOT NULL,
|
||||
"ticketId" TEXT NOT NULL,
|
||||
"fromHolderName" TEXT NOT NULL,
|
||||
"fromUserId" TEXT,
|
||||
"toName" TEXT NOT NULL,
|
||||
"toUserId" TEXT,
|
||||
"byUserId" TEXT,
|
||||
"oldQrCode" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "TicketTransfer_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "TicketTransfer_ticketId_idx" ON "TicketTransfer"("ticketId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "TicketTransfer_oldQrCode_idx" ON "TicketTransfer"("oldQrCode");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TicketTransfer" ADD CONSTRAINT "TicketTransfer_ticketId_fkey" FOREIGN KEY ("ticketId") REFERENCES "Ticket"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TicketTransfer" ADD CONSTRAINT "TicketTransfer_toUserId_fkey" FOREIGN KEY ("toUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TicketTransfer" ADD CONSTRAINT "TicketTransfer_byUserId_fkey" FOREIGN KEY ("byUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "collectGender" BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AllocationSet" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"showOnTicket" BOOLEAN NOT NULL DEFAULT false,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "AllocationSet_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AllocationGroup" (
|
||||
"id" TEXT NOT NULL,
|
||||
"setId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"capacity" INTEGER,
|
||||
"gender" TEXT,
|
||||
"leaderUserId" TEXT,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "AllocationGroup_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AllocationAssignment" (
|
||||
"id" TEXT NOT NULL,
|
||||
"setId" TEXT NOT NULL,
|
||||
"groupId" TEXT NOT NULL,
|
||||
"attendeeId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AllocationAssignment_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AllocationSet_eventId_idx" ON "AllocationSet"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AllocationGroup_setId_idx" ON "AllocationGroup"("setId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AllocationGroup_leaderUserId_idx" ON "AllocationGroup"("leaderUserId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AllocationAssignment_groupId_idx" ON "AllocationAssignment"("groupId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AllocationAssignment_attendeeId_idx" ON "AllocationAssignment"("attendeeId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "AllocationAssignment_setId_attendeeId_key" ON "AllocationAssignment"("setId", "attendeeId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AllocationSet" ADD CONSTRAINT "AllocationSet_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AllocationGroup" ADD CONSTRAINT "AllocationGroup_setId_fkey" FOREIGN KEY ("setId") REFERENCES "AllocationSet"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AllocationGroup" ADD CONSTRAINT "AllocationGroup_leaderUserId_fkey" FOREIGN KEY ("leaderUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AllocationAssignment" ADD CONSTRAINT "AllocationAssignment_setId_fkey" FOREIGN KEY ("setId") REFERENCES "AllocationSet"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AllocationAssignment" ADD CONSTRAINT "AllocationAssignment_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "AllocationGroup"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AllocationAssignment" ADD CONSTRAINT "AllocationAssignment_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "Attendee"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "allowSponsorships" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "showSponsorshipProgress" BOOLEAN NOT NULL DEFAULT true,
|
||||
ADD COLUMN "sponsorshipGoalSpots" INTEGER;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Payment" ADD COLUMN "isSponsorship" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "sponsorAnonymous" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "sponsorMessage" TEXT,
|
||||
ADD COLUMN "sponsorName" TEXT;
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "FormFieldType" ADD VALUE 'rating';
|
||||
ALTER TYPE "FormFieldType" ADD VALUE 'multiple_choice';
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "FeedbackForm" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"sendAt" TIMESTAMP(3),
|
||||
"audience" TEXT NOT NULL DEFAULT 'checked_in',
|
||||
"anonymous" BOOLEAN NOT NULL DEFAULT false,
|
||||
"intro" TEXT,
|
||||
"sentAt" TIMESTAMP(3),
|
||||
"reminderSentAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "FeedbackForm_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "FeedbackField" (
|
||||
"id" TEXT NOT NULL,
|
||||
"formId" TEXT NOT NULL,
|
||||
"type" "FormFieldType" NOT NULL,
|
||||
"label" TEXT NOT NULL,
|
||||
"isRequired" BOOLEAN NOT NULL DEFAULT false,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"helpText" TEXT,
|
||||
"options" JSONB,
|
||||
|
||||
CONSTRAINT "FeedbackField_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "FeedbackInvite" (
|
||||
"id" TEXT NOT NULL,
|
||||
"formId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"sentAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"remindedAt" TIMESTAMP(3),
|
||||
"respondedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "FeedbackInvite_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "FeedbackResponse" (
|
||||
"id" TEXT NOT NULL,
|
||||
"formId" TEXT NOT NULL,
|
||||
"userId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "FeedbackResponse_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "FeedbackAnswer" (
|
||||
"id" TEXT NOT NULL,
|
||||
"responseId" TEXT NOT NULL,
|
||||
"fieldId" TEXT NOT NULL,
|
||||
"value" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "FeedbackAnswer_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "FeedbackForm_eventId_key" ON "FeedbackForm"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "FeedbackField_formId_idx" ON "FeedbackField"("formId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "FeedbackInvite_tokenHash_key" ON "FeedbackInvite"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "FeedbackInvite_userId_idx" ON "FeedbackInvite"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "FeedbackInvite_formId_userId_key" ON "FeedbackInvite"("formId", "userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "FeedbackResponse_formId_idx" ON "FeedbackResponse"("formId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "FeedbackAnswer_responseId_idx" ON "FeedbackAnswer"("responseId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "FeedbackAnswer_fieldId_idx" ON "FeedbackAnswer"("fieldId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FeedbackForm" ADD CONSTRAINT "FeedbackForm_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FeedbackField" ADD CONSTRAINT "FeedbackField_formId_fkey" FOREIGN KEY ("formId") REFERENCES "FeedbackForm"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FeedbackInvite" ADD CONSTRAINT "FeedbackInvite_formId_fkey" FOREIGN KEY ("formId") REFERENCES "FeedbackForm"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FeedbackInvite" ADD CONSTRAINT "FeedbackInvite_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FeedbackResponse" ADD CONSTRAINT "FeedbackResponse_formId_fkey" FOREIGN KEY ("formId") REFERENCES "FeedbackForm"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FeedbackResponse" ADD CONSTRAINT "FeedbackResponse_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FeedbackAnswer" ADD CONSTRAINT "FeedbackAnswer_responseId_fkey" FOREIGN KEY ("responseId") REFERENCES "FeedbackResponse"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FeedbackAnswer" ADD CONSTRAINT "FeedbackAnswer_fieldId_fkey" FOREIGN KEY ("fieldId") REFERENCES "FeedbackField"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Registration" ADD COLUMN "analyticsSessionId" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AnalyticsEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"sessionId" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"stage" TEXT NOT NULL,
|
||||
"source" TEXT,
|
||||
"device" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AnalyticsEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AnalyticsDaily" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"day" DATE NOT NULL,
|
||||
"stage" TEXT NOT NULL,
|
||||
"source" TEXT NOT NULL DEFAULT 'direct',
|
||||
"device" TEXT NOT NULL DEFAULT 'unknown',
|
||||
"sessions" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "AnalyticsDaily_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AnalyticsEvent_eventId_createdAt_idx" ON "AnalyticsEvent"("eventId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "AnalyticsEvent_sessionId_eventId_stage_key" ON "AnalyticsEvent"("sessionId", "eventId", "stage");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AnalyticsDaily_eventId_day_idx" ON "AnalyticsDaily"("eventId", "day");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "AnalyticsDaily_eventId_day_stage_source_device_key" ON "AnalyticsDaily"("eventId", "day", "stage", "source", "device");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AnalyticsEvent" ADD CONSTRAINT "AnalyticsEvent_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AnalyticsDaily" ADD CONSTRAINT "AnalyticsDaily_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'impersonation_started';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'impersonation_ended';
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ImpersonationSession" (
|
||||
"id" TEXT NOT NULL,
|
||||
"adminId" TEXT NOT NULL,
|
||||
"targetUserId" TEXT NOT NULL,
|
||||
"reason" TEXT NOT NULL,
|
||||
"startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"endedAt" TIMESTAMP(3),
|
||||
"endedReason" TEXT,
|
||||
|
||||
CONSTRAINT "ImpersonationSession_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ImpersonationRequestLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"sessionId" TEXT NOT NULL,
|
||||
"method" TEXT NOT NULL,
|
||||
"path" TEXT NOT NULL,
|
||||
"blocked" BOOLEAN NOT NULL DEFAULT false,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "ImpersonationRequestLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ImpersonationSession_adminId_idx" ON "ImpersonationSession"("adminId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ImpersonationSession_targetUserId_idx" ON "ImpersonationSession"("targetUserId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ImpersonationRequestLog_sessionId_createdAt_idx" ON "ImpersonationRequestLog"("sessionId", "createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ImpersonationSession" ADD CONSTRAINT "ImpersonationSession_adminId_fkey" FOREIGN KEY ("adminId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ImpersonationSession" ADD CONSTRAINT "ImpersonationSession_targetUserId_fkey" FOREIGN KEY ("targetUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ImpersonationRequestLog" ADD CONSTRAINT "ImpersonationRequestLog_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "ImpersonationSession"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "TicketTransferRequest" (
|
||||
"id" TEXT NOT NULL,
|
||||
"ticketId" TEXT NOT NULL,
|
||||
"requestedById" TEXT NOT NULL,
|
||||
"toName" TEXT NOT NULL,
|
||||
"toEmail" TEXT,
|
||||
"toPhone" TEXT,
|
||||
"details" JSONB,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"respondedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "TicketTransferRequest_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "TicketTransferRequest_tokenHash_key" ON "TicketTransferRequest"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "TicketTransferRequest_ticketId_status_idx" ON "TicketTransferRequest"("ticketId", "status");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TicketTransferRequest" ADD CONSTRAINT "TicketTransferRequest_ticketId_fkey" FOREIGN KEY ("ticketId") REFERENCES "Ticket"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TicketTransferRequest" ADD CONSTRAINT "TicketTransferRequest_requestedById_fkey" FOREIGN KEY ("requestedById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'yoco_config_updated';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'yoco_webhook_registered';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'yoco_webhook_deleted';
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CashupWriteOffCategory" AS ENUM ('card_fees', 'bank_charges', 'cash_shortfall', 'other');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "EventCashupLine" ADD COLUMN "bankAmount" DOUBLE PRECISION,
|
||||
ADD COLUMN "onHandAmount" DOUBLE PRECISION,
|
||||
ADD COLUMN "pendingAmount" DOUBLE PRECISION,
|
||||
ADD COLUMN "pendingReference" TEXT,
|
||||
ADD COLUMN "writeOffTotal" DOUBLE PRECISION NOT NULL DEFAULT 0;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventCashupWriteOff" (
|
||||
"id" TEXT NOT NULL,
|
||||
"lineId" TEXT NOT NULL,
|
||||
"category" "CashupWriteOffCategory" NOT NULL,
|
||||
"amount" DOUBLE PRECISION NOT NULL,
|
||||
"reason" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "EventCashupWriteOff_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventCashupPendingResolution" (
|
||||
"id" TEXT NOT NULL,
|
||||
"lineId" TEXT NOT NULL,
|
||||
"outcome" TEXT NOT NULL,
|
||||
"amount" DOUBLE PRECISION NOT NULL,
|
||||
"category" "CashupWriteOffCategory",
|
||||
"notes" TEXT,
|
||||
"performedById" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "EventCashupPendingResolution_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventCashupWriteOff_lineId_idx" ON "EventCashupWriteOff"("lineId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventCashupPendingResolution_lineId_idx" ON "EventCashupPendingResolution"("lineId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventCashupPendingResolution_performedById_idx" ON "EventCashupPendingResolution"("performedById");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCashupWriteOff" ADD CONSTRAINT "EventCashupWriteOff_lineId_fkey" FOREIGN KEY ("lineId") REFERENCES "EventCashupLine"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCashupPendingResolution" ADD CONSTRAINT "EventCashupPendingResolution_lineId_fkey" FOREIGN KEY ("lineId") REFERENCES "EventCashupLine"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventCashupPendingResolution" ADD CONSTRAINT "EventCashupPendingResolution_performedById_fkey" FOREIGN KEY ("performedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,83 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'bundle_created';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'bundle_updated';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'bundle_deleted';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Registration" ADD COLUMN "bundleDiscount" DOUBLE PRECISION NOT NULL DEFAULT 0;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventBundle" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"price" DOUBLE PRECISION NOT NULL,
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
"validFrom" TIMESTAMP(3),
|
||||
"validUntil" TIMESTAMP(3),
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "EventBundle_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventBundleItem" (
|
||||
"id" TEXT NOT NULL,
|
||||
"bundleId" TEXT NOT NULL,
|
||||
"eventOptionId" TEXT NOT NULL,
|
||||
"variantId" TEXT,
|
||||
"quantity" INTEGER NOT NULL,
|
||||
|
||||
CONSTRAINT "EventBundleItem_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "RegistrationBundle" (
|
||||
"id" TEXT NOT NULL,
|
||||
"registrationId" TEXT NOT NULL,
|
||||
"bundleId" TEXT NOT NULL,
|
||||
"count" INTEGER NOT NULL,
|
||||
"discount" DOUBLE PRECISION NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "RegistrationBundle_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventBundle_eventId_idx" ON "EventBundle"("eventId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventBundleItem_bundleId_idx" ON "EventBundleItem"("bundleId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventBundleItem_eventOptionId_idx" ON "EventBundleItem"("eventOptionId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventBundleItem_variantId_idx" ON "EventBundleItem"("variantId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "RegistrationBundle_registrationId_idx" ON "RegistrationBundle"("registrationId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "RegistrationBundle_bundleId_idx" ON "RegistrationBundle"("bundleId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventBundle" ADD CONSTRAINT "EventBundle_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventBundleItem" ADD CONSTRAINT "EventBundleItem_bundleId_fkey" FOREIGN KEY ("bundleId") REFERENCES "EventBundle"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventBundleItem" ADD CONSTRAINT "EventBundleItem_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventBundleItem" ADD CONSTRAINT "EventBundleItem_variantId_fkey" FOREIGN KEY ("variantId") REFERENCES "OptionVariant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "RegistrationBundle" ADD CONSTRAINT "RegistrationBundle_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "RegistrationBundle" ADD CONSTRAINT "RegistrationBundle_bundleId_fkey" FOREIGN KEY ("bundleId") REFERENCES "EventBundle"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "BundleKind" AS ENUM ('exact', 'mix', 'free', 'group');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "BundleGroupPricing" AS ENUM ('per_ticket', 'percent');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "EventBundle" ADD COLUMN "freeCount" INTEGER,
|
||||
ADD COLUMN "groupPricing" "BundleGroupPricing",
|
||||
ADD COLUMN "kind" "BundleKind" NOT NULL DEFAULT 'exact',
|
||||
ADD COLUMN "setSize" INTEGER;
|
||||
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ScheduleType" AS ENUM ('single', 'sessions');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "AttendanceMode" AS ENUM ('whole', 'pick');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "LatePricing" AS ENUM ('full', 'prorata', 'fixed');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CheckInWindow" AS ENUM ('whole_day', 'session_only');
|
||||
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'event_sessions_changed';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'attendance_marked';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'attendance_unmarked';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'certificate_issued';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'certificate_revoked';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "attendanceMode" "AttendanceMode" NOT NULL DEFAULT 'whole',
|
||||
ADD COLUMN "certificateConfig" JSONB,
|
||||
ADD COLUMN "certificatesEnabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "checkInWindow" "CheckInWindow" NOT NULL DEFAULT 'whole_day',
|
||||
ADD COLUMN "lateFixedPrice" DOUBLE PRECISION,
|
||||
ADD COLUMN "lateJoinEnabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "lateJoinUntilSessionId" TEXT,
|
||||
ADD COLUMN "latePricing" "LatePricing" NOT NULL DEFAULT 'full',
|
||||
ADD COLUMN "scheduleType" "ScheduleType" NOT NULL DEFAULT 'single',
|
||||
ADD COLUMN "sessionReminders" JSONB;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "TicketUsage" ADD COLUMN "manual" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "sessionId" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EventSession" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"label" TEXT,
|
||||
"startsAt" TIMESTAMP(3) NOT NULL,
|
||||
"endsAt" TIMESTAMP(3) NOT NULL,
|
||||
"location" TEXT,
|
||||
"cancelledAt" TIMESTAMP(3),
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "EventSession_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SessionReminderLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"sessionId" TEXT NOT NULL,
|
||||
"offset" INTEGER NOT NULL,
|
||||
"sent" INTEGER NOT NULL DEFAULT 0,
|
||||
"sentAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "SessionReminderLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Certificate" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"ticketId" TEXT NOT NULL,
|
||||
"userId" TEXT,
|
||||
"name" TEXT NOT NULL,
|
||||
"code" TEXT NOT NULL,
|
||||
"sessionsAttended" INTEGER NOT NULL DEFAULT 0,
|
||||
"totalSessions" INTEGER NOT NULL DEFAULT 0,
|
||||
"manual" BOOLEAN NOT NULL DEFAULT false,
|
||||
"issuedById" TEXT,
|
||||
"issuedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"emailedAt" TIMESTAMP(3),
|
||||
"revokedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "Certificate_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventSession_eventId_startsAt_idx" ON "EventSession"("eventId", "startsAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "SessionReminderLog_sessionId_offset_key" ON "SessionReminderLog"("sessionId", "offset");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Certificate_code_key" ON "Certificate"("code");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Certificate_userId_idx" ON "Certificate"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Certificate_ticketId_idx" ON "Certificate"("ticketId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Certificate_issuedById_idx" ON "Certificate"("issuedById");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Certificate_eventId_ticketId_key" ON "Certificate"("eventId", "ticketId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "TicketUsage_sessionId_idx" ON "TicketUsage"("sessionId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "TicketUsage" ADD CONSTRAINT "TicketUsage_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "EventSession"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventSession" ADD CONSTRAINT "EventSession_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "SessionReminderLog" ADD CONSTRAINT "SessionReminderLog_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "EventSession"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Certificate" ADD CONSTRAINT "Certificate_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Certificate" ADD CONSTRAINT "Certificate_ticketId_fkey" FOREIGN KEY ("ticketId") REFERENCES "Ticket"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Certificate" ADD CONSTRAINT "Certificate_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Certificate" ADD CONSTRAINT "Certificate_issuedById_fkey" FOREIGN KEY ("issuedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "OptionSessionMode" AS ENUM ('all', 'pick');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "EventOption" ADD COLUMN "sessionMode" "OptionSessionMode" NOT NULL DEFAULT 'all';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "EventSession" ADD COLUMN "capacity" INTEGER;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "RegistrationOption" ADD COLUMN "sessionId" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "RegistrationOption_sessionId_idx" ON "RegistrationOption"("sessionId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "RegistrationOption" ADD CONSTRAINT "RegistrationOption_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "EventSession"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'job_run_manual';
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "WaitlistEntry" ADD COLUMN "sessionId" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "WaitlistEntry_sessionId_idx" ON "WaitlistEntry"("sessionId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "WaitlistEntry" ADD CONSTRAINT "WaitlistEntry_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "EventSession"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "RegistrationOption" ADD COLUMN "sessionIds" TEXT[] DEFAULT ARRAY[]::TEXT[];
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Payment providers (1.36.0). YocoTransaction becomes ProviderTransaction: renamed in place
|
||||
-- so every stored transaction is kept (Prisma's generated plan drops and recreates it).
|
||||
|
||||
-- AlterEnum
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'payment_providers_updated';
|
||||
|
||||
-- Rename YocoTransaction → ProviderTransaction
|
||||
ALTER TABLE "YocoTransaction" RENAME TO "ProviderTransaction";
|
||||
ALTER TABLE "ProviderTransaction" RENAME CONSTRAINT "YocoTransaction_pkey" TO "ProviderTransaction_pkey";
|
||||
ALTER TABLE "ProviderTransaction" RENAME CONSTRAINT "YocoTransaction_paymentId_fkey" TO "ProviderTransaction_paymentId_fkey";
|
||||
ALTER INDEX "YocoTransaction_paymentId_idx" RENAME TO "ProviderTransaction_paymentId_idx";
|
||||
|
||||
-- Which provider sent it; external ids are unique per provider
|
||||
ALTER TABLE "ProviderTransaction" ADD COLUMN "provider" TEXT NOT NULL DEFAULT 'yoco';
|
||||
DROP INDEX "YocoTransaction_externalId_key";
|
||||
CREATE UNIQUE INDEX "ProviderTransaction_provider_externalId_key" ON "ProviderTransaction"("provider", "externalId");
|
||||
|
||||
-- Payment.provider: every online payment so far came through Yoco (linked to a transaction,
|
||||
-- or the donation split off one)
|
||||
ALTER TABLE "Payment" ADD COLUMN "provider" TEXT;
|
||||
UPDATE "Payment" SET "provider" = 'yoco'
|
||||
WHERE "id" IN (SELECT "paymentId" FROM "ProviderTransaction" WHERE "paymentId" IS NOT NULL)
|
||||
OR "originalPaymentId" IN (SELECT "paymentId" FROM "ProviderTransaction" WHERE "paymentId" IS NOT NULL);
|
||||
@@ -0,0 +1,24 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'payfast_config_updated';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "ProviderTransaction" ADD COLUMN "note" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ProviderCheckout" (
|
||||
"id" TEXT NOT NULL,
|
||||
"provider" TEXT,
|
||||
"externalId" TEXT,
|
||||
"redirectUrl" TEXT,
|
||||
"amountCents" INTEGER NOT NULL,
|
||||
"currency" TEXT NOT NULL DEFAULT 'ZAR',
|
||||
"metadata" JSONB NOT NULL,
|
||||
"request" JSONB NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ProviderCheckout_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ProviderCheckout_provider_externalId_idx" ON "ProviderCheckout"("provider", "externalId");
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "DataRequestType" AS ENUM ('access', 'correction', 'deletion');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "DataRequestStatus" AS ENUM ('open', 'completed', 'rejected', 'cancelled');
|
||||
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'data_request_completed';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'data_request_rejected';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'user_anonymised';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "newsAskedAt" TIMESTAMP(3),
|
||||
ADD COLUMN "newsEmail" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "newsWhatsApp" BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "CommunicationConsent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT,
|
||||
"address" TEXT,
|
||||
"channel" TEXT NOT NULL,
|
||||
"granted" BOOLEAN NOT NULL,
|
||||
"source" TEXT NOT NULL,
|
||||
"ip" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "CommunicationConsent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "MessagingOptOut" (
|
||||
"id" TEXT NOT NULL,
|
||||
"channel" TEXT NOT NULL,
|
||||
"address" TEXT NOT NULL,
|
||||
"source" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "MessagingOptOut_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "DataRequest" (
|
||||
"id" TEXT NOT NULL,
|
||||
"type" "DataRequestType" NOT NULL,
|
||||
"status" "DataRequestStatus" NOT NULL DEFAULT 'open',
|
||||
"userId" TEXT,
|
||||
"name" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"details" TEXT,
|
||||
"response" TEXT,
|
||||
"selfService" BOOLEAN NOT NULL DEFAULT false,
|
||||
"dueAt" TIMESTAMP(3) NOT NULL,
|
||||
"closedAt" TIMESTAMP(3),
|
||||
"handledById" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "DataRequest_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "CommunicationConsent_userId_createdAt_idx" ON "CommunicationConsent"("userId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "CommunicationConsent_address_idx" ON "CommunicationConsent"("address");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "MessagingOptOut_channel_address_key" ON "MessagingOptOut"("channel", "address");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "DataRequest_status_dueAt_idx" ON "DataRequest"("status", "dueAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "DataRequest_userId_idx" ON "DataRequest"("userId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "CommunicationConsent" ADD CONSTRAINT "CommunicationConsent_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "DataRequest" ADD CONSTRAINT "DataRequest_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "DataRequest" ADD CONSTRAINT "DataRequest_handledById_fkey" FOREIGN KEY ("handledById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- Existing accounts: kept opted in to news (WhatsApp only when they have a phone number),
|
||||
-- logged as "existing_account", and asked once at their next login (newsAskedAt stays null).
|
||||
UPDATE "User" SET "newsEmail" = true, "newsWhatsApp" = ("phoneNumber" IS NOT NULL)
|
||||
WHERE "isActive" = true AND "email" NOT LIKE '%@deleted.invalid' AND "email" NOT LIKE '%@deleted.local' AND "email" NOT LIKE '%@guest.local';
|
||||
|
||||
INSERT INTO "CommunicationConsent" ("id", "userId", "channel", "granted", "source")
|
||||
SELECT gen_random_uuid()::text, "id", 'email', true, 'existing_account' FROM "User" WHERE "newsEmail" = true;
|
||||
|
||||
INSERT INTO "CommunicationConsent" ("id", "userId", "channel", "granted", "source")
|
||||
SELECT gen_random_uuid()::text, "id", 'whatsapp', true, 'existing_account' FROM "User" WHERE "newsWhatsApp" = true;
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'privacy_notice_published';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'operator_created';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'operator_updated';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'operator_deleted';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "noticeVersionAccepted" INTEGER;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "PrivacyNotice" (
|
||||
"id" TEXT NOT NULL,
|
||||
"version" INTEGER NOT NULL,
|
||||
"sections" JSONB NOT NULL,
|
||||
"changeSummary" TEXT,
|
||||
"requiresAcceptance" BOOLEAN NOT NULL DEFAULT false,
|
||||
"publishedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"publishedById" TEXT,
|
||||
|
||||
CONSTRAINT "PrivacyNotice_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "NoticeAcceptance" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT,
|
||||
"version" INTEGER NOT NULL,
|
||||
"source" TEXT NOT NULL,
|
||||
"ip" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "NoticeAcceptance_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Operator" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"purpose" TEXT NOT NULL,
|
||||
"dataShared" TEXT NOT NULL,
|
||||
"location" TEXT,
|
||||
"website" TEXT,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Operator_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "DataAccessLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"actorId" TEXT,
|
||||
"actorRole" TEXT NOT NULL,
|
||||
"action" TEXT NOT NULL,
|
||||
"what" TEXT NOT NULL,
|
||||
"eventId" TEXT,
|
||||
"records" INTEGER,
|
||||
"ip" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "DataAccessLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "PrivacyNotice_version_key" ON "PrivacyNotice"("version");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "NoticeAcceptance_userId_createdAt_idx" ON "NoticeAcceptance"("userId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "NoticeAcceptance_version_idx" ON "NoticeAcceptance"("version");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "DataAccessLog_createdAt_idx" ON "DataAccessLog"("createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "DataAccessLog_actorId_createdAt_idx" ON "DataAccessLog"("actorId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "DataAccessLog_action_createdAt_idx" ON "DataAccessLog"("action", "createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PrivacyNotice" ADD CONSTRAINT "PrivacyNotice_publishedById_fkey" FOREIGN KEY ("publishedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "NoticeAcceptance" ADD CONSTRAINT "NoticeAcceptance_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "DataAccessLog" ADD CONSTRAINT "DataAccessLog_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- The operator register starts with the services Hope Events itself uses. Admins correct the
|
||||
-- details (e.g. which email and hosting provider) in Admin → Privacy → Operators.
|
||||
INSERT INTO "Operator" ("id", "name", "purpose", "dataShared", "location", "website", "active", "order", "updatedAt") VALUES
|
||||
(gen_random_uuid()::text, 'Yoco', 'Card payments', 'Payment amount and reference; card details are entered on Yoco''s own page', 'South Africa', 'https://www.yoco.com', true, 1, CURRENT_TIMESTAMP),
|
||||
(gen_random_uuid()::text, 'PayFast', 'Online payments', 'Name, email address, payment amount and reference', 'South Africa', 'https://payfast.io', true, 2, CURRENT_TIMESTAMP),
|
||||
(gen_random_uuid()::text, 'WAWP', 'Delivering WhatsApp messages', 'Mobile number and message content', NULL, 'https://wawp.net', true, 3, CURRENT_TIMESTAMP),
|
||||
(gen_random_uuid()::text, 'WhatsApp (Meta Platforms)', 'The WhatsApp messaging service', 'Mobile number and message content', NULL, 'https://www.whatsapp.com/legal/privacy-policy', true, 4, CURRENT_TIMESTAMP),
|
||||
(gen_random_uuid()::text, 'Email delivery provider', 'Sending emails (the SMTP server in Site settings)', 'Name, email address and message content', NULL, NULL, true, 5, CURRENT_TIMESTAMP),
|
||||
(gen_random_uuid()::text, 'Hosting provider', 'The servers this site and its database run on', 'All information held by the site', 'South Africa', NULL, true, 6, CURRENT_TIMESTAMP),
|
||||
(gen_random_uuid()::text, 'Google Maps', 'Maps on event pages', 'Your device''s IP address and browser details when a map loads', NULL, 'https://policies.google.com/privacy', true, 7, CURRENT_TIMESTAMP),
|
||||
(gen_random_uuid()::text, 'Sentry', 'Error monitoring (only when it is set up)', 'Technical error reports, which can include the signed-in user''s id', NULL, 'https://sentry.io', false, 8, CURRENT_TIMESTAMP);
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "BreachStatus" AS ENUM ('open', 'contained', 'closed');
|
||||
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'retention_policies_updated';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'retention_run';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'breach_recorded';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'breach_updated';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "DataAccessLog" ADD COLUMN "sensitive" BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "inactivityWarnedAt" TIMESTAMP(3),
|
||||
ADD COLUMN "lastLoginAt" TIMESTAMP(3);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SecurityBreach" (
|
||||
"id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"status" "BreachStatus" NOT NULL DEFAULT 'open',
|
||||
"discoveredAt" TIMESTAMP(3) NOT NULL,
|
||||
"occurredAt" TIMESTAMP(3),
|
||||
"description" TEXT NOT NULL,
|
||||
"dataAffected" TEXT NOT NULL,
|
||||
"peopleAffected" INTEGER,
|
||||
"whoAffected" TEXT,
|
||||
"consequences" TEXT,
|
||||
"actionsTaken" TEXT,
|
||||
"adviceToPeople" TEXT,
|
||||
"causedBy" TEXT,
|
||||
"regulatorNotifiedAt" TIMESTAMP(3),
|
||||
"peopleNotifiedAt" TIMESTAMP(3),
|
||||
"createdById" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "SecurityBreach_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "SecurityBreach_status_discoveredAt_idx" ON "SecurityBreach"("status", "discoveredAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "SecurityBreach" ADD CONSTRAINT "SecurityBreach_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- Last login, from the login history (which the retention job will start expiring).
|
||||
UPDATE "User" u SET "lastLoginAt" = l.at
|
||||
FROM (SELECT "userId", MAX("createdAt") AS at FROM "SecurityEvent" WHERE "type" = 'login' AND "userId" IS NOT NULL GROUP BY "userId") l
|
||||
WHERE u."id" = l."userId";
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'hub_connected';
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'hub_update_requested';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'campuses_toggled';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'campus_created';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'campus_updated';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'campus_archived';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'campus_deleted';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'event_campus_changed';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "campusId" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "homeCampusId" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Campus" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"address" TEXT,
|
||||
"contactName" TEXT,
|
||||
"contactEmail" TEXT,
|
||||
"contactPhone" TEXT,
|
||||
"colour" TEXT,
|
||||
"logoUrl" TEXT,
|
||||
"defaultLocation" TEXT,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
"archivedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Campus_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "_CampusNotifyRecipients" (
|
||||
"A" TEXT NOT NULL,
|
||||
"B" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "_CampusNotifyRecipients_AB_pkey" PRIMARY KEY ("A","B")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Campus_slug_key" ON "Campus"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Campus_order_idx" ON "Campus"("order");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "_CampusNotifyRecipients_B_index" ON "_CampusNotifyRecipients"("B");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Event_campusId_idx" ON "Event"("campusId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "User_homeCampusId_idx" ON "User"("homeCampusId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "User" ADD CONSTRAINT "User_homeCampusId_fkey" FOREIGN KEY ("homeCampusId") REFERENCES "Campus"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Event" ADD CONSTRAINT "Event_campusId_fkey" FOREIGN KEY ("campusId") REFERENCES "Campus"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "_CampusNotifyRecipients" ADD CONSTRAINT "_CampusNotifyRecipients_A_fkey" FOREIGN KEY ("A") REFERENCES "Campus"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "_CampusNotifyRecipients" ADD CONSTRAINT "_CampusNotifyRecipients_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user