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.

Source: docs/architecture/*.md

Apps

PathRoleStatus
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

Browser ──Hotwire──► platform (Rails 8.1, Puma) iOS/Android (Expo) ──API──► platform │ ├── PostgreSQL ├── Solid Queue / Cache / Cable (production extra DBs) ├── Active Storage (S3: taskpaws-development / test / production) └── AWS SES + End User Messaging SMS
LayerChoiceNotes
LanguageRuby 4.0.2platform/.ruby-version
FrameworkRails 8.1.3.1config.load_defaults 8.1
DatabasePostgreSQL via pgConnection from Rails credentials
Web UIHotwire, import maps, PropshaftStimulus mobile-nav (marketing header), sidebar (icon rail), breadcrumbs / breadcrumb-seed (header trail), header-search (typeahead), searchable-selects and form-validation on every shell
CSSTailwind CSS 4 + taskpaws.cssTokens in app/assets/tailwind/application.css
IconsLucide 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 / cacheSolid Queue, Solid Cachebin/jobs; memory cache in development
CableSolid Cable (production), async (development)ClinicBoardChannel for Schedule/Whiteboard, PhotoUploadChannel for QR uploads. See Action Cable
AuthAuthlogicSeparate User and SuperUser; bcrypt. API uses hashed ApiToken Bearer tokens, not cookies
GeocodingAddressGeocoder (Nominatim)Client addresses → lat/lng. Locations not geocoded yet; PostGIS later if needed
AuditAuditedAccounts plus tenancy and clinic records; AuditTimeline on show pages
PaymentsStripeSaaS plan billing only
FilesActive StorageAmazon S3 (:amazon) in every environment
SMSAWS End User MessagingPlatform origination number; per-Location numbers later
i18nen default, esCookie 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):

RouteActionBehavior
GET /main#landingFeatures, pricing, FAQs, trial CTA
GET/POST /login, DELETE /logoutuser_sessionsStaff session → /app
GET/POST /registerusers#new/createCreates User, provisions Organization + Legal Entity + Location + Staff
POST /auth/:provider, callbackOmniAuthGoogle, Apple, Facebook for User only; new visitors finish on /register
GET /appapp/homes#showGreeting, clinic radar (ClinicDayRadar) at a Location with visits.read, SaaS billing widgets. Locked workspaces get the subscribe / buy-credits gate here
PATCH /app/preferenceapp/preferences#updatePer-User UI state (UserPreference: sidebar collapsed, schedule view and hidden columns, breadcrumbs, grid order, locale, appearance)
PATCH /app/workspaceapp/workspaces#updateLocation / Organization switcher (session)
GET /app/searchapp/searches#showHeader typeahead: Postgres FTS, max 10 hits, 3-character gate, patients.read
POST /app/photo_upload_sessions, GET/PATCH /photo_uploads/:tokenHands-off uploadsQR upload session (staff) and public phone page (15 min, single use)
GET/PATCH /app/settings, /app/billing/plan_changeapp/settingsHierarchy, legal entities, locations, location groups (Elite), Billing; /app/billing redirects there
/app/staffs, /app/staff_role_assignmentsapp/staffsDirectory, invite (pending), resend, withdraw, disable/enable, edit roles / hours / commissions
/app/legal_entities, /app/locations, /app/location_groupsCRUDLast entity / location cannot be destroyed. Hours and rooms/equipment on the Location ficha
/app/patients, /app/clientsCRUD (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/taxesCatalog and pricingMaster items, Location / group overrides, locks, exclusive items, taxes
/app/appointment_typesCRUDOrg list (duration, color, catalog item, deposit, clinical); override sets Location enabled. appointmenttypes.read / .manage / .override
/app/inventoryapp/inventory_itemsPer-Location on-hand; adjust quantity / batch
GET /app/scheduleapp/schedules#showStaff/Resource · Day/Week/Month/Year calendar
POST/PATCH /app/appointmentsapp/appointmentsOptional 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_showapp/appointmentsStatus transitions (+ *_series_occurrence)
GET /app/whiteboardapp/whiteboards#showFloor / Pipeline / List
GET /app/visits/:id, /cockpitapp/visits#show/cockpitVisit 360 workspace (full page or drawer). Visits are created only by check-in
PATCH /app/visits/:id, /undo_check_in, POST …/checkoutapp/visitsPlace/status change, narrow undo, open the sales order
/app/visits/:visit_id/soap_noteapp/soap_notesShow, edit, apply_previous, apply_template, save_template
/app/checkout, /app/invoices, /app/credit_notes, /app/depositsClinic financeSales orders, invoices, credit notes, payments, deposits
/app/tips, /app/commissions, /app/commission_groupsStaff payTips and commissions
/app/notification_settingsNotificationsClient email/SMS notifications and templates
/admin/*Admin consoleSee Admin console
/intake/:token, /plans/:token, /photo_uploads/:tokenPublic token pagesPatient intake, treatment plan approval, QR upload
GET /locale/:localelocales#updateSets locale cookie and redirects back
GET /privacy, /terms, /facebook/deletionLegalLegal pages; Facebook data deletion callback and status
POST /webhooks/stripewebhooks/stripe#createStripe SaaS billing webhooks
GET /uprails/health#showLoad 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

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.

PieceRole
OverrideLocksOn the master record: LOCK_COLUMNS (none / locations / everywhere), lock queries, override lookup, default overridable_at?
HierarchyOverrideFieldsOn Location and group override rows: upsert_for!, lock and scope validations, group lock_* booleans, hard-off rule for enabled
Hierarchy::EffectiveRecordResolver: value, source, and trace (the level trail)
Hierarchy::PolicyWho 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_optionsLock picker options; drops locations without Location Groups unless already set
UIApp::HierarchyOverrideParams, App::HierarchyShowOverrides (Details / All sites), App::HierarchyOverridesController (override drawer), App::HierarchyHelper, app/hierarchy/ partials, app.hierarchy.* copy
LocationGroups::OverridesSummaryEverything 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.

TermMeaningCode
Enable / disablePolicy switch: allowed to work or appear in pickersdisabled_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
OverrideA Location or group value replacing the inherited one for one field. Spanish UI “excepción”; never “exception” in English copylocation_*_overrides, location_group_*_overrides
Lock level“Anyone can override”, “Only location groups can override”, “Nobody can override”lock_* = none / locations / everywhere
SellableCatalog item offered for sale at a site (not a status)catalog_items.sellable; overrides use nullable sellable
ActiveReal-time running stateTreatment plan status: "active"; visit on_floor?
AvailableRoom or equipment in servicelocation_resources.available
Admin active usersRecency, not enable/disableactive_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.

PiecePartialRule
Page headerapp/shared/_page_headerTitle, one-line lead, badges, meta, actions right. One per page. crumbs / eyebrow append to the header trail instead of drawing in the page
Section tabsapp/shared/_subnav in page-header :actionsRight-aligned with the title row (wrap_class: nil). Segmented XOR control
Filters and searchapp/shared/_subnav / table_searchFull-width bar below the header (SUBNAV_BAR) only for search or filter rows
Identity carde.g. app/patients/_identityShow-page header: avatar, name, badges, then vitals and alerts
Vitals stripapp/shared/_vitalsFour stable facts in a hairline grid, label above value
Section cardapp/shared/_sectionIcon tile, title, lead, content. Rendered as a layout with a block
Factsapp/shared/_factLabel / value pair inside AppUi::FACT_GRID
Empty stateapp/shared/_empty_stateNeutral tile, one sentence, optional action. Never leave a card blank
Form save barapp/shared/_form_actionsSticky bar: hint, Cancel, one primary submit. Fields use AppUi::FIELD wrappers inside FORM_BODY
Drawerapp/shared/_drawerSlide-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.

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).

HelperWhenEffect
clear_header_crumbsHomeEmpties the trail
seed_header_crumbsSection index pages (Patients, Schedule, Whiteboard, …)Replaces the trail with that root
seed_header_crumbs(*AppNav.settings_trail(item))Settings childrenSeeds Settings > {child}
append_header_crumbsShow and edit pagesExtends 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.

EnvironmentDatabases
developmenttaskpaws_development
testtaskpaws_test
productiontaskpaws, 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!.

Organization ├── 0 ──* Location Group (Elite) ├── 1 ──* Legal Entity (EIN, legal name, currency) │ └── 1 ──* Location (time_zone, address, hours) │ ├── 1 ──* LocationResource (room or equipment) │ └── 1 ──* Appointment (optional patient — walk-in when blank —, optional type) │ ├── 0 ──* Staff, LocationResource │ └── 0 ──1 Visit (created by check-in) ├── 1 ──* AppointmentType (duration, color, catalog item; Location enabled override) ├── 1 ──* Staff (membership; role assignments; pending / disabled) │ └── belongs_to User ├── 1 ──* Client → Patient (disabled_at; patient also deceased_at) └── 1 ──* CatalogItem (master or exclusive; inherit-or-override; stock per Location) User (login; no organization_id) SuperUser (platform operator; no organization_id)

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.

ActorModelScopeSurfaces
Login identityUserIndependent; clinic access through Staff/app, /api/v1
Organization membershipStaffOne User + one Organization; pending until accepted; disabled_at suspends without touching UserFounder register and Staff.invite!
Platform operatorSuperUserEntire 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.

ChannelDomainMessageClients
StatusChannelConnection health (per user)NoneWeb header
ClinicBoardChannelSchedule and Whiteboard (clinic_board:organization:{id}:location:{id}:staff:{id}){ "action": "refresh" }Web. Mobile not subscribed yet
PhotoUploadChannelQR 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.

MethodPathAuthResult
POST / GET / DELETE/api/v1/session, /session/allnone / BearerLogin { token, user, organizations }; show; revoke this token or all
POST/api/v1/social_session, /social_registrationticketToken for an existing User, or registration_required; social founder register
GET/api/v1/homeBearerUser, organization, location, roles, capabilities, workspace
GET/api/v1/billingBearer + accepted StaffTrial, plan, credits, subscription
GET / PATCH/api/v1/organizationsettings viewer / organization.manageHierarchy, counts, rename
CRUD/api/v1/legal_entitiesorganization.manageLast entity / locations present 422
CRUD/api/v1/locations, /:location_id/resourcessettings viewer; manage locationAddress, hours, exceptions, rooms/equipment
CRUD/api/v1/location_groupsorganization.manage, Elite403 plan_feature_unavailable below Elite
GET / POST / PATCH / DELETE/api/v1/staffs, /staff_role_assignmentscan_assign_roles? / may_invite?List, invite, resend, withdraw, disable/enable, edit, assign/revoke roles
GET/api/v1/time_zones, /countriesBearerPicker options
GET / POST / PATCH/api/v1/clients, /api/v1/patientspatients.read / .manageDirectory, detail, create (multipart photo), update
GET / DELETE/api/v1/patient_catalog, /patient_tags/:idpatients.read / .manageAdmission pickers; remove a custom tag
GET/api/v1/scheduleappointments.read at the LocationOccurrences, conflicts, patients, staffs, resources, enabled appointment_types, can_manage
POST / PATCH / DELETE/api/v1/appointments, /:id, /series_occurrenceappointments.manage at the LocationAppointmentWriter: 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