This commit is contained in:
Marek Lenczewski
2026-04-18 07:41:09 +02:00
parent 18fc50c75b
commit bf6f5456d6
63 changed files with 288 additions and 21 deletions

View File

@@ -1 +0,0 @@
{"sessionId":"e480a2be-e00b-4a51-8cfc-f525e281eccb","pid":17506,"acquiredAt":1776357371970}

View File

@@ -17,9 +17,9 @@ MEILI_KEY=shop-dev-master-key
# Ollama
OLLAMA_URL=http://localhost:11434
OLLAMA_CHAT_MODEL=llama3.1
OLLAMA_EMBED_MODEL=nomic-embed-text
OLLAMA_EMBED_DIM=768
OLLAMA_CHAT_MODEL=qwen2.5:7b
OLLAMA_EMBED_MODEL=bge-m3
OLLAMA_EMBED_DIM=1024
# Mail (Mailhog in dev)
SMTP_HOST=localhost

View File

@@ -18,7 +18,7 @@ Custom E-Commerce Shopsystem (B2C + B2B), weltweit einsetzbar, als verkaufbares
- **Frontend**: Vue 3 + Vite + TypeScript + Pinia + Vue Router — Tooling: `pnpm`, `eslint`, `prettier`, `vitest`. Nur Web, responsives Design.
**Zwei getrennte Vue-Apps mit separatem Build:** `shop` und `admin`.
- **Auth**: JWT (Access + Refresh), `argon2` für Passwort-Hashing
- **KI**: Ollama (lokal) via RAG — Standard-Modelle `llama3.1` (Chat) + `nomic-embed-text` (Embeddings), per Abstraktion austauschbar
- **KI**: Ollama (lokal) via RAG — Standard-Modelle `qwen2.5:7b` (Chat) + `bge-m3` (Embeddings), per Abstraktion austauschbar
- **Suche**: austauschbar per Such-Abstraktion (Standard Meilisearch)
- **DB-Migrationen**: Alembic (SQLAlchemy)
- **i18n**: DE + EN initial

View File

@@ -8,6 +8,7 @@ from core.db import SessionLocal
from apps.ai_core.ollama_client import get_llm
from apps.ai_core.tools import describe_for_prompt, get_tool, validate_args
from apps.catalog.models import Category, Product
from apps.orders.models import Order
SYSTEM_PROMPT = """You are an admin assistant for an e-commerce shop.
@@ -44,7 +45,11 @@ def _shop_state_snapshot() -> dict:
{"id": c.id, "slug": c.slug, "name_de": (c.name or {}).get("de", "")}
for c in db.query(Category).order_by(Category.id).all()
]
return {"products": products, "categories": categories}
orders = [
{"id": o.id, "status": o.status, "total": float(o.total)}
for o in db.query(Order).order_by(Order.id.desc()).limit(20).all()
]
return {"products": products, "categories": categories, "orders": orders}
finally:
db.close()
@@ -54,7 +59,7 @@ def build_plan(user_prompt: str) -> list[dict]:
state = _shop_state_snapshot()
user_msg = (
f"TOOL CATALOG (JSON):\n{json.dumps(tools, ensure_ascii=False)}\n\n"
f"SHOP STATE (current products & categories):\n{json.dumps(state, ensure_ascii=False)}\n\n"
f"SHOP STATE (current products, categories, recent orders):\n{json.dumps(state, ensure_ascii=False)}\n\n"
f"USER REQUEST:\n{user_prompt}\n\n"
"Reply with ONLY the JSON object described in the rules."
)

View File

@@ -216,10 +216,49 @@ CATEGORY_CREATE = ToolSpec(
)
# ---- orders.update_status -----------------------------------------
def _handler_order_status(args: dict, db: Session) -> dict:
from apps.orders.models import Order, OrderStatusHistory
order_id = int(args["id"])
o = db.get(Order, order_id)
if not o:
raise ValueError(f"Order {order_id} not found")
new_status = args["status"]
note = _coalesce(args.get("note"), "")
o.status = new_status
db.add(OrderStatusHistory(order_id=order_id, status=new_status, note=note))
db.commit()
event_bus.publish("order.status_changed", {"id": order_id, "status": new_status}, db=db)
return {"id": order_id, "status": new_status}
ORDER_STATUS = ToolSpec(
name="orders.update_status",
description="Change the status of an order (e.g. paid, packed, shipped, delivered, cancelled).",
args_schema={
"type": "object",
"required": ["id", "status"],
"properties": {
"id": {"type": "integer", "description": "Order ID"},
"status": {
"type": "string",
"description": "New status: paid, packed, shipped, delivered, cancelled",
},
"note": {"type": "string", "description": "Optional note"},
},
},
handler=_handler_order_status,
examples=[{"id": 1, "status": "shipped", "note": "DHL versendet"}],
)
# ---- registration -------------------------------------------------
ALL_TOOLS = [SETTINGS_UPDATE, PRODUCT_CREATE, PRODUCT_UPDATE, CATEGORY_CREATE]
ALL_TOOLS = [SETTINGS_UPDATE, PRODUCT_CREATE, PRODUCT_UPDATE, CATEGORY_CREATE, ORDER_STATUS]
def register_all() -> None:

View File

@@ -12,9 +12,9 @@ class Settings(BaseSettings):
MEILI_KEY: str = "shop-dev-master-key"
OLLAMA_URL: str = "http://localhost:11434"
OLLAMA_CHAT_MODEL: str = "llama3.1"
OLLAMA_EMBED_MODEL: str = "nomic-embed-text"
OLLAMA_EMBED_DIM: int = 768
OLLAMA_CHAT_MODEL: str = "qwen2.5:7b"
OLLAMA_EMBED_MODEL: str = "bge-m3"
OLLAMA_EMBED_DIM: int = 1024
SMTP_HOST: str = "localhost"
SMTP_PORT: int = 1025

View File

@@ -0,0 +1,28 @@
"""ai_core: change embedding dim from 768 to 1024 (bge-m3)
Revision ID: 0007_embed1024
Revises: 0006_ai_core
Create Date: 2026-04-17
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0007_embed1024"
down_revision: str | None = "0006_ai_core"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
# Drop and recreate with new dimension — truncating old embeddings is fine,
# reindex will rebuild them.
op.execute("DELETE FROM ai_documents")
op.execute("ALTER TABLE ai_documents ALTER COLUMN embedding TYPE vector(1024)")
def downgrade() -> None:
op.execute("DELETE FROM ai_documents")
op.execute("ALTER TABLE ai_documents ALTER COLUMN embedding TYPE vector(768)")

View File

@@ -23,7 +23,7 @@ Kommunikation zwischen Apps: **Events** (lose Kopplung) + **Dependency Injection
- **Datenbank**: PostgreSQL (Write-Store) + Redis (Read-Store)
- **Frontend**: Vue 3 + Vite + TypeScript + Pinia + Vue Router (Tooling: `pnpm`, `eslint`, `prettier`, `vitest`) — nur Web, responsives Design für Mobile.
**Zwei getrennte Vue-Apps mit eigenem Build:** `shop` (Kundensicht) und `admin`.
- **KI**: Lokale KI via **Ollama** (Standard-Modelle z.B. `llama3.1` für Chat, `nomic-embed-text` für Embeddings), RAG über Shop-/Produkt-/Einstellungs-Daten. Per Abstraktion austauschbar.
- **KI**: Lokale KI via **Ollama** (Standard-Modelle z.B. `qwen2.5:7b` für Chat, `bge-m3` für Embeddings), RAG über Shop-/Produkt-/Einstellungs-Daten. Per Abstraktion austauschbar.
- **Auth**: JWT (Access + Refresh), Passwort-Hashing via `argon2`
- **Migrationen**: Alembic (SQLAlchemy)
- **Suche**: austauschbar per Such-Abstraktion (Standard Meilisearch)

View File

@@ -0,0 +1,7 @@
- ai_admin
- admin chat turns prompts or JSON bulk input into proposal cards; AI never executes directly
- routes: POST /ai/admin/plan, POST /ai/admin/execute (admin-only)
- cards carry tool name, args, missing fields (editable in UI), preview text
- execute validates args against tool JSON-schema, runs the tool, writes an audit-log entry
- depends on: core, auth, catalog, orders, ai_core
- room for growth: more tools (mail templates, bulk import, category mutation), undo history, approval levels, per-tool permissions, dry-run mode

View File

@@ -0,0 +1,4 @@
- __init__.py (router, on_load)
- planner.py (prompt/JSON → list of action cards)
- tool_defs.py (JSON-schema per tool for argument validation)
- manifest.yaml

View File

@@ -0,0 +1,7 @@
- ai_core
- RAG infrastructure: LLMProvider interface + Ollama implementation, pgvector-backed document store, tool registry
- routes: POST /ai/query; admin: POST /ai/reindex, GET /ai/tools
- events subscribe: product.*, category.*, core.settings_updated (triggers embedding updates)
- depends on: core, catalog
- tools are proposals only — never executed directly; ai_admin turns them into confirmation cards
- room for growth: re-ranking, source citations, streaming responses, alternative LLM providers (OpenAI-compatible, Anthropic), chunking strategies, evaluation harness

View File

@@ -0,0 +1,7 @@
- __init__.py (router, on_load, tool registry)
- models.py (AiDocument with pgvector column)
- indexer.py (embed + upsert documents)
- ollama_client.py (LLMProvider implementation)
- tools.py (Tool base + registry)
- reindex.py (full rebuild of embeddings)
- manifest.yaml

View File

@@ -0,0 +1,6 @@
- ai_shop
- natural-language product search for customers; hybrid of embedding similarity and keyword boost
- routes: POST /ai/shop/search
- shop-aware system prompt (currency, user locale)
- depends on: core, catalog, ai_core
- room for growth: conversational follow-ups, session memory, filter parsing (price, size, color), spell correction, personalized ranking

View File

@@ -0,0 +1,2 @@
- __init__.py (router, on_load)
- manifest.yaml

View File

@@ -0,0 +1,7 @@
- auth
- registration, login, refresh, logout, password change, own profile
- routes: POST /register, /login, /refresh, /logout, /change-password; GET/PUT /me
- events emit: user.registered, user.logged_in
- depends on: core
- seeds: admin@example.com + demo customer
- room for growth: OAuth/SSO, API-tokens for third-party apps, 2FA, refresh-token rotation, impersonation, B2B company accounts

View File

@@ -0,0 +1,3 @@
- __init__.py (router, on_load)
- models.py (User, RefreshToken)
- manifest.yaml

View File

@@ -0,0 +1,5 @@
- cart
- per-user shopping cart, read/write items
- routes: GET /cart, POST /cart/items, PUT /cart/items/{id}, DELETE /cart/items/{id}
- depends on: core, auth, catalog
- room for growth: guest cart (session-based), merge guest cart into user cart on login, saved carts / wishlists, price snapshotting at add-time

View File

@@ -0,0 +1,3 @@
- __init__.py (router, on_load)
- models.py (Cart, CartItem)
- manifest.yaml

View File

@@ -0,0 +1,7 @@
- catalog
- products and categories, DE/EN i18n fields, image upload (local storage today)
- public routes (read from redis): GET /products, /products/{id}, /categories
- admin routes: POST/PUT/DELETE /admin/products, /admin/categories, image upload endpoint
- events emit: product.created, product.updated, product.deleted, category.created, category.updated, category.deleted
- depends on: core, auth
- room for growth: product variants, attributes/tags, SEO slugs, pluggable image storage (S3), stock reservations, price lists (B2B)

View File

@@ -0,0 +1,4 @@
- __init__.py (router, on_load)
- models.py (Product, Category)
- projector.py (redis sync on product/category events)
- manifest.yaml

View File

@@ -0,0 +1,6 @@
- checkout
- validate cart, take address + payment selection, produce order via payment provider
- routes: POST /checkout/preview, POST /checkout/confirm
- events emit: checkout.confirmed
- depends on: core, auth, catalog, cart, payment
- room for growth: coupon slot, shipping-method slot, tax plug-in point, address book, guest checkout, order-draft persistence

View File

@@ -0,0 +1,2 @@
- __init__.py (router, on_load)
- manifest.yaml

View File

@@ -0,0 +1,6 @@
- core-apps
- shipped with the system, required for a functional shop
- same mechanics as any other app (manifest.yaml, router, migrations, events, DI) — no special status in the loader
- typically declared `required: true` in manifest so they cannot be switched off
- distinct from custom-apps (optional / third-party, not shipped)
- cover: auth, product catalog, cart, checkout, payment, orders, mail, shipment (planned), plus the AI layer (ai_core, ai_shop, ai_admin)

View File

@@ -0,0 +1,6 @@
- mail
- MailProvider service registered via DI; SMTP implementation (Mailhog in dev, real SMTP in prod)
- Jinja2 templates with DE/EN i18n
- no public routes — used by other apps (e.g. orders) through DI
- depends on: core
- room for growth: outbound queue with retries, provider abstraction (SendGrid, Postmark, SES), richer transactional templates, bounce/complaint handling

View File

@@ -0,0 +1,2 @@
- __init__.py (on_load, MailProvider, SMTP implementation)
- manifest.yaml

View File

@@ -0,0 +1,7 @@
- orders
- customer-facing order list + detail, admin-side management with status transitions
- routes: GET /orders, GET /orders/{id}; admin: GET /admin/orders, PUT /admin/orders/{id}/status
- events subscribe: checkout.confirmed (create order, trigger confirmation mail)
- events emit: order.created, order.status_changed
- depends on: core, auth, catalog, mail
- room for growth: returns, partial fulfillment, cancellations, invoice PDFs, shipment tracking, export (CSV/ERP)

View File

@@ -0,0 +1,3 @@
- __init__.py (router, on_load, event subscribers)
- models.py (Order, OrderItem, OrderStatusHistory)
- manifest.yaml

View File

@@ -0,0 +1,5 @@
- payment
- PaymentProvider interface + DummyPayment (always "paid") for dev
- routes: GET /payment/methods
- depends on: core
- room for growth: real providers as separate apps (Stripe, Mollie, Klarna, PayPal), refund API, webhook handling, 3DS/SCA flow, split payments

View File

@@ -0,0 +1,2 @@
- __init__.py (router, on_load, DummyPayment provider)
- manifest.yaml

11
doc/core-apps/specs.md Normal file
View File

@@ -0,0 +1,11 @@
- auth
- catalog
- cart
- checkout
- payment
- orders
- mail
- ai_core
- ai_shop
- ai_admin
- shipment (planned, not implemented)

View File

@@ -0,0 +1,6 @@
- authentication
- "who are you?"
- password hashing with argon2
- JWT (15 min access) with refresh (30 days)
- identity dependencies (current_user_claims, optional_user, get_current_user_id, oauth2_scheme)
- room for growth: OAuth/SSO, API-tokens for third-party apps, 2FA, refresh-token rotation, impersonation

View File

@@ -0,0 +1 @@
- authentication.py

View File

@@ -0,0 +1,4 @@
- authorization
- "what are you allowed to do?"
- role checks (require_admin today)
- room for growth: require_role, require_permission, per-resource checks (owner-of), B2B approval workflows, per-app permissions for marketplace apps

View File

@@ -0,0 +1 @@
- authorization.py

5
doc/core/cache/features.md vendored Normal file
View File

@@ -0,0 +1,5 @@
- cache
- shared read-store / cache client (Redis today)
- backend writes, frontend reads
- apps keep the cache in sync via event handlers (projectors), not the core client
- room for growth: CacheProvider abstraction so the read-store becomes swappable

1
doc/core/cache/specs.md vendored Normal file
View File

@@ -0,0 +1 @@
- cache.py

View File

@@ -0,0 +1,2 @@
- config
- read .env into Settings object

1
doc/core/config/specs.md Normal file
View File

@@ -0,0 +1 @@
- config.py

4
doc/core/db/features.md Normal file
View File

@@ -0,0 +1,4 @@
- db
- base setup for ORM
- use SQLAlchemy
- provide get_db() dependency

1
doc/core/db/specs.md Normal file
View File

@@ -0,0 +1 @@
- db.py

3
doc/core/di/features.md Normal file
View File

@@ -0,0 +1,3 @@
- di
- global register for services
- no direct service import between apps

1
doc/core/di/specs.md Normal file
View File

@@ -0,0 +1 @@
- di.py

View File

@@ -0,0 +1,5 @@
- events
- apps can react on events
- apps can emit events
- events persist in db (audit/replay)
- allow wildcard subscribe (e.g. product.*)

1
doc/core/events/specs.md Normal file
View File

@@ -0,0 +1 @@
- events.py

View File

@@ -0,0 +1,2 @@
- i18n
- internationalisation helper for DE/EN text fields

1
doc/core/i18n/specs.md Normal file
View File

@@ -0,0 +1 @@
- i18n.py

View File

@@ -0,0 +1,6 @@
- loader
- load apps as python module
- discover apps/*/manifest.yaml
- order by app dependency (topological sort), circles not allowed
- check for conflicts
- mount each app router under /api/<app>

1
doc/core/loader/specs.md Normal file
View File

@@ -0,0 +1 @@
- loader.py

View File

@@ -0,0 +1,5 @@
- main
- entrypoint for backend
- build fastAPI
- run loader on lifespan startup
- expose /health and core settings routes

1
doc/core/main/specs.md Normal file
View File

@@ -0,0 +1 @@
- main.py

View File

@@ -0,0 +1,4 @@
- middleware
- central place to install FastAPI middlewares (install_middlewares(app))
- today: CORS (allowed origins from .env)
- room for growth: request-id, access logging, rate-limit, security headers (HSTS/CSP), compression

View File

@@ -0,0 +1 @@
- middleware.py

View File

@@ -0,0 +1,5 @@
- migrations
- orchestrator (migrations.py): discover per-app migration folders (apps/<name>/migrations/), configure alembic version_locations dynamically, coordinate multi-head merging
- startup check: fail fast if schema is not up to date
- migrations/ directory: alembic version store (today still holds all migrations centrally; per-app folders are the target state)
- use alembic

View File

@@ -0,0 +1,2 @@
- migrations.py
- migrations/ (Alembic version store)

View File

@@ -0,0 +1,2 @@
- seed
- demo data (admin, demo customer, categories, products)

1
doc/core/seed/specs.md Normal file
View File

@@ -0,0 +1 @@
- seed.py

View File

@@ -0,0 +1,6 @@
- settings
- key-value store for shop settings (runtime-changeable, e.g. shop_name, currency)
- postgres is source of truth
- mirrored to redis on write
- emits core.settings_updated event
- distinct from config (which only reads .env infrastructure values)

View File

@@ -0,0 +1 @@
- settings.py

View File

@@ -0,0 +1,7 @@
- custom-apps
- not shipped with the system; installed on top
- same mechanics as core-apps (manifest, router, migrations, events, DI) — loader does not distinguish
- typically declared required: false → can be switched off; can declare conflicts_with to prevent incompatible pairs
- two categories: optional apps (same team, shipped later) and third-party apps (marketplace, external developers)
- planned optional apps (from base.md): wishlist, reviews, coupons / discount engine, product recommendations, multi-vendor, subscriptions
- room for growth: app signing / verification, loader version-compat checks, per-app permission declarations, isolated migration namespaces, install/uninstall lifecycle hooks, marketplace registry

7
doc/custom-apps/specs.md Normal file
View File

@@ -0,0 +1,7 @@
- manifest.yaml (name, version, depends_on, conflicts_with, required: false, provides)
- __init__.py (router: APIRouter, optional on_load() for event handlers / DI registration)
- models.py (optional, with own SQLAlchemy Base subclass)
- projector.py (optional, redis read-store sync via event handlers)
- migrations/ (optional, alembic version files discovered by core migrations orchestrator)
- i18n/ (optional, DE/EN strings)
- frontend components under frontend/shop and/or frontend/admin (optional)

View File

@@ -2,4 +2,3 @@
- AI search: Filter products by search with AI
- AI admin helper: Execute commands by description
- Products, Orders, Users, Events, Settings
-

View File

@@ -1,15 +1,12 @@
- pyhton: backend language
- python: backend language
- fastAPI: Rest-API framework, Async, OpenAPI Docs
- Pydantic: Validate API
- SQLAlchemy: ORM
- Alembic: Migrations
- Postgres: Relational database
- pgvector: Vector columns for search, RAG search
- Redis: Cache for backend-frontend comminication
- Redis: Cache for backend-frontend communication
- Ollama: LLM for chat / planning and LLM for embeddings
- Vue: Frontend and admin framework with router and pinia as SPA
- Meilisearch: Search server with fulltext
- Mailhog: Dummy mailing
App-Loader, DI, Event-Bus, Settings, Redis-Projektor, Security, Seed
auth, catalog, cart, checkout, payment, orders, mail, ai_core, ai_shop, ai_admin, hello

View File

@@ -53,8 +53,8 @@ services:
entrypoint: ["/bin/sh", "-c"]
command: >
"sleep 5 &&
OLLAMA_HOST=ollama:11434 ollama pull llama3.1 &&
OLLAMA_HOST=ollama:11434 ollama pull nomic-embed-text &&
OLLAMA_HOST=ollama:11434 ollama pull qwen2.5:7b &&
OLLAMA_HOST=ollama:11434 ollama pull bge-m3 &&
echo 'Models ready'"
restart: "no"