File size: 23,602 Bytes
2e7e617
 
8729c1d
816fa8a
2e7e617
816fa8a
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
2e7e617
 
816fa8a
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import { useEffect, useMemo, useRef, useState } from "react";
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal as raiseEvent } from "../apiContract";
import { BodyPortal, useOverlayLayer } from "../customer-grid/seam";
import { useAppFullscreen } from "../ui/useAppFullscreen";
import "./collection.css";
import "../styles/sdlc72/app-fullscreen.css";

type OpenDocument = {
  name: string;
  date: string | null;
  dueDate: string | null;
  daysOverdue: number;
  openBalance: number;
};

type CollectionRow = {
  partner_id: number;
  Customer: string;
  Tier: string;
  Overdue: number;
  Receivable: number;
  "Oldest (days)": number;
  "Open Docs": number;
  Email: string;
  Phone: string;
  Status: string;
  "Reconcile?": string;
  _docs: number;
  documents: OpenDocument[];
  sendRefusal: string | null;
};

type SendPolicy = {
  safeMode: boolean;
  safeRecipients: string[];
  sender: { name: string; email: string; replyTo: string };
};
type Worklist = SendPolicy & { rows: CollectionRow[] };
type Refusal = { customer: string; reason: string };
type Statement = {
  partnerId: number;
  customer: string;
  to: string;
  subject: string;
  html: string;
  refusal: string | null;
};
type Preview = SendPolicy & { requested: number; statements: Statement[]; refused: Refusal[] };
type SendResult = { created: number; refused: Refusal[]; safeMode: boolean };
type PageState =
  | { kind: "loading" }
  | { kind: "ready"; data: Worklist }
  | { kind: "error" | "restricted"; message: string };
type BatchState =
  | { kind: "loading"; ids: number[] }
  | { kind: "ready"; ids: number[]; data: Preview }
  | { kind: "error"; ids: number[]; message: string };

const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const count = new Intl.NumberFormat("en-US");
// C10: "Overdue" is Odoo's res.partner.total_overdue with no grace. A grace number reads "Overdue past grace".
const columns = ["Customer", "Tier", "Overdue", "Receivable", "Oldest days", "Open docs", "Email", "Phone", "Status", "Reconcile"];

function plural(value: number, one: string, many: string): string {
  return `${count.format(value)} ${value === 1 ? one : many}`;
}

function safeModeNotice(policy: SendPolicy): string {
  if (!policy.safeMode) return "Statements will be queued to each customer's Odoo email address.";
  if (!policy.safeRecipients.length) return "Safe mode is on; no recipient addresses can receive mail right now.";
  return `Safe mode is on; only ${policy.safeRecipients.join(", ")} can receive mail right now.`;
}

//: The only two refusals above 500 that are written FOR the reader rather than about the server.
const SPOKEN_5XX = new Set(["collection_send_unconfirmed", "collection_odoo_unavailable"]);

async function responseError(response: Response): Promise<string> {
  const body = await response.json().catch(() => null) as {
    error?: { code?: string; message?: string }; detail?: { error?: { code?: string; message?: string } };
  } | null;
  const error = body?.error || body?.detail?.error;
  // A 4xx message is policy and is shown; a 5xx detail is internal and is not (apiContract's rule).
  if (response.status >= 500 && !SPOKEN_5XX.has(error?.code || "")) {
    return "Something went wrong on our side. Try again in a moment.";
  }
  return error?.message || "Collection is temporarily unavailable.";
}

function Refusals({ items }: { items: Refusal[] }) {
  if (!items.length) return null;
  return <details className="collection-refusals" open>
    <summary>{plural(items.length, "customer refused", "customers refused")}</summary>
    <ul>{items.map((item, index) => <li key={`${index}-${item.customer}`}>
      <strong>{item.customer}</strong>: {item.reason}
    </li>)}</ul>
  </details>;
}

function TableSkeleton() {
  return <div className="collection-table-scroll" role="status" aria-label="Loading Collection worklist" aria-busy="true">
    <table className="collection-table" aria-hidden="true">
      <thead><tr><th>Select</th>{columns.map(label => <th key={label}>{label}</th>)}</tr></thead>
      <tbody>{Array.from({ length: 8 }, (_, index) => <tr key={index}>
        {Array.from({ length: columns.length + 1 }, (_, cell) => <td key={cell}><span className="collection-skeleton" /></td>)}
      </tr>)}</tbody>
    </table>
  </div>;
}

function CustomerDrawer({ row, onClose }: { row: CollectionRow; onClose: () => void }) {
  const panelRef = useRef<HTMLElement>(null);
  useOverlayLayer({ panelRef, onDismiss: onClose, dismissOnOutside: false, trapFocus: true });
  return <BodyPortal><div className="collection-overlay collection-overlay--drawer">
    <aside ref={panelRef} className="collection-drawer" role="dialog" aria-modal="true" aria-labelledby="collection-customer-title" tabIndex={-1}>
      <header className="collection-dialog-header">
        <h2 id="collection-customer-title">{row.Customer}</h2>
        <button type="button" className="collection-button" onClick={onClose}>Close</button>
      </header>
      <div className="collection-dialog-body">
        <dl className="collection-details">
          <div><dt>Email</dt><dd>{row.Email || "No email address"}</dd></div>
          <div><dt>Phone</dt><dd>{row.Phone || "Not recorded"}</dd></div>
          <div><dt>Status</dt><dd>{row.Status || "Not recorded"}</dd></div>
          <div><dt>Overdue</dt><dd className="collection-number collection-overdue">{money.format(row.Overdue)}</dd></div>
          <div><dt>Receivable</dt><dd className="collection-number">{money.format(row.Receivable)}</dd></div>
        </dl>
        <h3>Open documents</h3>
        {row.documents.length ? <div className="collection-document-scroll" tabIndex={0} aria-label="Open documents">
          <table className="collection-table">
            <thead><tr><th scope="col">Document</th><th scope="col">Date</th><th scope="col">Due</th><th scope="col" className="collection-number">Days overdue</th><th scope="col" className="collection-number">Open balance</th></tr></thead>
            <tbody>{row.documents.map((doc, index) => <tr key={`${doc.name}-${index}`}>
              <td>{doc.name}</td><td>{doc.date || "Not recorded"}</td><td>{doc.dueDate || "Not recorded"}</td>
              <td className="collection-number">{count.format(doc.daysOverdue)}</td>
              <td className="collection-number">{money.format(doc.openBalance)}</td>
            </tr>)}</tbody>
          </table>
        </div> : <p>No open documents for this customer.</p>}
      </div>
    </aside>
  </div></BodyPortal>;
}

function BatchDialog({ batch, sending, onClose, onSend }: {
  batch: BatchState; sending: boolean; onClose: () => void; onSend: (ids: number[]) => void;
}) {
  const panelRef = useRef<HTMLElement>(null);
  const confirmRef = useRef<HTMLButtonElement>(null);
  const sendRef = useRef<HTMLButtonElement>(null);
  const [confirming, setConfirming] = useState(false);
  const [statementIndex, setStatementIndex] = useState(0);
  useOverlayLayer({ panelRef, onDismiss: onClose, dismissOnOutside: false, trapFocus: true });
  useEffect(() => { (confirming ? confirmRef : sendRef).current?.focus(); }, [confirming]);
  const data = batch.kind === "ready" ? batch.data : null;
  const statement = data?.statements[statementIndex];
  const expected = data ? data.requested - data.refused.length : 0;
  return <BodyPortal><div className="collection-overlay">
    <section ref={panelRef} className="collection-modal" role="dialog" aria-modal="true" aria-labelledby="collection-batch-title" tabIndex={-1}>
      <header className="collection-dialog-header">
        <h2 id="collection-batch-title">{confirming ? "Confirm batch" : "Batch preview"}</h2>
        <button type="button" className="collection-button" onClick={onClose}>{sending ? "Close" : "Cancel"}</button>
      </header>
      <div className="collection-dialog-body">
        {batch.kind === "loading" && <div role="status" aria-busy="true" aria-label="Preparing statement previews"><span className="collection-preview-skeleton" /></div>}
        {batch.kind === "error" && <p role="alert">{batch.message}</p>}
        {data && <>
          <p className="collection-batch-count">{plural(data.requested, "customer", "customers")} selected. {plural(expected, "statement", "statements")} can be queued; {count.format(data.refused.length)} will be refused.</p>
          {confirming ? <>
            <p>Queue one statement per eligible customer in Odoo's outbox?</p>
            <p className="collection-muted">Balances and recipients are read again when you confirm.</p>
            <Refusals items={data.refused} />
          </> : <>
            <p className="collection-muted">From {data.sender.name} ({data.sender.email}). Replies go to {data.sender.replyTo}.</p>
            {statement && <>
              <label className="collection-field">Customer
                <select value={statementIndex} onChange={event => setStatementIndex(Number(event.target.value))}>
                  {data.statements.map((item, index) => <option key={item.partnerId} value={index}>{item.customer}{item.refusal ? " (will be refused)" : ""}</option>)}
                </select>
              </label>
              <dl className="collection-preview-details">
                <div><dt>To</dt><dd>{statement.to || "No email address"}</dd></div>
                <div><dt>Subject</dt><dd>{statement.subject}</dd></div>
              </dl>
              {statement.refusal && <p className="collection-notice">{statement.refusal}</p>}
              <div className="collection-preview-scroll" tabIndex={0} role="region" aria-label="Rendered statement">
                {/* Scripts and remote resources are blocked. The frame is read-only and sized to
                    its content, so scrolling and Escape stay in the parent overlay. */}
                <iframe key={statement.partnerId} className="collection-statement" title={`Statement for ${statement.customer}`}
                  sandbox="allow-same-origin" tabIndex={-1} referrerPolicy="no-referrer"
                  onLoad={event => {
                    const frame = event.currentTarget;
                    const content = frame.contentDocument?.documentElement;
                    if (!content) return;
                    frame.style.width = `${Math.max(frame.clientWidth, content.scrollWidth)}px`;
                    frame.style.height = `${Math.max(240, content.scrollHeight)}px`;
                  }}
                  srcDoc={`<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"></head><body>${statement.html}</body></html>`} />
              </div>
            </>}
            {!statement && <Refusals items={data.refused} />}
          </>}
        </>}
      </div>
      {data && <footer className="collection-dialog-footer">
        <p id="collection-send-policy" className={data.safeMode ? "collection-notice" : "collection-muted"}>{safeModeNotice(data)}</p>
        {sending && <p role="status">Queueing continues if you close this dialog.</p>}
        <div className="collection-dialog-actions">
          {confirming && !sending && <button type="button" className="collection-button" onClick={() => setConfirming(false)}>Back</button>}
          {confirming ? <button ref={confirmRef} type="button" className="collection-button collection-button--send" disabled={sending || !expected}
            aria-describedby="collection-send-policy" onClick={() => onSend(batch.ids)}>{sending ? "Queueing statements" : "Confirm send"}</button>
            : <button ref={sendRef} type="button" className="collection-button collection-button--primary" disabled={!expected}
              aria-describedby="collection-send-policy" onClick={() => setConfirming(true)}>Send</button>}
        </div>
      </footer>}
    </section>
  </div></BodyPortal>;
}

export default function CollectionPage() {
  const rootRef = useRef<HTMLElement>(null);
  const { fullscreen, toggleFullscreen } = useAppFullscreen(rootRef);
  const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
  const [page, setPage] = useState<PageState>({ kind: "loading" });
  const [reload, setReload] = useState(0);
  const [query, setQuery] = useState("");
  const [tier, setTier] = useState("");
  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [customer, setCustomer] = useState<CollectionRow | null>(null);
  const [batch, setBatch] = useState<BatchState | null>(null);
  const [sending, setSending] = useState(false);
  const [result, setResult] = useState<SendResult | null>(null);
  const [sendError, setSendError] = useState("");
  const [sendUnconfirmed, setSendUnconfirmed] = useState(false);
  const sendLock = useRef(false);
  const selectAllRef = useRef<HTMLInputElement>(null);
  const previewRequest = useRef<AbortController | null>(null);
  const refreshRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    const controller = new AbortController();
    setPage({ kind: "loading" });
    setSelected(new Set());
    void fetch(`${API_V1}/apps/collection/worklist`, { credentials: CREDENTIALS, signal: controller.signal }).then(async response => {
      if (checkTenant(response)) return;
      if (response.status === 401) raiseEvent(UNAUTHORIZED_EVENT);
      if (!response.ok) {
        const message = await responseError(response);
        setPage({ kind: [401, 403, 404].includes(response.status) ? "restricted" : "error", message });
        return;
      }
      const data = await response.json() as Worklist;
      if (!controller.signal.aborted) setPage({ kind: "ready", data });
    }).catch(() => {
      if (!controller.signal.aborted) setPage({ kind: "error", message: "The Collection worklist could not be loaded." });
    });
    return () => controller.abort();
  }, [reload]);
  useEffect(() => () => previewRequest.current?.abort(), []);

  const data = page.kind === "ready" ? page.data : null;
  const rows = useMemo(() => data?.rows ?? [], [data]);
  const tiers = useMemo(() => Array.from(new Set(rows.map(row => row.Tier))), [rows]);
  const visible = useMemo(() => {
    const search = query.trim().toLocaleLowerCase();
    return rows.filter(row => (!tier || row.Tier === tier) &&
      (!search || `${row.Customer} ${row.Email} ${row.Phone}`.toLocaleLowerCase().includes(search)));
  }, [rows, query, tier]);
  const selectedVisible = visible.filter(row => selected.has(row.partner_id)).length;
  const allVisible = visible.length > 0 && selectedVisible === visible.length;
  useEffect(() => {
    if (selectAllRef.current) selectAllRef.current.indeterminate = selectedVisible > 0 && !allVisible;
  }, [selectedVisible, allVisible]);

  function toggleVisible() {
    setSelected(previous => {
      const next = new Set(previous);
      visible.forEach(row => { if (allVisible) next.delete(row.partner_id); else next.add(row.partner_id); });
      return next;
    });
  }

  function closeBatch() {
    previewRequest.current?.abort();
    setBatch(null);
  }

  async function previewBatch() {
    if (!selected.size || sendLock.current || sendUnconfirmed) return;
    const ids = [...selected];
    const controller = new AbortController();
    previewRequest.current?.abort();
    previewRequest.current = controller;
    setBatch({ kind: "loading", ids });
    setSendError("");
    try {
      const response = await fetch(`${API_V1}/apps/collection/preview`, { method: "POST", credentials: CREDENTIALS,
        signal: controller.signal, headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ partnerIds: ids }) });
      if (checkTenant(response)) return;
      if (response.status === 401) raiseEvent(UNAUTHORIZED_EVENT);
      if (!response.ok) throw new Error(await responseError(response));
      const preview = await response.json() as Preview;
      if (!controller.signal.aborted) setBatch({ kind: "ready", ids, data: preview });
    } catch (error) {
      if (!controller.signal.aborted) setBatch({ kind: "error", ids, message: error instanceof Error ? error.message : "Statement previews could not be loaded." });
    }
  }

  async function sendBatch(ids: number[]) {
    if (sendLock.current) return;
    sendLock.current = true;
    setSending(true);
    setResult(null);
    setSendError("");
    // Never retry a write automatically: a lost response can follow successful mail creation.
    let uncertain = true;
    try {
      const response = await fetch(`${API_V1}/apps/collection/send`, { method: "POST", credentials: CREDENTIALS,
        headers: { "Content-Type": "application/json" }, body: JSON.stringify({ partnerIds: ids, confirm: true }) });
      if (checkTenant(response)) return;
      if (response.status === 401) raiseEvent(UNAUTHORIZED_EVENT);
      if (!response.ok) {
        uncertain = response.status >= 500;
        throw new Error(await responseError(response));
      }
      const sent = await response.json() as SendResult;
      setResult(sent);
      setSelected(new Set());
    } catch (error) {
      setSendUnconfirmed(uncertain);
      setSendError(uncertain
        ? "The batch result is unconfirmed. Some statements may already be in Odoo's outbox. Check Odoo before starting another batch."
        : error instanceof Error ? error.message : "The batch was refused.");
    } finally {
      sendLock.current = false;
      setSending(false);
      setBatch(null);
      window.requestAnimationFrame(() => refreshRef.current?.focus());
    }
  }

  return <section ref={rootRef} className="collection-page" aria-label="Collection"
    data-app-fullscreen={fullscreen ? "" : undefined}>
    <header className="collection-header">
      <h1>Collection</h1>
      <button type="button" className="collection-button" onClick={toggleFullscreen}
        aria-label={fullscreenLabel} aria-pressed={fullscreen}>{fullscreenLabel}</button>
      <button ref={refreshRef} type="button" className="collection-button" disabled={page.kind === "loading" || sending}
        onClick={() => setReload(value => value + 1)}>Refresh</button>
    </header>
    {page.kind === "loading" && <TableSkeleton />}
    {page.kind === "restricted" && <div className="collection-empty" role="status"><p>{page.message}</p></div>}
    {page.kind === "error" && <div className="collection-empty" role="alert"><p>{page.message}</p>
      <button type="button" className="collection-button" onClick={() => setReload(value => value + 1)}>Try again</button></div>}
    {data && <>
      <div className="collection-toolbar">
        <label className="collection-field">Search<input type="search" value={query} onChange={event => setQuery(event.target.value)} placeholder="Customer, email or phone" /></label>
        <label className="collection-field">Tier<select value={tier} onChange={event => setTier(event.target.value)}>
          <option value="">All tiers</option>{tiers.map(value => <option key={value} value={value}>{value}</option>)}
        </select></label>
        <div className="collection-selection" role="status" aria-live="polite">
          <span>{count.format(visible.length)} of {count.format(rows.length)} customers</span>
          <span>{count.format(selected.size)} selected{selected.size > selectedVisible ? ` (${count.format(selected.size - selectedVisible)} outside this filter)` : ""}</span>
        </div>
        <button type="button" className="collection-button" disabled={!selected.size || sending} onClick={() => setSelected(new Set())}>Clear selection</button>
        <button type="button" className="collection-button collection-button--primary" disabled={!selected.size || sending || sendUnconfirmed}
          aria-describedby="collection-worklist-policy" onClick={() => void previewBatch()}>Preview batch</button>
      </div>
      <p id="collection-worklist-policy" className={data.safeMode ? "collection-notice" : "collection-muted"}>{safeModeNotice(data)}</p>
      {sending && <p role="status">Queueing statements in Odoo's outbox.</p>}
      {sendError && <div className="collection-result" role="alert"><p>{sendError}</p>
        {sendUnconfirmed && <button type="button" className="collection-button" onClick={() => { setSendUnconfirmed(false); setSendError(""); setSelected(new Set()); setReload(value => value + 1); }}>I checked Odoo's outbox</button>}
      </div>}
      {result && <section className="collection-result" aria-label="Batch result">
        <p role="status">{plural(result.created, "mail.mail record", "mail.mail records")} created in Odoo's outbox. {plural(result.refused.length, "customer", "customers")} refused.{result.safeMode ? " Safe mode was on." : ""}</p>
        <Refusals items={result.refused} />
      </section>}
      {!rows.length ? <div className="collection-empty"><p>No customers on the Collection worklist.</p></div>
        : !visible.length ? <div className="collection-empty"><p>No customers match these filters.</p>
          <button type="button" className="collection-button" onClick={() => { setQuery(""); setTier(""); }}>Clear filters</button></div>
          : <div className="collection-table-scroll" tabIndex={0} role="region" aria-label="Collection worklist">
            <table className="collection-table">
              <thead><tr>
                <th scope="col" className="collection-check"><input ref={selectAllRef} type="checkbox" checked={allVisible} disabled={sending}
                  onChange={toggleVisible} aria-label={`Select all ${plural(visible.length, "visible customer", "visible customers")}`} /></th>
                {columns.map((label, index) => <th scope="col" key={label} className={index >= 2 && index <= 5 ? "collection-number" : undefined}>{label}</th>)}
              </tr></thead>
              <tbody>{visible.map(row => <tr key={row.partner_id} className={`collection-data-row${selected.has(row.partner_id) ? " collection-row--selected" : ""}`}
                onClick={event => { event.currentTarget.querySelector("button")?.focus(); setCustomer(row); }}>
                <td className="collection-check" onClick={event => event.stopPropagation()}><input type="checkbox" checked={selected.has(row.partner_id)} disabled={sending}
                  title={row.sendRefusal || undefined} aria-label={row.sendRefusal ? `Select ${row.Customer}. ${row.sendRefusal}` : `Select ${row.Customer}`}
                  onChange={() => setSelected(previous => { const next = new Set(previous); if (next.has(row.partner_id)) next.delete(row.partner_id); else next.add(row.partner_id); return next; })} /></td>
                <td><button type="button" className="collection-button collection-customer" onClick={() => setCustomer(row)}>{row.Customer}</button></td>
                <td>{row.Tier}</td><td className="collection-number collection-overdue">{money.format(row.Overdue)}</td>
                <td className="collection-number">{money.format(row.Receivable)}</td><td className="collection-number">{count.format(row["Oldest (days)"])}</td>
                <td className="collection-number">{count.format(row["Open Docs"])}</td><td>{row.Email || "No email address"}</td><td>{row.Phone || "Not recorded"}</td>
                <td>{row.Status || "Not recorded"}</td><td>{row["Reconcile?"] ? "Review" : "Clear"}</td>
              </tr>)}</tbody>
            </table>
          </div>}
    </>}
    {customer && <CustomerDrawer row={customer} onClose={() => setCustomer(null)} />}
    {batch && <BatchDialog batch={batch} sending={sending} onClose={closeBatch} onSend={ids => void sendBatch(ids)} />}
  </section>;
}