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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
// ---------------------------------------------------------------------------
// ui / primitives.tsx β€” EXIT wave 2 (W2-6, contract Y2).
//
// The shared presentation layer. Y2 fixes these names and neither side invents:
//   KpiRow Β· Section Β· DashHeader Β· DataTable Β· ClickableList Β· Download Β·
//   ValidationPanel   (+ `fmt` next door)
//
// WHY THIS IS THE WHOLE POINT OF THE WAVE. Sales is the pilot; Collections and
// Procurement are supposed to cost "two entries in a registry" in wave 3. That
// is only true if the page renderer is a function of the Y1 envelope and
// nothing else β€” so no primitive here knows the word "sales", and every one of
// them takes its content from data.
//
// TWO OWNER CONSTANTS ARE ENFORCED IN CODE HERE, not left to review:
//   Β· **Every count drills to exact rows; a silent [:N] cap is a defect.**
//     `DataTable` renders "showing N of M" whenever the block declares a cap,
//     and it renders it from the SERVER's numbers, never from `rows.length` β€”
//     a client-side count of a truncated list is exactly the lie being guarded.
//   Β· **No emojis** β€” the two status glyphs are SVG (`./icons`).
//
// Colour is CSS variables only (`--lp-*`); there is not one literal in this
// file or in the `.pg-*` block of index.css. Text, strokes and rules take the
// `-deep` weight: the pastels measure 1.38–1.94:1 on white and are legitimately
// unreadable as ink ([[loopable-brand-palette]]).
// ---------------------------------------------------------------------------

import { useMemo } from "react";
import { capDisclosure, cellDescriptor, emptyText } from "./blocks";
import { BLANK, fmt, formatValue } from "./fmt";
import { AlertIcon, CheckIcon, DownloadIcon } from "./icons";
import type {
  DrillDescriptor,
  DrillRule,
  EntityKind,
  KpiItem,
  PageControl,
  PageRow,
  TableColumn,
  ValidationCheck,
} from "./types";

/** What a drill does when it fires. The shell supplies it; a primitive never
 *  decides what "open" means. */
export type OnOpen = (d: DrillDescriptor) => void;

// ------------------------------------------------------------------ DashHeader

/**
 * The page title bar: title, a hairline rule with a gold head, the subtitle,
 * and the page's controls β€” mirroring `ui/primitives.py:dash_header` plus the
 * BU picker that lives in the Streamlit page body.
 *
 * ⚠ `controls` render their selection from `value` IN THE RESPONSE (Y1 rule 9),
 * never from local state. A parameter the server rejected or coerced therefore
 * cannot look accepted β€” the picker snaps back to what the server actually did.
 */
export function DashHeader({
  title,
  asOf,
  subtitle,
  controls,
  onControl,
  busy,
}: {
  title: string;
  asOf?: string;
  subtitle?: string;
  controls?: PageControl[];
  onControl?: (key: string, value: string) => void;
  busy?: boolean;
}) {
  return (
    <header className="pg-header">
      <div className="pg-title-row">
        <h1 className="pg-title">{title}</h1>
        {controls && controls.length > 0 ? (
          <div className="pg-controls">
            {controls.map((c) => (
              <label key={c.key} className="pg-control">
                <span className="pg-control-label">{c.label}</span>
                <select
                  className="pg-select"
                  value={String(c.value)}
                  disabled={busy || !onControl}
                  onChange={(e) => onControl?.(c.key, e.target.value)}
                >
                  {/* ⚠ Every option carries an explicit `value`. A <select>
                      whose selected option omits it renders the FIRST option
                      instead β€” a control that silently lies about the state it
                      is displaying ([[cg-condition-builder-items]]). */}
                  {c.options.map((o) => (
                    <option key={String(o.value)} value={String(o.value)}>
                      {o.label}
                    </option>
                  ))}
                </select>
              </label>
            ))}
          </div>
        ) : null}
      </div>
      <div className="pg-rule" />
      {subtitle ? <p className="pg-subtitle">{subtitle}</p> : null}
      {asOf ? (
        <p className="pg-asof">
          Data pulled <time dateTime={asOf}>{fmt.date(asOf)}</time>
        </p>
      ) : null}
    </header>
  );
}

// --------------------------------------------------------------------- Section

/** A section header with its explanation. The prose is a `note`, shown β€” not a
 *  tooltip: the Streamlit version hides it behind an β“˜ to save vertical space
 *  that a real page does not have to fight for. */
export function Section({
  label,
  note,
  children,
}: {
  label: string;
  note?: string;
  children?: React.ReactNode;
}) {
  return (
    <section className="pg-section">
      <h2 className="pg-section-label">{label}</h2>
      {note ? <p className="pg-section-note">{note}</p> : null}
      {children}
    </section>
  );
}

// ---------------------------------------------------------------------- KpiRow

/**
 * The scorecard. A card with a `drill` is a real button; one without is inert
 * and must not look otherwise β€” a card that invites a click and does nothing is
 * the cheapest way to lose a user's trust in the whole page.
 *
 * The delta is the subtle part. Y1 rule 4: when a period has no revenue the
 * server sends `delta: null` with a `delta_label` and `delta_dir:"off"`, so the
 * card reads "no orders yet" instead of an alarming βˆ’100%. `delta_dir` tints;
 * it never replaces the sign, which comes from the number itself.
 */
export function KpiRow({ items, onOpen }: { items: KpiItem[]; onOpen?: OnOpen }) {
  if (!items.length) return null;
  return (
    <div className="pg-kpis">
      {items.map((m, i) => {
        const value = formatValue(m.value, m.fmt);
        const hasDelta = m.delta != null;
        const deltaText = hasDelta
          ? formatValue(m.delta, m.delta_fmt ?? "pct", { signed: true })
          : "";
        const dir = m.delta_dir ?? (hasDelta ? "flat" : "off");
        const body = (
          <>
            <span className="pg-kpi-label">{m.label}</span>
            <span className="pg-kpi-value">{value}</span>
            {deltaText || m.delta_label ? (
              <span className={`pg-kpi-delta is-${dir}`}>
                {deltaText}
                {deltaText && m.delta_label ? " " : ""}
                {m.delta_label ?? ""}
              </span>
            ) : null}
          </>
        );
        const key = m.key ?? `${m.label}-${i}`;
        return m.drill && onOpen ? (
          <button
            key={key}
            type="button"
            className="pg-kpi is-clickable"
            onClick={() => onOpen(m.drill as DrillDescriptor)}
          >
            {body}
          </button>
        ) : (
          <div key={key} className="pg-kpi">
            {body}
          </div>
        );
      })}
    </div>
  );
}

// -------------------------------------------------------------------- Download

/** CSV of exactly what the table is showing. Built from the same `columns` the
 *  table rendered, in the same order, with the same formatting β€” a download
 *  that disagrees with the screen is worse than no download.
 *
 *  ⚠ Values are formatted, then quoted. RFC-4180 quoting (double the quote,
 *  wrap anything with a comma/quote/newline) β€” an unquoted `$1,204` splits one
 *  money column into two. */
export function Download({
  rows,
  columns,
  filename,
  note,
}: {
  rows: PageRow[];
  columns: TableColumn[];
  filename: string;
  note?: string;
}) {
  const href = useMemo(() => {
    const esc = (s: string) =>
      /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
    const head = columns.map((c) => esc(c.label)).join(",");
    const body = rows.map((r) =>
      columns.map((c) => esc(formatValue(r[c.key], c.fmt))).join(",")
    );
    // The BOM is what makes Excel read UTF-8 instead of the system codepage.
    const csv = "ο»Ώ" + [head, ...body].join("\r\n");
    return URL.createObjectURL(new Blob([csv], { type: "text/csv;charset=utf-8" }));
  }, [rows, columns]);

  return (
    <a className="pg-download" href={href} download={`${filename}.csv`}>
      <DownloadIcon />
      <span>Download CSV</span>
      {note ? <span className="pg-download-note">{note}</span> : null}
    </a>
  );
}

// ------------------------------------------------------------------- DataTable

/**
 * The table block.
 *
 * β›” THE CAP DISCLOSURE IS NOT DECORATION. `shown`/`total` come from the SERVER
 * and are rendered verbatim. Deriving "showing N of M" from `rows.length` would
 * make the disclosure agree with the truncated list by construction β€” it would
 * read correct on a lie. Owner rule [[no-unverifiable-aggregates]]: a number a
 * user cannot open to exact rows is a defect, and a count that cannot be wrong
 * is not a check.
 */
export function DataTable({
  columns,
  rows,
  drill,
  shown,
  total,
  onOpen,
  empty,
  download,
}: {
  columns: TableColumn[];
  rows: PageRow[];
  drill?: DrillRule;
  shown?: number;
  total?: number;
  onOpen?: OnOpen;
  empty?: string;
  download?: { filename: string };
}) {
  const cap = capDisclosure(shown, total);
  const capped = cap?.capped ?? false;

  if (!rows.length) {
    // An empty state SAYS WHAT EMPTY MEANS. "No data" is the sentence that
    // sends somebody to check whether the page is broken.
    return <p className="pg-empty">{emptyText(empty)}</p>;
  }

  return (
    <div className="pg-table-wrap">
      <table className="pg-table">
        <thead>
          <tr>
            {columns.map((c) => (
              <th
                key={c.key}
                className={c.align === "right" ? "is-right" : c.align === "center" ? "is-center" : ""}
                scope="col"
              >
                {c.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((r, i) => {
            const d = cellDescriptor(r, drill);
            return (
              <tr key={String(r[columns[0]?.key] ?? i)} className={d && onOpen ? "is-clickable" : ""}>
                {columns.map((c, ci) => {
                  const text = formatValue(r[c.key], c.fmt);
                  const cls =
                    c.align === "right" ? "is-right" : c.align === "center" ? "is-center" : "";
                  // Only the FIRST column becomes the affordance β€” a whole row
                  // of links reads as eight destinations, not one.
                  return (
                    <td key={c.key} className={cls}>
                      {ci === 0 && d && onOpen ? (
                        <button type="button" className="pg-cell-link" onClick={() => onOpen(d)}>
                          {text}
                        </button>
                      ) : (
                        text
                      )}
                    </td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>
      <div className="pg-table-foot">
        {cap ? (
          <span className={cap.capped ? "pg-shown is-capped" : "pg-shown"}>{cap.text}</span>
        ) : null}
        {download ? (
          <Download
            rows={rows}
            columns={columns}
            filename={download.filename}
            note={capped ? "the rows shown" : undefined}
          />
        ) : null}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------- ClickableList

/**
 * A compact list of entities, each opening its panel β€” the drawer affordance
 * from `ui/primitives.py:clickable_list`, for places a full table is too much.
 *
 * `kind` is the ENTITY KIND (Y6: `sku` is what Sales needs), and the emitted
 * descriptor is the same `EntityDescriptor` a table's block-level rule produces
 * β€” one grammar, so the shell has one handler and not one per surface.
 */
export function ClickableList({
  rows,
  kind,
  onOpen,
  idKey = "id",
  labelKey = "label",
  valueKey,
  valueFmt,
  shown,
  total,
  empty,
}: {
  rows: PageRow[];
  kind: EntityKind;
  onOpen?: OnOpen;
  idKey?: string;
  labelKey?: string;
  valueKey?: string;
  valueFmt?: string;
  shown?: number;
  total?: number;
  empty?: string;
}) {
  if (!rows.length) return <p className="pg-empty">{emptyText(empty)}</p>;
  const cap = capDisclosure(shown, total);
  return (
    <div className="pg-list">
      <ul className="pg-list-items">
        {rows.map((r, i) => {
          const id = r[idKey];
          const label = String(r[labelKey] ?? id ?? BLANK);
          const value = valueKey ? formatValue(r[valueKey], valueFmt) : null;
          const openable = onOpen && id != null && id !== "";
          return (
            <li key={String(id ?? i)} className="pg-list-item">
              {openable ? (
                <button
                  type="button"
                  className="pg-cell-link"
                  onClick={() =>
                    onOpen({ kind, id: id as string | number, label })
                  }
                >
                  {label}
                </button>
              ) : (
                <span>{label}</span>
              )}
              {value != null ? <span className="pg-list-value">{value}</span> : null}
            </li>
          );
        })}
      </ul>
      {cap ? <span className={cap.capped ? "pg-shown is-capped" : "pg-shown"}>{cap.text}</span> : null}
    </div>
  );
}

// ------------------------------------------------------------- ValidationPanel

/**
 * Every headline number reconciled to an independent aggregate β€” the platform's
 * standing rule ("a number that doesn't tie to Odoo does not ship") made
 * visible to the person reading the page rather than only to `validate.py`.
 *
 * A FAILING check is shown, never hidden: the panel exists to be believed, and
 * a panel that only ever shows green is decoration.
 */
export function ValidationPanel({ checks }: { checks: ValidationCheck[] }) {
  if (!checks.length) return null;
  const failed = checks.filter((c) => !c.ok).length;
  return (
    <details className="pg-validation" open={failed > 0}>
      <summary className={failed ? "is-failed" : "is-ok"}>
        {failed ? <AlertIcon /> : <CheckIcon />}
        <span>
          {failed
            ? `${fmt.int(failed)} of ${fmt.int(checks.length)} reconciliation checks did not tie`
            : `All ${fmt.int(checks.length)} reconciliation checks tie to Odoo`}
        </span>
      </summary>
      <table className="pg-table pg-validation-table">
        <thead>
          <tr>
            <th scope="col">Check</th>
            <th scope="col" className="is-right">Expected</th>
            <th scope="col" className="is-right">Actual</th>
            <th scope="col">Note</th>
          </tr>
        </thead>
        <tbody>
          {checks.map((c) => (
            <tr key={c.name} className={c.ok ? "" : "is-failed"}>
              <td>{c.name}</td>
              <td className="is-right">{formatValue(c.expected, c.fmt)}</td>
              <td className="is-right">{formatValue(c.actual, c.fmt)}</td>
              <td>{c.note ?? ""}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </details>
  );
}