Skip to content

Commit

Permalink
fix(home): filters
Browse files Browse the repository at this point in the history
  • Loading branch information
iammursal committed Mar 12, 2024
1 parent 1a70a94 commit b4237fb
Show file tree
Hide file tree
Showing 9 changed files with 124 additions and 73 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ export const FilterForm = () => {
const amount_range = form.watch('amount_range')
const arDefault = [amount_range?.from || 0, amount_range?.to || 100]

console.log("🚀 ~ FilterForm ~ amount_range:", amount_range)

return (
<Form {...form}>
<form
Expand Down Expand Up @@ -80,7 +78,7 @@ export const FilterForm = () => {
/>
</div>
</div>
<DialogTrigger className="w-full flex gap-4 pt-6">
<div className="w-full flex gap-4 pt-6">
<Button
type="submit"
variant="success"
Expand All @@ -96,7 +94,7 @@ export const FilterForm = () => {
>
Reset
</Button>
</DialogTrigger>
</div>
</form>
</Form>
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { User } from '@/modules/users/types'
import { QueryFilter } from '@/types/queryFilter'
import { zodResolver } from '@hookform/resolvers/zod'
import { format } from 'date-fns'
import { merge } from 'lodash-es'
import { useContext, useMemo } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { FormSchema } from './schema'
import { merge } from 'lodash-es'

export const useFilterForm = () => {
const { filters, setFilters } = useContext(TransactionFilterContext)
Expand Down Expand Up @@ -39,6 +39,9 @@ export const useFilterForm = () => {
},
} as z.infer<typeof FormSchema>

console.log({ defaultValues });


const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues,
Expand All @@ -52,66 +55,55 @@ export const useFilterForm = () => {
const onSubmit = (data: z.infer<typeof FormSchema>) => {
if (data && Object.keys(data).length === 0) return

console.log('onSubmit', data)

let filters = {
where: {
deleted_at: undefined
}
whereNull: ['deleted_at'],
} as QueryFilter
Object.keys(data)?.forEach((key: string) => {
let value = data[key as keyof typeof data]
if (
value === 'undefined' ||
value === '' ||
typeof value === 'undefined'
) {
return
}
if (
key === 'is_settled' &&
['1', '0'].includes(value as string)
) {
filters = {
...filters,

if (typeof value === 'undefined') return

if (key === 'is_settled') {
filters = merge({
where: {
...filters.where,
is_settled: Boolean(Number(value)),
},
}
}, filters)
} else if (key === 'user_id') {
filters = {
...filters,
filters = merge({
where: {
...filters.where,
user_id: value,
},
}
}, filters)
} else if (
key === 'amount_range' &&
typeof value === 'object' &&
typeof value?.from === 'number' &&
typeof value?.to === 'number'
) {
filters = merge({}, filters, {
filters = merge({
whereBetween: {
amount: [value.from, value.to],
}
})
}, filters)
} else if (
key === 'date_range' &&
typeof value === 'object' &&
typeof value?.from === 'object' &&
typeof value?.to === 'object'
) {
filters = {
...filters,
filters = merge({
whereBetween: {
...filters.whereBetween,
transacted_at: [
`${format(value.from, `yyyy-MM-dd'T'`)}00:00`,
`${format(value.to, `yyyy-MM-dd'T'`)}23:59`,
] as [string, string],
},
}
}, filters)
}
})
setFilters(filters)
Expand All @@ -126,7 +118,7 @@ export const useFilterFormState = () => {
let usersOptions = useMemo(
() =>
users?.map((user: User) => {
return { label: user.name, value: `${user.id} ` }
return { label: user.name, value: `${user.id}` }
}),
[users]
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import { z } from 'zod'



export const FormSchema = z.object({
// enum of 0, 1, undefined
is_settled: z
.string()
.refine((val) => ['0', '1', 'undefined'].includes(val)),
user_id: z.coerce.number().optional(),
is_settled: z.string()

.transform((value) => (value === 'undefined' ? undefined : value))
.refine((val) => ['0', '1', undefined].includes(val)),
// is_settled: z
// .string()
// .refine((val) => ['0', '1', 'undefined'].includes(val)),
user_id: z.string()
.transform((value) => (value === '' ? null : value))
.nullable()
.refine((value) => value === null || !isNaN(Number(value)), {
message: 'Invalid number',
})
.transform((value) => (value === null ? undefined : Number(value))).optional(),
date_range: z
.object({
from: z.date().optional(),
Expand All @@ -14,8 +26,20 @@ export const FormSchema = z.object({
.optional(),
amount_range: z
.object({
from: z.coerce.number().optional(),
to: z.coerce.number().optional(),
from: z.number()
.transform((value) => (!value ? null : value))
.nullable()
.refine((value) => value === null || !isNaN(Number(value)), {
message: 'Invalid number',
})
.transform((value) => (value === null ? undefined : Number(value))),
to: z.number()
.transform((value) => (!value ? null : value))
.nullable()
.refine((value) => value === null || !isNaN(Number(value)), {
message: 'Invalid number',
})
.transform((value) => (value === null ? undefined : Number(value))),
})
.optional(),
})
15 changes: 8 additions & 7 deletions app/(common)/components/HeroSection/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,25 @@ import { TransactionFilterContext } from '../../context/TransactionFilterProvide

const basicQuery = {
where: {
is_settled: true,
deleted_at: undefined
// is_settled: false,
},
whereNull: ['deleted_at'],
sumsOf: ['amount'],
}

export const useHeroSectionState = () => {

const { filters } = useContext(TransactionFilterContext)
const creditQuery = useQueryFilter('transactions', merge(basicQuery, filters, { where: { type: 'credit' }, }))
const debitQuery = useQueryFilter('transactions', merge(basicQuery, filters, { where: { type: 'debit' }, }))
console.log('filters', filters)
let f = merge(basicQuery, filters)
const creditFilters = merge({ where: { type: 'credit' } }, f)
const debitFilters = merge({ where: { type: 'debit' } }, f)
const debitQuery = useQueryFilter('transactions', debitFilters)
const creditQuery = useQueryFilter('transactions', creditFilters)

const totalCredit = creditQuery.data?.amount
const totalDebit = debitQuery.data?.amount

const isLoading = creditQuery.isLoading || debitQuery.isLoading
const error = creditQuery.error || debitQuery.error

const totalBalance =
typeof totalCredit === 'number' && typeof totalDebit === 'number'
? totalCredit - totalDebit
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,27 @@
'use client'

import { TransactionList } from '@/modules/transactions/components/list'
import { Transaction } from '@/modules/transactions/types'
import { merge } from 'lodash-es'
import Link from 'next/link'
import { useContext } from 'react'
import { TransactionFilterContext } from '../../context/TransactionFilterProvider'

export function RecentTransactionsSection({ }) {
const { filters } = useContext(TransactionFilterContext)
const { filters, setFilters } = useContext(TransactionFilterContext)
const recentTransactionFilters = merge({
where: {
// is_settled: false,
},
whereNull: ['deleted_at'],
}, filters)
const handleTransactionChange = (transaction: Transaction) => {
console.log('transaction', transaction)
setFilters(merge({
// @ts-ignore
refetch: !Boolean(!filters?.refetch),
}, filters))
}

return (
<section className="py-16 px-4">
Expand All @@ -19,11 +33,7 @@ export function RecentTransactionsSection({ }) {
</div>
{/* list */}
<div className="flex flex-col gap-y-4 divide-y divide-gray-500 ">
<TransactionList filters={merge({}, filters, {
whereNotNull: [
'deleted_at'
]
})} />
<TransactionList filters={recentTransactionFilters} onChange={handleTransactionChange} />
</div>
</section>
)
Expand Down
1 change: 0 additions & 1 deletion components/form/Field/SearchSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ export const SearchSelect: FC<FieldProps> = (props) => {
{
options?.find(
(option) => {
console.log(option.value, field.value)
return option.value == field.value
}
)?.label
Expand Down
12 changes: 12 additions & 0 deletions lib/zod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { z, ZodTypeAny } from 'zod';

export const zodInputStringPipe = (zodPipe: ZodTypeAny) =>
z
.string()
.transform((value) => (value === '' ? null : value))
.nullable()
.refine((value) => value === null || !isNaN(Number(value)), {
message: 'Nombre Invalide',
})
.transform((value) => (value === null ? 0 : Number(value)))
.pipe(zodPipe);
41 changes: 27 additions & 14 deletions modules/transactions/components/list/TransactionList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,29 @@ import { TransactionListItem } from './TransactionListItem'

type TransactionListProps = {
filters?: QueryFilter
onDelete?: (transaction: Transaction) => any
onSettle?: (transaction: Transaction) => any
onUnsettle?: (transaction: Transaction) => any
onChange?: (t: Transaction) => any
}

export const TransactionList: FC<TransactionListProps> = ({
filters,
onDelete,
onSettle,
onUnsettle,
onChange,
}) => {
const [drawerContent, setDrawerContent] = useState('') as any
const [drawerContent, setDrawerContent] = useState(null) as any
const [handleCancel, setHandleCancel] = useState(() => { }) as any
const [handleConfirm, setHandleConfirm] = useState(() => { })
const [handleConfirm, setHandleConfirm] = useState(() => { }) as any
const drawerTrigger = useRef(null)
const router = useRouter()

const { mutate, isLoading, error } = useTransactionUpdate({})
const { data: transactions, ...transactionQuery } = useQueryFilter(
'transactions',
{
...filters,
}
filters,
)

const { data: users, ...userQuery } = useQueryFilter('users', {
Expand All @@ -66,34 +72,41 @@ export const TransactionList: FC<TransactionListProps> = ({
setDrawerContent(description)
setHandleCancel(() => onCancel)
setHandleConfirm(() => onConfirm)
// @ts-ignore
drawerTrigger?.current?.click()
return
}

const actions = ({ id, is_settled }: Transaction) => ({
const actions = (t: Transaction) => ({
handleToggleSettle: () => {
console.log({ id, is_settled });

id && confirm(`Are you sure you want to ${is_settled ? 'unsettle' : 'settle'} this transaction?`, {
t?.id && confirm(`Are you sure you want to ${t?.is_settled ? 'unsettle' : 'settle'} this transaction?`, {
onConfirm: () => {
mutate(id, { is_settled: !is_settled })
t?.id && mutate(t.id, { is_settled: !t?.is_settled })
transactionQuery.refetch()
toast.success('Transaction Settled!')
if (t?.is_settled) {
onSettle && onSettle(t)
} else {
onUnsettle && onUnsettle(t)
}
onChange && onChange(t)
},
})
},

handleDelete: () => {
id && confirm('Are you sure you want to delete this transaction?', {
t?.id && confirm('Are you sure you want to delete this transaction?', {
onConfirm: () => {
mutate(id, { deleted_at: (new Date).toISOString() })
t?.id && mutate(t.id, { deleted_at: (new Date).toISOString() })
transactionQuery.refetch()
toast.success('Transaction Deleted!')
onDelete && onDelete(t)
onChange && onChange(t)
},
})
},
handleEdit: () => {
id && router.push(`/transactions/edit?id=${id}`)
t?.id && router.push(`/transactions/edit?id=${t?.id}`)
}
})

Expand All @@ -102,7 +115,7 @@ export const TransactionList: FC<TransactionListProps> = ({
return (
<>
<Accordion type="single" collapsible>
{transactions &&
{transactions && transactions?.map &&
transactions?.map((t: Transaction) => (
<TransactionListItem
key={`${t.id}`}
Expand Down
Loading

0 comments on commit b4237fb

Please sign in to comment.