Compare commits

..

No commits in common. "main" and "feat/b2b-samples" have entirely different histories.

46 changed files with 369 additions and 2418 deletions

View File

@ -1,61 +1,47 @@
kind: pipeline kind: pipeline
type: docker type: docker
name: Validate and deploy frontend name: Build Image
steps: steps:
- name: Validate Nginx configuration - name: Quality gates
image: nginx:alpine image: node:24-alpine
commands: commands:
- printf 'events {}\nhttp { server { listen 8080; include /drone/src/deploy/nginx-locations.conf; } }\n' > /tmp/manicandles-nginx.conf - npm ci
- nginx -t -c /tmp/manicandles-nginx.conf - npm audit --audit-level=high
- npm run check
- name: Quality gates
image: node:24-alpine - name: Build Docker Image
environment: image: plugins/docker
# Keep jsdom suites from competing for CPU on the Drone runner. settings:
VITEST_MAX_WORKERS: "1" username:
commands: from_secret: docker_username
- npm ci password:
- npm audit --audit-level=high from_secret: docker_password
- npm run check repo: git.midastix.com/ci-docker-repo-user/manicandles
- apk add --no-cache util-linux registry: git.midastix.com
- sh test/deployment.test.sh
- printf '%s\n' '${DRONE_BUILD_NUMBER}-${DRONE_COMMIT_SHA}' > dist/release.txt when:
branch:
- name: Upload frontend release - main
image: appleboy/drone-scp event:
settings: - push
host: server1.midastix.com
username: mihir - name: Deploy image
key: image: appleboy/drone-ssh
from_secret: manicandles_deploy_key settings:
port: 22 host: server1.midastix.com
source: dist,scripts/deploy-frontend.sh username: root
target: /var/www/manicandles/incoming/${DRONE_BUILD_NUMBER}-${DRONE_COMMIT_SHA} key:
from_secret: server_ssh_pkey
when: port: 22
branch: command_timeout: 5m
- main script:
event: - echo "Deploying ManiCandles"
- push - sudo /opt/deployable/manicandles/docker/deploy.sh
- echo "Completed Deployment"
- name: Activate and verify frontend when:
image: appleboy/drone-ssh branch:
settings: - main
host: server1.midastix.com event:
username: mihir - push
key:
from_secret: manicandles_deploy_key
port: 22
command_timeout: 5m
script_stop: true
script:
- sh /var/www/manicandles/incoming/${DRONE_BUILD_NUMBER}-${DRONE_COMMIT_SHA}/scripts/deploy-frontend.sh /var/www/manicandles '${DRONE_BUILD_NUMBER}-${DRONE_COMMIT_SHA}' manicandles.midastix.com
when:
branch:
- main
event:
- push

1
.gitattributes vendored
View File

@ -1 +0,0 @@
*.sh text eol=lf

View File

@ -25,11 +25,11 @@ docker build -t manicandles-frontend:uat .
docker run --rm -p 8080:80 manicandles-frontend:uat docker run --rm -p 8080:80 manicandles-frontend:uat
``` ```
After the one-time [server setup](docs/STATIC-DEPLOYMENT.md), main-branch Drone pushes upload the checked static build over SSH and activate it through the existing Nginx HTTPS site. Readiness failure restores the previous release. Drone requires the `manicandles_deploy_key` secret. Feature branches run validation without uploading or activating a release. The existing main-branch Drone pipeline deploys automatically on push. Work is on a feature branch; a local build is not deployment verification. Docker was unavailable locally for container verification.
Storefront list returns id/name/slug and the main photo; details return prices/attributes/groups and all photos. Staff upload up to 8 JPEG/PNG/WebP photos per product (2 MiB each) under Admin catalog; products without photos show a branded placeholder. 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.
Addresses, cart/checkout, orders, catalog, access, stock, coupons and pricing tools are available after sign-in. Customers can create their own account at `/workspace` (requires the backend `/auth/register` endpoint). 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).

View File

@ -1,48 +0,0 @@
# Include inside the existing HTTPS server block for manicandles.midastix.com.
# This supplies the root and locations. Keep the existing TLS directives.
root /var/www/manicandles/current;
index index.html;
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy strict-origin-when-cross-origin always;
add_header X-Frame-Options DENY always;
add_header Cache-Control "no-cache" 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/ {
proxy_pass https://manicandles-backend.midastix.com;
proxy_ssl_server_name on;
proxy_ssl_verify on;
proxy_ssl_verify_depth 3;
proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
proxy_set_header Host manicandles-backend.midastix.com;
proxy_set_header Authorization $http_authorization;
# The backend rate-limits per client IP; it trusts this hop via TRUST_PROXY.
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 10s;
proxy_read_timeout 20s;
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Credentials;
location ~ "^/api/v1/(?:(?:supplier-documents|b2b/artworks)/[0-9a-fA-F-]{36}/versions|products/[0-9a-fA-F-]{36}/images)$" {
client_max_body_size 3m;
proxy_pass https://manicandles-backend.midastix.com;
}
}
location = /release.txt {
try_files $uri =404;
}
location /assets/ {
try_files $uri @previous_assets;
}
# Existing browser tabs may still request the preceding release's chunks.
location @previous_assets {
root /var/www/manicandles/previous;
try_files $uri =404;
}
location / {
try_files $uri $uri/ /index.html;
}

View File

@ -58,10 +58,4 @@ Customer and administration screens are implemented, with recovery, pricing, sto
- Credit policy UAT should verify that unverified accounts and self-review are rejected, a second active policy in the same currency cannot be approved, and suspension permits a replacement. - Credit policy UAT should verify that unverified accounts and self-review are rejected, a second active policy in the same currency cannot be approved, and suspension permits a replacement.
- B2B samples support requests for published variants, independent approval or rejection, and manual dispatch records with staff and reference history. - B2B samples support requests for published variants, independent approval or rejection, and manual dispatch records with staff and reference history.
- Sample UAT should verify ineligible accounts and variants, self-review, dispatch only after approval, and replay with the original payload and key. - Sample UAT should verify ineligible accounts and variants, self-review, dispatch only after approval, and replay with the original payload and key.
- B2B artwork supports private PDF, PNG, and JPEG version uploads, independent review, and permission-based downloads. - Artwork, partner orders and payments, custom requests and reporting remain open.
- Artwork UAT should use separate uploader, reviewer, and reader accounts. Exercise the 2 MiB upload limit through ingress, approval and rejection, download permissions, and preservation of prior approved versions.
- Partner orders support conversion from accepted, unexpired quotations, immutable merchandise snapshots, and reasoned cancellation.
- Partner order UAT should verify expired quotes, duplicate references and quote conversion, exact retries, and cancellation blocked by an active payment receipt.
- Partner payments support manual external receipts, exact paid and outstanding merchandise balances, receipt details, and confirmed reasoned reversals. Read and manage permissions are separate, and payment readers can open an order's payment history without order-read permission.
- Partner payment UAT should exercise partial and full receipts, duplicate references, overpayments, cancelled orders, exact retries for recording and reversal, restored balances, and cancellation after reversing all active receipts. References normalize to uppercase and remain reserved after reversal.
- Custom requests and reporting remain open.

View File

@ -34,8 +34,8 @@ Production release is blocked until the environment checks below pass. Local imp
## Rollback ## Rollback
Record the active and previous build/commit release IDs before rollout. The SSH deployment restores the previous release automatically when its HTTPS checks fail. Follow the [static deployment runbook](STATIC-DEPLOYMENT.md) for manual rollback, then verify health, SPA deep links and /api connectivity. Retain orders, stock ledgers and accounts. Confirm the actual host procedure and measured rollback time in UAT before production. A feature-branch push does not deploy the main-branch pipeline. 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 ## 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 or contact delivery; customer self-registration is available. 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. 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.

View File

@ -1,90 +0,0 @@
# SSH deployment to server1
Drone validates the application and Nginx snippet, uploads `dist` and the release
script, and activates the release through SSH. The sole deployment secret is
`manicandles_deploy_key`. SSH uses `mihir@server1.midastix.com:22`.
## One-time server setup
Server inspection on 19 November 2026 found an HTTP-only site at
`/etc/nginx/sites-enabled/ManiCandles.midastix.com.conf`, with its old root at
`/var/www/ManiCandles.midastix.com`. Certbot is installed. The setup script is
specific to that configuration and refuses to overwrite a site with TLS settings.
Obtain this branch's files on server1 using your existing repository access.
From the repository directory, run the following as `mihir`.
```sh
sudo sh scripts/setup-static-host.sh
sudo certbot --nginx -d manicandles.midastix.com --redirect
sudo nginx -t
curl --fail --show-error https://manicandles.midastix.com/
```
Alternatively, copy `scripts/setup-static-host.sh` and
`deploy/nginx-locations.conf` together to `/tmp/` on server1, and run
`sudo sh /tmp/setup-static-host.sh`, followed by the Certbot and verification
commands above. The snippet must be beside the setup script for this layout.
Setup backs up the original site under `/var/backups`, prepares writable release
directories, installs the snippet, validates Nginx, and reloads it. Validation or
reload failure restores the saved site file. If the old root contains an index,
setup retains it as the initial `current` release and a rollback target. If no
old index exists, the frontend awaits its first deployment. DNS must point to
server1 and public port 80 must be reachable for certificate issuance. Complete
Certbot's email and agreement prompts yourself. Verify HTTPS before merging.
Save the complete matching private key in Drone's `manicandles_deploy_key`
secret. Its public key must be authorized for `mihir` on server1. Keep the
private key outside the repository and logs.
## Release and acceptance
After server setup, merge the change into main. Main-branch push builds perform
an SSH access check before the quality gates. Feature branches validate the
configuration, test rollback, and build the frontend without publishing a release.
Uploads first enter `incoming/BUILD-COMMIT`. A completed build moves to
`releases/BUILD-COMMIT/dist` under the deployment lock. Retried uploads cannot
overwrite a published release. A file lock
serializes activation. An older build cannot replace a newer active build.
The `current` symlink changes atomically. HTTPS checks use the real hostname
resolved to loopback and verify the certificate, release marker, homepage,
`/workspace`, `/cart`, and `/api/v1/health/ready`. Readiness must return the backend's
`{"status":"ok"}` response. An HTML fallback fails verification. Failure restores the previous
current symlink, or removes the first activation if no release existed before it.
The last successful release is also retained at `previous`. Its assets can serve
requests from browser tabs opened before the update. Failed first deployments
leave the site awaiting a successful release.
After the main build succeeds, test externally from a trusted terminal.
```sh
curl --fail --show-error https://manicandles.midastix.com/release.txt
curl --fail --show-error https://manicandles.midastix.com/api/v1/health/ready
```
Then exercise authenticated UAT journeys. The frontend release does not provision
an organization or user accounts.
## Manual rollback
As `mihir` on server1, restore the preceding successful release under the same
lock used by CI. Verify the marker and API after switching. Coordinate this with
active pipelines because a later successful deployment can activate a new release.
```sh
(
set -eu
cd /var/www/manicandles
flock -x 9
test -s previous/index.html
ln -s "$(readlink previous)" .rollback-current
mv -Tf .rollback-current current
) 9>/var/www/manicandles/.deploy.lock
curl --fail --show-error https://manicandles.midastix.com/release.txt
curl --fail --show-error https://manicandles.midastix.com/api/v1/health/ready
```
Retain release directories until rollback has been verified. Disk retention is
manual in this initial deployment flow.

View File

@ -4,14 +4,14 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
<title>Mani Candles Co.</title> <title>Mani Candles Co.</title>
<meta name="description" content="Handmade luxury candles from Mani Candles Co., poured in small batches." /> <meta name="description" content="Mani Candles Co. — built on Replit. Update this description to reflect the app." />
<meta name="robots" content="index, follow" /> <meta name="robots" content="index, follow" />
<meta property="og:title" content="Mani Candles Co." /> <meta property="og:title" content="Mani Candles Co." />
<meta property="og:description" content="Handmade luxury candles from Mani Candles Co., poured in small batches." /> <meta property="og:description" content="Mani Candles Co. — built on Replit. Update this description to reflect the app." />
<meta property="og:type" content="website" /> <meta property="og:type" content="website" />
<meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Mani Candles Co." /> <meta name="twitter:title" content="Mani Candles Co." />
<meta name="twitter:description" content="Handmade luxury candles from Mani Candles Co., poured in small batches." /> <meta name="twitter:description" content="Mani Candles Co. — built on Replit. Update this description to reflect the app." />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

View File

@ -12,18 +12,15 @@ server {
proxy_pass https://manicandles-backend.midastix.com; proxy_pass https://manicandles-backend.midastix.com;
proxy_ssl_server_name on; proxy_ssl_server_name on;
proxy_ssl_verify on; proxy_ssl_verify on;
proxy_ssl_verify_depth 3;
proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt; proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
proxy_set_header Host manicandles-backend.midastix.com; proxy_set_header Host manicandles-backend.midastix.com;
proxy_set_header Authorization $http_authorization; proxy_set_header Authorization $http_authorization;
# The backend rate-limits per client IP; it trusts this hop via TRUST_PROXY.
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 10s; proxy_connect_timeout 10s;
proxy_read_timeout 20s; proxy_read_timeout 20s;
proxy_hide_header Access-Control-Allow-Origin; proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Credentials; proxy_hide_header Access-Control-Allow-Credentials;
location ~ "^/api/v1/(?:(?:supplier-documents|b2b/artworks)/[0-9a-fA-F-]{36}/versions|products/[0-9a-fA-F-]{36}/images)$" { location ~ "^/api/v1/supplier-documents/[0-9a-fA-F-]{36}/versions$" {
client_max_body_size 3m; client_max_body_size 3m;
proxy_pass https://manicandles-backend.midastix.com; proxy_pass https://manicandles-backend.midastix.com;
} }

178
package-lock.json generated
View File

@ -1265,15 +1265,15 @@
} }
}, },
"node_modules/@eslint/config-array": { "node_modules/@eslint/config-array": {
"version": "0.23.6", "version": "0.23.5",
"resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.6.tgz", "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz",
"integrity": "sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==", "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==",
"dev": true, "dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@eslint/object-schema": "^3.0.5", "@eslint/object-schema": "^3.0.5",
"debug": "^4.3.1", "debug": "^4.3.1",
"minimatch": "^11.0.5" "minimatch": "^10.2.4"
}, },
"engines": { "engines": {
"node": "^20.19.0 || ^22.13.0 || >=24" "node": "^20.19.0 || ^22.13.0 || >=24"
@ -1486,13 +1486,6 @@
"url": "https://github.com/sponsors/nzakas" "url": "https://github.com/sponsors/nzakas"
} }
}, },
"node_modules/@isaacs/nonrecursive-glob-match": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
"integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
"dev": true,
"license": "BlueOak-1.0.0"
},
"node_modules/@jridgewell/gen-mapping": { "node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13", "version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@ -4290,17 +4283,17 @@
} }
}, },
"node_modules/@typescript-eslint/eslint-plugin": { "node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.74.0", "version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.74.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.2.tgz",
"integrity": "sha512-z3KXk1+Vm+d82ZRplOoC89ho4Rf1da5ju6sx8//92GnN532U62DGPjECXkkVqtYzIv0zoJlpO39SX2Z9tk6LVw==", "integrity": "sha512-222PKFXKihmFpi/pS5njoBgdAqsPhj2/GBmFbrNw8Tq8gEG9Sv+kSlKFy4u2q+mJv9ZzJgM2Gkv/bUzRZwZw5g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@eslint-community/regexpp": "^4.12.2", "@eslint-community/regexpp": "^4.12.2",
"@typescript-eslint/scope-manager": "8.74.0", "@typescript-eslint/scope-manager": "8.72.2",
"@typescript-eslint/type-utils": "8.74.0", "@typescript-eslint/type-utils": "8.72.2",
"@typescript-eslint/utils": "8.74.0", "@typescript-eslint/utils": "8.72.2",
"@typescript-eslint/visitor-keys": "8.74.0", "@typescript-eslint/visitor-keys": "8.72.2",
"ignore": "^7.0.5", "ignore": "^7.0.5",
"natural-compare": "^1.4.0", "natural-compare": "^1.4.0",
"ts-api-utils": "^2.5.0" "ts-api-utils": "^2.5.0"
@ -4313,15 +4306,15 @@
"url": "https://opencollective.com/typescript-eslint" "url": "https://opencollective.com/typescript-eslint"
}, },
"peerDependencies": { "peerDependencies": {
"@typescript-eslint/parser": "^8.74.0", "@typescript-eslint/parser": "^8.72.2",
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
"typescript": ">=4.8.4 <6.1.0" "typescript": ">=4.8.4 <6.1.0"
} }
}, },
"node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
"version": "7.0.16", "version": "7.0.14",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.16.tgz", "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.14.tgz",
"integrity": "sha512-52N+Y4HRMOJmbLmr+DqO4iSRyyB7N52gm7PWCT6h0p978+oKbqHCB7gIJIwZvBUsjlSdWbrBFqUSmIFNZMpn0A==", "integrity": "sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
@ -4329,16 +4322,16 @@
} }
}, },
"node_modules/@typescript-eslint/parser": { "node_modules/@typescript-eslint/parser": {
"version": "8.74.0", "version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.74.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.2.tgz",
"integrity": "sha512-ecr8AYdig7avVkxaHdQvxHnIJ/mOyliO4Gv/uWF8q69vBew/z3sexqBwHUZX5Vql+Ns0w4sH6gBLkICGbOvJkA==", "integrity": "sha512-llP+T1YuJOLlxEciP6OyQGtz5SMxyn+9LA2BvZw5RmToGVa1y4beEDVQL6Gje7T5WFYh19WREjDCN9Ev4gm5AA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "8.74.0", "@typescript-eslint/scope-manager": "8.72.2",
"@typescript-eslint/types": "8.74.0", "@typescript-eslint/types": "8.72.2",
"@typescript-eslint/typescript-estree": "8.74.0", "@typescript-eslint/typescript-estree": "8.72.2",
"@typescript-eslint/visitor-keys": "8.74.0", "@typescript-eslint/visitor-keys": "8.72.2",
"debug": "^4.4.3" "debug": "^4.4.3"
}, },
"engines": { "engines": {
@ -4354,14 +4347,14 @@
} }
}, },
"node_modules/@typescript-eslint/project-service": { "node_modules/@typescript-eslint/project-service": {
"version": "8.74.0", "version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.74.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.2.tgz",
"integrity": "sha512-z/mymuE+JlEeSFIv3Mo70EvgG1Zz74Hl0IDfExfXutARAP834bt+MppTD7mVAwmZO0GdxdOAi0jbTam749eH6g==", "integrity": "sha512-6y5dLTZdHhI8Eh3yIQ/bfQhRKwn5e+TpJj64o18Cngc0iW/BCrVvrr6zGYqXPnYH31u6YXAYiFh0+qxX5mybJw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/tsconfig-utils": "^8.74.0", "@typescript-eslint/tsconfig-utils": "^8.72.2",
"@typescript-eslint/types": "^8.74.0", "@typescript-eslint/types": "^8.72.2",
"debug": "^4.4.3" "debug": "^4.4.3"
}, },
"engines": { "engines": {
@ -4376,14 +4369,14 @@
} }
}, },
"node_modules/@typescript-eslint/scope-manager": { "node_modules/@typescript-eslint/scope-manager": {
"version": "8.74.0", "version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.74.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.2.tgz",
"integrity": "sha512-kpOdpu4CpWN5U38ox3f727DwWRBtUAVhyUJtqTBYe5gf2wYoxac7PgKP14txrxN7ICVtcjlLdzjqfRgpSnDKvQ==", "integrity": "sha512-iIoMJ6/8c1/QpFNyFjU0d1YzPco4MsZjQw0k3V+vfzNWAFmUmvhlyMoYEoYYDQZXc+J6Gi1X5XcxlzW2taIIGQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/types": "8.74.0", "@typescript-eslint/types": "8.72.2",
"@typescript-eslint/visitor-keys": "8.74.0" "@typescript-eslint/visitor-keys": "8.72.2"
}, },
"engines": { "engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0" "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@ -4394,9 +4387,9 @@
} }
}, },
"node_modules/@typescript-eslint/tsconfig-utils": { "node_modules/@typescript-eslint/tsconfig-utils": {
"version": "8.74.0", "version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.74.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.2.tgz",
"integrity": "sha512-p07wAuaS6BjCYgOSXKJi4YhvTnAf7fiG37e9THcpnYaQEt2QiTTYZWKwUFNgeRiywiMudazhzgddAirZ0GgHtQ==", "integrity": "sha512-+h3iCgZXuTNtoLXcnnjP12ZUHLMqoUcIHPfQrFEXTUqvb9dF8QK9b5nv5VtSo5fLkdHuks8ehbTzZj3rImAm9w==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
@ -4411,15 +4404,15 @@
} }
}, },
"node_modules/@typescript-eslint/type-utils": { "node_modules/@typescript-eslint/type-utils": {
"version": "8.74.0", "version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.74.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.2.tgz",
"integrity": "sha512-CV3Y3la8l3F9ANfxcfpgSSiQgJTe4IeLEoZV4O/gcW86Ugp8X6SKiQ0vm+QegXaRIbbDMokZZSF3A1CgiU/kPw==", "integrity": "sha512-STfkR38qIdhfkLpgtXnUjAzsNy4xouqiBO0lrVc/Wpk9Kem5/aHXUx1J8dGC16zpdYN1+yc2ILQ28er1kXX7ag==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/types": "8.74.0", "@typescript-eslint/types": "8.72.2",
"@typescript-eslint/typescript-estree": "8.74.0", "@typescript-eslint/typescript-estree": "8.72.2",
"@typescript-eslint/utils": "8.74.0", "@typescript-eslint/utils": "8.72.2",
"debug": "^4.4.3", "debug": "^4.4.3",
"ts-api-utils": "^2.5.0" "ts-api-utils": "^2.5.0"
}, },
@ -4436,9 +4429,9 @@
} }
}, },
"node_modules/@typescript-eslint/types": { "node_modules/@typescript-eslint/types": {
"version": "8.74.0", "version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.74.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.2.tgz",
"integrity": "sha512-MpnMrJCVNpP1iVL8NiHkQZgQqIMBH5ewDGUPBh1pqQXwFtMFjsl1M03QcYPXmv6stCKEiF0PN7CGbU1ZbXFzEA==", "integrity": "sha512-Xfn37OLZx03+PCU7qWx9DTv2FCRh1E6fk2+wONeNY15HXIwtcwuveaSwVpGAUptkNmPQegRxW5JyRel9T7wrog==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
@ -4450,18 +4443,18 @@
} }
}, },
"node_modules/@typescript-eslint/typescript-estree": { "node_modules/@typescript-eslint/typescript-estree": {
"version": "8.74.0", "version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.74.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.2.tgz",
"integrity": "sha512-wL348k6l92DNG+kPP5rVpKwNBoz7a3xRZy3TPKc1uymQttd7u7gcMv3eENmcuh4CjC4mO3FTM0DYstFXMyDLuw==", "integrity": "sha512-pQEGqIK/cqEvKivVWaFLYpe7XYejFxfuAOi4mu1oAWFvIo36aRHI9esRFTUxcIy/z8N482RJyH+LpZB0ZIU7Ow==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/project-service": "8.74.0", "@typescript-eslint/project-service": "8.72.2",
"@typescript-eslint/tsconfig-utils": "8.74.0", "@typescript-eslint/tsconfig-utils": "8.72.2",
"@typescript-eslint/types": "8.74.0", "@typescript-eslint/types": "8.72.2",
"@typescript-eslint/visitor-keys": "8.74.0", "@typescript-eslint/visitor-keys": "8.72.2",
"debug": "^4.4.3", "debug": "^4.4.3",
"minimatch": "^11.0.1", "minimatch": "^10.2.2",
"semver": "^7.7.3", "semver": "^7.7.3",
"tinyglobby": "^0.2.15", "tinyglobby": "^0.2.15",
"ts-api-utils": "^2.5.0" "ts-api-utils": "^2.5.0"
@ -4474,13 +4467,7 @@
"url": "https://opencollective.com/typescript-eslint" "url": "https://opencollective.com/typescript-eslint"
}, },
"peerDependencies": { "peerDependencies": {
"@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev",
"typescript": ">=4.8.4 <6.1.0" "typescript": ">=4.8.4 <6.1.0"
},
"peerDependenciesMeta": {
"@typescript/native": {
"optional": true
}
} }
}, },
"node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": {
@ -4497,16 +4484,16 @@
} }
}, },
"node_modules/@typescript-eslint/utils": { "node_modules/@typescript-eslint/utils": {
"version": "8.74.0", "version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.74.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.2.tgz",
"integrity": "sha512-IpWXPxXXomzxyTcvjhZJexgdvtTR1TooLAPpuxzaGqQ8BHll1lf4Ysp/BTE/l0U5TJ+x1j7B4bEM8pLRrvY+XA==", "integrity": "sha512-hv3eRYbpPbbpezuax1EfGrzpa3C4ySgNZkPUkLOWOAjU8HsOKowEDAr8C7nsNl1C+SBSKDpvno6VKHnlhvp9iA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.9.1", "@eslint-community/eslint-utils": "^4.9.1",
"@typescript-eslint/scope-manager": "8.74.0", "@typescript-eslint/scope-manager": "8.72.2",
"@typescript-eslint/types": "8.74.0", "@typescript-eslint/types": "8.72.2",
"@typescript-eslint/typescript-estree": "8.74.0" "@typescript-eslint/typescript-estree": "8.72.2"
}, },
"engines": { "engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0" "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@ -4521,13 +4508,13 @@
} }
}, },
"node_modules/@typescript-eslint/visitor-keys": { "node_modules/@typescript-eslint/visitor-keys": {
"version": "8.74.0", "version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.74.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.2.tgz",
"integrity": "sha512-XSZmOtMUbWCBIM+2BK134FyMFxmll1mW2mPLk/PSwYQYzGIPMgJAqL929U4qXVizLv7Xq5b7r41/o7Ombuwk0g==", "integrity": "sha512-NAGrjn0Pitjqzq/GkgMC4kBYm233PQ8GffyQ9+kTA3AlNQYEzOf25EIM02BAHZv5FRJSpHpJk+OGUxVkOB93GQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/types": "8.74.0", "@typescript-eslint/types": "8.72.2",
"eslint-visitor-keys": "^5.0.0" "eslint-visitor-keys": "^5.0.0"
}, },
"engines": { "engines": {
@ -4766,9 +4753,9 @@
} }
}, },
"node_modules/brace-expansion": { "node_modules/brace-expansion": {
"version": "5.1.0", "version": "5.0.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.1.0.tgz", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
"integrity": "sha512-aa11Dv491GKnYqxaul3aRJ0szew7yMJMfZPnqD44NjGrZXoj62l41OEDDpdpC4eE2P88vBFfLuSyRhpG91NUvg==", "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
@ -5385,9 +5372,9 @@
} }
}, },
"node_modules/eslint": { "node_modules/eslint": {
"version": "10.15.0", "version": "10.14.0",
"resolved": "https://registry.npmjs.org/eslint/-/eslint-10.15.0.tgz", "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.14.0.tgz",
"integrity": "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==", "integrity": "sha512-T0pNsxkb9IKmtQjhpK3d7nWOpFv+YHuMbTJnSVMoQblF0onvXfErrtp4V1jHtsQPan7dKaGVD0q1WCXnzMF31A==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"workspaces": [ "workspaces": [
@ -5396,7 +5383,7 @@
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.2", "@eslint-community/regexpp": "^4.12.2",
"@eslint/config-array": "^0.23.6", "@eslint/config-array": "^0.23.5",
"@eslint/config-helpers": "^0.7.0", "@eslint/config-helpers": "^0.7.0",
"@eslint/core": "^1.2.1", "@eslint/core": "^1.2.1",
"@eslint/plugin-kit": "^0.7.3", "@eslint/plugin-kit": "^0.7.3",
@ -5421,7 +5408,7 @@
"imurmurhash": "^0.1.4", "imurmurhash": "^0.1.4",
"is-glob": "^4.0.0", "is-glob": "^4.0.0",
"json-stable-stringify-without-jsonify": "^1.0.1", "json-stable-stringify-without-jsonify": "^1.0.1",
"minimatch": "^11.0.5", "minimatch": "^10.2.6",
"natural-compare": "^1.4.0", "natural-compare": "^1.4.0",
"optionator": "^0.9.3" "optionator": "^0.9.3"
}, },
@ -6482,17 +6469,16 @@
"license": "CC0-1.0" "license": "CC0-1.0"
}, },
"node_modules/minimatch": { "node_modules/minimatch": {
"version": "11.0.9", "version": "10.2.6",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
"integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
"dev": true, "dev": true,
"license": "BlueOak-1.0.0", "license": "BlueOak-1.0.0",
"dependencies": { "dependencies": {
"@isaacs/nonrecursive-glob-match": "^1.1.0", "brace-expansion": "^5.0.8"
"brace-expansion": "^5.0.12"
}, },
"engines": { "engines": {
"node": "20 || >=22" "node": "18 || 20 || >=22"
}, },
"funding": { "funding": {
"url": "https://github.com/sponsors/isaacs" "url": "https://github.com/sponsors/isaacs"
@ -7524,16 +7510,16 @@
} }
}, },
"node_modules/typescript-eslint": { "node_modules/typescript-eslint": {
"version": "8.74.0", "version": "8.72.2",
"resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.74.0.tgz", "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.72.2.tgz",
"integrity": "sha512-OsWQlsedt1ZpZXfZZMNK3m4SoQONFFcy4h/uRznsCeRfVuEic3gh4KGUs2pJJ5o0Jj0Jr7keUHQGN1Ns9aDw7Q==", "integrity": "sha512-c/+AKMW1KB81r28Sp0AAdcyXj5dzNmAsZFcsrxKbZTKmcBK2xIwBR31dcSYSDu3bKmzXe8GKrSxO+eDQ401Uzg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/eslint-plugin": "8.74.0", "@typescript-eslint/eslint-plugin": "8.72.2",
"@typescript-eslint/parser": "8.74.0", "@typescript-eslint/parser": "8.72.2",
"@typescript-eslint/typescript-estree": "8.74.0", "@typescript-eslint/typescript-estree": "8.72.2",
"@typescript-eslint/utils": "8.74.0" "@typescript-eslint/utils": "8.72.2"
}, },
"engines": { "engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0" "node": "^18.18.0 || ^20.9.0 || >=21.1.0"

View File

@ -1,90 +0,0 @@
#!/bin/sh
set -eu
root=${1:?Deployment directory required}
release_id=${2:?Build number and commit required}
host=${3:?Frontend hostname required}
case "$release_id" in *[!0-9a-f-]*|'') echo 'Invalid release ID' >&2; exit 1 ;; esac
build=${release_id%%-*}
case "$build" in *[!0-9]*|'') echo 'Invalid build number' >&2; exit 1 ;; esac
case "$host" in *[!a-zA-Z0-9.-]*|'') echo 'Invalid hostname' >&2; exit 1 ;; esac
cd "$root"
root=$(pwd -P)
exec 9> .deploy.lock
flock -x 9
release="$root/releases/$release_id/dist"
if [ ! -d "$release" ]; then
candidate="$root/incoming/$release_id/dist"
test -s "$candidate/index.html"
test "$(cat "$candidate/release.txt")" = "$release_id"
mkdir -p "$root/releases/$release_id"
mv "$candidate" "$release"
fi
test -s "$release/index.html"
test "$(cat "$release/release.txt")" = "$release_id"
# A slow older pipeline must not replace a newer successful release.
last_build=0
if [ -L current ] && [ -f current/release.txt ]; then
last_release=$(cat current/release.txt)
last_build=${last_release%%-*}
fi
if [ "$build" -lt "$last_build" ]; then
echo "Skipping superseded build $build (active build $last_build)"
exit 0
fi
if [ -e current ] && [ ! -L current ]; then
echo 'The current release must be a symlink' >&2
exit 1
fi
old=$(readlink current || true)
old_previous=$(readlink previous || true)
temporary="$root/.current-$release_id"
previous_temporary="$root/.previous-$release_id"
switched=false
restore() {
result=$?
trap - EXIT HUP INT TERM
if [ "$switched" = true ] && [ "$result" -ne 0 ]; then
if [ -n "$old" ]; then
ln -sfn "$old" "$temporary"
mv -Tf "$temporary" current
else
rm -f current
fi
if [ -n "$old_previous" ]; then
ln -sfn "$old_previous" "$previous_temporary"
mv -Tf "$previous_temporary" previous
else
rm -f previous
fi
echo 'Release verification failed. Restored the previous release.' >&2
fi
rm -f "$temporary" "$previous_temporary"
exit "$result"
}
trap restore EXIT
trap 'exit 1' HUP INT TERM
chmod a+rx "$root/releases/$release_id"
chmod -R a+rX "$release"
switched=true
if [ -n "$old" ] && [ "$old" != "$release" ]; then
ln -sfn "$old" "$previous_temporary"
mv -Tf "$previous_temporary" previous
fi
ln -sfn "$release" "$temporary"
mv -Tf "$temporary" current
# Verify this server through the existing HTTPS virtual host and certificate.
served=$(curl --fail --silent --show-error --max-time 20 \
--resolve "$host:443:127.0.0.1" "https://$host/release.txt")
test "$served" = "$release_id"
for path in / /workspace /cart; do
curl --fail --silent --show-error --output /dev/null --max-time 20 \
--resolve "$host:443:127.0.0.1" "https://$host$path"
done
ready=$(curl --fail --silent --show-error --max-time 20 \
--resolve "$host:443:127.0.0.1" "https://$host/api/v1/health/ready")
test "$(printf '%s' "$ready" | tr -d '[:space:]')" = '{"status":"ok"}'
echo "Activated $release_id on $host"

View File

@ -1,46 +0,0 @@
#!/bin/sh
set -eu
test "$(id -u)" = 0 || { echo 'Run this setup script with sudo.' >&2; exit 1; }
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
snippet="$script_dir/../deploy/nginx-locations.conf"
if [ ! -f "$snippet" ]; then snippet="$script_dir/nginx-locations.conf"; fi
test -s "$snippet"
site=$(readlink -f /etc/nginx/sites-enabled/ManiCandles.midastix.com.conf)
test -f "$site"
if grep -Eq 'listen[[:space:]].*443|ssl_certificate' "$site"; then
echo 'This site already contains TLS settings. Review its configuration before running setup.' >&2
exit 1
fi
nginx -t
command -v curl
command -v flock
command -v certbot
root=/var/www/manicandles
install -d -o mihir -g "$(id -gn mihir)" -m 0755 "$root" "$root/releases" "$root/incoming"
if [ ! -e "$root/current" ] && [ ! -L "$root/current" ] && [ -s /var/www/ManiCandles.midastix.com/index.html ]; then
ln -s /var/www/ManiCandles.midastix.com "$root/current"
chown -h mihir:"$(id -gn mihir)" "$root/current"
fi
install -d -m 0755 /etc/nginx/snippets /var/backups
backup="/var/backups/manicandles-nginx-$(date +%Y%m%d%H%M%S)-$$.conf"
cp -p "$site" "$backup"
if [ -e /etc/nginx/snippets/manicandles.conf ] && ! cmp -s "$snippet" /etc/nginx/snippets/manicandles.conf; then
echo 'A different deployment snippet exists. Review the existing setup before continuing.' >&2
exit 1
fi
install -m 0644 "$snippet" /etc/nginx/snippets/manicandles.conf
cat > "$site" <<'NGINX'
server {
listen 80;
server_name manicandles.midastix.com;
include /etc/nginx/snippets/manicandles.conf;
}
NGINX
if ! nginx -t || ! systemctl reload nginx; then
cp -p "$backup" "$site"
nginx -t && systemctl reload nginx
echo "Setup failed. Restored $backup" >&2
exit 1
fi
echo "Site prepared. Original configuration saved at $backup"
echo 'Next run: sudo certbot --nginx -d manicandles.midastix.com --redirect'

View File

@ -34,9 +34,6 @@ const PriceListsPage = lazy(() => import("@/pages/PriceListsPage"));
const QuotesPage = lazy(() => import("@/pages/QuotesPage")); const QuotesPage = lazy(() => import("@/pages/QuotesPage"));
const CreditPoliciesPage = lazy(() => import("@/pages/CreditPoliciesPage")); const CreditPoliciesPage = lazy(() => import("@/pages/CreditPoliciesPage"));
const SamplesPage = lazy(() => import("@/pages/SamplesPage")); const SamplesPage = lazy(() => import("@/pages/SamplesPage"));
const ArtworkPage = lazy(() => import("@/pages/ArtworkPage"));
const PartnerOrdersPage = lazy(() => import("@/pages/PartnerOrdersPage"));
const PartnerPaymentsPage = lazy(() => import("@/pages/PartnerPaymentsPage"));
const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage")); const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage"));
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage")); const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
const BomPage = lazy(() => import("@/pages/BomPage")); const BomPage = lazy(() => import("@/pages/BomPage"));
@ -120,32 +117,6 @@ function Router() {
<Route path="/admin/b2b-samples/:id"> <Route path="/admin/b2b-samples/:id">
{(params) => <SamplesPage id={params.id} />} {(params) => <SamplesPage id={params.id} />}
</Route> </Route>
<Route path="/admin/b2b-artwork">{() => <ArtworkPage />}</Route>
<Route path="/admin/b2b-artwork/new">{() => <ArtworkPage create />}</Route>
<Route path="/admin/b2b-artwork/new/:accountId">
{(params) => <ArtworkPage create accountId={params.accountId} />}
</Route>
<Route path="/admin/b2b-artwork/account/:accountId">
{(params) => <ArtworkPage accountId={params.accountId} />}
</Route>
<Route path="/admin/b2b-artwork/:id">
{(params) => <ArtworkPage id={params.id} />}
</Route>
<Route path="/admin/b2b-payments">{() => <PartnerPaymentsPage />}</Route>
<Route path="/admin/b2b-partner-orders/:orderId/payments">
{(params) => <PartnerPaymentsPage orderId={params.orderId} />}
</Route>
<Route path="/admin/b2b-partner-orders">{() => <PartnerOrdersPage />}</Route>
<Route path="/admin/b2b-partner-orders/new">{() => <PartnerOrdersPage create />}</Route>
<Route path="/admin/b2b-partner-orders/new/:quoteId">
{(params) => <PartnerOrdersPage create quoteId={params.quoteId} />}
</Route>
<Route path="/admin/b2b-partner-orders/account/:accountId">
{(params) => <PartnerOrdersPage accountId={params.accountId} />}
</Route>
<Route path="/admin/b2b-partner-orders/:id">
{(params) => <PartnerOrdersPage id={params.id} />}
</Route>
<Route path="/admin/catalog">{() => <CatalogAdminPage />}</Route> <Route path="/admin/catalog">{() => <CatalogAdminPage />}</Route>
<Route path="/admin/catalog/:id"> <Route path="/admin/catalog/:id">
{(params) => <CatalogAdminPage id={params.id} />} {(params) => <CatalogAdminPage id={params.id} />}

View File

@ -1,12 +0,0 @@
import type { z } from "zod";
import type { profileSnapshot } from "@/lib/business";
export function BusinessSnapshot({ account }: { account: z.infer<typeof profileSnapshot> }) {
return <section className="workspace-id">
<h3>Business at quotation issuance</h3>
<p>{account.legalName}{account.tradingName && ` · ${account.tradingName}`} · Profile version {account.profileVersion}</p>
<p>Registration {account.registrationNumber}{account.taxIdentifier && ` · Tax ID ${account.taxIdentifier}`}</p>
<p>{account.contactEmail}{account.contactPhone && ` · ${account.contactPhone}`}</p>
<p>{[account.billingLine1, account.billingCity, account.billingRegion, account.billingPostalCode, account.countryCode].join(", ")}</p>
</section>;
}

View File

@ -4,7 +4,7 @@ import Alert from "@mui/material/Alert";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
import Skeleton from "@mui/material/Skeleton"; import Skeleton from "@mui/material/Skeleton";
import { Flame } from "lucide-react"; import { Flame } from "lucide-react";
import { listProducts, productImageUrl } from "@/lib/api"; import { listProducts } from "@/lib/api";
import { usePlatform } from "@/lib/platform"; import { usePlatform } from "@/lib/platform";
import { ApiNotice } from "./ApiNotice"; import { ApiNotice } from "./ApiNotice";
import "@/pages/products.css"; import "@/pages/products.css";
@ -75,21 +75,11 @@ export function Catalog({
<article className="prod-card" key={product.id}> <article className="prod-card" key={product.id}>
<Link <Link
href={`/products/${product.id}`} href={`/products/${product.id}`}
className={`prod-img-wrap${product.images[0] ? "" : " catalog-placeholder"}`} className="prod-img-wrap catalog-placeholder"
aria-label={`View ${product.name}`} aria-label={`View ${product.name}`}
> >
{product.images[0] ? ( <Flame size={48} aria-hidden="true" />
<img <span>Mani Candles</span>
src={productImageUrl(organization, product.id, product.images[0].id)}
alt=""
loading="lazy"
/>
) : (
<>
<Flame size={48} aria-hidden="true" />
<span>Mani Candles</span>
</>
)}
</Link> </Link>
<div className="prod-info"> <div className="prod-info">
<h3 className="prod-name"> <h3 className="prod-name">

View File

@ -75,9 +75,6 @@ export function WorkspaceNavigation() {
{ label: "B2B quotations", path: "/admin/b2b-quotes", permission: "b2b.quote.read" }, { label: "B2B quotations", path: "/admin/b2b-quotes", permission: "b2b.quote.read" },
{ label: "B2B credit policies", path: "/admin/b2b-credit-policies", permission: "b2b.credit.read" }, { label: "B2B credit policies", path: "/admin/b2b-credit-policies", permission: "b2b.credit.read" },
{ label: "B2B samples", path: "/admin/b2b-samples", permission: "b2b.sample.read" }, { label: "B2B samples", path: "/admin/b2b-samples", permission: "b2b.sample.read" },
{ label: "B2B artwork", path: "/admin/b2b-artwork", permission: "b2b.artwork.read" },
{ label: "B2B partner orders", path: "/admin/b2b-partner-orders", permission: "b2b.order.read" },
{ label: "B2B partner payments", path: "/admin/b2b-payments", permission: "b2b.payment.read" },
]; ];
return ( return (
<nav className="workspace-links" aria-label="Workspace navigation"> <nav className="workspace-links" aria-label="Workspace navigation">

View File

@ -5,15 +5,7 @@ const productSummarySchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
name: z.string(), name: z.string(),
slug: z.string(), slug: z.string(),
images: z.array(z.object({ id: z.string().uuid() })).default([]),
}); });
export function productImageUrl(
organization: string,
productId: string,
imageId: string,
) {
return `/api/v1/storefront/${organization}/products/${productId}/images/${imageId}`;
}
export const productSchema = productSummarySchema.extend({ export const productSchema = productSummarySchema.extend({
description: z.string(), description: z.string(),
variants: z.array( variants: z.array(
@ -95,8 +87,8 @@ async function fetchApiResponse(
body, body,
method = "GET", method = "GET",
signal, signal,
attachmentMime, pdf = false,
}: ApiOptions & { attachmentMime?: string }, }: ApiOptions & { pdf?: boolean },
) { ) {
let response: Response; let response: Response;
const multipart = body instanceof FormData; const multipart = body instanceof FormData;
@ -105,10 +97,10 @@ async function fetchApiResponse(
response = await fetch(`/api/v1${path}`, { response = await fetch(`/api/v1${path}`, {
method, method,
signal: signal ? AbortSignal.any([signal, timeout]) : timeout, signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
...(attachmentMime || multipart ? { cache: "no-store", redirect: "error" } : {}), ...(pdf || multipart ? { cache: "no-store", redirect: "error" } : {}),
headers: { headers: {
...(body === undefined || multipart ? {} : { "Content-Type": "application/json" }), ...(body === undefined || multipart ? {} : { "Content-Type": "application/json" }),
...(attachmentMime ? { Accept: attachmentMime } : {}), ...(pdf ? { Accept: "application/pdf" } : {}),
...(token ? { Authorization: `Bearer ${token}` } : {}), ...(token ? { Authorization: `Bearer ${token}` } : {}),
}, },
...(body === undefined ? {} : { body: multipart ? body : JSON.stringify(body) }), ...(body === undefined ? {} : { body: multipart ? body : JSON.stringify(body) }),
@ -150,43 +142,14 @@ export async function apiRequest(path: string, options: ApiOptions = {}): Promis
return data; return data;
} }
async function apiAttachment( export async function apiPdf(path: string, size: number, token: string, signal: AbortSignal) {
path: string, const response = await fetchApiResponse(path, { token, signal, pdf: true });
size: number, const invalidPdf = () => new ApiError("The service returned an unexpected PDF.", response.status, "INVALID_RESPONSE");
attachmentMime: string, if (response.headers.get("content-type")?.split(";")[0].trim().toLowerCase() !== "application/pdf") throw invalidPdf();
token: string,
signal: AbortSignal,
errorMessage: string,
) {
const response = await fetchApiResponse(path, { token, signal, attachmentMime });
const invalidAttachment = () => new ApiError(errorMessage, response.status, "INVALID_RESPONSE");
if (response.headers.get("content-type")?.split(";")[0].trim().toLowerCase() !== attachmentMime) throw invalidAttachment();
const file = await response.blob(); const file = await response.blob();
if (file.size !== size) throw invalidAttachment(); if (file.size !== size) throw invalidPdf();
return file; return file;
} }
export function apiPdf(path: string, size: number, token: string, signal: AbortSignal) {
return apiAttachment(path, size, "application/pdf", token, signal, "The service returned an unexpected PDF.");
}
const artworkAttachment = z.object({
versionId: z.string().uuid(),
size: z.number().int().min(1).max(2 * 1024 * 1024),
mimeType: z.enum(["application/pdf", "image/png", "image/jpeg"]),
});
export async function apiArtwork(versionId: string, size: number, mimeType: string, token: string, signal: AbortSignal) {
const file = artworkAttachment.parse({ versionId, size, mimeType });
return apiAttachment(
`/b2b/artwork-versions/${file.versionId}/download`,
file.size,
file.mimeType,
token,
signal,
"The service returned an unexpected artwork attachment.",
);
}
export 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)
@ -243,21 +206,6 @@ export async function login(
}), }),
); );
} }
export async function register(
organizationId: string,
name: string,
email: string,
password: string,
) {
const organization = organizationSchema.parse(organizationId);
return parse(
sessionSchema,
await apiRequest("/auth/register", {
method: "POST",
body: { organizationId: organization, name, email, password },
}),
);
}
export async function getPrincipal(token: string) { export async function getPrincipal(token: string) {
return parse(principalSchema, await apiRequest("/auth/me", { token })); return parse(principalSchema, await apiRequest("/auth/me", { token }));
} }

View File

@ -1,67 +0,0 @@
import { z } from "zod";
import { uuid } from "./commerce.ts";
const plainText = (max: number) =>
z.string().trim().min(3).max(max).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
export const maxArtworkBytes = 2 * 1024 * 1024;
const filename = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,115}\.(pdf|png|jpg|jpeg)$/);
const mimeType = z.enum(["application/pdf", "image/png", "image/jpeg"]);
const fileTypes = new Map<string, z.infer<typeof mimeType>>([
["pdf", "application/pdf"],
["png", "image/png"],
["jpg", "image/jpeg"],
["jpeg", "image/jpeg"],
]);
export const artworkAccept = ".pdf,.png,.jpg,.jpeg";
export const artworkPlacement = z.enum(["LABEL", "PACKAGING", "CANDLE", "OTHER"]);
const outcome = z.enum(["APPROVED", "REJECTED"]);
export const artworkInput = z.object({
accountId: uuid,
name: plainText(160),
placement: artworkPlacement,
brief: plainText(1000),
}).strict();
export const artworkDecision = z.object({ outcome, note: plainText(500) }).strict();
export const artworkProject = artworkInput.extend({
id: uuid,
createdAt: z.string().datetime(),
}).strip();
export const artworkVersion = z.object({
id: uuid,
artworkId: uuid,
uploadedById: uuid,
version: z.number().int().min(1).max(20),
filename,
mimeType,
sha256: z.string().regex(/^[a-f0-9]{64}$/),
size: z.number().int().min(1).max(maxArtworkBytes),
createdAt: z.string().datetime(),
decision: artworkDecision.extend({ reviewerId: uuid, createdAt: z.string().datetime() }).strip().nullable(),
}).refine((version) => matchingType(version.filename) === version.mimeType, {
path: ["mimeType"],
message: "The artwork media type must match its filename.",
});
export const artworkDetails = artworkProject.extend({ versions: z.array(artworkVersion).max(20) });
function matchingType(name: string) {
return fileTypes.get(name.split(".").at(-1) ?? "");
}
export function prepareArtworkUpload(file: FormDataEntryValue | null) {
if (!(file instanceof File) || !file.size) throw new Error("Choose a PDF, PNG, or JPEG file.");
if (file.size > maxArtworkBytes) throw new Error("Choose an artwork file up to 2 MiB.");
const type = matchingType(file.name);
if (!filename.safeParse(file.name).success || !type) {
throw new Error("Use a simple filename ending in .pdf, .png, .jpg or .jpeg.");
}
if (file.type && file.type !== type) throw new Error("The file type must match its extension.");
const body = new FormData();
body.append("file", file.type ? file : new File([file], file.name, { type }));
return body;
}

View File

@ -154,26 +154,8 @@ export const adminProductSummary = productInput
.pick({ name: true, slug: true }) .pick({ name: true, slug: true })
.extend({ id: uuid, status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]) }) .extend({ id: uuid, status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]) })
.strip(); .strip();
export const productImage = z
.object({
id: uuid,
mimeType: z.enum(["image/jpeg", "image/png", "image/webp"]),
size: z.number().int().positive(),
})
.strip();
export const productImageAccept = "image/jpeg,image/png,image/webp";
export function prepareProductImage(file: FormDataEntryValue | null) {
if (!(file instanceof File) || !file.size) throw new Error("Choose a JPEG, PNG or WebP photo.");
if (file.size > 2 * 1024 * 1024) throw new Error("Choose a photo up to 2 MiB.");
if (!productImageAccept.split(",").includes(file.type))
throw new Error("Use a JPEG, PNG or WebP photo.");
const body = new FormData();
body.append("file", file);
return body;
}
export const adminProduct = adminProductSummary.extend({ export const adminProduct = adminProductSummary.extend({
description: z.string(), description: z.string(),
images: z.array(productImage).default([]),
variants: z.array(variant), variants: z.array(variant),
groups: z.array(z.object({ group })), groups: z.array(z.object({ group })),
}); });

View File

@ -1,53 +0,0 @@
import { z } from "zod";
import { profileSnapshot } from "./business.ts";
import { currency, uuid } from "./commerce.ts";
import { quote, quoteSummary } from "./quotes.ts";
const text = (max: number, min = 1) =>
z.string().trim().min(min).max(max).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
const timestamp = z.string().datetime({ offset: true });
const partnerReference = text(80);
const orderNote = text(500, 3);
export const createPartnerOrderInput = z.object({
quoteId: uuid,
partnerReference,
note: orderNote.nullable().optional(),
idempotencyKey: uuid,
}).strict();
export const cancelPartnerOrderInput = z.object({
reason: orderNote,
idempotencyKey: uuid,
}).strict();
export const partnerOrderSummary = z.object({
id: uuid,
accountId: uuid,
quoteId: uuid,
number: z.string(),
partnerReference,
accountSnapshot: profileSnapshot.pick({ legalName: true }).strip(),
currency,
merchandiseTotal: quoteSummary.shape.merchandiseTotal,
status: z.enum(["RECEIVED", "CANCELLED"]),
createdAt: timestamp,
});
export const partnerOrder = partnerOrderSummary.extend({
accountSnapshot: profileSnapshot,
createdById: uuid,
note: orderNote.nullable(),
lines: z.array(quote.shape.lines.element),
cancellation: z.object({
actorId: uuid,
reason: orderNote,
createdAt: timestamp,
}).nullable(),
});
export function partnerOrderEligible(
quote: Pick<z.infer<typeof quoteSummary>, "status" | "expiresAt">,
now = Date.now(),
) {
return quote.status === "ACCEPTED" && Date.parse(quote.expiresAt) > now;
}

View File

@ -1,29 +0,0 @@
import { z } from "zod";
import { currency, uuid } from "./commerce.ts";
import { paymentMethods } from "./supplier-finance.ts";
const amount = z.string().regex(/^(0|[1-9]\d{0,15})\.\d{2}$/, "Use two decimal places");
const reason = z.string().trim().min(3).max(500)
.regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
const timestamp = z.string().datetime({ offset: true });
export const partnerPaymentInput = z.object({
idempotencyKey: uuid,
reference: z.string().trim().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/).toUpperCase(),
method: paymentMethods,
amount: amount.refine((value) => value !== "0.00", "Amount must be positive"),
receivedOn: z.string().date(),
}).strict();
export const reversePartnerPaymentInput = z.object({ reason, idempotencyKey: uuid }).strict();
export const partnerPayment = z.object({
id: uuid, orderId: uuid, recordedById: uuid,
reference: z.string(), method: paymentMethods, currency, amount,
receivedOn: timestamp, createdAt: timestamp,
reversal: z.object({ reason, reversedById: uuid, createdAt: timestamp }).nullable(),
});
export const partnerPaymentHistory = z.object({
orderId: uuid, currency, merchandiseTotal: amount, paidTotal: amount, outstandingTotal: amount,
payments: z.array(partnerPayment),
});

View File

@ -11,14 +11,12 @@ import { useQueryClient } from "@tanstack/react-query";
import { z } from "zod"; import { z } from "zod";
import { import {
apiRequest, apiRequest,
apiArtwork,
apiPdf, apiPdf,
ApiError, ApiError,
getPrincipal, getPrincipal,
login, login,
organizationSchema, organizationSchema,
parse, parse,
register,
type Principal, type Principal,
type Session, type Session,
} from "./api"; } from "./api";
@ -30,7 +28,6 @@ const PlatformContext = createContext<{
principal: Principal | null; principal: Principal | null;
scope: string; scope: string;
signIn: (email: string, password: string) => Promise<void>; signIn: (email: string, password: string) => Promise<void>;
signUp: (name: string, email: string, password: string) => Promise<void>;
signOut: () => Promise<void>; signOut: () => Promise<void>;
notice: string; notice: string;
clearSession: (notice?: string) => void; clearSession: (notice?: string) => void;
@ -39,7 +36,6 @@ const PlatformContext = createContext<{
clearIntent: (key: string, idempotencyKey: string) => void; clearIntent: (key: string, idempotencyKey: string) => void;
can: (permission: string) => boolean; can: (permission: string) => boolean;
downloadPdf: (versionId: string, size: number) => Promise<Blob>; downloadPdf: (versionId: string, size: number) => Promise<Blob>;
downloadArtwork: (versionId: string, size: number, mimeType: string) => Promise<Blob>;
request: <T>( request: <T>(
path: string, path: string,
schema: z.ZodType<T>, schema: z.ZodType<T>,
@ -112,15 +108,9 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
/* The in-memory setting still works. */ /* The in-memory setting still works. */
} }
} }
function signIn(email: string, password: string) { async function signIn(email: string, password: string) {
return adopt(() => login(organization, email, password));
}
function signUp(name: string, email: string, password: string) {
return adopt(() => register(organization, name, email, password));
}
async function adopt(start: () => ReturnType<typeof login>) {
const version = ++generation.current; const version = ++generation.current;
const next = await start(); const next = await login(organization, email, password);
try { try {
const me = await getPrincipal(next.accessToken); const me = await getPrincipal(next.accessToken);
if ( if (
@ -244,9 +234,6 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
const id = z.string().uuid().parse(versionId); const id = z.string().uuid().parse(versionId);
return withSession((token, signal) => apiPdf(`/supplier-document-versions/${id}/download`, size, token, signal)); return withSession((token, signal) => apiPdf(`/supplier-document-versions/${id}/download`, size, token, signal));
} }
function downloadArtwork(versionId: string, size: number, mimeType: string) {
return withSession((token, signal) => apiArtwork(versionId, size, mimeType, token, signal));
}
return ( return (
<PlatformContext.Provider <PlatformContext.Provider
value={{ value={{
@ -255,7 +242,6 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
principal, principal,
scope: principal ? `${principal.sessionId}:${accessRevision}` : "", scope: principal ? `${principal.sessionId}:${accessRevision}` : "",
signIn, signIn,
signUp,
signOut, signOut,
notice, notice,
clearSession, clearSession,
@ -282,7 +268,6 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
can: (permission) => can: (permission) =>
Boolean(principal?.permissions.includes(permission)), Boolean(principal?.permissions.includes(permission)),
downloadPdf, downloadPdf,
downloadArtwork,
request, request,
}} }}
> >

View File

@ -43,6 +43,6 @@ export const quote = quoteSummary.extend({
priceListName: z.string(), priceListName: z.string(),
customerReference: z.string().nullable(), customerReference: z.string().nullable(),
createdAt: timestamp, createdAt: timestamp,
lines: z.array(priceCheck.shape.lines.element.extend({ id: uuid, sku: z.string(), name: z.string() }).strip()), lines: z.array(priceCheck.shape.lines.element.extend({ id: uuid, sku: z.string(), name: z.string() })),
response: z.object({ kind: responseKind, note: z.string(), createdAt: timestamp }).nullable(), response: z.object({ kind: responseKind, note: z.string(), createdAt: timestamp }).nullable(),
}); });

View File

@ -1,207 +0,0 @@
import { useId, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useLocation } from "wouter";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import Button from "@mui/material/Button";
import { ApiNotice } from "@/components/ApiNotice";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { isUnknownOutcome } from "@/lib/api";
import { artworkAccept, artworkDecision, artworkDetails, artworkInput, artworkPlacement, artworkProject, artworkVersion, prepareArtworkUpload } from "@/lib/artwork";
import { uuid } from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
const api = "/b2b/artworks";
const route = "/admin/b2b-artwork";
const placements = artworkPlacement.options.map((value) => ({ value, label: value[0] + value.slice(1).toLowerCase() }));
type Version = z.infer<typeof artworkVersion>;
function ArtworkList({ accountId }: { accountId?: string }) {
const { can } = usePlatform();
const [offset, setOffset] = useState(0);
const params = new URLSearchParams({ limit: "25", offset: String(offset) });
if (accountId) params.set("accountId", accountId);
const query = usePrivateQuery(`${api}?${params}`, z.array(artworkProject));
return <Panel title="Artwork projects">
{accountId && <p className="workspace-id">Business account {accountId}</p>}
{can("b2b.artwork.manage") && <p><WorkspaceLink href={`${route}/new${accountId ? `/${accountId}` : ""}`}>New artwork project</WorkspaceLink></p>}
<QueryView query={query}>{(rows) => <>
<Table head={["Project", "Placement", "Business account ID", "Created"]} rowKeys={rows.map((row) => row.id)}
rows={rows.map((row) => [
<WorkspaceLink href={`${route}/${row.id}`}>{row.name}</WorkspaceLink>,
row.placement, row.accountId, new Date(row.createdAt).toLocaleString(),
])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</>}</QueryView>
</Panel>;
}
function CreateArtwork({ accountId }: { accountId?: string }) {
const { can, request, scope } = usePlatform();
const [, navigate] = useLocation();
const client = useQueryClient();
const [uncertainAccount, setUncertainAccount] = useState("");
if (!can("b2b.artwork.manage")) return <Alert severity="warning">Your account does not have permission to create artwork projects.</Alert>;
function refreshLists() {
return client.invalidateQueries({
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
typeof queryKey[2] === "string" && queryKey[2].startsWith(`${api}?`),
});
}
return <Panel title="New artwork project">
{uncertainAccount ? <Alert severity="warning">
The server may have saved the project. <WorkspaceLink href={`${route}/account/${uncertainAccount}`}>Check the business’s artwork projects</WorkspaceLink> before creating it again.
</Alert> : <ActionForm label="Create artwork project" reset={false} read={(data) => ({
accountId: accountId ?? readText(data, "accountId").trim(),
name: readText(data, "name"),
placement: readText(data, "placement"),
brief: readText(data, "brief"),
})} submit={async (input) => {
const body = artworkInput.parse(input);
try {
const saved = await request(api, artworkProject, { method: "POST", body });
await refreshLists();
navigate(`${route}/${saved.id}`);
} catch (error) {
if (isUnknownOutcome(error)) {
setUncertainAccount(body.accountId);
await refreshLists();
}
throw error;
}
}}>
<p>Create a project for a verified business account.</p>
{accountId ? <p className="workspace-id">Business account {accountId}</p> :
<Field name="accountId" label="Business account ID" maxLength={36} />}
{!accountId && can("b2b.read") && <WorkspaceLink href="/admin/business-accounts">Business directory</WorkspaceLink>}
<Field name="name" label="Project name" maxLength={160} />
<Field name="placement" label="Artwork placement" value="LABEL" options={placements} />
<Field name="brief" label="Artwork brief" maxLength={1000} />
</ActionForm>}
</Panel>;
}
function ArtworkDetail({ id }: { id: string }) {
const { can, principal, request } = usePlatform();
const [uncertain, setUncertain] = useState(false);
const fileId = useId();
const path = `${api}/${id}`;
const query = usePrivateQuery(path, artworkDetails);
const reviewer = can("b2b.artwork.review");
const userId = principal?.userId.toLowerCase();
return <QueryView query={query}>{(project) => {
const latest = project.versions[0];
const pending = latest && !latest.decision;
return <div className="workspace-id">
<Panel title={project.name}>
<p>{project.placement} · Business account {project.accountId}</p>
<p>{project.brief}</p>
<WorkspaceLink href={`${route}/account/${project.accountId}`}>All artwork projects for this business</WorkspaceLink>
{can("b2b.read") && <p><WorkspaceLink href={`/admin/business-accounts/${project.accountId}`}>Business profile</WorkspaceLink></p>}
</Panel>
<Panel title="Artwork versions">
<Table head={["Version", "File", "Review", "Actions"]}
rowKeys={project.versions.map((version) => version.id)}
rows={project.versions.map((version) => [
version.version,
<><p>{version.filename} · {new Date(version.createdAt).toLocaleString()}</p>
<details><summary>Version identifiers</summary><p>ID {version.id}</p><p>SHA-256 {version.sha256}</p></details></>,
version.decision ? <>{version.decision.outcome} · {version.decision.note}
<p>Reviewed {new Date(version.decision.createdAt).toLocaleString()} by {version.decision.reviewerId}</p></> : "Pending",
(reviewer || version.uploadedById === userId || version.decision?.outcome === "APPROVED") &&
<DownloadArtwork version={version} />,
])} />
{pending && reviewer && (latest.uploadedById === userId ?
<Alert severity="info">A different staff member must review this version.</Alert> :
<ReviewArtwork key={latest.id} version={latest} refresh={query.refetch} />)}
{can("b2b.artwork.manage") && <>
{uncertain && <Alert severity="warning">
The server may have saved the file. Check the version history before attempting another upload.
<Button onClick={() => query.refetch()}>Refresh versions</Button>
</Alert>}
{pending ? <p>The latest version needs a review decision before another file can be uploaded.</p> :
project.versions.length >= 20 ? <p>This project has reached the 20-version limit.</p> :
!uncertain && <ActionForm label="Upload artwork version" read={(data) => prepareArtworkUpload(data.get("file"))}
submit={async (body) => {
try {
await request(`${path}/versions`, artworkVersion, { method: "POST", body });
} catch (error) {
if (isUnknownOutcome(error)) setUncertain(true);
throw error;
} finally {
await query.refetch();
}
}}>
<label htmlFor={fileId}>Artwork file</label>
<input id={fileId} name="file" type="file" accept={artworkAccept} required
aria-describedby={`${fileId}-help`} style={{ maxWidth: "100%" }} />
<p id={`${fileId}-help`}>Choose a PDF, PNG, or JPEG up to 2 MiB with a simple filename.</p>
</ActionForm>}
</>}
</Panel>
</div>;
}}</QueryView>;
}
function ReviewArtwork({ version, refresh }: { version: Version; refresh: () => Promise<unknown> }) {
const { request } = usePlatform();
return <ActionForm label="Record artwork decision" reset={false} read={(data) => artworkDecision.parse({
outcome: readText(data, "outcome"), note: readText(data, "note"),
})} submit={async (body) => {
try {
await request(`/b2b/artwork-versions/${version.id}/decision`, artworkVersion, { method: "POST", body });
} finally {
await refresh();
}
}}>
<p>Review version {version.version}. The decision is permanent and applies to this file.</p>
<Field name="outcome" label="Review decision" options={[
{ value: "", label: "Choose a decision" }, { value: "APPROVED", label: "Approve" }, { value: "REJECTED", label: "Reject" },
]} />
<Field name="note" label="Review note" maxLength={500} />
</ActionForm>;
}
function DownloadArtwork({ version }: { version: Version }) {
const { downloadArtwork } = usePlatform();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<unknown>(null);
return <>
<Button disabled={busy} onClick={async () => {
setBusy(true);
setError(null);
try {
const file = await downloadArtwork(version.id, version.size, version.mimeType);
const url = URL.createObjectURL(file);
const link = document.createElement("a");
link.href = url;
link.download = version.filename;
try {
document.body.append(link);
link.click();
} finally {
link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}
} catch (cause) {
setError(cause);
} finally {
setBusy(false);
}
}}>{busy ? "Downloading…" : `Download artwork version ${version.version}`}</Button>
<ApiNotice error={error} />
</>;
}
export default function ArtworkPage({ id, accountId, create = false }: { id?: string; accountId?: string; create?: boolean }) {
const project = uuid.safeParse(id);
const account = uuid.safeParse(accountId);
return <WorkspaceShell title="B2B Artwork" permission="b2b.artwork.read">
{(id || accountId || create) && <WorkspaceLink href={route}>All artwork projects</WorkspaceLink>}
{(id && !project.success) || (accountId && !account.success) ? <Alert severity="warning">Invalid project or business account ID.</Alert> :
create ? <CreateArtwork key={account.data ?? "new"} accountId={account.data} /> :
project.success ? <ArtworkDetail key={project.data} id={project.data} /> :
<ArtworkList key={account.data ?? "all"} accountId={account.data} />}
</WorkspaceShell>;
}

View File

@ -129,10 +129,6 @@ function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () =>
{can("b2b.sample.read") && <p><WorkspaceLink href={`/admin/b2b-samples/account/${account.id}`}>Business sample requests</WorkspaceLink></p>} {can("b2b.sample.read") && <p><WorkspaceLink href={`/admin/b2b-samples/account/${account.id}`}>Business sample requests</WorkspaceLink></p>}
{account.status === "VERIFIED" && can("b2b.sample.read") && can("b2b.sample.request") && {account.status === "VERIFIED" && can("b2b.sample.read") && can("b2b.sample.request") &&
<p><WorkspaceLink href={`/admin/b2b-samples/new/${account.id}`}>Request samples for this business</WorkspaceLink></p>} <p><WorkspaceLink href={`/admin/b2b-samples/new/${account.id}`}>Request samples for this business</WorkspaceLink></p>}
{can("b2b.artwork.read") && <p><WorkspaceLink href={`/admin/b2b-artwork/account/${account.id}`}>Business artwork projects</WorkspaceLink></p>}
{can("b2b.order.read") && <p><WorkspaceLink href={`/admin/b2b-partner-orders/account/${account.id}`}>Business partner orders</WorkspaceLink></p>}
{account.status === "VERIFIED" && can("b2b.artwork.read") && can("b2b.artwork.manage") &&
<p><WorkspaceLink href={`/admin/b2b-artwork/new/${account.id}`}>Create artwork project for this business</WorkspaceLink></p>}
<ReadProfile profile={account} /> <ReadProfile profile={account} />
</Panel> </Panel>
<Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} /> <Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} />

View File

@ -12,9 +12,6 @@ import {
group, group,
groupInput, groupInput,
money, money,
prepareProductImage,
productImage,
productImageAccept,
type AdminProduct, type AdminProduct,
uuid, uuid,
} from "@/lib/commerce"; } from "@/lib/commerce";
@ -34,8 +31,6 @@ import {
} from "@/components/WorkspaceTools"; } from "@/components/WorkspaceTools";
import { RecordSelection } from "@/components/RecordSelection"; import { RecordSelection } from "@/components/RecordSelection";
import { ConfirmAction } from "@/components/ConfirmAction"; import { ConfirmAction } from "@/components/ConfirmAction";
import { productImageUrl } from "@/lib/api";
import "./products.css";
function ProductForm({ function ProductForm({
item, item,
onSave, onSave,
@ -328,10 +323,8 @@ function Products() {
); );
} }
function ProductEditor({ id }: { id: string }) { function ProductEditor({ id }: { id: string }) {
const { request, can, organization } = usePlatform(); const { request, can } = usePlatform();
const query = usePrivateQuery(`/products/${id}`, adminProduct); const query = usePrivateQuery(`/products/${id}`, adminProduct);
const editable = (item: AdminProduct) =>
can("catalog.manage") && item.status !== "ARCHIVED";
const [editingVariant, setEditingVariant] = useState< const [editingVariant, setEditingVariant] = useState<
z.infer<typeof variant> | undefined z.infer<typeof variant> | undefined
>(); >();
@ -380,53 +373,6 @@ function ProductEditor({ id }: { id: string }) {
</> </>
)} )}
</Panel> </Panel>
<Panel title="Photos">
{!item.images.length && <p>No photos yet. The first photo is shown on the catalog card.</p>}
{item.status !== "PUBLISHED" && item.images.length > 0 && (
<Alert severity="info">Previews appear after the product is published.</Alert>
)}
<div className="product-gallery">
{item.images.map((image, index) => (
<figure key={image.id}>
{item.status === "PUBLISHED" ? (
<img src={productImageUrl(organization, id, image.id)} alt={`${item.name}, photo ${index + 1}`} />
) : (
<p>Photo {index + 1}</p>
)}
<figcaption>
{index === 0 ? "Main photo · " : ""}
{image.mimeType.replace("image/", "").toUpperCase()}, {Math.ceil(image.size / 1024)} KB
{editable(item) && (
<ConfirmAction
label="Remove"
message={`Remove photo ${index + 1}? This cannot be undone.`}
onConfirm={async () => {
await request(`/products/${id}/images/${image.id}`, z.unknown(), { method: "DELETE" });
await query.refetch();
}}
/>
)}
</figcaption>
</figure>
))}
</div>
{editable(item) && item.images.length < 8 && (
<ActionForm
label="Upload photo"
read={(data) => prepareProductImage(data.get("file"))}
submit={async (body) => {
try {
await request(`/products/${id}/images`, productImage, { method: "POST", body });
} finally {
await query.refetch();
}
}}
>
<label htmlFor={`photo-${id}`}>Photo (JPEG, PNG or WebP, up to 2 MiB)</label>
<input id={`photo-${id}`} name="file" type="file" accept={productImageAccept} required />
</ActionForm>
)}
</Panel>
<Panel title="Variants"> <Panel title="Variants">
<Table <Table
head={["Variant", "SKU", "Price", "Active", "ID", "Action"]} head={["Variant", "SKU", "Price", "Active", "ID", "Action"]}

View File

@ -1,165 +0,0 @@
import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useLocation } from "wouter";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import { BusinessSnapshot } from "@/components/BusinessSnapshot";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { ApiError } from "@/lib/api";
import { uuid } from "@/lib/commerce";
import { cancelPartnerOrderInput, createPartnerOrderInput, partnerOrder, partnerOrderEligible, partnerOrderSummary } from "@/lib/partner-orders";
import { usePlatform } from "@/lib/platform";
import { quote } from "@/lib/quotes";
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
const api = "/b2b/partner-orders";
const route = "/admin/b2b-partner-orders";
function useRefreshOrders() {
const { scope } = usePlatform();
const client = useQueryClient();
return () => client.invalidateQueries({
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
typeof queryKey[2] === "string" && queryKey[2].startsWith(`${api}?`),
});
}
function PartnerOrderList({ accountId }: { accountId?: string }) {
const { can } = usePlatform();
const [offset, setOffset] = useState(0);
const params = new URLSearchParams({ limit: "25", offset: String(offset) });
if (accountId) params.set("accountId", accountId);
const query = usePrivateQuery(`${api}?${params}`, z.array(partnerOrderSummary));
return <Panel title="Partner order history">
{accountId && <p className="workspace-id">Business account {accountId}</p>}
{can("b2b.order.manage") && <p><WorkspaceLink href={`${route}/new`}>Record a partner order</WorkspaceLink></p>}
<QueryView query={query}>{(rows) => <>
<Table head={["Order", "Business", "Partner reference", "Status", "Merchandise total", "Recorded"]}
rowKeys={rows.map((row) => row.id)} rows={rows.map((row) => [
<WorkspaceLink href={`${route}/${row.id}`}>{row.number}</WorkspaceLink>, row.accountSnapshot.legalName,
row.partnerReference, row.status, `${row.currency} ${row.merchandiseTotal}`, new Date(row.createdAt).toLocaleString(),
])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</>}</QueryView>
</Panel>;
}
function CreatePartnerOrder({ quoteId }: { quoteId?: string }) {
const { can } = usePlatform();
const [, navigate] = useLocation();
const refresh = useRefreshOrders();
const command = useIdempotentCommand(api, createPartnerOrderInput, partnerOrder, "create");
const pending = command.pending;
if (!can("b2b.order.manage")) return <Alert severity="warning">Your account does not have permission to record partner orders.</Alert>;
async function submit(input: unknown) {
const saved = await command.run(input);
await refresh();
navigate(`${route}/${saved.id}`);
}
return <Panel title="Record a partner purchase order">
<p>Use an accepted, unexpired quotation for a verified business. The order copies the quotation’s merchandise terms.</p>
{pending ? <ActionForm label="Retry partner order" read={() => ({})} submit={submit}>
<Alert severity="warning">The server may have recorded this order. Retrying reuses the original reference {pending.partnerReference} and quotation {pending.quoteId}.</Alert>
</ActionForm> : quoteId && can("b2b.quote.read") ?
<OrderFromQuote quoteId={quoteId} submit={submit} /> :
<OrderForm quoteId={quoteId} submit={submit} />}
</Panel>;
}
function OrderFromQuote({ quoteId, submit }: { quoteId: string; submit: (input: unknown) => Promise<void> }) {
const query = usePrivateQuery(`/b2b/quotes/${quoteId}`, quote);
return <QueryView query={query}>{(source) => <>
<p><WorkspaceLink href={`/admin/b2b-quotes/${quoteId}`}>{source.number}</WorkspaceLink> · {source.accountSnapshot.legalName} · {source.currency} {source.merchandiseTotal}</p>
<p>Expires {new Date(source.expiresAt).toLocaleString()}</p>
{partnerOrderEligible(source) ? <OrderForm quoteId={quoteId} submit={async (input) => {
if (!partnerOrderEligible(source)) throw new Error("This quotation has expired.");
await submit(input);
}} /> : <Alert severity="warning">Only an accepted, unexpired quotation can be converted.</Alert>}
</>}</QueryView>;
}
function OrderForm({ quoteId, submit }: { quoteId?: string; submit: (input: unknown) => Promise<void> }) {
const { can } = usePlatform();
return <ActionForm label="Record partner order" reset={false} read={(form) => ({
quoteId: quoteId ?? readText(form, "quoteId").trim(),
partnerReference: readText(form, "partnerReference"),
note: readText(form, "note").trim() || null,
})} submit={submit}>
{quoteId ? <p className="workspace-id">Quotation ID {quoteId}</p> : <>
{can("b2b.quote.read") && <WorkspaceLink href="/admin/b2b-quotes">Find a quotation</WorkspaceLink>}
<Field name="quoteId" label="Quotation ID" maxLength={36} />
</>}
<Field name="partnerReference" label="Partner reference" maxLength={80} />
<Field name="note" label="Order note" required={false} maxLength={500} />
</ActionForm>;
}
function PartnerOrderDetail({ id }: { id: string }) {
const { can, scope } = usePlatform();
const client = useQueryClient();
const refreshLists = useRefreshOrders();
const path = `${api}/${id}`;
const query = usePrivateQuery(path, partnerOrder);
const cancel = useIdempotentCommand(`${path}/cancel`, cancelPartnerOrderInput, partnerOrder, id);
async function cancelOrder(input: unknown) {
try {
const saved = await cancel.run(input);
client.setQueryData(["private", scope, path], saved);
await refreshLists();
} catch (error) {
if (error instanceof ApiError && error.code === "B2B_ORDER_ALREADY_CANCELLED") {
await Promise.all([query.refetch(), refreshLists()]);
}
throw error;
}
}
return <QueryView query={query}>{(order) => <div className="workspace-id">
<Panel title={order.number}>
<p>{order.status} · Partner reference {order.partnerReference}</p>
<p>Recorded {new Date(order.createdAt).toLocaleString()} by {order.createdById}</p>
{order.note && <p>{order.note}</p>}
<WorkspaceLink href={`${route}/account/${order.accountId}`}>All orders for this business</WorkspaceLink>
{can("b2b.payment.read") && <p><WorkspaceLink href={`${route}/${id}/payments`}>Partner receipts and balance</WorkspaceLink></p>}
{can("b2b.quote.read") && <p><WorkspaceLink href={`/admin/b2b-quotes/${order.quoteId}`}>Source quotation</WorkspaceLink></p>}
<BusinessSnapshot account={order.accountSnapshot} />
<Table head={["Variant", "Quantity", "Minimum", "Unit price", "Line total"]}
rowKeys={order.lines.map((line) => line.id)} rows={order.lines.map((line) => [
`${line.name} (${line.sku})`, line.quantity, line.minQuantity,
`${order.currency} ${line.unitPrice}`, `${order.currency} ${line.lineTotal}`,
])} />
<p>Merchandise total {order.currency} {order.merchandiseTotal}</p>
</Panel>
{order.cancellation ? <Panel title="Cancellation">
<p>{order.cancellation.reason}</p>
<p>Recorded {new Date(order.cancellation.createdAt).toLocaleString()} by {order.cancellation.actorId}</p>
</Panel> : can("b2b.order.manage") && order.status === "RECEIVED" && <Panel title="Cancel order">
<ActionForm key={cancel.pending ? "retry" : "cancel"} label={cancel.pending ? "Retry cancellation" : "Cancel partner order"}
read={(form) => cancel.pending ? {} : ({ reason: readText(form, "reason") })} submit={cancelOrder}>
{cancel.pending ? <Alert severity="warning">Retrying reuses the original cancellation reason and key.</Alert> : <>
<p>Cancellation is permanent. Any active payment receipts must be reversed first.</p>
<Field name="reason" label="Cancellation reason" maxLength={500} />
</>}
</ActionForm>
</Panel>}
</div>}</QueryView>;
}
export default function PartnerOrdersPage({ id, accountId, quoteId, create = false }: {
id?: string; accountId?: string; quoteId?: string; create?: boolean;
}) {
const order = uuid.safeParse(id);
const account = uuid.safeParse(accountId);
const source = uuid.safeParse(quoteId);
const invalid = (id && !order.success) || (accountId && !account.success) || (quoteId && !source.success);
return <WorkspaceShell title="B2B Partner Orders" permission="b2b.order.read">
{(id || accountId || create) && <WorkspaceLink href={route}>All partner orders</WorkspaceLink>}
{invalid ? <Alert severity="warning">Invalid order, account, or quotation ID.</Alert> :
create ? <CreatePartnerOrder key={source.data ?? "new"} quoteId={source.data} /> :
order.success ? <PartnerOrderDetail key={order.data} id={order.data} /> :
<PartnerOrderList key={account.data ?? "all"} accountId={account.data} />}
</WorkspaceShell>;
}

View File

@ -1,114 +0,0 @@
import { useState } from "react";
import { useLocation } from "wouter";
import { useQueryClient } from "@tanstack/react-query";
import Alert from "@mui/material/Alert";
import Button from "@mui/material/Button";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import { ActionForm, Check, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { uuid } from "@/lib/commerce";
import { partnerPayment, partnerPaymentHistory, partnerPaymentInput, reversePartnerPaymentInput } from "@/lib/partner-payments";
import { paymentMethods } from "@/lib/supplier-finance";
import { usePlatform } from "@/lib/platform";
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
const route = "/admin/b2b-partner-orders";
export default function PartnerPaymentsPage({ orderId }: { orderId?: string }) {
const [, navigate] = useLocation();
const id = uuid.safeParse(orderId);
return <WorkspaceShell title="B2B Partner Payments" permission="b2b.payment.read">
{orderId ? id.success ? <PaymentHistory key={id.data} orderId={id.data} /> :
<Alert severity="warning">Invalid partner order ID.</Alert> :
<Panel title="Find partner receipts">
<ActionForm label="View partner payments" read={(form) => uuid.parse(readText(form, "orderId").trim())}
submit={async (value) => { navigate(`${route}/${uuid.parse(value)}/payments`); }}>
<Field name="orderId" label="Partner order ID" maxLength={36} />
</ActionForm>
</Panel>}
</WorkspaceShell>;
}
function PaymentHistory({ orderId }: { orderId: string }) {
const { can } = usePlatform();
const [offset, setOffset] = useState(0);
const [selected, select] = useState("");
const path = `/b2b/partner-orders/${orderId}/payments`;
const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, partnerPaymentHistory);
const command = useIdempotentCommand(path, partnerPaymentInput, partnerPayment, orderId);
return <>
{can("b2b.order.read") && <WorkspaceLink href={`${route}/${orderId}`}>View partner order</WorkspaceLink>}
<Panel title="Partner receipt history">
<p className="workspace-id">Partner order {orderId}</p>
<QueryView query={query}>{(data) => <>
<dl>
<dt>Merchandise total</dt><dd>{data.currency} {data.merchandiseTotal}</dd>
<dt>Paid total</dt><dd>{data.currency} {data.paidTotal}</dd>
<dt>Outstanding total</dt><dd>{data.currency} {data.outstandingTotal}</dd>
</dl>
<Table head={["Reference", "Received", "Method", "Amount", "Status", "Actions"]}
rowKeys={data.payments.map((payment) => payment.id)} rows={data.payments.map((payment) => [
payment.reference, payment.receivedOn.slice(0, 10), payment.method.replaceAll("_", " "),
`${payment.currency} ${payment.amount}`, payment.reversal ? "Reversed" : "Recorded",
<Button onClick={() => select(payment.id)} aria-pressed={selected === payment.id}>View receipt {payment.reference}</Button>,
])} />
<Pager offset={offset} count={data.payments.length} onPage={setOffset} />
{can("b2b.payment.manage") && (command.pending || data.outstandingTotal !== "0.00") &&
<ActionForm key={command.pending ? "retry" : "record"}
label={command.pending ? "Retry partner receipt" : "Record partner receipt"}
read={(form) => command.pending ? {} : Object.fromEntries(form)}
submit={async (input) => {
await command.run(input);
if (offset) setOffset(0);
await query.refetch();
}}>
{command.pending ? <Alert severity="warning">
The server may have recorded this receipt. Retrying reuses reference {command.pending.reference},
amount {data.currency} {command.pending.amount}, and the original key.
</Alert> : <>
<p>Record an external payment after verifying the receipt. The server checks the remaining merchandise balance.</p>
<Field name="reference" label="Payment reference" maxLength={80} />
<Field name="method" label="Payment method" options={paymentMethods.options.map((value) => ({ value, label: value.replaceAll("_", " ") }))} />
<Field name="amount" label={`Receipt amount (${data.currency})`} helper="Use two decimal places." maxLength={19} />
<Field name="receivedOn" label="Received on (YYYY-MM-DD)" maxLength={10} />
</>}
</ActionForm>}
</>}</QueryView>
</Panel>
{selected && <ReceiptDetails key={selected} path={`${path}/${selected}`} refresh={query.refetch} />}
</>;
}
function ReceiptDetails({ path, refresh }: { path: string; refresh: () => Promise<unknown> }) {
const { can, scope } = usePlatform();
const client = useQueryClient();
const query = usePrivateQuery(path, partnerPayment);
const command = useIdempotentCommand(`${path}/reverse`, reversePartnerPaymentInput, partnerPayment, path);
return <QueryView query={query}>{(payment) => <Panel title={`Receipt ${payment.reference}`}>
<p>{payment.currency} {payment.amount} · {payment.method.replaceAll("_", " ")} · Received {payment.receivedOn.slice(0, 10)}</p>
<p className="workspace-id">Recorded by {payment.recordedById} on {new Date(payment.createdAt).toLocaleString()}</p>
{payment.reversal && <>
<Alert severity="info">Receipt reversed.</Alert>
<p>{payment.reversal.reason}</p>
<p className="workspace-id">Reversed by {payment.reversal.reversedById} on {new Date(payment.reversal.createdAt).toLocaleString()}</p>
</>}
{can("b2b.payment.manage") && (command.pending || !payment.reversal) &&
<ActionForm key={command.pending ? "retry" : "reverse"}
label={command.pending ? "Retry receipt reversal" : "Reverse partner receipt"}
read={(form) => {
if (command.pending) return {};
if (!form.has("confirmed")) throw new Error("Confirm the receipt reversal before continuing.");
return { reason: readText(form, "reason") };
}} submit={async (input) => {
const saved = await command.run(input);
client.setQueryData(["private", scope, path], saved);
await refresh();
}}>
{command.pending ? <Alert severity="warning">The server may have reversed this receipt. Retrying uses the original reason and key.</Alert> : <>
<p>Reversal corrects the recorded receipt. Arrange any external refund through your payment provider.</p>
<Field name="reason" label="Reversal reason" maxLength={500} />
<Check name="confirmed" label={`Confirm reversal of ${payment.reference}`} />
</>}
</ActionForm>}
</Panel>}</QueryView>;
}

View File

@ -5,7 +5,7 @@ import Alert from "@mui/material/Alert";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
import Skeleton from "@mui/material/Skeleton"; import Skeleton from "@mui/material/Skeleton";
import Chip from "@mui/material/Chip"; import Chip from "@mui/material/Chip";
import { getProduct, productImageUrl } from "@/lib/api"; 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";
@ -43,18 +43,6 @@ export default function ProductPage({ id }: { id: string }) {
</> </>
) : ( ) : (
<div className="product-detail"> <div className="product-detail">
{query.data.images.length > 0 && (
<div className="product-gallery">
{query.data.images.map((image, index) => (
<img
key={image.id}
src={productImageUrl(organization, id, image.id)}
alt={`${query.data.name}, photo ${index + 1}`}
loading={index ? "lazy" : "eager"}
/>
))}
</div>
)}
<h1>{query.data.name}</h1> <h1>{query.data.name}</h1>
<p className="product-description"> <p className="product-description">
{query.data.description || {query.data.description ||

View File

@ -4,7 +4,6 @@ import { useLocation } from "wouter";
import { z } from "zod"; import { z } from "zod";
import Alert from "@mui/material/Alert"; import Alert from "@mui/material/Alert";
import { WorkspaceShell } from "@/components/WorkspaceShell"; import { WorkspaceShell } from "@/components/WorkspaceShell";
import { BusinessSnapshot } from "@/components/BusinessSnapshot";
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools"; import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { VariantQuantityFields, readVariantQuantities } from "@/components/VariantQuantityFields"; import { VariantQuantityFields, readVariantQuantities } from "@/components/VariantQuantityFields";
import { ApiError } from "@/lib/api"; import { ApiError } from "@/lib/api";
@ -13,11 +12,11 @@ import { usePlatform } from "@/lib/platform";
import { priceListDetail } from "@/lib/price-lists"; import { priceListDetail } from "@/lib/price-lists";
import { issueQuoteInput, quote, quoteExpiry, quoteResponseInput, quoteSummary, responseKind } from "@/lib/quotes"; import { issueQuoteInput, quote, quoteExpiry, quoteResponseInput, quoteSummary, responseKind } from "@/lib/quotes";
import { useIdempotentCommand } from "@/lib/use-idempotent-command"; import { useIdempotentCommand } from "@/lib/use-idempotent-command";
import { partnerOrderEligible } from "@/lib/partner-orders";
const api = "/b2b/quotes"; const api = "/b2b/quotes";
const route = "/admin/b2b-quotes"; const route = "/admin/b2b-quotes";
const terms = "Merchandise only. Tax, shipping, stock reservation, credit, and payment are outside this quotation."; const terms = "Merchandise only. Tax, shipping, stock reservation, credit, and payment are outside this quotation.";
type Quote = z.infer<typeof quote>;
type Source = { accountId: string; priceListId: string }; type Source = { accountId: string; priceListId: string };
function useRefreshQuoteLists() { function useRefreshQuoteLists() {
@ -125,7 +124,7 @@ function QuoteDetails({ id }: { id: string }) {
const path = `${api}/${id}`; const path = `${api}/${id}`;
const query = usePrivateQuery(path, quote); const query = usePrivateQuery(path, quote);
const command = useIdempotentCommand(`${path}/response`, quoteResponseInput, quote, id); const command = useIdempotentCommand(`${path}/response`, quoteResponseInput, quote, id);
const expiry = query.data && (query.data.status === "ISSUED" || query.data.status === "ACCEPTED") ? query.data.expiresAt : undefined; const expiry = query.data?.status === "ISSUED" ? query.data.expiresAt : undefined;
const [, setExpired] = useState(false); const [, setExpired] = useState(false);
useEffect(() => { useEffect(() => {
if (!expiry) return; if (!expiry) return;
@ -155,7 +154,7 @@ function QuoteDetails({ id }: { id: string }) {
return <QueryView query={query}>{(record) => <Panel title={record.number}> return <QueryView query={query}>{(record) => <Panel title={record.number}>
<p>{visibleStatus(record)} · Issued {new Date(record.createdAt).toLocaleString()} · Expires {new Date(record.expiresAt).toLocaleString()}</p> <p>{visibleStatus(record)} · Issued {new Date(record.createdAt).toLocaleString()} · Expires {new Date(record.expiresAt).toLocaleString()}</p>
<p>Price list {record.priceListName}{record.customerReference && ` · Customer reference ${record.customerReference}`}</p> <p>Price list {record.priceListName}{record.customerReference && ` · Customer reference ${record.customerReference}`}</p>
<BusinessSnapshot account={record.accountSnapshot} /> <AccountSnapshot account={record.accountSnapshot} />
<Table head={["Variant", "Quantity", "Minimum", "Unit price", "Line total"]} rowKeys={record.lines.map((line) => line.id)} <Table head={["Variant", "Quantity", "Minimum", "Unit price", "Line total"]} rowKeys={record.lines.map((line) => line.id)}
rows={record.lines.map((line) => [ rows={record.lines.map((line) => [
`${line.name} (${line.sku})`, line.quantity, line.minQuantity, `${line.name} (${line.sku})`, line.quantity, line.minQuantity,
@ -163,8 +162,6 @@ function QuoteDetails({ id }: { id: string }) {
])} /> ])} />
<p>Merchandise total {record.currency} {record.merchandiseTotal}</p> <p>Merchandise total {record.currency} {record.merchandiseTotal}</p>
<p>{terms}</p> <p>{terms}</p>
{partnerOrderEligible(record) && can("b2b.order.read") && can("b2b.order.manage") &&
<p><WorkspaceLink href={`/admin/b2b-partner-orders/new/${record.id}`}>Record partner order from this quotation</WorkspaceLink></p>}
{record.response ? <Alert severity="info">{record.response.kind} on {new Date(record.response.createdAt).toLocaleString()} · {record.response.note}</Alert> : {record.response ? <Alert severity="info">{record.response.kind} on {new Date(record.response.createdAt).toLocaleString()} · {record.response.note}</Alert> :
can("b2b.quote.manage") && (command.pending || visibleStatus(record) === "ISSUED") && ( can("b2b.quote.manage") && (command.pending || visibleStatus(record) === "ISSUED") && (
<ActionForm key={command.pending ? "retry" : "response"} label={command.pending ? "Retry quotation response" : "Record quotation response"} <ActionForm key={command.pending ? "retry" : "response"} label={command.pending ? "Retry quotation response" : "Record quotation response"}
@ -183,6 +180,16 @@ function QuoteDetails({ id }: { id: string }) {
</Panel>}</QueryView>; </Panel>}</QueryView>;
} }
function AccountSnapshot({ account }: { account: Quote["accountSnapshot"] }) {
return <section>
<h3>Business at issuance</h3>
<p>{account.legalName}{account.tradingName && ` · ${account.tradingName}`} · Profile version {account.profileVersion}</p>
<p>Registration {account.registrationNumber}{account.taxIdentifier && ` · Tax ID ${account.taxIdentifier}`}</p>
<p className="workspace-id">{account.contactEmail}{account.contactPhone && ` · ${account.contactPhone}`}</p>
<p>{[account.billingLine1, account.billingCity, account.billingRegion, account.billingPostalCode, account.countryCode].join(", ")}</p>
</section>;
}
export default function QuotesPage({ id, accountId, priceListId, issue = false }: { export default function QuotesPage({ id, accountId, priceListId, issue = false }: {
id?: string; accountId?: string; priceListId?: string; issue?: boolean; id?: string; accountId?: string; priceListId?: string; issue?: boolean;
}) { }) {

View File

@ -11,25 +11,20 @@ import "./workspace.css";
import { WorkspaceNavigation } from "@/components/WorkspaceShell"; import { WorkspaceNavigation } from "@/components/WorkspaceShell";
export default function WorkspacePage() { export default function WorkspacePage() {
const { organization, principal, signIn, signUp, signOut, notice } = const { organization, principal, signIn, signOut, notice } = usePlatform();
usePlatform();
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [error, setError] = useState<unknown>(null); const [error, setError] = useState<unknown>(null);
const [creating, setCreating] = useState(false);
async function submit(event: FormEvent<HTMLFormElement>) { async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); event.preventDefault();
const form = event.currentTarget; const form = event.currentTarget;
const fields = new FormData(form); const fields = new FormData(form);
setBusy(true); setBusy(true);
setError(null); setError(null);
const name = String(fields.get("name") ?? "");
const email = String(fields.get("email")); const email = String(fields.get("email"));
const password = String(fields.get("password")); const password = String(fields.get("password"));
form.reset(); form.reset();
try { try {
await (creating await signIn(email, password);
? signUp(name, email, password)
: signIn(email, password));
} catch (error) { } catch (error) {
setError(error); setError(error);
} finally { } finally {
@ -52,7 +47,7 @@ export default function WorkspacePage() {
<Container maxWidth="md"> <Container maxWidth="md">
<h1>Account Workspace</h1> <h1>Account Workspace</h1>
<p className="workspace-intro"> <p className="workspace-intro">
Sign in, or create a customer account to shop. Sign in with your approved Mani Candles account.
</p> </p>
<Paper variant="outlined" className="workspace-panel"> <Paper variant="outlined" className="workspace-panel">
<ApiNotice error={error} /> <ApiNotice error={error} />
@ -73,7 +68,7 @@ export default function WorkspacePage() {
))} ))}
</ul> </ul>
) : ( ) : (
<p>Customer account. Use your cart, addresses and orders below.</p> <p>No permissions assigned. Contact your administrator.</p>
)} )}
<p className="workspace-intro"> <p className="workspace-intro">
Open a customer or administration tool below. Open a customer or administration tool below.
@ -94,20 +89,11 @@ export default function WorkspacePage() {
backend. backend.
</Alert> </Alert>
)} )}
{creating && (
<TextField
label="Full name"
name="name"
autoComplete="name"
required
inputProps={{ maxLength: 160 }}
/>
)}
<TextField <TextField
label="Email address" label="Email address"
name="email" name="email"
type="email" type="email"
autoComplete={creating ? "email" : "username"} autoComplete="username"
required required
inputProps={{ maxLength: 254 }} inputProps={{ maxLength: 254 }}
/> />
@ -115,36 +101,16 @@ export default function WorkspacePage() {
label="Password" label="Password"
name="password" name="password"
type="password" type="password"
autoComplete={creating ? "new-password" : "current-password"} autoComplete="current-password"
required required
helperText={creating ? "At least 15 characters." : undefined} inputProps={{ maxLength: 128 }}
inputProps={{ minLength: creating ? 15 : 1, maxLength: 128 }}
/> />
<Button <Button
variant="contained" variant="contained"
type="submit" type="submit"
disabled={busy || !organization} disabled={busy || !organization}
> >
{creating {busy ? "Signing in…" : "Sign in"}
? busy
? "Creating account…"
: "Create account"
: busy
? "Signing in…"
: "Sign in"}
</Button>
<Button
variant="text"
type="button"
disabled={busy}
onClick={() => {
setCreating(!creating);
setError(null);
}}
>
{creating
? "Already have an account? Sign in"
: "New customer? Create an account"}
</Button> </Button>
<small> <small>
Sessions stay in memory. Reloading or closing this page requires Sessions stay in memory. Reloading or closing this page requires

View File

@ -1,176 +1,176 @@
/* ─── products.css ───────────────────────────────────────── */ /* ─── products.css ───────────────────────────────────────── */
/* HERO */ /* HERO */
.products-hero { .products-hero {
padding: 6rem 1.5rem; padding: 6rem 1.5rem;
background: var(--brand-card); background: var(--brand-card);
text-align: center; text-align: center;
} }
.products-hero h1 { .products-hero h1 {
font-family: var(--font-serif); font-family: var(--font-serif);
font-size: clamp(2.5rem, 6vw, 4rem); font-size: clamp(2.5rem, 6vw, 4rem);
color: var(--brand-purple); color: var(--brand-purple);
margin-bottom: 1rem; margin-bottom: 1rem;
} }
.products-hero p { .products-hero p {
font-family: var(--font-sans); font-family: var(--font-sans);
font-size: 1.05rem; font-size: 1.05rem;
color: var(--brand-muted); color: var(--brand-muted);
line-height: 1.8; line-height: 1.8;
max-width: 640px; max-width: 640px;
margin: 0 auto 2rem; margin: 0 auto 2rem;
} }
/* FILTERS */ /* FILTERS */
.products-body { .products-body {
padding: 5rem 1.5rem; padding: 5rem 1.5rem;
background: var(--brand-light-lavender); background: var(--brand-light-lavender);
} }
.filter-bar { .filter-bar {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
justify-content: center; justify-content: center;
gap: 1rem; gap: 1rem;
margin-bottom: 4rem; margin-bottom: 4rem;
} }
.filter-btn { .filter-btn {
font-family: var(--font-display); font-family: var(--font-display);
font-size: 0.72rem; font-size: 0.72rem;
letter-spacing: 0.2em; letter-spacing: 0.2em;
text-transform: uppercase; text-transform: uppercase;
padding: 0.5rem 1.5rem; padding: 0.5rem 1.5rem;
background: none; background: none;
border: none; border: none;
border-bottom: 2px solid transparent; border-bottom: 2px solid transparent;
color: var(--brand-muted); color: var(--brand-muted);
cursor: pointer; cursor: pointer;
transition: color 0.3s ease, border-color 0.3s ease; transition: color 0.3s ease, border-color 0.3s ease;
} }
.filter-btn:hover { .filter-btn:hover {
color: var(--brand-purple); color: var(--brand-purple);
} }
.filter-btn.active { .filter-btn.active {
color: var(--brand-purple); color: var(--brand-purple);
border-bottom-color: var(--brand-gold); border-bottom-color: var(--brand-gold);
} }
/* PRODUCT GRID */ /* PRODUCT GRID */
.products-grid { .products-grid {
display: grid; display: grid;
grid-template-columns: 1fr; grid-template-columns: 1fr;
gap: 3rem 2rem; gap: 3rem 2rem;
max-width: 1280px; max-width: 1280px;
margin: 0 auto; margin: 0 auto;
} }
@media (min-width: 640px) { .products-grid { grid-template-columns: 1fr 1fr; } } @media (min-width: 640px) { .products-grid { grid-template-columns: 1fr 1fr; } }
@media (min-width: 1024px) { .products-grid { grid-template-columns: repeat(4, 1fr); } } @media (min-width: 1024px) { .products-grid { grid-template-columns: repeat(4, 1fr); } }
.prod-card { .prod-card {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
cursor: pointer; cursor: pointer;
} }
.prod-img-wrap { .prod-img-wrap {
position: relative; position: relative;
aspect-ratio: 4 / 5; aspect-ratio: 4 / 5;
overflow: hidden; overflow: hidden;
background: var(--brand-card); background: var(--brand-card);
border: 1px solid var(--brand-border); border: 1px solid var(--brand-border);
margin-bottom: 1.25rem; margin-bottom: 1.25rem;
} }
.prod-img-wrap img { .prod-img-wrap img {
width: 100%; width: 100%;
height: 100%; height: 100%;
object-fit: cover; object-fit: cover;
transition: transform 1s ease; transition: transform 1s ease;
} }
.prod-card:hover .prod-img-wrap img { .prod-card:hover .prod-img-wrap img {
transform: scale(1.05); transform: scale(1.05);
} }
.prod-overlay { .prod-overlay {
position: absolute; position: absolute;
inset: 0; inset: 0;
background: rgba(91,30,140,0.3); background: rgba(91,30,140,0.3);
opacity: 0; opacity: 0;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
backdrop-filter: blur(2px); backdrop-filter: blur(2px);
transition: opacity 0.5s ease; transition: opacity 0.5s ease;
} }
.prod-card:hover .prod-overlay { .prod-card:hover .prod-overlay {
opacity: 1; opacity: 1;
} }
.prod-overlay-btn { .prod-overlay-btn {
padding: 0.75rem 2rem; padding: 0.75rem 2rem;
background: var(--brand-light-lavender); background: var(--brand-light-lavender);
color: var(--brand-purple); color: var(--brand-purple);
font-family: var(--font-display); font-family: var(--font-display);
font-size: 0.72rem; font-size: 0.72rem;
letter-spacing: 0.18em; letter-spacing: 0.18em;
text-transform: uppercase; text-transform: uppercase;
border: none; border: none;
cursor: pointer; cursor: pointer;
transform: translateY(32px); transform: translateY(32px);
transition: transform 0.5s ease, background 0.3s ease, color 0.3s ease; transition: transform 0.5s ease, background 0.3s ease, color 0.3s ease;
box-shadow: 0 4px 16px rgba(0,0,0,0.15); box-shadow: 0 4px 16px rgba(0,0,0,0.15);
} }
.prod-card:hover .prod-overlay-btn { .prod-card:hover .prod-overlay-btn {
transform: translateY(0); transform: translateY(0);
} }
.prod-overlay-btn:hover { .prod-overlay-btn:hover {
background: var(--brand-gold); background: var(--brand-gold);
color: #ffffff; color: #ffffff;
} }
.prod-info { .prod-info {
flex: 1; flex: 1;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: space-between; justify-content: space-between;
} }
.prod-name { .prod-name {
font-family: var(--font-serif); font-family: var(--font-serif);
font-size: 1.4rem; font-size: 1.4rem;
color: var(--brand-purple); color: var(--brand-purple);
margin-bottom: 0.25rem; margin-bottom: 0.25rem;
} }
.prod-scent { .prod-scent {
font-family: var(--font-sans); font-family: var(--font-sans);
font-size: 0.85rem; font-size: 0.85rem;
color: var(--brand-muted); color: var(--brand-muted);
line-height: 1.5; line-height: 1.5;
margin-bottom: 0.75rem; margin-bottom: 0.75rem;
/* two-line clamp */ /* two-line clamp */
display: -webkit-box; display: -webkit-box;
-webkit-line-clamp: 2; -webkit-line-clamp: 2;
-webkit-box-orient: vertical; -webkit-box-orient: vertical;
overflow: hidden; overflow: hidden;
} }
.prod-price { .prod-price {
font-family: var(--font-sans); font-family: var(--font-sans);
font-weight: 500; font-weight: 500;
font-size: 1.05rem; font-size: 1.05rem;
color: var(--brand-gold); color: var(--brand-gold);
} }
.catalog-placeholder { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:1rem; color:var(--brand-purple); background:var(--brand-card); } .catalog-placeholder { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:1rem; color:var(--brand-purple); background:var(--brand-card); }
.catalog-placeholder span { font-family:var(--font-script); font-size:2rem; } .catalog-placeholder span { font-family:var(--font-script); font-size:2rem; }
@ -189,7 +189,3 @@
.variant-list dl>div { display:flex; flex-wrap:wrap; gap:.5rem; font-size:.9rem; } .variant-list dl>div { display:flex; flex-wrap:wrap; gap:.5rem; font-size:.9rem; }
.variant-list dt { font-weight:600; } .variant-list dt { font-weight:600; }
@media(max-width:480px) { .variant-list li { flex-direction:column; } .products-body { padding:3rem .5rem; } .catalog-search { flex-direction:column; } } @media(max-width:480px) { .variant-list li { flex-direction:column; } .products-body { padding:3rem .5rem; } .catalog-search { flex-direction:column; } }
.product-gallery { display:grid; grid-template-columns:repeat(auto-fill, minmax(200px, 1fr)); gap:1rem; margin:1.5rem 0; }
.product-gallery img { width:100%; aspect-ratio:4 / 5; object-fit:cover; border:1px solid var(--brand-border); }
.product-gallery img:first-child { grid-column:1 / -1; max-height:520px; }

View File

@ -3,7 +3,6 @@ import assert from "node:assert/strict";
import { import {
apiRequest, apiRequest,
apiPdf, apiPdf,
apiArtwork,
listProducts, listProducts,
getProduct, getProduct,
login, login,
@ -58,50 +57,6 @@ test("private PDF downloads preserve API denial and require the expected PDF med
globalThis.fetch = async () => Response.json({ code: "DOCUMENT_PENDING_REVIEW" }, { status: 403 }); globalThis.fetch = async () => Response.json({ code: "DOCUMENT_PENDING_REVIEW" }, { status: 403 });
await assert.rejects(apiPdf(path, content.length, "opaque", controller.signal), { code: "DOCUMENT_PENDING_REVIEW", status: 403 }); await assert.rejects(apiPdf(path, content.length, "opaque", controller.signal), { code: "DOCUMENT_PENDING_REVIEW", status: 403 });
}); });
test("private artwork downloads authenticate and enforce the declared file type and size", async () => {
const controller = new AbortController();
const content = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
const mimeType = "image/png";
globalThis.fetch = async (url, options) => {
assert.equal(url, `/api/v1/b2b/artwork-versions/${org}/download`);
const headers = new Headers(options?.headers);
assert.equal(headers.get("authorization"), "Bearer opaque");
assert.equal(headers.get("accept"), mimeType);
assert.equal(options?.cache, "no-store");
assert.equal(options?.redirect, "error");
assert.equal(options?.signal?.aborted, false);
return new Response(content, { headers: { "Content-Type": mimeType } });
};
const file = await apiArtwork(org, content.length, mimeType, "opaque", controller.signal);
assert.deepEqual(new Uint8Array(await file.arrayBuffer()), content);
await assert.rejects(apiArtwork(org, 1, mimeType, "opaque", controller.signal), { code: "INVALID_RESPONSE" });
globalThis.fetch = async () =>
new Response(content, { headers: { "Content-Type": "image/jpeg" } });
await assert.rejects(apiArtwork(org, content.length, mimeType, "opaque", controller.signal), { code: "INVALID_RESPONSE" });
globalThis.fetch = async () => Response.json({ code: "B2B_ARTWORK_DOWNLOAD_DENIED" }, { status: 403 });
await assert.rejects(apiArtwork(org, content.length, mimeType, "opaque", controller.signal), {
code: "B2B_ARTWORK_DOWNLOAD_DENIED", status: 403,
});
});
test("artwork download validates metadata before fetch and propagates aborts", async () => {
const controller = new AbortController();
globalThis.fetch = async () => {
assert.fail("Invalid artwork metadata must not send a request");
};
await assert.rejects(apiArtwork("../auth/me", 1, "application/pdf", "opaque", controller.signal), { name: "ZodError" });
await assert.rejects(apiArtwork(org, 1, "text/html", "opaque", controller.signal), { name: "ZodError" });
await assert.rejects(apiArtwork(org, 2 * 1024 * 1024 + 1, "image/jpeg", "opaque", controller.signal), { name: "ZodError" });
globalThis.fetch = async (_url, options) => {
const signal = options?.signal;
assert.ok(signal);
controller.abort(new Error("Test abort"));
assert.equal(signal.aborted, true);
throw new DOMException("Request cancelled", "AbortError");
};
await assert.rejects(apiArtwork(org, 1, "image/jpeg", "opaque", controller.signal), { name: "AbortError" });
});
test("invalid organization cannot trigger catalog requests", async () => { test("invalid organization cannot trigger catalog requests", async () => {
globalThis.fetch = async () => { globalThis.fetch = async () => {
assert.fail("Must not send a request"); assert.fail("Must not send a request");

View File

@ -1,57 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import {
artworkDecision,
artworkDetails,
artworkInput,
artworkProject,
artworkVersion,
maxArtworkBytes,
prepareArtworkUpload,
} from "../src/lib/artwork.ts";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
const date = "2026-11-16T00:00:00.000Z";
const input = { accountId: id, name: "Brand refresh", placement: "LABEL", brief: "Use the supplied customer logo." };
const version = {
id, artworkId: id, uploadedById: id, version: 1, filename: "brand-proof.jpeg",
mimeType: "image/jpeg", sha256: "a".repeat(64), size: 10, createdAt: date, decision: null,
};
test("artwork creation and decisions enforce placement and trimmed plain-text notes", () => {
assert.deepEqual(artworkInput.parse({ ...input, name: " Brand refresh " }), input);
assert.equal(artworkInput.safeParse({ ...input, placement: "BANNER" }).success, false);
assert.equal(artworkInput.safeParse({ ...input, brief: " " }).success, false);
assert.equal(artworkInput.safeParse({ ...input, brief: "<logo>" }).success, false);
assert.deepEqual(artworkDecision.parse({ outcome: "APPROVED", note: " Looks good " }), { outcome: "APPROVED", note: "Looks good" });
assert.equal(artworkDecision.safeParse({ outcome: "REJECTED", note: "" }).success, false);
});
test("project and version reads retain safe metadata and strip payload bytes", () => {
const project = { ...input, id, createdAt: date };
assert.deepEqual(artworkProject.parse({ ...project, organizationId: id }), project);
assert.deepEqual(artworkDetails.parse({ ...project, versions: [{ ...version, content: [1, 2, 3] }] }),
{ ...project, versions: [version] });
const decision = { outcome: "APPROVED", note: "Reviewed the final logo", reviewerId: id, createdAt: date };
assert.equal(artworkVersion.parse({ ...version, decision }).decision?.reviewerId, id);
assert.equal(artworkVersion.safeParse({ ...version, mimeType: "image/svg+xml" }).success, false);
assert.equal(artworkVersion.safeParse({ ...version, mimeType: "application/pdf" }).success, false);
assert.equal(artworkVersion.safeParse({ ...version, size: maxArtworkBytes + 1 }).success, false);
});
test("artwork uploads use a single multipart file with the permitted media type", () => {
for (const [filename, type] of [["proof.pdf", "application/pdf"], ["proof.png", "image/png"], ["proof.jpg", "image/jpeg"], ["proof.jpeg", "image/jpeg"]]) {
const form = prepareArtworkUpload(new File(["bytes"], filename, { type }));
const selected = form.get("file");
assert.ok(selected instanceof File);
assert.equal(selected.name, filename);
assert.equal(selected.type, type);
assert.deepEqual([...form.keys()], ["file"]);
}
assert.equal((prepareArtworkUpload(new File(["bytes"], "proof.png")).get("file") as File).type, "image/png");
assert.throws(() => prepareArtworkUpload(null));
assert.throws(() => prepareArtworkUpload(new File(["bytes"], "public.svg", { type: "image/svg+xml" })));
assert.throws(() => prepareArtworkUpload(new File(["bytes"], "unsafe name.png", { type: "image/png" })));
assert.throws(() => prepareArtworkUpload(new File(["bytes"], "wrong.png", { type: "image/jpeg" })));
assert.throws(() => prepareArtworkUpload(new File([new Uint8Array(maxArtworkBytes + 1)], "large.pdf", { type: "application/pdf" })));
});

View File

@ -1,182 +0,0 @@
import { type ReactNode } from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "@mui/material/styles";
import { afterEach, expect, test, vi } from "vitest";
import { Route, Switch } from "wouter";
import { PlatformProvider, usePlatform } from "../src/lib/platform";
import ArtworkPage from "../src/pages/ArtworkPage";
import theme from "../src/theme";
const accountId = "d66c798a-f764-4b88-8d13-ace328ff1010";
const artworkId = "d66c798a-f764-4b88-8d13-ace328ff1011";
const firstVersionId = "d66c798a-f764-4b88-8d13-ace328ff1012";
const secondVersionId = "d66c798a-f764-4b88-8d13-ace328ff1013";
const uploaderId = "d66c798a-f764-4b88-8d13-ace328ff1014";
const reviewerId = "d66c798a-f764-4b88-8d13-ace328ff1015";
const createdAt = "2026-11-16T08:00:00.000Z";
const api = "/b2b/artworks";
const path = `${api}/${artworkId}`;
const route = "/admin/b2b-artwork";
const project = {
id: artworkId, accountId, name: "Seasonal gift branding", placement: "PACKAGING",
brief: "Use the supplied mark on a matte kraft box", createdAt,
};
const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const first = {
id: firstVersionId, artworkId, uploadedById: uploaderId, version: 1, filename: "artwork-v1.png",
mimeType: "image/png", size: png.length, sha256: "a".repeat(64), createdAt,
};
const pendingVersion = { ...first, version: 2, id: secondVersionId, filename: "artwork-v2.png", decision: null };
const previousVersion = {
...first,
decision: { outcome: "APPROVED", note: "Original file approved", reviewerId, createdAt },
};
const json = (body: unknown) => new Response(JSON.stringify(body));
function staffSession(url: string, userId: string, permissions: string[]) {
if (url.endsWith("/auth/login")) {
return json({
accessToken: "test-opaque", tokenType: "Bearer",
expiresAt: new Date(Date.now() + 3_600_000).toISOString(),
});
}
if (url.endsWith("/auth/me")) return json({ userId, organizationId: accountId, sessionId: accountId, permissions });
}
function Login() {
const { signIn } = usePlatform();
return <button onClick={() => signIn("staff@example.com", "test password")}>Test login</button>;
}
function showArtwork(children: ReactNode) {
localStorage.setItem("mani.organization", accountId);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(<ThemeProvider theme={theme}>
<QueryClientProvider client={client}>
<PlatformProvider><Login />{children}</PlatformProvider>
</QueryClientProvider>
</ThemeProvider>);
}
afterEach(() => {
vi.unstubAllGlobals();
history.replaceState(null, "", "/");
});
test("artwork readers can download approved versions but cannot download pending versions", async () => {
const fetch = vi.fn(async (url: string) => {
const auth = staffSession(url, reviewerId, ["b2b.artwork.read"]);
if (auth) return auth;
if (url.endsWith(path)) return json({ ...project, versions: [pendingVersion, previousVersion] });
throw new Error(`Unexpected request ${url}`);
});
vi.stubGlobal("fetch", fetch);
showArtwork(<ArtworkPage id={artworkId} />);
expect(fetch).not.toHaveBeenCalled();
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await screen.findByRole("button", { name: "Download artwork version 1" });
expect(screen.getByText(/^artwork-v2\.png /)).toBeTruthy();
expect(screen.queryByRole("button", { name: "Download artwork version 2" })).toBeNull();
expect(screen.queryByRole("button", { name: "Record artwork decision" })).toBeNull();
expect(screen.queryByRole("button", { name: "Upload artwork version" })).toBeNull();
});
test("the uploader can download their pending file and must wait for independent review", async () => {
vi.stubGlobal("fetch", vi.fn(async (url: string) => {
const auth = staffSession(url, uploaderId, ["b2b.artwork.read", "b2b.artwork.manage", "b2b.artwork.review"]);
if (auth) return auth;
if (url.endsWith(path)) return json({ ...project, versions: [pendingVersion, previousVersion] });
throw new Error(`Unexpected request ${url}`);
}));
showArtwork(<ArtworkPage id={artworkId} />);
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await screen.findByText("A different staff member must review this version.");
expect(screen.getByRole("button", { name: "Download artwork version 2" })).toBeTruthy();
expect(screen.queryByRole("button", { name: "Record artwork decision" })).toBeNull();
expect(screen.queryByRole("button", { name: "Upload artwork version" })).toBeNull();
});
test("an independent reviewer can approve the latest artwork version", async () => {
const note = "Brand mark is legible";
let submitted: unknown;
let current: typeof pendingVersion | typeof previousVersion = pendingVersion;
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
const auth = staffSession(url, reviewerId, ["b2b.artwork.read", "b2b.artwork.review"]);
if (auth) return auth;
if (url.endsWith(path)) return json({ ...project, versions: [current, previousVersion] });
if (url.endsWith(`/b2b/artwork-versions/${secondVersionId}/decision`) && options?.method === "POST") {
submitted = JSON.parse(String(options.body));
current = { ...pendingVersion, decision: { outcome: "APPROVED", note, reviewerId, createdAt } };
return json(current);
}
throw new Error(`Unexpected request ${url}`);
}));
showArtwork(<ArtworkPage id={artworkId} />);
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await user.selectOptions(await screen.findByRole("combobox", { name: /Review decision/ }), "APPROVED");
await user.type(screen.getByRole("textbox", { name: /Review note/ }), note);
await user.click(screen.getByRole("button", { name: "Record artwork decision" }));
await screen.findByText(new RegExp(note));
expect(submitted).toEqual({ outcome: "APPROVED", note });
expect(screen.getByText(/Original file approved/)).toBeTruthy();
expect(screen.queryByRole("button", { name: "Record artwork decision" })).toBeNull();
});
test("a staff member can create a project and upload its first private PNG version", async () => {
const version = { ...first, decision: null };
let projectBody: unknown;
let uploadBody: FormData | undefined;
// jsdom reads its internal file list when constructing FormData, while user-event exposes the selected file on the input.
vi.stubGlobal("FormData", class extends FormData {
constructor(form?: HTMLFormElement) {
super(form);
const file = form?.querySelector<HTMLInputElement>("input[type=file]")?.files?.[0];
if (file) this.set("file", file);
}
});
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
const auth = staffSession(url, uploaderId, ["b2b.artwork.read", "b2b.artwork.manage"]);
if (auth) return auth;
if (url.endsWith(api) && options?.method === "POST") {
projectBody = JSON.parse(String(options.body));
return json(project);
}
if (url.endsWith(path)) return json({ ...project, versions: uploadBody ? [version] : [] });
if (url.endsWith(`${path}/versions`) && options?.method === "POST" && options.body instanceof FormData) {
uploadBody = options.body;
return json(version);
}
throw new Error(`Unexpected request ${url}`);
}));
history.replaceState(null, "", `${route}/new/${accountId}`);
showArtwork(<Switch>
<Route path={`${route}/new/:accountId`}>
{(params) => <ArtworkPage create accountId={params.accountId} />}
</Route>
<Route path={`${route}/:id`}>{(params) => <ArtworkPage id={params.id} />}</Route>
</Switch>);
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await user.type(await screen.findByRole("textbox", { name: /Project name/ }), project.name);
await user.selectOptions(screen.getByRole("combobox", { name: /Artwork placement/ }), project.placement);
await user.type(screen.getByRole("textbox", { name: /Artwork brief/ }), project.brief);
await user.click(screen.getByRole("button", { name: "Create artwork project" }));
const input = await screen.findByLabelText<HTMLInputElement>(/Artwork file/);
const file = new File([png], first.filename, { type: first.mimeType });
await user.upload(input, file);
expect(input.files?.[0]).toBe(file);
// The native required check also reads jsdom's internal list, so start at the submit event.
fireEvent.submit(screen.getByRole("form", { name: "Upload artwork version" }));
await screen.findByRole("button", { name: "Download artwork version 1" });
expect(location.pathname).toBe(`${route}/${artworkId}`);
expect(projectBody).toEqual({ accountId, name: project.name, placement: project.placement, brief: project.brief });
expect(uploadBody?.get("file")).toMatchObject({ name: first.filename, type: first.mimeType, size: png.length });
expect(screen.queryByRole("button", { name: "Upload artwork version" })).toBeNull();
});

View File

@ -1,74 +0,0 @@
#!/bin/sh
set -eu
fixture=$(mktemp -d)
trap 'rm -rf "$fixture"' EXIT
mkdir -p "$fixture/bin" "$fixture/site/releases"
export DEPLOY_TEST_ROOT="$fixture/site"
export PATH="$fixture/bin:$PATH"
cat > "$fixture/bin/curl" <<'MOCK'
#!/bin/sh
set -eu
case "$*" in
*release.txt*)
if [ -f "$DEPLOY_TEST_ROOT/wrong-marker" ]; then
echo wrong-release
else
cat "$DEPLOY_TEST_ROOT/current/release.txt"
fi ;;
*health/ready*)
test ! -f "$DEPLOY_TEST_ROOT/fail-health" || exit 1
if [ -f "$DEPLOY_TEST_ROOT/html-readiness" ]; then
echo '<html>Page not found</html>'
else
echo '{"status":"ok"}'
fi ;;
esac
MOCK
chmod +x "$fixture/bin/curl"
for release in 1-aaa 2-bbb 3-ccc 4-ddd; do
mkdir -p "$fixture/site/incoming/$release/dist"
printf '%s\n' "$release" > "$fixture/site/incoming/$release/dist/release.txt"
printf '<html>Test</html>\n' > "$fixture/site/incoming/$release/dist/index.html"
done
deploy() { sh scripts/deploy-frontend.sh "$fixture/site" "$1" test.example; }
touch "$fixture/site/fail-health"
if deploy 1-aaa; then echo 'Expected first release failure' >&2; exit 1; fi
test ! -L "$fixture/site/current"
rm "$fixture/site/fail-health"
deploy 1-aaa
deploy 2-bbb
test "$(cat "$fixture/site/current/release.txt")" = 2-bbb
test "$(cat "$fixture/site/previous/release.txt")" = 1-aaa
# A retried upload must not change files in an already published release.
mkdir -p "$fixture/site/incoming/2-bbb/dist"
echo 'incomplete retry' > "$fixture/site/incoming/2-bbb/dist/index.html"
deploy 2-bbb
test "$(cat "$fixture/site/current/index.html")" = '<html>Test</html>'
touch "$fixture/site/fail-health"
if deploy 3-ccc; then echo 'Expected rollback on readiness failure' >&2; exit 1; fi
test "$(cat "$fixture/site/current/release.txt")" = 2-bbb
test "$(cat "$fixture/site/previous/release.txt")" = 1-aaa
rm "$fixture/site/fail-health"
touch "$fixture/site/wrong-marker"
if deploy 3-ccc; then echo 'Expected rollback on wrong virtual host' >&2; exit 1; fi
test "$(cat "$fixture/site/current/release.txt")" = 2-bbb
rm "$fixture/site/wrong-marker"
deploy 1-aaa
test "$(cat "$fixture/site/current/release.txt")" = 2-bbb
# The existing HTTP site has no release metadata and must remain a rollback target.
rm "$fixture/site/current"
mkdir -p "$fixture/site/legacy"
echo legacy > "$fixture/site/legacy/index.html"
ln -s "$fixture/site/legacy" "$fixture/site/current"
touch "$fixture/site/fail-health"
if deploy 3-ccc; then echo 'Expected rollback to legacy site' >&2; exit 1; fi
test "$(cat "$fixture/site/current/index.html")" = legacy
rm "$fixture/site/fail-health"
deploy 3-ccc
test "$(cat "$fixture/site/previous/index.html")" = legacy
touch "$fixture/site/html-readiness"
if deploy 4-ddd; then echo 'Expected rollback when readiness serves HTML' >&2; exit 1; fi
test "$(cat "$fixture/site/current/release.txt")" = 3-ccc
printf 'Deployment activation, rollback and stale-build checks passed.\n'

View File

@ -1,75 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import {
cancelPartnerOrderInput,
createPartnerOrderInput,
partnerOrder,
partnerOrderEligible,
partnerOrderSummary,
} from "../src/lib/partner-orders.ts";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
const createdAt = "2026-11-17T00:00:00.000Z";
const accountSnapshot = {
legalName: "Northlight Studio",
tradingName: null,
registrationNumber: "REG-100",
taxIdentifier: null,
countryCode: "IN",
contactEmail: "buyer@example.com",
contactPhone: null,
billingLine1: "30 Market Road",
billingCity: "Mumbai",
billingRegion: "Maharashtra",
billingPostalCode: "400001",
profileVersion: 2,
};
test("partner order inputs retain reference case and require the exact payload", () => {
const input = { quoteId: id, partnerReference: " Customer-PO/42 ", note: null, idempotencyKey: id };
assert.deepEqual(createPartnerOrderInput.parse(input), { ...input, partnerReference: "Customer-PO/42" });
assert.equal(createPartnerOrderInput.safeParse({ ...input, note: "x" }).success, false);
assert.equal(createPartnerOrderInput.safeParse({ ...input, partnerReference: "x".repeat(81) }).success, false);
assert.equal(createPartnerOrderInput.safeParse({ ...input, partnerReference: "<reference>" }).success, false);
assert.equal(createPartnerOrderInput.safeParse({ ...input, accountId: id }).success, false);
assert.deepEqual(cancelPartnerOrderInput.parse({ reason: " Partner withdrew ", idempotencyKey: id }), {
reason: "Partner withdrew", idempotencyKey: id,
});
assert.equal(cancelPartnerOrderInput.safeParse({ reason: " ", idempotencyKey: id }).success, false);
});
test("an accepted quotation is eligible only before its expiry instant", () => {
const expiresAt = "2026-11-17T10:00:00+05:30";
const expiry = Date.parse(expiresAt);
assert.equal(partnerOrderEligible({ status: "ACCEPTED", expiresAt }, expiry - 1), true);
assert.equal(partnerOrderEligible({ status: "ACCEPTED", expiresAt }, expiry), false);
assert.equal(partnerOrderEligible({ status: "ISSUED", expiresAt }, expiry - 1), false);
assert.equal(partnerOrderEligible({ status: "ACCEPTED", expiresAt: "invalid" }, expiry - 1), false);
});
test("order parsers preserve immutable snapshots and exact amounts while dropping backend metadata", () => {
const order = {
id, accountId: id, quoteId: id, createdById: id, number: "BO-123", status: "CANCELLED",
partnerReference: "Customer-PO/42", note: null, currency: "INR", createdAt,
merchandiseTotal: "9999999999999999.99",
accountSnapshot,
organizationId: id,
requestHash: "opaque",
lines: [{
id, orderId: id, organizationId: id, variantId: id, sku: "AMBER", name: "Amber candle",
quantity: 12, minQuantity: 6, unitPrice: "123.45", lineTotal: "1481.40",
}],
cancellation: { actorId: id, reason: "Partner withdrew", createdAt, orderId: id, requestHash: "opaque" },
};
const detail = partnerOrder.parse(order);
assert.equal(detail.merchandiseTotal, order.merchandiseTotal);
assert.equal(detail.lines[0].lineTotal, "1481.40");
assert.equal(detail.accountSnapshot.profileVersion, 2);
assert.deepEqual(detail.cancellation, { actorId: id, reason: "Partner withdrew", createdAt });
assert.equal("requestHash" in detail, false);
assert.equal("organizationId" in detail.lines[0], false);
const summary = partnerOrderSummary.parse(order);
assert.deepEqual(summary.accountSnapshot, { legalName: accountSnapshot.legalName });
assert.equal("lines" in summary, false);
assert.equal(partnerOrder.safeParse({ ...order, merchandiseTotal: 123.45 }).success, false);
});

View File

@ -1,191 +0,0 @@
import { type ReactNode } from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "@mui/material/styles";
import { afterEach, expect, test, vi } from "vitest";
import { Route, Switch } from "wouter";
import { PlatformProvider, usePlatform } from "../src/lib/platform";
import PartnerOrdersPage from "../src/pages/PartnerOrdersPage";
import theme from "../src/theme";
const accountId = "d66c798a-f764-4b88-8d13-ace328ff1010";
const userId = "d66c798a-f764-4b88-8d13-ace328ff1011";
const quoteId = "d66c798a-f764-4b88-8d13-ace328ff1012";
const orderId = "d66c798a-f764-4b88-8d13-ace328ff1013";
const variantId = "d66c798a-f764-4b88-8d13-ace328ff1014";
const lineId = "d66c798a-f764-4b88-8d13-ace328ff1015";
const createdAt = "2026-11-17T08:00:00.000Z";
const route = "/admin/b2b-partner-orders";
const api = "/b2b/partner-orders";
const detail = `${api}/${orderId}`;
const profile = {
legalName: "Vanilla Gift Company", tradingName: null, registrationNumber: "REG-019", taxIdentifier: null,
countryCode: "IN", contactEmail: "partner@example.com", contactPhone: null, billingLine1: "42 Sample Road",
billingCity: "Mumbai", billingRegion: "Maharashtra", billingPostalCode: "400001", profileVersion: 1,
};
const line = {
id: lineId, variantId, sku: "VANILLA-TIN", name: "Vanilla tin",
quantity: 10, minQuantity: 8, unitPrice: "100.00", lineTotal: "1000.00",
};
const quote = {
id: quoteId, accountId, number: "BQ-ORDER-01", accountSnapshot: profile,
currency: "INR", merchandiseTotal: "1000.00", expiresAt: new Date(Date.now() + 86_400_000).toISOString(),
status: "ACCEPTED", priceListName: "Wholesale INR", customerReference: null, createdAt,
lines: [line], response: { kind: "ACCEPTED", note: "Customer accepted by email", createdAt },
};
const order = {
id: orderId, accountId, quoteId, createdById: userId, number: "BPO-ORDER-01",
partnerReference: "CUSTOMER-PO-123", note: "Requested by the purchasing team",
accountSnapshot: profile, currency: "INR", merchandiseTotal: "1000.00", createdAt,
status: "RECEIVED", lines: [line], cancellation: null,
};
const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status });
function staffSession(url: string, permissions: string[]) {
if (url.endsWith("/auth/login")) return json({
accessToken: "test-opaque", tokenType: "Bearer",
expiresAt: new Date(Date.now() + 3_600_000).toISOString(),
});
if (url.endsWith("/auth/me")) return json({
userId, organizationId: accountId, sessionId: accountId, permissions,
});
}
function Login() {
const { signIn } = usePlatform();
return <button onClick={() => signIn("staff@example.com", "test password")}>Test login</button>;
}
function showOrders(children: ReactNode) {
localStorage.setItem("mani.organization", accountId);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(<ThemeProvider theme={theme}>
<QueryClientProvider client={client}>
<PlatformProvider><Login />{children}</PlatformProvider>
</QueryClientProvider>
</ThemeProvider>);
}
afterEach(() => {
vi.unstubAllGlobals();
history.replaceState(null, "", "/");
});
test("conversion retries the same accepted quote, reference, note, and key after a lost response", async () => {
const attempts: unknown[] = [];
const fetch = vi.fn(async (url: string, options?: RequestInit) => {
const auth = staffSession(url, ["b2b.order.read", "b2b.order.manage", "b2b.quote.read"]);
if (auth) return auth;
if (url.endsWith(`/b2b/quotes/${quoteId}`)) return json(quote);
if (url.endsWith(api) && options?.method === "POST") {
attempts.push(JSON.parse(String(options.body)));
if (attempts.length === 1) throw new Error("Response lost");
return json(order);
}
if (url.endsWith(detail)) return json(order);
throw new Error(`Unexpected request ${url}`);
});
vi.stubGlobal("fetch", fetch);
history.replaceState(null, "", `${route}/new/${quoteId}`);
showOrders(<Switch>
<Route path={`${route}/new/:quoteId`}>{(params) => <PartnerOrdersPage create quoteId={params.quoteId} />}</Route>
<Route path={`${route}/:id`}>{(params) => <PartnerOrdersPage id={params.id} />}</Route>
</Switch>);
expect(fetch).not.toHaveBeenCalled();
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
fireEvent.change(await screen.findByRole("textbox", { name: /Partner reference/ }), {
target: { value: order.partnerReference },
});
fireEvent.change(screen.getByRole("textbox", { name: /Order note/ }), {
target: { value: order.note },
});
await user.click(screen.getByRole("button", { name: "Record partner order" }));
expect(attempts).toEqual([{
quoteId, partnerReference: order.partnerReference, note: order.note, idempotencyKey: expect.any(String),
}]);
await user.click(await screen.findByRole("button", { name: "Retry partner order" }));
await screen.findByRole("button", { name: "Cancel partner order" });
expect(location.pathname).toBe(`${route}/${orderId}`);
expect(attempts).toEqual([attempts[0], attempts[0]]);
});
test("a received partner order can be cancelled and the same cancellation key can be replayed", async () => {
const reason = "Partner withdrew purchase order";
let current: object = order;
const attempts: unknown[] = [];
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
const auth = staffSession(url, ["b2b.order.read", "b2b.order.manage"]);
if (auth) return auth;
if (url.endsWith(detail)) return json(current);
if (url.endsWith(`${detail}/cancel`) && options?.method === "POST") {
attempts.push(JSON.parse(String(options.body)));
current = { ...order, status: "CANCELLED", cancellation: { orderId, reason, actorId: userId, createdAt } };
if (attempts.length === 1) throw new Error("Response lost");
return json(current);
}
throw new Error(`Unexpected request ${url}`);
}));
showOrders(<PartnerOrdersPage id={orderId} />);
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
fireEvent.change(await screen.findByRole("textbox", { name: /Cancellation reason/ }), { target: { value: reason } });
await user.click(screen.getByRole("button", { name: "Cancel partner order" }));
expect(attempts).toEqual([{ reason, idempotencyKey: expect.any(String) }]);
await user.click(await screen.findByRole("button", { name: "Retry cancellation" }));
await screen.findByText(new RegExp(reason));
expect(screen.queryByRole("button", { name: "Cancel partner order" })).toBeNull();
expect(attempts).toEqual([attempts[0], attempts[0]]);
});
test("a read-only staff member can see the saved order without cancellation controls", async () => {
const fetch = vi.fn(async (url: string) => {
const auth = staffSession(url, ["b2b.order.read"]);
if (auth) return auth;
if (url.endsWith(detail)) return json(order);
throw new Error(`Unexpected request ${url}`);
});
vi.stubGlobal("fetch", fetch);
showOrders(<PartnerOrdersPage id={orderId} />);
expect(fetch).not.toHaveBeenCalled();
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await screen.findByText(/Vanilla tin/);
expect(screen.queryByRole("textbox", { name: /Cancellation reason/ })).toBeNull();
expect(screen.queryByRole("button", { name: "Cancel partner order" })).toBeNull();
});
test("a cancellation blocked by an active receipt keeps the saved order and explains the conflict", async () => {
const fetch = vi.fn(async (url: string, options?: RequestInit) => {
const auth = staffSession(url, ["b2b.order.read", "b2b.order.manage"]);
if (auth) return auth;
if (url.endsWith(detail)) return json(order);
if (url.endsWith(`${detail}/cancel`) && options?.method === "POST") return json({
message: "Reverse active payments before cancelling the order", code: "B2B_PAYMENT_CANCEL_BLOCKED",
}, 409);
throw new Error(`Unexpected request ${url}`);
});
vi.stubGlobal("fetch", fetch);
showOrders(<PartnerOrdersPage id={orderId} />);
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
fireEvent.change(await screen.findByRole("textbox", { name: /Cancellation reason/ }), {
target: { value: "Partner changed the order" },
});
await user.click(screen.getByRole("button", { name: "Cancel partner order" }));
await screen.findByText("Reverse active payments before cancelling the order");
expect(screen.getByRole("button", { name: "Cancel partner order" })).toBeTruthy();
expect(screen.queryByRole("button", { name: "Retry cancellation" })).toBeNull();
});

View File

@ -1,32 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { partnerPaymentInput, partnerPaymentHistory, reversePartnerPaymentInput } from "../src/lib/partner-payments.ts";
const idempotencyKey = "d66c798a-f764-4b88-8d13-ace328ff1010";
const receipt = { idempotencyKey, reference: " utr-123 ", method: "BANK_TRANSFER", amount: "9007199254740993.25", receivedOn: "2026-11-20" };
test("partner receipt input normalizes references and preserves the backend's full decimal range", () => {
assert.deepEqual(partnerPaymentInput.parse(receipt), { ...receipt, reference: "UTR-123" });
for (const amount of ["0.00", "1", "1.001", "01.00", "-1.00", "10000000000000000.00"]) {
assert.equal(partnerPaymentInput.safeParse({ ...receipt, amount }).success, false);
}
assert.equal(partnerPaymentInput.safeParse({ ...receipt, receivedOn: "2026-02-30" }).success, false);
assert.equal(partnerPaymentInput.safeParse({ ...receipt, orderId: idempotencyKey }).success, false);
});
test("partner payment reversals require a plain-text reason and a replay key", () => {
assert.deepEqual(reversePartnerPaymentInput.parse({ reason: " Wrong receipt ", idempotencyKey }), { reason: "Wrong receipt", idempotencyKey });
for (const reason of ["", "ab", "<script>", "bad\nreason"]) {
assert.equal(reversePartnerPaymentInput.safeParse({ reason, idempotencyKey }).success, false);
}
});
test("partner payment history retains exact authoritative balances and strips command metadata", () => {
const result = partnerPaymentHistory.parse({
orderId: idempotencyKey, currency: "INR", merchandiseTotal: "9999999999999999.99",
paidTotal: "9007199254740993.25", outstandingTotal: "992800745259006.74", payments: [], requestHash: "private",
});
assert.equal(result.paidTotal, receipt.amount);
assert.equal(result.outstandingTotal, "992800745259006.74");
assert.equal("requestHash" in result, false);
});

View File

@ -1,160 +0,0 @@
import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "@mui/material/styles";
import { afterEach, expect, test, vi } from "vitest";
import axe from "axe-core";
import { PlatformProvider, usePlatform } from "../src/lib/platform";
import PartnerPaymentsPage from "../src/pages/PartnerPaymentsPage";
import theme from "../src/theme";
const orderId = "d66c798a-f764-4b88-8d13-ace328ff1010";
const userId = "d66c798a-f764-4b88-8d13-ace328ff1011";
const paymentId = "d66c798a-f764-4b88-8d13-ace328ff1012";
const timestamp = "2026-11-20T00:00:00.000Z";
const path = `/b2b/partner-orders/${orderId}/payments`;
const payment = {
id: paymentId, orderId, recordedById: userId, reference: "UTR-123", method: "BANK_TRANSFER",
currency: "INR", amount: "100.25", receivedOn: timestamp, createdAt: timestamp, reversal: null,
};
const history = {
orderId, currency: "INR", merchandiseTotal: "1000.00", paidTotal: "0.00", outstandingTotal: "1000.00", payments: [],
};
const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status });
function Login() {
const { signIn } = usePlatform();
return <button onClick={() => signIn("staff@example.com", "test password")}>Test login</button>;
}
function show(permissions: string[], handle: (url: string, options?: RequestInit) => Promise<Response>, id = orderId) {
const fetch = vi.fn(async (url: string, options?: RequestInit) => {
if (url.endsWith("/auth/login")) return json({ accessToken: "opaque", tokenType: "Bearer", expiresAt: new Date(Date.now() + 3600000).toISOString() });
if (url.endsWith("/auth/me")) return json({ userId, organizationId: orderId, sessionId: userId, permissions });
return handle(url, options);
});
vi.stubGlobal("fetch", fetch);
localStorage.setItem("mani.organization", orderId);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(<ThemeProvider theme={theme}><QueryClientProvider client={client}>
<PlatformProvider><Login /><PartnerPaymentsPage orderId={id} /></PlatformProvider>
</QueryClientProvider></ThemeProvider>);
return fetch;
}
afterEach(() => vi.unstubAllGlobals());
test("recording a lost-response receipt replays the exact normalized body and refreshes authoritative balances", async () => {
const attempts: unknown[] = [];
let saved = false;
const fetch = show(["b2b.payment.read", "b2b.payment.manage"], async (url, options) => {
if (url.endsWith(path) && options?.method === "POST") {
attempts.push(JSON.parse(String(options.body)));
if (attempts.length === 1) throw new Error("Response lost");
saved = true;
return json(payment);
}
if (url.includes(`${path}?`)) return json(saved ? { ...history, paidTotal: "100.25", outstandingTotal: "899.75", payments: [payment] } : history);
throw new Error(`Unexpected request ${url}`);
});
expect(fetch).not.toHaveBeenCalled();
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
fireEvent.change(await screen.findByRole("textbox", { name: "Payment reference" }), { target: { value: " utr-123 " } });
fireEvent.change(screen.getByRole("textbox", { name: "Receipt amount (INR)" }), { target: { value: "100.25" } });
fireEvent.change(screen.getByRole("textbox", { name: "Received on (YYYY-MM-DD)" }), { target: { value: "2026-11-20" } });
await user.click(screen.getByRole("button", { name: "Record partner receipt" }));
await user.click(await screen.findByRole("button", { name: "Retry partner receipt" }));
await screen.findByText("INR 899.75");
expect(attempts[0]).toEqual({ reference: "UTR-123", method: "BANK_TRANSFER", amount: "100.25", receivedOn: "2026-11-20", idempotencyKey: expect.any(String) });
expect(attempts).toEqual([attempts[0], attempts[0]]);
});
test("reversal requires confirmation and replays its reason and key after a lost response", async () => {
const attempts: unknown[] = [];
const reason = "Receipt recorded against wrong bank entry";
let current: object = payment;
const user = userEvent.setup();
show(["b2b.payment.read", "b2b.payment.manage"], async (url, options) => {
if (url.endsWith(`${path}/${paymentId}/reverse`)) {
attempts.push(JSON.parse(String(options?.body)));
if (attempts.length === 1) throw new Error("Response lost");
current = { ...payment, reversal: { reason, reversedById: userId, createdAt: timestamp } };
return json(current);
}
if (url.endsWith(`${path}/${paymentId}`)) return json(current);
if (url.includes(`${path}?`)) return json({ ...history, payments: [current] });
throw new Error(`Unexpected request ${url}`);
});
await user.click(screen.getByRole("button", { name: "Test login" }));
await user.click(await screen.findByRole("button", { name: "View receipt UTR-123" }));
fireEvent.change(await screen.findByRole("textbox", { name: "Reversal reason" }), { target: { value: reason } });
await user.click(screen.getByRole("button", { name: "Reverse partner receipt" }));
expect(attempts).toEqual([]);
await screen.findByText("Confirm the receipt reversal before continuing.");
await user.click(screen.getByRole("checkbox", { name: "Confirm reversal of UTR-123" }));
await user.click(screen.getByRole("button", { name: "Reverse partner receipt" }));
await user.click(await screen.findByRole("button", { name: "Retry receipt reversal" }));
await screen.findByText(reason, { exact: true });
expect(attempts).toEqual([{ reason, idempotencyKey: expect.any(String) }, { reason, idempotencyKey: expect.any(String) }]);
expect(attempts[1]).toEqual(attempts[0]);
expect(screen.queryByRole("button", { name: "Reverse partner receipt" })).toBeNull();
});
test("payment readers can inspect history without order permissions or mutation controls", async () => {
show(["b2b.payment.read"], async () => json({ ...history, paidTotal: "9007199254740993.25", payments: [payment] }));
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await screen.findByText("INR 9007199254740993.25");
expect(screen.queryByRole("button", { name: "Record partner receipt" })).toBeNull();
});
test("missing payment permission and invalid order IDs never issue a payment request", async () => {
const handle = vi.fn(async () => json(history));
show(["b2b.order.read"], handle, "invalid");
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await screen.findByText("Your account does not have permission to view this page.");
expect(handle).not.toHaveBeenCalled();
});
test("invalid order IDs are rejected before querying even for payment readers", async () => {
const handle = vi.fn(async () => json(history));
show(["b2b.payment.read"], handle, "invalid");
await userEvent.setup().click(screen.getByRole("button", { name: "Test login" }));
await screen.findByText("Invalid partner order ID.");
expect(handle).not.toHaveBeenCalled();
});
test("a confirmed overpayment conflict displays the backend reason and permits correction", async () => {
let attempts = 0;
show(["b2b.payment.read", "b2b.payment.manage"], async (_url, options) => {
if (options?.method === "POST") {
attempts++;
return json({ message: "Payment exceeds the partner order balance", code: "B2B_PAYMENT_AMOUNT_LIMIT" }, 409);
}
return json(history);
});
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
fireEvent.change(await screen.findByRole("textbox", { name: "Payment reference" }), { target: { value: "UTR-123" } });
fireEvent.change(screen.getByRole("textbox", { name: "Receipt amount (INR)" }), { target: { value: "1001.00" } });
fireEvent.change(screen.getByRole("textbox", { name: "Received on (YYYY-MM-DD)" }), { target: { value: "2026-11-20" } });
await user.click(screen.getByRole("button", { name: "Record partner receipt" }));
await screen.findByText("Payment exceeds the partner order balance");
expect(attempts).toBe(1);
expect(screen.queryByRole("button", { name: "Retry partner receipt" })).toBeNull();
expect(screen.getByRole("textbox", { name: "Receipt amount (INR)" })).toHaveProperty("value", "1001.00");
});
test("fully paid orders keep their receipt history and hide new recording controls", async () => {
show(["b2b.payment.read", "b2b.payment.manage"], async () => json({ ...history, paidTotal: "1000.00", outstandingTotal: "0.00", payments: [payment] }));
await userEvent.setup().click(screen.getByRole("button", { name: "Test login" }));
await screen.findByRole("button", { name: "View receipt UTR-123" });
expect(screen.queryByRole("button", { name: "Record partner receipt" })).toBeNull();
});
test("the populated receipt form has no serious or critical axe violations", async () => {
show(["b2b.payment.read", "b2b.payment.manage"], async () => json(history));
await userEvent.setup().click(screen.getByRole("button", { name: "Test login" }));
await screen.findByRole("textbox", { name: "Payment reference" });
const result = await axe.run(document.body, { rules: { "color-contrast": { enabled: false } } });
expect(result.violations.filter(({ impact }) => impact === "serious" || impact === "critical")).toEqual([]);
});

View File

@ -1,24 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { productImageUrl, productSchema } from "../src/lib/api.ts";
import { adminProduct, prepareProductImage } from "../src/lib/commerce.ts";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
const product = { id, name: "Rose", slug: "rose", description: "", variants: [], groups: [] };
test("product images default to none and keep their storefront order", () => {
assert.deepEqual(productSchema.parse(product).images, []);
assert.deepEqual(productSchema.parse({ ...product, images: [{ id }] }).images, [{ id }]);
assert.throws(() => productSchema.parse({ ...product, images: [{ id: "../x" }] }));
assert.equal(productImageUrl(id, id, id), `/api/v1/storefront/${id}/products/${id}/images/${id}`);
const admin = adminProduct.parse({ ...product, status: "DRAFT", images: [{ id, mimeType: "image/webp", size: 10 }] });
assert.equal(admin.images[0].mimeType, "image/webp");
});
test("photo uploads accept only JPEG, PNG or WebP up to 2 MiB", () => {
const body = prepareProductImage(new File(["x"], "a.jpg", { type: "image/jpeg" }));
assert.ok(body.get("file") instanceof File);
assert.throws(() => prepareProductImage(new File(["<svg/>"], "a.svg", { type: "image/svg+xml" })), /JPEG, PNG or WebP/);
assert.throws(() => prepareProductImage(new File([new Uint8Array(2 * 1024 * 1024 + 1)], "a.png", { type: "image/png" })), /2 MiB/);
assert.throws(() => prepareProductImage(null), /Choose/);
});

View File

@ -1,6 +1,6 @@
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { issueQuoteInput, quote, quoteExpiry, quoteResponseInput } from "../src/lib/quotes.ts"; import { issueQuoteInput, quoteExpiry, quoteResponseInput } from "../src/lib/quotes.ts";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
@ -20,10 +20,3 @@ test("quotation commands enforce unique variant lines and a trimmed response not
assert.equal(quoteResponseInput.parse({ kind: "ACCEPTED", note: " Confirmed by email ", idempotencyKey: id }).note, "Confirmed by email"); assert.equal(quoteResponseInput.parse({ kind: "ACCEPTED", note: " Confirmed by email ", idempotencyKey: id }).note, "Confirmed by email");
assert.equal(quoteResponseInput.safeParse({ kind: "DECLINED", note: " ", idempotencyKey: id }).success, false); assert.equal(quoteResponseInput.safeParse({ kind: "DECLINED", note: " ", idempotencyKey: id }).success, false);
}); });
test("saved quotation lines retain price terms and strip database metadata", () => {
const line = { id, variantId: id, sku: "TIN-01", name: "Tin candle", quantity: 12, minQuantity: 6,
unitPrice: "10.50", lineTotal: "126.00" };
assert.deepEqual(quote.shape.lines.element.parse({ ...line, organizationId: id, quoteId: id }), line);
assert.equal(issueQuoteInput.shape.lines.element.safeParse({ variantId: id, quantity: 12, quoteId: id }).success, false);
});

View File

@ -1,5 +1,5 @@
import { type ReactNode } from "react"; import { type ReactNode } from "react";
import { fireEvent, render, screen } from "@testing-library/react"; import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event"; import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "@mui/material/styles"; import { ThemeProvider } from "@mui/material/styles";
@ -92,9 +92,11 @@ test("an uncertain sample request retries with its original account, variant, qu
const user = userEvent.setup(); const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" })); await user.click(screen.getByRole("button", { name: "Test login" }));
fireEvent.change(await screen.findByRole("textbox", { name: /Variant ID/ }), { target: { value: variantId } }); await user.type(await screen.findByRole("textbox", { name: /Variant ID/ }), variantId);
fireEvent.change(screen.getByRole("spinbutton", { name: /Sample quantity/ }), { target: { value: "4" } }); const quantity = screen.getByRole("spinbutton", { name: /Sample quantity/ });
fireEvent.change(screen.getByRole("textbox", { name: /Sample purpose/ }), { target: { value: sample.purpose } }); await user.clear(quantity);
await user.type(quantity, "4");
await user.type(screen.getByRole("textbox", { name: /Sample purpose/ }), sample.purpose);
await user.click(screen.getByRole("button", { name: "Request samples" })); await user.click(screen.getByRole("button", { name: "Request samples" }));
await user.click(await screen.findByRole("button", { name: "Retry sample request" })); await user.click(await screen.findByRole("button", { name: "Retry sample request" }));
await screen.findByText(sample.purpose); await screen.findByText(sample.purpose);
@ -155,11 +157,10 @@ test("an independent reviewer can approve a request and retry a manual dispatch"
const user = userEvent.setup(); const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" })); await user.click(screen.getByRole("button", { name: "Test login" }));
await user.selectOptions(await screen.findByRole("combobox", { name: /Review decision/ }), "APPROVED"); await user.selectOptions(await screen.findByRole("combobox", { name: /Review decision/ }), "APPROVED");
fireEvent.change(screen.getByRole("textbox", { name: /Review note/ }), { target: { value: approved.note } }); await user.type(screen.getByRole("textbox", { name: /Review note/ }), approved.note);
await user.click(screen.getByRole("button", { name: "Record sample decision" })); await user.click(screen.getByRole("button", { name: "Record sample decision" }));
expect(decision).toEqual({ decision: "APPROVED", note: approved.note, idempotencyKey: expect.any(String) }); await user.type(await screen.findByRole("textbox", { name: /Dispatch reference/ }), dispatched.dispatchReference);
fireEvent.change(await screen.findByRole("textbox", { name: /Dispatch reference/ }), { target: { value: dispatched.dispatchReference } }); await user.type(screen.getByRole("textbox", { name: /Dispatch note/ }), dispatched.note);
fireEvent.change(screen.getByRole("textbox", { name: /Dispatch note/ }), { target: { value: dispatched.note } });
await user.click(screen.getByRole("button", { name: "Record dispatch" })); await user.click(screen.getByRole("button", { name: "Record dispatch" }));
await user.click(await screen.findByRole("button", { name: "Retry dispatch" })); await user.click(await screen.findByRole("button", { name: "Retry dispatch" }));
await screen.findByRole("cell", { name: dispatched.dispatchReference }); await screen.findByRole("cell", { name: dispatched.dispatchReference });

View File

@ -332,19 +332,3 @@ test("organization change cancels private scope and removes cached data", async
await waitFor(() => expect(h.result.current.scope).toBe("")); await waitFor(() => expect(h.result.current.scope).toBe(""));
expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]); expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]);
}); });
test("sign-up registers in the configured organization and adopts the new session", async () => {
const bodies: unknown[] = [];
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
if (url.endsWith("/auth/register")) {
bodies.push(JSON.parse(String(options?.body)));
return json(session, 201);
}
if (url.endsWith("/auth/me")) return json({ ...me, permissions: [] });
throw new Error(`Unexpected request ${url}`);
}));
const h = harness();
await act(() => h.result.current.signUp("Asha Buyer", "buyer@example.com", "a long enough password"));
expect(bodies).toEqual([{ organizationId: id, name: "Asha Buyer", email: "buyer@example.com", password: "a long enough password" }]);
expect(h.result.current.principal).toMatchObject({ userId: id, permissions: [] });
});

View File

@ -1,5 +1,5 @@
import { type ReactNode } from "react"; import { type ReactNode } from "react";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { act, render, screen, waitFor, within } from "@testing-library/react";
import { Table } from "../src/components/WorkspaceTools"; import { Table } from "../src/components/WorkspaceTools";
import { ConfirmAction } from "../src/components/ConfirmAction"; import { ConfirmAction } from "../src/components/ConfirmAction";
import userEvent from "@testing-library/user-event"; import userEvent from "@testing-library/user-event";
@ -722,17 +722,19 @@ test("a production batch starts, safely retries usage and completes with reconci
await user.click(await screen.findByRole("button", { name: "Start batch" })); await user.click(await screen.findByRole("button", { name: "Start batch" }));
await user.click(screen.getByRole("button", { name: "Confirm" })); await user.click(screen.getByRole("button", { name: "Confirm" }));
await user.selectOptions(await screen.findByRole("combobox", { name: /Usage type/ }), "WASTED"); await user.selectOptions(await screen.findByRole("combobox", { name: /Usage type/ }), "WASTED");
fireEvent.change(screen.getByRole("textbox", { name: /Actual quantity/ }), { target: { value: "0.125" } }); await user.type(screen.getByRole("textbox", { name: /Actual quantity/ }), "0.125");
fireEvent.change(screen.getByRole("textbox", { name: /Usage reason/ }), { target: { value: "Spill" } }); await user.type(screen.getByRole("textbox", { name: /Usage reason/ }), "Spill");
await user.click(screen.getByRole("button", { name: "Record material usage" })); await user.click(screen.getByRole("button", { name: "Record material usage" }));
await user.click(await screen.findByRole("button", { name: "Retry material usage" })); await user.click(await screen.findByRole("button", { name: "Retry material usage" }));
await screen.findByRole("cell", { name: "199.875" }); await screen.findByRole("cell", { name: "199.875" });
expect(attempts).toHaveLength(2); expect(attempts).toHaveLength(2);
expect(attempts[0]).toEqual({ bomLineId: id, kind: "WASTED", quantity: "0.125", reason: "Spill", idempotencyKey: expect.any(String) }); expect(attempts[0]).toEqual({ bomLineId: id, kind: "WASTED", quantity: "0.125", reason: "Spill", idempotencyKey: expect.any(String) });
expect(attempts[1]).toEqual(attempts[0]); expect(attempts[1]).toEqual(attempts[0]);
fireEvent.change(screen.getByRole("spinbutton", { name: /Good pieces/ }), { target: { value: "18" } }); await user.type(screen.getByRole("spinbutton", { name: /Good pieces/ }), "18");
fireEvent.change(screen.getByRole("spinbutton", { name: /Rejected pieces/ }), { target: { value: "2" } }); const rejected = screen.getByRole("spinbutton", { name: /Rejected pieces/ });
fireEvent.change(screen.getByRole("textbox", { name: /Rejection reason/ }), { target: { value: "Surface defects" } }); await user.clear(rejected);
await user.type(rejected, "2");
await user.type(screen.getByRole("textbox", { name: /Rejection reason/ }), "Surface defects");
await user.click(screen.getByRole("button", { name: "Complete batch" })); await user.click(screen.getByRole("button", { name: "Complete batch" }));
await screen.findByText(/18 good · 2 rejected · Surface defects/); await screen.findByText(/18 good · 2 rejected · Surface defects/);
expect(screen.queryByRole("button", { name: "Record material usage" })).toBeNull(); expect(screen.queryByRole("button", { name: "Record material usage" })).toBeNull();

View File

@ -7,7 +7,5 @@ export default defineConfig({
include: ["test/*.ui.test.tsx"], include: ["test/*.ui.test.tsx"],
setupFiles: ["test/setup.ts"], setupFiles: ["test/setup.ts"],
restoreMocks: true, restoreMocks: true,
// Multi-step MUI workflows take ~1.5s locally but exceed 5s on the single-worker Drone runner.
testTimeout: 20000,
}, },
}); });