Backend Architecture¶
The backend is built with Django 6.1.2, Django REST Framework 3.18.3 and Celery 5.6.3
on Python 3.14. Dependencies are managed with pip against requirements.txt
(pinned versions).
Project Structure¶
backend/
├── apps/
│ ├── agent_api/ # Read-only API for the Freeze AI agent (/api/agent/v1/), keys, audit log, quote-assistant drafts
│ ├── analytics/ # Admin analytics (SQL aggregates), website figures (PostHog/Sentry), weekly snapshot
│ ├── clipart/ # SVG clipart library (figures, optional editable text) for the designer
│ ├── core/ # Site settings, CMS pages, audit log, backups, health, Discord + ntfy, healthchecks.io pings, email, postcode, Google reviews
│ ├── designs/ # Custom designs, review flow, shop collection, templates, fonts, text colours, guest retention
│ ├── informer/ # Informer bookkeeping link: paid order → sales invoice (off by default)
│ ├── invoices/ # Invoice PDF generation, gap-free numbering
│ ├── orders/ # Cart, team orders (OrderGroup), checkout, orders, production board, cart reminders, review requests
│ ├── payments/ # Mollie payments, webhook, refunds, payment audit log
│ ├── personalization/ # SVG colour/text personalisation templates per product
│ ├── pricing/ # Discount codes, volume discounts, offers, rules, decoration methods
│ ├── products/ # Catalog, variants, colour images, print zones, Google Shopping feed, catalog manager
│ ├── quotes/ # Customer quote (offerte) requests, gap-free quote numbering
│ └── users/ # Profiles, addresses, wishlist, newsletter, MFA enforcement, GDPR
├── config/
│ ├── settings.py # Django settings
│ ├── urls.py # URL routing (routers, allauth, payments, schema)
│ ├── celery.py # Celery app + beat schedule
│ └── checks.py # Deploy checks (run by deploy-rolling.sh on production)
├── fixtures/seed/ # Git-tracked seed data
├── media/ # Uploaded files (dev only; DO Spaces when USE_SPACES=True)
├── static/ # Static assets
└── templates/ # Django templates (emails, invoice/quote/report PDFs)
Each app follows the same layout: models.py, serializers.py, views.py
(public API), admin_views.py + admin_serializers.py (staff API under
/api/admin/), services.py (business logic), signals.py, tasks.py (Celery)
and tests/.
App Responsibilities¶
Products App¶
ProductwithCategory(MPTT tree, plusadditional_categories),Brand,Color(withColorCategoryand optionalsecondary_colorfor two-colour products),SizeType/Size,ProductVariant(colour × size, stock, cost)ProductColorImage: 4 view images per colour with legacy print-area boxes and 12 responsive WebP variants (generated by Celery via signals)ProductPrintZone+ProductViewScale: multi-zone print areas per view with cm dimensions, decoration method, fixed price or surchargeProductDetailImage,TwoColorCombination, size charts, cost price (admin only)- One definition of a sellable variant,
ProductVariant.objects.sellable()/is_sellable(variant and colour active), used by the product page, lists, filters,/api/variants/and the cart; a colour set inactive in the admin takes its variants out of the shop - New products are created inactive by the admin wizard and the simple form; "Activeren" lists what is still missing (price, variants, photo, print areas)
duplicate.py(adminPOST /api/admin/products/<id>/duplicate/, feedback #67): an inactive copy with the basic data, prices and print zones, without images, variants, colours and sizesProduct.is_listed(products/0037): off = only reachable by its direct link, not in lists, search, categories, sitemap or feed; used for the synthetics test product (synthetic.py,manage.py ensure_synthetic_product)- Photo check (
photo_checks.py): pixel sizes stored per photo (products/0038, measured on upload and once withmanage.py meet_productfotos) give red/orange/grey warnings in the admin; the shop hides an active colour without a front photo - Google Shopping product feed (
/api/feeds/google-shopping.xml,feeds.py, cached one hour in Redis) - Catalog Manager GUI and seed-data import/export (Django admin, Celery tasks);
manage.py vul_categorietekstenfills empty category SEO/intro/FAQ texts fromcategorieteksten.json(never overwrites,--dry-run)
Designs App¶
CustomDesign: Fabric.js JSON and preview image per view (front/back/left/right), print file,DesignCostMixinfor the legacy text/image/colour cost- Review flow:
draft → pending_review → approved | rejected, plusfinalized; customerrequest_approval, staffapprove/reject(see Design Review guide) - Shop collection: a staff design published with
publish-to-collectionbecomes a ready-made article (is_collection_item,collection_slug, served read-only at/api/collection/) DesignTemplate,TextColor(price modifiers),Font(uploaded + Google fonts), image upload with vector rasterisation and PNG preview validationDesignRenderServicerenders previews and print files- The admin design detail (
AdminDesignDetailSerializer) addsprint_views(design JSON and px-per-cm per side), from which the admin downloads the design as a loose PNG or SVG production file at true size (feedback #72) - Guests: designs are keyed by
session_key; a guest who requests a design check gives aguest_email(migrationdesigns/0012) for the review mails. Anonymous creation is throttled per IP (design_create_hour30/hour,design_create_day100/day);retention.pydeletes guest designs without an order after 90 days and wipesguest_emailafter 12 months (daily Celery tasks)
Orders App¶
ShoppingCart/CartItemfor users and anonymous sessions, discount code application, cart reminder opt-out; the cart serializer flags a personalised line whose template changed (personalization_changed), which checkout and quotes refuse- Team orders (
team_order_enabled):OrderGroup(team name, product, colour, optionalbase_design, JSONroster) with oneCartItem/OrderItem/QuoteItemof 1 piece per roster row. Cart APIPOST /api/cart/groups/,PATCH/DELETE /api/cart/groups/<id>/,POST /api/cart/group-price/;team_groups.pyvalidates the roster (max 200 rows, no template products, stock when enabled) and the print is priced once over the whole group - Checkout (
OrderViewSet.checkout): scoped throttle, cart row lock, idempotency key (checkout_idempotency_key/checkout_orderon the cart), order + Mollie payment in one transaction, pickup or shipping fulfilment, terms acceptance timestamps OrderService: order creation with pricing snapshots, team groups carried over from the cart,OrderItemPrintZonesnapshots, stock validation/decrement, artwork-review flag (needs_attention), status transition validationOrderMessage(staff ↔ customer thread),ManualProductionItem(off-webshop jobs on the production board), production statuses perOrderItem- Product slip for the embroidery studio (
production_slip.py, templateorders/production_slip.html): WeasyPrint PDF of the lines with a print, no prices, adminGET /api/admin/orders/<id>/production-slip/; 404 without such a line. Each line shows the product in the ordered colour and the design preview per side; a personalised line gets its preview drawn from the snapshot byapps.personalization.preview_svg - Status emails via
signals.py;set_statusandbulk-statustakenotify_customer(defaulttrue), and withfalseno status, shipping or cancellation email goes out (feedback #71). When the last item of an order in production is set to shipped on the production board, the order goes toshipped(pickup:ready_for_pickup) without a customer email - Post-payment work via Celery tasks
Payments App¶
PaymentServicewrapsmollie-api-python(payments, issuers, refunds; E2E stub whenE2E_TESTING=True)- Webhook handler fetches the real status from Mollie, verifies amount/currency, locks the order and applies the transition; 503 on transient Mollie errors so Mollie retries
Refundlifecycle,calculate_max_refundable,process_order_refund; failed/canceled refunds flip the order back fromrefundedtopaidPaymentAuditLogwith before/after state and Mollie response snapshots
Invoices App¶
- Sequential invoice numbering
INV-YYYY-NNNNNviaInvoiceCounter(per year, gap-free, row-locked) - PDF generation with WeasyPrint, done in Celery (
generate_invoice_and_email_task) after the paid transition, so the webhook never renders a PDF - One invoice per order (
OneToOneField); customer download at/api/invoices/download/, admin regeneration under/api/admin/invoices/
Pricing App¶
DiscountCode(percentage / fixed_amount / free_shipping, usage limits, product and category scope),VolumeDiscount+ tiers,SpecialOffer,PricingRuleDecorationMethod+DecorationAreaTier: setup fees, per-colour/location fees, area tiers and px-per-cm;pricing/decoration.pyprices a design per print zone (design_zone_unit_cost) in the 600 × 800 reference frame of the zones (ZONE_REF_W/ZONE_REF_H): object coordinates are scaled from the customer'scanvasSizeand readoriginX/originY, so phone and laptop give the same priceTeamDiscountis gone (migrationpricing/0003); team pricing is the group price- Admin pricing and design simulators (
/api/admin/pricing/simulate/,/api/admin/pricing/design-simulate/)
Quotes App¶
Quote+QuoteItemcapture a request for a custom/bulk offer from the cart;QuoteCounterissues gap-free numbersOFF-YYYY-NNNNNper year- Status flow:
requested → sent → accepted | rejected | expired → converted | cancelled - Customer actions: request, accept, convert (creates an order and starts payment), download PDF; staff: update items, send, reject
- Quote assistant: a new request asks the Freeze AI agent for a draft
(
agent_api/review.py, Celeryagent.request_quote_review); the draft is anAgentSuggestion, shown in the admin viasuggestion/suggestion-feedback
Agent API App¶
- Read-only API for the Freeze AI agent under
/api/agent/v1/(products, categories, decoration methods, pages, price estimate, open quotes) plusPOST suggestions/ - Three layers: nginx allows only the VM's tailnet IP, Django checks
AGENT_API_ALLOWED_IPS, and anApi-Keywith scopes (AgentApiKey, SHA-256 only); every call is logged (AgentApiCall). See the agent API runbook
Users App¶
UserProfile(theme, language, default addresses, admin notes),ShippingAddress(address book),WishlistItemNewsletterSubscriptionwith double opt-in and sync to the Resend contacts list (newsletter.py,POST /contacts, optional segment viaRESEND_SEGMENT_ID)- Registration/me/profile/password/preferences endpoints under
/api/auth/; login, signup, MFA and password reset run through django-allauth headless (/_allauth/), withStaffMFAEnforcementMiddlewarefor staff - GDPR export and account deletion; admin customer and staff management
Core App¶
SiteSettingssingleton (cached): pricing defaults, VAT, shipping, store and footer data (incl.footer_whatsapp_number, which replaced the LinkedIn column incore/0025), and the feature switchesstock_management_enabled,team_order_enabled,all_payment_methods_enabled+payment_methods_offered(Mollie methods),cart_reminder_enabled,review_request_enabled,newsletter_enabled,whatsapp_buttons_enabled(core/0026),catalog_color_swatches_enabled(core/0029),shop_order_email_enabled+shop_order_email_address(core/0027,shop_order_email_enabled_sinceincore/0028),informer_mode(+ ledger numbers and payment condition),homepage_collection_categoryPage(CMS pages with CKEditor 5),AdminAuditLog(before/after state),BackupRecord- Health checks (
/api/health/,/api/health/detailed/), admin health dashboard, setup-readiness checklist, postcode lookup, Google reviews block - Services: backup (S3-compatible, encryption, verification, restore test), payment
monitor, disk monitor, Discord notifications (forwarded to ntfy by
NotifyService), healthchecks.io pings (services/healthchecks.py), email environment guard
Personalization App¶
PersonalizationTemplate(one per product): cleaned SVG with colour roles, allowed fill/border colours, optional text group with rules (digits_exact,letters_max,text_max) and font, andsmall_texts(migrationpersonalization/0002): extra short texts the customer fills in or leaves empty (feedback #70)PersonalizationColorpalette; the chosen personalisation is snapshotted onOrderItem.personalizationpreview_svg.pydraws a line's preview from that snapshot (fontTools for the text outline) for the product slip
Clipart App¶
ClipartCategoryandClipartItem(SVG + thumbnail, tags) for the designer's Figuren tab; public read-only API plus admin CRUDClipartItem.editable_text_index(migrationclipart/0002) marks which<text>in the SVG the customer may change; single-colour figures can be recoloured in the designer
Informer App¶
- Bookkeeping link with Informer (feedback #57), off by default: with
SiteSettings.informer_mode = 'live'(andINFORMER_API_KEY,INFORMER_SECRET_KEY,INFORMER_ALLOW_WRITES=Trueon production) a paid order becomes a sales invoice with the customer as its own relation;previewonly reads InformerBookingper order: status (sending | retrying | sent | preview | failed | skipped), attempts, Informer ids, payment status (informer_paid,informer_open,informer_concept)- Tasks
informer.send_order(after payment),informer.sweep(retries, every 5 min) andinformer.refresh_payments(hourly); admin page Boekhouding under Financiën (/api/admin/informer/*) and per orderinformer-send,informer-refresh,informer-handled
Analytics App¶
- Admin dashboard analytics computed with SQL aggregates: revenue, orders, top products, category/brand breakdowns, margin, customer value, low stock, design and quote funnels, discounts/refunds, CSV/Excel export and a PDF report
- Website figures from the PostHog and Sentry APIs (
website.py, cached one hour) andWebsiteWeekSnapshotstored every Monday for the 12-week trend lines;manage.py website_weekcijfers_statuslists the latest rows read-only (for the Monday check viafreeze-ro),website_weekcijfers_inlezenloads a week
API Design¶
All APIs follow REST conventions on DRF routers (/api/<resource>/), with extra
@action routes for workflows (/api/orders/checkout/,
/api/designs/{id}/request_approval/, /api/quotes/{id}/convert/). The staff API
lives under /api/admin/ and is served by Admin*ViewSet classes in each app's
admin_views.py, protected by staff + MFA permissions and written to
AdminAuditLog.
Serializers¶
class ProductSerializer(serializers.ModelSerializer):
category = CategorySerializer()
color_variants = ColorVariantSerializer(many=True)
class Meta:
model = Product
fields = ['id', 'name', 'slug', 'category', ...] # explicit list: cost_price is admin-only
ViewSets¶
class ProductViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Product.objects.filter(is_active=True)
serializer_class = ProductSerializer
filterset_class = ProductFilter
search_fields = ['name', 'description', 'sku']
Throttling¶
API_THROTTLE_RATES in settings.py: anon 5000/hour, user 10000/hour,
uploads 20/hour, checkout 5/minute, payment_retry 3/minute,
payment_webhook 120/minute, resend_verification 5/hour, newsletter 10/hour,
design_create_hour 30/hour + design_create_day 100/day (anonymous POST
/api/designs/ only, FixedScopeRateThrottle). Client IPs come from the single
trusted nginx hop (TRUSTED_PROXY_COUNT = 1). The agent API throttles per key
(AGENT_API_THROTTLE_RATE, default 600/hour).
Background Tasks¶
Celery runs with a Redis broker (acks_late for the post-payment tasks, so they are
idempotent and guarded by payment_email_sent_at / admin_notified_at /
shop_email_sent_at).
- After payment (enqueued by
orders/signals.pyon thepaidtransition):notify_admin_paid_order_task,send_shop_order_email_task(shop mail "Nieuwe bestelling", behindshop_order_email_enabled),generate_invoice_and_email_task(WeasyPrint PDF - paid mail),
generate_print_files_for_order_task; the invoice task then enqueuesinformer.send_orderwheninformer_modeis notoff - Stock problems after payment:
notify_admin_stock_problem_task(Discord) - Backups: hourly dump to an S3-compatible bucket with checksums, retention cleanup, verification, monthly restore test, daily summary
- Monitoring: disk space, payment anomaly detection, daily payment summary,
recovery of paid orders missing invoice/mail/print files, healthchecks.io pings
(
monitoring.healthcheck_ping,monitoring.ntfy_public_heartbeat) - Customer journeys: abandoned-cart reminders, review requests after delivery
(both behind
SiteSettingsswitches), newsletter sync to Resend contacts - Bookkeeping: Informer retries (
informer.sweep) and payment status refresh - Retention: guest designs without an order after 90 days, guest emails after
12 months (
designs.purge_guest_designs,designs.purge_guest_emails) - Cleanup: guest carts without an order after 30 days, then expired sessions
(
cart.purge_stale) - Quote assistant:
agent.request_quote_reviewasks the Freeze AI agent for a draft after a new quote request (up to 3 retries; off withoutFREEZE_AI_AGENT_URL) - Media: WebP variants for product images (
convert_image_to_webp, via signals) - Catalog: seed data export/import (Catalog Manager GUI)
- Analytics: weekly website snapshot
Most transactional emails (order confirmation, status changes, design review, quotes)
are sent synchronously via Resend (django-anymail) from transaction.on_commit
hooks; only the paid mail with the invoice PDF goes through Celery.
Celery Beat Schedule¶
Defined in backend/config/celery.py; times are Dutch time (CELERY_TIMEZONE =
TIME_ZONE = "Europe/Amsterdam"). Beat touches a heartbeat file every tick; the
container healthcheck fails after 600 s and a cron job restarts an unhealthy beat.
| Task | Schedule | Purpose |
|---|---|---|
backup.daily_backup |
Hourly at :00 | Database backup to the backup bucket |
backup.cleanup_old_backups |
Daily 03:00 | Retention (24 hourly, 7 daily, 4 weekly) |
backup.verify_latest_backup |
Daily 04:00 | Backup integrity check |
backup.test_restore |
Monthly (1st, 05:00) | Full restore test |
backup.daily_summary |
Daily 06:00 | Backup status summary (Discord) |
monitoring.check_disk_space |
Hourly at :30 | Disk usage alerts |
monitoring.healthcheck_ping |
Every 5 min | Ping healthchecks.io: worker, beat and database alive (no-op without HEALTHCHECK_PING_URL) |
monitoring.ntfy_public_heartbeat |
Every 10 min (:02) | Silent ntfy message through the public URL, then a healthchecks.io ping (no-op without NTFY_HEARTBEAT_PING_URL) |
monitoring.check_payment_anomalies |
Every 15 min | Payment anomaly detection |
informer.sweep |
Every 5 min | Retry Informer bookings that are due and pick up paid orders left behind (no-op when informer_mode is off) |
informer.refresh_payments |
Hourly at :25 | Read the payment status of sent invoices from Informer |
monitoring.recover_incomplete_paid_orders |
Hourly at :45 | Re-schedule missing invoice/mail/print files and shop mail on paid orders |
monitoring.daily_payment_summary |
Daily 07:00 | Heartbeat for the payments Discord channel |
cart.send_reminders |
Hourly at :20 | Abandoned-cart email (if cart_reminder_enabled) |
reviews.send_requests |
Daily 08:15 | Review request after delivery (if review_request_enabled) |
newsletter.sync_pending |
Hourly at :40 | Push confirmed subscribers to the Resend contacts list |
designs.purge_guest_emails |
Daily 02:10 | Wipe guest_email of designs without an order after 12 months |
designs.purge_guest_designs |
Daily 02:20 | Delete guest designs without an order after 90 days |
cart.purge_stale |
Daily 02:30 | Delete guest carts without an order not updated for 30 days, then clearsessions |
analytics.save_website_week |
Monday 06:00 | Store last week's website figures (WebsiteWeekSnapshot) |
Management commands¶
Besides Django's own: import_seed_data / export_seed_data / update_seed_data
(catalog), backup_database / restore_database / verify_backup / backup_health
(backups, decrypting an encrypted dump themselves), safe_migrate (the production
gate in deploy-rolling.sh) and check_migrations (CI), convert_images_webp,
sanitize_clipart_svgs, report_zone_cm_conflicts, meet_productfotos (photo sizes for the
photo check, --droog, --alles), ensure_synthetic_product (the synthetics test product),
create_agent_key (agent API key, shown once), vul_categorieteksten
(one-off category texts, --dry-run), website_weekcijfers_status /
website_weekcijfers_inlezen (weekly snapshot), list_magic_links,
create_staff_user / setup_staff_2fa / generate_backup_codes, and the
ensure_e2e_* / seed_e2e_extras / seed_staging_data commands for test data.