Compare commits
93 Commits
fix/ci-onl
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| abe75fb1fd | |||
|
|
45fd6d34eb | ||
| 30233b430f | |||
|
|
924a28e201 | ||
|
|
2cd646ddea | ||
|
|
3f9e125412 | ||
| 7bca854058 | |||
|
|
96d2a966d7 | ||
|
|
666ae8d59b | ||
| 67f1e4a26a | |||
|
|
613784a1cc | ||
| ea9aceec46 | |||
|
|
bc8613bbbc | ||
|
|
a1dc4b0e47 | ||
| 81de80abb9 | |||
|
|
75c7c28f73 | ||
|
|
99fdaaa05a | ||
| 6870aea1a5 | |||
|
|
e589ff02f0 | ||
|
|
da4b765b14 | ||
|
|
326b30161b | ||
|
|
ac9b615470 | ||
|
|
785071e5fd | ||
|
|
0ca6ae7632 | ||
|
|
7d9aeaf188 | ||
|
|
be8cc0ad8b | ||
|
|
95cf017b4b | ||
|
|
a48da03289 | ||
|
|
e19cdc76e0 | ||
|
|
fe40b563d5 | ||
|
|
49db60e31f | ||
|
|
8820a56a51 | ||
|
|
0aa9345c27 | ||
|
|
3519db9bd9 | ||
|
|
0fd73015f7 | ||
|
|
d21972212b | ||
|
|
cf299ac1d2 | ||
|
|
6505b2dcb9 | ||
|
|
12a3e170de | ||
|
|
3ed2707a66 | ||
|
|
24ddb17ca8 | ||
|
|
bd2252e426 | ||
|
|
254fe0e5d5 | ||
|
|
5750af83d8 | ||
|
|
505f8fd4e4 | ||
|
|
a84530e80e | ||
|
|
b8e39369f1 | ||
|
|
81d37a2c68 | ||
|
|
70a924cfba | ||
| 2b9e99bbd6 | |||
|
|
a0be16d848 | ||
|
|
1673e18fe8 | ||
|
|
bd3a25aa1c | ||
| bd5f0ca511 | |||
|
|
aa5b53920d | ||
|
|
772d5578ad | ||
| 51e7902ee2 | |||
|
|
8256380cd1 | ||
|
|
199b9ab3b3 | ||
|
|
2b141d45f3 | ||
|
|
1c56023491 | ||
|
|
7b15f18e59 | ||
|
|
93450a1eb7 | ||
|
|
7aa81c4e7c | ||
|
|
b318345fdf | ||
|
|
cc5ab41da4 | ||
|
|
c54069ad99 | ||
|
|
04420dbd12 | ||
|
|
f538c60f3d | ||
|
|
1524153cfb | ||
|
|
4c31357428 | ||
|
|
b3e67d1483 | ||
|
|
3d081ee01f | ||
|
|
9942a5638f | ||
|
|
b40bab0391 | ||
|
|
de70fb47f9 | ||
|
|
c5d618698b | ||
|
|
54943ea1b7 | ||
|
|
ba1c385937 | ||
|
|
2231f06234 | ||
|
|
fe29e548fb | ||
|
|
3d72f04b14 | ||
|
|
36eb377583 | ||
|
|
b8f0c7ecba | ||
|
|
0034e0b8b3 | ||
|
|
d9a7409f9c | ||
|
|
358e07b1d5 | ||
|
|
5df914a40f | ||
|
|
1f8002629f | ||
|
|
ff2e4586f3 | ||
|
|
019867f1fa | ||
|
|
48d49a068a | ||
| 11f81cfd8e |
34
.gitea/workflows/build-devpod.yml
Normal file
34
.gitea/workflows/build-devpod.yml
Normal file
@@ -0,0 +1,34 @@
|
||||
name: Build Devpod
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- Dockerfile.devpod
|
||||
- entrypoint-devpod.sh
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
REGISTRY: registry.digitalocean.com/lunarfront
|
||||
DOCKER_HOST: tcp://localhost:2375
|
||||
VERSION: devpod-0.1.${{ github.run_number }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Login to DOCR
|
||||
run: echo "${{ secrets.DOCR_TOKEN }}" | docker login registry.digitalocean.com -u token --password-stdin
|
||||
|
||||
- name: Build and push devpod
|
||||
run: |
|
||||
docker build \
|
||||
-t $REGISTRY/manager:$VERSION \
|
||||
-t $REGISTRY/manager:devpod-latest \
|
||||
-f Dockerfile.devpod .
|
||||
docker push $REGISTRY/manager:$VERSION
|
||||
docker push $REGISTRY/manager:devpod-latest
|
||||
|
||||
@@ -12,53 +12,20 @@ concurrency:
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
if: "!startsWith(github.event.head_commit.message, 'chore: bump version')"
|
||||
env:
|
||||
REGISTRY: registry.digitalocean.com/lunarfront
|
||||
GIT_REMOTE: git2.lunarfront.tech
|
||||
DOCKER_HOST: tcp://localhost:2375
|
||||
VERSION: 0.1.${{ github.run_number }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.BOT_TOKEN }}
|
||||
|
||||
- name: Determine version bump
|
||||
id: bump
|
||||
run: |
|
||||
COMMIT_MSG=$(git log -1 --pretty=%s)
|
||||
if echo "$COMMIT_MSG" | grep -qiE "^breaking(\(.+\))?:|^.+!:"; then
|
||||
echo "type=major" >> $GITHUB_OUTPUT
|
||||
elif echo "$COMMIT_MSG" | grep -qiE "^feat(\(.+\))?:"; then
|
||||
echo "type=minor" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "type=patch" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Bump version in package.json
|
||||
id: version
|
||||
run: |
|
||||
VERSION=$(node -e "
|
||||
const fs = require('fs');
|
||||
const pkg = JSON.parse(fs.readFileSync('packages/backend/package.json', 'utf8'));
|
||||
const [major, minor, patch] = pkg.version.split('.').map(Number);
|
||||
const type = '${{ steps.bump.outputs.type }}';
|
||||
if (type === 'major') pkg.version = \`\${major + 1}.0.0\`;
|
||||
else if (type === 'minor') pkg.version = \`\${major}.\${minor + 1}.0\`;
|
||||
else pkg.version = \`\${major}.\${minor}.\${patch + 1}\`;
|
||||
fs.writeFileSync('packages/backend/package.json', JSON.stringify(pkg, null, 2) + '\n');
|
||||
console.log(pkg.version);
|
||||
")
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Login to DOCR
|
||||
run: echo "${{ secrets.DOCR_TOKEN }}" | docker login registry.digitalocean.com -u token --password-stdin
|
||||
|
||||
- name: Build and push backend
|
||||
run: |
|
||||
VERSION=${{ steps.version.outputs.version }}
|
||||
SHA=$(git rev-parse --short HEAD)
|
||||
docker build \
|
||||
--build-arg APP_VERSION=$VERSION \
|
||||
@@ -72,7 +39,6 @@ jobs:
|
||||
|
||||
- name: Build and push frontend
|
||||
run: |
|
||||
VERSION=${{ steps.version.outputs.version }}
|
||||
SHA=$(git rev-parse --short HEAD)
|
||||
docker build \
|
||||
-t $REGISTRY/lunarfront-frontend:$VERSION \
|
||||
@@ -84,31 +50,17 @@ jobs:
|
||||
docker push $REGISTRY/lunarfront-frontend:latest
|
||||
|
||||
- name: Install Helm
|
||||
run: |
|
||||
curl -fsSL https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
|
||||
run: curl -fsSL https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
|
||||
|
||||
- name: Package and push Helm chart
|
||||
run: |
|
||||
VERSION=${{ steps.version.outputs.version }}
|
||||
# Update chart version to match app version
|
||||
sed -i "s/^version:.*/version: $VERSION/" chart/Chart.yaml
|
||||
sed -i "s/^appVersion:.*/appVersion: \"$VERSION\"/" chart/Chart.yaml
|
||||
# Update default image tags in values.yaml to this version
|
||||
sed -i "s|tag: latest|tag: $VERSION|g" chart/values.yaml
|
||||
sed -i "s|tag: .*|tag: $VERSION|g" chart/values.yaml
|
||||
helm registry login registry.digitalocean.com -u token --password "${{ secrets.DOCR_TOKEN }}"
|
||||
helm package chart/
|
||||
helm push lunarfront-$VERSION.tgz oci://registry.digitalocean.com/lunarfront
|
||||
|
||||
- name: Commit version bump
|
||||
run: |
|
||||
git config user.name "lunarfront-bot"
|
||||
git config user.email "bot@lunarfront.tech"
|
||||
git remote set-url origin https://lunarfront-bot:${{ secrets.BOT_TOKEN }}@$GIT_REMOTE/ryan/lunarfront-app.git
|
||||
git add packages/backend/package.json
|
||||
git commit -m "chore: bump version to v${{ steps.version.outputs.version }}"
|
||||
git pull --rebase origin main
|
||||
git push origin main
|
||||
|
||||
- name: Logout
|
||||
if: always()
|
||||
run: docker logout registry.digitalocean.com
|
||||
|
||||
@@ -21,6 +21,10 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Generate route tree
|
||||
working-directory: packages/admin
|
||||
run: bunx @tanstack/router-cli generate
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
|
||||
112
CLAUDE.md
112
CLAUDE.md
@@ -63,3 +63,115 @@
|
||||
- API routes are thin — validate with Zod, call a service, return result
|
||||
- All financial events must be auditable (append-only audit records)
|
||||
- JSON structured logging with request IDs on every log line
|
||||
|
||||
---
|
||||
|
||||
## Infrastructure
|
||||
|
||||
### Overview
|
||||
LunarFront runs on DigitalOcean Kubernetes (DOKS). Each customer gets an isolated namespace, database, and Helm release managed by ArgoCD.
|
||||
|
||||
### Key Services
|
||||
- **Cluster:** `lunarfront` DOKS cluster, region NYC
|
||||
- **Registry:** `registry.digitalocean.com/lunarfront` (DOCR) — stores Docker images and Helm charts
|
||||
- **Git:** `git.lunarfront.tech` — self-hosted Gitea, source of truth for code and charts
|
||||
- **CI:** Gitea Actions — builds Docker images and Helm charts on push to `main`
|
||||
- **CD:** ArgoCD at `argocd.lunarfront.tech` — deploys from `lunarfront-charts` repo
|
||||
- **Database:** DO Managed PostgreSQL — one database per customer, plus manager DB
|
||||
- **Cache/Queue:** DO Managed Valkey — shared across all customers (key-prefixed per customer)
|
||||
- **Ingress:** nginx ingress controller with Cloudflare proxy in front
|
||||
- **TLS:** cert-manager with Let's Encrypt (letsencrypt-prod cluster issuer)
|
||||
- **DNS:** Cloudflare — wildcard `*.lunarfront.tech` → cluster LB IP `167.99.21.170`
|
||||
|
||||
### Node Pools
|
||||
- `system` — 2x s-2vcpu-4gb, runs ingress, ArgoCD, manager, pgbouncer
|
||||
- `customers` — autoscales 0→N, s-4vcpu-8gb, runs customer app pods (tainted `role=customer`)
|
||||
- `dev` — autoscales 0→1, s-4vcpu-8gb, runs dev pod only (tainted `dedicated=dev:NoSchedule`)
|
||||
|
||||
### Repos
|
||||
- `lunarfront-app` — main application code (this repo)
|
||||
- `lunarfront-charts` — Helm charts and ArgoCD app definitions
|
||||
- `lunarfront-infra` — Terraform for DO infrastructure (DOKS, managed DBs, registry, DNS)
|
||||
- `lunarfront-manager` — internal ops tool for provisioning/deprovisioning customers
|
||||
|
||||
---
|
||||
|
||||
## Build & Deploy Pipeline
|
||||
|
||||
### How it works
|
||||
1. Push code to `main` on `lunarfront-app`
|
||||
2. Gitea Actions runs `.gitea/workflows/build.yml`:
|
||||
- Builds `lunarfront-app` Docker image → pushes as `0.1.{run_number}`, `{sha}`, `latest`
|
||||
- Builds `lunarfront-frontend` Docker image → same tags
|
||||
- Packages Helm chart → pushes as `0.1.{run_number}` to DOCR OCI registry
|
||||
3. ArgoCD image updater detects new image digests → updates customer deployments
|
||||
4. New customer provisions always get the latest chart version (queried from DOCR at provision time)
|
||||
5. Existing customers upgraded via `POST /customers/:slug/upgrade` or `POST /customers/upgrade-all` in the manager
|
||||
|
||||
### Versioning
|
||||
- Version format: `0.1.{gitea_run_number}` — always incrementing, no git commit-back needed
|
||||
- No version stored in git — source of truth is DOCR tags
|
||||
- Chart version and app version are kept in sync
|
||||
|
||||
### Key files
|
||||
- `Dockerfile` — backend image (bun runtime, runs `packages/backend/src/main.ts` directly)
|
||||
- `Dockerfile.frontend` — frontend nginx image
|
||||
- `chart/` — Helm chart for customer app deployments
|
||||
- `.gitea/workflows/build.yml` — CI pipeline
|
||||
- `.gitea/workflows/build-devpod.yml` — builds dev box image on Dockerfile.devpod changes
|
||||
|
||||
---
|
||||
|
||||
## Dev Box
|
||||
|
||||
### What it is
|
||||
A persistent development pod running in the `dev` namespace on the cluster. Provides a full remote dev environment accessible from anywhere.
|
||||
|
||||
- **VS Code in browser:** `dev.lunarfront.tech` (Cloudflare Access protected, OTP to email)
|
||||
- **SSH:** `ssh -p 2222 root@dev-ssh.lunarfront.tech`
|
||||
- **Storage:** 100GB DO block storage PVC mounted at `/root` — everything in home dir persists
|
||||
- **Image:** `registry.digitalocean.com/lunarfront/manager:devpod-latest`
|
||||
- **Tools:** bun, Claude Code CLI, code-server, kubectl, helm, k9s, doctl, psql, redis-cli, git
|
||||
|
||||
### Managing the dev pod
|
||||
```bash
|
||||
# Scale up (provisions node automatically)
|
||||
kubectl scale deployment dev -n dev --replicas=1
|
||||
|
||||
# Scale down (node auto-terminates after ~15 min)
|
||||
kubectl scale deployment dev -n dev --replicas=0
|
||||
```
|
||||
|
||||
### Running the app locally on the dev box (no containers)
|
||||
The dev box runs the app as plain Bun processes, connecting to the same DO managed services as production.
|
||||
|
||||
**Required env vars** (create a `.env` file in the repo root or export in `.bashrc`):
|
||||
```bash
|
||||
DATABASE_URL=postgresql://... # DO managed postgres, lunarfront database
|
||||
REDIS_URL=rediss://... # DO managed valkey
|
||||
JWT_SECRET=... # any random hex string for local dev
|
||||
PORT=8000
|
||||
```
|
||||
|
||||
**Start the app:**
|
||||
```bash
|
||||
cd ~/lunarfront-app
|
||||
bun run dev
|
||||
```
|
||||
|
||||
Access the running backend at `dev.lunarfront.tech/proxy/8000/` in the browser (code-server proxy), or via SSH port forward:
|
||||
```bash
|
||||
ssh -p 2222 -L 8000:localhost:8000 root@dev-ssh.lunarfront.tech
|
||||
```
|
||||
|
||||
**Run migrations against the dev database:**
|
||||
```bash
|
||||
bunx drizzle-kit migrate
|
||||
```
|
||||
|
||||
### Workflow
|
||||
1. Edit code in VS Code at `dev.lunarfront.tech` or via SSH
|
||||
2. Run and test locally with `bun run dev` — app connects to DO managed postgres/valkey
|
||||
3. Push to `main` → Gitea Actions builds and pushes new Docker image + Helm chart
|
||||
4. ArgoCD deploys to the cluster automatically
|
||||
5. Use manager at `manager.lunarfront.tech` to upgrade customer instances if needed
|
||||
|
||||
14
Dockerfile
14
Dockerfile
@@ -6,8 +6,9 @@ COPY packages/backend/package.json packages/backend/
|
||||
COPY packages/admin/package.json packages/admin/
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
FROM oven/bun:1.3.11-alpine AS build
|
||||
FROM oven/bun:1.3.11-alpine
|
||||
ARG APP_VERSION=dev
|
||||
ENV APP_VERSION=${APP_VERSION}
|
||||
WORKDIR /app
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY --from=deps /app/packages/shared/node_modules ./packages/shared/node_modules
|
||||
@@ -16,18 +17,11 @@ COPY packages/shared ./packages/shared
|
||||
COPY packages/backend ./packages/backend
|
||||
COPY package.json ./
|
||||
COPY tsconfig.base.json ./
|
||||
WORKDIR /app/packages/backend
|
||||
RUN bun build src/main.ts --compile --outfile /app/server \
|
||||
--define "process.env.APP_VERSION='${APP_VERSION}'"
|
||||
|
||||
FROM alpine:3.21
|
||||
RUN addgroup -S app && adduser -S app -G app
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/server ./server
|
||||
COPY --from=build /app/packages/backend/src/db/migrations ./migrations
|
||||
COPY packages/backend/src/db/migrations ./migrations
|
||||
ENV MIGRATIONS_DIR=/app/migrations
|
||||
EXPOSE 8000
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD wget -qO- http://localhost:8000/v1/health || exit 1
|
||||
USER app
|
||||
CMD ["./server"]
|
||||
CMD ["bun", "run", "packages/backend/src/main.ts"]
|
||||
|
||||
47
Dockerfile.devpod
Normal file
47
Dockerfile.devpod
Normal file
@@ -0,0 +1,47 @@
|
||||
FROM ubuntu:24.04
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
ENV HOME=/root
|
||||
ENV PATH="/usr/local/bin:/root/.bun/bin:$PATH"
|
||||
|
||||
# Base tools
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
curl wget git openssh-server ca-certificates gnupg \
|
||||
build-essential unzip zip jq tmux zsh ripgrep \
|
||||
postgresql-client redis-tools haproxy tini \
|
||||
nano vim htop netcat-openbsd dnsutils iputils-ping lsof iproute2 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Bun — install then move to /usr/local/bin so it's on the image filesystem, not the /root PVC
|
||||
RUN curl -fsSL https://bun.sh/install | bash \
|
||||
&& mv /root/.bun/bin/bun /usr/local/bin/bun \
|
||||
&& ln -sf /usr/local/bin/bun /usr/local/bin/bunx \
|
||||
&& rm -rf /root/.bun
|
||||
|
||||
# code-server (VS Code in browser)
|
||||
RUN curl -fsSL https://code-server.dev/install.sh | sh
|
||||
|
||||
# kubectl
|
||||
RUN curl -fsSL "https://dl.k8s.io/release/$(curl -fsSL https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" \
|
||||
-o /usr/local/bin/kubectl && chmod +x /usr/local/bin/kubectl
|
||||
|
||||
# doctl
|
||||
RUN curl -fsSL https://github.com/digitalocean/doctl/releases/download/v1.119.0/doctl-1.119.0-linux-amd64.tar.gz \
|
||||
| tar xz -C /usr/local/bin
|
||||
|
||||
# helm
|
||||
RUN curl -fsSL https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
|
||||
|
||||
# k9s
|
||||
RUN curl -fsSL https://github.com/derailed/k9s/releases/latest/download/k9s_Linux_amd64.tar.gz \
|
||||
| tar xz -C /usr/local/bin k9s
|
||||
|
||||
# SSH setup — host keys generated at runtime via entrypoint
|
||||
RUN mkdir -p /run/sshd /root/.ssh && chmod 700 /root/.ssh
|
||||
|
||||
COPY entrypoint-devpod.sh /entrypoint.sh
|
||||
RUN chmod +x /entrypoint.sh
|
||||
|
||||
WORKDIR /root
|
||||
EXPOSE 8080 22
|
||||
ENTRYPOINT ["/usr/bin/tini", "--", "/entrypoint.sh"]
|
||||
@@ -16,6 +16,7 @@ COPY packages/admin ./packages/admin
|
||||
COPY package.json ./
|
||||
COPY tsconfig.base.json ./
|
||||
WORKDIR /app/packages/admin
|
||||
RUN bunx @tanstack/router-cli generate
|
||||
RUN bun run build
|
||||
|
||||
FROM nginx:alpine
|
||||
|
||||
8
bun.lock
8
bun.lock
@@ -34,6 +34,8 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"html2pdf.js": "^0.14.0",
|
||||
"jsbarcode": "^3.12.3",
|
||||
"jspdf": "^4.2.1",
|
||||
"lucide-react": "^1.7.0",
|
||||
"radix-ui": "^1.4.3",
|
||||
@@ -59,7 +61,7 @@
|
||||
},
|
||||
"packages/backend": {
|
||||
"name": "@lunarfront/backend",
|
||||
"version": "0.0.1",
|
||||
"version": "0.1.1",
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^10",
|
||||
"@fastify/jwt": "^9",
|
||||
@@ -806,6 +808,8 @@
|
||||
|
||||
"html2canvas": ["html2canvas@1.4.1", "", { "dependencies": { "css-line-break": "^2.1.0", "text-segmentation": "^1.0.3" } }, "sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA=="],
|
||||
|
||||
"html2pdf.js": ["html2pdf.js@0.14.0", "", { "dependencies": { "dompurify": "^3.3.1", "html2canvas": "^1.0.0", "jspdf": "^4.0.0" } }, "sha512-yvNJgE/8yru2UeGflkPdjW8YEY+nDH5X7/2WG4uiuSCwYiCp8PZ8EKNiTAa6HxJ1NjC51fZSIEq6xld5CADKBQ=="],
|
||||
|
||||
"ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="],
|
||||
|
||||
"import-fresh": ["import-fresh@3.3.1", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ=="],
|
||||
@@ -842,6 +846,8 @@
|
||||
|
||||
"js-yaml": ["js-yaml@4.1.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],
|
||||
|
||||
"jsbarcode": ["jsbarcode@3.12.3", "", {}, "sha512-CuHU9hC6dPsHF5oVFMo8NW76uQVjH4L22CsP4hW+dNnGywJHC/B0ThA1CTDVLnxKLrrpYdicBLnd2xsgTfRnvg=="],
|
||||
|
||||
"jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
|
||||
|
||||
"json-buffer": ["json-buffer@3.0.1", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="],
|
||||
|
||||
@@ -2,5 +2,5 @@ apiVersion: v2
|
||||
name: lunarfront
|
||||
description: LunarFront small business management platform
|
||||
type: application
|
||||
version: 0.1.0
|
||||
appVersion: "0.0.0"
|
||||
version: 0.1.1
|
||||
appVersion: "0.1.1"
|
||||
|
||||
@@ -38,11 +38,81 @@ spec:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: redis-url
|
||||
- name: REDIS_KEY_PREFIX
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: redis-key-prefix
|
||||
- name: SPACES_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: spaces-key
|
||||
- name: SPACES_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: spaces-secret
|
||||
- name: SPACES_BUCKET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: spaces-bucket
|
||||
- name: SPACES_ENDPOINT
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: spaces-endpoint
|
||||
- name: SPACES_PREFIX
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: spaces-prefix
|
||||
- name: JWT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: jwt-secret
|
||||
- name: ENCRYPTION_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: encryption-key
|
||||
- name: RESEND_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: resend-api-key
|
||||
- name: MAIL_FROM
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: mail-from
|
||||
- name: BUSINESS_NAME
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: business-name
|
||||
- name: APP_URL
|
||||
value: "https://{{ .Values.ingress.host }}"
|
||||
- name: INITIAL_USER_EMAIL
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: initial-user-email
|
||||
optional: true
|
||||
- name: INITIAL_USER_FIRST_NAME
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: initial-user-first-name
|
||||
optional: true
|
||||
- name: INITIAL_USER_LAST_NAME
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: lunarfront-secrets
|
||||
key: initial-user-last-name
|
||||
optional: true
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /v1/health
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-valkey
|
||||
namespace: {{ .Release.Namespace }}
|
||||
labels:
|
||||
{{- include "lunarfront.labels" . | nindent 4 }}
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: {{ .Release.Name }}-valkey
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: {{ .Release.Name }}-valkey
|
||||
spec:
|
||||
containers:
|
||||
- name: valkey
|
||||
image: "{{ .Values.valkey.image.repository }}:{{ .Values.valkey.image.tag }}"
|
||||
ports:
|
||||
- containerPort: {{ .Values.valkey.port }}
|
||||
resources:
|
||||
{{- toYaml .Values.valkey.resources | nindent 12 }}
|
||||
@@ -1,13 +0,0 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-valkey
|
||||
namespace: {{ .Release.Namespace }}
|
||||
labels:
|
||||
{{- include "lunarfront.labels" . | nindent 4 }}
|
||||
spec:
|
||||
selector:
|
||||
app: {{ .Release.Name }}-valkey
|
||||
ports:
|
||||
- port: {{ .Values.valkey.port }}
|
||||
targetPort: {{ .Values.valkey.port }}
|
||||
@@ -1,7 +1,7 @@
|
||||
backend:
|
||||
image:
|
||||
repository: registry.digitalocean.com/lunarfront/lunarfront-app
|
||||
tag: latest
|
||||
tag: 0.0.27
|
||||
pullPolicy: Always
|
||||
port: 8000
|
||||
resources:
|
||||
@@ -15,7 +15,7 @@ backend:
|
||||
frontend:
|
||||
image:
|
||||
repository: registry.digitalocean.com/lunarfront/lunarfront-frontend
|
||||
tag: latest
|
||||
tag: 0.0.27
|
||||
pullPolicy: Always
|
||||
port: 80
|
||||
resources:
|
||||
@@ -26,19 +26,6 @@ frontend:
|
||||
cpu: 200m
|
||||
memory: 128Mi
|
||||
|
||||
valkey:
|
||||
image:
|
||||
repository: valkey/valkey
|
||||
tag: "8"
|
||||
port: 6379
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
cpu: 200m
|
||||
memory: 128Mi
|
||||
|
||||
ingress:
|
||||
host: ""
|
||||
className: nginx
|
||||
|
||||
82
entrypoint-devpod.sh
Normal file
82
entrypoint-devpod.sh
Normal file
@@ -0,0 +1,82 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Generate SSH host keys if not present
|
||||
ssh-keygen -A
|
||||
|
||||
# Write authorized keys from env if provided
|
||||
if [ -n "$SSH_AUTHORIZED_KEYS" ]; then
|
||||
mkdir -p /root/.ssh
|
||||
chmod 700 /root/.ssh
|
||||
echo "$SSH_AUTHORIZED_KEYS" > /root/.ssh/authorized_keys
|
||||
chmod 600 /root/.ssh/authorized_keys
|
||||
fi
|
||||
|
||||
# Bootstrap home dir on fresh PVC
|
||||
if [ ! -f /root/.bashrc ]; then
|
||||
cp /etc/skel/.bashrc /root/.bashrc 2>/dev/null || true
|
||||
cat >> /root/.bashrc <<'EOF'
|
||||
export PATH="/usr/local/bin:$PATH"
|
||||
export HISTFILE=/root/.bash_history
|
||||
export HISTSIZE=10000
|
||||
EOF
|
||||
fi
|
||||
|
||||
if [ ! -f /root/.profile ]; then
|
||||
cat > /root/.profile <<'EOF'
|
||||
export PATH="/usr/local/bin:$PATH"
|
||||
[ -f /root/.bashrc ] && . /root/.bashrc
|
||||
EOF
|
||||
fi
|
||||
|
||||
if [ ! -f /root/.gitconfig ]; then
|
||||
cat > /root/.gitconfig <<'EOF'
|
||||
[user]
|
||||
name = ryan
|
||||
email = ryan@lunartech.com
|
||||
[init]
|
||||
defaultBranch = main
|
||||
[core]
|
||||
editor = code --wait
|
||||
EOF
|
||||
fi
|
||||
|
||||
# Install Claude Code on first boot (installs to /root/.claude, persists on PVC)
|
||||
if [ ! -f /root/.claude/bin/claude ]; then
|
||||
curl -fsSL https://claude.ai/install.sh | bash
|
||||
fi
|
||||
|
||||
# Allow root login via SSH key, listen on internal port 2222
|
||||
echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
|
||||
echo "Port 2222" >> /etc/ssh/sshd_config
|
||||
|
||||
# Start SSH daemon on internal port 2222
|
||||
/usr/sbin/sshd
|
||||
|
||||
# Start haproxy on port 22 to accept PROXY protocol from nginx and forward to sshd:2222
|
||||
cat > /etc/haproxy/haproxy.cfg <<'EOF'
|
||||
global
|
||||
daemon
|
||||
maxconn 256
|
||||
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 5s
|
||||
timeout client 60s
|
||||
timeout server 60s
|
||||
|
||||
frontend ssh
|
||||
bind *:22 accept-proxy
|
||||
default_backend sshd
|
||||
|
||||
backend sshd
|
||||
server local 127.0.0.1:2222
|
||||
EOF
|
||||
haproxy -f /etc/haproxy/haproxy.cfg
|
||||
|
||||
# Start code-server
|
||||
exec code-server \
|
||||
--bind-addr 0.0.0.0:8080 \
|
||||
--auth none \
|
||||
--disable-telemetry \
|
||||
/root
|
||||
@@ -25,6 +25,8 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"html2pdf.js": "^0.14.0",
|
||||
"jsbarcode": "^3.12.3",
|
||||
"jspdf": "^4.2.1",
|
||||
"lucide-react": "^1.7.0",
|
||||
"radix-ui": "^1.4.3",
|
||||
|
||||
@@ -14,3 +14,11 @@ interface LoginResponse {
|
||||
export async function login(email: string, password: string): Promise<LoginResponse> {
|
||||
return api.post<LoginResponse>('/v1/auth/login', { email, password })
|
||||
}
|
||||
|
||||
export async function forgotPassword(email: string): Promise<{ message: string }> {
|
||||
return api.post<{ message: string }>('/v1/auth/forgot-password', { email })
|
||||
}
|
||||
|
||||
export async function resetPassword(token: string, newPassword: string): Promise<{ message: string }> {
|
||||
return api.post<{ message: string }>('/v1/auth/reset-password', { token, newPassword })
|
||||
}
|
||||
|
||||
225
packages/admin/src/api/pos.ts
Normal file
225
packages/admin/src/api/pos.ts
Normal file
@@ -0,0 +1,225 @@
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
|
||||
// --- Types ---
|
||||
|
||||
export interface Transaction {
|
||||
id: string
|
||||
locationId: string | null
|
||||
transactionNumber: string
|
||||
accountId: string | null
|
||||
repairTicketId: string | null
|
||||
repairBatchId: string | null
|
||||
transactionType: string
|
||||
status: string
|
||||
subtotal: string
|
||||
discountTotal: string
|
||||
taxTotal: string
|
||||
total: string
|
||||
paymentMethod: string | null
|
||||
amountTendered: string | null
|
||||
changeGiven: string | null
|
||||
checkNumber: string | null
|
||||
roundingAdjustment: string
|
||||
taxExempt: boolean
|
||||
taxExemptReason: string | null
|
||||
processedBy: string
|
||||
drawerSessionId: string | null
|
||||
notes: string | null
|
||||
completedAt: string | null
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
lineItems?: TransactionLineItem[]
|
||||
}
|
||||
|
||||
export interface TransactionLineItem {
|
||||
id: string
|
||||
transactionId: string
|
||||
productId: string | null
|
||||
inventoryUnitId: string | null
|
||||
description: string
|
||||
qty: number
|
||||
unitPrice: string
|
||||
discountAmount: string
|
||||
discountReason: string | null
|
||||
taxRate: string
|
||||
taxAmount: string
|
||||
lineTotal: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface DrawerSession {
|
||||
id: string
|
||||
locationId: string | null
|
||||
openedBy: string
|
||||
closedBy: string | null
|
||||
openingBalance: string
|
||||
closingBalance: string | null
|
||||
expectedBalance: string | null
|
||||
overShort: string | null
|
||||
denominations: Record<string, number> | null
|
||||
status: string
|
||||
notes: string | null
|
||||
openedAt: string
|
||||
closedAt: string | null
|
||||
}
|
||||
|
||||
export interface Discount {
|
||||
id: string
|
||||
name: string
|
||||
discountType: string
|
||||
discountValue: string
|
||||
appliesTo: string
|
||||
requiresApprovalAbove: string | null
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
export interface Product {
|
||||
id: string
|
||||
name: string
|
||||
sku: string | null
|
||||
upc: string | null
|
||||
description: string | null
|
||||
price: string | null
|
||||
costPrice: string | null
|
||||
qtyOnHand: number | null
|
||||
taxCategory: string
|
||||
isSerialized: boolean
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
export interface Register {
|
||||
id: string
|
||||
locationId: string
|
||||
name: string
|
||||
isActive: boolean
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
// --- Query Keys ---
|
||||
|
||||
export interface DrawerAdjustment {
|
||||
id: string
|
||||
drawerSessionId: string
|
||||
type: string
|
||||
amount: string
|
||||
reason: string
|
||||
createdBy: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export const posKeys = {
|
||||
transaction: (id: string) => ['pos', 'transaction', id] as const,
|
||||
drawer: (locationId: string) => ['pos', 'drawer', locationId] as const,
|
||||
drawerAdjustments: (id: string) => ['pos', 'drawer-adjustments', id] as const,
|
||||
drawerReport: (id: string) => ['pos', 'drawer-report', id] as const,
|
||||
dailyReport: (locationId: string, date: string) => ['pos', 'daily-report', locationId, date] as const,
|
||||
registers: (locationId: string) => ['pos', 'registers', locationId] as const,
|
||||
products: (search: string) => ['pos', 'products', search] as const,
|
||||
discounts: ['pos', 'discounts'] as const,
|
||||
}
|
||||
|
||||
// --- Query Options ---
|
||||
|
||||
export function transactionOptions(id: string | null) {
|
||||
return queryOptions({
|
||||
queryKey: posKeys.transaction(id ?? ''),
|
||||
queryFn: () => api.get<Transaction>(`/v1/transactions/${id}`),
|
||||
enabled: !!id,
|
||||
})
|
||||
}
|
||||
|
||||
export function currentDrawerOptions(locationId: string | null) {
|
||||
return queryOptions({
|
||||
queryKey: posKeys.drawer(locationId ?? ''),
|
||||
queryFn: async (): Promise<DrawerSession | null> => {
|
||||
try {
|
||||
return await api.get<DrawerSession>('/v1/drawer/current', { locationId })
|
||||
} catch {
|
||||
return null // 404 = no open drawer
|
||||
}
|
||||
},
|
||||
enabled: !!locationId,
|
||||
retry: false,
|
||||
})
|
||||
}
|
||||
|
||||
export function productSearchOptions(search: string) {
|
||||
return queryOptions({
|
||||
queryKey: posKeys.products(search),
|
||||
queryFn: () => api.get<{ data: Product[]; pagination: { page: number; limit: number; total: number; totalPages: number } }>('/v1/products', { q: search, limit: 24, isActive: true, isConsumable: false }),
|
||||
enabled: search.length >= 1,
|
||||
})
|
||||
}
|
||||
|
||||
export function discountListOptions() {
|
||||
return queryOptions({
|
||||
queryKey: posKeys.discounts,
|
||||
queryFn: () => api.get<Discount[]>('/v1/discounts/all'),
|
||||
})
|
||||
}
|
||||
|
||||
export function registerListOptions(locationId: string | null) {
|
||||
return queryOptions({
|
||||
queryKey: posKeys.registers(locationId ?? ''),
|
||||
queryFn: () => api.get<{ data: Register[] }>('/v1/registers/all', { locationId }),
|
||||
enabled: !!locationId,
|
||||
})
|
||||
}
|
||||
|
||||
export function drawerReportOptions(drawerSessionId: string | null) {
|
||||
return queryOptions({
|
||||
queryKey: posKeys.drawerReport(drawerSessionId ?? ''),
|
||||
queryFn: () => api.get<any>(`/v1/reports/drawer/${drawerSessionId}`),
|
||||
enabled: !!drawerSessionId,
|
||||
})
|
||||
}
|
||||
|
||||
export function dailyReportOptions(locationId: string | null, date: string) {
|
||||
return queryOptions({
|
||||
queryKey: posKeys.dailyReport(locationId ?? '', date),
|
||||
queryFn: () => api.get<any>('/v1/reports/daily', { locationId, date }),
|
||||
enabled: !!locationId && !!date,
|
||||
})
|
||||
}
|
||||
|
||||
// --- Mutations ---
|
||||
|
||||
export const posMutations = {
|
||||
createTransaction: (data: { transactionType: string; locationId?: string; accountId?: string }) =>
|
||||
api.post<Transaction>('/v1/transactions', data),
|
||||
|
||||
addLineItem: (txnId: string, data: { productId?: string; inventoryUnitId?: string; description: string; qty: number; unitPrice: number }) =>
|
||||
api.post<TransactionLineItem>(`/v1/transactions/${txnId}/line-items`, data),
|
||||
|
||||
removeLineItem: (txnId: string, lineItemId: string) =>
|
||||
api.del<TransactionLineItem>(`/v1/transactions/${txnId}/line-items/${lineItemId}`),
|
||||
|
||||
applyDiscount: (txnId: string, data: { discountId?: string; amount: number; reason: string; lineItemId?: string }) =>
|
||||
api.post<Transaction>(`/v1/transactions/${txnId}/discounts`, data),
|
||||
|
||||
complete: (txnId: string, data: { paymentMethod: string; amountTendered?: number; checkNumber?: string }) =>
|
||||
api.post<Transaction>(`/v1/transactions/${txnId}/complete`, data),
|
||||
|
||||
void: (txnId: string) =>
|
||||
api.post<Transaction>(`/v1/transactions/${txnId}/void`, {}),
|
||||
|
||||
openDrawer: (data: { locationId?: string; registerId?: string; openingBalance: number }) =>
|
||||
api.post<DrawerSession>('/v1/drawer/open', data),
|
||||
|
||||
closeDrawer: (id: string, data: { closingBalance: number; denominations?: Record<string, number>; notes?: string }) =>
|
||||
api.post<DrawerSession>(`/v1/drawer/${id}/close`, data),
|
||||
|
||||
lookupUpc: (upc: string) =>
|
||||
api.get<Product>(`/v1/products/lookup/upc/${upc}`),
|
||||
|
||||
addAdjustment: (drawerId: string, data: { type: string; amount: number; reason: string }) =>
|
||||
api.post<DrawerAdjustment>(`/v1/drawer/${drawerId}/adjustments`, data),
|
||||
|
||||
getAdjustments: (drawerId: string) =>
|
||||
api.get<{ data: DrawerAdjustment[] }>(`/v1/drawer/${drawerId}/adjustments`),
|
||||
|
||||
createFromRepair: (ticketId: string, locationId?: string) =>
|
||||
api.post<Transaction>(`/v1/transactions/from-repair/${ticketId}`, { locationId }),
|
||||
}
|
||||
@@ -34,6 +34,7 @@ export function ProductForm({ defaultValues, onSubmit, loading }: Props) {
|
||||
isSerialized: defaultValues?.isSerialized ?? false,
|
||||
isRental: defaultValues?.isRental ?? false,
|
||||
isDualUseRepair: defaultValues?.isDualUseRepair ?? false,
|
||||
isConsumable: defaultValues?.isConsumable ?? false,
|
||||
isActive: defaultValues?.isActive ?? true,
|
||||
},
|
||||
})
|
||||
@@ -42,6 +43,7 @@ export function ProductForm({ defaultValues, onSubmit, loading }: Props) {
|
||||
const isRental = watch('isRental')
|
||||
const isSerialized = watch('isSerialized')
|
||||
const isDualUseRepair = watch('isDualUseRepair')
|
||||
const isConsumable = watch('isConsumable')
|
||||
const isActive = watch('isActive')
|
||||
|
||||
function handleFormSubmit(data: Record<string, unknown>) {
|
||||
@@ -61,6 +63,7 @@ export function ProductForm({ defaultValues, onSubmit, loading }: Props) {
|
||||
isSerialized: data.isSerialized,
|
||||
isRental: data.isRental,
|
||||
isDualUseRepair: data.isDualUseRepair,
|
||||
isConsumable: data.isConsumable,
|
||||
isActive: data.isActive,
|
||||
})
|
||||
}
|
||||
@@ -158,6 +161,10 @@ export function ProductForm({ defaultValues, onSubmit, loading }: Props) {
|
||||
<input type="checkbox" checked={isDualUseRepair} onChange={(e) => setValue('isDualUseRepair', e.target.checked)} className="h-4 w-4" />
|
||||
Available as Repair Line Item
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
||||
<input type="checkbox" checked={isConsumable} onChange={(e) => setValue('isConsumable', e.target.checked)} className="h-4 w-4" />
|
||||
Consumable (internal use, not sold at POS)
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
||||
<input type="checkbox" checked={isActive} onChange={(e) => setValue('isActive', e.target.checked)} className="h-4 w-4" />
|
||||
Active
|
||||
|
||||
522
packages/admin/src/components/pos/pos-cart-panel.tsx
Normal file
522
packages/admin/src/components/pos/pos-cart-panel.tsx
Normal file
@@ -0,0 +1,522 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { usePOSStore } from '@/stores/pos.store'
|
||||
import { posMutations, posKeys, type Transaction } from '@/api/pos'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { X, Banknote, CreditCard, FileText, Ban, UserRound, Tag } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { useState } from 'react'
|
||||
import { POSPaymentDialog } from './pos-payment-dialog'
|
||||
import { POSCustomerDialog } from './pos-customer-dialog'
|
||||
import { ManagerOverrideDialog, requiresOverride, requiresDiscountOverride } from './pos-manager-override'
|
||||
import type { TransactionLineItem } from '@/api/pos'
|
||||
|
||||
interface POSCartPanelProps {
|
||||
transaction: Transaction | null
|
||||
}
|
||||
|
||||
export function POSCartPanel({ transaction }: POSCartPanelProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const { currentTransactionId, setTransaction, accountName, accountPhone, accountEmail } = usePOSStore()
|
||||
const [paymentMethod, setPaymentMethod] = useState<string | null>(null)
|
||||
const [customerOpen, setCustomerOpen] = useState(false)
|
||||
const [overrideOpen, setOverrideOpen] = useState(false)
|
||||
const [priceItemId, setPriceItemId] = useState<string | null>(null)
|
||||
const [pendingDiscount, setPendingDiscount] = useState<{ lineItemId: string; amount: number; reason: string } | null>(null)
|
||||
const [pendingOrderDiscount, setPendingOrderDiscount] = useState<{ amount: number; reason: string } | null>(null)
|
||||
const [discountOverrideOpen, setDiscountOverrideOpen] = useState(false)
|
||||
const lineItems = transaction?.lineItems ?? []
|
||||
|
||||
const drawerSessionId = usePOSStore((s) => s.drawerSessionId)
|
||||
const drawerOpen = !!drawerSessionId
|
||||
|
||||
const removeItemMutation = useMutation({
|
||||
mutationFn: (lineItemId: string) =>
|
||||
posMutations.removeLineItem(currentTransactionId!, lineItemId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: posKeys.transaction(currentTransactionId!) })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const discountMutation = useMutation({
|
||||
mutationFn: (data: { lineItemId: string; amount: number; reason: string }) =>
|
||||
posMutations.applyDiscount(currentTransactionId!, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: posKeys.transaction(currentTransactionId!) })
|
||||
setPriceItemId(null)
|
||||
toast.success('Price adjusted')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const orderDiscountMutation = useMutation({
|
||||
mutationFn: async ({ amount, reason }: { amount: number; reason: string }) => {
|
||||
// Distribute discount proportionally across all line items
|
||||
let remaining = amount
|
||||
for (let i = 0; i < lineItems.length; i++) {
|
||||
const item = lineItems[i]
|
||||
const itemTotal = parseFloat(item.unitPrice) * item.qty
|
||||
const isLast = i === lineItems.length - 1
|
||||
const share = isLast ? remaining : Math.round((itemTotal / subtotal) * amount * 100) / 100
|
||||
remaining -= share
|
||||
if (share > 0) {
|
||||
await posMutations.applyDiscount(currentTransactionId!, { lineItemId: item.id, amount: share, reason })
|
||||
}
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: posKeys.transaction(currentTransactionId!) })
|
||||
toast.success('Order discount applied')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const voidMutation = useMutation({
|
||||
mutationFn: () => posMutations.void(currentTransactionId!),
|
||||
onSuccess: () => {
|
||||
setTransaction(null)
|
||||
toast.success('Transaction voided')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const subtotal = parseFloat(transaction?.subtotal ?? '0')
|
||||
const discountTotal = parseFloat(transaction?.discountTotal ?? '0')
|
||||
const taxTotal = parseFloat(transaction?.taxTotal ?? '0')
|
||||
const total = parseFloat(transaction?.total ?? '0')
|
||||
const hasItems = lineItems.length > 0
|
||||
const isPending = transaction?.status === 'pending'
|
||||
|
||||
function handlePaymentComplete() {
|
||||
setPaymentMethod(null)
|
||||
setTransaction(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full bg-card">
|
||||
{/* Header */}
|
||||
<div className="p-3 border-b border-border">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="font-semibold text-base">Current Sale</h2>
|
||||
{transaction && (
|
||||
<span className="text-xs text-muted-foreground font-mono">
|
||||
{transaction.transactionNumber}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setCustomerOpen(true)}
|
||||
className="flex items-start gap-1.5 mt-1 text-xs text-muted-foreground hover:text-foreground text-left"
|
||||
>
|
||||
<UserRound className="h-3 w-3 mt-0.5 shrink-0" />
|
||||
{accountName ? (
|
||||
<span>
|
||||
<span className="font-medium text-foreground">{accountName}</span>
|
||||
{(accountPhone || accountEmail) && (
|
||||
<span className="block text-[11px]">
|
||||
{[accountPhone, accountEmail].filter(Boolean).join(' · ')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
<span>Walk-in — tap to add customer</span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Line items */}
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{lineItems.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-full text-muted-foreground text-sm">
|
||||
No items yet
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-border">
|
||||
{lineItems.map((item) => {
|
||||
const unitPrice = parseFloat(item.unitPrice)
|
||||
const discount = parseFloat(item.discountAmount)
|
||||
const hasDiscount = discount > 0
|
||||
const listTotal = unitPrice * item.qty
|
||||
const discountPct = listTotal > 0 ? Math.round((discount / listTotal) * 100) : 0
|
||||
|
||||
return (
|
||||
<div key={item.id} className="flex items-center gap-2 px-3 py-2.5 group">
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{item.description}</p>
|
||||
<div className="text-xs text-muted-foreground flex items-center gap-2">
|
||||
<span>{item.qty} x ${unitPrice.toFixed(2)}</span>
|
||||
{hasDiscount && (
|
||||
<span className="text-green-600">-${discount.toFixed(2)} ({discountPct}%)</span>
|
||||
)}
|
||||
{parseFloat(item.taxAmount) > 0 && (
|
||||
<span>tax ${parseFloat(item.taxAmount).toFixed(2)}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<span className="text-sm font-medium tabular-nums">
|
||||
${parseFloat(item.lineTotal).toFixed(2)}
|
||||
</span>
|
||||
{isPending && (
|
||||
<div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 shrink-0">
|
||||
<PriceAdjuster
|
||||
item={item}
|
||||
open={priceItemId === item.id}
|
||||
onOpenChange={(o) => setPriceItemId(o ? item.id : null)}
|
||||
onApply={(amount, reason) => {
|
||||
const pct = listTotal > 0 ? (amount / listTotal) * 100 : 0
|
||||
if (requiresDiscountOverride(pct)) {
|
||||
setPendingDiscount({ lineItemId: item.id, amount, reason })
|
||||
setDiscountOverrideOpen(true)
|
||||
} else {
|
||||
discountMutation.mutate({ lineItemId: item.id, amount, reason })
|
||||
}
|
||||
}}
|
||||
isPending={discountMutation.isPending}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => removeItemMutation.mutate(item.id)}
|
||||
disabled={removeItemMutation.isPending}
|
||||
>
|
||||
<X className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Totals + payment */}
|
||||
<div className="shrink-0 border-t border-border">
|
||||
<div className="px-3 py-2 space-y-1 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Subtotal</span>
|
||||
<span className="tabular-nums">${subtotal.toFixed(2)}</span>
|
||||
</div>
|
||||
{discountTotal > 0 && (
|
||||
<div className="flex justify-between text-green-600">
|
||||
<span>Discount</span>
|
||||
<span className="tabular-nums">-${discountTotal.toFixed(2)}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Tax</span>
|
||||
<span className="tabular-nums">${taxTotal.toFixed(2)}</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between text-lg font-bold pt-1">
|
||||
<span>Total</span>
|
||||
<span className="tabular-nums">${total.toFixed(2)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Order discount button */}
|
||||
{hasItems && isPending && (
|
||||
<div className="px-3 pb-1">
|
||||
<OrderDiscountButton
|
||||
subtotal={subtotal}
|
||||
onApply={(amount, reason) => {
|
||||
const pct = subtotal > 0 ? (amount / subtotal) * 100 : 0
|
||||
if (requiresDiscountOverride(pct)) {
|
||||
setPendingOrderDiscount({ amount, reason })
|
||||
setDiscountOverrideOpen(true)
|
||||
} else {
|
||||
orderDiscountMutation.mutate({ amount, reason })
|
||||
}
|
||||
}}
|
||||
isPending={orderDiscountMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Payment buttons */}
|
||||
<div className="p-3 space-y-2">
|
||||
{!drawerOpen && hasItems && (
|
||||
<p className="text-xs text-destructive text-center">Open the drawer before accepting payment</p>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Button
|
||||
className="h-12 text-sm gap-2"
|
||||
disabled={!hasItems || !isPending || !drawerOpen}
|
||||
onClick={() => setPaymentMethod('cash')}
|
||||
>
|
||||
<Banknote className="h-4 w-4" />
|
||||
Cash
|
||||
</Button>
|
||||
<Button
|
||||
className="h-12 text-sm gap-2"
|
||||
disabled={!hasItems || !isPending || !drawerOpen}
|
||||
onClick={() => setPaymentMethod('card_present')}
|
||||
>
|
||||
<CreditCard className="h-4 w-4" />
|
||||
Card
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-12 text-sm gap-2"
|
||||
disabled={!hasItems || !isPending || !drawerOpen}
|
||||
onClick={() => setPaymentMethod('check')}
|
||||
>
|
||||
<FileText className="h-4 w-4" />
|
||||
Check
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
className="h-12 text-sm gap-2"
|
||||
disabled={!hasItems || !isPending}
|
||||
onClick={() => {
|
||||
if (requiresOverride('void_transaction')) {
|
||||
setOverrideOpen(true)
|
||||
} else {
|
||||
voidMutation.mutate()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Ban className="h-4 w-4" />
|
||||
Void
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment dialog */}
|
||||
{paymentMethod && transaction && (
|
||||
<POSPaymentDialog
|
||||
open={!!paymentMethod}
|
||||
onOpenChange={(open) => { if (!open) setPaymentMethod(null) }}
|
||||
paymentMethod={paymentMethod}
|
||||
transaction={transaction}
|
||||
onComplete={handlePaymentComplete}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Customer dialog */}
|
||||
<POSCustomerDialog open={customerOpen} onOpenChange={setCustomerOpen} />
|
||||
|
||||
{/* Manager override for void */}
|
||||
<ManagerOverrideDialog
|
||||
open={overrideOpen}
|
||||
onOpenChange={setOverrideOpen}
|
||||
action="Void transaction"
|
||||
onAuthorized={() => voidMutation.mutate()}
|
||||
/>
|
||||
|
||||
{/* Manager override for discount */}
|
||||
<ManagerOverrideDialog
|
||||
open={discountOverrideOpen}
|
||||
onOpenChange={setDiscountOverrideOpen}
|
||||
action="Price adjustment"
|
||||
onAuthorized={() => {
|
||||
if (pendingDiscount) {
|
||||
discountMutation.mutate(pendingDiscount)
|
||||
setPendingDiscount(null)
|
||||
} else if (pendingOrderDiscount) {
|
||||
orderDiscountMutation.mutate(pendingOrderDiscount)
|
||||
setPendingOrderDiscount(null)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// --- Order Discount Button ---
|
||||
|
||||
function OrderDiscountButton({ subtotal, onApply, isPending }: {
|
||||
subtotal: number
|
||||
onApply: (amount: number, reason: string) => void
|
||||
isPending: boolean
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [mode, setMode] = useState<AdjustMode>('percent')
|
||||
const [value, setValue] = useState('')
|
||||
|
||||
function calculate() {
|
||||
const v = parseFloat(value) || 0
|
||||
if (mode === 'amount_off') return Math.min(v, subtotal)
|
||||
if (mode === 'set_price') return Math.max(0, subtotal - v)
|
||||
return Math.round(subtotal * (v / 100) * 100) / 100
|
||||
}
|
||||
|
||||
const discountAmount = calculate()
|
||||
|
||||
function handleApply() {
|
||||
if (discountAmount <= 0) return
|
||||
const reason = mode === 'percent' ? `${parseFloat(value)}% order discount` : mode === 'set_price' ? `Order total set to $${parseFloat(value).toFixed(2)}` : `$${parseFloat(value).toFixed(2)} order discount`
|
||||
onApply(discountAmount, reason)
|
||||
setValue('')
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={(o) => { setOpen(o); if (!o) setValue('') }}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="w-full gap-2 text-xs h-8">
|
||||
<Tag className="h-3 w-3" />Order Discount
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-64 p-3" side="top" align="center">
|
||||
<div className="space-y-3">
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Subtotal: <span className="font-medium text-foreground">${subtotal.toFixed(2)}</span>
|
||||
</div>
|
||||
<div className="flex rounded-md border overflow-hidden text-xs">
|
||||
{([
|
||||
{ key: 'percent' as const, label: '% Off' },
|
||||
{ key: 'amount_off' as const, label: '$ Off' },
|
||||
{ key: 'set_price' as const, label: 'Set Total' },
|
||||
]).map((m) => (
|
||||
<button
|
||||
key={m.key}
|
||||
type="button"
|
||||
className={`flex-1 py-1.5 transition-colors ${mode === m.key ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'}`}
|
||||
onClick={() => { setMode(m.key); setValue('') }}
|
||||
>
|
||||
{m.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
placeholder={mode === 'percent' ? 'e.g. 10' : '0.00'}
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
className="h-9"
|
||||
autoFocus
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') handleApply() }}
|
||||
/>
|
||||
{value && discountAmount > 0 && (
|
||||
<div className="text-xs flex justify-between font-medium">
|
||||
<span className="text-green-600">-${discountAmount.toFixed(2)}</span>
|
||||
<span>New total: ${(subtotal - discountAmount).toFixed(2)}</span>
|
||||
</div>
|
||||
)}
|
||||
<Button size="sm" className="w-full" onClick={handleApply} disabled={isPending || discountAmount <= 0}>
|
||||
{isPending ? 'Applying...' : 'Apply Discount'}
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
// --- Price Adjuster Popover ---
|
||||
|
||||
type AdjustMode = 'amount_off' | 'set_price' | 'percent'
|
||||
|
||||
function PriceAdjuster({ item, open, onOpenChange, onApply, isPending }: {
|
||||
item: TransactionLineItem
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onApply: (amount: number, reason: string) => void
|
||||
isPending: boolean
|
||||
}) {
|
||||
const [mode, setMode] = useState<AdjustMode>('percent')
|
||||
const [value, setValue] = useState('')
|
||||
|
||||
const unitPrice = parseFloat(item.unitPrice)
|
||||
const listTotal = unitPrice * item.qty
|
||||
|
||||
function calculate(): { discountAmount: number; salePrice: number; pct: number } {
|
||||
const v = parseFloat(value) || 0
|
||||
if (mode === 'amount_off') {
|
||||
const d = Math.min(v, listTotal)
|
||||
return { discountAmount: d, salePrice: listTotal - d, pct: listTotal > 0 ? (d / listTotal) * 100 : 0 }
|
||||
}
|
||||
if (mode === 'set_price') {
|
||||
const d = Math.max(0, listTotal - v)
|
||||
return { discountAmount: d, salePrice: v, pct: listTotal > 0 ? (d / listTotal) * 100 : 0 }
|
||||
}
|
||||
// percent
|
||||
const d = Math.round(listTotal * (v / 100) * 100) / 100
|
||||
return { discountAmount: d, salePrice: listTotal - d, pct: v }
|
||||
}
|
||||
|
||||
const calc = calculate()
|
||||
|
||||
function handleApply() {
|
||||
if (calc.discountAmount <= 0) return
|
||||
const reason = mode === 'percent' ? `${parseFloat(value)}% off` : mode === 'set_price' ? `Price set to $${parseFloat(value).toFixed(2)}` : `$${parseFloat(value).toFixed(2)} off`
|
||||
onApply(calc.discountAmount, reason)
|
||||
setValue('')
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={(o) => { onOpenChange(o); if (!o) setValue('') }}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<Tag className="h-4 w-4" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-64 p-3" side="left" align="start">
|
||||
<div className="space-y-3">
|
||||
<div className="text-xs text-muted-foreground">
|
||||
List: <span className="font-medium text-foreground">${listTotal.toFixed(2)}</span>
|
||||
</div>
|
||||
|
||||
{/* Mode tabs */}
|
||||
<div className="flex rounded-md border overflow-hidden text-xs">
|
||||
{([
|
||||
{ key: 'percent' as const, label: '% Off' },
|
||||
{ key: 'amount_off' as const, label: '$ Off' },
|
||||
{ key: 'set_price' as const, label: 'Set Price' },
|
||||
]).map((m) => (
|
||||
<button
|
||||
key={m.key}
|
||||
type="button"
|
||||
className={`flex-1 py-1.5 transition-colors ${mode === m.key ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'}`}
|
||||
onClick={() => { setMode(m.key); setValue('') }}
|
||||
>
|
||||
{m.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
placeholder={mode === 'percent' ? 'e.g. 10' : '0.00'}
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
className="h-9"
|
||||
autoFocus
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') handleApply() }}
|
||||
/>
|
||||
|
||||
{value && parseFloat(value) > 0 && (
|
||||
<div className="text-xs space-y-0.5">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Discount</span>
|
||||
<span className="text-green-600">-${calc.discountAmount.toFixed(2)} ({calc.pct.toFixed(0)}%)</span>
|
||||
</div>
|
||||
<div className="flex justify-between font-medium">
|
||||
<span>Sale Price</span>
|
||||
<span>${calc.salePrice.toFixed(2)}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={handleApply}
|
||||
disabled={isPending || !value || calc.discountAmount <= 0}
|
||||
>
|
||||
{isPending ? 'Applying...' : 'Apply'}
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
254
packages/admin/src/components/pos/pos-customer-dialog.tsx
Normal file
254
packages/admin/src/components/pos/pos-customer-dialog.tsx
Normal file
@@ -0,0 +1,254 @@
|
||||
import { useState, useCallback } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { usePOSStore } from '@/stores/pos.store'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Search, X, History } from 'lucide-react'
|
||||
|
||||
interface Account {
|
||||
id: string
|
||||
name: string
|
||||
email: string | null
|
||||
phone: string | null
|
||||
accountNumber: string | null
|
||||
}
|
||||
|
||||
interface TransactionLineItem {
|
||||
id: string
|
||||
description: string
|
||||
qty: number
|
||||
unitPrice: string
|
||||
lineTotal: string
|
||||
}
|
||||
|
||||
interface Transaction {
|
||||
id: string
|
||||
transactionNumber: string
|
||||
total: string
|
||||
status: string
|
||||
paymentMethod: string | null
|
||||
transactionType: string
|
||||
completedAt: string | null
|
||||
createdAt: string
|
||||
lineItems?: TransactionLineItem[]
|
||||
}
|
||||
|
||||
function accountSearchOptions(search: string) {
|
||||
return queryOptions({
|
||||
queryKey: ['pos', 'accounts', search],
|
||||
queryFn: () => api.get<{ data: Account[] }>('/v1/accounts', { q: search, limit: 10 }),
|
||||
enabled: search.length >= 2,
|
||||
})
|
||||
}
|
||||
|
||||
function customerHistoryOptions(accountId: string | null, itemSearch?: string) {
|
||||
return queryOptions({
|
||||
queryKey: ['pos', 'customer-history', accountId, itemSearch ?? ''],
|
||||
queryFn: () => api.get<{ data: Transaction[] }>('/v1/transactions', {
|
||||
accountId,
|
||||
limit: 10,
|
||||
sort: 'created_at',
|
||||
order: 'desc',
|
||||
...(itemSearch ? { itemSearch } : {}),
|
||||
}),
|
||||
enabled: !!accountId,
|
||||
})
|
||||
}
|
||||
|
||||
interface POSCustomerDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
export function POSCustomerDialog({ open, onOpenChange }: POSCustomerDialogProps) {
|
||||
const { accountId, accountName, setAccount, clearAccount } = usePOSStore()
|
||||
const [search, setSearch] = useState('')
|
||||
const [showHistory, setShowHistory] = useState(false)
|
||||
const [historySearch, setHistorySearch] = useState('')
|
||||
|
||||
const { data: searchData, isLoading } = useQuery(accountSearchOptions(search))
|
||||
const accounts = searchData?.data ?? []
|
||||
|
||||
const { data: historyData } = useQuery(customerHistoryOptions(showHistory ? accountId : null, historySearch || undefined))
|
||||
const history = historyData?.data ?? []
|
||||
|
||||
function handleSelect(account: Account) {
|
||||
setAccount(account.id, account.name, account.phone, account.email)
|
||||
setSearch('')
|
||||
setShowHistory(false)
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
function handleClear() {
|
||||
clearAccount()
|
||||
setSearch('')
|
||||
setShowHistory(false)
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
const [expandedTxn, setExpandedTxn] = useState<string | null>(null)
|
||||
|
||||
// Fetch detail for expanded transaction
|
||||
const { data: txnDetail } = useQuery({
|
||||
queryKey: ['pos', 'transaction-detail', expandedTxn],
|
||||
queryFn: () => api.get<Transaction>(`/v1/transactions/${expandedTxn}`),
|
||||
enabled: !!expandedTxn,
|
||||
})
|
||||
|
||||
const toggleExpand = useCallback((id: string) => {
|
||||
setExpandedTxn((prev) => prev === id ? null : id)
|
||||
}, [])
|
||||
|
||||
// History view
|
||||
if (showHistory && accountId) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md max-h-[80vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center justify-between">
|
||||
<span>Order History — {accountName}</span>
|
||||
<Button variant="ghost" size="sm" onClick={() => { setShowHistory(false); setExpandedTxn(null) }}>Back</Button>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
{/* Search items in history */}
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
value={historySearch}
|
||||
onChange={(e) => setHistorySearch(e.target.value)}
|
||||
placeholder="Search items (e.g. strings, bow)..."
|
||||
className="pl-10 h-10 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{history.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-8">
|
||||
{historySearch ? `No orders with "${historySearch}"` : 'No transactions found'}
|
||||
</p>
|
||||
) : (
|
||||
<div className="divide-y divide-border">
|
||||
{history.map((txn) => (
|
||||
<div key={txn.id}>
|
||||
<button
|
||||
onClick={() => toggleExpand(txn.id)}
|
||||
className="w-full text-left py-2.5 px-1 hover:bg-accent/50 rounded transition-colors"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-mono">{txn.transactionNumber}</span>
|
||||
<span className="text-sm font-semibold">${parseFloat(txn.total).toFixed(2)}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-0.5">
|
||||
<Badge variant={txn.status === 'completed' ? 'default' : 'outline'} className="text-[10px]">
|
||||
{txn.status}
|
||||
</Badge>
|
||||
{txn.paymentMethod && (
|
||||
<span className="text-xs text-muted-foreground">{txn.paymentMethod.replace('_', ' ')}</span>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground ml-auto">
|
||||
{new Date(txn.completedAt ?? txn.createdAt).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
{expandedTxn === txn.id && txnDetail?.lineItems && (
|
||||
<div className="px-3 pb-2 space-y-1">
|
||||
{txnDetail.lineItems.map((item) => (
|
||||
<div key={item.id} className="flex justify-between text-xs text-muted-foreground">
|
||||
<span>{item.qty} x {item.description}</span>
|
||||
<span>${parseFloat(item.lineTotal).toFixed(2)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md max-h-[80vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Customer</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Current selection */}
|
||||
{accountId && (
|
||||
<>
|
||||
<div className="flex items-center justify-between p-3 rounded-md border bg-muted/30">
|
||||
<div>
|
||||
<p className="font-medium text-sm">{accountName}</p>
|
||||
<p className="text-xs text-muted-foreground">Selected customer</p>
|
||||
</div>
|
||||
<div className="flex gap-1">
|
||||
<Button variant="ghost" size="sm" onClick={() => setShowHistory(true)}>
|
||||
<History className="h-4 w-4 mr-1" />
|
||||
History
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={handleClear}>
|
||||
<X className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Separator />
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Search */}
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Search by name, phone, email, account #..."
|
||||
className="pl-10 h-11"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Results */}
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{isLoading ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">Searching...</p>
|
||||
) : search.length >= 2 && accounts.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">No customers found</p>
|
||||
) : (
|
||||
<div className="divide-y divide-border">
|
||||
{accounts.map((account) => (
|
||||
<button
|
||||
key={account.id}
|
||||
onClick={() => handleSelect(account)}
|
||||
className="w-full text-left px-2 py-3 hover:bg-accent rounded-md transition-colors"
|
||||
>
|
||||
<p className="font-medium text-sm">{account.name}</p>
|
||||
<div className="flex gap-3 text-xs text-muted-foreground mt-0.5">
|
||||
{account.phone && <span>{account.phone}</span>}
|
||||
{account.email && <span>{account.email}</span>}
|
||||
{account.accountNumber && <span>#{account.accountNumber}</span>}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Walk-in button */}
|
||||
{accountId && (
|
||||
<Button variant="outline" className="w-full h-11" onClick={handleClear}>
|
||||
Clear Customer (Walk-in)
|
||||
</Button>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
471
packages/admin/src/components/pos/pos-drawer-dialog.tsx
Normal file
471
packages/admin/src/components/pos/pos-drawer-dialog.tsx
Normal file
@@ -0,0 +1,471 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { usePOSStore } from '@/stores/pos.store'
|
||||
import { posMutations, posKeys, drawerReportOptions, type DrawerSession } from '@/api/pos'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { ArrowDownToLine, ArrowUpFromLine } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { ManagerOverrideDialog, requiresOverride } from './pos-manager-override'
|
||||
|
||||
interface POSDrawerDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
drawer: DrawerSession | null
|
||||
}
|
||||
|
||||
export function POSDrawerDialog({ open, onOpenChange, drawer }: POSDrawerDialogProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const { locationId, registerId, setDrawerSession } = usePOSStore()
|
||||
const isOpen = drawer?.status === 'open'
|
||||
|
||||
const [openingBalance, setOpeningBalance] = useState('200')
|
||||
const [closingBalance, setClosingBalance] = useState('')
|
||||
const [notes, setNotes] = useState('')
|
||||
const [adjustView, setAdjustView] = useState<'cash_in' | 'cash_out' | null>(null)
|
||||
const [adjAmount, setAdjAmount] = useState('')
|
||||
const [adjReason, setAdjReason] = useState('')
|
||||
const [overrideOpen, setOverrideOpen] = useState(false)
|
||||
const [pendingAdjustView, setPendingAdjustView] = useState<'cash_in' | 'cash_out' | null>(null)
|
||||
const [showZReport, setShowZReport] = useState(false)
|
||||
const [closedDrawerId, setClosedDrawerId] = useState<string | null>(null)
|
||||
const [showXReport, setShowXReport] = useState(false)
|
||||
|
||||
// Z Report data (after close)
|
||||
const { data: reportData } = useQuery(drawerReportOptions(closedDrawerId))
|
||||
|
||||
// X Report data (live, for open drawer)
|
||||
const { data: xReportData } = useQuery(drawerReportOptions(showXReport ? drawer?.id ?? null : null))
|
||||
|
||||
// Fetch adjustments for open drawer
|
||||
const { data: adjData } = useQuery({
|
||||
queryKey: posKeys.drawerAdjustments(drawer?.id ?? ''),
|
||||
queryFn: () => posMutations.getAdjustments(drawer!.id),
|
||||
enabled: !!drawer?.id && isOpen,
|
||||
})
|
||||
const adjustments = adjData?.data ?? []
|
||||
|
||||
const openMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
posMutations.openDrawer({
|
||||
locationId: locationId ?? undefined,
|
||||
registerId: registerId ?? undefined,
|
||||
openingBalance: parseFloat(openingBalance) || 0,
|
||||
}),
|
||||
onSuccess: async (session) => {
|
||||
setDrawerSession(session.id)
|
||||
await queryClient.invalidateQueries({ queryKey: posKeys.drawer(locationId ?? '') })
|
||||
toast.success('Drawer opened')
|
||||
onOpenChange(false)
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const closeMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
posMutations.closeDrawer(drawer!.id, {
|
||||
closingBalance: parseFloat(closingBalance) || 0,
|
||||
notes: notes || undefined,
|
||||
}),
|
||||
onSuccess: async (session) => {
|
||||
setDrawerSession(null)
|
||||
const overShort = parseFloat(session.overShort ?? '0')
|
||||
if (Math.abs(overShort) < 0.01) {
|
||||
toast.success('Drawer closed - balanced')
|
||||
} else {
|
||||
toast.warning(`Drawer closed - ${overShort > 0 ? 'over' : 'short'} $${Math.abs(overShort).toFixed(2)}`)
|
||||
}
|
||||
// Show Z report
|
||||
setClosedDrawerId(session.id)
|
||||
setShowZReport(true)
|
||||
await queryClient.invalidateQueries({ queryKey: posKeys.drawer(locationId ?? '') })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const adjustMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
posMutations.addAdjustment(drawer!.id, {
|
||||
type: adjustView!,
|
||||
amount: parseFloat(adjAmount) || 0,
|
||||
reason: adjReason,
|
||||
}),
|
||||
onSuccess: (adj) => {
|
||||
queryClient.invalidateQueries({ queryKey: posKeys.drawerAdjustments(drawer!.id) })
|
||||
toast.success(`${adj.type === 'cash_in' ? 'Cash added' : 'Cash removed'}: $${parseFloat(adj.amount).toFixed(2)}`)
|
||||
setAdjustView(null)
|
||||
setAdjAmount('')
|
||||
setAdjReason('')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
// Z Report view (shown after drawer close)
|
||||
if (showZReport && reportData) {
|
||||
const r = reportData
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={(o) => { onOpenChange(o); if (!o) { setShowZReport(false); setClosedDrawerId(null) } }}>
|
||||
<DialogContent className="max-w-md max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Z Report — Drawer Closed</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DrawerReportView report={r} />
|
||||
<Button variant="outline" className="w-full" onClick={() => { setShowZReport(false); setClosedDrawerId(null); onOpenChange(false) }}>
|
||||
Done
|
||||
</Button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// X Report view (mid-shift snapshot)
|
||||
if (showXReport && xReportData) {
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>X Report — Current Shift</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DrawerReportView report={xReportData} />
|
||||
<Button variant="outline" className="w-full" onClick={() => setShowXReport(false)}>
|
||||
Back
|
||||
</Button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// Adjustment entry view
|
||||
if (adjustView && isOpen) {
|
||||
const isCashIn = adjustView === 'cash_in'
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isCashIn ? 'Cash In' : 'Cash Out'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Amount *</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
value={adjAmount}
|
||||
onChange={(e) => setAdjAmount(e.target.value)}
|
||||
placeholder="0.00"
|
||||
className="h-11 text-lg"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Reason *</Label>
|
||||
<Input
|
||||
value={adjReason}
|
||||
onChange={(e) => setAdjReason(e.target.value)}
|
||||
placeholder={isCashIn ? 'e.g. Extra change' : 'e.g. Bank deposit'}
|
||||
className="h-11"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
className="flex-1 h-12"
|
||||
onClick={() => adjustMutation.mutate()}
|
||||
disabled={!adjAmount || !adjReason || adjustMutation.isPending}
|
||||
>
|
||||
{adjustMutation.isPending ? 'Saving...' : isCashIn ? 'Add Cash' : 'Remove Cash'}
|
||||
</Button>
|
||||
<Button variant="outline" className="h-12" onClick={() => setAdjustView(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isOpen ? 'Drawer' : 'Open Drawer'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{isOpen ? (
|
||||
<div className="space-y-4">
|
||||
<div className="text-sm space-y-1">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Opening Balance</span>
|
||||
<span>${parseFloat(drawer!.openingBalance).toFixed(2)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Opened</span>
|
||||
<span>{new Date(drawer!.openedAt).toLocaleTimeString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Cash In / Cash Out buttons */}
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-11 gap-2"
|
||||
onClick={() => {
|
||||
if (requiresOverride('cash_in_out')) {
|
||||
setPendingAdjustView('cash_in')
|
||||
setOverrideOpen(true)
|
||||
} else {
|
||||
setAdjustView('cash_in')
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ArrowDownToLine className="h-4 w-4 text-green-600" />
|
||||
Cash In
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-11 gap-2"
|
||||
onClick={() => {
|
||||
if (requiresOverride('cash_in_out')) {
|
||||
setPendingAdjustView('cash_out')
|
||||
setOverrideOpen(true)
|
||||
} else {
|
||||
setAdjustView('cash_out')
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ArrowUpFromLine className="h-4 w-4 text-red-600" />
|
||||
Cash Out
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* X Report button */}
|
||||
<Button variant="outline" className="w-full h-10 gap-2 text-sm" onClick={() => setShowXReport(true)}>
|
||||
Current Shift Report
|
||||
</Button>
|
||||
|
||||
{/* Adjustment history */}
|
||||
{adjustments.length > 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-1">
|
||||
<span className="text-xs font-medium text-muted-foreground">Adjustments</span>
|
||||
{adjustments.map((adj) => (
|
||||
<div key={adj.id} className="flex items-center justify-between text-sm py-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={adj.type === 'cash_in' ? 'default' : 'destructive'} className="text-[10px]">
|
||||
{adj.type === 'cash_in' ? 'IN' : 'OUT'}
|
||||
</Badge>
|
||||
<span className="text-muted-foreground truncate max-w-[140px]">{adj.reason}</span>
|
||||
</div>
|
||||
<span className={adj.type === 'cash_in' ? 'text-green-600' : 'text-red-600'}>
|
||||
{adj.type === 'cash_in' ? '+' : '-'}${parseFloat(adj.amount).toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Close drawer */}
|
||||
<div className="space-y-2">
|
||||
<Label>Closing Balance *</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={closingBalance}
|
||||
onChange={(e) => setClosingBalance(e.target.value)}
|
||||
placeholder="Count the cash in the drawer"
|
||||
className="h-11 text-lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Notes</Label>
|
||||
<Input
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
placeholder="End of shift notes"
|
||||
className="h-11"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
className="w-full h-12"
|
||||
onClick={() => closeMutation.mutate()}
|
||||
disabled={!closingBalance || closeMutation.isPending}
|
||||
>
|
||||
{closeMutation.isPending ? 'Closing...' : 'Close Drawer'}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Opening Balance *</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={openingBalance}
|
||||
onChange={(e) => setOpeningBalance(e.target.value)}
|
||||
placeholder="Starting cash amount"
|
||||
className="h-11 text-lg"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
className="w-full h-12"
|
||||
onClick={() => openMutation.mutate()}
|
||||
disabled={!openingBalance || openMutation.isPending}
|
||||
>
|
||||
{openMutation.isPending ? 'Opening...' : 'Open Drawer'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<ManagerOverrideDialog
|
||||
open={overrideOpen}
|
||||
onOpenChange={setOverrideOpen}
|
||||
action={pendingAdjustView === 'cash_in' ? 'Cash In' : 'Cash Out'}
|
||||
onAuthorized={() => {
|
||||
if (pendingAdjustView) setAdjustView(pendingAdjustView)
|
||||
setPendingAdjustView(null)
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// --- Shared report view used by both X and Z reports ---
|
||||
|
||||
const PAYMENT_LABELS: Record<string, string> = {
|
||||
cash: 'Cash',
|
||||
card_present: 'Card (Present)',
|
||||
card_keyed: 'Card (Keyed)',
|
||||
check: 'Check',
|
||||
account_charge: 'Account',
|
||||
unknown: 'Other',
|
||||
}
|
||||
|
||||
function DrawerReportView({ report }: { report: any }) {
|
||||
const { session, sales, payments, discounts, cash, adjustments } = report
|
||||
|
||||
return (
|
||||
<div className="space-y-4 text-sm">
|
||||
{/* Session info */}
|
||||
<div className="space-y-1">
|
||||
{session.register && <div className="flex justify-between"><span className="text-muted-foreground">Register</span><span>{session.register.name}</span></div>}
|
||||
{session.openedBy && <div className="flex justify-between"><span className="text-muted-foreground">Opened by</span><span>{session.openedBy.firstName} {session.openedBy.lastName}</span></div>}
|
||||
<div className="flex justify-between"><span className="text-muted-foreground">Opened</span><span>{new Date(session.openedAt).toLocaleString()}</span></div>
|
||||
{session.closedAt && (
|
||||
<>
|
||||
{session.closedBy && <div className="flex justify-between"><span className="text-muted-foreground">Closed by</span><span>{session.closedBy.firstName} {session.closedBy.lastName}</span></div>}
|
||||
<div className="flex justify-between"><span className="text-muted-foreground">Closed</span><span>{new Date(session.closedAt).toLocaleString()}</span></div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Sales */}
|
||||
<div>
|
||||
<h4 className="font-semibold text-xs uppercase text-muted-foreground mb-2">Sales</h4>
|
||||
<div className="space-y-1">
|
||||
<div className="flex justify-between"><span>Transactions</span><span>{sales.transactionCount}</span></div>
|
||||
<div className="flex justify-between"><span>Gross Sales</span><span className="tabular-nums">${sales.grossSales.toFixed(2)}</span></div>
|
||||
{sales.refundTotal > 0 && <div className="flex justify-between text-red-600"><span>Refunds</span><span className="tabular-nums">-${sales.refundTotal.toFixed(2)}</span></div>}
|
||||
<div className="flex justify-between font-medium"><span>Net Sales</span><span className="tabular-nums">${sales.netSales.toFixed(2)}</span></div>
|
||||
{sales.voidCount > 0 && <div className="flex justify-between text-muted-foreground"><span>Voided</span><span>{sales.voidCount}</span></div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Payment breakdown */}
|
||||
<div>
|
||||
<h4 className="font-semibold text-xs uppercase text-muted-foreground mb-2">Payments</h4>
|
||||
<div className="space-y-1">
|
||||
{Object.entries(payments as Record<string, { count: number; total: number }>).map(([method, data]) => (
|
||||
<div key={method} className="flex justify-between">
|
||||
<span>{PAYMENT_LABELS[method] ?? method} ({data.count})</span>
|
||||
<span className="tabular-nums">${data.total.toFixed(2)}</span>
|
||||
</div>
|
||||
))}
|
||||
{Object.keys(payments).length === 0 && <p className="text-muted-foreground">No payments</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Discounts */}
|
||||
{discounts.count > 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div>
|
||||
<h4 className="font-semibold text-xs uppercase text-muted-foreground mb-2">Discounts</h4>
|
||||
<div className="flex justify-between"><span>Total ({discounts.count})</span><span className="tabular-nums text-green-600">-${discounts.total.toFixed(2)}</span></div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Cash accountability */}
|
||||
<div>
|
||||
<h4 className="font-semibold text-xs uppercase text-muted-foreground mb-2">Cash</h4>
|
||||
<div className="space-y-1">
|
||||
<div className="flex justify-between"><span>Opening Balance</span><span className="tabular-nums">${cash.openingBalance.toFixed(2)}</span></div>
|
||||
<div className="flex justify-between"><span>Cash Sales</span><span className="tabular-nums">${cash.cashSales.toFixed(2)}</span></div>
|
||||
{cash.cashIn > 0 && <div className="flex justify-between text-green-600"><span>Cash In</span><span className="tabular-nums">+${cash.cashIn.toFixed(2)}</span></div>}
|
||||
{cash.cashOut > 0 && <div className="flex justify-between text-red-600"><span>Cash Out</span><span className="tabular-nums">-${cash.cashOut.toFixed(2)}</span></div>}
|
||||
<Separator />
|
||||
<div className="flex justify-between font-medium"><span>Expected</span><span className="tabular-nums">${cash.expectedBalance.toFixed(2)}</span></div>
|
||||
{cash.actualBalance !== null && (
|
||||
<>
|
||||
<div className="flex justify-between"><span>Actual Count</span><span className="tabular-nums">${cash.actualBalance.toFixed(2)}</span></div>
|
||||
<div className={`flex justify-between font-bold ${cash.overShort === 0 ? 'text-green-600' : 'text-red-600'}`}>
|
||||
<span>{cash.overShort! >= 0 ? 'Over' : 'Short'}</span>
|
||||
<span className="tabular-nums">${Math.abs(cash.overShort!).toFixed(2)}</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Adjustments */}
|
||||
{adjustments.length > 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div>
|
||||
<h4 className="font-semibold text-xs uppercase text-muted-foreground mb-2">Adjustments</h4>
|
||||
<div className="space-y-1">
|
||||
{adjustments.map((adj: any) => (
|
||||
<div key={adj.id} className="flex items-center justify-between text-xs">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={adj.type === 'cash_in' ? 'default' : 'destructive'} className="text-[10px]">
|
||||
{adj.type === 'cash_in' ? 'IN' : 'OUT'}
|
||||
</Badge>
|
||||
<span className="text-muted-foreground truncate max-w-[150px]">{adj.reason}</span>
|
||||
</div>
|
||||
<span className="tabular-nums">${parseFloat(adj.amount).toFixed(2)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
285
packages/admin/src/components/pos/pos-item-panel.tsx
Normal file
285
packages/admin/src/components/pos/pos-item-panel.tsx
Normal file
@@ -0,0 +1,285 @@
|
||||
import { useState, useRef, useCallback } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { usePOSStore } from '@/stores/pos.store'
|
||||
import { productSearchOptions, posMutations, posKeys, type Transaction, type Product } from '@/api/pos'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Search, ScanBarcode, Wrench, PenLine, ClipboardList } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { POSTransactionsDialog } from './pos-transactions-dialog'
|
||||
import { POSRepairDialog } from './pos-repair-dialog'
|
||||
|
||||
interface POSItemPanelProps {
|
||||
transaction: Transaction | null
|
||||
}
|
||||
|
||||
export function POSItemPanel({ transaction: _transaction }: POSItemPanelProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const { currentTransactionId, setTransaction, locationId, accountId } = usePOSStore()
|
||||
const [search, setSearch] = useState('')
|
||||
const [customOpen, setCustomOpen] = useState(false)
|
||||
const [txnDialogOpen, setTxnDialogOpen] = useState(false)
|
||||
const [repairOpen, setRepairOpen] = useState(false)
|
||||
const [customDesc, setCustomDesc] = useState('')
|
||||
const [customPrice, setCustomPrice] = useState('')
|
||||
const [customQty, setCustomQty] = useState('1')
|
||||
const searchRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// Debounced product search
|
||||
const { data: productsData, isLoading: searchLoading } = useQuery({
|
||||
...productSearchOptions(search),
|
||||
enabled: search.length >= 1,
|
||||
})
|
||||
const products = productsData?.data ?? []
|
||||
|
||||
// Add line item mutation
|
||||
const addItemMutation = useMutation({
|
||||
mutationFn: async (product: Product) => {
|
||||
let txnId = currentTransactionId
|
||||
// Auto-create transaction if none exists
|
||||
if (!txnId) {
|
||||
const txn = await posMutations.createTransaction({
|
||||
transactionType: 'sale',
|
||||
locationId: locationId ?? undefined,
|
||||
accountId: accountId ?? undefined,
|
||||
})
|
||||
txnId = txn.id
|
||||
setTransaction(txnId)
|
||||
}
|
||||
return posMutations.addLineItem(txnId, {
|
||||
productId: product.id,
|
||||
description: product.name,
|
||||
qty: 1,
|
||||
unitPrice: parseFloat(product.price ?? '0'),
|
||||
})
|
||||
},
|
||||
onSuccess: () => {
|
||||
const txnId = usePOSStore.getState().currentTransactionId
|
||||
queryClient.invalidateQueries({ queryKey: posKeys.transaction(txnId ?? '') })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
// Custom item mutation
|
||||
const addCustomMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
let txnId = currentTransactionId
|
||||
if (!txnId) {
|
||||
const txn = await posMutations.createTransaction({
|
||||
transactionType: 'sale',
|
||||
locationId: locationId ?? undefined,
|
||||
accountId: accountId ?? undefined,
|
||||
})
|
||||
txnId = txn.id
|
||||
setTransaction(txnId)
|
||||
}
|
||||
return posMutations.addLineItem(txnId, {
|
||||
description: customDesc,
|
||||
qty: parseInt(customQty) || 1,
|
||||
unitPrice: parseFloat(customPrice) || 0,
|
||||
})
|
||||
},
|
||||
onSuccess: () => {
|
||||
const txnId = usePOSStore.getState().currentTransactionId
|
||||
queryClient.invalidateQueries({ queryKey: posKeys.transaction(txnId ?? '') })
|
||||
setCustomOpen(false)
|
||||
setCustomDesc('')
|
||||
setCustomPrice('')
|
||||
setCustomQty('1')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
// UPC scan
|
||||
const scanMutation = useMutation({
|
||||
mutationFn: async (upc: string) => {
|
||||
const product = await posMutations.lookupUpc(upc)
|
||||
let txnId = currentTransactionId
|
||||
if (!txnId) {
|
||||
const txn = await posMutations.createTransaction({
|
||||
transactionType: 'sale',
|
||||
locationId: locationId ?? undefined,
|
||||
accountId: accountId ?? undefined,
|
||||
})
|
||||
txnId = txn.id
|
||||
setTransaction(txnId)
|
||||
}
|
||||
return posMutations.addLineItem(txnId, {
|
||||
productId: product.id,
|
||||
description: product.name,
|
||||
qty: 1,
|
||||
unitPrice: parseFloat(product.price ?? '0'),
|
||||
})
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: posKeys.transaction(currentTransactionId ?? '') })
|
||||
setSearch('')
|
||||
toast.success('Item scanned')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const handleSearchKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
// Barcode scanners typically send Enter after the code
|
||||
if (e.key === 'Enter' && search.length >= 6) {
|
||||
// Looks like a UPC — try scanning
|
||||
scanMutation.mutate(search)
|
||||
}
|
||||
}, [search, scanMutation])
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
{/* Search bar */}
|
||||
<div className="p-3 border-b border-border">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
ref={searchRef}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
onKeyDown={handleSearchKeyDown}
|
||||
placeholder="Search products or scan barcode..."
|
||||
className="pl-10 h-11 text-base"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Product grid */}
|
||||
<div className="flex-1 overflow-y-auto p-3">
|
||||
{searchLoading ? (
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-24 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
) : products.length > 0 ? (
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{products.map((product) => (
|
||||
<button
|
||||
key={product.id}
|
||||
onClick={() => addItemMutation.mutate(product)}
|
||||
disabled={addItemMutation.isPending}
|
||||
className="flex flex-col items-start p-3 rounded-lg border border-border bg-card hover:bg-accent active:bg-accent/80 transition-colors text-left min-h-[80px]"
|
||||
>
|
||||
<span className="font-medium text-sm line-clamp-2">{product.name}</span>
|
||||
<div className="mt-auto flex items-center justify-between w-full pt-1">
|
||||
<span className="text-base font-semibold">${parseFloat(product.price ?? '0').toFixed(2)}</span>
|
||||
{product.sku && <span className="text-xs text-muted-foreground">{product.sku}</span>}
|
||||
</div>
|
||||
{product.isSerialized ? (
|
||||
<span className="text-[10px] text-muted-foreground">Serialized</span>
|
||||
) : product.qtyOnHand !== null ? (
|
||||
<span className="text-[10px] text-muted-foreground">{product.qtyOnHand} in stock</span>
|
||||
) : null}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : search.length >= 1 ? (
|
||||
<div className="flex items-center justify-center h-32 text-muted-foreground text-sm">
|
||||
No products found for "{search}"
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-32 text-muted-foreground text-sm">
|
||||
Search for products to add to the sale
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Quick action buttons */}
|
||||
<div className="p-3 border-t border-border flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1 h-11 text-sm gap-2"
|
||||
onClick={() => searchRef.current?.focus()}
|
||||
>
|
||||
<ScanBarcode className="h-4 w-4" />
|
||||
Scan
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1 h-11 text-sm gap-2"
|
||||
onClick={() => setRepairOpen(true)}
|
||||
>
|
||||
<Wrench className="h-4 w-4" />
|
||||
Repairs
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1 h-11 text-sm gap-2"
|
||||
onClick={() => setCustomOpen(true)}
|
||||
>
|
||||
<PenLine className="h-4 w-4" />
|
||||
Custom
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1 h-11 text-sm gap-2"
|
||||
onClick={() => setTxnDialogOpen(true)}
|
||||
>
|
||||
<ClipboardList className="h-4 w-4" />
|
||||
Orders
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Custom item dialog */}
|
||||
<Dialog open={customOpen} onOpenChange={setCustomOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Custom Item</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form
|
||||
onSubmit={(e) => { e.preventDefault(); addCustomMutation.mutate() }}
|
||||
className="space-y-4"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<Label>Description *</Label>
|
||||
<Input
|
||||
value={customDesc}
|
||||
onChange={(e) => setCustomDesc(e.target.value)}
|
||||
placeholder="Item description"
|
||||
required
|
||||
className="h-11"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Price *</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={customPrice}
|
||||
onChange={(e) => setCustomPrice(e.target.value)}
|
||||
placeholder="0.00"
|
||||
required
|
||||
className="h-11"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Qty</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
value={customQty}
|
||||
onChange={(e) => setCustomQty(e.target.value)}
|
||||
className="h-11"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Button type="submit" className="w-full h-11" disabled={addCustomMutation.isPending}>
|
||||
{addCustomMutation.isPending ? 'Adding...' : 'Add Item'}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Transactions dialog */}
|
||||
<POSTransactionsDialog open={txnDialogOpen} onOpenChange={setTxnDialogOpen} />
|
||||
<POSRepairDialog open={repairOpen} onOpenChange={setRepairOpen} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
168
packages/admin/src/components/pos/pos-lock-screen.tsx
Normal file
168
packages/admin/src/components/pos/pos-lock-screen.tsx
Normal file
@@ -0,0 +1,168 @@
|
||||
import { useState, useCallback, useEffect, useRef } from 'react'
|
||||
import { usePOSStore } from '@/stores/pos.store'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Delete, Lock } from 'lucide-react'
|
||||
|
||||
interface PinUser {
|
||||
id: string
|
||||
email: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
role: string
|
||||
}
|
||||
|
||||
export function POSLockScreen() {
|
||||
const unlock = usePOSStore((s) => s.unlock)
|
||||
const [code, setCode] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Auto-focus on mount
|
||||
useEffect(() => {
|
||||
containerRef.current?.focus()
|
||||
}, [])
|
||||
|
||||
const handleDigit = useCallback((digit: string) => {
|
||||
setError('')
|
||||
setCode((p) => {
|
||||
if (p.length >= 10) return p
|
||||
return p + digit
|
||||
})
|
||||
}, [])
|
||||
|
||||
const handleBackspace = useCallback(() => {
|
||||
setError('')
|
||||
setCode((p) => p.slice(0, -1))
|
||||
}, [])
|
||||
|
||||
const handleClear = useCallback(() => {
|
||||
setError('')
|
||||
setCode('')
|
||||
}, [])
|
||||
|
||||
const handleSubmit = useCallback(async (submitCode: string) => {
|
||||
if (submitCode.length < 8) {
|
||||
setError('Enter your employee # (4) + PIN (4)')
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const res = await api.post<{ user: PinUser; token: string }>('/v1/auth/pin-login', { code: submitCode })
|
||||
unlock(res.user, res.token)
|
||||
setCode('')
|
||||
} catch {
|
||||
setError('Invalid code')
|
||||
setCode('')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [unlock])
|
||||
|
||||
// Auto-submit when 8 digits entered
|
||||
useEffect(() => {
|
||||
if (code.length === 8) {
|
||||
handleSubmit(code)
|
||||
}
|
||||
}, [code, handleSubmit])
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (e.key >= '0' && e.key <= '9') handleDigit(e.key)
|
||||
else if (e.key === 'Backspace') handleBackspace()
|
||||
else if (e.key === 'Enter' && code.length >= 8) handleSubmit(code)
|
||||
else if (e.key === 'Escape') handleClear()
|
||||
}, [handleDigit, handleBackspace, handleSubmit, handleClear, code])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="absolute inset-0 z-50 bg-background flex items-center justify-center"
|
||||
onKeyDown={handleKeyDown}
|
||||
tabIndex={0}
|
||||
>
|
||||
<div className="w-80 space-y-6">
|
||||
{/* Header */}
|
||||
<div className="text-center space-y-2">
|
||||
<Lock className="h-10 w-10 mx-auto text-muted-foreground" />
|
||||
<h1 className="text-xl font-semibold">POS Locked</h1>
|
||||
<p className="text-sm text-muted-foreground">Employee # + PIN</p>
|
||||
</div>
|
||||
|
||||
{/* Code dots — 4 employee + 4 PIN with separator */}
|
||||
<div className="flex justify-center items-center gap-2">
|
||||
<div className="flex gap-1.5">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<div
|
||||
key={`e${i}`}
|
||||
className={`w-3.5 h-3.5 rounded-full border-2 ${
|
||||
i < Math.min(code.length, 4) ? 'bg-foreground border-foreground' : 'border-muted-foreground/30'
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<span className="text-muted-foreground/40 text-lg">-</span>
|
||||
<div className="flex gap-1.5">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<div
|
||||
key={`p${i}`}
|
||||
className={`w-3.5 h-3.5 rounded-full border-2 ${
|
||||
i < Math.max(0, code.length - 4) ? 'bg-foreground border-foreground' : 'border-muted-foreground/30'
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<p className="text-sm text-destructive text-center">{error}</p>
|
||||
)}
|
||||
|
||||
{/* Numpad */}
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{['1', '2', '3', '4', '5', '6', '7', '8', '9'].map((d) => (
|
||||
<Button
|
||||
key={d}
|
||||
variant="outline"
|
||||
className="h-14 text-xl font-medium"
|
||||
onClick={() => handleDigit(d)}
|
||||
disabled={loading}
|
||||
>
|
||||
{d}
|
||||
</Button>
|
||||
))}
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-14 text-sm"
|
||||
onClick={handleClear}
|
||||
disabled={loading}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-14 text-xl font-medium"
|
||||
onClick={() => handleDigit('0')}
|
||||
disabled={loading}
|
||||
>
|
||||
0
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-14"
|
||||
onClick={handleBackspace}
|
||||
disabled={loading}
|
||||
>
|
||||
<Delete className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{loading && (
|
||||
<p className="text-sm text-muted-foreground text-center">Verifying...</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
201
packages/admin/src/components/pos/pos-manager-override.tsx
Normal file
201
packages/admin/src/components/pos/pos-manager-override.tsx
Normal file
@@ -0,0 +1,201 @@
|
||||
import { useState, useCallback, useEffect, useRef } from 'react'
|
||||
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { Delete, ShieldCheck } from 'lucide-react'
|
||||
|
||||
interface ManagerOverrideDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
action: string
|
||||
onAuthorized: () => void
|
||||
}
|
||||
|
||||
interface PinUser {
|
||||
id: string
|
||||
role: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
}
|
||||
|
||||
export function ManagerOverrideDialog({ open, onOpenChange, action, onAuthorized }: ManagerOverrideDialogProps) {
|
||||
const [code, setCode] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setCode('')
|
||||
setError('')
|
||||
containerRef.current?.focus()
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const handleDigit = useCallback((digit: string) => {
|
||||
setError('')
|
||||
setCode((p) => (p.length >= 10 ? p : p + digit))
|
||||
}, [])
|
||||
|
||||
const handleBackspace = useCallback(() => {
|
||||
setError('')
|
||||
setCode((p) => p.slice(0, -1))
|
||||
}, [])
|
||||
|
||||
const handleClear = useCallback(() => {
|
||||
setError('')
|
||||
setCode('')
|
||||
}, [])
|
||||
|
||||
const handleSubmit = useCallback(async (submitCode: string) => {
|
||||
if (submitCode.length < 8) {
|
||||
setError('Enter manager employee # + PIN')
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const res = await api.post<{ user: PinUser; token: string }>('/v1/auth/pin-login', { code: submitCode })
|
||||
if (res.user.role === 'admin' || res.user.role === 'manager') {
|
||||
onAuthorized()
|
||||
onOpenChange(false)
|
||||
} else {
|
||||
setError('Manager or admin access required')
|
||||
setCode('')
|
||||
}
|
||||
} catch {
|
||||
setError('Invalid code')
|
||||
setCode('')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [onAuthorized, onOpenChange])
|
||||
|
||||
useEffect(() => {
|
||||
if (code.length === 8) {
|
||||
handleSubmit(code)
|
||||
}
|
||||
}, [code, handleSubmit])
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (e.key >= '0' && e.key <= '9') handleDigit(e.key)
|
||||
else if (e.key === 'Backspace') handleBackspace()
|
||||
else if (e.key === 'Enter' && code.length >= 8) handleSubmit(code)
|
||||
else if (e.key === 'Escape') handleClear()
|
||||
}, [handleDigit, handleBackspace, handleSubmit, handleClear, code])
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-xs">
|
||||
<div
|
||||
ref={containerRef}
|
||||
onKeyDown={handleKeyDown}
|
||||
tabIndex={0}
|
||||
className="outline-none space-y-4"
|
||||
>
|
||||
<div className="text-center space-y-1">
|
||||
<ShieldCheck className="h-8 w-8 mx-auto text-amber-500" />
|
||||
<DialogTitle className="text-base">Manager Override</DialogTitle>
|
||||
<p className="text-xs text-muted-foreground">{action}</p>
|
||||
</div>
|
||||
|
||||
{/* Code dots */}
|
||||
<div className="flex justify-center items-center gap-2">
|
||||
<div className="flex gap-1.5">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<div
|
||||
key={`e${i}`}
|
||||
className={`w-3 h-3 rounded-full border-2 ${
|
||||
i < Math.min(code.length, 4) ? 'bg-foreground border-foreground' : 'border-muted-foreground/30'
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<span className="text-muted-foreground/40">-</span>
|
||||
<div className="flex gap-1.5">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<div
|
||||
key={`p${i}`}
|
||||
className={`w-3 h-3 rounded-full border-2 ${
|
||||
i < Math.max(0, code.length - 4) ? 'bg-foreground border-foreground' : 'border-muted-foreground/30'
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-xs text-destructive text-center">{error}</p>}
|
||||
|
||||
{/* Numpad */}
|
||||
<div className="grid grid-cols-3 gap-1.5">
|
||||
{['1', '2', '3', '4', '5', '6', '7', '8', '9'].map((d) => (
|
||||
<Button key={d} variant="outline" className="h-12 text-lg font-medium" onClick={() => handleDigit(d)} disabled={loading}>
|
||||
{d}
|
||||
</Button>
|
||||
))}
|
||||
<Button variant="outline" className="h-12 text-xs" onClick={handleClear} disabled={loading}>Clear</Button>
|
||||
<Button variant="outline" className="h-12 text-lg font-medium" onClick={() => handleDigit('0')} disabled={loading}>0</Button>
|
||||
<Button variant="outline" className="h-12" onClick={handleBackspace} disabled={loading}>
|
||||
<Delete className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{loading && <p className="text-xs text-muted-foreground text-center">Verifying...</p>}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
// --- Config types & helpers ---
|
||||
|
||||
export const OVERRIDE_ACTIONS = [
|
||||
{ key: 'void_transaction', label: 'Void Transaction', description: 'Cancel an in-progress sale' },
|
||||
{ key: 'refund', label: 'Refund', description: 'Process a return or refund' },
|
||||
{ key: 'manual_discount', label: 'Manual Discount', description: 'Apply a discount not from a preset' },
|
||||
{ key: 'price_override', label: 'Price Override', description: 'Change an item price at the register' },
|
||||
{ key: 'no_sale_drawer', label: 'No-Sale Drawer Open', description: 'Open the drawer without a transaction' },
|
||||
{ key: 'cash_in_out', label: 'Cash In / Cash Out', description: 'Add or remove cash from the drawer' },
|
||||
] as const
|
||||
|
||||
export type OverrideAction = typeof OVERRIDE_ACTIONS[number]['key']
|
||||
|
||||
const STORAGE_KEY = 'pos_manager_overrides'
|
||||
|
||||
export function getRequiredOverrides(): Set<OverrideAction> {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY)
|
||||
if (!stored) return new Set()
|
||||
return new Set(JSON.parse(stored) as OverrideAction[])
|
||||
} catch {
|
||||
return new Set()
|
||||
}
|
||||
}
|
||||
|
||||
export function setRequiredOverrides(actions: Set<OverrideAction>) {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify([...actions]))
|
||||
}
|
||||
|
||||
export function requiresOverride(action: OverrideAction): boolean {
|
||||
return getRequiredOverrides().has(action)
|
||||
}
|
||||
|
||||
// Discount threshold — discounts above this percentage require manager override
|
||||
const DISCOUNT_THRESHOLD_KEY = 'pos_discount_threshold_pct'
|
||||
|
||||
export function getDiscountThreshold(): number {
|
||||
const stored = localStorage.getItem(DISCOUNT_THRESHOLD_KEY)
|
||||
return stored ? parseInt(stored, 10) : 0 // 0 = disabled
|
||||
}
|
||||
|
||||
export function setDiscountThreshold(pct: number) {
|
||||
localStorage.setItem(DISCOUNT_THRESHOLD_KEY, String(pct))
|
||||
}
|
||||
|
||||
export function requiresDiscountOverride(discountPct: number): boolean {
|
||||
// Check percentage threshold first
|
||||
const threshold = getDiscountThreshold()
|
||||
if (threshold > 0 && discountPct >= threshold) return true
|
||||
// Fall back to the blanket manual_discount toggle
|
||||
return requiresOverride('manual_discount')
|
||||
}
|
||||
298
packages/admin/src/components/pos/pos-payment-dialog.tsx
Normal file
298
packages/admin/src/components/pos/pos-payment-dialog.tsx
Normal file
@@ -0,0 +1,298 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { usePOSStore } from '@/stores/pos.store'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { posMutations, posKeys, type Transaction } from '@/api/pos'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { CheckCircle, Printer, Mail } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { POSReceipt, downloadReceiptPDF, printReceipt } from './pos-receipt'
|
||||
|
||||
interface POSPaymentDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
paymentMethod: string
|
||||
transaction: Transaction
|
||||
onComplete: () => void
|
||||
}
|
||||
|
||||
export function POSPaymentDialog({ open, onOpenChange, paymentMethod, transaction, onComplete }: POSPaymentDialogProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const { currentTransactionId } = usePOSStore()
|
||||
const total = parseFloat(transaction.total)
|
||||
const [amountTendered, setAmountTendered] = useState('')
|
||||
const [checkNumber, setCheckNumber] = useState('')
|
||||
const [completed, setCompleted] = useState(false)
|
||||
const [result, setResult] = useState<Transaction | null>(null)
|
||||
|
||||
const completeMutation = useMutation({
|
||||
mutationFn: () => {
|
||||
const data: { paymentMethod: string; amountTendered?: number; checkNumber?: string } = {
|
||||
paymentMethod,
|
||||
}
|
||||
if (paymentMethod === 'cash') {
|
||||
data.amountTendered = parseFloat(amountTendered) || 0
|
||||
}
|
||||
if (paymentMethod === 'check') {
|
||||
data.checkNumber = checkNumber || undefined
|
||||
}
|
||||
return posMutations.complete(currentTransactionId!, data)
|
||||
},
|
||||
onSuccess: (txn) => {
|
||||
queryClient.invalidateQueries({ queryKey: posKeys.transaction(currentTransactionId!) })
|
||||
queryClient.invalidateQueries({ queryKey: ['pos', 'products'] })
|
||||
setResult(txn)
|
||||
setCompleted(true)
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const tenderedAmount = parseFloat(amountTendered) || 0
|
||||
const changeDue = paymentMethod === 'cash' ? Math.max(0, tenderedAmount - total) : 0
|
||||
const canComplete = paymentMethod === 'cash'
|
||||
? tenderedAmount >= total
|
||||
: true
|
||||
|
||||
function handleDone() {
|
||||
onComplete()
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
const QUICK_AMOUNTS = [1, 5, 10, 20, 50, 100]
|
||||
|
||||
// Fetch receipt config
|
||||
interface AppConfigEntry { key: string; value: string | null }
|
||||
const { data: configData } = useQuery({
|
||||
queryKey: ['config'],
|
||||
queryFn: () => api.get<{ data: AppConfigEntry[] }>('/v1/config'),
|
||||
enabled: !!result?.id,
|
||||
})
|
||||
const receiptFormat = usePOSStore((s) => s.receiptFormat)
|
||||
const receiptConfig = {
|
||||
header: configData?.data?.find((c) => c.key === 'receipt_header')?.value || undefined,
|
||||
footer: configData?.data?.find((c) => c.key === 'receipt_footer')?.value || undefined,
|
||||
returnPolicy: configData?.data?.find((c) => c.key === 'receipt_return_policy')?.value || undefined,
|
||||
social: configData?.data?.find((c) => c.key === 'receipt_social')?.value || undefined,
|
||||
}
|
||||
|
||||
// Fetch full receipt data after completion
|
||||
const { data: receiptData } = useQuery({
|
||||
queryKey: ['pos', 'receipt', result?.id],
|
||||
queryFn: () => api.get<{
|
||||
transaction: Transaction & { lineItems: { description: string; qty: number; unitPrice: string; taxAmount: string; lineTotal: string; discountAmount: string }[] }
|
||||
customerEmail: string | null
|
||||
company: { name: string; phone: string | null; email: string | null; address: { street?: string; city?: string; state?: string; zip?: string } | null }
|
||||
location: { name: string; phone: string | null; email: string | null; address: { street?: string; city?: string; state?: string; zip?: string } | null }
|
||||
}>(`/v1/transactions/${result!.id}/receipt`),
|
||||
enabled: !!result?.id,
|
||||
})
|
||||
|
||||
const [showReceipt, setShowReceipt] = useState(false)
|
||||
const [emailMode, setEmailMode] = useState(false)
|
||||
const [emailAddress, setEmailAddress] = useState('')
|
||||
const [emailSent, setEmailSent] = useState(false)
|
||||
|
||||
const emailReceiptMutation = useMutation({
|
||||
mutationFn: () => api.post<{ message: string }>(`/v1/transactions/${result!.id}/email-receipt`, { email: emailAddress }),
|
||||
onSuccess: () => {
|
||||
toast.success('Receipt emailed')
|
||||
setEmailMode(false)
|
||||
setEmailSent(true)
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
if (completed && result) {
|
||||
const changeGiven = parseFloat(result.changeGiven ?? '0')
|
||||
|
||||
// Receipt print view
|
||||
if (showReceipt && receiptData) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={() => { setShowReceipt(false); handleDone() }}>
|
||||
<DialogContent className={`${receiptFormat === 'full' ? 'max-w-2xl' : 'max-w-sm'} max-h-[90vh] overflow-y-auto print:max-w-none print:max-h-none print:overflow-visible print:shadow-none print:border-none`}>
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<Button variant="ghost" size="sm" onClick={() => setShowReceipt(false)}>Back</Button>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => downloadReceiptPDF(result.transactionNumber, receiptFormat)} className="gap-2">
|
||||
Save PDF
|
||||
</Button>
|
||||
<Button size="sm" onClick={printReceipt} className="gap-2">
|
||||
<Printer className="h-4 w-4" />Print
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="pos-receipt-print">
|
||||
<POSReceipt data={receiptData} size={receiptFormat} config={receiptConfig} />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={() => handleDone()}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<div className="flex flex-col items-center text-center space-y-4 py-4">
|
||||
<CheckCircle className="h-12 w-12 text-green-500" />
|
||||
<h2 className="text-xl font-bold">Sale Complete</h2>
|
||||
<p className="text-muted-foreground text-sm">{result.transactionNumber}</p>
|
||||
|
||||
<div className="w-full text-sm space-y-1">
|
||||
<div className="flex justify-between font-semibold text-base">
|
||||
<span>Total</span>
|
||||
<span>${parseFloat(result.total).toFixed(2)}</span>
|
||||
</div>
|
||||
{paymentMethod === 'cash' && changeGiven > 0 && (
|
||||
<div className="flex justify-between text-lg font-bold text-green-600">
|
||||
<span>Change Due</span>
|
||||
<span>${changeGiven.toFixed(2)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{emailMode ? (
|
||||
<div className="w-full space-y-2">
|
||||
<Label className="text-xs text-muted-foreground">Email receipt to:</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
type="email"
|
||||
value={emailAddress}
|
||||
onChange={(e) => setEmailAddress(e.target.value)}
|
||||
placeholder="customer@example.com"
|
||||
className="h-9"
|
||||
autoFocus
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-9 px-4"
|
||||
onClick={() => emailReceiptMutation.mutate()}
|
||||
disabled={!emailAddress || emailReceiptMutation.isPending}
|
||||
>
|
||||
{emailReceiptMutation.isPending ? 'Sending...' : 'Send'}
|
||||
</Button>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" className="text-xs" onClick={() => setEmailMode(false)}>Cancel</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-full grid grid-cols-2 gap-2">
|
||||
<Button variant="outline" className="h-11 gap-2" onClick={() => setShowReceipt(true)}>
|
||||
<Printer className="h-4 w-4" />Receipt
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-11 gap-2"
|
||||
onClick={() => {
|
||||
setEmailAddress(receiptData?.customerEmail ?? '')
|
||||
setEmailMode(true)
|
||||
}}
|
||||
disabled={emailSent}
|
||||
>
|
||||
<Mail className="h-4 w-4" />{emailSent ? 'Sent' : 'Email'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button className="w-full h-12 text-base" onClick={handleDone}>
|
||||
New Sale
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{paymentMethod === 'cash' ? 'Cash Payment' : paymentMethod === 'check' ? 'Check Payment' : 'Card Payment'}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between text-lg font-bold">
|
||||
<span>Total Due</span>
|
||||
<span>${total.toFixed(2)}</span>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{paymentMethod === 'cash' && (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label>Amount Tendered</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={amountTendered}
|
||||
onChange={(e) => setAmountTendered(e.target.value)}
|
||||
placeholder="0.00"
|
||||
className="h-12 text-xl text-right font-mono"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{QUICK_AMOUNTS.map((amt) => (
|
||||
<Button
|
||||
key={amt}
|
||||
variant="outline"
|
||||
className="h-11"
|
||||
onClick={() => setAmountTendered(String(amt))}
|
||||
>
|
||||
${amt}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-11"
|
||||
onClick={() => setAmountTendered(total.toFixed(2))}
|
||||
>
|
||||
Exact ${total.toFixed(2)}
|
||||
</Button>
|
||||
{tenderedAmount >= total && (
|
||||
<div className="flex justify-between text-lg font-bold text-green-600">
|
||||
<span>Change</span>
|
||||
<span>${changeDue.toFixed(2)}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{paymentMethod === 'check' && (
|
||||
<div className="space-y-2">
|
||||
<Label>Check Number</Label>
|
||||
<Input
|
||||
value={checkNumber}
|
||||
onChange={(e) => setCheckNumber(e.target.value)}
|
||||
placeholder="Check #"
|
||||
className="h-11"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{paymentMethod === 'card_present' && (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">
|
||||
Process card payment on terminal, then confirm below.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Button
|
||||
className="w-full h-12 text-base"
|
||||
disabled={!canComplete || completeMutation.isPending}
|
||||
onClick={() => completeMutation.mutate()}
|
||||
>
|
||||
{completeMutation.isPending ? 'Processing...' : `Complete ${paymentMethod === 'cash' ? 'Cash' : paymentMethod === 'check' ? 'Check' : 'Card'} Sale`}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
443
packages/admin/src/components/pos/pos-receipt.tsx
Normal file
443
packages/admin/src/components/pos/pos-receipt.tsx
Normal file
@@ -0,0 +1,443 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { usePOSStore } from '@/stores/pos.store'
|
||||
import JsBarcode from 'jsbarcode'
|
||||
|
||||
interface ReceiptLineItem {
|
||||
description: string
|
||||
qty: number
|
||||
unitPrice: string
|
||||
taxAmount: string
|
||||
lineTotal: string
|
||||
discountAmount?: string
|
||||
}
|
||||
|
||||
interface ReceiptData {
|
||||
transaction: {
|
||||
transactionNumber: string
|
||||
transactionType: string
|
||||
status: string
|
||||
subtotal: string
|
||||
discountTotal: string
|
||||
taxTotal: string
|
||||
total: string
|
||||
paymentMethod: string | null
|
||||
amountTendered: string | null
|
||||
changeGiven: string | null
|
||||
roundingAdjustment: string
|
||||
completedAt: string | null
|
||||
createdAt: string
|
||||
lineItems: ReceiptLineItem[]
|
||||
}
|
||||
company: {
|
||||
name: string
|
||||
phone: string | null
|
||||
email: string | null
|
||||
address: { street?: string; city?: string; state?: string; zip?: string } | null
|
||||
}
|
||||
location: {
|
||||
name: string
|
||||
phone: string | null
|
||||
email: string | null
|
||||
address: { street?: string; city?: string; state?: string; zip?: string } | null
|
||||
}
|
||||
}
|
||||
|
||||
interface ReceiptConfig {
|
||||
header?: string
|
||||
footer?: string
|
||||
returnPolicy?: string
|
||||
social?: string
|
||||
}
|
||||
|
||||
interface POSReceiptProps {
|
||||
data: ReceiptData
|
||||
size?: 'thermal' | 'full'
|
||||
footerText?: string
|
||||
config?: ReceiptConfig
|
||||
}
|
||||
|
||||
function useStoreLogo(companyId?: string) {
|
||||
const token = usePOSStore((s) => s.token)
|
||||
const [logoSrc, setLogoSrc] = useState<string | null>(null)
|
||||
|
||||
const { data: storeData } = useQuery(queryOptions({
|
||||
queryKey: ['store'],
|
||||
queryFn: () => api.get<{ id: string }>('/v1/store'),
|
||||
enabled: !!token,
|
||||
}))
|
||||
|
||||
const storeId = companyId ?? storeData?.id
|
||||
const { data: filesData } = useQuery(queryOptions({
|
||||
queryKey: ['files', 'company', storeId ?? ''],
|
||||
queryFn: () => api.get<{ data: { id: string; path: string }[] }>('/v1/files', { entityType: 'company', entityId: storeId }),
|
||||
enabled: !!storeId,
|
||||
}))
|
||||
|
||||
const logoFile = filesData?.data?.find((f) => f.path.includes('/logo-'))
|
||||
|
||||
useEffect(() => {
|
||||
if (!logoFile || !token) { setLogoSrc(null); return }
|
||||
let cancelled = false
|
||||
let blobUrl: string | null = null
|
||||
async function load() {
|
||||
try {
|
||||
const res = await fetch(`/v1/files/serve/${logoFile!.path}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
if (!res.ok || cancelled) return
|
||||
const blob = await res.blob()
|
||||
if (!cancelled) { blobUrl = URL.createObjectURL(blob); setLogoSrc(blobUrl) }
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
load()
|
||||
return () => { cancelled = true; if (blobUrl) URL.revokeObjectURL(blobUrl) }
|
||||
}, [logoFile?.path, token])
|
||||
|
||||
return logoSrc
|
||||
}
|
||||
|
||||
export function POSReceipt({ data, size = 'thermal', footerText, config }: POSReceiptProps) {
|
||||
const isThermal = size === 'thermal'
|
||||
|
||||
if (!isThermal) {
|
||||
return <FullPageReceipt data={data} config={config} footerText={footerText} />
|
||||
}
|
||||
|
||||
return <ThermalReceipt data={data} config={config} footerText={footerText} />
|
||||
}
|
||||
|
||||
function useReceiptData(data: POSReceiptProps['data']) {
|
||||
const { transaction: txn, company, location } = data
|
||||
return {
|
||||
txn,
|
||||
company,
|
||||
location,
|
||||
date: new Date(txn.completedAt ?? txn.createdAt),
|
||||
subtotal: parseFloat(txn.subtotal),
|
||||
discountTotal: parseFloat(txn.discountTotal),
|
||||
taxTotal: parseFloat(txn.taxTotal),
|
||||
total: parseFloat(txn.total),
|
||||
rounding: parseFloat(txn.roundingAdjustment),
|
||||
tendered: txn.amountTendered ? parseFloat(txn.amountTendered) : null,
|
||||
change: txn.changeGiven ? parseFloat(txn.changeGiven) : null,
|
||||
addr: location.address ?? company.address,
|
||||
phone: location.phone ?? company.phone,
|
||||
email: location.email ?? company.email,
|
||||
}
|
||||
}
|
||||
|
||||
function useBarcode(ref: React.RefObject<SVGSVGElement | null>, value: string, opts: { width: number; height: number; fontSize: number }) {
|
||||
useEffect(() => {
|
||||
if (ref.current) {
|
||||
try {
|
||||
JsBarcode(ref.current, value, { format: 'CODE128', displayValue: true, margin: 4, ...opts })
|
||||
} catch { /* barcode generation failed — show text fallback */ }
|
||||
}
|
||||
}, [value])
|
||||
}
|
||||
|
||||
function ThermalReceipt({ data, config, footerText }: { data: POSReceiptProps['data']; config?: ReceiptConfig; footerText?: string }) {
|
||||
const barcodeRef = useRef<SVGSVGElement>(null)
|
||||
const logoSrc = useStoreLogo()
|
||||
const { txn, company, location, date, subtotal, discountTotal, taxTotal, total, rounding, tendered, change, addr, phone } = useReceiptData(data)
|
||||
useBarcode(barcodeRef, txn.transactionNumber, { width: 1.5, height: 40, fontSize: 10 })
|
||||
|
||||
const s = {
|
||||
row: { display: 'flex', justifyContent: 'space-between' } as const,
|
||||
section: { padding: '8px 0', borderBottom: '1px dashed #999' } as const,
|
||||
gray: { color: '#666' } as const,
|
||||
light: { color: '#999' } as const,
|
||||
bold: { fontWeight: 'bold' } as const,
|
||||
center: { textAlign: 'center' } as const,
|
||||
nums: { fontVariantNumeric: 'tabular-nums' } as const,
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
background: '#fff', color: '#000', fontFamily: 'monospace',
|
||||
width: 260, maxWidth: 260, fontSize: 10, lineHeight: '1.3', margin: '0 auto',
|
||||
}}>
|
||||
{/* Store header */}
|
||||
<div style={{ ...s.section, ...s.center }}>
|
||||
{logoSrc ? (
|
||||
<img src={logoSrc} alt={company.name} style={{ display: 'block', margin: '0 auto 4px', maxHeight: 48, maxWidth: 200, objectFit: 'contain' }} />
|
||||
) : (
|
||||
<div style={{ ...s.bold, fontSize: 14 }}>{company.name}</div>
|
||||
)}
|
||||
{location.name !== company.name && <div style={s.gray}>{location.name}</div>}
|
||||
{addr?.street && <div>{addr.street}</div>}
|
||||
{(addr?.city || addr?.state || addr?.zip) && (
|
||||
<div>{[addr?.city, addr?.state].filter(Boolean).join(', ')} {addr?.zip}</div>
|
||||
)}
|
||||
{phone && <div>{phone}</div>}
|
||||
{config?.header && <div style={{ ...s.gray, marginTop: 4 }}>{config.header}</div>}
|
||||
</div>
|
||||
|
||||
{/* Transaction info */}
|
||||
<div style={s.section}>
|
||||
<div style={s.row}>
|
||||
<span>{txn.transactionNumber}</span>
|
||||
<span>{txn.transactionType.replace('_', ' ')}</span>
|
||||
</div>
|
||||
<div style={{ ...s.row, ...s.gray }}>
|
||||
<span>{date.toLocaleDateString()}</span>
|
||||
<span>{date.toLocaleTimeString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Line items */}
|
||||
<div style={s.section}>
|
||||
{txn.lineItems.map((item, i) => (
|
||||
<div key={i} style={{ padding: '2px 0' }}>
|
||||
<div style={s.row}>
|
||||
<span style={{ flex: 1, paddingRight: 8 }}>{item.description}</span>
|
||||
<span style={s.nums}>${parseFloat(item.lineTotal).toFixed(2)}</span>
|
||||
</div>
|
||||
{(item.qty > 1 || parseFloat(item.discountAmount ?? '0') > 0) && (
|
||||
<div style={{ ...s.light, paddingLeft: 8 }}>
|
||||
{item.qty > 1 && <span>{item.qty} x ${parseFloat(item.unitPrice).toFixed(2)}</span>}
|
||||
{parseFloat(item.discountAmount ?? '0') > 0 && (
|
||||
<span style={{ marginLeft: 8 }}>disc -${parseFloat(item.discountAmount!).toFixed(2)}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Totals */}
|
||||
<div style={s.section}>
|
||||
<div style={s.row}><span>Subtotal</span><span style={s.nums}>${subtotal.toFixed(2)}</span></div>
|
||||
{discountTotal > 0 && (
|
||||
<div style={s.row}><span>Discount</span><span style={s.nums}>-${discountTotal.toFixed(2)}</span></div>
|
||||
)}
|
||||
<div style={s.row}><span>Tax</span><span style={s.nums}>${taxTotal.toFixed(2)}</span></div>
|
||||
{rounding !== 0 && (
|
||||
<div style={{ ...s.row, ...s.gray }}><span>Rounding</span><span style={s.nums}>{rounding > 0 ? '+' : ''}{rounding.toFixed(2)}</span></div>
|
||||
)}
|
||||
<div style={{ ...s.row, ...s.bold, fontSize: 14, paddingTop: 4 }}>
|
||||
<span>TOTAL</span><span style={s.nums}>${total.toFixed(2)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment */}
|
||||
<div style={s.section}>
|
||||
<div style={s.row}><span>Payment</span><span style={{ textTransform: 'capitalize' }}>{txn.paymentMethod?.replace('_', ' ') ?? 'N/A'}</span></div>
|
||||
{tendered !== null && (
|
||||
<div style={s.row}><span>Tendered</span><span style={s.nums}>${tendered.toFixed(2)}</span></div>
|
||||
)}
|
||||
{change !== null && change > 0 && (
|
||||
<div style={{ ...s.row, ...s.bold }}><span>Change</span><span style={s.nums}>${change.toFixed(2)}</span></div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Barcode */}
|
||||
<div style={{ display: 'flex', justifyContent: 'center', padding: '12px 0' }}>
|
||||
<svg ref={barcodeRef} />
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
{(config?.footer || footerText) && (
|
||||
<div style={{ ...s.center, ...s.light, paddingBottom: 4 }}>{config?.footer || footerText}</div>
|
||||
)}
|
||||
{config?.returnPolicy && (
|
||||
<div style={{ ...s.center, color: '#aaa', fontSize: 10, paddingBottom: 4 }}>{config.returnPolicy}</div>
|
||||
)}
|
||||
{config?.social && (
|
||||
<div style={{ ...s.center, ...s.light, paddingBottom: 8 }}>{config.social}</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FullPageReceipt({ data, config, footerText }: { data: POSReceiptProps['data']; config?: ReceiptConfig; footerText?: string }) {
|
||||
const barcodeRef = useRef<SVGSVGElement>(null)
|
||||
const logoSrc = useStoreLogo()
|
||||
const { txn, company, location, date, subtotal, discountTotal, taxTotal, total, rounding, tendered, change, addr, phone, email } = useReceiptData(data)
|
||||
useBarcode(barcodeRef, txn.transactionNumber, { width: 2, height: 50, fontSize: 12 })
|
||||
|
||||
const f = (n: number) => `$${n.toFixed(2)}`
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
background: '#fff', color: '#000', fontFamily: 'Helvetica, Arial, sans-serif',
|
||||
width: '100%', maxWidth: 600, margin: '0 auto', fontSize: 13, lineHeight: '1.5',
|
||||
}}>
|
||||
{/* Header — company left, transaction right */}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', paddingBottom: 16 }}>
|
||||
<div>
|
||||
{logoSrc ? (
|
||||
<img src={logoSrc} alt={company.name} style={{ maxHeight: 56, maxWidth: 200, objectFit: 'contain', marginBottom: 4 }} />
|
||||
) : (
|
||||
<div style={{ fontSize: 20, fontWeight: 'bold' }}>{company.name}</div>
|
||||
)}
|
||||
{location.name !== company.name && <div style={{ color: '#555', fontSize: 12 }}>{location.name}</div>}
|
||||
{addr?.street && <div style={{ fontSize: 12 }}>{addr.street}</div>}
|
||||
{(addr?.city || addr?.state || addr?.zip) && (
|
||||
<div style={{ fontSize: 12 }}>{[addr?.city, addr?.state].filter(Boolean).join(', ')} {addr?.zip}</div>
|
||||
)}
|
||||
{phone && <div style={{ fontSize: 12 }}>{phone}</div>}
|
||||
{email && <div style={{ fontSize: 12 }}>{email}</div>}
|
||||
{config?.header && <div style={{ fontSize: 12, color: '#555', marginTop: 2 }}>{config.header}</div>}
|
||||
</div>
|
||||
<div style={{ textAlign: 'right' }}>
|
||||
<div style={{ fontSize: 16, fontWeight: 'bold' }}>{txn.transactionNumber}</div>
|
||||
<div style={{ fontSize: 12, color: '#555', textTransform: 'capitalize' }}>{txn.transactionType.replace('_', ' ')}</div>
|
||||
<div style={{ fontSize: 12, color: '#555' }}>{date.toLocaleDateString()}</div>
|
||||
<div style={{ fontSize: 12, color: '#555' }}>{date.toLocaleTimeString()}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div style={{ borderBottom: '1px solid #ddd', marginBottom: 16 }} />
|
||||
|
||||
{/* Line items table */}
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
|
||||
<thead>
|
||||
<tr style={{ background: '#f5f5f5' }}>
|
||||
<th style={{ textAlign: 'left', padding: '6px 8px', fontWeight: 600, fontSize: 11, textTransform: 'uppercase', color: '#555' }}>Item</th>
|
||||
<th style={{ textAlign: 'right', padding: '6px 8px', fontWeight: 600, fontSize: 11, textTransform: 'uppercase', color: '#555', width: 50 }}>Qty</th>
|
||||
<th style={{ textAlign: 'right', padding: '6px 8px', fontWeight: 600, fontSize: 11, textTransform: 'uppercase', color: '#555', width: 80 }}>Price</th>
|
||||
<th style={{ textAlign: 'right', padding: '6px 8px', fontWeight: 600, fontSize: 11, textTransform: 'uppercase', color: '#555', width: 80 }}>Total</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{txn.lineItems.map((item, i) => (
|
||||
<tr key={i} style={{ borderBottom: '1px solid #eee' }}>
|
||||
<td style={{ padding: '6px 8px' }}>
|
||||
{item.description}
|
||||
{parseFloat(item.discountAmount ?? '0') > 0 && (
|
||||
<div style={{ fontSize: 11, color: '#999' }}>Discount: -{f(parseFloat(item.discountAmount!))}</div>
|
||||
)}
|
||||
</td>
|
||||
<td style={{ padding: '6px 8px', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{item.qty}</td>
|
||||
<td style={{ padding: '6px 8px', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{f(parseFloat(item.unitPrice))}</td>
|
||||
<td style={{ padding: '6px 8px', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{f(parseFloat(item.lineTotal))}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{/* Totals — right aligned */}
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 12 }}>
|
||||
<div style={{ width: 220 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0' }}>
|
||||
<span>Subtotal</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{f(subtotal)}</span>
|
||||
</div>
|
||||
{discountTotal > 0 && (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0', color: '#555' }}>
|
||||
<span>Discount</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>-{f(discountTotal)}</span>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0' }}>
|
||||
<span>Tax</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{f(taxTotal)}</span>
|
||||
</div>
|
||||
{rounding !== 0 && (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0', color: '#888', fontSize: 12 }}>
|
||||
<span>Rounding</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{rounding > 0 ? '+' : ''}{rounding.toFixed(2)}</span>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ borderTop: '1px solid #ddd', marginTop: 4, paddingTop: 6, display: 'flex', justifyContent: 'space-between', fontWeight: 'bold', fontSize: 16 }}>
|
||||
<span>Total</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{f(total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment info */}
|
||||
<div style={{ marginTop: 16, padding: '12px 0', borderTop: '1px solid #ddd' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
<span>Payment Method</span>
|
||||
<span style={{ textTransform: 'capitalize', fontWeight: 500 }}>{txn.paymentMethod?.replace('_', ' ') ?? 'N/A'}</span>
|
||||
</div>
|
||||
{tendered !== null && (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', color: '#555', fontSize: 12, marginTop: 2 }}>
|
||||
<span>Tendered</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{f(tendered)}</span>
|
||||
</div>
|
||||
)}
|
||||
{change !== null && change > 0 && (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 'bold', marginTop: 2 }}>
|
||||
<span>Change</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{f(change)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Barcode */}
|
||||
<div style={{ display: 'flex', justifyContent: 'center', padding: '16px 0' }}>
|
||||
<svg ref={barcodeRef} />
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div style={{ borderTop: '1px solid #eee', paddingTop: 12, textAlign: 'center', fontSize: 11, color: '#999' }}>
|
||||
{(config?.footer || footerText) && <div>{config?.footer || footerText}</div>}
|
||||
{config?.returnPolicy && <div style={{ marginTop: 4 }}>{config.returnPolicy}</div>}
|
||||
{config?.social && <div style={{ marginTop: 4 }}>{config.social}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function printReceipt() {
|
||||
const el = document.getElementById('pos-receipt-print')
|
||||
if (!el) return
|
||||
|
||||
// Clone the receipt into an iframe for clean printing
|
||||
const iframe = document.createElement('iframe')
|
||||
iframe.style.cssText = 'position:fixed;left:-9999px;width:400px;height:800px;border:none;'
|
||||
document.body.appendChild(iframe)
|
||||
|
||||
const doc = iframe.contentDocument
|
||||
if (!doc) { document.body.removeChild(iframe); return }
|
||||
|
||||
doc.open()
|
||||
doc.write(`<!DOCTYPE html><html><head><style>body{margin:0;padding:8px;background:#fff;}</style></head><body>${el.innerHTML}</body></html>`)
|
||||
doc.close()
|
||||
|
||||
// Wait for content to render then print
|
||||
setTimeout(() => {
|
||||
try {
|
||||
iframe.contentWindow?.focus()
|
||||
iframe.contentWindow?.print()
|
||||
} catch {
|
||||
// Fallback: just use window.print
|
||||
window.print()
|
||||
}
|
||||
setTimeout(() => document.body.removeChild(iframe), 2000)
|
||||
}, 300)
|
||||
}
|
||||
|
||||
export async function downloadReceiptPDF(txnNumber?: string, format: 'thermal' | 'full' = 'thermal') {
|
||||
const el = document.getElementById('pos-receipt-print')
|
||||
if (!el) return
|
||||
|
||||
const html2pdf = (await import('html2pdf.js')).default
|
||||
|
||||
if (format === 'full') {
|
||||
html2pdf()
|
||||
.set({
|
||||
margin: [10, 10, 10, 10],
|
||||
filename: `receipt-${txnNumber ?? 'unknown'}.pdf`,
|
||||
image: { type: 'jpeg', quality: 0.95 },
|
||||
html2canvas: { scale: 2, useCORS: true },
|
||||
jsPDF: { unit: 'mm', format: 'letter', orientation: 'portrait' },
|
||||
})
|
||||
.from(el)
|
||||
.save()
|
||||
} else {
|
||||
// Thermal — dynamic height based on content
|
||||
const heightPx = el.scrollHeight + 16
|
||||
const heightMm = Math.ceil(heightPx * 0.265) + 8
|
||||
html2pdf()
|
||||
.set({
|
||||
margin: [2, 2, 2, 2],
|
||||
filename: `receipt-${txnNumber ?? 'unknown'}.pdf`,
|
||||
image: { type: 'jpeg', quality: 0.95 },
|
||||
html2canvas: { scale: 2, useCORS: true, width: 280 },
|
||||
jsPDF: { unit: 'mm', format: [72, heightMm], orientation: 'portrait' },
|
||||
})
|
||||
.from(el)
|
||||
.save()
|
||||
}
|
||||
}
|
||||
138
packages/admin/src/components/pos/pos-register.tsx
Normal file
138
packages/admin/src/components/pos/pos-register.tsx
Normal file
@@ -0,0 +1,138 @@
|
||||
import { useEffect, useRef, useCallback } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { usePOSStore } from '@/stores/pos.store'
|
||||
import { currentDrawerOptions, transactionOptions } from '@/api/pos'
|
||||
import { POSTopBar } from './pos-top-bar'
|
||||
import { POSItemPanel } from './pos-item-panel'
|
||||
import { POSCartPanel } from './pos-cart-panel'
|
||||
import { POSLockScreen } from './pos-lock-screen'
|
||||
|
||||
interface Location {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
interface AppConfigEntry {
|
||||
key: string
|
||||
value: string | null
|
||||
}
|
||||
|
||||
function locationsOptions() {
|
||||
return queryOptions({
|
||||
queryKey: ['locations'],
|
||||
queryFn: () => api.get<{ data: Location[] }>('/v1/locations'),
|
||||
})
|
||||
}
|
||||
|
||||
function configOptions(key: string) {
|
||||
return queryOptions({
|
||||
queryKey: ['config', key],
|
||||
queryFn: async (): Promise<string | null> => {
|
||||
try {
|
||||
const entry = await api.get<AppConfigEntry>(`/v1/config/${key}`)
|
||||
return entry.value
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function POSRegister() {
|
||||
const { locationId, setLocation, currentTransactionId, setDrawerSession, locked, lock, touchActivity, token } = usePOSStore()
|
||||
|
||||
// Fetch lock timeout from config
|
||||
const { data: lockTimeoutStr } = useQuery({
|
||||
...configOptions('pos_lock_timeout'),
|
||||
enabled: !!token,
|
||||
})
|
||||
const lockTimeoutMinutes = parseInt(lockTimeoutStr ?? '15') || 15
|
||||
|
||||
// Auto-lock timer
|
||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (locked || lockTimeoutMinutes === 0) {
|
||||
if (timerRef.current) clearInterval(timerRef.current)
|
||||
return
|
||||
}
|
||||
|
||||
timerRef.current = setInterval(() => {
|
||||
const { lastActivity, locked: isLocked } = usePOSStore.getState()
|
||||
if (!isLocked && Date.now() - lastActivity > lockTimeoutMinutes * 60_000) {
|
||||
lock()
|
||||
}
|
||||
}, 30_000)
|
||||
|
||||
return () => {
|
||||
if (timerRef.current) clearInterval(timerRef.current)
|
||||
}
|
||||
}, [locked, lockTimeoutMinutes, lock])
|
||||
|
||||
// Track activity on any interaction
|
||||
const handleActivity = useCallback(() => {
|
||||
if (!locked) touchActivity()
|
||||
}, [locked, touchActivity])
|
||||
|
||||
// Fetch locations
|
||||
const { data: locationsData } = useQuery({
|
||||
...locationsOptions(),
|
||||
enabled: !!token,
|
||||
})
|
||||
const locations = locationsData?.data ?? []
|
||||
|
||||
// Auto-select first location
|
||||
useEffect(() => {
|
||||
if (!locationId && locations.length > 0) {
|
||||
setLocation(locations[0].id)
|
||||
}
|
||||
}, [locationId, locations, setLocation])
|
||||
|
||||
// Fetch current drawer for selected location
|
||||
const { data: drawer } = useQuery({
|
||||
...currentDrawerOptions(locationId),
|
||||
retry: false,
|
||||
enabled: !!locationId && !!token,
|
||||
})
|
||||
|
||||
// Sync drawer session ID
|
||||
useEffect(() => {
|
||||
if (drawer?.id && drawer.status === 'open') {
|
||||
setDrawerSession(drawer.id)
|
||||
} else {
|
||||
setDrawerSession(null)
|
||||
}
|
||||
}, [drawer, setDrawerSession])
|
||||
|
||||
// Fetch current transaction
|
||||
const { data: transaction } = useQuery({
|
||||
...transactionOptions(currentTransactionId),
|
||||
enabled: !!currentTransactionId && !!token,
|
||||
})
|
||||
|
||||
return (
|
||||
<div
|
||||
className="relative flex flex-col h-full"
|
||||
onPointerDown={handleActivity}
|
||||
onKeyDown={handleActivity}
|
||||
>
|
||||
{locked && <POSLockScreen />}
|
||||
<POSTopBar
|
||||
locations={locations}
|
||||
locationId={locationId}
|
||||
onLocationChange={setLocation}
|
||||
drawer={drawer ?? null}
|
||||
/>
|
||||
<div className="flex flex-1 min-h-0">
|
||||
<div className="w-[60%] border-r border-border overflow-hidden">
|
||||
<POSItemPanel transaction={transaction ?? null} />
|
||||
</div>
|
||||
<div className="w-[40%] overflow-hidden">
|
||||
<POSCartPanel transaction={transaction ?? null} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
263
packages/admin/src/components/pos/pos-repair-dialog.tsx
Normal file
263
packages/admin/src/components/pos/pos-repair-dialog.tsx
Normal file
@@ -0,0 +1,263 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { usePOSStore } from '@/stores/pos.store'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { posMutations, posKeys } from '@/api/pos'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Search, Wrench, Plus } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
interface Account {
|
||||
id: string
|
||||
name: string
|
||||
email: string | null
|
||||
phone: string | null
|
||||
accountNumber: string | null
|
||||
}
|
||||
|
||||
interface RepairTicketSummary {
|
||||
id: string
|
||||
ticketNumber: string | null
|
||||
customerName: string
|
||||
customerPhone: string | null
|
||||
itemDescription: string | null
|
||||
estimatedCost: string | null
|
||||
status: string
|
||||
}
|
||||
|
||||
interface POSRepairDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
export function POSRepairDialog({ open, onOpenChange }: POSRepairDialogProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const { locationId, setTransaction, setAccount } = usePOSStore()
|
||||
const [search, setSearch] = useState('')
|
||||
const [tab, setTab] = useState('pickup')
|
||||
|
||||
// --- Pickup tab ---
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['pos', 'repair-tickets-ready', search],
|
||||
queryFn: () => api.get<{ data: RepairTicketSummary[] }>('/v1/repair-tickets/ready', { q: search || undefined, limit: 20 }),
|
||||
enabled: open && tab === 'pickup',
|
||||
})
|
||||
const tickets = data?.data ?? []
|
||||
|
||||
const pickupMutation = useMutation({
|
||||
mutationFn: (ticketId: string) => posMutations.createFromRepair(ticketId, locationId ?? undefined),
|
||||
onSuccess: (txn) => {
|
||||
setTransaction(txn.id)
|
||||
if (txn.accountId) {
|
||||
const ticket = tickets.find((t) => t.id === pickupMutation.variables)
|
||||
if (ticket) setAccount(txn.accountId, ticket.customerName, ticket.customerPhone)
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: posKeys.transaction(txn.id) })
|
||||
toast.success(`Repair payment loaded — ${txn.transactionNumber}`)
|
||||
close()
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
// --- New intake tab ---
|
||||
const [customerName, setCustomerName] = useState('')
|
||||
const [customerPhone, setCustomerPhone] = useState('')
|
||||
const [itemDescription, setItemDescription] = useState('')
|
||||
const [problemDescription, setProblemDescription] = useState('')
|
||||
const [estimatedCost, setEstimatedCost] = useState('')
|
||||
const [accountId, setAccountId] = useState<string | null>(null)
|
||||
const [customerSearch, setCustomerSearch] = useState('')
|
||||
const [showCustomers, setShowCustomers] = useState(false)
|
||||
|
||||
const { data: customerData } = useQuery({
|
||||
queryKey: ['pos', 'accounts', customerSearch],
|
||||
queryFn: () => api.get<{ data: Account[] }>('/v1/accounts', { q: customerSearch, limit: 10 }),
|
||||
enabled: customerSearch.length >= 2 && tab === 'intake',
|
||||
})
|
||||
const customerResults = customerData?.data ?? []
|
||||
|
||||
function selectCustomer(account: Account) {
|
||||
setAccountId(account.id)
|
||||
setCustomerName(account.name)
|
||||
setCustomerPhone(account.phone ?? '')
|
||||
setCustomerSearch('')
|
||||
setShowCustomers(false)
|
||||
}
|
||||
|
||||
function clearCustomer() {
|
||||
setAccountId(null)
|
||||
setCustomerName('')
|
||||
setCustomerPhone('')
|
||||
}
|
||||
|
||||
const intakeMutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) =>
|
||||
api.post<{ id: string; ticketNumber: string }>('/v1/repair-tickets', data),
|
||||
onSuccess: (ticket) => {
|
||||
toast.success(`Repair ticket #${ticket.ticketNumber} created`)
|
||||
close()
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
function handleIntakeSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
intakeMutation.mutate({
|
||||
customerName,
|
||||
customerPhone: customerPhone || undefined,
|
||||
accountId: accountId ?? undefined,
|
||||
itemDescription: itemDescription || undefined,
|
||||
problemDescription,
|
||||
estimatedCost: estimatedCost ? parseFloat(estimatedCost) : undefined,
|
||||
locationId: locationId ?? undefined,
|
||||
})
|
||||
}
|
||||
|
||||
function close() {
|
||||
onOpenChange(false)
|
||||
setSearch('')
|
||||
setCustomerName('')
|
||||
setCustomerPhone('')
|
||||
setItemDescription('')
|
||||
setProblemDescription('')
|
||||
setEstimatedCost('')
|
||||
setAccountId(null)
|
||||
setCustomerSearch('')
|
||||
setShowCustomers(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => { if (!o) close(); else onOpenChange(true) }}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Wrench className="h-5 w-5" />Repairs
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<Tabs value={tab} onValueChange={setTab}>
|
||||
<TabsList className="w-full">
|
||||
<TabsTrigger value="pickup" className="flex-1">Pickup</TabsTrigger>
|
||||
<TabsTrigger value="intake" className="flex-1">New Intake</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="pickup" className="mt-3 space-y-3">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search by ticket #, name, or phone..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-9"
|
||||
autoFocus={tab === 'pickup'}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="max-h-64 overflow-y-auto space-y-1">
|
||||
{isLoading ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">Loading...</p>
|
||||
) : tickets.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">
|
||||
{search ? 'No ready tickets found' : 'No tickets ready for pickup'}
|
||||
</p>
|
||||
) : (
|
||||
tickets.map((ticket) => (
|
||||
<button
|
||||
key={ticket.id}
|
||||
type="button"
|
||||
className="w-full text-left rounded-md border p-3 hover:bg-accent transition-colors"
|
||||
onClick={() => pickupMutation.mutate(ticket.id)}
|
||||
disabled={pickupMutation.isPending}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium text-sm">#{ticket.ticketNumber}</span>
|
||||
<Badge variant="outline" className="text-xs">Ready</Badge>
|
||||
</div>
|
||||
<div className="text-sm mt-0.5">{ticket.customerName}</div>
|
||||
{ticket.itemDescription && (
|
||||
<div className="text-xs text-muted-foreground mt-0.5 truncate">{ticket.itemDescription}</div>
|
||||
)}
|
||||
{ticket.estimatedCost && (
|
||||
<div className="text-xs text-muted-foreground mt-0.5">Est: ${ticket.estimatedCost}</div>
|
||||
)}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="intake" className="mt-3">
|
||||
<form onSubmit={handleIntakeSubmit} className="space-y-3">
|
||||
{/* Customer lookup */}
|
||||
<div className="relative space-y-1">
|
||||
<Label className="text-xs">Customer Lookup</Label>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search by name, phone, or email..."
|
||||
value={customerSearch}
|
||||
onChange={(e) => { setCustomerSearch(e.target.value); setShowCustomers(true) }}
|
||||
onFocus={() => customerSearch.length >= 2 && setShowCustomers(true)}
|
||||
className="pl-9 h-8 text-sm"
|
||||
/>
|
||||
</div>
|
||||
{accountId && (
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Badge variant="secondary" className="text-[10px]">Linked</Badge>
|
||||
<span>{customerName}</span>
|
||||
<button type="button" className="underline text-destructive ml-1" onClick={clearCustomer}>clear</button>
|
||||
</div>
|
||||
)}
|
||||
{showCustomers && customerSearch.length >= 2 && (
|
||||
<div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-40 overflow-auto">
|
||||
{customerResults.length === 0 ? (
|
||||
<div className="p-2 text-xs text-muted-foreground">No accounts found</div>
|
||||
) : customerResults.map((a) => (
|
||||
<button key={a.id} type="button" className="w-full text-left px-3 py-2 text-sm hover:bg-accent" onClick={() => selectCustomer(a)}>
|
||||
<div className="font-medium">{a.name}</div>
|
||||
<div className="text-xs text-muted-foreground">{[a.phone, a.email].filter(Boolean).join(' · ')}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Customer Name *</Label>
|
||||
<Input value={customerName} onChange={(e) => setCustomerName(e.target.value)} required />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Phone</Label>
|
||||
<Input value={customerPhone} onChange={(e) => setCustomerPhone(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Item Description</Label>
|
||||
<Input value={itemDescription} onChange={(e) => setItemDescription(e.target.value)} placeholder="e.g. Violin, iPhone 12, Trek bicycle" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Problem *</Label>
|
||||
<Textarea value={problemDescription} onChange={(e) => setProblemDescription(e.target.value)} rows={2} placeholder="What needs to be fixed?" required />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Estimated Cost</Label>
|
||||
<Input type="number" step="0.01" min="0" value={estimatedCost} onChange={(e) => setEstimatedCost(e.target.value)} placeholder="0.00" />
|
||||
</div>
|
||||
<Button type="submit" className="w-full gap-2" disabled={intakeMutation.isPending}>
|
||||
<Plus className="h-4 w-4" />
|
||||
{intakeMutation.isPending ? 'Creating...' : 'Create Repair Ticket'}
|
||||
</Button>
|
||||
</form>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
98
packages/admin/src/components/pos/pos-top-bar.tsx
Normal file
98
packages/admin/src/components/pos/pos-top-bar.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { usePOSStore } from '@/stores/pos.store'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { ArrowLeft, Lock, DollarSign, Receipt, FileText } from 'lucide-react'
|
||||
import type { DrawerSession } from '@/api/pos'
|
||||
import { useState } from 'react'
|
||||
import { POSDrawerDialog } from './pos-drawer-dialog'
|
||||
|
||||
interface POSTopBarProps {
|
||||
locations: { id: string; name: string }[]
|
||||
locationId: string | null
|
||||
onLocationChange: (id: string) => void
|
||||
drawer: DrawerSession | null
|
||||
}
|
||||
|
||||
export function POSTopBar({ locations, locationId, onLocationChange, drawer }: POSTopBarProps) {
|
||||
const cashier = usePOSStore((s) => s.cashier)
|
||||
const lockFn = usePOSStore((s) => s.lock)
|
||||
const receiptFormat = usePOSStore((s) => s.receiptFormat)
|
||||
const setReceiptFormat = usePOSStore((s) => s.setReceiptFormat)
|
||||
const [drawerDialogOpen, setDrawerDialogOpen] = useState(false)
|
||||
|
||||
const drawerOpen = drawer?.status === 'open'
|
||||
const isThermal = receiptFormat === 'thermal'
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="h-12 border-b border-border bg-card flex items-center justify-between px-3 shrink-0">
|
||||
{/* Left: back + location */}
|
||||
<div className="flex items-center gap-3">
|
||||
<Link to="/login" className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground">
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">Admin</span>
|
||||
</Link>
|
||||
|
||||
{locations.length > 1 ? (
|
||||
<Select value={locationId ?? ''} onValueChange={onLocationChange}>
|
||||
<SelectTrigger className="h-8 w-48 text-sm">
|
||||
<SelectValue placeholder="Select location" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{locations.map((loc) => (
|
||||
<SelectItem key={loc.id} value={loc.id}>{loc.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : locations.length === 1 ? (
|
||||
<span className="text-sm font-medium">{locations[0].name}</span>
|
||||
) : null}
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 gap-1.5 text-xs text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setReceiptFormat(isThermal ? 'full' : 'thermal')}
|
||||
title={isThermal ? 'Receipt: Thermal — click to switch to Full Page' : 'Receipt: Full Page — click to switch to Thermal'}
|
||||
>
|
||||
{isThermal ? <Receipt className="h-3.5 w-3.5" /> : <FileText className="h-3.5 w-3.5" />}
|
||||
<span className="hidden sm:inline">{isThermal ? 'Thermal' : 'Full Page'}</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Center: drawer status */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="flex items-center gap-2"
|
||||
onClick={() => setDrawerDialogOpen(true)}
|
||||
>
|
||||
<DollarSign className="h-4 w-4" />
|
||||
{drawerOpen ? (
|
||||
<Badge variant="default" className="text-xs">Drawer Open</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="text-xs">Drawer Closed</Badge>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Right: cashier + lock */}
|
||||
<div className="flex items-center gap-2">
|
||||
{cashier && (
|
||||
<span className="text-sm text-muted-foreground">{cashier.firstName}</span>
|
||||
)}
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={lockFn} title="Lock POS">
|
||||
<Lock className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<POSDrawerDialog
|
||||
open={drawerDialogOpen}
|
||||
onOpenChange={setDrawerDialogOpen}
|
||||
drawer={drawer}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
145
packages/admin/src/components/pos/pos-transactions-dialog.tsx
Normal file
145
packages/admin/src/components/pos/pos-transactions-dialog.tsx
Normal file
@@ -0,0 +1,145 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { usePOSStore } from '@/stores/pos.store'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Printer } from 'lucide-react'
|
||||
import { POSReceipt, printReceipt, downloadReceiptPDF } from './pos-receipt'
|
||||
import type { Transaction } from '@/api/pos'
|
||||
|
||||
interface ReceiptData {
|
||||
transaction: Transaction & { lineItems: { description: string; qty: number; unitPrice: string; taxAmount: string; lineTotal: string; discountAmount: string }[] }
|
||||
company: { name: string; phone: string | null; email: string | null; address: { street?: string; city?: string; state?: string; zip?: string } | null }
|
||||
location: { name: string; phone: string | null; email: string | null; address: { street?: string; city?: string; state?: string; zip?: string } | null }
|
||||
}
|
||||
|
||||
interface AppConfigEntry { key: string; value: string | null }
|
||||
|
||||
function recentTransactionsOptions(search: string) {
|
||||
return queryOptions({
|
||||
queryKey: ['pos', 'recent-transactions', search],
|
||||
queryFn: () => api.get<{ data: Transaction[] }>('/v1/transactions', {
|
||||
limit: 15,
|
||||
sort: 'created_at',
|
||||
order: 'desc',
|
||||
...(search ? { q: search } : {}),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
interface POSTransactionsDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
export function POSTransactionsDialog({ open, onOpenChange }: POSTransactionsDialogProps) {
|
||||
const [search, setSearch] = useState('')
|
||||
const [receiptTxnId, setReceiptTxnId] = useState<string | null>(null)
|
||||
|
||||
const { data: txnData } = useQuery({
|
||||
...recentTransactionsOptions(search),
|
||||
enabled: open,
|
||||
})
|
||||
const transactions = txnData?.data ?? []
|
||||
|
||||
// Fetch receipt for selected transaction
|
||||
const { data: receiptData } = useQuery({
|
||||
queryKey: ['pos', 'receipt', receiptTxnId],
|
||||
queryFn: () => api.get<ReceiptData>(`/v1/transactions/${receiptTxnId}/receipt`),
|
||||
enabled: !!receiptTxnId,
|
||||
})
|
||||
|
||||
const { data: configData } = useQuery({
|
||||
queryKey: ['config'],
|
||||
queryFn: () => api.get<{ data: AppConfigEntry[] }>('/v1/config'),
|
||||
enabled: !!receiptTxnId,
|
||||
})
|
||||
const receiptFormat = usePOSStore((s) => s.receiptFormat)
|
||||
const receiptConfig = {
|
||||
header: configData?.data?.find((c) => c.key === 'receipt_header')?.value || undefined,
|
||||
footer: configData?.data?.find((c) => c.key === 'receipt_footer')?.value || undefined,
|
||||
returnPolicy: configData?.data?.find((c) => c.key === 'receipt_return_policy')?.value || undefined,
|
||||
social: configData?.data?.find((c) => c.key === 'receipt_social')?.value || undefined,
|
||||
}
|
||||
|
||||
// Receipt view
|
||||
if (receiptTxnId && receiptData) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className={`${receiptFormat === 'full' ? 'max-w-2xl' : 'max-w-sm'} max-h-[90vh] overflow-y-auto`}>
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<Button variant="ghost" size="sm" onClick={() => setReceiptTxnId(null)}>Back</Button>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => downloadReceiptPDF(receiptData.transaction.transactionNumber, receiptFormat)}>
|
||||
Save PDF
|
||||
</Button>
|
||||
<Button size="sm" onClick={printReceipt} className="gap-2">
|
||||
<Printer className="h-4 w-4" />Print
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="pos-receipt-print">
|
||||
<POSReceipt data={receiptData} size={receiptFormat} config={receiptConfig} />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md max-h-[80vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Recent Transactions</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Search by transaction number..."
|
||||
className="h-10"
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{transactions.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-8">No transactions found</p>
|
||||
) : (
|
||||
<div className="divide-y divide-border">
|
||||
{transactions.map((txn) => (
|
||||
<button
|
||||
key={txn.id}
|
||||
onClick={() => setReceiptTxnId(txn.id)}
|
||||
className="w-full text-left py-2.5 px-1 hover:bg-accent/50 rounded transition-colors"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-mono">{txn.transactionNumber}</span>
|
||||
<span className="text-sm font-semibold">${parseFloat(txn.total).toFixed(2)}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-0.5">
|
||||
<Badge
|
||||
variant={txn.status === 'completed' ? 'default' : txn.status === 'voided' ? 'destructive' : 'outline'}
|
||||
className="text-[10px]"
|
||||
>
|
||||
{txn.status}
|
||||
</Badge>
|
||||
{txn.paymentMethod && (
|
||||
<span className="text-xs text-muted-foreground">{txn.paymentMethod.replace('_', ' ')}</span>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground ml-auto">
|
||||
{new Date(txn.completedAt ?? txn.createdAt).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -85,8 +85,9 @@ export function generateRepairPdf({ ticket, lineItems, notes, includeNotes, comp
|
||||
doc.text(dateInfo, 14, y)
|
||||
y += 8
|
||||
|
||||
// Line items table
|
||||
if (lineItems.length > 0) {
|
||||
// Line items table (exclude consumables — internal only)
|
||||
const billableItems = lineItems.filter((i) => i.itemType !== 'consumable')
|
||||
if (billableItems.length > 0) {
|
||||
doc.setDrawColor(200)
|
||||
doc.line(14, y, 196, y)
|
||||
y += 6
|
||||
@@ -109,7 +110,7 @@ export function generateRepairPdf({ ticket, lineItems, notes, includeNotes, comp
|
||||
|
||||
// Table rows
|
||||
doc.setFont('helvetica', 'normal')
|
||||
for (const item of lineItems) {
|
||||
for (const item of billableItems) {
|
||||
if (y > 270) { doc.addPage(); y = 20 }
|
||||
doc.text(item.itemType.replace('_', ' '), 16, y)
|
||||
const descLines = doc.splitTextToSize(item.description, 85)
|
||||
@@ -127,7 +128,7 @@ export function generateRepairPdf({ ticket, lineItems, notes, includeNotes, comp
|
||||
y += 5
|
||||
doc.setFont('helvetica', 'bold')
|
||||
doc.setFontSize(10)
|
||||
const total = lineItems.reduce((sum, i) => sum + parseFloat(i.totalPrice), 0)
|
||||
const total = billableItems.reduce((sum, i) => sum + parseFloat(i.totalPrice), 0)
|
||||
doc.text('Total:', 155, y, { align: 'right' })
|
||||
doc.text(`$${total.toFixed(2)}`, 190, y, { align: 'right' })
|
||||
y += 4
|
||||
|
||||
66
packages/admin/src/components/ui/alert.tsx
Normal file
66
packages/admin/src/components/ui/alert.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const alertVariants = cva(
|
||||
"relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-card text-card-foreground",
|
||||
destructive:
|
||||
"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Alert({
|
||||
className,
|
||||
variant,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert"
|
||||
role="alert"
|
||||
className={cn(alertVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-title"
|
||||
className={cn(
|
||||
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-description"
|
||||
className={cn(
|
||||
"col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription }
|
||||
46
packages/admin/src/components/ui/popover.tsx
Normal file
46
packages/admin/src/components/ui/popover.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import * as React from "react"
|
||||
import { Popover as PopoverPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||
}
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
|
||||
@@ -23,12 +23,13 @@ export function usePagination() {
|
||||
|
||||
function setParams(updates: Partial<PaginationSearch>) {
|
||||
navigate({
|
||||
search: ((prev: PaginationSearch) => ({
|
||||
// @ts-expect-error: navigate without a route context resolves search as never; safe here since we use strict:false
|
||||
search: (prev: any) => ({
|
||||
...prev,
|
||||
...updates,
|
||||
// Reset to page 1 when search or sort changes
|
||||
page: updates.q !== undefined || updates.sort !== undefined ? 1 : (updates.page ?? prev.page),
|
||||
})) as any,
|
||||
page: updates.q !== undefined || updates.sort !== undefined ? 1 : (updates.page ?? (prev as PaginationSearch).page),
|
||||
}),
|
||||
replace: true,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import { usePOSStore } from '@/stores/pos.store'
|
||||
|
||||
class ApiError extends Error {
|
||||
statusCode: number
|
||||
@@ -13,7 +14,8 @@ class ApiError extends Error {
|
||||
}
|
||||
|
||||
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||
const { token } = useAuthStore.getState()
|
||||
// Use POS token if available (POS screen), otherwise admin token
|
||||
const token = usePOSStore.getState().token ?? useAuthStore.getState().token
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
|
||||
@@ -32,9 +34,12 @@ async function request<T>(method: string, path: string, body?: unknown): Promise
|
||||
})
|
||||
|
||||
if (res.status === 401) {
|
||||
useAuthStore.getState().logout()
|
||||
// Don't use window.location — that causes a full reload and flash
|
||||
// The router's beforeLoad guard will redirect to /login on next navigation
|
||||
// On POS, lock the screen instead of logging out admin
|
||||
if (usePOSStore.getState().token) {
|
||||
usePOSStore.getState().lock()
|
||||
} else {
|
||||
useAuthStore.getState().logout()
|
||||
}
|
||||
throw new ApiError('Unauthorized', 401)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as ResetPasswordRouteImport } from './routes/reset-password'
|
||||
import { Route as PosRouteImport } from './routes/pos'
|
||||
import { Route as LoginRouteImport } from './routes/login'
|
||||
import { Route as AuthenticatedRouteImport } from './routes/_authenticated'
|
||||
import { Route as AuthenticatedIndexRouteImport } from './routes/_authenticated/index'
|
||||
@@ -26,6 +28,7 @@ import { Route as AuthenticatedFilesIndexRouteImport } from './routes/_authentic
|
||||
import { Route as AuthenticatedAccountsIndexRouteImport } from './routes/_authenticated/accounts/index'
|
||||
import { Route as AuthenticatedRolesNewRouteImport } from './routes/_authenticated/roles/new'
|
||||
import { Route as AuthenticatedRolesRoleIdRouteImport } from './routes/_authenticated/roles/$roleId'
|
||||
import { Route as AuthenticatedReportsDailyRouteImport } from './routes/_authenticated/reports/daily'
|
||||
import { Route as AuthenticatedRepairsTemplatesRouteImport } from './routes/_authenticated/repairs/templates'
|
||||
import { Route as AuthenticatedRepairsNewRouteImport } from './routes/_authenticated/repairs/new'
|
||||
import { Route as AuthenticatedRepairsTicketIdRouteImport } from './routes/_authenticated/repairs/$ticketId'
|
||||
@@ -56,6 +59,16 @@ import { Route as AuthenticatedAccountsAccountIdMembersRouteImport } from './rou
|
||||
import { Route as AuthenticatedAccountsAccountIdEnrollmentsRouteImport } from './routes/_authenticated/accounts/$accountId/enrollments'
|
||||
import { Route as AuthenticatedLessonsScheduleInstructorsInstructorIdRouteImport } from './routes/_authenticated/lessons/schedule/instructors/$instructorId'
|
||||
|
||||
const ResetPasswordRoute = ResetPasswordRouteImport.update({
|
||||
id: '/reset-password',
|
||||
path: '/reset-password',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const PosRoute = PosRouteImport.update({
|
||||
id: '/pos',
|
||||
path: '/pos',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const LoginRoute = LoginRouteImport.update({
|
||||
id: '/login',
|
||||
path: '/login',
|
||||
@@ -146,6 +159,12 @@ const AuthenticatedRolesRoleIdRoute =
|
||||
path: '/roles/$roleId',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedReportsDailyRoute =
|
||||
AuthenticatedReportsDailyRouteImport.update({
|
||||
id: '/reports/daily',
|
||||
path: '/reports/daily',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedRepairsTemplatesRoute =
|
||||
AuthenticatedRepairsTemplatesRouteImport.update({
|
||||
id: '/repairs/templates',
|
||||
@@ -323,6 +342,8 @@ const AuthenticatedLessonsScheduleInstructorsInstructorIdRoute =
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof AuthenticatedIndexRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/pos': typeof PosRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/help': typeof AuthenticatedHelpRoute
|
||||
'/profile': typeof AuthenticatedProfileRoute
|
||||
'/settings': typeof AuthenticatedSettingsRoute
|
||||
@@ -337,6 +358,7 @@ export interface FileRoutesByFullPath {
|
||||
'/repairs/$ticketId': typeof AuthenticatedRepairsTicketIdRoute
|
||||
'/repairs/new': typeof AuthenticatedRepairsNewRoute
|
||||
'/repairs/templates': typeof AuthenticatedRepairsTemplatesRoute
|
||||
'/reports/daily': typeof AuthenticatedReportsDailyRoute
|
||||
'/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
|
||||
'/roles/new': typeof AuthenticatedRolesNewRoute
|
||||
'/accounts/': typeof AuthenticatedAccountsIndexRoute
|
||||
@@ -369,6 +391,8 @@ export interface FileRoutesByFullPath {
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/login': typeof LoginRoute
|
||||
'/pos': typeof PosRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/help': typeof AuthenticatedHelpRoute
|
||||
'/profile': typeof AuthenticatedProfileRoute
|
||||
'/settings': typeof AuthenticatedSettingsRoute
|
||||
@@ -383,6 +407,7 @@ export interface FileRoutesByTo {
|
||||
'/repairs/$ticketId': typeof AuthenticatedRepairsTicketIdRoute
|
||||
'/repairs/new': typeof AuthenticatedRepairsNewRoute
|
||||
'/repairs/templates': typeof AuthenticatedRepairsTemplatesRoute
|
||||
'/reports/daily': typeof AuthenticatedReportsDailyRoute
|
||||
'/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
|
||||
'/roles/new': typeof AuthenticatedRolesNewRoute
|
||||
'/accounts': typeof AuthenticatedAccountsIndexRoute
|
||||
@@ -417,6 +442,8 @@ export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/_authenticated': typeof AuthenticatedRouteWithChildren
|
||||
'/login': typeof LoginRoute
|
||||
'/pos': typeof PosRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/_authenticated/help': typeof AuthenticatedHelpRoute
|
||||
'/_authenticated/profile': typeof AuthenticatedProfileRoute
|
||||
'/_authenticated/settings': typeof AuthenticatedSettingsRoute
|
||||
@@ -432,6 +459,7 @@ export interface FileRoutesById {
|
||||
'/_authenticated/repairs/$ticketId': typeof AuthenticatedRepairsTicketIdRoute
|
||||
'/_authenticated/repairs/new': typeof AuthenticatedRepairsNewRoute
|
||||
'/_authenticated/repairs/templates': typeof AuthenticatedRepairsTemplatesRoute
|
||||
'/_authenticated/reports/daily': typeof AuthenticatedReportsDailyRoute
|
||||
'/_authenticated/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
|
||||
'/_authenticated/roles/new': typeof AuthenticatedRolesNewRoute
|
||||
'/_authenticated/accounts/': typeof AuthenticatedAccountsIndexRoute
|
||||
@@ -467,6 +495,8 @@ export interface FileRouteTypes {
|
||||
fullPaths:
|
||||
| '/'
|
||||
| '/login'
|
||||
| '/pos'
|
||||
| '/reset-password'
|
||||
| '/help'
|
||||
| '/profile'
|
||||
| '/settings'
|
||||
@@ -481,6 +511,7 @@ export interface FileRouteTypes {
|
||||
| '/repairs/$ticketId'
|
||||
| '/repairs/new'
|
||||
| '/repairs/templates'
|
||||
| '/reports/daily'
|
||||
| '/roles/$roleId'
|
||||
| '/roles/new'
|
||||
| '/accounts/'
|
||||
@@ -513,6 +544,8 @@ export interface FileRouteTypes {
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to:
|
||||
| '/login'
|
||||
| '/pos'
|
||||
| '/reset-password'
|
||||
| '/help'
|
||||
| '/profile'
|
||||
| '/settings'
|
||||
@@ -527,6 +560,7 @@ export interface FileRouteTypes {
|
||||
| '/repairs/$ticketId'
|
||||
| '/repairs/new'
|
||||
| '/repairs/templates'
|
||||
| '/reports/daily'
|
||||
| '/roles/$roleId'
|
||||
| '/roles/new'
|
||||
| '/accounts'
|
||||
@@ -560,6 +594,8 @@ export interface FileRouteTypes {
|
||||
| '__root__'
|
||||
| '/_authenticated'
|
||||
| '/login'
|
||||
| '/pos'
|
||||
| '/reset-password'
|
||||
| '/_authenticated/help'
|
||||
| '/_authenticated/profile'
|
||||
| '/_authenticated/settings'
|
||||
@@ -575,6 +611,7 @@ export interface FileRouteTypes {
|
||||
| '/_authenticated/repairs/$ticketId'
|
||||
| '/_authenticated/repairs/new'
|
||||
| '/_authenticated/repairs/templates'
|
||||
| '/_authenticated/reports/daily'
|
||||
| '/_authenticated/roles/$roleId'
|
||||
| '/_authenticated/roles/new'
|
||||
| '/_authenticated/accounts/'
|
||||
@@ -609,10 +646,26 @@ export interface FileRouteTypes {
|
||||
export interface RootRouteChildren {
|
||||
AuthenticatedRoute: typeof AuthenticatedRouteWithChildren
|
||||
LoginRoute: typeof LoginRoute
|
||||
PosRoute: typeof PosRoute
|
||||
ResetPasswordRoute: typeof ResetPasswordRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface FileRoutesByPath {
|
||||
'/reset-password': {
|
||||
id: '/reset-password'
|
||||
path: '/reset-password'
|
||||
fullPath: '/reset-password'
|
||||
preLoaderRoute: typeof ResetPasswordRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/pos': {
|
||||
id: '/pos'
|
||||
path: '/pos'
|
||||
fullPath: '/pos'
|
||||
preLoaderRoute: typeof PosRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/login': {
|
||||
id: '/login'
|
||||
path: '/login'
|
||||
@@ -732,6 +785,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AuthenticatedRolesRoleIdRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/reports/daily': {
|
||||
id: '/_authenticated/reports/daily'
|
||||
path: '/reports/daily'
|
||||
fullPath: '/reports/daily'
|
||||
preLoaderRoute: typeof AuthenticatedReportsDailyRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/repairs/templates': {
|
||||
id: '/_authenticated/repairs/templates'
|
||||
path: '/repairs/templates'
|
||||
@@ -984,6 +1044,7 @@ interface AuthenticatedRouteChildren {
|
||||
AuthenticatedRepairsTicketIdRoute: typeof AuthenticatedRepairsTicketIdRoute
|
||||
AuthenticatedRepairsNewRoute: typeof AuthenticatedRepairsNewRoute
|
||||
AuthenticatedRepairsTemplatesRoute: typeof AuthenticatedRepairsTemplatesRoute
|
||||
AuthenticatedReportsDailyRoute: typeof AuthenticatedReportsDailyRoute
|
||||
AuthenticatedRolesRoleIdRoute: typeof AuthenticatedRolesRoleIdRoute
|
||||
AuthenticatedRolesNewRoute: typeof AuthenticatedRolesNewRoute
|
||||
AuthenticatedAccountsIndexRoute: typeof AuthenticatedAccountsIndexRoute
|
||||
@@ -1027,6 +1088,7 @@ const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
||||
AuthenticatedRepairsTicketIdRoute: AuthenticatedRepairsTicketIdRoute,
|
||||
AuthenticatedRepairsNewRoute: AuthenticatedRepairsNewRoute,
|
||||
AuthenticatedRepairsTemplatesRoute: AuthenticatedRepairsTemplatesRoute,
|
||||
AuthenticatedReportsDailyRoute: AuthenticatedReportsDailyRoute,
|
||||
AuthenticatedRolesRoleIdRoute: AuthenticatedRolesRoleIdRoute,
|
||||
AuthenticatedRolesNewRoute: AuthenticatedRolesNewRoute,
|
||||
AuthenticatedAccountsIndexRoute: AuthenticatedAccountsIndexRoute,
|
||||
@@ -1069,6 +1131,8 @@ const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren(
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
AuthenticatedRoute: AuthenticatedRouteWithChildren,
|
||||
LoginRoute: LoginRoute,
|
||||
PosRoute: PosRoute,
|
||||
ResetPasswordRoute: ResetPasswordRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
._addFileChildren(rootRouteChildren)
|
||||
|
||||
@@ -1,11 +1,29 @@
|
||||
import { createRootRoute, Outlet } from '@tanstack/react-router'
|
||||
import { Toaster } from 'sonner'
|
||||
import { useEffect } from 'react'
|
||||
|
||||
export const Route = createRootRoute({
|
||||
component: RootLayout,
|
||||
})
|
||||
|
||||
function RootLayout() {
|
||||
useEffect(() => {
|
||||
fetch('/v1/store/branding')
|
||||
.then((r) => r.ok ? r.json() : null)
|
||||
.then((data: { name: string | null; hasLogo: boolean } | null) => {
|
||||
if (!data) return
|
||||
if (data.name) document.title = data.name
|
||||
if (data.hasLogo) {
|
||||
const link = document.querySelector<HTMLLinkElement>('link[rel="icon"]')
|
||||
?? document.createElement('link')
|
||||
link.rel = 'icon'
|
||||
link.href = '/v1/store/logo'
|
||||
document.head.appendChild(link)
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<>
|
||||
<Outlet />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createFileRoute, Outlet, Link, redirect, useRouter } from '@tanstack/react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query'
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { api } from '@/lib/api-client'
|
||||
@@ -8,7 +8,10 @@ import { myPermissionsOptions } from '@/api/rbac'
|
||||
import { moduleListOptions } from '@/api/modules'
|
||||
import { Avatar } from '@/components/shared/avatar-upload'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Users, UserRound, HelpCircle, Shield, UserCog, LogOut, User, Wrench, Package, ClipboardList, FolderOpen, KeyRound, Settings, PanelLeftClose, PanelLeft, CalendarDays, GraduationCap, CalendarRange, BookOpen, BookMarked, Package2, Tag, Truck } from 'lucide-react'
|
||||
import { Users, UserRound, HelpCircle, Shield, UserCog, LogOut, User, Wrench, Package, ClipboardList, FolderOpen, KeyRound, Settings, PanelLeftClose, PanelLeft, CalendarDays, GraduationCap, CalendarRange, BookOpen, BookMarked, Package2, Tag, Truck, ShoppingCart } from 'lucide-react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated')({
|
||||
beforeLoad: () => {
|
||||
@@ -67,7 +70,7 @@ function NavLink({ to, icon, label, collapsed }: { to: string; icon: React.React
|
||||
return (
|
||||
<Link
|
||||
to={to as '/accounts'}
|
||||
search={{} as any}
|
||||
search={{ page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const }}
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground' }}
|
||||
title={collapsed ? label : undefined}
|
||||
@@ -104,6 +107,58 @@ function NavGroup({ label, children, collapsed }: { label: string; children: Rea
|
||||
)
|
||||
}
|
||||
|
||||
function SetPinModal() {
|
||||
const queryClient = useQueryClient()
|
||||
const [pin, setPin] = useState('')
|
||||
const [confirmPin, setConfirmPin] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const setPinMutation = useMutation({
|
||||
mutationFn: () => api.post('/v1/auth/set-pin', { pin }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
|
||||
toast.success('PIN set successfully')
|
||||
},
|
||||
onError: (err) => setError(err.message),
|
||||
})
|
||||
|
||||
function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
if (pin.length < 4 || pin.length > 6) { setError('PIN must be 4-6 digits'); return }
|
||||
if (!/^\d+$/.test(pin)) { setError('PIN must be digits only'); return }
|
||||
if (pin !== confirmPin) { setError('PINs do not match'); return }
|
||||
setPinMutation.mutate()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
|
||||
<div className="w-full max-w-sm rounded-xl border bg-card p-6 shadow-xl">
|
||||
<h2 className="text-lg font-semibold mb-1">Set your POS PIN</h2>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
A PIN is required to use the Point of Sale. Choose a 4-6 digit PIN you'll use to unlock the terminal.
|
||||
</p>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>PIN</Label>
|
||||
<Input type="password" inputMode="numeric" maxLength={6} value={pin} onChange={(e) => setPin(e.target.value)} placeholder="****" autoFocus />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Confirm PIN</Label>
|
||||
<Input type="password" inputMode="numeric" maxLength={6} value={confirmPin} onChange={(e) => setConfirmPin(e.target.value)} placeholder="****" />
|
||||
</div>
|
||||
</div>
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
<Button type="submit" className="w-full" disabled={setPinMutation.isPending}>
|
||||
{setPinMutation.isPending ? 'Setting...' : 'Set PIN'}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AuthenticatedLayout() {
|
||||
const router = useRouter()
|
||||
const user = useAuthStore((s) => s.user)
|
||||
@@ -112,6 +167,13 @@ function AuthenticatedLayout() {
|
||||
const setPermissions = useAuthStore((s) => s.setPermissions)
|
||||
const permissionsLoaded = useAuthStore((s) => s.permissionsLoaded)
|
||||
|
||||
// Fetch profile for PIN warning
|
||||
const { data: profile } = useQuery(queryOptions({
|
||||
queryKey: ['auth', 'me'],
|
||||
queryFn: () => api.get<{ hasPin: boolean }>('/v1/auth/me'),
|
||||
enabled: !!useAuthStore.getState().token,
|
||||
}))
|
||||
|
||||
// Fetch permissions on mount
|
||||
const { data: permData } = useQuery({
|
||||
...myPermissionsOptions(),
|
||||
@@ -145,6 +207,7 @@ function AuthenticatedLayout() {
|
||||
const canViewLessons = !permissionsLoaded || hasPermission('lessons.view')
|
||||
const canViewInventory = !permissionsLoaded || hasPermission('inventory.view')
|
||||
const canViewUsers = !permissionsLoaded || hasPermission('users.view')
|
||||
const canViewPOS = !permissionsLoaded || hasPermission('pos.view')
|
||||
|
||||
const [collapsed, setCollapsed] = useState(false)
|
||||
|
||||
@@ -173,6 +236,18 @@ function AuthenticatedLayout() {
|
||||
|
||||
{/* Scrollable nav links */}
|
||||
<div className="flex-1 overflow-y-auto px-2 space-y-1 scrollbar-thin">
|
||||
{isModuleEnabled('pos') && canViewPOS && (
|
||||
<div className="mb-2">
|
||||
<button
|
||||
onClick={() => { logout(); router.navigate({ to: '/pos' }) }}
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent w-full"
|
||||
title={collapsed ? 'Point of Sale' : undefined}
|
||||
>
|
||||
<ShoppingCart className="h-4 w-4" />
|
||||
{!collapsed && 'Point of Sale'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{canViewAccounts && (
|
||||
<NavGroup label="Customers" collapsed={collapsed}>
|
||||
<NavLink to="/accounts" icon={<Users className="h-4 w-4" />} label="Accounts" collapsed={collapsed} />
|
||||
@@ -250,6 +325,7 @@ function AuthenticatedLayout() {
|
||||
</div>
|
||||
</nav>
|
||||
<main className="flex-1 p-6 min-h-screen">
|
||||
{profile && !profile.hasPin && <SetPinModal />}
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -20,7 +20,7 @@ function statusBadge(status: string) {
|
||||
}
|
||||
|
||||
const columns: Column<Enrollment & { memberName?: string }>[] = [
|
||||
{ key: 'member_name', header: 'Member', sortable: true, render: (e) => <span className="font-medium">{(e as any).memberName ?? e.memberId}</span> },
|
||||
{ key: 'member_name', header: 'Member', sortable: true, render: (e) => <span className="font-medium">{e.memberName ?? e.memberId}</span> },
|
||||
{ key: 'status', header: 'Status', sortable: true, render: (e) => statusBadge(e.status) },
|
||||
{ key: 'start_date', header: 'Start', sortable: true, render: (e) => <>{new Date(e.startDate + 'T00:00:00').toLocaleDateString()}</> },
|
||||
{ key: 'rate', header: 'Rate', render: (e) => <>{e.rate ? `$${e.rate}${e.billingInterval ? ` / ${e.billingInterval} ${e.billingUnit}` : ''}` : <span className="text-muted-foreground">—</span>}</> },
|
||||
@@ -41,7 +41,7 @@ function AccountEnrollmentsTab() {
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-muted-foreground">{data?.pagination.total ?? 0} enrollment(s)</p>
|
||||
{hasPermission('lessons.edit') && (
|
||||
<Button size="sm" onClick={() => navigate({ to: '/lessons/enrollments/new', search: {} as any })}>
|
||||
<Button size="sm" onClick={() => navigate({ to: '/lessons/enrollments/new', search: { memberId: undefined, accountId: undefined } })}>
|
||||
<Plus className="h-4 w-4 mr-1" />Enroll a Member
|
||||
</Button>
|
||||
)}
|
||||
@@ -55,7 +55,7 @@ function AccountEnrollmentsTab() {
|
||||
total={data?.data?.length ?? 0}
|
||||
onPageChange={() => {}}
|
||||
onSort={() => {}}
|
||||
onRowClick={(e) => navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId: e.id }, search: {} as any })}
|
||||
onRowClick={(e) => navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId: e.id }, search: { tab: 'details' } })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -281,7 +281,7 @@ function MembersTab() {
|
||||
<DropdownMenuItem onClick={() => navigate({
|
||||
to: '/members/$memberId',
|
||||
params: { memberId: m.id },
|
||||
search: {} as any,
|
||||
search: { tab: 'details' },
|
||||
})}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit
|
||||
|
||||
@@ -92,7 +92,7 @@ function FileManagerPage() {
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}))
|
||||
toast.error(`Upload failed: ${(err as any).error?.message ?? file.name}`)
|
||||
toast.error(`Upload failed: ${(err as { error?: { message?: string } }).error?.message ?? file.name}`)
|
||||
}
|
||||
} catch {
|
||||
toast.error(`Upload failed: ${file.name}`)
|
||||
|
||||
@@ -2,6 +2,6 @@ import { createFileRoute, redirect } from '@tanstack/react-router'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/')({
|
||||
beforeLoad: () => {
|
||||
throw redirect({ to: '/accounts', search: {} as any })
|
||||
throw redirect({ to: '/accounts', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -159,7 +159,7 @@ function ProductDetailPage() {
|
||||
})
|
||||
|
||||
function setTab(t: string) {
|
||||
navigate({ to: '/inventory/$productId', params: { productId }, search: { tab: t } as any })
|
||||
navigate({ to: '/inventory/$productId', params: { productId }, search: { tab: t } })
|
||||
}
|
||||
|
||||
function handleQtySave() {
|
||||
@@ -192,7 +192,7 @@ function ProductDetailPage() {
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/inventory', search: {} as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/inventory', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const, categoryId: undefined, isActive: undefined, type: undefined, lowStock: undefined } })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="min-w-0">
|
||||
@@ -507,12 +507,12 @@ function SuppliersTab({
|
||||
setAddOpen: (v: boolean) => void
|
||||
editTarget: ProductSupplier | null
|
||||
setEditTarget: (v: ProductSupplier | null) => void
|
||||
addMutation: any
|
||||
updateMutation: any
|
||||
removeMutation: any
|
||||
addMutation: { mutate: (data: Record<string, unknown>) => void; isPending: boolean }
|
||||
updateMutation: { mutate: (args: { id: string; data: Record<string, unknown> }) => void; isPending: boolean }
|
||||
removeMutation: { mutate: (id: string) => void; isPending: boolean }
|
||||
canEdit: boolean
|
||||
}) {
|
||||
const { data: allSuppliersData } = useQuery(supplierListOptions({ page: 1, limit: 500, order: 'asc', sort: 'name' } as any))
|
||||
const { data: allSuppliersData } = useQuery(supplierListOptions({ page: 1, limit: 500, order: 'asc', sort: 'name' }))
|
||||
const allSuppliers = allSuppliersData?.data ?? []
|
||||
const linkedIds = new Set(linkedSuppliers.map((s) => s.supplierId))
|
||||
const availableSuppliers = allSuppliers.filter((s) => !linkedIds.has(s.id))
|
||||
|
||||
@@ -71,7 +71,7 @@ function InventoryPage() {
|
||||
queryClient.invalidateQueries({ queryKey: productKeys.all })
|
||||
toast.success('Product created')
|
||||
setCreateOpen(false)
|
||||
navigate({ to: '/inventory/$productId', params: { productId: product.id }, search: {} as any })
|
||||
navigate({ to: '/inventory/$productId', params: { productId: product.id }, search: { tab: 'details' } })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
@@ -83,23 +83,23 @@ function InventoryPage() {
|
||||
|
||||
function handleCategoryChange(v: string) {
|
||||
setCategoryFilter(v === 'all' ? '' : v)
|
||||
navigate({ to: '/inventory', search: { ...search, categoryId: v === 'all' ? undefined : v, page: 1 } as any })
|
||||
navigate({ to: '/inventory', search: { ...search, categoryId: v === 'all' ? undefined : v, page: 1 } })
|
||||
}
|
||||
|
||||
function handleActiveChange(v: string) {
|
||||
setActiveFilter(v === 'all' ? '' : v)
|
||||
navigate({ to: '/inventory', search: { ...search, isActive: v === 'all' ? undefined : v, page: 1 } as any })
|
||||
navigate({ to: '/inventory', search: { ...search, isActive: v === 'all' ? undefined : v, page: 1 } })
|
||||
}
|
||||
|
||||
function handleTypeChange(v: string) {
|
||||
setTypeFilter(v === 'all' ? '' : v)
|
||||
navigate({ to: '/inventory', search: { ...search, type: v === 'all' ? undefined : v, page: 1 } as any })
|
||||
navigate({ to: '/inventory', search: { ...search, type: v === 'all' ? undefined : v, page: 1 } })
|
||||
}
|
||||
|
||||
function handleLowStockChange(v: string) {
|
||||
const on = v === 'true'
|
||||
setLowStockFilter(on)
|
||||
navigate({ to: '/inventory', search: { ...search, lowStock: on ? 'true' : undefined, page: 1 } as any })
|
||||
navigate({ to: '/inventory', search: { ...search, lowStock: on ? 'true' : undefined, page: 1 } })
|
||||
}
|
||||
|
||||
const columns: Column<Product>[] = [
|
||||
@@ -246,7 +246,7 @@ function InventoryPage() {
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
onRowClick={(p) => navigate({ to: '/inventory/$productId', params: { productId: p.id }, search: {} as any })}
|
||||
onRowClick={(p) => navigate({ to: '/inventory/$productId', params: { productId: p.id }, search: { tab: 'details' } })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -130,7 +130,7 @@ function SuppliersPage() {
|
||||
<DialogContent>
|
||||
<DialogHeader><DialogTitle>New Supplier</DialogTitle></DialogHeader>
|
||||
<SupplierForm
|
||||
onSubmit={supplierMutations.create.bind(null) as any}
|
||||
onSubmit={(data) => { createMutation.mutate(data) }}
|
||||
loading={createMutation.isPending}
|
||||
/>
|
||||
</DialogContent>
|
||||
|
||||
@@ -21,7 +21,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
|
||||
import { ArrowLeft, RefreshCw } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import type { LessonSession, LessonPlan, LessonPlanTemplate } from '@/types/lesson'
|
||||
import type { Enrollment, LessonSession, LessonPlan, LessonPlanTemplate } from '@/types/lesson'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/lessons/enrollments/$enrollmentId')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
@@ -81,7 +81,7 @@ function EnrollmentDetailPage() {
|
||||
const tab = search.tab
|
||||
|
||||
function setTab(t: string) {
|
||||
navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId }, search: { tab: t } as any })
|
||||
navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId }, search: { tab: t } })
|
||||
}
|
||||
|
||||
const { data: enrollment, isLoading } = useQuery(enrollmentDetailOptions(enrollmentId))
|
||||
@@ -131,7 +131,7 @@ function EnrollmentDetailPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/enrollments', search: {} as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/enrollments', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'desc' as const, status: undefined, instructorId: undefined } })}>
|
||||
<ArrowLeft className="h-4 w-4 mr-1" />Back
|
||||
</Button>
|
||||
<div className="flex-1">
|
||||
@@ -193,7 +193,17 @@ const BILLING_UNITS = [
|
||||
function DetailsTab({
|
||||
enrollment, slotLabel, lessonTypeName, instructorName,
|
||||
canEdit, onSave, saving, onStatusChange, statusChanging,
|
||||
}: any) {
|
||||
}: {
|
||||
enrollment: Enrollment
|
||||
slotLabel: string
|
||||
lessonTypeName: string | undefined
|
||||
instructorName: string | undefined
|
||||
canEdit: boolean
|
||||
onSave: (data: Record<string, unknown>) => void
|
||||
saving: boolean
|
||||
onStatusChange: (status: string) => void
|
||||
statusChanging: boolean
|
||||
}) {
|
||||
const [rate, setRate] = useState(enrollment.rate ?? '')
|
||||
const [billingInterval, setBillingInterval] = useState(String(enrollment.billingInterval ?? 1))
|
||||
const [billingUnit, setBillingUnit] = useState(enrollment.billingUnit ?? 'month')
|
||||
@@ -255,7 +265,7 @@ function DetailsTab({
|
||||
onChange={(e) => setBillingInterval(e.target.value)}
|
||||
className="w-20"
|
||||
/>
|
||||
<Select value={billingUnit} onValueChange={setBillingUnit}>
|
||||
<Select value={billingUnit} onValueChange={(v) => setBillingUnit(v as typeof billingUnit)}>
|
||||
<SelectTrigger className="w-36"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILLING_UNITS.map((u) => (
|
||||
@@ -334,7 +344,7 @@ function SessionsTab({ enrollmentId, onGenerate, generating }: { enrollmentId: s
|
||||
total={data?.data?.length ?? 0}
|
||||
onPageChange={() => {}}
|
||||
onSort={() => {}}
|
||||
onRowClick={(s) => navigate({ to: '/lessons/sessions/$sessionId', params: { sessionId: s.id }, search: {} as any })}
|
||||
onRowClick={(s) => navigate({ to: '/lessons/sessions/$sessionId', params: { sessionId: s.id }, search: {} })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
@@ -373,7 +383,7 @@ function LessonPlanTab({ enrollmentId, memberId, canEdit }: { enrollmentId: stri
|
||||
queryClient.invalidateQueries({ queryKey: lessonPlanKeys.all })
|
||||
toast.success('Plan created from template')
|
||||
setTemplatePickerOpen(false)
|
||||
navigate({ to: '/lessons/plans/$planId', params: { planId: plan.id }, search: {} as any })
|
||||
navigate({ to: '/lessons/plans/$planId', params: { planId: plan.id }, search: {} })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
@@ -391,7 +401,7 @@ function LessonPlanTab({ enrollmentId, memberId, canEdit }: { enrollmentId: stri
|
||||
{Math.round(activePlan.progress)}% complete
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={() => navigate({ to: '/lessons/plans/$planId', params: { planId: activePlan.id }, search: {} as any })}>
|
||||
<Button variant="outline" size="sm" onClick={() => navigate({ to: '/lessons/plans/$planId', params: { planId: activePlan.id }, search: {} })}>
|
||||
View Plan
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -43,9 +43,9 @@ function statusBadge(status: string) {
|
||||
}
|
||||
|
||||
const columns: Column<Enrollment & { memberName?: string; instructorName?: string; slotInfo?: string; lessonTypeName?: string }>[] = [
|
||||
{ key: 'member_name', header: 'Member', sortable: true, render: (e) => <span className="font-medium">{(e as any).memberName ?? e.memberId}</span> },
|
||||
{ key: 'instructor_name', header: 'Instructor', render: (e) => <>{(e as any).instructorName ?? e.instructorId}</> },
|
||||
{ key: 'slot_info', header: 'Day / Time', render: (e) => <>{(e as any).slotInfo ?? '—'}</> },
|
||||
{ key: 'member_name', header: 'Member', sortable: true, render: (e) => <span className="font-medium">{e.memberName ?? e.memberId}</span> },
|
||||
{ key: 'instructor_name', header: 'Instructor', render: (e) => <>{e.instructorName ?? e.instructorId}</> },
|
||||
{ key: 'slot_info', header: 'Day / Time', render: (e) => <>{e.slotInfo ?? '—'}</> },
|
||||
{ key: 'status', header: 'Status', sortable: true, render: (e) => statusBadge(e.status) },
|
||||
{ key: 'start_date', header: 'Start', sortable: true, render: (e) => <>{new Date(e.startDate + 'T00:00:00').toLocaleDateString()}</> },
|
||||
{ key: 'rate', header: 'Rate', render: (e) => <>{e.rate ? `$${e.rate}${e.billingInterval ? ` / ${e.billingInterval} ${e.billingUnit}` : ''}` : <span className="text-muted-foreground">—</span>}</> },
|
||||
@@ -72,7 +72,7 @@ function EnrollmentsListPage() {
|
||||
function handleStatusChange(v: string) {
|
||||
const s = v === 'all' ? '' : v
|
||||
setStatusFilter(s)
|
||||
navigate({ to: '/lessons/enrollments', search: { ...search, status: s || undefined, page: 1 } as any })
|
||||
navigate({ to: '/lessons/enrollments', search: { ...search, status: s || undefined, page: 1 } })
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -80,7 +80,7 @@ function EnrollmentsListPage() {
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Enrollments</h1>
|
||||
{hasPermission('lessons.edit') && (
|
||||
<Button onClick={() => navigate({ to: '/lessons/enrollments/new', search: {} as any })}>
|
||||
<Button onClick={() => navigate({ to: '/lessons/enrollments/new', search: { memberId: undefined, accountId: undefined } })}>
|
||||
<Plus className="mr-2 h-4 w-4" />New Enrollment
|
||||
</Button>
|
||||
)}
|
||||
@@ -125,7 +125,7 @@ function EnrollmentsListPage() {
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
onRowClick={(e) => navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId: e.id }, search: {} as any })}
|
||||
onRowClick={(e) => navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId: e.id }, search: { tab: 'details' } })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -108,7 +108,7 @@ function NewEnrollmentPage() {
|
||||
},
|
||||
onSuccess: (enrollment) => {
|
||||
toast.success('Enrollment created')
|
||||
navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId: enrollment.id }, search: {} as any })
|
||||
navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId: enrollment.id }, search: { tab: 'details' } })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
@@ -141,7 +141,7 @@ function NewEnrollmentPage() {
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/enrollments', search: {} as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/enrollments', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'desc' as const, status: undefined, instructorId: undefined } })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h1 className="text-2xl font-bold">New Enrollment</h1>
|
||||
@@ -282,7 +282,7 @@ function NewEnrollmentPage() {
|
||||
<Button type="submit" disabled={mutation.isPending || !selectedMember || !selectedSlotId || !startDate} size="lg">
|
||||
{mutation.isPending ? 'Creating...' : 'Create Enrollment'}
|
||||
</Button>
|
||||
<Button variant="secondary" type="button" size="lg" onClick={() => navigate({ to: '/lessons/enrollments', search: {} as any })}>
|
||||
<Button variant="secondary" type="button" size="lg" onClick={() => navigate({ to: '/lessons/enrollments', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'desc' as const, status: undefined, instructorId: undefined } })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -93,7 +93,7 @@ function LessonPlanDetailPage() {
|
||||
return (
|
||||
<div className="space-y-6 max-w-3xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/plans', search: {} as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/plans', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="flex-1">
|
||||
|
||||
@@ -84,7 +84,7 @@ function LessonPlansPage() {
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
onRowClick={(p) => navigate({ to: '/lessons/plans/$planId', params: { planId: p.id }, search: {} as any })}
|
||||
onRowClick={(p) => navigate({ to: '/lessons/plans/$planId', params: { planId: p.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -49,7 +49,7 @@ function ScheduleHubPage() {
|
||||
const canAdmin = hasPermission('lessons.admin')
|
||||
|
||||
function setTab(t: string) {
|
||||
navigate({ to: '/lessons/schedule', search: { ...search, tab: t, page: 1 } as any })
|
||||
navigate({ to: '/lessons/schedule', search: { ...search, tab: t, page: 1 } })
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -90,7 +90,7 @@ const instructorColumns: Column<Instructor>[] = [
|
||||
},
|
||||
]
|
||||
|
||||
function InstructorsTab({ canAdmin, search: _search }: { canAdmin: boolean; search: any }) {
|
||||
function InstructorsTab({ canAdmin, search: _search }: { canAdmin: boolean; search: Record<string, unknown> }) {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const { params, setPage, setSearch, setSort } = usePagination()
|
||||
@@ -152,7 +152,7 @@ function InstructorsTab({ canAdmin, search: _search }: { canAdmin: boolean; sear
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
onRowClick={(i) => navigate({ to: '/lessons/schedule/instructors/$instructorId', params: { instructorId: i.id }, search: {} as any })}
|
||||
onRowClick={(i) => navigate({ to: '/lessons/schedule/instructors/$instructorId', params: { instructorId: i.id }, search: { tab: 'overview' } })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
@@ -169,7 +169,7 @@ const lessonTypeColumns: Column<LessonType>[] = [
|
||||
{ key: 'is_active', header: 'Status', render: (lt) => <Badge variant={lt.isActive ? 'default' : 'secondary'}>{lt.isActive ? 'Active' : 'Inactive'}</Badge> },
|
||||
]
|
||||
|
||||
function LessonTypesTab({ canAdmin, search: _search }: { canAdmin: boolean; search: any }) {
|
||||
function LessonTypesTab({ canAdmin, search: _search }: { canAdmin: boolean; search: Record<string, unknown> }) {
|
||||
const queryClient = useQueryClient()
|
||||
const { params, setPage, setSearch, setSort } = usePagination()
|
||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||
@@ -215,8 +215,8 @@ function LessonTypesTab({ canAdmin, search: _search }: { canAdmin: boolean; sear
|
||||
const columnsWithActions: Column<LessonType>[] = [
|
||||
...lessonTypeColumns,
|
||||
...(canAdmin ? [{
|
||||
key: 'actions' as any,
|
||||
header: '' as any,
|
||||
key: 'actions',
|
||||
header: '',
|
||||
render: (lt: LessonType) => (
|
||||
<div className="flex gap-1 justify-end">
|
||||
<Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); setEditTarget(lt) }}>Edit</Button>
|
||||
@@ -298,7 +298,7 @@ const gradingScaleColumns: Column<GradingScale>[] = [
|
||||
{ key: 'is_active', header: 'Status', render: (gs) => <Badge variant={gs.isActive ? 'default' : 'secondary'}>{gs.isActive ? 'Active' : 'Inactive'}</Badge> },
|
||||
]
|
||||
|
||||
function GradingScalesTab({ canAdmin, search: _search }: { canAdmin: boolean; search: any }) {
|
||||
function GradingScalesTab({ canAdmin, search: _search }: { canAdmin: boolean; search: Record<string, unknown> }) {
|
||||
const queryClient = useQueryClient()
|
||||
const { params, setPage, setSort } = usePagination()
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
@@ -327,8 +327,8 @@ function GradingScalesTab({ canAdmin, search: _search }: { canAdmin: boolean; se
|
||||
const columnsWithActions: Column<GradingScale>[] = [
|
||||
...gradingScaleColumns,
|
||||
...(canAdmin ? [{
|
||||
key: 'actions' as any,
|
||||
header: '' as any,
|
||||
key: 'actions',
|
||||
header: '',
|
||||
render: (gs: GradingScale) => (
|
||||
<Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); deleteMutation.mutate(gs.id) }}>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
|
||||
@@ -42,7 +42,7 @@ function InstructorDetailPage() {
|
||||
const tab = search.tab
|
||||
|
||||
function setTab(t: string) {
|
||||
navigate({ to: '/lessons/schedule/instructors/$instructorId', params: { instructorId }, search: { tab: t } as any })
|
||||
navigate({ to: '/lessons/schedule/instructors/$instructorId', params: { instructorId }, search: { tab: t } })
|
||||
}
|
||||
|
||||
const { data: instructor, isLoading } = useQuery(instructorDetailOptions(instructorId))
|
||||
@@ -62,7 +62,7 @@ function InstructorDetailPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/schedule', search: { tab: 'instructors' } as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/schedule', search: { tab: 'instructors', page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
<ArrowLeft className="h-4 w-4 mr-1" />Back
|
||||
</Button>
|
||||
<div className="flex-1">
|
||||
|
||||
@@ -18,7 +18,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { ArrowLeft, CheckSquare, Square } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import type { LessonPlan, LessonPlanSection } from '@/types/lesson'
|
||||
import type { LessonPlan, LessonPlanSection, LessonSession } from '@/types/lesson'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/lessons/sessions/$sessionId')({
|
||||
component: SessionDetailPage,
|
||||
@@ -126,7 +126,7 @@ function SessionDetailPage() {
|
||||
return (
|
||||
<div className="space-y-6 max-w-3xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/sessions', search: {} as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/sessions', search: { view: 'list' as const, page: 1, limit: 25, q: undefined, sort: undefined, order: 'desc' as const, status: undefined, instructorId: undefined } })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="flex-1">
|
||||
@@ -137,7 +137,7 @@ function SessionDetailPage() {
|
||||
<Link
|
||||
to="/lessons/enrollments/$enrollmentId"
|
||||
params={{ enrollmentId: enrollment.id }}
|
||||
search={{} as any}
|
||||
search={{ tab: 'details' }}
|
||||
className="text-sm text-primary hover:underline"
|
||||
>
|
||||
View Enrollment
|
||||
@@ -209,7 +209,12 @@ function SessionDetailPage() {
|
||||
|
||||
// ─── Notes Card ───────────────────────────────────────────────────────────────
|
||||
|
||||
function NotesCard({ session, canEdit, onSave, saving }: any) {
|
||||
function NotesCard({ session, canEdit, onSave, saving }: {
|
||||
session: LessonSession
|
||||
canEdit: boolean
|
||||
onSave: (data: Record<string, unknown>) => void
|
||||
saving: boolean
|
||||
}) {
|
||||
const [instructorNotes, setInstructorNotes] = useState(session.instructorNotes ?? '')
|
||||
const [memberNotes, setMemberNotes] = useState(session.memberNotes ?? '')
|
||||
const [homeworkAssigned, setHomeworkAssigned] = useState(session.homeworkAssigned ?? '')
|
||||
|
||||
@@ -92,13 +92,13 @@ function SessionsPage() {
|
||||
const weekEnd = endOfWeek(weekStart, { weekStartsOn: 0 })
|
||||
|
||||
function setView(v: 'list' | 'week') {
|
||||
navigate({ to: '/lessons/sessions', search: { ...search, view: v, page: 1 } as any })
|
||||
navigate({ to: '/lessons/sessions', search: { ...search, view: v, page: 1 } })
|
||||
}
|
||||
|
||||
function handleStatusChange(v: string) {
|
||||
const s = v === 'all' ? '' : v
|
||||
setStatusFilter(s)
|
||||
navigate({ to: '/lessons/sessions', search: { ...search, status: s || undefined, page: 1 } as any })
|
||||
navigate({ to: '/lessons/sessions', search: { ...search, status: s || undefined, page: 1 } })
|
||||
}
|
||||
|
||||
// List query
|
||||
@@ -189,7 +189,7 @@ function SessionsPage() {
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
onRowClick={(s) => navigate({ to: '/lessons/sessions/$sessionId', params: { sessionId: s.id }, search: {} as any })}
|
||||
onRowClick={(s) => navigate({ to: '/lessons/sessions/$sessionId', params: { sessionId: s.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
@@ -249,7 +249,7 @@ function SessionsPage() {
|
||||
{daySessions.map((s) => (
|
||||
<button
|
||||
key={s.id}
|
||||
onClick={() => navigate({ to: '/lessons/sessions/$sessionId', params: { sessionId: s.id }, search: {} as any })}
|
||||
onClick={() => navigate({ to: '/lessons/sessions/$sessionId', params: { sessionId: s.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}
|
||||
className={`w-full text-left rounded border px-1.5 py-1 text-xs hover:opacity-80 transition-opacity ${STATUS_COLORS[s.status] ?? STATUS_COLORS.scheduled}`}
|
||||
>
|
||||
<p className="font-semibold">{formatTime(s.scheduledTime)}</p>
|
||||
|
||||
@@ -18,7 +18,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
|
||||
import { ArrowLeft, Search, X, Zap } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import type { LessonPlanTemplate } from '@/types/lesson'
|
||||
import type { Enrollment, LessonPlanTemplate } from '@/types/lesson'
|
||||
import type { MemberWithAccount } from '@/api/members'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/lessons/templates/$templateId')({
|
||||
@@ -42,7 +42,7 @@ function TemplateDetailPage() {
|
||||
return (
|
||||
<div className="space-y-6 max-w-3xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/templates', search: {} as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/templates', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="flex-1">
|
||||
@@ -93,7 +93,7 @@ function TemplateDetailPage() {
|
||||
|
||||
// ─── Edit Form ────────────────────────────────────────────────────────────────
|
||||
|
||||
function EditTemplateForm({ template, templateId, queryClient }: { template: LessonPlanTemplate; templateId: string; queryClient: any }) {
|
||||
function EditTemplateForm({ template, templateId, queryClient }: { template: LessonPlanTemplate; templateId: string; queryClient: ReturnType<typeof useQueryClient> }) {
|
||||
const [name, setName] = useState(template.name)
|
||||
const [description, setDescription] = useState(template.description ?? '')
|
||||
const [instrument, setInstrument] = useState(template.instrument ?? '')
|
||||
@@ -218,7 +218,7 @@ function InstantiateDialog({ template, templateId, open, onClose }: {
|
||||
}),
|
||||
onSuccess: (plan) => {
|
||||
toast.success('Plan created from template')
|
||||
navigate({ to: '/lessons/plans/$planId', params: { planId: plan.id }, search: {} as any })
|
||||
navigate({ to: '/lessons/plans/$planId', params: { planId: plan.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
@@ -293,7 +293,7 @@ function InstantiateDialog({ template, templateId, open, onClose }: {
|
||||
<SelectTrigger><SelectValue placeholder="Not linked to enrollment" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">Not linked to enrollment</SelectItem>
|
||||
{enrollments.map((e: any) => (
|
||||
{enrollments.map((e: Enrollment) => (
|
||||
<SelectItem key={e.id} value={e.id}>Enrollment {e.id.slice(-6)}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
|
||||
@@ -81,8 +81,8 @@ function TemplatesListPage() {
|
||||
const columnsWithActions: Column<LessonPlanTemplate>[] = [
|
||||
...columns,
|
||||
...(canAdmin ? [{
|
||||
key: 'actions' as any,
|
||||
header: '' as any,
|
||||
key: 'actions',
|
||||
header: '',
|
||||
render: (t: LessonPlanTemplate) => (
|
||||
<Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); deleteMutation.mutate(t.id) }}>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
@@ -96,7 +96,7 @@ function TemplatesListPage() {
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Lesson Plan Templates</h1>
|
||||
{canAdmin && (
|
||||
<Button onClick={() => navigate({ to: '/lessons/templates/new', search: {} as any })}>
|
||||
<Button onClick={() => navigate({ to: '/lessons/templates/new', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
<Plus className="mr-2 h-4 w-4" />New Template
|
||||
</Button>
|
||||
)}
|
||||
@@ -126,7 +126,7 @@ function TemplatesListPage() {
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
onRowClick={(t) => navigate({ to: '/lessons/templates/$templateId', params: { templateId: t.id }, search: {} as any })}
|
||||
onRowClick={(t) => navigate({ to: '/lessons/templates/$templateId', params: { templateId: t.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -45,7 +45,7 @@ function NewTemplatePage() {
|
||||
}),
|
||||
onSuccess: (template) => {
|
||||
toast.success('Template created')
|
||||
navigate({ to: '/lessons/templates/$templateId', params: { templateId: template.id }, search: {} as any })
|
||||
navigate({ to: '/lessons/templates/$templateId', params: { templateId: template.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
@@ -63,7 +63,7 @@ function NewTemplatePage() {
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-6 max-w-3xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/templates', search: {} as any })}>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/templates', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h1 className="text-2xl font-bold">New Template</h1>
|
||||
@@ -112,7 +112,7 @@ function NewTemplatePage() {
|
||||
<Button type="submit" disabled={mutation.isPending || !name.trim() || !allSectionsValid} size="lg">
|
||||
{mutation.isPending ? 'Creating...' : 'Create Template'}
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" size="lg" onClick={() => navigate({ to: '/lessons/templates', search: {} as any })}>
|
||||
<Button type="button" variant="secondary" size="lg" onClick={() => navigate({ to: '/lessons/templates', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -70,11 +70,11 @@ function statusBadge(status: string) {
|
||||
return <Badge variant={variants[status] ?? 'outline'}>{status}</Badge>
|
||||
}
|
||||
|
||||
const enrollmentColumns: Column<Enrollment>[] = [
|
||||
const enrollmentColumns: Column<Enrollment & { instructorName?: string; slotInfo?: string; lessonTypeName?: string }>[] = [
|
||||
{ key: 'status', header: 'Status', sortable: true, render: (e) => statusBadge(e.status) },
|
||||
{ key: 'instructor_name', header: 'Instructor', render: (e) => <>{(e as any).instructorName ?? e.instructorId}</> },
|
||||
{ key: 'slot_info', header: 'Day / Time', render: (e) => <>{(e as any).slotInfo ?? '—'}</> },
|
||||
{ key: 'lesson_type', header: 'Lesson', render: (e) => <>{(e as any).lessonTypeName ?? '—'}</> },
|
||||
{ key: 'instructor_name', header: 'Instructor', render: (e) => <>{e.instructorName ?? e.instructorId}</> },
|
||||
{ key: 'slot_info', header: 'Day / Time', render: (e) => <>{e.slotInfo ?? '—'}</> },
|
||||
{ key: 'lesson_type', header: 'Lesson', render: (e) => <>{e.lessonTypeName ?? '—'}</> },
|
||||
{ key: 'start_date', header: 'Start', sortable: true, render: (e) => <>{new Date(e.startDate + 'T00:00:00').toLocaleDateString()}</> },
|
||||
{ key: 'rate', header: 'Rate', render: (e) => <>{e.rate ? `$${e.rate} / ${e.billingInterval} ${e.billingUnit}` : <span className="text-muted-foreground">—</span>}</> },
|
||||
]
|
||||
@@ -161,7 +161,7 @@ function MemberDetailPage() {
|
||||
})
|
||||
|
||||
function setTab(t: string) {
|
||||
navigate({ to: '/members/$memberId', params: { memberId }, search: { tab: t } as any })
|
||||
navigate({ to: '/members/$memberId', params: { memberId }, search: { tab: t } })
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
@@ -188,7 +188,7 @@ function MemberDetailPage() {
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/accounts/$accountId/members', params: { accountId: member.accountId }, search: {} as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/accounts/$accountId/members', params: { accountId: member.accountId }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div>
|
||||
@@ -293,7 +293,7 @@ function MemberDetailPage() {
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-muted-foreground">{enrollmentsData?.pagination.total ?? 0} enrollment(s)</p>
|
||||
{hasPermission('lessons.edit') && (
|
||||
<Button size="sm" onClick={() => navigate({ to: '/lessons/enrollments/new', search: { memberId } as any })}>
|
||||
<Button size="sm" onClick={() => navigate({ to: '/lessons/enrollments/new', search: { memberId, accountId: undefined } })}>
|
||||
<Plus className="h-4 w-4 mr-1" />Enroll
|
||||
</Button>
|
||||
)}
|
||||
@@ -307,7 +307,7 @@ function MemberDetailPage() {
|
||||
total={enrollmentsData?.data?.length ?? 0}
|
||||
onPageChange={() => {}}
|
||||
onSort={() => {}}
|
||||
onRowClick={(e) => navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId: e.id }, search: {} as any })}
|
||||
onRowClick={(e) => navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId: e.id }, search: { tab: 'details' } })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -84,7 +84,7 @@ function MembersListPage() {
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => navigate({ to: '/members/$memberId', params: { memberId: row.id }, search: {} as any })}>
|
||||
<DropdownMenuItem onClick={() => navigate({ to: '/members/$memberId', params: { memberId: row.id }, search: { tab: 'details' } })}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
@@ -134,7 +134,7 @@ function MembersListPage() {
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
onRowClick={(member) => navigate({ to: '/members/$memberId', params: { memberId: member.id }, search: {} as any })}
|
||||
onRowClick={(member) => navigate({ to: '/members/$memberId', params: { memberId: member.id }, search: { tab: 'details' } })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -11,10 +11,22 @@ import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { Sun, Moon, Monitor } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { AvatarUpload } from '@/components/shared/avatar-upload'
|
||||
|
||||
interface Profile {
|
||||
id: string
|
||||
email: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
role: string
|
||||
employeeNumber: string | null
|
||||
hasPin: boolean
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/profile')({
|
||||
component: ProfilePage,
|
||||
})
|
||||
@@ -22,21 +34,56 @@ export const Route = createFileRoute('/_authenticated/profile')({
|
||||
function profileOptions() {
|
||||
return queryOptions({
|
||||
queryKey: ['auth', 'me'],
|
||||
queryFn: () => api.get<{ id: string; email: string; firstName: string; lastName: string }>('/v1/auth/me'),
|
||||
queryFn: () => api.get<Profile>('/v1/auth/me'),
|
||||
})
|
||||
}
|
||||
|
||||
function ProfilePage() {
|
||||
const { tab } = Route.useSearch() as { tab?: string }
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
const setAuth = useAuthStore((s) => s.setAuth)
|
||||
const storeUser = useAuthStore((s) => s.user)
|
||||
const storeToken = useAuthStore((s) => s.token)
|
||||
const { mode, colorTheme, setMode, setColorTheme } = useThemeStore()
|
||||
|
||||
const { data: profile } = useQuery(profileOptions())
|
||||
|
||||
const [firstName, setFirstName] = useState('')
|
||||
const [lastName, setLastName] = useState('')
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<h1 className="text-2xl font-bold">Profile</h1>
|
||||
|
||||
<Tabs defaultValue={tab === 'security' || tab === 'appearance' ? tab : 'account'}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="account">Account</TabsTrigger>
|
||||
<TabsTrigger value="security">Security</TabsTrigger>
|
||||
<TabsTrigger value="appearance">Appearance</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="account">
|
||||
<AccountTab profile={profile} queryClient={queryClient} setAuth={setAuth} storeUser={storeUser} storeToken={storeToken} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="security">
|
||||
<SecurityTab profile={profile} queryClient={queryClient} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="appearance">
|
||||
<AppearanceTab />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AccountTab({ profile, queryClient, setAuth, storeUser, storeToken }: {
|
||||
profile: Profile | undefined
|
||||
queryClient: ReturnType<typeof useQueryClient>
|
||||
setAuth: (token: string, user: any) => void
|
||||
storeUser: any
|
||||
storeToken: string | null
|
||||
}) {
|
||||
const [firstName, setFirstName] = useState(profile?.firstName ?? '')
|
||||
const [lastName, setLastName] = useState(profile?.lastName ?? '')
|
||||
const [nameLoaded, setNameLoaded] = useState(false)
|
||||
|
||||
if (profile && !nameLoaded) {
|
||||
@@ -45,12 +92,8 @@ function ProfilePage() {
|
||||
setNameLoaded(true)
|
||||
}
|
||||
|
||||
const [currentPassword, setCurrentPassword] = useState('')
|
||||
const [newPassword, setNewPassword] = useState('')
|
||||
const [confirmPassword, setConfirmPassword] = useState('')
|
||||
|
||||
const updateProfileMutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) => api.patch<{ id: string; email: string; firstName: string; lastName: string }>('/v1/auth/me', data),
|
||||
mutationFn: (data: Record<string, unknown>) => api.patch<Profile>('/v1/auth/me', data),
|
||||
onSuccess: (updated) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
|
||||
if (storeToken && storeUser) {
|
||||
@@ -61,6 +104,59 @@ function ProfilePage() {
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Account</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{profile?.id && (
|
||||
<div className="flex items-center gap-4">
|
||||
<AvatarUpload entityType="user" entityId={profile.id} size="lg" />
|
||||
<div>
|
||||
<p className="font-medium">{profile.firstName} {profile.lastName}</p>
|
||||
<p className="text-sm text-muted-foreground">{profile.email}</p>
|
||||
{profile.employeeNumber && (
|
||||
<p className="text-xs text-muted-foreground">Employee #{profile.employeeNumber}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label>Email</Label>
|
||||
<Input value={profile?.email ?? ''} disabled className="opacity-60" />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>First Name</Label>
|
||||
<Input value={firstName} onChange={(e) => setFirstName(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Last Name</Label>
|
||||
<Input value={lastName} onChange={(e) => setLastName(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => updateProfileMutation.mutate({ firstName, lastName })}
|
||||
disabled={updateProfileMutation.isPending}
|
||||
>
|
||||
{updateProfileMutation.isPending ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function SecurityTab({ profile, queryClient }: {
|
||||
profile: Profile | undefined
|
||||
queryClient: ReturnType<typeof useQueryClient>
|
||||
}) {
|
||||
const [currentPassword, setCurrentPassword] = useState('')
|
||||
const [newPassword, setNewPassword] = useState('')
|
||||
const [confirmPassword, setConfirmPassword] = useState('')
|
||||
const [pin, setPin] = useState('')
|
||||
const [confirmPin, setConfirmPin] = useState('')
|
||||
|
||||
const changePasswordMutation = useMutation({
|
||||
mutationFn: () => api.post('/v1/auth/change-password', { currentPassword, newPassword }),
|
||||
onSuccess: () => {
|
||||
@@ -72,6 +168,26 @@ function ProfilePage() {
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const setPinMutation = useMutation({
|
||||
mutationFn: () => api.post('/v1/auth/set-pin', { pin }),
|
||||
onSuccess: () => {
|
||||
setPin('')
|
||||
setConfirmPin('')
|
||||
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
|
||||
toast.success('PIN set')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const removePinMutation = useMutation({
|
||||
mutationFn: () => api.del('/v1/auth/pin'),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
|
||||
toast.success('PIN removed')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
function handlePasswordChange() {
|
||||
if (newPassword.length < 12) {
|
||||
toast.error('Password must be at least 12 characters')
|
||||
@@ -84,47 +200,24 @@ function ProfilePage() {
|
||||
changePasswordMutation.mutate()
|
||||
}
|
||||
|
||||
function handleSetPin() {
|
||||
if (pin.length < 4 || pin.length > 6) {
|
||||
toast.error('PIN must be 4-6 digits')
|
||||
return
|
||||
}
|
||||
if (!/^\d+$/.test(pin)) {
|
||||
toast.error('PIN must be digits only')
|
||||
return
|
||||
}
|
||||
if (pin !== confirmPin) {
|
||||
toast.error('PINs do not match')
|
||||
return
|
||||
}
|
||||
setPinMutation.mutate()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<h1 className="text-2xl font-bold">Profile</h1>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Account</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{profile?.id && (
|
||||
<div className="flex items-center gap-4">
|
||||
<AvatarUpload entityType="user" entityId={profile.id} size="lg" />
|
||||
<div>
|
||||
<p className="font-medium">{profile.firstName} {profile.lastName}</p>
|
||||
<p className="text-sm text-muted-foreground">{profile.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label>Email</Label>
|
||||
<Input value={profile?.email ?? ''} disabled className="opacity-60" />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>First Name</Label>
|
||||
<Input value={firstName} onChange={(e) => setFirstName(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Last Name</Label>
|
||||
<Input value={lastName} onChange={(e) => setLastName(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => updateProfileMutation.mutate({ firstName, lastName })}
|
||||
disabled={updateProfileMutation.isPending}
|
||||
>
|
||||
{updateProfileMutation.isPending ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Change Password</CardTitle>
|
||||
@@ -150,53 +243,113 @@ function ProfilePage() {
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Appearance</CardTitle>
|
||||
<CardTitle className="text-lg">POS PIN</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Mode</Label>
|
||||
<div className="flex gap-2">
|
||||
{[
|
||||
{ value: 'light' as const, icon: Sun, label: 'Light' },
|
||||
{ value: 'dark' as const, icon: Moon, label: 'Dark' },
|
||||
{ value: 'system' as const, icon: Monitor, label: 'System' },
|
||||
].map((m) => (
|
||||
<Button
|
||||
key={m.value}
|
||||
variant={mode === m.value ? 'default' : 'secondary'}
|
||||
size="sm"
|
||||
onClick={() => setMode(m.value)}
|
||||
>
|
||||
<m.icon className="mr-2 h-4 w-4" />
|
||||
{m.label}
|
||||
{profile?.employeeNumber && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Your employee number is <span className="font-mono font-medium text-foreground">{profile.employeeNumber}</span>.
|
||||
To unlock the POS, enter your employee number followed by your PIN.
|
||||
</p>
|
||||
)}
|
||||
{profile?.hasPin ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">You have a PIN set. You can change or remove it below.</p>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>New PIN (4-6 digits)</Label>
|
||||
<Input type="password" inputMode="numeric" maxLength={6} value={pin} onChange={(e) => setPin(e.target.value)} placeholder="****" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Confirm PIN</Label>
|
||||
<Input type="password" inputMode="numeric" maxLength={6} value={confirmPin} onChange={(e) => setConfirmPin(e.target.value)} placeholder="****" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={handleSetPin} disabled={setPinMutation.isPending}>
|
||||
{setPinMutation.isPending ? 'Saving...' : 'Change PIN'}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Color Theme</Label>
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{themes.map((t) => (
|
||||
<Button
|
||||
key={t.name}
|
||||
variant={colorTheme === t.name ? 'default' : 'secondary'}
|
||||
size="sm"
|
||||
onClick={() => setColorTheme(t.name)}
|
||||
>
|
||||
<span
|
||||
className="mr-2 h-3 w-3 rounded-full border inline-block"
|
||||
style={{ backgroundColor: `hsl(${t.light.primary})` }}
|
||||
/>
|
||||
{t.label}
|
||||
<Button variant="outline" onClick={() => removePinMutation.mutate()} disabled={removePinMutation.isPending}>
|
||||
{removePinMutation.isPending ? 'Removing...' : 'Remove PIN'}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">Set a PIN to unlock the Point of Sale terminal.</p>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>PIN (4-6 digits)</Label>
|
||||
<Input type="password" inputMode="numeric" maxLength={6} value={pin} onChange={(e) => setPin(e.target.value)} placeholder="****" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Confirm PIN</Label>
|
||||
<Input type="password" inputMode="numeric" maxLength={6} value={confirmPin} onChange={(e) => setConfirmPin(e.target.value)} placeholder="****" />
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={handleSetPin} disabled={setPinMutation.isPending}>
|
||||
{setPinMutation.isPending ? 'Saving...' : 'Set PIN'}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AppearanceTab() {
|
||||
const { mode, colorTheme, setMode, setColorTheme } = useThemeStore()
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Appearance</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Mode</Label>
|
||||
<div className="flex gap-2">
|
||||
{[
|
||||
{ value: 'light' as const, icon: Sun, label: 'Light' },
|
||||
{ value: 'dark' as const, icon: Moon, label: 'Dark' },
|
||||
{ value: 'system' as const, icon: Monitor, label: 'System' },
|
||||
].map((m) => (
|
||||
<Button
|
||||
key={m.value}
|
||||
variant={mode === m.value ? 'default' : 'secondary'}
|
||||
size="sm"
|
||||
onClick={() => setMode(m.value)}
|
||||
>
|
||||
<m.icon className="mr-2 h-4 w-4" />
|
||||
{m.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Color Theme</Label>
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{themes.map((t) => (
|
||||
<Button
|
||||
key={t.name}
|
||||
variant={colorTheme === t.name ? 'default' : 'secondary'}
|
||||
size="sm"
|
||||
onClick={() => setColorTheme(t.name)}
|
||||
>
|
||||
<span
|
||||
className="mr-2 h-3 w-3 rounded-full border inline-block"
|
||||
style={{ backgroundColor: `hsl(${t.light.primary})` }}
|
||||
/>
|
||||
{t.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -96,12 +96,12 @@ function RepairBatchDetailPage() {
|
||||
const totalActual = tickets.reduce((sum, t) => sum + (t.actualCost ? parseFloat(t.actualCost) : 0), 0)
|
||||
|
||||
function handleTicketClick(ticket: RepairTicket) {
|
||||
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: {} as any })
|
||||
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })
|
||||
}
|
||||
|
||||
function handleAddRepair() {
|
||||
// Navigate to new repair with batch and account pre-linked
|
||||
navigate({ to: '/repairs/new', search: { batchId, batchName: batch!.batchNumber ?? '', accountId: batch!.accountId, contactName: batch!.contactName ?? '' } as any })
|
||||
navigate({ to: '/repairs/new', search: { batchId, batchName: batch!.batchNumber ?? '', accountId: batch!.accountId, contactName: batch!.contactName ?? '' } })
|
||||
}
|
||||
|
||||
async function generateBatchPdf() {
|
||||
@@ -233,7 +233,7 @@ function RepairBatchDetailPage() {
|
||||
return (
|
||||
<div className="space-y-6 max-w-5xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repair-batches', search: {} as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repair-batches', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="flex-1">
|
||||
|
||||
@@ -75,7 +75,7 @@ function RepairBatchesListPage() {
|
||||
}
|
||||
|
||||
function handleRowClick(batch: RepairBatch) {
|
||||
navigate({ to: '/repair-batches/$batchId', params: { batchId: batch.id }, search: {} as any })
|
||||
navigate({ to: '/repair-batches/$batchId', params: { batchId: batch.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -50,7 +50,7 @@ function NewRepairBatchPage() {
|
||||
mutationFn: repairBatchMutations.create,
|
||||
onSuccess: (batch) => {
|
||||
toast.success('Repair batch created')
|
||||
navigate({ to: '/repair-batches/$batchId', params: { batchId: batch.id }, search: {} as any })
|
||||
navigate({ to: '/repair-batches/$batchId', params: { batchId: batch.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
@@ -78,7 +78,7 @@ function NewRepairBatchPage() {
|
||||
return (
|
||||
<div className="space-y-6 max-w-3xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repair-batches', search: {} as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repair-batches', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h1 className="text-2xl font-bold">New Repair Batch</h1>
|
||||
@@ -176,7 +176,7 @@ function NewRepairBatchPage() {
|
||||
<Button type="submit" disabled={mutation.isPending} size="lg">
|
||||
{mutation.isPending ? 'Creating...' : 'Create Batch'}
|
||||
</Button>
|
||||
<Button variant="secondary" type="button" size="lg" onClick={() => navigate({ to: '/repair-batches', search: {} as any })}>
|
||||
<Button variant="secondary" type="button" size="lg" onClick={() => navigate({ to: '/repair-batches', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
repairLineItemListOptions, repairLineItemMutations, repairLineItemKeys,
|
||||
repairServiceTemplateListOptions,
|
||||
} from '@/api/repairs'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { usePagination } from '@/hooks/use-pagination'
|
||||
import { StatusProgress } from '@/components/repairs/status-progress'
|
||||
import { TicketPhotos } from '@/components/repairs/ticket-photos'
|
||||
@@ -20,7 +21,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { ArrowLeft, Plus, Trash2, RotateCcw, Save, Search } from 'lucide-react'
|
||||
import { ArrowLeft, Plus, Trash2, RotateCcw, Save, Search, Mail } from 'lucide-react'
|
||||
import { PdfModal } from '@/components/repairs/pdf-modal'
|
||||
import { toast } from 'sonner'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
@@ -77,6 +78,17 @@ function RepairTicketDetailPage() {
|
||||
const { data: lineItemsData, isLoading: itemsLoading } = useQuery(repairLineItemListOptions(ticketId, params))
|
||||
|
||||
const [editFields, setEditFields] = useState<Record<string, string>>({})
|
||||
const [emailEstimateOpen, setEmailEstimateOpen] = useState(false)
|
||||
const [estimateEmail, setEstimateEmail] = useState('')
|
||||
|
||||
const emailEstimateMutation = useMutation({
|
||||
mutationFn: () => api.post<{ message: string }>(`/v1/repair-tickets/${ticketId}/email-estimate`, { email: estimateEmail }),
|
||||
onSuccess: () => {
|
||||
toast.success('Estimate emailed')
|
||||
setEmailEstimateOpen(false)
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const statusMutation = useMutation({
|
||||
mutationFn: (status: string) => repairTicketMutations.updateStatus(ticketId, status),
|
||||
@@ -157,7 +169,12 @@ function RepairTicketDetailPage() {
|
||||
}
|
||||
|
||||
const lineItemColumns: Column<RepairLineItem>[] = [
|
||||
{ key: 'item_type', header: 'Type', sortable: true, render: (i) => <Badge variant="outline">{i.itemType.replace('_', ' ')}</Badge> },
|
||||
{ key: 'item_type', header: 'Type', sortable: true, render: (i) => (
|
||||
<div className="flex items-center gap-1">
|
||||
<Badge variant="outline">{i.itemType.replace('_', ' ')}</Badge>
|
||||
{i.itemType === 'consumable' && <Badge variant="secondary" className="text-[10px]">Internal</Badge>}
|
||||
</div>
|
||||
) },
|
||||
{ key: 'description', header: 'Description', render: (i) => <>{i.description}</> },
|
||||
{ key: 'qty', header: 'Qty', render: (i) => <>{i.qty}</> },
|
||||
{ key: 'unit_price', header: 'Unit Price', render: (i) => <>${i.unitPrice}</> },
|
||||
@@ -175,13 +192,44 @@ function RepairTicketDetailPage() {
|
||||
<div className="space-y-4 max-w-5xl">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repairs', search: {} as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repairs', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="flex-1">
|
||||
<h1 className="text-2xl font-bold">Ticket #{ticket.ticketNumber}</h1>
|
||||
<p className="text-sm text-muted-foreground">{ticket.customerName} — {ticket.itemDescription ?? 'No item description'}</p>
|
||||
</div>
|
||||
<Dialog open={emailEstimateOpen} onOpenChange={setEmailEstimateOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="gap-2" onClick={() => setEstimateEmail((ticket as any).customerEmail ?? '')}>
|
||||
<Mail className="h-4 w-4" />Email Estimate
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Email Estimate</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Send to</Label>
|
||||
<Input
|
||||
type="email"
|
||||
value={estimateEmail}
|
||||
onChange={(e) => setEstimateEmail(e.target.value)}
|
||||
placeholder="customer@example.com"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
className="w-full"
|
||||
onClick={() => emailEstimateMutation.mutate()}
|
||||
disabled={!estimateEmail || emailEstimateMutation.isPending}
|
||||
>
|
||||
{emailEstimateMutation.isPending ? 'Sending...' : 'Send Estimate'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<PdfModal ticket={ticket} lineItems={lineItemsData?.data ?? []} ticketId={ticketId} />
|
||||
</div>
|
||||
|
||||
@@ -391,11 +439,27 @@ function AddLineItemDialog({ ticketId, open, onOpenChange }: { ticketId: string;
|
||||
const [qty, setQty] = useState('1')
|
||||
const [unitPrice, setUnitPrice] = useState('0')
|
||||
const [cost, setCost] = useState('')
|
||||
const [productId, setProductId] = useState<string | null>(null)
|
||||
const [productSearch, setProductSearch] = useState('')
|
||||
const [showProducts, setShowProducts] = useState(false)
|
||||
|
||||
const showProductPicker = itemType === 'part' || itemType === 'consumable'
|
||||
|
||||
const { data: templatesData } = useQuery(
|
||||
repairServiceTemplateListOptions({ page: 1, limit: 20, q: templateSearch || undefined, order: 'asc', sort: 'name' }),
|
||||
)
|
||||
|
||||
const { data: productsData } = useQuery({
|
||||
queryKey: ['products', 'repair-picker', productSearch, itemType],
|
||||
queryFn: () => {
|
||||
const params: Record<string, string> = { q: productSearch, limit: '10', isActive: 'true' }
|
||||
if (itemType === 'consumable') params.isConsumable = 'true'
|
||||
else params.isDualUseRepair = 'true'
|
||||
return api.get<{ data: { id: string; name: string; sku: string | null; price: string | null; brand: string | null }[] }>('/v1/products', params)
|
||||
},
|
||||
enabled: showProductPicker && productSearch.length >= 1,
|
||||
})
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) => repairLineItemMutations.create(ticketId, data),
|
||||
onSuccess: () => {
|
||||
@@ -408,7 +472,7 @@ function AddLineItemDialog({ ticketId, open, onOpenChange }: { ticketId: string;
|
||||
})
|
||||
|
||||
function resetForm() {
|
||||
setDescription(''); setQty('1'); setUnitPrice('0'); setCost(''); setItemType('labor'); setTemplateSearch(''); setShowTemplates(false)
|
||||
setDescription(''); setQty('1'); setUnitPrice('0'); setCost(''); setItemType('labor'); setTemplateSearch(''); setShowTemplates(false); setProductId(null); setProductSearch(''); setShowProducts(false)
|
||||
}
|
||||
|
||||
function selectTemplate(template: { name: string; itemCategory: string | null; size: string | null; itemType: string; defaultPrice: string; defaultCost: string | null }) {
|
||||
@@ -416,15 +480,24 @@ function AddLineItemDialog({ ticketId, open, onOpenChange }: { ticketId: string;
|
||||
setDescription(desc); setItemType(template.itemType); setUnitPrice(template.defaultPrice); setCost(template.defaultCost ?? ''); setShowTemplates(false); setTemplateSearch('')
|
||||
}
|
||||
|
||||
function selectProduct(product: { id: string; name: string; price: string | null; brand: string | null }) {
|
||||
setProductId(product.id)
|
||||
setDescription(product.brand ? `${product.brand} ${product.name}` : product.name)
|
||||
setUnitPrice(product.price ?? '0')
|
||||
setProductSearch('')
|
||||
setShowProducts(false)
|
||||
}
|
||||
|
||||
function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
const q = parseFloat(qty) || 1
|
||||
const up = parseFloat(unitPrice) || 0
|
||||
const c = cost ? parseFloat(cost) : undefined
|
||||
mutation.mutate({ itemType, description, qty: q, unitPrice: up, totalPrice: q * up, cost: c })
|
||||
mutation.mutate({ itemType, description, qty: q, unitPrice: up, totalPrice: q * up, cost: c, productId: productId ?? undefined })
|
||||
}
|
||||
|
||||
const templates = templatesData?.data ?? []
|
||||
const products = productsData?.data ?? []
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => { onOpenChange(o); if (!o) resetForm() }}>
|
||||
@@ -454,8 +527,38 @@ function AddLineItemDialog({ ticketId, open, onOpenChange }: { ticketId: string;
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Type</Label>
|
||||
<Select value={itemType} onValueChange={setItemType}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent><SelectItem value="labor">Labor</SelectItem><SelectItem value="part">Part</SelectItem><SelectItem value="flat_rate">Flat Rate</SelectItem><SelectItem value="misc">Misc</SelectItem></SelectContent></Select>
|
||||
<Select value={itemType} onValueChange={(v) => { setItemType(v); setProductId(null); setProductSearch(''); setShowProducts(false) }}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent><SelectItem value="labor">Labor</SelectItem><SelectItem value="part">Part</SelectItem><SelectItem value="flat_rate">Flat Rate</SelectItem><SelectItem value="misc">Misc</SelectItem><SelectItem value="consumable">Consumable (internal)</SelectItem></SelectContent></Select>
|
||||
</div>
|
||||
{showProductPicker && (
|
||||
<div className="relative space-y-2">
|
||||
<Label>Search Inventory</Label>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={itemType === 'consumable' ? 'Search consumables...' : 'Search parts...'}
|
||||
value={productSearch}
|
||||
onChange={(e) => { setProductSearch(e.target.value); setShowProducts(true) }}
|
||||
onFocus={() => productSearch && setShowProducts(true)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
{productId && (
|
||||
<div className="text-xs text-muted-foreground flex items-center gap-1">
|
||||
Linked to product <button type="button" className="underline text-destructive" onClick={() => setProductId(null)}>clear</button>
|
||||
</div>
|
||||
)}
|
||||
{showProducts && productSearch.length >= 1 && (
|
||||
<div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-48 overflow-auto">
|
||||
{products.length === 0 ? <div className="p-3 text-sm text-muted-foreground">No products found</div> : products.map((p) => (
|
||||
<button key={p.id} type="button" className="w-full text-left px-3 py-2 text-sm hover:bg-accent flex justify-between" onClick={() => selectProduct(p)}>
|
||||
<span>{p.brand ? `${p.brand} ` : ''}{p.name}{p.sku ? ` (${p.sku})` : ''}</span>
|
||||
{p.price && <span className="text-muted-foreground">${p.price}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2"><Label>Description *</Label><Input value={description} onChange={(e) => setDescription(e.target.value)} required /></div>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="space-y-2"><Label>Qty</Label><Input type="number" step="0.001" value={qty} onChange={(e) => setQty(e.target.value)} /></div>
|
||||
|
||||
@@ -129,7 +129,7 @@ function RepairsListPage() {
|
||||
}
|
||||
|
||||
function handleRowClick(ticket: RepairTicket) {
|
||||
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: {} as any })
|
||||
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -137,7 +137,7 @@ function RepairsListPage() {
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Repairs</h1>
|
||||
{hasPermission('repairs.edit') && (
|
||||
<Button onClick={() => navigate({ to: '/repairs/new', search: {} as any })}>
|
||||
<Button onClick={() => navigate({ to: '/repairs/new', search: { batchId: undefined, batchName: undefined, accountId: undefined, contactName: undefined } })}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Repair
|
||||
</Button>
|
||||
|
||||
@@ -136,7 +136,7 @@ function NewRepairPage() {
|
||||
},
|
||||
onSuccess: (ticket) => {
|
||||
toast.success('Repair ticket created')
|
||||
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: {} as any })
|
||||
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
@@ -210,7 +210,7 @@ function NewRepairPage() {
|
||||
return (
|
||||
<div className="space-y-6 max-w-4xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repairs', search: {} as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repairs', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h1 className="text-2xl font-bold">New Repair Ticket</h1>
|
||||
@@ -314,7 +314,7 @@ function NewRepairPage() {
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Condition at Intake</Label>
|
||||
<Select onValueChange={(v) => setValue('conditionIn', v as any)}>
|
||||
<Select onValueChange={(v) => setValue('conditionIn', v as 'excellent' | 'good' | 'fair' | 'poor')}>
|
||||
<SelectTrigger><SelectValue placeholder="Select condition" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="excellent">Excellent</SelectItem>
|
||||
@@ -486,7 +486,7 @@ function NewRepairPage() {
|
||||
<Button type="submit" disabled={mutation.isPending} size="lg">
|
||||
{mutation.isPending ? 'Creating...' : 'Create Ticket'}
|
||||
</Button>
|
||||
<Button variant="secondary" type="button" size="lg" onClick={() => navigate({ to: '/repairs', search: {} as any })}>
|
||||
<Button variant="secondary" type="button" size="lg" onClick={() => navigate({ to: '/repairs', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
180
packages/admin/src/routes/_authenticated/reports/daily.tsx
Normal file
180
packages/admin/src/routes/_authenticated/reports/daily.tsx
Normal file
@@ -0,0 +1,180 @@
|
||||
import { useState } from 'react'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { dailyReportOptions } from '@/api/pos'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
interface Location {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
function locationsOptions() {
|
||||
return queryOptions({
|
||||
queryKey: ['locations'],
|
||||
queryFn: () => api.get<{ data: Location[] }>('/v1/locations'),
|
||||
})
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/reports/daily')({
|
||||
component: DailyReportPage,
|
||||
})
|
||||
|
||||
const PAYMENT_LABELS: Record<string, string> = {
|
||||
cash: 'Cash',
|
||||
card_present: 'Card (Present)',
|
||||
card_keyed: 'Card (Keyed)',
|
||||
check: 'Check',
|
||||
account_charge: 'Account',
|
||||
}
|
||||
|
||||
function DailyReportPage() {
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
const [date, setDate] = useState(today)
|
||||
const [locationId, setLocationId] = useState<string | null>(null)
|
||||
|
||||
const { data: locationsData } = useQuery(locationsOptions())
|
||||
const locations = locationsData?.data ?? []
|
||||
|
||||
// Auto-select first location
|
||||
if (!locationId && locations.length > 0) {
|
||||
setLocationId(locations[0].id)
|
||||
}
|
||||
|
||||
const { data: report, isLoading } = useQuery(dailyReportOptions(locationId, date))
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-3xl">
|
||||
<h1 className="text-2xl font-bold">Daily Report</h1>
|
||||
|
||||
<div className="flex gap-4">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Date</Label>
|
||||
<Input type="date" value={date} onChange={(e) => setDate(e.target.value)} className="w-44" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Location</Label>
|
||||
<Select value={locationId ?? ''} onValueChange={setLocationId}>
|
||||
<SelectTrigger className="w-48">
|
||||
<SelectValue placeholder="Select location" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{locations.map((loc) => (
|
||||
<SelectItem key={loc.id} value={loc.id}>{loc.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-32 w-full" />
|
||||
<Skeleton className="h-48 w-full" />
|
||||
</div>
|
||||
) : !report ? (
|
||||
<p className="text-muted-foreground">Select a location and date to view the report.</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{/* Sessions */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Drawer Sessions ({report.sessions.length})</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{report.sessions.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No drawer sessions on this date.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{report.sessions.map((s: any) => (
|
||||
<div key={s.id} className="flex items-center justify-between p-2 rounded border text-sm">
|
||||
<div>
|
||||
<span className="font-medium">{s.register?.name ?? 'Unassigned'}</span>
|
||||
<span className="text-muted-foreground ml-2">
|
||||
{new Date(s.openedAt).toLocaleTimeString()} — {s.closedAt ? new Date(s.closedAt).toLocaleTimeString() : 'Open'}
|
||||
</span>
|
||||
{s.openedBy && <span className="text-muted-foreground ml-2">({s.openedBy.firstName})</span>}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="tabular-nums text-sm">${s.grossSales.toFixed(2)}</span>
|
||||
{s.overShort !== null && (
|
||||
<Badge variant={s.overShort === 0 ? 'default' : 'destructive'} className="text-xs">
|
||||
{s.overShort === 0 ? 'Balanced' : `${s.overShort > 0 ? '+' : ''}$${s.overShort.toFixed(2)}`}
|
||||
</Badge>
|
||||
)}
|
||||
{s.status === 'open' && <Badge variant="outline" className="text-xs">Open</Badge>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Sales Summary */}
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-base">Sales</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-2 text-sm">
|
||||
<div className="flex justify-between"><span>Transactions</span><span>{report.sales.transactionCount}</span></div>
|
||||
<div className="flex justify-between"><span>Gross Sales</span><span className="tabular-nums">${report.sales.grossSales.toFixed(2)}</span></div>
|
||||
{report.sales.refundTotal > 0 && <div className="flex justify-between text-red-600"><span>Refunds</span><span className="tabular-nums">-${report.sales.refundTotal.toFixed(2)}</span></div>}
|
||||
<Separator />
|
||||
<div className="flex justify-between font-semibold"><span>Net Sales</span><span className="tabular-nums">${report.sales.netSales.toFixed(2)}</span></div>
|
||||
{report.sales.voidCount > 0 && <div className="flex justify-between text-muted-foreground"><span>Voided</span><span>{report.sales.voidCount}</span></div>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Payment Breakdown */}
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-base">Payments</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-2 text-sm">
|
||||
{Object.entries(report.payments as Record<string, { count: number; total: number }>).map(([method, data]) => (
|
||||
<div key={method} className="flex justify-between">
|
||||
<span>{PAYMENT_LABELS[method] ?? method} ({data.count})</span>
|
||||
<span className="tabular-nums">${data.total.toFixed(2)}</span>
|
||||
</div>
|
||||
))}
|
||||
{Object.keys(report.payments).length === 0 && <p className="text-muted-foreground">No payments</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Discounts */}
|
||||
{report.discounts.count > 0 && (
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-base">Discounts</CardTitle></CardHeader>
|
||||
<CardContent className="text-sm">
|
||||
<div className="flex justify-between"><span>Total ({report.discounts.count} transactions)</span><span className="tabular-nums text-green-600">-${report.discounts.total.toFixed(2)}</span></div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Cash Summary */}
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-base">Cash</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-2 text-sm">
|
||||
<div className="flex justify-between"><span>Total Opening</span><span className="tabular-nums">${report.cash.totalOpening.toFixed(2)}</span></div>
|
||||
<div className="flex justify-between"><span>Cash Sales</span><span className="tabular-nums">${report.cash.totalCashSales.toFixed(2)}</span></div>
|
||||
{report.cash.totalCashIn > 0 && <div className="flex justify-between text-green-600"><span>Cash In</span><span className="tabular-nums">+${report.cash.totalCashIn.toFixed(2)}</span></div>}
|
||||
{report.cash.totalCashOut > 0 && <div className="flex justify-between text-red-600"><span>Cash Out</span><span className="tabular-nums">-${report.cash.totalCashOut.toFixed(2)}</span></div>}
|
||||
<Separator />
|
||||
<div className="flex justify-between font-medium"><span>Expected Total</span><span className="tabular-nums">${report.cash.totalExpected.toFixed(2)}</span></div>
|
||||
<div className="flex justify-between"><span>Actual Total</span><span className="tabular-nums">${report.cash.totalActual.toFixed(2)}</span></div>
|
||||
<div className={`flex justify-between font-bold ${report.cash.totalOverShort === 0 ? 'text-green-600' : 'text-red-600'}`}>
|
||||
<span>{report.cash.totalOverShort >= 0 ? 'Over' : 'Short'}</span>
|
||||
<span className="tabular-nums">${Math.abs(report.cash.totalOverShort).toFixed(2)}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -100,7 +100,7 @@ function RoleDetailPage() {
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/roles', search: {} as any })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/roles', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div>
|
||||
@@ -177,7 +177,7 @@ function RoleDetailPage() {
|
||||
<Button onClick={handleSave} disabled={updateMutation.isPending}>
|
||||
{updateMutation.isPending ? 'Saving...' : 'Save Changes'}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles', search: {} as any })}>
|
||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -29,7 +29,7 @@ function NewRolePage() {
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
||||
toast.success('Role created')
|
||||
navigate({ to: '/roles', search: {} as any })
|
||||
navigate({ to: '/roles', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
@@ -153,7 +153,7 @@ function NewRolePage() {
|
||||
<Button onClick={handleSubmit} disabled={mutation.isPending}>
|
||||
{mutation.isPending ? 'Creating...' : 'Create Role'}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles', search: {} as any })}>
|
||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -13,8 +13,11 @@ import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { moduleListOptions, moduleMutations, moduleKeys } from '@/api/modules'
|
||||
import { Save, Plus, Trash2, MapPin, Building, ImageIcon, Blocks, Lock } from 'lucide-react'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { Save, Plus, Trash2, MapPin, Building, ImageIcon, Blocks, Lock, Settings2, Receipt, ShieldCheck } from 'lucide-react'
|
||||
import { OVERRIDE_ACTIONS, getRequiredOverrides, setRequiredOverrides, getDiscountThreshold, setDiscountThreshold, type OverrideAction } from '@/components/pos/pos-manager-override'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
interface StoreSettings {
|
||||
@@ -117,125 +120,150 @@ function SettingsPage() {
|
||||
<div className="space-y-6 max-w-3xl">
|
||||
<h1 className="text-2xl font-bold">Settings</h1>
|
||||
|
||||
{/* Store Info */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Building className="h-5 w-5" />Store Information
|
||||
</CardTitle>
|
||||
{!editing && <Button variant="outline" size="sm" onClick={startEdit}>Edit</Button>}
|
||||
{editing && (
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={saveEdit} disabled={updateMutation.isPending}>
|
||||
<Save className="mr-1 h-3 w-3" />{updateMutation.isPending ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditing(false)}>Cancel</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Logo upload */}
|
||||
<div>
|
||||
<LogoUpload entityId={store.id} category="logo" label="Store Logo" description="Used on PDFs, sidebar, and login screen" />
|
||||
</div>
|
||||
<Tabs defaultValue="store">
|
||||
<TabsList>
|
||||
<TabsTrigger value="store">Store</TabsTrigger>
|
||||
<TabsTrigger value="locations">Locations</TabsTrigger>
|
||||
<TabsTrigger value="modules">Modules</TabsTrigger>
|
||||
<TabsTrigger value="receipt">Receipt</TabsTrigger>
|
||||
<TabsTrigger value="pos">POS Security</TabsTrigger>
|
||||
<TabsTrigger value="advanced">Advanced</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{editing ? (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Store Name *</Label>
|
||||
<Input value={fields.name} onChange={(e) => setFields((p) => ({ ...p, name: e.target.value }))} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Timezone</Label>
|
||||
<Input value={fields.timezone} onChange={(e) => setFields((p) => ({ ...p, timezone: e.target.value }))} placeholder="America/Chicago" />
|
||||
<TabsContent value="store" className="mt-4">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Building className="h-5 w-5" />Store Information
|
||||
</CardTitle>
|
||||
{!editing && <Button variant="outline" size="sm" onClick={startEdit}>Edit</Button>}
|
||||
{editing && (
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={saveEdit} disabled={updateMutation.isPending}>
|
||||
<Save className="mr-1 h-3 w-3" />{updateMutation.isPending ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditing(false)}>Cancel</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div>
|
||||
<LogoUpload entityId={store.id} category="logo" label="Store Logo" description="Used on PDFs, sidebar, and login screen" />
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Phone</Label>
|
||||
<Input value={fields.phone} onChange={(e) => setFields((p) => ({ ...p, phone: e.target.value }))} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Email</Label>
|
||||
<Input value={fields.email} onChange={(e) => setFields((p) => ({ ...p, email: e.target.value }))} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Street</Label>
|
||||
<Input value={fields.street} onChange={(e) => setFields((p) => ({ ...p, street: e.target.value }))} />
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div className="space-y-2">
|
||||
<Label>City</Label>
|
||||
<Input value={fields.city} onChange={(e) => setFields((p) => ({ ...p, city: e.target.value }))} />
|
||||
|
||||
{editing ? (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Store Name *</Label>
|
||||
<Input value={fields.name} onChange={(e) => setFields((p) => ({ ...p, name: e.target.value }))} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Timezone</Label>
|
||||
<Input value={fields.timezone} onChange={(e) => setFields((p) => ({ ...p, timezone: e.target.value }))} placeholder="America/Chicago" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Phone</Label>
|
||||
<Input value={fields.phone} onChange={(e) => setFields((p) => ({ ...p, phone: e.target.value }))} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Email</Label>
|
||||
<Input value={fields.email} onChange={(e) => setFields((p) => ({ ...p, email: e.target.value }))} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Street</Label>
|
||||
<Input value={fields.street} onChange={(e) => setFields((p) => ({ ...p, street: e.target.value }))} />
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div className="space-y-2">
|
||||
<Label>City</Label>
|
||||
<Input value={fields.city} onChange={(e) => setFields((p) => ({ ...p, city: e.target.value }))} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>State</Label>
|
||||
<Input value={fields.state} onChange={(e) => setFields((p) => ({ ...p, state: e.target.value }))} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>ZIP</Label>
|
||||
<Input value={fields.zip} onChange={(e) => setFields((p) => ({ ...p, zip: e.target.value }))} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>State</Label>
|
||||
<Input value={fields.state} onChange={(e) => setFields((p) => ({ ...p, state: e.target.value }))} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>ZIP</Label>
|
||||
<Input value={fields.zip} onChange={(e) => setFields((p) => ({ ...p, zip: e.target.value }))} />
|
||||
<Label>Notes</Label>
|
||||
<Textarea value={fields.notes} onChange={(e) => setFields((p) => ({ ...p, notes: e.target.value }))} rows={2} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Notes</Label>
|
||||
<Textarea value={fields.notes} onChange={(e) => setFields((p) => ({ ...p, notes: e.target.value }))} rows={2} />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="text-lg font-semibold">{store.name}</div>
|
||||
<div><span className="text-muted-foreground">Phone:</span> {store.phone ?? '-'}</div>
|
||||
<div><span className="text-muted-foreground">Email:</span> {store.email ?? '-'}</div>
|
||||
<div><span className="text-muted-foreground">Timezone:</span> {store.timezone}</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="text-lg font-semibold">{store.name}</div>
|
||||
<div><span className="text-muted-foreground">Phone:</span> {store.phone ?? '-'}</div>
|
||||
<div><span className="text-muted-foreground">Email:</span> {store.email ?? '-'}</div>
|
||||
<div><span className="text-muted-foreground">Timezone:</span> {store.timezone}</div>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm">
|
||||
{store.address && (store.address.street || store.address.city) ? (
|
||||
<>
|
||||
<div className="font-medium flex items-center gap-1"><MapPin className="h-3 w-3" />Address</div>
|
||||
{store.address.street && <div>{store.address.street}</div>}
|
||||
<div>{[store.address.city, store.address.state, store.address.zip].filter(Boolean).join(', ')}</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-muted-foreground">No address set</div>
|
||||
)}
|
||||
{store.notes && <div className="mt-2"><span className="text-muted-foreground">Notes:</span> {store.notes}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm">
|
||||
{store.address && (store.address.street || store.address.city) ? (
|
||||
<>
|
||||
<div className="font-medium flex items-center gap-1"><MapPin className="h-3 w-3" />Address</div>
|
||||
{store.address.street && <div>{store.address.street}</div>}
|
||||
<div>{[store.address.city, store.address.state, store.address.zip].filter(Boolean).join(', ')}</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-muted-foreground">No address set</div>
|
||||
)}
|
||||
{store.notes && <div className="mt-2"><span className="text-muted-foreground">Notes:</span> {store.notes}</div>}
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="locations" className="mt-4">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<MapPin className="h-5 w-5" />Locations
|
||||
</CardTitle>
|
||||
<AddLocationDialog open={addLocationOpen} onOpenChange={setAddLocationOpen} />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{locations.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">No locations yet — add your first store location</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{locations.map((loc) => (
|
||||
<LocationCard key={loc.id} location={loc} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* Locations */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<MapPin className="h-5 w-5" />Locations
|
||||
</CardTitle>
|
||||
<AddLocationDialog open={addLocationOpen} onOpenChange={setAddLocationOpen} />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{locations.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">No locations yet — add your first store location</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{locations.map((loc) => (
|
||||
<LocationCard key={loc.id} location={loc} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<TabsContent value="modules" className="mt-4">
|
||||
<ModulesCard />
|
||||
</TabsContent>
|
||||
|
||||
{/* Modules */}
|
||||
<ModulesCard />
|
||||
<TabsContent value="receipt" className="mt-4">
|
||||
<ReceiptSettingsCard />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="pos" className="mt-4">
|
||||
<ManagerOverridesCard />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="advanced" className="mt-4">
|
||||
<AppConfigCard />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -296,6 +324,250 @@ function ModulesCard() {
|
||||
)
|
||||
}
|
||||
|
||||
interface AppConfigEntry {
|
||||
key: string
|
||||
value: string | null
|
||||
description: string | null
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
const LOG_LEVELS = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const
|
||||
|
||||
function configOptions() {
|
||||
return queryOptions({
|
||||
queryKey: ['config'],
|
||||
queryFn: () => api.get<{ data: AppConfigEntry[] }>('/v1/config'),
|
||||
})
|
||||
}
|
||||
|
||||
function AppConfigCard() {
|
||||
const queryClient = useQueryClient()
|
||||
const hasPermission = useAuthStore((s) => s.hasPermission)
|
||||
const canEdit = hasPermission('settings.edit')
|
||||
|
||||
const { data: configData, isLoading } = useQuery(configOptions())
|
||||
const configs = configData?.data ?? []
|
||||
const logLevel = configs.find((c) => c.key === 'log_level')?.value ?? 'info'
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ key, value }: { key: string; value: string }) =>
|
||||
api.patch<AppConfigEntry>(`/v1/config/${key}`, { value }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['config'] })
|
||||
toast.success('Configuration updated')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Settings2 className="h-5 w-5" />App Configuration
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<Skeleton className="h-12 w-full" />
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between p-3 rounded-md border">
|
||||
<div className="min-w-0">
|
||||
<span className="font-medium text-sm">Log Level</span>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">Controls the verbosity of application logs</p>
|
||||
</div>
|
||||
<Select
|
||||
value={logLevel}
|
||||
onValueChange={(value) => updateMutation.mutate({ key: 'log_level', value })}
|
||||
disabled={!canEdit || updateMutation.isPending}
|
||||
>
|
||||
<SelectTrigger className="w-32">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{LOG_LEVELS.map((level) => (
|
||||
<SelectItem key={level} value={level}>
|
||||
{level}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
const RECEIPT_FIELDS = [
|
||||
{ key: 'receipt_header', label: 'Header Text', placeholder: "e.g. San Antonio's Premier String Shop", multiline: false },
|
||||
{ key: 'receipt_footer', label: 'Footer Message', placeholder: 'e.g. Thank you for your business!', multiline: false },
|
||||
{ key: 'receipt_return_policy', label: 'Return Policy', placeholder: 'e.g. Returns accepted within 30 days with receipt.', multiline: true },
|
||||
{ key: 'receipt_social', label: 'Website / Social', placeholder: 'e.g. www.demostore.com | @demostore', multiline: false },
|
||||
]
|
||||
|
||||
function ReceiptSettingsCard() {
|
||||
const queryClient = useQueryClient()
|
||||
const hasPermission = useAuthStore((s) => s.hasPermission)
|
||||
const canEdit = hasPermission('settings.edit')
|
||||
|
||||
const { data: configData, isLoading } = useQuery(configOptions())
|
||||
const configs = configData?.data ?? []
|
||||
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [fields, setFields] = useState<Record<string, string>>({})
|
||||
|
||||
function startEdit() {
|
||||
const f: Record<string, string> = {}
|
||||
for (const rf of RECEIPT_FIELDS) {
|
||||
f[rf.key] = configs.find((c) => c.key === rf.key)?.value ?? ''
|
||||
}
|
||||
setFields(f)
|
||||
setEditing(true)
|
||||
}
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
for (const rf of RECEIPT_FIELDS) {
|
||||
await api.patch(`/v1/config/${rf.key}`, { value: fields[rf.key] || '' })
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['config'] })
|
||||
toast.success('Receipt settings saved')
|
||||
setEditing(false)
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Receipt className="h-5 w-5" />Receipt Customization
|
||||
</CardTitle>
|
||||
{canEdit && !editing && <Button variant="outline" size="sm" onClick={startEdit}>Edit</Button>}
|
||||
{editing && (
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={() => saveMutation.mutate()} disabled={saveMutation.isPending}>
|
||||
<Save className="mr-1 h-3 w-3" />{saveMutation.isPending ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditing(false)}>Cancel</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<Skeleton className="h-32 w-full" />
|
||||
) : editing ? (
|
||||
<div className="space-y-4">
|
||||
{RECEIPT_FIELDS.map((rf) => (
|
||||
<div key={rf.key} className="space-y-2">
|
||||
<Label>{rf.label}</Label>
|
||||
{rf.multiline ? (
|
||||
<Textarea
|
||||
value={fields[rf.key] ?? ''}
|
||||
onChange={(e) => setFields((p) => ({ ...p, [rf.key]: e.target.value }))}
|
||||
placeholder={rf.placeholder}
|
||||
rows={2}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
value={fields[rf.key] ?? ''}
|
||||
onChange={(e) => setFields((p) => ({ ...p, [rf.key]: e.target.value }))}
|
||||
placeholder={rf.placeholder}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{RECEIPT_FIELDS.map((rf) => {
|
||||
const value = configs.find((c) => c.key === rf.key)?.value
|
||||
return (
|
||||
<div key={rf.key} className="flex justify-between items-start">
|
||||
<span className="text-sm text-muted-foreground">{rf.label}</span>
|
||||
<span className="text-sm text-right max-w-[60%]">{value || <span className="text-muted-foreground/50">Not set</span>}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function ManagerOverridesCard() {
|
||||
const [overrides, setOverrides] = useState<Set<OverrideAction>>(() => getRequiredOverrides())
|
||||
const [threshold, setThreshold] = useState(() => getDiscountThreshold())
|
||||
|
||||
function toggle(action: OverrideAction) {
|
||||
setOverrides((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(action)) next.delete(action)
|
||||
else next.add(action)
|
||||
setRequiredOverrides(next)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<ShieldCheck className="h-5 w-5" />Manager Overrides
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
When enabled, these actions will require a manager or admin to enter their PIN before proceeding. This setting is stored per device.
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
{OVERRIDE_ACTIONS.map((action) => (
|
||||
<div key={action.key} className="flex items-center justify-between p-3 rounded-md border">
|
||||
<div className="min-w-0">
|
||||
<span className="font-medium text-sm">{action.label}</span>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">{action.description}</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={overrides.has(action.key)}
|
||||
onCheckedChange={() => toggle(action.key)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mt-4 p-3 rounded-md border">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="min-w-0">
|
||||
<span className="font-medium text-sm">Discount Threshold</span>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">Require manager approval for discounts at or above this percentage. Set to 0 to disable.</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
max="100"
|
||||
className="w-20 h-8 text-sm text-right"
|
||||
value={threshold}
|
||||
onChange={(e) => {
|
||||
const v = parseInt(e.target.value) || 0
|
||||
setThreshold(v)
|
||||
setDiscountThreshold(v)
|
||||
}}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function LocationCard({ location }: { location: Location }) {
|
||||
const queryClient = useQueryClient()
|
||||
const [editing, setEditing] = useState(false)
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
import { useState } from 'react'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { createFileRoute, useRouter, redirect } from '@tanstack/react-router'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import { login } from '@/api/auth'
|
||||
import { login, forgotPassword } from '@/api/auth'
|
||||
|
||||
interface Branding {
|
||||
name: string | null
|
||||
hasLogo: boolean
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/login')({
|
||||
beforeLoad: () => {
|
||||
const { token } = useAuthStore.getState()
|
||||
if (token) {
|
||||
throw redirect({ to: '/accounts', search: {} as any })
|
||||
throw redirect({ to: '/accounts', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })
|
||||
}
|
||||
},
|
||||
component: LoginPage,
|
||||
@@ -20,6 +25,16 @@ function LoginPage() {
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [branding, setBranding] = useState<Branding | null>(null)
|
||||
const [forgotMode, setForgotMode] = useState(false)
|
||||
const [forgotSent, setForgotSent] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/v1/store/branding')
|
||||
.then((r) => r.ok ? r.json() : null)
|
||||
.then((data) => { if (data) setBranding(data) })
|
||||
.catch(() => {})
|
||||
}, [])
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
@@ -30,7 +45,7 @@ function LoginPage() {
|
||||
const res = await login(email, password)
|
||||
setAuth(res.token, res.user)
|
||||
await router.invalidate()
|
||||
await router.navigate({ to: '/accounts', search: {} as any, replace: true })
|
||||
await router.navigate({ to: '/accounts', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const }, replace: true })
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Login failed')
|
||||
} finally {
|
||||
@@ -48,45 +63,128 @@ function LoginPage() {
|
||||
style={{ backgroundColor: '#131c2e', borderColor: '#1e2d45' }}
|
||||
>
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-3xl font-bold" style={{ color: '#d8dfe9' }}>LunarFront</h1>
|
||||
<p className="text-sm mt-1" style={{ color: '#6b7a8d' }}>Small Business Management</p>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Email</label>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="you@example.com"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Password</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
|
||||
{branding?.hasLogo ? (
|
||||
<img src="/v1/store/logo" alt={branding.name ?? 'Store'} className="max-h-14 max-w-[220px] object-contain mx-auto" />
|
||||
) : (
|
||||
<h1 className="text-3xl font-bold" style={{ color: '#d8dfe9' }}>{branding?.name ?? 'LunarFront'}</h1>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
|
||||
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
|
||||
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
|
||||
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
|
||||
>
|
||||
{loading ? 'Signing in...' : 'Sign in'}
|
||||
</button>
|
||||
</form>
|
||||
{branding?.name ? (
|
||||
<p className="text-[10px] mt-2" style={{ color: '#4a5568' }}>Powered by <span style={{ color: '#6b7a8d' }}>LunarFront</span></p>
|
||||
) : (
|
||||
<p className="text-sm mt-1" style={{ color: '#6b7a8d' }}>Small Business Management</p>
|
||||
)}
|
||||
</div>
|
||||
{forgotMode ? (
|
||||
forgotSent ? (
|
||||
<div className="text-center space-y-4">
|
||||
<p className="text-sm" style={{ color: '#b0bec5' }}>If an account exists with that email, you will receive a password reset link.</p>
|
||||
<button
|
||||
onClick={() => { setForgotMode(false); setForgotSent(false); setError('') }}
|
||||
className="text-xs"
|
||||
style={{ color: '#6b7a8d' }}
|
||||
>
|
||||
Back to sign in
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
await forgotPassword(email)
|
||||
setForgotSent(true)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Something went wrong')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}} className="space-y-4">
|
||||
<p className="text-sm" style={{ color: '#b0bec5' }}>Enter your email and we'll send you a reset link.</p>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Email</label>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="you@example.com"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
|
||||
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
|
||||
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
|
||||
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
|
||||
>
|
||||
{loading ? 'Sending...' : 'Send reset link'}
|
||||
</button>
|
||||
<div className="text-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setForgotMode(false); setError('') }}
|
||||
className="text-xs"
|
||||
style={{ color: '#6b7a8d' }}
|
||||
>
|
||||
Back to sign in
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
) : (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Email</label>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="you@example.com"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Password</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
|
||||
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
|
||||
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
|
||||
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
|
||||
>
|
||||
{loading ? 'Signing in...' : 'Sign in'}
|
||||
</button>
|
||||
<div className="text-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setForgotMode(true); setError('') }}
|
||||
className="text-xs"
|
||||
style={{ color: '#6b7a8d' }}
|
||||
>
|
||||
Forgot password?
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
14
packages/admin/src/routes/pos.tsx
Normal file
14
packages/admin/src/routes/pos.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { POSRegister } from '@/components/pos/pos-register'
|
||||
|
||||
export const Route = createFileRoute('/pos')({
|
||||
component: POSPage,
|
||||
})
|
||||
|
||||
function POSPage() {
|
||||
return (
|
||||
<div className="h-screen w-screen overflow-hidden bg-background text-foreground">
|
||||
<POSRegister />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
154
packages/admin/src/routes/reset-password.tsx
Normal file
154
packages/admin/src/routes/reset-password.tsx
Normal file
@@ -0,0 +1,154 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { resetPassword } from '@/api/auth'
|
||||
|
||||
interface Branding {
|
||||
name: string | null
|
||||
hasLogo: boolean
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/reset-password')({
|
||||
component: ResetPasswordPage,
|
||||
})
|
||||
|
||||
function ResetPasswordPage() {
|
||||
const { token } = Route.useSearch() as { token?: string }
|
||||
const [password, setPassword] = useState('')
|
||||
const [confirmPassword, setConfirmPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [success, setSuccess] = useState(false)
|
||||
const [branding, setBranding] = useState<Branding | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/v1/store/branding')
|
||||
.then((r) => r.ok ? r.json() : null)
|
||||
.then((data) => { if (data) setBranding(data) })
|
||||
.catch(() => {})
|
||||
}, [])
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
|
||||
if (!token) {
|
||||
setError('Missing reset token. Please use the link from your email.')
|
||||
return
|
||||
}
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
setError('Passwords do not match')
|
||||
return
|
||||
}
|
||||
|
||||
if (password.length < 12) {
|
||||
setError('Password must be at least 12 characters')
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
await resetPassword(token, password)
|
||||
setSuccess(true)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Reset failed. The link may have expired.')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex min-h-screen items-center justify-center"
|
||||
style={{ background: 'linear-gradient(135deg, #0f1724 0%, #142038 100%)' }}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-sm rounded-xl border p-8 shadow-2xl"
|
||||
style={{ backgroundColor: '#131c2e', borderColor: '#1e2d45' }}
|
||||
>
|
||||
<div className="text-center mb-8">
|
||||
{branding?.hasLogo ? (
|
||||
<img src="/v1/store/logo" alt={branding.name ?? 'Store'} className="max-h-14 max-w-[220px] object-contain mx-auto" />
|
||||
) : (
|
||||
<h1 className="text-3xl font-bold" style={{ color: '#d8dfe9' }}>{branding?.name ?? 'LunarFront'}</h1>
|
||||
)}
|
||||
{branding?.name ? (
|
||||
<p className="text-[10px] mt-2" style={{ color: '#4a5568' }}>Powered by <span style={{ color: '#6b7a8d' }}>LunarFront</span></p>
|
||||
) : (
|
||||
<p className="text-sm mt-1" style={{ color: '#6b7a8d' }}>Small Business Management</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{success ? (
|
||||
<div className="text-center space-y-4">
|
||||
<p style={{ color: '#81c784' }}>Password reset successfully.</p>
|
||||
<Link
|
||||
to="/login"
|
||||
className="inline-block h-9 rounded-md border px-4 py-2 text-sm font-medium transition-colors"
|
||||
style={{ color: '#d0d8e0', borderColor: '#3a4a62' }}
|
||||
>
|
||||
Sign in
|
||||
</Link>
|
||||
</div>
|
||||
) : !token ? (
|
||||
<div className="text-center space-y-4">
|
||||
<p style={{ color: '#e57373' }}>Invalid reset link. Please request a new one.</p>
|
||||
<Link
|
||||
to="/login"
|
||||
className="inline-block h-9 rounded-md border px-4 py-2 text-sm font-medium transition-colors"
|
||||
style={{ color: '#d0d8e0', borderColor: '#3a4a62' }}
|
||||
>
|
||||
Back to sign in
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<h2 className="text-lg font-semibold text-center mb-4" style={{ color: '#d8dfe9' }}>Set new password</h2>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>New password</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
minLength={12}
|
||||
placeholder="At least 12 characters"
|
||||
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Confirm password</label>
|
||||
<input
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
required
|
||||
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
|
||||
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
|
||||
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
|
||||
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
|
||||
>
|
||||
{loading ? 'Resetting...' : 'Reset password'}
|
||||
</button>
|
||||
<div className="text-center">
|
||||
<Link to="/login" className="text-xs" style={{ color: '#6b7a8d' }}>
|
||||
Back to sign in
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
72
packages/admin/src/stores/pos.store.ts
Normal file
72
packages/admin/src/stores/pos.store.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { create } from 'zustand'
|
||||
|
||||
interface POSUser {
|
||||
id: string
|
||||
email: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
role: string
|
||||
}
|
||||
|
||||
type ReceiptFormat = 'thermal' | 'full'
|
||||
|
||||
interface POSState {
|
||||
currentTransactionId: string | null
|
||||
locationId: string | null
|
||||
registerId: string | null
|
||||
drawerSessionId: string | null
|
||||
locked: boolean
|
||||
cashier: POSUser | null
|
||||
token: string | null
|
||||
lastActivity: number
|
||||
accountId: string | null
|
||||
accountName: string | null
|
||||
accountPhone: string | null
|
||||
accountEmail: string | null
|
||||
receiptFormat: ReceiptFormat
|
||||
setTransaction: (id: string | null) => void
|
||||
setLocation: (id: string) => void
|
||||
setRegister: (id: string | null) => void
|
||||
setDrawerSession: (id: string | null) => void
|
||||
unlock: (user: POSUser, token: string) => void
|
||||
lock: () => void
|
||||
touchActivity: () => void
|
||||
setAccount: (id: string, name: string, phone?: string | null, email?: string | null) => void
|
||||
clearAccount: () => void
|
||||
setReceiptFormat: (format: ReceiptFormat) => void
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
const RECEIPT_FORMAT_KEY = 'pos_receipt_format'
|
||||
|
||||
function getStoredReceiptFormat(): ReceiptFormat {
|
||||
const stored = localStorage.getItem(RECEIPT_FORMAT_KEY)
|
||||
return stored === 'full' ? 'full' : 'thermal'
|
||||
}
|
||||
|
||||
export const usePOSStore = create<POSState>((set) => ({
|
||||
currentTransactionId: null,
|
||||
locationId: null,
|
||||
registerId: localStorage.getItem('pos_register_id') ?? null,
|
||||
drawerSessionId: localStorage.getItem('pos_drawer_session_id') ?? null,
|
||||
locked: true,
|
||||
cashier: null,
|
||||
token: null,
|
||||
lastActivity: Date.now(),
|
||||
accountId: null,
|
||||
accountName: null,
|
||||
accountPhone: null,
|
||||
accountEmail: null,
|
||||
receiptFormat: getStoredReceiptFormat(),
|
||||
setTransaction: (id) => set({ currentTransactionId: id }),
|
||||
setLocation: (id) => set({ locationId: id }),
|
||||
setRegister: (id) => { if (id) localStorage.setItem('pos_register_id', id); else localStorage.removeItem('pos_register_id'); set({ registerId: id }) },
|
||||
setDrawerSession: (id) => { if (id) localStorage.setItem('pos_drawer_session_id', id); else localStorage.removeItem('pos_drawer_session_id'); set({ drawerSessionId: id }) },
|
||||
unlock: (user, token) => set({ locked: false, cashier: user, token, lastActivity: Date.now() }),
|
||||
lock: () => set({ locked: true, currentTransactionId: null }),
|
||||
touchActivity: () => set({ lastActivity: Date.now() }),
|
||||
setAccount: (id, name, phone, email) => set({ accountId: id, accountName: name, accountPhone: phone ?? null, accountEmail: email ?? null }),
|
||||
clearAccount: () => set({ accountId: null, accountName: null, accountPhone: null, accountEmail: null }),
|
||||
setReceiptFormat: (format) => { localStorage.setItem(RECEIPT_FORMAT_KEY, format); set({ receiptFormat: format }) },
|
||||
reset: () => set({ currentTransactionId: null, accountId: null, accountName: null, accountPhone: null, accountEmail: null }),
|
||||
}))
|
||||
@@ -44,6 +44,7 @@ export interface Product {
|
||||
isSerialized: boolean
|
||||
isRental: boolean
|
||||
isDualUseRepair: boolean
|
||||
isConsumable: boolean
|
||||
price: string | null
|
||||
minPrice: string | null
|
||||
rentalRateMonthly: string | null
|
||||
|
||||
@@ -28,7 +28,7 @@ export interface RepairTicket {
|
||||
export interface RepairLineItem {
|
||||
id: string
|
||||
repairTicketId: string
|
||||
itemType: 'labor' | 'part' | 'flat_rate' | 'misc'
|
||||
itemType: 'labor' | 'part' | 'flat_rate' | 'misc' | 'consumable'
|
||||
description: string
|
||||
productId: string | null
|
||||
qty: string
|
||||
@@ -82,7 +82,7 @@ export interface RepairServiceTemplate {
|
||||
itemCategory: string | null
|
||||
size: string | null
|
||||
description: string | null
|
||||
itemType: 'labor' | 'part' | 'flat_rate' | 'misc'
|
||||
itemType: 'labor' | 'part' | 'flat_rate' | 'misc' | 'consumable'
|
||||
defaultPrice: string
|
||||
defaultCost: string | null
|
||||
sortOrder: number
|
||||
|
||||
@@ -17,6 +17,7 @@ export default defineConfig({
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
allowedHosts: ['dev.lunarfront.tech'],
|
||||
proxy: {
|
||||
'/v1': {
|
||||
target: 'http://localhost:8000',
|
||||
|
||||
37
packages/backend/__tests__/services/tax-consumable.test.ts
Normal file
37
packages/backend/__tests__/services/tax-consumable.test.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { describe, it, expect } from 'bun:test'
|
||||
import { TaxService } from '../../src/services/tax.service.js'
|
||||
|
||||
describe('TaxService.repairItemTypeToTaxCategory — consumable', () => {
|
||||
it('maps consumable to exempt', () => {
|
||||
expect(TaxService.repairItemTypeToTaxCategory('consumable')).toBe('exempt')
|
||||
})
|
||||
|
||||
it('maps labor to service', () => {
|
||||
expect(TaxService.repairItemTypeToTaxCategory('labor')).toBe('service')
|
||||
})
|
||||
|
||||
it('maps part to goods', () => {
|
||||
expect(TaxService.repairItemTypeToTaxCategory('part')).toBe('goods')
|
||||
})
|
||||
|
||||
it('maps flat_rate to goods', () => {
|
||||
expect(TaxService.repairItemTypeToTaxCategory('flat_rate')).toBe('goods')
|
||||
})
|
||||
|
||||
it('maps misc to goods', () => {
|
||||
expect(TaxService.repairItemTypeToTaxCategory('misc')).toBe('goods')
|
||||
})
|
||||
|
||||
it('maps unknown type to goods (default)', () => {
|
||||
expect(TaxService.repairItemTypeToTaxCategory('anything_else')).toBe('goods')
|
||||
})
|
||||
})
|
||||
|
||||
describe('TaxService.getRateForLocation — exempt category', () => {
|
||||
it('returns 0 for exempt tax category without DB call', async () => {
|
||||
// Passing a fake DB and fake locationId — should short-circuit and return 0
|
||||
const fakeDb = {} as any
|
||||
const rate = await TaxService.getRateForLocation(fakeDb, 'fake-id', 'exempt')
|
||||
expect(rate).toBe(0)
|
||||
})
|
||||
})
|
||||
119
packages/backend/__tests__/services/tax.test.ts
Normal file
119
packages/backend/__tests__/services/tax.test.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { describe, it, expect } from 'bun:test'
|
||||
import { TaxService } from '../../src/services/tax.service.js'
|
||||
|
||||
describe('TaxService.calculateTax', () => {
|
||||
it('calculates tax on a simple amount', () => {
|
||||
// 8.25% on $100
|
||||
expect(TaxService.calculateTax(100, 0.0825)).toBe(8.25)
|
||||
})
|
||||
|
||||
it('rounds to 2 decimal places', () => {
|
||||
// 8.25% on $10.01 = 0.825825 → 0.83
|
||||
expect(TaxService.calculateTax(10.01, 0.0825)).toBe(0.83)
|
||||
})
|
||||
|
||||
it('returns 0 for zero rate', () => {
|
||||
expect(TaxService.calculateTax(100, 0)).toBe(0)
|
||||
})
|
||||
|
||||
it('returns 0 for zero amount', () => {
|
||||
expect(TaxService.calculateTax(0, 0.0825)).toBe(0)
|
||||
})
|
||||
|
||||
it('handles small amounts', () => {
|
||||
// 8.25% on $0.99 = 0.081675 → 0.08
|
||||
expect(TaxService.calculateTax(0.99, 0.0825)).toBe(0.08)
|
||||
})
|
||||
|
||||
it('handles large amounts', () => {
|
||||
// 8.25% on $9999.99 = 824.999175 → 825.00
|
||||
expect(TaxService.calculateTax(9999.99, 0.0825)).toBe(825)
|
||||
})
|
||||
|
||||
it('handles 5% service tax rate', () => {
|
||||
// 5% on $60 = 3.00
|
||||
expect(TaxService.calculateTax(60, 0.05)).toBe(3)
|
||||
})
|
||||
|
||||
it('handles fractional cent rounding down', () => {
|
||||
// 7% on $1.01 = 0.0707 → 0.07
|
||||
expect(TaxService.calculateTax(1.01, 0.07)).toBe(0.07)
|
||||
})
|
||||
|
||||
it('handles fractional cent rounding up', () => {
|
||||
// 7% on $1.05 = 0.0735 → 0.07
|
||||
expect(TaxService.calculateTax(1.05, 0.07)).toBe(0.07)
|
||||
})
|
||||
})
|
||||
|
||||
describe('TaxService.roundToNickel', () => {
|
||||
it('rounds .01 down to .00', () => {
|
||||
expect(TaxService.roundToNickel(10.01)).toBe(10.00)
|
||||
})
|
||||
|
||||
it('rounds .02 down to .00', () => {
|
||||
expect(TaxService.roundToNickel(10.02)).toBe(10.00)
|
||||
})
|
||||
|
||||
it('rounds .03 up to .05', () => {
|
||||
expect(TaxService.roundToNickel(10.03)).toBe(10.05)
|
||||
})
|
||||
|
||||
it('rounds .04 up to .05', () => {
|
||||
expect(TaxService.roundToNickel(10.04)).toBe(10.05)
|
||||
})
|
||||
|
||||
it('keeps .05 as is', () => {
|
||||
expect(TaxService.roundToNickel(10.05)).toBe(10.05)
|
||||
})
|
||||
|
||||
it('rounds .06 down to .05', () => {
|
||||
expect(TaxService.roundToNickel(10.06)).toBe(10.05)
|
||||
})
|
||||
|
||||
it('rounds .07 down to .05', () => {
|
||||
expect(TaxService.roundToNickel(10.07)).toBe(10.05)
|
||||
})
|
||||
|
||||
it('rounds .08 up to .10', () => {
|
||||
expect(TaxService.roundToNickel(10.08)).toBe(10.10)
|
||||
})
|
||||
|
||||
it('rounds .09 up to .10', () => {
|
||||
expect(TaxService.roundToNickel(10.09)).toBe(10.10)
|
||||
})
|
||||
|
||||
it('keeps .00 as is', () => {
|
||||
expect(TaxService.roundToNickel(10.00)).toBe(10.00)
|
||||
})
|
||||
|
||||
it('keeps .10 as is', () => {
|
||||
expect(TaxService.roundToNickel(10.10)).toBe(10.10)
|
||||
})
|
||||
|
||||
it('handles zero', () => {
|
||||
expect(TaxService.roundToNickel(0)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('TaxService.repairItemTypeToTaxCategory', () => {
|
||||
it('maps labor to service', () => {
|
||||
expect(TaxService.repairItemTypeToTaxCategory('labor')).toBe('service')
|
||||
})
|
||||
|
||||
it('maps part to goods', () => {
|
||||
expect(TaxService.repairItemTypeToTaxCategory('part')).toBe('goods')
|
||||
})
|
||||
|
||||
it('maps flat_rate to goods', () => {
|
||||
expect(TaxService.repairItemTypeToTaxCategory('flat_rate')).toBe('goods')
|
||||
})
|
||||
|
||||
it('maps misc to goods', () => {
|
||||
expect(TaxService.repairItemTypeToTaxCategory('misc')).toBe('goods')
|
||||
})
|
||||
|
||||
it('maps unknown type to goods (default)', () => {
|
||||
expect(TaxService.repairItemTypeToTaxCategory('something_else')).toBe('goods')
|
||||
})
|
||||
})
|
||||
144
packages/backend/__tests__/utils/email-templates.test.ts
Normal file
144
packages/backend/__tests__/utils/email-templates.test.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
import { describe, it, expect } from 'bun:test'
|
||||
import {
|
||||
renderReceiptEmailHtml,
|
||||
renderReceiptEmailText,
|
||||
renderEstimateEmailHtml,
|
||||
renderEstimateEmailText,
|
||||
} from '../../src/utils/email-templates.js'
|
||||
|
||||
const mockReceipt = {
|
||||
transaction: {
|
||||
transactionNumber: 'TXN-20260405-001',
|
||||
subtotal: '100.00',
|
||||
discountTotal: '10.00',
|
||||
taxTotal: '7.43',
|
||||
total: '97.43',
|
||||
paymentMethod: 'cash',
|
||||
amountTendered: '100.00',
|
||||
changeGiven: '2.57',
|
||||
roundingAdjustment: null,
|
||||
completedAt: '2026-04-05T12:00:00Z',
|
||||
lineItems: [
|
||||
{ description: 'Guitar Strings', qty: 2, unitPrice: '12.99', taxAmount: '2.14', lineTotal: '25.98', discountAmount: null },
|
||||
{ description: 'Tuner', qty: 1, unitPrice: '74.02', taxAmount: '5.29', lineTotal: '74.02', discountAmount: null },
|
||||
],
|
||||
},
|
||||
company: { name: 'Test Store', phone: '555-1234', email: 'store@test.com', address: { street: '123 Main St', city: 'Austin', state: 'TX', zip: '78701' } },
|
||||
location: null,
|
||||
}
|
||||
|
||||
const mockTicket = {
|
||||
ticketNumber: 'RPR-001',
|
||||
customerName: 'Jane Doe',
|
||||
customerPhone: '555-5678',
|
||||
itemDescription: 'Acoustic Guitar',
|
||||
serialNumber: 'AG-12345',
|
||||
problemDescription: 'Cracked neck joint',
|
||||
estimatedCost: '250.00',
|
||||
promisedDate: '2026-04-12',
|
||||
status: 'pending_approval',
|
||||
}
|
||||
|
||||
const mockLineItems = [
|
||||
{ itemType: 'labor', description: 'Neck repair', qty: 1, unitPrice: '150.00', totalPrice: '150.00' },
|
||||
{ itemType: 'part', description: 'Wood glue & clamps', qty: 1, unitPrice: '25.00', totalPrice: '25.00' },
|
||||
{ itemType: 'flat_rate', description: 'Setup & restring', qty: 1, unitPrice: '75.00', totalPrice: '75.00' },
|
||||
]
|
||||
|
||||
const mockCompany = { name: 'Test Store', phone: '555-1234', email: 'store@test.com', address: null }
|
||||
|
||||
describe('renderReceiptEmailHtml', () => {
|
||||
it('renders HTML with transaction details', () => {
|
||||
const html = renderReceiptEmailHtml(mockReceipt as any)
|
||||
expect(html).toContain('TXN-20260405-001')
|
||||
expect(html).toContain('Test Store')
|
||||
expect(html).toContain('Guitar Strings')
|
||||
expect(html).toContain('Tuner')
|
||||
expect(html).toContain('$97.43')
|
||||
expect(html).toContain('$100.00')
|
||||
expect(html).toContain('Powered by LunarFront')
|
||||
})
|
||||
|
||||
it('includes discount when present', () => {
|
||||
const html = renderReceiptEmailHtml(mockReceipt as any)
|
||||
expect(html).toContain('Discount')
|
||||
expect(html).toContain('$10.00')
|
||||
})
|
||||
|
||||
it('includes payment details for cash', () => {
|
||||
const html = renderReceiptEmailHtml(mockReceipt as any)
|
||||
expect(html).toContain('Cash')
|
||||
expect(html).toContain('$2.57')
|
||||
})
|
||||
|
||||
it('includes receipt config when provided', () => {
|
||||
const config = { receipt_footer: 'Thank you!', receipt_return_policy: '30-day returns' }
|
||||
const html = renderReceiptEmailHtml(mockReceipt as any, config)
|
||||
expect(html).toContain('Thank you!')
|
||||
expect(html).toContain('30-day returns')
|
||||
})
|
||||
|
||||
it('includes company address', () => {
|
||||
const html = renderReceiptEmailHtml(mockReceipt as any)
|
||||
expect(html).toContain('123 Main St')
|
||||
expect(html).toContain('Austin')
|
||||
})
|
||||
})
|
||||
|
||||
describe('renderReceiptEmailText', () => {
|
||||
it('renders plain text with transaction details', () => {
|
||||
const text = renderReceiptEmailText(mockReceipt as any)
|
||||
expect(text).toContain('TXN-20260405-001')
|
||||
expect(text).toContain('Guitar Strings')
|
||||
expect(text).toContain('Total: $97.43')
|
||||
expect(text).toContain('Cash')
|
||||
})
|
||||
})
|
||||
|
||||
describe('renderEstimateEmailHtml', () => {
|
||||
it('renders HTML with ticket details', () => {
|
||||
const html = renderEstimateEmailHtml(mockTicket as any, mockLineItems as any, mockCompany as any)
|
||||
expect(html).toContain('RPR-001')
|
||||
expect(html).toContain('Jane Doe')
|
||||
expect(html).toContain('Acoustic Guitar')
|
||||
expect(html).toContain('AG-12345')
|
||||
expect(html).toContain('Cracked neck joint')
|
||||
expect(html).toContain('$250.00')
|
||||
expect(html).toContain('Powered by LunarFront')
|
||||
})
|
||||
|
||||
it('renders line items with types', () => {
|
||||
const html = renderEstimateEmailHtml(mockTicket as any, mockLineItems as any, mockCompany as any)
|
||||
expect(html).toContain('Labor')
|
||||
expect(html).toContain('Neck repair')
|
||||
expect(html).toContain('Part')
|
||||
expect(html).toContain('Flat Rate')
|
||||
expect(html).toContain('Setup & restring')
|
||||
})
|
||||
|
||||
it('includes promised date', () => {
|
||||
const html = renderEstimateEmailHtml(mockTicket as any, mockLineItems as any, mockCompany as any)
|
||||
expect(html).toContain('Estimated completion')
|
||||
expect(html).toContain('Apr')
|
||||
})
|
||||
|
||||
it('renders without line items using estimatedCost', () => {
|
||||
const html = renderEstimateEmailHtml(mockTicket as any, [], mockCompany as any)
|
||||
expect(html).toContain('$250.00')
|
||||
})
|
||||
|
||||
it('includes company phone', () => {
|
||||
const html = renderEstimateEmailHtml(mockTicket as any, mockLineItems as any, mockCompany as any)
|
||||
expect(html).toContain('555-1234')
|
||||
})
|
||||
})
|
||||
|
||||
describe('renderEstimateEmailText', () => {
|
||||
it('renders plain text with ticket details', () => {
|
||||
const text = renderEstimateEmailText(mockTicket as any, mockLineItems as any, mockCompany as any)
|
||||
expect(text).toContain('RPR-001')
|
||||
expect(text).toContain('Jane Doe')
|
||||
expect(text).toContain('Neck repair')
|
||||
expect(text).toContain('$250.00')
|
||||
})
|
||||
})
|
||||
@@ -5,15 +5,18 @@ import { getSuites, runSuite } from './lib/context.js'
|
||||
import { createClient } from './lib/client.js'
|
||||
|
||||
// --- Config ---
|
||||
// Use DATABASE_URL from env if available, otherwise construct from individual vars
|
||||
const DB_HOST = process.env.DB_HOST ?? 'localhost'
|
||||
const DB_PORT = Number(process.env.DB_PORT ?? '5432')
|
||||
const DB_USER = process.env.DB_USER ?? 'lunarfront'
|
||||
const DB_PASS = process.env.DB_PASS ?? 'lunarfront'
|
||||
const TEST_DB = 'lunarfront_api_test'
|
||||
const DB_URL = process.env.DATABASE_URL ?? `postgresql://${DB_USER}:${DB_PASS}@${DB_HOST}:${DB_PORT}/${TEST_DB}`
|
||||
const USE_EXTERNAL_DB = !!process.env.DATABASE_URL
|
||||
const TEST_PORT = 8001
|
||||
const BASE_URL = `http://localhost:${TEST_PORT}`
|
||||
const COMPANY_ID = 'a0000000-0000-0000-0000-000000000001'
|
||||
const LOCATION_ID = 'a0000000-0000-0000-0000-000000000002'
|
||||
const COMPANY_ID = '10000000-1000-4000-8000-000000000001'
|
||||
const LOCATION_ID = '10000000-1000-4000-8000-000000000002'
|
||||
|
||||
// --- Parse CLI args ---
|
||||
const args = process.argv.slice(2)
|
||||
@@ -27,13 +30,16 @@ for (let i = 0; i < args.length; i++) {
|
||||
|
||||
// --- DB setup ---
|
||||
async function setupDatabase() {
|
||||
const adminSql = postgres(`postgresql://${DB_USER}:${DB_PASS}@${DB_HOST}:${DB_PORT}/postgres`)
|
||||
const [exists] = await adminSql`SELECT 1 FROM pg_database WHERE datname = ${TEST_DB}`
|
||||
if (!exists) {
|
||||
await adminSql.unsafe(`CREATE DATABASE ${TEST_DB}`)
|
||||
console.log(` Created database ${TEST_DB}`)
|
||||
if (!USE_EXTERNAL_DB) {
|
||||
// Local: create test DB if needed
|
||||
const adminSql = postgres(`postgresql://${DB_USER}:${DB_PASS}@${DB_HOST}:${DB_PORT}/postgres`)
|
||||
const [exists] = await adminSql`SELECT 1 FROM pg_database WHERE datname = ${TEST_DB}`
|
||||
if (!exists) {
|
||||
await adminSql.unsafe(`CREATE DATABASE ${TEST_DB}`)
|
||||
console.log(` Created database ${TEST_DB}`)
|
||||
}
|
||||
await adminSql.end()
|
||||
}
|
||||
await adminSql.end()
|
||||
|
||||
// Run migrations
|
||||
const { execSync } = await import('child_process')
|
||||
@@ -41,13 +47,13 @@ async function setupDatabase() {
|
||||
cwd: new URL('..', import.meta.url).pathname,
|
||||
env: {
|
||||
...process.env,
|
||||
DATABASE_URL: `postgresql://${DB_USER}:${DB_PASS}@${DB_HOST}:${DB_PORT}/${TEST_DB}`,
|
||||
DATABASE_URL: DB_URL,
|
||||
},
|
||||
stdio: 'pipe',
|
||||
})
|
||||
|
||||
// Truncate all tables
|
||||
const testSql = postgres(`postgresql://${DB_USER}:${DB_PASS}@${DB_HOST}:${DB_PORT}/${TEST_DB}`)
|
||||
const testSql = postgres(DB_URL)
|
||||
await testSql.unsafe(`
|
||||
DO $$ DECLARE r RECORD;
|
||||
BEGIN
|
||||
@@ -61,7 +67,8 @@ async function setupDatabase() {
|
||||
|
||||
// Seed company + location (company table stays as store settings)
|
||||
await testSql`INSERT INTO company (id, name, timezone) VALUES (${COMPANY_ID}, 'Test Store', 'America/Chicago')`
|
||||
await testSql`INSERT INTO location (id, name) VALUES (${LOCATION_ID}, 'Test Location')`
|
||||
await testSql`INSERT INTO location (id, name, tax_rate, service_tax_rate) VALUES (${LOCATION_ID}, 'Test Location', '0.0825', '0.0500')`
|
||||
await testSql`INSERT INTO location (id, name, tax_rate, service_tax_rate, cash_rounding) VALUES ('10000000-1000-4000-8000-000000000003', 'Rounding Location', '0.0825', '0.0500', true)`
|
||||
|
||||
// Seed lookup tables
|
||||
const { SYSTEM_UNIT_STATUSES, SYSTEM_ITEM_CONDITIONS } = await import('../src/db/schema/lookups.js')
|
||||
@@ -107,6 +114,10 @@ async function setupDatabase() {
|
||||
await testSql`INSERT INTO module_config (slug, name, description, licensed, enabled) VALUES (${m.slug}, ${m.name}, ${m.description}, true, ${m.enabled}) ON CONFLICT (slug) DO NOTHING`
|
||||
}
|
||||
|
||||
// Seed test email provider so email endpoints work without real provider
|
||||
await testSql`INSERT INTO app_settings (key, value, is_encrypted) VALUES ('email.provider', 'test', false) ON CONFLICT (key) DO NOTHING`
|
||||
await testSql`INSERT INTO app_settings (key, value, is_encrypted) VALUES ('email.from_address', 'Test Store <noreply@test.com>', false) ON CONFLICT (key) DO NOTHING`
|
||||
|
||||
await testSql.end()
|
||||
console.log(' Database ready')
|
||||
}
|
||||
@@ -115,7 +126,12 @@ async function setupDatabase() {
|
||||
async function killPort(port: number) {
|
||||
try {
|
||||
const { execSync } = await import('child_process')
|
||||
execSync(`lsof -ti:${port} | xargs kill -9 2>/dev/null || true`, { stdio: 'pipe' })
|
||||
// Try lsof first, fall back to fuser
|
||||
try {
|
||||
execSync(`lsof -ti:${port} | xargs kill -9 2>/dev/null || true`, { stdio: 'pipe' })
|
||||
} catch {
|
||||
execSync(`fuser -k ${port}/tcp 2>/dev/null || true`, { stdio: 'pipe' })
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 1000))
|
||||
} catch {}
|
||||
}
|
||||
@@ -127,7 +143,7 @@ async function startBackend(): Promise<Subprocess> {
|
||||
cwd: new URL('..', import.meta.url).pathname,
|
||||
env: {
|
||||
...process.env,
|
||||
DATABASE_URL: `postgresql://${DB_USER}:${DB_PASS}@${DB_HOST}:${DB_PORT}/${TEST_DB}`,
|
||||
DATABASE_URL: DB_URL,
|
||||
REDIS_URL: process.env.REDIS_URL ?? 'redis://localhost:6379',
|
||||
JWT_SECRET: 'test-secret-for-api-tests',
|
||||
PORT: String(TEST_PORT),
|
||||
@@ -181,7 +197,7 @@ async function registerTestUser(): Promise<string> {
|
||||
|
||||
// Assign admin role to the user via direct SQL
|
||||
if (registerRes.status === 201 && registerData.user) {
|
||||
const assignSql = postgres(`postgresql://${DB_USER}:${DB_PASS}@${DB_HOST}:${DB_PORT}/${TEST_DB}`)
|
||||
const assignSql = postgres(DB_URL)
|
||||
const [adminRole] = await assignSql`SELECT id FROM role WHERE slug = 'admin' LIMIT 1`
|
||||
if (adminRole) {
|
||||
await assignSql`INSERT INTO user_role_assignment (user_id, role_id) VALUES (${registerData.user.id}, ${adminRole.id}) ON CONFLICT DO NOTHING`
|
||||
|
||||
1098
packages/backend/api-tests/suites/pos.ts
Normal file
1098
packages/backend/api-tests/suites/pos.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -510,4 +510,55 @@ suite('Repairs', { tags: ['repairs'] }, (t) => {
|
||||
const fileRes = await fetch(`${t.baseUrl}${signedRes.data.url}`)
|
||||
t.assert.equal(fileRes.status, 200)
|
||||
})
|
||||
|
||||
// ─── Email Estimate ─────────────────────────────────────────────────────────
|
||||
|
||||
t.test('emails a repair estimate', { tags: ['tickets', 'email'] }, async () => {
|
||||
const ticket = await t.api.post('/v1/repair-tickets', {
|
||||
customerName: 'Email Estimate Customer',
|
||||
itemDescription: 'Broken Laptop',
|
||||
problemDescription: 'Won\'t power on',
|
||||
conditionIn: 'poor',
|
||||
estimatedCost: 200,
|
||||
})
|
||||
await t.api.post(`/v1/repair-tickets/${ticket.data.id}/line-items`, {
|
||||
itemType: 'labor',
|
||||
description: 'Diagnostic fee',
|
||||
qty: 1,
|
||||
unitPrice: 50,
|
||||
})
|
||||
|
||||
const res = await t.api.post(`/v1/repair-tickets/${ticket.data.id}/email-estimate`, { email: 'customer@test.com' })
|
||||
t.assert.status(res, 200)
|
||||
t.assert.equal(res.data.message, 'Estimate sent')
|
||||
t.assert.equal(res.data.sentTo, 'customer@test.com')
|
||||
})
|
||||
|
||||
t.test('rejects estimate email with invalid email', { tags: ['tickets', 'email', 'validation'] }, async () => {
|
||||
const ticket = await t.api.post('/v1/repair-tickets', {
|
||||
customerName: 'Bad Email Customer',
|
||||
problemDescription: 'Test',
|
||||
conditionIn: 'good',
|
||||
})
|
||||
const res = await t.api.post(`/v1/repair-tickets/${ticket.data.id}/email-estimate`, { email: 'bad' })
|
||||
t.assert.status(res, 400)
|
||||
})
|
||||
|
||||
t.test('returns 404 for estimate email on nonexistent ticket', { tags: ['tickets', 'email', 'validation'] }, async () => {
|
||||
const res = await t.api.post('/v1/repair-tickets/00000000-0000-0000-0000-000000000000/email-estimate', { email: 'test@test.com' })
|
||||
t.assert.status(res, 404)
|
||||
})
|
||||
|
||||
t.test('ticket detail includes customerEmail from account', { tags: ['tickets', 'email'] }, async () => {
|
||||
const acct = await t.api.post('/v1/accounts', { name: 'Repair Email Acct', email: 'repair@test.com', billingMode: 'consolidated' })
|
||||
const ticket = await t.api.post('/v1/repair-tickets', {
|
||||
customerName: 'Repair Email Acct',
|
||||
accountId: acct.data.id,
|
||||
problemDescription: 'Email test',
|
||||
conditionIn: 'good',
|
||||
})
|
||||
const detail = await t.api.get(`/v1/repair-tickets/${ticket.data.id}`)
|
||||
t.assert.status(detail, 200)
|
||||
t.assert.equal(detail.data.customerEmail, 'repair@test.com')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"name": "@lunarfront/backend",
|
||||
"version": "0.0.26",
|
||||
"version": "0.1.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun --watch run src/main.ts",
|
||||
"dev": "bun --env-file=../../.env --watch run src/main.ts",
|
||||
"start": "bun run src/main.ts",
|
||||
"test": "bun test || true",
|
||||
"test:watch": "bun test --watch",
|
||||
|
||||
@@ -2,3 +2,5 @@ export * from './schema/stores.js'
|
||||
export * from './schema/users.js'
|
||||
export * from './schema/accounts.js'
|
||||
export * from './schema/inventory.js'
|
||||
export * from './schema/pos.js'
|
||||
export * from './schema/settings.js'
|
||||
|
||||
111
packages/backend/src/db/migrations/0038_pos-core.sql
Normal file
111
packages/backend/src/db/migrations/0038_pos-core.sql
Normal file
@@ -0,0 +1,111 @@
|
||||
-- POS core: enums, tables, and new columns on existing tables
|
||||
|
||||
-- New enums
|
||||
CREATE TYPE "public"."transaction_type" AS ENUM('sale', 'repair_payment', 'rental_deposit', 'account_payment', 'refund');
|
||||
CREATE TYPE "public"."transaction_status" AS ENUM('pending', 'completed', 'voided', 'refunded');
|
||||
CREATE TYPE "public"."payment_method" AS ENUM('cash', 'card_present', 'card_keyed', 'check', 'account_charge');
|
||||
CREATE TYPE "public"."discount_type" AS ENUM('percent', 'fixed');
|
||||
CREATE TYPE "public"."discount_applies_to" AS ENUM('order', 'line_item', 'category');
|
||||
CREATE TYPE "public"."drawer_status" AS ENUM('open', 'closed');
|
||||
CREATE TYPE "public"."tax_category" AS ENUM('goods', 'service', 'exempt');
|
||||
|
||||
-- New columns on existing tables
|
||||
ALTER TABLE "product" ADD COLUMN "tax_category" "tax_category" NOT NULL DEFAULT 'goods';
|
||||
ALTER TABLE "location" ADD COLUMN "tax_rate" numeric(5, 4) NOT NULL DEFAULT '0';
|
||||
ALTER TABLE "location" ADD COLUMN "service_tax_rate" numeric(5, 4) NOT NULL DEFAULT '0';
|
||||
|
||||
-- Discount table
|
||||
CREATE TABLE "discount" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"location_id" uuid REFERENCES "location"("id"),
|
||||
"name" varchar(255) NOT NULL,
|
||||
"discount_type" "discount_type" NOT NULL,
|
||||
"discount_value" numeric(10, 2) NOT NULL,
|
||||
"applies_to" "discount_applies_to" NOT NULL DEFAULT 'line_item',
|
||||
"requires_approval_above" numeric(10, 2),
|
||||
"is_active" boolean NOT NULL DEFAULT true,
|
||||
"valid_from" timestamp with time zone,
|
||||
"valid_until" timestamp with time zone,
|
||||
"created_at" timestamp with time zone NOT NULL DEFAULT now(),
|
||||
"updated_at" timestamp with time zone NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Drawer session table
|
||||
CREATE TABLE "drawer_session" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"location_id" uuid REFERENCES "location"("id"),
|
||||
"opened_by" uuid NOT NULL REFERENCES "user"("id"),
|
||||
"closed_by" uuid REFERENCES "user"("id"),
|
||||
"opening_balance" numeric(10, 2) NOT NULL,
|
||||
"closing_balance" numeric(10, 2),
|
||||
"expected_balance" numeric(10, 2),
|
||||
"over_short" numeric(10, 2),
|
||||
"denominations" jsonb,
|
||||
"status" "drawer_status" NOT NULL DEFAULT 'open',
|
||||
"notes" text,
|
||||
"opened_at" timestamp with time zone NOT NULL DEFAULT now(),
|
||||
"closed_at" timestamp with time zone
|
||||
);
|
||||
|
||||
-- Transaction table
|
||||
CREATE TABLE "transaction" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"location_id" uuid REFERENCES "location"("id"),
|
||||
"transaction_number" varchar(50) NOT NULL UNIQUE,
|
||||
"account_id" uuid REFERENCES "account"("id"),
|
||||
"repair_ticket_id" uuid REFERENCES "repair_ticket"("id"),
|
||||
"repair_batch_id" uuid REFERENCES "repair_batch"("id"),
|
||||
"transaction_type" "transaction_type" NOT NULL,
|
||||
"status" "transaction_status" NOT NULL DEFAULT 'pending',
|
||||
"subtotal" numeric(10, 2) NOT NULL DEFAULT '0',
|
||||
"discount_total" numeric(10, 2) NOT NULL DEFAULT '0',
|
||||
"tax_total" numeric(10, 2) NOT NULL DEFAULT '0',
|
||||
"total" numeric(10, 2) NOT NULL DEFAULT '0',
|
||||
"payment_method" "payment_method",
|
||||
"amount_tendered" numeric(10, 2),
|
||||
"change_given" numeric(10, 2),
|
||||
"check_number" varchar(50),
|
||||
"stripe_payment_intent_id" varchar(255),
|
||||
"tax_exempt" boolean NOT NULL DEFAULT false,
|
||||
"tax_exempt_reason" text,
|
||||
"processed_by" uuid NOT NULL REFERENCES "user"("id"),
|
||||
"drawer_session_id" uuid REFERENCES "drawer_session"("id"),
|
||||
"notes" text,
|
||||
"completed_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone NOT NULL DEFAULT now(),
|
||||
"updated_at" timestamp with time zone NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Transaction line item table
|
||||
CREATE TABLE "transaction_line_item" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"transaction_id" uuid NOT NULL REFERENCES "transaction"("id"),
|
||||
"product_id" uuid REFERENCES "product"("id"),
|
||||
"inventory_unit_id" uuid REFERENCES "inventory_unit"("id"),
|
||||
"description" varchar(255) NOT NULL,
|
||||
"qty" integer NOT NULL DEFAULT 1,
|
||||
"unit_price" numeric(10, 2) NOT NULL,
|
||||
"discount_amount" numeric(10, 2) NOT NULL DEFAULT '0',
|
||||
"discount_reason" text,
|
||||
"tax_rate" numeric(5, 4) NOT NULL DEFAULT '0',
|
||||
"tax_amount" numeric(10, 2) NOT NULL DEFAULT '0',
|
||||
"line_total" numeric(10, 2) NOT NULL DEFAULT '0',
|
||||
"created_at" timestamp with time zone NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Discount audit table (append-only)
|
||||
CREATE TABLE "discount_audit" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"transaction_id" uuid NOT NULL REFERENCES "transaction"("id"),
|
||||
"transaction_line_item_id" uuid REFERENCES "transaction_line_item"("id"),
|
||||
"discount_id" uuid REFERENCES "discount"("id"),
|
||||
"applied_by" uuid NOT NULL REFERENCES "user"("id"),
|
||||
"approved_by" uuid REFERENCES "user"("id"),
|
||||
"original_amount" numeric(10, 2) NOT NULL,
|
||||
"discounted_amount" numeric(10, 2) NOT NULL,
|
||||
"reason" text NOT NULL,
|
||||
"created_at" timestamp with time zone NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- SKU unique partial index (from prior untracked migration)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS products_sku_unique ON product (sku) WHERE sku IS NOT NULL;
|
||||
@@ -1,2 +0,0 @@
|
||||
-- Add unique index on products.sku (null values are excluded from uniqueness)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS products_sku_unique ON product (sku) WHERE sku IS NOT NULL;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Cash rounding: location setting + transaction adjustment tracking
|
||||
ALTER TABLE "location" ADD COLUMN "cash_rounding" boolean NOT NULL DEFAULT false;
|
||||
ALTER TABLE "transaction" ADD COLUMN "rounding_adjustment" numeric(10, 2) NOT NULL DEFAULT '0';
|
||||
11
packages/backend/src/db/migrations/0040_app-config.sql
Normal file
11
packages/backend/src/db/migrations/0040_app-config.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE IF NOT EXISTS "app_config" (
|
||||
"key" varchar(100) PRIMARY KEY NOT NULL,
|
||||
"value" text,
|
||||
"description" text,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
|
||||
-- Seed default log level
|
||||
INSERT INTO "app_config" ("key", "value", "description")
|
||||
VALUES ('log_level', 'info', 'Application log level (fatal, error, warn, info, debug, trace)')
|
||||
ON CONFLICT ("key") DO NOTHING;
|
||||
8
packages/backend/src/db/migrations/0041_app_settings.sql
Normal file
8
packages/backend/src/db/migrations/0041_app_settings.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE IF NOT EXISTS "app_settings" (
|
||||
"key" varchar(100) PRIMARY KEY,
|
||||
"value" text,
|
||||
"is_encrypted" boolean NOT NULL DEFAULT false,
|
||||
"iv" text,
|
||||
"created_at" timestamptz NOT NULL DEFAULT now(),
|
||||
"updated_at" timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,14 @@
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE "adjustment_type" AS ENUM ('cash_in', 'cash_out');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL;
|
||||
END $$;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "drawer_adjustment" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"drawer_session_id" uuid NOT NULL REFERENCES "drawer_session"("id"),
|
||||
"type" "adjustment_type" NOT NULL,
|
||||
"amount" numeric(10, 2) NOT NULL,
|
||||
"reason" text NOT NULL,
|
||||
"created_by" uuid NOT NULL REFERENCES "user"("id"),
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
20
packages/backend/src/db/migrations/0043_user-pin.sql
Normal file
20
packages/backend/src/db/migrations/0043_user-pin.sql
Normal file
@@ -0,0 +1,20 @@
|
||||
ALTER TABLE "user" ADD COLUMN IF NOT EXISTS "pin_hash" varchar(255);
|
||||
ALTER TABLE "user" ADD COLUMN IF NOT EXISTS "employee_number" varchar(20) UNIQUE;
|
||||
|
||||
-- Auto-assign employee numbers to existing users
|
||||
DO $$ DECLARE r RECORD; num INT := 1001;
|
||||
BEGIN
|
||||
FOR r IN (SELECT id FROM "user" WHERE employee_number IS NULL ORDER BY created_at) LOOP
|
||||
UPDATE "user" SET employee_number = num::text WHERE id = r.id;
|
||||
num := num + 1;
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
-- Seed POS config
|
||||
INSERT INTO "app_config" ("key", "value", "description") VALUES
|
||||
('pos_lock_timeout', '15', 'POS auto-lock timeout in minutes (0 to disable)'),
|
||||
('receipt_header', '', 'Text shown below logo on receipts'),
|
||||
('receipt_footer', '', 'Thank you message at bottom of receipt'),
|
||||
('receipt_return_policy', '', 'Return policy text on receipt (blank to hide)'),
|
||||
('receipt_social', '', 'Website or social media shown on receipt')
|
||||
ON CONFLICT ("key") DO NOTHING;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Add 'consumable' to repair_line_item_type enum
|
||||
ALTER TYPE repair_line_item_type ADD VALUE IF NOT EXISTS 'consumable';
|
||||
|
||||
-- Add is_consumable flag to product table
|
||||
ALTER TABLE product ADD COLUMN IF NOT EXISTS is_consumable boolean NOT NULL DEFAULT false;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- Named registers for POS terminals
|
||||
CREATE TABLE IF NOT EXISTS register (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
location_id UUID NOT NULL REFERENCES location(id),
|
||||
name VARCHAR(100) NOT NULL,
|
||||
is_active BOOLEAN NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Link drawer sessions to registers
|
||||
ALTER TABLE drawer_session ADD COLUMN IF NOT EXISTS register_id UUID REFERENCES register(id);
|
||||
@@ -0,0 +1,31 @@
|
||||
-- Auto-assign employee_number on user insert if not provided
|
||||
CREATE OR REPLACE FUNCTION assign_employee_number()
|
||||
RETURNS TRIGGER AS $$
|
||||
DECLARE next_num INT;
|
||||
BEGIN
|
||||
IF NEW.employee_number IS NULL OR NEW.employee_number = '' THEN
|
||||
SELECT COALESCE(MAX(employee_number::int), 1000) + 1
|
||||
INTO next_num
|
||||
FROM "user"
|
||||
WHERE employee_number ~ '^\d+$';
|
||||
NEW.employee_number := next_num::text;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_assign_employee_number ON "user";
|
||||
CREATE TRIGGER trg_assign_employee_number
|
||||
BEFORE INSERT ON "user"
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION assign_employee_number();
|
||||
|
||||
-- Backfill any users missing an employee number
|
||||
DO $$ DECLARE r RECORD; num INT;
|
||||
BEGIN
|
||||
SELECT COALESCE(MAX(employee_number::int), 1000) INTO num FROM "user" WHERE employee_number ~ '^\d+$';
|
||||
FOR r IN (SELECT id FROM "user" WHERE employee_number IS NULL OR employee_number = '' ORDER BY created_at) LOOP
|
||||
num := num + 1;
|
||||
UPDATE "user" SET employee_number = num::text WHERE id = r.id;
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -267,6 +267,69 @@
|
||||
"when": 1774970000000,
|
||||
"tag": "0037_rate_cycles",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 38,
|
||||
"version": "7",
|
||||
"when": 1775321562910,
|
||||
"tag": "0038_pos-core",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 39,
|
||||
"version": "7",
|
||||
"when": 1775408000000,
|
||||
"tag": "0039_cash-rounding",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 40,
|
||||
"version": "7",
|
||||
"when": 1775494000000,
|
||||
"tag": "0040_app-config",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 41,
|
||||
"version": "7",
|
||||
"when": 1775580000000,
|
||||
"tag": "0041_app_settings",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 42,
|
||||
"version": "7",
|
||||
"when": 1775590000000,
|
||||
"tag": "0042_drawer-adjustments",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 43,
|
||||
"version": "7",
|
||||
"when": 1775600000000,
|
||||
"tag": "0043_user-pin",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 44,
|
||||
"version": "7",
|
||||
"when": 1775680000000,
|
||||
"tag": "0044_repair-pos-consumable",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 45,
|
||||
"version": "7",
|
||||
"when": 1775770000000,
|
||||
"tag": "0045_registers-reports",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 46,
|
||||
"version": "7",
|
||||
"when": 1775860000000,
|
||||
"tag": "0046_auto-employee-number",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
integer,
|
||||
numeric,
|
||||
date,
|
||||
pgEnum,
|
||||
} from 'drizzle-orm/pg-core'
|
||||
import { locations } from './stores.js'
|
||||
|
||||
@@ -41,6 +42,8 @@ export const suppliers = pgTable('supplier', {
|
||||
// See lookups.ts for inventory_unit_status and item_condition tables.
|
||||
// Columns below use varchar referencing the lookup slug.
|
||||
|
||||
export const taxCategoryEnum = pgEnum('tax_category', ['goods', 'service', 'exempt'])
|
||||
|
||||
export const products = pgTable('product', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
locationId: uuid('location_id').references(() => locations.id),
|
||||
@@ -54,6 +57,8 @@ export const products = pgTable('product', {
|
||||
isSerialized: boolean('is_serialized').notNull().default(false),
|
||||
isRental: boolean('is_rental').notNull().default(false),
|
||||
isDualUseRepair: boolean('is_dual_use_repair').notNull().default(false),
|
||||
isConsumable: boolean('is_consumable').notNull().default(false),
|
||||
taxCategory: taxCategoryEnum('tax_category').notNull().default('goods'),
|
||||
price: numeric('price', { precision: 10, scale: 2 }),
|
||||
minPrice: numeric('min_price', { precision: 10, scale: 2 }),
|
||||
rentalRateMonthly: numeric('rental_rate_monthly', { precision: 10, scale: 2 }),
|
||||
|
||||
194
packages/backend/src/db/schema/pos.ts
Normal file
194
packages/backend/src/db/schema/pos.ts
Normal file
@@ -0,0 +1,194 @@
|
||||
import {
|
||||
pgTable,
|
||||
uuid,
|
||||
varchar,
|
||||
text,
|
||||
timestamp,
|
||||
boolean,
|
||||
integer,
|
||||
numeric,
|
||||
pgEnum,
|
||||
jsonb,
|
||||
} from 'drizzle-orm/pg-core'
|
||||
import { locations } from './stores.js'
|
||||
import { accounts } from './accounts.js'
|
||||
import { products, inventoryUnits } from './inventory.js'
|
||||
import { users } from './users.js'
|
||||
import { repairTickets, repairBatches } from './repairs.js'
|
||||
|
||||
// --- Enums ---
|
||||
|
||||
export const transactionTypeEnum = pgEnum('transaction_type', [
|
||||
'sale',
|
||||
'repair_payment',
|
||||
'rental_deposit',
|
||||
'account_payment',
|
||||
'refund',
|
||||
])
|
||||
|
||||
export const transactionStatusEnum = pgEnum('transaction_status', [
|
||||
'pending',
|
||||
'completed',
|
||||
'voided',
|
||||
'refunded',
|
||||
])
|
||||
|
||||
export const paymentMethodEnum = pgEnum('payment_method', [
|
||||
'cash',
|
||||
'card_present',
|
||||
'card_keyed',
|
||||
'check',
|
||||
'account_charge',
|
||||
])
|
||||
|
||||
export const discountTypeEnum = pgEnum('discount_type', ['percent', 'fixed'])
|
||||
|
||||
export const discountAppliesToEnum = pgEnum('discount_applies_to', [
|
||||
'order',
|
||||
'line_item',
|
||||
'category',
|
||||
])
|
||||
|
||||
export const drawerStatusEnum = pgEnum('drawer_status', ['open', 'closed'])
|
||||
|
||||
// --- Tables ---
|
||||
|
||||
export const discounts = pgTable('discount', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
locationId: uuid('location_id').references(() => locations.id),
|
||||
name: varchar('name', { length: 255 }).notNull(),
|
||||
discountType: discountTypeEnum('discount_type').notNull(),
|
||||
discountValue: numeric('discount_value', { precision: 10, scale: 2 }).notNull(),
|
||||
appliesTo: discountAppliesToEnum('applies_to').notNull().default('line_item'),
|
||||
requiresApprovalAbove: numeric('requires_approval_above', { precision: 10, scale: 2 }),
|
||||
isActive: boolean('is_active').notNull().default(true),
|
||||
validFrom: timestamp('valid_from', { withTimezone: true }),
|
||||
validUntil: timestamp('valid_until', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
})
|
||||
|
||||
export const adjustmentTypeEnum = pgEnum('adjustment_type', ['cash_in', 'cash_out'])
|
||||
|
||||
export const registers = pgTable('register', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
locationId: uuid('location_id')
|
||||
.notNull()
|
||||
.references(() => locations.id),
|
||||
name: varchar('name', { length: 100 }).notNull(),
|
||||
isActive: boolean('is_active').notNull().default(true),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
})
|
||||
|
||||
export const drawerSessions = pgTable('drawer_session', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
locationId: uuid('location_id').references(() => locations.id),
|
||||
registerId: uuid('register_id').references(() => registers.id),
|
||||
openedBy: uuid('opened_by')
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
closedBy: uuid('closed_by').references(() => users.id),
|
||||
openingBalance: numeric('opening_balance', { precision: 10, scale: 2 }).notNull(),
|
||||
closingBalance: numeric('closing_balance', { precision: 10, scale: 2 }),
|
||||
expectedBalance: numeric('expected_balance', { precision: 10, scale: 2 }),
|
||||
overShort: numeric('over_short', { precision: 10, scale: 2 }),
|
||||
denominations: jsonb('denominations').$type<Record<string, number>>(),
|
||||
status: drawerStatusEnum('status').notNull().default('open'),
|
||||
notes: text('notes'),
|
||||
openedAt: timestamp('opened_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
closedAt: timestamp('closed_at', { withTimezone: true }),
|
||||
})
|
||||
|
||||
export const drawerAdjustments = pgTable('drawer_adjustment', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
drawerSessionId: uuid('drawer_session_id')
|
||||
.notNull()
|
||||
.references(() => drawerSessions.id),
|
||||
type: adjustmentTypeEnum('type').notNull(),
|
||||
amount: numeric('amount', { precision: 10, scale: 2 }).notNull(),
|
||||
reason: text('reason').notNull(),
|
||||
createdBy: uuid('created_by')
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
})
|
||||
|
||||
export const transactions = pgTable('transaction', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
locationId: uuid('location_id').references(() => locations.id),
|
||||
transactionNumber: varchar('transaction_number', { length: 50 }).notNull().unique(),
|
||||
accountId: uuid('account_id').references(() => accounts.id),
|
||||
repairTicketId: uuid('repair_ticket_id').references(() => repairTickets.id),
|
||||
repairBatchId: uuid('repair_batch_id').references(() => repairBatches.id),
|
||||
transactionType: transactionTypeEnum('transaction_type').notNull(),
|
||||
status: transactionStatusEnum('status').notNull().default('pending'),
|
||||
subtotal: numeric('subtotal', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||
discountTotal: numeric('discount_total', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||
taxTotal: numeric('tax_total', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||
total: numeric('total', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||
paymentMethod: paymentMethodEnum('payment_method'),
|
||||
amountTendered: numeric('amount_tendered', { precision: 10, scale: 2 }),
|
||||
changeGiven: numeric('change_given', { precision: 10, scale: 2 }),
|
||||
checkNumber: varchar('check_number', { length: 50 }),
|
||||
stripePaymentIntentId: varchar('stripe_payment_intent_id', { length: 255 }),
|
||||
roundingAdjustment: numeric('rounding_adjustment', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||
taxExempt: boolean('tax_exempt').notNull().default(false),
|
||||
taxExemptReason: text('tax_exempt_reason'),
|
||||
processedBy: uuid('processed_by')
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
drawerSessionId: uuid('drawer_session_id').references(() => drawerSessions.id),
|
||||
notes: text('notes'),
|
||||
completedAt: timestamp('completed_at', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
})
|
||||
|
||||
export const transactionLineItems = pgTable('transaction_line_item', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
transactionId: uuid('transaction_id')
|
||||
.notNull()
|
||||
.references(() => transactions.id),
|
||||
productId: uuid('product_id').references(() => products.id),
|
||||
inventoryUnitId: uuid('inventory_unit_id').references(() => inventoryUnits.id),
|
||||
description: varchar('description', { length: 255 }).notNull(),
|
||||
qty: integer('qty').notNull().default(1),
|
||||
unitPrice: numeric('unit_price', { precision: 10, scale: 2 }).notNull(),
|
||||
discountAmount: numeric('discount_amount', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||
discountReason: text('discount_reason'),
|
||||
taxRate: numeric('tax_rate', { precision: 5, scale: 4 }).notNull().default('0'),
|
||||
taxAmount: numeric('tax_amount', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||
lineTotal: numeric('line_total', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
})
|
||||
|
||||
export const discountAudits = pgTable('discount_audit', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
transactionId: uuid('transaction_id')
|
||||
.notNull()
|
||||
.references(() => transactions.id),
|
||||
transactionLineItemId: uuid('transaction_line_item_id').references(() => transactionLineItems.id),
|
||||
discountId: uuid('discount_id').references(() => discounts.id),
|
||||
appliedBy: uuid('applied_by')
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
approvedBy: uuid('approved_by').references(() => users.id),
|
||||
originalAmount: numeric('original_amount', { precision: 10, scale: 2 }).notNull(),
|
||||
discountedAmount: numeric('discounted_amount', { precision: 10, scale: 2 }).notNull(),
|
||||
reason: text('reason').notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
})
|
||||
|
||||
// --- Type exports ---
|
||||
|
||||
export type Discount = typeof discounts.$inferSelect
|
||||
export type DiscountInsert = typeof discounts.$inferInsert
|
||||
export type Transaction = typeof transactions.$inferSelect
|
||||
export type TransactionInsert = typeof transactions.$inferInsert
|
||||
export type TransactionLineItem = typeof transactionLineItems.$inferSelect
|
||||
export type TransactionLineItemInsert = typeof transactionLineItems.$inferInsert
|
||||
export type DiscountAudit = typeof discountAudits.$inferSelect
|
||||
export type DiscountAuditInsert = typeof discountAudits.$inferInsert
|
||||
export type DrawerSession = typeof drawerSessions.$inferSelect
|
||||
export type DrawerSessionInsert = typeof drawerSessions.$inferInsert
|
||||
@@ -36,6 +36,7 @@ export const repairLineItemTypeEnum = pgEnum('repair_line_item_type', [
|
||||
'part',
|
||||
'flat_rate',
|
||||
'misc',
|
||||
'consumable',
|
||||
])
|
||||
|
||||
export const repairConditionInEnum = pgEnum('repair_condition_in', [
|
||||
|
||||
13
packages/backend/src/db/schema/settings.ts
Normal file
13
packages/backend/src/db/schema/settings.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { pgTable, varchar, text, boolean, timestamp } from 'drizzle-orm/pg-core'
|
||||
|
||||
export const appSettings = pgTable('app_settings', {
|
||||
key: varchar('key', { length: 100 }).primaryKey(),
|
||||
value: text('value'),
|
||||
isEncrypted: boolean('is_encrypted').notNull().default(false),
|
||||
iv: text('iv'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
})
|
||||
|
||||
export type AppSetting = typeof appSettings.$inferSelect
|
||||
export type AppSettingInsert = typeof appSettings.$inferInsert
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user