# layout

Features served by the layout app, currently AI (`POST /api/ai/*`). The app needs no AI packages or AI
gateway env of its own for them.

## Notes

- **Setup:** add `LAYOUT_BASE_URL: z.url()` to the `server` block of `src/env.ts` with the layout
  app's URL in `.env`, and `layout: "api://wistron.com/devportal/access_as_user"` to the app's
  scopes. `AI_BASE_URL` is a different thing: the AI gateway `chatAdapter` calls (see the `ai` skill).
- **Translate instead of prompting:** text a user typed (a name, a question, a description) gets
  its other languages from `translate`; never write a translation prompt in the app.
- **Detected language:** `detected` is the language the text is written in, even one outside
  `languages`. When it is one of them, its field is the text exactly as typed (trimmed), never
  reworded; compare it with the field the user typed into to repair a wrong language toggle.
- One call per text, not streamed. Translate several texts with one call each, in parallel.
- **Extract instead of prompting:** data read from a document or photo (an invoice, a label, a
  form) comes from `extractFile`; never send a file to a model from the app. Upload the file with
  the file service first, then pass its `appName` and `fileId`.
- **File access:** the layout app downloads the file on behalf of the signed-in user (OBO), so it
  reads only files that user can open. A call without a user (a background job on the server
  `extractFile`) reads the file with the layout app's own token instead.
- **Fields:** each field is a name (letters, digits, `_`), a `type` (`string` by default,
  `number`, `boolean` or `date`) and a `description` that says what to read and in what form,
  e.g. "ISO 4217 code of the invoiced currency". Every field is `null` when the file does not
  show it; a `date` is `YYYY-MM-DD`. Values are copied as printed: conversions and calculations
  (currency, totals, thresholds) stay in the app's code.
- **Instructions:** optional context the model compares against, e.g. the approved items, with a
  field such as `note` that describes what to report.
- PDFs and images (PNG, JPEG, WebP, GIF) up to 20 MB; other types answer 415.

## Client

`import { ... } from "wcz-layout/data/client";`

- Mutation:
  `translateMutationOptions()` → `mutate(TranslateSchema)` → `Translation` // the text in every language of `languages`, and the language it is written in; signed-in users only
- Mutation:
  `extractFileMutationOptions()` → `mutate(ExtractFileSchema)` → `FileExtraction` // the value of each field read from the file; signed-in users only

## Server

`import { ... } from "wcz-layout/data/server";`

- `translate({ data: TranslateSchema })` → `Translation` // same, inside another server function
- `extractFile({ data: ExtractFileSchema })` → `FileExtraction` // same, inside another server function or a background job

## Schemas/Models

`import { TranslateSchema, ExtractFileSchema, type Translation, type FileExtraction } from "wcz-layout/models";`

```ts
const TranslateSchema = z.object({
  text: z.string().trim().min(1).max(4000),
  languages: z // BCP 47 tags: en, cs, zh-TW
    .array(z.string().regex(/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/))
    .min(1)
    .max(20),
});

type Translation = { detected: string } & Record<string, string>; // { detected: "cs", en, cs, uk }

const ExtractFileSchema = z.object({
  appName: z.string().min(1).max(255),
  fileId: z.uuid(),
  fields: z.record(
    z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,63}$/), // 1 to 50 fields
    z.object({
      type: z.enum(["string", "number", "boolean", "date"]).default("string"),
      description: z.string().trim().min(1).max(1000),
    }),
  ),
  instructions: z.string().trim().max(4000).optional(),
});

type FileExtraction = Record<string, string | number | boolean | null>; // keyed by field name
```

## Examples

```tsx
// client
import { useMutation } from "@tanstack/react-query";
import { translateMutationOptions } from "wcz-layout/data/client";

const { mutateAsync: translate, isPending } = useMutation(translateMutationOptions());

const { detected, ...name } = await translate({
  text: form.getFieldValue("name.en"),
  languages: ["en", "cs", "uk", "zh-TW"],
});
form.setFieldValue("name", name); // { en, cs, uk, "zh-TW" }

// server (inside another server function)
import { translate } from "wcz-layout/data/server";

const translations = await Promise.all(
  tasks.map((task) => translate({ data: { text: task.text, languages: ["cs", "en", "uk"] } })),
);
```

```ts
// server: read an uploaded invoice, then convert and compare in code
import { extractFile } from "wcz-layout/data/server";

const invoice = await extractFile({
  data: {
    appName: "cid",
    fileId,
    fields: {
      invoice: {
        description:
          "Invoice number exactly as printed; the primary document number on a debit note or RMA",
      },
      total: {
        type: "number",
        description: "Grand total exactly as printed, in the document's own currency",
      },
      currency: { description: "ISO 4217 code of the invoiced currency (TWD for NTD)" },
      note: {
        description:
          "Discrepancies against the approved items: unexpected part numbers, quantities, supplier",
      },
    },
    instructions: `Approved items:\n${items.map((item) => `- ${item.pn}: qty ${item.quantity}`).join("\n")}`,
  },
});
const totalNtd =
  invoice.total === null ? null : await toNtd(Number(invoice.total), String(invoice.currency));
```
