File size: 14,131 Bytes
c72f0a1 071ce2b c72f0a1 071ce2b c72f0a1 071ce2b c72f0a1 071ce2b c72f0a1 071ce2b c72f0a1 071ce2b c72f0a1 071ce2b c72f0a1 071ce2b c72f0a1 071ce2b c72f0a1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | 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;
|