-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathview-requests.svelte
1226 lines (1117 loc) · 35 KB
/
view-requests.svelte
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
<svelte:options customElement="invoice-dashboard" />
<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<script lang="ts">
import { getAccount, watchAccount } from "@wagmi/core";
// Components
import Copy from "@requestnetwork/shared-components/copy.svelte";
import Dropdown from "@requestnetwork/shared-components/dropdown.svelte";
import Switch from "@requestnetwork/shared-components/switch.svelte";
import Input from "@requestnetwork/shared-components/input.svelte";
import PoweredBy from "@requestnetwork/shared-components/powered-by.svelte";
import StatusLabel from "@requestnetwork/shared-components/status-label.svelte";
import Toaster from "@requestnetwork/shared-components/sonner.svelte";
import Tooltip from "@requestnetwork/shared-components/tooltip.svelte";
import TxType from "@requestnetwork/shared-components/tx-type.svelte";
import DashboardSkeleton from "@requestnetwork/shared-components/dashboard-skeleton.svelte";
import { toast } from "svelte-sonner";
import Modal from "@requestnetwork/shared-components/modal.svelte";
import SearchableDropdownCheckbox from "@requestnetwork/shared-components/searchable-checkbox-dropdown.svelte";
// Icons
import ChevronDown from "@requestnetwork/shared-icons/chevron-down.svelte";
import ChevronLeft from "@requestnetwork/shared-icons/chevron-left.svelte";
import ChevronRight from "@requestnetwork/shared-icons/chevron-right.svelte";
import ChevronUp from "@requestnetwork/shared-icons/chevron-up.svelte";
import Download from "@requestnetwork/shared-icons/download.svelte";
import Search from "@requestnetwork/shared-icons/search.svelte";
import Network from "@requestnetwork/shared-icons/network/network-icon.svelte";
// Types
import type {
GetAccountReturnType,
Config as WagmiConfig,
WatchAccountReturnType,
} from "@wagmi/core";
import { Types } from "@requestnetwork/request-client.js";
import type { IConfig } from "@requestnetwork/shared-types";
import type { RequestNetwork } from "@requestnetwork/request-client.js";
// Utils
import { config as defaultConfig } from "@requestnetwork/shared-utils/config";
import { initializeCurrencyManager } from "@requestnetwork/shared-utils/initCurrencyManager";
import { exportToPDF } from "@requestnetwork/shared-utils/generateInvoice";
import { getCurrencyFromManager } from "@requestnetwork/shared-utils/getCurrency";
import { CurrencyManager } from "@requestnetwork/currency";
import { onDestroy, onMount, tick } from "svelte";
import { formatUnits } from "viem";
import { debounce, formatAddress, getEthersSigner } from "../utils";
import { Drawer, InvoiceView } from "./dashboard";
import { getPaymentNetworkExtension } from "@requestnetwork/payment-detection";
import { CipherProviderTypes, CurrencyTypes } from "@requestnetwork/types";
import { checkStatus } from "@requestnetwork/shared-utils/checkStatus";
import { ethers } from "ethers";
interface CipherProvider extends CipherProviderTypes.ICipherProvider {
getSessionSignatures: (
signer: ethers.Signer,
walletAddress: `0x${string}`,
domain: string,
statement: string
) => Promise<any>;
disconnectWallet: () => void;
}
export let config: IConfig;
export let wagmiConfig: WagmiConfig;
export let requestNetwork: RequestNetwork | null | undefined;
let cipherProvider: CipherProvider | undefined;
let sliderValueForDecryption = JSON.parse(
localStorage?.getItem("isDecryptionEnabled") ?? "false"
)
? "on"
: "off";
let signer: `0x${string}` | undefined;
let activeConfig = config ? config : defaultConfig;
let mainColor = activeConfig.colors.main;
let secondaryColor = activeConfig.colors.secondary;
let account: GetAccountReturnType | undefined =
wagmiConfig && getAccount(wagmiConfig);
let loading = false;
let searchQuery = "";
let debouncedUpdate: any;
let isRequestPayed = false;
let currentTab = "All";
let requests: Types.IRequestDataWithEvents[] | undefined = [];
let activeRequest:
| (Types.IRequestDataWithEvents & {
formattedAmount: string;
currencySymbol: string;
})
| undefined;
let currencyManager: CurrencyManager;
let loadSessionSignatures = false;
let columns = {
issuedAt: false,
dueDate: false,
};
const columnOptions = [
{ value: "dueDate", label: "Due Date" },
{ value: "issuedAt", label: "Issued Date" },
];
let sortOrder = "desc";
let sortColumn = "timestamp";
let selectedNetworks: string[] = [];
let networkOptions: { value: string; checked: boolean }[] = [];
let selectedTxTypes: string[] = [];
let txTypeOptions = [
{ value: "IN", checked: false },
{ value: "OUT", checked: false },
];
let selectedStatuses: string[] = [];
let statusOptions = [
{ value: "paid", checked: false },
{ value: "partially paid", checked: false },
{ value: "accepted", checked: false },
{ value: "awaiting payment", checked: false },
{ value: "canceled", checked: false },
{ value: "rejected", checked: false },
{ value: "overdue", checked: false },
{ value: "pending", checked: false },
];
const handleWalletConnection = async () => {
account = getAccount(wagmiConfig);
await loadRequests(sliderValueForDecryption, account, requestNetwork);
};
const handleWalletDisconnection = () => {
account = undefined;
requests = [];
activeRequest = undefined;
cipherProvider?.disconnectWallet();
cipherProvider = undefined;
};
const handleWalletChange = (
account: GetAccountReturnType,
previousAccount: GetAccountReturnType
) => {
if (account?.address !== previousAccount?.address) {
handleWalletDisconnection();
handleWalletConnection();
} else if (account?.address) {
handleWalletConnection();
} else {
handleWalletDisconnection();
}
};
onMount(() => {
unwatchAccount = watchAccount(wagmiConfig, {
onChange(
account: GetAccountReturnType,
previousAccount: GetAccountReturnType
) {
tick().then(() => {
handleWalletChange(account, previousAccount);
});
},
});
});
let unwatchAccount: WatchAccountReturnType | undefined;
onDestroy(() => {
if (typeof unwatchAccount === "function") unwatchAccount();
});
$: cipherProvider = requestNetwork?.getCipherProvider() as CipherProvider;
$: {
signer = account?.address;
}
$: isRequestPayed, getOneRequest(activeRequest);
onMount(async () => {
currencyManager = await initializeCurrencyManager();
});
const getRequests = async (
account: GetAccountReturnType,
requestNetwork: RequestNetwork | undefined | null
) => {
if (!account?.address || !requestNetwork) return;
loading = true;
try {
const requestsData = await requestNetwork?.fromIdentity({
type: Types.Identity.TYPE.ETHEREUM_ADDRESS,
value: account?.address,
});
requests = requestsData
?.map((request) => request.getData())
.sort((a, b) => b.timestamp - a.timestamp);
const uniqueNetworks = new Set<string>();
requests?.forEach((request) => {
const network = request.currencyInfo.network;
if (network) {
uniqueNetworks.add(network);
}
});
networkOptions = Array.from(uniqueNetworks).map((network) => ({
value: network,
checked: selectedNetworks.includes(network),
}));
} catch (error) {
console.error("Failed to fetch requests:", error);
} finally {
loading = false;
}
};
const getOneRequest = async (activeRequest: any) => {
if (!activeRequest) return;
try {
const _request = await requestNetwork?.fromRequestId(
activeRequest?.requestId!
);
requests = requests?.filter(
(request) => request.requestId !== activeRequest.requestId
);
requests = [...requests, _request?.getData()].sort(
(a, b) => b.timestamp - a.timestamp
);
} catch (error) {
console.error("Failed to fetch request:", error);
}
};
const itemsPerPage = 10;
let currentPage = 1;
let totalPages = 1;
$: {
if (sortColumn && sortOrder) {
requests = [...(requests ?? [])].sort((a, b) => {
let valueA = sortColumn.includes(".")
? getNestedValue(a, sortColumn)
: ((a as any)[sortColumn] as any);
let valueB = sortColumn.includes(".")
? getNestedValue(b, sortColumn)
: ((b as any)[sortColumn] as any);
if (valueA === undefined && valueB === undefined) return 0;
if (valueA === undefined) return sortOrder === "asc" ? 1 : -1;
if (valueB === undefined) return sortOrder === "asc" ? -1 : 1;
if (typeof valueA === "string") valueA = valueA.toLowerCase();
if (typeof valueB === "string") valueB = valueB.toLowerCase();
if (valueA < valueB) return sortOrder === "asc" ? -1 : 1;
if (valueA > valueB) return sortOrder === "asc" ? 1 : -1;
return 0;
});
}
}
$: filteredRequests = requests?.filter((request) => {
const terms = searchQuery.toLowerCase();
const network = request.currencyInfo.network;
const txType = signer === request.payer?.value ? "OUT" : "IN";
const status = checkStatus(request).toLowerCase();
const networkMatch =
selectedNetworks.length === 0 ||
(network && selectedNetworks.includes(network));
const txTypeMatch =
selectedTxTypes.length === 0 || selectedTxTypes.includes(txType);
const statusMatch =
selectedStatuses.length === 0 || selectedStatuses.includes(status);
if (
networkMatch &&
txTypeMatch &&
statusMatch &&
(currentTab === "All" ||
(currentTab === "Get Paid" &&
request.payee?.value?.toLowerCase() === signer?.toLowerCase()) ||
(currentTab === "Pay" &&
request.payer?.value?.toLowerCase() === signer?.toLowerCase()))
) {
const invoiceMatches = request.contentData?.invoiceNumber
?.toString()
.toLowerCase()
.includes(terms);
const payeeMatches = formatAddress(request.payee?.value ?? "")
.toLowerCase()
.includes(terms);
const payerMatches = formatAddress(request.payer?.value ?? "")
.toLowerCase()
.includes(terms);
const amountMatches = request.expectedAmount.toString().includes(terms);
return invoiceMatches || payeeMatches || payerMatches || amountMatches;
}
return false;
});
$: totalPages = Math.ceil(filteredRequests?.length! / itemsPerPage);
$: paginatedRequests = (filteredRequests ?? []).slice(
(currentPage - 1) * itemsPerPage,
currentPage * itemsPerPage
);
$: processedRequests = paginatedRequests?.map(
(
request
): Types.IRequestDataWithEvents & {
formattedAmount: string;
currencySymbol: string;
paymentCurrencies: (
| CurrencyTypes.ERC20Currency
| CurrencyTypes.NativeCurrency
| undefined
)[];
} => {
const currencyInfo = getCurrencyFromManager(
request.currencyInfo,
currencyManager
);
const formattedAmount =
currencyInfo?.decimals !== undefined
? formatUnits(BigInt(request.expectedAmount), currencyInfo.decimals)
: "Unknown";
let paymentNetworkExtension = getPaymentNetworkExtension(request);
let paymentCurrencies: (
| CurrencyTypes.ERC20Currency
| CurrencyTypes.NativeCurrency
| undefined
)[] = [];
if (
paymentNetworkExtension?.id ===
Types.Extension.PAYMENT_NETWORK_ID.ANY_TO_ERC20_PROXY
) {
paymentCurrencies =
paymentNetworkExtension?.values?.acceptedTokens?.map((token: any) =>
currencyManager.fromAddress(
token,
paymentNetworkExtension?.values?.network
)
);
} else if (
paymentNetworkExtension?.id ===
Types.Extension.PAYMENT_NETWORK_ID.ANY_TO_ETH_PROXY
) {
const network = paymentNetworkExtension?.values?.network;
paymentCurrencies = [
currencyManager.getNativeCurrency(
Types.RequestLogic.CURRENCY.ETH,
network
) as CurrencyTypes.NativeCurrency,
];
} else if (
paymentNetworkExtension?.id ===
Types.Extension.PAYMENT_NETWORK_ID.ERC20_FEE_PROXY_CONTRACT ||
paymentNetworkExtension?.id ===
Types.Extension.PAYMENT_NETWORK_ID.ETH_FEE_PROXY_CONTRACT
) {
paymentCurrencies = [
currencyInfo as
| CurrencyTypes.ERC20Currency
| CurrencyTypes.NativeCurrency,
];
} else {
console.error(
"Payment network extension not supported:",
paymentNetworkExtension
);
}
return {
...request,
formattedAmount,
currencySymbol: currencyInfo?.symbol ?? "",
paymentCurrencies,
};
}
);
const goToPage = (page: number) => {
if (page >= 1 && page <= totalPages) {
currentPage = page;
}
};
const changeTab = (tab: string) => {
currentTab = tab;
activeRequest = undefined;
currentPage = 1;
};
const handleColumnChange = (selectedOption: any) => {
columns = {
...columns,
[selectedOption]: !(columns as Record<string, boolean>)[selectedOption],
};
};
onMount(() => {
debouncedUpdate = debounce((value: string) => {
searchQuery = value.toLowerCase();
}, 500);
});
const handleSearchChange = (event: Event) => {
const { value } = event.target as HTMLInputElement;
searchQuery = value;
currentPage = 1;
};
const handleSort = (column: string) => {
sortOrder = column === sortColumn && sortOrder === "asc" ? "desc" : "asc";
sortColumn = column;
};
const getNestedValue = (obj: object, path: string) => {
return path
.split(".")
.reduce((acc, part) => acc && acc[part], obj as Record<string, any>);
};
const handleRequestSelect = (
e: Event,
request: Types.IRequestDataWithEvents & {
formattedAmount: string;
currencySymbol: string;
}
) => {
activeRequest = request;
};
const handleRemoveSelectedRequest = () => {
activeRequest = undefined;
};
const loadRequests = async (
sliderValue: string,
currentAccount: GetAccountReturnType | undefined,
currentRequestNetwork: RequestNetwork | undefined | null
) => {
if (!currentAccount?.address || !currentRequestNetwork || !cipherProvider)
return;
loading = true;
const previousNetworks = [...selectedNetworks]; // Store current selection
try {
if (sliderValue === "on") {
try {
const signer = await getEthersSigner(wagmiConfig);
if (signer && currentAccount?.address) {
loadSessionSignatures =
localStorage?.getItem("lit-wallet-sig") === null;
await cipherProvider?.getSessionSignatures(
signer,
currentAccount.address,
window.location.host,
"Sign in to Lit Protocol through Request Network"
);
cipherProvider?.enableDecryption(true);
localStorage?.setItem("isDecryptionEnabled", JSON.stringify(true));
}
} catch (error) {
console.error("Failed to enable decryption:", error);
toast.error("Failed to enable decryption.");
return;
} finally {
loadSessionSignatures = false;
}
} else {
cipherProvider?.enableDecryption(false);
localStorage?.setItem("isDecryptionEnabled", JSON.stringify(false));
}
await getRequests(currentAccount, currentRequestNetwork);
selectedNetworks = previousNetworks; // Restore selection
} finally {
loading = false;
}
};
$: loadRequests(sliderValueForDecryption, account, requestNetwork);
const handleNetworkSelection = async (networks: string[]) => {
selectedNetworks = networks;
currentPage = 1;
if (networks.length === 0 && selectedNetworks.length > 0) {
loading = true;
try {
await getRequests(account!, requestNetwork!);
} finally {
loading = false;
}
}
};
const handleTxTypeSelection = (types: string[]) => {
selectedTxTypes = types;
currentPage = 1;
};
const handleStatusSelection = (statuses: string[]) => {
selectedStatuses = statuses;
currentPage = 1;
};
</script>
<div
class="main-table"
style="--mainColor: {mainColor}; --secondaryColor: {secondaryColor}; "
>
{#if loadSessionSignatures}
<Modal {config} isOpen={true} title="Lit Protocol Signature Required">
<div class="modal-content">
<p>
This signature is required only once per session and will allow you
to:
</p>
<ul>
<li>Access encrypted invoice details</li>
</ul>
</div>
</Modal>
{/if}
<div class="tabs">
<ul>
<li
on:click={() => changeTab("All")}
class={`${currentTab === "All" && "active"}`}
>
All
</li>
<li
on:click={() => changeTab("Pay")}
class={`${currentTab === "Pay" && "active"}`}
>
Pay
</li>
<li
on:click={() => changeTab("Get Paid")}
class={`${currentTab === "Get Paid" && "active"}`}
>
Get Paid
</li>
</ul>
</div>
<div style="display: flex; flex-direction: column;">
<div class="search-wrapper">
<Input
placeholder="Search..."
width="w-[300px]"
handleInput={handleSearchChange}
>
<div slot="icon">
<Search />
</div>
</Input>
{#if cipherProvider}
<div class="switch-wrapper">
<Switch
bind:value={sliderValueForDecryption}
label="Show encrypted requests"
fontSize={14}
design="slider"
/>
</div>
{/if}
<div class="dropdown-controls">
<SearchableDropdownCheckbox
config={activeConfig}
options={statusOptions}
placeholder="Filter by Status"
onchange={handleStatusSelection}
searchPlaceholder="Search statuses..."
type="status"
/>
<SearchableDropdownCheckbox
config={activeConfig}
options={txTypeOptions}
placeholder="Filter by Type"
onchange={handleTxTypeSelection}
type="transaction"
noSearch={true}
/>
<SearchableDropdownCheckbox
config={activeConfig}
options={networkOptions}
placeholder="Filter by Chain"
onchange={handleNetworkSelection}
searchPlaceholder="Search chains..."
type="network"
/>
<Dropdown
config={activeConfig}
type="checkbox"
options={columnOptions}
placeholder="Select Columns"
onchange={handleColumnChange}
/>
</div>
</div>
<div class="table-wrapper">
<table>
<thead class="table-head">
<tr style="width: 100%;">
{#if columns.issuedAt}
<th on:click={() => handleSort("contentData.creationDate")}>
<div>
Issued Date<i class="caret">
{#if sortOrder === "asc" && sortColumn === "contentData.creationDate"}
<ChevronUp />
{:else}
<ChevronDown />
{/if}
</i>
</div>
</th>
{/if}
{#if columns.dueDate}
<th on:click={() => handleSort("contentData.dueDate")}>
<div>
Due Date<i class="caret">
{#if sortOrder === "asc" && sortColumn === "contentData.dueDate"}
<ChevronUp />
{:else}
<ChevronDown />
{/if}
</i>
</div>
</th>
{/if}
<th on:click={() => handleSort("timestamp")}>
<div>
Created<i class="caret">
{#if sortOrder === "asc" && sortColumn === "timestamp"}
<ChevronUp />
{:else}
<ChevronDown />
{/if}
</i>
</div></th
>
<th on:click={() => handleSort("contentData.invoiceNumber")}>
<div>
Invoice #<i class="caret">
{#if sortOrder === "asc" && sortColumn === "contentData.invoiceNumber"}
<ChevronUp />
{:else}
<ChevronDown />
{/if}
</i>
</div></th
>
{#if currentTab === "All"}
<th on:click={() => handleSort("payee.value")}>
<div>
Payee<i class="caret">
{#if sortOrder === "asc" && sortColumn === "payee.value"}
<ChevronUp />
{:else}
<ChevronDown />
{/if}
</i>
</div>
</th>
<th on:click={() => handleSort("payer.value")}>
<div>
Payer<i class={`caret `}>
{#if sortOrder === "asc" && sortColumn === "payer.value"}
<ChevronUp />
{:else}
<ChevronDown />
{/if}
</i>
</div>
</th>
{:else}
<th
scope="col"
on:click={() =>
handleSort(
currentTab === "Pay" ? "payee.value" : "payer.value"
)}
>{currentTab === "Pay" ? "Payee" : "Payer"}<i class={`caret `}>
{#if ((currentTab === "Pay" && sortColumn === "payee.value") || sortColumn === "payer.value") && sortOrder === "asc"}
<ChevronUp />
{:else}
<ChevronDown />
{/if}</i
></th
>
{/if}
<th on:click={() => handleSort("expectedAmount")}>
<div>
Expected Amount<i class={`caret `}>
{#if sortOrder === "asc" && sortColumn === "expectedAmount"}
<ChevronUp />
{:else}
<ChevronDown />
{/if}
</i>
</div>
</th>
<th
on:click={() => {
const sortBy = processedRequests?.some(
(req) => req.payer?.value === signer
)
? "payer.value"
: "payee.value";
handleSort(sortBy);
}}
>
<div>
Type<i class={`caret `}>
{#if sortOrder === "asc" && (sortColumn === "payer.value" || sortColumn === "payee.value")}
<ChevronUp />
{:else}
<ChevronDown />
{/if}
</i>
</div>
</th>
<th on:click={() => handleSort("state")}>
<div>
Status<i class={`caret `}>
{#if sortOrder === "asc" && sortColumn === "state"}
<ChevronUp />
{:else}
<ChevronDown />
{/if}
</i>
</div>
</th>
<th on:click={() => handleSort("currencyInfo.network")}>
<div>
Payment Chain<i class={`caret `}>
{#if sortOrder === "asc" && sortColumn === "currencyInfo.network"}
<ChevronUp />
{:else}
<ChevronDown />
{/if}
</i>
</div>
</th>
<th></th>
</tr>
</thead>
<tbody>
{#if !loading && processedRequests.length > 0}
{#each processedRequests as request}
<tr class="row" on:click={(e) => handleRequestSelect(e, request)}>
{#if columns.issuedAt}
<td
>{new Date(
request.contentData.creationDate
).toLocaleDateString() || "-"}</td
>
{/if}
{#if columns.dueDate}
<td
>{request?.contentData?.paymentTerms?.dueDate
? new Date(
request?.contentData?.paymentTerms?.dueDate
).toLocaleDateString()
: "-"}</td
>
{/if}
<td>
{new Date(request.timestamp * 1000).toLocaleDateString()}
</td>
<td>{request.contentData.invoiceNumber || "-"}</td>
{#if currentTab === "All"}
<td
><div class="address">
<span>{formatAddress(request.payee?.value ?? "")}</span>
<Copy textToCopy={request.payee?.value} />
</div></td
>
<td
><div class="address">
<span>{formatAddress(request.payer?.value ?? "")}</span>
<Copy textToCopy={request.payer?.value} />
</div></td
>
{:else}
<td>
<div class="address">
<span
>{formatAddress(
currentTab === "Pay"
? (request.payee?.value ?? "")
: (request.payer?.value ?? "")
)}</span
>
<Copy
textToCopy={currentTab === "Pay"
? request.payee?.value
: request.payer?.value || ""}
/>
</div>
</td>
{/if}
<td>
{#if request.formattedAmount === "Unknown"}
<Tooltip
text="Cannot calculate the expected amount due to unknown decimals"
>
Unknown
</Tooltip>
{:else if request.formattedAmount.includes(".") && request.formattedAmount.split(".")[1].length > 5}
<Tooltip text={request.formattedAmount}>
{Number(request.formattedAmount).toFixed(5)}
</Tooltip>
{:else}
{request.formattedAmount}
{/if}
{request.currencySymbol}
</td>
<td>
<TxType
type={signer === request.payer?.value ? "OUT" : "IN"}
showBoth={request.payer?.value === request.payee?.value}
/>
</td>
<td><StatusLabel status={checkStatus(request)} /></td>
<td>
{#if request.paymentCurrencies.length > 0}
<Network
network={request.paymentCurrencies[0]?.network}
showLabel={true}
/>
{:else}
<span class="text-gray-400">-</span>
{/if}
</td>
<td
><Tooltip text="Download PDF">
<Download
onClick={async () => {
try {
await exportToPDF(
request,
getCurrencyFromManager(
request.currencyInfo,
currencyManager
),
request.paymentCurrencies,
config.logo
);
} catch (error) {
toast.error(`Failed to export PDF`, {
description: `${error}`,
action: {
label: "X",
onClick: () => console.info("Close"),
},
});
console.error("Failed to export PDF:", error);
}
}}
/>
</Tooltip></td
>
</tr>
{/each}
{:else if loading}
<DashboardSkeleton />
{/if}
</tbody>
</table>
<Drawer
config={activeConfig}
active={activeRequest !== undefined}
onClose={handleRemoveSelectedRequest}
>
{#if activeRequest !== undefined}
<InvoiceView
{account}
{wagmiConfig}
bind:isRequestPayed
{requestNetwork}
bind:currencyManager
config={activeConfig}
request={activeRequest}
/>
{/if}
</Drawer>
</div>
{#if paginatedRequests.length > 0}
<div class="pagination">
<button
class="chevron-button"
disabled={currentPage === 1}
on:click={() => goToPage(currentPage - 1)}
>
<i>
<ChevronLeft />
</i>
</button>
{#each Array(totalPages).fill(null) as _, i}
<button
class={`active-page page-${currentPage === i + 1 ? "on" : "off"}`}
class:active={currentPage === i + 1}
on:click={() => goToPage(i + 1)}
>
{i + 1}
</button>
{/each}
<button
class="chevron-button"
disabled={currentPage === totalPages}
on:click={() => goToPage(currentPage + 1)}
>
<i>
<ChevronRight />
</i>
</button>
</div>
{/if}
</div>
{#if !loading && paginatedRequests.length === 0}
<div class="no-requests">
<p>No requests found</p>
<span>(Please connect a wallet or create a request)</span>
</div>
{/if}
<PoweredBy />
<Toaster />
</div>
<style>
@font-face {
font-family: "Montserrat";
src: url("./fonts/Montserrat-VariableFont_wght.ttf") format("truetype");
font-weight: normal;
font-style: normal;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Montserrat", sans-serif;
color-scheme: light;
}
.main-table {
display: flex;
flex-direction: column;
gap: 20px;
position: relative;
color: black;
}
.tabs {
width: fit-content;
border-bottom: 1px solid #d1d5db;
}
.tabs ul {
display: flex;
flex-wrap: wrap;
font-weight: 500;
text-align: center;
color: #6b7280;
margin: 0;
padding-left: 0;
}
.tabs ul li {
width: 110px;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 1rem;
border-top-left-radius: 0.5rem;
border-top-right-radius: 0.5rem;