From 6bd3299331265ea2a0c800e3c3199ad4e32ce8de Mon Sep 17 00:00:00 2001
From: Ankit Bahl <ankit2bahl@gmail.com>
Date: Tue, 9 Jan 2024 05:08:17 -0800
Subject: Add activeUser for default payer per group (#16)

* Add activeUser for default payer per group

* Prettier, change labels, use useEffect

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
---
 src/components/expense-form.tsx | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

(limited to 'src/components/expense-form.tsx')

diff --git a/src/components/expense-form.tsx b/src/components/expense-form.tsx
index dff6867..d14d72e 100644
--- a/src/components/expense-form.tsx
+++ b/src/components/expense-form.tsx
@@ -51,6 +51,15 @@ export type Props = {
 export function ExpenseForm({ group, expense, onSubmit, onDelete }: Props) {
   const isCreate = expense === undefined
   const searchParams = useSearchParams()
+  const getSelectedPayer = (field?: { value: string }) => {
+    if (isCreate && typeof window !== 'undefined') {
+      const activeUser = localStorage.getItem(`${group.id}-activeUser`)
+      if (activeUser && activeUser !== 'None') {
+        return activeUser
+      }
+    }
+    return field?.value
+  }
   const form = useForm<ExpenseFormValues>({
     resolver: zodResolver(expenseFormSchema),
     defaultValues: expense
@@ -87,6 +96,7 @@ export function ExpenseForm({ group, expense, onSubmit, onDelete }: Props) {
           expenseDate: new Date(),
           amount: 0,
           paidFor: [],
+          paidBy: getSelectedPayer(),
           isReimbursement: false,
           splitMode: 'EVENLY',
         },
@@ -199,7 +209,7 @@ export function ExpenseForm({ group, expense, onSubmit, onDelete }: Props) {
                   <FormLabel>Paid by</FormLabel>
                   <Select
                     onValueChange={field.onChange}
-                    defaultValue={field.value}
+                    defaultValue={getSelectedPayer(field)}
                   >
                     <SelectTrigger>
                       <SelectValue placeholder="Select a participant" />
-- 
cgit v1.3

