Skip to content

Nevvyboi/DataBrew

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

98 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

DataBrew

DataBrew 🍺

Turn raw data into strategic foresight.
A multi-tenant B2B analytics platform that ingests messy POS, delivery, and spreadsheet exports, then maps, cleans, and transforms them into clean, client-facing dashboards. Automatically.

Django Python PostgreSQL Redis HTMX Docker License: MIT CI

πŸ‡ΏπŸ‡¦ Built for the South African market Β Β·Β  πŸ’° ZAR Β Β·Β  🧾 15% VAT Β Β·Β  πŸ•‘ Africa/Johannesburg

DataBrew landing page


πŸ“– Table of Contents


✨ What is DataBrew?

Multi-branch businesses (restaurant groups, franchises, distributors) drown in data fragments. Every POS system, delivery app, and location exports its own messy CSV/Excel/PDF with its own product names and column layouts. DataBrew unifies all of it.

It ingests those raw exports, fuzzy-matches every product name to a canonical master catalog, runs the data through a three-stage ETL pipeline, and serves clean, branded, self-service dashboards to each client, with full multi-tenant isolation, role-based access, and a REST API.

  πŸ“₯ Raw POS/delivery exports   ->   🧠 ML product mapping   ->   πŸ“Š Clean client dashboards
🏒 Multi-tenant Every row scoped to a tenant; middleware + ORM-level isolation prevents cross-tenant leaks
🧠 ML auto-mapping Seed-token + fuzzy matching maps raw product names to a master catalog with manual override
βš™οΈ 3-stage ETL RawRecord -> StagingRecord -> AnalyticsRecord, materialized into a star schema
πŸ“Š Self-service BI Branded client portal with KPIs, trends, maps, drill-downs, and exports
πŸ‘₯ 6 roles Superadmin, data engineer, mapper, delivery manager, client admin, client viewer
πŸ”Œ REST API Tenant-scoped, throttled DRF endpoints for programmatic access

🎬 Feature Tour

πŸ“Š Client Portal & Dashboards

Each client logs into their own branded portal (logo, colours, tagline) and gets a self-service analytics workspace. No spreadsheets required.

Dashboard, Overview tab: headline KPIs (revenue, units, margin, avg price), a revenue trend chart, top products, and a revenue-by-category breakdown.

Client dashboard overview

πŸ“ Locations
Interactive Leaflet map of every branch with per-store revenue & volume.
Locations map
πŸ—‚οΈ Data Sources
Every feed powering a tenant, with freshness and quality at a glance.
Client sources
πŸ—‚οΈ Catalog
Browse the product hierarchy and categories per tenant.
Catalog
πŸ“€ Exports
Saved export templates and downloadable reports (incl. PDF with tenant logo).
Exports

πŸ”„ Data Pipeline: Ingest, Map, Publish

The engine room. Raw files become trustworthy analytics through a reviewable, reversible pipeline.

πŸ“₯ Imports. Upload CSV/Excel/PDF, auto-detect columns, map them to standard fields, review duplicates & quality, then approve. SHA-256 hashing catches duplicate files, and a quality score grades each import.

Imports manager

🧩 Mapping. Every raw product name is matched to a canonical MasterProduct. The mapping workspace shows coverage per source, pending suggestions, and unmapped items. Mapping is seed-token based, so "Castle Lager 340ml" mapped once covers every branch and every future import.

Product mapping

⚑ Speed Mapper. A keyboard-first triage UI for blitzing through unmapped products: approve, reject, or skip without touching the mouse, with live progress and an undo trail.

Speed Mapper


🚚 Operations & Delivery

The internal cockpit for the team running data delivery across all clients.

Delivery Dashboard. A 6-month grid of which client received data when, freshness indicators, recent activity, and an at-a-glance data-quality overview.

Delivery dashboard

πŸ‘₯ Clients
Every tenant, paginated, with status & source counts.
Clients
πŸ—“οΈ Delivery Overview
Per-source mapping stats and refresh controls.
Delivery overview

♻️ Analytics refresh runs as a tracked async task with six phases (starting -> deleting -> building -> curating -> snapshots -> finalizing) and live progress polling.


πŸ› οΈ System, Admin & Analytics

🧠 ML Model Stats. A live view of the fuzzy-matching engine: the matching pipeline (barcode -> cross-tenant -> fuzzy name -> size/unit -> brand -> score), signal weights, engine configuration, and learning/acceptance metrics.

ML model stats

πŸ—„οΈ Database Schema Explorer. Live introspection of every model across all apps, with row counts, relationships, and clickable foreign keys. (42 tables Β· 94 relationships in the demo dataset.)

Database schema explorer

πŸ“ˆ System Analytics. Platform-wide traffic, import volume, mapping coverage, and client breakdown.

System analytics

πŸ‘€ Users & Roles
Users
βš™οΈ System Settings
System settings
πŸ“ Audit Log
Audit log
πŸ”” Notifications
Notifications
πŸ” Secure Login
Login
βš–οΈ Legal / Docs
Legal

⚑ Tech Stack

Layer Technology
🐍 Backend Django 5.1.4, Python 3.12, Django REST Framework
🐘 Database PostgreSQL 16 (star schema for analytics)
πŸ”΄ Cache / Queue Redis 7 (with DB-cache fallback)
πŸ–₯️ Frontend HTMX, Alpine.js, Chart.js, Leaflet (server-rendered, no SPA build step)
πŸ“¦ Data pandas, numpy, openpyxl, pdfplumber, RapidFuzz (fuzzy matching)
πŸ” Security Argon2, django-axes (brute-force lockout), PyJWT
🐳 Deployment Docker, Docker Compose, Nginx, Gunicorn, WhiteNoise, Let's Encrypt
πŸ“‘ Monitoring Sentry, custom traffic analytics

πŸ’‘ All front-end libraries are vendored locally under static/, so there is no runtime CDN dependency: dashboards render reliably offline and aren't subject to CDN or SRI drift.


πŸ—οΈ Architecture

πŸ”„ Data Flow

πŸ“₯ CSV / XLSX / PDF upload
        |
   πŸ“‹ RawRecord ............ raw rows stored as-is, file SHA-256 hashed
        |
   πŸ”— ColumnMap ............ maps raw columns to standard fields
        |
   βœ… StagingRecord ........ cleaned, validated, VAT-resolved
        |
   🧠 MappingRule + ML ..... fuzzy / seed-token match to MasterProduct catalog
        |
   πŸ“Š AnalyticsRecord ...... fully mapped, analytics-ready
        |
   ⭐ FactSale + Dimensions  star schema powering every dashboard

🏒 Multi-Tenancy

Every model carries a tenant ForeignKey. TenantMiddleware scopes each request and TenantManager guarantees queries never leak across tenants, enforced at the middleware, view, and ORM layers.

⭐ Star Schema

Table Role
FactSale πŸ“Š Central fact, one row per product Γ— store Γ— date Γ— source
DimDate πŸ“… Date dimension: day, week, month, quarter, year
DimProduct 🏷️ Product dimension, linked to the MasterProduct catalog
DimStore πŸ“ Store/location dimension, linked to MappedLocation

πŸš€ Quick Start (Local)

Prerequisites: Python 3.12, PostgreSQL 16, and libmagic (file-type detection: brew install libmagic on macOS, apt install libmagic1 on Debian/Ubuntu). Redis is optional; it falls back to the database cache.

# 1. Clone & create a virtualenv
git clone https://github.com/Nevvyboi/DataBrew.git
cd DataBrew
python3.12 -m venv venv && source venv/bin/activate    # Windows: venv\Scripts\activate
pip install -r requirements.txt

# 2. Create the database + an owning user
createuser databrew_user --pwprompt              # set a password when prompted
createdb -O databrew_user databrew               # -O makes the new user the DB owner

# 3. Configure environment
cp .env.example .env
#  - set DB_USER / DB_PASSWORD to match step 2
#  - generate a SECRET_KEY:  python -c "import secrets; print(secrets.token_urlsafe(50))"
#  - leave REDIS_URL blank to use the database cache fallback (no Redis needed)

# 4. Migrate & seed a full demo tenant (~56k sales rows, 67 products, 8 locations)
python manage.py migrate
python manage.py createcachetable          # backs the DB cache when REDIS_URL is blank
python manage.py generate_sample_data

# 5. Run
python manage.py runserver

Visit http://127.0.0.1:8000 and sign in to the seeded demo tenant:

Role Email Password
πŸ‘€ Client Admin [email protected] demo1234

Create an internal superadmin to explore the operations, mapping, and system areas:

python manage.py createsuperuser

🧰 Set DEBUG_TOOLBAR=0 in your environment to hide the Django Debug Toolbar (e.g. for clean screenshots).


πŸ§ͺ Quality & Tests

python manage.py test     # tenant isolation, ML matching, VAT, ETL, API
ruff check .              # lint (config in ruff.toml)

The test suite focuses on the load-bearing logic: multi-tenant data isolation (the ORM TenantManager plus the DRF API), the fuzzy product-matching engine, VAT breakdowns, seed-token generation, the ETL transitions, and the role-permission matrix. Every push and PR runs lint, a migrations check, and the full suite with coverage via GitHub Actions.


πŸ”Œ REST API

Tenant-scoped, authenticated, and rate-throttled (Django REST Framework). All endpoints live under /api/v1/.

Method Endpoint Description
GET /api/v1/snapshots/ Pre-computed period snapshots (revenue/volume/cost)
GET /api/v1/products/ Master product catalog (filter by brand)
GET /api/v1/locations/ Mapped store locations
GET /api/v1/sources/ Data sources
GET /api/v1/kpis/?start=YYYY-MM-DD&end=YYYY-MM-DD Pre-computed KPIs for a date range

Auth: IsAuthenticated + IsTenantMember (responses are automatically filtered to the caller's tenant).


πŸ“ Project Structure

DataBrew/
β”œβ”€β”€ apps/
β”‚   β”œβ”€β”€ accounts/       πŸ‘€ Users, Tenants, Roles, audit logging, onboarding wizard
β”‚   β”œβ”€β”€ ingestion/      πŸ“₯ DataSource, ImportJob, RawRecord, ColumnMap (upload & parse)
β”‚   β”œβ”€β”€ mapping/        🧩 MasterProduct catalog, MappingRule, ML matching, locations
β”‚   β”œβ”€β”€ pipeline/       βš™οΈ StagingRecord, AnalyticsRecord, ImportSnapshot (ETL)
β”‚   β”œβ”€β”€ dashboards/     πŸ“Š Star schema, client portal, KPIs, shared dashboards
β”‚   β”œβ”€β”€ delivery/       🚚 Operations dashboard, async RefreshTask worker
β”‚   β”œβ”€β”€ notifications/  πŸ”” AlertRule, Notification, dispatch engine
β”‚   β”œβ”€β”€ operations/     πŸ› οΈ System settings, schema viewer, ML stats, health
β”‚   β”œβ”€β”€ analytics/      πŸ“ˆ Traffic & performance analytics
β”‚   β”œβ”€β”€ api/            πŸ”Œ REST API (DRF): serializers, permissions, throttling
β”‚   β”œβ”€β”€ sharing/        🀝 Cross-tenant shared data-source access
β”‚   └── core/           🧱 Shared utilities: image serving, middleware, template tags
β”œβ”€β”€ config/             βš™οΈ Settings (base/development/production), URLs, WSGI
β”œβ”€β”€ templates/          🎨 Server-rendered HTML (HTMX partials, email templates)
β”œβ”€β”€ static/             πŸ–ΌοΈ CSS, JS (vendored libs), brand assets, screenshots
β”œβ”€β”€ locale/             🌍 Translations (French, Italian)
β”œβ”€β”€ nginx/              🌐 Reverse proxy: SSL, rate limiting, security headers
β”œβ”€β”€ scripts/            πŸš€ deploy.sh Β· update.sh Β· backup.sh
β”œβ”€β”€ sample_data/        πŸ“‹ Demo CSVs for testing imports
β”œβ”€β”€ Dockerfile          🐳 Multi-stage production image
└── docker-compose*.yml 🐳 Local & production stacks

πŸ”’ Security

Feature Detail
πŸ” Passwords Argon2 hashing, 10+ char minimum, common-password rejection
🚫 Brute force 5 attempts then a 1-hour lockout (django-axes), plus a login honeypot
πŸ•΅οΈ Enumeration Constant-time password check prevents email enumeration
πŸ›‘οΈ CSRF SameSite=Strict cookies, token on every form
πŸ”’ HTTPS SSL-only with HSTS (1 year) in production
πŸ“Ž File uploads MIME type + extension + magic-byte validation
🏒 Tenant isolation Enforced at the middleware, view, and ORM layers
πŸ“ Audit trail Every login, logout, password change, and import is logged

🐳 Deployment

bash scripts/deploy.sh    # first-time: prompts for domain/email, builds images,
                          #   runs migrations, configures SSL (Let's Encrypt)
bash scripts/update.sh    # pull, rebuild, migrate, zero-downtime restart

All containers run restart: always behind Nginx + Gunicorn, so a server reboot brings the whole stack back online automatically.


πŸ“„ License

Released under the MIT License, free to use, modify, and build on, with attribution.


Built with β˜• and πŸ”₯ in South Africa

About

🍺 Multi-tenant B2B data analytics platform β€” ingests messy POS/delivery exports, ML-maps products to a master catalog, and serves clean client dashboards. Django + PostgreSQL + HTMX.

Topics

Resources

License

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors