forked from Stellar-split/split-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpage.tsx
More file actions
1182 lines (1088 loc) · 43.1 KB
/
Copy pathpage.tsx
File metadata and controls
1182 lines (1088 loc) · 43.1 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
"use client";
import { useState, useEffect, useCallback, useMemo, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
import dynamic from "next/dynamic";
import Stepper, { type Step } from "@/components/ui/Stepper";
import { splitClient } from "@/lib/stellar";
import { getFreighterPublicKey } from "@/lib/freighter";
import { deadlineFromDays, parseAmount, formatAmount } from "@stellar-split/sdk";
import TxConfirmModal from "@/components/TxConfirmModal";
import { recordInvoiceHistory } from "@/lib/invoiceHistory";
import { useI18n } from "@/components/I18nProvider";
import DeadlineSuggester from "@/components/DeadlineSuggester";
import { validateDeadline } from "@/components/DuplicateModal";
import { decodeTemplate } from "@/lib/templateSharing";
import type { ImportedTxData } from "@/lib/txImport";
import {
generateRetroactiveInvoiceId,
saveRetroactiveInvoice,
type RetroactiveInvoice,
} from "@/lib/retroactiveInvoices";
import { useOfflineDraftAutosave } from "@/hooks/useOfflineDraftAutosave";
import {
getOrCreateLocalUserId,
listDraftsForUser,
type StoredDraft,
} from "@/lib/offlineDraftDB";
import SplitCalculator from "@/components/SplitCalculator";
import TagInput from "@/components/invoice/TagInput";
import { useInvoiceTags } from "@/hooks/useInvoiceTags";
import {
calculateSplit,
type SplitMeta,
} from "@/hooks/useSplitCalculator";
import InstallmentPlanBuilder from "@/components/invoice/InstallmentPlanBuilder";
import AmountDenominationInput from "@/components/AmountDenominationInput";
import { useXlmUsdcRate } from "@/hooks/useXlmUsdcRate";
import { useInvoiceCollaboration } from "@/hooks/useInvoiceCollaboration";
import CursorOverlay from "@/components/CursorOverlay";
import PresencePill from "@/components/PresencePill";
import ReconnectionBanner from "@/components/ReconnectionBanner";
const RecipientForm = dynamic(() => import("@/components/RecipientForm"), { ssr: false });
const TemplateManager = dynamic(() => import("@/components/TemplateManager"), { ssr: false });
const TxImportPanel = dynamic(() => import("@/components/invoice/TxImportPanel"), { ssr: false });
const DraftRecoveryBanner = dynamic(() => import("@/components/invoice/DraftRecoveryBanner"), { ssr: false });
interface RecipientRow {
address: string;
amount: string;
}
interface InvoiceTemplate {
recipients: RecipientRow[];
deadlineDays: number;
token: string;
}
interface Toast {
id: number;
message: string;
type: "success" | "error";
}
let _toastId = 0;
function useToasts() {
const [toasts, setToasts] = useState<Toast[]>([]);
const addToast = useCallback((message: string, type: Toast["type"]) => {
const id = ++_toastId;
setToasts((prev) => [...prev, { id, message, type }]);
setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), 5000);
}, []);
return { toasts, addToast };
}
const STEPS = ["Basic Info", "Recipients", "Options", "Review & Submit"];
/** Clamp an arbitrary `?step=` value onto a real step index. */
function parseStep(raw: string | null): number {
const n = Number(raw);
if (!Number.isInteger(n) || n < 1 || n > STEPS.length) return 0;
return n - 1;
}
function ChangedField({ changed, children }: { changed: boolean; children: React.ReactNode }) {
if (!changed) return <>{children}</>;
return (
<div className="relative group">
<div className="ring-2 ring-yellow-400 rounded-lg">{children}</div>
<span
role="tooltip"
className="pointer-events-none absolute -top-7 left-0 z-10 hidden group-hover:block bg-yellow-900 text-yellow-200 text-xs px-2 py-1 rounded whitespace-nowrap"
>
Changed from original
</span>
</div>
);
}
export default function NewInvoicePage() {
return (
<Suspense fallback={<div className="max-w-xl mx-auto px-4 py-16 text-gray-600 dark:text-gray-400">Loading…</div>}>
<NewInvoiceForm />
</Suspense>
);
}
function NewInvoiceForm() {
const { t } = useI18n();
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
// The active step lives in the URL rather than component state so browser
// back/forward moves through the form instead of leaving the page.
const step = parseStep(searchParams.get("step"));
const goToStep = useCallback(
(next: number) => {
const params = new URLSearchParams(searchParams.toString());
if (next === 0) {
params.delete("step");
} else {
params.set("step", String(next + 1));
}
const query = params.toString();
router.push(query ? `${pathname}?${query}` : pathname);
},
[router, pathname, searchParams]
);
const [recipients, setRecipients] = useState<RecipientRow[]>([
{ address: "", amount: "" },
]);
const [deadlineDays, setDeadlineDays] = useState(7);
const [token, setToken] = useState(
process.env.NEXT_PUBLIC_USDC_ADDRESS ?? ""
);
const [recurring, setRecurring] = useState(false);
const [intervalDays, setIntervalDays] = useState<7 | 30>(7);
const [submitting, setSubmitting] = useState(false);
const [splitMeta, setSplitMeta] = useState<SplitMeta | null>(null);
const [installments, setInstallments] = useState<{ id: string; amount: number; dueDate: number; status: string; txHash?: string }[]>([]);
const [tags, setTags] = useState<string[]>([]);
const { allTags, saveTags } = useInvoiceTags();
const fromId = searchParams.get("from");
const deadlineParam = searchParams.get("deadline");
const [cloneSourceId, setCloneSourceId] = useState<string | null>(null);
const [originalToken, setOriginalToken] = useState<string | null>(null);
const [originalRecipients, setOriginalRecipients] = useState<RecipientRow[] | null>(null);
const [deadlineError, setDeadlineError] = useState<string | null>(null);
const [cloneDeadlineIso, setCloneDeadlineIso] = useState<string>(deadlineParam ?? "");
const [formMode, setFormMode] = useState<"create" | "import">("create");
const [importedTx, setImportedTx] = useState<ImportedTxData | null>(null);
const [retroSubmitting, setRetroSubmitting] = useState(false);
const [retroError, setRetroError] = useState<string | null>(null);
const [draftUserId, setDraftUserId] = useState<string | null>(null);
const [draftId, setDraftId] = useState<string | null>(null);
const [recoveredDraft, setRecoveredDraft] = useState<StoredDraft | null>(null);
useEffect(() => {
getFreighterPublicKey()
.then((pk) => setDraftUserId(pk))
.catch(() => setDraftUserId(getOrCreateLocalUserId()));
setDraftId(crypto.randomUUID());
}, []);
useEffect(() => {
if (!draftUserId || fromId || searchParams.get("template") || searchParams.get("address")) return;
listDraftsForUser(draftUserId)
.then((drafts) => {
if (drafts.length > 0) setRecoveredDraft(drafts[0]);
})
.catch(() => null);
// Only check once per mount, independent of draftId (the newly generated
// draft won't exist yet so it can never be the one we find here).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [draftUserId]);
const draftSnapshot = {
recipients,
token,
deadlineDays,
recurring,
intervalDays,
splitMeta,
installments,
};
const { isOffline: draftOffline, discardDraft } = useOfflineDraftAutosave(
draftUserId ?? "",
formMode === "create" && !cloneSourceId ? draftId ?? "" : "",
draftSnapshot
);
const handleRestoreDraft = () => {
if (!recoveredDraft) return;
setRecipients(recoveredDraft.data.recipients);
setToken(recoveredDraft.data.token);
setDeadlineDays(recoveredDraft.data.deadlineDays);
setRecurring(recoveredDraft.data.recurring);
setIntervalDays(recoveredDraft.data.intervalDays);
if ((recoveredDraft.data as any).splitMeta) {
setSplitMeta((recoveredDraft.data as any).splitMeta);
}
if (draftUserId) {
import("@/lib/offlineDraftDB").then(({ deleteDraft }) =>
deleteDraft(draftUserId, recoveredDraft.draftId)
);
}
setRecoveredDraft(null);
addToast("Draft restored", "success");
};
const handleDiscardDraft = () => {
if (recoveredDraft && draftUserId) {
import("@/lib/offlineDraftDB").then(({ deleteDraft }) =>
deleteDraft(draftUserId, recoveredDraft.draftId)
);
}
setRecoveredDraft(null);
};
const { toasts, addToast } = useToasts();
const handleImported = (data: ImportedTxData) => {
setImportedTx(data);
setRetroError(null);
};
const handleRetroactiveSubmit = async () => {
if (!importedTx) return;
setRetroSubmitting(true);
setRetroError(null);
try {
const creator = await getFreighterPublicKey().catch(() => importedTx.recipients[0]?.address ?? "unknown");
const recipients = importedTx.recipients.map((r) => ({
address: r.address,
amount: parseAmount(r.amount),
}));
const total = recipients.reduce((s, r) => s + r.amount, 0n);
const id = generateRetroactiveInvoiceId(importedTx.txHash);
const record: RetroactiveInvoice = {
id,
creator,
recipients,
token: importedTx.recipients[0]?.asset ?? "XLM",
deadline: 0,
funded: total,
status: "Released",
payments: [{ payer: creator, amount: total }],
retroactive: true,
sourceTxHash: importedTx.txHash,
memo: importedTx.memo,
createdAt: importedTx.createdAt,
};
saveRetroactiveInvoice(record);
addToast(`Retroactive invoice #${id} created`, "success");
router.push(`/invoice/${id}`);
} catch (err) {
setRetroError(err instanceof Error ? err.message : String(err));
} finally {
setRetroSubmitting(false);
}
};
useEffect(() => {
const address = searchParams.get("address");
const templateParam = searchParams.get("template");
if (address) {
setRecipients([{ address, amount: "" }]);
return;
}
if (templateParam) {
const decoded = decodeTemplate(templateParam);
if (decoded) {
setRecipients(decoded.recipients);
setToken(decoded.token);
addToast("Shared template loaded successfully", "success");
} else {
addToast("Failed to decode shared template: invalid format", "error");
}
return;
}
const template = sessionStorage.getItem("invoiceTemplate");
if (template) {
const parsed: InvoiceTemplate = JSON.parse(template);
setRecipients(parsed.recipients);
setDeadlineDays(parsed.deadlineDays);
setToken(parsed.token);
sessionStorage.removeItem("invoiceTemplate");
}
}, [searchParams, addToast]);
const [publicKey, setPublicKey] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [txModal, setTxModal] = useState<{ txHash: string; invoiceId: string } | null>(null);
const [equalSplit, setEqualSplit] = useState(false);
const [totalAmount, setTotalAmount] = useState("");
const [loading, setLoading] = useState(false);
const [autofilled, setAutofilled] = useState(false);
const [stepErrors, setStepErrors] = useState<Record<number, string | null>>({});
// Denomination toggle state (XLM / USDC)
type Denomination = "XLM" | "USDC";
const [amountDenom, setAmountDenom] = useState<Denomination>("USDC");
const xlmUsdcRate = useXlmUsdcRate();
/** Convert an amount string from current denomination to USDC for on-chain use */
const toUsdc = useCallback(
(amount: string): string => {
if (amountDenom === "USDC" || !xlmUsdcRate) return amount;
const n = parseFloat(amount);
if (isNaN(n)) return amount;
return (n * xlmUsdcRate).toFixed(7).replace(/\.?0+$/, "");
},
[amountDenom, xlmUsdcRate],
);
useEffect(() => {
getFreighterPublicKey().then(setPublicKey).catch(() => null);
}, []);
useEffect(() => {
if (fromId || sessionStorage.getItem("invoiceTemplate") || searchParams.get("address")) return;
getFreighterPublicKey()
// as any: getInvoicesByCreator is not yet declared in the published @stellar-split/sdk types
.then((pk) => (splitClient as any).getInvoicesByCreator(pk))
.then((invoices: import("@stellar-split/sdk").Invoice[]) => {
if (!invoices || invoices.length === 0) return;
const recent = invoices.slice(-5);
const latestToken = recent[recent.length - 1].token;
const now = Math.floor(Date.now() / 1000);
const daysList = recent
.map((inv) => Math.round((inv.deadline - now) / 86400))
.filter((d) => d > 0)
.sort((a, b) => a - b);
const medianDays =
daysList.length > 0
? daysList[Math.floor(daysList.length / 2)]
: null;
const lastRecipients = recent[recent.length - 1].recipients.map((r) => ({
address: r.address,
amount: formatAmount(r.amount),
}));
setToken(latestToken);
if (medianDays !== null) setDeadlineDays(medianDays);
setRecipients(lastRecipients.length > 0 ? lastRecipients : [{ address: "", amount: "" }]);
setAutofilled(true);
})
.catch(() => null);
}, []);
useEffect(() => {
if (!fromId) return;
setLoading(true);
splitClient
.getInvoice(fromId)
.then((invoice) => {
const recipientRows = invoice.recipients.map((r) => ({
address: r.address,
amount: formatAmount(r.amount),
}));
setRecipients(recipientRows);
setOriginalRecipients(recipientRows);
setToken(invoice.token);
setOriginalToken(invoice.token);
setCloneSourceId(fromId);
if (deadlineParam) {
const err = validateDeadline(deadlineParam);
if (err) setDeadlineError(err);
setCloneDeadlineIso(deadlineParam);
}
})
.catch((err) => {
setError(`Failed to load source invoice: ${err}`);
})
.finally(() => {
setLoading(false);
});
}, [fromId]);
const perRecipientAmount =
equalSplit && totalAmount && recipients.length > 0
? (parseFloat(totalAmount) / recipients.length).toFixed(7)
: undefined;
const handleLoadTemplate = (template: { recipients: RecipientRow[]; token: string }) => {
setRecipients(template.recipients);
setToken(template.token);
};
const recipientsChanged =
!!originalRecipients &&
JSON.stringify(recipients) !== JSON.stringify(originalRecipients);
const tokenChanged = !!originalToken && token !== originalToken;
const validateStep = (s: number): boolean => {
switch (s) {
case 0: {
if (!token || !token.startsWith("C")) {
setStepErrors((prev) => ({ ...prev, [s]: "Valid token contract address is required" }));
return false;
}
if (cloneSourceId && cloneDeadlineIso) {
const err = validateDeadline(cloneDeadlineIso);
if (err) {
setDeadlineError(err);
setStepErrors((prev) => ({ ...prev, [s]: err }));
return false;
}
}
setStepErrors((prev) => ({ ...prev, [s]: null }));
return true;
}
case 1: {
if (recipients.length === 0 || !recipients[0].address) {
setStepErrors((prev) => ({ ...prev, [s]: "At least one recipient is required" }));
return false;
}
const validRecipients = recipients.every(
(r) => r.address.startsWith("G") && r.address.length >= 50 && parseFloat(r.amount || "0") > 0
);
if (!validRecipients) {
setStepErrors((prev) => ({ ...prev, [s]: "Each recipient needs a valid G... address and positive amount" }));
return false;
}
if (splitMeta && splitMeta.recipients.length > 0) {
const splitResult = calculateSplit(splitMeta.totalAmount, splitMeta.recipients, splitMeta.assetCode);
if (!splitResult.validation.isValid) {
setStepErrors((prev) => ({
...prev,
[s]: splitResult.validation.errorMessage ?? "Split calculator has invalid configuration",
}));
return false;
}
}
setStepErrors((prev) => ({ ...prev, [s]: null }));
return true;
}
case 2:
setStepErrors((prev) => ({ ...prev, [s]: null }));
return true;
default:
return true;
}
};
/**
* Reason the split is not submittable, or null when it is. Drives both the
* disabled state and the tooltip on the create button so the user can see
* *why* it is blocked without first clicking it.
*/
const splitBlockReason = useMemo(() => {
if (!splitMeta || splitMeta.recipients.length === 0) return null;
const { validation } = calculateSplit(
splitMeta.totalAmount,
splitMeta.recipients,
splitMeta.assetCode
);
return validation.isValid ? null : validation.errorMessage ?? "Split configuration is invalid";
}, [splitMeta]);
const handleNext = () => {
if (validateStep(step)) {
goToStep(Math.min(step + 1, STEPS.length - 1));
}
};
const handleBack = () => {
goToStep(Math.max(step - 1, 0));
};
const payloadForApi = () => {
if (!splitMeta) return null;
if (installments.length === 0) return splitMeta;
return { ...splitMeta, installments };
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!validateStep(step)) return;
setError(null);
if (cloneSourceId && cloneDeadlineIso) {
const err = validateDeadline(cloneDeadlineIso);
if (err) {
setDeadlineError(err);
return;
}
}
setSubmitting(true);
try {
const creator = await getFreighterPublicKey();
if (cloneSourceId) {
const deadlineTs = Math.floor(new Date(cloneDeadlineIso).getTime() / 1000);
// as any: cloneInvoice is not yet declared in the published @stellar-split/sdk types
const { invoiceId, txHash } = await (splitClient as any).cloneInvoice({
creator,
sourceInvoiceId: cloneSourceId,
recipients: recipients.map((r) => ({
address: r.address,
amount: parseAmount(toUsdc(r.amount)),
})),
token,
deadline: deadlineTs,
});
recordInvoiceHistory(
recipients.map((r) => ({ address: r.address, amount: r.amount }))
);
addToast(`Invoice #${invoiceId} created`, "success");
const apiPayload = payloadForApi();
if (apiPayload && (apiPayload as any).recipients?.length > 0) {
fetch(`/api/invoices/${invoiceId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ splitMeta: apiPayload }),
}).catch(() => null);
}
if (tags.length > 0) {
saveTags(invoiceId, tags).catch(() => null);
}
setTxModal({ txHash, invoiceId });
} else {
const { invoiceId, txHash } = await splitClient.createInvoice({
creator,
recipients: recipients.map((r) => ({
address: r.address,
amount: parseAmount(equalSplit ? toUsdc(perRecipientAmount ?? "0") : toUsdc(r.amount)),
})),
token,
deadline: deadlineFromDays(deadlineDays),
...(recurring && { recurring, intervalDays }),
});
recordInvoiceHistory(
recipients.map((r) => ({
address: r.address,
amount: equalSplit ? (perRecipientAmount ?? "0") : r.amount,
}))
);
const apiPayload = payloadForApi();
if (apiPayload && (apiPayload as any).recipients?.length > 0) {
fetch(`/api/invoices/${invoiceId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ splitMeta: apiPayload }),
}).catch(() => null);
}
if (tags.length > 0) {
saveTags(invoiceId, tags).catch(() => null);
}
setTxModal({ txHash, invoiceId });
}
discardDraft();
} catch (err) {
const msg = String(err);
setError(msg);
if (cloneSourceId) addToast(msg, "error");
} finally {
setSubmitting(false);
}
};
const stepperSteps: Step[] = useMemo(
() =>
STEPS.map((label, index) => ({
label,
status: index < step ? "complete" : index === step ? "current" : "upcoming",
})),
[step]
);
const renderStepIndicator = () => (
<Stepper steps={stepperSteps} onStepClick={goToStep} className="mb-8" />
);
const renderBasicInfo = () => (
<div className="flex flex-col gap-6">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">Basic Info</h2>
{!cloneSourceId && (
<TemplateManager
recipients={recipients}
token={token}
onLoad={handleLoadTemplate}
/>
)}
<div>
<label htmlFor="token-address" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t("invoiceNew.tokenAddress")}
</label>
<ChangedField changed={tokenChanged}>
<input
id="token-address"
type="text"
value={token}
onChange={(e) => setToken(e.target.value)}
onFocus={() => setFocusedField("token-address")}
onBlur={() => {
if (focusedField === "token-address") emitFieldBlur();
}}
required
placeholder="C..."
className="w-full min-h-11 bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-sm text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
<CursorOverlay cursors={remoteCursors} fieldName="token-address" />
</ChangedField>
</div>
{cloneSourceId ? (
<div>
<label htmlFor="clone-deadline" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t("invoiceNew.deadline")}
</label>
<input
id="clone-deadline"
type="datetime-local"
value={cloneDeadlineIso.slice(0, 16)}
onChange={(e) => {
setCloneDeadlineIso(e.target.value);
const err = validateDeadline(e.target.value);
setDeadlineError(err);
setStepErrors((prev) => ({ ...prev, [0]: err }));
}}
required
className={`w-full min-h-11 bg-gray-800 border rounded-lg px-4 py-2 text-sm text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 ${
deadlineError ? "border-red-500" : "border-gray-700"
}`}
aria-describedby={deadlineError ? "clone-deadline-error" : undefined}
aria-invalid={!!deadlineError}
/>
{deadlineError && (
<p id="clone-deadline-error" role="alert" className="text-red-600 dark:text-red-400 text-sm mt-1">
{deadlineError}
</p>
)}
</div>
) : (
<div>
<label htmlFor="deadline-days" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t("invoiceNew.deadline")}
</label>
<input
id="deadline-days"
type="number"
min={1}
max={365}
value={deadlineDays}
onChange={(e) => setDeadlineDays(Number(e.target.value))}
onFocus={() => setFocusedField("deadline-days")}
onBlur={() => {
if (focusedField === "deadline-days") emitFieldBlur();
}}
required
className="w-full min-h-11 bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-sm text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
<CursorOverlay cursors={remoteCursors} fieldName="deadline-days" />
<DeadlineSuggester
totalAmount={
equalSplit
? totalAmount
: recipients
.reduce((sum, r) => sum + parseFloat(r.amount || "0"), 0)
.toString()
}
recipientCount={recipients.filter((r) => r.address).length}
onUseSuggestion={(days: number) => setDeadlineDays(days)}
/>
</div>
)}
{!cloneSourceId && (
<div className="flex items-center justify-between rounded-lg bg-gray-800 border border-gray-700 px-4 py-3">
<label htmlFor="recurring-toggle" className="text-sm font-medium text-gray-300 cursor-pointer">
Recurring invoice
</label>
<button
id="recurring-toggle"
type="button"
role="switch"
aria-checked={recurring}
onClick={() => setRecurring((v) => !v)}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 ${
recurring ? "bg-indigo-600" : "bg-gray-600"
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
recurring ? "translate-x-6" : "translate-x-1"
}`}
/>
</button>
</div>
)}
{recurring && !cloneSourceId && (
<div>
<label htmlFor="interval-days" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Repeat every
</label>
<select
id="interval-days"
value={intervalDays}
onChange={(e) => setIntervalDays(Number(e.target.value) as 7 | 30)}
className="w-full min-h-11 bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-sm text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500"
>
<option value={7}>7 days</option>
<option value={30}>30 days</option>
</select>
</div>
)}
</div>
);
const renderRecipients = () => (
<div className="flex flex-col gap-6">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">Recipients</h2>
{!cloneSourceId && (
<div className="flex items-center justify-between rounded-lg bg-gray-800 border border-gray-700 px-4 py-3">
<label htmlFor="equal-split-toggle" className="text-sm font-medium text-gray-300 cursor-pointer">
{t("invoiceNew.equalSplit")}
</label>
<button
id="equal-split-toggle"
type="button"
role="switch"
aria-checked={equalSplit}
aria-label="Toggle equal split mode"
onClick={() => setEqualSplit((v) => !v)}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 ${
equalSplit ? "bg-indigo-600" : "bg-gray-300 dark:bg-gray-600"
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
equalSplit ? "translate-x-6" : "translate-x-1"
}`}
/>
</button>
</div>
)}
{equalSplit && !cloneSourceId && (
<div>
<label htmlFor="total-amount" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t("invoiceNew.totalAmount")}
</label>
<input
id="total-amount"
type="number"
placeholder="0.00"
step="0.0000001"
min="0.0000001"
value={totalAmount}
onChange={(e) => setTotalAmount(e.target.value)}
onFocus={() => setFocusedField("total-amount")}
onBlur={() => {
if (focusedField === "total-amount") emitFieldBlur();
}}
required
className="w-full min-h-11 bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-sm text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
<CursorOverlay cursors={remoteCursors} fieldName="total-amount" />
{perRecipientAmount && (
<p className="mt-1 text-xs text-gray-600 dark:text-gray-400">
{perRecipientAmount} {t("invoiceNew.perRecipient")}
</p>
)}
</div>
)}
<div>
<div className="flex items-center justify-between mb-2">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
{equalSplit ? t("invoiceNew.recipients") : t("invoiceNew.recipientsAndAmounts")}
</label>
{!equalSplit && !cloneSourceId && (
<div className="flex items-center gap-1.5">
<span className="text-xs text-gray-500">Amounts in:</span>
<button
type="button"
onClick={() => setAmountDenom((d) => d === "XLM" ? "USDC" : "XLM")}
aria-label={`Switch amount denomination to ${amountDenom === "XLM" ? "USDC" : "XLM"}`}
title={xlmUsdcRate ? `1 XLM ≈ ${xlmUsdcRate.toFixed(4)} USDC` : "Rate unavailable"}
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold border transition-colors ${
amountDenom === "XLM"
? "bg-yellow-500/15 border-yellow-500/40 text-yellow-300 hover:bg-yellow-500/25"
: "bg-blue-500/15 border-blue-500/40 text-blue-300 hover:bg-blue-500/25"
}`}
>
<span aria-hidden="true">{amountDenom === "XLM" ? "✦" : "$"}</span>
{amountDenom}
<svg xmlns="http://www.w3.org/2000/svg" className="w-3 h-3 opacity-60" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5} aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" d="M7 16V4m0 0L3 8m4-4l4 4M17 8v12m0 0l4-4m-4 4l-4-4" />
</svg>
</button>
{xlmUsdcRate && (
<span className="text-xs text-gray-500">1 XLM ≈ {xlmUsdcRate.toFixed(4)} USDC</span>
)}
</div>
)}
</div>
<ChangedField changed={recipientsChanged}>
<RecipientForm
recipients={recipients}
onChange={setRecipients}
equalSplit={equalSplit}
amountOverride={perRecipientAmount}
/>
</ChangedField>
</div>
<SplitCalculator
initialTotal={equalSplit ? totalAmount : recipients.reduce((s, r) => s + parseFloat(r.amount || "0"), 0).toFixed(7)}
onSplitMetaChange={setSplitMeta}
/>
</div>
);
const renderOptions = () => {
const total = recipients.reduce((s, r) => s + parseFloat(r.amount || "0"), 0);
return (
<div className="flex flex-col gap-6">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">Options</h2>
<TagInput
value={tags}
onChange={setTags}
suggestions={allTags}
placeholder="e.g. design, q3-retainer"
/>
{cloneSourceId && (
<div className="flex items-center gap-2 text-sm bg-indigo-950/60 border border-indigo-700 text-indigo-300 rounded-lg px-3 py-2">
<span>Cloned from</span>
<a
href={`/invoice/${cloneSourceId}`}
className="underline hover:text-indigo-200 font-mono"
>
#{cloneSourceId}
</a>
</div>
)}
{!cloneSourceId && (
<TemplateManager
recipients={recipients}
token={token}
onLoad={handleLoadTemplate}
/>
)}
{autofilled && !cloneSourceId && (
<p className="text-xs text-indigo-400 bg-indigo-950/50 border border-indigo-800 rounded-lg px-3 py-2">
Autofilled from history — you can override any value below.
</p>
)}
{recurring && !cloneSourceId && (
<div className="rounded-lg bg-gray-800 border border-gray-700 px-4 py-3">
<p className="text-sm text-gray-300">
This invoice will repeat every <span className="font-semibold text-indigo-300">{intervalDays} days</span>
</p>
</div>
)}
<InstallmentPlanBuilder
totalAmount={total}
installments={installments}
assetCode={token === (process.env.NEXT_PUBLIC_USDC_ADDRESS ?? "") ? "USDC" : "XLM"}
onChange={setInstallments}
/>
</div>
);
};
const renderReview = () => {
const total = recipients.reduce((s, r) => s + parseFloat(r.amount || "0"), 0);
return (
<div className="flex flex-col gap-6">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">Review & Submit</h2>
{cloneSourceId && (
<div className="flex items-center gap-2 text-sm bg-indigo-950/60 border border-indigo-700 text-indigo-300 rounded-lg px-3 py-2">
<span>Cloned from</span>
<a href={`/invoice/${cloneSourceId}`} className="underline hover:text-indigo-200 font-mono">
#{cloneSourceId}
</a>
</div>
)}
<div className="rounded-lg bg-gray-800 border border-gray-700 divide-y divide-gray-700">
<div className="px-4 py-3 flex justify-between">
<span className="text-sm text-gray-400">Token</span>
<span className="text-sm text-gray-200 font-mono truncate ml-2">{token}</span>
</div>
<div className="px-4 py-3 flex justify-between">
<span className="text-sm text-gray-400">Deadline</span>
<span className="text-sm text-gray-200">
{cloneSourceId
? new Date(cloneDeadlineIso).toLocaleString()
: `${deadlineDays} days`}
</span>
</div>
{recurring && !cloneSourceId && (
<div className="px-4 py-3 flex justify-between">
<span className="text-sm text-gray-400">Recurring</span>
<span className="text-sm text-gray-200">Every {intervalDays} days</span>
</div>
)}
<div className="px-4 py-3 flex justify-between">
<span className="text-sm text-gray-400">Recipients</span>
<span className="text-sm text-gray-200">{recipients.length}</span>
</div>
<div className="px-4 py-3 flex justify-between">
<span className="text-sm text-gray-400">Total</span>
<span className="text-sm text-gray-200 font-semibold">
{equalSplit ? totalAmount : total.toFixed(7)} USDC
</span>
</div>
</div>
<div className="rounded-lg bg-gray-800 border border-gray-700">
<div className="px-4 py-2 text-xs font-medium text-gray-400 border-b border-gray-700">
Recipients
</div>
<ul className="divide-y divide-gray-700">
{recipients.map((r, i) => (
<li key={i} className="px-4 py-2 flex justify-between items-center gap-2">
<span className="text-sm font-mono text-gray-300 truncate">{r.address}</span>
<span className="text-sm text-indigo-300 shrink-0">
{equalSplit ? perRecipientAmount : r.amount} USDC
</span>
</li>
))}
</ul>
</div>
</div>
);
};
return (
<main className="max-w-xl mx-auto w-full px-4 sm:px-6 py-16 overflow-x-hidden">
{/* Collaboration presence */}
{publicKey && <PresencePill presences={remotePresence} currentAddress={publicKey} />}
<ReconnectionBanner
show={!collabConnected && !!publicKey}
isConnected={collabConnected}
/>
<div
aria-live="polite"
className="fixed bottom-4 right-4 z-50 flex flex-col gap-2 pointer-events-none"
>
{toasts.map((t) => (
<div
key={t.id}
role="status"
className={`px-4 py-2 rounded-lg text-sm font-medium shadow-lg pointer-events-auto ${
t.type === "success"
? "bg-green-800 text-green-100"
: "bg-red-800 text-red-100"
}`}
>
{t.message}
</div>
))}
</div>
{txModal && (
<TxConfirmModal
txHash={txModal.txHash}
action="Invoice created"
onClose={() => router.push(`/invoice/${txModal.invoiceId}`)}
/>
)}
<div className="flex items-center gap-3 mb-8 flex-wrap">
<h1 className="text-3xl font-bold">Create Invoice</h1>
{draftOffline && (
<span
role="status"
className="inline-flex items-center gap-1 rounded-full font-semibold text-xs px-2 py-1 bg-yellow-500/20 text-yellow-400"