-
-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathAddExpensePage.tsx
More file actions
441 lines (410 loc) · 14.9 KB
/
Copy pathAddExpensePage.tsx
File metadata and controls
441 lines (410 loc) · 14.9 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
import { HeartHandshakeIcon, Landmark, RefreshCcwDot, X } from 'lucide-react';
import { useTranslation } from 'next-i18next';
import Link from 'next/link';
import { useRouter } from 'next/router';
import React, { useCallback } from 'react';
import { type CurrencyCode } from '~/lib/currency';
import { useAddExpenseStore } from '~/store/addStore';
import { api } from '~/utils/api';
import { toast } from 'sonner';
import { useTranslationWithUtils } from '~/hooks/useTranslationWithUtils';
import { cronToBackend } from '~/lib/cron';
import { cn } from '~/lib/utils';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import AddBankTransactions from './AddBankTransactions';
import { CategoryPicker } from './CategoryPicker';
import { CurrencyPicker } from './CurrencyPicker';
import { DateSelector } from './DateSelector';
import { RecurrenceInput } from './RecurrenceInput';
import { SelectUserOrGroup } from './SelectUserOrGroup';
import { PayerSelectionForm, SplitExpenseForm } from './SplitTypeSection';
import { UploadFile } from './UploadFile';
import { UserInput } from './UserInput';
import { CurrencyInput } from '../ui/currency-input';
import { CurrencyConversion } from '../Friend/CurrencyConversion';
import { currencyConversion } from '~/utils/numbers';
import { CurrencyConversionIcon } from '../ui/categoryIcons';
import { useSession } from 'next-auth/react';
export const AddOrEditExpensePage: React.FC<{
enableSendingInvites: boolean;
expenseId?: string;
bankConnectionEnabled: boolean;
}> = ({ enableSendingInvites, expenseId, bankConnectionEnabled }) => {
const showFriends = useAddExpenseStore((s) => s.showFriends);
const amount = useAddExpenseStore((s) => s.amount);
const isNegative = useAddExpenseStore((s) => s.isNegative);
const participants = useAddExpenseStore((s) => s.participants);
const group = useAddExpenseStore((s) => s.group);
const currency = useAddExpenseStore((s) => s.currency);
const category = useAddExpenseStore((s) => s.category);
const description = useAddExpenseStore((s) => s.description);
const isFileUploading = useAddExpenseStore((s) => s.isFileUploading);
const amtStr = useAddExpenseStore((s) => s.amountStr);
const expenseDate = useAddExpenseStore((s) => s.expenseDate);
const isExpenseSettled = useAddExpenseStore((s) => s.canSplitScreenClosed);
const paidBy = useAddExpenseStore((s) => s.paidBy);
const splitType = useAddExpenseStore((s) => s.splitType);
const fileKey = useAddExpenseStore((s) => s.fileKey);
const currentUser = useAddExpenseStore((s) => s.currentUser);
const splitShares = useAddExpenseStore((s) => s.splitShares);
const transactionId = useAddExpenseStore((s) => s.transactionId);
const cronExpression = useAddExpenseStore((s) => s.cronExpression);
const multipleTransactions = useAddExpenseStore((s) => s.multipleTransactions);
const { t, displayName, generateSplitDescription, getCurrencyHelpersCached } =
useTranslationWithUtils();
const {
setCurrency,
setCategory,
setDescription,
setAmount,
setAmountStr,
resetState,
setExpenseDate,
setMultipleTransactions,
setIsTransactionLoading,
setSingleTransaction,
} = useAddExpenseStore((s) => s.actions);
const addExpenseMutation = api.expense.addOrEditExpense.useMutation();
const updateProfile = api.user.updateUserDetail.useMutation();
const { update } = useSession();
const onCurrencyPick = useCallback(
(newCurrency: CurrencyCode | null) => {
if (!newCurrency) {
return;
}
updateProfile.mutate({ currency: newCurrency });
previousCurrencyRef.current = currency;
setCurrency(newCurrency);
},
[currency, setCurrency, updateProfile],
);
const router = useRouter();
const onUpdateAmount = useCallback(
({ strValue, bigIntValue }: { strValue?: string; bigIntValue?: bigint }) => {
if (strValue !== undefined) {
setAmountStr(strValue);
}
if (bigIntValue !== undefined) {
setAmount(bigIntValue);
}
previousCurrencyRef.current = null;
},
[setAmount, setAmountStr],
);
const addExpense = useCallback(async () => {
if (!paidBy) {
return;
}
setMultipleTransactions([]);
setIsTransactionLoading(false);
const sign = isNegative ? -1n : 1n;
try {
await addExpenseMutation.mutateAsync(
[
{
name: description,
currency,
amount: amount * sign,
groupId: group?.id ?? null,
splitType,
participants: participants.map((p) => ({
userId: p.id,
amount: (p.amount ?? 0n) * sign,
})),
paidBy: paidBy.id,
category,
fileKey,
expenseDate,
expenseId,
transactionId,
cronExpression: cronExpression ? cronToBackend(cronExpression) : undefined,
},
],
{
onSuccess: (d) => {
if (d) {
if (multipleTransactions.length > 0) {
const allTransactions = [...multipleTransactions];
const transactionToAdd = allTransactions.pop();
if (transactionToAdd) {
setMultipleTransactions(allTransactions);
setSingleTransaction(transactionToAdd);
}
return;
} else {
const id = d.length > 0 ? d[0]?.id : expenseId;
let navPromise: () => Promise<any> = () => Promise.resolve(true);
const { friendId, groupId } = router.query;
if (friendId && !groupId) {
navPromise = () => router.push(`/balances/${friendId as string}/expenses/${id}`);
} else if (groupId) {
navPromise = () => router.push(`/groups/${groupId as string}/expenses/${id}`);
} else {
navPromise = () => router.push(`/expenses/${id}?keepAdding=1`);
}
if (expenseId) {
navPromise = async () => router.back();
}
update((session: any) => ({
...session,
user: {
...(session?.user ?? {}),
currency,
},
}))
.then(() => navPromise())
.then(() => resetState())
.catch(console.error);
}
}
},
},
);
} catch (error) {
console.error(error);
if (error instanceof Error) {
toast.error(error.message);
} else {
toast.error('An unexpected error occurred while submitting the expense.');
}
}
}, [
description,
currency,
isNegative,
amount,
participants,
category,
expenseDate,
expenseId,
router,
resetState,
addExpenseMutation,
group,
paidBy,
splitType,
fileKey,
setMultipleTransactions,
transactionId,
setIsTransactionLoading,
cronExpression,
multipleTransactions,
setSingleTransaction,
update,
]);
const handleDescriptionChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
setDescription(e.target.value.toString() ?? '');
},
[setDescription],
);
const clearTransaction = useCallback(() => {
resetState();
setMultipleTransactions([]);
}, [resetState, setMultipleTransactions]);
const previousCurrencyRef = React.useRef<CurrencyCode | null>(null);
const onConvertAmount: React.ComponentProps<typeof CurrencyConversion>['onSubmit'] = useCallback(
({ amount: absAmount, rate }) => {
if (!previousCurrencyRef.current) {
return;
}
const targetAmount =
(absAmount >= 0n ? 1n : -1n) *
currencyConversion({
amount: absAmount,
rate,
from: previousCurrencyRef.current,
to: currency,
});
setAmount(targetAmount);
setAmountStr(getCurrencyHelpersCached(currency).toUIString(targetAmount, false, true));
previousCurrencyRef.current = null;
},
[setAmount, setAmountStr, currency, getCurrencyHelpersCached],
);
const currencyConversionComponent = React.useMemo(() => {
if (
currency === previousCurrencyRef.current ||
previousCurrencyRef.current === null ||
!amount ||
0n === amount
) {
return null;
}
return (
<CurrencyConversion
onSubmit={onConvertAmount}
amount={amount}
currency={previousCurrencyRef.current}
editingTargetCurrency={currency}
>
<Button size="icon" variant="secondary" className="size-8">
<CurrencyConversionIcon className="size-4" />
</Button>
</CurrencyConversion>
);
}, [amount, currency, onConvertAmount]);
const onBackButtonPress = useCallback(() => {
router.back();
}, [router]);
return (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<Button variant="ghost" className="text-primary px-0" onClick={onBackButtonPress}>
{t('actions.cancel')}
</Button>
<div className="text-center">
{expenseId ? t('actions.edit_expense') : t('actions.add_expense')}
</div>
<Button
variant="ghost"
className="text-primary px-0"
disabled={
addExpenseMutation.isPending || !amount || '' === description || isFileUploading
}
onClick={addExpense}
>
{t('actions.save')}
</Button>{' '}
</div>
<UserInput isEditing={Boolean(expenseId)} />
{showFriends || (1 === participants.length && !group) ? (
<SelectUserOrGroup enableSendingInvites={enableSendingInvites} />
) : (
<>
<div className="mt-4 flex gap-2 sm:mt-10">
<CategoryPicker category={category} onCategoryPick={setCategory} />
<Input
placeholder={t('expense_details.add_expense_details.description_placeholder')}
value={description}
onChange={handleDescriptionChange}
className="text-lg placeholder:text-sm"
autoFocus
/>
</div>
<div className="flex gap-2">
<CurrencyPicker currentCurrency={currency} onCurrencyPick={onCurrencyPick} />
<CurrencyInput
placeholder={t('expense_details.add_expense_details.amount_placeholder')}
currency={currency}
strValue={amtStr}
allowNegative
hideSymbol
onValueChange={onUpdateAmount}
rightIcon={currencyConversionComponent}
/>
</div>
<div className="h-[180px]">
{amount && '' !== description ? (
<>
<div className="flex flex-col items-center justify-center text-sm text-gray-400 sm:mt-4 sm:flex-row">
<p>{t(`ui.expense.${isNegative ? 'received_by' : 'paid_by'}`)}</p>
<PayerSelectionForm>
<Button variant="ghost" className="text-primary h-8 px-1.5 py-0 text-base">
{displayName(paidBy, currentUser?.id, 'dativus')}
</Button>
</PayerSelectionForm>
<p>{t('ui.and')} </p>
<SplitExpenseForm>
<Button variant="ghost" className="text-primary h-8 px-1.5 py-0 text-base">
{generateSplitDescription(
splitType,
participants,
splitShares,
paidBy,
currentUser,
isNegative,
)}
</Button>
</SplitExpenseForm>
</div>
<div className="mt-4 flex items-start justify-between sm:mt-10">
<DateSelector
mode="single"
required
selected={expenseDate}
onSelect={setExpenseDate}
/>
<div className="flex items-center gap-4">
<UploadFile />
<Button
className="min-w-[100px]"
size="sm"
loading={addExpenseMutation.isPending || isFileUploading}
disabled={
addExpenseMutation.isPending ||
!amount ||
'' === description ||
isFileUploading ||
!isExpenseSettled
}
onClick={addExpense}
>
{t('actions.save')}
</Button>
</div>
</div>
</>
) : null}
</div>
<div className="flex items-center justify-evenly px-4 lg:px-0">
{!expenseId && (
<RecurrenceInput>
<Button variant="ghost" size="sm">
<RefreshCcwDot
className={cn(
cronExpression && 'text-primary',
(!amtStr || !description) && 'invisible',
'size-6',
)}
/>
<span className="sr-only">Toggle recurring expense options</span>
</Button>
</RecurrenceInput>
)}
<SponsorUs />
<div className="flex gap-2">
<AddBankTransactions bankConnectionEnabled={bankConnectionEnabled}>
<Button
variant="ghost"
className="hover:text-foreground/80 items-center justify-between px-2"
>
<Landmark
className={cn(transactionId ? 'text-primary' : 'text-white-500', 'h-6 w-6')}
/>
</Button>
</AddBankTransactions>
<Button
variant="ghost"
className={cn('px-2', transactionId ? 'text-red-500' : 'invisible')}
disabled={!transactionId}
onClick={clearTransaction}
>
<X className="h-6 w-6" />
</Button>
</div>
</div>
</>
)}
</div>
);
};
const SponsorUs = () => {
const { t } = useTranslation();
return (
<div className="flex justify-center">
<Link href="https://github.com/sponsors/krokosik" target="_blank" className="mx-auto">
<Button
variant="outline"
className="text-md hover:text-foreground/80 justify-between rounded-full border-pink-500"
>
<div className="flex items-center gap-4">
<HeartHandshakeIcon className="h-5 w-5 text-pink-500" />
{t('expense_details.add_expense_details.sponsor_us')}
</div>
</Button>
</Link>
</div>
);
};