import React, { useEffect, useState } from "react"; import { InertiaFormProps } from "@inertiajs/react"; import { route } from "ziggy-js"; import axios from "axios"; import { Button, Stack, TextInput, NumberInput, Loader, Select, Switch, Text } from "@mantine/core"; import { DateInput } from "@mantine/dates"; import { IconDeviceFloppy } from "@tabler/icons-react"; import dayjs from "dayjs"; export interface InvoiceFormValues { invoice_no: string; linked_invoice_id: string; is_credit_card: boolean; is_paid: boolean; payment_no: string; start_date: string; end_date: string; amount: string; management_fee: string; media_fee: string; tax_percent: string; total_spending: string; client_id?: string; customer_id?: string; } interface InvoiceOption { value: string; label: string; } interface Props { form: InertiaFormProps; onSubmit: (event: React.FormEvent) => void; submitLabel?: string; invoiceOptions?: InvoiceOption[]; } export default function InvoiceForm({ form, onSubmit, submitLabel = "Save invoice", invoiceOptions = [], }: Props) { const formatDate = (value: string) => (value ? dayjs(value).toDate() : null); const [fetchingSpend, setFetchingSpend] = useState(false); useEffect(() => { if (!form.data.is_credit_card) return; // Credit-card invoices can be fee-free; normalize fields to 0 for convenience. if (form.data.management_fee !== "0") form.setData("management_fee", "0"); if (form.data.media_fee !== "0") form.setData("media_fee", "0"); if (form.data.tax_percent !== "0") form.setData("tax_percent", "0"); }, [form.data.is_credit_card]); useEffect(() => { const startDate = form.data.start_date; const endDate = form.data.end_date; const customerId = form.data.customer_id; if (!startDate || !endDate) { form.setData("total_spending", "0"); setFetchingSpend(false); return; } let canceled = false; setFetchingSpend(true); axios .post( route("google.getCampaignsDetails"), { clientCustomerId: customerId, startDate, endDate, }, { withCredentials: true, } ) .then((response) => { if (canceled) return; const value = parseFloat(response.data?.summary?.total_actual_spend ?? 0) || 0; const formatted = value.toFixed(2); form.setData("total_spending", formatted); }) .catch(() => { if (!canceled) { form.setData("total_spending", ""); } }) .finally(() => { if (!canceled) { setFetchingSpend(false); } }); return () => { canceled = true; }; }, [form.data.start_date, form.data.end_date, form.data.customer_id]); return (
form.setData("invoice_no", event.target.value)} error={form.errors.invoice_no} required />