Skip to content

Commit

Permalink
fix: submit credit update and credit details pages
Browse files Browse the repository at this point in the history
  • Loading branch information
alnavarrop99 committed Apr 6, 2024
1 parent dba6dca commit 9b772a5
Show file tree
Hide file tree
Showing 5 changed files with 115 additions and 97 deletions.
6 changes: 0 additions & 6 deletions src/pages/_layout/credit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import { format, isValid } from 'date-fns'
import styles from "@/styles/global.module.css";
import { getFrecuencyById } from '@/lib/type/frecuency'
import { getClientById } from '@/api/clients'
import { create } from 'zustand'

export const Route = createFileRoute('/_layout/credit')({
component: Credits,
Expand Down Expand Up @@ -57,9 +56,6 @@ interface TCreditsProps {
}

export const _creditSelected = createContext<TCREDIT_GET_FILTER | undefined>(undefined)
export const useCreditFilter = create<{ creditFilter?: TCREDIT_GET_FILTER, setCreditFilter: ( creditFilter: TCREDIT_GET_FILTER ) => void }>()( (set) => ({
setCreditFilter: ( creditFilter ) => set( () => ({creditFilter}) )
}) )

/* eslint-disable-next-line */
export function Credits({
Expand All @@ -71,7 +67,6 @@ export function Credits({
const [selectedCredit, setSelectedCredit] = useState<TCREDIT_GET_FILTER | undefined>(undefined)
const { open = _open, setOpen } = useStatus()
const navigate = useNavigate()
const { setCreditFilter } = useCreditFilter()

const onClick: (index: number) => React.MouseEventHandler<React.ComponentRef<typeof Button>> = (index) => () => {
if(!creditsDB || !creditsDB?.[index]) return;
Expand All @@ -81,7 +76,6 @@ export function Credits({

const onLink: (index: number) => React.MouseEventHandler<React.ComponentRef<typeof Link>> = (index) => () => {
if(!creditsDB || !creditsDB?.[index]) return;
setCreditFilter(creditsDB?.[index])
}

const onOpenChange = (open: boolean) => {
Expand Down
17 changes: 9 additions & 8 deletions src/pages/_layout/credit/pay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { _creditSelected } from "@/pages/_layout/credit";
import { useNotifications } from '@/lib/context/notification'
import { useStatus } from '@/lib/context/layout'
import { useMutation } from '@tanstack/react-query'
import { formatISO } from 'date-fns'

export const Route = createFileRoute('/_layout/credit/pay')({
component: PaySelectedCredit,
Expand All @@ -30,7 +31,7 @@ interface TPaySelectedCreditProps {
}

/* eslint-disable-next-line */
type TFormName = keyof TPAYMENT_POST_BODY
type TFormName = keyof Omit<TPAYMENT_POST_BODY, "credito_id">

/* eslint-disable-next-line */
export function PaySelectedCredit( { credit: _credit = {} as TCREDIT_GET }: TPaySelectedCreditProps ) {
Expand All @@ -52,8 +53,10 @@ export function PaySelectedCredit( { credit: _credit = {} as TCREDIT_GET }: TPay
if (!form.current) return

const items = Object.fromEntries(
new FormData(form.current).entries()
) as Record<TFormName, string>
[...new FormData(form.current).entries()]?.map( ([ key, value ]) => {
if( value === "" ) return [ key, undefined ]
return [ key, value ]
})) as Record<TFormName, string>

const description = text.notification.decription({
username: credit.nombre_del_cliente,
Expand All @@ -63,13 +66,11 @@ export function PaySelectedCredit( { credit: _credit = {} as TCREDIT_GET }: TPay
const action =
({ ...items }: Record<TFormName, string>) =>
() => {
console.table(items)
console.table(credit)
createPayment({
valor_del_pago: +items?.valor_del_pago,
comentario: items?.comentario,
comentario: items?.comentario ?? "",
credito_id: credit?.id,
fecha_de_pago: items?.fecha_de_pago
fecha_de_pago: formatISO(items?.fecha_de_pago ?? new Date())
})
pushNotification({
date: new Date(),
Expand Down Expand Up @@ -126,10 +127,10 @@ export function PaySelectedCredit( { credit: _credit = {} as TCREDIT_GET }: TPay
<Input
required
min={0}
step={50}
name={'valor_del_pago' as TFormName}
type="number"
placeholder={text.form.amount.placeholder}
defaultValue={ credit?.valor_de_cuota }
/>
</Label>
<Label className='!col-span-1'>
Expand Down
74 changes: 39 additions & 35 deletions src/pages/_layout/credit_/$creditId.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
createFileRoute,
useNavigate,
} from '@tanstack/react-router'
import { type TCREDIT_GET, getCreditById, TCREDIT_GET_FILTER } from '@/api/credit'
import { type TCREDIT_GET, getCreditById } from '@/api/credit'
import { Separator } from '@/components/ui/separator'
import { Switch } from '@/components/ui/switch'
import {
Expand All @@ -27,11 +27,19 @@ import { useStatus } from '@/lib/context/layout'
import { getFrecuencyById } from '@/lib/type/frecuency'
import { createContext } from 'react'
import { TMORA_TYPE, getMoraTypeById } from '@/lib/type/moraType'
import { _creditSelected, useCreditFilter } from '@/pages/_layout/credit'
import { _creditSelected } from '@/pages/_layout/credit'
import { getClientById } from '@/api/clients'

export const Route = createFileRoute('/_layout/credit/$creditId')({
component: CreditById,
loader: getCreditById,
loader: async ({ params }) => {
const credit = await getCreditById({ params })
const client = await getClientById({ params: { clientId: ""+credit?.owner_id } })
return ({
credit,
client
})
},
})

/* eslint-disable-next-line */
Expand All @@ -48,10 +56,9 @@ export function CreditById({
open: _open,
credit: _credit = {} as TCREDIT_GET,
}: React.PropsWithChildren<TCreditByIdProps>) {
const creditDB = Route.useLoaderData() ?? _credit
const { credit, client } = Route.useLoaderData() ?? _credit
const { open = _open, setOpen } = useStatus()
const navigate = useNavigate()
const { creditFilter } = useCreditFilter()

const onOpenChange = (open: boolean) => {
if (!open) {
Expand All @@ -60,16 +67,16 @@ export function CreditById({
setOpen({ open })
}

const mora = creditDB?.cuotas?.at(-1)?.valor_de_mora
const moraType = getMoraTypeById({ moraTypeId: creditDB?.tipo_de_mora_id })?.nombre
const mora = credit?.cuotas?.at(-1)?.valor_de_mora
const moraType = getMoraTypeById({ moraTypeId: credit?.tipo_de_mora_id })?.nombre
const moraStatus = !!mora && mora > 0

const cuoteValue = creditDB?.cuotas?.at(-1)?.valor_de_cuota
const interestValue = (creditDB?.tasa_de_interes/100) * (cuoteValue ?? 1)
const moreValue = moraType === "Porciento" ? ((creditDB?.valor_de_mora + creditDB?.tasa_de_interes)/100 * (cuoteValue ?? 1)) : creditDB?.valor_de_mora
const cuoteValue = credit?.cuotas?.at(-1)?.valor_de_cuota
const interestValue = (credit?.tasa_de_interes/100) * (cuoteValue ?? 1)
const moreValue = moraType === "Porciento" ? ((credit?.valor_de_mora + credit?.tasa_de_interes)/100 * (cuoteValue ?? 1)) : credit?.valor_de_mora

return (
<_selectedCredit.Provider value={[ creditDB ]}>
<_selectedCredit.Provider value={[ credit ]}>
{!children && <Navigate to={Route.to} />}
<div className="space-y-4">
<div className="flex gap-2">
Expand Down Expand Up @@ -98,7 +105,6 @@ export function CreditById({
<DialogTrigger asChild>
<Link to={'./delete'}>
<Button variant="default" className="hover:bg-destructive">

{text.button.delete}
</Button>
</Link>
Expand All @@ -113,58 +119,52 @@ export function CreditById({
<b>{text.details.status + ":"}</b>
<Switch
className={'cursor-not-allowed'}
checked={!!creditDB?.estado}
checked={!!credit?.estado}
>
</Switch>
</li>
<li>
<b>{text.details.name + ":"}</b> <span>{ creditFilter?.nombre_del_cliente + "." }</span>
<b>{text.details.name + ":"}</b> <span>{ client?.nombres + " " + client?.apellidos + "." }</span>
</li>
<li>
<b>{text.details.date + ":"}</b> <span>{ format(creditDB?.fecha_de_aprobacion, 'dd-MM-yyyy') + '.'}</span>
<b>{text.details.date + ":"}</b> <span>{ format(credit?.fecha_de_aprobacion, 'dd-MM-yyyy') + '.'}</span>
</li>
<li>
<b>{text.details.aditionalsDays + ":"}</b> <span>{creditDB?.dias_adicionales + '.'}</span>
<b>{text.details.aditionalsDays + ":"}</b> <span>{credit?.dias_adicionales + '.'}</span>
</li>
<li>
<b>{text.details.amount + ":"}</b> <span>{'$' + creditDB?.monto + '.'}</span>
<b>{text.details.amount + ":"}</b> <span>{'$' + credit?.monto + '.'}</span>
</li>
<li>
<b>{text.details.cuote + ":"}</b> <span>{'$' + cuoteValue + '.'}</span>
</li>
<li>
<b>{text.details.cuoteNumber + ":"}</b> <span>{creditDB.pagos?.length + '/' + creditDB.numero_de_cuotas + '.'}</span>
<b>{text.details.cuoteNumber + ":"}</b> <span>{credit.pagos?.length + '/' + credit.numero_de_cuotas + '.'}</span>
</li>
<li>
<b>{text.details.frecuency + ":"}</b> <span>{getFrecuencyById({ frecuencyId: creditDB?.frecuencia_del_credito_id })?.nombre + '.'}</span>
<b>{text.details.frecuency + ":"}</b> <span>{getFrecuencyById({ frecuencyId: credit?.frecuencia_del_credito_id })?.nombre + '.'}</span>
</li>
<li className={clsx({ "[&>b]:text-green-700": !moraStatus, "[&>b]:line-through": moraStatus })}>
<b>{text.details.interest + ":"}</b> <span>{creditDB?.tasa_de_interes + '% de $' + cuoteValue + "."}</span>
<b>{text.details.interest + ":"}</b> <span>{credit?.tasa_de_interes + '% de $' + cuoteValue + "."}</span>
</li>
<li className={clsx({ "[&>b]:text-destructive": moraStatus, "[&>b]:line-through": !moraStatus })}>
<b>{text.details.installmants(moraType) + ":"}</b>
{ moraType === "Valor fijo" ?
<span >{'$' + moreValue + '.'}</span> :
<span>{creditDB?.valor_de_mora + "% de $" + ((cuoteValue ?? 0)) + '.'}</span> }
<span>{credit?.valor_de_mora + "% de $" + ((cuoteValue ?? 0)) + '.'}</span> }
</li>
<li>
<b>{text.details.pay + ":"}</b> <span>{'$' + ( (moraStatus ? ( (cuoteValue ?? 0) + moreValue ) : ( (cuoteValue ?? 0) + interestValue ))).toFixed(2) + '.'}</span>
</li>
<li>
<b>{text.details.user + ":"}</b> <span>{creditDB.cobrador_id}</span>
</li>
<li>
<b>{text.details.ref + ":"}</b> <span>{creditDB.garante_id}</span>
</li>
<li>
<b>{text.details.comment + ":"}</b> <p>{creditDB?.comentario}</p>
<b>{text.details.comment + ":"}</b> <p>{credit?.comentario}</p>
</li>
</ul>
<Separator />
{!!creditDB?.cuotas?.length && !!creditDB?.pagos?.length && (
{!!credit?.cuotas?.length && !!credit?.pagos?.length && (
<h2 className="text-2xl font-bold"> {text.cuotes.title} </h2>
)}
{!!creditDB?.cuotas?.length && !!creditDB?.pagos?.length && (
{!!credit?.cuotas?.length && !!credit?.pagos?.length && (
<Table className="w-full px-4 py-2">
<TableHeader className='bg-muted'>
<TableRow>
Expand All @@ -178,13 +178,17 @@ export function CreditById({
</TableRow>
</TableHeader>
<TableBody>
{creditDB?.cuotas.map(({id, fecha_de_pago, valor_pagado, valor_de_cuota, valor_de_mora, pagada, numero_de_cuota, fecha_de_aplicacion_de_mora}) => (
<TableRow key={id}>
{credit?.cuotas.map(({fecha_de_pago, valor_pagado, valor_de_cuota, valor_de_mora, pagada, numero_de_cuota, fecha_de_aplicacion_de_mora}, index) => (
<TableRow key={index}>
<TableCell>
<p><b>{numero_de_cuota}</b></p>
</TableCell>
<TableCell>
<p>{format(fecha_de_pago, 'MM-dd-yyyy')}</p>
{/* fix this date because returt a invalid date time */}
<ul>
<li className='before:content-["_-_"] before:font-bold before:text-destructive'>{credit?.pagos?.[index]?.fecha_de_pago?.slice(0,10)}</li>
<li className='before:content-["_+_"] before:font-bold before:text-green-700'>{format(fecha_de_pago, 'yyyy-MM-dd')}</li>
</ul>
</TableCell>
<TableCell>
<p><b>$</b>
Expand All @@ -207,15 +211,15 @@ export function CreditById({
></Switch>
</TableCell>
</TableRow>
))}
))?.slice(0, credit?.pagos?.length)}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={5} className="font-bold">
<p>{text.cuotes.total + ":"}</p>
</TableCell>
<TableCell colSpan={2} className="text-right">
<GetPay credit={creditDB} />
<GetPay credit={credit} />
</TableCell>
</TableRow>
</TableFooter>
Expand Down
54 changes: 30 additions & 24 deletions src/pages/_layout/credit_/$creditId_/update.confirm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ import { Checkbox } from '@/components/ui/checkbox'
import { useStatus } from '@/lib/context/layout'
import { patchCreditsById, type TCREDIT_GET, getCreditById } from '@/api/credit'
import { useNotifications } from '@/lib/context/notification'
import { _creditChangeContext, _paymentDeleteContext } from './update'
import { _clientContext, _creditChangeContext, _paymentDeleteContext } from './update'
import { useMutation } from '@tanstack/react-query'
import { TPAYMENT_GET_BASE, deletePaymentById, patchPaymentById } from "@/api/payment";
import { TCLIENT_GET_BASE } from '@/api/clients'

export const Route = createFileRoute('/_layout/credit/$creditId/update/confirm')({
component: UpdateConfirmationCredit,
Expand All @@ -33,9 +34,10 @@ export function UpdateConfirmationCredit({ credit: _credit = {} as TCREDIT_GET }
const [checked, setChecked] = useState(false)
const creditDB = Route.useLoaderData()
const [ creditChange ] = useContext(_creditChangeContext) ?? [ _credit ]
const [ deletePayment, setPaymentDelete ] = useContext(_paymentDeleteContext) ?? [ [], (() => {}) ]
const [ deletePayment, setPaymentDelete ] = useContext(_paymentDeleteContext) ?? [ {}, (() => {}) ]
const { open, setOpen } = useStatus()
const { pushNotification } = useNotifications()
const [ client ] = useContext(_clientContext) ?? [{} as TCLIENT_GET_BASE]

const { mutate: updateCredit } = useMutation({
mutationKey: ["update-credit"],
Expand All @@ -56,9 +58,10 @@ export function UpdateConfirmationCredit({ credit: _credit = {} as TCREDIT_GET }
setChecked(!checked)
}


const onSubmit: React.FormEventHandler< React.ComponentRef< typeof Button > > = (ev) => {
const description = text.notification.decription({
username: ""+creditDB?.owner_id,
username: client?.nombres + " " + client?.apellidos,
})

const creditItems = Object.fromEntries(
Expand All @@ -74,25 +77,28 @@ export function UpdateConfirmationCredit({ credit: _credit = {} as TCREDIT_GET }
} )?.filter( ([, value]) => !!value )
) as Record< keyof TPAYMENT_GET_BASE, string> & { id: number } )?.filter( ( { id, ...items } ) => ( Object.values( items ).some( ( item ) => ( !!item ) ) ) )

const deleteItems = Object.values( deletePayment )

const action = (credit: Record< keyof TCREDIT_GET, string> & { id: number }, payment: (Record< keyof TPAYMENT_GET_BASE, string> & { id: number })[], deletePay: number[]) => () => {
if(!credit?.id) return
updateCredit({
creditId: credit.id,
updateCredit: {
valor_de_mora: +credit?.valor_de_mora || undefined,
cobrador_id: +credit?.cobrador_id || undefined,
garante_id: +credit?.garante_id || undefined,
comentario: credit?.comentario,
estado: +credit?.estado || undefined,
monto: +credit?.monto || undefined,
tasa_de_interes: +credit?.tasa_de_interes || undefined,
tipo_de_mora_id: +credit?.tipo_de_mora_id || undefined,
dias_adicionales: +credit?.dias_adicionales || undefined,
numero_de_cuotas: +credit?.numero_de_cuotas || undefined,
fecha_de_aprobacion: credit?.fecha_de_aprobacion,
frecuencia_del_credito_id: +credit?.frecuencia_del_credito_id || undefined,
}
if(credit?.id && Object?.values( credit )?.length > 1) {
updateCredit({
creditId: credit.id,
updateCredit: {
valor_de_mora: +credit?.valor_de_mora || undefined,
cobrador_id: +credit?.cobrador_id || undefined,
garante_id: +credit?.garante_id || undefined,
comentario: credit?.comentario,
estado: +credit?.estado || undefined,
monto: +credit?.monto || undefined,
tasa_de_interes: +credit?.tasa_de_interes || undefined,
tipo_de_mora_id: +credit?.tipo_de_mora_id || undefined,
dias_adicionales: +credit?.dias_adicionales || undefined,
numero_de_cuotas: +credit?.numero_de_cuotas || undefined,
fecha_de_aprobacion: credit?.fecha_de_aprobacion,
frecuencia_del_credito_id: +credit?.frecuencia_del_credito_id || undefined,
}
})
}
for ( const pay of payment ){
if( !pay?.id ) continue;
updatePayment({
Expand All @@ -108,20 +114,20 @@ export function UpdateConfirmationCredit({ credit: _credit = {} as TCREDIT_GET }
if( !pay ) continue;
removePaymentById({ paymentId: pay })
}
setPaymentDelete([])

setPaymentDelete({})
pushNotification({
date: new Date(),
action: "PATH",
description,
})
}

const timer = setTimeout(action(creditItems, paymentItems, deletePayment ?? []), 6 * 1000)
const timer = setTimeout(action(creditItems, paymentItems, deleteItems), 6 * 1000)
setOpen({open: !open})

const onClick = () => {
clearTimeout(timer)
setPaymentDelete(deletePayment)
}

toast({
Expand All @@ -142,7 +148,7 @@ export function UpdateConfirmationCredit({ credit: _credit = {} as TCREDIT_GET }

return (
<>
{!open && <Navigate to={"../"} /> }
{!open && <Navigate to={"../../"} /> }
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle className="text-2xl">{text.title}</DialogTitle>
Expand Down
Loading

0 comments on commit 9b772a5

Please sign in to comment.