feat/frontend-phase2 #9

Merged
mihir merged 4 commits from feat/frontend-phase2 into main 2026-11-12 00:36:31 +05:30
50 changed files with 6826 additions and 109 deletions

View File

@ -3,6 +3,13 @@ type: docker
name: Build Image name: Build Image
steps: steps:
- name: Quality gates
image: node:24-alpine
commands:
- npm ci
- npm audit --audit-level=high
- npm run check
- name: Build Docker Image - name: Build Docker Image
image: plugins/docker image: plugins/docker
settings: settings:

1
AGENTS.md Normal file
View File

@ -0,0 +1 @@
Read CONSTRAINTS.md before writing code. Do not weaken it to make a change pass.

10
CHANGELOG.md Normal file
View File

@ -0,0 +1,10 @@
# Changelog
## Phase 2 — 13 October 2026
- Add private addresses, versioned carts, reviewed/idempotent checkout, own and staff order history/details/cancellation.
- Add permission-gated user/role/audit, product/group/variant, finished-stock/warehouse/ledger/reservation, coupon and pricing tools.
- Add account recovery/reset with fragment-token removal.
- Fix decimal output compatibility, immediate private session cleanup, permission downgrade privacy and stale request/intent races.
- Add lazy routes, build-size gate, lint/component/workflow/accessibility tests, dependency audit in CI and Nginx security headers.
- Production acceptance still requires provisioned UAT accounts, approved pricing/SMTP and verified deployment/rollback.

17
CONSTRAINTS.md Normal file
View File

@ -0,0 +1,17 @@
# Production quality constraints
Reviewed 12 October 2026. User accepted strict types, workflow tests, security, keyboard/responsive and deployment/rollback checks; no UAT account is provisioned yet.
| Gate | Required result | Evidence |
| ------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| Types | Zero errors, strict mode retained | npm run typecheck |
| Lint | Zero errors on source/tests | npm run lint |
| Tests | All contract/workflow/component tests pass; no skipped tests | npm test |
| Dependency security | Zero high/critical findings | npm audit --audit-level=high |
| Build | Successful; no oversized chunk warnings; each JS chunk below 500 kB | npm run build |
| Accessibility | Keyboard flows, labels/errors, contrast; zero serious/critical axe findings on tested routes | component accessibility tests and browser checklist |
| Responsive | No horizontal overflow at 320, 768, 1024, 1440 px | Browser UAT evidence |
| Deployment | Nginx validates; container/deep links/API verified; HTTPS ingress | container smoke checks + deployed UAT |
| Release | No unresolved critical/high defects; permissions/privacy/conflicts exercised; rollback verified | docs/RELEASE-CHECKLIST.md |
No new type/lint suppressions, unimplemented stubs, disabled tests or secrets. Do not weaken these gates to make changes pass. Pending environment checks stay pending and block a production-ready claim. Backend business rules, tax/shipping policy approval, SMTP, account provisioning and deployment access remain explicit external gates.

View File

@ -8,7 +8,7 @@ RUN npm ci
COPY . . COPY . .
RUN npm run typecheck && npm test && npm run build RUN npm run check
FROM nginx:alpine FROM nginx:alpine
@ -16,6 +16,7 @@ RUN apk add --no-cache ca-certificates
COPY --from=build /app/dist /usr/share/nginx/html COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d/default.conf
RUN nginx -t
EXPOSE 80 EXPOSE 80

View File

@ -1,6 +1,6 @@
# Mani Candles frontend # Mani Candles frontend
The existing ManiCandles site upgraded against the deployed Nest API. Its purple/gold design, branding, and marketing pages are retained. Phase 1 connects catalog discovery, variants, staff sessions, organization setup and health checks. The existing ManiCandles site upgraded against the deployed Nest API. Its purple/gold design, branding, and marketing pages are retained. Phase 2 adds customer commerce, permission-gated administration, account recovery and enforced release checks.
## Development ## Development
@ -29,6 +29,10 @@ The existing main-branch Drone pipeline deploys automatically on push. Work is o
Storefront list returns only id/name/slug; details return prices/attributes/groups. The API has no product-media fields, so catalog cards use a generic branded placeholder rather than assigning local photos to unknown records. Existing marketing imagery remains intact. Storefront list returns only id/name/slug; details return prices/attributes/groups. The API has no product-media fields, so catalog cards use a generic branded placeholder rather than assigning local photos to unknown records. Existing marketing imagery remains intact.
Cart/checkout, registration and admin/operations tools are subsequent phases. There is no contact-message endpoint; simulated success was replaced with an availability notice. Newsletter signup awaits consent/messaging flows. Addresses, cart/checkout, orders, catalog, access, stock, coupons and pricing tools are available after sign-in. Public registration and procurement/production/B2B tools remain subsequent phases. There is no contact-message endpoint; simulated success was replaced with an availability notice. Newsletter signup awaits consent/messaging flows.
See [delivery phases](docs/PHASES.md) and [UAT evidence](docs/UAT-RESULTS.md). See [delivery phases](docs/PHASES.md) and [UAT evidence](docs/UAT-RESULTS.md).
Phase 2 commands: `npm run check` runs lint, strict types, contract/component/workflow tests and the measured production build. Dependency security is checked with `npm audit --audit-level=high` in CI. See [Phase 2 evidence](docs/UAT-PHASE2.md) and [release checklist](docs/RELEASE-CHECKLIST.md).
Set the backend RECOVERY_URL to your HTTPS frontend /reset-password route. Pending checkout and stock commands survive navigation within an active session; reload discards local credentials and intents. If interrupted, check orders/ledger before starting a new command.

View File

@ -2,14 +2,14 @@
Canonical implementation: this checkout from ssh://git@git.midastix.com:2212/internal/ManiCandles.git. The standalone frontend created earlier is superseded for ongoing development. Canonical implementation: this checkout from ssh://git@git.midastix.com:2212/internal/ManiCandles.git. The standalone frontend created earlier is superseded for ongoing development.
| Phase | Scope | Acceptance gate | | Phase | Scope | Acceptance gate |
| --- | --- | --- | | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| 1 — Existing-site foundation | Preserve branding, connect home/catalog/search/pagination/variants, staff login/me/logout/expiry, organization setup, health checks, API proxy and SPA routing | Real published records and approved account; loading/empty/failure states; keyboard and responsive verification | | 1 — Existing-site foundation | Preserve branding, connect home/catalog/search/pagination/variants, staff login/me/logout/expiry, organization setup, health checks, API proxy and SPA routing | Real published records and approved account; loading/empty/failure states; keyboard and responsive verification |
| 2 — Commerce and administration | Users/roles/audit, products/groups/variants/stock, addresses/cart/coupons/checkout/orders, recovery | Permission failures, conflicts, exact totals and expiry; no simulated live payment | | 2 — Commerce and administration | Users/roles/audit, products/groups/variants/stock, addresses/cart/coupons/checkout/orders, recovery | Permission failures, conflicts, exact totals and expiry; no simulated live payment |
| 3 — Procurement and production | Suppliers/materials, POs/receipts/QC, invoices/payments/documents, BOMs/batches/usage/packaging/costing, warehouse stock | Supplier-to-finished-goods journey; independent review; partials/idempotency; stock invariants | | 3 — Procurement and production | Suppliers/materials, POs/receipts/QC, invoices/payments/documents, BOMs/batches/usage/packaging/costing, warehouse stock | Supplier-to-finished-goods journey; independent review; partials/idempotency; stock invariants |
| 4 — B2B | Verification, price lists/MOQ, quotes/credit/samples/artwork, partner orders/payments, custom requests/reports | Independent approvals, expiry, reversals and currency/account boundaries | | 4 — B2B | Verification, price lists/MOQ, quotes/credit/samples/artwork, partner orders/payments, custom requests/reports | Independent approvals, expiry, reversals and currency/account boundaries |
| 5 — Growth and reporting | Wishlist/reviews, campaigns/discounts, recovery/consent, blog/segments/forum, analytics/forecast/accounting | Publication/moderation, consent, private data and report verification | | 5 — Growth and reporting | Wishlist/reviews, campaigns/discounts, recovery/consent, blog/segments/forum, analytics/forecast/accounting | Publication/moderation, consent, private data and report verification |
| 6 — Complete UAT and release | Dedicated deployment, disposable fixtures, role matrix, end-to-end scripts, accessibility/security review, defect retests and release/rollback runbook | Critical journeys pass; no critical/high defects; owner acceptance | | 6 — Complete UAT and release | Dedicated deployment, disposable fixtures, role matrix, end-to-end scripts, accessibility/security review, defect retests and release/rollback runbook | Critical journeys pass; no critical/high defects; owner acceptance |
## Phase 1 setup ## Phase 1 setup
@ -22,3 +22,7 @@ Enter the UUID at `/connection`, then credentials at `/workspace`. Published pro
Reference: deployed `/api/docs-json` and backend source API guides. Storefront lists are arrays; detail includes decimal price strings, currency, attributes and nested groups. Zod validates returned shapes. Errors preserve code/requestId. React escapes API content; request timeout is 15 seconds. Session tokens/passwords are not persisted. UUID is configuration, not an authorization boundary; backend permissions remain authoritative. Reference: deployed `/api/docs-json` and backend source API guides. Storefront lists are arrays; detail includes decimal price strings, currency, attributes and nested groups. Zod validates returned shapes. Errors preserve code/requestId. React escapes API content; request timeout is 15 seconds. Session tokens/passwords are not persisted. UUID is configuration, not an authorization boundary; backend permissions remain authoritative.
Use existing MUI theme and React Query. Query keys include organization. Search is bounded to 100 characters; catalog pages contain 12 records and respect the API offset cap. No product-image mapping is invented. Nginx forwards `/api/` to the known HTTPS upstream, verifies TLS and handles SPA deep links. No public owner/account creation is exposed. Use existing MUI theme and React Query. Query keys include organization. Search is bounded to 100 characters; catalog pages contain 12 records and respect the API offset cap. No product-image mapping is invented. Nginx forwards `/api/` to the known HTTPS upstream, verifies TLS and handles SPA deep links. No public owner/account creation is exposed.
## Phase 2 implementation status — 12 October 2026
Customer and administration screens are implemented, with recovery, pricing, stock lifecycle and quality gates. See UAT-PHASE2.md and RELEASE-CHECKLIST.md. Authenticated UAT, container/ingress verification and production sign-off remain pending; Phase 3 has not started.

41
docs/RELEASE-CHECKLIST.md Normal file
View File

@ -0,0 +1,41 @@
# Phase 2 release checklist
Production release is blocked until the environment checks below pass. Local implementation verification does not replace authenticated UAT or deployment acceptance.
## Code gates
- [x] Purpose-built customer and administration routes, with session/permission guards.
- [x] Exact decimal display, strict write inputs, validated response shapes.
- [x] Private caches and requests cleared on logout, expiry, organization change and permission downgrade.
- [x] Stale responses cannot invalidate a newer session or remove its pending command.
- [x] Cart writes serialize locally; stale versions require review.
- [x] Checkout confirmation uses the reviewed version; unknown results retain the same payload/key across navigation.
- [x] Adjustment/reservation intents stay in session memory for exact retries; session termination discards them.
- [x] Order charges use authoritative server totals; null means unfinalized, not zero; payment collection stays unavailable.
- [x] Recovery tokens captured once in memory and removed from browser history; never persisted or logged.
- [x] Destructive lifecycle actions have confirmation; system/owner/self restrictions remain enforced by the backend.
- [x] Strict TypeScript, lint without warnings, all tests passing, build below the 500 kB per-chunk budget.
- [x] Dependency audit has no reported vulnerabilities.
- [x] CI runs dependency audit and npm run check on pushes/PRs; Docker validates Nginx syntax during build.
- [x] No new type/lint suppressions, skipped tests, debug logging or source credentials.
## Environment and acceptance gates — pending
- [ ] Provision the installation owner on the intended UAT backend host/database; record organizationId. Never run local bootstrap against an unknown database.
- [ ] Provision least-privilege UAT staff and customer accounts, including denied/suspended accounts and independent reviewer roles.
- [ ] Exercise actual catalog/group/variant creation and publication, warehouse opening stock, private address/cart, coupon and checkout/order journeys against the deployed backend.
- [ ] Verify cross-account privacy, revoked sessions, changed permissions, concurrent carts, stock contention, duplicate retries and order expiry in live UAT.
- [ ] Configure approved pricing policies and SMTP; verify recovery delivery and one-time token expiry/reset.
- [ ] Build/run the container and test /workspace, /cart, /admin/catalog deep links; inspect CSP, certificate verification and /api health responses.
- [ ] Verify HTTPS ingress, HSTS, trusted proxy/rate-limit policy and deployment secrets. Nginx forwards /api over verified HTTPS; frontend does not change backend trust-proxy policy.
- [ ] Test complete populated screens in browsers at 320/768/1024/1440 widths; full keyboard/dialog/screen-reader/contrast checks and deployed axe/Lighthouse runs.
- [ ] Verify production Core Web Vitals, expected traffic, infrastructure logs/alerts and privacy-safe client error collection. APPLICATION_RENDER_FAILED is the safe local render diagnostic; API requestId correlates service errors.
- [ ] Confirm remote CI passes, observe deployment health/error/latency metrics, rehearse rollback, and obtain owner sign-off.
## Rollback
Record the immutable deployed image digest and previous known-good digest before rollout. On the deployment host, use the existing deployment mechanism to restore the previous frontend image, then verify health, SPA deep links and /api connectivity. No backend schema changes are included; retain orders, stock ledgers and accounts. Do not reset or delete database records. Confirm the actual host procedure and measured rollback time in UAT before production. A feature-branch push does not deploy the main-branch pipeline.
## Operational limits
Pending intents exist only within the active browser session; reloading signs out and discards them. After interruption, inspect orders or the stock ledger before beginning a new intent. The backend currently has no live gateway/carrier, public registration or contact delivery. Staff catalog/role writes follow the backend's existing concurrency policy; coordinate overlapping administration edits. Never reinterpret finalized merchandise as proof of payment or fulfillment.

7
docs/SPEC-phase2.md Normal file
View File

@ -0,0 +1,7 @@
# Phase 2 — commerce and administration
Preserve the existing brand/theme; add purpose-built MUI customer and administration screens. Modules: session boundary → addresses/cart/orders; session/permissions → users/roles/audit, catalog, stock, coupons/pricing; recovery is public and clears fragment secrets from history. Backend remains authoritative. Production payment collection and public registration are unavailable.
Build in slices: (1) schemas/exact decimal and session privacy; (2) addresses/cart/idempotent checkout/order lifecycle; (3) user/role/audit and catalog/variant/group management; (4) inventory, coupons/pricing and recovery; (5) lint/tests/accessibility/security, chunk budgets, CI/container/release runbook.
Acceptance: valid decimal output including integers; two-decimal write inputs; cache cancellation/removal and request generation isolation on logout/expiry/revocation; serialized cart writes with conflict refetch; checkout timeout retries retain identical intent/key; nullable charges remain unfinalized; permission-gated UI plus backend checks; independent account/role safeguards; no fake successes; all CONSTRAINTS.md gates have recorded outcomes. Existing accounts are provisioned by backend CLI/staff APIs; live UAT cannot pass until account setup.

19
docs/UAT-PHASE2.md Normal file
View File

@ -0,0 +1,19 @@
# Phase 2 implementation verification — 13 October 2026
Final local gate: 30 tests passed, strict TypeScript and lint passed, production build passed with all 27 JavaScript chunks below 500 kB (largest approximately 494 kB). The dependency audit reported zero vulnerabilities.
| Area | Evidence / outcome |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Contract | Deployed Swagger exposes cart, checkout, addresses, users, roles, admin orders, pricing and coupon routes; backend stores/schemas determine response and mutation contracts. |
| Automated tests | Contract tests cover exact decimal strings, persisted metadata, strict inputs, coupon limits/windows, recovery fragment cleanup and error diagnostics. Component/workflow tests cover session privacy, expiry, permission downgrade, stale responses, navigation-safe checkout retry, changed-cart review and nullable order charges. |
| Accessibility | Axe on the permission-denied workspace reports no serious/critical findings. JSDOM color-contrast execution is unavailable; color contrast and populated-route browser axe remain a deployed acceptance gate. |
| Browser routes | Addresses/orders/access/roles/catalog/inventory/coupons/pricing/audit all show the sign-in gate with no private input forms when unauthenticated. No captured errors on those route checks. |
| Responsive | Cart shell checked at 320, 768, 1024, 1440; document width did not exceed viewport. Populated authenticated screens still require live UAT. |
| Recovery | Invalid organization input showed a field-associated local validation error; no recovery email was sent. |
| Build/performance | Routes load lazily; JavaScript chunks are measured by scripts/check-build.mjs and must remain below 500,000 bytes. No oversized-chunk warnings are accepted. |
| Dependency audit | No reported vulnerabilities with the finalized npm lockfile. |
| Independent review | Three bounded adversarial cycles. Decimal handling, session cleanup/revocation, intent persistence, reviewed-version concurrency, permissions cache erasure and cancellation/session races were reconciled and guarded by tests. User chose independent review plus tests without external cross-model execution. |
| Deployment | Nginx CSP/frame/referrer/type headers and verified HTTPS API proxy added; CI quality gates and image-build nginx -t added. No local Docker runtime was available; container/ingress execution and remote CI remain unverified. |
| Live authenticated UAT | Pending: user confirmed no organization/account setup. No account was created, data seeded, mail sent, payment collected or deployment performed. |
See RELEASE-CHECKLIST.md for production acceptance gates. Previous Phase 1 results remain historical in UAT-RESULTS.md.

BIN
docs/phase2-preview.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

23
eslint.config.js Normal file
View File

@ -0,0 +1,23 @@
import tseslint from "typescript-eslint";
import reactHooks from "eslint-plugin-react-hooks";
export default tseslint.config(
{ ignores: ["dist/**", "node_modules/**", ".yarn/**"] },
...tseslint.configs.recommended,
{
files: ["**/*.ts", "**/*.tsx"],
plugins: { "react-hooks": reactHooks },
rules: {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "error",
"@typescript-eslint/no-unused-vars": [
"error",
{
argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
ignoreRestSiblings: true,
},
],
},
},
);

View File

@ -5,6 +5,8 @@ server {
index index.html; index index.html;
add_header X-Content-Type-Options nosniff always; add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy strict-origin-when-cross-origin always; add_header Referrer-Policy strict-origin-when-cross-origin always;
add_header X-Frame-Options DENY always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https://www.transparenttextures.com; connect-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
location /api/ { location /api/ {
proxy_pass https://manicandles-backend.midastix.com; proxy_pass https://manicandles-backend.midastix.com;

2232
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -5,10 +5,12 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite --config vite.config.ts", "dev": "vite --config vite.config.ts",
"build": "vite build --config vite.config.ts", "build": "vite build --config vite.config.ts && node scripts/check-build.mjs",
"serve": "vite preview --config vite.config.ts", "serve": "vite preview --config vite.config.ts",
"typecheck": "tsc -p tsconfig.json --noEmit", "typecheck": "tsc -p tsconfig.json --noEmit",
"test": "node --test test/*.test.ts" "test": "node --test test/*.test.ts && vitest run --config vitest.config.ts",
"lint": "eslint src test --max-warnings=0",
"check": "npm run lint && npm run typecheck && npm test && npm run build"
}, },
"engines": { "engines": {
"node": ">=24 <25" "node": ">=24 <25"
@ -17,6 +19,7 @@
"devDependencies": { "devDependencies": {
"@emotion/react": "^11.11.4", "@emotion/react": "^11.11.4",
"@emotion/styled": "^11.11.5", "@emotion/styled": "^11.11.5",
"@eslint/js": "^10.0.1",
"@hookform/resolvers": "^3.10.0", "@hookform/resolvers": "^3.10.0",
"@mui/icons-material": "^5.15.15", "@mui/icons-material": "^5.15.15",
"@mui/material": "^5.15.15", "@mui/material": "^5.15.15",
@ -49,17 +52,23 @@
"@radix-ui/react-tooltip": "^1.2.0", "@radix-ui/react-tooltip": "^1.2.0",
"@tailwindcss/vite": "^4.1.6", "@tailwindcss/vite": "^4.1.6",
"@tanstack/react-query": "^5.56.2", "@tanstack/react-query": "^5.56.2",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.7",
"@types/node": "^22.5.5", "@types/node": "^22.5.5",
"@types/react": "^18.3.5", "@types/react": "^18.3.5",
"@types/react-dom": "^18.3.0", "@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.7.0", "@vitejs/plugin-react": "^4.7.0",
"axe-core": "^4.14.0",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
"date-fns": "^3.6.0", "date-fns": "^3.6.0",
"embla-carousel-react": "^8.6.0", "embla-carousel-react": "^8.6.0",
"eslint": "^10.12.0",
"eslint-plugin-react-hooks": "^7.1.1",
"framer-motion": "^11.9.0", "framer-motion": "^11.9.0",
"input-otp": "^1.4.2", "input-otp": "^1.4.2",
"jsdom": "^30.1.2",
"lucide-react": "^0.469.0", "lucide-react": "^0.469.0",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"react": "^18.3.1", "react": "^18.3.1",
@ -74,9 +83,11 @@
"tailwindcss": "^4.1.6", "tailwindcss": "^4.1.6",
"tw-animate-css": "^1.4.0", "tw-animate-css": "^1.4.0",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"typescript-eslint": "^8.71.1",
"vaul": "^1.1.2", "vaul": "^1.1.2",
"vite": "^6.4.4", "vite": "^6.4.4",
"vitest": "^5.0.3",
"wouter": "^3.3.5", "wouter": "^3.3.5",
"zod": "^3.23.8" "zod": "^4.6.7"
} }
} }

17
scripts/check-build.mjs Normal file
View File

@ -0,0 +1,17 @@
import { readdir, stat } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import assert from "node:assert/strict";
const assets = new URL("../dist/assets/", import.meta.url);
const files = (await readdir(assets)).filter((file) => file.endsWith(".js"));
assert(files.length > 0, "No built JavaScript assets were found.");
for (const file of files) {
const size = (await stat(join(fileURLToPath(assets), file))).size;
assert(
size < 500000,
`${file} exceeds the 500 kB chunk budget (${size} bytes).`,
);
}
console.log(
`Build budget passed: ${files.length} JavaScript chunks below 500 kB.`,
);

View File

@ -1,50 +1,94 @@
import { lazy, Suspense } from "react";
import { Switch, Route, Router as WouterRouter } from "wouter"; import { Switch, Route, Router as WouterRouter } from "wouter";
import NotFound from "@/pages/not-found";
import { Layout } from "@/components/Layout"; import { Layout } from "@/components/Layout";
import Home from "@/pages/home";
import ProductsPage from "@/pages/ProductsPage";
import AboutPage from "@/pages/AboutPage";
import ContactPage from "@/pages/ContactPage";
import ProductPage from "@/pages/ProductPage";
import WorkspacePage from "@/pages/WorkspacePage";
import ConnectionPage from "@/pages/ConnectionPage";
import { PlatformProvider } from "@/lib/platform"; import { PlatformProvider } from "@/lib/platform";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import LinearProgress from "@mui/material/LinearProgress";
import { ErrorBoundary } from "@/components/ErrorBoundary";
const Home = lazy(() => import("@/pages/home"));
const ProductsPage = lazy(() => import("@/pages/ProductsPage"));
const ProductPage = lazy(() => import("@/pages/ProductPage"));
const AboutPage = lazy(() => import("@/pages/AboutPage"));
const ContactPage = lazy(() => import("@/pages/ContactPage"));
const WorkspacePage = lazy(() => import("@/pages/WorkspacePage"));
const ConnectionPage = lazy(() => import("@/pages/ConnectionPage"));
const AddressesPage = lazy(() => import("@/pages/AddressesPage"));
const CartPage = lazy(() => import("@/pages/CartPage"));
const OrdersPage = lazy(() => import("@/pages/OrdersPage"));
const AccessPage = lazy(() => import("@/pages/AccessPage"));
const RolesPage = lazy(() =>
import("@/pages/AccessPage").then((module) => ({
default: module.RolesPage,
})),
);
const AuditPage = lazy(() =>
import("@/pages/AccessPage").then((module) => ({
default: module.AuditPage,
})),
);
const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage"));
const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
const OffersPage = lazy(() => import("@/pages/OffersPage"));
const RecoveryPage = lazy(() => import("@/pages/RecoveryPage"));
const NotFound = lazy(() => import("@/pages/not-found"));
const queryClient = new QueryClient({ const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } }, defaultOptions: { queries: { retry: false } },
}); });
function Router() { function Router() {
return ( return (
<Switch> <Suspense fallback={<LinearProgress aria-label="Loading page" />}>
<Route path="/" component={Home} /> <Switch>
<Route path="/products" component={ProductsPage} /> <Route path="/" component={Home} />
<Route path="/products/:id"> <Route path="/products" component={ProductsPage} />
{(params) => <ProductPage id={params.id} />} <Route path="/products/:id">
</Route> {(params) => <ProductPage id={params.id} />}
<Route path="/workspace" component={WorkspacePage} /> </Route>
<Route path="/connection" component={ConnectionPage} /> <Route path="/workspace" component={WorkspacePage} />
<Route path="/about" component={AboutPage} /> <Route path="/connection" component={ConnectionPage} />
<Route path="/contact" component={ContactPage} /> <Route path="/addresses" component={AddressesPage} />
<Route component={NotFound} /> <Route path="/cart" component={CartPage} />
</Switch> <Route path="/orders">{() => <OrdersPage />}</Route>
<Route path="/orders/:id">
{(params) => <OrdersPage id={params.id} />}
</Route>
<Route path="/admin/orders">{() => <OrdersPage admin />}</Route>
<Route path="/admin/orders/:id">
{(params) => <OrdersPage admin id={params.id} />}
</Route>
<Route path="/admin/access" component={AccessPage} />
<Route path="/admin/roles" component={RolesPage} />
<Route path="/admin/audit" component={AuditPage} />
<Route path="/admin/catalog">{() => <CatalogAdminPage />}</Route>
<Route path="/admin/catalog/:id">
{(params) => <CatalogAdminPage id={params.id} />}
</Route>
<Route path="/admin/inventory">{() => <InventoryPage />}</Route>
<Route path="/admin/inventory/:id">
{(params) => <InventoryPage id={params.id} />}
</Route>
<Route path="/admin/coupons">{() => <OffersPage />}</Route>
<Route path="/admin/pricing">{() => <OffersPage pricing />}</Route>
<Route path="/recovery">{() => <RecoveryPage />}</Route>
<Route path="/reset-password">{() => <RecoveryPage reset />}</Route>
<Route path="/about" component={AboutPage} />
<Route path="/contact" component={ContactPage} />
<Route component={NotFound} />
</Switch>
</Suspense>
); );
} }
export default function App() {
function App() {
return ( return (
<QueryClientProvider client={queryClient}> <ErrorBoundary>
<PlatformProvider> <QueryClientProvider client={queryClient}>
<WouterRouter base={import.meta.env.BASE_URL.replace(/\/$/, "")}> <PlatformProvider>
<Layout> <WouterRouter base={import.meta.env.BASE_URL.replace(/\/$/, "")}>
<Router /> <Layout>
</Layout> <Router />
</WouterRouter> </Layout>
</PlatformProvider> </WouterRouter>
</QueryClientProvider> </PlatformProvider>
</QueryClientProvider>
</ErrorBoundary>
); );
} }
export default App;

View File

@ -0,0 +1,84 @@
import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import Alert from "@mui/material/Alert";
import { Link } from "wouter";
import { cart } from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
import { ApiNotice } from "./ApiNotice";
export function AddToCart({ variantId }: { variantId: string }) {
const { principal, request, scope } = usePlatform(),
client = useQueryClient();
const [busy, setBusy] = useState(false),
[error, setError] = useState<unknown>(null),
[saved, setSaved] = useState(false),
[quantity, setQuantity] = useState(1);
if (!principal)
return (
<Link href="/workspace">
<u>Sign in to add to cart</u>
</Link>
);
return (
<div>
<form
className="cart-add"
onSubmit={async (event) => {
event.preventDefault();
if (busy) return;
setBusy(true);
setError(null);
setSaved(false);
try {
z.number().int().min(1).max(100).parse(quantity);
const current = await request("/cart", cart);
const total =
(current.lines.find((l) => l.variantId === variantId)?.quantity ||
0) + quantity;
z.number().int().max(100).parse(total);
await request(
`/cart/lines/${variantId}`,
z.object({ version: z.number() }),
{
method: "PUT",
body: { quantity: total, version: current.version },
},
);
await client.invalidateQueries({
queryKey: ["private", scope, "/cart"],
});
setSaved(true);
} catch (error) {
setError(error);
} finally {
setBusy(false);
}
}}
>
<TextField
label="Quantity"
type="number"
size="small"
value={quantity}
onChange={(e) => setQuantity(Number(e.target.value))}
inputProps={{ min: 1, max: 100, step: 1 }}
disabled={busy}
/>
<Button type="submit" variant="contained" disabled={busy}>
{busy ? "Adding…" : "Add to cart"}
</Button>
</form>
<ApiNotice error={error} />
{saved && (
<Alert severity="success">
Added.{" "}
<Link href="/cart">
<u>Review cart</u>
</Link>
</Alert>
)}
</div>
);
}

View File

@ -0,0 +1,70 @@
import { useState } from "react";
import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import DialogActions from "@mui/material/DialogActions";
import { ApiNotice } from "./ApiNotice";
export function ConfirmAction({
label,
message,
onConfirm,
disabled = false,
}: {
label: string;
message: string;
onConfirm: () => Promise<unknown>;
disabled?: boolean;
}) {
const [open, setOpen] = useState(false),
[busy, setBusy] = useState(false),
[error, setError] = useState<unknown>(null);
return (
<>
<Button
disabled={disabled}
onClick={() => {
setError(null);
setOpen(true);
}}
>
{label}
</Button>
<Dialog
open={open}
onClose={() => {
if (!busy) setOpen(false);
}}
aria-labelledby="confirm-title"
>
<DialogTitle id="confirm-title">{label}</DialogTitle>
<DialogContent>
<p>{message}</p>
<ApiNotice error={error} />
</DialogContent>
<DialogActions>
<Button disabled={busy} onClick={() => setOpen(false)}>
Keep current state
</Button>
<Button
disabled={busy}
variant="contained"
onClick={async () => {
setBusy(true);
try {
await onConfirm();
setOpen(false);
} catch (error) {
setError(error);
} finally {
setBusy(false);
}
}}
>
{busy ? "Working…" : "Confirm"}
</Button>
</DialogActions>
</Dialog>
</>
);
}

View File

@ -0,0 +1,27 @@
import { Component, type ReactNode } from "react";
import Alert from "@mui/material/Alert";
import Button from "@mui/material/Button";
export class ErrorBoundary extends Component<
{ children: ReactNode },
{ failed: boolean }
> {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
componentDidCatch() {
console.error("APPLICATION_RENDER_FAILED");
}
render() {
return this.state.failed ? (
<main className="workspace-page">
<Alert severity="error">
This page could not be displayed. Reload to start a fresh session.
</Alert>
<Button onClick={() => location.reload()}>Reload application</Button>
</main>
) : (
this.props.children
);
}
}

View File

@ -14,12 +14,12 @@ const logoPath = "/opengraph.jpg";
// ── Ticker messages ────────────────────────────────────── // ── Ticker messages ──────────────────────────────────────
const TICKER_ITEMS = [ const TICKER_ITEMS = [
{ icon: <Flame size={12} />, text: "UAT — catalog and staff access" }, { icon: <Flame size={12} />, text: "UAT — commerce and administration" },
{ icon: <Sparkles size={12} />, text: "Explore the published collection" }, { icon: <Sparkles size={12} />, text: "Explore the published collection" },
{ icon: <Star size={12} />, text: "Handpoured in small batches" }, { icon: <Star size={12} />, text: "Handpoured in small batches" },
{ icon: <Flame size={12} />, text: "100% Natural Soy Wax" }, { icon: <Flame size={12} />, text: "100% Natural Soy Wax" },
{ icon: <Sparkles size={12} />, text: "Phthalate-free fragrance oils" }, { icon: <Sparkles size={12} />, text: "Phthalate-free fragrance oils" },
{ icon: <Star size={12} />, text: "Ordering arrives in the commerce phase" }, { icon: <Star size={12} />, text: "Payment collection is not enabled" },
]; ];
// ── Nav structure with dropdowns ───────────────────────── // ── Nav structure with dropdowns ─────────────────────────
@ -50,6 +50,7 @@ const NAV_LINKS = [
], ],
}, },
{ name: "Workspace", path: "/workspace", dropdown: null }, { name: "Workspace", path: "/workspace", dropdown: null },
{ name: "Cart", path: "/cart", dropdown: null },
{ name: "Connection", path: "/connection", dropdown: null }, { name: "Connection", path: "/connection", dropdown: null },
]; ];

View File

@ -0,0 +1,73 @@
import { useState } from "react";
import { z } from "zod";
import Checkbox from "@mui/material/Checkbox";
import { usePlatform } from "@/lib/platform";
import { Pager, QueryView, Table, usePrivateQuery } from "./WorkspaceTools";
const record = z.object({
id: z.string().uuid(),
name: z.string(),
isSystem: z.boolean().optional(),
permissions: z.array(z.string()).optional(),
});
export function RecordSelection({
name,
label,
path,
initial = [],
roles = false,
}: {
name: string;
label: string;
path: string;
initial?: string[];
roles?: boolean;
}) {
const { principal } = usePlatform();
const [selected, setSelected] = useState(initial),
[offset, setOffset] = useState(0);
const query = usePrivateQuery(
`${path}?limit=25&offset=${offset}`,
z.array(record),
);
return (
<fieldset className="record-picker">
<legend>{label}</legend>
<p>{selected.length} selected. Selections are retained across pages.</p>
{selected.map((id) => (
<input key={id} type="hidden" name={name} value={id} />
))}
<QueryView query={query}>
{(items) => (
<>
<Table
head={["Select", "Name"]}
rowKeys={items.map((item) => item.id)}
rows={items.map((item) => [
<Checkbox
inputProps={{ "aria-label": `Select ${item.name}` }}
checked={selected.includes(item.id)}
disabled={
roles &&
(item.isSystem ||
item.permissions?.some(
(p) => !principal?.permissions.includes(p),
))
}
onChange={(_, checked) =>
setSelected((ids) =>
checked
? [...ids, item.id]
: ids.filter((id) => id !== item.id),
)
}
/>,
item.name,
])}
/>
<Pager offset={offset} count={items.length} onPage={setOffset} />
</>
)}
</QueryView>
</fieldset>
);
}

View File

@ -0,0 +1,76 @@
import type { ReactNode } from "react";
import { Link } from "wouter";
import Container from "@mui/material/Container";
import Alert from "@mui/material/Alert";
import Button from "@mui/material/Button";
import { usePlatform } from "@/lib/platform";
import "@/pages/workspace.css";
export function WorkspaceShell({
title,
permission,
children,
}: {
title: string;
permission?: string;
children: ReactNode;
}) {
const { principal, can, scope } = usePlatform();
return (
<section className="workspace-page">
<Container maxWidth="lg">
<h1>{title}</h1>
{!principal ? (
<Alert severity="info">
Sign in to continue.{" "}
<Link href="/workspace">
<u>Account sign-in</u>
</Link>
</Alert>
) : (
<>
<WorkspaceNavigation />
{permission && !can(permission) ? (
<Alert severity="warning">
Your account does not have permission to view this page.
</Alert>
) : (
<div key={scope}>{children}</div>
)}
</>
)}
</Container>
</section>
);
}
export function WorkspaceNavigation() {
const { can } = usePlatform();
const links = [
{ label: "My cart", path: "/cart" },
{ label: "Addresses", path: "/addresses" },
{ label: "My orders", path: "/orders" },
{ label: "Access", path: "/admin/access", permission: "users.read" },
{ label: "Roles", path: "/admin/roles", permission: "roles.read" },
{ label: "Catalog", path: "/admin/catalog", permission: "catalog.read" },
{
label: "Inventory",
path: "/admin/inventory",
permission: "inventory.read",
},
{ label: "Coupons", path: "/admin/coupons", permission: "coupons.manage" },
{ label: "Pricing", path: "/admin/pricing", permission: "pricing.manage" },
{ label: "All orders", path: "/admin/orders", permission: "orders.read" },
{ label: "Audit", path: "/admin/audit", permission: "audit.read" },
];
return (
<nav className="workspace-links" aria-label="Workspace navigation">
{links
.filter((l) => !l.permission || can(l.permission))
.map((l) => (
<Button key={l.path} component={Link} href={l.path}>
{l.label}
</Button>
))}
</nav>
);
}

View File

@ -0,0 +1,286 @@
import {
createContext,
useContext,
useId,
useRef,
useState,
type ReactNode,
} from "react";
import { Link } from "wouter";
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import Checkbox from "@mui/material/Checkbox";
import FormControlLabel from "@mui/material/FormControlLabel";
import LinearProgress from "@mui/material/LinearProgress";
import Paper from "@mui/material/Paper";
import { usePlatform } from "@/lib/platform";
import { ApiNotice } from "./ApiNotice";
export function usePrivateQuery<T>(path: string, schema: z.ZodType<T>) {
const { scope, request } = usePlatform();
return useQuery({
queryKey: ["private", scope, path],
queryFn: ({ signal }) => request(path, schema, { signal }),
enabled: Boolean(scope),
retry: false,
});
}
export function QueryView<T>({
query,
children,
}: {
query: UseQueryResult<T>;
children: (data: T) => ReactNode;
}) {
if (query.isPending) return <LinearProgress aria-label="Loading workspace" />;
if (query.isError)
return (
<>
<ApiNotice error={query.error} />
<Button onClick={() => query.refetch()}>Try again</Button>
</>
);
return <>{children(query.data)}</>;
}
export function Panel({
title,
children,
}: {
title: string;
children: ReactNode;
}) {
return (
<Paper variant="outlined" className="workspace-panel">
<h2>{title}</h2>
{children}
</Paper>
);
}
const Errors = createContext<Record<string, string>>({});
export function ActionForm({
label,
read,
submit,
children,
reset = true,
lockFields = false,
}: {
label: string;
read: (data: FormData) => unknown;
submit: (input: unknown) => Promise<unknown>;
children: ReactNode;
reset?: boolean;
lockFields?: boolean;
}) {
const [busy, setBusy] = useState(false),
[error, setError] = useState<unknown>(null),
[success, setSuccess] = useState(false),
[fields, setFields] = useState<Record<string, string>>({});
const submitting = useRef(false);
return (
<form
className="workspace-form"
aria-label={label}
onSubmit={async (event) => {
event.preventDefault();
if (submitting.current) return;
submitting.current = true;
const form = event.currentTarget;
setBusy(true);
setError(null);
setSuccess(false);
setFields({});
try {
await submit(read(new FormData(form)));
if (reset) form.reset();
setSuccess(true);
} catch (error) {
if (error instanceof z.ZodError) {
setFields(
Object.fromEntries(
error.issues.map((i) => [String(i.path[0]), i.message]),
),
);
setError(
new Error(
error.issues
.map((issue) => `${issue.path.join(".")}: ${issue.message}`)
.join("; "),
),
);
} else setError(error);
} finally {
submitting.current = false;
setBusy(false);
}
}}
>
<fieldset disabled={busy || lockFields}>
<Errors.Provider value={fields}>{children}</Errors.Provider>
</fieldset>
<ApiNotice error={error} />
{success && <Alert severity="success">Saved successfully.</Alert>}
<Button type="submit" variant="contained" disabled={busy}>
{busy ? "Saving…" : label}
</Button>
</form>
);
}
export function Field({
name,
label,
type = "text",
value,
required = true,
maxLength,
options,
multiple = false,
helper,
onChange,
}: {
name: string;
label: string;
type?: string;
value?: string | number | string[];
required?: boolean;
maxLength?: number;
options?: { value: string; label: string }[];
multiple?: boolean;
helper?: string;
onChange?: (value: string) => void;
}) {
const errors = useContext(Errors),
id = useId();
return (
<TextField
id={id}
name={name}
label={label}
type={type}
defaultValue={onChange ? undefined : (value ?? (multiple ? [] : ""))}
value={onChange ? value : undefined}
onChange={onChange ? (event) => onChange(event.target.value) : undefined}
autoComplete={type === "password" ? "new-password" : undefined}
required={required}
fullWidth
error={Boolean(errors[name])}
helperText={errors[name] || helper}
inputProps={{ maxLength }}
select={Boolean(options)}
InputLabelProps={multiple ? { shrink: true } : undefined}
SelectProps={options ? { native: true, multiple } : undefined}
>
{options && (
<>
{!required && !multiple && <option value="">None</option>}
{options.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</>
)}
</TextField>
);
}
export function Check({
name,
label,
value = false,
}: {
name: string;
label: string;
value?: boolean;
}) {
return (
<FormControlLabel
control={<Checkbox name={name} defaultChecked={value} />}
label={label}
/>
);
}
export const readText = (data: FormData, name: string) =>
String(data.get(name) ?? "");
export const readNumber = (data: FormData, name: string) =>
Number(data.get(name));
export function Pager({
offset,
count,
onPage,
}: {
offset: number;
count: number;
onPage: (offset: number) => void;
}) {
return (
<div className="catalog-pagination">
<Button
disabled={!offset}
onClick={() => onPage(Math.max(0, offset - 25))}
>
Previous
</Button>
<span>Page {offset / 25 + 1}</span>
<Button
disabled={count < 25 || offset + 25 > 10000}
onClick={() => onPage(offset + 25)}
>
Next
</Button>
</div>
);
}
export function Empty({ label = "No records yet." }: { label?: string }) {
return <Alert severity="info">{label}</Alert>;
}
export function Table({
head,
rows,
rowKeys,
}: {
head: string[];
rows: ReactNode[][];
rowKeys: string[];
}) {
return rows.length ? (
<div className="workspace-table">
<table>
<thead>
<tr>
{head.map((h) => (
<th key={h} scope="col">
{h}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, index) => (
<tr key={rowKeys[index]}>
{row.map((cell, i) => (
<td key={i}>{cell}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
) : (
<Empty />
);
}
export function WorkspaceLink({
href,
children,
}: {
href: string;
children: ReactNode;
}) {
return (
<Link href={href}>
<u>{children}</u>
</Link>
);
}

View File

@ -15,12 +15,12 @@ type ToasterToast = ToastProps & {
action?: ToastActionElement action?: ToastActionElement
} }
const actionTypes = { type ActionType = {
ADD_TOAST: "ADD_TOAST", ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST", UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST", DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST", REMOVE_TOAST: "REMOVE_TOAST",
} as const }
let count = 0 let count = 0
@ -29,7 +29,7 @@ function genId() {
return count.toString() return count.toString()
} }
type ActionType = typeof actionTypes
type Action = type Action =
| { | {

View File

@ -1,6 +1,6 @@
import { z } from "zod"; import { z } from "zod";
export const organizationSchema = z.string().uuid(); export const organizationSchema = z.string().uuid().toLowerCase();
const productSummarySchema = z.object({ const productSummarySchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
name: z.string(), name: z.string(),
@ -13,9 +13,9 @@ export const productSchema = productSummarySchema.extend({
id: z.string().uuid(), id: z.string().uuid(),
sku: z.string(), sku: z.string(),
name: z.string(), name: z.string(),
price: z.string().regex(/^\d+\.\d{2}$/), price: z.string().regex(/^\d+(?:\.\d{1,2})?$/),
currency: z.string(), currency: z.string(),
attributes: z.record(z.string()), attributes: z.record(z.string(), z.string()),
}), }),
), ),
groups: z.array( groups: z.array(
@ -62,6 +62,16 @@ export class ApiError extends Error {
this.requestId = requestId; this.requestId = requestId;
} }
} }
export function isUnknownOutcome(error: unknown) {
return (
(error instanceof Error && error.name === "AbortError") ||
(error instanceof ApiError &&
(error.status === 0 ||
error.status >= 500 ||
error.code === "INVALID_RESPONSE" ||
error.code === "SESSION_CHANGED"))
);
}
export async function apiRequest( export async function apiRequest(
path: string, path: string,
@ -118,7 +128,7 @@ export async function apiRequest(
); );
return data; return data;
} }
function parse<T>(schema: z.ZodType<T>, data: unknown): T { export function parse<T>(schema: z.ZodType<T>, data: unknown): T {
const result = schema.safeParse(data); const result = schema.safeParse(data);
if (!result.success) if (!result.success)
throw new ApiError( throw new ApiError(
@ -165,12 +175,12 @@ export async function login(
email: string, email: string,
password: string, password: string,
) { ) {
organizationSchema.parse(organizationId); const organization = organizationSchema.parse(organizationId);
return parse( return parse(
sessionSchema, sessionSchema,
await apiRequest("/auth/login", { await apiRequest("/auth/login", {
method: "POST", method: "POST",
body: { organizationId, email, password }, body: { organizationId: organization, email, password },
}), }),
); );
} }

311
src/lib/commerce.ts Normal file
View File

@ -0,0 +1,311 @@
import { z } from "zod";
export const uuid = z.string().uuid().toLowerCase();
export const currency = z.enum(["INR", "USD", "EUR", "GBP"]);
export const decimal = z.string().regex(/^\d+(?:\.\d{1,2})?$/);
export const amount = z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/);
const text = (max: number, min = 1) =>
z
.string()
.trim()
.min(min)
.max(max)
.regex(/^[^<>\u0000-\u001F\u007F]*$/, "Plain text only");
export const addressInput = z
.object({
recipient: text(160),
line1: text(200),
line2: text(200, 0),
city: text(100),
region: text(100),
postalCode: text(20).regex(/^[A-Za-z0-9 -]+$/),
countryCode: z
.string()
.toUpperCase()
.regex(/^[A-Z]{2}$/),
phone: z.string().regex(/^\+[1-9]\d{6,14}$/),
isDefault: z.boolean(),
})
.strict();
export const address = addressInput.extend({ id: uuid }).strip();
export type Address = z.infer<typeof address>;
export const cart = z.object({
version: z.number().int().nonnegative(),
lines: z.array(
z.object({
variantId: uuid,
quantity: z.number().int().positive(),
variant: z.object({
name: z.string(),
sku: z.string(),
price: decimal,
currency,
active: z.boolean(),
product: z.object({ name: z.string(), status: z.string() }),
}),
}),
),
});
export type Cart = z.infer<typeof cart>;
export const couponCode = text(40)
.toUpperCase()
.regex(/^[A-Z0-9][A-Z0-9_-]{0,39}$/);
export const checkoutInput = z
.object({
cartVersion: z.number().int().min(0).max(2147483646),
addressId: uuid,
idempotencyKey: uuid,
couponCode: couponCode.optional(),
})
.strict();
export type CheckoutIntent = z.infer<typeof checkoutInput>;
export function checkoutIntent(
input: Omit<CheckoutIntent, "idempotencyKey">,
key: string,
) {
return Object.freeze(checkoutInput.parse({ ...input, idempotencyKey: key }));
}
export function money(value: string) {
decimal.parse(value);
const [whole, fraction = ""] = value.split(".");
return `${BigInt(whole)}.${fraction.padEnd(2, "0")}`;
}
export function moneyTotal(lines: { price: string; quantity: number }[]) {
const total = lines.reduce((sum, line) => {
z.number().int().nonnegative().parse(line.quantity);
return (
sum + BigInt(money(line.price).replace(".", "")) * BigInt(line.quantity)
);
}, 0n);
return `${total / 100n}.${(total % 100n).toString().padStart(2, "0")}`;
}
export const orderSummary = z.object({
id: uuid,
status: z.enum(["PENDING_PAYMENT", "CANCELLED", "EXPIRED"]),
currency,
merchandiseTotal: decimal,
createdAt: z.string(),
expiresAt: z.string(),
});
export const order = orderSummary.extend({
subtotal: decimal,
discount: decimal,
pricingStatus: z.enum(["FINALIZED", "UNFINALIZED"]),
taxTotal: decimal.nullable(),
shippingTotal: decimal.nullable(),
payableTotal: decimal.nullable(),
paymentAvailable: z.literal(false),
address: addressInput.omit({ isDefault: true }).strip(),
lines: z.array(
z.object({
variantId: uuid,
sku: z.string(),
productName: z.string(),
variantName: z.string(),
quantity: z.number().int(),
unitPrice: decimal,
lineTotal: decimal,
}),
),
});
export type Order = z.infer<typeof order>;
export const productInput = z
.object({
name: text(160),
slug: text(160).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
description: text(5000, 0),
groupIds: z
.array(uuid)
.max(20)
.refine((v) => new Set(v).size === v.length),
})
.strict();
export const groupInput = z
.object({
name: text(100),
slug: text(100).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
kind: z.enum(["CATEGORY", "COLLECTION"]),
})
.strict();
export const group = groupInput.extend({ id: uuid }).strip();
export const variantInput = z
.object({
sku: text(64)
.toUpperCase()
.regex(/^[A-Z0-9][A-Z0-9_-]*$/),
name: text(160),
price: amount.refine((v) => v !== "0.00"),
currency,
active: z.boolean(),
attributes: z
.record(
z
.string()
.regex(/^[a-z][a-z0-9_]{0,31}$/)
.refine((v) => !["constructor", "prototype"].includes(v)),
text(100),
)
.refine((v) => Object.keys(v).length <= 20),
})
.strict();
export const variant = variantInput
.extend({ id: uuid, price: decimal })
.strip();
export const adminProductSummary = productInput
.pick({ name: true, slug: true })
.extend({ id: uuid, status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]) })
.strip();
export const adminProduct = adminProductSummary.extend({
description: z.string(),
variants: z.array(variant),
groups: z.array(z.object({ group })),
});
export type AdminProduct = z.infer<typeof adminProduct>;
export const userInput = z
.object({
name: text(160),
email: z.string().email().max(254).toLowerCase(),
password: z.string().min(15).max(128),
})
.strict();
export const user = userInput.omit({ password: true }).extend({
id: uuid,
status: z.enum(["PENDING", "ACTIVE", "SUSPENDED"]),
isOwner: z.boolean(),
createdAt: z.string(),
});
export const roleInput = z
.object({
name: text(80),
permissions: z
.array(z.string())
.refine((v) => new Set(v).size === v.length),
})
.strict();
export const role = roleInput
.extend({ id: uuid, isSystem: z.boolean() })
.strip();
export const audit = z.object({
id: uuid,
actorId: uuid.nullable(),
action: z.string(),
targetId: z.string().nullable(),
createdAt: z.string(),
});
export const warehouseInput = z.object({ name: text(100) }).strict();
export const warehouse = warehouseInput.extend({ id: uuid }).strip();
export const stockInput = z
.object({ variantId: uuid, warehouseId: uuid })
.strict();
export const stock = stockInput
.extend({ id: uuid, onHand: z.number().int() })
.strip();
export const stockDetail = stock.extend({
reserved: z.number().int(),
available: z.number().int(),
});
export const adjustmentInput = z
.object({
stockItemId: uuid,
delta: z
.number()
.int()
.min(-1000000)
.max(1000000)
.refine((v) => v !== 0),
reason: text(200),
idempotencyKey: uuid,
})
.strict();
export const ledger = z.object({
id: uuid,
delta: z.number().int(),
reason: z.string(),
createdAt: z.string(),
});
export const reservationInput = z
.object({
stockItemId: uuid,
quantity: z.number().int().min(1).max(1000000),
ttlMinutes: z.number().int().min(1).max(60),
idempotencyKey: uuid,
})
.strict();
export const reservation = z.object({
id: uuid,
orderId: uuid.nullable().optional(),
stockItemId: uuid,
quantity: z.number().int(),
status: z.enum(["ACTIVE", "RELEASED", "COMMITTED", "EXPIRED"]),
expiresAt: z.string(),
});
const couponCommon = z.object({
code: couponCode,
currency,
minimumSubtotal: amount,
maxUses: z.number().int().min(1).max(1000000),
perUserLimit: z.number().int().min(1).max(100),
startsAt: z.string().datetime({ offset: true }),
endsAt: z.string().datetime({ offset: true }),
});
export const couponInput = z
.discriminatedUnion("kind", [
couponCommon
.extend({
kind: z.literal("FIXED"),
amount: amount.refine((v) => v !== "0.00"),
})
.strict(),
couponCommon
.extend({
kind: z.literal("PERCENT"),
percentBps: z.number().int().min(1).max(10000),
})
.strict(),
])
.refine((v) => Date.parse(v.endsAt) > Date.parse(v.startsAt), {
path: ["endsAt"],
message: "End must follow start",
})
.refine((v) => v.perUserLimit <= v.maxUses, {
path: ["perUserLimit"],
message: "Per-user limit exceeds total limit",
});
export const coupon = z.object({
id: uuid,
code: z.string(),
currency,
kind: z.enum(["FIXED", "PERCENT"]),
amount: decimal.nullable(),
percentBps: z.number().nullable(),
minimumSubtotal: decimal,
maxUses: z.number(),
perUserLimit: z.number(),
active: z.boolean(),
startsAt: z.string(),
endsAt: z.string(),
});
export const pricingInput = z
.object({
name: text(100),
currency,
countryCode: z
.string()
.trim()
.toUpperCase()
.regex(/^[A-Z]{2}$/),
region: text(100, 0).toUpperCase(),
taxMode: z.enum(["INCLUSIVE", "EXCLUSIVE"]),
merchandiseTaxBps: z.number().int().min(0).max(10000),
shippingFee: amount,
shippingTaxBps: z.number().int().min(0).max(10000),
freeShippingMinimum: amount.nullable(),
})
.strict();
export const pricing = pricingInput
.extend({
id: uuid,
active: z.boolean(),
shippingFee: decimal,
freeShippingMinimum: decimal.nullable(),
})
.strip();

View File

@ -1,28 +1,44 @@
import { import {
createContext, createContext,
useContext, useContext,
useCallback,
useEffect, useEffect,
useRef, useRef,
useState, useState,
type ReactNode, type ReactNode,
} from "react"; } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import { import {
apiRequest, apiRequest,
ApiError, ApiError,
getPrincipal, getPrincipal,
login, login,
organizationSchema, organizationSchema,
parse,
type Principal, type Principal,
type Session, type Session,
} from "./api"; } from "./api";
type Options = { method?: string; body?: unknown; signal?: AbortSignal };
const PlatformContext = createContext<{ const PlatformContext = createContext<{
organization: string; organization: string;
setOrganization: (value: string) => void; setOrganization: (value: string) => void;
principal: Principal | null; principal: Principal | null;
scope: string;
signIn: (email: string, password: string) => Promise<void>; signIn: (email: string, password: string) => Promise<void>;
signOut: () => Promise<void>; signOut: () => Promise<void>;
notice: string; notice: string;
clearSession: (notice?: string) => void;
getIntent: (key: string) => unknown;
saveIntent: (key: string, value: unknown) => void;
clearIntent: (key: string, idempotencyKey: string) => void;
can: (permission: string) => boolean;
request: <T>(
path: string,
schema: z.ZodType<T>,
options?: Options,
) => Promise<T>;
} | null>(null); } | null>(null);
function initialOrganization() { function initialOrganization() {
let value = import.meta.env.VITE_ORGANIZATION_ID || ""; let value = import.meta.env.VITE_ORGANIZATION_ID || "";
@ -31,54 +47,80 @@ function initialOrganization() {
} catch { } catch {
/* Storage can be disabled. */ /* Storage can be disabled. */
} }
return organizationSchema.safeParse(value).success ? value : ""; const parsed = organizationSchema.safeParse(value);
return parsed.success ? parsed.data : "";
} }
export function PlatformProvider({ children }: { children: ReactNode }) { export function PlatformProvider({ children }: { children: ReactNode }) {
const client = useQueryClient();
const [organization, updateOrganization] = useState(initialOrganization); const [organization, updateOrganization] = useState(initialOrganization);
const [session, setSession] = useState<Session | null>(null); const [session, setSession] = useState<Session | null>(null);
const [principal, setPrincipal] = useState<Principal | null>(null); const [principal, setPrincipal] = useState<Principal | null>(null);
const [notice, setNotice] = useState(""); const [notice, setNotice] = useState("");
const loginVersion = useRef(0); const [accessRevision, setAccessRevision] = useState(0);
const revision = useRef(0),
intents = useRef(new Map<string, unknown>());
const current = useRef<Session | null>(null),
generation = useRef(0),
scopeAbort = useRef(new AbortController());
const clearSession = useCallback(
(message = "") => {
generation.current += 1;
current.current = null;
revision.current += 1;
setAccessRevision(revision.current);
intents.current.clear();
scopeAbort.current.abort();
scopeAbort.current = new AbortController();
void client.cancelQueries({ queryKey: ["private"] });
client.removeQueries({ queryKey: ["private"] });
client.getMutationCache().clear();
setSession(null);
setPrincipal(null);
setNotice(message);
},
[client],
);
useEffect(() => { useEffect(() => {
if (!session) return; if (!session) return;
const timer = setTimeout( const timer = setTimeout(
() => { () => clearSession("Your session expired. Sign in again."),
setSession(null);
setPrincipal(null);
setNotice("Your session expired. Sign in again.");
},
Math.max(0, Date.parse(session.expiresAt) - Date.now()), Math.max(0, Date.parse(session.expiresAt) - Date.now()),
); );
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, [session]); }, [session, clearSession]);
useEffect(() => {
scopeAbort.current = new AbortController();
return () => {
generation.current += 1;
scopeAbort.current.abort();
};
}, []);
function setOrganization(value: string) { function setOrganization(value: string) {
organizationSchema.parse(value); const normalized = organizationSchema.parse(value);
if (value !== organization) { if (normalized !== organization) clearSession();
loginVersion.current += 1; updateOrganization(normalized);
setSession(null);
setPrincipal(null);
}
updateOrganization(value);
setNotice(""); setNotice("");
try { try {
localStorage.setItem("mani.organization", value); localStorage.setItem("mani.organization", normalized);
} catch { } catch {
/* The in-memory setting still works. */ /* The in-memory setting still works. */
} }
} }
async function signIn(email: string, password: string) { async function signIn(email: string, password: string) {
const version = ++loginVersion.current; const version = ++generation.current;
const next = await login(organization, email, password); const next = await login(organization, email, password);
try { try {
const me = await getPrincipal(next.accessToken); const me = await getPrincipal(next.accessToken);
if (version !== loginVersion.current) if (
version !== generation.current ||
me.organizationId !== organization ||
Date.parse(next.expiresAt) <= Date.now()
)
throw new Error( throw new Error(
"The connection changed during sign-in. Please try again.", "The session changed during sign-in. Please try again.",
);
if (me.organizationId !== organization)
throw new Error(
"The session organization does not match the configured organization.",
); );
clearSession();
current.current = next;
setSession(next); setSession(next);
setPrincipal(me); setPrincipal(me);
setNotice(""); setNotice("");
@ -86,24 +128,103 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
await apiRequest("/auth/logout", { await apiRequest("/auth/logout", {
method: "POST", method: "POST",
token: next.accessToken, token: next.accessToken,
}).catch(() => {}); }).catch(() => {
/* Best-effort revoke; this token is never retained locally. */
});
throw error; throw error;
} }
} }
async function signOut() { async function signOut() {
loginVersion.current += 1; const previous = current.current;
if (!session) return; clearSession();
if (!previous) return;
try { try {
await apiRequest("/auth/logout", { await apiRequest("/auth/logout", {
method: "POST", method: "POST",
token: session.accessToken, token: previous.accessToken,
}); });
} catch (error) { } catch (error) {
if (!(error instanceof ApiError && error.status === 401)) throw error; if (error instanceof ApiError && error.status === 401) return;
throw new Error(
"You are signed out locally, but server revocation could not be confirmed. The server session will expire automatically.",
);
}
}
async function request<T>(
path: string,
schema: z.ZodType<T>,
options: Options = {},
) {
const active = session;
if (
!active ||
current.current !== active ||
revision.current !== accessRevision
)
throw new ApiError("Sign in to continue.", 401, "SESSION_CHANGED");
if (Date.parse(active.expiresAt) <= Date.now()) {
clearSession("Your session expired. Sign in again.");
throw new ApiError("Your session expired.", 401, "SESSION_EXPIRED");
}
const signal = options.signal
? AbortSignal.any([scopeAbort.current.signal, options.signal])
: scopeAbort.current.signal;
try {
const data = await apiRequest(path, {
...options,
token: active.accessToken,
signal,
});
if (current.current !== active || revision.current !== accessRevision)
throw new ApiError(
"Your session changed. Sign in again.",
401,
"SESSION_CHANGED",
);
return parse(schema, data);
} catch (error) {
if (
current.current === active &&
revision.current === accessRevision &&
error instanceof ApiError
) {
if (error.status === 401)
clearSession("Your session is no longer valid. Sign in again.");
else if (error.status === 403) {
try {
const me = await getPrincipal(active.accessToken);
if (
current.current === active &&
revision.current === accessRevision
) {
if (
me.permissions.length !== principal?.permissions.length ||
me.permissions.some(
(permission) => !principal?.permissions.includes(permission),
)
) {
scopeAbort.current.abort();
scopeAbort.current = new AbortController();
revision.current += 1;
setAccessRevision(revision.current);
void client.cancelQueries({ queryKey: ["private"] });
client.removeQueries({ queryKey: ["private"] });
client.getMutationCache().clear();
}
setPrincipal(me);
}
} catch (refresh) {
if (
current.current === active &&
refresh instanceof ApiError &&
refresh.status === 401
)
clearSession("Your session is no longer valid. Sign in again.");
}
}
}
throw error;
} }
setSession(null);
setPrincipal(null);
setNotice("");
} }
return ( return (
<PlatformContext.Provider <PlatformContext.Provider
@ -111,9 +232,34 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
organization, organization,
setOrganization, setOrganization,
principal, principal,
scope: principal ? `${principal.sessionId}:${accessRevision}` : "",
signIn, signIn,
signOut, signOut,
notice, notice,
clearSession,
getIntent: (key) =>
session && current.current === session
? intents.current.get(key)
: undefined,
saveIntent: (key, value) => {
if (session && current.current === session)
intents.current.set(key, value);
},
clearIntent: (key, idempotencyKey) => {
const stored = intents.current.get(key);
if (
session &&
current.current === session &&
typeof stored === "object" &&
stored !== null &&
"idempotencyKey" in stored &&
stored.idempotencyKey === idempotencyKey
)
intents.current.delete(key);
},
can: (permission) =>
Boolean(principal?.permissions.includes(permission)),
request,
}} }}
> >
{children} {children}

20
src/lib/recovery-token.ts Normal file
View File

@ -0,0 +1,20 @@
let token: string | null = null;
export function captureRecoveryToken(
location: { hash: string; pathname: string; search: string },
history: {
replaceState: (data: unknown, unused: string, url: string) => void;
},
) {
const params = new URLSearchParams(location.hash.slice(1));
if (!params.has("token")) return null;
const value = params.get("token") || "";
history.replaceState(null, "", location.pathname + location.search);
token = /^[A-Za-z0-9_-]{43}$/.test(value) ? value : null;
return token;
}
export function getRecoveryToken() {
return token;
}
export function clearRecoveryToken() {
token = null;
}

View File

@ -0,0 +1,44 @@
import { useRef, useState } from "react";
import { z } from "zod";
import { isUnknownOutcome } from "./api";
import { usePlatform } from "./platform";
export function useIdempotentCommand<T extends { idempotencyKey: string }, R>(
path: string,
input: z.ZodType<T>,
output: z.ZodType<R>,
commandId: string,
) {
const { request, getIntent, saveIntent, clearIntent } = usePlatform();
const key = `${path}:${commandId}`;
const saved = getIntent(key);
const intent = useRef<T | null>(saved ? input.parse(saved) : null);
const [uncertain, setUncertain] = useState(Boolean(saved));
async function run(value: unknown) {
if (!intent.current) {
const object = z.record(z.string(), z.unknown()).parse(value);
intent.current = Object.freeze(
input.parse({ ...object, idempotencyKey: crypto.randomUUID() }),
);
saveIntent(key, intent.current);
}
try {
const result = await request(path, output, {
method: "POST",
body: intent.current,
});
clearIntent(key, intent.current.idempotencyKey);
intent.current = null;
setUncertain(false);
return result;
} catch (error) {
if (isUnknownOutcome(error)) setUncertain(true);
else {
if (intent.current) clearIntent(key, intent.current.idempotencyKey);
intent.current = null;
setUncertain(false);
}
throw error;
}
}
return { run, uncertain };
}

View File

@ -3,7 +3,10 @@ import { ThemeProvider } from "@mui/material/styles";
import CssBaseline from "@mui/material/CssBaseline"; import CssBaseline from "@mui/material/CssBaseline";
import App from "./App"; import App from "./App";
import theme from "./theme"; import theme from "./theme";
import "./index.css"; import "./index.css";
import { captureRecoveryToken } from "./lib/recovery-token";
captureRecoveryToken(window.location, window.history);
createRoot(document.getElementById("root")!).render( createRoot(document.getElementById("root")!).render(
<ThemeProvider theme={theme}> <ThemeProvider theme={theme}>

297
src/pages/AccessPage.tsx Normal file
View File

@ -0,0 +1,297 @@
import { RecordSelection } from "@/components/RecordSelection";
import { useState } from "react";
import { z } from "zod";
import Button from "@mui/material/Button";
import Alert from "@mui/material/Alert";
import { user, userInput, role, roleInput, uuid, audit } from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import {
ActionForm,
Field,
Pager,
Panel,
QueryView,
Table,
usePrivateQuery,
readText,
} from "@/components/WorkspaceTools";
import { ConfirmAction } from "@/components/ConfirmAction";
function Roles() {
const { request, can, principal } = usePlatform();
const [offset, setOffset] = useState(0),
[editing, setEditing] = useState<z.infer<typeof role> | null>(null);
const roles = usePrivateQuery(
`/roles?limit=25&offset=${offset}`,
z.array(role),
);
return (
<Panel title="Roles">
<QueryView query={roles}>
{(items) => (
<>
<Table
head={["Role", "Permissions", "Actions"]}
rowKeys={items.map((item) => item.id)}
rows={items.map((r) => [
r.name,
r.permissions.join(", "),
can("roles.manage") &&
!r.isSystem &&
r.permissions.every((p) =>
principal?.permissions.includes(p),
) ? (
<Button onClick={() => setEditing(r)}>Edit</Button>
) : r.isSystem ? (
"System role"
) : (
"Read only"
),
])}
/>
<Pager offset={offset} count={items.length} onPage={setOffset} />
</>
)}
</QueryView>
{can("roles.manage") && (
<>
<h3>{editing ? `Edit ${editing.name}` : "Create a role"}</h3>
<ActionForm
key={editing?.id || "new"}
label="Save role"
read={(data) => ({
name: readText(data, "name"),
permissions: data.getAll("permissions").map(String),
})}
submit={async (value) => {
const body = roleInput.parse(value);
if (
body.permissions.some(
(p) => !principal?.permissions.includes(p),
)
)
throw new Error(
"You cannot grant a permission you do not hold.",
);
await request(editing ? `/roles/${editing.id}` : "/roles", role, {
method: editing ? "PATCH" : "POST",
body,
});
setEditing(null);
await roles.refetch();
}}
>
<Field
name="name"
label="Role name"
maxLength={80}
value={editing?.name}
/>
<Field
name="permissions"
label="Permissions to grant"
options={
principal?.permissions.map((p) => ({ value: p, label: p })) ||
[]
}
multiple
required={false}
value={editing?.permissions || []}
helper="Select only permissions this role should receive."
/>
</ActionForm>
{editing && (
<Button onClick={() => setEditing(null)}>Cancel editing</Button>
)}
</>
)}
</Panel>
);
}
function UserRoles({ userId }: { userId: string }) {
const { request } = usePlatform();
return (
<>
<Alert severity="warning">
This replaces all role assignments. The API does not expose current
assignments; select the full intended set. System roles cannot be
assigned.
</Alert>
<ActionForm
label="Replace role assignments"
read={(data) => ({ roleIds: data.getAll("roleIds").map(String) })}
submit={async (value) => {
const body = z
.object({
roleIds: z
.array(uuid)
.max(20)
.refine((v) => new Set(v).size === v.length),
})
.parse(value);
await request(`/users/${userId}/roles`, z.object({ id: uuid }), {
method: "PATCH",
body,
});
}}
reset={false}
>
<RecordSelection
name="roleIds"
label="Intended role assignments"
path="/roles"
roles
/>
</ActionForm>
</>
);
}
function Users() {
const { request, can, principal } = usePlatform();
const [offset, setOffset] = useState(0),
[selected, setSelected] = useState<string | null>(null);
const query = usePrivateQuery(
`/users?limit=25&offset=${offset}`,
z.array(user),
);
return (
<>
<Panel title="Staff accounts">
<QueryView query={query}>
{(items) => (
<>
<Table
head={["Name", "Email", "Status", "Actions"]}
rowKeys={items.map((item) => item.id)}
rows={items.map((u) => [
u.name,
u.email,
u.status,
<>
{!u.isOwner && u.id !== principal?.userId && (
<>
{can("users.approve") && (
<ConfirmAction
label={
u.status === "ACTIVE" ? "Suspend" : "Approve"
}
message={
u.status === "ACTIVE"
? "Suspend this account and revoke its sessions?"
: "Approve this account? It must have suitable roles before accessing staff tools."
}
onConfirm={async () => {
await request(`/users/${u.id}/status`, user, {
method: "PATCH",
body: {
status:
u.status === "ACTIVE"
? "SUSPENDED"
: "ACTIVE",
},
});
await query.refetch();
}}
/>
)}
{can("users.roles.assign") && can("roles.read") && (
<Button
onClick={() =>
setSelected(selected === u.id ? null : u.id)
}
>
Assign roles
</Button>
)}
</>
)}
</>,
])}
/>
<Pager offset={offset} count={items.length} onPage={setOffset} />
{selected && <UserRoles key={selected} userId={selected} />}
</>
)}
</QueryView>
</Panel>
{can("users.create") && (
<Panel title="Provision a pending account">
<ActionForm
label="Create pending account"
read={(data) => ({
name: readText(data, "name"),
email: readText(data, "email"),
password: readText(data, "password"),
})}
submit={async (value) => {
await request("/users", user, {
method: "POST",
body: userInput.parse(value),
});
await query.refetch();
}}
>
<Field name="name" label="Full name" maxLength={160} />
<Field name="email" label="Email" type="email" maxLength={254} />
<Field
name="password"
label="Initial password"
type="password"
maxLength={128}
helper="15–128 characters. The account starts pending."
/>
</ActionForm>
</Panel>
)}
</>
);
}
export default function AccessPage() {
return (
<WorkspaceShell title="Access Administration" permission="users.read">
<Users />
</WorkspaceShell>
);
}
export function RolesPage() {
return (
<WorkspaceShell title="Role Administration" permission="roles.read">
<Roles />
</WorkspaceShell>
);
}
function Audit() {
const [offset, setOffset] = useState(0);
const query = usePrivateQuery(
`/audit-events?limit=25&offset=${offset}`,
z.array(audit),
);
return (
<Panel title="Immutable audit history">
<QueryView query={query}>
{(items) => (
<>
<Table
head={["Time", "Action", "Actor", "Target"]}
rowKeys={items.map((item) => item.id)}
rows={items.map((a) => [
new Date(a.createdAt).toLocaleString(),
a.action,
a.actorId || "System",
a.targetId || "—",
])}
/>
<Pager offset={offset} count={items.length} onPage={setOffset} />
</>
)}
</QueryView>
</Panel>
);
}
export function AuditPage() {
return (
<WorkspaceShell title="Audit History" permission="audit.read">
<Audit />
</WorkspaceShell>
);
}

130
src/pages/AddressesPage.tsx Normal file
View File

@ -0,0 +1,130 @@
import { useState } from "react";
import { z } from "zod";
import Button from "@mui/material/Button";
import { address, addressInput, type Address } from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import {
ActionForm,
Check,
Field,
Panel,
QueryView,
readText,
usePrivateQuery,
Empty,
} from "@/components/WorkspaceTools";
import { ConfirmAction } from "@/components/ConfirmAction";
function Addresses() {
const { request } = usePlatform(),
query = usePrivateQuery("/addresses", z.array(address));
const [editing, setEditing] = useState<Address | null>(null);
return (
<>
<Panel title="Saved addresses">
<QueryView query={query}>
{(items) => (
<>
{!items.length && <Empty />}
{items.map((item) => (
<article className="address-card" key={item.id}>
<h3>
{item.recipient}
{item.isDefault ? " · Default" : ""}
</h3>
<p>
{item.line1} {item.line2}
<br />
{item.city}, {item.region} {item.postalCode}
<br />
{item.countryCode} · {item.phone}
</p>
<Button onClick={() => setEditing(item)}>Edit address</Button>
<ConfirmAction
label="Delete address"
message="Delete this saved address? Existing order snapshots will be retained."
onConfirm={async () => {
await request(`/addresses/${item.id}`, z.null(), {
method: "DELETE",
});
await query.refetch();
if (editing?.id === item.id) setEditing(null);
}}
/>
</article>
))}
</>
)}
</QueryView>
</Panel>
<Panel title={editing ? "Edit address" : "New address"}>
<ActionForm
key={editing?.id || "new"}
label="Save address"
read={(data) => ({
...Object.fromEntries(
[
"recipient",
"line1",
"line2",
"city",
"region",
"postalCode",
"countryCode",
"phone",
].map((name) => [name, readText(data, name)]),
),
isDefault: data.has("isDefault"),
})}
submit={async (value) => {
const body = addressInput.parse(value);
await request(
editing ? `/addresses/${editing.id}` : "/addresses",
address,
{ method: editing ? "PUT" : "POST", body },
);
setEditing(null);
await query.refetch();
}}
>
{(
[
["recipient", "Recipient", 160],
["line1", "Address line 1", 200],
["line2", "Address line 2", 200],
["city", "City", 100],
["region", "State or region", 100],
["postalCode", "Postal code", 20],
["countryCode", "Country code (IN, US, etc.)", 2],
["phone", "Phone (+country code)", 16],
] as const
).map(([name, label, maxLength]) => (
<Field
key={name}
name={name}
label={label}
maxLength={maxLength}
required={name !== "line2"}
value={editing?.[name] || (name === "countryCode" ? "IN" : "")}
/>
))}
<Check
name="isDefault"
label="Default address"
value={editing?.isDefault}
/>
</ActionForm>
{editing && (
<Button onClick={() => setEditing(null)}>Cancel editing</Button>
)}
</Panel>
</>
);
}
export default function AddressesPage() {
return (
<WorkspaceShell title="My Addresses">
<Addresses />
</WorkspaceShell>
);
}

327
src/pages/CartPage.tsx Normal file
View File

@ -0,0 +1,327 @@
import { useEffect, useRef, useState } from "react";
import { Link, useLocation } from "wouter";
import { z } from "zod";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import MenuItem from "@mui/material/MenuItem";
import Alert from "@mui/material/Alert";
import {
cart,
address,
checkoutIntent,
checkoutInput,
order,
money,
moneyTotal,
type CheckoutIntent,
} from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
import { ApiError, isUnknownOutcome } from "@/lib/api";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import { Panel, QueryView, usePrivateQuery } from "@/components/WorkspaceTools";
import { ApiNotice } from "@/components/ApiNotice";
function Cart() {
const { request, getIntent, saveIntent, clearIntent } = usePlatform(),
query = usePrivateQuery("/cart", cart),
addresses = usePrivateQuery("/addresses", z.array(address));
const [, navigate] = useLocation();
const locked = useRef(false),
attempt = useRef<CheckoutIntent | null>(
getIntent("checkout") ? checkoutInput.parse(getIntent("checkout")) : null,
);
const [busy, setBusy] = useState(false),
[error, setError] = useState<unknown>(null),
[addressId, setAddressId] = useState(""),
[coupon, setCoupon] = useState(""),
[uncertain, setUncertain] = useState(Boolean(attempt.current)),
[review, setReview] = useState(false);
const [reviewedVersion, setReviewedVersion] = useState<number | null>(null);
useEffect(() => {
if (review && query.data && query.data.version !== reviewedVersion) {
setReview(false);
setError(
new Error(
"The cart changed. Review the updated quantities before checkout.",
),
);
}
}, [review, query.data, reviewedVersion]);
async function edit(id: string, quantity: number, version: number) {
if (locked.current) return;
locked.current = true;
setBusy(true);
setError(null);
try {
z.number().int().min(0).max(100).parse(quantity);
await request(`/cart/lines/${id}`, z.object({ version: z.number() }), {
method: quantity ? "PUT" : "DELETE",
body: quantity ? { quantity, version } : { version },
});
await query.refetch();
} catch (error) {
setError(error);
if (error instanceof ApiError && error.code === "CART_CHANGED")
await query.refetch();
} finally {
locked.current = false;
setBusy(false);
setReview(false);
}
}
async function checkout() {
if (locked.current || (!attempt.current && !query.data)) return;
locked.current = true;
setBusy(true);
setError(null);
try {
if (!attempt.current) {
if (
!query.data ||
query.isFetching ||
query.data.version !== reviewedVersion
)
throw new Error("The cart changed. Review it again before checkout.");
attempt.current = checkoutIntent(
{
cartVersion: reviewedVersion,
addressId,
couponCode: coupon.trim() ? coupon : undefined,
},
crypto.randomUUID(),
);
saveIntent("checkout", attempt.current);
}
const result = await request("/checkout", order, {
method: "POST",
body: attempt.current,
});
clearIntent("checkout", attempt.current.idempotencyKey);
attempt.current = null;
setUncertain(false);
await query.refetch();
navigate(`/orders/${result.id}`);
} catch (error) {
setError(error);
if (isUnknownOutcome(error)) {
setUncertain(true);
} else {
if (attempt.current)
clearIntent("checkout", attempt.current.idempotencyKey);
attempt.current = null;
setReview(false);
await query.refetch();
}
} finally {
locked.current = false;
setBusy(false);
}
}
return (
<>
<Panel title="Cart">
<ApiNotice error={error} />
<QueryView query={query}>
{(data) => (
<>
{!data.lines.length ? (
<Alert severity="info">
Your cart is empty.{" "}
<Link href="/products">
<u>Explore candles</u>
</Link>
</Alert>
) : (
<>
<fieldset
className="cart-lines"
disabled={busy || uncertain || review}
>
{data.lines.map((line) => (
<div
className="cart-line"
key={`${line.variantId}-${data.version}`}
>
<div>
<h3>
{line.variant.product.name} · {line.variant.name}
</h3>
<p>
{line.variant.currency} {money(line.variant.price)}{" "}
each
</p>
{(!line.variant.active ||
line.variant.product.status !== "PUBLISHED") && (
<Alert severity="warning">
This variant is no longer available.
</Alert>
)}
</div>
<form
onSubmit={(e) => {
e.preventDefault();
const quantity = Number(
new FormData(e.currentTarget).get("quantity"),
);
void edit(line.variantId, quantity, data.version);
}}
>
<TextField
name="quantity"
label={`Quantity for ${line.variant.name}`}
type="number"
defaultValue={line.quantity}
inputProps={{ min: 1, max: 100, step: 1 }}
/>
<Button type="submit">Update</Button>
<Button
onClick={() =>
edit(line.variantId, 0, data.version)
}
>
Remove
</Button>
</form>
</div>
))}
</fieldset>
<p className="workspace-intro">
Estimated merchandise: {data.lines[0].variant.currency}{" "}
{moneyTotal(
data.lines.map((l) => ({
price: l.variant.price,
quantity: l.quantity,
})),
)}
</p>
<Alert severity="info">
The cart does not reserve stock. Checkout rechecks current
prices and creates a 15-minute hold. This estimate excludes
coupon, tax and shipping.
</Alert>
</>
)}
</>
)}
</QueryView>
</Panel>
<Panel title="Create an order">
<QueryView query={addresses}>
{(items) => (
<>
{!items.length ? (
<Alert severity="info">
Save an{" "}
<Link href="/addresses">
<u>address</u>
</Link>{" "}
before checkout.
</Alert>
) : (
<>
<TextField
select
label="Delivery address"
fullWidth
value={addressId}
onChange={(e) => {
setAddressId(e.target.value);
setReview(false);
}}
disabled={busy || uncertain || review}
>
{items.map((a) => (
<MenuItem key={a.id} value={a.id}>
{a.recipient} · {a.line1}, {a.city} {a.postalCode}
</MenuItem>
))}
</TextField>
<TextField
label="Coupon code (optional)"
fullWidth
value={coupon}
onChange={(e) => {
setCoupon(e.target.value);
setReview(false);
}}
inputProps={{ maxLength: 40 }}
disabled={busy || uncertain || review}
/>
</>
)}
</>
)}
</QueryView>
<Alert severity="warning">
Payment collection is unavailable. Creating an order reserves stock;
it does not charge you or confirm fulfillment.
</Alert>
{uncertain ? (
<>
<Alert severity="warning">
The result is unknown. Retry the exact original request to recover
it. Do not create another order until you have checked your order
history.
</Alert>
<Button
disabled={busy || (!uncertain && query.isFetching)}
variant="contained"
onClick={checkout}
>
Retry original checkout
</Button>
<Link href="/orders">
<u>Check orders</u>
</Link>
</>
) : review ? (
<>
<p>
Review the selected address, coupon and cart quantities above.
Confirm to create a pending order using the current server prices.
</p>
<Button disabled={busy} onClick={() => setReview(false)}>
Back to editing
</Button>
<Button
disabled={busy || (!uncertain && query.isFetching)}
variant="contained"
onClick={checkout}
>
{busy ? "Creating…" : "Confirm order"}
</Button>
</>
) : (
<Button
disabled={
busy ||
!addressId ||
!query.data?.lines.length ||
query.isFetching ||
addresses.isFetching ||
query.isError ||
addresses.isError ||
query.data.lines.some(
(l) =>
!l.variant.active || l.variant.product.status !== "PUBLISHED",
)
}
variant="contained"
onClick={() => {
setReviewedVersion(query.data?.version ?? null);
setReview(true);
}}
>
Review checkout
</Button>
)}
</Panel>
</>
);
}
export default function CartPage() {
return (
<WorkspaceShell title="My Cart">
<Cart />
</WorkspaceShell>
);
}

View File

@ -0,0 +1,434 @@
import { useState } from "react";
import { useLocation } from "wouter";
import { z } from "zod";
import Button from "@mui/material/Button";
import Alert from "@mui/material/Alert";
import {
adminProduct,
adminProductSummary,
productInput,
variant,
variantInput,
group,
groupInput,
money,
type AdminProduct,
uuid,
} from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import {
ActionForm,
Check,
Field,
Pager,
Panel,
QueryView,
Table,
usePrivateQuery,
readText,
WorkspaceLink,
} from "@/components/WorkspaceTools";
import { RecordSelection } from "@/components/RecordSelection";
import { ConfirmAction } from "@/components/ConfirmAction";
function ProductForm({
item,
onSave,
}: {
item?: AdminProduct;
onSave: () => Promise<unknown>;
}) {
const { request } = usePlatform(),
[, navigate] = useLocation();
return (
<ActionForm
key={item?.id || "new"}
label="Save product"
read={(data) => ({
name: readText(data, "name"),
slug: readText(data, "slug"),
description: readText(data, "description"),
groupIds: data.getAll("groupIds").map(String),
})}
submit={async (value) => {
const saved = await request(
item ? `/products/${item.id}` : "/products",
adminProductSummary,
{ method: item ? "PUT" : "POST", body: productInput.parse(value) },
);
await onSave();
if (!item) navigate(`/admin/catalog/${saved.id}`);
}}
>
<Field
name="name"
label="Product name"
maxLength={160}
value={item?.name}
/>
<Field
name="slug"
label="URL slug"
maxLength={160}
value={item?.slug}
helper="Lowercase words separated by hyphens."
/>
<Field
name="description"
label="Description"
required={false}
maxLength={5000}
value={item?.description}
/>
<RecordSelection
name="groupIds"
label="Categories and collections"
path="/catalog-groups"
initial={item?.groups.map((g) => g.group.id)}
/>
</ActionForm>
);
}
function VariantForm({
productId,
item,
onSave,
}: {
productId: string;
item?: z.infer<typeof variant>;
onSave: () => Promise<unknown>;
}) {
const { request } = usePlatform();
const [attributes, setAttributes] = useState(
Object.entries(item?.attributes || {}),
);
return (
<ActionForm
key={item?.id || "new"}
label="Save variant"
read={(data) => {
const entries = attributes.map((_, i) => [
readText(data, `key${i}`).trim(),
readText(data, `value${i}`),
]);
if (new Set(entries.map((e) => e[0])).size !== entries.length)
throw new Error("Attribute names must be unique.");
return {
name: readText(data, "name"),
sku: readText(data, "sku"),
price: readText(data, "price"),
currency: readText(data, "currency"),
active: data.has("active"),
attributes: Object.fromEntries(entries),
};
}}
submit={async (value) => {
await request(
`/products/${productId}/variants${item ? `/${item.id}` : ""}`,
variant,
{ method: item ? "PUT" : "POST", body: variantInput.parse(value) },
);
await onSave();
}}
>
<Field
name="name"
label="Variant name"
maxLength={160}
value={item?.name}
/>
<Field name="sku" label="SKU" maxLength={64} value={item?.sku} />
<Field
name="price"
label="Price"
value={item ? money(item.price) : ""}
helper="Positive decimal with two fractional digits, e.g. 250.00."
/>
<Field
name="currency"
label="Currency"
value={item?.currency || "INR"}
options={["INR", "USD", "EUR", "GBP"].map((value) => ({
value,
label: value,
}))}
/>
<Check
name="active"
label="Active variant"
value={item?.active ?? true}
/>
{attributes.map(([key, value], i) => (
<div className="attribute-row" key={i}>
<Field
name={`key${i}`}
label={`Attribute ${i + 1} name`}
value={key}
onChange={(next) =>
setAttributes((rows) =>
rows.map((row, index) => (index === i ? [next, row[1]] : row)),
)
}
maxLength={32}
/>
<Field
name={`value${i}`}
label={`Attribute ${i + 1} value`}
value={value}
onChange={(next) =>
setAttributes((rows) =>
rows.map((row, index) => (index === i ? [row[0], next] : row)),
)
}
maxLength={100}
/>
<Button
onClick={() =>
setAttributes((rows) => rows.filter((_, index) => index !== i))
}
>
Remove attribute
</Button>
</div>
))}
<Button
disabled={attributes.length >= 20}
onClick={() => setAttributes((rows) => [...rows, ["", ""]])}
>
Add attribute
</Button>
</ActionForm>
);
}
function Groups() {
const { request, can } = usePlatform();
const [offset, setOffset] = useState(0),
[editing, setEditing] = useState<z.infer<typeof group> | null>(null);
const query = usePrivateQuery(
`/catalog-groups?limit=25&offset=${offset}`,
z.array(group),
);
return (
<Panel title="Categories and collections">
<QueryView query={query}>
{(items) => (
<>
<Table
head={["Name", "Kind", "Slug", "Action"]}
rowKeys={items.map((item) => item.id)}
rows={items.map((g) => [
g.name,
g.kind,
g.slug,
can("catalog.manage") ? (
<Button onClick={() => setEditing(g)}>Edit</Button>
) : (
"Read only"
),
])}
/>
<Pager offset={offset} count={items.length} onPage={setOffset} />
</>
)}
</QueryView>
{can("catalog.manage") && (
<>
<ActionForm
key={editing?.id || "new"}
label="Save group"
read={(data) => ({
name: readText(data, "name"),
slug: readText(data, "slug"),
kind: readText(data, "kind"),
})}
submit={async (value) => {
await request(
editing ? `/catalog-groups/${editing.id}` : "/catalog-groups",
group,
{
method: editing ? "PUT" : "POST",
body: groupInput.parse(value),
},
);
setEditing(null);
await query.refetch();
}}
>
<Field
name="name"
label="Group name"
value={editing?.name}
maxLength={100}
/>
<Field
name="slug"
label="Group slug"
value={editing?.slug}
maxLength={100}
/>
<Field
name="kind"
label="Group kind"
value={editing?.kind || "CATEGORY"}
options={["CATEGORY", "COLLECTION"].map((value) => ({
value,
label: value,
}))}
/>
</ActionForm>
{editing && (
<Button onClick={() => setEditing(null)}>Cancel editing</Button>
)}
</>
)}
</Panel>
);
}
function Products() {
const { can } = usePlatform();
const [offset, setOffset] = useState(0);
const query = usePrivateQuery(
`/products?limit=25&offset=${offset}`,
z.array(adminProductSummary),
);
return (
<>
<Panel title="Products">
<QueryView query={query}>
{(items) => (
<>
<Table
head={["Product", "Status", "Slug"]}
rowKeys={items.map((item) => item.id)}
rows={items.map((p) => [
<WorkspaceLink href={`/admin/catalog/${p.id}`}>
{p.name}
</WorkspaceLink>,
p.status,
p.slug,
])}
/>
<Pager offset={offset} count={items.length} onPage={setOffset} />
</>
)}
</QueryView>
</Panel>
{can("catalog.manage") && (
<Panel title="New draft product">
<ProductForm onSave={() => query.refetch()} />
</Panel>
)}
<Groups />
</>
);
}
function ProductEditor({ id }: { id: string }) {
const { request, can } = usePlatform();
const query = usePrivateQuery(`/products/${id}`, adminProduct);
const [editingVariant, setEditingVariant] = useState<
z.infer<typeof variant> | undefined
>();
return (
<QueryView query={query}>
{(item) => (
<>
<Panel title={item.name}>
<p>Status: {item.status}</p>
<p className="workspace-id">Product ID: {item.id}</p>
{item.status === "ARCHIVED" ? (
<Alert severity="info">Archived products cannot be edited.</Alert>
) : (
<>
{can("catalog.manage") && (
<ProductForm item={item} onSave={() => query.refetch()} />
)}{" "}
{can("catalog.publish") &&
["DRAFT", "PUBLISHED", "ARCHIVED"]
.filter((status) => status !== item.status)
.map((status) => (
<ConfirmAction
key={status}
label={
status === "PUBLISHED"
? "Publish"
: status === "DRAFT"
? "Return to draft"
: "Archive"
}
message={
status === "ARCHIVED"
? "Archive this product? Archived products cannot be edited or republished."
: `Change this product to ${status.toLowerCase()}? Publishing requires an active variant.`
}
onConfirm={async () => {
await request(
`/products/${id}/status`,
adminProductSummary,
{ method: "PATCH", body: { status } },
);
await query.refetch();
}}
/>
))}
</>
)}
</Panel>
<Panel title="Variants">
<Table
head={["Variant", "SKU", "Price", "Active", "ID", "Action"]}
rowKeys={item.variants.map((item) => item.id)}
rows={item.variants.map((v) => [
v.name,
v.sku,
`${v.currency} ${money(v.price)}`,
v.active ? "Yes" : "No",
v.id,
can("catalog.manage") && item.status !== "ARCHIVED" ? (
<Button onClick={() => setEditingVariant(v)}>Edit</Button>
) : (
"Read only"
),
])}
/>
{can("catalog.manage") && item.status !== "ARCHIVED" && (
<>
<h3>
{editingVariant
? `Edit ${editingVariant.name}`
: "New variant"}
</h3>
<VariantForm
key={editingVariant?.id || "new"}
productId={id}
item={editingVariant}
onSave={async () => {
setEditingVariant(undefined);
await query.refetch();
}}
/>
{editingVariant && (
<Button onClick={() => setEditingVariant(undefined)}>
Cancel editing
</Button>
)}
</>
)}
</Panel>
</>
)}
</QueryView>
);
}
export default function CatalogAdminPage({ id }: { id?: string }) {
return (
<WorkspaceShell title="Catalog Administration" permission="catalog.read">
{id && !uuid.safeParse(id).success ? (
<Alert severity="error">Invalid product identifier.</Alert>
) : id ? (
<ProductEditor key={uuid.parse(id)} id={uuid.parse(id)} />
) : (
<Products />
)}
</WorkspaceShell>
);
}

370
src/pages/InventoryPage.tsx Normal file
View File

@ -0,0 +1,370 @@
import { useEffect, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import {
warehouse,
warehouseInput,
stock,
stockInput,
stockDetail,
adjustmentInput,
ledger,
reservation,
reservationInput,
uuid,
} from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import {
ActionForm,
Field,
Pager,
Panel,
QueryView,
Table,
usePrivateQuery,
readText,
readNumber,
WorkspaceLink,
} from "@/components/WorkspaceTools";
import { ConfirmAction } from "@/components/ConfirmAction";
function StockList() {
const { request, can } = usePlatform();
const [offset, setOffset] = useState(0),
[warehouseOffset, setWarehouseOffset] = useState(0);
const query = usePrivateQuery(
`/inventory/stock-items?limit=25&offset=${offset}`,
z.array(stock),
),
warehouses = usePrivateQuery(
`/inventory/warehouses?limit=25&offset=${warehouseOffset}`,
z.array(warehouse),
);
return (
<>
<Panel title="Finished-goods stock">
<QueryView query={query}>
{(items) => (
<>
<Table
head={["Stock item", "Variant", "Warehouse", "On hand"]}
rowKeys={items.map((item) => item.id)}
rows={items.map((s) => [
<WorkspaceLink href={`/admin/inventory/${s.id}`}>
{s.id}
</WorkspaceLink>,
s.variantId,
s.warehouseId,
s.onHand,
])}
/>
<Pager offset={offset} count={items.length} onPage={setOffset} />
</>
)}
</QueryView>
{can("inventory.manage") && (
<ActionForm
label="Create stock item"
read={(data) => ({
variantId: readText(data, "variantId"),
warehouseId: readText(data, "warehouseId"),
})}
submit={async (value) => {
await request("/inventory/stock-items", stock, {
method: "POST",
body: stockInput.parse(value),
});
await query.refetch();
}}
>
<Field
name="variantId"
label="Variant UUID"
helper="Copy the variant ID from catalog administration."
/>
<Field
name="warehouseId"
label="Warehouse UUID"
helper="Copy the warehouse ID from the warehouse list below."
/>
</ActionForm>
)}
</Panel>
<Panel title="Warehouses">
<QueryView query={warehouses}>
{(items) => (
<>
<Table
head={["Warehouse", "ID"]}
rowKeys={items.map((item) => item.id)}
rows={items.map((w) => [w.name, w.id])}
/>
<Pager
offset={warehouseOffset}
count={items.length}
onPage={setWarehouseOffset}
/>
</>
)}
</QueryView>
{can("inventory.manage") && (
<ActionForm
label="Create warehouse"
read={(data) => ({ name: readText(data, "name") })}
submit={async (value) => {
await request("/inventory/warehouses", warehouse, {
method: "POST",
body: warehouseInput.parse(value),
});
await warehouses.refetch();
}}
>
<Field name="name" label="Warehouse name" maxLength={100} />
</ActionForm>
)}
</Panel>
</>
);
}
function ReservationCard({ id }: { id: string }) {
const { request, can, scope } = usePlatform(),
query = usePrivateQuery(`/inventory/reservations/${id}`, reservation);
const client = useQueryClient(),
{ data, refetch } = query;
useEffect(() => {
if (data?.status !== "ACTIVE") return;
const timer = setTimeout(
() => {
void client.invalidateQueries({
predicate: (query) =>
query.queryKey[0] === "private" &&
query.queryKey[1] === scope &&
String(query.queryKey[2]).startsWith("/inventory/"),
});
},
Math.max(1000, Date.parse(data.expiresAt) - Date.now() + 250),
);
return () => clearTimeout(timer);
}, [data, client, scope]);
async function refreshStock() {
await refetch();
await client.invalidateQueries({
predicate: (query) =>
query.queryKey[0] === "private" &&
query.queryKey[1] === scope &&
String(query.queryKey[2]).startsWith("/inventory/"),
});
}
return (
<QueryView query={query}>
{(record) => (
<>
<p className="workspace-id">
Reservation {record.id}: {record.status}, {record.quantity} units.
Expires {new Date(record.expiresAt).toLocaleString()}.
</p>
{record.orderId && (
<Alert severity="info">
This hold is managed by its order and cannot be committed or
released here.
</Alert>
)}
{record.status === "ACTIVE" && !record.orderId && (
<>
<ConfirmAction
label="Release reservation"
message="Release this standalone hold? Order-managed holds cannot be changed here."
onConfirm={async () => {
await request(
`/inventory/reservations/${id}/release`,
reservation,
{ method: "POST" },
);
await refreshStock();
}}
/>
{can("inventory.commit") && (
<ConfirmAction
label="Commit reservation"
message="Commit this reservation? This deducts finished-goods stock and writes an immutable ledger entry."
onConfirm={async () => {
await request(
`/inventory/reservations/${id}/commit`,
reservation,
{ method: "POST" },
);
await refreshStock();
}}
/>
)}
</>
)}
</>
)}
</QueryView>
);
}
function StockEditor({ id }: { id: string }) {
const { can } = usePlatform();
const [offset, setOffset] = useState(0),
[reservationId, setReservationId] = useState("");
const query = usePrivateQuery(`/inventory/stock-items/${id}`, stockDetail),
history = usePrivateQuery(
`/inventory/stock-items/${id}/ledger?limit=25&offset=${offset}`,
z.array(ledger),
);
const adjust = useIdempotentCommand(
"/inventory/adjustments",
adjustmentInput,
ledger,
id,
),
reserve = useIdempotentCommand(
"/inventory/reservations",
reservationInput,
reservation,
id,
);
return (
<>
<Panel title="Stock balance">
<QueryView query={query}>
{(s) => (
<>
<p className="workspace-id">
Stock item: {s.id}
<br />
Variant: {s.variantId}
<br />
Warehouse: {s.warehouseId}
</p>
<dl className="order-totals">
<dt>On hand</dt>
<dd>{s.onHand}</dd>
<dt>Reserved</dt>
<dd>{s.reserved}</dd>
<dt>Available</dt>
<dd>{s.available}</dd>
</dl>
</>
)}
</QueryView>
</Panel>
{can("inventory.adjust") && (
<Panel title="Reasoned stock adjustment">
{adjust.uncertain && (
<Alert severity="warning">
The result is unknown. Retry the original adjustment; the same key
and input will be reused. Check the ledger before starting another
adjustment.
</Alert>
)}
<ActionForm
label={
adjust.uncertain ? "Retry original adjustment" : "Post adjustment"
}
lockFields={adjust.uncertain}
read={(data) => ({
stockItemId: id,
delta: readNumber(data, "delta"),
reason: readText(data, "reason"),
})}
submit={async (value) => {
await adjust.run(value);
await query.refetch();
await history.refetch();
}}
>
<Field
name="delta"
label="Quantity change (+ or −)"
type="number"
/>
<Field name="reason" label="Adjustment reason" maxLength={200} />
</ActionForm>
</Panel>
)}
{can("inventory.reserve") && (
<Panel title="Standalone stock reservation">
{reserve.uncertain && (
<Alert severity="warning">
Retry the original reservation to recover the same result.
</Alert>
)}
<ActionForm
label={
reserve.uncertain ? "Retry original reservation" : "Reserve stock"
}
lockFields={reserve.uncertain}
read={(data) => ({
stockItemId: id,
quantity: readNumber(data, "quantity"),
ttlMinutes: readNumber(data, "ttlMinutes"),
})}
submit={async (value) => {
const result = await reserve.run(value);
setReservationId(result.id);
await query.refetch();
}}
>
<Field name="quantity" label="Units to reserve" type="number" />
<Field
name="ttlMinutes"
label="Hold duration in minutes"
type="number"
value={15}
/>
</ActionForm>
<ActionForm
label="Look up own reservation"
read={(data) => readText(data, "id")}
submit={async (value) => {
setReservationId(z.string().uuid().parse(value));
}}
>
<Field name="id" label="Reservation UUID" />
</ActionForm>
{reservationId && (
<ReservationCard key={reservationId} id={reservationId} />
)}
</Panel>
)}
<Panel title="Immutable stock ledger">
<QueryView query={history}>
{(items) => (
<>
<Table
head={["Time", "Change", "Reason"]}
rowKeys={items.map((item) => item.id)}
rows={items.map((e) => [
new Date(e.createdAt).toLocaleString(),
e.delta,
e.reason,
])}
/>
<Pager offset={offset} count={items.length} onPage={setOffset} />
</>
)}
</QueryView>
</Panel>
</>
);
}
export default function InventoryPage({ id }: { id?: string }) {
return (
<WorkspaceShell
title="Finished-goods Inventory"
permission="inventory.read"
>
{id && !uuid.safeParse(id).success ? (
<Alert severity="error">Invalid stock identifier.</Alert>
) : id ? (
<StockEditor key={uuid.parse(id)} id={uuid.parse(id)} />
) : (
<StockList />
)}
</WorkspaceShell>
);
}

287
src/pages/OffersPage.tsx Normal file
View File

@ -0,0 +1,287 @@
import { useState } from "react";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import { coupon, couponInput, pricing, pricingInput } from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import {
ActionForm,
Field,
Pager,
Panel,
QueryView,
Table,
usePrivateQuery,
readText,
readNumber,
} from "@/components/WorkspaceTools";
import { ConfirmAction } from "@/components/ConfirmAction";
const currencies = ["INR", "USD", "EUR", "GBP"].map((value) => ({
value,
label: value,
}));
function Coupons() {
const { request } = usePlatform();
const [offset, setOffset] = useState(0),
[kind, setKind] = useState("PERCENT");
const query = usePrivateQuery(
`/coupons?limit=25&offset=${offset}`,
z.array(coupon),
);
return (
<>
<Panel title="Coupon rules">
<QueryView query={query}>
{(items) => (
<>
<Table
head={["Code", "Rule", "Window", "Status", "Action"]}
rowKeys={items.map((item) => item.id)}
rows={items.map((c) => [
c.code,
c.kind === "FIXED"
? `${c.currency} ${c.amount}`
: `${(c.percentBps || 0) / 100}%`,
`${new Date(c.startsAt).toLocaleString()} – ${new Date(c.endsAt).toLocaleString()}`,
c.active ? "Active" : "Inactive",
<ConfirmAction
label={c.active ? "Deactivate" : "Activate"}
message="Change this coupon's availability? Order snapshots remain unchanged."
onConfirm={async () => {
await request(`/coupons/${c.id}/status`, coupon, {
method: "PATCH",
body: { active: !c.active },
});
await query.refetch();
}}
/>,
])}
/>
<Pager offset={offset} count={items.length} onPage={setOffset} />
</>
)}
</QueryView>
</Panel>
<Panel title="Create an immutable coupon">
<Alert severity="info">
Rules cannot be edited after creation. Dates must include an explicit
timezone. Campaign-linked coupons belong to the growth phase.
</Alert>
<div className="coupon-kind">
<button
type="button"
onClick={() => setKind("PERCENT")}
aria-pressed={kind === "PERCENT"}
>
Percentage
</button>
<button
type="button"
onClick={() => setKind("FIXED")}
aria-pressed={kind === "FIXED"}
>
Fixed amount
</button>
</div>
<ActionForm
key={kind}
label="Create coupon"
read={(data) => ({
code: readText(data, "code"),
currency: readText(data, "currency"),
minimumSubtotal: readText(data, "minimumSubtotal"),
maxUses: readNumber(data, "maxUses"),
perUserLimit: readNumber(data, "perUserLimit"),
startsAt: readText(data, "startsAt"),
endsAt: readText(data, "endsAt"),
kind,
...(kind === "FIXED"
? { amount: readText(data, "amount") }
: { percentBps: readNumber(data, "percentBps") }),
})}
submit={async (value) => {
await request("/coupons", coupon, {
method: "POST",
body: couponInput.parse(value),
});
await query.refetch();
}}
>
<Field name="code" label="Coupon code" maxLength={40} />
<Field
name="currency"
label="Currency"
options={currencies}
value="INR"
/>
<Field
name="minimumSubtotal"
label="Minimum merchandise subtotal"
value="0.00"
/>
{kind === "FIXED" ? (
<Field
name="amount"
label="Fixed discount amount"
helper="Two decimal places, e.g. 50.00"
/>
) : (
<Field
name="percentBps"
label="Discount in basis points"
type="number"
helper="1000 means 10%; maximum 10000."
/>
)}
<Field name="maxUses" label="Total usage limit" type="number" />
<Field
name="perUserLimit"
label="Per-account usage limit"
type="number"
value={1}
/>
<Field
name="startsAt"
label="Starts at (ISO with timezone)"
helper="Example: 2026-10-12T00:00:00+05:30"
/>
<Field name="endsAt" label="Ends at (ISO with timezone)" />
</ActionForm>
</Panel>
</>
);
}
function Pricing() {
const { request } = usePlatform();
const [offset, setOffset] = useState(0);
const query = usePrivateQuery(
`/admin/pricing-policies?limit=25&offset=${offset}`,
z.array(pricing),
);
return (
<>
<Panel title="Pricing policy versions">
<Alert severity="warning">
Use approved tax and shipping rules. New versions do not reprice
existing orders and do not enable payment.
</Alert>
<QueryView query={query}>
{(items) => (
<>
<Table
head={["Policy", "Scope", "Tax mode", "Status", "Action"]}
rowKeys={items.map((item) => item.id)}
rows={items.map((p) => [
p.name,
`${p.currency} · ${p.countryCode} · ${p.region || "Country fallback"}`,
p.taxMode,
p.active ? "Active" : "Inactive",
<ConfirmAction
label={p.active ? "Deactivate" : "Activate"}
message="Change this policy's status? Activation disables the previous version for this scope."
onConfirm={async () => {
await request(
`/admin/pricing-policies/${p.id}/status`,
pricing,
{ method: "PATCH", body: { active: !p.active } },
);
await query.refetch();
}}
/>,
])}
/>
<Pager offset={offset} count={items.length} onPage={setOffset} />
</>
)}
</QueryView>
</Panel>
<Panel title="New inactive pricing policy">
<ActionForm
label="Create pricing policy"
read={(data) => ({
name: readText(data, "name"),
currency: readText(data, "currency"),
countryCode: readText(data, "countryCode"),
region: readText(data, "region"),
taxMode: readText(data, "taxMode"),
merchandiseTaxBps: readNumber(data, "merchandiseTaxBps"),
shippingTaxBps: readNumber(data, "shippingTaxBps"),
shippingFee: readText(data, "shippingFee"),
freeShippingMinimum: readText(data, "freeShippingMinimum") || null,
})}
submit={async (value) => {
await request("/admin/pricing-policies", pricing, {
method: "POST",
body: pricingInput.parse(value),
});
await query.refetch();
}}
>
<Field name="name" label="Policy name" maxLength={100} />
<Field
name="currency"
label="Currency"
value="INR"
options={currencies}
/>
<Field
name="countryCode"
label="Country code"
maxLength={2}
value="IN"
/>
<Field
name="region"
label="Region (blank for country fallback)"
required={false}
maxLength={100}
/>
<Field
name="taxMode"
label="Merchandise tax mode"
value="EXCLUSIVE"
options={["INCLUSIVE", "EXCLUSIVE"].map((value) => ({
value,
label: value,
}))}
/>
<Field
name="merchandiseTaxBps"
label="Merchandise tax basis points"
type="number"
/>
<Field
name="shippingFee"
label="Net shipping fee"
helper="Two decimal places."
/>
<Field
name="shippingTaxBps"
label="Shipping tax basis points"
type="number"
/>
<Field
name="freeShippingMinimum"
label="Free-shipping minimum (optional)"
required={false}
helper="Leave blank if there is no threshold."
/>
</ActionForm>
</Panel>
</>
);
}
export default function OffersPage({
pricing: showPricing = false,
}: {
pricing?: boolean;
}) {
return (
<WorkspaceShell
title={showPricing ? "Pricing Policies" : "Coupon Administration"}
permission={showPricing ? "pricing.manage" : "coupons.manage"}
>
{showPricing ? <Pricing /> : <Coupons />}
</WorkspaceShell>
);
}

176
src/pages/OrdersPage.tsx Normal file
View File

@ -0,0 +1,176 @@
import { useEffect, useState } from "react";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import { order, orderSummary, money, uuid } from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import {
Pager,
Panel,
QueryView,
Table,
usePrivateQuery,
WorkspaceLink,
} from "@/components/WorkspaceTools";
import { ConfirmAction } from "@/components/ConfirmAction";
function OrderList({ admin }: { admin: boolean }) {
const [offset, setOffset] = useState(0);
const path = admin ? "/admin/orders" : "/orders";
const query = usePrivateQuery(
`${path}?limit=25&offset=${offset}`,
z.array(orderSummary),
);
const { refetch } = query;
useEffect(() => {
const timer = setInterval(() => {
void refetch();
}, 30000);
return () => clearInterval(timer);
}, [refetch]);
return (
<Panel title="Order history">
<QueryView query={query}>
{(items) => (
<>
<Table
head={["Order", "Status", "Merchandise", "Created"]}
rowKeys={items.map((item) => item.id)}
rows={items.map((item) => [
<WorkspaceLink href={`${path}/${item.id}`}>
{item.id}
</WorkspaceLink>,
item.status,
`${item.currency} ${money(item.merchandiseTotal)}`,
new Date(item.createdAt).toLocaleString(),
])}
/>
<Pager offset={offset} count={items.length} onPage={setOffset} />
</>
)}
</QueryView>
</Panel>
);
}
function OrderDetail({ admin, id }: { admin: boolean; id: string }) {
const { request, can } = usePlatform(),
path = `${admin ? "/admin/orders" : "/orders"}/${id}`,
query = usePrivateQuery(path, order);
const { refetch } = query;
useEffect(() => {
if (!query.data || query.data.status !== "PENDING_PAYMENT") return;
const timeout = setTimeout(
() => {
void refetch();
},
Math.max(1000, Date.parse(query.data.expiresAt) - Date.now() + 250),
);
return () => clearTimeout(timeout);
}, [query.data, refetch]);
return (
<Panel title="Order details">
<QueryView query={query}>
{(item) => (
<>
<p className="workspace-id">
Order {item.id} · {item.status}
</p>
<p>Hold expires: {new Date(item.expiresAt).toLocaleString()}</p>
<Table
head={["Candle", "SKU", "Quantity", "Unit price", "Line total"]}
rowKeys={item.lines.map((line) => line.variantId)}
rows={item.lines.map((l) => [
`${l.productName} · ${l.variantName}`,
l.sku,
l.quantity,
`${item.currency} ${money(l.unitPrice)}`,
`${item.currency} ${money(l.lineTotal)}`,
])}
/>
<dl className="order-totals">
<dt>Subtotal</dt>
<dd>
{item.currency} {money(item.subtotal)}
</dd>
<dt>Discount</dt>
<dd>
{item.currency} {money(item.discount)}
</dd>
<dt>Merchandise total</dt>
<dd>
{item.currency} {money(item.merchandiseTotal)}
</dd>
<dt>Tax</dt>
<dd>
{item.taxTotal === null
? "Unfinalized"
: `${item.currency} ${money(item.taxTotal)}`}
</dd>
<dt>Shipping</dt>
<dd>
{item.shippingTotal === null
? "Unfinalized"
: `${item.currency} ${money(item.shippingTotal)}`}
</dd>
<dt>Server payable total</dt>
<dd>
{item.payableTotal === null
? "Unfinalized"
: `${item.currency} ${money(item.payableTotal)}`}
</dd>
</dl>
<Alert severity="info">
{item.pricingStatus === "UNFINALIZED"
? "Tax and shipping have not been finalized. "
: "Tax may already be included in merchandise prices. "}
Payment collection is unavailable.
</Alert>
<h3>Delivery snapshot</h3>
<p>
{item.address.recipient}
<br />
{item.address.line1} {item.address.line2}
<br />
{item.address.city}, {item.address.region}{" "}
{item.address.postalCode}
<br />
{item.address.countryCode} · {item.address.phone}
</p>
{item.status === "PENDING_PAYMENT" &&
(!admin || can("orders.manage")) && (
<ConfirmAction
label="Cancel order"
message="Cancel this order and release its stock holds? Cancellation does not rebuild your cart."
onConfirm={async () => {
await request(`${path}/cancel`, order, { method: "POST" });
await query.refetch();
}}
/>
)}
</>
)}
</QueryView>
</Panel>
);
}
export default function OrdersPage({
admin = false,
id,
}: {
admin?: boolean;
id?: string;
}) {
return (
<WorkspaceShell
title={admin ? "Organization Orders" : "My Orders"}
permission={admin ? "orders.read" : undefined}
>
{id && !uuid.safeParse(id).success ? (
<Alert severity="error">Invalid order identifier.</Alert>
) : id ? (
<OrderDetail key={uuid.parse(id)} admin={admin} id={uuid.parse(id)} />
) : (
<OrderList admin={admin} />
)}
</WorkspaceShell>
);
}

View File

@ -9,6 +9,8 @@ import { getProduct } from "@/lib/api";
import { usePlatform } from "@/lib/platform"; import { usePlatform } from "@/lib/platform";
import { ApiNotice } from "@/components/ApiNotice"; import { ApiNotice } from "@/components/ApiNotice";
import "./products.css"; import "./products.css";
import { AddToCart } from "@/components/AddToCart";
import { money } from "@/lib/commerce";
export default function ProductPage({ id }: { id: string }) { export default function ProductPage({ id }: { id: string }) {
const { organization } = usePlatform(); const { organization } = usePlatform();
@ -73,15 +75,19 @@ export default function ProductPage({ id }: { id: string }) {
</dl> </dl>
</div> </div>
<strong> <strong>
{variant.currency} {variant.price} {variant.currency} {money(variant.price)}
</strong> </strong>
<AddToCart
key={`${variant.id}-${organization}`}
variantId={variant.id}
/>
</li> </li>
))} ))}
</ul> </ul>
)} )}
<Alert severity="info"> <Alert severity="info">
Ordering will be available in the commerce phase. Payment and Orders reserve stock while pending. Payment and shipping
shipping integrations are not enabled yet. integrations are not enabled yet.
</Alert> </Alert>
</div> </div>
)} )}

138
src/pages/RecoveryPage.tsx Normal file
View File

@ -0,0 +1,138 @@
import { useState } from "react";
import { Link } from "wouter";
import { z } from "zod";
import Container from "@mui/material/Container";
import Alert from "@mui/material/Alert";
import { apiRequest, parse, organizationSchema } from "@/lib/api";
import { clearRecoveryToken, getRecoveryToken } from "@/lib/recovery-token";
import { usePlatform } from "@/lib/platform";
import {
ActionForm,
Field,
Panel,
readText,
} from "@/components/WorkspaceTools";
import "./workspace.css";
export default function RecoveryPage({ reset = false }: { reset?: boolean }) {
const { organization, clearSession } = usePlatform();
const [complete, setComplete] = useState(false);
const token = getRecoveryToken();
return (
<section className="workspace-page">
<Container maxWidth="sm">
<h1>{reset ? "Reset Password" : "Account Recovery"}</h1>
<Panel
title={
reset ? "Choose a new password" : "Request recovery instructions"
}
>
{complete ? (
<Alert severity="success">
{reset
? "Your password was reset and previous sessions were invalidated."
: "If the account is eligible, recovery instructions will be sent."}{" "}
<Link href="/workspace">
<u>Return to sign-in</u>
</Link>
</Alert>
) : reset ? (
!token ? (
<Alert severity="warning">
This reset link is missing or invalid. Request a new recovery
link.
</Alert>
) : (
<ActionForm
label="Reset password"
read={(data) => {
const password = readText(data, "password");
if (password !== readText(data, "confirm"))
throw new Error("Passwords do not match.");
return { token, password };
}}
submit={async (value) => {
const body = z
.object({
token: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
password: z.string().min(15).max(128),
})
.strict()
.parse(value);
parse(
z.null(),
await apiRequest("/auth/recovery/reset", {
method: "POST",
body,
}),
);
clearRecoveryToken();
clearSession(
"Password reset. Sign in with your new password.",
);
setComplete(true);
}}
>
<Field
name="password"
label="New password"
type="password"
maxLength={128}
helper="15–128 characters."
/>
<Field
name="confirm"
label="Confirm new password"
type="password"
maxLength={128}
/>
</ActionForm>
)
) : (
<>
<Alert severity="info">
Recovery delivery requires the backend SMTP configuration.
Acceptance does not confirm account existence or email delivery.
</Alert>
<ActionForm
label="Request recovery"
read={(data) => ({
organizationId: readText(data, "organizationId"),
email: readText(data, "email"),
})}
submit={async (value) => {
const body = z
.object({
organizationId: organizationSchema,
email: z.string().email().max(254).toLowerCase(),
})
.strict()
.parse(value);
parse(
z.object({ message: z.string() }),
await apiRequest("/auth/recovery/request", {
method: "POST",
body,
}),
);
setComplete(true);
}}
>
<Field
name="organizationId"
label="Organization UUID"
value={organization}
/>
<Field
name="email"
label="Account email"
type="email"
maxLength={254}
/>
</ActionForm>
</>
)}
</Panel>
</Container>
</section>
);
}

View File

@ -8,6 +8,7 @@ import Alert from "@mui/material/Alert";
import { usePlatform } from "@/lib/platform"; import { usePlatform } from "@/lib/platform";
import { ApiNotice } from "@/components/ApiNotice"; import { ApiNotice } from "@/components/ApiNotice";
import "./workspace.css"; import "./workspace.css";
import { WorkspaceNavigation } from "@/components/WorkspaceShell";
export default function WorkspacePage() { export default function WorkspacePage() {
const { organization, principal, signIn, signOut, notice } = usePlatform(); const { organization, principal, signIn, signOut, notice } = usePlatform();
@ -44,7 +45,7 @@ export default function WorkspacePage() {
return ( return (
<section className="workspace-page"> <section className="workspace-page">
<Container maxWidth="md"> <Container maxWidth="md">
<h1>Staff Workspace</h1> <h1>Account Workspace</h1>
<p className="workspace-intro"> <p className="workspace-intro">
Sign in with your approved Mani Candles account. Sign in with your approved Mani Candles account.
</p> </p>
@ -53,6 +54,7 @@ export default function WorkspacePage() {
{notice && <Alert severity="info">{notice}</Alert>} {notice && <Alert severity="info">{notice}</Alert>}
{principal ? ( {principal ? (
<> <>
<WorkspaceNavigation />
<h2>Your session</h2> <h2>Your session</h2>
<p className="workspace-id"> <p className="workspace-id">
Organization: {principal.organizationId} Organization: {principal.organizationId}
@ -69,8 +71,7 @@ export default function WorkspacePage() {
<p>No permissions assigned. Contact your administrator.</p> <p>No permissions assigned. Contact your administrator.</p>
)} )}
<p className="workspace-intro"> <p className="workspace-intro">
Operational tools will be connected in the following frontend Open a customer or administration tool below.
phases.
</p> </p>
<Button variant="contained" disabled={busy} onClick={logout}> <Button variant="contained" disabled={busy} onClick={logout}>
{busy ? "Signing out…" : "Sign out"} {busy ? "Signing out…" : "Sign out"}
@ -115,6 +116,9 @@ export default function WorkspacePage() {
Sessions stay in memory. Reloading or closing this page requires Sessions stay in memory. Reloading or closing this page requires
a new sign-in. a new sign-in.
</small> </small>
<Link href="/recovery">
<u>Forgot password?</u>
</Link>
</form> </form>
)} )}
</Paper> </Paper>

View File

@ -53,7 +53,7 @@ export default function Home() {
}, 8000); }, 8000);
return () => clearInterval(interval); return () => clearInterval(interval);
}, []); }, [moods.length]);
return ( return (
<Box> <Box>

View File

@ -56,3 +56,116 @@
padding: 1.25rem; padding: 1.25rem;
} }
} }
.workspace-links {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin: 1.5rem 0;
}
.workspace-panel {
margin: 1.5rem 0;
}
.workspace-form fieldset {
border: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 1.25rem;
min-width: 0;
}
.workspace-table {
overflow-x: auto;
}
.workspace-table table {
border-collapse: collapse;
width: 100%;
font-size: 0.9rem;
}
.workspace-table th,
.workspace-table td {
padding: 0.75rem;
text-align: left;
border-bottom: 1px solid var(--brand-border);
overflow-wrap: anywhere;
}
.workspace-table th {
white-space: nowrap;
}
.workspace-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 1.5rem;
}
.workspace-grid .workspace-panel {
margin: 0;
}
.order-totals {
display: grid;
grid-template-columns: 1fr auto;
gap: 0.75rem;
margin: 1.5rem 0;
}
@media (max-width: 768px) {
.workspace-grid {
grid-template-columns: 1fr;
}
}
.cart-lines {
border: 0;
min-width: 0;
}
.cart-line {
border-bottom: 1px solid var(--brand-border);
padding: 1.5rem 0;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 1rem;
}
.cart-line form,
.cart-add {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
}
.cart-line input,
.cart-add input {
max-width: 100px;
}
.address-card {
padding: 1rem 0;
border-bottom: 1px solid var(--brand-border);
}
.record-picker {
border: 1px solid var(--brand-border) !important;
padding: 1rem !important;
}
.attribute-row {
display: grid;
grid-template-columns: 1fr 1fr auto;
gap: 0.75rem;
}
.coupon-kind {
display: flex;
gap: 1rem;
margin-top: 1rem;
}
.coupon-kind button {
padding: 0.75rem;
background: var(--brand-card);
border: 1px solid var(--brand-purple);
color: var(--brand-purple);
cursor: pointer;
}
.coupon-kind button[aria-pressed="true"] {
background: var(--brand-purple);
color: white;
}
@media (max-width: 768px) {
.attribute-row {
grid-template-columns: 1fr;
}
}

241
test/phase2.test.ts Normal file
View File

@ -0,0 +1,241 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { productSchema, organizationSchema } from "../src/lib/api.ts";
import {
captureRecoveryToken,
getRecoveryToken,
clearRecoveryToken,
} from "../src/lib/recovery-token.ts";
import {
addressInput,
address,
role,
group,
variant,
warehouse,
stock,
stockInput,
adminProductSummary,
pricing,
checkoutInput,
couponInput,
variantInput,
money,
moneyTotal,
checkoutIntent,
} from "../src/lib/commerce.ts";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
test("organization UUIDs normalize case before session organization checks", () => {
assert.equal(organizationSchema.parse(id.toUpperCase()), id);
});
test("stock identifiers normalize case before request and retry scopes", () => {
assert.equal(
stockInput.parse({
variantId: id.toUpperCase(),
warehouseId: id.toUpperCase(),
}).variantId,
id,
);
});
test("response schemas accept persisted metadata while write schemas stay strict", () => {
const extra = {
id,
organizationId: id,
createdAt: "2026-10-12T00:00:00.000Z",
};
const samples = [
[
address,
{
...extra,
recipient: "A",
line1: "Street",
line2: "",
city: "City",
region: "State",
postalCode: "100000",
countryCode: "IN",
phone: "+919999999999",
isDefault: true,
},
],
[role, { ...extra, name: "Staff", permissions: [], isSystem: false }],
[group, { ...extra, name: "Floral", slug: "floral", kind: "CATEGORY" }],
[
variant,
{
...extra,
productId: id,
sku: "A",
name: "Small",
price: "10",
currency: "INR",
active: true,
attributes: {},
},
],
[warehouse, { ...extra, name: "Main" }],
[stock, { ...extra, variantId: id, warehouseId: id, onHand: 10 }],
[
adminProductSummary,
{
...extra,
name: "Candle",
slug: "candle",
description: "",
status: "DRAFT",
},
],
[
pricing,
{
...extra,
name: "India",
currency: "INR",
countryCode: "IN",
region: "",
taxMode: "EXCLUSIVE",
merchandiseTaxBps: 0,
shippingFee: "0",
shippingTaxBps: 0,
freeShippingMinimum: null,
active: false,
},
],
] as const;
for (const [schema, value] of samples) {
const parsed = schema.safeParse(value);
assert.equal(parsed.success, true, JSON.stringify(parsed));
}
assert.equal(addressInput.safeParse(samples[0][1]).success, false);
});
test("recovery token is captured in memory and removed from URL history", () => {
const token = "A".repeat(43);
let replaced = "";
captureRecoveryToken(
{ hash: `#token=${token}`, pathname: "/reset-password", search: "" },
{
replaceState: (_data, _unused, url) => {
replaced = url;
},
},
);
assert.equal(replaced, "/reset-password");
assert.equal(getRecoveryToken(), token);
clearRecoveryToken();
assert.equal(getRecoveryToken(), null);
captureRecoveryToken(
{ hash: "#token=invalid", pathname: "/reset-password", search: "" },
{
replaceState: (_data, _unused, url) => {
replaced = url;
},
},
);
assert.equal(getRecoveryToken(), null);
});
test("backend decimal output accepts integer and one-decimal strings", () => {
for (const price of ["10", "10.5", "10.50"])
assert.equal(
productSchema.safeParse({
id,
name: "Candle",
slug: "candle",
description: "",
variants: [
{
id,
name: "Small",
sku: "CANDLE",
price,
currency: "INR",
attributes: {},
},
],
groups: [],
}).success,
true,
);
});
test("money display and estimated totals remain exact", () => {
assert.equal(money("10.5"), "10.50");
assert.equal(
moneyTotal([
{ price: "0.1", quantity: 3 },
{ price: "9999999999.99", quantity: 100 },
]),
"999999999999.30",
);
for (const invalid of ["NaN", "1e3", "-1", "1.234"])
assert.throws(() => money(invalid));
});
test("write schemas reject unsafe input before requests", () => {
assert.equal(
variantInput.safeParse({
sku: "A",
name: "Candle",
price: "10.5",
currency: "INR",
active: true,
attributes: {},
}).success,
false,
);
assert.equal(
addressInput.safeParse({
recipient: "A",
line1: "Street",
line2: "",
city: "City",
region: "State",
postalCode: "100000",
countryCode: "IN",
phone: "not-phone",
isDefault: false,
}).success,
false,
);
assert.equal(
checkoutInput.safeParse({
cartVersion: 0,
addressId: id,
idempotencyKey: id,
organizationId: id,
}).success,
false,
);
});
test("checkout intent normalizes coupon and freezes identical retry payload", () => {
const intent = checkoutIntent(
{ cartVersion: 3, addressId: id, couponCode: " save10 " },
id,
);
assert.deepEqual(intent, {
cartVersion: 3,
addressId: id,
couponCode: "SAVE10",
idempotencyKey: id,
});
assert.equal(Object.isFrozen(intent), true);
});
test("coupon date, currency and usage rules are enforced", () => {
const valid = {
code: "SAVE",
currency: "INR",
minimumSubtotal: "0.00",
kind: "PERCENT",
percentBps: 1000,
maxUses: 5,
perUserLimit: 1,
startsAt: "2026-10-12T00:00:00+05:30",
endsAt: "2026-10-13T00:00:00+05:30",
};
assert.equal(couponInput.safeParse(valid).success, true);
for (const change of [
{ percentBps: 10001 },
{ perUserLimit: 6 },
{ endsAt: valid.startsAt },
{ currency: "XXX" },
])
assert.equal(couponInput.safeParse({ ...valid, ...change }).success, false);
});

309
test/session.ui.test.tsx Normal file
View File

@ -0,0 +1,309 @@
import { StrictMode, type ReactNode } from "react";
import { act, renderHook, waitFor } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { z } from "zod";
import { PlatformProvider, usePlatform } from "../src/lib/platform";
import { useIdempotentCommand } from "../src/lib/use-idempotent-command";
import { adjustmentInput, ledger } from "../src/lib/commerce";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
const me = {
userId: id,
organizationId: id,
sessionId: id,
permissions: ["users.read"],
};
const session = {
accessToken: "test-opaque",
tokenType: "Bearer",
expiresAt: new Date(Date.now() + 3600000).toISOString(),
};
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status });
afterEach(() => {
vi.unstubAllGlobals();
vi.useRealTimers();
});
function harness() {
localStorage.setItem("mani.organization", id);
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
const wrapper = ({ children }: { children: ReactNode }) => (
<StrictMode>
<QueryClientProvider client={client}>
<PlatformProvider>{children}</PlatformProvider>
</QueryClientProvider>
</StrictMode>
);
return { client, ...renderHook(() => usePlatform(), { wrapper }) };
}
test("old-session intent callbacks cannot erase a newer session's command", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) =>
url.endsWith("/auth/login")
? json(session)
: url.endsWith("/auth/logout")
? new Response(null, { status: 204 })
: json(me),
),
);
const h = harness();
await act(() =>
h.result.current.signIn("staff@example.com", "test password"),
);
const old = h.result.current;
await act(() => old.signOut());
await act(() =>
h.result.current.signIn("staff@example.com", "test password"),
);
const next = { idempotencyKey: "new-key", cartVersion: 2 };
h.result.current.saveIntent("checkout", next);
old.clearIntent("checkout", "new-key");
old.saveIntent("checkout", { idempotencyKey: "old-key" });
expect(h.result.current.getIntent("checkout")).toEqual(next);
h.result.current.clearIntent("checkout", "wrong-key");
expect(h.result.current.getIntent("checkout")).toEqual(next);
h.result.current.clearIntent("checkout", "new-key");
expect(h.result.current.getIntent("checkout")).toBeUndefined();
});
test("absolute expiry removes private data and pending commands", async () => {
vi.useFakeTimers();
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) =>
url.endsWith("/auth/login")
? json({
...session,
expiresAt: new Date(Date.now() + 60000).toISOString(),
})
: json(me),
),
);
const h = harness();
await act(() =>
h.result.current.signIn("staff@example.com", "test password"),
);
h.client.setQueryData(
["private", h.result.current.scope, "/orders"],
[{ private: "order" }],
);
h.result.current.saveIntent("checkout", { idempotencyKey: id });
await act(async () => {
vi.advanceTimersByTime(61000);
});
expect(h.result.current.principal).toBeNull();
expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]);
expect(h.result.current.getIntent("checkout")).toBeUndefined();
});
test("permission-change cancellation preserves a submitted stock command for exact replay", async () => {
let principalReads = 0,
finish: (response: Response) => void = () => {
throw new Error("Not submitted");
};
const attempts: unknown[] = [];
vi.stubGlobal(
"fetch",
vi.fn(async (url: string, options?: RequestInit) => {
if (url.endsWith("/auth/login")) return json(session);
if (url.endsWith("/auth/me"))
return json({
...me,
permissions:
++principalReads === 1
? ["users.read", "inventory.adjust"]
: ["inventory.adjust"],
});
if (url.endsWith("/users")) return json({ message: "Denied" }, 403);
attempts.push(JSON.parse(String(options?.body)));
if (attempts.length === 1)
return new Promise<Response>((resolve) => {
finish = resolve;
});
return json({
id,
delta: -1,
reason: "Test",
createdAt: new Date().toISOString(),
});
}),
);
localStorage.setItem("mani.organization", id);
const client = new QueryClient();
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={client}>
<PlatformProvider>{children}</PlatformProvider>
</QueryClientProvider>
);
const h = renderHook(
() => ({
platform: usePlatform(),
command: useIdempotentCommand(
"/inventory/adjustments",
adjustmentInput,
ledger,
id,
),
}),
{ wrapper },
);
await act(() =>
h.result.current.platform.signIn("staff@example.com", "test password"),
);
let pending: Promise<unknown>;
act(() => {
pending = h.result.current.command
.run({ stockItemId: id, delta: -1, reason: "Test" })
.catch((error) => error);
});
await act(async () => {
await h.result.current.platform
.request("/users", z.unknown())
.catch((error) => error);
});
await act(async () => {
finish(
json({
id,
delta: -1,
reason: "Test",
createdAt: new Date().toISOString(),
}),
);
await pending;
});
expect(h.result.current.command.uncertain).toBe(true);
expect(
h.result.current.platform.getIntent(`/inventory/adjustments:${id}`),
).toEqual(attempts[0]);
await act(() =>
h.result.current.command.run({
stockItemId: id,
delta: 999,
reason: "Changed",
}),
);
expect(attempts[1]).toEqual(attempts[0]);
expect(h.result.current.command.uncertain).toBe(false);
});
test("logout network failure clears auth and private caches immediately", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) => {
if (url.endsWith("/auth/login")) return json(session);
if (url.endsWith("/auth/me")) return json(me);
throw new Error("Offline");
}),
);
const h = harness();
await act(() =>
h.result.current.signIn("staff@example.com", "test password"),
);
h.client.setQueryData(
["private", id, "/addresses"],
[{ private: "address" }],
);
await act(async () => {
await expect(h.result.current.signOut()).rejects.toThrow(
"signed out locally",
);
});
expect(h.result.current.principal).toBeNull();
expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]);
});
test("authenticated 401 clears the matching session but not a later login", async () => {
let finish: (response: Response) => void = () => {
throw new Error("Request not started");
};
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) => {
if (url.endsWith("/auth/login")) return json(session);
if (url.endsWith("/auth/me")) return json(me);
return new Promise<Response>((resolve) => {
finish = resolve;
});
}),
);
const h = harness();
await act(() =>
h.result.current.signIn("staff@example.com", "test password"),
);
let pending: Promise<unknown>;
act(() => {
pending = h.result.current
.request("/addresses", z.array(z.unknown()))
.catch((error) => error);
});
await act(() =>
h.result.current.signIn("staff@example.com", "test password"),
);
await act(async () => {
finish(json({ message: "Expired" }, 401));
await pending;
});
expect(h.result.current.principal).not.toBeNull();
let denied: Promise<unknown>;
act(() => {
denied = h.result.current
.request("/addresses", z.array(z.unknown()))
.catch((error) => error);
});
await act(async () => {
finish(json({ message: "Expired" }, 401));
await denied;
});
expect(h.result.current.principal).toBeNull();
});
test("403 refreshes effective permissions without retaining the denied action", async () => {
let calls = 0;
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) =>
url.endsWith("/auth/login")
? json(session)
: url.endsWith("/auth/me")
? json({ ...me, permissions: ++calls === 1 ? ["users.read"] : [] })
: json({ message: "Denied" }, 403),
),
);
const h = harness();
await act(() =>
h.result.current.signIn("staff@example.com", "test password"),
);
const oldScope = h.result.current.scope;
h.client.setQueryData(
["private", oldScope, "/users"],
[{ private: "staff record" }],
);
await act(async () => {
await expect(
h.result.current.request("/users", z.array(z.unknown())),
).rejects.toThrow("Denied");
});
expect(h.result.current.can("users.read")).toBe(false);
expect(h.result.current.scope).not.toBe(oldScope);
expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]);
});
test("organization change cancels private scope and removes cached data", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) =>
url.endsWith("/auth/login") ? json(session) : json(me),
),
);
const h = harness();
await act(() =>
h.result.current.signIn("staff@example.com", "test password"),
);
h.client.setQueryData(["private", id, "/orders"], [{ private: "order" }]);
act(() =>
h.result.current.setOrganization("f66c798a-f764-4b88-8d13-ace328ff1010"),
);
await waitFor(() => expect(h.result.current.scope).toBe(""));
expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]);
});

6
test/setup.ts Normal file
View File

@ -0,0 +1,6 @@
import { afterEach } from "vitest";
import { cleanup } from "@testing-library/react";
afterEach(() => {
cleanup();
localStorage.clear();
});

286
test/workflows.ui.test.tsx Normal file
View File

@ -0,0 +1,286 @@
import { type ReactNode } from "react";
import { act, render, screen, waitFor } from "@testing-library/react";
import { Table } from "../src/components/WorkspaceTools";
import { ConfirmAction } from "../src/components/ConfirmAction";
import userEvent from "@testing-library/user-event";
import { afterEach, expect, test, vi } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "@mui/material/styles";
import axe from "axe-core";
import { PlatformProvider, usePlatform } from "../src/lib/platform";
import CartPage from "../src/pages/CartPage";
import AccessPage, { RolesPage } from "../src/pages/AccessPage";
import OrdersPage from "../src/pages/OrdersPage";
import theme from "../src/theme";
import { Switch, Route } from "wouter";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
test("table refresh keeps an open confirmation bound to its original record", async () => {
const approve = vi.fn(async (_id: string) => undefined);
const table = (ids: string[]) => (
<Table
head={["Name", "Action"]}
rowKeys={ids}
rows={ids.map((id) => [
id,
<ConfirmAction
label="Approve"
message={`Approve ${id}?`}
onConfirm={() => approve(id)}
/>,
])}
/>
);
const view = render(table(["A", "B"])),
user = userEvent.setup();
await user.click(screen.getAllByRole("button", { name: "Approve" })[0]);
view.rerender(table(["B", "A"]));
await user.click(screen.getByRole("button", { name: "Confirm" }));
expect(approve).toHaveBeenCalledWith("A");
});
test("role-read accounts can view roles without user-read access", async () => {
const fetch = vi.fn(async (url: string) =>
url.endsWith("/auth/login")
? json(session)
: url.endsWith("/auth/me")
? json({ ...me, permissions: ["roles.read"] })
: url.includes("/roles?")
? json([
{
id,
name: "Observer",
permissions: [],
isSystem: false,
organizationId: id,
},
])
: Promise.reject(new Error("Unexpected private request")),
);
vi.stubGlobal("fetch", fetch);
harness(<RolesPage />);
const user = userEvent.setup();
await user.click(screen.getByText("Test login"));
await screen.findByText("Observer");
expect(fetch.mock.calls.some(([url]) => url.includes("/users"))).toBe(false);
expect(screen.queryByRole("link", { name: "Access" })).toBeNull();
});
const me = { userId: id, organizationId: id, sessionId: id, permissions: [] };
const session = {
accessToken: "test-opaque",
tokenType: "Bearer",
expiresAt: new Date(Date.now() + 3600000).toISOString(),
};
const address = {
id,
recipient: "Test Recipient",
line1: "Test Street",
line2: "",
city: "Test City",
region: "Test State",
postalCode: "123456",
countryCode: "IN",
phone: "+919999999999",
isDefault: true,
};
const line = {
variantId: id,
quantity: 1,
variant: {
name: "Small",
sku: "TEST",
price: "10",
currency: "INR",
active: true,
product: { name: "Test candle", status: "PUBLISHED" },
},
};
const { id: _addressId, isDefault: _isDefault, ...snapshotAddress } = address;
const order = {
id,
status: "PENDING_PAYMENT",
currency: "INR",
merchandiseTotal: "10",
subtotal: "10",
discount: "0",
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 900000).toISOString(),
pricingStatus: "UNFINALIZED",
taxTotal: null,
shippingTotal: null,
payableTotal: null,
paymentAvailable: false,
address: snapshotAddress,
lines: [
{
variantId: id,
sku: "TEST",
productName: "Test candle",
variantName: "Small",
quantity: 1,
unitPrice: "10",
lineTotal: "10",
},
],
};
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status });
afterEach(() => {
vi.unstubAllGlobals();
history.replaceState(null, "", "/");
});
function Login() {
const platform = usePlatform();
return (
<button
onClick={() => platform.signIn("staff@example.com", "test password")}
>
Test login
</button>
);
}
function harness(children: ReactNode) {
localStorage.setItem("mani.organization", id);
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
const result = render(
<ThemeProvider theme={theme}>
<QueryClientProvider client={client}>
<PlatformProvider>
<Login />
{children}
</PlatformProvider>
</QueryClientProvider>
</ThemeProvider>,
);
return { client, ...result };
}
test("uncertain checkout replays identical input after the cart version changes", async () => {
const attempts: unknown[] = [];
let cartChanged = false;
vi.stubGlobal(
"fetch",
vi.fn(async (url: string, options?: RequestInit) => {
if (url.endsWith("/auth/login")) return json(session);
if (url.endsWith("/auth/me")) return json(me);
if (url.endsWith("/addresses")) return json([address]);
if (url.endsWith("/cart"))
return json({
version: cartChanged ? 1 : 0,
lines: cartChanged ? [] : [line],
});
if (url.endsWith("/checkout")) {
attempts.push(JSON.parse(String(options?.body)));
cartChanged = true;
if (attempts.length === 1) throw new Error("Response lost");
return json(order);
}
if (url.includes("/orders?")) return json([]);
if (url.includes(`/orders/${id}`)) return json(order);
throw new Error(`Unexpected ${url}`);
}),
);
history.replaceState(null, "", "/cart");
const h = harness(
<Switch>
<Route path="/cart" component={CartPage} />
<Route path="/orders">{() => <OrdersPage />}</Route>
<Route path="/orders/:id">
{(params) => <OrdersPage id={params.id} />}
</Route>
</Switch>,
),
user = userEvent.setup();
await user.click(screen.getByText("Test login"));
await screen.findByText("Test candle · Small");
await user.click(screen.getByRole("combobox", { name: "Delivery address" }));
await user.click(await screen.findByRole("option"));
await user.click(screen.getByRole("button", { name: "Review checkout" }));
await user.click(screen.getByRole("button", { name: "Confirm order" }));
await screen.findByRole("button", { name: "Retry original checkout" });
await act(() => h.client.invalidateQueries({ queryKey: ["private"] }));
await screen.findByText(/Your cart is empty/);
await user.click(screen.getByRole("link", { name: "Check orders" }));
await screen.findByText("Order history");
await user.click(screen.getByRole("link", { name: "My cart" }));
await user.click(
screen.getByRole("button", { name: "Retry original checkout" }),
);
await waitFor(() => expect(attempts).toHaveLength(2));
expect(attempts[1]).toEqual(attempts[0]);
expect(attempts[0]).toMatchObject({ cartVersion: 0, addressId: id });
await waitFor(() => expect(location.pathname).toBe(`/orders/${id}`));
});
test("a changed cart invalidates checkout review instead of adopting a new version", async () => {
let changed = false;
const attempts: unknown[] = [];
vi.stubGlobal(
"fetch",
vi.fn(async (url: string, options?: RequestInit) => {
if (url.endsWith("/auth/login")) return json(session);
if (url.endsWith("/auth/me")) return json(me);
if (url.endsWith("/addresses")) return json([address]);
if (url.endsWith("/cart"))
return json({
version: changed ? 2 : 0,
lines: [{ ...line, quantity: changed ? 3 : 1 }],
});
attempts.push(options?.body);
return json(order);
}),
);
const h = harness(<CartPage />),
user = userEvent.setup();
await user.click(screen.getByText("Test login"));
await screen.findByText("Test candle · Small");
await user.click(screen.getByRole("combobox", { name: "Delivery address" }));
await user.click(await screen.findByRole("option"));
await user.click(screen.getByRole("button", { name: "Review checkout" }));
changed = true;
await act(() => h.client.invalidateQueries({ queryKey: ["private"] }));
await screen.findByText(/Review the updated quantities/);
expect(screen.queryByRole("button", { name: "Confirm order" })).toBeNull();
expect(attempts).toEqual([]);
});
test("permission-denied administration never fetches private staff records", async () => {
const fetch = vi.fn(async (url: string) =>
url.endsWith("/auth/login")
? json(session)
: url.endsWith("/auth/me")
? json(me)
: Promise.reject(new Error("Private records must not be fetched")),
);
vi.stubGlobal("fetch", fetch);
const h = harness(<AccessPage />),
user = userEvent.setup();
await user.click(screen.getByText("Test login"));
await screen.findByText(/does not have permission/);
expect(fetch.mock.calls.some(([url]) => url.includes("/users"))).toBe(false);
const result = await axe.run(h.container, {
rules: { "color-contrast": { enabled: false } },
});
expect(
result.violations.filter(
(v) => v.impact === "serious" || v.impact === "critical",
),
).toEqual([]);
});
test("unfinalized order charges are never shown as zero or payable", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) =>
url.endsWith("/auth/login")
? json(session)
: url.endsWith("/auth/me")
? json(me)
: json(order),
),
);
harness(<OrdersPage id={id} />);
const user = userEvent.setup();
await user.click(screen.getByText("Test login"));
await screen.findByText(/Order .*PENDING_PAYMENT/);
expect(screen.getAllByText("Unfinalized")).toHaveLength(3);
expect(screen.queryByRole("button", { name: /pay now/i })).toBeNull();
expect(screen.getByText(/Payment collection is unavailable/)).toBeTruthy();
});

View File

@ -1,6 +1,6 @@
{ {
"include": ["src/**/*"], "include": ["src/**/*", "test/**/*", "vite.config.ts", "vitest.config.ts"],
"exclude": ["node_modules", "build", "dist", "**/*.test.ts"], "exclude": ["node_modules", "build", "dist"],
"compilerOptions": { "compilerOptions": {
"target": "ES2020", "target": "ES2020",
"useDefineForClassFields": true, "useDefineForClassFields": true,

View File

@ -17,6 +17,11 @@ export default defineConfig({
build: { build: {
outDir: path.resolve(projectRoot, "dist"), outDir: path.resolve(projectRoot, "dist"),
emptyOutDir: true, emptyOutDir: true,
rollupOptions: {
output: {
manualChunks: { validation: ["zod"] },
},
},
}, },
server: { server: {
port: 5173, port: 5173,

11
vitest.config.ts Normal file
View File

@ -0,0 +1,11 @@
import { defineConfig } from "vitest/config";
import { fileURLToPath } from "node:url";
export default defineConfig({
resolve: { alias: { "@": fileURLToPath(new URL("./src", import.meta.url)) } },
test: {
environment: "jsdom",
include: ["test/*.ui.test.tsx"],
setupFiles: ["test/setup.ts"],
restoreMocks: true,
},
});