Engineering
Architecture
How TaskPaws is put together: the Rails platform, the React Native clients, and the contracts between them. Record decisions that affect more than one app or that would be expensive to reverse.
Apps
| Path | Role | Status |
|---|---|---|
platform/ | Fullstack Rails: public web, workspace, Admin, API, jobs, database. Source of truth for domain behavior. | Marketing, User / SuperUser sessions, social login, founder provision, /app workspace (home radar, settings with SaaS billing, clinic workflows), Admin console, staff JSON API at /api/v1. |
mobile/ | React Native / Expo for iOS and Android. Same organization workflows against the Rails API. | Expo SDK 58. Login (email, social), register, Home, Schedule (types, walk-ins, check-in / undo), Patients, Clients, Staff, Organization settings. No Whiteboard, checkout, or Action Cable yet. |
Staff get the same functionality as the web, packaged as Expo rather than a browser UI. Super users use the web Admin console and may enter any organization context. Domain behavior stays in platform/ models; the API is a JSON adapter beside the Hotwire UI.
Stack
| Layer | Choice | Notes |
|---|---|---|
| Language | Ruby 4.0.2 | platform/.ruby-version |
| Framework | Rails 8.1.3.1 | config.load_defaults 8.1 |
| Database | PostgreSQL via pg | Connection from Rails credentials |
| Web UI | Hotwire, import maps, Propshaft | Stimulus mobile-nav (marketing header), sidebar (icon rail), breadcrumbs / breadcrumb-seed (header trail), header-search (typeahead), searchable-selects and form-validation on every shell |
| CSS | Tailwind CSS 4 + taskpaws.css | Tokens in app/assets/tailwind/application.css |
| Icons | Lucide webfont (lucide-static 0.546.0) | Views call icon_tag with material-style names; Icon emits lucide icon-…. Phosphor is retired. Guide: docs/architecture/icons.md |
| Jobs / cache | Solid Queue, Solid Cache | bin/jobs; memory cache in development |
| Cable | Solid Cable (production), async (development) | ClinicBoardChannel for Schedule/Whiteboard, PhotoUploadChannel for QR uploads. See Action Cable |
| Auth | Authlogic | Separate User and SuperUser; bcrypt. API uses hashed ApiToken Bearer tokens, not cookies |
| Geocoding | AddressGeocoder (Nominatim) | Client addresses → lat/lng. Locations not geocoded yet; PostGIS later if needed |
| Audit | Audited | Accounts plus tenancy and clinic records; AuditTimeline on show pages |
| Payments | Stripe | SaaS plan billing only |
| Files | Active Storage | Amazon S3 (:amazon) in every environment |
| SMS | AWS End User Messaging | Platform origination number; per-Location numbers later |
| i18n | en default, es | Cookie from /locale/:locale, else Accept-Language via AppLocale |
Web surface
MainController serves marketing and legal. Staff land on /app after UserSession; SuperUsers land on /admin after SuperUserSession. Key routes (full table in docs/architecture/README.md):
| Route | Action | Behavior |
|---|---|---|
GET / | main#landing | Features, pricing, FAQs, trial CTA |
GET/POST /login, DELETE /logout | user_sessions | Staff session → /app |
GET/POST /register | users#new/create | Creates User, provisions Organization + Legal Entity + Location + Staff |
POST /auth/:provider, callback | OmniAuth | Google, Apple, Facebook for User only; new visitors finish on /register |
GET /app | app/homes#show | Greeting, clinic radar (ClinicDayRadar) at a Location with visits.read, SaaS billing widgets. Locked workspaces get the subscribe / buy-credits gate here |
PATCH /app/preference | app/preferences#update | Per-User UI state (UserPreference: sidebar collapsed, schedule view and hidden columns, breadcrumbs, grid order, locale, appearance) |
PATCH /app/workspace | app/workspaces#update | Location / Organization switcher (session) |
GET /app/search | app/searches#show | Header typeahead: Postgres FTS, max 10 hits, 3-character gate, patients.read |
POST /app/photo_upload_sessions, GET/PATCH /photo_uploads/:token | Hands-off uploads | QR upload session (staff) and public phone page (15 min, single use) |
GET/PATCH /app/settings, /app/billing/plan_change | app/settings | Hierarchy, legal entities, locations, location groups (Elite), Billing; /app/billing redirects there |
/app/staffs, /app/staff_role_assignments | app/staffs | Directory, invite (pending), resend, withdraw, disable/enable, edit roles / hours / commissions |
/app/legal_entities, /app/locations, /app/location_groups | CRUD | Last entity / location cannot be destroyed. Hours and rooms/equipment on the Location ficha |
/app/patients, /app/clients | CRUD (no destroy) | Charts and pet parents. POST /app/patients/:id/invite sends a 48-hour intake link (/intake/:token) |
/app/catalog, /app/pricing_groups, /app/patient_groups, /app/tax_groups, /app/taxes | Catalog and pricing | Master items, Location / group overrides, locks, exclusive items, taxes |
/app/appointment_types | CRUD | Org list (duration, color, catalog item, deposit, clinical); override sets Location enabled. appointmenttypes.read / .manage / .override |
/app/inventory | app/inventory_items | Per-Location on-hand; adjust quantity / batch |
GET /app/schedule | app/schedules#show | Staff/Resource · Day/Week/Month/Year calendar |
POST/PATCH /app/appointments | app/appointments | Optional patient (blank = walk-in), type, staff. status_action: checked_in, undo_check_in, scheduled, canceled, no_show |
PATCH /app/appointments/:id/check_in, /cancel, /mark_no_show | app/appointments | Status transitions (+ *_series_occurrence) |
GET /app/whiteboard | app/whiteboards#show | Floor / Pipeline / List |
GET /app/visits/:id, /cockpit | app/visits#show/cockpit | Visit 360 workspace (full page or drawer). Visits are created only by check-in |
PATCH /app/visits/:id, /undo_check_in, POST …/checkout | app/visits | Place/status change, narrow undo, open the sales order |
/app/visits/:visit_id/soap_note | app/soap_notes | Show, edit, apply_previous, apply_template, save_template |
/app/checkout, /app/invoices, /app/credit_notes, /app/deposits | Clinic finance | Sales orders, invoices, credit notes, payments, deposits |
/app/tips, /app/commissions, /app/commission_groups | Staff pay | Tips and commissions |
/app/notification_settings | Notifications | Client email/SMS notifications and templates |
/admin/* | Admin console | See Admin console |
/intake/:token, /plans/:token, /photo_uploads/:token | Public token pages | Patient intake, treatment plan approval, QR upload |
GET /locale/:locale | locales#update | Sets locale cookie and redirects back |
GET /privacy, /terms, /facebook/deletion | Legal | Legal pages; Facebook data deletion callback and status |
POST /webhooks/stripe | webhooks/stripe#create | Stripe SaaS billing webhooks |
GET /up | rails/health#show | Load balancer health |
Status transitions are shared by web and API: AppointmentCheckIn, AppointmentUndoCheckIn, AppointmentDismiss, AppointmentRestore, AppointmentDelete, and AppointmentWriter (the /api/v1 create/update adapter). UserPreference / BreadcrumbTrail hold per-User UI state; HomeDashboard / ClinicDayRadar back Home.
Request scope and shell
- Workspace — current Location is
session[:workspace_location_id](must be granted; default first). Organization scope when the Staff has more than one granted Location; it only changes from the sidebar switcher. Schedule and Whiteboard in Organization scope show a pick-a-Location placeholder. - Header — breadcrumb trail, Location or Organization name, trial days while
on_trial?(Upgrade → Settings → Billing), header search, and Add (Appointment, Patient, Customer, Staff — each gated by RBAC and plan). - Workspace lock — when
workspace_locked?(trial ended without a subscription, or credits exhausted),App::BaseController#require_paid_accessredirects every/apppage to Home, which shows a blocking subscribe / buy-credits gate. The API returns402 payment_requiredorcredits_exhausted. - Sidebar — items gated by plan feature and RBAC, rendered disabled otherwise: Whiteboard after Home, Schedule, Clients, Patients, Inventory, Checkout, Invoices, Credit notes, Tips, Commissions. Billing, Messages, Reports are placeholders. Catalog, Appointment types, Taxes, Commission groups, and Staff live in the Settings flyout.
Hierarchy inheritance
Catalog items, pricing group prices, patient groups, taxes, tax groups, commission groups and rates, and appointment types share one inherit-or-override stack. A Location stores only differences; each attribute resolves on its own.
| Piece | Role |
|---|---|
OverrideLocks | On the master record: LOCK_COLUMNS (none / locations / everywhere), lock queries, override lookup, default overridable_at? |
HierarchyOverrideFields | On Location and group override rows: upsert_for!, lock and scope validations, group lock_* booleans, hard-off rule for enabled |
Hierarchy::EffectiveRecord | Resolver: value, source, and trace (the level trail) |
Hierarchy::Policy | Who may override or lock; subclassed by taxes, commissions, pricing, and appointment types. lock_levels? (Organization only), see_locks?; Hierarchy::Policy.for maps a record to its policy |
OverrideLocks.lock_level_options | Lock picker options; drops locations without Location Groups unless already set |
| UI | App::HierarchyOverrideParams, App::HierarchyShowOverrides (Details / All sites), App::HierarchyOverridesController (override drawer), App::HierarchyHelper, app/hierarchy/ partials, app.hierarchy.* copy |
LocationGroups::OverridesSummary | Everything a group overrides, for the Location group page |
Order per attribute: disabled master (for enabled) → locked everywhere → at a Location locked for Locations, group value or master → Location override → group override → master. Adding a new overridable record: see docs/architecture/README.md#hierarchy-inheritance.
Status vocabulary
These words are not interchangeable. Use the code names in docs, wiki, UI copy, and APIs.
| Term | Meaning | Code |
|---|---|---|
| Enable / disable | Policy switch: allowed to work or appear in pickers | disabled_at on User, Staff, Patient, Client, CatalogItem, AppointmentType, PricingGroup, PatientGroup, Tax, TaxGroup, CommissionGroup; Location / group overrides use nullable enabled and can only turn an enabled record off |
| Override | A Location or group value replacing the inherited one for one field. Spanish UI “excepción”; never “exception” in English copy | location_*_overrides, location_group_*_overrides |
| Lock level | “Anyone can override”, “Only location groups can override”, “Nobody can override” | lock_* = none / locations / everywhere |
| Sellable | Catalog item offered for sale at a site (not a status) | catalog_items.sellable; overrides use nullable sellable |
| Active | Real-time running state | Treatment plan status: "active"; visit on_floor? |
| Available | Room or equipment in service | location_resources.available |
| Admin active users | Recency, not enable/disable | active_users = signed in within 7 days |
Section design
Every /app section follows the pattern set by Patients (/app/patients). Copy it instead of inventing a new layout. The full component rules live in docs/architecture/design-system.md.
| Piece | Partial | Rule |
|---|---|---|
| Page header | app/shared/_page_header | Title, one-line lead, badges, meta, actions right. One per page. crumbs / eyebrow append to the header trail instead of drawing in the page |
| Section tabs | app/shared/_subnav in page-header :actions | Right-aligned with the title row (wrap_class: nil). Segmented XOR control |
| Filters and search | app/shared/_subnav / table_search | Full-width bar below the header (SUBNAV_BAR) only for search or filter rows |
| Identity card | e.g. app/patients/_identity | Show-page header: avatar, name, badges, then vitals and alerts |
| Vitals strip | app/shared/_vitals | Four stable facts in a hairline grid, label above value |
| Section card | app/shared/_section | Icon tile, title, lead, content. Rendered as a layout with a block |
| Facts | app/shared/_fact | Label / value pair inside AppUi::FACT_GRID |
| Empty state | app/shared/_empty_state | Neutral tile, one sentence, optional action. Never leave a card blank |
| Form save bar | app/shared/_form_actions | Sticky bar: hint, Cancel, one primary submit. Fields use AppUi::FIELD wrappers inside FORM_BODY |
| Drawer | app/shared/_drawer | Slide-over with turbo frame app_drawer for cockpit, checkout, deposit flows (embed=1) |
Tones carry meaning, not decoration: neutral (facts), brand (identity), success (verified, opted in), caution (needs attention soon), danger (expired, blocking). The record picks its tone in Ruby (ui_tone + status_label) and views render it through AppUi.chip, chip_solid, tile, dot, panel, and rail_dot. Each emits one tp-* class plus one tp-tone-* class; taskpaws.css derives colours from a single --tp-tone.
Views stay declarative: aggregation lives in POROs (PatientDirectory, PatientSummary) and labels live on the record. A class string used twice becomes an AppUi constant; never build Tailwind classes from fragments.
Breadcrumbs and sidebar
The way back lives in the workspace header (app/shared/_crumbs), not in the page. The trail is per User, persisted in UserPreference (settings["breadcrumbs"]), normalized by BreadcrumbTrail (label + path starting with /, at most 8 entries).
| Helper | When | Effect |
|---|---|---|
clear_header_crumbs | Home | Empties the trail |
seed_header_crumbs | Section index pages (Patients, Schedule, Whiteboard, …) | Replaces the trail with that root |
seed_header_crumbs(*AppNav.settings_trail(item)) | Settings children | Seeds Settings > {child} |
append_header_crumbs | Show and edit pages | Extends the trail; the same path is replaced in place, not duplicated |
Client side, Stimulus breadcrumbs truncates the trail when an earlier crumb is clicked, and breadcrumb-seed seeds a one-item trail from sidebar links and the header Add menu. Both persist through PATCH /app/preference.
The sidebar collapses to an icon rail. Collapsed state is a User preference (sidebar_collapsed; AppUi.sidebar_class adds is-collapsed), so it survives reloads and devices. Collapsed links show tooltips; the Settings flyout keeps its labels.
Data and secrets
PostgreSQL in every environment. Host, port, username, and password come from Rails.application.credentials.dig(:database, :production) and are reused; only the database name changes.
| Environment | Databases |
|---|---|
| development | taskpaws_development |
| test | taskpaws_test |
| production | taskpaws, taskpaws_cache, taskpaws_queue, taskpaws_cable |
Application tables in db/schema.rb cover auth and tenancy, RBAC, clients and patients, appointments, series, appointment types and overrides, visits, SOAP and diagnostics, catalog and inventory, pricing / patient / tax / commission groups, sales orders, invoices, payments, deposits, credit notes, tips, commissions, notifications, user_preferences, and SaaS billing.
Secrets stay in config/credentials.yml.enc (needs gitignored config/master.key). Credential keys: database, amazon.s3, amazon.ses, amazon.sms, super_user, google, facebook, apple, active_record_encryption, stripe, deploy. Edit with bin/rails credentials:edit from platform/.
OAuth redirect URIs (local): http://localhost:3000/auth/google_oauth2/callback, /auth/facebook/callback, /auth/apple/callback.
Storage
config/storage.yml defines Disk (local, test) as unused fallbacks and Amazon S3 (amazon). Every environment uses :amazon. Buckets follow taskpaws-<%= Rails.env %> in us-west-2.
Tenancy
The tenant is an Organization. It owns 1..N Legal Entities (fiscal identity) and 1..N Locations (physical sites); Elite adds optional Location groups. Each Location belongs to exactly one Legal Entity. Location is not the legal or billing identity. User is an independent login; a Staff record is membership in an Organization. Founder /register calls Organization.provision!.
Day-to-day clinic work is scoped to a Location and uses its time_zone. Patient charts and master catalog are Organization-scoped. Invoice headers and payouts follow the Location’s Legal Entity.
Product rules: Organization structure. Access: Staff access.
Authentication
Two actor types, both Authlogic. Separate models and sessions. Do not collapse them into one table with a flag.
| Actor | Model | Scope | Surfaces |
|---|---|---|---|
| Login identity | User | Independent; clinic access through Staff | /app, /api/v1 |
| Organization membership | Staff | One User + one Organization; pending until accepted; disabled_at suspends without touching User | Founder register and Staff.invite! |
| Platform operator | SuperUser | Entire system | /admin; may impersonate a staff User into /app |
New social visitors finish on /register (clinic name required); existing Users log in without provisioning. The mobile app opens /auth/mobile/:provider in a browser and exchanges a single-use MobileSocialHandoff ticket at POST /api/v1/social_session or /social_registration; it registers by email through POST /register as JSON.
Not built: invite email / accept-by-token page, Location geocoding, Admin tenant CRUD, customer portal, SuperUser on the API, partner API keys, CORS.
Admin console
Dedicated Rails namespace at /admin; only SuperUser sessions. Lists users (show, edit, disable/enable, invites, impersonate), SuperUsers (CRUD), organizations (trial days, credit adjustments, plan change via Billing::PlanChange), billing transactions, the RBAC catalog (roles, actions), plans and translations, platform catalogs (breeds, catalog item categories, observation kinds), audits, and settings (default free-trial length). It does not create tenant structure yet. Next: tenant CRUD and elevated org access as a SuperUser.
Action Cable
A few domain channels on one WebSocket per client — not one mega-channel and not one channel per screen. Messages are refresh signals; the client reloads over HTTP or Turbo. Extend a domain channel with a typed action / surface; add a channel only when auth, lifecycle, or payload differ.
| Channel | Domain | Message | Clients |
|---|---|---|---|
StatusChannel | Connection health (per user) | None | Web header |
ClinicBoardChannel | Schedule and Whiteboard (clinic_board:organization:{id}:location:{id}:staff:{id}) | { "action": "refresh" } | Web. Mobile not subscribed yet |
PhotoUploadChannel | QR upload preview (per session) | { "action": "uploaded", "preview_url" } | Web |
Live boards
Schedule and Whiteboard subscribe to ClinicBoardChannel while open. ClinicBoardPublisher broadcasts a refresh after appointment, series, or visit commits to every Staff who can read that Location. The web page waits ~100 ms and Turbo-refreshes, holding while a popover, submit, or drag is open. Each browser keeps its own socket.
The mobile Schedule ships without a socket (HTTP load, pull to refresh); there is no mobile Whiteboard. When it subscribes it will use the same signal and reload over HTTP, hold while a draft is open, and reload on foreground. Push does not paint the board. Prerequisites: Bearer ApiToken on the cable handshake (never in the URL, never persistence_token) and the current Staff id on GET /api/v1/home. Contract: docs/architecture/live-boards.md.
Hands-off uploads
Every staff file field offers one menu: this device (file browser on desktop, camera on a phone or tablet) or a QR code. Any phone scans the code and uploads without signing in; the file appears live on the open form over PhotoUploadChannel and is attached only when staff save, so it works on new records. One approach for profiles (Client and Patient photos, shipped), documents, and captures (planned).
Each PhotoUploadSession issues two signed_id tokens: the upload token (in the QR, 15 minutes, single use) and the claim token (staff browser, 1 day, same Organization only). Stale sessions are purged hourly. Public intake pages do not offer the QR option; the Expo app uses the device camera directly. Contract: docs/architecture/hands-off-uploads.md.
API and mobile
Mobile and other systems talk to platform/ as a User over /api/v1. Api::BaseController inherits ActionController::API; cookies are never set.
| Method | Path | Auth | Result |
|---|---|---|---|
POST / GET / DELETE | /api/v1/session, /session/all | none / Bearer | Login { token, user, organizations }; show; revoke this token or all |
POST | /api/v1/social_session, /social_registration | ticket | Token for an existing User, or registration_required; social founder register |
GET | /api/v1/home | Bearer | User, organization, location, roles, capabilities, workspace |
GET | /api/v1/billing | Bearer + accepted Staff | Trial, plan, credits, subscription |
GET / PATCH | /api/v1/organization | settings viewer / organization.manage | Hierarchy, counts, rename |
| CRUD | /api/v1/legal_entities | organization.manage | Last entity / locations present 422 |
| CRUD | /api/v1/locations, /:location_id/resources | settings viewer; manage location | Address, hours, exceptions, rooms/equipment |
| CRUD | /api/v1/location_groups | organization.manage, Elite | 403 plan_feature_unavailable below Elite |
GET / POST / PATCH / DELETE | /api/v1/staffs, /staff_role_assignments | can_assign_roles? / may_invite? | List, invite, resend, withdraw, disable/enable, edit, assign/revoke roles |
GET | /api/v1/time_zones, /countries | Bearer | Picker options |
GET / POST / PATCH | /api/v1/clients, /api/v1/patients | patients.read / .manage | Directory, detail, create (multipart photo), update |
GET / DELETE | /api/v1/patient_catalog, /patient_tags/:id | patients.read / .manage | Admission pickers; remove a custom tag |
GET | /api/v1/schedule | appointments.read at the Location | Occurrences, conflicts, patients, staffs, resources, enabled appointment_types, can_manage |
POST / PATCH / DELETE | /api/v1/appointments, /:id, /series_occurrence | appointments.manage at the Location | AppointmentWriter: walk-ins, types, staff, resources, recurrence; status checked_in checks in, scheduled undoes |
Tokens: plaintext returned once; token_digest stores SHA256 with secret_key_base; always Authorization: Bearer, never a query param. Org-scoped calls accept optional X-Organization-Id and X-Location-Id (must be granted). Errors are { "error": { "code", "message" } } (400, 401, 402, 403, 404, 422). Endpoints also check plan features and the workspace lock. Not in this slice: SuperUser, partner API keys, CORS, visit / whiteboard / checkout / search endpoints.
Expo SDK 58, React 19.3, React Native 0.88 in mobile/. Native ios/ and android/ are gitignored until prebuild.
Background work
Solid Queue. Procfile.dev runs web + Tailwind watcher; run bin/jobs separately in development. Production recurring work (config/recurring.yml): finished-job cleanup and stale PhotoUploadSession purge (hourly), Billing::RenewDueSubscriptionsJob (daily 6am), and AppointmentReminderJob (every 5 minutes). NotificationDispatchJob delivers templated client notifications.
Internationalization
en default, es supported. Cookie from the marketing nav, /app profile menu, or Admin account menu (GET /locale/:locale) wins over Accept-Language. html[lang] follows the locale.
Two string systems: YAML UI copy in en.yml / es.yml (legal in legal.*.yml); landing plan/feature marketing in the translations table, edited at Admin /admin/translations. Mobile chrome uses mobile/src/i18n/locales/*.json. Guide: docs/architecture/translations.md.
Tests and CI
bin/ci runs setup, RuboCop (omakase), bundler-audit, importmap audit, Brakeman, Rails tests, and a seed replant. Controller tests cover marketing, auth, OmniAuth, /api/v1 (session through schedule and appointments, including walk-ins, check-in, and undo check-in), /app shell and settings, clinic workflows, and Admin. Model tests include AppointmentType, BreadcrumbTrail, UserPreference, and LocationGroup. System tests cover the breadcrumb trail, clinic board refresh, clock time, and the sidebar (including the collapsed flyout).
Conventions
- All documentation is written in English.
- Fat models, thin controllers. POROs are fine when there is no table yet.
- Prefer objects over helpers and service objects.
- Omakase Rails style (rubocop-rails-omakase);
bin/rubocopmust pass. Ruby 1.9 hash syntax (key: value), including in ERB views. - Snake case for Ruby files and identifiers.