system overview - BevvyTech/BrewskiDocs GitHub Wiki

🍺 Brewski Platform – System Overview

High-Level Architecture

  • Admin/ – React/Next admin UI delivered to brewery staff. Handles navigation, data entry, and integrates with the AI sidebar.
  • API/ – Fastify + PostgreSQL backend. Exposes REST endpoints, manages auth, orchestrates PDF generation, and hosts the AI WebSocket gateway.
  • Docs/ – Canonical product and integration documentation. Ingested into the AI knowledge base (see AI Knowledge Access).
  • Show/ – Marketing site (static/Next) for public-facing content.
  • Health/ – Static React dashboard served at health.brewskiapp.com that checks API/Admin/Shop/Show uptime.
  • Scripts/ – Automation helpers including CI tooling, DigitalOcean build emulation, and AI document ingestion.

Runtime environments are deployed via DigitalOcean App Platform. Infrastructure expects API and Admin services plus managed PostgreSQL and Spaces (S3-compatible) for document storage.

Core Domains

  • Authentication – Brewski IdP (email/password, Google OAuth), migrating to self-hosted Keycloak. Users belong to one or more Teams through user_team_roles.
  • Brew Operations – Beers, Batches, Fermentation readings, Packaging lots, Packaged units.
  • Order Management – Orders, line items, payments, delivery notes, signatures, generated documents (labels/invoices/delivery notes).
  • Clients & Settings – Client address books, team-level billing/payment configs, container defaults, locale/currency.
  • Documents/PDFs – Generated via Puppeteer/pdfmake; stored in DigitalOcean Spaces and tracked in documents.
  • Support & Notifications – Support tickets (support_tickets) now capture both brewery-facing and storefront-originated issues. Tickets may reference a brewery (team_id) and, when raised from the shop, a linked client (client_id) plus an origin_channel (admin, shop, automation). Messages, attachments, and credit tracking continue to live in support_messages, support_message_attachments, support_ticket_credit_periods, and support_ticket_credit_transactions, with activity fan-out via user_notifications.
    • Storefront clients hit the public support endpoints (GET/POST /public/support/tickets and /public/support/tickets/:id/messages) to list, view, and respond to issues. These routes enforce Bearer authentication and automatically scope queries to the authenticated client.
  • Deposits & Returns – Reusable keg movements are captured in container_returns, while deposit_transactions maintains the liability/credit ledger per team/client.
  • Marketplace & Off-Trade/offtrade endpoints handle brewery licensing, off-licence shop onboarding, and customer collection requests. Public submissions are rate limited and routed to team contacts; a daily summary script (tsx scripts/offtrade/daily-summary.ts) emails outstanding requests and marks notifications as sent.
  • Storefront Commerce – Consumer auth + carts (storefront_* tables) powering IndieBrewer checkout. The upsell catalogue (storefront_upsells) holds keg accessories and fittings, including optional coupler metadata so the shop can promote compatible hardware beside keg variants. See Docs/backend/shop-cart.md for API contracts.

Team Operating Modes

  • none – Default state for new teams with no behavioural overrides. The setup wizard flags this section as incomplete until a concrete mode is chosen.
  • strict – Inventory is managed exclusively through batches and packaging; manual adjustments and manual-only beers are blocked.
  • hybrid – Combines managed brewing workflows with manual adjustments so bought-in or contract products can coexist with brewed stock.
  • shop – Disables brewing flows entirely and relies on manual stock, intended for retail/taproom teams without production.

Integrations

  • OpenAI Responses API – Drives the AI assistant. Usage guidelines and payload examples live in Docs/OPENAI-API.md.
  • Google OAuth – For user sign-in.
  • DigitalOcean Spaces – Asset storage for PDFs and team logos.
  • (Planned) Keycloak – Will back unified auth once rolled out.
  • Breww / Kegstar Connectors – Brewery production and keg logistics syncs surfaced through the Admin “Integrations” surface. A dedicated persistence layer (team_integrations) holds connector state per team:
    • id (UUID primary key), team_id (FK), integration (enum key such as breww, kegstar), last_state (connected, disconnected, error, etc.).
    • config (jsonb) stores provider-specific secrets or mappings (e.g., Breww API key plus resolved business metadata).
    • connected_at (timestamp when the most recent successful auth completed) and last_seen_at (timestamp of the last health ping/webhook).
    • Standard created_at / updated_at audit columns.
    • Per-beer mappings live in beer_integrations (team_id, beer_id, integration, external beer/container identifiers, optional metadata JSON, timestamps) so multiple containers/providers can coexist alongside the core record.
  • Admin providers in src/features/integrations/ consume this record so card badges/buttons always reflect server truth; the API validates Breww credentials by calling https://breww.com/api/business-details/ during connect flows before persisting secrets.

AI Assistant Pipeline

  1. Frontend (Admin) opens a WebSocket to /ai/ws with team + user context.
  2. API enqueues messages to AiMessageQueueAiChatProcessor.
  3. Processor:
    • Builds OpenAI Responses request, including prior conversation, retrieved docs, and registered tools (navigate, create_beer, list_clients, etc.).
    • Streams deltas/tool calls back over the WebSocket.
  4. Tool Execution – Tool invocations are persisted to AiActionLog and executed via ai/tools/*. navigate outputs trigger frontend routing.
    • Image generation requests persist cost metadata in ai_image_usage and upload artefacts tracked via ai_generated_images, so badges can be revisited or re-applied later.
    • Action telemetry is exposed via GET /ai/logs (session owner, team member, or super-user only) so operators can review tool usage in the Admin debug panel.
  5. Knowledge Retrieval (RAG)retrieveRelevantDocuments pulls top docs from docs_chunks (ingested from Docs/).

Documentation Lookup

  • API endpoint: GET /ai/docs/search?q=...&limit=... (auth required). Returns curated snippets from Docs/ (backed by docs_chunks).
  • Assistant tool: search_docs hits the same query path and is the preferred way for the model to borrow product/integration guidance on demand.

AI Knowledge Access

  • Docs ingestion script: pnpm run ai:ingest (run from API/). It scans Docs/, chunks markdown, generates embeddings, and stores them in docs_sources / docs_chunks.
  • AI sessions query the embeddings for the active team (brewski-core) when search_docs is invoked or when auto-RAG triggers for documentation-heavy prompts.
  • When adding or updating docs, re-run the ingestion script so new material is available to the assistant.

Working with Documentation

  • All new documentation belongs under Docs/. Keep public/internal separation per guidelines.
  • Docs/OPENAI-API.md contains the authoritative reference for the OpenAI Responses API integration.
  • Docs/system-overview.md (this file) captures the platform map—update it when adding subsystems, new integrations, or significant architectural shifts.

Deployment & Ops Notes

  • Apply database schema updates via Prisma migrations (pnpm run db:migrate).
  • CI/local verification available through make verify (Docker-based).
  • Never modify API/storage/ contents—treated as immutable user data.
  • AI rate limiting defaults to 20 messages/minute; failures emit user-facing errors.
  • Marketplace payment mocks honour ADYEN_MOCK_DELAY_MS (default 0) to emulate provider latency during development.
  • Postcode lookups use api.postcodes.io by default; override via POSTCODES_IO_BASE_URL when proxying through internal networks.

Public Marketplace Endpoints

  • GET /public/teams – List storefront-enabled teams (used for public discovery).
  • GET /public/:identifier/beers – Team-specific catalogue for public viewing.
  • GET /public/beers/latest – Cross-team feed ordered by most recent batch with live stock counts; powers the shop “Latest beers” carousel.
  • GET /public/upsells – Platform-wide upsell accessories (optionally filtered by coupler type) surfaced on the shop home page and beer detail views.

Quick Checklist Before Shipping Changes

  • Schema change? → Add migration + regenerate prisma client.
  • New AI tool/provider? → Register in ai/tools, log actions, document env vars in .env.example, and update Docs/ai/agent-rules.md.
  • New documentation? → Place under Docs/, then run pnpm run ai:ingest.
  • Frontend copy changes? → Update localization bundles (en, de, es, fr, cs) and ensure navigation taxonomy is respected.