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.comthat 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 anorigin_channel(admin,shop,automation). Messages, attachments, and credit tracking continue to live insupport_messages,support_message_attachments,support_ticket_credit_periods, andsupport_ticket_credit_transactions, with activity fan-out viauser_notifications.- Storefront clients hit the public support endpoints (
GET/POST /public/support/ticketsand/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.
- Storefront clients hit the public support endpoints (
- Deposits & Returns – Reusable keg movements are captured in
container_returns, whiledeposit_transactionsmaintains the liability/credit ledger per team/client. - Marketplace & Off-Trade –
/offtradeendpoints 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. SeeDocs/backend/shop-cart.mdfor 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 asbreww,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) andlast_seen_at(timestamp of the last health ping/webhook).- Standard
created_at/updated_ataudit 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 callinghttps://breww.com/api/business-details/during connect flows before persisting secrets.
AI Assistant Pipeline
- Frontend (Admin) opens a WebSocket to
/ai/wswith team + user context. - API enqueues messages to
AiMessageQueue→AiChatProcessor. - 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.
- Builds OpenAI Responses request, including prior conversation, retrieved docs, and registered tools (
- Tool Execution – Tool invocations are persisted to
AiActionLogand executed viaai/tools/*.navigateoutputs trigger frontend routing.- Image generation requests persist cost metadata in
ai_image_usageand upload artefacts tracked viaai_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.
- Image generation requests persist cost metadata in
- Knowledge Retrieval (RAG) –
retrieveRelevantDocumentspulls top docs fromdocs_chunks(ingested fromDocs/).
Documentation Lookup
- API endpoint:
GET /ai/docs/search?q=...&limit=...(auth required). Returns curated snippets fromDocs/(backed bydocs_chunks). - Assistant tool:
search_docshits 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 fromAPI/). It scansDocs/, chunks markdown, generates embeddings, and stores them indocs_sources/docs_chunks. - AI sessions query the embeddings for the active team (
brewski-core) whensearch_docsis 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.mdcontains 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(default0) to emulate provider latency during development. - Postcode lookups use
api.postcodes.ioby default; override viaPOSTCODES_IO_BASE_URLwhen 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 updateDocs/ai/agent-rules.md. - New documentation? → Place under
Docs/, then runpnpm run ai:ingest. - Frontend copy changes? → Update localization bundles (
en,de,es,fr,cs) and ensure navigation taxonomy is respected.