Compare commits
No commits in common. "main" and "feat/backend-phase1" have entirely different histories.
main
...
feat/backe
101
.drone.yml
101
.drone.yml
|
|
@ -1,61 +1,40 @@
|
|||
kind: pipeline
|
||||
type: docker
|
||||
name: Validate and deploy frontend
|
||||
|
||||
steps:
|
||||
- name: Validate Nginx configuration
|
||||
image: nginx:alpine
|
||||
commands:
|
||||
- printf 'events {}\nhttp { server { listen 8080; include /drone/src/deploy/nginx-locations.conf; } }\n' > /tmp/manicandles-nginx.conf
|
||||
- nginx -t -c /tmp/manicandles-nginx.conf
|
||||
|
||||
- name: Quality gates
|
||||
image: node:24-alpine
|
||||
environment:
|
||||
# Keep jsdom suites from competing for CPU on the Drone runner.
|
||||
VITEST_MAX_WORKERS: "1"
|
||||
commands:
|
||||
- npm ci
|
||||
- npm audit --audit-level=high
|
||||
- npm run check
|
||||
- apk add --no-cache util-linux
|
||||
- sh test/deployment.test.sh
|
||||
- printf '%s\n' '${DRONE_BUILD_NUMBER}-${DRONE_COMMIT_SHA}' > dist/release.txt
|
||||
|
||||
- name: Upload frontend release
|
||||
image: appleboy/drone-scp
|
||||
settings:
|
||||
host: server1.midastix.com
|
||||
username: mihir
|
||||
key:
|
||||
from_secret: manicandles_deploy_key
|
||||
port: 22
|
||||
source: dist,scripts/deploy-frontend.sh
|
||||
target: /var/www/manicandles/incoming/${DRONE_BUILD_NUMBER}-${DRONE_COMMIT_SHA}
|
||||
|
||||
when:
|
||||
branch:
|
||||
- main
|
||||
event:
|
||||
- push
|
||||
|
||||
|
||||
- name: Activate and verify frontend
|
||||
image: appleboy/drone-ssh
|
||||
settings:
|
||||
host: server1.midastix.com
|
||||
username: mihir
|
||||
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
|
||||
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: Build Image
|
||||
|
||||
steps:
|
||||
- name: Build Docker Image
|
||||
image: plugins/docker
|
||||
settings:
|
||||
username:
|
||||
from_secret: docker_username
|
||||
password:
|
||||
from_secret: docker_password
|
||||
repo: git.midastix.com/ci-docker-repo-user/manicandles
|
||||
registry: git.midastix.com
|
||||
|
||||
when:
|
||||
branch:
|
||||
- main
|
||||
event:
|
||||
- push
|
||||
|
||||
- name: Deploy image
|
||||
image: appleboy/drone-ssh
|
||||
settings:
|
||||
host: server1.midastix.com
|
||||
username: root
|
||||
key:
|
||||
from_secret: server_ssh_pkey
|
||||
port: 22
|
||||
command_timeout: 5m
|
||||
script:
|
||||
- echo "Deploying ManiCandles"
|
||||
- sudo /opt/deployable/manicandles/docker/deploy.sh
|
||||
- echo "Completed Deployment"
|
||||
|
||||
when:
|
||||
branch:
|
||||
- main
|
||||
event:
|
||||
- push
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
*.sh text eol=lf
|
||||
|
|
@ -1 +0,0 @@
|
|||
Read CONSTRAINTS.md before writing code. Do not weaken it to make a change pass.
|
||||
10
CHANGELOG.md
10
CHANGELOG.md
|
|
@ -1,10 +0,0 @@
|
|||
# Changelog
|
||||
|
||||
## Phase 2 — 13 October 2026
|
||||
|
||||
- Add private addresses, versioned carts, reviewed/idempotent checkout, own and staff order history/details/cancellation.
|
||||
- Add permission-gated user/role/audit, product/group/variant, finished-stock/warehouse/ledger/reservation, coupon and pricing tools.
|
||||
- Add account recovery/reset with fragment-token removal.
|
||||
- Fix decimal output compatibility, immediate private session cleanup, permission downgrade privacy and stale request/intent races.
|
||||
- Add lazy routes, build-size gate, lint/component/workflow/accessibility tests, dependency audit in CI and Nginx security headers.
|
||||
- Production acceptance still requires provisioned UAT accounts, approved pricing/SMTP and verified deployment/rollback.
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
# Production quality constraints
|
||||
|
||||
Reviewed 12 October 2026. User accepted strict types, workflow tests, security, keyboard/responsive and deployment/rollback checks; no UAT account is provisioned yet.
|
||||
|
||||
| Gate | Required result | Evidence |
|
||||
| ------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------- |
|
||||
| Types | Zero errors, strict mode retained | npm run typecheck |
|
||||
| Lint | Zero errors on source/tests | npm run lint |
|
||||
| Tests | All contract/workflow/component tests pass; no skipped tests | npm test |
|
||||
| Dependency security | Zero high/critical findings | npm audit --audit-level=high |
|
||||
| Build | Successful; no oversized chunk warnings; each JS chunk below 500 kB | npm run build |
|
||||
| Accessibility | Keyboard flows, labels/errors, contrast; zero serious/critical axe findings on tested routes | component accessibility tests and browser checklist |
|
||||
| Responsive | No horizontal overflow at 320, 768, 1024, 1440 px | Browser UAT evidence |
|
||||
| Deployment | Nginx validates; container/deep links/API verified; HTTPS ingress | container smoke checks + deployed UAT |
|
||||
| Release | No unresolved critical/high defects; permissions/privacy/conflicts exercised; rollback verified | docs/RELEASE-CHECKLIST.md |
|
||||
|
||||
No new type/lint suppressions, unimplemented stubs, disabled tests or secrets. Do not weaken these gates to make changes pass. Pending environment checks stay pending and block a production-ready claim. Backend business rules, tax/shipping policy approval, SMTP, account provisioning and deployment access remain explicit external gates.
|
||||
|
|
@ -8,7 +8,7 @@ RUN npm ci
|
|||
|
||||
COPY . .
|
||||
|
||||
RUN npm run check
|
||||
RUN npm run typecheck && npm test && npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
|
||||
|
|
@ -16,7 +16,6 @@ RUN apk add --no-cache ca-certificates
|
|||
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
RUN nginx -t
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
|
|
|
|||
12
README.md
12
README.md
|
|
@ -1,6 +1,6 @@
|
|||
# Mani Candles frontend
|
||||
|
||||
The existing ManiCandles site upgraded against the deployed Nest API. Its purple/gold design, branding, and marketing pages are retained. Phase 2 adds customer commerce, permission-gated administration, account recovery and enforced release checks.
|
||||
The existing ManiCandles site upgraded against the deployed Nest API. Its purple/gold design, branding, and marketing pages are retained. Phase 1 connects catalog discovery, variants, staff sessions, organization setup and health checks.
|
||||
|
||||
## Development
|
||||
|
||||
|
|
@ -25,14 +25,10 @@ docker build -t 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.
|
||||
Cart/checkout, registration and admin/operations tools are subsequent phases. There is no contact-message endpoint; simulated success was replaced with an availability notice. Newsletter signup awaits consent/messaging flows.
|
||||
|
||||
See [delivery phases](docs/PHASES.md) and [UAT evidence](docs/UAT-RESULTS.md).
|
||||
|
||||
Phase 2 commands: `npm run check` runs lint, strict types, contract/component/workflow tests and the measured production build. Dependency security is checked with `npm audit --audit-level=high` in CI. See [Phase 2 evidence](docs/UAT-PHASE2.md) and [release checklist](docs/RELEASE-CHECKLIST.md).
|
||||
|
||||
Set the backend RECOVERY_URL to your HTTPS frontend /reset-password route. Pending checkout and stock commands survive navigation within an active session; reload discards local credentials and intents. If interrupted, check orders/ledger before starting a new command.
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -2,14 +2,14 @@
|
|||
|
||||
Canonical implementation: this checkout from ssh://git@git.midastix.com:2212/internal/ManiCandles.git. The standalone frontend created earlier is superseded for ongoing development.
|
||||
|
||||
| Phase | Scope | Acceptance gate |
|
||||
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
|
||||
| 1 — Existing-site foundation | Preserve branding, connect home/catalog/search/pagination/variants, staff login/me/logout/expiry, organization setup, health checks, API proxy and SPA routing | Real published records and approved account; loading/empty/failure states; keyboard and responsive verification |
|
||||
| 2 — Commerce and administration | Users/roles/audit, products/groups/variants/stock, addresses/cart/coupons/checkout/orders, recovery | Permission failures, conflicts, exact totals and expiry; no simulated live payment |
|
||||
| 3 — Procurement and production | Suppliers/materials, POs/receipts/QC, invoices/payments/documents, BOMs/batches/usage/packaging/costing, warehouse stock | Supplier-to-finished-goods journey; independent review; partials/idempotency; stock invariants |
|
||||
| 4 — B2B | Verification, price lists/MOQ, quotes/credit/samples/artwork, partner orders/payments, custom requests/reports | Independent approvals, expiry, reversals and currency/account boundaries |
|
||||
| 5 — Growth and reporting | Wishlist/reviews, campaigns/discounts, recovery/consent, blog/segments/forum, analytics/forecast/accounting | Publication/moderation, consent, private data and report verification |
|
||||
| 6 — Complete UAT and release | Dedicated deployment, disposable fixtures, role matrix, end-to-end scripts, accessibility/security review, defect retests and release/rollback runbook | Critical journeys pass; no critical/high defects; owner acceptance |
|
||||
| Phase | Scope | Acceptance gate |
|
||||
| --- | --- | --- |
|
||||
| 1 — Existing-site foundation | Preserve branding, connect home/catalog/search/pagination/variants, staff login/me/logout/expiry, organization setup, health checks, API proxy and SPA routing | Real published records and approved account; loading/empty/failure states; keyboard and responsive verification |
|
||||
| 2 — Commerce and administration | Users/roles/audit, products/groups/variants/stock, addresses/cart/coupons/checkout/orders, recovery | Permission failures, conflicts, exact totals and expiry; no simulated live payment |
|
||||
| 3 — Procurement and production | Suppliers/materials, POs/receipts/QC, invoices/payments/documents, BOMs/batches/usage/packaging/costing, warehouse stock | Supplier-to-finished-goods journey; independent review; partials/idempotency; stock invariants |
|
||||
| 4 — B2B | Verification, price lists/MOQ, quotes/credit/samples/artwork, partner orders/payments, custom requests/reports | Independent approvals, expiry, reversals and currency/account boundaries |
|
||||
| 5 — Growth and reporting | Wishlist/reviews, campaigns/discounts, recovery/consent, blog/segments/forum, analytics/forecast/accounting | Publication/moderation, consent, private data and report verification |
|
||||
| 6 — Complete UAT and release | Dedicated deployment, disposable fixtures, role matrix, end-to-end scripts, accessibility/security review, defect retests and release/rollback runbook | Critical journeys pass; no critical/high defects; owner acceptance |
|
||||
|
||||
## Phase 1 setup
|
||||
|
||||
|
|
@ -22,46 +22,3 @@ Enter the UUID at `/connection`, then credentials at `/workspace`. Published pro
|
|||
Reference: deployed `/api/docs-json` and backend source API guides. Storefront lists are arrays; detail includes decimal price strings, currency, attributes and nested groups. Zod validates returned shapes. Errors preserve code/requestId. React escapes API content; request timeout is 15 seconds. Session tokens/passwords are not persisted. UUID is configuration, not an authorization boundary; backend permissions remain authoritative.
|
||||
|
||||
Use existing MUI theme and React Query. Query keys include organization. Search is bounded to 100 characters; catalog pages contain 12 records and respect the API offset cap. No product-image mapping is invented. Nginx forwards `/api/` to the known HTTPS upstream, verifies TLS and handles SPA deep links. No public owner/account creation is exposed.
|
||||
|
||||
## Phase 2 implementation status — 12 October 2026
|
||||
|
||||
Customer and administration screens are implemented, with recovery, pricing, stock lifecycle and quality gates. See UAT-PHASE2.md and RELEASE-CHECKLIST.md. Authenticated UAT, container/ingress verification and production sign-off remain pending.
|
||||
|
||||
## Phase 3 implementation status
|
||||
|
||||
- Supplier and material directories support listing, creation and editing. Supplier material terms include SKU, lead time, minimum order quantity and unit price.
|
||||
- Staff can create a purchase order draft from supplier terms, review the backend price snapshots, then issue or cancel the draft.
|
||||
- Issued orders support partial goods receipts and final quality inspections, with exact accepted and rejected quantities and rejection reasons.
|
||||
- Inspected receipts support idempotent posting to a warehouse. Staff can review material balances and movement ledgers.
|
||||
- Issued orders support supplier invoices, payment records, reversals and voids. The backend enforces accepted quantities, outstanding balances and correction rules.
|
||||
- Private supplier PDFs support version uploads, independent review decisions, and authenticated downloads.
|
||||
- Production and packaging BOMs support separate revision histories, draft creation, material snapshots and confirmed activation.
|
||||
- Production batches support draft planning, start, completion, cancellation, and exact planned material quantities. Staff can log consumption and waste and reconcile the results against the plan.
|
||||
- Completed batches support packaging runs, production and packaging material debits, and receipt of good finished pieces into warehouse stock.
|
||||
- Costing supports immutable material rate revisions, current-rate BOM estimates, and completed-batch cost snapshots with exact totals and saved rate revisions.
|
||||
- Material warehouse transfers post matched debits and credits. Authorized adjusters can record signed corrections with reasons, including positive corrections for materials with no balance at the selected warehouse.
|
||||
- Live acceptance requires an organization and procurement test users. Exercise read-only and manage roles, inactive suppliers and materials, mixed currencies, below-minimum quantities, price snapshots and purchase order state conflicts.
|
||||
- Supplier document UAT requires an uploader, an independent reviewer, and a read-only account. Through the deployed ingress, upload a valid PDF near the 2 MiB limit, verify that the uploader cannot decide on it, and check that a reader can download it only after approval.
|
||||
- BOM UAT should activate a second revision and confirm the previous revision becomes superseded. Repeat for the other BOM type and verify its active revision is independent. Check that inactive materials and stale drafts are rejected.
|
||||
- Costing UAT should revise a material rate and verify that future BOM estimates use the new revision while an existing batch snapshot retains its original amounts and rates. Test missing rates, missing usage, and fully rejected output.
|
||||
- Warehouse movement UAT should verify both ledgers and unchanged combined stock after a transfer, rejection of insufficient stock, and one ledger entry for a retried adjustment.
|
||||
|
||||
## Phase 4 implementation status
|
||||
|
||||
- Staff can create, edit, submit and review B2B business accounts. Verification uses submitted profile snapshots, separate permissions for submission and review, and an immutable event history.
|
||||
- B2B UAT should use distinct submitting and reviewing accounts. Verify self-review is blocked, rejection allows correction and resubmission, and a verified profile is read-only.
|
||||
- B2B price lists support draft variant prices and minimum quantities, activation, archiving, and active-list merchandise previews.
|
||||
- Price-list UAT should verify that unverified accounts and competing active lists cannot activate a draft, archived terms stay read-only, and price checks reject quantities below the variant minimum.
|
||||
- Staff can issue B2B quotations from account-specific price lists, review saved profile and pricing snapshots, and record acceptance, decline, or withdrawal before expiry.
|
||||
- Quotation UAT should verify minimum quantities, expiry, immutable snapshots after archiving a price list, and exact retries for issuance and responses.
|
||||
- B2B credit policies support immutable proposals, independent approval or rejection, and suspension with decision history.
|
||||
- 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.
|
||||
- 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 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.
|
||||
|
|
|
|||
|
|
@ -1,41 +0,0 @@
|
|||
# Phase 2 release checklist
|
||||
|
||||
Production release is blocked until the environment checks below pass. Local implementation verification does not replace authenticated UAT or deployment acceptance.
|
||||
|
||||
## Code gates
|
||||
|
||||
- [x] Purpose-built customer and administration routes, with session/permission guards.
|
||||
- [x] Exact decimal display, strict write inputs, validated response shapes.
|
||||
- [x] Private caches and requests cleared on logout, expiry, organization change and permission downgrade.
|
||||
- [x] Stale responses cannot invalidate a newer session or remove its pending command.
|
||||
- [x] Cart writes serialize locally; stale versions require review.
|
||||
- [x] Checkout confirmation uses the reviewed version; unknown results retain the same payload/key across navigation.
|
||||
- [x] Adjustment/reservation intents stay in session memory for exact retries; session termination discards them.
|
||||
- [x] Order charges use authoritative server totals; null means unfinalized, not zero; payment collection stays unavailable.
|
||||
- [x] Recovery tokens captured once in memory and removed from browser history; never persisted or logged.
|
||||
- [x] Destructive lifecycle actions have confirmation; system/owner/self restrictions remain enforced by the backend.
|
||||
- [x] Strict TypeScript, lint without warnings, all tests passing, build below the 500 kB per-chunk budget.
|
||||
- [x] Dependency audit has no reported vulnerabilities.
|
||||
- [x] CI runs dependency audit and npm run check on pushes/PRs; Docker validates Nginx syntax during build.
|
||||
- [x] No new type/lint suppressions, skipped tests, debug logging or source credentials.
|
||||
|
||||
## Environment and acceptance gates — pending
|
||||
|
||||
- [ ] Provision the installation owner on the intended UAT backend host/database; record organizationId. Never run local bootstrap against an unknown database.
|
||||
- [ ] Provision least-privilege UAT staff and customer accounts, including denied/suspended accounts and independent reviewer roles.
|
||||
- [ ] Exercise actual catalog/group/variant creation and publication, warehouse opening stock, private address/cart, coupon and checkout/order journeys against the deployed backend.
|
||||
- [ ] Verify cross-account privacy, revoked sessions, changed permissions, concurrent carts, stock contention, duplicate retries and order expiry in live UAT.
|
||||
- [ ] Configure approved pricing policies and SMTP; verify recovery delivery and one-time token expiry/reset.
|
||||
- [ ] Build/run the container and test /workspace, /cart, /admin/catalog deep links; inspect CSP, certificate verification and /api health responses.
|
||||
- [ ] Verify HTTPS ingress, HSTS, trusted proxy/rate-limit policy and deployment secrets. Nginx forwards /api over verified HTTPS; frontend does not change backend trust-proxy policy.
|
||||
- [ ] Test complete populated screens in browsers at 320/768/1024/1440 widths; full keyboard/dialog/screen-reader/contrast checks and deployed axe/Lighthouse runs.
|
||||
- [ ] Verify production Core Web Vitals, expected traffic, infrastructure logs/alerts and privacy-safe client error collection. APPLICATION_RENDER_FAILED is the safe local render diagnostic; API requestId correlates service errors.
|
||||
- [ ] Confirm remote CI passes, observe deployment health/error/latency metrics, rehearse rollback, and obtain owner sign-off.
|
||||
|
||||
## Rollback
|
||||
|
||||
Record the 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.
|
||||
|
||||
## 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.
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
# Phase 2 — commerce and administration
|
||||
|
||||
Preserve the existing brand/theme; add purpose-built MUI customer and administration screens. Modules: session boundary → addresses/cart/orders; session/permissions → users/roles/audit, catalog, stock, coupons/pricing; recovery is public and clears fragment secrets from history. Backend remains authoritative. Production payment collection and public registration are unavailable.
|
||||
|
||||
Build in slices: (1) schemas/exact decimal and session privacy; (2) addresses/cart/idempotent checkout/order lifecycle; (3) user/role/audit and catalog/variant/group management; (4) inventory, coupons/pricing and recovery; (5) lint/tests/accessibility/security, chunk budgets, CI/container/release runbook.
|
||||
|
||||
Acceptance: valid decimal output including integers; two-decimal write inputs; cache cancellation/removal and request generation isolation on logout/expiry/revocation; serialized cart writes with conflict refetch; checkout timeout retries retain identical intent/key; nullable charges remain unfinalized; permission-gated UI plus backend checks; independent account/role safeguards; no fake successes; all CONSTRAINTS.md gates have recorded outcomes. Existing accounts are provisioned by backend CLI/staff APIs; live UAT cannot pass until account setup.
|
||||
|
|
@ -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.
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
# Phase 2 implementation verification — 13 October 2026
|
||||
|
||||
Final local gate: 30 tests passed, strict TypeScript and lint passed, production build passed with all 27 JavaScript chunks below 500 kB (largest approximately 494 kB). The dependency audit reported zero vulnerabilities.
|
||||
|
||||
| Area | Evidence / outcome |
|
||||
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Contract | Deployed Swagger exposes cart, checkout, addresses, users, roles, admin orders, pricing and coupon routes; backend stores/schemas determine response and mutation contracts. |
|
||||
| Automated tests | Contract tests cover exact decimal strings, persisted metadata, strict inputs, coupon limits/windows, recovery fragment cleanup and error diagnostics. Component/workflow tests cover session privacy, expiry, permission downgrade, stale responses, navigation-safe checkout retry, changed-cart review and nullable order charges. |
|
||||
| Accessibility | Axe on the permission-denied workspace reports no serious/critical findings. JSDOM color-contrast execution is unavailable; color contrast and populated-route browser axe remain a deployed acceptance gate. |
|
||||
| Browser routes | Addresses/orders/access/roles/catalog/inventory/coupons/pricing/audit all show the sign-in gate with no private input forms when unauthenticated. No captured errors on those route checks. |
|
||||
| Responsive | Cart shell checked at 320, 768, 1024, 1440; document width did not exceed viewport. Populated authenticated screens still require live UAT. |
|
||||
| Recovery | Invalid organization input showed a field-associated local validation error; no recovery email was sent. |
|
||||
| Build/performance | Routes load lazily; JavaScript chunks are measured by scripts/check-build.mjs and must remain below 500,000 bytes. No oversized-chunk warnings are accepted. |
|
||||
| Dependency audit | No reported vulnerabilities with the finalized npm lockfile. |
|
||||
| Independent review | Three bounded adversarial cycles. Decimal handling, session cleanup/revocation, intent persistence, reviewed-version concurrency, permissions cache erasure and cancellation/session races were reconciled and guarded by tests. User chose independent review plus tests without external cross-model execution. |
|
||||
| Deployment | Nginx CSP/frame/referrer/type headers and verified HTTPS API proxy added; CI quality gates and image-build nginx -t added. No local Docker runtime was available; container/ingress execution and remote CI remain unverified. |
|
||||
| Live authenticated UAT | Pending: user confirmed no organization/account setup. No account was created, data seeded, mail sent, payment collected or deployment performed. |
|
||||
|
||||
See RELEASE-CHECKLIST.md for production acceptance gates. Previous Phase 1 results remain historical in UAT-RESULTS.md.
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 75 KiB |
|
|
@ -1,23 +0,0 @@
|
|||
import tseslint from "typescript-eslint";
|
||||
import reactHooks from "eslint-plugin-react-hooks";
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ["dist/**", "node_modules/**", ".yarn/**"] },
|
||||
...tseslint.configs.recommended,
|
||||
{
|
||||
files: ["**/*.ts", "**/*.tsx"],
|
||||
plugins: { "react-hooks": reactHooks },
|
||||
rules: {
|
||||
"react-hooks/rules-of-hooks": "error",
|
||||
"react-hooks/exhaustive-deps": "error",
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
argsIgnorePattern: "^_",
|
||||
varsIgnorePattern: "^_",
|
||||
ignoreRestSiblings: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
|
@ -4,14 +4,14 @@
|
|||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
|
||||
<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 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 name="twitter:card" content="summary_large_image" />
|
||||
<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="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
|
|
|
|||
10
nginx.conf
10
nginx.conf
|
|
@ -5,28 +5,18 @@ server {
|
|||
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 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 / {
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
17
package.json
17
package.json
|
|
@ -5,12 +5,10 @@
|
|||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --config vite.config.ts",
|
||||
"build": "vite build --config vite.config.ts && node scripts/check-build.mjs",
|
||||
"build": "vite build --config vite.config.ts",
|
||||
"serve": "vite preview --config vite.config.ts",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "node --test test/*.test.ts && vitest run --config vitest.config.ts",
|
||||
"lint": "eslint src test --max-warnings=0",
|
||||
"check": "npm run lint && npm run typecheck && npm test && npm run build"
|
||||
"test": "node --test test/*.test.ts"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24 <25"
|
||||
|
|
@ -19,7 +17,6 @@
|
|||
"devDependencies": {
|
||||
"@emotion/react": "^11.11.4",
|
||||
"@emotion/styled": "^11.11.5",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@hookform/resolvers": "^3.10.0",
|
||||
"@mui/icons-material": "^5.15.15",
|
||||
"@mui/material": "^5.15.15",
|
||||
|
|
@ -52,23 +49,17 @@
|
|||
"@radix-ui/react-tooltip": "^1.2.0",
|
||||
"@tailwindcss/vite": "^4.1.6",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"@testing-library/user-event": "^14.6.7",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/react": "^18.3.5",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@vitejs/plugin-react": "^4.7.0",
|
||||
"axe-core": "^4.14.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"eslint": "^10.12.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"framer-motion": "^11.9.0",
|
||||
"input-otp": "^1.4.2",
|
||||
"jsdom": "^30.1.2",
|
||||
"lucide-react": "^0.469.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^18.3.1",
|
||||
|
|
@ -83,11 +74,9 @@
|
|||
"tailwindcss": "^4.1.6",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.71.1",
|
||||
"vaul": "^1.1.2",
|
||||
"vite": "^6.4.4",
|
||||
"vitest": "^5.0.3",
|
||||
"wouter": "^3.3.5",
|
||||
"zod": "^4.6.7"
|
||||
"zod": "^3.23.8"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +0,0 @@
|
|||
import { readdir, stat } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import assert from "node:assert/strict";
|
||||
const assets = new URL("../dist/assets/", import.meta.url);
|
||||
const files = (await readdir(assets)).filter((file) => file.endsWith(".js"));
|
||||
assert(files.length > 0, "No built JavaScript assets were found.");
|
||||
for (const file of files) {
|
||||
const size = (await stat(join(fileURLToPath(assets), file))).size;
|
||||
assert(
|
||||
size < 500000,
|
||||
`${file} exceeds the 500 kB chunk budget (${size} bytes).`,
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
`Build budget passed: ${files.length} JavaScript chunks below 500 kB.`,
|
||||
);
|
||||
|
|
@ -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"
|
||||
|
|
@ -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'
|
||||
245
src/App.tsx
245
src/App.tsx
|
|
@ -1,223 +1,50 @@
|
|||
import { lazy, Suspense } from "react";
|
||||
import { Switch, Route, Router as WouterRouter } from "wouter";
|
||||
import NotFound from "@/pages/not-found";
|
||||
|
||||
import { Layout } from "@/components/Layout";
|
||||
import Home from "@/pages/home";
|
||||
import ProductsPage from "@/pages/ProductsPage";
|
||||
import AboutPage from "@/pages/AboutPage";
|
||||
import ContactPage from "@/pages/ContactPage";
|
||||
import ProductPage from "@/pages/ProductPage";
|
||||
import WorkspacePage from "@/pages/WorkspacePage";
|
||||
import ConnectionPage from "@/pages/ConnectionPage";
|
||||
import { PlatformProvider } from "@/lib/platform";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import LinearProgress from "@mui/material/LinearProgress";
|
||||
import { ErrorBoundary } from "@/components/ErrorBoundary";
|
||||
const Home = lazy(() => import("@/pages/home"));
|
||||
const ProductsPage = lazy(() => import("@/pages/ProductsPage"));
|
||||
const ProductPage = lazy(() => import("@/pages/ProductPage"));
|
||||
const AboutPage = lazy(() => import("@/pages/AboutPage"));
|
||||
const ContactPage = lazy(() => import("@/pages/ContactPage"));
|
||||
const WorkspacePage = lazy(() => import("@/pages/WorkspacePage"));
|
||||
const ConnectionPage = lazy(() => import("@/pages/ConnectionPage"));
|
||||
const AddressesPage = lazy(() => import("@/pages/AddressesPage"));
|
||||
const CartPage = lazy(() => import("@/pages/CartPage"));
|
||||
const OrdersPage = lazy(() => import("@/pages/OrdersPage"));
|
||||
const AccessPage = lazy(() => import("@/pages/AccessPage"));
|
||||
const RolesPage = lazy(() =>
|
||||
import("@/pages/AccessPage").then((module) => ({
|
||||
default: module.RolesPage,
|
||||
})),
|
||||
);
|
||||
const AuditPage = lazy(() =>
|
||||
import("@/pages/AccessPage").then((module) => ({
|
||||
default: module.AuditPage,
|
||||
})),
|
||||
);
|
||||
const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage"));
|
||||
const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
|
||||
const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage"));
|
||||
const BusinessAccountsPage = lazy(() => import("@/pages/BusinessAccountsPage"));
|
||||
const PriceListsPage = lazy(() => import("@/pages/PriceListsPage"));
|
||||
const QuotesPage = lazy(() => import("@/pages/QuotesPage"));
|
||||
const CreditPoliciesPage = lazy(() => import("@/pages/CreditPoliciesPage"));
|
||||
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 ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
|
||||
const BomPage = lazy(() => import("@/pages/BomPage"));
|
||||
const ProductionBatchesPage = lazy(() => import("@/pages/ProductionBatchesPage"));
|
||||
const SupplierDocumentsPage = lazy(() => import("@/pages/SupplierDocumentsPage"));
|
||||
const PurchaseOrdersPage = lazy(() =>
|
||||
import("@/pages/ProcurementPage").then((module) => ({ default: module.PurchaseOrdersPage })),
|
||||
);
|
||||
const OffersPage = lazy(() => import("@/pages/OffersPage"));
|
||||
const RecoveryPage = lazy(() => import("@/pages/RecoveryPage"));
|
||||
const NotFound = lazy(() => import("@/pages/not-found"));
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
|
||||
function Router() {
|
||||
return (
|
||||
<Suspense fallback={<LinearProgress aria-label="Loading page" />}>
|
||||
<Switch>
|
||||
<Route path="/" component={Home} />
|
||||
<Route path="/products" component={ProductsPage} />
|
||||
<Route path="/products/:id">
|
||||
{(params) => <ProductPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/workspace" component={WorkspacePage} />
|
||||
<Route path="/connection" component={ConnectionPage} />
|
||||
<Route path="/addresses" component={AddressesPage} />
|
||||
<Route path="/cart" component={CartPage} />
|
||||
<Route path="/orders">{() => <OrdersPage />}</Route>
|
||||
<Route path="/orders/:id">
|
||||
{(params) => <OrdersPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/orders">{() => <OrdersPage admin />}</Route>
|
||||
<Route path="/admin/orders/:id">
|
||||
{(params) => <OrdersPage admin id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/access" component={AccessPage} />
|
||||
<Route path="/admin/roles" component={RolesPage} />
|
||||
<Route path="/admin/audit" component={AuditPage} />
|
||||
<Route path="/admin/business-accounts">{() => <BusinessAccountsPage />}</Route>
|
||||
<Route path="/admin/business-accounts/new">{() => <BusinessAccountsPage create />}</Route>
|
||||
<Route path="/admin/business-accounts/:id">
|
||||
{(params) => <BusinessAccountsPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-price-lists">{() => <PriceListsPage />}</Route>
|
||||
<Route path="/admin/b2b-price-lists/account/:id">
|
||||
{(params) => <PriceListsPage account id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-price-lists/:id">
|
||||
{(params) => <PriceListsPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-quotes">{() => <QuotesPage />}</Route>
|
||||
<Route path="/admin/b2b-quotes/new">{() => <QuotesPage issue />}</Route>
|
||||
<Route path="/admin/b2b-quotes/new/:accountId/:priceListId">
|
||||
{(params) => <QuotesPage issue accountId={params.accountId} priceListId={params.priceListId} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-quotes/account/:accountId">
|
||||
{(params) => <QuotesPage accountId={params.accountId} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-quotes/:id">
|
||||
{(params) => <QuotesPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-credit-policies">{() => <CreditPoliciesPage />}</Route>
|
||||
<Route path="/admin/b2b-credit-policies/new">{() => <CreditPoliciesPage propose />}</Route>
|
||||
<Route path="/admin/b2b-credit-policies/new/:accountId">
|
||||
{(params) => <CreditPoliciesPage propose accountId={params.accountId} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-credit-policies/account/:accountId">
|
||||
{(params) => <CreditPoliciesPage accountId={params.accountId} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-credit-policies/:id">
|
||||
{(params) => <CreditPoliciesPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-samples">{() => <SamplesPage />}</Route>
|
||||
<Route path="/admin/b2b-samples/new">{() => <SamplesPage create />}</Route>
|
||||
<Route path="/admin/b2b-samples/new/:accountId">
|
||||
{(params) => <SamplesPage create accountId={params.accountId} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-samples/account/:accountId">
|
||||
{(params) => <SamplesPage accountId={params.accountId} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-samples/:id">
|
||||
{(params) => <SamplesPage id={params.id} />}
|
||||
</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/:id">
|
||||
{(params) => <CatalogAdminPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/inventory">{() => <InventoryPage />}</Route>
|
||||
<Route path="/admin/material-stock">{() => <MaterialStockPage />}</Route>
|
||||
<Route path="/admin/material-stock/adjust">{() => <MaterialStockPage adjust />}</Route>
|
||||
<Route path="/admin/material-stock/adjust/:id">
|
||||
{(params) => <MaterialStockPage adjust id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/material-stock/:id">
|
||||
{(params) => <MaterialStockPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/material-cost-rates">{() => <MaterialCostRatesPage />}</Route>
|
||||
<Route path="/admin/material-cost-rates/:id">
|
||||
{(params) => <MaterialCostRatesPage materialId={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/inventory/:id">
|
||||
{(params) => <InventoryPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/coupons">{() => <OffersPage />}</Route>
|
||||
<Route path="/admin/procurement">{() => <ProcurementPage />}</Route>
|
||||
<Route path="/admin/procurement/materials">{() => <ProcurementPage materials />}</Route>
|
||||
<Route path="/admin/procurement/suppliers/:id">
|
||||
{(params) => <ProcurementPage supplierId={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/supplier-documents">{() => <SupplierDocumentsPage />}</Route>
|
||||
<Route path="/admin/supplier-documents/:id">
|
||||
{(params) => <SupplierDocumentsPage supplierId={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/boms">{() => <BomPage />}</Route>
|
||||
<Route path="/admin/boms/:id">
|
||||
{(params) => <BomPage variantId={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/packaging-boms">{() => <BomPage packaging />}</Route>
|
||||
<Route path="/admin/packaging-boms/:id">
|
||||
{(params) => <BomPage packaging variantId={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/production-batches">{() => <ProductionBatchesPage />}</Route>
|
||||
<Route path="/admin/production-batches/new">{() => <ProductionBatchesPage create />}</Route>
|
||||
<Route path="/admin/production-batches/new/:bomId">
|
||||
{(params) => <ProductionBatchesPage create bomId={params.bomId} />}
|
||||
</Route>
|
||||
<Route path="/admin/production-batches/:id">
|
||||
{(params) => <ProductionBatchesPage batchId={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/purchase-orders">{() => <PurchaseOrdersPage />}</Route>
|
||||
<Route path="/admin/purchase-orders/:id">
|
||||
{(params) => <PurchaseOrdersPage orderId={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/pricing">{() => <OffersPage pricing />}</Route>
|
||||
<Route path="/recovery">{() => <RecoveryPage />}</Route>
|
||||
<Route path="/reset-password">{() => <RecoveryPage reset />}</Route>
|
||||
<Route path="/about" component={AboutPage} />
|
||||
<Route path="/contact" component={ContactPage} />
|
||||
<Route component={NotFound} />
|
||||
</Switch>
|
||||
</Suspense>
|
||||
<Switch>
|
||||
<Route path="/" component={Home} />
|
||||
<Route path="/products" component={ProductsPage} />
|
||||
<Route path="/products/:id">
|
||||
{(params) => <ProductPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/workspace" component={WorkspacePage} />
|
||||
<Route path="/connection" component={ConnectionPage} />
|
||||
<Route path="/about" component={AboutPage} />
|
||||
<Route path="/contact" component={ContactPage} />
|
||||
<Route component={NotFound} />
|
||||
</Switch>
|
||||
);
|
||||
}
|
||||
export default function App() {
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<PlatformProvider>
|
||||
<WouterRouter base={import.meta.env.BASE_URL.replace(/\/$/, "")}>
|
||||
<Layout>
|
||||
<Router />
|
||||
</Layout>
|
||||
</WouterRouter>
|
||||
</PlatformProvider>
|
||||
</QueryClientProvider>
|
||||
</ErrorBoundary>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<PlatformProvider>
|
||||
<WouterRouter base={import.meta.env.BASE_URL.replace(/\/$/, "")}>
|
||||
<Layout>
|
||||
<Router />
|
||||
</Layout>
|
||||
</WouterRouter>
|
||||
</PlatformProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
|
|
|
|||
|
|
@ -1,84 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { z } from "zod";
|
||||
import Button from "@mui/material/Button";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { Link } from "wouter";
|
||||
import { cart } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { ApiNotice } from "./ApiNotice";
|
||||
export function AddToCart({ variantId }: { variantId: string }) {
|
||||
const { principal, request, scope } = usePlatform(),
|
||||
client = useQueryClient();
|
||||
const [busy, setBusy] = useState(false),
|
||||
[error, setError] = useState<unknown>(null),
|
||||
[saved, setSaved] = useState(false),
|
||||
[quantity, setQuantity] = useState(1);
|
||||
if (!principal)
|
||||
return (
|
||||
<Link href="/workspace">
|
||||
<u>Sign in to add to cart</u>
|
||||
</Link>
|
||||
);
|
||||
return (
|
||||
<div>
|
||||
<form
|
||||
className="cart-add"
|
||||
onSubmit={async (event) => {
|
||||
event.preventDefault();
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setSaved(false);
|
||||
try {
|
||||
z.number().int().min(1).max(100).parse(quantity);
|
||||
const current = await request("/cart", cart);
|
||||
const total =
|
||||
(current.lines.find((l) => l.variantId === variantId)?.quantity ||
|
||||
0) + quantity;
|
||||
z.number().int().max(100).parse(total);
|
||||
await request(
|
||||
`/cart/lines/${variantId}`,
|
||||
z.object({ version: z.number() }),
|
||||
{
|
||||
method: "PUT",
|
||||
body: { quantity: total, version: current.version },
|
||||
},
|
||||
);
|
||||
await client.invalidateQueries({
|
||||
queryKey: ["private", scope, "/cart"],
|
||||
});
|
||||
setSaved(true);
|
||||
} catch (error) {
|
||||
setError(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<TextField
|
||||
label="Quantity"
|
||||
type="number"
|
||||
size="small"
|
||||
value={quantity}
|
||||
onChange={(e) => setQuantity(Number(e.target.value))}
|
||||
inputProps={{ min: 1, max: 100, step: 1 }}
|
||||
disabled={busy}
|
||||
/>
|
||||
<Button type="submit" variant="contained" disabled={busy}>
|
||||
{busy ? "Adding…" : "Add to cart"}
|
||||
</Button>
|
||||
</form>
|
||||
<ApiNotice error={error} />
|
||||
{saved && (
|
||||
<Alert severity="success">
|
||||
Added.{" "}
|
||||
<Link href="/cart">
|
||||
<u>Review cart</u>
|
||||
</Link>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -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>;
|
||||
}
|
||||
|
|
@ -4,7 +4,7 @@ import Alert from "@mui/material/Alert";
|
|||
import Button from "@mui/material/Button";
|
||||
import Skeleton from "@mui/material/Skeleton";
|
||||
import { Flame } from "lucide-react";
|
||||
import { listProducts, productImageUrl } from "@/lib/api";
|
||||
import { listProducts } from "@/lib/api";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { ApiNotice } from "./ApiNotice";
|
||||
import "@/pages/products.css";
|
||||
|
|
@ -75,21 +75,11 @@ export function Catalog({
|
|||
<article className="prod-card" key={product.id}>
|
||||
<Link
|
||||
href={`/products/${product.id}`}
|
||||
className={`prod-img-wrap${product.images[0] ? "" : " catalog-placeholder"}`}
|
||||
className="prod-img-wrap catalog-placeholder"
|
||||
aria-label={`View ${product.name}`}
|
||||
>
|
||||
{product.images[0] ? (
|
||||
<img
|
||||
src={productImageUrl(organization, product.id, product.images[0].id)}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<Flame size={48} aria-hidden="true" />
|
||||
<span>Mani Candles</span>
|
||||
</>
|
||||
)}
|
||||
<Flame size={48} aria-hidden="true" />
|
||||
<span>Mani Candles</span>
|
||||
</Link>
|
||||
<div className="prod-info">
|
||||
<h3 className="prod-name">
|
||||
|
|
|
|||
|
|
@ -1,70 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import Button from "@mui/material/Button";
|
||||
import Dialog from "@mui/material/Dialog";
|
||||
import DialogTitle from "@mui/material/DialogTitle";
|
||||
import DialogContent from "@mui/material/DialogContent";
|
||||
import DialogActions from "@mui/material/DialogActions";
|
||||
import { ApiNotice } from "./ApiNotice";
|
||||
export function ConfirmAction({
|
||||
label,
|
||||
message,
|
||||
onConfirm,
|
||||
disabled = false,
|
||||
}: {
|
||||
label: string;
|
||||
message: string;
|
||||
onConfirm: () => Promise<unknown>;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false),
|
||||
[busy, setBusy] = useState(false),
|
||||
[error, setError] = useState<unknown>(null);
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
disabled={disabled}
|
||||
onClick={() => {
|
||||
setError(null);
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={() => {
|
||||
if (!busy) setOpen(false);
|
||||
}}
|
||||
aria-labelledby="confirm-title"
|
||||
>
|
||||
<DialogTitle id="confirm-title">{label}</DialogTitle>
|
||||
<DialogContent>
|
||||
<p>{message}</p>
|
||||
<ApiNotice error={error} />
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button disabled={busy} onClick={() => setOpen(false)}>
|
||||
Keep current state
|
||||
</Button>
|
||||
<Button
|
||||
disabled={busy}
|
||||
variant="contained"
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await onConfirm();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
setError(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{busy ? "Working…" : "Confirm"}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
import { Component, type ReactNode } from "react";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import Button from "@mui/material/Button";
|
||||
export class ErrorBoundary extends Component<
|
||||
{ children: ReactNode },
|
||||
{ failed: boolean }
|
||||
> {
|
||||
state = { failed: false };
|
||||
static getDerivedStateFromError() {
|
||||
return { failed: true };
|
||||
}
|
||||
componentDidCatch() {
|
||||
console.error("APPLICATION_RENDER_FAILED");
|
||||
}
|
||||
render() {
|
||||
return this.state.failed ? (
|
||||
<main className="workspace-page">
|
||||
<Alert severity="error">
|
||||
This page could not be displayed. Reload to start a fresh session.
|
||||
</Alert>
|
||||
<Button onClick={() => location.reload()}>Reload application</Button>
|
||||
</main>
|
||||
) : (
|
||||
this.props.children
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -14,12 +14,12 @@ const logoPath = "/opengraph.jpg";
|
|||
|
||||
// ── Ticker messages ──────────────────────────────────────
|
||||
const TICKER_ITEMS = [
|
||||
{ icon: <Flame size={12} />, text: "UAT — commerce and administration" },
|
||||
{ icon: <Flame size={12} />, text: "UAT — catalog and staff access" },
|
||||
{ icon: <Sparkles size={12} />, text: "Explore the published collection" },
|
||||
{ icon: <Star size={12} />, text: "Handpoured in small batches" },
|
||||
{ icon: <Flame size={12} />, text: "100% Natural Soy Wax" },
|
||||
{ icon: <Sparkles size={12} />, text: "Phthalate-free fragrance oils" },
|
||||
{ icon: <Star size={12} />, text: "Payment collection is not enabled" },
|
||||
{ icon: <Star size={12} />, text: "Ordering arrives in the commerce phase" },
|
||||
];
|
||||
|
||||
// ── Nav structure with dropdowns ─────────────────────────
|
||||
|
|
@ -50,7 +50,6 @@ const NAV_LINKS = [
|
|||
],
|
||||
},
|
||||
{ name: "Workspace", path: "/workspace", dropdown: null },
|
||||
{ name: "Cart", path: "/cart", dropdown: null },
|
||||
{ name: "Connection", path: "/connection", dropdown: null },
|
||||
];
|
||||
|
||||
|
|
|
|||
|
|
@ -1,73 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
import Checkbox from "@mui/material/Checkbox";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { Pager, QueryView, Table, usePrivateQuery } from "./WorkspaceTools";
|
||||
const record = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string(),
|
||||
isSystem: z.boolean().optional(),
|
||||
permissions: z.array(z.string()).optional(),
|
||||
});
|
||||
export function RecordSelection({
|
||||
name,
|
||||
label,
|
||||
path,
|
||||
initial = [],
|
||||
roles = false,
|
||||
}: {
|
||||
name: string;
|
||||
label: string;
|
||||
path: string;
|
||||
initial?: string[];
|
||||
roles?: boolean;
|
||||
}) {
|
||||
const { principal } = usePlatform();
|
||||
const [selected, setSelected] = useState(initial),
|
||||
[offset, setOffset] = useState(0);
|
||||
const query = usePrivateQuery(
|
||||
`${path}?limit=25&offset=${offset}`,
|
||||
z.array(record),
|
||||
);
|
||||
return (
|
||||
<fieldset className="record-picker">
|
||||
<legend>{label}</legend>
|
||||
<p>{selected.length} selected. Selections are retained across pages.</p>
|
||||
{selected.map((id) => (
|
||||
<input key={id} type="hidden" name={name} value={id} />
|
||||
))}
|
||||
<QueryView query={query}>
|
||||
{(items) => (
|
||||
<>
|
||||
<Table
|
||||
head={["Select", "Name"]}
|
||||
rowKeys={items.map((item) => item.id)}
|
||||
rows={items.map((item) => [
|
||||
<Checkbox
|
||||
inputProps={{ "aria-label": `Select ${item.name}` }}
|
||||
checked={selected.includes(item.id)}
|
||||
disabled={
|
||||
roles &&
|
||||
(item.isSystem ||
|
||||
item.permissions?.some(
|
||||
(p) => !principal?.permissions.includes(p),
|
||||
))
|
||||
}
|
||||
onChange={(_, checked) =>
|
||||
setSelected((ids) =>
|
||||
checked
|
||||
? [...ids, item.id]
|
||||
: ids.filter((id) => id !== item.id),
|
||||
)
|
||||
}
|
||||
/>,
|
||||
item.name,
|
||||
])}
|
||||
/>
|
||||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
import { useRef, useState } from "react";
|
||||
import Button from "@mui/material/Button";
|
||||
import { Field } from "./WorkspaceTools";
|
||||
|
||||
export function readVariantQuantities(form: FormData) {
|
||||
const quantities = form.getAll("quantity");
|
||||
return form.getAll("variantId").map((id, index) => ({
|
||||
variantId: String(id).trim(),
|
||||
quantity: Number(quantities[index]),
|
||||
}));
|
||||
}
|
||||
|
||||
export function VariantQuantityFields({ options }: { options?: { value: string; label: string }[] }) {
|
||||
const next = useRef(1);
|
||||
const [rows, setRows] = useState([0]);
|
||||
const limit = Math.min(100, options?.length ?? 100);
|
||||
return <>
|
||||
{rows.map((key, index) => <fieldset className="record-picker" key={key}>
|
||||
<legend>Line {index + 1}</legend>
|
||||
<Field name="variantId" label={`Variant for line ${index + 1}`} maxLength={36}
|
||||
options={options && [{ value: "", label: "Choose a variant" }, ...options]} />
|
||||
<Field name="quantity" label={`Quantity for line ${index + 1}`} type="number" />
|
||||
<Button type="button" disabled={rows.length === 1} onClick={() => setRows(rows.filter((row) => row !== key))}>Remove line {index + 1}</Button>
|
||||
</fieldset>)}
|
||||
<Button type="button" disabled={rows.length >= limit} onClick={() => {
|
||||
const key = next.current++;
|
||||
setRows([...rows, key]);
|
||||
}}>Add line</Button>
|
||||
</>;
|
||||
}
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
import { useState, type ReactNode } from "react";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { z } from "zod";
|
||||
import { ActionForm, Field, Pager, QueryView, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { warehouse } from "@/lib/commerce";
|
||||
|
||||
export function WarehousePostingForm({ label, instruction, warehouseLabel = "Warehouse", excludeWarehouseId, read, children, reset = false, submit }: {
|
||||
label: string;
|
||||
instruction: string;
|
||||
warehouseLabel?: string;
|
||||
excludeWarehouseId?: string;
|
||||
read?: (data: FormData) => unknown;
|
||||
children?: ReactNode;
|
||||
reset?: boolean;
|
||||
submit: (input: unknown) => Promise<void>;
|
||||
}) {
|
||||
const [offset, setOffset] = useState(0);
|
||||
const query = usePrivateQuery(`/inventory/warehouses?limit=25&offset=${offset}`, z.array(warehouse));
|
||||
return <QueryView query={query}>{(rows) => {
|
||||
const options = rows.filter((row) => row.id !== excludeWarehouseId);
|
||||
return <>
|
||||
{options.length ? <ActionForm key={offset} label={label} reset={reset}
|
||||
read={read ?? ((data) => ({ warehouseId: readText(data, "warehouseId") }))} submit={submit}>
|
||||
<p>{instruction}</p>
|
||||
<Field name="warehouseId" label={warehouseLabel} options={[
|
||||
{ value: "", label: "Choose a warehouse" },
|
||||
...options.map((row) => ({ value: row.id, label: row.name })),
|
||||
]} />
|
||||
{children}
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</ActionForm> : <>
|
||||
<Alert severity="info">No eligible warehouses on this page.</Alert>
|
||||
{(offset > 0 || rows.length === 25) && <Pager offset={offset} count={rows.length} onPage={setOffset} />}
|
||||
</>}
|
||||
</>;
|
||||
}}</QueryView>;
|
||||
}
|
||||
|
|
@ -1,93 +0,0 @@
|
|||
import type { ReactNode } from "react";
|
||||
import { Link } from "wouter";
|
||||
import Container from "@mui/material/Container";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import Button from "@mui/material/Button";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import "@/pages/workspace.css";
|
||||
export function WorkspaceShell({
|
||||
title,
|
||||
permission,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
permission?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { principal, can, scope } = usePlatform();
|
||||
return (
|
||||
<section className="workspace-page">
|
||||
<Container maxWidth="lg">
|
||||
<h1>{title}</h1>
|
||||
{!principal ? (
|
||||
<Alert severity="info">
|
||||
Sign in to continue.{" "}
|
||||
<Link href="/workspace">
|
||||
<u>Account sign-in</u>
|
||||
</Link>
|
||||
</Alert>
|
||||
) : (
|
||||
<>
|
||||
<WorkspaceNavigation />
|
||||
{permission && !can(permission) ? (
|
||||
<Alert severity="warning">
|
||||
Your account does not have permission to view this page.
|
||||
</Alert>
|
||||
) : (
|
||||
<div key={scope}>{children}</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Container>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function WorkspaceNavigation() {
|
||||
const { can } = usePlatform();
|
||||
const links = [
|
||||
{ label: "My cart", path: "/cart" },
|
||||
{ label: "Addresses", path: "/addresses" },
|
||||
{ label: "My orders", path: "/orders" },
|
||||
{ label: "Access", path: "/admin/access", permission: "users.read" },
|
||||
{ label: "Roles", path: "/admin/roles", permission: "roles.read" },
|
||||
{ label: "Catalog", path: "/admin/catalog", permission: "catalog.read" },
|
||||
{
|
||||
label: "Inventory",
|
||||
path: "/admin/inventory",
|
||||
permission: "inventory.read",
|
||||
},
|
||||
{ label: "Coupons", path: "/admin/coupons", permission: "coupons.manage" },
|
||||
{ label: "Suppliers", path: "/admin/procurement", permission: "procurement.read" },
|
||||
{ label: "Supplier documents", path: "/admin/supplier-documents", permission: "supplier_document.read" },
|
||||
{ label: "Materials", path: "/admin/procurement/materials", permission: "procurement.read" },
|
||||
{ label: "Purchase orders", path: "/admin/purchase-orders", permission: "procurement.read" },
|
||||
{ label: "Material stock", path: "/admin/material-stock", permission: "inventory.read" },
|
||||
{ label: "Material cost rates", path: "/admin/material-cost-rates", permission: "cost.read" },
|
||||
{ label: "Production BOMs", path: "/admin/boms", permission: "bom.read" },
|
||||
{ label: "Production batches", path: "/admin/production-batches", permission: "production.read" },
|
||||
{ label: "Packaging BOMs", path: "/admin/packaging-boms", permission: "packaging.read" },
|
||||
{ label: "Pricing", path: "/admin/pricing", permission: "pricing.manage" },
|
||||
{ label: "All orders", path: "/admin/orders", permission: "orders.read" },
|
||||
{ label: "Audit", path: "/admin/audit", permission: "audit.read" },
|
||||
{ label: "Business accounts", path: "/admin/business-accounts", permission: "b2b.read" },
|
||||
{ label: "B2B price lists", path: "/admin/b2b-price-lists", permission: "b2b.price.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 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 (
|
||||
<nav className="workspace-links" aria-label="Workspace navigation">
|
||||
{links
|
||||
.filter((l) => !l.permission || can(l.permission))
|
||||
.map((l) => (
|
||||
<Button key={l.path} component={Link} href={l.path}>
|
||||
{l.label}
|
||||
</Button>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,286 +0,0 @@
|
|||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useId,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { Link } from "wouter";
|
||||
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import Button from "@mui/material/Button";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import Checkbox from "@mui/material/Checkbox";
|
||||
import FormControlLabel from "@mui/material/FormControlLabel";
|
||||
import LinearProgress from "@mui/material/LinearProgress";
|
||||
import Paper from "@mui/material/Paper";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { ApiNotice } from "./ApiNotice";
|
||||
export function usePrivateQuery<T>(path: string, schema: z.ZodType<T>) {
|
||||
const { scope, request } = usePlatform();
|
||||
return useQuery({
|
||||
queryKey: ["private", scope, path],
|
||||
queryFn: ({ signal }) => request(path, schema, { signal }),
|
||||
enabled: Boolean(scope),
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
export function QueryView<T>({
|
||||
query,
|
||||
children,
|
||||
}: {
|
||||
query: UseQueryResult<T>;
|
||||
children: (data: T) => ReactNode;
|
||||
}) {
|
||||
if (query.isPending) return <LinearProgress aria-label="Loading workspace" />;
|
||||
if (query.isError)
|
||||
return (
|
||||
<>
|
||||
<ApiNotice error={query.error} />
|
||||
<Button onClick={() => query.refetch()}>Try again</Button>
|
||||
</>
|
||||
);
|
||||
return <>{children(query.data)}</>;
|
||||
}
|
||||
export function Panel({
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<Paper variant="outlined" className="workspace-panel">
|
||||
<h2>{title}</h2>
|
||||
{children}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
const Errors = createContext<Record<string, string>>({});
|
||||
export function ActionForm({
|
||||
label,
|
||||
read,
|
||||
submit,
|
||||
children,
|
||||
reset = true,
|
||||
lockFields = false,
|
||||
}: {
|
||||
label: string;
|
||||
read: (data: FormData) => unknown;
|
||||
submit: (input: unknown) => Promise<unknown>;
|
||||
children: ReactNode;
|
||||
reset?: boolean;
|
||||
lockFields?: boolean;
|
||||
}) {
|
||||
const [busy, setBusy] = useState(false),
|
||||
[error, setError] = useState<unknown>(null),
|
||||
[success, setSuccess] = useState(false),
|
||||
[fields, setFields] = useState<Record<string, string>>({});
|
||||
const submitting = useRef(false);
|
||||
return (
|
||||
<form
|
||||
className="workspace-form"
|
||||
aria-label={label}
|
||||
onSubmit={async (event) => {
|
||||
event.preventDefault();
|
||||
if (submitting.current) return;
|
||||
submitting.current = true;
|
||||
const form = event.currentTarget;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setSuccess(false);
|
||||
setFields({});
|
||||
try {
|
||||
await submit(read(new FormData(form)));
|
||||
if (reset) form.reset();
|
||||
setSuccess(true);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
setFields(
|
||||
Object.fromEntries(
|
||||
error.issues.map((i) => [String(i.path[0]), i.message]),
|
||||
),
|
||||
);
|
||||
setError(
|
||||
new Error(
|
||||
error.issues
|
||||
.map((issue) => `${issue.path.join(".")}: ${issue.message}`)
|
||||
.join("; "),
|
||||
),
|
||||
);
|
||||
} else setError(error);
|
||||
} finally {
|
||||
submitting.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<fieldset disabled={busy || lockFields}>
|
||||
<Errors.Provider value={fields}>{children}</Errors.Provider>
|
||||
</fieldset>
|
||||
<ApiNotice error={error} />
|
||||
{success && <Alert severity="success">Saved successfully.</Alert>}
|
||||
<Button type="submit" variant="contained" disabled={busy}>
|
||||
{busy ? "Saving…" : label}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
export function Field({
|
||||
name,
|
||||
label,
|
||||
type = "text",
|
||||
value,
|
||||
required = true,
|
||||
maxLength,
|
||||
options,
|
||||
multiple = false,
|
||||
helper,
|
||||
onChange,
|
||||
}: {
|
||||
name: string;
|
||||
label: string;
|
||||
type?: string;
|
||||
value?: string | number | string[];
|
||||
required?: boolean;
|
||||
maxLength?: number;
|
||||
options?: { value: string; label: string }[];
|
||||
multiple?: boolean;
|
||||
helper?: string;
|
||||
onChange?: (value: string) => void;
|
||||
}) {
|
||||
const errors = useContext(Errors),
|
||||
id = useId();
|
||||
return (
|
||||
<TextField
|
||||
id={id}
|
||||
name={name}
|
||||
label={label}
|
||||
type={type}
|
||||
defaultValue={onChange ? undefined : (value ?? (multiple ? [] : ""))}
|
||||
value={onChange ? value : undefined}
|
||||
onChange={onChange ? (event) => onChange(event.target.value) : undefined}
|
||||
autoComplete={type === "password" ? "new-password" : undefined}
|
||||
required={required}
|
||||
fullWidth
|
||||
error={Boolean(errors[name])}
|
||||
helperText={errors[name] || helper}
|
||||
inputProps={{ maxLength }}
|
||||
select={Boolean(options)}
|
||||
InputLabelProps={multiple ? { shrink: true } : undefined}
|
||||
SelectProps={options ? { native: true, multiple } : undefined}
|
||||
>
|
||||
{options && (
|
||||
<>
|
||||
{!required && !multiple && <option value="">None</option>}
|
||||
{options.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</TextField>
|
||||
);
|
||||
}
|
||||
export function Check({
|
||||
name,
|
||||
label,
|
||||
value = false,
|
||||
}: {
|
||||
name: string;
|
||||
label: string;
|
||||
value?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<FormControlLabel
|
||||
control={<Checkbox name={name} defaultChecked={value} />}
|
||||
label={label}
|
||||
/>
|
||||
);
|
||||
}
|
||||
export const readText = (data: FormData, name: string) =>
|
||||
String(data.get(name) ?? "");
|
||||
export const readNumber = (data: FormData, name: string) =>
|
||||
Number(data.get(name));
|
||||
export function Pager({
|
||||
offset,
|
||||
count,
|
||||
onPage,
|
||||
}: {
|
||||
offset: number;
|
||||
count: number;
|
||||
onPage: (offset: number) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="catalog-pagination">
|
||||
<Button
|
||||
disabled={!offset}
|
||||
onClick={() => onPage(Math.max(0, offset - 25))}
|
||||
>
|
||||
Previous
|
||||
</Button>
|
||||
<span>Page {offset / 25 + 1}</span>
|
||||
<Button
|
||||
disabled={count < 25 || offset + 25 > 10000}
|
||||
onClick={() => onPage(offset + 25)}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function Empty({ label = "No records yet." }: { label?: string }) {
|
||||
return <Alert severity="info">{label}</Alert>;
|
||||
}
|
||||
export function Table({
|
||||
head,
|
||||
rows,
|
||||
rowKeys,
|
||||
}: {
|
||||
head: string[];
|
||||
rows: ReactNode[][];
|
||||
rowKeys: string[];
|
||||
}) {
|
||||
return rows.length ? (
|
||||
<div className="workspace-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
{head.map((h) => (
|
||||
<th key={h} scope="col">
|
||||
{h}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row, index) => (
|
||||
<tr key={rowKeys[index]}>
|
||||
{row.map((cell, i) => (
|
||||
<td key={i}>{cell}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<Empty />
|
||||
);
|
||||
}
|
||||
export function WorkspaceLink({
|
||||
href,
|
||||
children,
|
||||
}: {
|
||||
href: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<Link href={href}>
|
||||
<u>{children}</u>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import { useQuery } from "@tanstack/react-query";
|
||||
import { z } from "zod";
|
||||
import { ApiError } from "@/lib/api";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
|
||||
export function useOptionalPrivateQuery<T>(path: string, schema: z.ZodType<T>, missingCode: string) {
|
||||
const { request, scope } = usePlatform();
|
||||
return useQuery({
|
||||
queryKey: ["private", scope, path],
|
||||
enabled: Boolean(scope),
|
||||
retry: false,
|
||||
queryFn: async ({ signal }) => {
|
||||
try {
|
||||
return await request(path, schema, { signal });
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 404 && error.code === missingCode) return null;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -15,12 +15,12 @@ type ToasterToast = ToastProps & {
|
|||
action?: ToastActionElement
|
||||
}
|
||||
|
||||
type ActionType = {
|
||||
const actionTypes = {
|
||||
ADD_TOAST: "ADD_TOAST",
|
||||
UPDATE_TOAST: "UPDATE_TOAST",
|
||||
DISMISS_TOAST: "DISMISS_TOAST",
|
||||
REMOVE_TOAST: "REMOVE_TOAST",
|
||||
}
|
||||
} as const
|
||||
|
||||
let count = 0
|
||||
|
||||
|
|
@ -29,7 +29,7 @@ function genId() {
|
|||
return count.toString()
|
||||
}
|
||||
|
||||
|
||||
type ActionType = typeof actionTypes
|
||||
|
||||
type Action =
|
||||
| {
|
||||
|
|
|
|||
122
src/lib/api.ts
122
src/lib/api.ts
|
|
@ -1,19 +1,11 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const organizationSchema = z.string().uuid().toLowerCase();
|
||||
export const organizationSchema = z.string().uuid();
|
||||
const productSummarySchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: 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({
|
||||
description: z.string(),
|
||||
variants: z.array(
|
||||
|
|
@ -21,9 +13,9 @@ export const productSchema = productSummarySchema.extend({
|
|||
id: z.string().uuid(),
|
||||
sku: z.string(),
|
||||
name: z.string(),
|
||||
price: z.string().regex(/^\d+(?:\.\d{1,2})?$/),
|
||||
price: z.string().regex(/^\d+\.\d{2}$/),
|
||||
currency: z.string(),
|
||||
attributes: z.record(z.string(), z.string()),
|
||||
attributes: z.record(z.string()),
|
||||
}),
|
||||
),
|
||||
groups: z.array(
|
||||
|
|
@ -70,48 +62,32 @@ export class ApiError extends Error {
|
|||
this.requestId = requestId;
|
||||
}
|
||||
}
|
||||
export function isUnknownOutcome(error: unknown) {
|
||||
return (
|
||||
(error instanceof Error && error.name === "AbortError") ||
|
||||
(error instanceof ApiError &&
|
||||
(error.status === 0 ||
|
||||
error.status >= 500 ||
|
||||
error.code === "INVALID_RESPONSE" ||
|
||||
error.code === "SESSION_CHANGED"))
|
||||
);
|
||||
}
|
||||
|
||||
type ApiOptions = {
|
||||
token?: string;
|
||||
body?: unknown;
|
||||
method?: string;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
async function fetchApiResponse(
|
||||
export async function apiRequest(
|
||||
path: string,
|
||||
{
|
||||
token,
|
||||
body,
|
||||
method = "GET",
|
||||
signal,
|
||||
attachmentMime,
|
||||
}: ApiOptions & { attachmentMime?: string },
|
||||
) {
|
||||
}: {
|
||||
token?: string;
|
||||
body?: unknown;
|
||||
method?: string;
|
||||
signal?: AbortSignal;
|
||||
} = {},
|
||||
): Promise<unknown> {
|
||||
let response: Response;
|
||||
const multipart = body instanceof FormData;
|
||||
try {
|
||||
const timeout = AbortSignal.timeout(15000);
|
||||
response = await fetch(`/api/v1${path}`, {
|
||||
method,
|
||||
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
||||
...(attachmentMime || multipart ? { cache: "no-store", redirect: "error" } : {}),
|
||||
headers: {
|
||||
...(body === undefined || multipart ? {} : { "Content-Type": "application/json" }),
|
||||
...(attachmentMime ? { Accept: attachmentMime } : {}),
|
||||
...(body === undefined ? {} : { "Content-Type": "application/json" }),
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
...(body === undefined ? {} : { body: multipart ? body : JSON.stringify(body) }),
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AbortError") throw error;
|
||||
|
|
@ -121,8 +97,9 @@ async function fetchApiResponse(
|
|||
"NETWORK_ERROR",
|
||||
);
|
||||
}
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
if (response.status === 204) return null;
|
||||
const data = await response.json().catch(() => null);
|
||||
if (!response.ok)
|
||||
throw new ApiError(
|
||||
typeof data?.message === "string"
|
||||
? data.message
|
||||
|
|
@ -133,14 +110,6 @@ async function fetchApiResponse(
|
|||
? data.requestId
|
||||
: (response.headers.get("x-request-id") ?? undefined),
|
||||
);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
export async function apiRequest(path: string, options: ApiOptions = {}): Promise<unknown> {
|
||||
const response = await fetchApiResponse(path, options);
|
||||
if (response.status === 204) return null;
|
||||
const data = await response.json().catch(() => null);
|
||||
if (data === null)
|
||||
throw new ApiError(
|
||||
"The service returned an unexpected response.",
|
||||
|
|
@ -149,45 +118,7 @@ export async function apiRequest(path: string, options: ApiOptions = {}): Promis
|
|||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
async function apiAttachment(
|
||||
path: string,
|
||||
size: number,
|
||||
attachmentMime: string,
|
||||
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();
|
||||
if (file.size !== size) throw invalidAttachment();
|
||||
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 {
|
||||
function parse<T>(schema: z.ZodType<T>, data: unknown): T {
|
||||
const result = schema.safeParse(data);
|
||||
if (!result.success)
|
||||
throw new ApiError(
|
||||
|
|
@ -234,27 +165,12 @@ export async function login(
|
|||
email: string,
|
||||
password: string,
|
||||
) {
|
||||
const organization = organizationSchema.parse(organizationId);
|
||||
organizationSchema.parse(organizationId);
|
||||
return parse(
|
||||
sessionSchema,
|
||||
await apiRequest("/auth/login", {
|
||||
method: "POST",
|
||||
body: { organizationId: organization, email, password },
|
||||
}),
|
||||
);
|
||||
}
|
||||
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 },
|
||||
body: { organizationId, email, password },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { uuid } from "./commerce.ts";
|
||||
import { materialInput } from "./procurement.ts";
|
||||
|
||||
export const bomKind = z.enum(["PRODUCTION", "PACKAGING"]);
|
||||
export const bomStatus = z.enum(["DRAFT", "ACTIVE", "SUPERSEDED"]);
|
||||
export const packagingMaterialKinds = ["PACKAGING", "LABEL"] as const;
|
||||
|
||||
export const bomInput = z.object({
|
||||
outputQuantity: z.number().int().min(1).max(100000),
|
||||
lines: z.array(z.object({
|
||||
materialId: uuid,
|
||||
quantity: z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Use three decimal places")
|
||||
.refine((value) => value !== "0.000", "Quantity must be positive"),
|
||||
}).strict()).min(1, "Add at least one material").max(50)
|
||||
.refine((lines) => new Set(lines.map((line) => line.materialId)).size === lines.length, "Each material may occur once"),
|
||||
}).strict();
|
||||
|
||||
export const bomSummary = z.object({
|
||||
id: uuid,
|
||||
variantId: uuid,
|
||||
kind: bomKind,
|
||||
status: bomStatus,
|
||||
revision: z.number().int().min(1).max(100),
|
||||
outputQuantity: bomInput.shape.outputQuantity,
|
||||
activatedAt: z.string().datetime().nullable(),
|
||||
});
|
||||
|
||||
export const bomDetail = bomSummary.extend({
|
||||
lines: z.array(z.object({
|
||||
id: uuid,
|
||||
materialId: uuid,
|
||||
materialName: z.string(),
|
||||
materialCode: z.string(),
|
||||
unit: materialInput.shape.unit,
|
||||
quantity: z.string().regex(/^\d{1,9}(\.\d{1,3})?$/),
|
||||
})),
|
||||
});
|
||||
|
|
@ -1,49 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { uuid } from "./commerce.ts";
|
||||
|
||||
const text = (max: number, min = 1) =>
|
||||
z.string().trim().min(min).max(max).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
|
||||
|
||||
export const businessProfile = z.object({
|
||||
legalName: text(160),
|
||||
tradingName: text(160).nullable(),
|
||||
registrationNumber: text(64, 3),
|
||||
taxIdentifier: text(64).nullable(),
|
||||
countryCode: z.string().trim().toUpperCase().regex(/^[A-Z]{2}$/, "Use a two-letter country code"),
|
||||
contactEmail: z.string().trim().email().max(254).toLowerCase(),
|
||||
contactPhone: z.string().trim().regex(/^\+?[0-9 ()-]{7,24}$/, "Enter a valid phone number").nullable(),
|
||||
billingLine1: text(200),
|
||||
billingCity: text(100),
|
||||
billingRegion: text(100),
|
||||
billingPostalCode: text(20),
|
||||
}).strict();
|
||||
|
||||
export const businessInput = businessProfile.extend({
|
||||
code: z.string().trim().toUpperCase().max(32).regex(/^[A-Z0-9][A-Z0-9_-]*$/, "Use letters, numbers, hyphens or underscores"),
|
||||
});
|
||||
export const profileVersion = z.number().int().positive();
|
||||
export const profileSnapshot = businessProfile.extend({ profileVersion });
|
||||
|
||||
export const submissionInput = z.object({ idempotencyKey: uuid }).strict();
|
||||
export const decisionInput = submissionInput.extend({
|
||||
decision: z.enum(["APPROVED", "REJECTED"]),
|
||||
note: text(500, 3),
|
||||
});
|
||||
|
||||
export const businessEvent = z.object({
|
||||
id: uuid,
|
||||
actorId: uuid,
|
||||
sequence: z.number().int().positive(),
|
||||
kind: z.enum(["SUBMITTED", "APPROVED", "REJECTED"]),
|
||||
profileSnapshot: profileSnapshot.nullable(),
|
||||
note: z.string().nullable(),
|
||||
createdAt: z.string().datetime(),
|
||||
});
|
||||
export const businessAccount = businessInput.extend({
|
||||
id: uuid,
|
||||
profileVersion,
|
||||
status: z.enum(["DRAFT", "PENDING", "VERIFIED", "REJECTED"]),
|
||||
latestEvent: businessEvent.nullable(),
|
||||
}).strip();
|
||||
|
||||
export const businessSearch = text(100, 0);
|
||||
|
|
@ -1,329 +0,0 @@
|
|||
import { z } from "zod";
|
||||
export const uuid = z.string().uuid().toLowerCase();
|
||||
export const currency = z.enum(["INR", "USD", "EUR", "GBP"]);
|
||||
export const decimal = z.string().regex(/^\d+(?:\.\d{1,2})?$/);
|
||||
export const amount = z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/);
|
||||
const text = (max: number, min = 1) =>
|
||||
z
|
||||
.string()
|
||||
.trim()
|
||||
.min(min)
|
||||
.max(max)
|
||||
.regex(/^[^<>\u0000-\u001F\u007F]*$/, "Plain text only");
|
||||
export const addressInput = z
|
||||
.object({
|
||||
recipient: text(160),
|
||||
line1: text(200),
|
||||
line2: text(200, 0),
|
||||
city: text(100),
|
||||
region: text(100),
|
||||
postalCode: text(20).regex(/^[A-Za-z0-9 -]+$/),
|
||||
countryCode: z
|
||||
.string()
|
||||
.toUpperCase()
|
||||
.regex(/^[A-Z]{2}$/),
|
||||
phone: z.string().regex(/^\+[1-9]\d{6,14}$/),
|
||||
isDefault: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
export const address = addressInput.extend({ id: uuid }).strip();
|
||||
export type Address = z.infer<typeof address>;
|
||||
export const cart = z.object({
|
||||
version: z.number().int().nonnegative(),
|
||||
lines: z.array(
|
||||
z.object({
|
||||
variantId: uuid,
|
||||
quantity: z.number().int().positive(),
|
||||
variant: z.object({
|
||||
name: z.string(),
|
||||
sku: z.string(),
|
||||
price: decimal,
|
||||
currency,
|
||||
active: z.boolean(),
|
||||
product: z.object({ name: z.string(), status: z.string() }),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
});
|
||||
export type Cart = z.infer<typeof cart>;
|
||||
export const couponCode = text(40)
|
||||
.toUpperCase()
|
||||
.regex(/^[A-Z0-9][A-Z0-9_-]{0,39}$/);
|
||||
export const checkoutInput = z
|
||||
.object({
|
||||
cartVersion: z.number().int().min(0).max(2147483646),
|
||||
addressId: uuid,
|
||||
idempotencyKey: uuid,
|
||||
couponCode: couponCode.optional(),
|
||||
})
|
||||
.strict();
|
||||
export type CheckoutIntent = z.infer<typeof checkoutInput>;
|
||||
export function checkoutIntent(
|
||||
input: Omit<CheckoutIntent, "idempotencyKey">,
|
||||
key: string,
|
||||
) {
|
||||
return Object.freeze(checkoutInput.parse({ ...input, idempotencyKey: key }));
|
||||
}
|
||||
export function money(value: string) {
|
||||
decimal.parse(value);
|
||||
const [whole, fraction = ""] = value.split(".");
|
||||
return `${BigInt(whole)}.${fraction.padEnd(2, "0")}`;
|
||||
}
|
||||
export function moneyTotal(lines: { price: string; quantity: number }[]) {
|
||||
const total = lines.reduce((sum, line) => {
|
||||
z.number().int().nonnegative().parse(line.quantity);
|
||||
return (
|
||||
sum + BigInt(money(line.price).replace(".", "")) * BigInt(line.quantity)
|
||||
);
|
||||
}, 0n);
|
||||
return `${total / 100n}.${(total % 100n).toString().padStart(2, "0")}`;
|
||||
}
|
||||
export const orderSummary = z.object({
|
||||
id: uuid,
|
||||
status: z.enum(["PENDING_PAYMENT", "CANCELLED", "EXPIRED"]),
|
||||
currency,
|
||||
merchandiseTotal: decimal,
|
||||
createdAt: z.string(),
|
||||
expiresAt: z.string(),
|
||||
});
|
||||
export const order = orderSummary.extend({
|
||||
subtotal: decimal,
|
||||
discount: decimal,
|
||||
pricingStatus: z.enum(["FINALIZED", "UNFINALIZED"]),
|
||||
taxTotal: decimal.nullable(),
|
||||
shippingTotal: decimal.nullable(),
|
||||
payableTotal: decimal.nullable(),
|
||||
paymentAvailable: z.literal(false),
|
||||
address: addressInput.omit({ isDefault: true }).strip(),
|
||||
lines: z.array(
|
||||
z.object({
|
||||
variantId: uuid,
|
||||
sku: z.string(),
|
||||
productName: z.string(),
|
||||
variantName: z.string(),
|
||||
quantity: z.number().int(),
|
||||
unitPrice: decimal,
|
||||
lineTotal: decimal,
|
||||
}),
|
||||
),
|
||||
});
|
||||
export type Order = z.infer<typeof order>;
|
||||
export const productInput = z
|
||||
.object({
|
||||
name: text(160),
|
||||
slug: text(160).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
|
||||
description: text(5000, 0),
|
||||
groupIds: z
|
||||
.array(uuid)
|
||||
.max(20)
|
||||
.refine((v) => new Set(v).size === v.length),
|
||||
})
|
||||
.strict();
|
||||
export const groupInput = z
|
||||
.object({
|
||||
name: text(100),
|
||||
slug: text(100).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
|
||||
kind: z.enum(["CATEGORY", "COLLECTION"]),
|
||||
})
|
||||
.strict();
|
||||
export const group = groupInput.extend({ id: uuid }).strip();
|
||||
export const variantInput = z
|
||||
.object({
|
||||
sku: text(64)
|
||||
.toUpperCase()
|
||||
.regex(/^[A-Z0-9][A-Z0-9_-]*$/),
|
||||
name: text(160),
|
||||
price: amount.refine((v) => v !== "0.00"),
|
||||
currency,
|
||||
active: z.boolean(),
|
||||
attributes: z
|
||||
.record(
|
||||
z
|
||||
.string()
|
||||
.regex(/^[a-z][a-z0-9_]{0,31}$/)
|
||||
.refine((v) => !["constructor", "prototype"].includes(v)),
|
||||
text(100),
|
||||
)
|
||||
.refine((v) => Object.keys(v).length <= 20),
|
||||
})
|
||||
.strict();
|
||||
export const variant = variantInput
|
||||
.extend({ id: uuid, price: decimal })
|
||||
.strip();
|
||||
export const adminProductSummary = productInput
|
||||
.pick({ name: true, slug: true })
|
||||
.extend({ id: uuid, status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]) })
|
||||
.strip();
|
||||
export const 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({
|
||||
description: z.string(),
|
||||
images: z.array(productImage).default([]),
|
||||
variants: z.array(variant),
|
||||
groups: z.array(z.object({ group })),
|
||||
});
|
||||
export type AdminProduct = z.infer<typeof adminProduct>;
|
||||
export const userInput = z
|
||||
.object({
|
||||
name: text(160),
|
||||
email: z.string().email().max(254).toLowerCase(),
|
||||
password: z.string().min(15).max(128),
|
||||
})
|
||||
.strict();
|
||||
export const user = userInput.omit({ password: true }).extend({
|
||||
id: uuid,
|
||||
status: z.enum(["PENDING", "ACTIVE", "SUSPENDED"]),
|
||||
isOwner: z.boolean(),
|
||||
createdAt: z.string(),
|
||||
});
|
||||
export const roleInput = z
|
||||
.object({
|
||||
name: text(80),
|
||||
permissions: z
|
||||
.array(z.string())
|
||||
.refine((v) => new Set(v).size === v.length),
|
||||
})
|
||||
.strict();
|
||||
export const role = roleInput
|
||||
.extend({ id: uuid, isSystem: z.boolean() })
|
||||
.strip();
|
||||
export const audit = z.object({
|
||||
id: uuid,
|
||||
actorId: uuid.nullable(),
|
||||
action: z.string(),
|
||||
targetId: z.string().nullable(),
|
||||
createdAt: z.string(),
|
||||
});
|
||||
export const warehouseInput = z.object({ name: text(100) }).strict();
|
||||
export const warehouse = warehouseInput.extend({ id: uuid }).strip();
|
||||
export const stockInput = z
|
||||
.object({ variantId: uuid, warehouseId: uuid })
|
||||
.strict();
|
||||
export const stock = stockInput
|
||||
.extend({ id: uuid, onHand: z.number().int() })
|
||||
.strip();
|
||||
export const stockDetail = stock.extend({
|
||||
reserved: z.number().int(),
|
||||
available: z.number().int(),
|
||||
});
|
||||
export const adjustmentInput = z
|
||||
.object({
|
||||
stockItemId: uuid,
|
||||
delta: z
|
||||
.number()
|
||||
.int()
|
||||
.min(-1000000)
|
||||
.max(1000000)
|
||||
.refine((v) => v !== 0),
|
||||
reason: text(200),
|
||||
idempotencyKey: uuid,
|
||||
})
|
||||
.strict();
|
||||
export const ledger = z.object({
|
||||
id: uuid,
|
||||
delta: z.number().int(),
|
||||
reason: z.string(),
|
||||
createdAt: z.string(),
|
||||
});
|
||||
export const reservationInput = z
|
||||
.object({
|
||||
stockItemId: uuid,
|
||||
quantity: z.number().int().min(1).max(1000000),
|
||||
ttlMinutes: z.number().int().min(1).max(60),
|
||||
idempotencyKey: uuid,
|
||||
})
|
||||
.strict();
|
||||
export const reservation = z.object({
|
||||
id: uuid,
|
||||
orderId: uuid.nullable().optional(),
|
||||
stockItemId: uuid,
|
||||
quantity: z.number().int(),
|
||||
status: z.enum(["ACTIVE", "RELEASED", "COMMITTED", "EXPIRED"]),
|
||||
expiresAt: z.string(),
|
||||
});
|
||||
const couponCommon = z.object({
|
||||
code: couponCode,
|
||||
currency,
|
||||
minimumSubtotal: amount,
|
||||
maxUses: z.number().int().min(1).max(1000000),
|
||||
perUserLimit: z.number().int().min(1).max(100),
|
||||
startsAt: z.string().datetime({ offset: true }),
|
||||
endsAt: z.string().datetime({ offset: true }),
|
||||
});
|
||||
export const couponInput = z
|
||||
.discriminatedUnion("kind", [
|
||||
couponCommon
|
||||
.extend({
|
||||
kind: z.literal("FIXED"),
|
||||
amount: amount.refine((v) => v !== "0.00"),
|
||||
})
|
||||
.strict(),
|
||||
couponCommon
|
||||
.extend({
|
||||
kind: z.literal("PERCENT"),
|
||||
percentBps: z.number().int().min(1).max(10000),
|
||||
})
|
||||
.strict(),
|
||||
])
|
||||
.refine((v) => Date.parse(v.endsAt) > Date.parse(v.startsAt), {
|
||||
path: ["endsAt"],
|
||||
message: "End must follow start",
|
||||
})
|
||||
.refine((v) => v.perUserLimit <= v.maxUses, {
|
||||
path: ["perUserLimit"],
|
||||
message: "Per-user limit exceeds total limit",
|
||||
});
|
||||
export const coupon = z.object({
|
||||
id: uuid,
|
||||
code: z.string(),
|
||||
currency,
|
||||
kind: z.enum(["FIXED", "PERCENT"]),
|
||||
amount: decimal.nullable(),
|
||||
percentBps: z.number().nullable(),
|
||||
minimumSubtotal: decimal,
|
||||
maxUses: z.number(),
|
||||
perUserLimit: z.number(),
|
||||
active: z.boolean(),
|
||||
startsAt: z.string(),
|
||||
endsAt: z.string(),
|
||||
});
|
||||
export const pricingInput = z
|
||||
.object({
|
||||
name: text(100),
|
||||
currency,
|
||||
countryCode: z
|
||||
.string()
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
.regex(/^[A-Z]{2}$/),
|
||||
region: text(100, 0).toUpperCase(),
|
||||
taxMode: z.enum(["INCLUSIVE", "EXCLUSIVE"]),
|
||||
merchandiseTaxBps: z.number().int().min(0).max(10000),
|
||||
shippingFee: amount,
|
||||
shippingTaxBps: z.number().int().min(0).max(10000),
|
||||
freeShippingMinimum: amount.nullable(),
|
||||
})
|
||||
.strict();
|
||||
export const pricing = pricingInput
|
||||
.extend({
|
||||
id: uuid,
|
||||
active: z.boolean(),
|
||||
shippingFee: decimal,
|
||||
freeShippingMinimum: decimal.nullable(),
|
||||
})
|
||||
.strip();
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { bomKind } from "./bom.ts";
|
||||
import { currency, uuid } from "./commerce.ts";
|
||||
import { materialInput } from "./procurement.ts";
|
||||
|
||||
const cents = z.string().regex(/^\d{1,10}\.\d{2}$/);
|
||||
const quantity = z.string().regex(/^\d{1,9}\.\d{3}$/);
|
||||
const rateRevision = z.number().int().min(1).max(1000);
|
||||
const timestamp = z.string().datetime();
|
||||
|
||||
export const costRateInput = z.object({
|
||||
currency,
|
||||
unitCost: z.string().regex(/^(0|[1-9]\d{0,7})\.\d{4}$/, "Use four decimal places")
|
||||
.refine((value) => value !== "0.0000", "Unit cost must be positive"),
|
||||
}).strict();
|
||||
|
||||
export const costRate = z.object({
|
||||
id: uuid,
|
||||
materialId: uuid,
|
||||
currency,
|
||||
revision: rateRevision,
|
||||
unitCost: z.string().regex(/^\d{1,8}(\.\d{1,4})?$/),
|
||||
createdAt: timestamp,
|
||||
});
|
||||
|
||||
const costLine = z.object({
|
||||
bomLineId: uuid,
|
||||
materialId: uuid,
|
||||
materialCode: z.string(),
|
||||
materialName: z.string(),
|
||||
unit: materialInput.shape.unit,
|
||||
rateId: uuid,
|
||||
rateRevision,
|
||||
unitCost: costRateInput.shape.unitCost,
|
||||
});
|
||||
|
||||
export const bomEstimate = z.object({
|
||||
bomId: uuid,
|
||||
kind: bomKind,
|
||||
currency,
|
||||
outputQuantity: z.number().int().positive(),
|
||||
estimatedAt: timestamp,
|
||||
estimatedTotal: cents,
|
||||
lines: z.array(costLine.extend({ quantity, estimatedCost: cents })),
|
||||
});
|
||||
|
||||
export const snapshotInput = z.object({ currency, idempotencyKey: uuid }).strict();
|
||||
export const batchSnapshot = z.object({
|
||||
id: uuid,
|
||||
batchId: uuid,
|
||||
currency,
|
||||
goodQuantity: z.number().int().min(0).max(100000),
|
||||
createdAt: timestamp,
|
||||
productionTotal: cents,
|
||||
packagingTotal: cents,
|
||||
total: cents,
|
||||
lines: z.array(costLine.extend({
|
||||
kind: bomKind,
|
||||
usedQuantity: quantity,
|
||||
wastedQuantity: quantity,
|
||||
lineCost: cents,
|
||||
})),
|
||||
});
|
||||
|
||||
export const costCurrencies = currency.options.map((value) => ({ value, label: value }));
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { currency, uuid } from "./commerce.ts";
|
||||
|
||||
const note = z.string().trim().min(3).max(500).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
|
||||
export const creditStatus = z.enum(["PROPOSED", "ACTIVE", "REJECTED", "SUSPENDED"]);
|
||||
export const creditDecision = z.enum(["APPROVED", "REJECTED"]);
|
||||
|
||||
const terms = z.object({
|
||||
accountId: uuid,
|
||||
currency,
|
||||
creditLimit: z.string().regex(/^(0|[1-9]\d{0,13})\.\d{2}$/, "Use exactly two decimal places")
|
||||
.refine((value) => value !== "0.00", "Enter a positive credit limit"),
|
||||
netDays: z.number().int().min(1).max(180),
|
||||
rationale: note,
|
||||
});
|
||||
export const creditProposalInput = terms.extend({ idempotencyKey: uuid }).strict();
|
||||
export const creditSuspensionInput = z.object({ note, idempotencyKey: uuid }).strict();
|
||||
export const creditDecisionInput = creditSuspensionInput.extend({ decision: creditDecision });
|
||||
|
||||
export const creditPolicy = terms.extend({
|
||||
id: uuid,
|
||||
proposedById: uuid,
|
||||
status: creditStatus,
|
||||
createdAt: z.string().datetime(),
|
||||
events: z.array(z.object({
|
||||
id: uuid,
|
||||
actorId: uuid,
|
||||
kind: z.enum([...creditDecision.options, "SUSPENDED"]),
|
||||
sequence: z.number().int().min(1).max(2),
|
||||
note,
|
||||
createdAt: z.string().datetime(),
|
||||
})),
|
||||
});
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { uuid, warehouse } from "./commerce.ts";
|
||||
import { material } from "./procurement.ts";
|
||||
|
||||
const quantity = z.string().regex(/^\d{1,9}\.\d{3}$/);
|
||||
const positiveQuantity = quantity.refine((value) => value !== "0.000");
|
||||
const signedQuantity = z.string().regex(/^-?\d{1,9}\.\d{3}$/);
|
||||
|
||||
export const receiptPostingInput = z.object({
|
||||
warehouseId: uuid,
|
||||
idempotencyKey: uuid,
|
||||
}).strict();
|
||||
|
||||
export const receiptPosting = z.object({
|
||||
id: uuid,
|
||||
receiptId: uuid,
|
||||
warehouseId: uuid,
|
||||
createdAt: z.string().datetime(),
|
||||
entries: z.array(z.object({
|
||||
id: uuid,
|
||||
stockItemId: uuid,
|
||||
receiptLineId: uuid,
|
||||
kind: z.literal("RECEIPT_ACCEPTED"),
|
||||
delta: quantity.refine((value) => value !== "0.000"),
|
||||
})),
|
||||
});
|
||||
|
||||
export const materialStockItem = z.object({
|
||||
id: uuid,
|
||||
warehouse,
|
||||
material,
|
||||
onHand: quantity,
|
||||
});
|
||||
|
||||
export const materialStockEntry = z.object({
|
||||
id: uuid,
|
||||
kind: z.string(),
|
||||
delta: signedQuantity,
|
||||
createdAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
const transferFields = z.object({
|
||||
materialId: uuid,
|
||||
fromWarehouseId: uuid,
|
||||
toWarehouseId: uuid,
|
||||
});
|
||||
export const materialTransferInput = transferFields.extend({
|
||||
quantity: z.string().regex(/^(?:0|[1-9]\d{0,8})\.\d{3}$/, "Use three decimal places")
|
||||
.refine((value) => value !== "0.000", "Enter a positive quantity"),
|
||||
idempotencyKey: uuid,
|
||||
}).strict().refine((value) => value.fromWarehouseId !== value.toWarehouseId, {
|
||||
path: ["toWarehouseId"],
|
||||
message: "Choose a different destination warehouse.",
|
||||
});
|
||||
|
||||
export const materialTransfer = transferFields.extend({
|
||||
id: uuid,
|
||||
fromStockItemId: uuid,
|
||||
toStockItemId: uuid,
|
||||
quantity: positiveQuantity,
|
||||
createdAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const materialAdjustmentInput = z.object({
|
||||
materialId: uuid,
|
||||
warehouseId: uuid,
|
||||
delta: z.string().regex(/^-?(?:0|[1-9]\d{0,8})\.\d{3}$/, "Use three decimal places and a minus sign for decreases")
|
||||
.refine((value) => value !== "0.000" && value !== "-0.000", "Enter a nonzero change"),
|
||||
reason: z.string().trim().min(3).max(200),
|
||||
idempotencyKey: uuid,
|
||||
}).strict();
|
||||
|
||||
export const materialAdjustment = materialAdjustmentInput.omit({ idempotencyKey: true }).extend({
|
||||
id: uuid,
|
||||
stockItemId: uuid,
|
||||
createdAt: z.string().datetime(),
|
||||
}).strip();
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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),
|
||||
});
|
||||
|
|
@ -1,50 +1,28 @@
|
|||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
apiRequest,
|
||||
apiArtwork,
|
||||
apiPdf,
|
||||
ApiError,
|
||||
getPrincipal,
|
||||
login,
|
||||
organizationSchema,
|
||||
parse,
|
||||
register,
|
||||
type Principal,
|
||||
type Session,
|
||||
} from "./api";
|
||||
|
||||
type Options = { method?: string; body?: unknown; signal?: AbortSignal };
|
||||
const PlatformContext = createContext<{
|
||||
organization: string;
|
||||
setOrganization: (value: string) => void;
|
||||
principal: Principal | null;
|
||||
scope: string;
|
||||
signIn: (email: string, password: string) => Promise<void>;
|
||||
signUp: (name: string, email: string, password: string) => Promise<void>;
|
||||
signOut: () => Promise<void>;
|
||||
notice: string;
|
||||
clearSession: (notice?: string) => void;
|
||||
getIntent: (key: string) => unknown;
|
||||
saveIntent: (key: string, value: unknown) => void;
|
||||
clearIntent: (key: string, idempotencyKey: string) => void;
|
||||
can: (permission: string) => boolean;
|
||||
downloadPdf: (versionId: string, size: number) => Promise<Blob>;
|
||||
downloadArtwork: (versionId: string, size: number, mimeType: string) => Promise<Blob>;
|
||||
request: <T>(
|
||||
path: string,
|
||||
schema: z.ZodType<T>,
|
||||
options?: Options,
|
||||
) => Promise<T>;
|
||||
} | null>(null);
|
||||
function initialOrganization() {
|
||||
let value = import.meta.env.VITE_ORGANIZATION_ID || "";
|
||||
|
|
@ -53,86 +31,54 @@ function initialOrganization() {
|
|||
} catch {
|
||||
/* Storage can be disabled. */
|
||||
}
|
||||
const parsed = organizationSchema.safeParse(value);
|
||||
return parsed.success ? parsed.data : "";
|
||||
return organizationSchema.safeParse(value).success ? value : "";
|
||||
}
|
||||
export function PlatformProvider({ children }: { children: ReactNode }) {
|
||||
const client = useQueryClient();
|
||||
const [organization, updateOrganization] = useState(initialOrganization);
|
||||
const [session, setSession] = useState<Session | null>(null);
|
||||
const [principal, setPrincipal] = useState<Principal | null>(null);
|
||||
const [notice, setNotice] = useState("");
|
||||
const [accessRevision, setAccessRevision] = useState(0);
|
||||
const revision = useRef(0),
|
||||
intents = useRef(new Map<string, unknown>());
|
||||
const current = useRef<Session | null>(null),
|
||||
generation = useRef(0),
|
||||
scopeAbort = useRef(new AbortController());
|
||||
const clearSession = useCallback(
|
||||
(message = "") => {
|
||||
generation.current += 1;
|
||||
current.current = null;
|
||||
revision.current += 1;
|
||||
setAccessRevision(revision.current);
|
||||
intents.current.clear();
|
||||
scopeAbort.current.abort();
|
||||
scopeAbort.current = new AbortController();
|
||||
void client.cancelQueries({ queryKey: ["private"] });
|
||||
client.removeQueries({ queryKey: ["private"] });
|
||||
client.getMutationCache().clear();
|
||||
setSession(null);
|
||||
setPrincipal(null);
|
||||
setNotice(message);
|
||||
},
|
||||
[client],
|
||||
);
|
||||
const loginVersion = useRef(0);
|
||||
useEffect(() => {
|
||||
if (!session) return;
|
||||
const timer = setTimeout(
|
||||
() => clearSession("Your session expired. Sign in again."),
|
||||
() => {
|
||||
setSession(null);
|
||||
setPrincipal(null);
|
||||
setNotice("Your session expired. Sign in again.");
|
||||
},
|
||||
Math.max(0, Date.parse(session.expiresAt) - Date.now()),
|
||||
);
|
||||
return () => clearTimeout(timer);
|
||||
}, [session, clearSession]);
|
||||
useEffect(() => {
|
||||
scopeAbort.current = new AbortController();
|
||||
return () => {
|
||||
generation.current += 1;
|
||||
scopeAbort.current.abort();
|
||||
};
|
||||
}, []);
|
||||
}, [session]);
|
||||
function setOrganization(value: string) {
|
||||
const normalized = organizationSchema.parse(value);
|
||||
if (normalized !== organization) clearSession();
|
||||
updateOrganization(normalized);
|
||||
organizationSchema.parse(value);
|
||||
if (value !== organization) {
|
||||
loginVersion.current += 1;
|
||||
setSession(null);
|
||||
setPrincipal(null);
|
||||
}
|
||||
updateOrganization(value);
|
||||
setNotice("");
|
||||
try {
|
||||
localStorage.setItem("mani.organization", normalized);
|
||||
localStorage.setItem("mani.organization", value);
|
||||
} catch {
|
||||
/* The in-memory setting still works. */
|
||||
}
|
||||
}
|
||||
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 next = await start();
|
||||
async function signIn(email: string, password: string) {
|
||||
const version = ++loginVersion.current;
|
||||
const next = await login(organization, email, password);
|
||||
try {
|
||||
const me = await getPrincipal(next.accessToken);
|
||||
if (
|
||||
version !== generation.current ||
|
||||
me.organizationId !== organization ||
|
||||
Date.parse(next.expiresAt) <= Date.now()
|
||||
)
|
||||
if (version !== loginVersion.current)
|
||||
throw new Error(
|
||||
"The session changed during sign-in. Please try again.",
|
||||
"The connection changed during sign-in. Please try again.",
|
||||
);
|
||||
if (me.organizationId !== organization)
|
||||
throw new Error(
|
||||
"The session organization does not match the configured organization.",
|
||||
);
|
||||
clearSession();
|
||||
current.current = next;
|
||||
setSession(next);
|
||||
setPrincipal(me);
|
||||
setNotice("");
|
||||
|
|
@ -140,112 +86,24 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
|
|||
await apiRequest("/auth/logout", {
|
||||
method: "POST",
|
||||
token: next.accessToken,
|
||||
}).catch(() => {
|
||||
/* Best-effort revoke; this token is never retained locally. */
|
||||
});
|
||||
}).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async function signOut() {
|
||||
const previous = current.current;
|
||||
clearSession();
|
||||
if (!previous) return;
|
||||
loginVersion.current += 1;
|
||||
if (!session) return;
|
||||
try {
|
||||
await apiRequest("/auth/logout", {
|
||||
method: "POST",
|
||||
token: previous.accessToken,
|
||||
token: session.accessToken,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 401) return;
|
||||
throw new Error(
|
||||
"You are signed out locally, but server revocation could not be confirmed. The server session will expire automatically.",
|
||||
);
|
||||
if (!(error instanceof ApiError && error.status === 401)) throw error;
|
||||
}
|
||||
}
|
||||
async function withSession<T>(
|
||||
perform: (token: string, signal: AbortSignal) => Promise<T>,
|
||||
callerSignal?: AbortSignal,
|
||||
) {
|
||||
const active = session;
|
||||
if (
|
||||
!active ||
|
||||
current.current !== active ||
|
||||
revision.current !== accessRevision
|
||||
)
|
||||
throw new ApiError("Sign in to continue.", 401, "SESSION_CHANGED");
|
||||
if (Date.parse(active.expiresAt) <= Date.now()) {
|
||||
clearSession("Your session expired. Sign in again.");
|
||||
throw new ApiError("Your session expired.", 401, "SESSION_EXPIRED");
|
||||
}
|
||||
const signal = callerSignal
|
||||
? AbortSignal.any([scopeAbort.current.signal, callerSignal])
|
||||
: scopeAbort.current.signal;
|
||||
try {
|
||||
const data = await perform(active.accessToken, signal);
|
||||
if (current.current !== active || revision.current !== accessRevision)
|
||||
throw new ApiError(
|
||||
"Your session changed. Sign in again.",
|
||||
401,
|
||||
"SESSION_CHANGED",
|
||||
);
|
||||
return data;
|
||||
} catch (error) {
|
||||
if (
|
||||
current.current === active &&
|
||||
revision.current === accessRevision &&
|
||||
error instanceof ApiError
|
||||
) {
|
||||
if (error.status === 401)
|
||||
clearSession("Your session is no longer valid. Sign in again.");
|
||||
else if (error.status === 403) {
|
||||
try {
|
||||
const me = await getPrincipal(active.accessToken);
|
||||
if (
|
||||
current.current === active &&
|
||||
revision.current === accessRevision
|
||||
) {
|
||||
if (
|
||||
me.permissions.length !== principal?.permissions.length ||
|
||||
me.permissions.some(
|
||||
(permission) => !principal?.permissions.includes(permission),
|
||||
)
|
||||
) {
|
||||
scopeAbort.current.abort();
|
||||
scopeAbort.current = new AbortController();
|
||||
revision.current += 1;
|
||||
setAccessRevision(revision.current);
|
||||
void client.cancelQueries({ queryKey: ["private"] });
|
||||
client.removeQueries({ queryKey: ["private"] });
|
||||
client.getMutationCache().clear();
|
||||
}
|
||||
setPrincipal(me);
|
||||
}
|
||||
} catch (refresh) {
|
||||
if (
|
||||
current.current === active &&
|
||||
refresh instanceof ApiError &&
|
||||
refresh.status === 401
|
||||
)
|
||||
clearSession("Your session is no longer valid. Sign in again.");
|
||||
}
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async function request<T>(path: string, schema: z.ZodType<T>, options: Options = {}) {
|
||||
const data = await withSession(
|
||||
(token, signal) => apiRequest(path, { ...options, token, signal }),
|
||||
options.signal,
|
||||
);
|
||||
return parse(schema, data);
|
||||
}
|
||||
function downloadPdf(versionId: string, size: number) {
|
||||
const id = z.string().uuid().parse(versionId);
|
||||
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));
|
||||
setSession(null);
|
||||
setPrincipal(null);
|
||||
setNotice("");
|
||||
}
|
||||
return (
|
||||
<PlatformContext.Provider
|
||||
|
|
@ -253,37 +111,9 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
|
|||
organization,
|
||||
setOrganization,
|
||||
principal,
|
||||
scope: principal ? `${principal.sessionId}:${accessRevision}` : "",
|
||||
signIn,
|
||||
signUp,
|
||||
signOut,
|
||||
notice,
|
||||
clearSession,
|
||||
getIntent: (key) =>
|
||||
session && current.current === session
|
||||
? intents.current.get(key)
|
||||
: undefined,
|
||||
saveIntent: (key, value) => {
|
||||
if (session && current.current === session)
|
||||
intents.current.set(key, value);
|
||||
},
|
||||
clearIntent: (key, idempotencyKey) => {
|
||||
const stored = intents.current.get(key);
|
||||
if (
|
||||
session &&
|
||||
current.current === session &&
|
||||
typeof stored === "object" &&
|
||||
stored !== null &&
|
||||
"idempotencyKey" in stored &&
|
||||
stored.idempotencyKey === idempotencyKey
|
||||
)
|
||||
intents.current.delete(key);
|
||||
},
|
||||
can: (permission) =>
|
||||
Boolean(principal?.permissions.includes(permission)),
|
||||
downloadPdf,
|
||||
downloadArtwork,
|
||||
request,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
|
|
|||
|
|
@ -1,39 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { currency, uuid } from "./commerce.ts";
|
||||
|
||||
const units = z.number().int().min(1).max(1_000_000);
|
||||
const cents = z.string().regex(/^\d+\.\d{2}$/);
|
||||
export const priceListStatus = z.enum(["DRAFT", "ACTIVE", "ARCHIVED"]);
|
||||
export const priceListInput = z.object({
|
||||
name: z.string().trim().min(1).max(100).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text"),
|
||||
currency,
|
||||
}).strict();
|
||||
export const priceList = priceListInput.extend({ id: uuid, accountId: uuid, status: priceListStatus }).strip();
|
||||
|
||||
export const priceTermsInput = z.object({
|
||||
unitPrice: z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/, "Use exactly two decimal places")
|
||||
.refine((price) => price !== "0.00", "Enter a positive price"),
|
||||
minQuantity: units,
|
||||
}).strict();
|
||||
export const priceListItem = priceTermsInput.extend({
|
||||
id: uuid,
|
||||
variantId: uuid,
|
||||
unitPrice: z.string().regex(/^\d{1,10}(\.\d{1,2})?$/),
|
||||
}).strip();
|
||||
export const priceListDetail = priceList.extend({ items: z.array(priceListItem) });
|
||||
|
||||
const requestedLine = z.object({ variantId: uuid, quantity: units }).strict();
|
||||
export const priceCheckInput = z.object({
|
||||
lines: z.array(requestedLine).min(1, "Enter a quantity for at least one variant").max(100)
|
||||
.refine((lines) => new Set(lines.map((line) => line.variantId)).size === lines.length, "Use each variant once."),
|
||||
}).strict();
|
||||
export const priceCheck = z.object({
|
||||
priceListId: uuid,
|
||||
currency,
|
||||
merchandiseTotal: cents,
|
||||
lines: z.array(requestedLine.extend({
|
||||
minQuantity: units,
|
||||
unitPrice: cents,
|
||||
lineTotal: cents,
|
||||
})),
|
||||
});
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { currency, uuid } from "./commerce.ts";
|
||||
|
||||
const plainText = (max: number, min = 1) =>
|
||||
z.string().trim().min(min).max(max).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
|
||||
const directoryInput = z.object({
|
||||
name: plainText(160),
|
||||
code: z.string().trim().toUpperCase().max(32).regex(/^[A-Z0-9][A-Z0-9_-]*$/, "Use letters, numbers, hyphens or underscores"),
|
||||
active: z.boolean(),
|
||||
});
|
||||
export const supplierInput = directoryInput.extend({
|
||||
contactName: plainText(160),
|
||||
email: z.string().email().max(254).toLowerCase(),
|
||||
phone: z.string().trim().regex(/^\+?[0-9 ()-]{7,24}$/, "Enter a valid phone number").max(24),
|
||||
}).strict();
|
||||
export const materialInput = directoryInput.extend({
|
||||
kind: z.enum(["WAX", "FRAGRANCE", "WICK", "DYE", "VESSEL", "PACKAGING", "LABEL", "OTHER"]),
|
||||
unit: z.enum(["GRAM", "KILOGRAM", "MILLILITRE", "LITRE", "PIECE", "METRE"]),
|
||||
}).strict();
|
||||
export const supplier = supplierInput.extend({ id: uuid }).strip();
|
||||
export const material = materialInput.extend({ id: uuid }).strip();
|
||||
|
||||
const fixedQuantity = z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Enter exactly three decimal places");
|
||||
const quantity = fixedQuantity.refine((value) => value !== "0.000", "Quantity must be positive");
|
||||
export const supplyTermsInput = z.object({
|
||||
supplierSku: plainText(64, 0),
|
||||
leadTimeDays: z.number().int().min(0).max(365),
|
||||
minOrderQuantity: quantity,
|
||||
unitPrice: z.string().regex(/^(0|[1-9]\d{0,8})\.\d{2}$/, "Enter exactly two decimal places"),
|
||||
currency,
|
||||
active: z.boolean(),
|
||||
}).strict();
|
||||
|
||||
// Prisma serializes Decimal values without trailing zeroes.
|
||||
const decimalResponse = z.string().regex(/^\d+(\.\d+)?$/);
|
||||
export const supplyTerms = supplyTermsInput.extend({
|
||||
id: uuid,
|
||||
materialId: uuid,
|
||||
minOrderQuantity: decimalResponse,
|
||||
unitPrice: decimalResponse,
|
||||
}).strip();
|
||||
export const supplierMaterial = supplyTerms.extend({ material });
|
||||
|
||||
export const purchaseOrderInput = z.object({
|
||||
supplierId: uuid,
|
||||
expectedDeliveryDate: z.string().date().optional(),
|
||||
lines: z.array(z.object({ materialId: uuid, quantity }).strict()).min(1, "Enter a quantity for at least one material").max(100).refine(
|
||||
(lines) => new Set(lines.map((line) => line.materialId)).size === lines.length,
|
||||
"Select each material once",
|
||||
),
|
||||
}).strict();
|
||||
|
||||
export const purchaseOrder = z.object({
|
||||
id: uuid,
|
||||
reference: z.string(),
|
||||
status: z.enum(["DRAFT", "ISSUED", "CANCELLED"]),
|
||||
currency,
|
||||
supplier: supplier.pick({ id: true, name: true }),
|
||||
expectedDeliveryAt: z.string().datetime().nullable(),
|
||||
merchandiseTotal: decimalResponse,
|
||||
lines: z.array(z.object({
|
||||
id: uuid,
|
||||
materialName: z.string(),
|
||||
materialCode: z.string(),
|
||||
quantity: decimalResponse,
|
||||
unit: materialInput.shape.unit,
|
||||
unitPrice: decimalResponse,
|
||||
lineTotal: decimalResponse,
|
||||
})),
|
||||
});
|
||||
|
||||
export const receiptInput = z.object({
|
||||
deliveryNote: z.string().trim().min(1).max(80).optional(),
|
||||
lines: z.array(z.object({ purchaseOrderLineId: uuid, quantity }).strict()).min(1).max(100)
|
||||
.refine((lines) => new Set(lines.map((line) => line.purchaseOrderLineId)).size === lines.length),
|
||||
}).strict();
|
||||
|
||||
const inspection = z.object({
|
||||
acceptedQuantity: decimalResponse,
|
||||
rejectedQuantity: decimalResponse,
|
||||
rejectionReason: z.string().nullable(),
|
||||
});
|
||||
|
||||
export const goodsReceipt = z.object({
|
||||
id: uuid,
|
||||
deliveryNote: z.string().nullable(),
|
||||
createdAt: z.string().datetime(),
|
||||
lines: z.array(z.object({
|
||||
id: uuid,
|
||||
purchaseOrderLineId: uuid,
|
||||
quantity: z.string().regex(/^\d+(\.\d{1,3})?$/),
|
||||
inspection: inspection.nullable(),
|
||||
})).min(1),
|
||||
});
|
||||
|
||||
const inspectionInput = z.object({
|
||||
lines: z.array(z.object({
|
||||
receiptLineId: uuid,
|
||||
acceptedQuantity: fixedQuantity,
|
||||
rejectedQuantity: fixedQuantity,
|
||||
rejectionReason: z.string().trim().min(1).max(500).optional(),
|
||||
}).strict()).min(1).max(100),
|
||||
}).strict();
|
||||
|
||||
const thousandths = (value: string) => {
|
||||
const [whole, fraction = ""] = value.split(".");
|
||||
return BigInt(whole + fraction.padEnd(3, "0"));
|
||||
};
|
||||
|
||||
export function parseInspection(value: unknown, receipt: z.infer<typeof goodsReceipt>) {
|
||||
const input = inspectionInput.parse(value);
|
||||
const received = new Map(receipt.lines.map((line) => [line.id, line.quantity]));
|
||||
if (input.lines.length !== received.size || new Set(input.lines.map((line) => line.receiptLineId)).size !== received.size) {
|
||||
throw new Error("Enter one decision for each receipt line.");
|
||||
}
|
||||
for (const line of input.lines) {
|
||||
const delivered = received.get(line.receiptLineId);
|
||||
if (!delivered || thousandths(line.acceptedQuantity) + thousandths(line.rejectedQuantity) !== thousandths(delivered)) {
|
||||
throw new Error("Accepted and rejected quantities must add up to the delivered quantity on each line.");
|
||||
}
|
||||
if (line.rejectedQuantity !== "0.000" && !line.rejectionReason) {
|
||||
throw new Error("Enter a rejection reason for each rejected quantity.");
|
||||
}
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { uuid } from "./commerce.ts";
|
||||
import { bomDetail } from "./bom.ts";
|
||||
|
||||
const quantity = z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Use three decimal places");
|
||||
const signedQuantity = z.string().regex(/^-?\d+\.\d{3}$/);
|
||||
const packagingLine = z.object({
|
||||
bomLineId: uuid,
|
||||
usedQuantity: quantity,
|
||||
wastedQuantity: quantity,
|
||||
wasteReason: z.string().trim().min(1).max(500).optional(),
|
||||
}).strict().refine((line) => line.wastedQuantity === "0.000" || Boolean(line.wasteReason), {
|
||||
path: ["wasteReason"],
|
||||
message: "Enter a reason for wasted material.",
|
||||
});
|
||||
|
||||
export const packagingRunInput = z.object({
|
||||
bomId: uuid,
|
||||
idempotencyKey: uuid,
|
||||
lines: z.array(packagingLine).min(1).max(100)
|
||||
.refine((lines) => new Set(lines.map((line) => line.bomLineId)).size === lines.length, "Record each material once."),
|
||||
}).strict();
|
||||
|
||||
const record = z.object({
|
||||
id: uuid,
|
||||
batchId: uuid,
|
||||
createdAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const packagingRun = record.extend({
|
||||
bomId: uuid,
|
||||
lines: z.array(z.object({
|
||||
bomLineId: uuid,
|
||||
materialId: uuid,
|
||||
materialName: z.string(),
|
||||
materialCode: z.string(),
|
||||
unit: bomDetail.shape.lines.element.shape.unit,
|
||||
plannedQuantity: quantity,
|
||||
usedQuantity: quantity,
|
||||
wastedQuantity: quantity,
|
||||
varianceQuantity: signedQuantity,
|
||||
wasteReason: z.string().nullable(),
|
||||
})),
|
||||
});
|
||||
|
||||
const stockMovement = record.extend({ warehouseId: uuid });
|
||||
const debit = z.object({
|
||||
id: uuid,
|
||||
materialId: uuid,
|
||||
stockItemId: uuid,
|
||||
delta: signedQuantity.refine((value) => value.startsWith("-") && value !== "-0.000"),
|
||||
});
|
||||
export const productionDebit = stockMovement.extend({
|
||||
entries: z.array(debit.extend({ kind: z.enum(["PRODUCTION_CONSUMED", "PRODUCTION_WASTED"]) })),
|
||||
});
|
||||
export const packagingDebit = stockMovement.extend({
|
||||
entries: z.array(debit.extend({ kind: z.enum(["PACKAGING_USED", "PACKAGING_WASTED"]) })),
|
||||
});
|
||||
export const finishedGoodsReceipt = stockMovement.extend({
|
||||
variantId: uuid,
|
||||
stockItemId: uuid,
|
||||
ledgerEntryId: uuid,
|
||||
quantity: z.number().int().min(1).max(100000),
|
||||
});
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { bomDetail, bomSummary } from "./bom.ts";
|
||||
import { uuid } from "./commerce.ts";
|
||||
|
||||
const reason = z.string().trim().min(1).max(500);
|
||||
const output = z.number().int().min(0).max(100000);
|
||||
const decimal = z.string().regex(/^\d+(\.\d{1,3})?$/);
|
||||
const exactTotal = z.string().regex(/^\d+\.\d{3}$/);
|
||||
const materialLine = bomDetail.shape.lines.element;
|
||||
|
||||
export const batchStatus = z.enum(["DRAFT", "IN_PROGRESS", "COMPLETED", "CANCELLED"]);
|
||||
export const batchInput = z.object({
|
||||
bomId: uuid,
|
||||
reference: z.string().trim().toUpperCase().max(32).regex(/^[A-Z0-9][A-Z0-9_-]*$/),
|
||||
plannedQuantity: output.min(1),
|
||||
scheduledDate: z.string().date().optional(),
|
||||
}).strict();
|
||||
export const cancelBatchInput = z.object({ reason }).strict();
|
||||
const completeBatchInput = z.object({
|
||||
goodQuantity: output,
|
||||
rejectedQuantity: output,
|
||||
rejectionReason: reason.optional(),
|
||||
}).strict().refine((value) => value.rejectedQuantity === 0 || Boolean(value.rejectionReason), {
|
||||
path: ["rejectionReason"],
|
||||
message: "Enter a reason for the rejected pieces.",
|
||||
});
|
||||
|
||||
export function parseCompletion(input: unknown, plannedQuantity: number) {
|
||||
const value = completeBatchInput.parse(input);
|
||||
if (value.goodQuantity + value.rejectedQuantity !== plannedQuantity) {
|
||||
throw new Error(`Good and rejected quantities must total ${plannedQuantity} pieces.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export const productionBatch = z.object({
|
||||
id: uuid,
|
||||
reference: z.string(),
|
||||
plannedQuantity: batchInput.shape.plannedQuantity,
|
||||
status: batchStatus,
|
||||
scheduledDate: z.string().datetime().nullable(),
|
||||
startedAt: z.string().datetime().nullable(),
|
||||
});
|
||||
|
||||
export const batchDetail = productionBatch.extend({
|
||||
bom: bomSummary,
|
||||
plannedMaterials: z.array(materialLine.extend({ plannedQuantity: exactTotal })),
|
||||
completion: z.object({
|
||||
goodQuantity: output,
|
||||
rejectedQuantity: output,
|
||||
rejectionReason: z.string().nullable(),
|
||||
createdAt: z.string().datetime(),
|
||||
}).nullable(),
|
||||
cancellation: z.object({
|
||||
reason,
|
||||
createdAt: z.string().datetime(),
|
||||
}).nullable(),
|
||||
});
|
||||
|
||||
export const usageKind = z.enum(["CONSUMED", "WASTED"]);
|
||||
export const usageInput = z.object({
|
||||
bomLineId: uuid,
|
||||
kind: usageKind,
|
||||
quantity: z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Use three decimal places")
|
||||
.refine((value) => value !== "0.000", "Quantity must be positive"),
|
||||
reason: reason.optional(),
|
||||
idempotencyKey: uuid,
|
||||
}).strict().refine((value) => value.kind !== "WASTED" || Boolean(value.reason), {
|
||||
path: ["reason"],
|
||||
message: "Enter a reason for the wasted material.",
|
||||
});
|
||||
|
||||
export const usageEvent = z.object({
|
||||
id: uuid,
|
||||
bomLineId: uuid,
|
||||
kind: usageKind,
|
||||
quantity: decimal,
|
||||
reason: z.string().nullable(),
|
||||
createdAt: z.string().datetime(),
|
||||
});
|
||||
export const batchUsage = z.object({
|
||||
total: z.number().int().min(0).max(500),
|
||||
events: z.array(usageEvent),
|
||||
materials: z.array(z.object({
|
||||
bomLineId: uuid,
|
||||
materialName: z.string(),
|
||||
materialCode: z.string(),
|
||||
unit: materialLine.shape.unit,
|
||||
plannedQuantity: exactTotal,
|
||||
consumedQuantity: exactTotal,
|
||||
wastedQuantity: exactTotal,
|
||||
varianceQuantity: z.string().regex(/^-?\d+\.\d{3}$/),
|
||||
})),
|
||||
});
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { profileSnapshot } from "./business.ts";
|
||||
import { currency, uuid } from "./commerce.ts";
|
||||
import { priceCheck, priceCheckInput } from "./price-lists.ts";
|
||||
|
||||
const plainText = (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 });
|
||||
export const responseKind = z.enum(["ACCEPTED", "DECLINED", "WITHDRAWN"]);
|
||||
export const quoteResponseInput = z.object({
|
||||
kind: responseKind,
|
||||
note: plainText(500, 3),
|
||||
idempotencyKey: uuid,
|
||||
}).strict();
|
||||
export const issueQuoteInput = z.object({
|
||||
accountId: uuid,
|
||||
priceListId: uuid,
|
||||
expiresAt: timestamp,
|
||||
customerReference: plainText(100).nullable().optional(),
|
||||
lines: priceCheckInput.shape.lines,
|
||||
idempotencyKey: uuid,
|
||||
}).strict();
|
||||
|
||||
export function quoteExpiry(value: string, now = Date.now()) {
|
||||
const expiry = Date.parse(timestamp.parse(value));
|
||||
if (!(expiry > now && expiry - now <= 90 * 24 * 60 * 60 * 1000)) {
|
||||
throw new Error("Choose an expiry in the next 90 days.");
|
||||
}
|
||||
return new Date(expiry).toISOString();
|
||||
}
|
||||
|
||||
export const quoteSummary = z.object({
|
||||
id: uuid,
|
||||
accountId: uuid,
|
||||
number: z.string(),
|
||||
accountSnapshot: profileSnapshot,
|
||||
currency,
|
||||
merchandiseTotal: priceCheck.shape.merchandiseTotal,
|
||||
expiresAt: timestamp,
|
||||
status: z.enum(["ISSUED", "EXPIRED", ...responseKind.options]),
|
||||
});
|
||||
export const quote = quoteSummary.extend({
|
||||
priceListName: z.string(),
|
||||
customerReference: z.string().nullable(),
|
||||
createdAt: timestamp,
|
||||
lines: z.array(priceCheck.shape.lines.element.extend({ id: uuid, sku: z.string(), name: z.string() }).strip()),
|
||||
response: z.object({ kind: responseKind, note: z.string(), createdAt: timestamp }).nullable(),
|
||||
});
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
let token: string | null = null;
|
||||
export function captureRecoveryToken(
|
||||
location: { hash: string; pathname: string; search: string },
|
||||
history: {
|
||||
replaceState: (data: unknown, unused: string, url: string) => void;
|
||||
},
|
||||
) {
|
||||
const params = new URLSearchParams(location.hash.slice(1));
|
||||
if (!params.has("token")) return null;
|
||||
const value = params.get("token") || "";
|
||||
history.replaceState(null, "", location.pathname + location.search);
|
||||
token = /^[A-Za-z0-9_-]{43}$/.test(value) ? value : null;
|
||||
return token;
|
||||
}
|
||||
export function getRecoveryToken() {
|
||||
return token;
|
||||
}
|
||||
export function clearRecoveryToken() {
|
||||
token = null;
|
||||
}
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { uuid } from "./commerce.ts";
|
||||
|
||||
const text = (max: number) =>
|
||||
z.string().trim().min(3).max(max).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
|
||||
const note = text(500);
|
||||
const decision = z.enum(["APPROVED", "REJECTED"]);
|
||||
export const sampleStatus = z.enum(["REQUESTED", ...decision.options, "DISPATCHED"]);
|
||||
|
||||
const requestFields = z.object({
|
||||
accountId: uuid,
|
||||
variantId: uuid,
|
||||
quantity: z.number().int().min(1).max(100),
|
||||
purpose: text(500),
|
||||
});
|
||||
const key = { idempotencyKey: uuid };
|
||||
export const sampleRequestInput = requestFields.extend(key).strict();
|
||||
export const sampleDecisionInput = z.object({ decision, note, ...key }).strict();
|
||||
export const sampleDispatchInput = z.object({ dispatchReference: text(100), note, ...key }).strict();
|
||||
|
||||
const sampleEvent = z.object({
|
||||
id: uuid,
|
||||
actorId: uuid,
|
||||
sequence: z.number().int().min(1).max(2),
|
||||
kind: z.enum([...decision.options, "DISPATCHED"]),
|
||||
note,
|
||||
dispatchReference: text(100).nullable(),
|
||||
createdAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const sampleRequest = requestFields.extend({
|
||||
id: uuid,
|
||||
requestedById: uuid,
|
||||
sku: z.string(),
|
||||
variantName: z.string(),
|
||||
status: sampleStatus,
|
||||
createdAt: z.string().datetime(),
|
||||
events: z.array(sampleEvent),
|
||||
});
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { uuid } from "./commerce.ts";
|
||||
|
||||
export const maxDocumentBytes = 2 * 1024 * 1024;
|
||||
const pdfFilename = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,115}\.pdf$/);
|
||||
const decisionOutcome = z.enum(["APPROVED", "REJECTED"]);
|
||||
|
||||
export const documentInput = z.object({
|
||||
code: z.string().trim().max(32).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/).toUpperCase(),
|
||||
kind: z.enum(["REGISTRATION", "TAX_CERTIFICATE", "COMPLIANCE_CERTIFICATE", "OTHER"]),
|
||||
title: z.string().trim().min(1).max(160),
|
||||
}).strict();
|
||||
|
||||
export const supplierDocument = documentInput.extend({ id: uuid }).strip();
|
||||
export const documentVersion = z.object({
|
||||
id: uuid,
|
||||
uploadedById: uuid,
|
||||
version: z.number().int().min(1).max(20),
|
||||
filename: pdfFilename,
|
||||
mimeType: z.literal("application/pdf"),
|
||||
size: z.number().int().min(1).max(maxDocumentBytes),
|
||||
createdAt: z.string().datetime(),
|
||||
decision: z.object({
|
||||
outcome: decisionOutcome,
|
||||
reason: z.string().nullable(),
|
||||
}).nullable(),
|
||||
});
|
||||
export const documentDetails = supplierDocument.extend({ versions: z.array(documentVersion).max(20) });
|
||||
|
||||
export const documentDecision = z.object({
|
||||
outcome: decisionOutcome,
|
||||
reason: z.string().trim().min(1).max(500).optional(),
|
||||
}).strict().refine((value) => value.outcome !== "REJECTED" || Boolean(value.reason), {
|
||||
path: ["reason"],
|
||||
message: "Enter a reason for rejecting this version.",
|
||||
});
|
||||
|
||||
export function prepareDocumentUpload(file: FormDataEntryValue | null) {
|
||||
if (!(file instanceof File) || !file.size) throw new Error("Choose a PDF file.");
|
||||
if (file.size > maxDocumentBytes) throw new Error("Choose a PDF up to 2 MiB.");
|
||||
if (!pdfFilename.safeParse(file.name).success) {
|
||||
throw new Error("Use a simple .pdf filename with letters, numbers, dots, hyphens or underscores.");
|
||||
}
|
||||
if (file.type && file.type !== "application/pdf") throw new Error("Choose a PDF file.");
|
||||
const body = new FormData();
|
||||
body.append("file", file.type ? file : new File([file], file.name, { type: "application/pdf" }));
|
||||
return body;
|
||||
}
|
||||
|
|
@ -1,69 +0,0 @@
|
|||
import { z } from "zod";
|
||||
import { currency, uuid } from "./commerce.ts";
|
||||
|
||||
const reference = (max: number) =>
|
||||
z.string().trim().min(1).max(max).regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/).toUpperCase();
|
||||
const amount = z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/, "Use two decimal places");
|
||||
const decimal = z.string().regex(/^\d+(\.\d+)?$/);
|
||||
const reason = z.string().trim().min(1).max(500);
|
||||
const correction = z.object({ reason });
|
||||
export const correctionInput = correction.strict();
|
||||
|
||||
export const invoiceInput = z.object({
|
||||
invoiceNumber: reference(64),
|
||||
invoiceDate: z.string().date(),
|
||||
taxAmount: amount,
|
||||
shippingAmount: amount,
|
||||
lines: z.array(z.object({
|
||||
purchaseOrderLineId: uuid,
|
||||
quantity: z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Use three decimal places")
|
||||
.refine((value) => value !== "0.000", "Quantity must be positive"),
|
||||
}).strict()).min(1, "Enter a quantity for at least one line").max(100)
|
||||
.refine((lines) => new Set(lines.map((line) => line.purchaseOrderLineId)).size === lines.length),
|
||||
}).strict();
|
||||
|
||||
export const supplierInvoice = z.object({
|
||||
id: uuid,
|
||||
invoiceNumber: z.string(),
|
||||
invoiceDate: z.string().datetime(),
|
||||
currency,
|
||||
merchandiseTotal: decimal,
|
||||
taxAmount: decimal,
|
||||
shippingAmount: decimal,
|
||||
payableTotal: decimal,
|
||||
void: correction.nullable(),
|
||||
lines: z.array(z.object({
|
||||
id: uuid,
|
||||
purchaseOrderLineId: uuid,
|
||||
quantity: decimal,
|
||||
unitPrice: decimal,
|
||||
lineTotal: decimal,
|
||||
})),
|
||||
});
|
||||
|
||||
export const paymentMethods = z.enum(["BANK_TRANSFER", "UPI", "CHEQUE", "CASH", "OTHER"]);
|
||||
export const paymentInput = z.object({
|
||||
idempotencyKey: uuid,
|
||||
reference: reference(80),
|
||||
method: paymentMethods,
|
||||
amount: amount.refine((value) => value !== "0.00", "Amount must be positive"),
|
||||
paidDate: z.string().date(),
|
||||
}).strict();
|
||||
|
||||
export const supplierPayment = z.object({
|
||||
id: uuid,
|
||||
reference: z.string(),
|
||||
method: paymentMethods,
|
||||
currency,
|
||||
amount: decimal,
|
||||
paidAt: z.string().datetime(),
|
||||
reversal: correction.nullable(),
|
||||
});
|
||||
|
||||
export const paymentHistory = z.object({
|
||||
currency,
|
||||
payableTotal: amount,
|
||||
paidTotal: amount,
|
||||
outstandingTotal: amount,
|
||||
payments: z.array(supplierPayment),
|
||||
});
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
import { useRef, useState } from "react";
|
||||
import { z } from "zod";
|
||||
import { isUnknownOutcome } from "./api";
|
||||
import { usePlatform } from "./platform";
|
||||
export function useIdempotentCommand<T extends { idempotencyKey: string }, R>(
|
||||
path: string,
|
||||
input: z.ZodType<T>,
|
||||
output: z.ZodType<R>,
|
||||
commandId: string,
|
||||
) {
|
||||
const { request, getIntent, saveIntent, clearIntent } = usePlatform();
|
||||
const key = `${path}:${commandId}`;
|
||||
const saved = getIntent(key);
|
||||
const intent = useRef<T | null>(saved ? input.parse(saved) : null);
|
||||
const [uncertain, setUncertain] = useState(Boolean(saved));
|
||||
async function run(value: unknown) {
|
||||
if (!intent.current) {
|
||||
const object = z.record(z.string(), z.unknown()).parse(value);
|
||||
intent.current = Object.freeze(
|
||||
input.parse({ ...object, idempotencyKey: crypto.randomUUID() }),
|
||||
);
|
||||
saveIntent(key, intent.current);
|
||||
}
|
||||
try {
|
||||
const result = await request(path, output, {
|
||||
method: "POST",
|
||||
body: intent.current,
|
||||
});
|
||||
clearIntent(key, intent.current.idempotencyKey);
|
||||
intent.current = null;
|
||||
setUncertain(false);
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (isUnknownOutcome(error)) setUncertain(true);
|
||||
else {
|
||||
if (intent.current) clearIntent(key, intent.current.idempotencyKey);
|
||||
intent.current = null;
|
||||
setUncertain(false);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return { run, uncertain, pending: uncertain ? intent.current : null };
|
||||
}
|
||||
|
|
@ -3,10 +3,7 @@ import { ThemeProvider } from "@mui/material/styles";
|
|||
import CssBaseline from "@mui/material/CssBaseline";
|
||||
import App from "./App";
|
||||
import theme from "./theme";
|
||||
import "./index.css";
|
||||
import { captureRecoveryToken } from "./lib/recovery-token";
|
||||
|
||||
captureRecoveryToken(window.location, window.history);
|
||||
import "./index.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<ThemeProvider theme={theme}>
|
||||
|
|
|
|||
|
|
@ -1,297 +0,0 @@
|
|||
import { RecordSelection } from "@/components/RecordSelection";
|
||||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
import Button from "@mui/material/Button";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { user, userInput, role, roleInput, uuid, audit } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import {
|
||||
ActionForm,
|
||||
Field,
|
||||
Pager,
|
||||
Panel,
|
||||
QueryView,
|
||||
Table,
|
||||
usePrivateQuery,
|
||||
readText,
|
||||
} from "@/components/WorkspaceTools";
|
||||
import { ConfirmAction } from "@/components/ConfirmAction";
|
||||
function Roles() {
|
||||
const { request, can, principal } = usePlatform();
|
||||
const [offset, setOffset] = useState(0),
|
||||
[editing, setEditing] = useState<z.infer<typeof role> | null>(null);
|
||||
const roles = usePrivateQuery(
|
||||
`/roles?limit=25&offset=${offset}`,
|
||||
z.array(role),
|
||||
);
|
||||
return (
|
||||
<Panel title="Roles">
|
||||
<QueryView query={roles}>
|
||||
{(items) => (
|
||||
<>
|
||||
<Table
|
||||
head={["Role", "Permissions", "Actions"]}
|
||||
rowKeys={items.map((item) => item.id)}
|
||||
rows={items.map((r) => [
|
||||
r.name,
|
||||
r.permissions.join(", "),
|
||||
can("roles.manage") &&
|
||||
!r.isSystem &&
|
||||
r.permissions.every((p) =>
|
||||
principal?.permissions.includes(p),
|
||||
) ? (
|
||||
<Button onClick={() => setEditing(r)}>Edit</Button>
|
||||
) : r.isSystem ? (
|
||||
"System role"
|
||||
) : (
|
||||
"Read only"
|
||||
),
|
||||
])}
|
||||
/>
|
||||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
{can("roles.manage") && (
|
||||
<>
|
||||
<h3>{editing ? `Edit ${editing.name}` : "Create a role"}</h3>
|
||||
<ActionForm
|
||||
key={editing?.id || "new"}
|
||||
label="Save role"
|
||||
read={(data) => ({
|
||||
name: readText(data, "name"),
|
||||
permissions: data.getAll("permissions").map(String),
|
||||
})}
|
||||
submit={async (value) => {
|
||||
const body = roleInput.parse(value);
|
||||
if (
|
||||
body.permissions.some(
|
||||
(p) => !principal?.permissions.includes(p),
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
"You cannot grant a permission you do not hold.",
|
||||
);
|
||||
await request(editing ? `/roles/${editing.id}` : "/roles", role, {
|
||||
method: editing ? "PATCH" : "POST",
|
||||
body,
|
||||
});
|
||||
setEditing(null);
|
||||
await roles.refetch();
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
name="name"
|
||||
label="Role name"
|
||||
maxLength={80}
|
||||
value={editing?.name}
|
||||
/>
|
||||
<Field
|
||||
name="permissions"
|
||||
label="Permissions to grant"
|
||||
options={
|
||||
principal?.permissions.map((p) => ({ value: p, label: p })) ||
|
||||
[]
|
||||
}
|
||||
multiple
|
||||
required={false}
|
||||
value={editing?.permissions || []}
|
||||
helper="Select only permissions this role should receive."
|
||||
/>
|
||||
</ActionForm>
|
||||
{editing && (
|
||||
<Button onClick={() => setEditing(null)}>Cancel editing</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
function UserRoles({ userId }: { userId: string }) {
|
||||
const { request } = usePlatform();
|
||||
return (
|
||||
<>
|
||||
<Alert severity="warning">
|
||||
This replaces all role assignments. The API does not expose current
|
||||
assignments; select the full intended set. System roles cannot be
|
||||
assigned.
|
||||
</Alert>
|
||||
<ActionForm
|
||||
label="Replace role assignments"
|
||||
read={(data) => ({ roleIds: data.getAll("roleIds").map(String) })}
|
||||
submit={async (value) => {
|
||||
const body = z
|
||||
.object({
|
||||
roleIds: z
|
||||
.array(uuid)
|
||||
.max(20)
|
||||
.refine((v) => new Set(v).size === v.length),
|
||||
})
|
||||
.parse(value);
|
||||
await request(`/users/${userId}/roles`, z.object({ id: uuid }), {
|
||||
method: "PATCH",
|
||||
body,
|
||||
});
|
||||
}}
|
||||
reset={false}
|
||||
>
|
||||
<RecordSelection
|
||||
name="roleIds"
|
||||
label="Intended role assignments"
|
||||
path="/roles"
|
||||
roles
|
||||
/>
|
||||
</ActionForm>
|
||||
</>
|
||||
);
|
||||
}
|
||||
function Users() {
|
||||
const { request, can, principal } = usePlatform();
|
||||
const [offset, setOffset] = useState(0),
|
||||
[selected, setSelected] = useState<string | null>(null);
|
||||
const query = usePrivateQuery(
|
||||
`/users?limit=25&offset=${offset}`,
|
||||
z.array(user),
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Panel title="Staff accounts">
|
||||
<QueryView query={query}>
|
||||
{(items) => (
|
||||
<>
|
||||
<Table
|
||||
head={["Name", "Email", "Status", "Actions"]}
|
||||
rowKeys={items.map((item) => item.id)}
|
||||
rows={items.map((u) => [
|
||||
u.name,
|
||||
u.email,
|
||||
u.status,
|
||||
<>
|
||||
{!u.isOwner && u.id !== principal?.userId && (
|
||||
<>
|
||||
{can("users.approve") && (
|
||||
<ConfirmAction
|
||||
label={
|
||||
u.status === "ACTIVE" ? "Suspend" : "Approve"
|
||||
}
|
||||
message={
|
||||
u.status === "ACTIVE"
|
||||
? "Suspend this account and revoke its sessions?"
|
||||
: "Approve this account? It must have suitable roles before accessing staff tools."
|
||||
}
|
||||
onConfirm={async () => {
|
||||
await request(`/users/${u.id}/status`, user, {
|
||||
method: "PATCH",
|
||||
body: {
|
||||
status:
|
||||
u.status === "ACTIVE"
|
||||
? "SUSPENDED"
|
||||
: "ACTIVE",
|
||||
},
|
||||
});
|
||||
await query.refetch();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{can("users.roles.assign") && can("roles.read") && (
|
||||
<Button
|
||||
onClick={() =>
|
||||
setSelected(selected === u.id ? null : u.id)
|
||||
}
|
||||
>
|
||||
Assign roles
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>,
|
||||
])}
|
||||
/>
|
||||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||||
{selected && <UserRoles key={selected} userId={selected} />}
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
</Panel>
|
||||
{can("users.create") && (
|
||||
<Panel title="Provision a pending account">
|
||||
<ActionForm
|
||||
label="Create pending account"
|
||||
read={(data) => ({
|
||||
name: readText(data, "name"),
|
||||
email: readText(data, "email"),
|
||||
password: readText(data, "password"),
|
||||
})}
|
||||
submit={async (value) => {
|
||||
await request("/users", user, {
|
||||
method: "POST",
|
||||
body: userInput.parse(value),
|
||||
});
|
||||
await query.refetch();
|
||||
}}
|
||||
>
|
||||
<Field name="name" label="Full name" maxLength={160} />
|
||||
<Field name="email" label="Email" type="email" maxLength={254} />
|
||||
<Field
|
||||
name="password"
|
||||
label="Initial password"
|
||||
type="password"
|
||||
maxLength={128}
|
||||
helper="15–128 characters. The account starts pending."
|
||||
/>
|
||||
</ActionForm>
|
||||
</Panel>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
export default function AccessPage() {
|
||||
return (
|
||||
<WorkspaceShell title="Access Administration" permission="users.read">
|
||||
<Users />
|
||||
</WorkspaceShell>
|
||||
);
|
||||
}
|
||||
export function RolesPage() {
|
||||
return (
|
||||
<WorkspaceShell title="Role Administration" permission="roles.read">
|
||||
<Roles />
|
||||
</WorkspaceShell>
|
||||
);
|
||||
}
|
||||
function Audit() {
|
||||
const [offset, setOffset] = useState(0);
|
||||
const query = usePrivateQuery(
|
||||
`/audit-events?limit=25&offset=${offset}`,
|
||||
z.array(audit),
|
||||
);
|
||||
return (
|
||||
<Panel title="Immutable audit history">
|
||||
<QueryView query={query}>
|
||||
{(items) => (
|
||||
<>
|
||||
<Table
|
||||
head={["Time", "Action", "Actor", "Target"]}
|
||||
rowKeys={items.map((item) => item.id)}
|
||||
rows={items.map((a) => [
|
||||
new Date(a.createdAt).toLocaleString(),
|
||||
a.action,
|
||||
a.actorId || "System",
|
||||
a.targetId || "—",
|
||||
])}
|
||||
/>
|
||||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
export function AuditPage() {
|
||||
return (
|
||||
<WorkspaceShell title="Audit History" permission="audit.read">
|
||||
<Audit />
|
||||
</WorkspaceShell>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,130 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
import Button from "@mui/material/Button";
|
||||
import { address, addressInput, type Address } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import {
|
||||
ActionForm,
|
||||
Check,
|
||||
Field,
|
||||
Panel,
|
||||
QueryView,
|
||||
readText,
|
||||
usePrivateQuery,
|
||||
Empty,
|
||||
} from "@/components/WorkspaceTools";
|
||||
import { ConfirmAction } from "@/components/ConfirmAction";
|
||||
function Addresses() {
|
||||
const { request } = usePlatform(),
|
||||
query = usePrivateQuery("/addresses", z.array(address));
|
||||
const [editing, setEditing] = useState<Address | null>(null);
|
||||
return (
|
||||
<>
|
||||
<Panel title="Saved addresses">
|
||||
<QueryView query={query}>
|
||||
{(items) => (
|
||||
<>
|
||||
{!items.length && <Empty />}
|
||||
{items.map((item) => (
|
||||
<article className="address-card" key={item.id}>
|
||||
<h3>
|
||||
{item.recipient}
|
||||
{item.isDefault ? " · Default" : ""}
|
||||
</h3>
|
||||
<p>
|
||||
{item.line1} {item.line2}
|
||||
<br />
|
||||
{item.city}, {item.region} {item.postalCode}
|
||||
<br />
|
||||
{item.countryCode} · {item.phone}
|
||||
</p>
|
||||
<Button onClick={() => setEditing(item)}>Edit address</Button>
|
||||
<ConfirmAction
|
||||
label="Delete address"
|
||||
message="Delete this saved address? Existing order snapshots will be retained."
|
||||
onConfirm={async () => {
|
||||
await request(`/addresses/${item.id}`, z.null(), {
|
||||
method: "DELETE",
|
||||
});
|
||||
await query.refetch();
|
||||
if (editing?.id === item.id) setEditing(null);
|
||||
}}
|
||||
/>
|
||||
</article>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
</Panel>
|
||||
<Panel title={editing ? "Edit address" : "New address"}>
|
||||
<ActionForm
|
||||
key={editing?.id || "new"}
|
||||
label="Save address"
|
||||
read={(data) => ({
|
||||
...Object.fromEntries(
|
||||
[
|
||||
"recipient",
|
||||
"line1",
|
||||
"line2",
|
||||
"city",
|
||||
"region",
|
||||
"postalCode",
|
||||
"countryCode",
|
||||
"phone",
|
||||
].map((name) => [name, readText(data, name)]),
|
||||
),
|
||||
isDefault: data.has("isDefault"),
|
||||
})}
|
||||
submit={async (value) => {
|
||||
const body = addressInput.parse(value);
|
||||
await request(
|
||||
editing ? `/addresses/${editing.id}` : "/addresses",
|
||||
address,
|
||||
{ method: editing ? "PUT" : "POST", body },
|
||||
);
|
||||
setEditing(null);
|
||||
await query.refetch();
|
||||
}}
|
||||
>
|
||||
{(
|
||||
[
|
||||
["recipient", "Recipient", 160],
|
||||
["line1", "Address line 1", 200],
|
||||
["line2", "Address line 2", 200],
|
||||
["city", "City", 100],
|
||||
["region", "State or region", 100],
|
||||
["postalCode", "Postal code", 20],
|
||||
["countryCode", "Country code (IN, US, etc.)", 2],
|
||||
["phone", "Phone (+country code)", 16],
|
||||
] as const
|
||||
).map(([name, label, maxLength]) => (
|
||||
<Field
|
||||
key={name}
|
||||
name={name}
|
||||
label={label}
|
||||
maxLength={maxLength}
|
||||
required={name !== "line2"}
|
||||
value={editing?.[name] || (name === "countryCode" ? "IN" : "")}
|
||||
/>
|
||||
))}
|
||||
<Check
|
||||
name="isDefault"
|
||||
label="Default address"
|
||||
value={editing?.isDefault}
|
||||
/>
|
||||
</ActionForm>
|
||||
{editing && (
|
||||
<Button onClick={() => setEditing(null)}>Cancel editing</Button>
|
||||
)}
|
||||
</Panel>
|
||||
</>
|
||||
);
|
||||
}
|
||||
export default function AddressesPage() {
|
||||
return (
|
||||
<WorkspaceShell title="My Addresses">
|
||||
<Addresses />
|
||||
</WorkspaceShell>
|
||||
);
|
||||
}
|
||||
|
|
@ -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>;
|
||||
}
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { ActionForm, Field, Pager, Panel, QueryView, Table, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { batchDetail, batchUsage, usageEvent, usageInput } from "@/lib/production";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
|
||||
export function BatchMaterialUsage({ batch }: { batch: z.infer<typeof batchDetail> }) {
|
||||
const { can } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const path = `/production-batches/${batch.id}/material-usage`;
|
||||
const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, batchUsage);
|
||||
const command = useIdempotentCommand(path, usageInput, usageEvent, batch.id);
|
||||
const labels = new Map(batch.plannedMaterials.map((line) => [line.id, `${line.materialName} (${line.materialCode}) · ${line.unit}`]));
|
||||
const pending = command.pending;
|
||||
|
||||
return <Panel title="Material usage">
|
||||
<QueryView query={query}>{(data) => <>
|
||||
<Table head={["Material", "Planned", "Consumed", "Wasted", "Variance"]}
|
||||
rowKeys={data.materials.map((line) => line.bomLineId)} rows={data.materials.map((line) => [
|
||||
`${line.materialName} (${line.materialCode}) · ${line.unit}`, line.plannedQuantity,
|
||||
line.consumedQuantity, line.wastedQuantity, line.varianceQuantity,
|
||||
])} />
|
||||
<h3>Usage history</h3>
|
||||
<Table head={["Time", "Material", "Event", "Quantity", "Reason"]}
|
||||
rowKeys={data.events.map((event) => event.id)} rows={data.events.map((event) => [
|
||||
new Date(event.createdAt).toLocaleString(), labels.get(event.bomLineId) ?? event.bomLineId,
|
||||
event.kind, event.quantity, event.reason ?? "—",
|
||||
])} />
|
||||
<Pager offset={offset} count={offset + data.events.length < data.total ? 25 : 0} onPage={setOffset} />
|
||||
{can("production.material.record") && (pending || (batch.status === "IN_PROGRESS" && data.total < 500)) && (
|
||||
<ActionForm key={pending ? "retry" : "record"} label={pending ? "Retry material usage" : "Record material usage"}
|
||||
read={(form) => pending ? {} : ({
|
||||
bomLineId: readText(form, "bomLineId"),
|
||||
kind: readText(form, "kind"),
|
||||
quantity: readText(form, "quantity").trim(),
|
||||
reason: readText(form, "reason").trim() || undefined,
|
||||
})}
|
||||
submit={async (input) => {
|
||||
await command.run(input);
|
||||
const result = await query.refetch();
|
||||
if (result.data) setOffset(Math.floor(Math.max(0, result.data.total - 1) / 25) * 25);
|
||||
}}>
|
||||
{pending ? (
|
||||
<Alert severity="warning">The server may have saved this entry. Retrying reuses {pending.quantity} for {labels.get(pending.bomLineId) ?? pending.bomLineId} as {pending.kind.toLowerCase()}.</Alert>
|
||||
) : <>
|
||||
<Field name="bomLineId" label="Material" value={batch.plannedMaterials[0]?.id}
|
||||
options={[...labels].map(([value, label]) => ({ value, label }))} />
|
||||
<Field name="kind" label="Usage type" value="CONSUMED"
|
||||
options={[{ value: "CONSUMED", label: "Consumed" }, { value: "WASTED", label: "Wasted" }]} />
|
||||
<Field name="quantity" label="Actual quantity" maxLength={13} helper="Use three decimal places in the material’s unit." />
|
||||
<Field name="reason" label="Usage reason" required={false} maxLength={500} helper="Required for waste." />
|
||||
</>}
|
||||
</ActionForm>
|
||||
)}
|
||||
{batch.status === "IN_PROGRESS" && data.total === 500 && <Alert severity="info">This batch has reached the 500-event limit.</Alert>}
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
|
@ -1,134 +0,0 @@
|
|||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { ActionForm, Panel, QueryView, Table, WorkspaceLink } from "@/components/WorkspaceTools";
|
||||
import { WarehousePostingForm } from "@/components/WarehousePostingForm";
|
||||
import { useOptionalPrivateQuery } from "@/components/useOptionalPrivateQuery";
|
||||
import { ApiError } from "@/lib/api";
|
||||
import { receiptPostingInput } from "@/lib/material-stock";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { finishedGoodsReceipt, packagingDebit, productionDebit } from "@/lib/production-stock";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
|
||||
const material = {
|
||||
endpoint: "material-stock-posting",
|
||||
missing: "PRODUCTION_STOCK_POSTING_NOT_FOUND",
|
||||
duplicate: "PRODUCTION_STOCK_ALREADY_POSTED",
|
||||
cachePath: "/inventory/material-stock-items",
|
||||
title: "Production material stock",
|
||||
label: "Post production material",
|
||||
instruction: "Choose the warehouse to debit for the batch’s consumed and wasted materials. Every BOM material needs a usage record.",
|
||||
schema: productionDebit,
|
||||
};
|
||||
const packaging = {
|
||||
endpoint: "packaging-stock-posting",
|
||||
missing: "PACKAGING_STOCK_POSTING_NOT_FOUND",
|
||||
duplicate: "PACKAGING_STOCK_ALREADY_POSTED",
|
||||
cachePath: material.cachePath,
|
||||
title: "Packaging material stock",
|
||||
label: "Post packaging material",
|
||||
instruction: "Choose the warehouse to debit for used and wasted packaging material.",
|
||||
schema: packagingDebit,
|
||||
};
|
||||
const finished = {
|
||||
endpoint: "finished-goods-receipt",
|
||||
missing: "FINISHED_GOODS_RECEIPT_NOT_FOUND",
|
||||
duplicate: "FINISHED_GOODS_ALREADY_POSTED",
|
||||
cachePath: "/inventory/stock-items",
|
||||
title: "Finished-goods receipt",
|
||||
label: "Receive finished goods",
|
||||
schema: finishedGoodsReceipt,
|
||||
};
|
||||
|
||||
export function BatchStock({ batchId, goodQuantity, names, packagingRecorded }: {
|
||||
batchId: string;
|
||||
goodQuantity: number;
|
||||
names: Map<string, string>;
|
||||
packagingRecorded?: boolean;
|
||||
}) {
|
||||
const path = `/production-batches/${batchId}`;
|
||||
const productionQuery = useOptionalPrivateQuery(`${path}/${material.endpoint}`, material.schema, material.missing);
|
||||
const packagingQuery = useOptionalPrivateQuery(`${path}/${packaging.endpoint}`, packaging.schema, packaging.missing);
|
||||
const receiptQuery = useOptionalPrivateQuery(`${path}/${finished.endpoint}`, finished.schema, finished.missing);
|
||||
|
||||
return <>
|
||||
<StockStep batchId={batchId} config={material} query={productionQuery}>
|
||||
{(posting) => <DebitSummary posting={posting} names={names} />}
|
||||
</StockStep>
|
||||
<StockStep batchId={batchId} config={packaging} query={packagingQuery}
|
||||
blocked={packagingRecorded === false ? "Record the packaging run before posting its material." : undefined}>
|
||||
{(posting) => <DebitSummary posting={posting} names={names} />}
|
||||
</StockStep>
|
||||
<StockStep batchId={batchId} config={{ ...finished, instruction: `Choose the warehouse that will receive the ${goodQuantity} good pieces.` }}
|
||||
query={receiptQuery} blocked={goodQuantity === 0 ? "This batch has no good pieces to receive." :
|
||||
!productionQuery.data || !packagingQuery.data ? "Post production and packaging material stock before receiving finished goods." : undefined}>
|
||||
{(receipt) => <>
|
||||
<p>Received {receipt.quantity} pieces into warehouse {receipt.warehouseId} on {new Date(receipt.createdAt).toLocaleString()}.</p>
|
||||
<WorkspaceLink href={`/admin/inventory/${receipt.stockItemId}`}>View finished-goods stock ledger</WorkspaceLink>
|
||||
</>}
|
||||
</StockStep>
|
||||
</>;
|
||||
}
|
||||
|
||||
type StepConfig<T> = {
|
||||
endpoint: string;
|
||||
duplicate: string;
|
||||
cachePath: string;
|
||||
title: string;
|
||||
label: string;
|
||||
instruction: string;
|
||||
schema: z.ZodType<T>;
|
||||
};
|
||||
|
||||
function StockStep<T>({ batchId, config, query, blocked, children }: {
|
||||
batchId: string;
|
||||
config: StepConfig<T>;
|
||||
query: ReturnType<typeof useOptionalPrivateQuery<T>>;
|
||||
blocked?: string;
|
||||
children: (record: T) => React.ReactNode;
|
||||
}) {
|
||||
const { can, scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
const path = `/production-batches/${batchId}/${config.endpoint}`;
|
||||
const command = useIdempotentCommand(path, receiptPostingInput, config.schema, batchId);
|
||||
const pending = command.pending;
|
||||
async function submit(input: unknown) {
|
||||
let record: T;
|
||||
try {
|
||||
record = await command.run(input);
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.code === config.duplicate) await query.refetch();
|
||||
throw error;
|
||||
}
|
||||
client.setQueryData(["private", scope, path], record);
|
||||
await client.invalidateQueries({
|
||||
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
|
||||
typeof queryKey[2] === "string" && queryKey[2].startsWith(config.cachePath),
|
||||
});
|
||||
}
|
||||
return <Panel title={config.title}>
|
||||
<QueryView query={query}>{(record) => {
|
||||
if (record) return children(record);
|
||||
if (!can("inventory.manage")) return <Alert severity="info">Awaiting warehouse posting.</Alert>;
|
||||
if (pending) return <ActionForm label={`Retry ${config.label.toLowerCase()}`} read={() => ({})} submit={submit}>
|
||||
<Alert severity="warning">The server may have saved the movement. Retrying uses the original warehouse {pending.warehouseId}.</Alert>
|
||||
</ActionForm>;
|
||||
if (blocked) return <Alert severity="info">{blocked}</Alert>;
|
||||
return <WarehousePostingForm label={config.label} instruction={config.instruction} submit={submit} />;
|
||||
}}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function DebitSummary({ posting, names }: {
|
||||
posting: z.infer<typeof productionDebit> | z.infer<typeof packagingDebit>;
|
||||
names: Map<string, string>;
|
||||
}) {
|
||||
return <>
|
||||
<p>Posted from warehouse {posting.warehouseId} on {new Date(posting.createdAt).toLocaleString()}.</p>
|
||||
{posting.entries.length ? <Table head={["Material", "Movement", "Quantity change", "Ledger"]}
|
||||
rowKeys={posting.entries.map((entry) => entry.id)} rows={posting.entries.map((entry) => [
|
||||
names.get(entry.materialId) ?? entry.materialId, entry.kind.replaceAll("_", " ").toLowerCase(),
|
||||
entry.delta, <WorkspaceLink href={`/admin/material-stock/${entry.stockItemId}`}>View material ledger</WorkspaceLink>,
|
||||
])} /> : <p>The posting recorded zero material movements.</p>}
|
||||
</>;
|
||||
}
|
||||
|
|
@ -1,198 +0,0 @@
|
|||
import { useRef, useState } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import Button from "@mui/material/Button";
|
||||
import { ConfirmAction } from "@/components/ConfirmAction";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { isUnknownOutcome } from "@/lib/api";
|
||||
import { bomDetail, bomInput, bomStatus, bomSummary, packagingMaterialKinds } from "@/lib/bom";
|
||||
import { uuid } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { material } from "@/lib/procurement";
|
||||
import { BomCostEstimate } from "./CostingPanels";
|
||||
|
||||
const kinds = {
|
||||
production: { title: "Production BOMs", api: "boms", read: "bom.read", manage: "bom.manage", kind: "PRODUCTION" },
|
||||
packaging: { title: "Packaging BOMs", api: "packaging-boms", read: "packaging.read", manage: "packaging.manage", kind: "PACKAGING" },
|
||||
} as const;
|
||||
type Config = (typeof kinds)[keyof typeof kinds];
|
||||
type Material = z.infer<typeof material>;
|
||||
type DraftLine = { key: number; material?: Material };
|
||||
|
||||
function FindVariant({ config }: { config: Config }) {
|
||||
const { can } = usePlatform();
|
||||
const [, navigate] = useLocation();
|
||||
return <Panel title="Open variant revisions">
|
||||
{can("catalog.read") && <p>You can also open revisions from a variant in the <WorkspaceLink href="/admin/catalog">product catalog</WorkspaceLink>.</p>}
|
||||
<ActionForm label="Open revisions"
|
||||
read={(data) => ({ variantId: readText(data, "variantId").trim() })}
|
||||
submit={async (value) => {
|
||||
const { variantId } = z.object({ variantId: uuid }).parse(value);
|
||||
navigate(`/admin/${config.api}/${variantId}`);
|
||||
}}>
|
||||
<Field name="variantId" label="Variant ID" maxLength={36} helper="Enter the UUID of the product variant." />
|
||||
</ActionForm>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function Revisions({ config, variantId }: { config: Config; variantId: string }) {
|
||||
const { can, request, scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [status, setStatus] = useState("ALL");
|
||||
const [selected, select] = useState("");
|
||||
const [uncertain, setUncertain] = useState(false);
|
||||
const path = `/variants/${variantId}/${config.api}`;
|
||||
const params = new URLSearchParams({ limit: "25", offset: String(offset), ...(status === "ALL" ? {} : { status }) });
|
||||
const query = usePrivateQuery(`${path}?${params}`, z.array(bomSummary));
|
||||
function showLatest() {
|
||||
setStatus("ALL");
|
||||
setOffset(0);
|
||||
return client.invalidateQueries({ queryKey: ["private", scope, `${path}?limit=25&offset=0`] });
|
||||
}
|
||||
|
||||
return <>
|
||||
<p className="workspace-id">Variant ID {variantId}</p>
|
||||
<WorkspaceLink href={`/admin/${config.api}`}>Open another variant</WorkspaceLink>
|
||||
<Panel title="Revision history">
|
||||
<Field name="status" label="Revision status" value={status} onChange={(next) => { setStatus(next); setOffset(0); }}
|
||||
options={[{ value: "ALL", label: "All statuses" }, ...bomStatus.options.map((value) => ({ value, label: value }))]} />
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Revision", "Yield", "Status", "Actions"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
row.revision, `${row.outputQuantity} pieces`, row.status,
|
||||
<Button onClick={() => select(row.id)} aria-pressed={row.id === selected}>View revision {row.revision}</Button>,
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>
|
||||
{selected && <RevisionDetail key={selected} config={config} id={selected} refreshList={query.refetch} />}
|
||||
{can(config.manage) && <Panel title="New draft revision">
|
||||
{uncertain ? <Alert severity="warning">
|
||||
The server may have saved the draft. Check revision history before reopening this variant to create another draft.
|
||||
<Button onClick={() => showLatest()}>Show latest revisions</Button>
|
||||
</Alert> : <DraftForm packaging={config.kind === "PACKAGING"} submit={async (body) => {
|
||||
try {
|
||||
const revision = await request(path, bomDetail, { method: "POST", body });
|
||||
select(revision.id);
|
||||
} catch (error) {
|
||||
if (isUnknownOutcome(error)) {
|
||||
setUncertain(true);
|
||||
await showLatest();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
await showLatest();
|
||||
}} />}
|
||||
</Panel>}
|
||||
</>;
|
||||
}
|
||||
|
||||
function RevisionDetail({ config, id, refreshList }: {
|
||||
config: Config;
|
||||
id: string;
|
||||
refreshList: () => Promise<unknown>;
|
||||
}) {
|
||||
const { can, request } = usePlatform();
|
||||
const path = `/${config.api}/${id}`;
|
||||
const query = usePrivateQuery(path, bomDetail);
|
||||
return <QueryView query={query}>{(revision) => <Panel title={`Revision ${revision.revision}`}>
|
||||
<p>{revision.status} · Yields {revision.outputQuantity} finished pieces</p>
|
||||
{revision.activatedAt && <p>Activated {new Date(revision.activatedAt).toLocaleString()}</p>}
|
||||
<Table head={["Material", "Code", "Unit", "Quantity for this yield"]}
|
||||
rowKeys={revision.lines.map((line) => line.id)}
|
||||
rows={revision.lines.map((line) => [
|
||||
can("cost.read") ? <WorkspaceLink href={`/admin/material-cost-rates/${line.materialId}`}>{line.materialName}</WorkspaceLink> : line.materialName,
|
||||
line.materialCode, line.unit, line.quantity,
|
||||
])} />
|
||||
{config.kind === "PRODUCTION" && revision.status === "ACTIVE" && can("production.read") && can("production.manage") && (
|
||||
<WorkspaceLink href={`/admin/production-batches/new/${revision.id}`}>Plan a batch from revision {revision.revision}</WorkspaceLink>
|
||||
)}
|
||||
{can(config.manage) && revision.status === "DRAFT" && (
|
||||
<ConfirmAction label={`Activate revision ${revision.revision}`}
|
||||
message="Activation supersedes the current active revision of this type for this variant."
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await request(`${path}/activate`, bomDetail, { method: "POST" });
|
||||
} finally {
|
||||
await Promise.all([query.refetch(), refreshList()]);
|
||||
}
|
||||
}} />
|
||||
)}
|
||||
{can("cost.read") && <BomCostEstimate path={path} />}
|
||||
</Panel>}</QueryView>;
|
||||
}
|
||||
|
||||
function DraftForm({ packaging, submit }: {
|
||||
packaging: boolean;
|
||||
submit: (value: unknown) => Promise<void>;
|
||||
}) {
|
||||
const { can } = usePlatform();
|
||||
const [lines, setLines] = useState<DraftLine[]>([]);
|
||||
const nextKey = useRef(0);
|
||||
function addLine(material?: Material) {
|
||||
const key = nextKey.current++;
|
||||
setLines((current) => [...current, { key, material }]);
|
||||
}
|
||||
|
||||
return <ActionForm label="Create draft revision" read={(data) => bomInput.parse({
|
||||
outputQuantity: Number(readText(data, "outputQuantity")),
|
||||
lines: lines.map((line) => ({
|
||||
materialId: line.material?.id ?? readText(data, `material-${line.key}`).trim(),
|
||||
quantity: readText(data, `quantity-${line.key}`).trim(),
|
||||
})),
|
||||
})} submit={async (body) => { await submit(body); setLines([]); }}>
|
||||
<p>Enter material quantities for the full yield. Saved revisions keep their material names, codes and units.</p>
|
||||
<Field name="outputQuantity" label="Finished pieces per yield" type="number" />
|
||||
{can("procurement.read") && <MaterialPicker packaging={packaging} lines={lines} addLine={addLine} />}
|
||||
<Button type="button" onClick={() => addLine()} disabled={lines.length >= 50}>Add material by ID</Button>
|
||||
{lines.map((line, index) => (
|
||||
<fieldset className="record-picker" key={line.key}>
|
||||
<legend>{line.material ? `${line.material.name} (${line.material.code})` : `Material line ${index + 1}`}</legend>
|
||||
{!line.material && <Field name={`material-${line.key}`} label={`Material ID for line ${index + 1}`} maxLength={36} />}
|
||||
<Field name={`quantity-${line.key}`} maxLength={13} label={line.material ? `Quantity for ${line.material.name}` : `Quantity for line ${index + 1}`}
|
||||
helper={line.material ? `Use three decimal places in ${line.material.unit}.` : "Use three decimal places in the material’s native unit."} />
|
||||
<Button type="button" onClick={() => setLines((current) => current.filter((entry) => entry.key !== line.key))}>Remove line {index + 1}</Button>
|
||||
</fieldset>
|
||||
))}
|
||||
</ActionForm>;
|
||||
}
|
||||
|
||||
function MaterialPicker({ packaging, lines, addLine }: {
|
||||
packaging: boolean;
|
||||
lines: DraftLine[];
|
||||
addLine: (material: Material) => void;
|
||||
}) {
|
||||
const [offset, setOffset] = useState(0);
|
||||
const query = usePrivateQuery(`/materials?limit=25&offset=${offset}&active=true`, z.array(material));
|
||||
return <fieldset className="record-picker">
|
||||
<legend>{packaging ? "Active packaging and label materials" : "Active materials"}</legend>
|
||||
<QueryView query={query}>{(rows) => {
|
||||
const available = packaging ? rows.filter((row) => packagingMaterialKinds.some((kind) => kind === row.kind)) : rows;
|
||||
return <>
|
||||
<Table head={["Material", "Code", "Unit", "Actions"]} rowKeys={available.map((row) => row.id)}
|
||||
rows={available.map((row) => [
|
||||
row.name, row.code, row.unit,
|
||||
<Button type="button" onClick={() => addLine(row)}
|
||||
disabled={lines.length >= 50 || lines.some((line) => line.material?.id === row.id)}>
|
||||
Add {row.name}
|
||||
</Button>,
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>;
|
||||
}}</QueryView>
|
||||
</fieldset>;
|
||||
}
|
||||
|
||||
export default function BomPage({ variantId, packaging = false }: { variantId?: string; packaging?: boolean }) {
|
||||
const config = packaging ? kinds.packaging : kinds.production;
|
||||
const id = uuid.safeParse(variantId);
|
||||
return <WorkspaceShell title={config.title} permission={config.read}>
|
||||
{!variantId ? <FindVariant key={config.api} config={config} /> : id.success ? (
|
||||
<Revisions key={`${config.api}:${id.data}`} config={config} variantId={id.data} />
|
||||
) : <Alert severity="warning">Invalid variant ID.</Alert>}
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
|
@ -1,241 +0,0 @@
|
|||
import { useRef, useState } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { ConfirmAction } from "@/components/ConfirmAction";
|
||||
import { businessAccount, businessEvent, businessInput, businessProfile, businessSearch, decisionInput, submissionInput } from "@/lib/business";
|
||||
import { isUnknownOutcome } from "@/lib/api";
|
||||
import { uuid } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
|
||||
const route = "/admin/business-accounts";
|
||||
const api = "/b2b/accounts";
|
||||
type Account = z.infer<typeof businessAccount>;
|
||||
type Profile = z.infer<typeof businessProfile>;
|
||||
|
||||
const fields = [
|
||||
{ name: "legalName", label: "Legal name", maxLength: 160 },
|
||||
{ name: "tradingName", label: "Trading name", maxLength: 160, optional: true },
|
||||
{ name: "registrationNumber", label: "Registration number", maxLength: 64 },
|
||||
{ name: "taxIdentifier", label: "Tax identifier", maxLength: 64, optional: true },
|
||||
{ name: "countryCode", label: "Country code", maxLength: 2 },
|
||||
{ name: "contactEmail", label: "Contact email", maxLength: 254, type: "email" },
|
||||
{ name: "contactPhone", label: "Contact phone", maxLength: 24, type: "tel", optional: true },
|
||||
{ name: "billingLine1", label: "Billing address", maxLength: 200 },
|
||||
{ name: "billingCity", label: "Billing city", maxLength: 100 },
|
||||
{ name: "billingRegion", label: "Billing region", maxLength: 100 },
|
||||
{ name: "billingPostalCode", label: "Billing postal code", maxLength: 20 },
|
||||
] as const satisfies readonly { name: keyof Profile; label: string; maxLength: number; optional?: boolean; type?: string }[];
|
||||
|
||||
function AccountList() {
|
||||
const { can } = usePlatform();
|
||||
const [search, setSearch] = useState("");
|
||||
const [offset, setOffset] = useState(0);
|
||||
const params = new URLSearchParams({ limit: "25", offset: String(offset), ...(search ? { search } : {}) });
|
||||
const query = usePrivateQuery(`${api}?${params}`, z.array(businessAccount));
|
||||
return <Panel title="Business directory">
|
||||
{can("b2b.manage") && <p><WorkspaceLink href={`${route}/new`}>Create business account</WorkspaceLink></p>}
|
||||
<ActionForm label="Search businesses" reset={false}
|
||||
read={(form) => ({ search: readText(form, "search") })}
|
||||
submit={async (value) => {
|
||||
setSearch(z.object({ search: businessSearch }).parse(value).search);
|
||||
setOffset(0);
|
||||
}}>
|
||||
<Field name="search" label="Business name or code" required={false} maxLength={100} />
|
||||
</ActionForm>
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Business", "Code", "Country", "Status"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
<WorkspaceLink href={`${route}/${row.id}`}>{row.legalName}</WorkspaceLink>,
|
||||
row.code, row.countryCode, row.status,
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function ProfileFields({ account }: { account?: Account }) {
|
||||
return <>
|
||||
{!account && <Field name="code" label="Business code" maxLength={32} helper="The business code is permanent." />}
|
||||
{fields.map((field) => (
|
||||
<Field key={field.name} name={field.name} label={field.label} maxLength={field.maxLength}
|
||||
required={!("optional" in field)} type={"type" in field ? field.type : undefined}
|
||||
value={account?.[field.name] ?? ""} />
|
||||
))}
|
||||
</>;
|
||||
}
|
||||
|
||||
function readProfile(form: FormData) {
|
||||
return Object.fromEntries(fields.map((field) => {
|
||||
const value = readText(form, field.name).trim();
|
||||
return [field.name, "optional" in field ? value || null : value];
|
||||
}));
|
||||
}
|
||||
|
||||
function ReadProfile({ profile }: { profile: Profile }) {
|
||||
return <dl className="permission-list">
|
||||
{fields.map((field) => <div key={field.name}><dt>{field.label}</dt><dd>{profile[field.name] ?? "—"}</dd></div>)}
|
||||
</dl>;
|
||||
}
|
||||
|
||||
function CreateAccount({ refreshDirectory }: { refreshDirectory: () => Promise<void> }) {
|
||||
const { can, request } = usePlatform();
|
||||
const [, navigate] = useLocation();
|
||||
const [uncertainCode, setUncertainCode] = useState("");
|
||||
if (!can("b2b.manage")) return <Alert severity="warning">Your account does not have permission to create business profiles.</Alert>;
|
||||
return <Panel title="New business profile">
|
||||
{uncertainCode ? <Alert severity="warning">The server may have saved {uncertainCode}. Search the business directory for that code before creating it again.</Alert> :
|
||||
<ActionForm label="Save business draft" reset={false}
|
||||
read={(form) => businessInput.parse({ ...readProfile(form), code: readText(form, "code") })}
|
||||
submit={async (value) => {
|
||||
const body = businessInput.parse(value);
|
||||
try {
|
||||
const saved = await request(api, businessAccount, { method: "POST", body });
|
||||
await refreshDirectory();
|
||||
navigate(`${route}/${saved.id}`);
|
||||
} catch (error) {
|
||||
if (isUnknownOutcome(error)) {
|
||||
setUncertainCode(body.code);
|
||||
await refreshDirectory();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}}>
|
||||
<ProfileFields />
|
||||
</ActionForm>}
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () => Promise<void> }) {
|
||||
const { can } = usePlatform();
|
||||
const path = `${api}/${id}`;
|
||||
const query = usePrivateQuery(path, businessAccount);
|
||||
const events = usePrivateQuery(`${path}/events`, z.array(businessEvent));
|
||||
async function refresh() {
|
||||
await Promise.all([query.refetch(), events.refetch(), refreshDirectory()]);
|
||||
}
|
||||
return <QueryView query={query}>{(account) => <>
|
||||
<Panel title={account.legalName}>
|
||||
<p>Business {account.code} · {account.status} · Profile version {account.profileVersion}</p>
|
||||
{can("b2b.price.read") && <WorkspaceLink href={`/admin/b2b-price-lists/account/${account.id}`}>Business price lists</WorkspaceLink>}
|
||||
{can("b2b.quote.read") && <p><WorkspaceLink href={`/admin/b2b-quotes/account/${account.id}`}>Business quotations</WorkspaceLink></p>}
|
||||
{can("b2b.credit.read") && <p><WorkspaceLink href={`/admin/b2b-credit-policies/account/${account.id}`}>Business credit policies</WorkspaceLink></p>}
|
||||
{account.status === "VERIFIED" && can("b2b.credit.read") && can("b2b.credit.propose") &&
|
||||
<p><WorkspaceLink href={`/admin/b2b-credit-policies/new/${account.id}`}>Propose credit terms for this business</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") &&
|
||||
<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} />
|
||||
</Panel>
|
||||
<Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} />
|
||||
<Panel title="Verification history">
|
||||
<QueryView query={events}>{(rows) => (
|
||||
<Table head={["Sequence", "Event", "Date", "Staff ID", "Note"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
row.sequence, row.profileSnapshot ? <details>
|
||||
<summary>Submitted profile version {row.profileSnapshot.profileVersion}</summary>
|
||||
<ReadProfile profile={row.profileSnapshot} />
|
||||
</details> : row.kind, new Date(row.createdAt).toLocaleString(), row.actorId, row.note ?? "—",
|
||||
])} />
|
||||
)}</QueryView>
|
||||
</Panel>
|
||||
</>}</QueryView>;
|
||||
}
|
||||
|
||||
function Review({ account, path, refresh }: { account: Account; path: string; refresh: () => Promise<void> }) {
|
||||
const { can, principal, request } = usePlatform();
|
||||
const sequence = account.latestEvent?.sequence ?? 0;
|
||||
const submit = useIdempotentCommand(`${path}/submit`, submissionInput, businessEvent, `profile:${account.profileVersion}:${sequence}`);
|
||||
const decision = useIdempotentCommand(`${path}/decision`, decisionInput, businessEvent, `submission:${sequence}`);
|
||||
const editable = account.status === "DRAFT" || account.status === "REJECTED";
|
||||
const ownSubmission = account.latestEvent?.actorId === principal?.userId.toLowerCase();
|
||||
const latest = account.latestEvent;
|
||||
const [busy, setBusy] = useState(false);
|
||||
const updating = useRef(false);
|
||||
|
||||
async function whileCurrent(action: () => Promise<unknown>) {
|
||||
if (updating.current) throw new Error("A profile or review update is already in progress.");
|
||||
updating.current = true;
|
||||
setBusy(true);
|
||||
try {
|
||||
const current = await request(path, businessAccount);
|
||||
if (current.profileVersion !== account.profileVersion || current.latestEvent?.id !== latest?.id) {
|
||||
throw new Error("The business profile or review has changed. Open the latest version.");
|
||||
}
|
||||
await action();
|
||||
} finally {
|
||||
try {
|
||||
await refresh();
|
||||
} finally {
|
||||
updating.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return <>
|
||||
{editable && can("b2b.manage") && <Panel title="Prepare for verification">
|
||||
{submit.pending ? (
|
||||
<ActionForm label="Retry verification submission" read={() => ({})} submit={() => whileCurrent(() => submit.run({}))}>
|
||||
<Alert severity="warning">Retrying uses the original submission key for this profile version.</Alert>
|
||||
</ActionForm>
|
||||
) : <>
|
||||
<ActionForm label="Save profile changes" reset={false} lockFields={busy}
|
||||
read={(form) => businessProfile.parse(readProfile(form))}
|
||||
submit={(body) => whileCurrent(() => request(path, businessAccount, { method: "PATCH", body }))}>
|
||||
<ProfileFields account={account} />
|
||||
</ActionForm>
|
||||
<ConfirmAction label="Submit for verification" disabled={busy}
|
||||
message={`Send saved profile version ${account.profileVersion} for review? Confirm that any edits have been saved.`}
|
||||
onConfirm={() => whileCurrent(() => submit.run({}))} />
|
||||
</>}
|
||||
</Panel>}
|
||||
{account.status === "PENDING" && latest?.kind === "SUBMITTED" && latest.profileSnapshot && <Panel title="Submitted profile for review">
|
||||
<p>Profile version {latest.profileSnapshot.profileVersion} · Submitted {new Date(latest.createdAt).toLocaleString()}</p>
|
||||
<ReadProfile profile={latest.profileSnapshot} />
|
||||
{can("b2b.verify") && (ownSubmission ? <Alert severity="info">A different staff member must review this submission.</Alert> :
|
||||
<ActionForm key={decision.pending ? "retry" : "decide"} label={decision.pending ? "Retry verification decision" : "Record verification decision"}
|
||||
read={(form) => decision.pending ? {} : ({ decision: readText(form, "decision"), note: readText(form, "note") })}
|
||||
submit={(value) => whileCurrent(() => decision.run(value))}>
|
||||
{decision.pending ? <Alert severity="warning">Retrying uses the saved {decision.pending.decision.toLowerCase()} decision and note.</Alert> : <>
|
||||
<p>Record the outcome of your manual review of this submitted profile.</p>
|
||||
<Field name="decision" label="Review outcome" options={[
|
||||
{ value: "", label: "Choose an outcome" }, { value: "APPROVED", label: "Approve" }, { value: "REJECTED", label: "Reject" },
|
||||
]} />
|
||||
<Field name="note" label="Review note" maxLength={500} helper="Describe the basis for the decision." />
|
||||
</>}
|
||||
</ActionForm>)}
|
||||
</Panel>}
|
||||
</>;
|
||||
}
|
||||
|
||||
function Accounts({ id, create }: { id?: string; create?: boolean }) {
|
||||
const { scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
const refreshDirectory = () => client.invalidateQueries({
|
||||
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
|
||||
typeof queryKey[2] === "string" && queryKey[2].startsWith(`${api}?`),
|
||||
});
|
||||
const parsed = uuid.safeParse(id);
|
||||
if (!create && !id) return <AccountList />;
|
||||
return <>
|
||||
<WorkspaceLink href={route}>All business accounts</WorkspaceLink>
|
||||
{create ? <CreateAccount refreshDirectory={refreshDirectory} /> : parsed.success ?
|
||||
<Details key={parsed.data} id={parsed.data} refreshDirectory={refreshDirectory} /> :
|
||||
<Alert severity="warning">Invalid business account ID.</Alert>}
|
||||
</>;
|
||||
}
|
||||
|
||||
export default function BusinessAccountsPage(props: { id?: string; create?: boolean }) {
|
||||
return <WorkspaceShell title="B2B Business Accounts" permission="b2b.read">
|
||||
<Accounts {...props} />
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
|
@ -1,327 +0,0 @@
|
|||
import { useEffect, useRef, useState } from "react";
|
||||
import { Link, useLocation } from "wouter";
|
||||
import { z } from "zod";
|
||||
import Button from "@mui/material/Button";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import MenuItem from "@mui/material/MenuItem";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import {
|
||||
cart,
|
||||
address,
|
||||
checkoutIntent,
|
||||
checkoutInput,
|
||||
order,
|
||||
money,
|
||||
moneyTotal,
|
||||
type CheckoutIntent,
|
||||
} from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { ApiError, isUnknownOutcome } from "@/lib/api";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import { Panel, QueryView, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { ApiNotice } from "@/components/ApiNotice";
|
||||
function Cart() {
|
||||
const { request, getIntent, saveIntent, clearIntent } = usePlatform(),
|
||||
query = usePrivateQuery("/cart", cart),
|
||||
addresses = usePrivateQuery("/addresses", z.array(address));
|
||||
const [, navigate] = useLocation();
|
||||
const locked = useRef(false),
|
||||
attempt = useRef<CheckoutIntent | null>(
|
||||
getIntent("checkout") ? checkoutInput.parse(getIntent("checkout")) : null,
|
||||
);
|
||||
const [busy, setBusy] = useState(false),
|
||||
[error, setError] = useState<unknown>(null),
|
||||
[addressId, setAddressId] = useState(""),
|
||||
[coupon, setCoupon] = useState(""),
|
||||
[uncertain, setUncertain] = useState(Boolean(attempt.current)),
|
||||
[review, setReview] = useState(false);
|
||||
const [reviewedVersion, setReviewedVersion] = useState<number | null>(null);
|
||||
useEffect(() => {
|
||||
if (review && query.data && query.data.version !== reviewedVersion) {
|
||||
setReview(false);
|
||||
setError(
|
||||
new Error(
|
||||
"The cart changed. Review the updated quantities before checkout.",
|
||||
),
|
||||
);
|
||||
}
|
||||
}, [review, query.data, reviewedVersion]);
|
||||
async function edit(id: string, quantity: number, version: number) {
|
||||
if (locked.current) return;
|
||||
locked.current = true;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
z.number().int().min(0).max(100).parse(quantity);
|
||||
await request(`/cart/lines/${id}`, z.object({ version: z.number() }), {
|
||||
method: quantity ? "PUT" : "DELETE",
|
||||
body: quantity ? { quantity, version } : { version },
|
||||
});
|
||||
await query.refetch();
|
||||
} catch (error) {
|
||||
setError(error);
|
||||
if (error instanceof ApiError && error.code === "CART_CHANGED")
|
||||
await query.refetch();
|
||||
} finally {
|
||||
locked.current = false;
|
||||
setBusy(false);
|
||||
setReview(false);
|
||||
}
|
||||
}
|
||||
async function checkout() {
|
||||
if (locked.current || (!attempt.current && !query.data)) return;
|
||||
locked.current = true;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (!attempt.current) {
|
||||
if (
|
||||
!query.data ||
|
||||
query.isFetching ||
|
||||
query.data.version !== reviewedVersion
|
||||
)
|
||||
throw new Error("The cart changed. Review it again before checkout.");
|
||||
attempt.current = checkoutIntent(
|
||||
{
|
||||
cartVersion: reviewedVersion,
|
||||
addressId,
|
||||
couponCode: coupon.trim() ? coupon : undefined,
|
||||
},
|
||||
crypto.randomUUID(),
|
||||
);
|
||||
saveIntent("checkout", attempt.current);
|
||||
}
|
||||
const result = await request("/checkout", order, {
|
||||
method: "POST",
|
||||
body: attempt.current,
|
||||
});
|
||||
clearIntent("checkout", attempt.current.idempotencyKey);
|
||||
attempt.current = null;
|
||||
setUncertain(false);
|
||||
await query.refetch();
|
||||
navigate(`/orders/${result.id}`);
|
||||
} catch (error) {
|
||||
setError(error);
|
||||
if (isUnknownOutcome(error)) {
|
||||
setUncertain(true);
|
||||
} else {
|
||||
if (attempt.current)
|
||||
clearIntent("checkout", attempt.current.idempotencyKey);
|
||||
attempt.current = null;
|
||||
setReview(false);
|
||||
await query.refetch();
|
||||
}
|
||||
} finally {
|
||||
locked.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Panel title="Cart">
|
||||
<ApiNotice error={error} />
|
||||
<QueryView query={query}>
|
||||
{(data) => (
|
||||
<>
|
||||
{!data.lines.length ? (
|
||||
<Alert severity="info">
|
||||
Your cart is empty.{" "}
|
||||
<Link href="/products">
|
||||
<u>Explore candles</u>
|
||||
</Link>
|
||||
</Alert>
|
||||
) : (
|
||||
<>
|
||||
<fieldset
|
||||
className="cart-lines"
|
||||
disabled={busy || uncertain || review}
|
||||
>
|
||||
{data.lines.map((line) => (
|
||||
<div
|
||||
className="cart-line"
|
||||
key={`${line.variantId}-${data.version}`}
|
||||
>
|
||||
<div>
|
||||
<h3>
|
||||
{line.variant.product.name} · {line.variant.name}
|
||||
</h3>
|
||||
<p>
|
||||
{line.variant.currency} {money(line.variant.price)}{" "}
|
||||
each
|
||||
</p>
|
||||
{(!line.variant.active ||
|
||||
line.variant.product.status !== "PUBLISHED") && (
|
||||
<Alert severity="warning">
|
||||
This variant is no longer available.
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const quantity = Number(
|
||||
new FormData(e.currentTarget).get("quantity"),
|
||||
);
|
||||
void edit(line.variantId, quantity, data.version);
|
||||
}}
|
||||
>
|
||||
<TextField
|
||||
name="quantity"
|
||||
label={`Quantity for ${line.variant.name}`}
|
||||
type="number"
|
||||
defaultValue={line.quantity}
|
||||
inputProps={{ min: 1, max: 100, step: 1 }}
|
||||
/>
|
||||
<Button type="submit">Update</Button>
|
||||
<Button
|
||||
onClick={() =>
|
||||
edit(line.variantId, 0, data.version)
|
||||
}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
))}
|
||||
</fieldset>
|
||||
<p className="workspace-intro">
|
||||
Estimated merchandise: {data.lines[0].variant.currency}{" "}
|
||||
{moneyTotal(
|
||||
data.lines.map((l) => ({
|
||||
price: l.variant.price,
|
||||
quantity: l.quantity,
|
||||
})),
|
||||
)}
|
||||
</p>
|
||||
<Alert severity="info">
|
||||
The cart does not reserve stock. Checkout rechecks current
|
||||
prices and creates a 15-minute hold. This estimate excludes
|
||||
coupon, tax and shipping.
|
||||
</Alert>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
</Panel>
|
||||
<Panel title="Create an order">
|
||||
<QueryView query={addresses}>
|
||||
{(items) => (
|
||||
<>
|
||||
{!items.length ? (
|
||||
<Alert severity="info">
|
||||
Save an{" "}
|
||||
<Link href="/addresses">
|
||||
<u>address</u>
|
||||
</Link>{" "}
|
||||
before checkout.
|
||||
</Alert>
|
||||
) : (
|
||||
<>
|
||||
<TextField
|
||||
select
|
||||
label="Delivery address"
|
||||
fullWidth
|
||||
value={addressId}
|
||||
onChange={(e) => {
|
||||
setAddressId(e.target.value);
|
||||
setReview(false);
|
||||
}}
|
||||
disabled={busy || uncertain || review}
|
||||
>
|
||||
{items.map((a) => (
|
||||
<MenuItem key={a.id} value={a.id}>
|
||||
{a.recipient} · {a.line1}, {a.city} {a.postalCode}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
<TextField
|
||||
label="Coupon code (optional)"
|
||||
fullWidth
|
||||
value={coupon}
|
||||
onChange={(e) => {
|
||||
setCoupon(e.target.value);
|
||||
setReview(false);
|
||||
}}
|
||||
inputProps={{ maxLength: 40 }}
|
||||
disabled={busy || uncertain || review}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
<Alert severity="warning">
|
||||
Payment collection is unavailable. Creating an order reserves stock;
|
||||
it does not charge you or confirm fulfillment.
|
||||
</Alert>
|
||||
{uncertain ? (
|
||||
<>
|
||||
<Alert severity="warning">
|
||||
The result is unknown. Retry the exact original request to recover
|
||||
it. Do not create another order until you have checked your order
|
||||
history.
|
||||
</Alert>
|
||||
<Button
|
||||
disabled={busy || (!uncertain && query.isFetching)}
|
||||
variant="contained"
|
||||
onClick={checkout}
|
||||
>
|
||||
Retry original checkout
|
||||
</Button>
|
||||
<Link href="/orders">
|
||||
<u>Check orders</u>
|
||||
</Link>
|
||||
</>
|
||||
) : review ? (
|
||||
<>
|
||||
<p>
|
||||
Review the selected address, coupon and cart quantities above.
|
||||
Confirm to create a pending order using the current server prices.
|
||||
</p>
|
||||
<Button disabled={busy} onClick={() => setReview(false)}>
|
||||
Back to editing
|
||||
</Button>
|
||||
<Button
|
||||
disabled={busy || (!uncertain && query.isFetching)}
|
||||
variant="contained"
|
||||
onClick={checkout}
|
||||
>
|
||||
{busy ? "Creating…" : "Confirm order"}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
disabled={
|
||||
busy ||
|
||||
!addressId ||
|
||||
!query.data?.lines.length ||
|
||||
query.isFetching ||
|
||||
addresses.isFetching ||
|
||||
query.isError ||
|
||||
addresses.isError ||
|
||||
query.data.lines.some(
|
||||
(l) =>
|
||||
!l.variant.active || l.variant.product.status !== "PUBLISHED",
|
||||
)
|
||||
}
|
||||
variant="contained"
|
||||
onClick={() => {
|
||||
setReviewedVersion(query.data?.version ?? null);
|
||||
setReview(true);
|
||||
}}
|
||||
>
|
||||
Review checkout
|
||||
</Button>
|
||||
)}
|
||||
</Panel>
|
||||
</>
|
||||
);
|
||||
}
|
||||
export default function CartPage() {
|
||||
return (
|
||||
<WorkspaceShell title="My Cart">
|
||||
<Cart />
|
||||
</WorkspaceShell>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,491 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import { z } from "zod";
|
||||
import Button from "@mui/material/Button";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import {
|
||||
adminProduct,
|
||||
adminProductSummary,
|
||||
productInput,
|
||||
variant,
|
||||
variantInput,
|
||||
group,
|
||||
groupInput,
|
||||
money,
|
||||
prepareProductImage,
|
||||
productImage,
|
||||
productImageAccept,
|
||||
type AdminProduct,
|
||||
uuid,
|
||||
} from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import {
|
||||
ActionForm,
|
||||
Check,
|
||||
Field,
|
||||
Pager,
|
||||
Panel,
|
||||
QueryView,
|
||||
Table,
|
||||
usePrivateQuery,
|
||||
readText,
|
||||
WorkspaceLink,
|
||||
} from "@/components/WorkspaceTools";
|
||||
import { RecordSelection } from "@/components/RecordSelection";
|
||||
import { ConfirmAction } from "@/components/ConfirmAction";
|
||||
import { productImageUrl } from "@/lib/api";
|
||||
import "./products.css";
|
||||
function ProductForm({
|
||||
item,
|
||||
onSave,
|
||||
}: {
|
||||
item?: AdminProduct;
|
||||
onSave: () => Promise<unknown>;
|
||||
}) {
|
||||
const { request } = usePlatform(),
|
||||
[, navigate] = useLocation();
|
||||
return (
|
||||
<ActionForm
|
||||
key={item?.id || "new"}
|
||||
label="Save product"
|
||||
read={(data) => ({
|
||||
name: readText(data, "name"),
|
||||
slug: readText(data, "slug"),
|
||||
description: readText(data, "description"),
|
||||
groupIds: data.getAll("groupIds").map(String),
|
||||
})}
|
||||
submit={async (value) => {
|
||||
const saved = await request(
|
||||
item ? `/products/${item.id}` : "/products",
|
||||
adminProductSummary,
|
||||
{ method: item ? "PUT" : "POST", body: productInput.parse(value) },
|
||||
);
|
||||
await onSave();
|
||||
if (!item) navigate(`/admin/catalog/${saved.id}`);
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
name="name"
|
||||
label="Product name"
|
||||
maxLength={160}
|
||||
value={item?.name}
|
||||
/>
|
||||
<Field
|
||||
name="slug"
|
||||
label="URL slug"
|
||||
maxLength={160}
|
||||
value={item?.slug}
|
||||
helper="Lowercase words separated by hyphens."
|
||||
/>
|
||||
<Field
|
||||
name="description"
|
||||
label="Description"
|
||||
required={false}
|
||||
maxLength={5000}
|
||||
value={item?.description}
|
||||
/>
|
||||
<RecordSelection
|
||||
name="groupIds"
|
||||
label="Categories and collections"
|
||||
path="/catalog-groups"
|
||||
initial={item?.groups.map((g) => g.group.id)}
|
||||
/>
|
||||
</ActionForm>
|
||||
);
|
||||
}
|
||||
function VariantForm({
|
||||
productId,
|
||||
item,
|
||||
onSave,
|
||||
}: {
|
||||
productId: string;
|
||||
item?: z.infer<typeof variant>;
|
||||
onSave: () => Promise<unknown>;
|
||||
}) {
|
||||
const { request } = usePlatform();
|
||||
const [attributes, setAttributes] = useState(
|
||||
Object.entries(item?.attributes || {}),
|
||||
);
|
||||
return (
|
||||
<ActionForm
|
||||
key={item?.id || "new"}
|
||||
label="Save variant"
|
||||
read={(data) => {
|
||||
const entries = attributes.map((_, i) => [
|
||||
readText(data, `key${i}`).trim(),
|
||||
readText(data, `value${i}`),
|
||||
]);
|
||||
if (new Set(entries.map((e) => e[0])).size !== entries.length)
|
||||
throw new Error("Attribute names must be unique.");
|
||||
return {
|
||||
name: readText(data, "name"),
|
||||
sku: readText(data, "sku"),
|
||||
price: readText(data, "price"),
|
||||
currency: readText(data, "currency"),
|
||||
active: data.has("active"),
|
||||
attributes: Object.fromEntries(entries),
|
||||
};
|
||||
}}
|
||||
submit={async (value) => {
|
||||
await request(
|
||||
`/products/${productId}/variants${item ? `/${item.id}` : ""}`,
|
||||
variant,
|
||||
{ method: item ? "PUT" : "POST", body: variantInput.parse(value) },
|
||||
);
|
||||
await onSave();
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
name="name"
|
||||
label="Variant name"
|
||||
maxLength={160}
|
||||
value={item?.name}
|
||||
/>
|
||||
<Field name="sku" label="SKU" maxLength={64} value={item?.sku} />
|
||||
<Field
|
||||
name="price"
|
||||
label="Price"
|
||||
value={item ? money(item.price) : ""}
|
||||
helper="Positive decimal with two fractional digits, e.g. 250.00."
|
||||
/>
|
||||
<Field
|
||||
name="currency"
|
||||
label="Currency"
|
||||
value={item?.currency || "INR"}
|
||||
options={["INR", "USD", "EUR", "GBP"].map((value) => ({
|
||||
value,
|
||||
label: value,
|
||||
}))}
|
||||
/>
|
||||
<Check
|
||||
name="active"
|
||||
label="Active variant"
|
||||
value={item?.active ?? true}
|
||||
/>
|
||||
{attributes.map(([key, value], i) => (
|
||||
<div className="attribute-row" key={i}>
|
||||
<Field
|
||||
name={`key${i}`}
|
||||
label={`Attribute ${i + 1} name`}
|
||||
value={key}
|
||||
onChange={(next) =>
|
||||
setAttributes((rows) =>
|
||||
rows.map((row, index) => (index === i ? [next, row[1]] : row)),
|
||||
)
|
||||
}
|
||||
maxLength={32}
|
||||
/>
|
||||
<Field
|
||||
name={`value${i}`}
|
||||
label={`Attribute ${i + 1} value`}
|
||||
value={value}
|
||||
onChange={(next) =>
|
||||
setAttributes((rows) =>
|
||||
rows.map((row, index) => (index === i ? [row[0], next] : row)),
|
||||
)
|
||||
}
|
||||
maxLength={100}
|
||||
/>
|
||||
<Button
|
||||
onClick={() =>
|
||||
setAttributes((rows) => rows.filter((_, index) => index !== i))
|
||||
}
|
||||
>
|
||||
Remove attribute
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
disabled={attributes.length >= 20}
|
||||
onClick={() => setAttributes((rows) => [...rows, ["", ""]])}
|
||||
>
|
||||
Add attribute
|
||||
</Button>
|
||||
</ActionForm>
|
||||
);
|
||||
}
|
||||
function Groups() {
|
||||
const { request, can } = usePlatform();
|
||||
const [offset, setOffset] = useState(0),
|
||||
[editing, setEditing] = useState<z.infer<typeof group> | null>(null);
|
||||
const query = usePrivateQuery(
|
||||
`/catalog-groups?limit=25&offset=${offset}`,
|
||||
z.array(group),
|
||||
);
|
||||
return (
|
||||
<Panel title="Categories and collections">
|
||||
<QueryView query={query}>
|
||||
{(items) => (
|
||||
<>
|
||||
<Table
|
||||
head={["Name", "Kind", "Slug", "Action"]}
|
||||
rowKeys={items.map((item) => item.id)}
|
||||
rows={items.map((g) => [
|
||||
g.name,
|
||||
g.kind,
|
||||
g.slug,
|
||||
can("catalog.manage") ? (
|
||||
<Button onClick={() => setEditing(g)}>Edit</Button>
|
||||
) : (
|
||||
"Read only"
|
||||
),
|
||||
])}
|
||||
/>
|
||||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
{can("catalog.manage") && (
|
||||
<>
|
||||
<ActionForm
|
||||
key={editing?.id || "new"}
|
||||
label="Save group"
|
||||
read={(data) => ({
|
||||
name: readText(data, "name"),
|
||||
slug: readText(data, "slug"),
|
||||
kind: readText(data, "kind"),
|
||||
})}
|
||||
submit={async (value) => {
|
||||
await request(
|
||||
editing ? `/catalog-groups/${editing.id}` : "/catalog-groups",
|
||||
group,
|
||||
{
|
||||
method: editing ? "PUT" : "POST",
|
||||
body: groupInput.parse(value),
|
||||
},
|
||||
);
|
||||
setEditing(null);
|
||||
await query.refetch();
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
name="name"
|
||||
label="Group name"
|
||||
value={editing?.name}
|
||||
maxLength={100}
|
||||
/>
|
||||
<Field
|
||||
name="slug"
|
||||
label="Group slug"
|
||||
value={editing?.slug}
|
||||
maxLength={100}
|
||||
/>
|
||||
<Field
|
||||
name="kind"
|
||||
label="Group kind"
|
||||
value={editing?.kind || "CATEGORY"}
|
||||
options={["CATEGORY", "COLLECTION"].map((value) => ({
|
||||
value,
|
||||
label: value,
|
||||
}))}
|
||||
/>
|
||||
</ActionForm>
|
||||
{editing && (
|
||||
<Button onClick={() => setEditing(null)}>Cancel editing</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
function Products() {
|
||||
const { can } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const query = usePrivateQuery(
|
||||
`/products?limit=25&offset=${offset}`,
|
||||
z.array(adminProductSummary),
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Panel title="Products">
|
||||
<QueryView query={query}>
|
||||
{(items) => (
|
||||
<>
|
||||
<Table
|
||||
head={["Product", "Status", "Slug"]}
|
||||
rowKeys={items.map((item) => item.id)}
|
||||
rows={items.map((p) => [
|
||||
<WorkspaceLink href={`/admin/catalog/${p.id}`}>
|
||||
{p.name}
|
||||
</WorkspaceLink>,
|
||||
p.status,
|
||||
p.slug,
|
||||
])}
|
||||
/>
|
||||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
</Panel>
|
||||
{can("catalog.manage") && (
|
||||
<Panel title="New draft product">
|
||||
<ProductForm onSave={() => query.refetch()} />
|
||||
</Panel>
|
||||
)}
|
||||
<Groups />
|
||||
</>
|
||||
);
|
||||
}
|
||||
function ProductEditor({ id }: { id: string }) {
|
||||
const { request, can, organization } = usePlatform();
|
||||
const query = usePrivateQuery(`/products/${id}`, adminProduct);
|
||||
const editable = (item: AdminProduct) =>
|
||||
can("catalog.manage") && item.status !== "ARCHIVED";
|
||||
const [editingVariant, setEditingVariant] = useState<
|
||||
z.infer<typeof variant> | undefined
|
||||
>();
|
||||
return (
|
||||
<QueryView query={query}>
|
||||
{(item) => (
|
||||
<>
|
||||
<Panel title={item.name}>
|
||||
<p>Status: {item.status}</p>
|
||||
<p className="workspace-id">Product ID: {item.id}</p>
|
||||
{item.status === "ARCHIVED" ? (
|
||||
<Alert severity="info">Archived products cannot be edited.</Alert>
|
||||
) : (
|
||||
<>
|
||||
{can("catalog.manage") && (
|
||||
<ProductForm item={item} onSave={() => query.refetch()} />
|
||||
)}{" "}
|
||||
{can("catalog.publish") &&
|
||||
["DRAFT", "PUBLISHED", "ARCHIVED"]
|
||||
.filter((status) => status !== item.status)
|
||||
.map((status) => (
|
||||
<ConfirmAction
|
||||
key={status}
|
||||
label={
|
||||
status === "PUBLISHED"
|
||||
? "Publish"
|
||||
: status === "DRAFT"
|
||||
? "Return to draft"
|
||||
: "Archive"
|
||||
}
|
||||
message={
|
||||
status === "ARCHIVED"
|
||||
? "Archive this product? Archived products cannot be edited or republished."
|
||||
: `Change this product to ${status.toLowerCase()}? Publishing requires an active variant.`
|
||||
}
|
||||
onConfirm={async () => {
|
||||
await request(
|
||||
`/products/${id}/status`,
|
||||
adminProductSummary,
|
||||
{ method: "PATCH", body: { status } },
|
||||
);
|
||||
await query.refetch();
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</Panel>
|
||||
<Panel title="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">
|
||||
<Table
|
||||
head={["Variant", "SKU", "Price", "Active", "ID", "Action"]}
|
||||
rowKeys={item.variants.map((item) => item.id)}
|
||||
rows={item.variants.map((v) => [
|
||||
v.name,
|
||||
v.sku,
|
||||
`${v.currency} ${money(v.price)}`,
|
||||
v.active ? "Yes" : "No",
|
||||
v.id,
|
||||
<>
|
||||
{can("catalog.manage") && item.status !== "ARCHIVED" && (
|
||||
<Button onClick={() => setEditingVariant(v)} aria-label={`Edit ${v.name}`}>Edit</Button>
|
||||
)}
|
||||
{can("bom.read") && <div><WorkspaceLink href={`/admin/boms/${v.id}`}>Production BOMs for {v.name}</WorkspaceLink></div>}
|
||||
{can("packaging.read") && <div><WorkspaceLink href={`/admin/packaging-boms/${v.id}`}>Packaging BOMs for {v.name}</WorkspaceLink></div>}
|
||||
{!can("bom.read") && !can("packaging.read") && (!can("catalog.manage") || item.status === "ARCHIVED") && "Read only"}
|
||||
</>,
|
||||
])}
|
||||
/>
|
||||
{can("catalog.manage") && item.status !== "ARCHIVED" && (
|
||||
<>
|
||||
<h3>
|
||||
{editingVariant
|
||||
? `Edit ${editingVariant.name}`
|
||||
: "New variant"}
|
||||
</h3>
|
||||
<VariantForm
|
||||
key={editingVariant?.id || "new"}
|
||||
productId={id}
|
||||
item={editingVariant}
|
||||
onSave={async () => {
|
||||
setEditingVariant(undefined);
|
||||
await query.refetch();
|
||||
}}
|
||||
/>
|
||||
{editingVariant && (
|
||||
<Button onClick={() => setEditingVariant(undefined)}>
|
||||
Cancel editing
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Panel>
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
);
|
||||
}
|
||||
export default function CatalogAdminPage({ id }: { id?: string }) {
|
||||
return (
|
||||
<WorkspaceShell title="Catalog Administration" permission="catalog.read">
|
||||
{id && !uuid.safeParse(id).success ? (
|
||||
<Alert severity="error">Invalid product identifier.</Alert>
|
||||
) : id ? (
|
||||
<ProductEditor key={uuid.parse(id)} id={uuid.parse(id)} />
|
||||
) : (
|
||||
<Products />
|
||||
)}
|
||||
</WorkspaceShell>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,102 +0,0 @@
|
|||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { ActionForm, Field, Panel, QueryView, Table, readText } from "@/components/WorkspaceTools";
|
||||
import { useOptionalPrivateQuery } from "@/components/useOptionalPrivateQuery";
|
||||
import { ApiError } from "@/lib/api";
|
||||
import { bomDetail } from "@/lib/bom";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { batchDetail } from "@/lib/production";
|
||||
import { packagingRun, packagingRunInput } from "@/lib/production-stock";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
import { BatchStock } from "./BatchStock";
|
||||
|
||||
type Batch = z.infer<typeof batchDetail>;
|
||||
type Run = z.infer<typeof packagingRun>;
|
||||
|
||||
export function CompletedBatchOperations({ batch }: { batch: Batch }) {
|
||||
const { can } = usePlatform();
|
||||
const good = batch.completion?.goodQuantity ?? 0;
|
||||
return can("packaging.read") ? <PackagingOperations batch={batch} good={good} /> :
|
||||
can("inventory.read") ? <BatchStock batchId={batch.id} goodQuantity={good} names={materialNames(batch)} /> : null;
|
||||
}
|
||||
|
||||
function materialNames(batch: Batch, run?: Run | null) {
|
||||
return new Map([...batch.plannedMaterials, ...(run?.lines ?? [])].map((line) => [
|
||||
line.materialId, `${line.materialName} (${line.materialCode}) · ${line.unit}`,
|
||||
]));
|
||||
}
|
||||
|
||||
function PackagingOperations({ batch, good }: { batch: Batch; good: number }) {
|
||||
const { can, scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
const path = `/production-batches/${batch.id}/packaging`;
|
||||
const query = useOptionalPrivateQuery(path, packagingRun, "PACKAGING_RUN_NOT_FOUND");
|
||||
const command = useIdempotentCommand(path, packagingRunInput, packagingRun, batch.id);
|
||||
async function submit(input: unknown) {
|
||||
try {
|
||||
const saved = await command.run(input);
|
||||
client.setQueryData(["private", scope, path], saved);
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.code === "PACKAGING_ALREADY_RECORDED") await query.refetch();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return <>
|
||||
<Panel title="Packaging run">
|
||||
<QueryView query={query}>{(run) => {
|
||||
if (run) return <>
|
||||
<p>Recorded {new Date(run.createdAt).toLocaleString()} using BOM {run.bomId}.</p>
|
||||
<Table head={["Material", "Planned", "Used", "Wasted", "Variance", "Waste reason"]}
|
||||
rowKeys={run.lines.map((line) => line.bomLineId)} rows={run.lines.map((line) => [
|
||||
`${line.materialName} (${line.materialCode}) · ${line.unit}`, line.plannedQuantity,
|
||||
line.usedQuantity, line.wastedQuantity, line.varianceQuantity, line.wasteReason ?? "—",
|
||||
])} />
|
||||
</>;
|
||||
if (!good) return <Alert severity="info">This batch has no good pieces to package.</Alert>;
|
||||
if (!can("packaging.record")) return <Alert severity="info">Awaiting a packaging run.</Alert>;
|
||||
if (command.pending) return <ActionForm label="Retry packaging run" read={() => ({})} submit={submit}>
|
||||
<Alert severity="warning">The server may have recorded the run. Retrying uses the original BOM and quantities.</Alert>
|
||||
</ActionForm>;
|
||||
return <PackagingForm variantId={batch.bom.variantId} good={good} submit={submit} />;
|
||||
}}</QueryView>
|
||||
</Panel>
|
||||
{can("inventory.read") && (
|
||||
<BatchStock batchId={batch.id} goodQuantity={good} names={materialNames(batch, query.data)}
|
||||
packagingRecorded={good === 0 ? false : query.data === undefined ? undefined : query.data !== null} />
|
||||
)}
|
||||
</>;
|
||||
}
|
||||
|
||||
function PackagingForm({ variantId, good, submit }: {
|
||||
variantId: string;
|
||||
good: number;
|
||||
submit: (input: unknown) => Promise<void>;
|
||||
}) {
|
||||
const query = useOptionalPrivateQuery(`/variants/${variantId}/packaging-boms/active`, bomDetail, "BOM_NOT_FOUND");
|
||||
return <QueryView query={query}>{(bom) => {
|
||||
if (!bom) return <Alert severity="info">Activate a packaging BOM for this variant before recording its run.</Alert>;
|
||||
if (good % bom.outputQuantity !== 0) return <Alert severity="warning">
|
||||
The {good} good pieces must be a multiple of the active packaging BOM yield of {bom.outputQuantity}.
|
||||
</Alert>;
|
||||
return <ActionForm key={bom.id} label="Record packaging run" read={(form) => ({
|
||||
bomId: bom.id,
|
||||
lines: bom.lines.map((line) => ({
|
||||
bomLineId: line.id,
|
||||
usedQuantity: readText(form, `${line.id}-used`).trim(),
|
||||
wastedQuantity: readText(form, `${line.id}-wasted`).trim(),
|
||||
wasteReason: readText(form, `${line.id}-reason`).trim() || undefined,
|
||||
})),
|
||||
})} submit={submit}>
|
||||
<p>Record actual packaging for {good} good pieces using revision {bom.revision}. This record is final.</p>
|
||||
{bom.lines.map((line) => (
|
||||
<fieldset className="record-picker" key={line.id}>
|
||||
<legend>{line.materialName} ({line.materialCode}) · {line.unit}</legend>
|
||||
<Field name={`${line.id}-used`} label={`Used quantity for ${line.materialName}`} maxLength={13} helper="Use three decimal places." />
|
||||
<Field name={`${line.id}-wasted`} label={`Wasted quantity for ${line.materialName}`} value="0.000" maxLength={13} />
|
||||
<Field name={`${line.id}-reason`} label={`Waste reason for ${line.materialName}`} required={false} maxLength={500} />
|
||||
</fieldset>
|
||||
))}
|
||||
</ActionForm>;
|
||||
}}</QueryView>;
|
||||
}
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { ActionForm, Field, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { useOptionalPrivateQuery } from "@/components/useOptionalPrivateQuery";
|
||||
import { ApiError } from "@/lib/api";
|
||||
import { batchSnapshot, bomEstimate, costCurrencies, snapshotInput } from "@/lib/costing";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
|
||||
export function BomCostEstimate({ path }: { path: string }) {
|
||||
const [currency, setCurrency] = useState("INR");
|
||||
const query = usePrivateQuery(`${path}/cost-estimate?currency=${currency}`, bomEstimate);
|
||||
return <Panel title="Standard cost estimate">
|
||||
<Field name="currency" label="Estimate currency" value={currency} onChange={setCurrency} options={costCurrencies} />
|
||||
<QueryView query={query}>{(data) => <>
|
||||
<p>{data.currency} {data.estimatedTotal} for {data.outputQuantity} pieces · Calculated {new Date(data.estimatedAt).toLocaleString()}</p>
|
||||
<Table head={["Material", "Quantity", "Rate per unit", "Rate revision", "Estimated cost"]}
|
||||
rowKeys={data.lines.map((line) => line.bomLineId)}
|
||||
rows={data.lines.map((line) => [
|
||||
<WorkspaceLink href={`/admin/material-cost-rates/${line.materialId}`}>{line.materialName} ({line.materialCode})</WorkspaceLink>,
|
||||
`${line.quantity} ${line.unit}`, `${data.currency} ${line.unitCost}`, line.rateRevision,
|
||||
`${data.currency} ${line.estimatedCost}`,
|
||||
])} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
export function BatchCostSnapshot({ batchId, goodQuantity }: { batchId: string; goodQuantity: number }) {
|
||||
const { can, scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
const path = `/production-batches/${batchId}/cost-snapshot`;
|
||||
const query = useOptionalPrivateQuery(path, batchSnapshot, "BATCH_COST_NOT_FOUND");
|
||||
const command = useIdempotentCommand(path, snapshotInput, batchSnapshot, batchId);
|
||||
const pending = command.pending;
|
||||
|
||||
return <Panel title="Batch cost snapshot">
|
||||
<p>Standard material costs include production and packaging use and waste. Labor, overhead, tax and freight are excluded.</p>
|
||||
<QueryView query={query}>{(snapshot) => {
|
||||
if (snapshot) return <>
|
||||
<p>Saved {new Date(snapshot.createdAt).toLocaleString()} · {snapshot.goodQuantity} good pieces</p>
|
||||
<dl className="order-totals">
|
||||
<dt>Production</dt><dd>{snapshot.currency} {snapshot.productionTotal}</dd>
|
||||
<dt>Packaging</dt><dd>{snapshot.currency} {snapshot.packagingTotal}</dd>
|
||||
<dt>Total</dt><dd>{snapshot.currency} {snapshot.total}</dd>
|
||||
</dl>
|
||||
<Table head={["Stage", "Material", "Used", "Wasted", "Rate per unit", "Rate revision", "Cost"]}
|
||||
rowKeys={snapshot.lines.map((line) => `${line.kind}:${line.bomLineId}`)}
|
||||
rows={snapshot.lines.map((line) => [
|
||||
line.kind === "PRODUCTION" ? "Production" : "Packaging",
|
||||
<WorkspaceLink href={`/admin/material-cost-rates/${line.materialId}`}>{line.materialName} ({line.materialCode})</WorkspaceLink>,
|
||||
`${line.usedQuantity} ${line.unit}`, `${line.wastedQuantity} ${line.unit}`,
|
||||
`${snapshot.currency} ${line.unitCost}`, line.rateRevision, `${snapshot.currency} ${line.lineCost}`,
|
||||
])} />
|
||||
</>;
|
||||
if (!can("cost.manage")) return <Alert severity="info">No cost snapshot recorded.</Alert>;
|
||||
return <ActionForm key={pending ? "retry" : "create"} label={pending ? "Retry cost snapshot" : "Create cost snapshot"}
|
||||
read={(form) => pending ? {} : ({ currency: readText(form, "currency") })}
|
||||
submit={async (body) => {
|
||||
try {
|
||||
const saved = await command.run(body);
|
||||
client.setQueryData(["private", scope, path], saved);
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.code === "BATCH_COST_ALREADY_RECORDED") await query.refetch();
|
||||
throw error;
|
||||
}
|
||||
}}>
|
||||
{pending ? <Alert severity="warning">The server may have saved the snapshot. Retrying uses the original currency {pending.currency}.</Alert> : <>
|
||||
<p>Record usage for every production material{goodQuantity > 0 ? " and complete the packaging run" : ""}. Creating a snapshot fixes its currency and rates.</p>
|
||||
<Field name="currency" label="Snapshot currency" options={costCurrencies} value="INR" />
|
||||
</>}
|
||||
</ActionForm>;
|
||||
}}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
|
@ -1,171 +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 { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readNumber, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { ApiError } from "@/lib/api";
|
||||
import { currency, uuid } from "@/lib/commerce";
|
||||
import { creditDecisionInput, creditPolicy, creditProposalInput, creditStatus, creditSuspensionInput } from "@/lib/credit";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
|
||||
const api = "/b2b/credit-policies";
|
||||
const route = "/admin/b2b-credit-policies";
|
||||
type Policy = z.infer<typeof creditPolicy>;
|
||||
|
||||
function useRefreshCreditLists() {
|
||||
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 PolicyList({ accountId }: { accountId?: string }) {
|
||||
const { can } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [status, setStatus] = useState("ALL");
|
||||
const params = new URLSearchParams({ limit: "25", offset: String(offset) });
|
||||
if (accountId) params.set("accountId", accountId);
|
||||
if (status !== "ALL") params.set("status", status);
|
||||
const query = usePrivateQuery(`${api}?${params}`, z.array(creditPolicy));
|
||||
return <Panel title="Policy history">
|
||||
{accountId && <p className="workspace-id">Business account {accountId}</p>}
|
||||
{can("b2b.credit.propose") && <p><WorkspaceLink href={`${route}/new${accountId ? `/${accountId}` : ""}`}>Propose credit terms</WorkspaceLink></p>}
|
||||
<Field name="status" label="Policy status" value={status} onChange={(value) => { setStatus(value); setOffset(0); }}
|
||||
options={[{ value: "ALL", label: "All statuses" }, ...creditStatus.options.map((value) => ({ value, label: value }))]} />
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Business account ID", "Credit limit", "Net days", "Status", "Proposed"]}
|
||||
rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
<WorkspaceLink href={`${route}/${row.id}`}>{row.accountId}</WorkspaceLink>,
|
||||
`${row.currency} ${row.creditLimit}`, row.netDays, row.status, new Date(row.createdAt).toLocaleString(),
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function ProposePolicy({ accountId }: { accountId?: string }) {
|
||||
const { can } = usePlatform();
|
||||
const [, navigate] = useLocation();
|
||||
const refresh = useRefreshCreditLists();
|
||||
const command = useIdempotentCommand(api, creditProposalInput, creditPolicy, "propose");
|
||||
const pending = command.pending;
|
||||
if (!can("b2b.credit.propose")) return <Alert severity="warning">Your account does not have permission to propose credit terms.</Alert>;
|
||||
return <Panel title="Propose credit terms">
|
||||
<p>Propose terms for a verified business account. A different staff member must review them.</p>
|
||||
<ActionForm key={pending ? "retry" : "new"} label={pending ? "Retry credit proposal" : "Submit credit proposal"} reset={false}
|
||||
read={(form) => pending ? {} : ({
|
||||
accountId: accountId ?? readText(form, "accountId").trim(),
|
||||
currency: readText(form, "currency"),
|
||||
creditLimit: readText(form, "creditLimit").trim(),
|
||||
netDays: readNumber(form, "netDays"),
|
||||
rationale: readText(form, "rationale"),
|
||||
})}
|
||||
submit={async (input) => {
|
||||
const saved = await command.run(input);
|
||||
await refresh();
|
||||
navigate(`${route}/${saved.id}`);
|
||||
}}>
|
||||
{pending ? <Alert severity="warning">
|
||||
The server may have saved this proposal. Retrying reuses {pending.currency} {pending.creditLimit} with net {pending.netDays} days for account {pending.accountId}.
|
||||
</Alert> : <>
|
||||
{accountId ? <p className="workspace-id">Business account {accountId}</p> :
|
||||
<Field name="accountId" label="Business account ID" maxLength={36} helper={can("b2b.read") ? "Find the account ID in the business directory." : undefined} />}
|
||||
{!accountId && can("b2b.read") && <WorkspaceLink href="/admin/business-accounts">Business directory</WorkspaceLink>}
|
||||
<Field name="currency" label="Policy currency" value="INR" options={currency.options.map((value) => ({ value, label: value }))} />
|
||||
<Field name="creditLimit" label="Credit limit" maxLength={17} helper="Use two decimal places." />
|
||||
<Field name="netDays" label="Net days" type="number" helper="Enter 1 to 180 days." />
|
||||
<Field name="rationale" label="Proposal rationale" maxLength={500} />
|
||||
</>}
|
||||
</ActionForm>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function PolicyDetail({ id }: { id: string }) {
|
||||
const { can } = usePlatform();
|
||||
const query = usePrivateQuery(`${api}/${id}`, creditPolicy);
|
||||
return <QueryView query={query}>{(policy) => <>
|
||||
<Panel title="Credit terms">
|
||||
<p>{policy.status} · {policy.currency} {policy.creditLimit} · Net {policy.netDays} days</p>
|
||||
<p className="workspace-id">Business account {policy.accountId}</p>
|
||||
<WorkspaceLink href={`${route}/account/${policy.accountId}`}>All policies for this business</WorkspaceLink>
|
||||
{can("b2b.read") && <p><WorkspaceLink href={`/admin/business-accounts/${policy.accountId}`}>Business profile</WorkspaceLink></p>}
|
||||
<p>Proposed {new Date(policy.createdAt).toLocaleString()} by {policy.proposedById}</p>
|
||||
<p>{policy.rationale}</p>
|
||||
<PolicyReview policy={policy} refresh={query.refetch} />
|
||||
</Panel>
|
||||
<Panel title="Decision history">
|
||||
<Table head={["Sequence", "Event", "Staff ID", "Recorded", "Note"]}
|
||||
rowKeys={policy.events.map((event) => event.id)} rows={policy.events.map((event) => [
|
||||
event.sequence, event.kind, event.actorId, new Date(event.createdAt).toLocaleString(), event.note,
|
||||
])} />
|
||||
</Panel>
|
||||
</>}</QueryView>;
|
||||
}
|
||||
|
||||
function PolicyReview({ policy, refresh }: { policy: Policy; refresh: () => Promise<unknown> }) {
|
||||
const { can, principal, scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
const refreshLists = useRefreshCreditLists();
|
||||
const path = `${api}/${policy.id}`;
|
||||
const decision = useIdempotentCommand(`${path}/decision`, creditDecisionInput, creditPolicy, policy.id);
|
||||
const suspend = useIdempotentCommand(`${path}/suspend`, creditSuspensionInput, creditPolicy, policy.id);
|
||||
if (!can("b2b.credit.review")) return null;
|
||||
if (policy.status === "PROPOSED" && policy.proposedById === principal?.userId.toLowerCase()) {
|
||||
return <Alert severity="info">A different staff member must approve or reject this proposal.</Alert>;
|
||||
}
|
||||
if (policy.status !== "PROPOSED" && policy.status !== "ACTIVE") return null;
|
||||
|
||||
const reviewing = policy.status === "PROPOSED";
|
||||
const command = reviewing ? decision : suspend;
|
||||
const pending = command.pending;
|
||||
const pendingDecision = reviewing ? decision.pending?.decision : undefined;
|
||||
const label = reviewing ? "Record credit decision" : "Suspend credit policy";
|
||||
return <ActionForm key={`${policy.status}:${Boolean(pending)}`} label={pending ? `Retry ${reviewing ? "credit decision" : "suspension"}` : label}
|
||||
read={(form) => pending ? {} : ({
|
||||
note: readText(form, "note"),
|
||||
...(reviewing ? { decision: readText(form, "decision") } : {}),
|
||||
})}
|
||||
submit={async (input) => {
|
||||
try {
|
||||
const saved = await command.run(input);
|
||||
client.setQueryData(["private", scope, path], saved);
|
||||
await refreshLists();
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && ["B2B_CREDIT_REVIEW_STATE", "B2B_CREDIT_SUSPEND_STATE"].includes(error.code ?? "")) {
|
||||
await Promise.all([refresh(), refreshLists()]);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}}>
|
||||
{pending ? <Alert severity="warning">Retrying reuses the original {pendingDecision?.toLowerCase() ?? "suspension"} and note.</Alert> : <>
|
||||
{reviewing ? <>
|
||||
<p>Approval is final. The business can have one active policy in {policy.currency}.</p>
|
||||
<Field name="decision" label="Credit decision" options={[
|
||||
{ value: "", label: "Choose an outcome" },
|
||||
{ value: "APPROVED", label: "Approve" },
|
||||
{ value: "REJECTED", label: "Reject" },
|
||||
]} />
|
||||
</> : <p>Suspending retires these terms and frees the active slot for a new policy.</p>}
|
||||
<Field name="note" label={reviewing ? "Decision note" : "Suspension note"} maxLength={500} />
|
||||
</>}
|
||||
</ActionForm>;
|
||||
}
|
||||
|
||||
export default function CreditPoliciesPage({ id, accountId, propose = false }: { id?: string; accountId?: string; propose?: boolean }) {
|
||||
const policy = uuid.safeParse(id);
|
||||
const account = uuid.safeParse(accountId);
|
||||
return <WorkspaceShell title="B2B Credit Policies" permission="b2b.credit.read">
|
||||
{(id || accountId || propose) && <WorkspaceLink href={route}>All credit policies</WorkspaceLink>}
|
||||
<p>These policies record credit limits and terms. Checkout and receivables are separate workflows.</p>
|
||||
{(id && !policy.success) || (accountId && !account.success) ? <Alert severity="warning">Invalid policy or business account ID.</Alert> :
|
||||
propose ? <ProposePolicy key={account.data ?? "new"} accountId={account.data} /> :
|
||||
policy.success ? <PolicyDetail key={policy.data} id={policy.data} /> :
|
||||
<PolicyList key={account.data ?? "all"} accountId={account.data} />}
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
|
@ -1,370 +0,0 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import {
|
||||
warehouse,
|
||||
warehouseInput,
|
||||
stock,
|
||||
stockInput,
|
||||
stockDetail,
|
||||
adjustmentInput,
|
||||
ledger,
|
||||
reservation,
|
||||
reservationInput,
|
||||
uuid,
|
||||
} from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import {
|
||||
ActionForm,
|
||||
Field,
|
||||
Pager,
|
||||
Panel,
|
||||
QueryView,
|
||||
Table,
|
||||
usePrivateQuery,
|
||||
readText,
|
||||
readNumber,
|
||||
WorkspaceLink,
|
||||
} from "@/components/WorkspaceTools";
|
||||
import { ConfirmAction } from "@/components/ConfirmAction";
|
||||
function StockList() {
|
||||
const { request, can } = usePlatform();
|
||||
const [offset, setOffset] = useState(0),
|
||||
[warehouseOffset, setWarehouseOffset] = useState(0);
|
||||
const query = usePrivateQuery(
|
||||
`/inventory/stock-items?limit=25&offset=${offset}`,
|
||||
z.array(stock),
|
||||
),
|
||||
warehouses = usePrivateQuery(
|
||||
`/inventory/warehouses?limit=25&offset=${warehouseOffset}`,
|
||||
z.array(warehouse),
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Panel title="Finished-goods stock">
|
||||
<QueryView query={query}>
|
||||
{(items) => (
|
||||
<>
|
||||
<Table
|
||||
head={["Stock item", "Variant", "Warehouse", "On hand"]}
|
||||
rowKeys={items.map((item) => item.id)}
|
||||
rows={items.map((s) => [
|
||||
<WorkspaceLink href={`/admin/inventory/${s.id}`}>
|
||||
{s.id}
|
||||
</WorkspaceLink>,
|
||||
s.variantId,
|
||||
s.warehouseId,
|
||||
s.onHand,
|
||||
])}
|
||||
/>
|
||||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
{can("inventory.manage") && (
|
||||
<ActionForm
|
||||
label="Create stock item"
|
||||
read={(data) => ({
|
||||
variantId: readText(data, "variantId"),
|
||||
warehouseId: readText(data, "warehouseId"),
|
||||
})}
|
||||
submit={async (value) => {
|
||||
await request("/inventory/stock-items", stock, {
|
||||
method: "POST",
|
||||
body: stockInput.parse(value),
|
||||
});
|
||||
await query.refetch();
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
name="variantId"
|
||||
label="Variant UUID"
|
||||
helper="Copy the variant ID from catalog administration."
|
||||
/>
|
||||
<Field
|
||||
name="warehouseId"
|
||||
label="Warehouse UUID"
|
||||
helper="Copy the warehouse ID from the warehouse list below."
|
||||
/>
|
||||
</ActionForm>
|
||||
)}
|
||||
</Panel>
|
||||
<Panel title="Warehouses">
|
||||
<QueryView query={warehouses}>
|
||||
{(items) => (
|
||||
<>
|
||||
<Table
|
||||
head={["Warehouse", "ID"]}
|
||||
rowKeys={items.map((item) => item.id)}
|
||||
rows={items.map((w) => [w.name, w.id])}
|
||||
/>
|
||||
<Pager
|
||||
offset={warehouseOffset}
|
||||
count={items.length}
|
||||
onPage={setWarehouseOffset}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
{can("inventory.manage") && (
|
||||
<ActionForm
|
||||
label="Create warehouse"
|
||||
read={(data) => ({ name: readText(data, "name") })}
|
||||
submit={async (value) => {
|
||||
await request("/inventory/warehouses", warehouse, {
|
||||
method: "POST",
|
||||
body: warehouseInput.parse(value),
|
||||
});
|
||||
await warehouses.refetch();
|
||||
}}
|
||||
>
|
||||
<Field name="name" label="Warehouse name" maxLength={100} />
|
||||
</ActionForm>
|
||||
)}
|
||||
</Panel>
|
||||
</>
|
||||
);
|
||||
}
|
||||
function ReservationCard({ id }: { id: string }) {
|
||||
const { request, can, scope } = usePlatform(),
|
||||
query = usePrivateQuery(`/inventory/reservations/${id}`, reservation);
|
||||
const client = useQueryClient(),
|
||||
{ data, refetch } = query;
|
||||
useEffect(() => {
|
||||
if (data?.status !== "ACTIVE") return;
|
||||
const timer = setTimeout(
|
||||
() => {
|
||||
void client.invalidateQueries({
|
||||
predicate: (query) =>
|
||||
query.queryKey[0] === "private" &&
|
||||
query.queryKey[1] === scope &&
|
||||
String(query.queryKey[2]).startsWith("/inventory/"),
|
||||
});
|
||||
},
|
||||
Math.max(1000, Date.parse(data.expiresAt) - Date.now() + 250),
|
||||
);
|
||||
return () => clearTimeout(timer);
|
||||
}, [data, client, scope]);
|
||||
async function refreshStock() {
|
||||
await refetch();
|
||||
await client.invalidateQueries({
|
||||
predicate: (query) =>
|
||||
query.queryKey[0] === "private" &&
|
||||
query.queryKey[1] === scope &&
|
||||
String(query.queryKey[2]).startsWith("/inventory/"),
|
||||
});
|
||||
}
|
||||
return (
|
||||
<QueryView query={query}>
|
||||
{(record) => (
|
||||
<>
|
||||
<p className="workspace-id">
|
||||
Reservation {record.id}: {record.status}, {record.quantity} units.
|
||||
Expires {new Date(record.expiresAt).toLocaleString()}.
|
||||
</p>
|
||||
{record.orderId && (
|
||||
<Alert severity="info">
|
||||
This hold is managed by its order and cannot be committed or
|
||||
released here.
|
||||
</Alert>
|
||||
)}
|
||||
{record.status === "ACTIVE" && !record.orderId && (
|
||||
<>
|
||||
<ConfirmAction
|
||||
label="Release reservation"
|
||||
message="Release this standalone hold? Order-managed holds cannot be changed here."
|
||||
onConfirm={async () => {
|
||||
await request(
|
||||
`/inventory/reservations/${id}/release`,
|
||||
reservation,
|
||||
{ method: "POST" },
|
||||
);
|
||||
await refreshStock();
|
||||
}}
|
||||
/>
|
||||
{can("inventory.commit") && (
|
||||
<ConfirmAction
|
||||
label="Commit reservation"
|
||||
message="Commit this reservation? This deducts finished-goods stock and writes an immutable ledger entry."
|
||||
onConfirm={async () => {
|
||||
await request(
|
||||
`/inventory/reservations/${id}/commit`,
|
||||
reservation,
|
||||
{ method: "POST" },
|
||||
);
|
||||
await refreshStock();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
);
|
||||
}
|
||||
function StockEditor({ id }: { id: string }) {
|
||||
const { can } = usePlatform();
|
||||
const [offset, setOffset] = useState(0),
|
||||
[reservationId, setReservationId] = useState("");
|
||||
const query = usePrivateQuery(`/inventory/stock-items/${id}`, stockDetail),
|
||||
history = usePrivateQuery(
|
||||
`/inventory/stock-items/${id}/ledger?limit=25&offset=${offset}`,
|
||||
z.array(ledger),
|
||||
);
|
||||
const adjust = useIdempotentCommand(
|
||||
"/inventory/adjustments",
|
||||
adjustmentInput,
|
||||
ledger,
|
||||
id,
|
||||
),
|
||||
reserve = useIdempotentCommand(
|
||||
"/inventory/reservations",
|
||||
reservationInput,
|
||||
reservation,
|
||||
id,
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Panel title="Stock balance">
|
||||
<QueryView query={query}>
|
||||
{(s) => (
|
||||
<>
|
||||
<p className="workspace-id">
|
||||
Stock item: {s.id}
|
||||
<br />
|
||||
Variant: {s.variantId}
|
||||
<br />
|
||||
Warehouse: {s.warehouseId}
|
||||
</p>
|
||||
<dl className="order-totals">
|
||||
<dt>On hand</dt>
|
||||
<dd>{s.onHand}</dd>
|
||||
<dt>Reserved</dt>
|
||||
<dd>{s.reserved}</dd>
|
||||
<dt>Available</dt>
|
||||
<dd>{s.available}</dd>
|
||||
</dl>
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
</Panel>
|
||||
{can("inventory.adjust") && (
|
||||
<Panel title="Reasoned stock adjustment">
|
||||
{adjust.uncertain && (
|
||||
<Alert severity="warning">
|
||||
The result is unknown. Retry the original adjustment; the same key
|
||||
and input will be reused. Check the ledger before starting another
|
||||
adjustment.
|
||||
</Alert>
|
||||
)}
|
||||
<ActionForm
|
||||
label={
|
||||
adjust.uncertain ? "Retry original adjustment" : "Post adjustment"
|
||||
}
|
||||
lockFields={adjust.uncertain}
|
||||
read={(data) => ({
|
||||
stockItemId: id,
|
||||
delta: readNumber(data, "delta"),
|
||||
reason: readText(data, "reason"),
|
||||
})}
|
||||
submit={async (value) => {
|
||||
await adjust.run(value);
|
||||
await query.refetch();
|
||||
await history.refetch();
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
name="delta"
|
||||
label="Quantity change (+ or −)"
|
||||
type="number"
|
||||
/>
|
||||
<Field name="reason" label="Adjustment reason" maxLength={200} />
|
||||
</ActionForm>
|
||||
</Panel>
|
||||
)}
|
||||
{can("inventory.reserve") && (
|
||||
<Panel title="Standalone stock reservation">
|
||||
{reserve.uncertain && (
|
||||
<Alert severity="warning">
|
||||
Retry the original reservation to recover the same result.
|
||||
</Alert>
|
||||
)}
|
||||
<ActionForm
|
||||
label={
|
||||
reserve.uncertain ? "Retry original reservation" : "Reserve stock"
|
||||
}
|
||||
lockFields={reserve.uncertain}
|
||||
read={(data) => ({
|
||||
stockItemId: id,
|
||||
quantity: readNumber(data, "quantity"),
|
||||
ttlMinutes: readNumber(data, "ttlMinutes"),
|
||||
})}
|
||||
submit={async (value) => {
|
||||
const result = await reserve.run(value);
|
||||
setReservationId(result.id);
|
||||
await query.refetch();
|
||||
}}
|
||||
>
|
||||
<Field name="quantity" label="Units to reserve" type="number" />
|
||||
<Field
|
||||
name="ttlMinutes"
|
||||
label="Hold duration in minutes"
|
||||
type="number"
|
||||
value={15}
|
||||
/>
|
||||
</ActionForm>
|
||||
<ActionForm
|
||||
label="Look up own reservation"
|
||||
read={(data) => readText(data, "id")}
|
||||
submit={async (value) => {
|
||||
setReservationId(z.string().uuid().parse(value));
|
||||
}}
|
||||
>
|
||||
<Field name="id" label="Reservation UUID" />
|
||||
</ActionForm>
|
||||
{reservationId && (
|
||||
<ReservationCard key={reservationId} id={reservationId} />
|
||||
)}
|
||||
</Panel>
|
||||
)}
|
||||
<Panel title="Immutable stock ledger">
|
||||
<QueryView query={history}>
|
||||
{(items) => (
|
||||
<>
|
||||
<Table
|
||||
head={["Time", "Change", "Reason"]}
|
||||
rowKeys={items.map((item) => item.id)}
|
||||
rows={items.map((e) => [
|
||||
new Date(e.createdAt).toLocaleString(),
|
||||
e.delta,
|
||||
e.reason,
|
||||
])}
|
||||
/>
|
||||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
</Panel>
|
||||
</>
|
||||
);
|
||||
}
|
||||
export default function InventoryPage({ id }: { id?: string }) {
|
||||
return (
|
||||
<WorkspaceShell
|
||||
title="Finished-goods Inventory"
|
||||
permission="inventory.read"
|
||||
>
|
||||
{id && !uuid.safeParse(id).success ? (
|
||||
<Alert severity="error">Invalid stock identifier.</Alert>
|
||||
) : id ? (
|
||||
<StockEditor key={uuid.parse(id)} id={uuid.parse(id)} />
|
||||
) : (
|
||||
<StockList />
|
||||
)}
|
||||
</WorkspaceShell>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,102 +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 Button from "@mui/material/Button";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { isUnknownOutcome } from "@/lib/api";
|
||||
import { uuid } from "@/lib/commerce";
|
||||
import { costCurrencies, costRate, costRateInput } from "@/lib/costing";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
|
||||
const route = "/admin/material-cost-rates";
|
||||
|
||||
function OpenMaterial() {
|
||||
const { can } = usePlatform();
|
||||
const [, navigate] = useLocation();
|
||||
return <Panel title="Open material rates">
|
||||
{can("procurement.read") && <p>Choose a material from the <WorkspaceLink href="/admin/procurement/materials">material directory</WorkspaceLink>.</p>}
|
||||
<ActionForm label="Open cost rates" read={(data) => ({ materialId: readText(data, "materialId").trim() })}
|
||||
submit={async (input) => {
|
||||
const { materialId } = z.object({ materialId: uuid }).parse(input);
|
||||
navigate(`${route}/${materialId}`);
|
||||
}}>
|
||||
<Field name="materialId" label="Material ID" maxLength={36} />
|
||||
</ActionForm>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function Rates({ id }: { id: string }) {
|
||||
const { can, request, scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
const [currency, setCurrency] = useState("INR");
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [uncertain, setUncertain] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const path = `/materials/${id}/cost-rates`;
|
||||
const page = `${path}?currency=${currency}&limit=25&offset=${offset}`;
|
||||
const query = usePrivateQuery(page, z.array(costRate));
|
||||
|
||||
async function refresh() {
|
||||
setOffset(0);
|
||||
await client.invalidateQueries({
|
||||
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
|
||||
typeof queryKey[2] === "string" &&
|
||||
(queryKey[2].startsWith(`${path}?currency=${currency}&`) || queryKey[2].endsWith(`/cost-estimate?currency=${currency}`)),
|
||||
});
|
||||
}
|
||||
|
||||
return <>
|
||||
<WorkspaceLink href={route}>Open another material</WorkspaceLink>
|
||||
<p className="workspace-id">Material ID {id}</p>
|
||||
<Panel title="Rate history">
|
||||
<fieldset disabled={saving} className="cart-lines">
|
||||
<Field name="currency" label="Rate currency" value={currency} options={costCurrencies}
|
||||
onChange={(value) => { setCurrency(value); setOffset(0); }} />
|
||||
</fieldset>
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Revision", "Rate per native unit", "Recorded"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [row.revision, `${row.currency} ${row.unitCost}`, new Date(row.createdAt).toLocaleString()])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>
|
||||
{can("cost.manage") && <Panel title={`New ${currency} rate revision`}>
|
||||
{uncertain ? <Alert severity="warning">
|
||||
The server may have saved the {uncertain} rate. Check its latest revision before recording another rate.
|
||||
<Button onClick={() => {
|
||||
setCurrency(uncertain);
|
||||
setOffset(0);
|
||||
void client.invalidateQueries({ queryKey: ["private", scope, `${path}?currency=${uncertain}&limit=25&offset=0`] });
|
||||
}}>Check rate history</Button>
|
||||
</Alert> : <ActionForm key={currency} label="Record standard cost rate"
|
||||
read={(form) => costRateInput.parse({ currency, unitCost: readText(form, "unitCost").trim() })}
|
||||
submit={async (body) => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await request(path, costRate, { method: "POST", body });
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
if (isUnknownOutcome(error)) {
|
||||
setUncertain(currency);
|
||||
await refresh();
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}}>
|
||||
<p>Each rate is an immutable revision. Enter the cost per material’s native unit.</p>
|
||||
<Field name="unitCost" label={`Unit cost in ${currency}`} maxLength={13} helper="Use four decimal places." />
|
||||
</ActionForm>}
|
||||
</Panel>}
|
||||
</>;
|
||||
}
|
||||
|
||||
export default function MaterialCostRatesPage({ materialId }: { materialId?: string }) {
|
||||
const id = uuid.safeParse(materialId);
|
||||
return <WorkspaceShell title="Material Cost Rates" permission="cost.read">
|
||||
{!materialId ? <OpenMaterial /> : id.success ? <Rates key={id.data} id={id.data} /> : <Alert severity="warning">Invalid material ID.</Alert>}
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
|
@ -1,137 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { WarehousePostingForm } from "@/components/WarehousePostingForm";
|
||||
import { materialAdjustment, materialAdjustmentInput, materialStockItem, materialTransfer, materialTransferInput } from "@/lib/material-stock";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
|
||||
const transferPath = "/inventory/material-transfers";
|
||||
const adjustmentPath = "/inventory/material-adjustments";
|
||||
const stockRoute = "/admin/material-stock";
|
||||
type Stock = z.infer<typeof materialStockItem>;
|
||||
type Adjustment = z.infer<typeof materialAdjustment>;
|
||||
|
||||
function useRefreshMovements(path: string) {
|
||||
const { scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
return () => client.invalidateQueries({
|
||||
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
|
||||
typeof queryKey[2] === "string" &&
|
||||
(queryKey[2].startsWith("/inventory/material-stock-items") || queryKey[2].startsWith(path)),
|
||||
});
|
||||
}
|
||||
|
||||
export function MaterialStockMovements({ stock }: { stock: Stock }) {
|
||||
const { can } = usePlatform();
|
||||
return <>
|
||||
<Transfers stock={stock} write={can("inventory.manage")} />
|
||||
<AdjustmentHistory materialId={stock.material.id} warehouseId={stock.warehouse.id} unit={stock.material.unit} />
|
||||
{can("inventory.adjust") && <MaterialAdjustmentForm stock={stock} />}
|
||||
</>;
|
||||
}
|
||||
|
||||
function Transfers({ stock, write }: { stock: Stock; write: boolean }) {
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [saved, setSaved] = useState<z.infer<typeof materialTransfer>>();
|
||||
const query = usePrivateQuery(
|
||||
`${transferPath}?materialId=${stock.material.id}&limit=25&offset=${offset}`,
|
||||
z.array(materialTransfer),
|
||||
);
|
||||
const command = useIdempotentCommand(transferPath, materialTransferInput, materialTransfer, stock.id);
|
||||
const refresh = useRefreshMovements(transferPath);
|
||||
const pending = command.pending;
|
||||
async function submit(value: unknown) {
|
||||
const transfer = await command.run(value);
|
||||
setSaved(transfer);
|
||||
setOffset(0);
|
||||
await refresh();
|
||||
}
|
||||
return <Panel title="Warehouse transfers for this material">
|
||||
{saved && <Alert severity="success">Transferred {saved.quantity} {stock.material.unit}. <WorkspaceLink href={`${stockRoute}/${saved.toStockItemId}`}>Open destination ledger</WorkspaceLink></Alert>}
|
||||
{write && (pending ? (
|
||||
<ActionForm label="Retry material transfer" read={() => ({})} submit={submit}>
|
||||
<Alert severity="warning">Retrying uses the original quantity {pending.quantity} {stock.material.unit} and destination warehouse {pending.toWarehouseId}.</Alert>
|
||||
</ActionForm>
|
||||
) : <WarehousePostingForm label="Transfer material" warehouseLabel="Destination warehouse" excludeWarehouseId={stock.warehouse.id}
|
||||
instruction={`Move stock from ${stock.warehouse.name}. Both warehouse ledgers update together.`}
|
||||
reset read={(data) => ({
|
||||
materialId: stock.material.id,
|
||||
fromWarehouseId: stock.warehouse.id,
|
||||
toWarehouseId: readText(data, "warehouseId"),
|
||||
quantity: readText(data, "quantity").trim(),
|
||||
})} submit={submit}>
|
||||
<Field name="quantity" label={`Quantity to transfer (${stock.material.unit})`} maxLength={13} helper="Enter a positive quantity with three decimal places." />
|
||||
</WarehousePostingForm>)}
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Time", "Quantity", "Source", "Destination"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
new Date(row.createdAt).toLocaleString(), `${row.quantity} ${stock.material.unit}`,
|
||||
<WorkspaceLink href={`${stockRoute}/${row.fromStockItemId}`}>{row.fromWarehouseId === stock.warehouse.id ? stock.warehouse.name : "Source ledger"}</WorkspaceLink>,
|
||||
<WorkspaceLink href={`${stockRoute}/${row.toStockItemId}`}>{row.toWarehouseId === stock.warehouse.id ? stock.warehouse.name : "Destination ledger"}</WorkspaceLink>,
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function AdjustmentHistory({ materialId, warehouseId, unit }: { materialId: string; warehouseId: string; unit: string }) {
|
||||
const [offset, setOffset] = useState(0);
|
||||
const query = usePrivateQuery(
|
||||
`${adjustmentPath}?materialId=${materialId}&warehouseId=${warehouseId}&limit=25&offset=${offset}`,
|
||||
z.array(materialAdjustment),
|
||||
);
|
||||
return <Panel title="Warehouse adjustments for this material">
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Time", "Quantity change", "Reason"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [new Date(row.createdAt).toLocaleString(), `${signed(row.delta)} ${unit}`, row.reason])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
export function MaterialAdjustmentForm({ stock, materialId }: { stock?: Stock; materialId?: string }) {
|
||||
const [saved, setSaved] = useState<Adjustment>();
|
||||
const command = useIdempotentCommand(adjustmentPath, materialAdjustmentInput, materialAdjustment, stock?.id ?? materialId ?? "new");
|
||||
const refresh = useRefreshMovements(adjustmentPath);
|
||||
const pending = command.pending;
|
||||
const instruction = "Record a counted discrepancy or stock correction. Use a minus sign for decreases.";
|
||||
const fields = <>
|
||||
{!stock && !materialId && <Field name="materialId" label="Material ID" maxLength={36} />}
|
||||
<Field name="delta" label={stock ? `Quantity change (${stock.material.unit})` : "Quantity change"}
|
||||
maxLength={14} helper="Use three decimal places in the material’s native unit." />
|
||||
<Field name="reason" label="Adjustment reason" maxLength={200} />
|
||||
</>;
|
||||
function read(data: FormData) {
|
||||
return {
|
||||
materialId: stock?.material.id ?? materialId ?? readText(data, "materialId").trim(),
|
||||
warehouseId: stock?.warehouse.id ?? readText(data, "warehouseId"),
|
||||
delta: readText(data, "delta").trim(),
|
||||
reason: readText(data, "reason"),
|
||||
};
|
||||
}
|
||||
async function submit(input: unknown) {
|
||||
setSaved(await command.run(input));
|
||||
await refresh();
|
||||
}
|
||||
return <Panel title="Adjust material stock">
|
||||
{materialId && <p className="workspace-id">Material ID {materialId}</p>}
|
||||
{saved && <Alert severity="success">Recorded {signed(saved.delta)}. <WorkspaceLink href={`${stockRoute}/${saved.stockItemId}`}>Open adjusted stock ledger</WorkspaceLink></Alert>}
|
||||
{pending ? (
|
||||
<ActionForm label="Retry stock adjustment" read={() => ({})} submit={submit}>
|
||||
<Alert severity="warning">Retrying uses the original change {signed(pending.delta)} and reason. Warehouse {pending.warehouseId}.</Alert>
|
||||
</ActionForm>
|
||||
) : stock ? (
|
||||
<ActionForm label="Record stock adjustment" read={read} submit={submit}>
|
||||
<p>{instruction}</p>
|
||||
{fields}
|
||||
</ActionForm>
|
||||
) : <WarehousePostingForm label="Record stock adjustment" instruction={instruction} read={read} submit={submit} reset>{fields}</WarehousePostingForm>}
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function signed(delta: string) {
|
||||
return delta.startsWith("-") ? delta : `+${delta}`;
|
||||
}
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import { Pager, Panel, QueryView, Table, WorkspaceLink, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { uuid } from "@/lib/commerce";
|
||||
import { materialStockEntry, materialStockItem } from "@/lib/material-stock";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { MaterialAdjustmentForm, MaterialStockMovements } from "./MaterialStockMovements";
|
||||
|
||||
const stockPath = "/inventory/material-stock-items";
|
||||
|
||||
function StockList() {
|
||||
const { can } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const query = usePrivateQuery(`${stockPath}?limit=25&offset=${offset}`, z.array(materialStockItem));
|
||||
return <Panel title="Warehouse balances">
|
||||
{can("inventory.adjust") && <p><WorkspaceLink href="/admin/material-stock/adjust">Record a material adjustment</WorkspaceLink></p>}
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Material", "Warehouse", "On hand", "Ledger"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
`${row.material.name} (${row.material.code})`, row.warehouse.name,
|
||||
`${row.onHand} ${row.material.unit}`,
|
||||
<WorkspaceLink href={`/admin/material-stock/${row.id}`}>Ledger for {row.material.name} at {row.warehouse.name}</WorkspaceLink>,
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function StockLedger({ id }: { id: string }) {
|
||||
const [offset, setOffset] = useState(0);
|
||||
const item = usePrivateQuery(`${stockPath}/${id}`, materialStockItem);
|
||||
const ledger = usePrivateQuery(`${stockPath}/${id}/ledger?limit=25&offset=${offset}`, z.array(materialStockEntry));
|
||||
return <Panel title="Material stock ledger">
|
||||
<WorkspaceLink href="/admin/material-stock">All material stock</WorkspaceLink>
|
||||
<QueryView query={item}>{(row) => (
|
||||
<p>{row.material.name} at {row.warehouse.name} · On hand {row.onHand} {row.material.unit}</p>
|
||||
)}</QueryView>
|
||||
<QueryView query={ledger}>{(rows) => <>
|
||||
<Table head={["Time", "Movement", "Quantity change"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
new Date(row.createdAt).toLocaleString(), row.kind.replaceAll("_", " ").toLowerCase(),
|
||||
row.delta.startsWith("-") ? row.delta : `+${row.delta}`,
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
<QueryView query={item}>{(row) => <MaterialStockMovements stock={row} />}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
export default function MaterialStockPage({ id, adjust = false }: { id?: string; adjust?: boolean }) {
|
||||
const parsed = uuid.safeParse(id);
|
||||
return <WorkspaceShell title="Material Stock" permission="inventory.read">
|
||||
{adjust ? <AdjustmentRoute materialId={id} /> : !id ? <StockList /> : parsed.success ? (
|
||||
<StockLedger key={parsed.data} id={parsed.data} />
|
||||
) : <Alert severity="warning">Invalid stock item ID.</Alert>}
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
||||
function AdjustmentRoute({ materialId }: { materialId?: string }) {
|
||||
const { can } = usePlatform();
|
||||
const id = uuid.safeParse(materialId);
|
||||
return <>
|
||||
<WorkspaceLink href="/admin/material-stock">All material stock</WorkspaceLink>
|
||||
{!can("inventory.adjust") ? <Alert severity="warning">Your account does not have permission to adjust material stock.</Alert> :
|
||||
materialId && !id.success ? <Alert severity="warning">Invalid material ID.</Alert> :
|
||||
<MaterialAdjustmentForm key={id.data ?? "new"} materialId={id.data} />}
|
||||
</>;
|
||||
}
|
||||
|
|
@ -1,287 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { coupon, couponInput, pricing, pricingInput } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import {
|
||||
ActionForm,
|
||||
Field,
|
||||
Pager,
|
||||
Panel,
|
||||
QueryView,
|
||||
Table,
|
||||
usePrivateQuery,
|
||||
readText,
|
||||
readNumber,
|
||||
} from "@/components/WorkspaceTools";
|
||||
import { ConfirmAction } from "@/components/ConfirmAction";
|
||||
const currencies = ["INR", "USD", "EUR", "GBP"].map((value) => ({
|
||||
value,
|
||||
label: value,
|
||||
}));
|
||||
function Coupons() {
|
||||
const { request } = usePlatform();
|
||||
const [offset, setOffset] = useState(0),
|
||||
[kind, setKind] = useState("PERCENT");
|
||||
const query = usePrivateQuery(
|
||||
`/coupons?limit=25&offset=${offset}`,
|
||||
z.array(coupon),
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Panel title="Coupon rules">
|
||||
<QueryView query={query}>
|
||||
{(items) => (
|
||||
<>
|
||||
<Table
|
||||
head={["Code", "Rule", "Window", "Status", "Action"]}
|
||||
rowKeys={items.map((item) => item.id)}
|
||||
rows={items.map((c) => [
|
||||
c.code,
|
||||
c.kind === "FIXED"
|
||||
? `${c.currency} ${c.amount}`
|
||||
: `${(c.percentBps || 0) / 100}%`,
|
||||
`${new Date(c.startsAt).toLocaleString()} – ${new Date(c.endsAt).toLocaleString()}`,
|
||||
c.active ? "Active" : "Inactive",
|
||||
<ConfirmAction
|
||||
label={c.active ? "Deactivate" : "Activate"}
|
||||
message="Change this coupon's availability? Order snapshots remain unchanged."
|
||||
onConfirm={async () => {
|
||||
await request(`/coupons/${c.id}/status`, coupon, {
|
||||
method: "PATCH",
|
||||
body: { active: !c.active },
|
||||
});
|
||||
await query.refetch();
|
||||
}}
|
||||
/>,
|
||||
])}
|
||||
/>
|
||||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
</Panel>
|
||||
<Panel title="Create an immutable coupon">
|
||||
<Alert severity="info">
|
||||
Rules cannot be edited after creation. Dates must include an explicit
|
||||
timezone. Campaign-linked coupons belong to the growth phase.
|
||||
</Alert>
|
||||
<div className="coupon-kind">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setKind("PERCENT")}
|
||||
aria-pressed={kind === "PERCENT"}
|
||||
>
|
||||
Percentage
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setKind("FIXED")}
|
||||
aria-pressed={kind === "FIXED"}
|
||||
>
|
||||
Fixed amount
|
||||
</button>
|
||||
</div>
|
||||
<ActionForm
|
||||
key={kind}
|
||||
label="Create coupon"
|
||||
read={(data) => ({
|
||||
code: readText(data, "code"),
|
||||
currency: readText(data, "currency"),
|
||||
minimumSubtotal: readText(data, "minimumSubtotal"),
|
||||
maxUses: readNumber(data, "maxUses"),
|
||||
perUserLimit: readNumber(data, "perUserLimit"),
|
||||
startsAt: readText(data, "startsAt"),
|
||||
endsAt: readText(data, "endsAt"),
|
||||
kind,
|
||||
...(kind === "FIXED"
|
||||
? { amount: readText(data, "amount") }
|
||||
: { percentBps: readNumber(data, "percentBps") }),
|
||||
})}
|
||||
submit={async (value) => {
|
||||
await request("/coupons", coupon, {
|
||||
method: "POST",
|
||||
body: couponInput.parse(value),
|
||||
});
|
||||
await query.refetch();
|
||||
}}
|
||||
>
|
||||
<Field name="code" label="Coupon code" maxLength={40} />
|
||||
<Field
|
||||
name="currency"
|
||||
label="Currency"
|
||||
options={currencies}
|
||||
value="INR"
|
||||
/>
|
||||
<Field
|
||||
name="minimumSubtotal"
|
||||
label="Minimum merchandise subtotal"
|
||||
value="0.00"
|
||||
/>
|
||||
{kind === "FIXED" ? (
|
||||
<Field
|
||||
name="amount"
|
||||
label="Fixed discount amount"
|
||||
helper="Two decimal places, e.g. 50.00"
|
||||
/>
|
||||
) : (
|
||||
<Field
|
||||
name="percentBps"
|
||||
label="Discount in basis points"
|
||||
type="number"
|
||||
helper="1000 means 10%; maximum 10000."
|
||||
/>
|
||||
)}
|
||||
<Field name="maxUses" label="Total usage limit" type="number" />
|
||||
<Field
|
||||
name="perUserLimit"
|
||||
label="Per-account usage limit"
|
||||
type="number"
|
||||
value={1}
|
||||
/>
|
||||
<Field
|
||||
name="startsAt"
|
||||
label="Starts at (ISO with timezone)"
|
||||
helper="Example: 2026-10-12T00:00:00+05:30"
|
||||
/>
|
||||
<Field name="endsAt" label="Ends at (ISO with timezone)" />
|
||||
</ActionForm>
|
||||
</Panel>
|
||||
</>
|
||||
);
|
||||
}
|
||||
function Pricing() {
|
||||
const { request } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const query = usePrivateQuery(
|
||||
`/admin/pricing-policies?limit=25&offset=${offset}`,
|
||||
z.array(pricing),
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Panel title="Pricing policy versions">
|
||||
<Alert severity="warning">
|
||||
Use approved tax and shipping rules. New versions do not reprice
|
||||
existing orders and do not enable payment.
|
||||
</Alert>
|
||||
<QueryView query={query}>
|
||||
{(items) => (
|
||||
<>
|
||||
<Table
|
||||
head={["Policy", "Scope", "Tax mode", "Status", "Action"]}
|
||||
rowKeys={items.map((item) => item.id)}
|
||||
rows={items.map((p) => [
|
||||
p.name,
|
||||
`${p.currency} · ${p.countryCode} · ${p.region || "Country fallback"}`,
|
||||
p.taxMode,
|
||||
p.active ? "Active" : "Inactive",
|
||||
<ConfirmAction
|
||||
label={p.active ? "Deactivate" : "Activate"}
|
||||
message="Change this policy's status? Activation disables the previous version for this scope."
|
||||
onConfirm={async () => {
|
||||
await request(
|
||||
`/admin/pricing-policies/${p.id}/status`,
|
||||
pricing,
|
||||
{ method: "PATCH", body: { active: !p.active } },
|
||||
);
|
||||
await query.refetch();
|
||||
}}
|
||||
/>,
|
||||
])}
|
||||
/>
|
||||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
</Panel>
|
||||
<Panel title="New inactive pricing policy">
|
||||
<ActionForm
|
||||
label="Create pricing policy"
|
||||
read={(data) => ({
|
||||
name: readText(data, "name"),
|
||||
currency: readText(data, "currency"),
|
||||
countryCode: readText(data, "countryCode"),
|
||||
region: readText(data, "region"),
|
||||
taxMode: readText(data, "taxMode"),
|
||||
merchandiseTaxBps: readNumber(data, "merchandiseTaxBps"),
|
||||
shippingTaxBps: readNumber(data, "shippingTaxBps"),
|
||||
shippingFee: readText(data, "shippingFee"),
|
||||
freeShippingMinimum: readText(data, "freeShippingMinimum") || null,
|
||||
})}
|
||||
submit={async (value) => {
|
||||
await request("/admin/pricing-policies", pricing, {
|
||||
method: "POST",
|
||||
body: pricingInput.parse(value),
|
||||
});
|
||||
await query.refetch();
|
||||
}}
|
||||
>
|
||||
<Field name="name" label="Policy name" maxLength={100} />
|
||||
<Field
|
||||
name="currency"
|
||||
label="Currency"
|
||||
value="INR"
|
||||
options={currencies}
|
||||
/>
|
||||
<Field
|
||||
name="countryCode"
|
||||
label="Country code"
|
||||
maxLength={2}
|
||||
value="IN"
|
||||
/>
|
||||
<Field
|
||||
name="region"
|
||||
label="Region (blank for country fallback)"
|
||||
required={false}
|
||||
maxLength={100}
|
||||
/>
|
||||
<Field
|
||||
name="taxMode"
|
||||
label="Merchandise tax mode"
|
||||
value="EXCLUSIVE"
|
||||
options={["INCLUSIVE", "EXCLUSIVE"].map((value) => ({
|
||||
value,
|
||||
label: value,
|
||||
}))}
|
||||
/>
|
||||
<Field
|
||||
name="merchandiseTaxBps"
|
||||
label="Merchandise tax basis points"
|
||||
type="number"
|
||||
/>
|
||||
<Field
|
||||
name="shippingFee"
|
||||
label="Net shipping fee"
|
||||
helper="Two decimal places."
|
||||
/>
|
||||
<Field
|
||||
name="shippingTaxBps"
|
||||
label="Shipping tax basis points"
|
||||
type="number"
|
||||
/>
|
||||
<Field
|
||||
name="freeShippingMinimum"
|
||||
label="Free-shipping minimum (optional)"
|
||||
required={false}
|
||||
helper="Leave blank if there is no threshold."
|
||||
/>
|
||||
</ActionForm>
|
||||
</Panel>
|
||||
</>
|
||||
);
|
||||
}
|
||||
export default function OffersPage({
|
||||
pricing: showPricing = false,
|
||||
}: {
|
||||
pricing?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<WorkspaceShell
|
||||
title={showPricing ? "Pricing Policies" : "Coupon Administration"}
|
||||
permission={showPricing ? "pricing.manage" : "coupons.manage"}
|
||||
>
|
||||
{showPricing ? <Pricing /> : <Coupons />}
|
||||
</WorkspaceShell>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,176 +0,0 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { order, orderSummary, money, uuid } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import {
|
||||
Pager,
|
||||
Panel,
|
||||
QueryView,
|
||||
Table,
|
||||
usePrivateQuery,
|
||||
WorkspaceLink,
|
||||
} from "@/components/WorkspaceTools";
|
||||
import { ConfirmAction } from "@/components/ConfirmAction";
|
||||
function OrderList({ admin }: { admin: boolean }) {
|
||||
const [offset, setOffset] = useState(0);
|
||||
const path = admin ? "/admin/orders" : "/orders";
|
||||
const query = usePrivateQuery(
|
||||
`${path}?limit=25&offset=${offset}`,
|
||||
z.array(orderSummary),
|
||||
);
|
||||
const { refetch } = query;
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
void refetch();
|
||||
}, 30000);
|
||||
return () => clearInterval(timer);
|
||||
}, [refetch]);
|
||||
return (
|
||||
<Panel title="Order history">
|
||||
<QueryView query={query}>
|
||||
{(items) => (
|
||||
<>
|
||||
<Table
|
||||
head={["Order", "Status", "Merchandise", "Created"]}
|
||||
rowKeys={items.map((item) => item.id)}
|
||||
rows={items.map((item) => [
|
||||
<WorkspaceLink href={`${path}/${item.id}`}>
|
||||
{item.id}
|
||||
</WorkspaceLink>,
|
||||
item.status,
|
||||
`${item.currency} ${money(item.merchandiseTotal)}`,
|
||||
new Date(item.createdAt).toLocaleString(),
|
||||
])}
|
||||
/>
|
||||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
function OrderDetail({ admin, id }: { admin: boolean; id: string }) {
|
||||
const { request, can } = usePlatform(),
|
||||
path = `${admin ? "/admin/orders" : "/orders"}/${id}`,
|
||||
query = usePrivateQuery(path, order);
|
||||
const { refetch } = query;
|
||||
useEffect(() => {
|
||||
if (!query.data || query.data.status !== "PENDING_PAYMENT") return;
|
||||
const timeout = setTimeout(
|
||||
() => {
|
||||
void refetch();
|
||||
},
|
||||
Math.max(1000, Date.parse(query.data.expiresAt) - Date.now() + 250),
|
||||
);
|
||||
return () => clearTimeout(timeout);
|
||||
}, [query.data, refetch]);
|
||||
return (
|
||||
<Panel title="Order details">
|
||||
<QueryView query={query}>
|
||||
{(item) => (
|
||||
<>
|
||||
<p className="workspace-id">
|
||||
Order {item.id} · {item.status}
|
||||
</p>
|
||||
<p>Hold expires: {new Date(item.expiresAt).toLocaleString()}</p>
|
||||
<Table
|
||||
head={["Candle", "SKU", "Quantity", "Unit price", "Line total"]}
|
||||
rowKeys={item.lines.map((line) => line.variantId)}
|
||||
rows={item.lines.map((l) => [
|
||||
`${l.productName} · ${l.variantName}`,
|
||||
l.sku,
|
||||
l.quantity,
|
||||
`${item.currency} ${money(l.unitPrice)}`,
|
||||
`${item.currency} ${money(l.lineTotal)}`,
|
||||
])}
|
||||
/>
|
||||
<dl className="order-totals">
|
||||
<dt>Subtotal</dt>
|
||||
<dd>
|
||||
{item.currency} {money(item.subtotal)}
|
||||
</dd>
|
||||
<dt>Discount</dt>
|
||||
<dd>
|
||||
{item.currency} {money(item.discount)}
|
||||
</dd>
|
||||
<dt>Merchandise total</dt>
|
||||
<dd>
|
||||
{item.currency} {money(item.merchandiseTotal)}
|
||||
</dd>
|
||||
<dt>Tax</dt>
|
||||
<dd>
|
||||
{item.taxTotal === null
|
||||
? "Unfinalized"
|
||||
: `${item.currency} ${money(item.taxTotal)}`}
|
||||
</dd>
|
||||
<dt>Shipping</dt>
|
||||
<dd>
|
||||
{item.shippingTotal === null
|
||||
? "Unfinalized"
|
||||
: `${item.currency} ${money(item.shippingTotal)}`}
|
||||
</dd>
|
||||
<dt>Server payable total</dt>
|
||||
<dd>
|
||||
{item.payableTotal === null
|
||||
? "Unfinalized"
|
||||
: `${item.currency} ${money(item.payableTotal)}`}
|
||||
</dd>
|
||||
</dl>
|
||||
<Alert severity="info">
|
||||
{item.pricingStatus === "UNFINALIZED"
|
||||
? "Tax and shipping have not been finalized. "
|
||||
: "Tax may already be included in merchandise prices. "}
|
||||
Payment collection is unavailable.
|
||||
</Alert>
|
||||
<h3>Delivery snapshot</h3>
|
||||
<p>
|
||||
{item.address.recipient}
|
||||
<br />
|
||||
{item.address.line1} {item.address.line2}
|
||||
<br />
|
||||
{item.address.city}, {item.address.region}{" "}
|
||||
{item.address.postalCode}
|
||||
<br />
|
||||
{item.address.countryCode} · {item.address.phone}
|
||||
</p>
|
||||
{item.status === "PENDING_PAYMENT" &&
|
||||
(!admin || can("orders.manage")) && (
|
||||
<ConfirmAction
|
||||
label="Cancel order"
|
||||
message="Cancel this order and release its stock holds? Cancellation does not rebuild your cart."
|
||||
onConfirm={async () => {
|
||||
await request(`${path}/cancel`, order, { method: "POST" });
|
||||
await query.refetch();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</QueryView>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
export default function OrdersPage({
|
||||
admin = false,
|
||||
id,
|
||||
}: {
|
||||
admin?: boolean;
|
||||
id?: string;
|
||||
}) {
|
||||
return (
|
||||
<WorkspaceShell
|
||||
title={admin ? "Organization Orders" : "My Orders"}
|
||||
permission={admin ? "orders.read" : undefined}
|
||||
>
|
||||
{id && !uuid.safeParse(id).success ? (
|
||||
<Alert severity="error">Invalid order identifier.</Alert>
|
||||
) : id ? (
|
||||
<OrderDetail key={uuid.parse(id)} admin={admin} id={uuid.parse(id)} />
|
||||
) : (
|
||||
<OrderList admin={admin} />
|
||||
)}
|
||||
</WorkspaceShell>
|
||||
);
|
||||
}
|
||||
|
|
@ -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>;
|
||||
}
|
||||
|
|
@ -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>;
|
||||
}
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
import { ActionForm, Panel, Table } from "@/components/WorkspaceTools";
|
||||
import { VariantQuantityFields, readVariantQuantities } from "@/components/VariantQuantityFields";
|
||||
import { priceCheck, priceCheckInput, priceListDetail } from "@/lib/price-lists";
|
||||
import { money } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
|
||||
export function PriceListCheck({ list }: { list: z.infer<typeof priceListDetail> }) {
|
||||
const { request } = usePlatform();
|
||||
const [checked, setChecked] = useState<z.infer<typeof priceCheck>>();
|
||||
const options = list.items.map((item) => ({
|
||||
value: item.variantId, label: `${item.variantId} · ${list.currency} ${money(item.unitPrice)} · minimum ${item.minQuantity}`,
|
||||
}));
|
||||
return <Panel title="Check order quantities">
|
||||
<p>The preview covers merchandise only. Enter quantities for up to 100 distinct variants.</p>
|
||||
<ActionForm label="Check partner prices" reset={false} read={(form) => {
|
||||
setChecked(undefined);
|
||||
return priceCheckInput.parse({ lines: readVariantQuantities(form) });
|
||||
}} submit={async (body) => {
|
||||
setChecked(await request(`/b2b/price-lists/${list.id}/price-check`, priceCheck, { method: "POST", body }));
|
||||
}}>
|
||||
<VariantQuantityFields options={options} />
|
||||
</ActionForm>
|
||||
{checked && <>
|
||||
<h3>Last price check</h3>
|
||||
<p>Merchandise total {checked.currency} {checked.merchandiseTotal}</p>
|
||||
<Table head={["Variant", "Quantity", "Minimum", "Unit price", "Line total"]}
|
||||
rowKeys={checked.lines.map((line) => line.variantId)}
|
||||
rows={checked.lines.map((line) => [
|
||||
line.variantId, line.quantity, line.minQuantity,
|
||||
`${checked.currency} ${line.unitPrice}`, `${checked.currency} ${line.lineTotal}`,
|
||||
])} />
|
||||
</>}
|
||||
</Panel>;
|
||||
}
|
||||
|
|
@ -1,187 +0,0 @@
|
|||
import { useRef, 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 { ConfirmAction } from "@/components/ConfirmAction";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readNumber, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { isUnknownOutcome } from "@/lib/api";
|
||||
import { currency, money, uuid } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { priceList, priceListDetail, priceListInput, priceListItem, priceListStatus, priceTermsInput } from "@/lib/price-lists";
|
||||
import { PriceListCheck } from "./PriceListCheck";
|
||||
|
||||
const route = "/admin/b2b-price-lists";
|
||||
const currencies = currency.options.map((value) => ({ value, label: value }));
|
||||
const accountLists = (id: string) => `/b2b/accounts/${id}/price-lists`;
|
||||
|
||||
function useRefreshPriceLists() {
|
||||
const { scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
return (accountId: string) => client.invalidateQueries({
|
||||
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
|
||||
typeof queryKey[2] === "string" && queryKey[2].startsWith(`${accountLists(accountId)}?`),
|
||||
});
|
||||
}
|
||||
|
||||
function OpenAccount() {
|
||||
const { can } = usePlatform();
|
||||
const [, navigate] = useLocation();
|
||||
return <Panel title="Open an account’s price lists">
|
||||
{can("b2b.read") && <p>Choose a business in the <WorkspaceLink href="/admin/business-accounts">business directory</WorkspaceLink>.</p>}
|
||||
<ActionForm label="Open price lists" read={(form) => ({ accountId: readText(form, "accountId").trim() })}
|
||||
submit={async (input) => {
|
||||
const { accountId } = z.object({ accountId: uuid }).parse(input);
|
||||
navigate(`${route}/account/${accountId}`);
|
||||
}}>
|
||||
<Field name="accountId" label="Business account ID" maxLength={36} />
|
||||
</ActionForm>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function AccountPriceLists({ id }: { id: string }) {
|
||||
const { can, request } = usePlatform();
|
||||
const [, navigate] = useLocation();
|
||||
const refresh = useRefreshPriceLists();
|
||||
const [status, setStatus] = useState("ALL");
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [uncertain, setUncertain] = useState("");
|
||||
const path = accountLists(id);
|
||||
const query = usePrivateQuery(
|
||||
`${path}?limit=25&offset=${offset}${status === "ALL" ? "" : `&status=${status}`}`,
|
||||
z.array(priceList),
|
||||
);
|
||||
return <>
|
||||
<p className="workspace-id">Business account {id}</p>
|
||||
<WorkspaceLink href={route}>Open another account</WorkspaceLink>
|
||||
{can("b2b.read") && <p><WorkspaceLink href={`/admin/business-accounts/${id}`}>Business profile</WorkspaceLink></p>}
|
||||
<Panel title="Account price lists">
|
||||
<Field name="status" label="List status" value={status} onChange={(value) => { setStatus(value); setOffset(0); }}
|
||||
options={[{ value: "ALL", label: "All statuses" }, ...priceListStatus.options.map((value) => ({ value, label: value }))]} />
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Price list", "Currency", "Status"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
<WorkspaceLink href={`${route}/${row.id}`}>{row.name}</WorkspaceLink>, row.currency, row.status,
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>
|
||||
{can("b2b.price.manage") && <Panel title="New price list">
|
||||
{uncertain ? <Alert severity="warning">The server may have saved {uncertain}. Review the latest lists before creating another draft.</Alert> :
|
||||
<ActionForm label="Create draft price list" reset={false}
|
||||
read={(form) => priceListInput.parse(Object.fromEntries(form))}
|
||||
submit={async (input) => {
|
||||
const body = priceListInput.parse(input);
|
||||
try {
|
||||
const saved = await request(path, priceList, { method: "POST", body });
|
||||
await refresh(id);
|
||||
navigate(`${route}/${saved.id}`);
|
||||
} catch (error) {
|
||||
if (isUnknownOutcome(error)) {
|
||||
setUncertain(body.name);
|
||||
setStatus("ALL");
|
||||
setOffset(0);
|
||||
await refresh(id);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}}>
|
||||
<Field name="name" label="List name" maxLength={100} />
|
||||
<Field name="currency" label="List currency" options={currencies} value="INR" />
|
||||
</ActionForm>}
|
||||
</Panel>}
|
||||
</>;
|
||||
}
|
||||
|
||||
function PriceListDetails({ id }: { id: string }) {
|
||||
const { can, request } = usePlatform();
|
||||
const refreshDirectory = useRefreshPriceLists();
|
||||
const path = `/b2b/price-lists/${id}`;
|
||||
const query = usePrivateQuery(path, priceListDetail);
|
||||
const [selected, setSelected] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const updating = useRef(false);
|
||||
async function update(action: () => Promise<unknown>, accountId: string) {
|
||||
if (updating.current) throw new Error("A price list update is already in progress.");
|
||||
updating.current = true;
|
||||
setBusy(true);
|
||||
try {
|
||||
await action();
|
||||
} finally {
|
||||
try {
|
||||
await Promise.all([query.refetch(), refreshDirectory(accountId)]);
|
||||
} finally {
|
||||
updating.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return <QueryView query={query}>{(list) => {
|
||||
const manage = can("b2b.price.manage");
|
||||
const edit = manage && list.status === "DRAFT";
|
||||
const item = list.items.find((entry) => entry.variantId === selected);
|
||||
return <>
|
||||
<WorkspaceLink href={`${route}/account/${list.accountId}`}>All price lists for this account</WorkspaceLink>
|
||||
<Panel title={list.name}>
|
||||
<p>{list.currency} · {list.status}</p>
|
||||
<Table head={["Variant ID", "Unit price", "Minimum quantity", ...(edit ? ["Actions"] : [])]}
|
||||
rowKeys={list.items.map((entry) => entry.id)} rows={list.items.map((entry) => [
|
||||
entry.variantId, `${list.currency} ${money(entry.unitPrice)}`, entry.minQuantity,
|
||||
...(edit ? [<>
|
||||
<Button disabled={busy} onClick={() => setSelected(entry.variantId)} aria-label={`Edit terms for ${entry.variantId}`}>Edit</Button>
|
||||
<ConfirmAction label={`Remove terms for ${entry.variantId}`} disabled={busy}
|
||||
message="Remove this variant from the draft price list?"
|
||||
onConfirm={() => update(async () => {
|
||||
await request(`${path}/items/${entry.variantId}`, z.object({ removed: z.literal(true) }), { method: "DELETE" });
|
||||
if (selected === entry.variantId) setSelected("");
|
||||
}, list.accountId)} />
|
||||
</>] : []),
|
||||
])} />
|
||||
{edit && <>
|
||||
<p>Activation requires a verified business, eligible variants, and an available active slot in {list.currency}.</p>
|
||||
<ConfirmAction label="Activate price list" disabled={busy || !list.items.length}
|
||||
message="Activate this list and freeze its variant prices and minimum quantities?"
|
||||
onConfirm={() => update(() => request(`${path}/activate`, priceList, { method: "POST" }), list.accountId)} />
|
||||
</>}
|
||||
{manage && list.status === "ACTIVE" && <ConfirmAction label="Archive price list" disabled={busy}
|
||||
message="Archive this list to free its active slot for a replacement?"
|
||||
onConfirm={() => update(() => request(`${path}/archive`, priceList, { method: "POST" }), list.accountId)} />}
|
||||
</Panel>
|
||||
{edit && <Panel title={item ? "Edit variant terms" : "Add or update variant terms"}>
|
||||
{can("catalog.read") && <p>Find active variant IDs on published products in the <WorkspaceLink href="/admin/catalog">catalog</WorkspaceLink>.</p>}
|
||||
{item && <p className="workspace-id">Variant ID {item.variantId}</p>}
|
||||
{item && <Button disabled={busy} onClick={() => setSelected("")}>Cancel editing</Button>}
|
||||
<ActionForm key={item?.id ?? "new"} label="Save variant terms" lockFields={busy} reset={!item}
|
||||
read={(form) => ({
|
||||
variantId: item?.variantId ?? uuid.parse(readText(form, "variantId").trim()),
|
||||
terms: priceTermsInput.parse({ unitPrice: readText(form, "unitPrice").trim(), minQuantity: readNumber(form, "minQuantity") }),
|
||||
})}
|
||||
submit={async (input) => {
|
||||
const { variantId, terms } = z.object({ variantId: uuid, terms: priceTermsInput }).parse(input);
|
||||
await update(() => request(`${path}/items/${variantId}`, priceListItem, { method: "PUT", body: terms }), list.accountId);
|
||||
}}>
|
||||
{!item && <Field name="variantId" label="Variant ID" maxLength={36} />}
|
||||
<Field name="unitPrice" label={`Unit price in ${list.currency}`} value={item && money(item.unitPrice)} maxLength={13} helper="Use two decimal places." />
|
||||
<Field name="minQuantity" label="Minimum order quantity" type="number" value={item?.minQuantity} />
|
||||
</ActionForm>
|
||||
</Panel>}
|
||||
{list.status === "ACTIVE" && <>
|
||||
{can("b2b.quote.read") && can("b2b.quote.manage") && <WorkspaceLink href={`/admin/b2b-quotes/new/${list.accountId}/${list.id}`}>Issue a quotation from this list</WorkspaceLink>}
|
||||
<PriceListCheck list={list} />
|
||||
</>}
|
||||
</>;
|
||||
}}</QueryView>;
|
||||
}
|
||||
|
||||
export default function PriceListsPage({ id, account = false }: { id?: string; account?: boolean }) {
|
||||
const parsed = uuid.safeParse(id);
|
||||
return <WorkspaceShell title="B2B Price Lists" permission="b2b.price.read">
|
||||
{!id ? <OpenAccount /> : parsed.success ? account ?
|
||||
<AccountPriceLists key={parsed.data} id={parsed.data} /> :
|
||||
<PriceListDetails key={parsed.data} id={parsed.data} /> :
|
||||
<Alert severity="warning">Invalid {account ? "business account" : "price list"} ID.</Alert>}
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
|
@ -1,239 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
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 { usePlatform } from "@/lib/platform";
|
||||
import { currency, uuid } from "@/lib/commerce";
|
||||
import { material, materialInput, purchaseOrder, purchaseOrderInput, supplier, supplierInput, supplierMaterial, supplyTerms, supplyTermsInput } from "@/lib/procurement";
|
||||
import { useLocation } from "wouter";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { ConfirmAction } from "@/components/ConfirmAction";
|
||||
import { isUnknownOutcome } from "@/lib/api";
|
||||
import { PurchaseOrderReceipts } from "./PurchaseOrderReceipts";
|
||||
import { PurchaseOrderInvoices } from "./PurchaseOrderInvoices";
|
||||
|
||||
type Supplier = z.infer<typeof supplier>;
|
||||
type Material = z.infer<typeof material>;
|
||||
const options = (values: readonly string[]) => values.map((value) => ({ value, label: value }));
|
||||
|
||||
function Directory({ materials }: { materials: boolean }) {
|
||||
const { can, request } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [selected, select] = useState("");
|
||||
const path = materials ? "/materials" : "/suppliers";
|
||||
const schema = z.union([supplier, material]);
|
||||
const listSchema: z.ZodType<(Supplier | Material)[]> = materials ? z.array(material) : z.array(supplier);
|
||||
const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, listSchema);
|
||||
return (
|
||||
<Panel title={materials ? "Material directory" : "Supplier directory"}>
|
||||
<QueryView query={query}>
|
||||
{(rows) => {
|
||||
const record = rows.find((row) => row.id === selected);
|
||||
return <>
|
||||
<Table head={["Name", "Code", "Details", "Status", "Actions"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
row.name, row.code,
|
||||
"kind" in row ? <>{row.kind} · {row.unit}<br />ID: {row.id}</> : `${row.contactName} · ${row.email} · ${row.phone}`,
|
||||
row.active ? "Active" : "Inactive",
|
||||
<>
|
||||
{can("procurement.manage") && <Button onClick={() => select(row.id)} aria-label={`Edit ${row.name}`}>Edit</Button>}
|
||||
{"kind" in row && can("cost.read") && <WorkspaceLink href={`/admin/material-cost-rates/${row.id}`}>Cost rates for {row.name}</WorkspaceLink>}
|
||||
{"kind" in row && can("inventory.adjust") && can("inventory.read") && (
|
||||
<div><WorkspaceLink href={`/admin/material-stock/adjust/${row.id}`}>Adjust stock for {row.name}</WorkspaceLink></div>
|
||||
)}
|
||||
{"contactName" in row && <WorkspaceLink href={`/admin/procurement/suppliers/${row.id}`}>Supply terms and orders for {row.name}</WorkspaceLink>}
|
||||
{"contactName" in row && can("supplier_document.read") && (
|
||||
<> · <WorkspaceLink href={`/admin/supplier-documents/${row.id}`}>Documents for {row.name}</WorkspaceLink></>
|
||||
)}
|
||||
</>,
|
||||
])} />
|
||||
<Pager count={rows.length} offset={offset} onPage={(next) => { select(""); setOffset(next); }} />
|
||||
{can("procurement.manage") && <>
|
||||
{record && <Button onClick={() => select("")}>Cancel editing</Button>}
|
||||
<DirectoryForm key={record?.id ?? "create"} materials={materials} record={record}
|
||||
submit={async (value) => {
|
||||
await request(record ? `${path}/${record.id}` : path, schema, {
|
||||
method: record ? "PUT" : "POST",
|
||||
body: (materials ? materialInput : supplierInput).parse(value),
|
||||
});
|
||||
await query.refetch();
|
||||
}} />
|
||||
</>}
|
||||
</>;
|
||||
}}
|
||||
</QueryView>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function DirectoryForm({ materials, record, submit }: {
|
||||
materials: boolean;
|
||||
record?: Supplier | Material;
|
||||
submit: (value: unknown) => Promise<void>;
|
||||
}) {
|
||||
const detail = record && "kind" in record ? record : undefined;
|
||||
const contact = record && "contactName" in record ? record : undefined;
|
||||
return (
|
||||
<ActionForm label={`${record ? "Save" : "Create"} ${materials ? "material" : "supplier"}`} submit={submit} reset={!record}
|
||||
read={(data) => ({ ...Object.fromEntries(data), active: data.has("active") })}>
|
||||
<Field name="name" label="Name" value={record?.name} maxLength={160} />
|
||||
<Field name="code" label="Code" value={record?.code} maxLength={32} />
|
||||
{materials ? <>
|
||||
<Field name="kind" label="Material kind" value={detail?.kind ?? "WAX"} options={options(materialInput.shape.kind.options)} />
|
||||
<Field name="unit" label="Unit of measure" value={detail?.unit ?? "GRAM"} options={options(materialInput.shape.unit.options)} />
|
||||
</> : <>
|
||||
<Field name="contactName" label="Contact name" value={contact?.contactName} maxLength={160} />
|
||||
<Field name="email" label="Email" type="email" value={contact?.email} maxLength={254} />
|
||||
<Field name="phone" label="Phone" type="tel" value={contact?.phone} maxLength={24} />
|
||||
</>}
|
||||
<Check name="active" label="Active" value={record?.active ?? true} />
|
||||
</ActionForm>
|
||||
);
|
||||
}
|
||||
|
||||
function SupplierTerms({ id }: { id: string }) {
|
||||
const { can, request } = usePlatform();
|
||||
const [, navigate] = useLocation();
|
||||
const query = usePrivateQuery(`/suppliers/${id}/materials`, z.array(supplierMaterial));
|
||||
const [selected, select] = useState("");
|
||||
const [draftUncertain, setDraftUncertain] = useState(false);
|
||||
return <Panel title="Supplier material terms">
|
||||
<WorkspaceLink href="/admin/procurement">Supplier directory</WorkspaceLink>
|
||||
<QueryView query={query}>{(rows) => {
|
||||
const terms = rows.find((row) => row.materialId === selected);
|
||||
return <>
|
||||
<Table head={["Material", "Supplier SKU", "Minimum quantity", "Unit price", "Lead time", "Status", "Actions"]}
|
||||
rowKeys={rows.map((row) => row.id)} rows={rows.map((row) => [
|
||||
row.material.name, row.supplierSku || "—", `${row.minOrderQuantity} ${row.material.unit}`,
|
||||
`${row.currency} ${row.unitPrice}`, `${row.leadTimeDays} days`, row.active ? "Active" : "Inactive",
|
||||
can("procurement.manage") && <Button onClick={() => select(row.materialId)} aria-label={`Edit terms for ${row.material.name}`}>Edit</Button>,
|
||||
])} />
|
||||
{can("procurement.manage") && <>
|
||||
{terms && <Button onClick={() => select("")}>Cancel editing</Button>}
|
||||
<ActionForm key={terms?.id ?? "new"} label="Save supply terms" reset={!terms}
|
||||
read={(data) => ({
|
||||
materialId: terms?.materialId ?? uuid.parse(readText(data, "materialId").trim()),
|
||||
body: supplyTermsInput.parse({
|
||||
...Object.fromEntries([...data].filter(([name]) => name !== "materialId")),
|
||||
leadTimeDays: Number(readText(data, "leadTimeDays")),
|
||||
active: data.has("active"),
|
||||
}),
|
||||
})}
|
||||
submit={async (value) => {
|
||||
const input = z.object({ materialId: uuid, body: supplyTermsInput }).parse(value);
|
||||
await request(`/suppliers/${id}/materials/${input.materialId}`, supplyTerms, { method: "PUT", body: input.body });
|
||||
await query.refetch();
|
||||
}}>
|
||||
{terms ? <p>{terms.material.name}</p> : <Field name="materialId" label="Material ID" maxLength={36} helper="Find the ID in the material directory." />}
|
||||
<Field name="supplierSku" label="Supplier SKU" required={false} maxLength={64} value={terms?.supplierSku} />
|
||||
<Field name="leadTimeDays" label="Lead time (days)" type="number" value={terms?.leadTimeDays ?? 0} />
|
||||
<Field name="minOrderQuantity" label="Minimum order quantity" helper="Use three decimal places." value={terms?.minOrderQuantity && padDecimal(terms.minOrderQuantity, 3)} />
|
||||
<Field name="unitPrice" label="Unit price" helper="Use two decimal places." value={terms?.unitPrice && padDecimal(terms.unitPrice, 2)} />
|
||||
<Field name="currency" label="Currency" options={options(currency.options)} value={terms?.currency ?? "INR"} />
|
||||
<Check name="active" label="Active" value={terms?.active ?? true} />
|
||||
</ActionForm>
|
||||
</>}
|
||||
{can("procurement.manage") && rows.some((row) => row.active && row.material.active) && (
|
||||
<Panel title="Draft purchase order">
|
||||
<Alert severity="info">Enter quantities for the materials to order. The backend applies current supplier terms and snapshots prices when the draft is saved.</Alert>
|
||||
{draftUncertain ? <Alert severity="warning">
|
||||
The server may have saved the draft. <WorkspaceLink href="/admin/purchase-orders">Check purchase orders</WorkspaceLink> before submitting again.
|
||||
</Alert> : <ActionForm label="Create purchase order" reset={false}
|
||||
read={(data) => purchaseOrderInput.parse({
|
||||
supplierId: id,
|
||||
expectedDeliveryDate: readText(data, "expectedDeliveryDate") || undefined,
|
||||
lines: rows.filter((row) => row.active && row.material.active).flatMap((row) => {
|
||||
const quantity = readText(data, row.materialId).trim();
|
||||
return quantity ? [{ materialId: row.materialId, quantity }] : [];
|
||||
}),
|
||||
})}
|
||||
submit={async (body) => {
|
||||
try {
|
||||
const order = await request("/purchase-orders", purchaseOrder, { method: "POST", body });
|
||||
navigate(`/admin/purchase-orders/${order.id}`);
|
||||
} catch (error) {
|
||||
if (isUnknownOutcome(error)) setDraftUncertain(true);
|
||||
throw error;
|
||||
}
|
||||
}}>
|
||||
<Field name="expectedDeliveryDate" label="Expected delivery date (YYYY-MM-DD)" required={false} maxLength={10} />
|
||||
{rows.filter((row) => row.active && row.material.active).map((row) => (
|
||||
<Field key={row.materialId} name={row.materialId} label={`Quantity of ${row.material.name} (${row.material.code})`}
|
||||
required={false} helper={`Use three decimals in ${row.material.unit}. Minimum ${row.minOrderQuantity}, unit price ${row.currency} ${row.unitPrice}.`} />
|
||||
))}
|
||||
</ActionForm>}
|
||||
</Panel>
|
||||
)}
|
||||
</>;
|
||||
}}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function PurchaseOrders() {
|
||||
const [offset, setOffset] = useState(0);
|
||||
const query = usePrivateQuery(`/purchase-orders?limit=25&offset=${offset}`, z.array(purchaseOrder));
|
||||
return <Panel title="Purchase orders">
|
||||
<p>To create a draft, choose a supplier and open its supply terms.</p>
|
||||
<WorkspaceLink href="/admin/procurement">Supplier directory</WorkspaceLink>
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Reference", "Supplier", "Status", "Merchandise total"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
<WorkspaceLink href={`/admin/purchase-orders/${row.id}`}>{row.reference}</WorkspaceLink>,
|
||||
row.supplier.name, row.status, `${row.currency} ${row.merchandiseTotal}`,
|
||||
])} />
|
||||
<Pager count={rows.length} offset={offset} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function PurchaseOrderDetails({ id }: { id: string }) {
|
||||
const { can, request } = usePlatform();
|
||||
const query = usePrivateQuery(`/purchase-orders/${id}`, purchaseOrder);
|
||||
return <QueryView query={query}>{(order) => <Panel title={order.reference}>
|
||||
<WorkspaceLink href="/admin/purchase-orders">All purchase orders</WorkspaceLink>
|
||||
<p>{order.supplier.name} · {order.status}</p>
|
||||
{order.expectedDeliveryAt && <p>Expected delivery {order.expectedDeliveryAt.slice(0, 10)}</p>}
|
||||
<Table head={["Material", "Quantity", "Unit price", "Line total"]} rowKeys={order.lines.map((line) => line.id)}
|
||||
rows={order.lines.map((line) => [
|
||||
`${line.materialName} (${line.materialCode})`, `${line.quantity} ${line.unit}`,
|
||||
`${order.currency} ${line.unitPrice}`, `${order.currency} ${line.lineTotal}`,
|
||||
])} />
|
||||
<p>Merchandise total {order.currency} {order.merchandiseTotal}</p>
|
||||
{order.status === "ISSUED" && <PurchaseOrderReceipts order={order} />}
|
||||
{order.status === "ISSUED" && <PurchaseOrderInvoices order={order} />}
|
||||
{can("procurement.manage") && order.status === "DRAFT" && <>
|
||||
<ConfirmAction label="Issue purchase order" message={`Issue ${order.reference} so it can receive deliveries?`}
|
||||
onConfirm={async () => {
|
||||
await request(`/purchase-orders/${id}/issue`, purchaseOrder, { method: "POST" });
|
||||
await query.refetch();
|
||||
}} />
|
||||
<ConfirmAction label="Cancel purchase order" message={`Cancel draft ${order.reference}?`}
|
||||
onConfirm={async () => {
|
||||
await request(`/purchase-orders/${id}/cancel`, purchaseOrder, { method: "POST" });
|
||||
await query.refetch();
|
||||
}} />
|
||||
</>}
|
||||
</Panel>}</QueryView>;
|
||||
}
|
||||
|
||||
export function PurchaseOrdersPage({ orderId }: { orderId?: string }) {
|
||||
const id = uuid.safeParse(orderId);
|
||||
return <WorkspaceShell title="Purchase Orders" permission="procurement.read">
|
||||
{orderId ? id.success ? <PurchaseOrderDetails key={id.data} id={id.data} /> : <Alert severity="warning">Invalid purchase order ID.</Alert> : <PurchaseOrders />}
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
||||
function padDecimal(value: string, scale: number) {
|
||||
const [whole, fraction = ""] = value.split(".");
|
||||
return `${whole}.${fraction.padEnd(scale, "0")}`;
|
||||
}
|
||||
|
||||
export default function ProcurementPage({ materials = false, supplierId }: { materials?: boolean; supplierId?: string }) {
|
||||
const id = uuid.safeParse(supplierId);
|
||||
return (
|
||||
<WorkspaceShell title={materials ? "Materials" : supplierId ? "Supply terms" : "Suppliers"} permission="procurement.read">
|
||||
{supplierId ? id.success ? <SupplierTerms key={id.data} id={id.data} /> : <p>Invalid supplier ID.</p> : <Directory key={String(materials)} materials={materials} />}
|
||||
</WorkspaceShell>
|
||||
);
|
||||
}
|
||||
|
|
@ -5,12 +5,10 @@ import Alert from "@mui/material/Alert";
|
|||
import Button from "@mui/material/Button";
|
||||
import Skeleton from "@mui/material/Skeleton";
|
||||
import Chip from "@mui/material/Chip";
|
||||
import { getProduct, productImageUrl } from "@/lib/api";
|
||||
import { getProduct } from "@/lib/api";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { ApiNotice } from "@/components/ApiNotice";
|
||||
import "./products.css";
|
||||
import { AddToCart } from "@/components/AddToCart";
|
||||
import { money } from "@/lib/commerce";
|
||||
|
||||
export default function ProductPage({ id }: { id: string }) {
|
||||
const { organization } = usePlatform();
|
||||
|
|
@ -43,18 +41,6 @@ export default function ProductPage({ id }: { id: string }) {
|
|||
</>
|
||||
) : (
|
||||
<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>
|
||||
<p className="product-description">
|
||||
{query.data.description ||
|
||||
|
|
@ -87,19 +73,15 @@ export default function ProductPage({ id }: { id: string }) {
|
|||
</dl>
|
||||
</div>
|
||||
<strong>
|
||||
{variant.currency} {money(variant.price)}
|
||||
{variant.currency} {variant.price}
|
||||
</strong>
|
||||
<AddToCart
|
||||
key={`${variant.id}-${organization}`}
|
||||
variantId={variant.id}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<Alert severity="info">
|
||||
Orders reserve stock while pending. Payment and shipping
|
||||
integrations are not enabled yet.
|
||||
Ordering will be available in the commerce phase. Payment and
|
||||
shipping integrations are not enabled yet.
|
||||
</Alert>
|
||||
</div>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -1,155 +0,0 @@
|
|||
import { useRef, useState } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { ConfirmAction } from "@/components/ConfirmAction";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readNumber, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { uuid } from "@/lib/commerce";
|
||||
import { isUnknownOutcome } from "@/lib/api";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { batchDetail, batchInput, batchStatus, cancelBatchInput, parseCompletion, productionBatch } from "@/lib/production";
|
||||
import { BatchMaterialUsage } from "./BatchMaterialUsage";
|
||||
import { CompletedBatchOperations } from "./CompletedBatchOperations";
|
||||
import { BatchCostSnapshot } from "./CostingPanels";
|
||||
|
||||
const route = "/admin/production-batches";
|
||||
const api = "/production-batches";
|
||||
|
||||
function BatchList() {
|
||||
const { can } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [status, setStatus] = useState("ALL");
|
||||
const query = usePrivateQuery(
|
||||
`${api}?limit=25&offset=${offset}${status === "ALL" ? "" : `&status=${status}`}`,
|
||||
z.array(productionBatch),
|
||||
);
|
||||
return <Panel title="Batch history">
|
||||
{can("production.manage") && <p><WorkspaceLink href={`${route}/new`}>Plan a production batch</WorkspaceLink></p>}
|
||||
<Field name="status" label="Batch status" value={status} onChange={(value) => { setStatus(value); setOffset(0); }}
|
||||
options={[{ value: "ALL", label: "All statuses" }, ...batchStatus.options.map((value) => ({ value, label: value.replaceAll("_", " ") }))]} />
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Reference", "Status", "Planned pieces", "Scheduled date"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
<WorkspaceLink href={`${route}/${row.id}`}>{row.reference}</WorkspaceLink>,
|
||||
row.status.replaceAll("_", " "), row.plannedQuantity, row.scheduledDate?.slice(0, 10) ?? "—",
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function PlanBatch({ bomId }: { bomId?: string }) {
|
||||
const { can, request } = usePlatform();
|
||||
const [, navigate] = useLocation();
|
||||
const [uncertain, setUncertain] = useState(false);
|
||||
return <Panel title="Plan a production batch">
|
||||
<WorkspaceLink href={route}>All production batches</WorkspaceLink>
|
||||
{can("bom.read") && <p><WorkspaceLink href="/admin/boms">Browse production BOM revisions</WorkspaceLink></p>}
|
||||
{uncertain ? <Alert severity="warning">The server may have created the batch. Check batch history for its reference before submitting again.</Alert> :
|
||||
<ActionForm label="Create production batch" reset={false} read={(form) => batchInput.parse({
|
||||
bomId: bomId ?? readText(form, "bomId").trim(),
|
||||
reference: readText(form, "reference"),
|
||||
plannedQuantity: readNumber(form, "plannedQuantity"),
|
||||
scheduledDate: readText(form, "scheduledDate") || undefined,
|
||||
})} submit={async (body) => {
|
||||
try {
|
||||
const saved = await request(api, batchDetail, { method: "POST", body });
|
||||
navigate(`${route}/${saved.id}`);
|
||||
} catch (error) {
|
||||
if (isUnknownOutcome(error)) setUncertain(true);
|
||||
throw error;
|
||||
}
|
||||
}}>
|
||||
{bomId ? <p className="workspace-id">Production BOM ID {bomId}</p> :
|
||||
<Field name="bomId" label="Active production BOM ID" maxLength={36} />}
|
||||
<Field name="reference" label="Batch reference" maxLength={32} />
|
||||
<Field name="plannedQuantity" label="Planned pieces" type="number" helper="Enter a multiple of the active BOM’s yield." />
|
||||
<Field name="scheduledDate" label="Scheduled date (YYYY-MM-DD)" maxLength={10} required={false} />
|
||||
</ActionForm>}
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function BatchDetails({ id }: { id: string }) {
|
||||
const { can, request } = usePlatform();
|
||||
const path = `${api}/${id}`;
|
||||
const query = usePrivateQuery(path, batchDetail);
|
||||
const running = useRef(false);
|
||||
async function transition(action: "start" | "complete" | "cancel", body?: unknown) {
|
||||
if (running.current) throw new Error("A batch update is already in progress.");
|
||||
running.current = true;
|
||||
try {
|
||||
await request(`${path}/${action}`, batchDetail, { method: "POST", body });
|
||||
} finally {
|
||||
await query.refetch();
|
||||
running.current = false;
|
||||
}
|
||||
}
|
||||
return <>
|
||||
<WorkspaceLink href={route}>All production batches</WorkspaceLink>
|
||||
<QueryView query={query}>{(batch) => <>
|
||||
<Panel title={batch.reference}>
|
||||
<p>{batch.status.replaceAll("_", " ")} · Planned {batch.plannedQuantity} pieces</p>
|
||||
<p>BOM revision {batch.bom.revision} · {batch.bom.outputQuantity} pieces per yield</p>
|
||||
{batch.scheduledDate && <p>Scheduled for {batch.scheduledDate.slice(0, 10)}</p>}
|
||||
{batch.startedAt && <p>Started {new Date(batch.startedAt).toLocaleString()}</p>}
|
||||
{batch.completion && <p>Completed {new Date(batch.completion.createdAt).toLocaleString()} · {batch.completion.goodQuantity} good · {batch.completion.rejectedQuantity} rejected{batch.completion.rejectionReason && ` · ${batch.completion.rejectionReason}`}</p>}
|
||||
{batch.cancellation && <p>Cancelled {new Date(batch.cancellation.createdAt).toLocaleString()} · {batch.cancellation.reason}</p>}
|
||||
<h3>Planned materials</h3>
|
||||
<Table head={["Material", "Code", "Unit", "Planned quantity"]} rowKeys={batch.plannedMaterials.map((line) => line.id)}
|
||||
rows={batch.plannedMaterials.map((line) => [line.materialName, line.materialCode, line.unit, line.plannedQuantity])} />
|
||||
{can("production.manage") && batch.status === "DRAFT" && (
|
||||
<ConfirmAction label="Start batch" message={`Start production for ${batch.reference}?`} onConfirm={() => transition("start")} />
|
||||
)}
|
||||
</Panel>
|
||||
<BatchMaterialUsage batch={batch} />
|
||||
{batch.status === "COMPLETED" && <CompletedBatchOperations batch={batch} />}
|
||||
{batch.status === "COMPLETED" && batch.completion && can("cost.read") && (
|
||||
<BatchCostSnapshot batchId={batch.id} goodQuantity={batch.completion.goodQuantity} />
|
||||
)}
|
||||
{can("production.manage") && batch.status === "IN_PROGRESS" && (
|
||||
<Panel title="Record batch output">
|
||||
<p>Record all material usage before completing production. Completion closes the batch to new usage entries.</p>
|
||||
<ActionForm label="Complete batch" read={(form) => parseCompletion({
|
||||
goodQuantity: readNumber(form, "goodQuantity"),
|
||||
rejectedQuantity: readNumber(form, "rejectedQuantity"),
|
||||
rejectionReason: readText(form, "rejectionReason").trim() || undefined,
|
||||
}, batch.plannedQuantity)} submit={(body) => transition("complete", body)}>
|
||||
<Field name="goodQuantity" label="Good pieces" type="number" />
|
||||
<Field name="rejectedQuantity" label="Rejected pieces" type="number" value={0} />
|
||||
<Field name="rejectionReason" label="Rejection reason" required={false} maxLength={500} />
|
||||
</ActionForm>
|
||||
</Panel>
|
||||
)}
|
||||
{can("production.manage") && (batch.status === "DRAFT" || batch.status === "IN_PROGRESS") && (
|
||||
<Panel title="Cancel production">
|
||||
<ActionForm label="Cancel batch" read={(form) => cancelBatchInput.parse({ reason: readText(form, "reason") })}
|
||||
submit={(body) => transition("cancel", body)}>
|
||||
<Field name="reason" label="Cancellation reason" maxLength={500} />
|
||||
</ActionForm>
|
||||
</Panel>
|
||||
)}
|
||||
</>}</QueryView>
|
||||
</>;
|
||||
}
|
||||
|
||||
export default function ProductionBatchesPage({ batchId, create = false, bomId }: {
|
||||
batchId?: string;
|
||||
create?: boolean;
|
||||
bomId?: string;
|
||||
}) {
|
||||
const parsedBatch = uuid.safeParse(batchId);
|
||||
const parsedBom = uuid.safeParse(bomId);
|
||||
return <WorkspaceShell title="Production Batches" permission="production.read">
|
||||
{create ? <CreateRoute bomId={bomId} parsedBom={parsedBom.success ? parsedBom.data : undefined} /> : batchId ? (
|
||||
parsedBatch.success ? <BatchDetails key={parsedBatch.data} id={parsedBatch.data} /> : <Alert severity="warning">Invalid batch ID.</Alert>
|
||||
) : <BatchList />}
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
||||
function CreateRoute({ bomId, parsedBom }: { bomId?: string; parsedBom?: string }) {
|
||||
const { can } = usePlatform();
|
||||
if (!can("production.manage")) return <Alert severity="warning">Your account does not have permission to plan production.</Alert>;
|
||||
if (bomId && !parsedBom) return <Alert severity="warning">Invalid production BOM ID.</Alert>;
|
||||
return <PlanBatch key={parsedBom ?? "new"} bomId={parsedBom} />;
|
||||
}
|
||||
|
|
@ -1,190 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import Button from "@mui/material/Button";
|
||||
import { ActionForm, Field, Pager, Panel, QueryView, Table, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { ApiError, isUnknownOutcome } from "@/lib/api";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { purchaseOrder } from "@/lib/procurement";
|
||||
import { correctionInput, invoiceInput, paymentHistory, paymentInput, paymentMethods, supplierInvoice, supplierPayment } from "@/lib/supplier-finance";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
|
||||
type Order = z.infer<typeof purchaseOrder>;
|
||||
type Invoice = z.infer<typeof supplierInvoice>;
|
||||
|
||||
export function PurchaseOrderInvoices({ order }: { order: Order }) {
|
||||
const { can, request } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [selected, select] = useState("");
|
||||
const [uncertain, setUncertain] = useState(false);
|
||||
const path = `/purchase-orders/${order.id}/invoices`;
|
||||
const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, z.array(supplierInvoice));
|
||||
const lineNames = new Map(order.lines.map((line) => [
|
||||
line.id, `${line.materialName} (${line.materialCode}) · ${line.unit}`,
|
||||
]));
|
||||
|
||||
return <Panel title="Supplier invoices">
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Invoice", "Date", "Payable", "Status", "Actions"]} rowKeys={rows.map((invoice) => invoice.id)}
|
||||
rows={rows.map((invoice) => [
|
||||
invoice.invoiceNumber, invoice.invoiceDate.slice(0, 10),
|
||||
`${invoice.currency} ${invoice.payableTotal}`, invoice.void ? "Void" : "Recorded",
|
||||
<Button onClick={() => select(invoice.id)} aria-pressed={selected === invoice.id}>
|
||||
View invoice {invoice.invoiceNumber}
|
||||
</Button>,
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
{selected && <InvoiceDetails key={selected} id={selected} lineNames={lineNames} refreshList={query.refetch} />}
|
||||
{can("procurement.manage") && (uncertain ? (
|
||||
<Alert severity="warning">
|
||||
The server may have recorded this invoice. Check the latest invoices for its number before recording it again.
|
||||
<Button onClick={() => { if (offset) setOffset(0); else void query.refetch(); }}>Refresh latest invoices</Button>
|
||||
</Alert>
|
||||
) : (
|
||||
<ActionForm label="Record supplier invoice" read={(data) => invoiceInput.parse({
|
||||
invoiceNumber: readText(data, "invoiceNumber"),
|
||||
invoiceDate: readText(data, "invoiceDate"),
|
||||
taxAmount: readText(data, "taxAmount").trim(),
|
||||
shippingAmount: readText(data, "shippingAmount").trim(),
|
||||
lines: order.lines.flatMap((line) => {
|
||||
const quantity = readText(data, line.id).trim();
|
||||
return quantity ? [{ purchaseOrderLineId: line.id, quantity }] : [];
|
||||
}),
|
||||
})} submit={async (body) => {
|
||||
try {
|
||||
const saved = await request(path, supplierInvoice, { method: "POST", body });
|
||||
select(saved.id);
|
||||
setOffset(0);
|
||||
await query.refetch();
|
||||
} catch (error) {
|
||||
if (isUnknownOutcome(error)) {
|
||||
setUncertain(true);
|
||||
setOffset(0);
|
||||
await query.refetch();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}}>
|
||||
<p>Invoice only quantities accepted in quality inspection and still available to bill. The backend uses the purchase order's saved prices.</p>
|
||||
<Field name="invoiceNumber" label="Supplier invoice number" maxLength={64} />
|
||||
<Field name="invoiceDate" label="Invoice date (YYYY-MM-DD)" maxLength={10} />
|
||||
<Field name="taxAmount" label={`Tax amount (${order.currency})`} value="0.00" />
|
||||
<Field name="shippingAmount" label={`Shipping amount (${order.currency})`} value="0.00" />
|
||||
{order.lines.map((line) => (
|
||||
<Field key={line.id} name={line.id} label={`Billed quantity for ${line.materialName} (${line.materialCode})`}
|
||||
required={false} helper={`Use three decimal places in ${line.unit}. Leave blank to omit this material.`} />
|
||||
))}
|
||||
</ActionForm>
|
||||
))}
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function InvoiceDetails({ id, lineNames, refreshList }: {
|
||||
id: string;
|
||||
lineNames: Map<string, string>;
|
||||
refreshList: () => Promise<unknown>;
|
||||
}) {
|
||||
const path = `/supplier-invoices/${id}`;
|
||||
const invoice = usePrivateQuery(path, supplierInvoice);
|
||||
return <QueryView query={invoice}>{(record) => <Panel title={`Invoice ${record.invoiceNumber}`}>
|
||||
<Table head={["Material", "Quantity", "Unit price", "Line total"]} rowKeys={record.lines.map((line) => line.id)}
|
||||
rows={record.lines.map((line) => [
|
||||
lineNames.get(line.purchaseOrderLineId) ?? line.purchaseOrderLineId,
|
||||
line.quantity, `${record.currency} ${line.unitPrice}`, `${record.currency} ${line.lineTotal}`,
|
||||
])} />
|
||||
<dl>
|
||||
<dt>Merchandise</dt><dd>{record.currency} {record.merchandiseTotal}</dd>
|
||||
<dt>Tax</dt><dd>{record.currency} {record.taxAmount}</dd>
|
||||
<dt>Shipping</dt><dd>{record.currency} {record.shippingAmount}</dd>
|
||||
<dt>Payable total</dt><dd>{record.currency} {record.payableTotal}</dd>
|
||||
</dl>
|
||||
{record.void && <Alert severity="info">Voided. {record.void.reason}</Alert>}
|
||||
<InvoicePayments invoice={record} refreshInvoice={async () => {
|
||||
await Promise.all([invoice.refetch(), refreshList()]);
|
||||
}} />
|
||||
</Panel>}</QueryView>;
|
||||
}
|
||||
|
||||
function InvoicePayments({ invoice, refreshInvoice }: {
|
||||
invoice: Invoice;
|
||||
refreshInvoice: () => Promise<void>;
|
||||
}) {
|
||||
const { can, request } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [reversing, setReversing] = useState("");
|
||||
const invoicePath = `/supplier-invoices/${invoice.id}`;
|
||||
const path = `${invoicePath}/payments`;
|
||||
const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, paymentHistory);
|
||||
const command = useIdempotentCommand(path, paymentInput, supplierPayment, invoice.id);
|
||||
|
||||
return <Panel title="Supplier payment records">
|
||||
<QueryView query={query}>{(data) => {
|
||||
const payment = data.payments.find((entry) => entry.id === reversing && !entry.reversal);
|
||||
return <>
|
||||
<p>Paid {data.currency} {data.paidTotal}{!invoice.void && ` · Outstanding ${data.currency} ${data.outstandingTotal}`}</p>
|
||||
<Table head={["Reference", "Payment date", "Method", "Amount", "Status", "Actions"]}
|
||||
rowKeys={data.payments.map((entry) => entry.id)} rows={data.payments.map((entry) => [
|
||||
entry.reference, entry.paidAt.slice(0, 10), entry.method.replaceAll("_", " "),
|
||||
`${entry.currency} ${entry.amount}`, entry.reversal ? `Reversed · ${entry.reversal.reason}` : "Recorded",
|
||||
can("supplier_payment.manage") && !entry.reversal &&
|
||||
<Button onClick={() => setReversing(entry.id)} aria-label={`Reverse payment ${entry.reference}`}>Reverse</Button>,
|
||||
])} />
|
||||
<Pager offset={offset} count={data.payments.length} onPage={(next) => { setReversing(""); setOffset(next); }} />
|
||||
{payment && can("supplier_payment.manage") && (
|
||||
<CorrectionForm key={payment.id} label={`Reverse payment ${payment.reference}`}
|
||||
submit={async (body) => {
|
||||
try {
|
||||
await request(`/supplier-payments/${payment.id}/reverse`, supplierPayment, { method: "POST", body });
|
||||
} finally {
|
||||
await query.refetch();
|
||||
}
|
||||
}} />
|
||||
)}
|
||||
{!invoice.void && can("supplier_payment.manage") && (command.pending || data.outstandingTotal !== "0.00") && (
|
||||
<ActionForm key={command.pending ? "retry" : "record"} label={command.pending ? "Retry supplier payment record" : "Record supplier payment"}
|
||||
read={(form) => command.pending ? {} : Object.fromEntries(form)}
|
||||
submit={async (body) => {
|
||||
try {
|
||||
await command.run(body);
|
||||
setOffset(0);
|
||||
await query.refetch();
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.code === "PAYMENT_INVOICE_VOID") await refreshInvoice();
|
||||
throw error;
|
||||
}
|
||||
}}>
|
||||
{command.pending ? (
|
||||
<Alert severity="warning">Retrying uses the same reference {command.pending.reference} and amount {invoice.currency} {command.pending.amount}.</Alert>
|
||||
) : <>
|
||||
<p>Record a payment already made to the supplier.</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={`Payment amount (${invoice.currency})`} helper="Use two decimal places." />
|
||||
<Field name="paidDate" label="Payment date (YYYY-MM-DD)" maxLength={10} />
|
||||
</>}
|
||||
</ActionForm>
|
||||
)}
|
||||
{!invoice.void && can("procurement.manage") && data.paidTotal === "0.00" && !command.pending && (
|
||||
<CorrectionForm label={`Void invoice ${invoice.invoiceNumber}`} submit={async (body) => {
|
||||
try {
|
||||
await request(`${invoicePath}/void`, supplierInvoice, { method: "POST", body });
|
||||
} finally {
|
||||
await Promise.all([refreshInvoice(), query.refetch()]);
|
||||
}
|
||||
}} />
|
||||
)}
|
||||
</>;
|
||||
}}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function CorrectionForm({ label, submit }: {
|
||||
label: string;
|
||||
submit: (input: z.infer<typeof correctionInput>) => Promise<void>;
|
||||
}) {
|
||||
return <ActionForm label={label} read={(data) => ({ reason: readText(data, "reason") })}
|
||||
submit={(value) => submit(correctionInput.parse(value))}>
|
||||
<Field name="reason" label={`Reason to ${label.toLowerCase()}`} maxLength={500} />
|
||||
</ActionForm>;
|
||||
}
|
||||
|
|
@ -1,124 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import Button from "@mui/material/Button";
|
||||
import { ActionForm, Field, Panel, QueryView, Table, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { isUnknownOutcome } from "@/lib/api";
|
||||
import { goodsReceipt, parseInspection, purchaseOrder, receiptInput } from "@/lib/procurement";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { ReceiptStockPosting } from "./ReceiptStockPosting";
|
||||
|
||||
type Order = z.infer<typeof purchaseOrder>;
|
||||
type Receipt = z.infer<typeof goodsReceipt>;
|
||||
|
||||
export function PurchaseOrderReceipts({ order }: { order: Order }) {
|
||||
const { can, request } = usePlatform();
|
||||
const path = `/purchase-orders/${order.id}/receipts`;
|
||||
const query = usePrivateQuery(path, z.array(goodsReceipt));
|
||||
const [selected, select] = useState("");
|
||||
const [uncertain, setUncertain] = useState(false);
|
||||
const lineNames = new Map(order.lines.map((line) => [line.id, `${line.materialName} (${line.materialCode}) · ${line.unit}`]));
|
||||
return (
|
||||
<Panel title="Goods receipts">
|
||||
<QueryView query={query}>{(receipts) => {
|
||||
const receipt = receipts.find((entry) => entry.id === selected);
|
||||
return <>
|
||||
<Table head={["Received", "Delivery note", "Inspection", "Actions"]}
|
||||
rowKeys={receipts.map((entry) => entry.id)}
|
||||
rows={receipts.map((entry) => [
|
||||
new Date(entry.createdAt).toLocaleString(), entry.deliveryNote || "—",
|
||||
entry.lines.every((line) => line.inspection) ? "Inspected" : "Pending",
|
||||
<Button onClick={() => select(entry.id)} aria-pressed={selected === entry.id}>
|
||||
View receipt {entry.deliveryNote || entry.id.slice(0, 8)}
|
||||
</Button>,
|
||||
])} />
|
||||
{receipt && <Panel title="Receipt details">
|
||||
<Table head={["Material", "Delivered", "Accepted", "Rejected", "Reason"]}
|
||||
rowKeys={receipt.lines.map((line) => line.id)}
|
||||
rows={receipt.lines.map((line) => [
|
||||
lineNames.get(line.purchaseOrderLineId) ?? line.purchaseOrderLineId,
|
||||
line.quantity, line.inspection?.acceptedQuantity ?? "—", line.inspection?.rejectedQuantity ?? "—",
|
||||
line.inspection?.rejectionReason ?? "—",
|
||||
])} />
|
||||
{can("procurement.manage") && receipt.lines.every((line) => !line.inspection) && (
|
||||
<InspectionForm key={receipt.id} receipt={receipt} lineNames={lineNames} refresh={query.refetch} />
|
||||
)}
|
||||
{can("inventory.read") && receipt.lines.every((line) => line.inspection) && (
|
||||
<ReceiptStockPosting key={receipt.id} receiptId={receipt.id}
|
||||
lineNames={new Map(receipt.lines.map((line) => [line.id, lineNames.get(line.purchaseOrderLineId) ?? line.purchaseOrderLineId]))} />
|
||||
)}
|
||||
</Panel>}
|
||||
{can("procurement.manage") && (uncertain ? (
|
||||
<Alert severity="warning">The server may have saved this receipt. Review the receipt list before recording the delivery again. <Button onClick={() => query.refetch()}>Refresh receipts</Button></Alert>
|
||||
) : (
|
||||
<ActionForm label="Record goods receipt"
|
||||
read={(data) => receiptInput.parse({
|
||||
deliveryNote: readText(data, "deliveryNote").trim() || undefined,
|
||||
lines: order.lines.flatMap((line) => {
|
||||
const quantity = readText(data, line.id).trim();
|
||||
return quantity ? [{ purchaseOrderLineId: line.id, quantity }] : [];
|
||||
}),
|
||||
})}
|
||||
submit={async (body) => {
|
||||
try {
|
||||
const saved = await request(path, goodsReceipt, { method: "POST", body });
|
||||
await query.refetch();
|
||||
select(saved.id);
|
||||
} catch (error) {
|
||||
if (isUnknownOutcome(error)) {
|
||||
setUncertain(true);
|
||||
await query.refetch();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}}>
|
||||
<Field name="deliveryNote" label="Delivery note" required={false} maxLength={80} />
|
||||
{order.lines.map((line) => (
|
||||
<Field key={line.id} name={line.id} label={`Delivered quantity for ${line.materialName} (${line.materialCode})`}
|
||||
required={false} helper={`Use three decimal places in ${line.unit}. Leave blank for undelivered materials.`} />
|
||||
))}
|
||||
</ActionForm>
|
||||
))}
|
||||
</>;
|
||||
}}</QueryView>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function InspectionForm({ receipt, lineNames, refresh }: {
|
||||
receipt: Receipt;
|
||||
lineNames: Map<string, string>;
|
||||
refresh: () => Promise<unknown>;
|
||||
}) {
|
||||
const { request } = usePlatform();
|
||||
return (
|
||||
<ActionForm label="Finalize inspection" reset={false}
|
||||
read={(data) => parseInspection({
|
||||
lines: receipt.lines.map((line) => ({
|
||||
receiptLineId: line.id,
|
||||
acceptedQuantity: readText(data, `${line.id}-accepted`).trim(),
|
||||
rejectedQuantity: readText(data, `${line.id}-rejected`).trim(),
|
||||
rejectionReason: readText(data, `${line.id}-reason`).trim() || undefined,
|
||||
})),
|
||||
}, receipt)}
|
||||
submit={async (body) => {
|
||||
try {
|
||||
await request(`/goods-receipts/${receipt.id}/inspect`, goodsReceipt, { method: "POST", body });
|
||||
} catch (error) {
|
||||
if (isUnknownOutcome(error)) await refresh();
|
||||
throw error;
|
||||
}
|
||||
await refresh();
|
||||
}}>
|
||||
<p>Inspection is final. Enter accepted and rejected quantities with three decimal places for every line.</p>
|
||||
{receipt.lines.map((line) => (
|
||||
<fieldset key={line.id}>
|
||||
<legend>{lineNames.get(line.purchaseOrderLineId) ?? line.purchaseOrderLineId} · Delivered {line.quantity}</legend>
|
||||
<Field name={`${line.id}-accepted`} label="Accepted quantity" />
|
||||
<Field name={`${line.id}-rejected`} label="Rejected quantity" value="0.000" />
|
||||
<Field name={`${line.id}-reason`} label="Rejection reason" required={false} maxLength={500} helper="Required when any quantity is rejected." />
|
||||
</fieldset>
|
||||
))}
|
||||
</ActionForm>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,201 +0,0 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useLocation } from "wouter";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import { BusinessSnapshot } from "@/components/BusinessSnapshot";
|
||||
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { VariantQuantityFields, readVariantQuantities } from "@/components/VariantQuantityFields";
|
||||
import { ApiError } from "@/lib/api";
|
||||
import { money, uuid } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { priceListDetail } from "@/lib/price-lists";
|
||||
import { issueQuoteInput, quote, quoteExpiry, quoteResponseInput, quoteSummary, responseKind } from "@/lib/quotes";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
import { partnerOrderEligible } from "@/lib/partner-orders";
|
||||
|
||||
const api = "/b2b/quotes";
|
||||
const route = "/admin/b2b-quotes";
|
||||
const terms = "Merchandise only. Tax, shipping, stock reservation, credit, and payment are outside this quotation.";
|
||||
type Source = { accountId: string; priceListId: string };
|
||||
|
||||
function useRefreshQuoteLists() {
|
||||
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 QuoteList({ accountId }: { accountId?: string }) {
|
||||
const { can } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const query = usePrivateQuery(
|
||||
`${api}?limit=25&offset=${offset}${accountId ? `&accountId=${accountId}` : ""}`,
|
||||
z.array(quoteSummary),
|
||||
);
|
||||
return <Panel title="Quotation history">
|
||||
{accountId && <p className="workspace-id">Business account {accountId}</p>}
|
||||
{can("b2b.quote.manage") && <p><WorkspaceLink href={`${route}/new`}>Issue a quotation</WorkspaceLink></p>}
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Quotation", "Business", "Status", "Merchandise total", "Expires"]}
|
||||
rowKeys={rows.map((row) => row.id)} rows={rows.map((row) => [
|
||||
<WorkspaceLink href={`${route}/${row.id}`}>{row.number}</WorkspaceLink>,
|
||||
row.accountSnapshot.legalName, visibleStatus(row),
|
||||
`${row.currency} ${row.merchandiseTotal}`, new Date(row.expiresAt).toLocaleString(),
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function IssueQuote({ source }: { source?: Source }) {
|
||||
const { can } = usePlatform();
|
||||
const [, navigate] = useLocation();
|
||||
const refresh = useRefreshQuoteLists();
|
||||
const command = useIdempotentCommand(api, issueQuoteInput, quote, "issue");
|
||||
if (!can("b2b.quote.manage")) return <Alert severity="warning">Your account does not have permission to issue quotations.</Alert>;
|
||||
async function submit(input: unknown) {
|
||||
const saved = await command.run(input);
|
||||
await refresh();
|
||||
navigate(`${route}/${saved.id}`);
|
||||
}
|
||||
return <Panel title="Issue a quotation">
|
||||
<p>{terms} Issuing saves the account and price terms in the quotation.</p>
|
||||
{command.pending ? <ActionForm label="Retry quotation issuance" read={() => ({})} submit={submit}>
|
||||
<Alert severity="warning">The server may have issued this quotation. Retrying uses the original quantities, expiry, and price list.</Alert>
|
||||
<p className="workspace-id">Price list {command.pending.priceListId}</p>
|
||||
</ActionForm> : source && can("b2b.price.read") ? <IssueFromList source={source} submit={submit} /> :
|
||||
<IssueForm source={source} submit={submit} />}
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function IssueFromList({ source, submit }: { source: Source; submit: (input: unknown) => Promise<void> }) {
|
||||
const query = usePrivateQuery(`/b2b/price-lists/${source.priceListId}`, priceListDetail);
|
||||
return <QueryView query={query}>{(list) => {
|
||||
if (list.status !== "ACTIVE" || list.accountId !== source.accountId) {
|
||||
return <Alert severity="warning">Choose an active price list for this business account.</Alert>;
|
||||
}
|
||||
return <>
|
||||
<p>{list.name} · {list.currency}</p>
|
||||
<IssueForm source={source} submit={submit} options={list.items.map((item) => ({
|
||||
value: item.variantId, label: `${item.variantId} · ${list.currency} ${money(item.unitPrice)} · minimum ${item.minQuantity}`,
|
||||
}))} />
|
||||
</>;
|
||||
}}</QueryView>;
|
||||
}
|
||||
|
||||
function IssueForm({ source, options, submit }: {
|
||||
source?: Source;
|
||||
options?: { value: string; label: string }[];
|
||||
submit: (input: unknown) => Promise<void>;
|
||||
}) {
|
||||
const { can } = usePlatform();
|
||||
return <ActionForm label="Issue quotation" reset={false}
|
||||
read={(form) => ({
|
||||
accountId: source?.accountId ?? readText(form, "accountId").trim(),
|
||||
priceListId: source?.priceListId ?? readText(form, "priceListId").trim(),
|
||||
expiresAt: quoteExpiry(readText(form, "expiresAt").trim()),
|
||||
customerReference: readText(form, "customerReference").trim() || null,
|
||||
lines: readVariantQuantities(form),
|
||||
})} submit={submit}>
|
||||
{!source && <>
|
||||
<p>Use an active price list for a verified business account. {can("b2b.price.read") &&
|
||||
<WorkspaceLink href="/admin/b2b-price-lists">Browse account price lists</WorkspaceLink>}</p>
|
||||
<Field name="accountId" label="Business account ID" maxLength={36} />
|
||||
<Field name="priceListId" label="Active price list ID" maxLength={36} />
|
||||
</>}
|
||||
<Field name="expiresAt" label="Expiry with timezone" maxLength={35}
|
||||
helper="Use YYYY-MM-DDTHH:mm:ss with a timezone offset, such as +05:30, or Z for UTC." />
|
||||
<Field name="customerReference" label="Customer reference" required={false} maxLength={100} />
|
||||
<VariantQuantityFields options={options} />
|
||||
</ActionForm>;
|
||||
}
|
||||
|
||||
function visibleStatus(record: z.infer<typeof quoteSummary>) {
|
||||
return record.status === "ISSUED" && Date.parse(record.expiresAt) <= Date.now() ? "EXPIRED" : record.status;
|
||||
}
|
||||
|
||||
function QuoteDetails({ id }: { id: string }) {
|
||||
const { can, scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
const refresh = useRefreshQuoteLists();
|
||||
const path = `${api}/${id}`;
|
||||
const query = usePrivateQuery(path, quote);
|
||||
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 [, setExpired] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!expiry) return;
|
||||
let timer: number;
|
||||
function tick(at: string) {
|
||||
const remaining = Date.parse(at) - Date.now();
|
||||
if (remaining <= 0) setExpired(true);
|
||||
else timer = window.setTimeout(() => tick(at), Math.min(remaining, 2_147_483_647));
|
||||
}
|
||||
tick(expiry);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [expiry]);
|
||||
|
||||
async function respond(input: unknown) {
|
||||
try {
|
||||
const saved = await command.run(input);
|
||||
client.setQueryData(["private", scope, path], saved);
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && ["B2B_QUOTE_EXPIRED", "B2B_QUOTE_ALREADY_RESOLVED"].includes(error.code ?? "")) {
|
||||
await Promise.all([query.refetch(), refresh()]);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
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>Price list {record.priceListName}{record.customerReference && ` · Customer reference ${record.customerReference}`}</p>
|
||||
<BusinessSnapshot account={record.accountSnapshot} />
|
||||
<Table head={["Variant", "Quantity", "Minimum", "Unit price", "Line total"]} rowKeys={record.lines.map((line) => line.id)}
|
||||
rows={record.lines.map((line) => [
|
||||
`${line.name} (${line.sku})`, line.quantity, line.minQuantity,
|
||||
`${record.currency} ${line.unitPrice}`, `${record.currency} ${line.lineTotal}`,
|
||||
])} />
|
||||
<p>Merchandise total {record.currency} {record.merchandiseTotal}</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> :
|
||||
can("b2b.quote.manage") && (command.pending || visibleStatus(record) === "ISSUED") && (
|
||||
<ActionForm key={command.pending ? "retry" : "response"} label={command.pending ? "Retry quotation response" : "Record quotation response"}
|
||||
read={(form) => command.pending ? {} : ({ kind: readText(form, "kind"), note: readText(form, "note") })}
|
||||
submit={respond}>
|
||||
{command.pending ? <Alert severity="warning">Retrying reuses the original response and note.</Alert> : <>
|
||||
<p>Record the customer’s decision or a staff withdrawal. The saved response is final.</p>
|
||||
<Field name="kind" label="Quotation response" options={[
|
||||
{ value: "", label: "Choose a response" },
|
||||
...responseKind.options.map((value) => ({ value, label: value.toLowerCase() })),
|
||||
]} />
|
||||
<Field name="note" label="Response note" maxLength={500} helper="Record the basis for the response." />
|
||||
</>}
|
||||
</ActionForm>
|
||||
)}
|
||||
</Panel>}</QueryView>;
|
||||
}
|
||||
|
||||
export default function QuotesPage({ id, accountId, priceListId, issue = false }: {
|
||||
id?: string; accountId?: string; priceListId?: string; issue?: boolean;
|
||||
}) {
|
||||
const account = uuid.safeParse(accountId);
|
||||
const list = uuid.safeParse(priceListId);
|
||||
const quoteId = uuid.safeParse(id);
|
||||
const source = account.success && list.success ? { accountId: account.data, priceListId: list.data } : undefined;
|
||||
return <WorkspaceShell title="B2B Quotations" permission="b2b.quote.read">
|
||||
{(id || issue || accountId) && <WorkspaceLink href={route}>All quotations</WorkspaceLink>}
|
||||
{(id && !quoteId.success) || (accountId && !account.success) || (priceListId && !source) ?
|
||||
<Alert severity="warning">Invalid quotation, account, or price list ID.</Alert> :
|
||||
issue ? <IssueQuote key={source?.priceListId ?? "new"} source={source} /> :
|
||||
quoteId.success ? <QuoteDetails key={quoteId.data} id={quoteId.data} /> :
|
||||
<QuoteList key={account.data ?? "all"} accountId={account.data} />}
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { ActionForm, Panel, QueryView, Table, WorkspaceLink } from "@/components/WorkspaceTools";
|
||||
import { WarehousePostingForm } from "@/components/WarehousePostingForm";
|
||||
import { useOptionalPrivateQuery } from "@/components/useOptionalPrivateQuery";
|
||||
import { ApiError } from "@/lib/api";
|
||||
import { receiptPosting, receiptPostingInput } from "@/lib/material-stock";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
|
||||
export function ReceiptStockPosting({ receiptId, lineNames }: {
|
||||
receiptId: string;
|
||||
lineNames: Map<string, string>;
|
||||
}) {
|
||||
const { can } = usePlatform();
|
||||
const path = `/goods-receipts/${receiptId}/stock-posting`;
|
||||
const query = useOptionalPrivateQuery(path, receiptPosting, "MATERIAL_POSTING_NOT_FOUND");
|
||||
return <Panel title="Material warehouse posting">
|
||||
<QueryView query={query}>{(posting) => posting ? <>
|
||||
<p>Posted to warehouse {posting.warehouseId} on {new Date(posting.createdAt).toLocaleString()}.</p>
|
||||
<Table head={["Material", "Quantity posted", "Stock ledger"]}
|
||||
rowKeys={posting.entries.map((entry) => entry.id)}
|
||||
rows={posting.entries.map((entry) => [
|
||||
lineNames.get(entry.receiptLineId) ?? entry.receiptLineId,
|
||||
entry.delta,
|
||||
<WorkspaceLink href={`/admin/material-stock/${entry.stockItemId}`}>View stock ledger</WorkspaceLink>,
|
||||
])} />
|
||||
{!posting.entries.length && <p>The inspection accepted zero material. The posting recorded no stock movements.</p>}
|
||||
</> : can("inventory.manage") ? (
|
||||
<PostReceipt path={path} receiptId={receiptId} refresh={query.refetch} />
|
||||
) : <Alert severity="info">This receipt is awaiting warehouse posting.</Alert>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function PostReceipt({ path, receiptId, refresh }: {
|
||||
path: string;
|
||||
receiptId: string;
|
||||
refresh: () => Promise<unknown>;
|
||||
}) {
|
||||
const { scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
const command = useIdempotentCommand(path, receiptPostingInput, receiptPosting, receiptId);
|
||||
async function submit(input: unknown) {
|
||||
try {
|
||||
await command.run(input);
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.code === "MATERIAL_RECEIPT_ALREADY_POSTED") await refresh();
|
||||
throw error;
|
||||
}
|
||||
await client.invalidateQueries({
|
||||
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
|
||||
typeof queryKey[2] === "string" && queryKey[2].startsWith("/inventory/material-stock-items"),
|
||||
});
|
||||
await refresh();
|
||||
}
|
||||
return command.pending ? (
|
||||
<ActionForm label="Retry warehouse posting" read={() => ({})} submit={submit}>
|
||||
<Alert severity="warning">The server may have posted this receipt. Retrying uses the same request and warehouse {command.pending.warehouseId}.</Alert>
|
||||
</ActionForm>
|
||||
) : <WarehousePostingForm label="Post accepted material" warehouseLabel="Destination warehouse" submit={submit}
|
||||
instruction="Choose the warehouse to credit with all accepted quantities from this receipt. A receipt can be posted once." />;
|
||||
}
|
||||
|
|
@ -1,138 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { Link } from "wouter";
|
||||
import { z } from "zod";
|
||||
import Container from "@mui/material/Container";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import { apiRequest, parse, organizationSchema } from "@/lib/api";
|
||||
import { clearRecoveryToken, getRecoveryToken } from "@/lib/recovery-token";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import {
|
||||
ActionForm,
|
||||
Field,
|
||||
Panel,
|
||||
readText,
|
||||
} from "@/components/WorkspaceTools";
|
||||
import "./workspace.css";
|
||||
export default function RecoveryPage({ reset = false }: { reset?: boolean }) {
|
||||
const { organization, clearSession } = usePlatform();
|
||||
const [complete, setComplete] = useState(false);
|
||||
const token = getRecoveryToken();
|
||||
return (
|
||||
<section className="workspace-page">
|
||||
<Container maxWidth="sm">
|
||||
<h1>{reset ? "Reset Password" : "Account Recovery"}</h1>
|
||||
<Panel
|
||||
title={
|
||||
reset ? "Choose a new password" : "Request recovery instructions"
|
||||
}
|
||||
>
|
||||
{complete ? (
|
||||
<Alert severity="success">
|
||||
{reset
|
||||
? "Your password was reset and previous sessions were invalidated."
|
||||
: "If the account is eligible, recovery instructions will be sent."}{" "}
|
||||
<Link href="/workspace">
|
||||
<u>Return to sign-in</u>
|
||||
</Link>
|
||||
</Alert>
|
||||
) : reset ? (
|
||||
!token ? (
|
||||
<Alert severity="warning">
|
||||
This reset link is missing or invalid. Request a new recovery
|
||||
link.
|
||||
</Alert>
|
||||
) : (
|
||||
<ActionForm
|
||||
label="Reset password"
|
||||
read={(data) => {
|
||||
const password = readText(data, "password");
|
||||
if (password !== readText(data, "confirm"))
|
||||
throw new Error("Passwords do not match.");
|
||||
return { token, password };
|
||||
}}
|
||||
submit={async (value) => {
|
||||
const body = z
|
||||
.object({
|
||||
token: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
|
||||
password: z.string().min(15).max(128),
|
||||
})
|
||||
.strict()
|
||||
.parse(value);
|
||||
parse(
|
||||
z.null(),
|
||||
await apiRequest("/auth/recovery/reset", {
|
||||
method: "POST",
|
||||
body,
|
||||
}),
|
||||
);
|
||||
clearRecoveryToken();
|
||||
clearSession(
|
||||
"Password reset. Sign in with your new password.",
|
||||
);
|
||||
setComplete(true);
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
name="password"
|
||||
label="New password"
|
||||
type="password"
|
||||
maxLength={128}
|
||||
helper="15–128 characters."
|
||||
/>
|
||||
<Field
|
||||
name="confirm"
|
||||
label="Confirm new password"
|
||||
type="password"
|
||||
maxLength={128}
|
||||
/>
|
||||
</ActionForm>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
<Alert severity="info">
|
||||
Recovery delivery requires the backend SMTP configuration.
|
||||
Acceptance does not confirm account existence or email delivery.
|
||||
</Alert>
|
||||
<ActionForm
|
||||
label="Request recovery"
|
||||
read={(data) => ({
|
||||
organizationId: readText(data, "organizationId"),
|
||||
email: readText(data, "email"),
|
||||
})}
|
||||
submit={async (value) => {
|
||||
const body = z
|
||||
.object({
|
||||
organizationId: organizationSchema,
|
||||
email: z.string().email().max(254).toLowerCase(),
|
||||
})
|
||||
.strict()
|
||||
.parse(value);
|
||||
parse(
|
||||
z.object({ message: z.string() }),
|
||||
await apiRequest("/auth/recovery/request", {
|
||||
method: "POST",
|
||||
body,
|
||||
}),
|
||||
);
|
||||
setComplete(true);
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
name="organizationId"
|
||||
label="Organization UUID"
|
||||
value={organization}
|
||||
/>
|
||||
<Field
|
||||
name="email"
|
||||
label="Account email"
|
||||
type="email"
|
||||
maxLength={254}
|
||||
/>
|
||||
</ActionForm>
|
||||
</>
|
||||
)}
|
||||
</Panel>
|
||||
</Container>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,168 +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 { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readNumber, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { ApiError } from "@/lib/api";
|
||||
import { uuid } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { sampleDecisionInput, sampleDispatchInput, sampleRequest, sampleRequestInput, sampleStatus } from "@/lib/samples";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
|
||||
const api = "/b2b/samples";
|
||||
const route = "/admin/b2b-samples";
|
||||
type Sample = z.infer<typeof sampleRequest>;
|
||||
|
||||
function useRefreshSampleLists() {
|
||||
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 SampleList({ accountId }: { accountId?: string }) {
|
||||
const { can } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [status, setStatus] = useState("ALL");
|
||||
const params = new URLSearchParams({ limit: "25", offset: String(offset) });
|
||||
if (accountId) params.set("accountId", accountId);
|
||||
if (status !== "ALL") params.set("status", status);
|
||||
const query = usePrivateQuery(`${api}?${params}`, z.array(sampleRequest));
|
||||
|
||||
return <Panel title="Sample request history">
|
||||
{accountId && <p className="workspace-id">Business account {accountId}</p>}
|
||||
{can("b2b.sample.request") && <p><WorkspaceLink href={`${route}/new${accountId ? `/${accountId}` : ""}`}>Request samples</WorkspaceLink></p>}
|
||||
<Field name="status" label="Sample status" value={status} onChange={(value) => { setStatus(value); setOffset(0); }}
|
||||
options={[{ value: "ALL", label: "All statuses" }, ...sampleStatus.options.map((value) => ({ value, label: value }))]} />
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Sample", "Business account ID", "Quantity", "Status", "Requested"]}
|
||||
rowKeys={rows.map((row) => row.id)} rows={rows.map((row) => [
|
||||
<WorkspaceLink href={`${route}/${row.id}`}>{row.variantName} ({row.sku})</WorkspaceLink>,
|
||||
row.accountId, row.quantity, row.status, new Date(row.createdAt).toLocaleString(),
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function RequestSamples({ accountId }: { accountId?: string }) {
|
||||
const { can } = usePlatform();
|
||||
const [, navigate] = useLocation();
|
||||
const refresh = useRefreshSampleLists();
|
||||
const command = useIdempotentCommand(api, sampleRequestInput, sampleRequest, "request");
|
||||
const pending = command.pending;
|
||||
if (!can("b2b.sample.request")) return <Alert severity="warning">Your account does not have permission to request samples.</Alert>;
|
||||
return <Panel title="New sample request">
|
||||
<p>Use a verified business account and an active variant of a published product.</p>
|
||||
<ActionForm key={pending ? "retry" : "new"} label={pending ? "Retry sample request" : "Request samples"} reset={false}
|
||||
read={(form) => pending ? {} : ({
|
||||
accountId: accountId ?? readText(form, "accountId").trim(),
|
||||
variantId: readText(form, "variantId").trim(),
|
||||
quantity: readNumber(form, "quantity"),
|
||||
purpose: readText(form, "purpose"),
|
||||
})}
|
||||
submit={async (input) => {
|
||||
const saved = await command.run(input);
|
||||
await refresh();
|
||||
navigate(`${route}/${saved.id}`);
|
||||
}}>
|
||||
{pending ? <Alert severity="warning">
|
||||
The server may have saved this request. Retrying reuses account {pending.accountId}, variant {pending.variantId}, and quantity {pending.quantity}.
|
||||
</Alert> : <>
|
||||
{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="variantId" label="Variant ID" maxLength={36} />
|
||||
{can("catalog.read") && <WorkspaceLink href="/admin/catalog">Find variant IDs in the product catalog</WorkspaceLink>}
|
||||
<Field name="quantity" label="Sample quantity" type="number" helper="Enter 1 to 100." />
|
||||
<Field name="purpose" label="Sample purpose" maxLength={500} />
|
||||
</>}
|
||||
</ActionForm>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function SampleDetail({ id }: { id: string }) {
|
||||
const { can } = usePlatform();
|
||||
const query = usePrivateQuery(`${api}/${id}`, sampleRequest);
|
||||
return <QueryView query={query}>{(sample) => <div className="workspace-id">
|
||||
<Panel title={`${sample.variantName} (${sample.sku})`}>
|
||||
<p>{sample.status} · Quantity {sample.quantity}</p>
|
||||
<p>{sample.purpose}</p>
|
||||
<p>Business account {sample.accountId}</p>
|
||||
<WorkspaceLink href={`${route}/account/${sample.accountId}`}>All sample requests for this business</WorkspaceLink>
|
||||
{can("b2b.read") && <p><WorkspaceLink href={`/admin/business-accounts/${sample.accountId}`}>Business profile</WorkspaceLink></p>}
|
||||
<p>Requested {new Date(sample.createdAt).toLocaleString()} by {sample.requestedById}</p>
|
||||
<SampleAction sample={sample} refresh={query.refetch} />
|
||||
</Panel>
|
||||
<Panel title="Review and dispatch history">
|
||||
<Table head={["Event", "Recorded", "Staff ID", "Note", "Dispatch reference"]}
|
||||
rowKeys={sample.events.map((event) => event.id)} rows={sample.events.map((event) => [
|
||||
event.kind, new Date(event.createdAt).toLocaleString(), event.actorId, event.note, event.dispatchReference ?? "—",
|
||||
])} />
|
||||
</Panel>
|
||||
</div>}</QueryView>;
|
||||
}
|
||||
|
||||
function SampleAction({ sample, refresh }: { sample: Sample; refresh: () => Promise<unknown> }) {
|
||||
const { can, principal, scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
const refreshLists = useRefreshSampleLists();
|
||||
const path = `${api}/${sample.id}`;
|
||||
const review = useIdempotentCommand(`${path}/decision`, sampleDecisionInput, sampleRequest, sample.id);
|
||||
const dispatch = useIdempotentCommand(`${path}/dispatch`, sampleDispatchInput, sampleRequest, sample.id);
|
||||
const reviewing = sample.status === "REQUESTED" && can("b2b.sample.review");
|
||||
const dispatching = sample.status === "APPROVED" && can("b2b.sample.dispatch");
|
||||
if (!reviewing && !dispatching) return null;
|
||||
if (reviewing && sample.requestedById === principal?.userId.toLowerCase()) {
|
||||
return <Alert severity="info">A different staff member must review this sample request.</Alert>;
|
||||
}
|
||||
|
||||
const command = reviewing ? review : dispatch;
|
||||
const pending = command.pending;
|
||||
const label = reviewing ? (pending ? "Retry sample decision" : "Record sample decision") :
|
||||
(pending ? "Retry dispatch" : "Record dispatch");
|
||||
return <ActionForm key={`${sample.status}:${Boolean(pending)}`} label={label}
|
||||
read={(form) => pending ? {} : ({
|
||||
note: readText(form, "note"),
|
||||
...(reviewing ? { decision: readText(form, "decision") } :
|
||||
{ dispatchReference: readText(form, "dispatchReference") }),
|
||||
})}
|
||||
submit={async (input) => {
|
||||
try {
|
||||
const saved = await command.run(input);
|
||||
client.setQueryData(["private", scope, path], saved);
|
||||
await refreshLists();
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && ["B2B_SAMPLE_REVIEW_STATE", "B2B_SAMPLE_DISPATCH_STATE"].includes(error.code ?? "")) {
|
||||
await Promise.all([refresh(), refreshLists()]);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}}>
|
||||
{pending ? <Alert severity="warning">The server may have saved this action. Retrying reuses the original details.</Alert> : <>
|
||||
{reviewing ? <Field name="decision" label="Review decision" options={[
|
||||
{ value: "", label: "Choose an outcome" }, { value: "APPROVED", label: "Approve" }, { value: "REJECTED", label: "Reject" },
|
||||
]} /> : <>
|
||||
<p>Record dispatch after the physical handoff. Enter the shipment or handoff reference.</p>
|
||||
<Field name="dispatchReference" label="Dispatch reference" maxLength={100} />
|
||||
</>}
|
||||
<Field name="note" label={reviewing ? "Review note" : "Dispatch note"} maxLength={500} />
|
||||
</>}
|
||||
</ActionForm>;
|
||||
}
|
||||
|
||||
export default function SamplesPage({ id, accountId, create = false }: { id?: string; accountId?: string; create?: boolean }) {
|
||||
const sample = uuid.safeParse(id);
|
||||
const account = uuid.safeParse(accountId);
|
||||
return <WorkspaceShell title="B2B Samples" permission="b2b.sample.read">
|
||||
{(id || accountId || create) && <WorkspaceLink href={route}>All sample requests</WorkspaceLink>}
|
||||
{(id && !sample.success) || (accountId && !account.success) ? <Alert severity="warning">Invalid sample or business account ID.</Alert> :
|
||||
create ? <RequestSamples key={account.data ?? "new"} accountId={account.data} /> :
|
||||
sample.success ? <SampleDetail key={sample.data} id={sample.data} /> :
|
||||
<SampleList key={account.data ?? "all"} accountId={account.data} />}
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
|
@ -1,183 +0,0 @@
|
|||
import { useId, useState } from "react";
|
||||
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 { uuid } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { documentDecision, documentDetails, documentInput, documentVersion, prepareDocumentUpload, supplierDocument } from "@/lib/supplier-documents";
|
||||
|
||||
const kindOptions = [
|
||||
{ value: "REGISTRATION", label: "Registration" },
|
||||
{ value: "TAX_CERTIFICATE", label: "Tax certificate" },
|
||||
{ value: "COMPLIANCE_CERTIFICATE", label: "Compliance certificate" },
|
||||
{ value: "OTHER", label: "Other" },
|
||||
];
|
||||
type Version = z.infer<typeof documentVersion>;
|
||||
|
||||
function FindSupplier() {
|
||||
const { can } = usePlatform();
|
||||
const [, navigate] = useLocation();
|
||||
return <Panel title="Open supplier documents">
|
||||
{can("procurement.read") && <p>Choose a supplier in the <WorkspaceLink href="/admin/procurement">supplier directory</WorkspaceLink>.</p>}
|
||||
<ActionForm label="Open documents" read={(data) => ({ supplierId: readText(data, "supplierId").trim() })}
|
||||
submit={async (input) => {
|
||||
const { supplierId } = z.object({ supplierId: uuid }).parse(input);
|
||||
navigate(`/admin/supplier-documents/${supplierId}`);
|
||||
}}>
|
||||
<Field name="supplierId" label="Supplier ID" maxLength={36} helper="Enter the supplier UUID from a supplier document link." />
|
||||
</ActionForm>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function SupplierDocumentList({ id }: { id: string }) {
|
||||
const { can, request } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [selected, select] = useState("");
|
||||
const path = `/suppliers/${id}/documents`;
|
||||
const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, z.array(supplierDocument));
|
||||
return <>
|
||||
<p className="workspace-id">Supplier ID {id}</p>
|
||||
<WorkspaceLink href="/admin/supplier-documents">Open another supplier</WorkspaceLink>
|
||||
<Panel title="Documents">
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Code", "Title", "Type", "Actions"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
row.code, row.title, kindOptions.find((kind) => kind.value === row.kind)?.label ?? row.kind,
|
||||
<Button onClick={() => select(row.id)} aria-pressed={selected === row.id}>Open {row.code}</Button>,
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
{can("supplier_document.manage") && <ActionForm label="Create document"
|
||||
read={(data) => documentInput.parse(Object.fromEntries(data))}
|
||||
submit={async (body) => {
|
||||
try {
|
||||
const result = await request(path, supplierDocument, { method: "POST", body });
|
||||
select(result.id);
|
||||
setOffset(0);
|
||||
} finally {
|
||||
await query.refetch();
|
||||
}
|
||||
}}>
|
||||
<Field name="code" label="Document code" maxLength={32} />
|
||||
<Field name="title" label="Document title" maxLength={160} />
|
||||
<Field name="kind" label="Document type" options={kindOptions} />
|
||||
</ActionForm>}
|
||||
</>}</QueryView>
|
||||
</Panel>
|
||||
{selected && <DocumentVersions key={selected} id={selected} close={() => select("")} />}
|
||||
</>;
|
||||
}
|
||||
|
||||
function DocumentVersions({ id, close }: { id: string; close: () => void }) {
|
||||
const { can, request } = usePlatform();
|
||||
const [versionId, select] = useState("");
|
||||
const [uncertain, setUncertain] = useState(false);
|
||||
const fileId = useId();
|
||||
const path = `/supplier-documents/${id}`;
|
||||
const query = usePrivateQuery(path, documentDetails);
|
||||
return <>
|
||||
<Button onClick={close}>Close document</Button>
|
||||
<QueryView query={query}>{(record) => {
|
||||
const version = record.versions.find((entry) => entry.id === versionId);
|
||||
return <Panel title={`Versions of ${record.code}`}>
|
||||
<Table head={["Version", "PDF", "Uploaded", "Review", "Actions"]} rowKeys={record.versions.map((entry) => entry.id)}
|
||||
rows={record.versions.map((entry) => [
|
||||
entry.version, entry.filename, new Date(entry.createdAt).toLocaleString(),
|
||||
entry.decision?.outcome ?? "Pending",
|
||||
<Button onClick={() => select(entry.id)} aria-pressed={versionId === entry.id}>View version {entry.version}</Button>,
|
||||
])} />
|
||||
{version && <VersionActions key={version.id} version={version} refresh={query.refetch} />}
|
||||
{uncertain ? <Alert severity="warning">
|
||||
The server may have saved the PDF. Review the version list, then close and reopen the document before uploading again.
|
||||
<Button onClick={() => query.refetch()}>Refresh versions</Button>
|
||||
</Alert> : can("supplier_document.manage") && (record.versions.length < 20 ? (
|
||||
<ActionForm label="Upload PDF version" read={(data) => prepareDocumentUpload(data.get("file"))}
|
||||
submit={async (body) => {
|
||||
try {
|
||||
const saved = await request(`${path}/versions`, documentVersion, { method: "POST", body });
|
||||
select(saved.id);
|
||||
} catch (error) {
|
||||
if (isUnknownOutcome(error)) setUncertain(true);
|
||||
throw error;
|
||||
} finally {
|
||||
await query.refetch();
|
||||
}
|
||||
}}>
|
||||
<label htmlFor={fileId}>PDF file</label>
|
||||
<input id={fileId} name="file" type="file" accept="application/pdf,.pdf" required aria-describedby={`${fileId}-help`} style={{ maxWidth: "100%" }} />
|
||||
<p id={`${fileId}-help`}>Maximum 2 MiB. Use a simple .pdf filename.</p>
|
||||
</ActionForm>
|
||||
) : <Alert severity="info">This document has reached the 20-version limit.</Alert>)}
|
||||
</Panel>;
|
||||
}}</QueryView>
|
||||
</>;
|
||||
}
|
||||
|
||||
function VersionActions({ version, refresh }: { version: Version; refresh: () => Promise<unknown> }) {
|
||||
const { can, principal, request, downloadPdf } = usePlatform();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<unknown>(null);
|
||||
const reviewer = can("supplier_document.validate");
|
||||
const ownVersion = version.uploadedById === principal?.userId.toLowerCase();
|
||||
return <Panel title={`Version ${version.version}`}>
|
||||
<p className="workspace-id">{version.filename}</p>
|
||||
{version.decision && <p>{version.decision.outcome}{version.decision.reason && ` · ${version.decision.reason}`}</p>}
|
||||
{(reviewer || version.decision?.outcome === "APPROVED") && <>
|
||||
<Button disabled={busy} onClick={async () => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const file = await downloadPdf(version.id, version.size);
|
||||
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 (error) {
|
||||
setError(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}>{busy ? "Downloading…" : "Download PDF"}</Button>
|
||||
<ApiNotice error={error} />
|
||||
</>}
|
||||
{reviewer && !version.decision && (ownVersion ? (
|
||||
<Alert severity="info">Another reviewer must decide on this version.</Alert>
|
||||
) : <ActionForm label="Save review decision" read={(data) => documentDecision.parse({
|
||||
outcome: readText(data, "outcome"),
|
||||
reason: readText(data, "reason").trim() || undefined,
|
||||
})} submit={async (body) => {
|
||||
try {
|
||||
await request(`/supplier-document-versions/${version.id}/decision`, documentVersion, { method: "POST", body });
|
||||
} finally {
|
||||
await refresh();
|
||||
}
|
||||
}}>
|
||||
<p>Review decisions are final.</p>
|
||||
<Field name="outcome" label="Review outcome" options={[
|
||||
{ value: "", label: "Choose an outcome" },
|
||||
{ value: "APPROVED", label: "Approve" },
|
||||
{ value: "REJECTED", label: "Reject" },
|
||||
]} />
|
||||
<Field name="reason" label="Review reason" maxLength={500} required={false} helper="Required when rejecting a version." />
|
||||
</ActionForm>)}
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
export default function SupplierDocumentsPage({ supplierId }: { supplierId?: string }) {
|
||||
const id = uuid.safeParse(supplierId);
|
||||
return <WorkspaceShell title="Supplier Documents" permission="supplier_document.read">
|
||||
{!supplierId ? <FindSupplier /> : id.success ? <SupplierDocumentList key={id.data} id={id.data} /> :
|
||||
<Alert severity="warning">Invalid supplier ID. <WorkspaceLink href="/admin/supplier-documents">Open supplier documents</WorkspaceLink></Alert>}
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
|
@ -8,28 +8,22 @@ import Alert from "@mui/material/Alert";
|
|||
import { usePlatform } from "@/lib/platform";
|
||||
import { ApiNotice } from "@/components/ApiNotice";
|
||||
import "./workspace.css";
|
||||
import { WorkspaceNavigation } from "@/components/WorkspaceShell";
|
||||
|
||||
export default function WorkspacePage() {
|
||||
const { organization, principal, signIn, signUp, signOut, notice } =
|
||||
usePlatform();
|
||||
const { organization, principal, signIn, signOut, notice } = usePlatform();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<unknown>(null);
|
||||
const [creating, setCreating] = useState(false);
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const fields = new FormData(form);
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const name = String(fields.get("name") ?? "");
|
||||
const email = String(fields.get("email"));
|
||||
const password = String(fields.get("password"));
|
||||
form.reset();
|
||||
try {
|
||||
await (creating
|
||||
? signUp(name, email, password)
|
||||
: signIn(email, password));
|
||||
await signIn(email, password);
|
||||
} catch (error) {
|
||||
setError(error);
|
||||
} finally {
|
||||
|
|
@ -50,16 +44,15 @@ export default function WorkspacePage() {
|
|||
return (
|
||||
<section className="workspace-page">
|
||||
<Container maxWidth="md">
|
||||
<h1>Account Workspace</h1>
|
||||
<h1>Staff Workspace</h1>
|
||||
<p className="workspace-intro">
|
||||
Sign in, or create a customer account to shop.
|
||||
Sign in with your approved Mani Candles account.
|
||||
</p>
|
||||
<Paper variant="outlined" className="workspace-panel">
|
||||
<ApiNotice error={error} />
|
||||
{notice && <Alert severity="info">{notice}</Alert>}
|
||||
{principal ? (
|
||||
<>
|
||||
<WorkspaceNavigation />
|
||||
<h2>Your session</h2>
|
||||
<p className="workspace-id">
|
||||
Organization: {principal.organizationId}
|
||||
|
|
@ -73,10 +66,11 @@ export default function WorkspacePage() {
|
|||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>Customer account. Use your cart, addresses and orders below.</p>
|
||||
<p>No permissions assigned. Contact your administrator.</p>
|
||||
)}
|
||||
<p className="workspace-intro">
|
||||
Open a customer or administration tool below.
|
||||
Operational tools will be connected in the following frontend
|
||||
phases.
|
||||
</p>
|
||||
<Button variant="contained" disabled={busy} onClick={logout}>
|
||||
{busy ? "Signing out…" : "Sign out"}
|
||||
|
|
@ -94,20 +88,11 @@ export default function WorkspacePage() {
|
|||
backend.
|
||||
</Alert>
|
||||
)}
|
||||
{creating && (
|
||||
<TextField
|
||||
label="Full name"
|
||||
name="name"
|
||||
autoComplete="name"
|
||||
required
|
||||
inputProps={{ maxLength: 160 }}
|
||||
/>
|
||||
)}
|
||||
<TextField
|
||||
label="Email address"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete={creating ? "email" : "username"}
|
||||
autoComplete="username"
|
||||
required
|
||||
inputProps={{ maxLength: 254 }}
|
||||
/>
|
||||
|
|
@ -115,44 +100,21 @@ export default function WorkspacePage() {
|
|||
label="Password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete={creating ? "new-password" : "current-password"}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
helperText={creating ? "At least 15 characters." : undefined}
|
||||
inputProps={{ minLength: creating ? 15 : 1, maxLength: 128 }}
|
||||
inputProps={{ maxLength: 128 }}
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
type="submit"
|
||||
disabled={busy || !organization}
|
||||
>
|
||||
{creating
|
||||
? 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"}
|
||||
{busy ? "Signing in…" : "Sign in"}
|
||||
</Button>
|
||||
<small>
|
||||
Sessions stay in memory. Reloading or closing this page requires
|
||||
a new sign-in.
|
||||
</small>
|
||||
<Link href="/recovery">
|
||||
<u>Forgot password?</u>
|
||||
</Link>
|
||||
</form>
|
||||
)}
|
||||
</Paper>
|
||||
|
|
|
|||
|
|
@ -53,7 +53,7 @@ export default function Home() {
|
|||
}, 8000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [moods.length]);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Box>
|
||||
|
|
|
|||
|
|
@ -1,176 +1,176 @@
|
|||
/* ─── products.css ───────────────────────────────────────── */
|
||||
|
||||
/* HERO */
|
||||
.products-hero {
|
||||
padding: 6rem 1.5rem;
|
||||
background: var(--brand-card);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.products-hero h1 {
|
||||
font-family: var(--font-serif);
|
||||
font-size: clamp(2.5rem, 6vw, 4rem);
|
||||
color: var(--brand-purple);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.products-hero p {
|
||||
font-family: var(--font-sans);
|
||||
font-size: 1.05rem;
|
||||
color: var(--brand-muted);
|
||||
line-height: 1.8;
|
||||
max-width: 640px;
|
||||
margin: 0 auto 2rem;
|
||||
}
|
||||
|
||||
/* FILTERS */
|
||||
.products-body {
|
||||
padding: 5rem 1.5rem;
|
||||
background: var(--brand-light-lavender);
|
||||
}
|
||||
|
||||
.filter-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
margin-bottom: 4rem;
|
||||
}
|
||||
|
||||
.filter-btn {
|
||||
font-family: var(--font-display);
|
||||
font-size: 0.72rem;
|
||||
letter-spacing: 0.2em;
|
||||
text-transform: uppercase;
|
||||
padding: 0.5rem 1.5rem;
|
||||
background: none;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
color: var(--brand-muted);
|
||||
cursor: pointer;
|
||||
transition: color 0.3s ease, border-color 0.3s ease;
|
||||
}
|
||||
|
||||
.filter-btn:hover {
|
||||
color: var(--brand-purple);
|
||||
}
|
||||
|
||||
.filter-btn.active {
|
||||
color: var(--brand-purple);
|
||||
border-bottom-color: var(--brand-gold);
|
||||
}
|
||||
|
||||
/* PRODUCT GRID */
|
||||
.products-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 3rem 2rem;
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
@media (min-width: 640px) { .products-grid { grid-template-columns: 1fr 1fr; } }
|
||||
@media (min-width: 1024px) { .products-grid { grid-template-columns: repeat(4, 1fr); } }
|
||||
|
||||
.prod-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.prod-img-wrap {
|
||||
position: relative;
|
||||
aspect-ratio: 4 / 5;
|
||||
overflow: hidden;
|
||||
background: var(--brand-card);
|
||||
border: 1px solid var(--brand-border);
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.prod-img-wrap img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
transition: transform 1s ease;
|
||||
}
|
||||
|
||||
.prod-card:hover .prod-img-wrap img {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.prod-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(91,30,140,0.3);
|
||||
opacity: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
backdrop-filter: blur(2px);
|
||||
transition: opacity 0.5s ease;
|
||||
}
|
||||
|
||||
.prod-card:hover .prod-overlay {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.prod-overlay-btn {
|
||||
padding: 0.75rem 2rem;
|
||||
background: var(--brand-light-lavender);
|
||||
color: var(--brand-purple);
|
||||
font-family: var(--font-display);
|
||||
font-size: 0.72rem;
|
||||
letter-spacing: 0.18em;
|
||||
text-transform: uppercase;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
transform: translateY(32px);
|
||||
transition: transform 0.5s ease, background 0.3s ease, color 0.3s ease;
|
||||
box-shadow: 0 4px 16px rgba(0,0,0,0.15);
|
||||
}
|
||||
|
||||
.prod-card:hover .prod-overlay-btn {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.prod-overlay-btn:hover {
|
||||
background: var(--brand-gold);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.prod-info {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.prod-name {
|
||||
font-family: var(--font-serif);
|
||||
font-size: 1.4rem;
|
||||
color: var(--brand-purple);
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.prod-scent {
|
||||
font-family: var(--font-sans);
|
||||
font-size: 0.85rem;
|
||||
color: var(--brand-muted);
|
||||
line-height: 1.5;
|
||||
margin-bottom: 0.75rem;
|
||||
/* two-line clamp */
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.prod-price {
|
||||
font-family: var(--font-sans);
|
||||
font-weight: 500;
|
||||
font-size: 1.05rem;
|
||||
color: var(--brand-gold);
|
||||
}
|
||||
/* ─── products.css ───────────────────────────────────────── */
|
||||
|
||||
/* HERO */
|
||||
.products-hero {
|
||||
padding: 6rem 1.5rem;
|
||||
background: var(--brand-card);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.products-hero h1 {
|
||||
font-family: var(--font-serif);
|
||||
font-size: clamp(2.5rem, 6vw, 4rem);
|
||||
color: var(--brand-purple);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.products-hero p {
|
||||
font-family: var(--font-sans);
|
||||
font-size: 1.05rem;
|
||||
color: var(--brand-muted);
|
||||
line-height: 1.8;
|
||||
max-width: 640px;
|
||||
margin: 0 auto 2rem;
|
||||
}
|
||||
|
||||
/* FILTERS */
|
||||
.products-body {
|
||||
padding: 5rem 1.5rem;
|
||||
background: var(--brand-light-lavender);
|
||||
}
|
||||
|
||||
.filter-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
margin-bottom: 4rem;
|
||||
}
|
||||
|
||||
.filter-btn {
|
||||
font-family: var(--font-display);
|
||||
font-size: 0.72rem;
|
||||
letter-spacing: 0.2em;
|
||||
text-transform: uppercase;
|
||||
padding: 0.5rem 1.5rem;
|
||||
background: none;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
color: var(--brand-muted);
|
||||
cursor: pointer;
|
||||
transition: color 0.3s ease, border-color 0.3s ease;
|
||||
}
|
||||
|
||||
.filter-btn:hover {
|
||||
color: var(--brand-purple);
|
||||
}
|
||||
|
||||
.filter-btn.active {
|
||||
color: var(--brand-purple);
|
||||
border-bottom-color: var(--brand-gold);
|
||||
}
|
||||
|
||||
/* PRODUCT GRID */
|
||||
.products-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 3rem 2rem;
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
@media (min-width: 640px) { .products-grid { grid-template-columns: 1fr 1fr; } }
|
||||
@media (min-width: 1024px) { .products-grid { grid-template-columns: repeat(4, 1fr); } }
|
||||
|
||||
.prod-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.prod-img-wrap {
|
||||
position: relative;
|
||||
aspect-ratio: 4 / 5;
|
||||
overflow: hidden;
|
||||
background: var(--brand-card);
|
||||
border: 1px solid var(--brand-border);
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.prod-img-wrap img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
transition: transform 1s ease;
|
||||
}
|
||||
|
||||
.prod-card:hover .prod-img-wrap img {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.prod-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(91,30,140,0.3);
|
||||
opacity: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
backdrop-filter: blur(2px);
|
||||
transition: opacity 0.5s ease;
|
||||
}
|
||||
|
||||
.prod-card:hover .prod-overlay {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.prod-overlay-btn {
|
||||
padding: 0.75rem 2rem;
|
||||
background: var(--brand-light-lavender);
|
||||
color: var(--brand-purple);
|
||||
font-family: var(--font-display);
|
||||
font-size: 0.72rem;
|
||||
letter-spacing: 0.18em;
|
||||
text-transform: uppercase;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
transform: translateY(32px);
|
||||
transition: transform 0.5s ease, background 0.3s ease, color 0.3s ease;
|
||||
box-shadow: 0 4px 16px rgba(0,0,0,0.15);
|
||||
}
|
||||
|
||||
.prod-card:hover .prod-overlay-btn {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.prod-overlay-btn:hover {
|
||||
background: var(--brand-gold);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.prod-info {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.prod-name {
|
||||
font-family: var(--font-serif);
|
||||
font-size: 1.4rem;
|
||||
color: var(--brand-purple);
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.prod-scent {
|
||||
font-family: var(--font-sans);
|
||||
font-size: 0.85rem;
|
||||
color: var(--brand-muted);
|
||||
line-height: 1.5;
|
||||
margin-bottom: 0.75rem;
|
||||
/* two-line clamp */
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.prod-price {
|
||||
font-family: var(--font-sans);
|
||||
font-weight: 500;
|
||||
font-size: 1.05rem;
|
||||
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 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 dt { font-weight:600; }
|
||||
@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; }
|
||||
|
|
|
|||
|
|
@ -56,116 +56,3 @@
|
|||
padding: 1.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.workspace-links {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin: 1.5rem 0;
|
||||
}
|
||||
.workspace-panel {
|
||||
margin: 1.5rem 0;
|
||||
}
|
||||
.workspace-form fieldset {
|
||||
border: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
min-width: 0;
|
||||
}
|
||||
.workspace-table {
|
||||
overflow-x: auto;
|
||||
}
|
||||
.workspace-table table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.workspace-table th,
|
||||
.workspace-table td {
|
||||
padding: 0.75rem;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--brand-border);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.workspace-table th {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.workspace-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 1.5rem;
|
||||
}
|
||||
.workspace-grid .workspace-panel {
|
||||
margin: 0;
|
||||
}
|
||||
.order-totals {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
gap: 0.75rem;
|
||||
margin: 1.5rem 0;
|
||||
}
|
||||
@media (max-width: 768px) {
|
||||
.workspace-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.cart-lines {
|
||||
border: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
.cart-line {
|
||||
border-bottom: 1px solid var(--brand-border);
|
||||
padding: 1.5rem 0;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
.cart-line form,
|
||||
.cart-add {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.cart-line input,
|
||||
.cart-add input {
|
||||
max-width: 100px;
|
||||
}
|
||||
.address-card {
|
||||
padding: 1rem 0;
|
||||
border-bottom: 1px solid var(--brand-border);
|
||||
}
|
||||
.record-picker {
|
||||
border: 1px solid var(--brand-border) !important;
|
||||
padding: 1rem !important;
|
||||
}
|
||||
.attribute-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr auto;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.coupon-kind {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
.coupon-kind button {
|
||||
padding: 0.75rem;
|
||||
background: var(--brand-card);
|
||||
border: 1px solid var(--brand-purple);
|
||||
color: var(--brand-purple);
|
||||
cursor: pointer;
|
||||
}
|
||||
.coupon-kind button[aria-pressed="true"] {
|
||||
background: var(--brand-purple);
|
||||
color: white;
|
||||
}
|
||||
@media (max-width: 768px) {
|
||||
.attribute-row {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,8 +2,6 @@ import { test, afterEach } from "node:test";
|
|||
import assert from "node:assert/strict";
|
||||
import {
|
||||
apiRequest,
|
||||
apiPdf,
|
||||
apiArtwork,
|
||||
listProducts,
|
||||
getProduct,
|
||||
login,
|
||||
|
|
@ -11,97 +9,11 @@ import {
|
|||
healthCheck,
|
||||
ApiError,
|
||||
} from "../src/lib/api.ts";
|
||||
import { documentDecision, maxDocumentBytes, prepareDocumentUpload } from "../src/lib/supplier-documents.ts";
|
||||
const originalFetch = globalThis.fetch;
|
||||
const org = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
test("supplier document upload sends an authenticated multipart file with a browser-generated boundary", async () => {
|
||||
const file = new File(["%PDF-1.7\n%%EOF"], "certificate.pdf", { type: "application/pdf" });
|
||||
const body = prepareDocumentUpload(file);
|
||||
globalThis.fetch = async (url, options) => {
|
||||
assert.equal(url, `/api/v1/supplier-documents/${org}/versions`);
|
||||
assert.equal(options?.method, "POST");
|
||||
const headers = new Headers(options?.headers);
|
||||
assert.equal(headers.get("authorization"), "Bearer opaque");
|
||||
assert.equal(headers.has("content-type"), false);
|
||||
assert.equal(options?.redirect, "error");
|
||||
assert.equal(options?.body, body);
|
||||
assert.equal(body.get("file"), file);
|
||||
return new Response(JSON.stringify({ version: 1 }));
|
||||
};
|
||||
await apiRequest(`/supplier-documents/${org}/versions`, { method: "POST", token: "opaque", body });
|
||||
assert.throws(() => prepareDocumentUpload(new File(["x"], "unsafe filename.pdf")), /simple .pdf filename/);
|
||||
assert.throws(() => prepareDocumentUpload(new File([new Uint8Array(maxDocumentBytes + 1)], "large.pdf")), /2 MiB/);
|
||||
assert.equal(documentDecision.safeParse({ outcome: "REJECTED", reason: " " }).success, false);
|
||||
assert.equal(documentDecision.safeParse({ outcome: "APPROVED" }).success, true);
|
||||
});
|
||||
|
||||
test("private PDF downloads preserve API denial and require the expected PDF media type and size", async () => {
|
||||
const controller = new AbortController();
|
||||
const path = `/supplier-document-versions/${org}/download`;
|
||||
const content = "%PDF-1.7\n%%EOF";
|
||||
globalThis.fetch = async (url, options) => {
|
||||
assert.equal(url, `/api/v1${path}`);
|
||||
const headers = new Headers(options?.headers);
|
||||
assert.equal(headers.get("authorization"), "Bearer opaque");
|
||||
assert.equal(headers.get("accept"), "application/pdf");
|
||||
assert.equal(options?.cache, "no-store");
|
||||
assert.equal(options?.redirect, "error");
|
||||
return new Response(content, { headers: { "Content-Type": "application/pdf" } });
|
||||
};
|
||||
assert.equal(await (await apiPdf(path, content.length, "opaque", controller.signal)).text(), content);
|
||||
await assert.rejects(apiPdf(path, 1, "opaque", controller.signal), { code: "INVALID_RESPONSE" });
|
||||
globalThis.fetch = async () => new Response(content, { headers: { "Content-Type": "text/html" } });
|
||||
await assert.rejects(apiPdf(path, content.length, "opaque", controller.signal), { code: "INVALID_RESPONSE" });
|
||||
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 });
|
||||
});
|
||||
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 () => {
|
||||
globalThis.fetch = async () => {
|
||||
assert.fail("Must not send a request");
|
||||
|
|
|
|||
|
|
@ -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" })));
|
||||
});
|
||||
|
|
@ -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();
|
||||
});
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { bomDetail, bomInput, bomSummary } from "../src/lib/bom.ts";
|
||||
|
||||
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
||||
|
||||
test("draft BOMs preserve exact quantities and reject duplicate materials and invalid yields", () => {
|
||||
const line = { materialId: id, quantity: "0.125" };
|
||||
const input = { outputQuantity: 10, lines: [line] };
|
||||
assert.deepEqual(bomInput.parse(input), input);
|
||||
assert.equal(bomInput.safeParse({ ...input, outputQuantity: 100001 }).success, false);
|
||||
assert.equal(bomInput.safeParse({ ...input, lines: [] }).success, false);
|
||||
assert.equal(bomInput.safeParse({ ...input, lines: [{ ...line, quantity: "0.000" }] }).success, false);
|
||||
assert.equal(bomInput.safeParse({ ...input, lines: [{ ...line, quantity: "0.12" }] }).success, false);
|
||||
assert.equal(bomInput.safeParse({ ...input, lines: [line, { ...line, materialId: id.toUpperCase() }] }).success, false);
|
||||
});
|
||||
|
||||
test("revision lists accept metadata without lines and details accept serialized decimal snapshots", () => {
|
||||
const metadata = { id, variantId: id, kind: "PACKAGING", status: "DRAFT", revision: 1, outputQuantity: 10, activatedAt: null };
|
||||
assert.deepEqual(bomSummary.parse(metadata), metadata);
|
||||
assert.equal(bomDetail.safeParse(metadata).success, false);
|
||||
const line = { id, materialId: id, materialName: "Label", materialCode: "LABEL", unit: "PIECE", quantity: "10" };
|
||||
assert.deepEqual(bomDetail.parse({ ...metadata, lines: [line] }).lines, [line]);
|
||||
});
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { businessEvent, businessInput, businessProfile, decisionInput } from "../src/lib/business.ts";
|
||||
|
||||
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
||||
const profile = {
|
||||
legalName: "Studio", tradingName: null, registrationNumber: "REG-42", taxIdentifier: null,
|
||||
countryCode: "IN", contactEmail: "buyer@example.com", contactPhone: null, billingLine1: "42 Example Road",
|
||||
billingCity: "Mumbai", billingRegion: "Maharashtra", billingPostalCode: "400001",
|
||||
};
|
||||
|
||||
test("business drafts normalize identifiers and keep optional details nullable", () => {
|
||||
assert.deepEqual(businessInput.parse({ ...profile, code: " studio ", countryCode: "in", contactEmail: "BUYER@example.com" }),
|
||||
{ ...profile, code: "STUDIO" });
|
||||
assert.equal(businessProfile.safeParse({ ...profile, code: "CANNOT_CHANGE" }).success, false);
|
||||
assert.equal(businessProfile.safeParse({ ...profile, legalName: "<invalid>" }).success, false);
|
||||
});
|
||||
|
||||
test("review events preserve submitted profile versions without command metadata", () => {
|
||||
const event = businessEvent.parse({
|
||||
id, actorId: id, sequence: 1, kind: "SUBMITTED", profileSnapshot: { ...profile, profileVersion: 2 },
|
||||
note: null, createdAt: "2026-11-14T00:00:00.000Z", requestHash: "internal", idempotencyKey: id,
|
||||
});
|
||||
assert.equal(event.profileSnapshot?.profileVersion, 2);
|
||||
assert.equal("requestHash" in event, false);
|
||||
assert.equal(decisionInput.safeParse({ decision: "APPROVED", note: " ", idempotencyKey: id }).success, false);
|
||||
assert.equal(decisionInput.parse({ decision: "REJECTED", note: " Details differ ", idempotencyKey: id }).note, "Details differ");
|
||||
});
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { batchSnapshot, bomEstimate, costRate, costRateInput } from "../src/lib/costing.ts";
|
||||
|
||||
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
||||
const date = "2026-11-14T00:00:00.000Z";
|
||||
const material = {
|
||||
bomLineId: id, materialId: id, materialCode: "WAX", materialName: "Wax",
|
||||
unit: "GRAM", rateId: id, rateRevision: 2, unitCost: "99999999.9999",
|
||||
};
|
||||
|
||||
test("standard rates preserve four input decimals and accept serialized revision history", () => {
|
||||
const input = { currency: "INR", unitCost: "0.1250" };
|
||||
assert.deepEqual(costRateInput.parse(input), input);
|
||||
assert.equal(costRateInput.safeParse({ ...input, unitCost: "0.0000" }).success, false);
|
||||
assert.equal(costRateInput.safeParse({ ...input, unitCost: "0.125" }).success, false);
|
||||
assert.equal(costRateInput.safeParse({ ...input, currency: "JPY" }).success, false);
|
||||
assert.equal(costRate.parse({ ...input, id, materialId: id, revision: 2, createdAt: date, unitCost: "0.125" }).unitCost, "0.125");
|
||||
});
|
||||
|
||||
test("estimates and snapshots preserve exact backend totals and rate references", () => {
|
||||
const estimate = {
|
||||
bomId: id, kind: "PACKAGING", currency: "USD", outputQuantity: 10, estimatedAt: date,
|
||||
estimatedTotal: "9999999999.99", lines: [{ ...material, quantity: "100.000", estimatedCost: "9999999999.99" }],
|
||||
};
|
||||
assert.deepEqual(bomEstimate.parse(estimate), estimate);
|
||||
const snapshot = {
|
||||
id, batchId: id, currency: "USD", goodQuantity: 0, createdAt: date, productionTotal: "9999999999.99",
|
||||
packagingTotal: "0.00", total: "9999999999.99",
|
||||
lines: [{ ...material, kind: "PRODUCTION", usedQuantity: "100.000", wastedQuantity: "0.000", lineCost: "9999999999.99" }],
|
||||
};
|
||||
assert.deepEqual(batchSnapshot.parse(snapshot), snapshot);
|
||||
assert.equal(batchSnapshot.safeParse({ ...snapshot, total: 9999999999.99 }).success, false);
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue