import { FormPercentageField } from "@/components"; import { useLocalization } from "@/lib/hooks"; import { Card, CardContent, CardDescription, CardTitle, Separator } from "@/ui"; import { CurrencyData, MoneyValue, Percentage } from "@shared/contexts"; import { t } from "i18next"; import { useMemo } from "react"; import { useFormContext, useWatch } from "react-hook-form"; const calculateQuoteTotals = (prices: any) => { const discountOrError = Percentage.create( prices[1] || { amount: null, scale: 2, } ); if (discountOrError.isFailure) { throw discountOrError.error; } const discount = discountOrError.object; const taxOrError = Percentage.create( prices[2] || { amount: null, scale: 2, } ); if (taxOrError.isFailure) { throw taxOrError.error; } const tax = taxOrError.object; const subtotalOrError = MoneyValue.create( prices[0] || { amount: null, scale: 2, } ); if (subtotalOrError.isFailure) { throw subtotalOrError.error; } const subtotalPrice = subtotalOrError.object; const discountPrice = subtotalPrice.percentage(discount.toNumber()).convertScale(2); const priceBeforeTaxes = subtotalPrice.subtract(discountPrice).convertScale(2); const taxesPrice = priceBeforeTaxes.percentage(tax.toNumber()).convertScale(2); const totalPrice = priceBeforeTaxes.add(taxesPrice).convertScale(2); return { subtotalPrice: subtotalPrice.toObject(), discount: discount.toObject(), discountPrice: discountPrice.toObject(), priceBeforeTaxes: priceBeforeTaxes.toObject(), tax: tax.toObject(), taxesPrice: taxesPrice.toObject(), totalPrice: totalPrice.toObject(), }; }; export const QuotePricesResume = ({ currency }: { currency: CurrencyData }) => { const { formState, control } = useFormContext(); const { formatNumber } = useLocalization(); const pricesWatch = useWatch({ control, name: ["subtotal_price", "discount", "tax"] }); const taxLabel = useWatch({ control, name: "tax_label" }) || t("quotes.form_fields.tax.label"); const totals = calculateQuoteTotals(pricesWatch); const subtotal_price = formatNumber(totals.subtotalPrice); const discount_price = formatNumber(totals.discountPrice); const tax_price = formatNumber(totals.taxesPrice); const total_price = formatNumber(totals.totalPrice); const currency_symbol = useMemo(() => currency.symbol || "", [currency]); return (
{t("quotes.form_fields.subtotal_price.label")} {subtotal_price} {currency_symbol}
{t("quotes.form_fields.discount.label")} { //console.log("discount", value); }} />
{t("quotes.form_fields.discount_price.label")} {discount_price} {currency_symbol}
{taxLabel}
{t("quotes.form_fields.tax_price.label", { label: "" })} {tax_price} {currency_symbol}
{" "}
{t("quotes.form_fields.total_price.label")} {total_price} {currency_symbol}
); };