Files
faunosteo/faunosteo-business-architecture.md
bchanot b0cce2cd8c docs(docs): add SaaS implementation plan and architecture docs (step 0)
Eight documents under docs/development/ confronting the approved business
architecture with the audited code: 27-step plan, repository migration map,
domain map, frontend/backend architecture, migration and test strategy,
open questions. Reference document placed at the repository root.
2026-10-08 21:41:39 +02:00

59 KiB

Faunosteo — Business model & technical architecture

Version: 2026-10-07 Status: architecture proposal based on the product brief, answers 1→120 and the Claude Code audit of the current repository.

0. Executive decision

Faunosteo should evolve from a static report generator into a multi-tenant SaaS whose two core domains are:

  1. Care data: client → animal → consultations/reports.
  2. Anatomical content: species → anatomical sheet → immutable versions → SVG/views/annotations/findings.

The report remains a document-oriented object, but is linked to an exact anatomical-sheet version. This makes an old report reproducible even if the sheet later changes or disappears.

The current SVG/pathology system should not be mapped 1:1 into SQL. It should first be normalized into a versioned Anatomical Sheet document model with stable internal IDs. The current fuzzy label matching becomes a migration/import compatibility mechanism, not the runtime relationship between SVG and findings.

The private application can remain close to the existing React/Vite codebase. Public SEO pages should be rendered server-side. Supabase/PostgreSQL/RLS is the system of record. Files use private object storage. Long-lived archives are moved to S3-compatible cold storage according to a legal retention policy.


1. Product / business model

1.1 Target

Initial market: France only.

Languages: French and English.

Audience: animal osteopath professionals, with student/professor education access and platform administration roles.

Product: web application, mobile-friendly from day one. A future native-like application can reuse the private application domain without forcing the public SEO site to become a mobile app.

1.2 Commercial offers

Individual

  • €9/month TTC, proposed launch price.
  • €100/year TTC, proposed launch price.
  • Monthly renewal can be enabled or disabled by the customer.
  • No 10-year offer.
  • Stripe is the future payment processor for Faunosteo subscriptions.
  • Subscription invoices are accessible in the account.

Free launch plan

  • 5 completed/validated reports over the lifetime of the free account.
  • Drafts do not count.
  • Deleting a completed report does not restore quota.
  • Editing a report does not consume a new quota unit, but free accounts can only modify a completed report during the first 5 days after validation; after that it requires a paid entitlement.
  • Imported completed reports count toward the same lifetime quota.
  • A free account can keep its clients/animals, but cannot complete more than 5 reports.
  • If an import would exceed the free quota, the import is blocked before changing data and the user is sent to the pricing page.

Cabinet

A cabinet is an Organization, not a human login.

Possible commercial model:

  • organization/base fee;
  • paid seats belonging to the organization;
  • several seat bundles can be offered later (3, 5, 10, etc.);
  • unused seats are paid;
  • extra seats can be added later.

A personally subscribed practitioner can belong to several cabinets. A practitioner whose access is paid by one cabinet cannot simultaneously use another cabinet-paid seat in another cabinet.

Exact cabinet pricing is deliberately not fixed yet. The commercial constraint is that the final price must preserve approximately the desired revenue per practitioner while adding the cabinet base fee.

Invited access

Admins/owner can grant a full paid-equivalent entitlement to an invited user. It can be:

  • indefinite until revoked;
  • or explicitly expiration-dated.

Platform roles (owner/admin/moderator/support) do not pay.

Referral

  • Referrer: 1 free month after the referred practitioner becomes a real paying customer.
  • Referred practitioner: 1 free month after the end of their own free period.
  • Up to 5 successful referred customers per year per referrer.
  • Rewards stack.
  • Exact anti-fraud rules: verified email + verified phone + rate/abuse controls; temporary/disposable email and suspicious phone sources can be blocked or escalated.

Anatomical-sheet privacy add-on

Public by default.

A creator can pay for private visibility. Private sheets can be shared explicitly with a practitioner or cabinet and can be used to create a copy/fork when permission allows.

Price is intentionally left open.

Future, not MVP

  • online consultation payments;
  • Stripe Connect-style practitioner payouts;
  • certified/integrated invoicing for consultations;
  • customer reviews;
  • full client portal;
  • SMS;
  • native mobile application;
  • white-label;
  • advanced institution/school plans.

2. Core business concepts

2.1 Human account

One person has one Faunosteo account.

Roles are additive:

  • practitioner
  • student
  • professor
  • owner
  • admin
  • moderator
  • support
  • invited entitlement

A user can be, for example, practitioner + professor + moderator without creating multiple accounts.

2.2 Organization / Cabinet

A cabinet is a first-class organization.

Membership roles:

  • owner
  • manager/admin
  • practitioner
  • secretary

A secretary can manage customers, animals, appointments and documents, but cannot create/modify professional reports unless that account also has the practitioner role.

2.3 Client

Client is a global Faunosteo person record, not a copy per practitioner.

A client may have:

  • no login account, but consented stored data;
  • or a linked Auth user account.

Client identity is never exposed to another practitioner merely because an email/phone happens to match. Cross-practitioner association uses a secure verification/consent flow.

2.4 Animal

Animal belongs to a client.

Required:

  • name
  • species
  • breed
  • sex
  • owner/client

Recommended stored fields:

  • date of birth
  • neutered/spayed status
  • identification number
  • weight
  • colour
  • photo
  • general notes
  • death status/date/cause/comment

Animal history is retained when marked deceased.

2.5 Report

A report is a consultation document.

It has one business owner context:

  • cabinet-owned if created in a cabinet context;
  • practitioner-owned if created outside cabinets.

It has a creator practitioner and a current document snapshot.

It stores the exact anatomical-sheet version used.

It has a human-readable report number built from creator-practitioner identity + practitioner-local increment.

2.6 Anatomical Sheet

This is the key new domain object.

A sheet is the whole anatomical configuration, not merely an SVG.

It contains:

  • species;
  • sheet identity/name;
  • creator/owner;
  • visibility;
  • version state;
  • one main view;
  • zero or more detail views;
  • annotations (points/zones/detail triggers);
  • vertebral configuration;
  • categories;
  • finding/observation/anamnesis tree;
  • provenance/fork relationship;
  • legal/disclaimer metadata;
  • publication metadata.

The product vocabulary should use Fiche anatomique everywhere.

2.7 Anatomical Sheet Version

Published versions are immutable.

Editing the visible/current sheet creates a new version. Historical versions stay usable by historical reports.

A deprecated version that is not referenced by any report and has no active derived dependency can be physically deleted by garbage-collection logic. A version referenced by a report is never physically deleted during normal product lifecycle.

This resolves the user's saturation concern without breaking historical documents.

2.8 Fork

Copying an official/community sheet creates a new sheet and records:

  • source sheet ID;
  • source version ID;
  • creator;
  • fork date.

The copied sheet becomes independent. It can later be published as a new community sheet.

2.9 Follow + usage permission

For public community sheets, follow is both:

  • social subscription;
  • permission to use the sheet for new reports.

For private sheets, explicit grants are required. A grant can allow:

  • read/use;
  • fork/copy.

It can target a practitioner or organization and can expire or be indefinite.


3. Main user journeys

3.1 Practitioner onboarding

  1. Create account.
  2. Verify email.
  3. Verify phone.
  4. Fill professional identity.
  5. Upload required professional/legal documents.
  6. Verification becomes pending.
  7. Owner/admin reviews.
  8. Account becomes verified.
  9. User chooses free launch or paid plan.
  10. Create/import first client/animal.

A non-verified account must not access full professional functionality.

3.2 Consultation

  1. Open animal.
  2. Create a report.
  3. Select anatomical sheet from:
    • official sheets;
    • own sheets;
    • sheets of followed practitioners.
  4. Select exact version.
  5. Work in combined Anatomical Sheet editor / report workflow.
  6. Autosave continuously.
  7. A manually created point exists only in this report until promoted to a personal sheet.
  8. Finish report.
  9. Generate/save PDF.
  10. Optional secure sending to the owner.

3.3 Community sheet

  1. Practitioner creates or forks a sheet.
  2. Edits SVG/views/findings.
  3. Publishes a new immutable version.
  4. Public by default.
  5. Other practitioners can discover it.
  6. They follow the creator.
  7. They can use the sheet.
  8. A user can create a personal fork without modifying the original.

3.4 Cross-practitioner animal sharing

  1. Practitioner requests/initiates sharing.
  2. Client receives secure confirmation flow when client identity is not already established for the receiving practitioner.
  3. Client grants selected scope:
    • selected reports;
    • animal/future care relationship;
    • files where appropriate.
  4. Grant can have a duration or be consultation-only.
  5. Grant can be revoked at any time.

Receiving practitioner creates their own report; this does not replace the original report unless the original owner explicitly accepts the new version as current.

3.5 Booking

  1. Client opens public profile/widget.
  2. Chooses service, location, date/time.
  3. Faunosteo evaluates availability including configurable travel time before and after the appointment.
  4. Client fills the configured intake form.
  5. One pending slot maximum for that client per practitioner request context.
  6. Practitioner may auto-confirm or manually approve.
  7. Pending request blocks the slot until accepted/rejected/expired.
  8. Confirmation creates the appointment.
  9. Future reminders are queued if configured.

3.6 Import

  1. User chooses source (Animalib, Kiwi, generic).
  2. Uploads export package.
  3. Faunosteo runs a read-only preflight.
  4. Mapping is shown.
  5. Free-plan quota is checked before import.
  6. User confirms.
  7. Canonical data is created.
  8. Unsupported fields go to "Données importées" and are retained.

AI may assist column mapping/classification, but it must not invent clinical data. Deterministic mapping + user confirmation remains authoritative.


4. PostgreSQL conceptual model

4.1 Identity / access

profiles

  • id uuid PK = auth.users.id
  • display_name
  • first_name
  • last_name
  • phone
  • phone_verified_at
  • avatar_asset_id
  • locale
  • timezone
  • active
  • timestamps

profile_roles

  • user_id
  • role enum (practitioner, student, professor, owner, admin, moderator, support)
  • granted_at
  • granted_by
  • revoked_at

organizations

  • id
  • name
  • slug
  • owner_user_id
  • logo_asset_id
  • public profile settings
  • timestamps

organization_members

  • organization_id
  • user_id
  • role enum (owner, manager, secretary, practitioner)
  • billing_source (seat, personal)
  • joined_at
  • left_at

platform_invitations

For invited accounts and internal access grants.

  • id
  • email
  • user_id
  • invited_by
  • starts_at
  • expires_at nullable
  • revoked_at

5. Professional verification

professional_verifications

  • id
  • user_id
  • status (pending, verified, rejected, expired)
  • siret
  • professional_identifier
  • c2v_theoretical_result/reference
  • c2v_practical_result/reference
  • submitted_at
  • reviewed_at
  • reviewed_by
  • rejection_reason

professional_documents

  • id
  • verification_id
  • document_type (rc_pro, c2v_proof, other_required)
  • asset_id
  • issued_at
  • expires_at nullable
  • status

Automatic expiry should move verification to expired where a required time-bounded document is no longer valid.

Exact required documents and legal acceptance criteria are a legal/business rule to validate before launch.


6. Clients / animals

clients

  • id
  • auth_user_id nullable UNIQUE
  • first_name
  • last_name
  • notes_general nullable
  • timestamps

client_contacts

Allows multiple emails/phones without making email globally unique.

  • id
  • client_id
  • type (email, phone)
  • value
  • normalized_value
  • is_primary
  • verified_at

A secure candidate-matching RPC may use normalized values but must not reveal another professional relationship to an unauthorised practitioner.

client_consents

  • id
  • client_id
  • purpose (care_data, retention, professional_sharing, document_delivery, marketing)
  • status
  • legal_text_version
  • granted_at
  • revoked_at
  • source
  • optional audit metadata

client_access_grants

  • id
  • client_id
  • grantee_type (user, organization)
  • grantee_id
  • scope
  • starts_at
  • expires_at nullable
  • granted_by
  • revoked_at

animals

  • id
  • client_id
  • species_id
  • name
  • breed
  • sex
  • neutered_status
  • birth_date
  • identification_number
  • weight
  • colour
  • photo_asset_id
  • general_notes
  • deceased_at
  • death_cause
  • death_comment
  • timestamps

animal_access_grants

  • animal_id
  • grantee_type
  • grantee_id
  • scope
  • starts_at
  • expires_at
  • granted_by
  • revoked_at

7. Anatomical sheets

7.1 Relational identity

anatomical_sheets

  • id
  • species_id
  • name
  • slug
  • description
  • creator_user_id
  • visibility (public, private)
  • visibility_plan_required
  • status (active, archived, deleted)
  • based_on_sheet_id nullable
  • based_on_version_id nullable
  • current_version_id nullable
  • timestamps

anatomical_sheet_versions

  • id
  • sheet_id
  • version_number
  • status (draft, published, deprecated)
  • document_schema_version
  • content_jsonb
  • main_svg_asset_id
  • published_at
  • deprecated_at
  • published_by
  • timestamps

Published content is immutable.

The database should keep a canonical JSONB document rather than treating raw SVG as the primary data model.

Conceptually:

{
  "schema_version": 1,
  "species_id": "canine",
  "vertebral_formula": {
    "C": 7,
    "T": 13,
    "L": 7,
    "S": 3,
    "Cd": 20
  },
  "views": [
    {
      "id": "view-main",
      "kind": "main",
      "parent_view_id": null,
      "opened_by_annotation_id": null,
      "view_box": "...",
      "svg_asset_id": "..."
    },
    {
      "id": "view-head",
      "kind": "detail",
      "parent_view_id": "view-main",
      "opened_by_annotation_id": "ann-head",
      "view_box": "...",
      "svg_asset_id": "..."
    }
  ],
  "annotations": [
    {
      "id": "ann-...",
      "view_id": "view-main",
      "kind": "point",
      "category_id": "...",
      "name_fr": "...",
      "name_en": "...",
      "laterality": "bilateral",
      "special": null,
      "geometry": {}
    }
  ],
  "finding_tree": {
    "zones": {}
  }
}

Stable internal IDs are generated once and used by both annotations and finding mappings. Human labels are presentation data, not identifiers.

7.3 Detail views

A detail view is a first-class child view, not a special hard-coded head field.

The future editor can create:

main body
 ├── head
 ├── anterior limb
 └── pelvis

and deeper nesting can be supported if technically useful.

The current Horse_head.svg is imported as a manually authored detail view. Automatic crop generation is a future editor operation that writes a real child view.

7.4 Finding catalog

Finding trees remain nested:

  • Dysfonctions ostéopathiques
  • Observations / motifs de consultation
  • Anamnèse / facteurs rapportés
  • plus creator-defined categories.

A node has a stable ID unique at least within the sheet-version document. For database indexing and references, use globally unique UUIDs for persisted nodes.

A finding can contain:

  • FR name
  • EN name
  • descriptions
  • veterinary referral flag
  • sources
  • children

8. Community model

practitioner_follows

  • follower_user_id
  • followed_user_id
  • timestamps
  • unique pair

sheet_usage_grants

For explicit private sharing and future granular permissions.

  • sheet_id
  • grantee_type (user, organization)
  • grantee_id
  • permission (use, fork)
  • starts_at
  • expires_at nullable
  • granted_by
  • revoked_at

Public sheet use is granted by a valid follow. Private use is granted by an explicit row.

community_reports

  • id
  • reporter_user_id
  • resource_type (profile, sheet)
  • resource_id
  • reason
  • details
  • status
  • moderated_by
  • moderated_at

Owner/admin/moderator can moderate. Support should not automatically receive moderation powers.


9. Reports / revisions

reports

  • id uuid
  • report_number
  • animal_id
  • practitioner_user_id
  • organization_id nullable
  • ownership_scope (personal, organization)
  • status (draft, completed, archived)
  • report_date
  • anatomical_sheet_version_id
  • current_document jsonb
  • current_revision_no
  • completed_at nullable
  • free_edit_until nullable
  • deleted_at nullable
  • timestamps

The report number is generated under a row-locked practitioner counter to guarantee per-practitioner monotonic numbering.

report_revisions

  • id
  • report_id
  • revision_no
  • document jsonb
  • created_by
  • reason (autosave_checkpoint, manual_save, completion, restore, shared_practitioner_version, import)
  • timestamps

Autosave updates the current report frequently, but history snapshots are checkpointed at controlled moments rather than every keystroke.

report_access_grants

  • report_id
  • grantee_type (user, organization)
  • grantee_id
  • permission (read, fork_revision)
  • starts_at
  • expires_at
  • granted_by
  • revoked_at

A shared report is not directly edited by the receiving practitioner. They create a version attached to the same logical report history. The original owner must accept it before it becomes the current version.

9.1 Report history semantics

When a report is changed:

  1. current document is copied to report_revisions;
  2. new current document is stored in reports.current_document;
  3. revision number increments;
  4. previous PDF remains available as a document artifact;
  5. historical revision can be restored.

10. Appointments / agenda

service_types

  • id
  • owner scope (practitioner/org)
  • name
  • species applicability
  • duration
  • booking mode (automatic, manual)
  • cancellation deadline
  • reschedule deadline if desired
  • reminder rules
  • deposit settings (future-compatible)
  • active

locations

  • id
  • owner scope
  • name
  • type (practice, home, other)
  • address
  • lat/lng
  • active

availability_rules

  • scope owner
  • weekday
  • local start/end
  • location
  • recurrence metadata

availability_exceptions

  • owner
  • start/end
  • reason
  • blocked/available

travel_profiles

  • owner
  • base location
  • home-return policy
  • routing provider
  • default buffer before/after
  • manual overrides allowed

travel_pricing_rules

  • owner
  • max radius km
  • surcharge
  • priority/order

appointments

  • id
  • practitioner
  • organization nullable
  • client
  • animal
  • service type
  • location
  • start/end
  • status (requested, confirmed, rejected, cancelled, completed, no_show)
  • request expiration
  • cancellation reason
  • reschedule metadata
  • deposit-required flag
  • deposit status (not_required, requested, paid, not_confirmed)
  • deposit amount
  • deposit method
  • travel_before_minutes
  • travel_after_minutes
  • travel_override_minutes nullable
  • source (profile, widget, manual, external_sync)
  • timestamps

Booking expiry rules

  • Normally pending request expires 48h before appointment.
  • If requested less than 72h before the appointment, expire 24h before.
  • If requested less than 25h before, expire 1h before.
  • Pending request then releases the slot.

These rules should be implemented in one database/backend function, not duplicated in several UI components.

Client restriction

A client may not hold multiple simultaneously pending slot requests against the same practitioner booking flow. This mitigates intentional agenda blocking.


11. Travel-aware availability engine

Travel is a core product feature.

For each appointment, the scheduler evaluates:

previous event location
        ↓
travel to new location
        ↓
appointment duration
        ↓
travel after appointment
        ↓
next event / optional return to base

A practitioner can manually increase travel time for an individual customer/appointment even when a route estimate already exists.

The engine should expose a provider interface:

RoutingProvider
  getRouteDuration(origin, destination, departureTime)
  getDistance(origin, destination)
  getMatrix(origins, destinations)

Do not hard-code Google/Waze/Mappy into business logic. The production provider can be selected after testing France coverage, quotas, terms and cost. Waze/Mappy/other map services should be treated as replaceable providers, not hard dependencies.

Use a route cache for repeated origin/destination calculations. For booking, the final check must be performed server-side to avoid client-side manipulation.


12. External calendars

external_calendar_connections

  • id
  • user/org
  • provider (google, future apple_ics)
  • account label
  • encrypted refresh credentials (server only)
  • sync state
  • active

external_calendar_events

  • connection
  • provider event ID
  • start/end
  • external calendar ID
  • blocks_faunosteo_booking
  • checksum/version
  • last_seen_at

Google should support two-way synchronization. Apple starts with ICS/subscription semantics rather than trying to reproduce Google's full account integration in the first release.

External-event titles/details are never exposed to clients. Only availability/blocking state is public.

Conflicts discovered during synchronization generate an alert for the practitioner.


13. Booking widget / public API

booking_widget_tokens

  • id
  • owner user/org
  • token hash
  • allowed origins
  • active
  • created_at
  • revoked_at

Public widget architecture:

customer site
    ↓
Faunosteo script
    ↓
Faunosteo iframe / booking UI
    ↓
public booking endpoints

The first implementation should prefer an iframe controlled by Faunosteo, with postMessage for height/theme communication. The token identifies the practitioner/widget and can be revoked. Direct public database access is not granted.

The API may later expose read-only service/availability endpoints and webhook-style booking events for developer integrations.


14. Intake forms

intake_forms

  • owner scope
  • name
  • species optional
  • active
  • version

intake_questions

  • form/version
  • stable key
  • type
  • label FR/EN
  • required
  • conditional expression
  • order
  • validation rules

appointment_intake_answers

  • appointment
  • form version
  • answer JSONB
  • submitted_at

Default templates can exist per species; practitioners can create custom questions.

Historical appointment answers remain tied to the form version used at that time.


15. Documents / Storage

15.1 Active storage

Use private Supabase Storage buckets for active user files:

avatars/
logos/
professional-documents/
client-files/
animal-files/
report-files/
anatomical-sheets/
imports/

PostgreSQL stores metadata, ownership, resource relations and access rules. Storage objects contain the bytes.

Supabase Storage is designed to be controlled with Postgres RLS policies on storage.objects, so all buckets should be private by default and access should be explicitly granted. citeturn899094search3

Never use user-controlled filenames as authorization identifiers.

Example:

report-files/<report-id>/<asset-id>/<safe-filename>

The database remains authoritative for whether the requesting user may access that object.

15.3 SVG security

User/community SVGs must be sanitized server-side before becoming available to others. The current client-side sanitizer is not sufficient as the security boundary in a multi-user SaaS.

Disallow dangerous constructs such as scripts, event handlers, javascript URLs and unsafe embedded content. Render only sanitized content.

15.4 Archive storage

After one year without payment, the account data is exported/archived and removed from the primary database according to the final retention/legal policy.

Use an S3-compatible archive layer. S3 lifecycle rules can transition objects to lower-cost storage classes or expire them, and S3 Versioning can preserve multiple object versions. citeturn899094search4turn899094search8

Do not enable S3 Object Lock by default for ordinary customer archives. It can make deletion impossible during the retention period, which conflicts with some data-erasure workflows. Use it only if legal counsel establishes a requirement; AWS documents that Object Lock is deliberately designed to prevent deletion/overwrite during a retention period. citeturn899094search0turn899094search9


16. Data lifecycle / deletion

Active account

Primary database contains active records and active files.

1 year without subscription

  1. Restrict application access.
  2. Allow data export.
  3. Create an archive package.
  4. Verify archive checksum/manifest.
  5. Copy to archive storage.
  6. Remove hot database copies according to legal policy.
  7. Keep an archive pointer in a minimal operational record if legally permitted.

Account deletion

Same approach:

  • 1 year hot retention as currently requested;
  • archive after the hot retention window;
  • definitive deletion after the final legal retention period.

Exact retention durations remain a legal decision.

Anatomical-sheet garbage collection

For deprecated sheet versions:

Safe physical deletion only when all are true:

  • no report references the version;
  • no active fork depends on it;
  • no required share/grant references it;
  • no pending process references it.

Otherwise mark/deprecate and retain.


17. Roles / RLS strategy

Supabase Auth provides the authenticated identity; PostgreSQL RLS is the final authorization boundary. Supabase recommends enabling RLS on every table exposed to clients and separating SELECT/INSERT/UPDATE/DELETE policies. citeturn899094search1

17.1 Never use the browser as the security boundary

The browser can hide buttons, but RLS must enforce access.

Never ship:

  • service-role keys;
  • admin credentials;
  • storage master credentials;
  • third-party refresh tokens.

17.2 Security helper functions

Create small, tested SQL security-definer helpers:

is_platform_owner(uid uuid)
is_platform_admin(uid uuid)
is_platform_moderator(uid uuid)
is_support(uid uuid)
is_org_member(uid uuid, org uuid)
is_org_manager(uid uuid, org uuid)
is_org_practitioner(uid uuid, org uuid)
can_view_client(uid uuid, client uuid)
can_view_animal(uid uuid, animal uuid)
can_view_report(uid uuid, report uuid)
can_edit_report(uid uuid, report uuid)
can_use_sheet(uid uuid, sheet uuid)
can_fork_sheet(uid uuid, sheet uuid)
has_active_entitlement(uid uuid, feature text)

Functions should be minimal, deterministic, indexed and protected from recursive RLS evaluation.

17.3 Core RLS rules

Profiles

User can read/update own profile. Admins can manage platform roles through dedicated server actions, not arbitrary browser updates.

Organizations

Members can see their organization. Managers/owners manage membership. Secretaries cannot grant themselves practitioner access.

Clients

A practitioner can only see a client where they have a care relationship/access grant through their own work or a cabinet, or where a verified client-sharing grant exists.

Animals

Owner/client and authorized practitioners/cabinets can read. Update is owner-controlled, with practitioner update permitted only after a consultation context or explicit owner permission.

Reports

Read if:

  • current practitioner owns it;
  • organization owns it and the user is authorized member;
  • explicit report access grant exists;
  • explicit client-approved share permits it.

Write if the user owns/works within the owning scope. External practitioners create their own revision/version, not overwrite the original directly.

Anatomical sheets

Public metadata is exposed through dedicated public views/RPCs.

Private/full content requires:

  • creator/owner access;
  • explicit grant;
  • or follow-based public-use permission.

Community moderation

Only owner/admin/moderator can moderate reports. Support does not inherit moderation automatically.

17.4 Public endpoints

For public profiles, public sheet discovery and booking, prefer security-definer RPCs or narrowly exposed SQL views returning only approved public columns. Do not create broad SELECT policies on core customer tables for anonymous users.

17.5 Admin impersonation

Support/admin debugging may use a controlled impersonation feature, but:

  • explicit authorization;
  • short-lived session/token;
  • audit record;
  • visible “acting as” banner;
  • automatic expiry;
  • no password access.

18. Subscription / entitlements model

Do not spread is_paid booleans across tables.

Use:

plans

  • code
  • product type
  • billing interval
  • price TTC
  • feature limits

subscriptions

  • subscriber type (user, organization)
  • subscriber ID
  • Stripe customer/subscription IDs
  • status
  • period start/end
  • cancel-at-period-end

subscription_seats

  • subscription ID
  • seat ID
  • assigned user
  • status
  • assigned_at
  • removed_at

entitlement_grants

For non-Stripe access sources:

  • student
  • invited
  • promo
  • admin
  • professor

Then expose a single SQL view/RPC:

get_effective_entitlements(user_id)

The application asks for capabilities, not raw billing flags.

Example:

reports.write
reports.edit_after_free_window
community.publish_sheet
booking.manage
profile.public
student.review

This prevents future plan changes from requiring a rewrite of authorization logic.


19. Student / professor model

This is after the commercial MVP but should be designed now.

  • student user
  • professor user
  • status
  • started_at
  • ended_at
  • revoked_at

student_access_periods

  • student
  • professor
  • starts_at
  • ends_at
  • renewal source

Students can work on real educational cases and real reports, but cannot autonomously create their own client base or public professional profile.

They can:

  • create educational reports;
  • access animals/reports shared by their professor;
  • see/read shared peer work in the professor's group;
  • submit reports to the professor;
  • receive annotations/review.

Student reports are student_owned educational records and are not automatically transferred to practitioner history when the student graduates.

A professor can revoke access. A student cannot self-renew a free year without a professor relationship.


20. Future client account

MVP:

  • client does not need an account;
  • secure email links;
  • consented storage;
  • secure document delivery.

Sprint 2 client portal:

  • claim account;
  • verify identity;
  • see animals;
  • see appointments;
  • see reports/documents;
  • update personal information;
  • manage sharing/consents;
  • eventually search practitioners.

A secure claim token should connect a verified client to their existing global client record rather than exposing records by raw email match.


21. Frontend architecture

21.1 Keep the current application close to its working form

Recommended monorepo:

apps/
  public-web/     Next.js, SEO/public pages
  app/            React/Vite, private application
  worker/         Node worker for asynchronous jobs

packages/
  domain/         canonical types + Zod
  anatomy/        anatomical sheet editor/model
  pdf/            PDF generation/import
  i18n/           FR/EN
  supabase/       shared DB clients/types
  ui/             shared UI primitives
  config/         environment/runtime config

supabase/
  migrations/
  functions/
  seed/
  tests/

docs/

21.2 Public site

Next.js for:

  • landing page;
  • practitioner public profiles;
  • public practitioner search;
  • community sheet discovery;
  • SEO landing pages;
  • blog later.

Supabase supports SSR flows, and its current recommended SSR package is @supabase/ssr; its current documentation notes that this package is still beta, so keep the public/auth adapter isolated behind a small internal module. citeturn851632search1turn851632search8

21.3 Private app

Keep the current Vite/React app initially.

Routes should become roughly:

/app
/app/dashboard
/app/calendar
/app/clients
/app/animals/:animalId
/app/reports/:reportId
/app/anatomy
/app/anatomy/:sheetId/editor
/app/community
/app/profile/edit
/app/settings
/app/billing
/app/admin/*

21.4 State management

Zustand remains useful for ephemeral report/editor state.

Server truth is PostgreSQL. Do not mirror the whole database into Zustand.

Pattern:

React Query / server data
        +
Zustand editor session state

The current report store should be refactored so its persistence adapter can target Supabase rather than localStorage/sessionStorage.

21.5 Domain boundaries

No business rule should live in a random component.

Use:

UI
 ↓
application service / mutation
 ↓
Supabase RPC or Edge Function
 ↓
PostgreSQL/RLS

22. Backend architecture

22.1 Supabase core

Use:

  • Auth
  • PostgreSQL
  • RLS
  • Storage
  • database functions
  • Edge Functions where appropriate.

Supabase Auth integrates with Postgres and RLS, and Supabase explicitly documents the combination as the normal row-by-row authorization model. citeturn851632search4turn899094search1

Self-hosted Supabase is supported via Docker, which matches the initial Scaleway strategy. citeturn899094search10

22.2 Edge Functions

Good uses:

  • booking API;
  • public widget endpoints;
  • email send orchestration;
  • Stripe webhooks later;
  • public/share tokens;
  • lightweight import preflight;
  • signed URLs;
  • external calendar callbacks.

Keep heavy operations out of short-lived HTTP functions. Supabase documents wall-clock, memory and CPU limits for hosted Edge Functions and recommends moving heavier work to background workers. citeturn851632search0turn851632search7

22.3 Worker

Run one small Node worker initially on the same Scaleway infrastructure.

Responsibilities:

  • reminder emails;
  • appointment expiry;
  • calendar sync jobs;
  • route-cache refresh;
  • PDF generation if later server-side;
  • long imports;
  • archive jobs;
  • data cleanup;
  • community garbage collection.

Start with PostgreSQL-backed jobs to avoid Redis on day one. Move to SQS/another queue only when actual load justifies it.

22.4 Email

Use a transactional email provider rather than an SMTP server maintained by Faunosteo.

Provider abstraction:

EmailProvider
  send(template, recipient, payload)

Candidate providers can be evaluated later based on EU processing, deliverability, price and API quality.


23. Current-code migration strategy

23.1 What is preserved

The current project already provides valuable components:

  • report domain validation;
  • observation UI;
  • finding tree UI;
  • PDF generation/import;
  • SVG parsing/rendering concepts;
  • FR/EN dictionaries;
  • report snapshots.

23.2 What must be refactored

SVG IDs

Replace opaque timestamp-like IDs as primary references with stable generated IDs.

Current fuzzy name matching becomes an import/migration helper only. Runtime mapping is explicit:

annotation_id → finding-zone-id

Vertices / spine

Move vertebral regions/formulas into the anatomical sheet's data model. Remove hard-coded five-region assumptions from generic domain code.

Detail views

Replace hard-coded details.head with generic child views and parent/trigger relationships.

SVG document model

Extract the current DOM-centric editor into:

load document
→ edit model
→ render SVG
→ serialize

not:

DOM is the database

Pathology editor

Merge its domain model with the anatomical sheet model while preserving reusable recursive tree logic.

23.3 Official equine seed migration

Create:

Faunosteo / Cheval
  Fiche anatomique officielle
    v1

Import:

  • Horse.svg;
  • Horse_head.svg;
  • current manifest settings;
  • current pathologies.json.

Generate explicit stable annotation IDs and a deterministic old-ID → new-ID mapping.

Build explicit finding-zone mappings from the current 26 zone names once during migration.

Never perform fuzzy matching during normal report rendering.

23.4 Current report compatibility

Because there is no customer install base, the migration does not need to preserve a public contract with old users.

Still keep a development-only adapter for current Report v2/PDF import so regression tests can validate the move.

23.5 Current known quirks

The migration should explicitly normalize:

  • duplicate catalogue IDs in unrelated zones;
  • old category slug anomalies;
  • missing English descriptions;
  • current detail SVG manual-copy model;
  • orphaned findings behaviour;
  • hard-coded equine vertebral region parsing.

24. Competitor migration architecture

24.1 Staging model

import_jobs
import_files
import_raw_records
import_mappings
import_errors
import_unmapped_data

Raw source content remains available for troubleshooting/audit.

24.2 Adapter model

ImportAdapter
  detect(file/package)
  inspect()
  map()
  validate()
  transform()
  commit()

Adapters:

  • animalib
  • kiwi
  • generic_csv
  • generic_xlsx
  • generic_json
  • generic_zip

Additional vendor adapters can be added without changing the canonical data model.

24.3 Duplicate resolution

Never silently merge.

Potential match:

Jean Dupont
email match
phone mismatch

becomes:

candidate duplicate → user confirmation

24.4 Unsupported fields

Data that has no canonical destination goes into a visible Données importées area linked to the import job/source record.

24.5 Acquisition of vendor exports

Before production adapters are finalized, obtain anonymized representative exports from Animalib and Kiwi. Where vendor export formats are undocumented, collect sample exports through cooperating practitioners rather than building assumptions from marketing pages.

24.6 Commercial migration offer

If an automated import fails, offer a migration-assistance path rather than blocking adoption. A temporary free month can be granted while the transfer is completed manually.


25. PDF strategy

The PDF remains a first-class portable artifact.

Every completed report should be renderable from its stored snapshot plus the exact anatomical-sheet version reference.

For maximal long-term resilience, the PDF should continue to contain a portable JSON attachment/snapshot. The attachment should contain:

  • report document;
  • report schema version;
  • sheet version ID/reference;
  • enough sheet content snapshot to render the historical report independently.

If some PDF viewers ignore attachments, the visible PDF remains the human-readable archive.

Tenant/practitioner branding must be injected through configuration rather than hard-coded logos/URLs.


26. Offline strategy

MVP target:

network interruption safety, not a full offline mirror of the whole account.

The report editor should:

  1. persist current unsynced report changes locally in IndexedDB;
  2. show sync state;
  3. retry automatically;
  4. reconcile conflicts by creating a conflict revision rather than silently overwriting.

If two devices edit the same report offline, the user chooses the final version. Both versions remain recoverable.

Do not attempt to cache the complete customer database for offline use in the MVP.


27. Public profile / SEO model

public_practitioner_profiles

  • practitioner
  • slug
  • public name
  • biography
  • profile photo
  • logo
  • address/locations as permitted
  • service types
  • prices
  • intervention zones
  • travel policies
  • species
  • social links
  • verification status
  • published flag

Public page:

/faunosteo/osteopathe/<slug>

Possible future SEO pages:

/osteopathes-animaliers/<region>
/osteopathes-animaliers/<city>
/osteopathes-animaliers/<species>

Only public profile data is indexed. No clinical/client data is indexed.


28. RGPD / privacy architecture

The legal model should be validated formally before launch.

Architecture should nevertheless assume:

  • least privilege;
  • consent/version tracking;
  • exportability;
  • deletion workflows;
  • access grants with expiry/revocation;
  • audit trail;
  • private Storage;
  • secure links;
  • no sensitive data in URLs;
  • no clinical data in logs;
  • no third-party analytics on clinical screens unless legally justified/configured.

Recommended conceptual responsibility split to validate legally:

  • practitioner/cabinet: likely data controller for their client/animal care records;
  • Faunosteo: likely processor for those records while also being controller for its own account, billing and public/community data.

Do not publish this legal qualification without legal validation.


29. Audit logs

audit_logs

  • id
  • actor_user_id
  • action
  • resource_type
  • resource_id
  • organization_id nullable
  • target_user_id nullable
  • metadata JSONB, sanitized
  • occurred_at
  • request correlation ID

Log at least:

  • professional verification decisions;
  • role changes;
  • organization membership changes;
  • data export;
  • account deletion;
  • report sharing/revocation;
  • client consent changes;
  • admin impersonation;
  • moderation actions;
  • subscription entitlement overrides;
  • large imports.

Never log report contents or passwords.


30. Security baseline

Required for MVP:

  • email verification;
  • phone verification;
  • strong password policy;
  • password reset;
  • Google login;
  • Apple login;
  • magic link/OTP where useful;
  • admin MFA mandatory;
  • practitioner MFA optional initially;
  • rate limiting;
  • private storage;
  • server-only service keys;
  • RLS on all exposed tables;
  • security tests for representative cross-tenant cases;
  • automated backup verification;
  • dependency audit;
  • CSP and secure headers;
  • audit logs.

Supabase supports email/password and passwordless authentication, plus Google and Apple OAuth, so the requested authentication methods fit the chosen platform. citeturn851632search4turn851632search6turn851632search5turn851632search12


31. Self-hosted → managed migration

Stage 1: launch

  • Scaleway France infrastructure.
  • self-hosted Supabase.
  • private Storage.
  • one application server/worker.
  • daily backups.
  • monthly retained backup.

Stage 2: approximately 100 paying members

Trigger a migration project when one or more are true:

  • 100 paying members;
  • backup/upgrade operations are becoming risky;
  • uptime requirements increase;
  • database/storage traffic justifies managed services.

Move to managed cloud while preserving the logical contract:

same PostgreSQL schema
same RLS rules
same object-key conventions
same API contracts

Self-hosted Supabase is explicitly supported and is intended for Docker-based deployment, so the initial environment is aligned with the current Supabase model. citeturn899094search10

The migration should be rehearsed on a staging copy before production cutover.


32. Database indexes that matter

At minimum:

clients: normalized contact indexes
animals: client_id, species_id
reports: animal_id, practitioner_user_id, organization_id, status, report_date
reports: anatomical_sheet_version_id
report_revisions: report_id, revision_no
organization_members: organization_id, user_id
client_access_grants: client_id, grantee
animal_access_grants: animal_id, grantee
report_access_grants: report_id, grantee
anatomical_sheets: species_id, creator_user_id, visibility, status
anatomical_sheet_versions: sheet_id, status, version_number
practitioner_follows: followed_user_id, follower_user_id
appointments: practitioner + start/end + status
external_calendar_events: connection_id + start/end
availability_rules: owner + weekday

The exact composite indexes should be validated with EXPLAIN ANALYZE against realistic seed data.


33. MVP scope

The sellable MVP includes:

Identity

  • professional account;
  • verification workflow;
  • practitioner profile;
  • email/phone verification;
  • Google/Apple/password auth.

Cabinet

  • organization;
  • members;
  • secretary;
  • organization ownership of organization-created reports;
  • personal vs organization context.

Clients/animals

  • global client records;
  • consented implicit client account;
  • animals;
  • deceased status;
  • photos/files;
  • access/sharing.

Reports

  • cloud autosave;
  • draft/completed;
  • history/revisions;
  • report number;
  • anatomical-sheet version reference;
  • PDF export/import;
  • copy from previous report.

Anatomical content

  • official sheets;
  • personal sheets;
  • SVG editor;
  • finding editor;
  • detail SVG creation;
  • species architecture;
  • versioning;
  • publication/deprecation;
  • fork/copy.

Community — mandatory for commercial MVP

  • practitioner profiles;
  • follow;
  • public sheets;
  • sheet usage permission;
  • simple search;
  • usage/download/adoption count as appropriate;
  • reporting/moderation;
  • version evolution.

Agenda

  • availability;
  • services;
  • locations;
  • home visits;
  • travel buffers;
  • route calculation;
  • auto/manual booking;
  • request expiry;
  • cancellation;
  • rescheduling request/acceptance;
  • future-ready deposit status;
  • Google Calendar integration;
  • Apple ICS;
  • public widget/token.

Public website

  • landing page;
  • practitioner public profile;
  • basic practitioner search;
  • SEO.

Billing

  • free 5-report plan;
  • individual monthly/yearly;
  • cabinet plan groundwork;
  • referral;
  • Stripe subscription billing;
  • subscription invoices.

Import

  • import framework;
  • generic CSV/XLSX/JSON/ZIP where feasible;
  • Animalib adapter when sample export is available;
  • Kiwi adapter when sample export is available;
  • unmapped-data preservation;
  • free-plan preflight.

34. Post-MVP order

Sprint immediately after MVP

  • configurable email reminders;
  • client portal;
  • full owner self-service;
  • more polished external calendar sync.

Next

  • professor/student system;
  • review/annotation workflow;
  • school-oriented features.

Later

  • consultation online payment;
  • advanced invoicing;
  • reviews;
  • public practitioner directory;
  • native mobile;
  • SMS;
  • advanced analytics;
  • white-label.

35. Sprint breakdown

The sprint numbers are deliberately feature-based rather than arbitrary calendar estimates.

Sprint 0 — Architecture foundation

Deliver:

  • monorepo structure;
  • Supabase local/self-host environment;
  • migration system;
  • environment management;
  • generated DB types;
  • CI checks;
  • RLS testing harness;
  • backup job;
  • audit-log skeleton.

Exit criteria:

  • clean development bootstrap;
  • pnpm typecheck, tests and lint pass;
  • authenticated request can hit a protected table safely.

Sprint 1 — Auth + profile + professional verification

  • Supabase Auth;
  • email/password;
  • Google;
  • Apple;
  • magic link/OTP;
  • phone verification;
  • profile;
  • verification workflow;
  • admin review.

Sprint 2 — Organizations / cabinets

  • organization creation;
  • membership;
  • roles;
  • personal/cabinet context;
  • permission tests;
  • seat abstraction.

Sprint 3 — Client / animal domain

  • clients;
  • contact methods;
  • consent model;
  • animals;
  • ownership;
  • deceased;
  • private notes;
  • files.

Sprint 4 — Cloud reports

  • migrate report store to server persistence;
  • autosave;
  • drafts;
  • revisions;
  • restore;
  • previous-report copy;
  • report numbering;
  • 5-day free editing rule;
  • 5-report lifetime quota.

Sprint 5 — Anatomical sheet data model

  • canonical JSON schema;
  • sheet/version tables;
  • stable annotation IDs;
  • explicit SVG ↔ finding mapping;
  • species abstraction;
  • seed equine sheet v1.

Sprint 6 — Anatomical editor merge

  • main/detail views;
  • points/zones;
  • detail generation;
  • vertebral configuration;
  • finding tree editor;
  • create/delete/edit categories and findings;
  • manual report point → promote to personal sheet.

Sprint 7 — PDF + historical portability

  • PDF storage;
  • tenant branding;
  • snapshot attachment;
  • import;
  • report rendering from exact sheet version;
  • migration regression suite.

Sprint 8 — Agenda core

  • services;
  • availability;
  • locations;
  • travel rules;
  • booking engine;
  • pending request expiry;
  • cancellation/reschedule;
  • manual appointment creation.

Sprint 9 — Travel engine + calendars

  • routing provider abstraction;
  • cache;
  • before/after travel;
  • return-home policy;
  • Google sync;
  • Apple ICS;
  • conflicts/alerts.

Sprint 10 — Public profile + widget

  • public profile;
  • public routes;
  • SEO metadata;
  • location/intervention zone;
  • service display;
  • booking widget;
  • token management.

Sprint 11 — Community

Mandatory before commercial sale:

  • practitioner follow;
  • community sheet discovery;
  • public sheet use permission;
  • forks;
  • versions;
  • private sheet grants;
  • report content moderation;
  • profile/sheet reporting.

Sprint 12 — Billing + referral

  • Stripe customer/subscription;
  • monthly/yearly plans;
  • trial/free state;
  • entitlement engine;
  • referral rules;
  • billing history;
  • subscription lock/archive states.

Sprint 13 — Migration engine

  • staging/import framework;
  • generic CSV/XLSX/JSON;
  • import preview;
  • duplicate review;
  • unmapped data;
  • Animalib adapter;
  • Kiwi adapter when format obtained.

Sprint 14 — Production hardening

  • full RLS audit;
  • storage policy audit;
  • admin MFA;
  • rate limiting;
  • backup restore test;
  • security headers;
  • upload sanitization;
  • monitoring;
  • data export;
  • deletion flows;
  • legal-document acceptance/versioning.

At the end of Sprint 14, the target is the first real paid practitioner cohort.


36. Claude Code operating rules

Claude Code must not be allowed to redesign the database ad hoc from one feature to another.

The architecture should be implemented from reviewed migration files and domain contracts.

Every feature must include:

  1. schema/migration;
  2. RLS tests;
  3. domain Zod types;
  4. application service;
  5. UI;
  6. unit/integration tests;
  7. migration/backward-data considerations;
  8. documentation.

Before every commit:

pnpm typecheck
pnpm test:run
pnpm lint

For database changes:

supabase db reset
supabase test db

Then run the application regression suite.


37. Claude Code prompts

Prompt 1 — Architecture bootstrap

You are the lead engineer for Faunosteo.

Read:
- the existing repository;
- docs/faunosteo-audit/;
- the approved Faunosteo business architecture document.

Do not implement features yet.

Produce:
1. a target monorepo tree;
2. domain boundaries;
3. proposed Supabase migration order;
4. RLS helper-function design;
5. storage bucket design;
6. shared package boundaries;
7. migration risks from the current code;
8. a dependency graph of implementation stages.

Important:
- do not redesign the business rules;
- do not invent alternative product rules;
- flag contradictions instead of silently resolving them;
- do not write application code beyond minimal scaffolding.

Prompt 2 — Database foundation

Implement only the PostgreSQL/Supabase foundation described in the approved architecture.

Create migrations for:
- profiles
- profile_roles
- organizations
- organization_members
- clients
- client_contacts
- client_consents
- animals
- access grants
- audit_logs
- plans/subscriptions/entitlements skeleton

Requirements:
- UUID primary keys;
- foreign keys;
- useful CHECK constraints;
- timestamps;
- indexes based on access paths;
- RLS enabled on every exposed table;
- no broad permissive policies;
- security-definer helper functions for authorization;
- database tests for cross-user/cross-organization isolation.

Do not build the UI.
Do not use service-role access from browser code.
Report all assumptions before implementation.

Prompt 3 — Anatomical-sheet refactor

Read docs/faunosteo-audit/03-svg-editor.md,
04-detail-svg-generation.md,
05-findings-editor.md,
06-svg-findings-link.md,
07-special-cases.md,
08-report-and-pdf.md,
09-data-model.md,
10-current-limitations.md,
11-future-merge.md.

Refactor the current anatomy domain into a canonical versioned Anatomical Sheet model.

Goals:
- stable annotation IDs;
- explicit annotation -> finding-zone mapping;
- generic detail views;
- species-owned vertebral formula;
- recursive finding tree;
- no runtime fuzzy matching;
- fuzzy matching allowed only by import/migration helpers.

Seed the current equine assets as official sheet version 1.

Do not implement community sharing yet.
Do not change report UI beyond the minimum adapter layer.

Write tests for every old special case found in the audit.

Prompt 4 — Editor merge

Merge the current SVG editor and finding editor into the new Anatomical Sheet editor.

The editor must operate on a structured model, not treat the DOM as the source of truth.

Required:
- main SVG;
- detail SVG/views;
- select/create/edit/delete points and zones;
- custom categories;
- findings/observations/anamnesis tree;
- laterality;
- vertebral precision;
- create a detail view from a selected zone;
- stable IDs;
- save draft/publish version flow.

A published version is immutable.
Editing creates the next version.
Old versions used by reports must remain valid.

Preserve existing report behaviour while changing the underlying storage model.

Prompt 5 — Reports / autosave / history

Implement cloud-persisted reports.

Rules:
- client -> animal -> report;
- report can be personal or organization-owned;
- autosave to PostgreSQL;
- IndexedDB fallback for temporary network loss;
- report revision history;
- restore revision;
- complete report;
- 5-day editing window for free plan;
- lifetime quota of 5 completed reports for free users;
- deleted completed reports still count;
- imported completed reports count;
- previous report copy;
- exact anatomical-sheet version reference.

The UI must clearly show sync state and never claim a completed save before the server has acknowledged it.

Prompt 6 — Agenda/travel

Implement the appointment system using a server-authoritative booking engine.

Rules:
- automatic or manual approval;
- one pending request per client/practitioner flow;
- pending slot blocks until resolution;
- expiry: 48h normally, 24h when requested <72h before, 1h when requested <25h before;
- cancellation and client-requested rescheduling;
- practitioner can cancel;
- service types;
- locations;
- availability rules/exceptions;
- home-visit zones;
- travel before and after every appointment;
- optional return-to-base;
- per-appointment manual travel override;
- deposit state without online collection.

Booking race conditions must be prevented by PostgreSQL locking/constraints, not UI logic.

Prompt 7 — Community

Implement the community model.

Required:
- practitioner follow;
- public practitioner profile;
- discoverable anatomical sheets;
- follow is required to use a public sheet;
- private sheets require explicit grants;
- grant can allow use or fork;
- creator cannot be modified by followers;
- fork records provenance;
- sheet versions are immutable once published;
- deprecated unused versions can be garbage-collected;
- reporting/moderation for profiles and sheets;
- public counts for followers and sheet usage.

Do not add likes/comments/rating.

Prompt 8 — Billing/referral

Implement subscription entitlements.

Plans:
- individual monthly €9 TTC;
- individual yearly €100 TTC;
- free launch entitlement: 5 lifetime completed reports.

Implement:
- Stripe customer/subscription mapping;
- monthly/yearly renewals;
- cancellation at period end;
- billing history;
- invoice links;
- entitlement calculation;
- referral: 1 free month to referrer and 1 free month to referred paid customer;
- max 5 successful referrals/year per referrer;
- verified email + verified phone prerequisites;
- cabinet-seat abstraction.

Do not implement payment collection for consultations.

Prompt 9 — Migration import framework

Build an import framework with staging and preview.

Required source abstraction:
- Animalib
- Kiwi
- CSV
- XLSX
- JSON
- ZIP

Rules:
- read-only preflight before commit;
- duplicate candidates are never silently merged;
- unsupported source fields are preserved in “Données importées”;
- free-plan quota is checked before import;
- 20-report import cannot partially slip through on a free account;
- deterministic mappings are authoritative;
- AI may suggest mappings but cannot invent values;
- every transformed field must be traceable to source data.

Do not scrape competitor websites for customer data.

Prompt 10 — Production hardening

Perform a security and reliability audit of the completed Faunosteo SaaS.

Test:
- every RLS policy;
- cross-tenant isolation;
- organization membership changes;
- report-sharing edge cases;
- expired/revoked grants;
- private anatomical sheets;
- storage object access;
- uploaded SVG sanitization;
- admin impersonation audit;
- backup/restore;
- account deletion;
- archive jobs;
- subscription expiration;
- booking race conditions;
- offline conflict handling;
- public SEO data leaks.

Do not fix blindly. For each finding, show:
- severity;
- attack/bug scenario;
- affected code;
- recommended fix;
- regression test.

38. Definition of done for commercial MVP

Faunosteo is ready for the first paying practitioner cohort only when all are true:

  • a practitioner can create and verify an account;
  • a cabinet can be created and members managed;
  • client/animal records are persisted securely;
  • reports autosave and survive network loss;
  • report history/restoration works;
  • official and personal anatomical sheets work;
  • the merged editor supports points, zones, details and findings;
  • old report content remains reproducible against its sheet version;
  • PDF export/import works;
  • public practitioner profile works;
  • booking works with travel constraints;
  • widget works on third-party websites;
  • community follow + public sheets + forks work;
  • referral works;
  • subscription billing works;
  • free quota abuse is prevented;
  • basic competitor import framework exists;
  • admin moderation works;
  • data export works;
  • account deletion/archive flow works;
  • RLS/security tests pass;
  • backup restore has been successfully rehearsed;
  • legal documents and privacy flows have been professionally validated before production use.

39. Key architectural principles to preserve

  1. Animal ≠ Anatomical Sheet.
  2. Report ≠ Anatomical Sheet.
  3. Published sheet versions are immutable.
  4. Historical reports always reference an exact sheet version.
  5. Fuzzy matching is not runtime authorization/data linkage.
  6. RLS is mandatory security, not UI convention.
  7. PostgreSQL is the source of truth for rights and business state.
  8. Storage contains files, PostgreSQL contains their metadata and permissions.
  9. Public pages are separated from private clinical application pages.
  10. Community copies/forks never mutate their source.
  11. Client identity matching never reveals another professional relationship without verification.
  12. Free-plan limits are counted server-side.
  13. Booking is server-authoritative and race-safe.
  14. Heavy jobs run asynchronously.
  15. Current code is migrated by adapters, not rewritten blindly.