docs re-org

This commit is contained in:
IGNY8 VPS (Salman)
2025-12-09 13:26:35 +00:00
parent 4d13a57068
commit 6a4f95c35a
231 changed files with 11353 additions and 31152 deletions

View File

@@ -0,0 +1,67 @@
# Account Lifecycle
## Purpose
Explain how accounts are created, activated, associated with plans/subscriptions, how users access them, and how account state affects the platform.
## Code Locations (exact paths)
- Models: `backend/igny8_core/auth/models.py` (`Account`, `User`, `Plan`, `Subscription`, `Site`, `SiteUserAccess`)
- Auth middleware: `backend/igny8_core/auth/middleware.py` (sets `request.account`, validates plan status)
- Permissions: `backend/igny8_core/auth/permissions.py`
- Account settings API: `backend/igny8_core/modules/system/views.py` (account settings), `auth/views.py` (team)
- Frontend account settings: `frontend/src/pages/account/AccountSettingsPage.tsx`
- Frontend auth store: `frontend/src/store/authStore.ts`
## High-Level Responsibilities
- Maintain tenant identity (`Account`) and link users, sites, sectors, plans, subscriptions, and credits.
- Control access via account state and user roles.
- Provide account-level settings (name, billing email/address, tax info).
## Detailed Behavior
- Account fields: `name`, `slug`, `owner`, `plan`, `credits`, `status` (`active`, `suspended`, `trial`, `cancelled`), timestamps.
- User fields: extends Django user with `account` FK and `role` (`developer`, `owner`, `admin`, `editor`, `viewer`, `system_bot`).
- Plan/subscription: `Plan` defines limits and included credits; `Subscription` links account to plan and holds billing cycle/status; `Account.plan` references current plan.
- Sites: `Site` attaches to account; `SiteUserAccess` grants non-admin users site-level access.
- Middleware: `AccountContextMiddleware` resolves account from JWT or session, ensures account is active, and attaches plan information; rejects access for inactive accounts.
- Settings update: `AccountSettings` API exposes billing fields consumed by `AccountSettingsPage`.
## Data Structures / Models Involved (no code)
- `Account`, `User`, `Plan`, `Subscription`, `Site`, `SiteUserAccess`, `Sector`, `CreditTransaction`, `CreditUsageLog`.
## Execution Flow
- Signup/Login → JWT issued with `account_id` → middleware sets `request.account`.
- Requests pass through permissions tied to roles and account context.
- Plan changes/subscriptions update `Account.plan` and `Subscription` records (via billing endpoints and `invoice_service`/`payment_service`).
- Account settings updates persist via system/account settings endpoint and reflect in billing data.
## Cross-Module Interactions
- Billing uses `Account.credits` and plan linkage; `credit_service` deducts/credits per action.
- Sites/Planner/Writer/Automation all inherit account scoping via base viewsets and base models.
- Integration (WordPress) uses account-scoped `Site.wp_api_key` for API key auth.
## State Transitions (if applicable)
- `status`: trial → active → (suspended/cancelled) based on plan/payment handling (enforced via middleware checks).
- `plan` changes when subscriptions are created/updated; `Subscription.status` drives billing state.
- Site activation independent per site; account state still gates overall access.
## Error Handling
- Middleware rejects requests for inactive/suspended accounts; API returns unified error response.
- Permissions reject unauthorized roles before hitting business logic.
## Tenancy Rules
- Every model inherits account (direct FK or via base models); every request resolves `request.account`.
- Querysets in viewsets filter by `account` (and site/sector where applicable); public reads limited to specific cases (e.g., active site by slug).
## Billing Rules (if applicable)
- Plan inclusion and subscription determine credit grants; credits stored on `Account`; deductions logged via `CreditTransaction`/`CreditUsageLog`.
## Background Tasks / Schedulers (if applicable)
- None specific to account state; billing/automation tasks run with account context provided by Celery payloads.
## Key Design Considerations
- Account is the tenant boundary; all downstream objects carry account FK for isolation.
- Middleware centralizes account activation/plan validation to avoid per-view duplication.
## How Developers Should Work With This Module
- When adding new resources, inherit from `AccountBaseModel`/`SiteSectorBaseModel` and use base viewsets to enforce scoping.
- On new plan features/limits, extend `Plan` and ensure middleware/permissions or service checks enforce them.
- Preserve slug immutability for stability across integrations.

View File

@@ -0,0 +1,69 @@
# Billing Lifecycle
## Purpose
Detail how credits, plans, subscriptions, invoices, and payments flow through the system, and where deductions/additions are enforced.
## Code Locations (exact paths)
- Models: `backend/igny8_core/business/billing/models.py` (`CreditTransaction`, `CreditUsageLog`, `CreditCostConfig`, `Invoice`, `Payment`, `CreditPackage`, `PaymentMethodConfig`, `AccountPaymentMethod`)
- Services: `backend/igny8_core/business/billing/services/credit_service.py`, `services/invoice_service.py`, `services/payment_service.py`
- Views/Endpoints: `backend/igny8_core/modules/billing/views.py`
- Frontend billing pages: `frontend/src/pages/account/{AccountBillingPage.tsx,PlansAndBillingPage.tsx,PurchaseCreditsPage.tsx}`
## High-Level Responsibilities
- Track credit balance, record usage, and enforce costs for AI/automation actions.
- Manage plans/subscriptions, generate invoices, and record payments.
- Expose account-scoped billing data (balance, usage, invoices, payments, packages, payment methods).
## Detailed Behavior
- Credit balance: stored on `Account.credits`; `CreditService` adds/deducts via `CreditTransaction` and logs usage in `CreditUsageLog`.
- Costs: read from `CreditCostConfig` or hardcoded `CREDIT_COSTS` fallbacks inside `credit_service.py`.
- Deductions: called from AI/automation flows to ensure sufficient credits; `InsufficientCreditsError` thrown on shortage.
- Plans/Subscriptions: `Plan` defines price, billing_cycle, included_credits, max sites/sectors/users; `Subscription` links account to plan. Plan selection handled via billing endpoints and frontend plan tabs.
- Invoices: `InvoiceService` creates invoices for subscriptions and credit packages; generates unique invoice numbers and line items.
- Payments: `PaymentService` records payments; manual payments stored with status (pending/processing/etc.); payment methods configured via `PaymentMethodConfig`/`AccountPaymentMethod`.
- Packages: `CreditPackage` defines purchasable credit bundles; purchasing triggers invoice/payment flows.
## Data Structures / Models Involved (no code)
- Billing: `CreditTransaction`, `CreditUsageLog`, `CreditCostConfig`, `Invoice`, `Payment`, `CreditPackage`, `PaymentMethodConfig`, `AccountPaymentMethod`.
- Plan: `Plan`, `Subscription` (in `auth/models.py`).
- Account linkage: `Account` holds `credits` and `plan`.
## Execution Flow
- Balance/Usage read: billing endpoints return account-scoped balance and usage summaries.
- AI/Automation call: service invokes `CreditService.deduct_credits_for_action` → creates `CreditTransaction` + `CreditUsageLog`.
- Purchase credits: frontend calls billing endpoint → `CreditService.add_credits` + `InvoiceService` for package; payment recorded via `PaymentService` (manual/other).
- Subscription change: endpoint updates `Subscription` + `Account.plan`, generates invoice as needed; payment recorded if required.
- Invoice download: `modules/billing/views.py` exposes invoice retrieval; frontend uses `downloadInvoicePDF`.
## Cross-Module Interactions
- Automation/writer AI calls depend on credit checks; insufficient balance blocks operations.
- Account settings feed invoice billing details; payments/invoices are tied to account.
## State Transitions (if applicable)
- Payment status: `pending``processing/pending_approval``succeeded/completed` or `failed/refunded/cancelled/void/uncollectible`.
- Subscription status: `active`/`cancelled` (persisted in `Subscription`); plan reference on account updates accordingly.
## Error Handling
- `InsufficientCreditsError` for low balance; surfaces to API as error response.
- Payment/Invoice service raise validation errors (e.g., already paid invoice).
## Tenancy Rules
- All billing queries filter by `request.user.account`; viewsets inherit from `AccountModelViewSet`.
- Payment methods, invoices, payments, credit transactions are account-scoped; no cross-tenant access.
## Billing Rules (if applicable)
- Costs derived from config constants or `CreditCostConfig`.
- Included credits and limits come from `Plan`; extra purchases via `CreditPackage`.
- Credits must be available before AI/automation runs proceed.
## Background Tasks / Schedulers (if applicable)
- None dedicated; billing operations are request-driven. Automation tasks carry account context to deduct credits within Celery runs.
## Key Design Considerations
- CreditService centralizes deductions to avoid scattered logic.
- Manual payment flow avoids storing sensitive data; relies on transaction_reference and admin approval.
## How Developers Should Work With This Module
- When adding new billable actions, route them through `CreditService` with a defined cost key.
- To change pricing, update `CreditCostConfig` data or the `CREDIT_COSTS` fallback map.
- Keep all billing endpoints inheriting `AccountModelViewSet` to maintain isolation.

View File

@@ -0,0 +1,73 @@
# Content Lifecycle
## Purpose
Trace content from keyword intake through clustering, idea generation, task creation, AI writing, image generation, and publishing/sync, mapping to backend services and frontend pages.
## Code Locations (exact paths)
- Planner models: `backend/igny8_core/business/planning/models.py` (`Keywords`, `Clusters`, `ContentIdeas`)
- Writer models: `backend/igny8_core/business/content/models.py` (`Tasks`, `Content`, `Images`, `ContentTaxonomy`)
- ViewSets: `backend/igny8_core/modules/planner/views.py`; `backend/igny8_core/modules/writer/views.py`
- Automation orchestration: `backend/igny8_core/business/automation/services/automation_service.py`; Celery tasks `business/automation/tasks.py`
- WordPress sync/publish: `backend/igny8_core/business/integration/services/integration_service.py`, `modules/integration/views.py`
- Frontend pages: `frontend/src/pages/Planner/*`, `frontend/src/pages/Writer/*`, `frontend/src/pages/Automation/AutomationPage.tsx`, `frontend/src/pages/Sites/*`
## High-Level Responsibilities
- Collect and cluster keywords, generate ideas, create tasks, generate content and images, then publish/sync.
- Support manual steps via Planner/Writer pages and automated runs via Automation pipeline.
- Maintain site/sector scoping and credit enforcement throughout AI operations.
## Detailed Behavior
- Keywords → Clusters: `KeywordViewSet` (upload/create) and `ClusterViewSet` (manual or AI auto_cluster). Models inherit `SiteSectorBaseModel` for scoping.
- Clusters → ContentIdeas: `ContentIdeasViewSet` with AI generation endpoint; ideas track status.
- Ideas/Tasks: `Tasks` model holds brief/keywords/structure/status; created manually or by automation stage.
- Tasks → Content: Writer endpoints generate content (AI) and update `Content` records; statuses managed in writer views.
- Content → Images: `ImagesViewSet` handles image generation and storage; images linked to tasks/content.
- Publishing: Integration service sends content to WordPress via `/api/v1/integration` endpoints; WP plugin responds with IDs and syncs status back.
- Automation: `automation_service.run_automation` executes 7 stages with delays/retries/credit estimates; run status tracked in `AutomationRun`.
## Data Structures / Models Involved (no code)
- Planner: `Keywords`, `Clusters`, `ContentIdeas`.
- Writer: `Tasks`, `Content`, `Images`, `ContentTaxonomy`.
- Automation: `AutomationConfig`, `AutomationRun`.
- Integration: `SiteIntegration`.
## Execution Flow
- Manual path: upload keywords → cluster (auto/manual) → generate ideas → create tasks → generate content → generate images → publish to WP → WP syncs status back.
- Automated path: Automation pipeline stages perform the same transitions in sequence, logging progress and deducting credits.
- Each stage uses DRF viewsets; automation uses Celery tasks (`run_automation_task`, `resume_automation_task`) and logger for trace files.
## Cross-Module Interactions
- Automation consumes planner/writer endpoints and triggers integration publish.
- Integration relies on sites WP API key (`Site.wp_api_key`) and `SiteIntegration` config for credentials/URLs.
- Billing deducts credits for AI operations through `CreditService`.
## State Transitions (if applicable)
- Keywords: status (active/inactive/used) per model.
- Clusters: status (active/archived).
- ContentIdeas: status (draft/approved/in_progress/completed).
- Tasks: status simplified (queued/completed) in Stage 1; content status (draft/published) and image status stored on related models.
- AutomationRun: status across run lifecycle (created/running/paused/completed/failed).
## Error Handling
- Viewsets rely on unified DRF error responses; automation logger records failures per stage; Celery retries configured where applicable.
- WordPress sync errors surfaced via integration service responses.
## Tenancy Rules
- All planner/writer/automation/integration models inherit account/site/sector via base models; viewsets filter by `request.account` and query params.
## Billing Rules (if applicable)
- AI clustering/idea/content/image generation deduct credits via `CreditService` cost map; automation blocks run if estimated credits insufficient.
## Background Tasks / Schedulers (if applicable)
- Automation scheduler: `check_scheduled_automations` enqueues runs; `run_automation_task`/`resume_automation_task` execute pipeline in Celery.
- AI tasks run async via Celery wrappers (`ai/tasks.py`).
## Key Design Considerations
- Single source of truth for tenancy via base models; prevents cross-tenant data exposure.
- Automation mirrors manual flow; manual pages remain usable when automation is paused or disabled.
- WordPress publish/sync uses API key auth to avoid storing user credentials beyond site integration config.
## How Developers Should Work With This Module
- When adding new content stages, update both manual endpoints and automation stages.
- Ensure every new action that calls AI is wired through `CreditService` and respects site/sector filters.
- For new publishing targets, extend `SiteIntegration` and integration service while keeping site/account scoping.

View File

@@ -0,0 +1,54 @@
# Permission Matrix
## Purpose
Define which roles can perform which actions across major modules, based on backend permission classes and role checks, so feature teams know the enforced access patterns.
## Code Locations (exact paths)
- Roles: `backend/igny8_core/auth/models.py` (`User.role`)
- Permission classes: `backend/igny8_core/auth/permissions.py` (`IsOwnerOrAdmin`, `IsEditorOrAbove`, `IsViewerOrAbove`, `AccountPermission`)
- Base viewsets: `backend/igny8_core/api/base.py` (Account/Site/Sector scoping; unified responses)
- Middleware: `backend/igny8_core/auth/middleware.py` (ensures account context and plan status)
- Frontend guards: `frontend/src/App.tsx` (`ProtectedRoute`, `ModuleGuard`), `frontend/src/store/authStore.ts` (role in state)
## Roles
- `developer`
- `owner`
- `admin`
- `editor`
- `viewer`
- `system_bot`
## High-Level Rules (backend)
- Owner/Admin: full CRUD on account resources; pass `IsOwnerOrAdmin`.
- Editor: edit/create content within account; passes `IsEditorOrAbove`.
- Viewer: read-only access; passes `IsViewerOrAbove`.
- AccountPermission: checks authenticated user and role presence; used as base for many endpoints.
- SiteUserAccess: for non-admins, site membership governs visibility in `SiteViewSet` list.
## Module Access (derived from permission classes)
- Auth/Account: team management/settings via owner/admin; viewers can read limited data.
- Planner (keywords/clusters/ideas): editor+ for write; viewer for read (via `IsEditorOrAbove` on actions).
- Writer (tasks/content/images): editor+ for write (generate/update/delete); viewer for read.
- Automation: editor+ to configure/run/pause/resume; viewer can read status/history where permitted.
- Integration: editor+ to connect/test/sync; viewer can typically read integration status.
- Billing: owner/admin for invoices/payments/payment methods/plan changes; others read balance/usage where exposed.
- System settings: owner/admin for global/account settings; viewer may read select public prompts/strategies if exposed by viewset permissions.
## Tenancy Enforcement
- Middleware sets `request.account`; base viewsets filter by account/site/sector; permissions applied after scoping.
- API key auth (WordPress) sets account from `Site.wp_api_key`, bypassing user roles for plugin calls but still scoped to site/account.
## Execution Flow
- Request → JWT/API key auth → `AccountContextMiddleware` (account + plan validation) → DRF permission class → queryset filtering by base viewset → action logic.
## Error Handling
- Permission denials return unified error response via DRF handler; 403 for insufficient role; 401 for unauthenticated.
## Cross-Module Interactions
- Role checks consistent via shared permission classes; modules rely on same `IsEditorOrAbove`/`IsOwnerOrAdmin`.
- Frontend `ModuleGuard` mirrors backend by restricting route access based on `authStore.user.role` and `allowedModules`.
## How Developers Should Work With This Module
- When adding endpoints, choose the strictest applicable permission (`IsOwnerOrAdmin` > `IsEditorOrAbove` > `IsViewerOrAbove`).
- Keep AccountPermission (auth required) on all tenant resources; avoid anonymous access except intentional public endpoints (e.g., site slug read).
- If creating module-specific roles, extend permission classes centrally to avoid drift between modules.

View File

@@ -0,0 +1,36 @@
# Role Definitions
## Purpose
Define each role available in IGNY8, what it can access, and where those permissions are enforced.
## Code Locations (exact paths)
- Role field: `backend/igny8_core/auth/models.py` (`User.role`)
- Permission classes: `backend/igny8_core/auth/permissions.py` (`IsOwnerOrAdmin`, `IsEditorOrAbove`, `IsViewerOrAbove`, `AccountPermission`)
- Frontend guards: `frontend/src/App.tsx` (`ProtectedRoute`, `ModuleGuard`), `frontend/src/store/authStore.ts` (role persisted in state)
## Roles and Capabilities (backend-enforced)
- `developer`: Treated as admin-level for debugging; passes owner/admin checks.
- `owner`: Full tenant control (users, billing, plans, sites, automation).
- `admin`: Nearly full control; same as owner for most modules except potential business policy differences (not differentiated in code).
- `editor`: Can create/update planner/writer/automation configs; cannot perform owner/admin-only billing or team admin actions.
- `viewer`: Read-only access where `IsViewerOrAbove` is applied; cannot mutate resources.
- `system_bot`: Reserved for system automation; not typically used via UI; expected to bypass some checks when invoked server-side (still scoped to account).
## Enforcement Points
- DRF permissions: Applied per view/action using classes above; combined with account/site/sector scoping from base viewsets.
- Middleware: `AccountContextMiddleware` must set `request.account` and reject inactive accounts before permissions run.
- Site scoping: For non-admins, `SiteUserAccess` limits visible sites in `SiteViewSet`.
## Cross-Module Impact
- Planner/Writer/Automation: `IsEditorOrAbove` gates writes; viewers read only.
- Billing: owner/admin (and developer) expected for invoices/payments/plan changes; editors/viewers not permitted to mutate.
- Integration: editor+ for connect/test/sync; viewer may read status where allowed.
- System settings: owner/admin for account/system settings; others limited.
## Tenancy Rules
- Roles operate within the resolved `request.account`; there is no cross-tenant role scope. API key flows bypass user roles but remain account-scoped.
## How Developers Should Work With This Module
- When adding a new endpoint, pick the minimal role needed and reuse existing permission classes.
- If introducing finer-grained roles, extend `permissions.py` centrally and update `ModuleGuard` to mirror backend expectations.
- Keep `User.role` values consistent; avoid hardcoding role strings outside permission helpers.

View File

@@ -0,0 +1,82 @@
# Site Lifecycle
## Purpose
Describe how sites are created, configured, activated, integrated, and used across planner/writer/automation flows, including sector selection and WordPress connectivity.
## Code Locations (exact paths)
- Models: `backend/igny8_core/auth/models.py` (`Site`, `Sector`, `Industry`, `IndustrySector`, `SiteUserAccess`)
- ViewSet: `backend/igny8_core/auth/views.py` (`SiteViewSet`)
- Routing: `backend/igny8_core/auth/urls.py` (paths under `/api/v1/auth/sites/`)
- Sector selection logic: `SiteViewSet.select_sectors` action
- Frontend pages: `frontend/src/pages/Sites/{Manage.tsx,Dashboard.tsx,Settings.tsx}`
- WordPress integration service: `backend/igny8_core/business/integration/services/integration_service.py`, `modules/integration/views.py`
## High-Level Responsibilities
- Create and manage sites per account, with optional industry and sector assignments.
- Enforce plan-based sector limits and site activation.
- Provide public read-by-slug for active sites (renderer support).
- Connect to external platforms (WordPress) using API keybased integration.
## Detailed Behavior
- Creation (`POST /auth/sites/`): Authenticated user; account auto-set from request; slug stored; no single-active constraint.
- Listing (`GET /auth/sites/`):
- Unauthenticated + `slug` param: returns active site matching slug (public read).
- Admin/developer: all sites.
- Owner/admin: sites for users account.
- Others: sites where `SiteUserAccess` exists.
- Activation (`POST /auth/sites/{id}/set_active/`): Marks site active; does not auto-deactivate others.
- Sector selection (`POST /auth/sites/{id}/select_sectors/`):
- Requires `industry_slug`; optional `sector_slugs`.
- Validates industry active; enforces `get_max_sectors_limit` from plan.
- Deactivates sectors not provided; ensures sectors belong to industry; creates missing site sectors; returns site + sectors.
- Sectors listing (`GET /auth/sites/{id}/sectors/`): Active sectors for site.
- WordPress integration: `Site.wp_api_key` used by API key auth; `SiteIntegration` stores credentials/config; integration endpoints test connection and sync structure/content.
- Frontend:
- Manage list (`Sites/Manage.tsx`): cards with hosting/type, WP integration button, CRUD, navigation to settings.
- Dashboard (`Sites/Dashboard.tsx`): site overview, stats placeholders, quick actions.
- Settings (`Sites/Settings.tsx`): edit core fields, SEO metadata, industry/sector selection, WP integration tab and content-types tab.
## Data Structures / Models Involved (no code)
- `Site`: account FK, name, slug, domain/wordpress fields, industry, hosting_type/site_type, status, is_active, `wp_api_key`.
- `Sector`: account/site FK, name, industry_sector FK, status.
- `Industry`/`IndustrySector`: reference data for industry/sector taxonomy.
- `SiteIntegration`: platform, credentials_json, config_json, flags.
- `SiteUserAccess`: grants non-admin access to specific sites.
## Execution Flow
- Create site → optionally set industry/sectors via `select_sectors` → activate → connect WordPress (integration endpoints) → use site across planner/writer/automation via site/sector filters.
- Renderer/public slug access: unauthenticated `GET /auth/sites/?slug=...` returns active site for public consumption.
## Cross-Module Interactions
- Planner/Writer/Automation viewsets inherit `SiteSectorModelViewSet` to require `site_id`/`sector_id` filters and attach site/sector to records.
- Integration module uses `Site.wp_api_key` to authenticate WP plugin requests and `SiteIntegration` for config/credentials.
- Plan limits (max sectors) enforced during `select_sectors`.
## State Transitions (if applicable)
- Site `status`/`is_active` set via activation endpoint.
- Sectors activated/deactivated by `select_sectors`; industry assignment updated.
- Integration connection status managed via integration service responses (not persisted on Site).
## Error Handling
- 400 on missing industry slug or exceeding sector limits; 404 for missing site/industry; 500 if account missing on site during sector selection.
- Integration connection errors returned from integration service; frontend shows toasts.
## Tenancy Rules
- `SiteViewSet` filters by account via `AccountModelViewSet`; public slug read is the only unauthenticated path and limited to active site.
- `SiteUserAccess` governs non-admin user visibility.
## Billing Rules (if applicable)
- Sector limit enforced from plan (`get_max_sectors_limit`); additional sites/sectors constrained by plan.
## Background Tasks / Schedulers (if applicable)
- None for site management; integration sync tasks may run via integration services but are triggered, not scheduled here.
## Key Design Considerations
- Public slug read enables site renderer without auth while keeping other operations tenant-scoped.
- Sector selection centralizes industry/plan validation and avoids orphaned sectors.
- WP integration uses API key to avoid sharing user passwords.
## How Developers Should Work With This Module
- When adding new hosting/platform types, extend Site model fields plus integration handling.
- Keep all site-scoped resources inheriting site/sector base models and viewsets to maintain isolation.
- If adding analytics/stats, expose a dedicated endpoint and wire to Dashboard page cards.

View File

@@ -0,0 +1,77 @@
# User Flow Overview
## Purpose
Describe the end-to-end journey from signup through planning, writing, automation, publishing, and billing within IGNY8, mapping each step to concrete backend/frontend modules so engineers can navigate without scanning code.
## Code Locations (exact paths)
- Auth & account: `backend/igny8_core/auth/{views.py,serializers.py,models.py,middleware.py}`, `frontend/src/store/authStore.ts`, routes in `frontend/src/App.tsx`
- Planner: `backend/igny8_core/modules/planner/views.py`, `business/planning/models.py`, `frontend/src/pages/Planner/*`
- Writer: `backend/igny8_core/modules/writer/views.py`, `business/content/models.py`, `frontend/src/pages/Writer/*`
- Automation: `backend/igny8_core/business/automation/{services/automation_service.py,tasks.py,views.py}`, `frontend/src/pages/Automation/AutomationPage.tsx`
- Publishing/Integration: `backend/igny8_core/business/integration/{models.py,services/integration_service.py}`, `modules/integration/views.py`, WordPress plugin endpoints consumed via `/api/v1/integration/`; `frontend/src/pages/Sites/*`
- Billing: `backend/igny8_core/business/billing/{models.py,services/credit_service.py,services/invoice_service.py,views.py}`, `frontend/src/pages/account/*`
- Tenancy enforcement: `backend/igny8_core/auth/middleware.py`, `backend/igny8_core/api/base.py`
## High-Level Responsibilities
- Authenticate users and attach account context to every request.
- Let users plan keywords/clusters/ideas, create tasks and content, optionally automate all seven pipeline stages.
- Manage sites/sectors and connect WordPress for publishing/sync.
- Track credits, plans, subscriptions, invoices, and payments through billing services.
## Detailed Behavior
- Signup/Login: `auth/views.py` issues JWTs; `AccountContextMiddleware` sets `request.account`; frontend `authStore` stores tokens and refreshes them.
- Planning: `KeywordViewSet`, `ClusterViewSet`, `ContentIdeasViewSet` create/list/update scoped by `SiteSectorModelViewSet` filters; frontend planner pages drive these endpoints.
- Writing: `TasksViewSet`, `ContentViewSet`, `ImagesViewSet` manage tasks/content/images; AI generation endpoints trigger Celery-backed functions.
- Automation: `AutomationViewSet` + `automation_service.py` orchestrate 7 stages (keywords→clusters→ideas→tasks→content→image-prompts→images/manual review) with pause/resume and credit estimation; Celery tasks `run_automation_task`/`resume_automation_task` execute runs.
- Publishing/Integration: `IntegrationViewSet` handles WP connection tests and sync; WP plugin sends/receives data via API key; content publish endpoints in writer module update WordPress via integration services.
- Billing: credit balances and costs computed in `credit_service.py`; invoices via `invoice_service.py`; payments via `payment_service.py`; endpoints in `modules/billing/views.py` feed frontend billing pages.
## Data Structures / Models Involved (no code)
- Tenancy: `Account`, `Site`, `Sector` (plus `SiteUserAccess`), base models `AccountBaseModel`/`SiteSectorBaseModel`.
- Planning: `Keywords`, `Clusters`, `ContentIdeas`.
- Writing: `Tasks`, `Content`, `Images`.
- Automation: `AutomationConfig`, `AutomationRun`.
- Billing: `CreditTransaction`, `CreditUsageLog`, `CreditCostConfig`, `Invoice`, `Payment`, `CreditPackage`, `Subscription`, `Plan`.
- Integration: `SiteIntegration`.
## Execution Flow
1) User signs in → JWT stored → `AccountContextMiddleware` populates `request.account`.
2) Tenant creates sites/sectors (`SiteViewSet`), selects industry/sectors, optionally connects WordPress.
3) Planner: upload/enter keywords → cluster → generate ideas (manual or via automation/AI functions).
4) Writer: create tasks from ideas, generate content/images (manual endpoints or automation stages).
5) Publish: send to WordPress via integration endpoints or automation publish step; WP plugin syncs back statuses.
6) Automation (optional): run 7-stage pipeline via `AutomationViewSet` + Celery tasks; pause/resume supported.
7) Billing: credits deducted per AI/pipeline usage (`credit_service`), invoices/payments recorded; users view in billing pages.
## Cross-Module Interactions
- Automation invokes planner/writer endpoints/services and logs credit estimates.
- Billing hooks into automation and writer AI calls via credit deduction utilities.
- Integration uses site/account context and WP API key for sync; writer publish flows depend on integration configuration.
## State Transitions (if applicable)
- Account status (`active/suspended/trial/cancelled`) governs access; plan/subscription affect limits.
- Tasks/content/images status transitions handled in writer endpoints; automation run status moves through `created/running/paused/completed/failed`.
- Site activation via `set_active`; sectors toggled via `select_sectors`.
## Error Handling
- Unified API responses via `api/response.py`; DRF exception handler configured in settings; frontend shows toasts/banners.
- Automation errors logged via `automation_logger`; tasks wrapped in Celery with retries where defined.
## Tenancy Rules
- `AccountContextMiddleware` sets `request.account`; base viewsets filter by account/site/sector; API key auth sets account from `Site.wp_api_key`; public site slug reads limited to active sites.
## Billing Rules (if applicable)
- AI/automation uses `CreditService.deduct_credits_for_action`; credit balance required before runs; plans/subscriptions define included credits and sector/site limits.
## Background Tasks / Schedulers (if applicable)
- Celery tasks: automation runs (`run_automation_task`, `resume_automation_task`), scheduler `check_scheduled_automations`, AI functions (`ai/tasks.py`), publishing tasks (`tasks/wordpress_publishing.py`).
## Key Design Considerations
- Strong tenant isolation via middleware + filtered querysets.
- Automation relies on polling and Celery; frontend automation page polls every 5s during runs.
- Billing is authoritative in backend; frontend is read-only except initiating purchases/subscriptions.
## How Developers Should Work With This Module
- Trace user-visible flows by following router → page component → service call → backend viewset.
- When adding steps, ensure credit deductions and tenancy filters are applied in the corresponding backend service/viewset.
- Keep WP integration changes consistent with API key auth and `SiteIntegration` schema.