-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
5201 lines (4870 loc) · 250 KB
/
Copy pathindex.html
File metadata and controls
5201 lines (4870 loc) · 250 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="color-scheme" content="light dark" />
<title>DeliverPort - Share work. Get paid on-chain.</title>
<meta name="description" content="The delivery portal for freelancers who bill in USDC on Base. Share deliverables, create invoices, and get paid on-chain." />
<!-- ═══════════════════════════════════════════════════════════════
FONTS - editorial + utility pairing
═══════════════════════════════════════════════════════════════ -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Instrument+Serif:ital@0;1&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<!-- Warm API origin early for faster first authenticated request on GitHub Pages -->
<link rel="preconnect" href="https://deliverport-api-production.up.railway.app" crossorigin>
<link rel="dns-prefetch" href="https://deliverport-api-production.up.railway.app">
<!-- Tailwind Play CDN (MVP - swap for build later) -->
<script src="https://cdn.tailwindcss.com?plugins=forms,typography"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: { extend: {
fontFamily: {
sans: ['Inter','ui-sans-serif','system-ui','sans-serif'],
display: ['"Instrument Serif"','ui-serif','Georgia','serif'],
mono: ['"JetBrains Mono"','ui-monospace','monospace'],
},
}}
}
</script>
<style>
/* ═══════════════════════════════════════════════════════════════
DESIGN TOKENS + GLOBAL STYLES
DeliverPort: warm earth tones + blue-indigo brand
═══════════════════════════════════════════════════════════════ */
:root {
--bg: #f6f4ef;
--bg-elev: #fbfaf6;
--bg-sunken: #efebe0;
--border: #e3ddcb;
--border-strong: #cdc3a8;
--ink: #1a170f;
--ink-muted: #5e533a;
--ink-faint: #8f8158;
--brand: #4338ca;
--brand-ink: #f6f4ef;
--accent: #c97627;
--danger: #a33222;
}
.dark {
--bg: #0e0c07;
--bg-elev: #15120a;
--bg-sunken: #0a0804;
--border: #2a2519;
--border-strong: #3e3727;
--ink: #f6f4ef;
--ink-muted: #b9ac86;
--ink-faint: #8f8158;
--brand: #818cf8;
--brand-ink: #0a0d20;
}
* { -webkit-tap-highlight-color: transparent; }
html, body { background: var(--bg); color: var(--ink); }
body {
font-family: Inter, ui-sans-serif, system-ui, sans-serif;
font-feature-settings: "ss01","cv11";
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
background-image:
radial-gradient(1200px 600px at 100% -10%, rgba(99,102,241,0.06), transparent 60%),
radial-gradient(900px 500px at -10% 110%, rgba(67,56,202,0.05), transparent 60%);
}
.font-display { font-family: "Instrument Serif", ui-serif, Georgia, serif; letter-spacing: -0.01em; }
.font-mono { font-family: "JetBrains Mono", ui-monospace, monospace; }
/* Glass card - warm, subtle */
.card {
background: color-mix(in srgb, var(--bg-elev) 88%, transparent);
border: 1px solid var(--border);
border-radius: 14px;
box-shadow: 0 1px 0 rgba(14,12,7,0.04), 0 1px 2px rgba(14,12,7,0.05), 0 12px 36px -18px rgba(14,12,7,0.12);
backdrop-filter: blur(8px) saturate(1.05);
}
.card-flat {
background: var(--bg-elev);
border: 1px solid var(--border);
border-radius: 12px;
}
.hairline { border-color: var(--border); }
.divide-hair > * + * { border-top: 1px solid var(--border); }
/* Buttons */
.btn {
display:inline-flex; align-items:center; gap:.5rem;
padding:.55rem .9rem; border-radius:10px;
font-weight:500; font-size:.875rem; line-height:1;
border:1px solid var(--border-strong);
background: var(--bg-elev); color: var(--ink);
transition: transform .08s ease, background .15s ease, border-color .15s ease, box-shadow .15s ease;
cursor: pointer;
}
.btn:hover { background: color-mix(in srgb, var(--bg-elev) 80%, var(--ink) 4%); }
.btn:active { transform: translateY(1px); }
.btn-primary {
background: var(--brand); color: var(--brand-ink); border-color: transparent;
box-shadow: 0 1px 0 rgba(0,0,0,.15), 0 6px 18px -6px color-mix(in srgb, var(--brand) 55%, transparent);
}
.btn-primary:hover { background: color-mix(in srgb, var(--brand) 90%, #000); }
.btn-ghost { background: transparent; border-color: transparent; }
.btn-ghost:hover { background: color-mix(in srgb, var(--ink) 6%, transparent); }
.btn-danger { background: var(--danger); color: #fff7f3; border-color: transparent; }
.btn-danger:hover { background: color-mix(in srgb, var(--danger) 90%, #000); }
.btn:disabled { opacity:.45; cursor:not-allowed; }
/* Inputs */
.field {
width: 100%;
background: var(--bg-elev);
border: 1px solid var(--border-strong);
border-radius: 10px;
padding: .65rem .8rem;
font-size: .9rem;
color: var(--ink);
transition: border-color .15s ease, box-shadow .15s ease;
font-family: inherit;
}
.field:focus {
outline: none;
border-color: var(--brand);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--brand) 22%, transparent);
}
textarea.field { min-height: 96px; resize: vertical; line-height: 1.55; }
label.lbl { display:block; font-size:.72rem; font-weight:600; text-transform:uppercase; letter-spacing:.08em; color: var(--ink-muted); margin-bottom:.35rem; }
/* Chips */
.chip {
display:inline-flex; align-items:center; gap:.35rem;
padding:.2rem .55rem; border-radius:999px;
font-size:.72rem; font-weight:600; letter-spacing:.02em;
border:1px solid var(--border-strong);
background: var(--bg-elev); color: var(--ink-muted);
}
.chip-dot { width:6px; height:6px; border-radius:999px; background: currentColor; }
.chip-moss { color:#1f5d23; background:#eef7ee; border-color:#a9d5a7; }
.chip-amber { color:#8a4b03; background:#fff4e6; border-color:#ffc166; }
.chip-clay { color:#7e420d; background:#fbf1e7; border-color:#e8b985; }
.chip-danger { color:#7c241a; background:#fbeae6; border-color:#e9a79c; }
.chip-ink { color:#1a170f; background:#ece8dc; border-color:#b9ac86; }
.chip-indigo { color:#3730a3; background:#eef2ff; border-color:#a5b4fc; }
/* Editorial type */
.eyebrow { font-family:"Instrument Serif", serif; font-style: italic; color: var(--ink-faint); font-size: 1rem; }
.h1 { font-family:"Instrument Serif", serif; font-size: clamp(2rem, 4.2vw, 3.2rem); line-height: 1.05; letter-spacing: -0.015em; font-weight: 400; }
.h2 { font-family:"Instrument Serif", serif; font-size: clamp(1.5rem, 2.8vw, 2rem); line-height: 1.1; font-weight: 400; }
.kbd { font-family:"JetBrains Mono", monospace; font-size:.7rem; padding:.1rem .4rem; border-radius:5px; background:var(--bg-sunken); border:1px solid var(--border); color:var(--ink-muted); }
/* Nav */
.navlink { display:flex; align-items:center; gap:.6rem; padding:.55rem .75rem; border-radius:10px; color:var(--ink-muted); font-size:.88rem; font-weight:500; text-decoration:none; }
.navlink:hover { background: color-mix(in srgb, var(--ink) 5%, transparent); color: var(--ink); }
.navlink.active { background: color-mix(in srgb, var(--brand) 12%, transparent); color: var(--ink); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--brand) 25%, transparent); }
.navlink .ico { width:16px; height:16px; stroke-width:2; flex-shrink:0; }
.navlink .ico { width:16px; height:16px; stroke-width:2; flex-shrink:0; }
/* Toast */
.toast {
position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%) translateY(20px);
background: var(--ink); color: var(--bg);
padding:.75rem 1.2rem; border-radius:12px; font-size:.85rem; font-weight:500;
box-shadow: 0 12px 40px -12px rgba(0,0,0,.4);
opacity:0; pointer-events:none; transition: all .25s ease; z-index:100;
}
.toast.show { opacity:1; transform: translateX(-50%) translateY(0); }
/* Modal */
.modal-backdrop { position: fixed; inset:0; background: color-mix(in srgb, var(--ink) 40%, transparent); backdrop-filter: blur(6px); z-index:50; display:flex; align-items:center; justify-content:center; padding:1rem; }
.modal { width:100%; max-width:640px; max-height:88vh; overflow-y:auto; }
/* Responsive sidebar */
.sidebar { transition: transform .25s ease; }
@media (max-width: 900px) {
.sidebar { position: fixed; top:0; bottom:0; left:0; width:260px; transform: translateX(-100%); z-index:40; }
.sidebar.open { transform: translateX(0); }
.main-area { margin-left: 0 !important; }
}
/* Animations */
@keyframes fadeUp { from { opacity:0; transform: translateY(8px);} to { opacity:1; transform:none;} }
.anim-in { animation: fadeUp .3s ease both; }
@keyframes spin { to { transform: rotate(360deg); } }
.spin { animation: spin 1s linear infinite; }
/* Charts */
.bar { transition: width .4s cubic-bezier(.2,.8,.2,1); }
/* Line clamp */
.clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
</style>
</head>
<body class="min-h-screen antialiased">
<div id="boot" class="fixed inset-0 flex items-center justify-center z-[100]" style="background:var(--bg)">
<div class="text-center px-6">
<div class="inline-flex items-center justify-center w-12 h-12 rounded-2xl mb-5" style="background:linear-gradient(135deg,#4338ca,#6366f1);color:#fff;box-shadow:0 12px 36px -20px rgba(99,102,241,.65)">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" class="w-6 h-6"><path d="M12 3v12M7 10l5-5 5 5"/><path d="M5 21h14"/></svg>
</div>
<div class="font-display text-3xl">DeliverPort</div>
<div class="mt-3 text-sm" style="color:var(--ink-muted)">Preparing your workspace...</div>
<div class="mt-1 text-xs" style="color:var(--ink-faint)">Share work, review progress, and get paid with confidence.</div>
</div>
</div>
<div id="app"></div>
<div id="modal-root"></div>
<div id="toast" class="toast"></div>
<script type="module">
/* ════════════════════════════════════════════════════════════════════════════
DELIVERPORT - single-file app
Client delivery portal + on-chain billing for freelancers.
Organised into labelled sections:
1. CONFIG - tunables, pricing, currencies
2. ICONS - inline SVG library
3. UTILS - helpers (format, csv, download, esc...)
4. AUTH CRYPTO - password hashing
5. SCHEMA - SQL DDL (tables, indexes)
6. SEED - initial demo data
7. DB - PGlite instance + query facade
8. FX - live currency conversion
9. STORE - reactive in-memory projection
10. SERVICES - business logic (Users, Auth, Clients, Projects, Revenue)
11. COMPONENTS - shared UI pieces (Toast, Modal, UI helpers)
12. PAGES - landing, login, dashboard, billing, portal, share
13. ROUTER - hash router + shell layout
14. BOOT - bring up PGlite, hydrate store, first render
════════════════════════════════════════════════════════════════════════════ */
import { PGlite } from 'https://cdn.jsdelivr.net/npm/@electric-sql/pglite/dist/index.js';
/* ══════════════════════════════════════ 0. CRYPTO - Base USDC payment layer ══════════════════════════════════════
Lazy-loads viem from esm.sh CDN. Only downloaded when a user interacts with wallet features.
Chain: Base (8453) · Tokens: USDC (6 dec), USDT (6 dec)
═══════════════════════════════════════════════════════════════════════════════════════════════════════ */
const BASE_TOKENS = {
USDC: { address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', decimals: 6, symbol: 'USDC', name: 'USD Coin' },
USDT: { address: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2', decimals: 6, symbol: 'USDT', name: 'Tether USD' },
};
const BASE_CHAIN = {
id: 8453, name: 'Base',
rpcUrls: ['https://mainnet.base.org', 'https://base.llamarpc.com', 'https://base.drpc.org'],
blockExplorer: 'https://basescan.org',
};
const ERC20_ABI = [
{ inputs:[{name:'account',type:'address'}], name:'balanceOf', outputs:[{name:'',type:'uint256'}], stateMutability:'view', type:'function' },
{ inputs:[{name:'to',type:'address'},{name:'value',type:'uint256'}], name:'transfer', outputs:[{name:'',type:'bool'}], stateMutability:'nonpayable', type:'function' },
{ anonymous:false, inputs:[{indexed:true,name:'from',type:'address'},{indexed:true,name:'to',type:'address'},{indexed:false,name:'value',type:'uint256'}], name:'Transfer', type:'event' },
];
const Crypto = {
_viem: null, _client: null, _wallet: null, _account: null, _loading: false, _listeners: new Set(),
async _loadViem() {
if (this._viem) return this._viem;
this._viem = await import('https://esm.sh/viem@2.47.12');
return this._viem;
},
async getPublicClient() {
if (this._client) return this._client;
const viem = await this._loadViem();
for (const rpc of BASE_CHAIN.rpcUrls) {
try {
this._client = viem.createPublicClient({
chain: { id: BASE_CHAIN.id, name: BASE_CHAIN.name, nativeCurrency: { name:'Ether', symbol:'ETH', decimals:18 }, rpcUrls: { default: { http: [rpc] } } },
transport: viem.http(rpc),
});
await this._client.getBlockNumber();
return this._client;
} catch { this._client = null; }
}
throw new Error('All Base RPC endpoints failed');
},
hasWallet() { return typeof window !== 'undefined' && !!window.ethereum; },
async connect() {
if (!this.hasWallet()) throw new Error('No wallet detected. Install MetaMask or Coinbase Wallet.');
this._loading = true; this._notify();
try {
const viem = await this._loadViem();
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
if (!accounts?.length) throw new Error('No accounts returned');
await this._switchToBase();
this._account = accounts[0];
this._wallet = viem.createWalletClient({
account: this._account,
chain: { id: BASE_CHAIN.id, name: BASE_CHAIN.name, nativeCurrency: { name:'Ether', symbol:'ETH', decimals:18 }, rpcUrls: { default: { http: [BASE_CHAIN.rpcUrls[0]] } } },
transport: viem.custom(window.ethereum),
});
window.ethereum.on('accountsChanged', (a) => { this._account = a[0] || null; if (!this._account) this.disconnect(); this._notify(); });
window.ethereum.on('chainChanged', () => window.location.reload());
} finally { this._loading = false; this._notify(); }
return this._account;
},
async _switchToBase() {
try { await window.ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: '0x' + BASE_CHAIN.id.toString(16) }] }); }
catch (e) {
if (e.code === 4902) await window.ethereum.request({ method: 'wallet_addEthereumChain', params: [{ chainId: '0x'+BASE_CHAIN.id.toString(16), chainName:'Base', nativeCurrency:{name:'Ether',symbol:'ETH',decimals:18}, rpcUrls:[BASE_CHAIN.rpcUrls[0]], blockExplorerUrls:[BASE_CHAIN.blockExplorer] }] });
else throw e;
}
},
disconnect() { this._wallet = null; this._account = null; this._notify(); },
address() { return this._account || null; },
shortAddress(addr) { const a = addr || this._account; return a ? a.slice(0,6) + '...' + a.slice(-4) : ''; },
isConnected() { return !!this._account; },
async getBalance(address, token = 'USDC') {
const client = await this.getPublicClient();
const t = BASE_TOKENS[token]; if (!t) throw new Error(`Unknown token: ${token}`);
const raw = await client.readContract({ address: t.address, abi: ERC20_ABI, functionName: 'balanceOf', args: [address] });
return Number(raw) / (10 ** t.decimals);
},
async sendPayment(toAddress, amountUsd, token = 'USDC') {
if (!this._wallet) throw new Error('Wallet not connected');
const viem = await this._loadViem();
const t = BASE_TOKENS[token]; if (!t) throw new Error(`Unknown token: ${token}`);
const amountRaw = BigInt(Math.round(amountUsd * (10 ** t.decimals)));
const data = viem.encodeFunctionData({ abi: ERC20_ABI, functionName: 'transfer', args: [toAddress, amountRaw] });
return this._wallet.sendTransaction({
to: t.address, data,
chain: { id: BASE_CHAIN.id, name: BASE_CHAIN.name, nativeCurrency: { name:'Ether', symbol:'ETH', decimals:18 }, rpcUrls: { default: { http: [BASE_CHAIN.rpcUrls[0]] } } },
});
},
async waitForTx(hash) { const c = await this.getPublicClient(); return c.waitForTransactionReceipt({ hash, confirmations: 2 }); },
async findPayment(toAddress, amountUsd, token = 'USDC', opts = {}) {
const client = await this.getPublicClient();
const t = BASE_TOKENS[token]; if (!t) throw new Error(`Unknown token: ${token}`);
const expectedRaw = BigInt(Math.round(amountUsd * (10 ** t.decimals)));
const toleranceRaw = BigInt(Math.round((opts.tolerance ?? 0.02) * (10 ** t.decimals)));
const currentBlock = await client.getBlockNumber();
const fromBlock = opts.fromBlock || (currentBlock - 3600n);
const logs = await client.getContractEvents({ address: t.address, abi: ERC20_ABI, eventName: 'Transfer', args: { to: toAddress }, fromBlock, toBlock: 'latest' });
for (const log of logs) {
const diff = log.args.value > expectedRaw ? log.args.value - expectedRaw : expectedRaw - log.args.value;
if (diff <= toleranceRaw) return { txHash: log.transactionHash, from: log.args.from, amount: Number(log.args.value) / (10 ** t.decimals), blockNumber: Number(log.blockNumber), token };
}
return null;
},
paymentLink(toAddress, amountUsd, token = 'USDC') {
const t = BASE_TOKENS[token];
return `ethereum:${t.address}@${BASE_CHAIN.id}/transfer?address=${toAddress}&uint256=${BigInt(Math.round(amountUsd * (10 ** t.decimals)))}`;
},
txUrl(hash) { return `${BASE_CHAIN.blockExplorer}/tx/${hash}`; },
addressUrl(addr) { return `${BASE_CHAIN.blockExplorer}/address/${addr}`; },
formatAmount(amount, token = 'USDC') { return `${Number(amount).toFixed(2)} ${token}`; },
onChange(fn) { this._listeners.add(fn); return () => this._listeners.delete(fn); },
_notify() {
const state = { connected: this.isConnected(), address: this._account, loading: this._loading };
for (const fn of this._listeners) { try { fn(state); } catch (e) { console.error('[Crypto]', e); } }
},
};
/* ══════════════════════════════════════ 1. CONFIG ══════════════════════════════════════ */
const DEFAULT_DB_NAME = 'idb://deliverport';
const DEMO_DB_NAME = 'idb://deliverport-demo';
function resolveDbName() {
try {
const url = new URL(location.href);
const raw = url.searchParams.get('db') || '';
const slug = raw.trim().replace(/[^a-zA-Z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
if (slug) return `idb://${slug}`;
if (url.searchParams.get('demo') === '1') return DEMO_DB_NAME;
return DEFAULT_DB_NAME;
} catch {
return DEFAULT_DB_NAME;
}
}
const APP = (() => {
const url = new URL(location.href);
return {
demo: url.searchParams.get('demo') === '1',
debug: url.searchParams.get('debug') === '1',
basePath: url.pathname,
};
})();
const CONFIG = {
appName: 'DeliverPort',
tagline: 'Share work. Get paid on-chain.',
dbName: resolveDbName(),
schemaVersion: 1,
auth: {
sessionHours: 72,
seedPasswords: {
operator: crypto.getRandomValues(new Uint8Array(12)).reduce((s,b) => s + b.toString(36).padStart(2,'0'), '').slice(0,16) + '!A',
client: crypto.getRandomValues(new Uint8Array(12)).reduce((s,b) => s + b.toString(36).padStart(2,'0'), '').slice(0,16) + '!A',
},
},
clientStatuses: ['active','paused'],
projectStatuses: ['active','delivery','archived'],
invoiceStatuses: ['draft','sent','paid'],
payoutRunStatuses: ['draft','queued','completed'],
paymentRails: {
billing: ['USDC (Base)', 'USDT (Base)', 'Manual'],
payouts: ['USDC (Base)', 'USDT (Base)', 'Manual'],
},
defaultCurrency: 'USD',
// On production pages, default to the hosted API unless the user explicitly forced local mode.
defaultApiOriginByHost: {
'siliconstate.github.io': 'https://deliverport-api-production.up.railway.app',
},
// Freemium tiers
plans: {
free: { label: 'Free', maxProjects: 2, canArchive: false, canDeleteProject: false },
pro: { label: 'Pro', maxProjects: Infinity, canArchive: true, canDeleteProject: true },
},
defaultPlan: 'free',
// Supported display currencies. Exchange rates are fetched live from
// @fawazahmed0/currency-api (free, no key, CDN-served, 200+ currencies).
currencies: [
{ code: 'USD', symbol: '$', name: 'US Dollar', locale: 'en-US' },
{ code: 'NGN', symbol: '₦', name: 'Nigerian Naira', locale: 'en-NG' },
{ code: 'KES', symbol: 'KSh', name: 'Kenyan Shilling', locale: 'en-KE' },
{ code: 'GHS', symbol: 'GH₵', name: 'Ghanaian Cedi', locale: 'en-GH' },
{ code: 'ZAR', symbol: 'R', name: 'South African Rand', locale: 'en-ZA' },
{ code: 'EGP', symbol: 'E£', name: 'Egyptian Pound', locale: 'en-EG' },
{ code: 'EUR', symbol: '€', name: 'Euro', locale: 'en-IE' },
{ code: 'GBP', symbol: '£', name: 'British Pound', locale: 'en-GB' },
{ code: 'CAD', symbol: 'C$', name: 'Canadian Dollar', locale: 'en-CA' },
{ code: 'AUD', symbol: 'A$', name: 'Australian Dollar', locale: 'en-AU' },
{ code: 'INR', symbol: '₹', name: 'Indian Rupee', locale: 'en-IN' },
{ code: 'CNY', symbol: '¥', name: 'Chinese Yuan', locale: 'zh-CN' },
],
};
/* ══════════════════════════════════════ 2. ICONS ══════════════════════════════════════ */
const I = {
dash: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></svg>`,
folder: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M4 4h5l2 2h9a1 1 0 0 1 1 1v11a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z"/></svg>`,
money: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="2" y="6" width="20" height="13" rx="2"/><circle cx="12" cy="12.5" r="2.5"/></svg>`,
search: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>`,
plus: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 5v14M5 12h14"/></svg>`,
export: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 3v12M7 10l5-5 5 5"/><path d="M5 21h14"/></svg>`,
check: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M5 12l5 5L20 7"/></svg>`,
x: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M6 6l12 12M18 6l-12 12"/></svg>`,
menu: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M4 6h16M4 12h16M4 18h16"/></svg>`,
file: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><path d="M14 3v6h6"/></svg>`,
user: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>`,
users: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><circle cx="9" cy="7" r="3.5"/><path d="M2 21a7 7 0 0 1 14 0"/><circle cx="17" cy="9" r="2.5"/><path d="M22 21a5 5 0 0 0-7.5-4.3"/></svg>`,
db: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><ellipse cx="12" cy="5" rx="8" ry="3"/><path d="M4 5v14c0 1.7 3.6 3 8 3s8-1.3 8-3V5"/><path d="M4 12c0 1.7 3.6 3 8 3s8-1.3 8-3"/></svg>`,
link: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.5 1.5"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.5-1.5"/></svg>`,
wallet: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="2" y="6" width="20" height="14" rx="2"/><path d="M2 10h20"/><circle cx="17" cy="14" r="1.5"/></svg>`,
globe: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10Z"/></svg>`,
shield: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 2 4 6v6c0 5 3.5 8.5 8 10 4.5-1.5 8-5 8-10V6l-8-4Z"/><path d="m9 12 2 2 4-4"/></svg>`,
chart: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M3 3v18h18"/><path d="m7 15 4-4 3 3 5-6"/></svg>`,
copy: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="9" y="9" width="12" height="12" rx="1.5"/><path d="M5 15H4a1.5 1.5 0 0 1-1.5-1.5V4A1.5 1.5 0 0 1 4 2.5h9.5A1.5 1.5 0 0 1 15 4v1"/></svg>`,
sun: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><circle cx="12" cy="12" r="4"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4 7 17M17 7l1.4-1.4"/></svg>`,
moon: `<svg class="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M20 14.5A8 8 0 1 1 9.5 4 6.5 6.5 0 0 0 20 14.5Z"/></svg>`,
};
/* ══════════════════════════════════════ 3. UTILS ══════════════════════════════════════ */
const U = {
uid: (p='id') => p + '_' + Math.random().toString(36).slice(2,10) + Date.now().toString(36).slice(-4),
fmtDate: (iso) => iso ? new Date(iso).toLocaleString('en-US', { dateStyle:'medium', timeStyle:'short' }) : '-',
fmtDay: (iso) => iso ? new Date(iso).toLocaleDateString('en-US', { month:'short', day:'numeric' }) : '-',
fmtMoney: (n, src, dst) => {
const srcCur = src || CONFIG.defaultCurrency || 'USD';
const dstCur = dst || Store.state?.displayCurrency || CONFIG.defaultCurrency || 'USD';
const converted = FX.convert(Number(n) || 0, srcCur, dstCur);
const meta = CONFIG.currencies.find(c => c.code === dstCur) || CONFIG.currencies[0];
const hardCurrency = new Set(['USD','EUR','GBP','CAD','AUD']);
const frac = hardCurrency.has(dstCur) ? 2 : (Math.abs(converted) < 10 ? 2 : 0);
return new Intl.NumberFormat(meta.locale || 'en-US', {
style: 'currency', currency: dstCur,
maximumFractionDigits: frac, minimumFractionDigits: frac,
}).format(converted);
},
fmtNum: (n) => new Intl.NumberFormat('en-US').format(Number(n) || 0),
fmtPct: (n) => (Math.round((Number(n)||0) * 1000) / 10) + '%',
clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)),
norm: (s='') => String(s || '')
.toLowerCase()
.normalize('NFKD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-z0-9]+/g, ' ')
.trim(),
slug: (s='') => String(s || '')
.toLowerCase()
.normalize('NFKD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '') || 'export',
inferDisplayCurrency: (opts = {}) => {
const supported = new Set(CONFIG.currencies.map(c => c.code));
const regionToCurrency = {
US:'USD', NG:'NGN', KE:'KES', GH:'GHS', ZA:'ZAR', EG:'EGP',
GB:'GBP', IE:'EUR', FR:'EUR', DE:'EUR', ES:'EUR', IT:'EUR', NL:'EUR',
BE:'EUR', PT:'EUR', AT:'EUR', FI:'EUR', GR:'EUR', LU:'EUR', SI:'EUR',
SK:'EUR', LV:'EUR', LT:'EUR', EE:'EUR', CY:'EUR', MT:'EUR', HR:'EUR',
CA:'CAD', AU:'AUD', IN:'INR', CN:'CNY',
};
const timezoneToCurrency = {
'Africa/Lagos': 'NGN', 'Africa/Nairobi': 'KES', 'Africa/Accra': 'GHS',
'Africa/Johannesburg': 'ZAR', 'Africa/Cairo': 'EGP', 'Europe/London': 'GBP',
};
const locales = Array.isArray(opts.locales) && opts.locales.length
? opts.locales
: [navigator.language, ...(navigator.languages || [])].filter(Boolean);
const timezone = opts.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone || '';
const regionFromLocale = (locale) => {
try { return new Intl.Locale(locale).region || null; }
catch { const match = String(locale || '').match(/[-_]([A-Za-z]{2})\b/); return match?.[1]?.toUpperCase() || null; }
};
for (const locale of locales) {
const region = regionFromLocale(locale);
const code = region && regionToCurrency[region];
if (code && supported.has(code)) return code;
}
const zoneCode = timezoneToCurrency[timezone];
if (zoneCode && supported.has(zoneCode)) return zoneCode;
return CONFIG.defaultCurrency || 'USD';
},
avg: (arr) => arr.length ? arr.reduce((a,b)=>a+Number(b),0)/arr.length : 0,
esc: (s) => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])),
debounce: (fn, ms=200) => { let t; return (...a) => { clearTimeout(t); t=setTimeout(()=>fn(...a), ms); }; },
download: (name, mime, data) => {
const blob = new Blob([data], { type: mime });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = name; document.body.appendChild(a); a.click();
a.remove(); URL.revokeObjectURL(url);
},
toCSV: (rows) => {
if (!rows.length) return '';
const cols = Object.keys(rows[0]);
const esc = v => {
if (v == null) return '';
const s = typeof v === 'object' ? JSON.stringify(v) : String(v);
return /[",\n\r]/.test(s) ? `"${s.replace(/"/g,'""')}"` : s;
};
return [cols.join(','), ...rows.map(r => cols.map(c => esc(r[c])).join(','))].join('\n');
},
hashParams: (hash = location.hash || '') => {
const idx = String(hash).indexOf('?');
const raw = idx >= 0 ? hash.slice(idx + 1) : '';
return Object.fromEntries(new URLSearchParams(raw).entries());
},
setHashParams: (path, params = {}) => {
const qs = new URLSearchParams(Object.entries(params).filter(([, value]) => value != null && value !== '')).toString();
return qs ? `${path}?${qs}` : path;
},
href: (hash = '#/landing', { demo = APP.demo, search = {} } = {}) => {
const url = new URL(location.origin + APP.basePath);
if (demo) url.searchParams.set('demo', '1');
Object.entries(search || {}).forEach(([key, value]) => {
if (value == null || value === '') url.searchParams.delete(key);
else url.searchParams.set(key, value);
});
return `${url.pathname}${url.search}${hash}`;
},
safeExternalUrl: (raw = '') => {
const value = String(raw || '').trim();
if (!value) return '';
const coerce = (input) => {
try {
const parsed = new URL(input);
return /^https?:$/i.test(parsed.protocol) ? parsed.href : '';
} catch {
return '';
}
};
const direct = coerce(value);
if (direct) return direct;
if (!/^[a-z]+:/i.test(value)) return coerce(`https://${value}`);
return '';
},
bytesToBase64: (bytes) => btoa(String.fromCharCode(...Array.from(bytes || []))),
base64ToBytes: (b64 = '') => Uint8Array.from(atob(String(b64 || '')), c => c.charCodeAt(0)),
copyToClipboard: async (text) => {
try { await navigator.clipboard.writeText(text); return true; }
catch { return false; }
},
};
/* ══════════════════════════════════════ 4. AUTH CRYPTO ══════════════════════════════════════ */
const AuthCrypto = {
async hashPassword(password, saltB64 = null, iterations = 120000) {
const salt = saltB64 ? U.base64ToBytes(saltB64) : crypto.getRandomValues(new Uint8Array(16));
const keyMaterial = await crypto.subtle.importKey('raw', new TextEncoder().encode(String(password || '')), 'PBKDF2', false, ['deriveBits']);
const bits = await crypto.subtle.deriveBits({ name: 'PBKDF2', salt, iterations, hash: 'SHA-256' }, keyMaterial, 256);
const hash = new Uint8Array(bits);
return `pbkdf2$${iterations}$${U.bytesToBase64(salt)}$${U.bytesToBase64(hash)}`;
},
async verifyPassword(password, stored = '') {
const [algo, iterations, saltB64, hashB64] = String(stored || '').split('$');
if (algo !== 'pbkdf2' || !iterations || !saltB64 || !hashB64) return false;
const next = await this.hashPassword(password, saltB64, Number(iterations));
return next === stored;
},
};
/* ══════════════════════════════════════ 5. SCHEMA ══════════════════════════════════════ */
const SCHEMA = `
CREATE TABLE IF NOT EXISTS meta (
key TEXT PRIMARY KEY,
value JSONB NOT NULL
);
CREATE TABLE IF NOT EXISTS clients (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
company TEXT,
email TEXT,
country TEXT,
billing_currency TEXT NOT NULL DEFAULT 'USD',
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active','paused')),
notes TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS projects (
id TEXT PRIMARY KEY,
client_id TEXT REFERENCES clients(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT,
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active','delivery','archived')),
portal_token TEXT UNIQUE,
deliverables JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
start_at TIMESTAMPTZ,
due_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
role TEXT NOT NULL CHECK (role IN ('operator','client')),
password_hash TEXT,
auth_status TEXT NOT NULL DEFAULT 'active',
client_id TEXT REFERENCES clients(id) ON DELETE SET NULL,
wallet_address TEXT,
phone TEXT,
last_login_at TIMESTAMPTZ,
joined_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS invoices (
id TEXT PRIMARY KEY,
client_id TEXT REFERENCES clients(id) ON DELETE SET NULL,
project_id TEXT REFERENCES projects(id) ON DELETE SET NULL,
status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft','sent','paid')),
currency TEXT NOT NULL DEFAULT 'USD',
amount NUMERIC NOT NULL DEFAULT 0,
provider TEXT,
external_ref TEXT,
line_items JSONB,
notes TEXT,
payment_address TEXT,
chain TEXT DEFAULT 'base',
token TEXT DEFAULT 'USDC',
issued_at TIMESTAMPTZ NOT NULL DEFAULT now(),
due_at TIMESTAMPTZ,
paid_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS payout_runs (
id TEXT PRIMARY KEY,
status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft','queued','completed')),
currency TEXT NOT NULL DEFAULT 'USD',
amount NUMERIC NOT NULL DEFAULT 0,
provider TEXT,
external_ref TEXT,
line_items JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
queued_at TIMESTAMPTZ,
completed_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_projects_client ON projects(client_id);
CREATE INDEX IF NOT EXISTS idx_invoices_project ON invoices(project_id);
CREATE INDEX IF NOT EXISTS idx_payout_runs_state ON payout_runs(status);
`;
/* ══════════════════════════════════════ 6. SEED DATA ══════════════════════════════════════ */
const SEED_CLIENTS = [
{
id: 'c_demo',
name: 'Apex Studios',
company: 'Apex Studios',
email: 'hello@apexstudios.io',
country: 'United States',
billing_currency: 'USD',
status: 'active',
notes: 'Demo client for the delivery portal. Brand design & web dev project.',
},
];
const SEED_PROJECTS = [
{
id: 'p_brand',
client_id: 'c_demo',
name: 'Brand identity refresh',
description: 'Complete brand identity redesign including logo, color system, typography, and brand guidelines document. Phase 1 of a broader website redesign.',
status: 'active',
portal_token: 'portal-demo-brand',
deliverables: JSON.stringify([
{ name: 'Logo suite (SVG + PNG)', status: 'delivered', note: 'Primary, stacked, icon-only variants' },
{ name: 'Color system', status: 'delivered', note: '5-color palette with accessibility ratios' },
{ name: 'Typography guide', status: 'in_progress', note: 'Font pairing, scale, and usage rules' },
{ name: 'Brand guidelines PDF', status: 'pending', note: 'Final compiled document' },
]),
},
{
id: 'p_web',
client_id: 'c_demo',
name: 'Marketing website',
description: 'Responsive marketing site built on Next.js with CMS integration. 8-page site with blog, case studies, and contact form.',
status: 'active',
portal_token: 'portal-demo-web',
deliverables: JSON.stringify([
{ name: 'Wireframes', status: 'delivered', note: 'Figma file with 8 page layouts' },
{ name: 'High-fidelity mockups', status: 'in_progress', note: 'Desktop + mobile for all pages' },
{ name: 'Development build', status: 'pending', note: 'Next.js + Sanity CMS' },
{ name: 'QA & launch', status: 'pending', note: 'Cross-browser testing, DNS, deploy' },
]),
},
];
const SEED_USERS = [
{ id: 'u_operator', name: 'Jordan Rivera', email: 'jordan@deliverport.io', role: 'operator', passwordKey: 'operator', wallet_address: '0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18' },
{ id: 'u_client', name: 'Sam Chen', email: 'sam@apexstudios.io', role: 'client', passwordKey: 'client', client_id: 'c_demo' },
];
const SEED_INVOICES = [
{
id: 'inv_001',
client_id: 'c_demo',
project_id: 'p_brand',
status: 'paid',
currency: 'USD',
amount: 2500,
provider: 'USDC (Base)',
payment_address: '0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18',
chain: 'base',
token: 'USDC',
line_items: JSON.stringify([
{ description: 'Logo suite design', quantity: 1, rate: 1500, amount: 1500 },
{ description: 'Color system & palette', quantity: 1, rate: 1000, amount: 1000 },
]),
notes: 'Phase 1 - logo + color. Paid via USDC on Base.', // historical note, intentional
},
{
id: 'inv_002',
client_id: 'c_demo',
project_id: 'p_brand',
status: 'sent',
currency: 'USD',
amount: 1800,
provider: 'USDC (Base)',
payment_address: '0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18',
chain: 'base',
token: 'USDC',
line_items: JSON.stringify([
{ description: 'Typography guide', quantity: 1, rate: 800, amount: 800 },
{ description: 'Brand guidelines PDF', quantity: 1, rate: 1000, amount: 1000 },
]),
notes: 'Phase 2 - typography + guidelines.',
},
];
/* ══════════════════════════════════════ 7. DB - PGlite facade ══════════════════════════════════════ */
const DB = {
pg: null,
ready: false,
async init() {
this.pg = new PGlite(CONFIG.dbName);
await this.pg.waitReady;
await this.pg.exec(SCHEMA);
await this.runMigrations();
await this.seedIfEmpty();
await this.backfillSeedPasswords();
this.ready = true;
},
async setWorkspaceKind(kind) {
await this.query(
`INSERT INTO meta(key,value) VALUES ('workspace_kind', $1::jsonb)
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,
[JSON.stringify(kind)]
);
},
async query(sql, params=[]) {
const res = await this.pg.query(sql, params);
return res.rows || [];
},
async exec(sql) { return this.pg.exec(sql); },
async runMigrations() {
const [row] = await this.query(`SELECT value FROM meta WHERE key='schema_version'`);
const current = Number(row?.value || 0) || 0;
if (!row) {
await this.query(`INSERT INTO meta(key,value) VALUES ('schema_version', $1::jsonb)`, [String(CONFIG.schemaVersion)]);
}
// Future migrations go here (if current < 2) { ... }
await this.query(
`INSERT INTO meta(key,value) VALUES ('schema_version', $1::jsonb)
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,
[String(CONFIG.schemaVersion)]
);
},
async backfillSeedPasswords() {
for (const user of SEED_USERS) {
const [row] = await this.query(`SELECT id, password_hash FROM users WHERE id = $1`, [user.id]);
if (!row) continue;
const password = CONFIG.auth.seedPasswords[user.passwordKey || 'operator'] || CONFIG.auth.seedPasswords.operator;
const passwordHash = row.password_hash || await AuthCrypto.hashPassword(password);
await this.query(
`UPDATE users SET password_hash = $2, auth_status = COALESCE(auth_status, 'active'),
client_id = COALESCE(client_id, $3), wallet_address = COALESCE(wallet_address, $4)
WHERE id = $1`,
[user.id, passwordHash, user.client_id || null, user.wallet_address || null]
);
}
},
async seedDemoWorkspace() {
for (const client of SEED_CLIENTS) {
await this.query(
`INSERT INTO clients(id,name,company,email,country,billing_currency,status,notes)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`,
[client.id, client.name, client.company || null, client.email || null, client.country || null, client.billing_currency || 'USD', client.status || 'active', client.notes || null]
);
}
for (const project of SEED_PROJECTS) {
await this.query(
`INSERT INTO projects(id,client_id,name,description,status,portal_token,deliverables)
VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb)`,
[project.id, project.client_id, project.name, project.description || null, project.status || 'active', project.portal_token, project.deliverables || null]
);
}
for (const user of SEED_USERS) {
const password = CONFIG.auth.seedPasswords[user.passwordKey || 'operator'] || CONFIG.auth.seedPasswords.operator;
await this.query(
`INSERT INTO users(id,name,email,role,password_hash,client_id,auth_status,wallet_address)
VALUES ($1,$2,$3,$4,$5,$6,'active',$7)`,
[user.id, user.name, user.email, user.role, await AuthCrypto.hashPassword(password), user.client_id || null, user.wallet_address || null]
);
}
for (const inv of SEED_INVOICES) {
const paidAt = inv.status === 'paid' ? new Date(Date.now() - 7 * 24 * 3600 * 1000).toISOString() : null;
const dueAt = new Date(Date.now() + 14 * 24 * 3600 * 1000).toISOString();
await this.query(
`INSERT INTO invoices(id,client_id,project_id,status,currency,amount,provider,payment_address,chain,token,line_items,notes,due_at,paid_at)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::jsonb,$12,$13,$14)`,
[inv.id, inv.client_id, inv.project_id, inv.status, inv.currency, inv.amount, inv.provider, inv.payment_address, inv.chain, inv.token, inv.line_items, inv.notes || null, dueAt, paidAt]
);
}
await this.setWorkspaceKind('demo');
},
async isSeedWorkspace() {
const [kindRow] = await this.query(`SELECT value FROM meta WHERE key='workspace_kind'`);
if (kindRow?.value === 'demo') return true;
const rows = await this.query(`SELECT id FROM users ORDER BY id`);
if (!rows.length) return false;
const seedIds = new Set(SEED_USERS.map(user => user.id));
return rows.length === SEED_USERS.length && rows.every(row => seedIds.has(row.id));
},
async seedIfEmpty() {
const [{ count: userCount }] = await this.query(`SELECT COUNT(*)::int AS count FROM users`);
if (userCount > 0) return;
if (APP.demo) {
await this.seedDemoWorkspace();
} else {
await this.setWorkspaceKind('live');
}
},
async prepareRealWorkspace() {
if (APP.demo) return;
if (await this.isSeedWorkspace()) {
await this.wipe({ seedDemo: false });
return;
}
await this.setWorkspaceKind('live');
},
expectedSchema() {
return {
tables: ['meta', 'clients', 'projects', 'users', 'invoices', 'payout_runs'],
columns: {
users: ['id', 'name', 'email', 'role', 'password_hash', 'auth_status', 'client_id', 'wallet_address', 'phone', 'last_login_at', 'joined_at'],
clients: ['id', 'name', 'company', 'email', 'country', 'billing_currency', 'status', 'notes', 'created_at'],
projects: ['id', 'client_id', 'name', 'description', 'status', 'portal_token', 'deliverables', 'created_at', 'start_at', 'due_at'],
invoices: ['id', 'client_id', 'project_id', 'status', 'currency', 'amount', 'provider', 'external_ref', 'line_items', 'notes', 'payment_address', 'chain', 'token', 'issued_at', 'due_at', 'paid_at'],
payout_runs: ['id', 'status', 'currency', 'amount', 'provider', 'external_ref', 'line_items', 'created_at', 'queued_at', 'completed_at'],
},
};
},
async schemaHealth() {
const spec = this.expectedSchema();
const tables = await this.query(`SELECT table_name FROM information_schema.tables WHERE table_schema NOT IN ('pg_catalog', 'information_schema')`);
const columns = await this.query(`SELECT table_name, column_name FROM information_schema.columns WHERE table_schema NOT IN ('pg_catalog', 'information_schema')`);
const tableSet = new Set(tables.map(row => row.table_name));
const columnMap = columns.reduce((acc, row) => { (acc[row.table_name] ||= new Set()).add(row.column_name); return acc; }, {});
const missingTables = spec.tables.filter(name => !tableSet.has(name));
const missingColumns = Object.entries(spec.columns).flatMap(([table, names]) =>
names.filter(name => !(columnMap[table] || new Set()).has(name)).map(name => `${table}.${name}`)
);
const [schemaRow] = tableSet.has('meta') ? await this.query(`SELECT value FROM meta WHERE key='schema_version'`) : [null];
const version = Number(schemaRow?.value || 0) || 0;
return {
dbName: CONFIG.dbName, version, expectedVersion: CONFIG.schemaVersion,
tableCount: spec.tables.length, missingTables, missingColumns,
ok: version >= CONFIG.schemaVersion && !missingTables.length && !missingColumns.length,
};
},
async repair() {
await this.pg.exec(SCHEMA);
await this.runMigrations();
await this.backfillSeedPasswords();
await Store.rehydrate();
return this.schemaHealth();
},
async wipe({ seedDemo = APP.demo } = {}) {
await this.exec(`
DROP TABLE IF EXISTS payout_runs CASCADE;
DROP TABLE IF EXISTS invoices CASCADE;
DROP TABLE IF EXISTS users CASCADE;
DROP TABLE IF EXISTS projects CASCADE;
DROP TABLE IF EXISTS clients CASCADE;
DROP TABLE IF EXISTS meta CASCADE;
`);
await this.pg.exec(SCHEMA);
await this.runMigrations();
if (seedDemo) await this.seedDemoWorkspace();
else await this.setWorkspaceKind('live');
await this.backfillSeedPasswords();
},
async hardReset(opts = {}) {
await this.wipe(opts);
await Store.rehydrate();
return this.schemaHealth();
},
};
/* ══════════════════════════════════════ 7b. API CLIENT - remote backend ══════════════════════════════════════ */
const ApiClient = {
baseUrl: '',
token: null,
_bootstrapInFlight: null,
_bootstrapTrailingForceRequested: false,
_lastBootstrapSnapshot: null,
_lastBootstrapFetchedAt: 0,
_bootstrapDebounceMs: 320,
init(baseUrl) {
this.baseUrl = baseUrl.replace(/\/+$/, '');
this.token = localStorage.getItem('deliverport_jwt') || null;
this.prefetchOrigin(this.baseUrl);
},
prefetchOrigin(url) {
try {
const origin = new URL(url).origin;
const head = document.head || document.querySelector('head');
if (!head) return;
if (!head.querySelector(`link[data-api-preconnect="${origin}"]`)) {
const preconnect = document.createElement('link');
preconnect.rel = 'preconnect';
preconnect.href = origin;
preconnect.crossOrigin = 'anonymous';
preconnect.dataset.apiPreconnect = origin;
head.appendChild(preconnect);
}