Presupuestador_web/client/src/app/quotes/edit.tsx

234 lines
7.1 KiB
TypeScript
Raw Normal View History

2024-07-11 17:43:08 +00:00
import {
BackHistoryButton,
CancelButton,
ErrorOverlay,
FormCurrencyField,
LoadingOverlay,
SubmitButton,
} from "@/components";
2024-07-09 16:21:12 +00:00
import { calculateItemTotals } from "@/lib/calc";
import { useUrlId } from "@/lib/hooks/useUrlId";
2024-07-01 17:12:15 +00:00
import { Badge, Button, Form, Tabs, TabsContent, TabsList, TabsTrigger } from "@/ui";
2024-07-10 18:54:33 +00:00
import { CurrencyData, IUpdateQuote_Request_DTO, MoneyValue } from "@shared/contexts";
2024-07-01 17:12:15 +00:00
import { t } from "i18next";
2024-07-09 16:21:12 +00:00
import { useEffect, useState } from "react";
2024-07-01 17:12:15 +00:00
import { SubmitHandler, useForm } from "react-hook-form";
2024-07-11 18:49:06 +00:00
import useFormPersist from "react-hook-form-persist";
2024-07-11 17:43:08 +00:00
import { useNavigate } from "react-router-dom";
2024-07-11 18:49:06 +00:00
import { toast } from "react-toastify";
2024-07-09 16:21:12 +00:00
import { QuoteDetailsCardEditor, QuoteGeneralCardEditor } from "./components/editors";
2024-07-01 17:12:15 +00:00
import { useQuotes } from "./hooks";
2024-07-10 18:54:33 +00:00
interface QuoteDataForm extends IUpdateQuote_Request_DTO {}
2024-07-01 17:12:15 +00:00
2024-07-09 16:21:12 +00:00
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export const QuoteEdit = () => {
2024-07-11 17:43:08 +00:00
const navigate = useNavigate();
2024-07-09 16:21:12 +00:00
const quoteId = useUrlId();
2024-07-10 18:54:33 +00:00
const [quoteCurrency, setQuoteCurrency] = useState<CurrencyData>(
CurrencyData.createDefaultCode().object
);
/*const { data: userIdentity } = useGetIdentity();
console.log(userIdentity);
2024-07-01 17:12:15 +00:00
2024-07-10 18:54:33 +00:00
const { flag } = useLocalization({
locale: userIdentity?.language ?? "es-es",
});
console.log(flag);*/
2024-07-01 17:12:15 +00:00
2024-07-09 16:21:12 +00:00
const { useOne, useUpdate } = useQuotes();
2024-07-01 17:12:15 +00:00
2024-07-10 18:54:33 +00:00
const { data, status, error: queryError } = useOne(quoteId);
2024-07-09 18:29:02 +00:00
const { mutate } = useUpdate(String(quoteId));
2024-07-01 17:12:15 +00:00
const form = useForm<QuoteDataForm>({
mode: "onBlur",
values: data,
defaultValues: {
date: "",
reference: "",
customer_information: "",
lang_code: "",
currency_code: "",
payment_method: "",
notes: "",
validity: "",
2024-07-11 17:43:08 +00:00
subtotal_price: {
amount: undefined,
precision: 2,
currency_code: data?.currency_code,
},
discount: {
amount: undefined,
precision: 0,
},
total_price: {
amount: undefined,
precision: 2,
currency_code: data?.currency_code,
},
2024-07-11 18:31:01 +00:00
items: [
{
subtotal_price: {
amount: undefined,
precision: 4,
currency_code: data?.currency_code,
},
discount: {
amount: undefined,
precision: 0,
},
total_price: {
amount: undefined,
precision: 4,
currency_code: data?.currency_code,
},
},
],
2024-07-01 17:12:15 +00:00
},
});
2024-07-09 18:29:02 +00:00
const { watch, getValues, setValue, formState } = form;
2024-07-11 18:49:06 +00:00
const { clear } = useFormPersist("quote-edit", { watch, setValue, storage: window.localStorage });
2024-07-09 18:29:02 +00:00
const { isSubmitting } = formState;
2024-07-01 17:12:15 +00:00
const onSubmit: SubmitHandler<QuoteDataForm> = async (data) => {
2024-07-10 18:54:33 +00:00
// Transformación del form -> typo de request
mutate(data, {
onError: (error) => {
2024-07-11 16:40:46 +00:00
console.debug(error);
//alert(error.message);
2024-07-10 18:54:33 +00:00
},
//onSettled: () => {},
onSuccess: () => {
2024-07-11 18:49:06 +00:00
toast("Guardado!");
clear();
2024-07-10 18:54:33 +00:00
},
});
2024-07-01 17:12:15 +00:00
};
2024-07-09 16:21:12 +00:00
useEffect(() => {
2024-07-11 16:40:46 +00:00
// eslint-disable-next-line @typescript-eslint/no-unused-vars
2024-07-09 16:21:12 +00:00
const { unsubscribe } = watch((_, { name, type }) => {
const value = getValues();
if (name) {
2024-07-10 18:54:33 +00:00
if (name === "currency_code") {
setQuoteCurrency(
CurrencyData.createFromCode(value.lang_code ?? CurrencyData.DEFAULT_CURRENCY_CODE)
.object
);
}
2024-07-09 16:21:12 +00:00
if (name === "items") {
const { items } = value;
let quoteSubtotal = MoneyValue.create().object;
// Recálculo líneas
items.map((item, index) => {
const itemTotals = calculateItemTotals(item);
2024-07-11 16:40:46 +00:00
if (itemTotals === null) {
return;
}
2024-07-09 16:21:21 +00:00
quoteSubtotal = quoteSubtotal.add(itemTotals.totalPrice);
2024-07-09 16:21:12 +00:00
2024-07-09 16:21:21 +00:00
setValue(`items.${index}.subtotal_price`, itemTotals.subtotalPrice.toObject());
setValue(`items.${index}.total_price`, itemTotals.totalPrice.toObject());
2024-07-09 16:21:12 +00:00
});
// Recálculo completo
2024-07-10 18:54:33 +00:00
setValue("subtotal_price", quoteSubtotal.toObject());
2024-07-09 16:21:12 +00:00
}
2024-07-11 16:40:46 +00:00
if (name.endsWith("quantity") || name.endsWith("unit_price") || name.endsWith("discount")) {
2024-07-09 16:21:12 +00:00
const { items } = value;
2024-07-10 18:54:33 +00:00
// eslint-disable-next-line @typescript-eslint/no-unused-vars
2024-07-09 16:21:12 +00:00
const [, indexString, fieldName] = String(name).split(".");
const index = parseInt(indexString);
const itemTotals = calculateItemTotals(items[index]);
2024-07-11 16:40:46 +00:00
if (itemTotals === null) {
return;
}
2024-07-09 16:21:12 +00:00
2024-07-09 16:21:21 +00:00
setValue(`items.${index}.subtotal_price`, itemTotals.subtotalPrice.toObject());
setValue(`items.${index}.total_price`, itemTotals.totalPrice.toObject());
2024-07-09 16:21:12 +00:00
// Recálculo completo
}
}
});
return () => unsubscribe();
}, [watch, getValues, setValue]);
2024-07-09 18:29:02 +00:00
if (isSubmitting) {
return <LoadingOverlay />;
}
if (status === "error") {
return <ErrorOverlay errorMessage={queryError.message} />;
}
2024-07-09 16:21:12 +00:00
if (status !== "success") {
return <LoadingOverlay />;
}
2024-07-01 17:12:15 +00:00
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className='mx-auto grid max-w-[90rem] flex-1 auto-rows-max gap-6'>
<div className='flex items-center gap-4'>
2024-07-11 17:43:08 +00:00
<BackHistoryButton />
2024-07-01 17:12:15 +00:00
<h1 className='flex-1 text-xl font-semibold tracking-tight shrink-0 whitespace-nowrap sm:grow-0'>
2024-07-09 16:21:12 +00:00
{t("quotes.edit.title")}
2024-07-01 17:12:15 +00:00
</h1>
<Badge variant='default' className='ml-auto sm:ml-0'>
2024-07-09 16:21:12 +00:00
{data.status}
2024-07-01 17:12:15 +00:00
</Badge>
<div className='items-center hidden gap-2 md:ml-auto md:flex'>
2024-07-11 17:43:08 +00:00
<CancelButton variant='outline' size='sm' onClick={() => navigate("/quotes")}>
2024-07-09 16:21:12 +00:00
{t("common.cancel")}
2024-07-11 17:43:08 +00:00
</CancelButton>
2024-07-01 17:12:15 +00:00
<SubmitButton variant={form.formState.isDirty ? "default" : "outline"} size='sm'>
2024-07-09 16:21:12 +00:00
{t("common.save")}
2024-07-01 17:12:15 +00:00
</SubmitButton>
</div>
</div>
2024-07-09 16:21:12 +00:00
2024-07-12 16:13:53 +00:00
<QuoteGeneralCardEditor />
<QuoteDetailsCardEditor currency={quoteCurrency} />
2024-07-09 16:21:12 +00:00
<Tabs defaultValue='items' className='space-y-4'>
2024-07-01 17:12:15 +00:00
<TabsList>
<TabsTrigger value='general'>{t("quotes.create.tabs.general")}</TabsTrigger>
<TabsTrigger value='items'>{t("quotes.create.tabs.items")}</TabsTrigger>
2024-07-11 18:49:06 +00:00
{/* <TabsTrigger value='history'>{t("quotes.create.tabs.history")}</TabsTrigger>*/}
2024-07-01 17:12:15 +00:00
</TabsList>
<TabsContent value='general'>
<QuoteGeneralCardEditor />
</TabsContent>
<TabsContent value='items'>
2024-07-10 18:54:33 +00:00
<QuoteDetailsCardEditor currency={quoteCurrency} />
2024-07-01 17:12:15 +00:00
</TabsContent>
<TabsContent value='history'></TabsContent>
</Tabs>
<div className='flex items-center justify-center gap-2 md:hidden'>
<Button variant='outline' size='sm'>
{t("quotes.create.buttons.discard")}
</Button>
<Button size='sm'>{t("quotes.create.buttons.save_quote")}</Button>
</div>
</div>
</form>
</Form>
);
};