### Environment Variables Setup Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/README.md Copy the example file and fill in your specific values for the required environment variables. This is crucial for configuring the application's secrets and credentials. ```env # Copy .env.example and fill in your values SECRET_KEY=YOUR_VALUE_HERE JWT_SECRET=YOUR_VALUE_HERE SESSION_SECRET=YOUR_VALUE_HERE ``` -------------------------------- ### Development Mode Setup Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DEPLOYMENT_OVERVIEW.md Steps to set up and run the Meta Ads Intelligence Platform in development mode. This includes cloning the repository, installing dependencies, configuring environment variables, and running the application with auto-reloading. ```bash git clone meta-ads cd meta-ads pip install -r requirements.txt cp .env.example .env # Edit .env with your values python run.py ``` -------------------------------- ### Install Dependencies Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DEPLOYMENT_OVERVIEW.md Install new Python dependencies from the requirements file during an upgrade. ```bash pip install -r requirements.txt ``` -------------------------------- ### systemd Service Management Commands Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DEPLOYMENT_OVERVIEW.md Commands to reload systemd, enable, and start the Meta Ads Intelligence Platform service. These commands are used after creating or modifying the service file. ```bash sudo systemctl daemon-reload sudo systemctl enable meta-ads sudo systemctl start meta-ads ``` -------------------------------- ### Run Python Application Locally Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/README.md Execute the main Python script to start the application in local development mode. This typically enables auto-reloading for faster development cycles. ```bash python run.py ``` -------------------------------- ### Cache File JSON Structure Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DATABASE_OVERVIEW.md Example structure for cache files stored in `data/cache/`. Each file represents cached data for an ad account and has a TTL of 60 minutes. ```json { "timestamp": "2025-01-15T09:15:00", "data": [ ... enriched row dicts ... ] } ``` -------------------------------- ### Sync Status JSON Structure Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DATABASE_OVERVIEW.md Example structure for `sync_status.json`, which tracks the last sync result per ad account. This file is written after every sync run. ```json { "account-uuid-here": { "account_id": "account-uuid-here", "account_name": "My Ad Account", "timestamp": "2025-01-15T08:05:22", "status": "success", "rows_added": 47, "message": "47 rows added, 12 skipped" } } ``` -------------------------------- ### Dockerfile for Meta Ads Intelligence Platform Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DEPLOYMENT_OVERVIEW.md A Dockerfile to build a container image for the Meta Ads Intelligence Platform. It installs dependencies, copies application code, and exposes the application port. ```dockerfile FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "run.py"] ``` -------------------------------- ### Application Directory Structure Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DEPLOYMENT_OVERVIEW.md This is the expected directory layout for the application on a Linux VPS. ```bash /opt/meta-ads/ ├── run.py ├── requirements.txt ├── .env <- ├── core/ ├── db/ ├── web/ ├── data/ <- └── logs/ <- ``` -------------------------------- ### Run Python Application with Docker Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/README.md Deploy the application using Docker. Ensure to provide the environment file and mount necessary volumes for data and logs persistence. ```bash docker run (env-file .env, volumes: data/, logs/) -> port 8000 ``` -------------------------------- ### Tenant Context Management Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/ARCHITECTURE.md Demonstrates how tenant context is managed using ContextVars. The auth middleware sets the current organization ID, which can then be accessed globally within the request's call stack. ```python set_current_org(org_id) # ... anywhere in the call stack get_current_org() ``` -------------------------------- ### Docker Run Command Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DEPLOYMENT_OVERVIEW.md Command to build and run the Meta Ads Intelligence Platform Docker container. It maps ports, mounts volumes for persistent data, and uses an environment file for configuration. ```bash docker build -t meta-ads . docker run -d \ -p 8000:8000 \ -v $(pwd)/data:/app/data \ -v $(pwd)/logs:/app/logs \ --env-file .env \ --name meta-ads \ meta-ads ``` -------------------------------- ### systemd Service Configuration Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DEPLOYMENT_OVERVIEW.md Configuration file for systemd to manage the Meta Ads Intelligence Platform service. Ensures the application runs as a service and restarts on failure. ```ini [Unit] Description=Meta Ads Intelligence Platform After=network.target [Service] User=www-data WorkingDirectory=/opt/meta-ads ExecStart=/opt/meta-ads/venv/bin/python run.py Restart=on-failure RestartSec=5 EnvironmentFile=/opt/meta-ads/.env [Install] WantedBy=multi-user.target ``` -------------------------------- ### Entity Relationship Diagram Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DATABASE_OVERVIEW.md Visualizes the relationships between organizations, users, and tenant databases. Use this diagram to understand the data model. ```mermaid erDiagram Organization ||--o{ User : "has members" Organization ||--o| TenantDatabase : "maps to" Organization { id PK name created_at } User { id PK email username name role organization_id FK is_profile_complete google_id created_at } TenantDatabase { organization_id PK FK db_name } ``` -------------------------------- ### Restart Service Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DEPLOYMENT_OVERVIEW.md Restart the systemd service for the Meta Ads application. ```bash sudo systemctl restart meta-ads ``` -------------------------------- ### View Mermaid ER Diagram Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/README.md To visualize the database entity relationship diagram, open the provided .mmd file in the Mermaid Live Editor. ```mermaid erDiagram Organization ||--o{ User : "has" Organization ||--o| TenantDatabase : "maps to" User }o--|| Organization : "belongs to" ``` -------------------------------- ### Sync Pipeline Data Flow Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/ARCHITECTURE.md Details the steps involved in fetching data from the Meta Marketing API, processing it, and writing it to Google Sheets. ```flowchart Meta Marketing API | paginated HTTP GET (ad insights, level=ad, time_increment=1) v meta_fetcher.py | list of raw API row dicts v sync_engine.py | loads account settings from config_manager | checks existing RAW_DATA sheet for known date+ad_id keys | filters out duplicates v row_builder.py | maps API fields to sheet columns using field_map config v sheets_writer.py | appends new rows to RAW_DATA | rebuilds ANALYTICS tab from RAW_DATA (cleans numeric types, applies formatting) v Google Sheets | v sync_engine.py | invalidates data_reader cache for this account | sends Telegram summary via Telegram Bot API ``` -------------------------------- ### Mermaid Sequence Diagram for Dashboard Data Flow Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/README.md Illustrates the flow of data from user interaction to rendering dashboard charts, including API calls and data processing steps. ```mermaid sequenceDiagram actor User participant Browser participant FastAPI participant DataReader participant GoogleSheets participant RulesEngine User->>Browser: Open dashboard Browser->>FastAPI: GET /dashboard/{account_id} FastAPI->>Browser: HTML shell (Jinja2) Browser->>FastAPI: GET /api/chart-data/{account_id}?start=...&end=... FastAPI->>DataReader: read_analytics_sheet(account) DataReader->>GoogleSheets: get_all_values() (or serve from cache) GoogleSheets-->>DataReader: Raw rows DataReader->>DataReader: enrich_all() (compute derived metrics) DataReader->>RulesEngine: evaluate_all_adsets() RulesEngine-->>DataReader: Ad set rows with rule_flag DataReader-->>FastAPI: KPIs, charts, flags FastAPI-->>Browser: JSON payload Browser->>Browser: Render Chart.js charts ``` -------------------------------- ### Request Lifecycle Flowchart Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/ARCHITECTURE.md Illustrates the sequence of middleware and route handlers a browser request follows within the FastAPI application. ```flowchart Browser Request | v SessionMiddleware (decode session cookie, attach session to request) | v AuthMiddleware (check session.user_id; redirect to /login if absent) | (set ContextVar org_id for duration of request) v Route Handler (validate input, call core services) | v Core Service (business logic: read, compute, write) | v Response (JSON or HTML via Jinja2) ``` -------------------------------- ### Service Dependency Map Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/ARCHITECTURE.md Visual representation of the service dependencies within the application, illustrating how different modules and external services interact. ```text web/routes/dashboard.py -> core/data_reader.py -> gspread (Google Sheets) -> core/rules_engine.py web/routes/settings.py -> core/config_manager.py -> core/license.py -> core/scheduler.py (reschedule) -> core/meta_fetcher.py (validate_meta_token) -> core/sync_engine.py (send_telegram_alert) web/routes/sync.py -> core/sync_engine.py -> core/meta_fetcher.py -> core/row_builder.py -> core/sheets_writer.py -> core/config_manager.py -> core/data_reader.py (invalidate_cache) core/scheduler.py -> db/main_db.py (query all org IDs) -> db/tenant_manager.py (set_current_org) -> core/sync_engine.py (run_all_accounts) web/routes/auth.py -> db/main_db.py -> db/password.py -> db/tenant_manager.py (create_tenant_db on register) ``` -------------------------------- ### Mermaid System Diagram Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/README.md Visual representation of the Meta Ads Intelligence system architecture, showing interactions between external services, frontend, web layer, core layer, and data layer. View in Mermaid Live Editor. ```mermaid flowchart TD subgraph External["External Services"] META[Meta Marketing API] GSHEET[Google Sheets API] TG[Telegram Bot API] GOOGLE_AUTH[Google OAuth] end subgraph Frontend["Frontend Layer"] BROWSER[Browser Jinja2 + Chart.js] end subgraph Web["Web Layer (FastAPI)"] AUTH[Auth Routes] DASH[Dashboard Routes] SETS[Settings Routes] SYNC[Sync Routes] USERS[Users Routes] API[API Routes] MW[Auth Middleware] end subgraph Core["Core Layer"] FETCHER[Meta Fetcher] SYNCENG[Sync Engine] WRITER[Sheets Writer] READER[Data Reader] RULES[Rules Engine] SCHED[Scheduler] CFG[Config Manager] LIC[License System] end subgraph DB["Data Layer"] MAINDB[(Main DB SQLite)] TENANTDB[(Tenant DBs SQLite per org)] CACHE[File Cache 60-min TTL] SETTINGS[Encrypted Settings Files] end BROWSER --> Web MW --> AUTH & DASH & SETS & SYNC & USERS & API DASH & API --> READER SETS --> CFG SYNC --> SYNCENG SCHED --> SYNCENG SYNCENG --> FETCHER --> META SYNCENG --> WRITER --> GSHEET READER --> GSHEET READER --> CACHE READER --> RULES CFG --> SETTINGS SYNCENG --> TG AUTH --> GOOGLE_AUTH Web --> MAINDB Web --> TENANTDB LIC --> CFG style External fill:#f5f5f5 style Frontend fill:#dbeafe style Web fill:#d1fae5 style Core fill:#d1fae5 style DB fill:#fed7aa ``` -------------------------------- ### Generate Fernet Key Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DEPLOYMENT_OVERVIEW.md Python command to generate a Fernet key, which is required for encrypting settings files at rest. This key is used for the SECRET_KEY environment variable. ```bash python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())" ``` -------------------------------- ### Dashboard Data Flow Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/ARCHITECTURE.md Explains how dashboard data is fetched, processed, and rendered for a given account, including caching and rule evaluation. ```flowchart Browser GET /dashboard/{account_id} | v dashboard.py (route) | returns HTML shell (Jinja2 template) v Browser (JavaScript) | fires GET /api/chart-data/{account_id}?start=...&end=... v dashboard.py (JSON endpoint) | v data_reader.py | checks file cache (data/cache/{account_id}.json, 60-min TTL) | if stale: fetches all rows from ANALYTICS worksheet via gspread | enriches every row with computed metrics (Hook Rate, CVR, etc.) | applies date filter | v rules_engine.py | groups enriched rows by Ad Set ID | evaluates each ad set against pause/scale rules | assigns rule_flag: scale | pause | watch | ok | v data_reader.py (aggregation) | computes KPI totals with period-over-period change | computes daily trend per metric | computes campaign breakdown | computes funnel with leakage detection | computes frequency vs CTR scatter data | computes day-of-week heatmap | computes platform breakdown | v JSON response to Browser | v Chart.js renders all charts ``` -------------------------------- ### Nginx Reverse Proxy Configuration Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/DEPLOYMENT_OVERVIEW.md Nginx configuration to act as a reverse proxy for the Meta Ads Intelligence Platform, handling HTTPS and forwarding requests to the application. Use Certbot or Caddy for SSL management. ```nginx server { listen 443 ssl; server_name your-domain.com; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } ``` -------------------------------- ### Module Map of Meta Ads Intelligence Source: https://github.com/salehmdasif/meta-ads-intelligence-public/blob/main/ARCHITECTURE.md Provides a hierarchical view of the project's directory structure and the primary function of each module. ```tree meta-ads-intelligence/ ├── run.py Entry point — starts Uvicorn ├── web/ │ ├── app.py FastAPI app instance, middleware registration, startup events │ └── routes/ │ ├── auth.py Login, register, Google OAuth, password reset, profile update │ ├── dashboard.py Dashboard HTML page + JSON data endpoints │ ├── settings.py Settings page + all config save/update endpoints │ ├── sync.py Manual sync trigger │ ├── setup.py Post-OAuth profile completion │ ├── users.py Admin: create and delete staff users │ └── api.py Super-admin API endpoints (health, status) ├── core/ │ ├── meta_fetcher.py Calls Meta Graph API, handles pagination and errors │ ├── sync_engine.py Orchestrates one full sync: fetch → deduplicate → write │ ├── sheets_writer.py Connects to Google Sheets, writes RAW_DATA, rebuilds ANALYTICS │ ├── row_builder.py Maps Meta API response fields to flat sheet columns │ ├── data_reader.py Reads ANALYTICS sheet, manages 60-min cache, computes metrics │ ├── rules_engine.py Groups rows by ad set, evaluates automation rules, assigns flags │ ├── scheduler.py APScheduler: starts, configures, and reschedules sync jobs │ ├── config_manager.py Load/save per-tenant encrypted settings.json │ └── license.py JWT license key decoder, account limit enforcement ├── db/ │ ├── main_db.py SQLAlchemy models: Organization, User, TenantDatabase │ ├── tenant_manager.py ContextVar-based tenant routing, DB provisioning, path resolution │ └── password.py bcrypt hash and verify wrapper └── scripts/ └── migrate_existing.py One-time migration for legacy single-user installations ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.