wcz-layout 10.1.9 → 10.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/dist/{Approval-DoD-GRRH.mjs → Approval-D1TfISUL.mjs} +11 -21
  2. package/dist/Approval-D1TfISUL.mjs.map +1 -0
  3. package/dist/{LayoutTable-CRo43iWr.d.mts → ChatLayout-BmLySLXy.d.mts} +11 -18
  4. package/dist/ChatLayout-Tpuwo8-b.mjs +1622 -0
  5. package/dist/ChatLayout-Tpuwo8-b.mjs.map +1 -0
  6. package/dist/{DialogsContext-DLqA8RJ_.mjs → DialogsContext-D23fJjYR.mjs} +2 -3
  7. package/dist/DialogsContext-D23fJjYR.mjs.map +1 -0
  8. package/dist/{Email-CKUxOURX.d.mts → Email-Dz5k0UWE.d.mts} +1 -3
  9. package/dist/{Email-BzQQkbe9.mjs → Email-rnz3H0x3.mjs} +3 -5
  10. package/dist/Email-rnz3H0x3.mjs.map +1 -0
  11. package/dist/{Employee-agVPiGrJ.d.mts → Employee-C8xIlBxY.d.mts} +1 -7
  12. package/dist/{FileMeta-Be9viU7D.d.mts → FileMeta-B39e2FLC.d.mts} +1 -3
  13. package/dist/{FileMeta-DDqUju1Y.mjs → FileMeta-CPBWI_jA.mjs} +2 -3
  14. package/dist/FileMeta-CPBWI_jA.mjs.map +1 -0
  15. package/dist/{QueryClientParam-JcH0mJWl.d.mts → QueryClientParam-CTV1vj76.d.mts} +1 -3
  16. package/dist/RouterListItemButton-CF-8w-08.mjs +62 -0
  17. package/dist/RouterListItemButton-CF-8w-08.mjs.map +1 -0
  18. package/dist/{User-D4__w1I1.d.mts → User-aJksXItw.d.mts} +1 -3
  19. package/dist/{approval-L09uPzTU.mjs → approval-HB2w5jzc.mjs} +4 -5
  20. package/dist/approval-HB2w5jzc.mjs.map +1 -0
  21. package/dist/auth.d.mts +0 -4
  22. package/dist/auth.mjs +5 -6
  23. package/dist/auth.mjs.map +1 -1
  24. package/dist/components.d.mts +63 -33
  25. package/dist/components.mjs +658 -748
  26. package/dist/components.mjs.map +1 -1
  27. package/dist/{createApi-BhNkG4jz.mjs → createApi-CKgFi53y.mjs} +4 -6
  28. package/dist/createApi-CKgFi53y.mjs.map +1 -0
  29. package/dist/data/client.d.mts +2 -8
  30. package/dist/data/client.mjs +6 -9
  31. package/dist/data/client.mjs.map +1 -1
  32. package/dist/data/server.d.mts +2 -4
  33. package/dist/data/server.mjs +6 -7
  34. package/dist/data/server.mjs.map +1 -1
  35. package/dist/env-BwFl7nWc.mjs +48 -0
  36. package/dist/env-BwFl7nWc.mjs.map +1 -0
  37. package/dist/{file-Chlljz3o.mjs → file-X1sK4ok6.mjs} +7 -8
  38. package/dist/file-X1sK4ok6.mjs.map +1 -0
  39. package/dist/{file-Dl8JCcqy.mjs → file-tkfsnk5F.mjs} +8 -8
  40. package/dist/file-tkfsnk5F.mjs.map +1 -0
  41. package/dist/generatedChart-k7NEdi5Z.mjs +211 -0
  42. package/dist/generatedChart-k7NEdi5Z.mjs.map +1 -0
  43. package/dist/hooks.d.mts +30 -30
  44. package/dist/hooks.mjs +1828 -1304
  45. package/dist/hooks.mjs.map +1 -1
  46. package/dist/index.d.mts +11 -14
  47. package/dist/index.mjs +1273 -1051
  48. package/dist/index.mjs.map +1 -1
  49. package/dist/middleware.d.mts +1 -7
  50. package/dist/middleware.mjs +5 -8
  51. package/dist/middleware.mjs.map +1 -1
  52. package/dist/models.d.mts +4 -32
  53. package/dist/models.mjs +7 -11
  54. package/dist/models.mjs.map +1 -1
  55. package/dist/{peoplesoft-D6q3cYsH.d.mts → peoplesoft-C-zPdRVj.d.mts} +3 -9
  56. package/dist/{peoplesoft-BhintHQz.mjs → peoplesoft-RnvfLbWH.mjs} +5 -25
  57. package/dist/peoplesoft-RnvfLbWH.mjs.map +1 -0
  58. package/dist/{providers-BvuZWkpD.mjs → providers-BfFg_3eo.mjs} +5 -23
  59. package/dist/providers-BfFg_3eo.mjs.map +1 -0
  60. package/dist/{tokens-XuFhVbh5.mjs → tokens-C4SErO-K.mjs} +12 -8
  61. package/dist/tokens-C4SErO-K.mjs.map +1 -0
  62. package/dist/{utils-CaeVFWF-.mjs → utils-C2MZoH9U.mjs} +8 -39
  63. package/dist/utils-C2MZoH9U.mjs.map +1 -0
  64. package/dist/{utils-Bhi0KiBx.d.mts → utils-CNYCSgip.d.mts} +3 -5
  65. package/dist/utils-DnMFybj3.mjs +27 -0
  66. package/dist/utils-DnMFybj3.mjs.map +1 -0
  67. package/dist/utils.d.mts +11 -2
  68. package/dist/utils.mjs +3 -5
  69. package/dist/vite.d.mts +0 -2
  70. package/dist/vite.mjs +2 -4
  71. package/dist/vite.mjs.map +1 -1
  72. package/package.json +131 -131
  73. package/skills/ai/SKILL.md +136 -39
  74. package/skills/client-db/SKILL.md +104 -90
  75. package/skills/db-schema/SKILL.md +28 -20
  76. package/skills/dialogs/SKILL.md +26 -38
  77. package/skills/forms/SKILL.md +133 -73
  78. package/skills/general/SKILL.md +99 -105
  79. package/skills/general/references/auth.md +70 -0
  80. package/skills/migrations/versions/migrate-v10-to-v11.md +30 -4
  81. package/skills/routing/SKILL.md +60 -58
  82. package/skills/scanning/SKILL.md +67 -0
  83. package/skills/server-functions/SKILL.md +71 -26
  84. package/skills/services/SKILL.md +4 -4
  85. package/skills/services/docs/approval.md +70 -24
  86. package/skills/services/docs/email.md +24 -3
  87. package/skills/services/docs/file.md +69 -27
  88. package/skills/services/docs/peoplesoft.md +55 -39
  89. package/skills/start/steps/03-apm-setup.md +9 -9
  90. package/skills/table/SKILL.md +250 -267
  91. package/dist/AggregatedCell-oGcwbetF.mjs +0 -559
  92. package/dist/AggregatedCell-oGcwbetF.mjs.map +0 -1
  93. package/dist/Approval-DoD-GRRH.mjs.map +0 -1
  94. package/dist/DialogsContext-DLqA8RJ_.mjs.map +0 -1
  95. package/dist/Email-BzQQkbe9.mjs.map +0 -1
  96. package/dist/FileMeta-DDqUju1Y.mjs.map +0 -1
  97. package/dist/RouterListItemButton-ULMlaQh6.mjs +0 -80
  98. package/dist/RouterListItemButton-ULMlaQh6.mjs.map +0 -1
  99. package/dist/approval-L09uPzTU.mjs.map +0 -1
  100. package/dist/createApi-BhNkG4jz.mjs.map +0 -1
  101. package/dist/file-Chlljz3o.mjs.map +0 -1
  102. package/dist/file-Dl8JCcqy.mjs.map +0 -1
  103. package/dist/peoplesoft-BhintHQz.mjs.map +0 -1
  104. package/dist/providers-BvuZWkpD.mjs.map +0 -1
  105. package/dist/tokens-XuFhVbh5.mjs.map +0 -1
  106. package/dist/utils-CaeVFWF-.mjs.map +0 -1
  107. package/skills/general/references/exports.md +0 -114
@@ -1,87 +1,89 @@
1
1
  ---
2
2
  name: routing
3
- description: "Use when adding or changing a page, route file, navigation entry, search params, or route-level access control. Covers createFileRoute, beforeLoad requireAuth, loader preloads, validateSearch, useSearch, src/routes/ naming and colocation, __root.tsx navigation, the auth and login routes, and the RouterLink/RouterButton link components."
3
+ description: "Use when adding or changing a page or route file in app: list, detail, create and edit routes, loaders and preloading, pending skeletons, missing rows (not found), search params, route access (requireAuth), navigation entries and LayoutProvider options in __root.tsx, or in-app links (RouterLink, RouterButton, RouterIconButton)."
4
4
  metadata:
5
5
  type: convention
6
6
  library: wcz-layout
7
7
  ---
8
8
 
9
- > Mechanics (route definitions, loaders, context, guards, navigation, search params,
10
- > route-tree fundamentals) are covered by TanStack's own skills. List the skills shipped by
11
- > `@tanstack/router-core` and `@tanstack/react-router` and load whichever cover the task at
12
- > hand. This skill adds the wcz-layout conventions.
9
+ Route mechanics (file routes, loaders, search params, navigation, not-found, type safety): load
10
+ `@tanstack/router-core#router-core` and the sub-skills the task needs (`data-loading`,
11
+ `search-params`, `navigation`, `not-found-and-errors`).
13
12
 
14
13
  ## Rules
15
14
 
16
- - Include `requireAuth(<permissionKey>)` in the route's `beforeLoad` to enforce access
17
- control — pass a key defined in your app's `src/lib/auth/permissions.ts`. Use bare
18
- `requireAuth()` when any signed-in user may enter, and omit it entirely only for
19
- intentionally public routes.
20
- - Route-level `requireAuth` only hides the UI. Every server function or server route that
21
- accesses protected data still needs `authMiddleware`; see the `server-functions` skill.
22
- - Use `Route.useRouteContext()` to access the authenticated user. `user` can be `null` if
23
- the route doesn't include `requireAuth`.
24
- - Preload the route's live queries in the loader and return the promise:
25
- `loader: ({ context }) => context.dbClient.preloadLiveQuery(<x>QueryOptions)`. Detail
26
- routes await it and throw `notFound()` for a missing row; see the `client-db` skill.
27
- - Literal URL segments and feature folders use kebab-case. Entity feature names are plural;
28
- TanStack special route tokens retain their required syntax.
29
- - If a feature contains only one route, create a single file route: `src/routes/<feature>s.tsx`
30
- - If a feature contains multiple related routes, create a folder: `src/routes/<feature>s/index.tsx`
31
- - Colocate route-specific components/hooks inside `routes/<feature>s/-components` or `-hooks`.
32
- - When a route needs its own components/hooks that no sibling route uses, wrap it in a route
33
- group folder named after the route and colocate them there: `routes/<feature>s/(index)/index.tsx` with `(index)/-components` and `(index)/-hooks`.
34
- - Root-level `components/` and `hooks/` are only for code shared across multiple routes.
35
- - After creating a new route, add a navigation item with a unique icon from
36
- `@mui/icons-material` in `src/routes/__root.tsx`.
37
- - Hide a navigation entry from users who cannot open it: `hidden: !hasPermission(user, <key>)`
38
- with the same key as its route's `requireAuth(<key>)`.
39
- - For user-clickable in-app navigation, use the type-safe router components from
40
- `wcz-layout/components` (`RouterButton`, `RouterIconButton`, `RouterLink`, `RouterFab`,
41
- `RouterTab`, `RouterListItemButton`) rather than raw MUI with a manual `href` — they wrap
42
- `createLink`, so `to`/`params`/`search` are type-checked.
15
+ - Access: `beforeLoad: requireAuth("<key>")` with a key from `src/lib/auth/permissions.ts`, or
16
+ `requireAuth()` for any signed-in user; omit it only on intentionally public pages. It hides
17
+ the page; server functions guard themselves (server-functions). On a guarded route
18
+ `Route.useRouteContext().user` is a `User`, elsewhere `User | null`. `requireAuth` and
19
+ `hasPermission` come from `wcz-layout/utils`.
20
+ - Data: the loader returns `context.dbClient.preloadLiveQuery(…)` (client-db). A route
21
+ reading a suspense query sets `pendingComponent: <Entity>Skeleton`, MUI `Skeleton`s in the
22
+ page's own shape, from its `-components`. A missing row renders
23
+ `<RouterNotFound />` from the component.
24
+ - Names: feature folders and literal segments are kebab-case, entity features plural. One page
25
+ is `src/routes/<entities>.tsx`; several live in `src/routes/<entities>/` as `index.tsx`,
26
+ `$id.tsx`, `create.tsx`, `edit.$id.tsx`.
27
+ - Colocation: a feature's components and hooks go in `<entities>/-components` and `-hooks`.
28
+ Code only one of its routes uses goes in a group named after that route:
29
+ `<entities>/(index)/index.tsx` with `(index)/-components`. `src/components` and `src/hooks`
30
+ hold only code shared across features.
31
+ - One page per feature: narrow rows with filters or search params.
32
+ - Every new page gets a navigation item in `__root.tsx`: its own `@mui/icons-material` icon,
33
+ `title` through `t`, and `hidden: !hasPermission(user, "<key>")` with the route's key.
34
+ Kinds: `item` (`title`, `icon`, `to` with `params`/`search`, or `href` for an external URL),
35
+ `group` (`title`, `icon`, `children`), `header` (`title`), `divider`; all accept `hidden`.
36
+ - `LayoutProvider` in `__root.tsx` takes `theme`, `navigation` and `options`: `appBarActions`
37
+ (nodes between the app title and the account menu), `showShell` (app bar and navigation) and
38
+ `chat` (a chat docked beside every page; see the ai skill).
39
+ - Links a user clicks are `RouterLink`, `RouterButton`, `RouterIconButton`, `RouterFab`,
40
+ `RouterTab`, `RouterListItemButton` from `wcz-layout/components`: typed `to`/`params`/
41
+ `search`, MUI props, and hover preloads the target's loader. `useNavigate()` only after an
42
+ action, e.g. a save.
43
43
 
44
44
  ## Examples
45
45
 
46
46
  ```tsx
47
- // imports
48
- import AccountTree from "@mui/icons-material/AccountTree";
49
- import Code from "@mui/icons-material/Code";
50
- import Home from "@mui/icons-material/Home";
51
- import Widgets from "@mui/icons-material/Widgets";
52
- import { createFileRoute } from "@tanstack/react-router";
53
- import type { Navigation } from "wcz-layout";
54
- import { useDialogs, useTranslation } from "wcz-layout/hooks";
55
- import { hasPermission, requireAuth } from "wcz-layout/utils";
56
-
57
- // src/routes/<feature>s/index.tsx
58
- export const Route = createFileRoute("/<feature>s/")({
47
+ // src/routes/features/$id.tsx — detail page; edit.$id.tsx has the same route options (forms)
48
+ export const Route = createFileRoute("/features/$id")({
59
49
  component: RouteComponent,
50
+ pendingComponent: FeatureSkeleton,
60
51
  beforeLoad: requireAuth("admin"),
61
- loader: ({ context }) => context.dbClient.preloadLiveQuery(featuresQueryOptions),
52
+ loader: ({ context, params }) =>
53
+ context.dbClient.preloadLiveQuery(featureByIdQueryOptions(params.id)),
62
54
  });
63
55
 
64
56
  function RouteComponent() {
57
+ const { id } = Route.useParams();
65
58
  const { t } = useTranslation();
66
- const { alert, confirm } = useDialogs();
67
- const { user } = Route.useRouteContext();
68
- // route component code...
59
+ const { data } = useLiveSuspenseQuery(featureByIdQueryOptions(id));
60
+
61
+ if (!data) return <RouterNotFound />;
62
+
63
+ return (
64
+ <>
65
+ <Typography>{data.name}</Typography>
66
+ <RouterButton to="/features/edit/$id" params={{ id }} startIcon={<Edit />}>
67
+ {t("Edit")}
68
+ </RouterButton>
69
+ {/* Delete: confirm(), optimistic delete, when("settled"), navigate({ to: "/features" }) */}
70
+ </>
71
+ );
69
72
  }
73
+ ```
74
+
75
+ ```tsx
76
+ // src/routes/__root.tsx, inside RootDocument
77
+ const { user } = Route.useRouteContext();
70
78
 
71
- // __root.tsx navigation
72
79
  const navigation: Navigation = [
73
- { kind: "item", to: "/", title: t("Home"), icon: <Home /> },
74
- { kind: "header", title: t("Documentation") },
80
+ { kind: "item", to: "/", title: t("Homepage"), icon: <Home /> },
75
81
  {
76
- kind: "group",
77
- title: t("Components"),
82
+ kind: "item",
83
+ to: "/features",
84
+ title: t("Feature.Features"),
78
85
  icon: <Widgets />,
79
86
  hidden: !hasPermission(user, "admin"),
80
- children: [
81
- { kind: "item", to: "/components/navigation", title: t("Navigation"), icon: <AccountTree /> },
82
- { kind: "divider" },
83
- { kind: "item", to: "/components/forms", title: t("Forms"), icon: <Code /> },
84
- ],
85
87
  },
86
88
  ];
87
89
  ```
@@ -0,0 +1,67 @@
1
+ ---
2
+ name: scanning
3
+ description: "Use when a feature reads barcodes or QR codes, from a handheld laser scanner (keystrokes) via useScanDetection or from the device camera via @yudiel/react-qr-scanner."
4
+ metadata:
5
+ type: convention
6
+ library: wcz-layout
7
+ ---
8
+
9
+ ## Rules
10
+
11
+ - Laser scanners type the code as fast keystrokes. Catch them with `useScanDetection` from
12
+ `wcz-layout/hooks`, never a hidden input or an own `keydown` listener. It listens on
13
+ `document`, so nothing needs focus.
14
+ - `useScanDetection({ onComplete, ... })` options (defaults): `minLength` (1),
15
+ `averageWaitTime` (50 ms between keys, slower input counts as typing), `timeToEvaluate`
16
+ (100 ms), `startCharacter` (`[]`), `endCharacter` (`["Enter", "Escape"]`), `onError`,
17
+ `container` (`document`), `ignoreIfFocusOn`, `preventDefault` / `stopPropagation` (`false`),
18
+ `enabled` (`true`). Set `minLength` to the shortest valid code; use `enabled: false` while
19
+ scans must be ignored.
20
+ - Camera scanning always uses `Scanner` from `@yudiel/react-qr-scanner` (install if missing),
21
+ never another QR/barcode library. Rear camera, finder and torch are on by default. Always set:
22
+ - `constraints={{ width: { ideal: 1920 }, height: { ideal: 1080 } }}`: Full HD, the default
23
+ 720p misses small and dense codes.
24
+ - `formats`: only the symbologies the feature expects (`qr_code`, `code_128`, `ean_13`, …).
25
+ All formats are scanned by default, which is slower and misreads more.
26
+ - `onError`: alert `error.message` (permission denied, no camera, camera in use).
27
+ - Open the camera in a custom dialog that resolves with the first scanned value (see `dialogs`).
28
+ It needs HTTPS or `localhost`; the component is SSR-safe.
29
+ - Where both scanners may be used, keep `useScanDetection` on the page, add a camera button,
30
+ and send both results to the same handler.
31
+
32
+ ## Examples
33
+
34
+ ```tsx
35
+ import { Dialog, DialogContent, DialogTitle } from "@mui/material";
36
+ import { Scanner } from "@yudiel/react-qr-scanner";
37
+ import type { DialogProps } from "wcz-layout/hooks";
38
+ import { useDialogs, useScanDetection, useTranslation } from "wcz-layout/hooks";
39
+
40
+ // laser scanner
41
+ useScanDetection({ onComplete: handleCode, minLength: 8 });
42
+
43
+ // camera button
44
+ const { open } = useDialogs();
45
+ const code = await open(ScanDialog);
46
+ if (code) await handleCode(code);
47
+
48
+ // camera dialog
49
+ export const ScanDialog = ({ open, onClose }: DialogProps<undefined, string | undefined>) => {
50
+ const { t } = useTranslation();
51
+ const { alert } = useDialogs();
52
+
53
+ return (
54
+ <Dialog fullWidth open={open} onClose={() => onClose(undefined)}>
55
+ <DialogTitle>{t("Scan")}</DialogTitle>
56
+ <DialogContent>
57
+ <Scanner
58
+ constraints={{ width: { ideal: 1920 }, height: { ideal: 1080 } }}
59
+ formats={["qr_code", "code_128"]}
60
+ onScan={([code]) => onClose(code.rawValue)}
61
+ onError={(error) => alert(error.message)}
62
+ />
63
+ </DialogContent>
64
+ </Dialog>
65
+ );
66
+ };
67
+ ```
@@ -1,43 +1,70 @@
1
1
  ---
2
2
  name: server-functions
3
- description: "Use when adding or changing server functions, REST/API routes, background-job endpoints, or server-side data access."
3
+ description: "Use when adding or changing server-side code in app: server functions (createServerFn) that select or write data, their middleware, global request middleware (src/start.ts), validation, transactions and error messages, on-demand subset selects, REST/API routes, background-job endpoints, or deciding what client code may import from src/server."
4
4
  metadata:
5
5
  type: convention
6
6
  library: wcz-layout
7
7
  ---
8
8
 
9
- > Mechanics (`createServerFn`, `.validator`, `createMiddleware`, `createHandlers`) are covered by TanStack's own skills. List the skills shipped by `@tanstack/start-client-core` and `@tanstack/react-start` and load whichever cover the task at hand. This skill adds only the wcz-layout middleware conventions on top.
9
+ Mechanics (`createServerFn`, `.validator`, `createMiddleware`, server routes, `createHandlers`):
10
+ load `@tanstack/start-client-core#start-core` with its `server-functions`, `middleware` and
11
+ `server-routes` sub-skills. Our RPC entrypoints stay in `actions/<entity>.ts`, not
12
+ `*.functions.ts`; server-only helper protection still applies.
10
13
 
11
14
  ## Rules
12
15
 
13
- - Before generating code, clarify whether the feature should be exposed as public REST API routes or implemented as internal TanStack Start server functions (recommended), and what permission should be required for access.
14
- - Include `authMiddleware` in every server function by default — server functions are callable RPC endpoints, so a route-level `requireAuth` in `beforeLoad` only hides the UI and does not protect them. Omit it only for server functions backing intentionally public routes.
15
- - Order inside a middleware **array** matters, because the array runs in order and the later entry wins the merged context type. Always `databaseMiddleware()` → `authMiddleware(<permissionKey>)` → `validationMiddleware(<schema>)`. `databaseMiddleware` declares `userMiddleware` and so contributes `user: User | null`; putting it first lets `authMiddleware` narrow `context.user` to `User` for the handler. `authMiddleware` still comes before `validationMiddleware` — otherwise an unauthenticated caller gets their body parsed and gets your validation errors back.
16
- - The builder itself accepts its links in any order. Write them as `.validator()` → `.middleware()` → `.handler()` to match the reference app. Middleware always runs before the handler regardless of where it appears.
17
- - `validationMiddleware` is for REST API routes only. Server functions use `.validator()`.
18
- - `databaseMiddleware` is **app-local**, not a wcz-layout export. Every app writes it once (see below). It owns the transaction, so never open another one in a handler.
19
- - Reuse schemas from `src/lib/schemas/`.
20
- - Everything under `src/server/**` is server-only, but Start's import protection only guards `**/*.server.*` filenames. Never import from `src/server/` in a component or route file. Import the server function, not what it uses.
21
- - Background jobs are API routes with exactly `[databaseMiddleware(), authMiddleware()]` — plain `authMiddleware()`, no permission key. Cron runs in Kubernetes and authenticates via app token. This is intentional and sufficient: do not add any other extra security layer, even if any signed-in user could trigger the job.
16
+ - Default to internal server functions in `src/server/actions/<entity>.ts`. Build REST routes
17
+ (`src/routes/api/<entities>/`) only for a requested public API. Ask which permission guards
18
+ the functions when the task does not say.
19
+ - Every server function has `authMiddleware()` (any signed-in user) or
20
+ `authMiddleware("<key>")`, after `databaseMiddleware()` when it touches the database. Route
21
+ guards only hide pages; a server function is a public endpoint. Omit authentication only
22
+ for an intentionally public operation.
23
+ - Middleware arrays run in order; later entries override overlapping context properties:
24
+ `databaseMiddleware()` → `authMiddleware(key)` → `validationMiddleware(schema)` (REST only;
25
+ server functions use `.validator()`). `databaseMiddleware` brings `user: User | null` and
26
+ `authMiddleware` narrows it to `User`; auth before validation keeps validation errors from
27
+ anonymous callers.
28
+ - Start checks server functions for CSRF by default, but a `createStart` in `src/start.ts`
29
+ replaces that default: an app that adds the file (global middleware) puts `csrfMiddleware`
30
+ from `wcz-layout/middleware` first in `requestMiddleware`, never a hand-made origin check.
31
+ - Builders read `.validator(schema)` → `.middleware([...])` → `.handler()`. Every input has a
32
+ schema from `src/lib/schemas/` (a list of ids: `z.array(z.uuid())`).
33
+ - `databaseMiddleware` is app-local (`src/server/middleware/`, in the template): one
34
+ transaction per call as `context.db`, the acting user stamped for the audit trigger, and
35
+ Postgres errors rethrown as `Error(detail)`. Never open another transaction or import `db` in
36
+ a handler. Fail with `throw new Error(message)`; the client shows the message in `alert()`.
37
+ - Selects return rows of the collection's schema. Writes return nothing, the client refetches.
38
+ Inserts end with `.onConflictDoNothing({ target: table.id })`, so a replayed create is a
39
+ no-op.
40
+ - The select behind an on-demand collection is POST (a lazy join asks for `id IN (…)`, and a GET
41
+ URL with a thousand ids fails with 431), validates `createQuerySchema<Entity>()` from
42
+ `agnostic-query/zod` and returns `toDrizzle(context.db, table, data)` from
43
+ `agnostic-query/drizzle/pg` (example; more in `agnostic-query#adapters`). The type argument
44
+ types the rows: without it the collection's `queryFn` fails to type-check.
45
+ - Client and isomorphic code import from `src/server/` only server functions (`actions/`) and
46
+ table definitions (`db/schemas/`, for `createSelectSchema`). Import protection guards only
47
+ `*.server.*` filenames, so nothing else stops a wrong import. Logic shared by several handlers
48
+ goes in `src/server/<entity>.ts`, imported by actions only.
49
+ - Background jobs are API routes with exactly `[databaseMiddleware(), authMiddleware()]`:
50
+ Kubernetes cron calls them with an app token. Add no other security layer, even though any
51
+ signed-in user could trigger the job.
22
52
 
23
53
  ## Examples
24
54
 
25
55
  ```ts
26
- // src/server/actions/<table>.ts
27
- import { createFileRoute } from "@tanstack/react-router";
56
+ // src/server/actions/feature.ts
28
57
  import { createServerFn } from "@tanstack/react-start";
29
58
  import { eq, inArray } from "drizzle-orm";
30
- import { authMiddleware, validationMiddleware } from "wcz-layout/middleware";
59
+ import { authMiddleware } from "wcz-layout/middleware";
31
60
  import z from "zod";
32
61
  import { FeatureSchema } from "~/lib/schemas/feature";
33
62
  import { featureTable } from "../db/schemas/feature";
34
63
  import { databaseMiddleware } from "../middleware/databaseMiddleware";
35
64
 
36
65
  export const selectFeatures = createServerFn()
37
- .middleware([databaseMiddleware(), authMiddleware()])
38
- .handler(({ context }) => {
39
- return context.db.select().from(featureTable);
40
- });
66
+ .middleware([databaseMiddleware(), authMiddleware("admin")])
67
+ .handler(({ context }) => context.db.select().from(featureTable));
41
68
 
42
69
  export const insertFeature = createServerFn({ method: "POST" })
43
70
  .validator(FeatureSchema)
@@ -62,18 +89,36 @@ export const deleteFeatures = createServerFn({ method: "POST" })
62
89
  .handler(async ({ data, context }) => {
63
90
  await context.db.delete(featureTable).where(inArray(featureTable.id, data));
64
91
  });
92
+ ```
93
+
94
+ ```ts
95
+ // on-demand select (its collection: client-db, Sync mode)
96
+ import { toDrizzle } from "agnostic-query/drizzle/pg";
97
+ import { createQuerySchema } from "agnostic-query/zod";
98
+ import type { Feature } from "~/lib/schemas/feature";
99
+
100
+ export const selectFeatures = createServerFn({ method: "POST" })
101
+ .validator(createQuerySchema<Feature>())
102
+ .middleware([databaseMiddleware(), authMiddleware("admin")])
103
+ .handler(({ data, context }) => toDrizzle(context.db, featureTable, data));
104
+ ```
105
+
106
+ ```ts
107
+ // src/routes/api/features/index.ts
108
+ import { createFileRoute } from "@tanstack/react-router";
109
+ import { authMiddleware, validationMiddleware } from "wcz-layout/middleware";
110
+ import { FeatureSchema } from "~/lib/schemas/feature";
111
+ import { featureTable } from "~/server/db/schemas/feature";
112
+ import { databaseMiddleware } from "~/server/middleware/databaseMiddleware";
65
113
 
66
- // src/routes/api/<feature>s/index.ts
67
114
  export const Route = createFileRoute("/api/features/")({
68
115
  server: {
69
116
  handlers: ({ createHandlers }) =>
70
117
  createHandlers({
71
118
  GET: {
72
- middleware: [databaseMiddleware(), authMiddleware()],
73
- handler: async ({ context }) => {
74
- const items = await context.db.select().from(featureTable);
75
- return Response.json(items);
76
- },
119
+ middleware: [databaseMiddleware(), authMiddleware("admin")],
120
+ handler: async ({ context }) =>
121
+ Response.json(await context.db.select().from(featureTable)),
77
122
  },
78
123
  POST: {
79
124
  middleware: [
@@ -82,11 +127,11 @@ export const Route = createFileRoute("/api/features/")({
82
127
  validationMiddleware(FeatureSchema),
83
128
  ],
84
129
  handler: async ({ context }) => {
85
- const [response] = await context.db
130
+ const [created] = await context.db
86
131
  .insert(featureTable)
87
132
  .values(context.data)
88
133
  .returning();
89
- return Response.json(response, { status: 201 });
134
+ return Response.json(created, { status: 201 });
90
135
  },
91
136
  },
92
137
  }),
@@ -10,9 +10,10 @@ metadata:
10
10
 
11
11
  You can read about each service in the links below. Services are categorized as either client or server exports, depending on their intended usage.
12
12
 
13
- - **Client exports** — React Query option factories from `wcz-layout/data/client`.
13
+ - **Client exports** — TanStack Query options from `wcz-layout/data/client`.
14
14
  - **Server exports** — Direct service operations from `wcz-layout/data/server`; import them only in server code.
15
- - Invalidating mutation factories take `{ queryClient }`.
15
+ - Client exports marked `server fn (RPC)` are TanStack Start server functions callable from the client; use them as `queryFn` in a TanStack DB collection.
16
+ - Invalidating mutation options take `{ queryClient }`.
16
17
  - Access `queryClient` with `Route.useRouteContext()` in a route file, or `useRouteContext({ from: "path" })` in a component.
17
18
  - To read about a service, open the linked file in the **File** column directly.
18
19
 
@@ -21,6 +22,7 @@ You can read about each service in the links below. Services are categorized as
21
22
  - Client exports: `wcz-layout/data/client`
22
23
  - Server exports: `wcz-layout/data/server`
23
24
  - Schemas & Models: `wcz-layout/models`
25
+ - In service docs, inputs are referenced by schema name (`Schema`) and return values by model type (`Model` = `z.infer<typeof Schema>`); both are defined in each doc's **Schemas/Models** section.
24
26
 
25
27
  ## Services
26
28
 
@@ -30,5 +32,3 @@ You can read about each service in the links below. Services are categorized as
30
32
  | approval | [approval.md](docs/approval.md) | Approval request lifecycle, approvers, flows, statuses, step results |
31
33
  | peoplesoft | [peoplesoft.md](docs/peoplesoft.md) | Employee, manager, department, and company general manager lookups |
32
34
  | email | [email.md](docs/email.md) | Server-only email sending with optional file attachment references |
33
-
34
- > The attendance service is not available yet — do not generate code against it; tell the user it is coming in a future release.
@@ -2,27 +2,31 @@
2
2
 
3
3
  ## Client
4
4
 
5
+ `import { ... } from "wcz-layout/data/client";`
6
+
5
7
  - Query:
6
- `approvalsQueryOptions`
7
- `approvalQueryOptions`
8
+ `approvalsQueryOptions(GetApprovalsSchema)` → `Approval[]` // approvals of the application, optionally filtered; `appName` is sent as `applicationName`
9
+ `approvalQueryOptions(GetApprovalSchema)` → `Approval` // single approval
8
10
  - Mutation:
9
- `createApprovalMutationOptions`
10
- `approveApprovalMutationOptions`
11
- `resubmitApprovalMutationOptions`
12
- `withdrawApprovalMutationOptions`
13
- `cancelApprovalMutationOptions`
11
+ `createApprovalMutationOptions({ queryClient })` → `mutate(CreateApprovalSchema)` → `Approval` // create a new approval request
12
+ `approveApprovalMutationOptions({ queryClient })` → `mutate(ApproveApprovalSchema)` → `Approval` // current approver's decision (`"Approved"` / `"Rejected"`) on the active step
13
+ `resubmitApprovalMutationOptions({ queryClient })` → `mutate(ResubmitApprovalSchema)` → `Approval` // resubmit with new flows (same flow shape as create)
14
+ `withdrawApprovalMutationOptions({ queryClient })` → `mutate(WithdrawApprovalSchema)` → `void` // withdraw the request
15
+ `cancelApprovalMutationOptions({ queryClient })` → `mutate(CancelApprovalSchema)` → `void` // cancel the request
14
16
 
15
17
  ## Server
16
18
 
19
+ `import { ... } from "wcz-layout/data/server";`
20
+
17
21
  - Fetch:
18
- `getApprovals`
19
- `getApproval`
22
+ `getApprovals({ data: GetApprovalsSchema })` → `Approval[]` // approvals of the application, optionally filtered
23
+ `getApproval({ data: GetApprovalSchema })` → `Approval` // single approval
20
24
  - Mutate:
21
- `createApproval`
22
- `approveApproval`
23
- `resubmitApproval`
24
- `withdrawApproval`
25
- `cancelApproval`
25
+ `createApproval({ data: CreateApprovalSchema })` → `Approval` // create a new approval request
26
+ `approveApproval({ data: ApproveApprovalSchema })` → `Approval` // approve / reject the active step
27
+ `resubmitApproval({ data: ResubmitApprovalSchema })` → `Approval` // resubmit with new flows
28
+ `withdrawApproval({ data: WithdrawApprovalSchema })` → `void` // withdraw the request
29
+ `cancelApproval({ data: CancelApprovalSchema })` → `void` // cancel the request
26
30
 
27
31
  ## Schemas/Models
28
32
 
@@ -57,12 +61,17 @@ const ApprovalEmployeeSchema = z.object({
57
61
  email: z.email().min(1).max(100),
58
62
  });
59
63
 
64
+ const ApprovalProxySchema = z.object({
65
+ proxy: ApprovalEmployeeSchema,
66
+ });
67
+
60
68
  const ApprovalFlowStepSchema = z.object({
61
69
  id: z.uuid(),
62
70
  order: z.number(),
63
71
  approverRole: z.string().trim().min(1).max(100).default("Approver").optional(),
64
72
  approver: ApprovalEmployeeSchema,
65
73
  actualApprover: ApprovalEmployeeSchema.optional(),
74
+ proxies: z.array(ApprovalProxySchema),
66
75
  result: ApprovalStepResult.default("NotAvailable").optional(),
67
76
  resultDate: z.date().optional(),
68
77
  resultComment: z.string().trim().max(2000).optional(),
@@ -74,7 +83,7 @@ const ApprovalFlowSchema = z.object({
74
83
  batchSequence: z.number().optional(),
75
84
  approvalSequence: z.number(),
76
85
  stepApprovalOrder: StepApprovalOrder,
77
- steps: z.array(ApprovalFlowStepSchema),
86
+ steps: z.array(z.custom<ApprovalFlowStep>()),
78
87
  isActive: z.boolean().default(false).optional(),
79
88
  });
80
89
 
@@ -164,7 +173,9 @@ const ApprovalSchema = z.object({
164
173
  updated: z.date().optional(),
165
174
  updatedBy: z.custom<ApprovalEmployee>().optional(),
166
175
  approvalFlows: z.array(z.custom<ApprovalFlow>()).min(1),
167
- currentApprovers: z.array(z.custom<ApprovalEmployee>()),
176
+ currentApprovers: z.array(
177
+ ApprovalEmployeeSchema.extend({ proxies: z.array(ApprovalProxySchema) }),
178
+ ),
168
179
  coRequestors: z.array(ApprovalCoRequestorSchema).optional(),
169
180
  });
170
181
 
@@ -197,7 +208,7 @@ const CreateApprovalSchema = ApprovalSchema.pick({
197
208
  stepApprovalOrder: true,
198
209
  steps: true,
199
210
  }).extend({
200
- steps: z.array(ApprovalFlowStepSchema.pick({ approverRole: true, approver: true })),
211
+ steps: z.array(ApprovalFlowStepSchema.pick({ approverRole: true, approver: true })).min(1),
201
212
  }),
202
213
  )
203
214
  .min(1),
@@ -224,7 +235,7 @@ const ResubmitApprovalSchema = ApprovalSchema.pick({
224
235
  stepApprovalOrder: true,
225
236
  steps: true,
226
237
  }).extend({
227
- steps: z.array(ApprovalFlowStepSchema.pick({ approverRole: true, approver: true })),
238
+ steps: z.array(ApprovalFlowStepSchema.pick({ approverRole: true, approver: true })).min(1),
228
239
  }),
229
240
  )
230
241
  .min(1),
@@ -246,13 +257,48 @@ const WithdrawApprovalSchema = z.object({
246
257
  ## Examples
247
258
 
248
259
  ```ts
249
- import { approvalQueryOptions, approveApprovalMutationOptions } from "wcz-layout/data/client";
250
- import { approveApproval } from "wcz-layout/data/server";
251
-
252
- // client
260
+ import {
261
+ approvalQueryOptions,
262
+ approvalsQueryOptions,
263
+ approveApprovalMutationOptions,
264
+ createApprovalMutationOptions,
265
+ } from "wcz-layout/data/client";
266
+ import { createApproval } from "wcz-layout/data/server";
267
+ import { uuidv7 } from "wcz-layout/utils";
268
+
269
+ const { queryClient } = Route.useRouteContext();
270
+
271
+ // fetch
272
+ const { data: approvals = [] } = useQuery(
273
+ approvalsQueryOptions({ appName: packageJson.name, status: "WaitingForApproval" }),
274
+ );
253
275
  const { data: approval } = useQuery(approvalQueryOptions({ id }));
276
+
277
+ // create
278
+ const { mutate: create } = useMutation(createApprovalMutationOptions({ queryClient }));
279
+
280
+ create({
281
+ id: uuidv7(),
282
+ number: "REQ-0001",
283
+ applicationName: packageJson.name,
284
+ status: "WaitingForApproval",
285
+ emailBody: "<p>Please approve REQ-0001.</p>",
286
+ approvalFlows: [
287
+ {
288
+ approvalStage: 1,
289
+ stepApprovalOrder: "Serial",
290
+ steps: [{ approver: { employeeId, name, email } }],
291
+ },
292
+ ],
293
+ });
294
+
295
+ // approve / reject
254
296
  const { mutate: approve } = useMutation(approveApprovalMutationOptions({ queryClient }));
255
297
 
256
- // server
257
- await approveApproval({ data: { id, result: "Approved", emailBody } });
298
+ approve({ id, result: "Approved", emailBody: "<p>REQ-0001 was approved.</p>" });
299
+
300
+ // server (inside another server function)
301
+ const created = await createApproval({
302
+ data: { id, number, applicationName, status, emailBody, approvalFlows },
303
+ });
258
304
  ```
@@ -2,7 +2,11 @@
2
2
 
3
3
  ## Server
4
4
 
5
- - `sendEmail`
5
+ `import { ... } from "wcz-layout/data/server";`
6
+
7
+ - `sendEmail({ data: EmailSchema })` → `void` // server-only, call inside another server function
8
+ - `body` // HTML string
9
+ - `attachments` // `appName` + `subId` used when uploading the files (see [file.md](file.md)); the email service attaches all files stored under that `subId`
6
10
 
7
11
  ## Schemas/Models
8
12
 
@@ -27,6 +31,23 @@ const EmailAttachmentSchema = z.object({
27
31
  ```ts
28
32
  import { sendEmail } from "wcz-layout/data/server";
29
33
 
30
- // server
31
- await sendEmail({ data: { subject: "Hello", body: "<p>Hi</p>", to: ["user@example.com"] } });
34
+ // inside another server function
35
+ await sendEmail({
36
+ data: {
37
+ subject: "Hello",
38
+ body: "<p>Hi</p>",
39
+ to: ["user@example.com"],
40
+ },
41
+ });
42
+
43
+ // with cc and attachments (files previously uploaded with uploadFileMutationOptions({ appName, subId, file }))
44
+ await sendEmail({
45
+ data: {
46
+ subject: "Document Submission",
47
+ body: "<p>Attached are the requested documents.</p>",
48
+ to: ["recipient@example.com"],
49
+ cc: ["team@example.com"],
50
+ attachments: [{ appName: packageJson.name, subId }],
51
+ },
52
+ });
32
53
  ```