Commit Graph

67 Commits

Author SHA1 Message Date
Ryan Moon
d36c6f7135 Remove multi-tenant company_id scoping from entire codebase
Drop company_id column from all 22 domain tables via migration.
Remove companyId from JWT payload, auth plugins, all service method
signatures (~215 occurrences), all route handlers (~105 occurrences),
test runner, test suites, and frontend auth store/types.

The company table stays as store settings (name, timezone). Tenant
isolation in a SaaS deployment would be at the database level (one
DB per customer) not the application level.

All 107 API tests pass. Zero TSC errors across all packages.
2026-03-29 14:58:33 -05:00
Ryan Moon
55f8591cf1 Add dev seed data, batch status progress bar, pre-fill account from batch
Dev seed script creates 8 accounts, 8 members, 16 repair templates,
6 repair tickets in various statuses, and a school batch with 5
instruments. Run with bun run db:seed-dev.

Batch detail page now has a status progress bar matching the ticket
detail pattern. Add Repair from batch pre-fills the account and
contact name. New repair form reads accountId and contactName from
search params when linked from a batch.
2026-03-29 14:04:02 -05:00
Ryan Moon
f7e78bec84 Improve repair batches: account search, add repair button, batch PDF
Batch create form now uses searchable account picker (same as ticket
intake) instead of a dropdown. Batch detail shows + Add Repair button
that creates a ticket pre-linked to the batch. Repair count and total
estimate auto-calculated from linked tickets. Batch PDF generates a
summary with all repairs, statuses, estimates, and grand total. Added
Mark Delivered button for completed batches. New repair form shows
batch badge when linked from a batch.
2026-03-29 13:38:25 -05:00
Ryan Moon
916eb29895 Add PDF generation modal with content picker, repairs help pages
PDF button now opens a modal where staff can select which line items,
customer-visible notes, and photos to include before generating. Defaults
to all customer notes and completed photos. Replaces the old one-click
generation.

Added 4 help/wiki pages for the Repairs module: Repairs Overview, Repair
Templates, Repair Batches, and Notes & Photos. Covers ticket workflow,
template usage, batch management, note visibility, photo phases, and
signed approval process. Updated Getting Started nav to include Repairs.
2026-03-29 13:20:32 -05:00
Ryan Moon
591be589f0 Add vault password manager planning doc (on-prem only) 2026-03-29 12:17:25 -05:00
Ryan Moon
72d0ff0a33 Fix security and quality issues from code review
Critical: Add company scoping to line item update/delete and note
delete via ownership verification through ticket join. Add companyId
validation to signed URL file serving. High: Paginate notes list
endpoint with search and sort support. Fix blob URL memory leaks in
AuthImage components with proper cleanup on unmount. Improve photo
upload error handling — count failures and show specific error count
instead of silently clearing form.
2026-03-29 12:16:17 -05:00
Ryan Moon
21ef7e7059 Expand repair tests to 43 cases, fix default status to new
Comprehensive test coverage for repairs: full status lifecycle (new →
picked_up), in_transit branch, pending_parts round-trip, delivered
alternate ending, reopen cancelled, validation errors, search by
instrument, filter by status and isBatch, notes CRUD with visibility
and status capture, service templates CRUD with soft-delete, signed
URL generation and access. Migration to set column default to new.
107 total API tests passing.
2026-03-29 11:56:06 -05:00
Ryan Moon
b0379052d6 Add 'new' status as default, in_transit becomes branch state
New tickets start as 'new' (just created, not yet examined). In Transit
is now a branch status off New for school pickups and shipped instruments.
Intake means the instrument has been physically received and documented.
Status progress bar, labels, filters, and default status all updated.
Removed debug logging from file upload endpoint.
2026-03-29 11:45:41 -05:00
Ryan Moon
ba94adb8d7 Fix DELETE sending empty JSON body, add repair_note to allowed file entity types
API client no longer sets Content-Type: application/json on requests
without a body (fixes DELETE 400 errors). Added repair_note to the
allowed entityTypes whitelist for file uploads so photos can be
attached to repair notes.
2026-03-29 11:23:21 -05:00
Ryan Moon
e224b535ce Fix auth for all file thumbnails, add upload error logging
All image thumbnails in ticket photos and note attachments now use
AuthImage component that fetches via Bearer token. Fixed 401 errors
on Photos & Docs tab. Added error logging for note photo uploads to
surface upload failures.
2026-03-29 11:19:39 -05:00
Ryan Moon
d936871a49 Fix note photos not displaying by using authenticated image fetching
Note photo thumbnails were failing because img src pointed at an
authenticated endpoint without auth headers. Added AuthImage component
that fetches images via Bearer token and renders as blob URLs. Photos
now display inline in note entries. Clicking still opens via signed URL.
2026-03-29 11:10:05 -05:00
Ryan Moon
cf98c305df Add photo attachments to repair notes
Notes can now have N photos attached. Attach Photo button in the note
form allows selecting multiple images before posting. Photos are uploaded
after the note is created, linked via entityType repair_note. Photos
display inline in each note entry as clickable thumbnails that open via
signed URL.
2026-03-29 11:06:12 -05:00
Ryan Moon
bf2091365d Add signed URLs for file access, fix unauthorized file viewing
New /files/signed-url/:id endpoint generates a 15-minute JWT-signed URL
for any file. New /files/s/* endpoint serves files using the token from
the query string without requiring auth headers. This allows files to
open in new browser tabs without authentication issues. Photos and
documents in repair tickets now use signed URLs when clicked.
2026-03-29 11:02:24 -05:00
Ryan Moon
77e56b7837 Make photos and documents clickable, show PDFs with file icon
Photos open in new tab on click. PDFs display as a file icon with
filename instead of broken image. Both images and PDFs are clickable
to view full size in a new browser tab.
2026-03-29 10:55:16 -05:00
Ryan Moon
ee8d6f7aad Add jsPDF dependency and PDF generation module for repair tickets
Install jsPDF, add generate-pdf.ts with customer-facing PDF layout,
wire PDF button in ticket detail to generate and auto-upload.
2026-03-29 10:52:17 -05:00
Ryan Moon
d04bf231f8 Add PDF generation for repair tickets with auto-upload to documents
Generates a customer-facing PDF with ticket details, line items, and
customer-visible notes using jsPDF. PDF is both downloaded to the user
and automatically uploaded to the ticket's documents section. Works as
a quote (pending_approval) or receipt (picked_up). Button in ticket
detail header.
2026-03-29 10:51:31 -05:00
Ryan Moon
79b7377fd2 Restructure ticket detail into tabs, add documents section
Ticket detail page now uses tabs (Details, Line Items, Notes, Photos &
Docs) instead of a long scrolling page. Photos section gains a Documents
category for uploading signed approvals, quotes, and receipts (accepts
PDFs). PDF generation button added to header (stub for now).
2026-03-29 10:42:40 -05:00
Ryan Moon
7eac03f6c2 Add repair notes journal with running feed, visibility, and status tagging
New repair_note table for timestamped journal entries on tickets. Each
note captures author, content, visibility (internal or customer-facing),
and the ticket status at time of writing. Notes display as a running
feed on the ticket detail page with newest first. Internal notes have
a lock icon, customer-visible notes highlighted in blue. Supports add
and delete with appropriate permission gating.
2026-03-29 10:27:39 -05:00
Ryan Moon
01cff80f2b Add repair list filters, template management page, and backend filter support
Repairs list now has a filter panel with status (defaults to active only),
condition, batch/individual toggle, and date range filters for intake and
promised dates. Added Batch column to the repairs table. Backend list
endpoint accepts filter query params for status, condition, dates, and
batch membership. Template management page (admin only) with CRUD for
common repair services (rehair, string change, etc.) with instrument
type, size, and default pricing. Sidebar updated with Repair Templates
link gated on repairs.admin permission.
2026-03-29 10:13:38 -05:00
Ryan Moon
7d55fbe7ef Add repair ticket detail improvements and intake estimate builder
Status progress bar component with visual step indicator, in_transit
status for instruments being transported to shop. Ticket detail page
reworked with inline edit form, reopen for cancelled tickets, photos
grouped by repair phase (intake/in_progress/completed). Intake form
now supports building estimates with template picker and manual line
items that carry over to the ticket. Service template API client and
types added for template search in line item dialogs.
2026-03-29 09:56:28 -05:00
Ryan Moon
f17bbff02c Add repairs domain with tickets, line items, batches, and service templates
Full-stack implementation of instrument repair tracking: DB schema with
repair_ticket, repair_line_item, repair_batch, and repair_service_template
tables. Backend services and routes with pagination/search/sort. 20 API
tests covering CRUD, status workflow, line items, and batch operations.
Admin frontend with ticket list, detail with status progression, line item
management, batch list/detail with approval workflow, and new ticket form
with searchable account picker and intake photo uploads.
2026-03-29 09:12:40 -05:00
Ryan Moon
1d48f0befa Add README and technical docs
- README with quick start, package overview, links to docs
- docs/setup.md — prerequisites, env vars, installation, running, testing
- docs/architecture.md — monorepo structure, backend/frontend design
- docs/api.md — full endpoint reference with permissions
- docs/database.md — schema overview, migrations, multi-tenancy
- docs/testing.md — test runner, suites, writing tests
- Updated .env.example with all supported variables
2026-03-29 08:31:20 -05:00
Ryan Moon
b9f78639e2 Add paginated users/roles, user status, frontend permissions, profile pictures, identifier file storage
- Users page: paginated, searchable, sortable with inline roles (no N+1)
- Roles page: paginated, searchable, sortable + /roles/all for dropdowns
- User is_active field with migration, PATCH toggle, auth check (disabled=401)
- Frontend permission checks: auth store loads permissions, sidebar/buttons conditional
- Profile pictures via file storage for users and members, avatar component
- Identifier images use file storage API instead of base64
- Fix TypeScript errors across admin UI
- 64 API tests passing (10 new)
2026-03-29 08:16:34 -05:00
Ryan Moon
92371ff228 Add RBAC tests, wiki docs, reset token to 1 hour
12 RBAC API tests: permission denial for no-role users, viewer read-only,
sales associate can create but not delete, technician scoped access,
instructor inventory denied, admin full access, permission inheritance
(admin implies edit+view), system role undeletable, custom role lifecycle.

Wiki articles for Users & Roles and Profile settings.
Reset password link expires in 1 hour instead of 24.
2026-03-28 18:11:32 -05:00
Ryan Moon
7dea20e818 Add user profile page, password change, reset links, auto-seed RBAC
Backend:
- POST /v1/auth/change-password (current user)
- POST /v1/auth/reset-password/:userId (admin generates 24h signed link)
- POST /v1/auth/reset-password (token-based reset, no auth required)
- GET/PATCH /v1/auth/me (profile read/update)
- Auto-seed system permissions on server startup

Frontend:
- Profile page with name edit, password change, theme/color settings
- Sidebar user link goes to profile page (replaces dropdown)
- Users page: "Reset Password Link" in kebab (copies to clipboard)
- Sign out button below profile link
2026-03-28 17:59:55 -05:00
Ryan Moon
58bf54a251 Add roles and users admin UI with role management API
Backend:
- GET /v1/users (list company users)
- GET/POST/PATCH/DELETE /v1/roles (role CRUD with permissions)
- GET/POST/DELETE /v1/users/:userId/roles (role assignment)
- GET /v1/me/permissions (current user's effective permissions)

Frontend:
- Roles list page with kebab menu (edit permissions, delete custom)
- Role detail page with grouped permission checkboxes and inheritance note
- New role page with auto-generated slug
- Users list page showing assigned roles per user
- Manage Roles dialog for adding/removing roles per user
- Sidebar: Admin section with Users, Roles, Help links
2026-03-28 17:16:53 -05:00
Ryan Moon
4a1fc608f0 Implement RBAC with permissions, roles, and route guards
- permission, role, role_permission, user_role_assignment tables
- 42 system permissions across 13 domains
- 6 default roles: Admin, Manager, Sales Associate, Technician, Instructor, Viewer
- Permission inheritance: admin implies edit implies view
- requirePermission() Fastify decorator on ALL routes
- System permissions and roles seeded per company
- Test helpers and API test runner seed RBAC data
- All 42 API tests pass with permissions enforced
2026-03-28 17:00:42 -05:00
Ryan Moon
dd03fb79ef Add audit trail planning doc for database change history
Application-level audit logging with 30-day default retention. Captures
insert/update/delete on all domain tables with field-level diffs, user
attribution, and request ID correlation. Sensitive fields masked.
Configurable retention, BullMQ cleanup job, admin UI for querying.
2026-03-28 16:26:31 -05:00
Ryan Moon
e0493814f7 Add audit logging for sensitive operations
Structured logging with request ID correlation throughout:
- Auth: register, login success, login failure (warn level)
- Accounts: soft-delete
- Members: move between accounts
- Tax exemptions: approve (info), revoke (warn with reason)
- Files: upload, delete (already had logging)

All logs include userId, entityId, and contextual data for debugging.
4xx errors logged as warn, 5xx as error.
2026-03-28 16:23:20 -05:00
Ryan Moon
e44d461de1 Fix MEDIUM security issues, add logging and request timeout
- Password minimum increased from 8 to 12 characters
- CORS configurable via CORS_ORIGINS env var (comma-separated whitelist)
- Pagination empty string q param handled via preprocess
- Request timeout set to 30 seconds
- Log file output via LOG_FILE env var (stdout + file in production)
- Pino-pretty in development, JSON to stdout + file in production
2026-03-28 16:14:05 -05:00
Ryan Moon
693121ec14 Add permissions and RBAC planning doc
Granular permission system: domain.action pattern (accounts.view, pos.edit,
repairs.admin). Custom roles composed of permissions. Default system roles
(Admin, Manager, Sales Associate, Technician, Instructor, Viewer). Migration
plan from current role enum. API and frontend guard patterns.
2026-03-28 16:06:23 -05:00
Ryan Moon
e65175ef19 Fix security issues: path traversal, typed errors, file validation
- Fix path traversal in file serve endpoint (validate company prefix, block ..)
- Add typed error classes: ValidationError, NotFoundError, ForbiddenError,
  ConflictError, StorageError
- Global error handler catches AppError subclasses with correct status codes
- 4xx logged as warn, 5xx as error with request ID
- File upload validates entityType whitelist, UUID format, category pattern
- Remove fragile string-matching error handling from routes
- Services throw typed errors instead of plain Error
- Health endpoint documented as intentionally public
2026-03-28 16:03:45 -05:00
Ryan Moon
5aadd68128 Add email system planning doc for transactional and mass email
Provider abstraction (SMTP, SendGrid, SES, Postmark), email templates with
merge fields, BullMQ queue for async sending, mass email campaigns with
recipient filtering, CAN-SPAM unsubscribe management, email logging.
2026-03-28 15:38:54 -05:00
Ryan Moon
6adce51e6c Add member profile photo to planning docs
profile_image_file_id on member table, entity_type=member category=profile
in file storage. UI shows silhouette placeholder when empty.
2026-03-28 15:34:57 -05:00
Ryan Moon
760e995ae3 Implement file storage layer with local provider, upload/download API, tests
- StorageProvider interface with LocalProvider (S3 placeholder)
- File table with entity_type/entity_id references, content type, path
- POST /v1/files (multipart upload), GET /v1/files (list by entity),
  GET /v1/files/:id (metadata), GET /v1/files/serve/* (content),
  DELETE /v1/files/:id
- member_identifier drops base64 columns, uses file_id FKs
- File validation: type whitelist, size limits, per-entity max
- Fastify storage plugin injects provider into app
- 6 API tests for upload, list, get, delete, validation
- Test runner kills stale port before starting backend
2026-03-28 15:29:06 -05:00
Ryan Moon
de4d2e0a32 Add file storage architecture planning doc
Defines storage provider abstraction (local filesystem + S3), file table
schema, path conventions per entity, upload/download API, image processing,
backup/restore CLI, and domain integration plan. Covers member IDs, product
photos, rental agreements, repair tickets, and all future file needs.
2026-03-28 13:50:58 -05:00
Ryan Moon
f359f92071 Fix members routing - restructure as directory for detail page to work
Move members.tsx to members/index.tsx so $memberId.tsx resolves as a
sibling route. Fixes member detail page not loading when navigating
from members list.
2026-03-28 13:30:30 -05:00
Ryan Moon
95bf9472e0 Add member identifiers UI, member detail page, kebab menus
- Member detail page at /members/:id with edit form and identity documents
- Expandable identity documents on account members tab
- Kebab menu on both members list and account members tab (Edit, View IDs, View Account, Delete)
- Identifier form with image upload (base64), ID type select, dates
- Wiki article for identity documents
2026-03-28 13:22:44 -05:00
Ryan Moon
c7e2c141ec Add in-app wiki help system with accounts and members articles
Markdown-based help pages rendered in the admin UI. Sidebar category
navigation with search. Articles: Getting Started, Accounts Overview,
Members Overview, Payment Methods, Tax Exemptions. Written for
non-technical store staff.
2026-03-28 13:05:52 -05:00
Ryan Moon
ce560cc568 Add comprehensive account and member API tests
12 new tests: search by email/phone, pagination params, sort order,
billing mode, scoped member list, isMinor from DOB, DOB override,
isMinor recalculation on update, 404 for missing member. Total: 36.
2026-03-28 12:57:57 -05:00
Ryan Moon
f47bfdbcdb Add standalone API test runner with accounts and members suites
Custom test framework that starts the backend, creates a test DB, runs
migrations, and hits real HTTP endpoints. Supports --suite and --tag
filtering. 24 tests covering account CRUD, member inheritance, state
normalization, move, search, and auto-generated numbers. Run with
bun run api-test.
2026-03-28 12:52:04 -05:00
Ryan Moon
b9e984cfa3 Add member address, state normalization, account inheritance, fix member form
- Address field on member table (jsonb, same format as account)
- Members inherit email, phone, address from account when not provided
- State normalization: "Texas" → "TX", "california" → "CA" via shared util
- Member form drops zodResolver to fix optional field validation flashing
- Account name auto-format: "First Last - Account"
- US state lookup with full name + code support
2026-03-28 12:31:02 -05:00
Ryan Moon
ce2a61ced9 Fix empty string validation on all optional form fields across all schemas
Add opt() preprocessor that coerces empty strings to undefined before Zod
validation. Applied to every optional string field in account, member,
identifier, supplier, product, inventory unit, tax exemption, payment
method, and lookup schemas. Fixes forms rejecting blank optional fields.
2026-03-28 11:40:48 -05:00
Ryan Moon
6ca38e2105 Fix account/member form validation, add member number to tables
- Fix account create form blocking on empty name when includeFirstMember
- Add noValidate to forms to prevent browser native validation on optional fields
- Show member number column on account members tab
- Replace DOB with phone in members table for better at-a-glance info
2026-03-28 11:31:28 -05:00
Ryan Moon
f4e5a57846 Update planning docs to reflect current implementation state
- Doc 02: Add member_identifier table, member_number, primary_member_id,
  account_number auto-generation, isMinor override, tax_exemption as
  separate table, member move, updated business rules
- Doc 03: Document lookup table pattern replacing pgEnums for status and
  condition, add system/custom value distinction
- Doc 22: Mark all Phase 2 items as complete, add new tables to additions
  section, update audit findings, note admin frontend exists
2026-03-28 09:49:34 -05:00
Ryan Moon
c7b460c0bf Add member identifiers table for ID documents (DL, passport, school ID)
member_identifier table with type, value, issuing authority, expiry,
front/back image storage (base64 in Postgres), primary flag. CRUD
endpoints under /members/:memberId/identifiers. Zod schemas with
constrained type enum.
2026-03-28 09:38:01 -05:00
Ryan Moon
727275af59 Add integration tests for members list, move, auto-numbers, primary member, isMinor flag 2026-03-28 09:18:32 -05:00
Ryan Moon
8ea3b8dffb Add auto-generated account numbers and member numbers
6-digit random numbers generated on create, unique per company. Member
number column added to member table. Both displayed in UI tables.
2026-03-28 09:15:27 -05:00
Ryan Moon
572af05a3f Add top-level members list, primary member on account, member move, combined create flows
- GET /v1/members with search across all members (includes account name)
- POST /members/:id/move with optional accountId (creates new account if omitted)
- primary_member_id on account table, auto-set when first member added
- isMinor flag on member create (manual override when no DOB provided)
- Account search now includes member names
- New account form includes primary contact fields, auto-generates name
- Members page in sidebar with global search
2026-03-28 09:08:06 -05:00
Ryan Moon
7c64a928e1 Add theme system with color presets, fix login page styling, persist auth session
Theme system with 5 color presets (Slate, Emerald, Violet, Amber, Rose)
and light/dark/system mode. User menu in sidebar with theme picker and
sign out. Login page uses standalone dark branded styling with autofill
override. Auth persists in sessionStorage across refreshes.
2026-03-28 08:30:24 -05:00