Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download web/src/apps/customer-card/CustomerCardView.tsx from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/apps/customer-card/CustomerCardView.tsx
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/web/src/apps/customer-card/CustomerCardView.tsx
-
curl -L -o CustomerCardView.tsx https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/apps/customer-card/CustomerCardView.tsx
14.1 kB
| import { useEffect, useRef, useState } from "react"; | |
| import { API_V1, CREDENTIALS, TOAST_EVENT, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract"; | |
| import { ConfirmDialog } from "../../ui/ConfirmDialog"; | |
| import "../../styles/sdlc74/customer-card.css"; | |
| export type CustomerCardApplication = { | |
| id: string; | |
| name: string; | |
| templateKind: string; | |
| sourceDatabase: string; | |
| deepLink: string; | |
| }; | |
| export type CustomerCardCustomer = { id: number; name: string }; | |
| export type CustomerCardInvoice = { | |
| id: number; | |
| number: string; | |
| date: string | null; | |
| dueDate: string | null; | |
| openAmount: number; | |
| paymentState: string; | |
| kind: string; | |
| }; | |
| export type CustomerCardAgent = { | |
| id: number; | |
| name: string; | |
| phone: string | null; | |
| email: string | null; | |
| }; | |
| export type CustomerCardData = { | |
| application: CustomerCardApplication; | |
| customer: CustomerCardCustomer; | |
| businessUnit: number | null; | |
| state: string; | |
| total: number; | |
| invoices: { | |
| rows: CustomerCardInvoice[]; | |
| total: number; | |
| totalCount: number; | |
| offset: number; | |
| limit: number; | |
| hasMore: boolean; | |
| }; | |
| products: { | |
| productId: number; | |
| name: string; | |
| lastOrderDate: string | null; | |
| price: number; | |
| unit: string; | |
| saleLineId: number; | |
| }[]; | |
| productWindow: { from: string; to: string }; | |
| agent: CustomerCardAgent | null; | |
| agents: CustomerCardAgent[]; | |
| source: { observation: string; proof: string; reconciliation: string }; | |
| // T67's server capability preserves the Administrator and Royal restrictions. | |
| capabilities?: { emailAvailable?: boolean }; | |
| }; | |
| export type CustomerCardLink = { slug: string; url: string }; | |
| export type CustomerCardPrivatePreview = { | |
| applicationId: string; | |
| customerId: number; | |
| ensureLink: () => Promise<CustomerCardLink>; | |
| emailAvailable?: boolean; | |
| }; | |
| export type CustomerCardViewProps = { | |
| data: CustomerCardData | null; | |
| loading?: boolean; | |
| error?: string; | |
| onRetry?: () => void; | |
| onLoadMoreInvoices?: () => void; | |
| invoiceLoading?: boolean; | |
| invoiceError?: string; | |
| privatePreview?: CustomerCardPrivatePreview; | |
| onEmailLink?: (context: CustomerCardPrivatePreview) => void; | |
| }; | |
| const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }); | |
| const dateFormat = new Intl.DateTimeFormat("en-US", { | |
| month: "short", day: "numeric", year: "numeric", timeZone: "UTC", | |
| }); | |
| function dueDate(value: string | null): string { | |
| if (!value) return "No due date"; | |
| const parsed = new Date(`${value.slice(0, 10)}T00:00:00Z`); | |
| return Number.isNaN(parsed.getTime()) ? "No due date" : dateFormat.format(parsed); | |
| } | |
| type EmailPreview = { previewToken: string; to: string; subject: string; body: string; refusal?: string | null }; | |
| type EmailResult = { state: "queued" | "refused"; created: number; message?: string }; | |
| class EmailRefused extends Error {} | |
| function useRefusalToast() { | |
| const [messages, setMessages] = useState<{ id: number; text: string }[]>([]); | |
| const sequence = useRef(0); | |
| const delivered = useRef(0); | |
| useEffect(() => { | |
| if (!messages.length) return; | |
| const through = messages[messages.length - 1].id; | |
| for (const message of messages) { | |
| if (message.id <= delivered.current) continue; | |
| delivered.current = message.id; | |
| const text = message.text; | |
| window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } })); | |
| } | |
| setMessages((current) => current.filter((message) => message.id > through)); | |
| }, [messages]); | |
| return (text: string) => { | |
| if (!text) return; | |
| const message = { id: ++sequence.current, text }; | |
| setMessages((current) => [...current, message]); | |
| }; | |
| } | |
| async function emailRequest<T>(path: string, body: object, abort: AbortSignal): Promise<T> { | |
| const response = await fetch(`${API_V1}${path}`, { method: "POST", credentials: CREDENTIALS, | |
| headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), signal: abort }); | |
| if (checkTenant(response)) throw new Error("Workspace changed."); | |
| if (response.status === 401) signal(UNAUTHORIZED_EVENT); | |
| const result = await response.json(); | |
| if (!response.ok) { | |
| const message = result?.error?.message || "The email could not be prepared."; | |
| if ([401, 403, 404].includes(response.status)) throw new EmailRefused(message); | |
| throw new Error(message); | |
| } | |
| return result as T; | |
| } | |
| function CustomerCardEmail({ context, onEmailLink }: { | |
| context: CustomerCardPrivatePreview; | |
| onEmailLink?: CustomerCardViewProps["onEmailLink"]; | |
| }) { | |
| const emailRefusal = useRefusalToast(); | |
| const [preview, setPreview] = useState<EmailPreview | null>(null); | |
| const [preparing, setPreparing] = useState(false); | |
| const [queueing, setQueueing] = useState(false); | |
| const [result, setResult] = useState(""); | |
| const [failed, setFailed] = useState(false); | |
| const mounted = useRef(true); | |
| const pending = useRef(false); | |
| const controller = useRef<AbortController | null>(null); | |
| const emailButton = useRef<HTMLButtonElement>(null); | |
| const emailStatus = useRef<HTMLParagraphElement>(null); | |
| const restoreEmailFocus = useRef(false); | |
| const base = `/customer-card/${encodeURIComponent(context.applicationId)}/customers/${context.customerId}/email`; | |
| useEffect(() => { | |
| mounted.current = true; | |
| return () => { mounted.current = false; controller.current?.abort(); }; | |
| }, []); | |
| // Preparation disables the opener before the shared overlay can capture it. | |
| useEffect(() => { | |
| if (preview !== null) { restoreEmailFocus.current = true; return; } | |
| if (!restoreEmailFocus.current || preparing || queueing) return; | |
| restoreEmailFocus.current = false; | |
| if (!mounted.current || emailButton.current?.disabled) return; | |
| const target = result === "Queued" ? emailStatus.current : emailButton.current; | |
| if (target?.isConnected) target.focus({ preventScroll: true }); | |
| }, [preview, preparing, queueing, result]); | |
| async function openEmail() { | |
| if (pending.current || result === "Queued") return; | |
| if (onEmailLink) { onEmailLink(context); return; } | |
| const request = new AbortController(); | |
| controller.current = request; | |
| pending.current = true; | |
| setPreparing(true); | |
| setResult(""); | |
| setFailed(false); | |
| try { | |
| const link = await context.ensureLink(); | |
| if (!mounted.current || request.signal.aborted) return; | |
| const next = await emailRequest<EmailPreview>(`${base}/preview`, { slug: link.slug }, request.signal); | |
| if (!mounted.current || request.signal.aborted) return; | |
| if (typeof next.previewToken !== "string" || !next.previewToken || typeof next.to !== "string" | |
| || typeof next.subject !== "string" || typeof next.body !== "string") throw new Error("The email could not be prepared."); | |
| setPreview(next); | |
| if (next.refusal) emailRefusal(next.refusal); | |
| } catch (error) { | |
| if (mounted.current && !request.signal.aborted) { | |
| if (error instanceof EmailRefused) emailRefusal(error.message); | |
| else { | |
| setResult(error instanceof Error ? error.message : "The email could not be prepared."); | |
| setFailed(true); | |
| } | |
| } | |
| } finally { | |
| if (mounted.current && !request.signal.aborted) { pending.current = false; setPreparing(false); } | |
| } | |
| } | |
| async function queueEmail() { | |
| if (!preview || pending.current) return; | |
| if (preview.refusal) { emailRefusal(preview.refusal); return; } | |
| const request = new AbortController(); | |
| controller.current = request; | |
| pending.current = true; | |
| setQueueing(true); | |
| try { | |
| const next = await emailRequest<EmailResult>(`${base}/send`, | |
| { previewToken: preview.previewToken, confirm: true }, request.signal); | |
| if (!mounted.current || request.signal.aborted) return; | |
| if (next.state !== "queued" && next.state !== "refused") throw new Error("Queueing was not confirmed. Check Odoo before trying again."); | |
| if (next.state === "refused") { | |
| setResult(""); | |
| setFailed(false); | |
| emailRefusal("Safe mode does not allow this recipient address."); | |
| } else { | |
| setResult("Queued"); | |
| setFailed(false); | |
| } | |
| } catch (error) { | |
| if (mounted.current && !request.signal.aborted) { | |
| if (error instanceof EmailRefused) { setResult(""); emailRefusal(error.message); } | |
| else { | |
| setResult(error instanceof Error ? error.message : "Queueing was not confirmed. Check Odoo before trying again."); | |
| setFailed(true); | |
| } | |
| } | |
| } finally { | |
| if (mounted.current && !request.signal.aborted) { | |
| pending.current = false; | |
| setQueueing(false); | |
| setPreview(null); | |
| } | |
| } | |
| } | |
| return <> | |
| <button type="button" className="set-secondary customer-card-button" data-customer-card-email="" | |
| ref={emailButton} | |
| disabled={preparing || queueing || preview !== null} aria-disabled={result === "Queued"} | |
| onClick={() => void openEmail()}>{preparing ? "Preparing email" : result === "Queued" ? "Queued" : "Email link"}</button> | |
| {result && <p ref={emailStatus} tabIndex={result === "Queued" ? -1 : undefined} | |
| className="customer-card-message" role={failed ? "alert" : "status"}>{result}</p>} | |
| <ConfirmDialog open={preview !== null} title="Email link" tone="primary" busy={queueing} | |
| confirmLabel={queueing ? "Queueing" : "Queue email"} onConfirm={() => void queueEmail()} | |
| onCancel={() => setPreview(null)} body={preview && <div data-customer-card-email-confirm="" | |
| style={{ fontVariantNumeric: "tabular-nums", overflowWrap: "anywhere" }}> | |
| <p className="customer-card-label">To</p><p data-email-recipient="">{preview.to}</p> | |
| <p className="customer-card-label">Subject</p><p data-email-subject="">{preview.subject}</p> | |
| <p className="customer-card-label">Body</p> | |
| <p data-email-body="" style={{ whiteSpace: "pre-wrap" }}>{preview.body}</p> | |
| </div>} /> | |
| </>; | |
| } | |
| export function CustomerCardSkeleton() { | |
| return <div className="customer-card-loading" role="status" aria-label="Loading customer card" aria-busy="true"> | |
| {[0, 1, 2, 3].map(section => <div className="customer-card-section" key={section} aria-hidden="true"> | |
| <span className="customer-card-skeleton customer-card-skeleton-title" /> | |
| <span className="customer-card-skeleton" /> | |
| <span className="customer-card-skeleton customer-card-skeleton-short" /> | |
| </div>)} | |
| </div>; | |
| } | |
| export function CustomerCardView({ | |
| data, loading = false, error, onRetry, onLoadMoreInvoices, invoiceLoading = false, | |
| invoiceError, privatePreview, onEmailLink, | |
| }: CustomerCardViewProps) { | |
| if (loading) return <CustomerCardSkeleton />; | |
| if (error) return <div className="customer-card-message" role="alert"> | |
| <p>{error}</p> | |
| {onRetry && <button type="button" className="set-secondary customer-card-button" onClick={onRetry}>Retry</button>} | |
| </div>; | |
| if (!data) return <p className="customer-card-message">Choose a customer.</p>; | |
| const agents = data.agents?.length ? data.agents : data.agent ? [data.agent] : []; | |
| return <article className="customer-card-view" aria-label={`Customer card for ${data.customer.name}`}> | |
| <header className="customer-card-section customer-card-recipient"> | |
| <p className="customer-card-label">For</p> | |
| <h1>{data.customer.name}</h1> | |
| </header> | |
| <section className="customer-card-section" aria-labelledby="customer-card-outstanding"> | |
| <h2 id="customer-card-outstanding">Outstanding</h2> | |
| {data.invoices.totalCount === 0 ? <p className="customer-card-empty">Nothing is outstanding.</p> : <> | |
| <table className="customer-card-invoices"> | |
| <thead><tr><th scope="col">Invoice</th><th scope="col">Due date</th><th scope="col">Amount</th></tr></thead> | |
| <tbody>{data.invoices.rows.map(invoice => <tr key={invoice.id}> | |
| <td>{invoice.number}{invoice.kind === "out_refund" && <span className="customer-card-meta">Credit</span>}</td> | |
| <td>{dueDate(invoice.dueDate)}</td> | |
| <td>{money.format(invoice.openAmount)}</td> | |
| </tr>)}</tbody> | |
| </table> | |
| {data.invoices.hasMore && onLoadMoreInvoices && <button type="button" | |
| className="set-secondary customer-card-button customer-card-more" disabled={invoiceLoading} | |
| onClick={onLoadMoreInvoices}>{invoiceLoading ? "Loading invoices" : "More invoices"}</button>} | |
| {invoiceError && <p className="customer-card-message" role="alert">{invoiceError}</p>} | |
| <div className="customer-card-total"><span>Total outstanding</span><strong>{money.format(data.total)}</strong></div> | |
| </>} | |
| </section> | |
| <section className="customer-card-section" aria-labelledby="customer-card-products"> | |
| <h2 id="customer-card-products">Products</h2> | |
| {data.products.length ? <ul className="customer-card-products"> | |
| {data.products.map(product => <li key={product.productId}> | |
| <span className="customer-card-product-name">{product.name}</span> | |
| <span className="customer-card-price">{money.format(product.price)}<span className="customer-card-meta">per {product.unit}</span></span> | |
| </li>)} | |
| </ul> : <p className="customer-card-empty">No products yet.</p>} | |
| </section> | |
| <section className="customer-card-section" aria-labelledby="customer-card-contact"> | |
| <h2 id="customer-card-contact">Your contact</h2> | |
| {agents.length ? agents.map(agent => <address className="customer-card-contact" key={agent.id}> | |
| <span>{agent.name}</span> | |
| {agent.phone && <a href={`tel:${agent.phone.replace(/[^+\d]/g, "")}`}>{agent.phone}</a>} | |
| {agent.email && <a href={`mailto:${agent.email}`}>{agent.email}</a>} | |
| </address>) : <p className="customer-card-empty">No contact is listed.</p>} | |
| </section> | |
| {privatePreview && data.capabilities?.emailAvailable === true | |
| && privatePreview.applicationId === data.application.id && privatePreview.customerId === data.customer.id | |
| && <CustomerCardEmail key={`${privatePreview.applicationId}:${privatePreview.customerId}`} | |
| context={privatePreview} onEmailLink={onEmailLink} />} | |
| </article>; | |
| } | |
| export default CustomerCardView; | |