-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcreate-invoice-form.svelte
481 lines (429 loc) · 13.9 KB
/
create-invoice-form.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
<svelte:options customElement="create-invoice-form" />
<script lang="ts">
import {
getAccount,
watchAccount,
WatchAccountReturnType,
} from "@wagmi/core";
import { Config as WagmiConfig } from "wagmi";
// Types
import { type GetAccountReturnType } from "@wagmi/core";
import type { IConfig } from "@requestnetwork/shared-types";
import { APP_STATUS } from "@requestnetwork/shared-types/enums";
import type { RequestNetwork } from "@requestnetwork/request-client.js";
import { Types } from "@requestnetwork/request-client.js";
import { CurrencyTypes } from "@requestnetwork/types";
// Utils
import { getInitialFormData, prepareRequestParams } from "./utils";
import { config as defaultConfig } from "@requestnetwork/shared-utils/config";
import { calculateInvoiceTotals } from "@requestnetwork/shared-utils/invoiceTotals";
import {
getCurrencySupportedNetworksForConversion,
initializeCreateInvoiceCurrencyManager,
initializeCurrencyManager,
} from "@requestnetwork/shared-utils/initCurrencyManager";
// Components
import { InvoiceForm, InvoiceView } from "./invoice";
import Button from "@requestnetwork/shared-components/button.svelte";
import Status from "@requestnetwork/shared-components/status.svelte";
import Modal from "@requestnetwork/shared-components/modal.svelte";
import { EncryptionTypes, CipherProviderTypes } from "@requestnetwork/types";
import { onDestroy, onMount, tick } from "svelte";
import { CurrencyManager } from "@requestnetwork/currency";
interface CipherProvider extends CipherProviderTypes.ICipherProvider {
disconnectWallet: () => void;
}
export let config: IConfig;
export let wagmiConfig: WagmiConfig;
export let requestNetwork: RequestNetwork | null | undefined;
export let currencies: string[] = [];
let cipherProvider: CipherProvider | undefined;
let account: GetAccountReturnType | undefined =
wagmiConfig && getAccount(wagmiConfig);
let isTimeout = false;
let activeConfig = config ? config : defaultConfig;
let mainColor = activeConfig.colors.main;
let secondaryColor = activeConfig.colors.secondary;
let currencyManager: CurrencyManager;
let invoiceCurrencyDropdown: { clear: () => void };
let networkDropdown: { clear: () => void };
let currencyDropdown: { clear: () => void };
let filteredSettlementCurrencies: CurrencyTypes.CurrencyDefinition[] = [];
let networks: string[] = [];
let network: string | undefined = undefined;
let currency: CurrencyTypes.CurrencyDefinition | undefined = undefined;
let invoiceCurrency: CurrencyTypes.CurrencyDefinition | undefined = undefined;
let defaultCurrencies: any[] = [];
onMount(async () => {
currencyManager = await initializeCreateInvoiceCurrencyManager(currencies);
defaultCurrencies = Object.values(
currencyManager.knownCurrencies.reduce(
(
unique: { [x: string]: any },
currency: { symbol: string | number }
) => {
const baseSymbol = String(currency.symbol).split("-")[0];
if (!unique[baseSymbol]) {
unique[baseSymbol] = {
...currency,
symbol: baseSymbol,
};
}
return unique;
},
{}
)
);
unwatchAccount = watchAccount(wagmiConfig, {
onChange(
account: GetAccountReturnType,
previousAccount: GetAccountReturnType
) {
tick().then(() => {
handleWalletChange(account, previousAccount);
});
},
});
});
const handleNetworkChange = (newNetwork: string) => {
if (newNetwork) {
currencyDropdown.clear();
invoiceCurrency =
invoiceCurrency?.type !== Types.RequestLogic.CURRENCY.ISO4217
? currencyManager.knownCurrencies.find(
(currency) =>
currency.symbol.split("-")[0] ===
invoiceCurrency?.symbol.split("-")[0] &&
currency.network === newNetwork
)
: invoiceCurrency;
network = newNetwork;
currency = undefined;
filteredSettlementCurrencies = currencyManager.knownCurrencies.filter(
(currency: CurrencyTypes.CurrencyDefinition) => {
if (!invoiceCurrency) {
return false;
}
// For ISO4217 currencies (like EUR)
if (invoiceCurrency.type === Types.RequestLogic.CURRENCY.ISO4217) {
const hasValidPath =
currencyManager?.getConversionPath(
invoiceCurrency,
currency,
currency?.network
)?.length > 0;
return (
currency.type !== Types.RequestLogic.CURRENCY.ISO4217 &&
hasValidPath &&
currency.network === newNetwork
);
}
// For other currency types (like ERC20)
// Compare base symbols (without network suffix)
const invoiceBaseSymbol = invoiceCurrency.symbol.split("-")[0];
const currencyBaseSymbol = currency.symbol.split("-")[0];
return (
invoiceBaseSymbol === currencyBaseSymbol &&
currency.network === newNetwork
);
}
);
}
};
let activeRequest: any = null;
let canSubmit = false;
let appStatus: APP_STATUS[] = [];
let formData = getInitialFormData();
const handleInvoiceCurrencyChange = (
value: CurrencyTypes.CurrencyDefinition
) => {
if (value !== invoiceCurrency) {
networkDropdown.clear();
currencyDropdown.clear();
invoiceCurrency = value;
currency = undefined;
filteredSettlementCurrencies = [];
network = undefined;
networks = [];
if (invoiceCurrency.type === Types.RequestLogic.CURRENCY.ISO4217) {
networks = (getCurrencySupportedNetworksForConversion(
invoiceCurrency.hash,
currencyManager
) ?? []) as string[];
} else {
const baseSymbol = invoiceCurrency.symbol.split("-")[0];
networks = currencyManager.knownCurrencies
.filter((currency) => {
const currencyBaseSymbol = currency.symbol.split("-")[0];
return currencyBaseSymbol === baseSymbol;
})
.map((currency) => currency.network);
}
}
};
const handleCurrencyChange = (value: CurrencyTypes.CurrencyDefinition) => {
currency = value;
};
let invoiceTotals = {
amountWithoutTax: 0,
totalTaxAmount: 0,
totalAmount: 0,
};
$: cipherProvider = requestNetwork?.getCipherProvider() as CipherProvider;
const handleWalletConnection = async () => {
account = getAccount(wagmiConfig);
};
const handleWalletDisconnection = () => {
cipherProvider?.disconnectWallet();
};
const handleWalletChange = (
account: GetAccountReturnType,
previousAccount: GetAccountReturnType
) => {
if (account?.address !== previousAccount?.address) {
handleWalletDisconnection();
handleWalletConnection();
} else if (account?.address) {
handleWalletConnection();
} else {
handleWalletDisconnection();
}
};
let unwatchAccount: WatchAccountReturnType | undefined;
onDestroy(() => {
if (typeof unwatchAccount === "function") unwatchAccount();
});
$: {
formData.creatorId = (account?.address ?? "") as string;
invoiceTotals = calculateInvoiceTotals(formData.invoiceItems);
}
const isValidItem = (item: any) =>
item.name && item.quantity > 0 && Number(item.unitPrice) > 0;
$: {
const basicDetailsFilled =
formData.payeeAddress &&
formData.payerAddress &&
formData.dueDate &&
formData.invoiceNumber &&
formData.issuedOn &&
invoiceCurrency &&
currency &&
formData.issuedOn;
const hasItems =
formData.invoiceItems.length > 0 &&
formData.invoiceItems.every(isValidItem);
canSubmit = basicDetailsFilled && hasItems && requestNetwork ? true : false;
}
const addToStatus = (newStatus: APP_STATUS) => {
appStatus = [...appStatus, newStatus];
};
const removeAllStatuses = () => {
appStatus = [];
};
const handleGoToDashboard = (dashboardLink: string) => {
removeAllStatuses();
window.location.href = dashboardLink;
};
const hanldeCreateNewInvoice = () => {
removeAllStatuses();
formData = getInitialFormData();
};
const handleCloseInvoiceModal = () => {
removeAllStatuses();
};
const submitForm = async (e: Event) => {
e.preventDefault();
formData.miscellaneous.builderId = activeConfig?.builderId || "";
formData.miscellaneous.createdWith = window.location.hostname;
const requestCreateParameters = prepareRequestParams({
address: account?.address,
formData,
invoiceCurrency,
currency,
invoiceTotals,
});
if (requestNetwork) {
try {
addToStatus(APP_STATUS.PERSISTING_TO_IPFS);
let request;
if (cipherProvider && formData.isEncrypted) {
const payeeEncryptionParams = {
key: requestCreateParameters.requestInfo.payee?.value!,
method: EncryptionTypes.METHOD.KMS,
};
const payerEncryptionParams = {
key: requestCreateParameters.requestInfo.payer?.value!,
method: EncryptionTypes.METHOD.KMS,
};
request = await requestNetwork._createEncryptedRequest(
{
requestInfo: requestCreateParameters.requestInfo,
signer: requestCreateParameters.signer,
paymentNetwork: requestCreateParameters.paymentNetwork,
contentData: requestCreateParameters.contentData,
},
[payeeEncryptionParams, payerEncryptionParams]
);
} else {
request = await requestNetwork.createRequest({
requestInfo: requestCreateParameters.requestInfo,
paymentNetwork: requestCreateParameters.paymentNetwork,
contentData: requestCreateParameters.contentData,
signer: requestCreateParameters.signer,
});
}
activeRequest = request;
addToStatus(APP_STATUS.PERSISTING_ON_CHAIN);
await request.waitForConfirmation();
addToStatus(APP_STATUS.REQUEST_CONFIRMED);
} catch (error: any) {
if (error.message.includes("Transaction confirmation not received")) {
isTimeout = true;
removeAllStatuses();
} else {
addToStatus(APP_STATUS.ERROR_OCCURRED);
console.error("Failed to create request:", error);
}
}
}
};
</script>
<div
class="create-invoice-form-wrapper"
style="--mainColor: {mainColor}; --secondaryColor: {secondaryColor}"
>
<div class="create-invoice-form-content">
<InvoiceForm
bind:formData
config={activeConfig}
bind:defaultCurrencies
bind:filteredSettlementCurrencies
{handleInvoiceCurrencyChange}
{handleCurrencyChange}
{handleNetworkChange}
bind:networks
{cipherProvider}
bind:invoiceCurrencyDropdown
bind:networkDropdown
bind:currencyDropdown
/>
<div class="invoice-view-wrapper">
<InvoiceView
config={activeConfig}
{invoiceCurrency}
{currency}
bind:formData
bind:canSubmit
{invoiceTotals}
{submitForm}
bind:defaultCurrencies
/>
</div>
</div>
<Modal
config={activeConfig}
title="Creating the invoice"
isOpen={appStatus?.length > 0}
onClose={handleCloseInvoiceModal}
>
<Status config={activeConfig} statuses={appStatus} />
<div class="modal-footer">
<Button
type="button"
onClick={() => handleGoToDashboard(activeConfig.dashboardLink)}
text="Go to dashboard"
disabled={!appStatus.includes(APP_STATUS.REQUEST_CONFIRMED)}
/>
<Button
type="button"
onClick={hanldeCreateNewInvoice}
text="Create a new invoice"
disabled={!appStatus.includes(APP_STATUS.REQUEST_CONFIRMED)}
/>
</div>
</Modal>
<Modal
config={activeConfig}
title="Invoice Creation Taking Longer Than Expected"
isOpen={isTimeout}
onClose={() => (isTimeout = false)}
>
<p>
Creating the invoice is taking longer than expected. You can refresh and
keep waiting or return to the dashboard. Your invoice will be created
eventually.
</p>
<div class="modal-footer">
<Button
type="button"
onClick={async () => {
isTimeout = false;
addToStatus(APP_STATUS.PERSISTING_TO_IPFS);
addToStatus(APP_STATUS.PERSISTING_ON_CHAIN);
await activeRequest.waitForConfirmation();
addToStatus(APP_STATUS.REQUEST_CONFIRMED);
}}
text="Refresh and Keep Waiting"
/>
<Button
type="button"
onClick={() => handleGoToDashboard(activeConfig.dashboardLink)}
text="Return to Dashboard"
/>
</div>
</Modal>
</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;
}
.create-invoice-form-wrapper {
display: flex;
flex-direction: column;
gap: 20px;
box-sizing: border-box;
color: black;
}
.create-invoice-form-content {
display: flex;
gap: 20px;
width: 100%;
}
@media only screen and (max-width: 1024px) {
.create-invoice-form-content {
flex-direction: column;
}
}
.invoice-view-wrapper {
height: fit-content;
display: flex;
flex-direction: column;
gap: 12px;
width: 100%;
}
.modal-footer {
display: flex;
justify-content: space-between;
margin-top: 20px;
}
@media only screen and (max-width: 880px) {
.modal-footer {
gap: 10px;
}
}
:global(.modal-footer button) {
padding: 6px 14px !important;
width: fit-content !important;
height: fit-content !important;
}
</style>