'use client' import { useEffect, useState } from 'react' import { invoices as invoicesApi, payments as paymentsApi, shopPos as shopPosApi, getApiError } from '@/lib/api/index' import type { PaymentResponse, InvoiceResponse } from '@/types/api' import type { InvoiceCustomer } from './invoice-template' // Loads everything the printed invoice needs. Only the invoice is required — if payments or the // customer details fail to load, that block is simply left out. export function useInvoiceDocument(invoiceId: string | null | undefined, enabled = true) { const [invoice, setInvoice] = useState(null) const [payments, setPayments] = useState([]) const [customer, setCustomer] = useState() const [error, setError] = useState(null) useEffect(() => { if (!enabled || !invoiceId) return let cancelled = false setInvoice(null) setPayments([]) setCustomer(undefined) setError(null) invoicesApi.get(invoiceId) .then((inv) => { if (cancelled) return setInvoice(inv) paymentsApi.listByInvoice(inv.id).then((p) => !cancelled && setPayments(p)).catch(() => {}) shopPosApi.get(inv.shopPOId) .then((po) => !cancelled && setCustomer({ address: po.storeAddress, phone: po.storeContactNumber })) .catch(() => {}) }) .catch((err) => !cancelled && setError(getApiError(err))) return () => { cancelled = true } }, [invoiceId, enabled]) return { invoice, payments, customer, error } }