revamps docs complete
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
# Frontend Architecture
|
||||
|
||||
## Purpose
|
||||
Explain the frontend structure, routing, state management, providers, and module organization in the React/Vite app.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Entry: `frontend/src/main.tsx`
|
||||
- Root app/routing: `frontend/src/App.tsx`
|
||||
- State (Zustand stores): `frontend/src/store/*` (authStore, siteStore, billingStore, settingsStore, onboardingStore, columnVisibilityStore, pageSizeStore)
|
||||
- API layer: `frontend/src/api/*` and `frontend/src/services/api.ts`
|
||||
- Layout and components: `frontend/src/layout/*`, `frontend/src/components/*`
|
||||
- Pages: `frontend/src/pages/*` (modules and settings)
|
||||
- Config: `frontend/src/config/*`
|
||||
- Styles: `frontend/src/index.css`, `frontend/src/styles/igny8-colors.css`
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Provide SPA routing with protected routes and module guards.
|
||||
- Maintain global state for auth, site context, billing, settings, UI preferences via Zustand.
|
||||
- Lazy-load module pages to optimize initial load.
|
||||
- Wrap the app with providers for theming, toasts, header metrics, error boundary, and router.
|
||||
|
||||
## Detailed Behavior
|
||||
- Entry (`main.tsx`):
|
||||
- Imports global styles and vendor CSS (Swiper, Flatpickr).
|
||||
- Wraps the app with `ErrorBoundary`, `ThemeProvider`, `HeaderMetricsProvider`, `ToastProvider`, `BrowserRouter`, then renders `<App />` via React 18 `createRoot`.
|
||||
- Routing (`App.tsx`):
|
||||
- Uses `BrowserRouter` (in main) with `<Routes>`/`<Route>` inside App.
|
||||
- Public routes: `/signin`, `/signup`.
|
||||
- Protected routes wrapped by `ProtectedRoute` → `AppLayout`; `ModuleGuard` used per-module.
|
||||
- Default dashboard `/` loads `Dashboard/Home`.
|
||||
- Planner routes redirect `/planner` → `/planner/keywords`; writer routes redirect `/writer` → `/writer/tasks`.
|
||||
- Extensive lazy-loaded pages for Planner, Writer, Automation, Linker, Optimizer, Thinker (system), Billing, Admin, Settings, Sites, Help, Reference, Components, UI elements, etc.
|
||||
- `GlobalErrorDisplay` and `LoadingStateMonitor` mounted globally; `ScrollToTop` for navigation changes.
|
||||
- Auth refresh: on mount, if authenticated with token, calls `refreshUser`; on failure with missing credentials message, ignores; otherwise logs out.
|
||||
- State (Zustand examples):
|
||||
- `authStore`: persists user/token/refreshToken; `login`/`register` hit `/api/v1/auth/...`; enforces account and active plan presence; `refreshUser` fetches user from `/api/v1/auth/users/me/`; `refreshToken` hits `/api/v1/auth/refresh/`; logout clears all auth fields.
|
||||
- `siteStore`: stores current site/sector and list; used for context across modules.
|
||||
- `billingStore`, `settingsStore`, `onboardingStore`, `columnVisibilityStore`, `pageSizeStore`: manage billing data, settings flags, onboarding steps, table visibility, pagination sizes.
|
||||
- API layer:
|
||||
- `services/api.ts` provides `fetchAPI` helper for authenticated calls (uses token from auth store, handles JSON, throws on non-OK).
|
||||
- `api/*` modules define typed client calls per domain (auth, planner, writer, etc.).
|
||||
- Layout/components:
|
||||
- `AppLayout` wraps sidebar/header/content; `ModuleGuard` enforces module access flags; `ProtectedRoute` enforces auth.
|
||||
- UI utilities: toasts, error boundary, global loading monitor, scroll-to-top, etc.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- Frontend state shapes defined in Zustand stores (auth user, site context, billing info, settings).
|
||||
|
||||
## Execution Flow
|
||||
- App bootstrap → providers → App routes → ProtectedRoute checks auth → ModuleGuard checks module access → lazy-loaded pages fetch data via `api/*` using tokens from authStore → state updates via stores.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Auth store tokens used by fetchAPI for all modules.
|
||||
- Site store context influences planner/writer/automation calls.
|
||||
- Billing store interacts with billing endpoints; settings store influences UI/features; onboarding/table stores affect page rendering.
|
||||
|
||||
## State Transitions
|
||||
- Auth: login/register → set user/token; refresh → update tokens/user; logout clears.
|
||||
- Site context changes update current site/sector for downstream calls.
|
||||
- Billing/settings/onboarding/table state mutate via respective store actions.
|
||||
|
||||
## Error Handling
|
||||
- `GlobalErrorDisplay` shows errors; `LoadingStateMonitor` tracks loading; `ProtectedRoute` logs out on failed refresh.
|
||||
- `fetchAPI` throws on non-OK; authStore catches and surfaces messages; ModuleGuard/ProtectedRoute handle unauthorized access.
|
||||
|
||||
## Tenancy Rules
|
||||
- Enforced via tokens and site context; ModuleGuard and ProtectedRoute rely on backend responses (account/plan) and module flags.
|
||||
|
||||
## Billing Rules
|
||||
- Auth store enforces active plan on login; billing store/pages call billing endpoints for balances/transactions/purchases.
|
||||
|
||||
## Background Tasks / Schedulers
|
||||
- None on frontend; relies on backend/Celery for async work; uses Suspense for lazy loading.
|
||||
|
||||
## Key Design Considerations
|
||||
- Lazy-loaded routes minimize initial bundle.
|
||||
- Zustand persistence keeps auth/session across reloads.
|
||||
- Providers wrap app for theming, toasts, error boundary to improve UX stability.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- Add routes inside `App.tsx` under ProtectedRoute for authenticated pages; use ModuleGuard for module-gated pages.
|
||||
- Create new stores in `src/store` for shared state; use `fetchAPI` for authenticated requests.
|
||||
- Keep lazy loading for heavy pages and maintain Suspense fallbacks where needed.
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# Global UI Components and Providers
|
||||
|
||||
## Purpose
|
||||
Describe global layout, guards, and utility components/providers used throughout the frontend.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- App composition and routing: `frontend/src/App.tsx`
|
||||
- Entry/providers: `frontend/src/main.tsx`
|
||||
- Layout: `frontend/src/layout/AppLayout.tsx`, `frontend/src/layout/AppSidebar.tsx`, `frontend/src/layout/AppHeader.tsx` (and related layout files)
|
||||
- Guards: `frontend/src/components/auth/ProtectedRoute.tsx`, `frontend/src/components/common/ModuleGuard.tsx`
|
||||
- Global utilities: `frontend/src/components/common/ScrollToTop.tsx`, `frontend/src/components/common/GlobalErrorDisplay.tsx`, `frontend/src/components/common/LoadingStateMonitor.tsx`, `frontend/src/components/common/ErrorBoundary.tsx`
|
||||
- Providers: `frontend/src/context/ThemeContext.tsx`, `frontend/src/context/HeaderMetricsContext.tsx`, `frontend/src/components/ui/toast/ToastContainer.tsx`
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Wrap the app with error handling, theming, metrics, toasts, and routing.
|
||||
- Enforce authentication and module access at the route level.
|
||||
- Provide global UI behaviors (scroll reset, error banner, loading monitor).
|
||||
- Supply consistent layout (sidebar/header/content) for protected areas.
|
||||
|
||||
## Detailed Behavior
|
||||
- Providers (`main.tsx`):
|
||||
- `ErrorBoundary` wraps the entire app.
|
||||
- `ThemeProvider` supplies theme context.
|
||||
- `HeaderMetricsProvider` supplies header metrics context.
|
||||
- `ToastProvider` exposes toast notifications.
|
||||
- `BrowserRouter` provides routing; renders `<App />`.
|
||||
- Routing shell (`App.tsx`):
|
||||
- `GlobalErrorDisplay` renders global errors; `LoadingStateMonitor` tracks loading states.
|
||||
- `ScrollToTop` resets scroll on route changes.
|
||||
- Public routes: `/signin`, `/signup`.
|
||||
- Protected routes: wrapped in `ProtectedRoute` → `AppLayout`; `ModuleGuard` used per-module.
|
||||
- Lazy-loaded module pages inside routes; ModuleGuard enforces module access flags.
|
||||
- Guards:
|
||||
- `ProtectedRoute`: checks `useAuthStore` for authentication; redirects unauthenticated users to sign-in; logs out on failed refresh in App effect.
|
||||
- `ModuleGuard`: gates module pages based on module enable settings/permissions.
|
||||
- Layout:
|
||||
- `AppLayout` composes sidebar/header/content; `AppSidebar` uses auth store for user/nav; header components provide top-level actions and metrics.
|
||||
- Utilities:
|
||||
- `ScrollToTop` listens to route changes and scrolls to top.
|
||||
- `GlobalErrorDisplay` shows global error banners.
|
||||
- `LoadingStateMonitor` tracks loading indicators globally.
|
||||
- `ToastProvider` supplies toast UI primitives for notifications.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- Context values from theme, header metrics, toast providers; auth state from `authStore`; module enable settings from `settingsStore`.
|
||||
|
||||
## Execution Flow
|
||||
- App bootstrap wraps providers → routes render → ProtectedRoute checks auth → ModuleGuard checks module access → layout renders with sidebar/header → pages load lazily and fetch data.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Auth/module settings drive guards; toasts/errors/loading monitors are available to all pages; layout navigation links modules.
|
||||
|
||||
## Error Handling
|
||||
- `ErrorBoundary` catches render errors.
|
||||
- `GlobalErrorDisplay` surfaces application-level errors.
|
||||
- `ProtectedRoute` logs out on failed refresh in App effect; unauthorized users are redirected.
|
||||
|
||||
## Tenancy Rules
|
||||
- Enforced via backend auth and module enable settings; guards rely on auth/module settings to gate access.
|
||||
|
||||
## Billing Rules
|
||||
- None in UI components; billing info shown in pages that consume billing store/endpoints.
|
||||
|
||||
## Background Tasks / Schedulers
|
||||
- None; components react to store state and router changes.
|
||||
|
||||
## Key Design Considerations
|
||||
- Provider stack covers theme, metrics, toasts, error boundary, routing.
|
||||
- Guards ensure unauthorized access is blocked at the route level.
|
||||
- Global utilities avoid repeated boilerplate for scroll/error/loading behaviors.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- Add new protected pages under `ProtectedRoute` and wrap with `ModuleGuard` when module-scoped.
|
||||
- Use existing toast/error/loading utilities instead of duplicating.
|
||||
- Keep provider order consistent (ErrorBoundary → Theme/Header/Toast → Router → App).
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# State Management
|
||||
|
||||
## Purpose
|
||||
Describe how the frontend manages global state with Zustand stores, including authentication, site context, billing, and settings.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Auth store: `frontend/src/store/authStore.ts`
|
||||
- Site store: `frontend/src/store/siteStore.ts`
|
||||
- Billing store: `frontend/src/store/billingStore.ts`
|
||||
- Settings store: `frontend/src/store/settingsStore.ts`
|
||||
- Other UI/state stores: `frontend/src/store/onboardingStore.ts`, `columnVisibilityStore.ts`, `pageSizeStore.ts`, `settingsStore.ts`, etc.
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Persist authentication state (user, tokens), refresh sessions, and enforce account/plan presence.
|
||||
- Track the active site (and sector via sector store) across modules, with persistence and change events.
|
||||
- Fetch and cache billing balances/usage/limits.
|
||||
- Load and update account/module settings with coalesced fetches and persistence.
|
||||
|
||||
## Detailed Behavior
|
||||
- `authStore`:
|
||||
- Persists `user`, `token`, `refreshToken`, `isAuthenticated`, `loading`.
|
||||
- `login(email,password)`: POST `/api/v1/auth/login/`; stores tokens/user; errors mapped to PLAN_REQUIRED/ACCOUNT_REQUIRED/AUTH_FAILED; resets loading on error.
|
||||
- `register(data)`: POST `/api/v1/auth/register/`; stores tokens/user; resets loading on error.
|
||||
- `refreshToken()`: POST `/api/v1/auth/refresh/`; updates access token; attempts `refreshUser`; logs out on failure.
|
||||
- `refreshUser()`: GET `/api/v1/auth/users/me/`; requires account+plan; updates user or logs out on auth failure; clears loading guard.
|
||||
- `logout()`: clears all auth fields.
|
||||
- `siteStore`:
|
||||
- Persists `activeSite`; stores `loading`/`error`.
|
||||
- `setActiveSite(site)`: sets/persists site, dispatches `siteChanged` event, triggers sector store load for the site.
|
||||
- `loadActiveSite()`: fetches sites via `fetchSites`; picks prior site if still active, else first active; persists selection.
|
||||
- `refreshActiveSite()`: refreshes current site from server; reloads if inactive/missing.
|
||||
- `billingStore`:
|
||||
- Holds `balance`, `usageSummary`, `usageLimits`, `loading`/`error`, `lastUpdated`.
|
||||
- `loadBalance()`: calls `getCreditBalance`; keeps prior balance during retry; sets `lastUpdated`.
|
||||
- `loadUsageSummary(startDate?, endDate?)`: calls `getCreditUsageSummary`; updates summary.
|
||||
- `loadUsageLimits()`: calls `getCreditUsageLimits`; tolerates 404 by returning null; records errors otherwise.
|
||||
- `reset()`: clears billing state.
|
||||
- `settingsStore`:
|
||||
- Persists `accountSettings`, `moduleSettings`, `moduleEnableSettings`, `loading`/`error`.
|
||||
- Account settings: load all, load one, create/update with create/update endpoints; handles typed errors (not found vs validation).
|
||||
- Module settings: load/update per module; stores per-module map.
|
||||
- Module enable settings: caches for 60s, coalesces concurrent fetches; `isModuleEnabled` helper.
|
||||
- `reset()` clears settings state.
|
||||
- Other stores:
|
||||
- `onboardingStore`, `columnVisibilityStore`, `pageSizeStore` manage UI/onboarding/table preferences (see respective files for exact fields/actions).
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- Store state interfaces defined in each file (auth user shape, site, billing balance/usage, settings maps).
|
||||
|
||||
## Execution Flow
|
||||
- Components/hooks read/write state via `useXStore` hooks.
|
||||
- Auth flows call store actions, which perform fetches and update state; ProtectedRoute/ModuleGuard rely on auth and settings/module enable flags.
|
||||
- Site changes dispatch `siteChanged` for downstream listeners and trigger sector loading.
|
||||
- Billing/settings loads fetch data on demand and cache/persist where configured.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Auth tokens consumed by `fetchAPI` for all API calls.
|
||||
- Active site influences planner/writer/automation calls via query params/context.
|
||||
- Module enable settings influence `ModuleGuard`.
|
||||
- Billing data feeds billing pages and credit displays.
|
||||
|
||||
## State Transitions
|
||||
- Auth: unauthenticated → login/register → authenticated; refresh updates tokens/user; logout clears.
|
||||
- Site: load/refresh/set updates `activeSite` and notifies listeners.
|
||||
- Billing/settings: load/update actions mutate cached maps and loading/error flags.
|
||||
|
||||
## Error Handling
|
||||
- Auth store resets loading on all error paths; throws descriptive errors.
|
||||
- Billing store tolerates missing limits (404) and surfaces messages; balance retry preserves prior state.
|
||||
- Settings store differentiates not-found vs validation errors; stores messages in `error`.
|
||||
|
||||
## Tenancy Rules
|
||||
- Auth store requires account+plan; site store filters on accessible sites; billing/settings calls use authenticated endpoints tied to the user’s account.
|
||||
|
||||
## Billing Rules
|
||||
- Enforced via backend; billing store reads balances/usage/limits and does not mutate credits.
|
||||
|
||||
## Background Tasks / Schedulers
|
||||
- None; all store actions are user-driven fetches with immediate state updates.
|
||||
|
||||
## Key Design Considerations
|
||||
- Zustand `persist` used for auth/site/settings to survive reloads.
|
||||
- Guarded loading flags and error handling prevent stuck states.
|
||||
- Site changes broadcast events for dependent components/stores.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- Use existing store actions for auth/site/billing/settings instead of duplicating fetch logic.
|
||||
- When adding new shared state, create a dedicated store in `src/store` and persist only needed slices.
|
||||
- Keep error/reset semantics consistent (always clear loading on failure).
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# Account Page (Account Settings)
|
||||
|
||||
## Purpose
|
||||
Provide a full account-level settings form for name, slug (read-only), billing contact email, billing address, and tax ID. Acts as the frontend surface for `getAccountSettings`/`updateAccountSettings` and reflects saved tenant metadata.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Page component: `frontend/src/pages/account/AccountSettingsPage.tsx`
|
||||
- API client: `frontend/src/services/billing.api` (`getAccountSettings`, `updateAccountSettings`, `AccountSettings` type)
|
||||
- UI primitives: `frontend/src/components/ui/card`
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Fetch current account settings on load and bind them into a local form.
|
||||
- Allow updating account display name, billing contact email, billing address fields, and tax/VAT ID.
|
||||
- Keep account slug immutable/read-only while exposing it for reference.
|
||||
- Surface success/error feedback inline.
|
||||
|
||||
## Detailed Behavior
|
||||
- On mount: calls `getAccountSettings()`; populates `settings` and `formData` with server values.
|
||||
- Form fields: `name`, `billing_email`, `billing_address_line1/2`, `billing_city`, `billing_state`, `billing_postal_code`, `billing_country`, `tax_id`; `slug` shown read-only from `settings.slug`.
|
||||
- Submit: `handleSubmit` -> `updateAccountSettings(formData)`; on success shows success banner then reloads settings; on failure shows error banner.
|
||||
- Loading states: full-page spinner before data load; button shows saving state.
|
||||
- Errors surfaced from caught exceptions (`err.message`) with console logging.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- Account settings DTO returned by `getAccountSettings` with fields listed above plus `slug`.
|
||||
|
||||
## Execution Flow
|
||||
- `useEffect` → `loadSettings` → `getAccountSettings` → set local state.
|
||||
- User edits controlled inputs → `handleSubmit` → `updateAccountSettings` → reload via `loadSettings`.
|
||||
- All network ops are direct REST calls via `billing.api`.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Shares account identity with billing pages (same `billing.api` source). Updated billing email/address is used by invoicing flows.
|
||||
|
||||
## State Transitions (if applicable)
|
||||
- View state: `loading` → loaded; `saving` toggles during submit. Success/error banners reflect last operation outcome.
|
||||
|
||||
## Error Handling
|
||||
- Catches fetch/update errors; shows inline red banner; logs to console. No retries.
|
||||
|
||||
## Tenancy Rules
|
||||
- Relies on backend to scope `getAccountSettings`/`updateAccountSettings` to the authenticated user’s account; no client-side tenancy logic beyond using the current auth token.
|
||||
|
||||
## Billing Rules (if applicable)
|
||||
- Billing contact and address collected here feed invoice generation; no pricing logic on this page.
|
||||
|
||||
## Background Tasks / Schedulers (if applicable)
|
||||
- None.
|
||||
|
||||
## Key Design Considerations
|
||||
- Slug is immutable to prevent accidental tenant identifier changes.
|
||||
- Form is fully controlled; reload after save ensures UI mirrors server truth.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- Add new account-level fields by extending `AccountSettings` in `billing.api`, wiring controlled inputs, and persisting via `updateAccountSettings`.
|
||||
- Keep slug read-only; any slug mutation must be handled server-side with explicit UX.
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# Billing Page (Plans & Billing Dashboard)
|
||||
|
||||
## Purpose
|
||||
Present a consolidated billing dashboard with tabs for credit balance, plans, invoices, payments, and available payment methods. Acts as the UI client for billing endpoints (balance, invoices, payments, credit packages, payment methods, plans, subscriptions).
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Page: `frontend/src/pages/account/AccountBillingPage.tsx`
|
||||
- Billing API client: `frontend/src/services/billing.api` (`getInvoices`, `getPayments`, `getCreditBalance`, `getCreditPackages`, `getAvailablePaymentMethods`, `downloadInvoicePDF`, `getPlans`, `getSubscriptions`)
|
||||
- UI: `frontend/src/components/ui/card`, `frontend/src/components/billing/BillingRecentTransactions`, `frontend/src/components/ui/pricing-table/PricingTable`
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Fetch and render account-scoped billing data (credits, invoices, payments, packages, payment methods, plans, subscriptions).
|
||||
- Provide tabbed navigation across overview, plans, invoices, payments, methods.
|
||||
- Allow invoice PDF download.
|
||||
|
||||
## Detailed Behavior
|
||||
- On mount: `loadData()` runs seven parallel calls for balance, invoices, payments, packages, payment methods, plans, subscriptions. Results populate local state; errors render a banner.
|
||||
- Overview tab: shows four metric cards (balance, monthly allocation, used this month, plan status) from `creditBalance`.
|
||||
- Plans tab: displays `PricingTable` with static plan catalog (Starter/Growth/Scale) plus dynamic plans from API; shows current subscription chips if present.
|
||||
- Invoices tab: lists invoices with amount/currency/status/date; supports PDF download via `downloadInvoicePDF(invoiceId)` using blob download flow.
|
||||
- Payments tab: lists payments with status badges derived from status-to-style map (paid/succeeded/completed/pending/pending_approval/processing/failed/refunded/cancelled/void/uncollectible).
|
||||
- Methods tab: lists available payment methods from `getAvailablePaymentMethods`.
|
||||
- “Purchase Credits” button links to `/account/purchase-credits`.
|
||||
- Loading: full-page spinner until `loadData` completes.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- `Invoice`, `Payment`, `CreditBalance`, `CreditPackage`, `PaymentMethod`, `Plan`, `Subscription` DTOs from `billing.api`.
|
||||
|
||||
## Execution Flow
|
||||
- `useEffect` → `loadData` (Promise.all) → set state.
|
||||
- Tab click sets `activeTab`; conditional renders per tab.
|
||||
- Invoice download: fetch blob → create object URL → anchor click → revoke URL.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Reads auth user from `useAuthStore` for contextual display; all billing data is backend-scoped to account.
|
||||
- Plans tab uses static catalog for marketing copy but still shows live plan/subscription data from API.
|
||||
|
||||
## State Transitions
|
||||
- `activeTab` switches UI sections; `loading` gates initial fetch; error banner shows on fetch failure.
|
||||
- Status badges reflect backend payment/invoice statuses only; no client mutation flows here.
|
||||
|
||||
## Error Handling
|
||||
- Catches fetch errors → sets `error` message → red banner.
|
||||
- Invoice download failure shows `alert`.
|
||||
|
||||
## Tenancy Rules
|
||||
- Relies on backend scoping through authenticated requests; no client-side account selection.
|
||||
|
||||
## Billing Rules (if applicable)
|
||||
- Read-only view of credits, invoices, payments, and plans; purchases/plan changes are triggered elsewhere (Purchase Credits page or separate plan change flows).
|
||||
|
||||
## Background Tasks / Schedulers (if applicable)
|
||||
- None client-side; periodic refresh is not scheduled (one-time load per mount).
|
||||
|
||||
## Key Design Considerations
|
||||
- Minimizes throttling risk by batching fetches but does not paginate invoices/payments on the client; relies on API pagination responses.
|
||||
- Uses static plan catalog for UX but shows actual subscriptions from API to avoid mismatch with assigned plan.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- Add or reorder tabs by extending the `TabType` union and tab config array.
|
||||
- When adding new billing surfaces (e.g., disputes/refunds), mirror the pattern: fetch via `billing.api`, guard with `loading/error`, render tab content.
|
||||
- Keep invoice download flow consistent (blob + object URL) for cross-browser support.
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# Payment Methods Page
|
||||
|
||||
## Purpose
|
||||
Display available payment methods for the tenant and support selection for purchases/subscriptions. Methods originate from backend billing configs and are reused across plan changes and credit purchases.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Consolidated flows: `frontend/src/pages/account/PlansAndBillingPage.tsx` (tab `payment-methods`)
|
||||
- Purchase credits: `frontend/src/pages/account/PurchaseCreditsPage.tsx` (method selection + manual payment proof)
|
||||
- API: `frontend/src/services/billing.api` (`getAvailablePaymentMethods`, `createPaymentMethod`, `deletePaymentMethod`, `setDefaultPaymentMethod`)
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Fetch account-scoped payment methods (bank transfer, local wallet, manual/other).
|
||||
- Allow choosing a default method for purchases/subscriptions.
|
||||
- Provide instructions/details (bank or wallet) for manual/offline flows.
|
||||
|
||||
## Detailed Behavior
|
||||
- PlansAndBillingPage:
|
||||
- On load, calls `getAvailablePaymentMethods()` with other billing calls; filters out disabled methods (`is_enabled === false`).
|
||||
- Chooses preferred method for selection: bank_transfer, then manual, else default flag, else first item.
|
||||
- Renders payment-methods tab listing methods, default flag, instructions; supports create/delete/default actions via `createPaymentMethod`, `deletePaymentMethod`, `setDefaultPaymentMethod`.
|
||||
- Selection state (`selectedPaymentMethod`) is reused when purchasing packages or creating subscriptions.
|
||||
- PurchaseCreditsPage:
|
||||
- Fetches methods and auto-selects bank_transfer, then manual, else first.
|
||||
- For bank/local/manual methods, shows instructions and bank/wallet details and collects `transaction_reference` + `notes` when the payment is manual/offline.
|
||||
- Stripe/PayPal placeholders show “integration pending”.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- `PaymentMethod` DTO: `id`, `type` (`bank_transfer`, `local_wallet`, `manual`, `stripe`, `paypal`), `display_name`, `instructions`, optional `bank_details`/`wallet_details`, `is_default`, `is_enabled`.
|
||||
|
||||
## Execution Flow
|
||||
- Load methods → set local `paymentMethods` → derive `selectedPaymentMethod`.
|
||||
- User selects method → stored in component state; used by purchase/subscription handlers.
|
||||
- Optional CRUD (create/delete/default) triggered in `PlansAndBillingPage` tab using billing API helpers.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Used by credit purchase (`purchaseCreditPackage`) and subscription updates (`createSubscription`, `cancelSubscription`) within `PlansAndBillingPage`.
|
||||
|
||||
## State Transitions
|
||||
- Local selection state only; backend default flag can be updated via `setDefaultPaymentMethod`.
|
||||
|
||||
## Error Handling
|
||||
- Errors surface via toast/banner in `PlansAndBillingPage`; inline error message in `PurchaseCreditsPage` for missing selections or failed calls.
|
||||
|
||||
## Tenancy Rules
|
||||
- All calls are account-scoped by backend auth; no client multi-tenant switching.
|
||||
|
||||
## Billing Rules (if applicable)
|
||||
- Selected method is passed to credit purchase and subscription creation; manual methods require proof submission (transaction reference) and remain pending approval server-side.
|
||||
|
||||
## Background Tasks / Schedulers (if applicable)
|
||||
- None on client.
|
||||
|
||||
## Key Design Considerations
|
||||
- Prefers offline-safe methods (bank/manual) to avoid blocking when card gateways are unavailable.
|
||||
- Keeps selection sticky within the session to reduce user friction across tabs.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- To add a new gateway type, extend `PaymentMethod` type, update selection logic, and render gateway-specific instructions or redirection flows.
|
||||
- Keep manual/offline instructions editable via backend configs; surface them read-only in the UI.
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# Subscription Page (Plans & Upgrades)
|
||||
|
||||
## Purpose
|
||||
Let tenants view current subscription, browse available plans, start or cancel subscriptions, and align payment method selection with plan changes. Uses the same billing data as the Billing dashboard but focuses on plan lifecycle.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Page: `frontend/src/pages/account/PlansAndBillingPage.tsx` (tabs `plan` and `upgrade`)
|
||||
- API: `frontend/src/services/billing.api` (`getPlans`, `getSubscriptions`, `createSubscription`, `cancelSubscription`)
|
||||
- Payment selection (shared): same page via `getAvailablePaymentMethods`
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Fetch active plans and the tenant’s current subscription.
|
||||
- Enable plan change (create/update subscription) gated by payment method selection.
|
||||
- Allow cancellation of the active subscription.
|
||||
|
||||
## Detailed Behavior
|
||||
- Initial load (`loadData`):
|
||||
- Fetches credit balance, packages, invoices, payments, payment methods, plans, subscriptions (with retry/backoff for 429).
|
||||
- Filters plans to active ones; excludes Enterprise for non `aws-admin` accounts but re-injects the account’s assigned plan so UI always reflects truth.
|
||||
- Ensures there is at least one subscription entry; if none returned, synthesizes one from `user.account.plan`.
|
||||
- Plan selection:
|
||||
- Requires a chosen payment method if any exist.
|
||||
- `handleSelectPlan(planId)` → `createSubscription({ plan_id, payment_method })` → reload data.
|
||||
- Cancellation:
|
||||
- `handleCancelSubscription` calls `cancelSubscription(currentSubscription.id)` and refreshes state.
|
||||
- Tabs:
|
||||
- `plan` shows current subscription summary.
|
||||
- `upgrade` lists available plans (filtered) with select buttons; highlights defaults via UI styling.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- `Plan`: name, slug, price, billing cycle, features, `is_active`.
|
||||
- `Subscription`: `id`, `plan`, `status`.
|
||||
|
||||
## Execution Flow
|
||||
- `useEffect` → `loadData` (controlled sequence + throttling gaps) → set plans/subscriptions/paymentMethods.
|
||||
- Select plan → API call → toast → reload.
|
||||
- Cancel → API call → toast → reload.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Shares payment method selection with credit purchase; uses `useAuthStore` for account plan fallbacks.
|
||||
|
||||
## State Transitions
|
||||
- `activeTab` controls view; `planLoadingId`/`purchaseLoadingId` track in-flight plan or package actions.
|
||||
- Subscription status rendered from backend; cancellation triggers status change server-side.
|
||||
|
||||
## Error Handling
|
||||
- Central `handleBillingError` surfaces message + toast.
|
||||
- Throttle (429) handled with delayed retry for subscriptions; errors suppressed if retry fails to keep page usable.
|
||||
|
||||
## Tenancy Rules
|
||||
- All subscription APIs are account-scoped by the backend; client does not switch tenants.
|
||||
|
||||
## Billing Rules (if applicable)
|
||||
- Requires a payment method before subscription create/update.
|
||||
- Enterprise plans hidden for non-admin tenants to prevent accidental selection.
|
||||
|
||||
## Background Tasks / Schedulers (if applicable)
|
||||
- None client-side; no polling beyond initial load.
|
||||
|
||||
## Key Design Considerations
|
||||
- Guardrails to avoid showing empty state when account already has a plan (synthesizes subscription from account plan).
|
||||
- Prefers bank/manual methods when selecting plan for safer checkout in absence of Stripe/PayPal integrations.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- To expose new plan attributes, extend plan cards in the upgrade tab and ensure `Plan` type carries those fields.
|
||||
- Keep enterprise-plan visibility rules aligned with backend authorization; avoid client-side-only blocking for sensitive plans.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# Automation Components
|
||||
|
||||
## Purpose
|
||||
Describe the reusable UI components that compose the automation dashboard: stage cards, current processing card, run history, activity log, and configuration modal. These components visualize pipeline state, history, and settings sourced from automation services.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Stage cards & layout: `frontend/src/pages/Automation/AutomationPage.tsx` (renders stage cards from `STAGE_CONFIG`)
|
||||
- Current run card: `frontend/src/components/Automation/CurrentProcessingCard.tsx`
|
||||
- Activity log: `frontend/src/components/Automation/ActivityLog.tsx`
|
||||
- Run history: `frontend/src/components/Automation/RunHistory.tsx`
|
||||
- Config modal: `frontend/src/components/Automation/ConfigModal.tsx`
|
||||
- Shared UI: `frontend/src/components/common/{ComponentCard,PageMeta,DebugSiteSelector}`, `frontend/src/components/dashboard/EnhancedMetricCard`
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Stage cards: show each of the 7 pipeline stages with icon/color/status derived from pipeline overview.
|
||||
- CurrentProcessingCard: surface active run details, stage name, status, percent, timestamps, and controls (Pause/Resume).
|
||||
- ActivityLog: list recent automation events (from run log feed).
|
||||
- RunHistory: show prior runs with status and timestamps.
|
||||
- ConfigModal: edit and persist automation configuration per site.
|
||||
|
||||
## Detailed Behavior
|
||||
- Stage Cards:
|
||||
- Built from `STAGE_CONFIG` array (keywords→clusters, clusters→ideas, ideas→tasks, tasks→content, content→image prompts, image prompts→images, manual review).
|
||||
- Status/progress comes from `pipelineOverview.stages` provided by `automationService.getPipelineOverview`.
|
||||
- CurrentProcessingCard:
|
||||
- Receives `currentRun` and shows status; displays pause/resume buttons wired to page handlers that call `automationService.pause/resume`.
|
||||
- Hidden when no current run; toggled by `showProcessingCard`.
|
||||
- RunHistory:
|
||||
- Takes run list (from `automationService.getCurrentRun` payload history) and renders chronological entries.
|
||||
- ActivityLog:
|
||||
- Displays textual log entries for the active run; consumes run log data supplied by the page.
|
||||
- ConfigModal:
|
||||
- Opens from page button; on save calls `automationService.updateConfig(activeSite.id, newConfig)`; merges into local config and refreshes pipeline/metrics.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- `AutomationRun` (id, status, stage, progress, started_at/ended_at).
|
||||
- `PipelineStage` array with stage identifiers, names, progress.
|
||||
- `AutomationConfig` fields shown in modal (intervals/gates/etc., defined server-side).
|
||||
|
||||
## Execution Flow
|
||||
- Page loads run + pipeline → passes data into stage cards, processing card, history, activity log.
|
||||
- User opens ConfigModal → submit triggers updateConfig → page reloads pipeline/metrics/run to reflect new settings.
|
||||
- Pause/Resume buttons on CurrentProcessingCard call page handlers, which in turn call automationService.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Components depend on site context from `useSiteStore` and data from automationService; no direct planner/writer calls (metrics happen in page).
|
||||
|
||||
## State Transitions
|
||||
- Components are pure renderers; state (visibility, selected config) managed by `AutomationPage`.
|
||||
|
||||
## Error Handling
|
||||
- Errors in save/pause/resume are surfaced by the page via toasts; components render based on provided props.
|
||||
|
||||
## Tenancy Rules
|
||||
- All data passed in is already scoped to `activeSite`; components do not alter scoping.
|
||||
|
||||
## Billing Rules (if applicable)
|
||||
- None inside components; Run Now credit gating handled at page level.
|
||||
|
||||
## Background Tasks / Schedulers (if applicable)
|
||||
- None; updates driven by page polling interval.
|
||||
|
||||
## Key Design Considerations
|
||||
- Separation of concerns: components stay presentational; network calls remain in page.
|
||||
- Stage cards use color/icon metadata for fast visual scanning of pipeline status.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- Add new stages by extending `STAGE_CONFIG` and ensuring pipeline overview includes the new stage id/status.
|
||||
- Extend ConfigModal fields in sync with backend `AutomationConfig`; persist via automationService.
|
||||
- Keep CurrentProcessingCard controls minimal; any new action should call automationService and refresh run/pipeline afterward.
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# Automation Page (AI Automation Pipeline Dashboard)
|
||||
|
||||
## Purpose
|
||||
Provide a site-scoped dashboard to configure, run, pause, resume, and monitor the 7-stage automation pipeline. Surfaces pipeline overview, current run status, metrics, history, configuration modal, and credit sufficiency checks.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Primary page: `frontend/src/pages/Automation/AutomationPage.tsx`
|
||||
- Service: `frontend/src/services/automationService` (config, current run, estimate, pipeline overview, runNow, pause, resume, publishWithoutReview)
|
||||
- Metrics sources: `frontend/src/services/api` (`fetchKeywords`, `fetchClusters`, `fetchContentIdeas`, `fetchTasks`, `fetchContent`, `fetchContentImages`)
|
||||
- UI components: `frontend/src/components/Automation/{ActivityLog,ConfigModal,RunHistory,CurrentProcessingCard}`, `frontend/src/components/dashboard/EnhancedMetricCard`, `frontend/src/components/common/ComponentCard`, `frontend/src/components/common/PageMeta`, `frontend/src/components/common/DebugSiteSelector`
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Load automation config, current run, credit estimate, and pipeline overview for the active site.
|
||||
- Poll current run and pipeline status while running/paused; refresh metrics regularly during runs.
|
||||
- Provide controls: Run Now, Pause, Resume, Save Config, Publish Without Review.
|
||||
- Show per-stage cards, current processing card, run history, and activity log.
|
||||
|
||||
## Detailed Behavior
|
||||
- Site binding: requires `useSiteStore.activeSite`; without it, page shows a “select a site” message.
|
||||
- Initial load (`loadData`): parallel calls to `getConfig`, `getCurrentRun`, `estimate`, `getPipelineOverview` plus low-level metrics (keywords/clusters/ideas/tasks/content/images counts) per site_id.
|
||||
- Polling: 5s interval; if run status is `running`/`paused`, refresh run, pipeline, and metrics; otherwise refresh pipeline only.
|
||||
- Metrics: counts for keywords (total/new/mapped), clusters (total/new/mapped), ideas (total/new/queued/completed), tasks (total), content (total/draft/review/published), images (total/pending).
|
||||
- Stage cards: derived from `STAGE_CONFIG` array representing 7 pipeline stages including manual review gate.
|
||||
- Actions:
|
||||
- Run Now: checks credit sufficiency from `estimate`; blocks if insufficient.
|
||||
- Pause/Resume: call automationService with site + run_id, then refresh run/pipeline/metrics.
|
||||
- Save Config: persists partial config, updates local state, reloads pipeline/metrics/run.
|
||||
- Publish Without Review: calls `publishWithoutReview` with confirmation prompt, then reloads.
|
||||
- UI states: `loading` spinner until initial fetch; `showProcessingCard` toggled on when a run exists.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- `AutomationConfig`: site-level automation settings (intervals, gates, etc.).
|
||||
- `AutomationRun`: run_id, status (`running`, `paused`, etc.), stage info.
|
||||
- `PipelineStage`: stage list with status/progress.
|
||||
- Metrics DTOs from planner/writer/image endpoints (`count` fields only).
|
||||
|
||||
## Execution Flow
|
||||
- `useEffect` with site dependency → `loadData`.
|
||||
- Interval polling while active runs → `loadCurrentRun`, `loadPipelineOverview`, `loadMetrics`.
|
||||
- User actions dispatch to automationService; toasts for success/error; follow-up refreshes.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Pulls planner/writer/image counts to present authoritative pipeline context.
|
||||
- Uses `useSiteStore` for tenant/site scoping; credit checks rely on billing estimate API.
|
||||
|
||||
## State Transitions
|
||||
- `currentRun.status` drives polling and control availability.
|
||||
- `showProcessingCard` turns on when a run exists.
|
||||
- `estimate.sufficient` gates Run Now action.
|
||||
|
||||
## Error Handling
|
||||
- Toast-based error reporting; fetch failures log to console but keep page usable.
|
||||
- Metrics fetch wrapped in try/catch; failure degrades to missing metrics without blocking the rest.
|
||||
|
||||
## Tenancy Rules
|
||||
- All automation service calls require `activeSite.id`; backend enforces account/site scoping. No client override for other tenants.
|
||||
|
||||
## Billing Rules (if applicable)
|
||||
- Run Now is blocked when `estimate.sufficient` is false; shows required vs current credits.
|
||||
|
||||
## Background Tasks / Schedulers (if applicable)
|
||||
- Client-side polling (5s) during active runs; no background scheduling beyond that.
|
||||
|
||||
## Key Design Considerations
|
||||
- Polling keeps UI aligned with long-running Celery pipeline states.
|
||||
- Credit gate prevents user-initiated runs that would immediately fail server-side.
|
||||
- Metrics are read-only mirrors of backend aggregates to align UI with planner/writer state.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- When adding new stages, extend `STAGE_CONFIG` and ensure backend pipeline overview includes them.
|
||||
- Keep polling interval modest; if adding heavier metrics, consider staggering fetches to avoid rate limits.
|
||||
- Wire new config fields through `AutomationConfig` type, `ConfigModal`, and `updateConfig` payload.
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# Site Dashboard
|
||||
|
||||
## Purpose
|
||||
Provide a per-site overview showing basic site info, stats (pages/content/integrations/deployments), and quick actions for navigation. Serves as the landing view for a specific site id.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Page: `frontend/src/pages/Sites/Dashboard.tsx`
|
||||
- API: `frontend/src/services/api` (`fetchAPI` for `/v1/auth/sites/{id}/`; `fetchSiteStats` placeholder)
|
||||
- UI: `frontend/src/components/common/{PageMeta,PageHeader,ComponentCard}`, `frontend/src/components/dashboard/EnhancedMetricCard`, `frontend/src/components/sites/SiteProgressWidget`, `frontend/src/components/ui/{card,button}`
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Load a single site’s record (name/slug/type/hosting/domain/status) and display a card-based dashboard.
|
||||
- Show metric cards for pages, integrations, deployments, and content counts (placeholder stats until backend endpoint exists).
|
||||
- Provide quick actions to manage pages, sync, publish, or open settings.
|
||||
|
||||
## Detailed Behavior
|
||||
- Routing: expects `:id` param; uses `useParams` and `fetchAPI(/v1/auth/sites/{id}/)` to load site.
|
||||
- Stats: `fetchSiteStats` currently returns placeholder structure (zeros); TODO noted to back with a real endpoint.
|
||||
- If site not found: shows “Site not found” with Back to Sites button.
|
||||
- Metric cards (EnhancedMetricCard) link to pages list, published filter, draft filter, integrations tab, deployments preview, and content list.
|
||||
- Quick actions: buttons for Manage Pages, View Integrations, View Content, Deployments (navigations).
|
||||
- Header shows site name, slug, type, hosting, optional domain, and Settings button linking to `/sites/{id}/settings`.
|
||||
- Loading state: spinner until data fetch completes.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- Site DTO: `id`, `name`, `slug`, `site_type`, `hosting_type`, `status`, `is_active`, `domain`.
|
||||
- Stats DTO (placeholder): counts for pages/content/integrations/deployments/views/visitors.
|
||||
|
||||
## Execution Flow
|
||||
- `useEffect` on `siteId` → `loadSiteData` (Promise.all for site + stats) → set `site` + `stats`.
|
||||
- Renders cards and actions with derived links.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Integrations quick action routes to Site Settings integrations tab.
|
||||
- Content and pages links route to module pages that rely on planner/writer data scoped by site.
|
||||
|
||||
## State Transitions
|
||||
- `loading` gates initial fetch; absent site shows fallback card.
|
||||
|
||||
## Error Handling
|
||||
- Errors during fetch show toast (`Failed to load site data`) and stop loading spinner.
|
||||
|
||||
## Tenancy Rules
|
||||
- Site fetch is account-scoped server-side; client only supplies the site id from the router.
|
||||
|
||||
## Billing Rules (if applicable)
|
||||
- None on this page.
|
||||
|
||||
## Background Tasks / Schedulers (if applicable)
|
||||
- None; no polling.
|
||||
|
||||
## Key Design Considerations
|
||||
- Uses placeholder stats until backend supplies real site analytics; structure prepared for drop-in replacement.
|
||||
- Quick navigation shortcuts reduce hops for site-level operations.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- Replace `fetchSiteStats` with a real endpoint and map returned fields into `statCards`.
|
||||
- Add new quick actions by extending the ComponentCard grid with navigation handlers.
|
||||
- Keep links consistent with router paths in `App.tsx` to avoid broken navigation.
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
# Site Flow (Listing & Management)
|
||||
|
||||
## Purpose
|
||||
Provide the tenant-facing list and management surface for all sites, including creation, navigation to settings/integrations, viewing, editing, and deletion. This is the primary entry point before drilling into site dashboard or settings.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Page: `frontend/src/pages/Sites/Manage.tsx` (titled “Site Management”)
|
||||
- API: `frontend/src/services/api` (`fetchAPI` for sites collection and integration checks)
|
||||
- UI: `frontend/src/components/ui/{card,button,badge}`, `frontend/src/components/sites/SiteTypeBadge`, `frontend/src/components/ui/badge/Badge`
|
||||
|
||||
## High-Level Responsibilities
|
||||
- List all account sites with status, type, hosting, and integration hints.
|
||||
- Offer actions per site: view, edit, settings, delete, manage WordPress integration.
|
||||
- Provide entry point for creating new sites (routes to builder).
|
||||
|
||||
## Detailed Behavior
|
||||
- On mount: `loadSites()` → GET `/v1/auth/sites/`; if hosting_type is `wordpress`, performs an additional call to `/v1/integration/integrations/?site={id}&platform=wordpress` to flag `has_wordpress_integration`.
|
||||
- Renders grid of cards:
|
||||
- Shows name, slug, active badge, hosting badge, site type, optional WP integration button (“Connect WordPress” / “Manage Integration”).
|
||||
- Footer actions: View (`/sites/{id}`), Edit (`/sites/{id}/edit`), Settings (`/sites/{id}/settings`), Delete (DELETE `/v1/auth/sites/{id}/` after confirm).
|
||||
- Empty state: if no sites, shows CTA to create first site (`/sites/builder`).
|
||||
- Create button in header also routes to `/sites/builder`.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- Site list DTO: id, name, slug, site_type, hosting_type, status, is_active, page_count, integration_count.
|
||||
- Integration probe response: `results` length indicates WP connection presence.
|
||||
|
||||
## Execution Flow
|
||||
- `useEffect` → `loadSites` → set `sites`.
|
||||
- Per-site integration check executed inside `Promise.all` when hosting_type is `wordpress`.
|
||||
- Action buttons call navigation or delete; delete triggers reload.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Integrations tab reachable via settings link; integration existence probed via integration module API.
|
||||
- Builder route (`/sites/builder`) ties into site creation flow (outside this component).
|
||||
|
||||
## State Transitions
|
||||
- `loading` gates initial render; after deletion, reload resets state.
|
||||
- WP integration flag stored per site for button labeling.
|
||||
|
||||
## Error Handling
|
||||
- Load errors show toast (`Failed to load sites`); delete errors show toast.
|
||||
- Integration probe failures fall back to `has_wordpress_integration: false` without blocking list.
|
||||
|
||||
## Tenancy Rules
|
||||
- Backend scopes `/v1/auth/sites/` to current account; page does not switch tenants.
|
||||
|
||||
## Billing Rules (if applicable)
|
||||
- None on this page; plan limits enforced server-side when creating/managing sites.
|
||||
|
||||
## Background Tasks / Schedulers (if applicable)
|
||||
- None; no polling.
|
||||
|
||||
## Key Design Considerations
|
||||
- Integration probe is conditional to reduce extra calls for non-WordPress hosting.
|
||||
- Delete confirmation prevents accidental site removal.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- When adding new hosting types or platforms, adjust integration probe logic and `SiteTypeBadge`.
|
||||
- Keep routes aligned with `App.tsx`; ensure permissions enforced server-side for edit/delete.
|
||||
- If adding pagination/filtering, wire through `fetchAPI` params and preserve integration detection per page.
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# Site Settings Page
|
||||
|
||||
## Purpose
|
||||
Advanced site management surface to edit site metadata, SEO fields, industry/sector selection, activation, and WordPress integration. Supports site switching, tabbed sections, and content-type syncing for WP.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Page: `frontend/src/pages/Sites/Settings.tsx`
|
||||
- APIs: `frontend/src/services/api` (`fetchAPI`, `fetchSites`, `fetchIndustries`, dynamic imports for `fetchAccountSetting`, `fetchSiteSectors`), `frontend/src/services/integration.api` (`integrationApi.getWordPressIntegration`)
|
||||
- UI: `frontend/src/components/common/{PageMeta,PageHeader}`, `frontend/src/components/ui/{card,button,badge}`, `frontend/src/components/form/{Label,SelectDropdown,Checkbox,TextArea}`, `frontend/src/components/ui/dropdown/{Dropdown,DropdownItem}`, `frontend/src/components/sites/WordPressIntegrationForm`
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Load a specific site by id and allow editing of general fields (name, slug, URL, type, hosting, active flag).
|
||||
- Manage SEO metadata (meta/OG/schema fields) per site.
|
||||
- Select industry and sectors for the site; load available industries and current sector assignments.
|
||||
- Manage WordPress integration (fetch existing integration, display form, load content types when tab active).
|
||||
- Provide site switcher dropdown for quickly navigating between active sites.
|
||||
|
||||
## Detailed Behavior
|
||||
- Routing: uses `:id` param; optional `tab` query (`general`, `integrations`, `content-types`) controls active tab.
|
||||
- Initial loads:
|
||||
- `loadSite` → GET `/v1/auth/sites/{id}/`; seeds formData with site fields plus SEO metadata (from `seo_metadata` or `metadata`).
|
||||
- `loadIntegrations` → `integrationApi.getWordPressIntegration(siteId)`; ignores missing integration.
|
||||
- `loadIndustries` → fetches industries (and sectors) for selection.
|
||||
- `loadSites` → fetches active sites for selector; `loadUserPreferences` → account setting `user_preferences` (industry/sector defaults).
|
||||
- When site + industries loaded → `loadSiteSectors` to map sector slugs to selections.
|
||||
- Tabs:
|
||||
- General: edits site core fields and SEO fields; save handler persists via `fetchAPI` PATCH/PUT (not fully shown in snippet but formData bound for submission).
|
||||
- Integrations: shows WordPress integration form, uses `integrationApi` to fetch/update connection; `integrationLoading` guards state.
|
||||
- Content-types: when tab active and WP integration exists, calls `loadContentTypes` to fetch available structures from WP.
|
||||
- Industry/Sector selection:
|
||||
- Industries from backend; sectors filtered by selected industry; selected sector slugs stored in state.
|
||||
- `loadSiteSectors` pulls current site sectors; tries to infer industry from sectors if not set.
|
||||
- Site switcher: dropdown using `fetchSites` results; navigates to new site settings route preserving tab query.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- Site DTO: id, name, slug, domain/url, site_type, hosting_type, is_active, industry_slug, seo_metadata fields.
|
||||
- Industry DTO: slug, name, sectors[] (each sector has slug/name).
|
||||
- WordPress integration DTO (`SiteIntegration`): platform, credentials/config, status (from `integration.api`).
|
||||
|
||||
## Execution Flow
|
||||
- `useEffect` on siteId → clear integration/content types → load site, integration, industries.
|
||||
- `useEffect` on activeTab & integration → load content types when needed.
|
||||
- `useEffect` on site+industries → load site sectors.
|
||||
- Dropdown selection → navigate to other site settings URL; closes selector.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Integration tab depends on integration service; content-types fetch hits integration endpoints.
|
||||
- Sector selection aligns with planner/writer scoping by site/sector.
|
||||
|
||||
## State Transitions
|
||||
- `activeTab` from query or state; `loading`, `saving`, `integrationLoading`, `sitesLoading` gate respective sections.
|
||||
- Form data is controlled; when site changes, state resets.
|
||||
|
||||
## Error Handling
|
||||
- Toast errors for site load failure and integration load; silent handling for user preference load failures.
|
||||
- Integration fetch failures simply show no integration; no hard failure.
|
||||
|
||||
## Tenancy Rules
|
||||
- All requests are account-scoped server-side; page uses site id route but does not allow cross-tenant access.
|
||||
- Site selector filters to `is_active` sites from the same account.
|
||||
|
||||
## Billing Rules (if applicable)
|
||||
- None directly; industry/sector constraints enforced server-side (plan limits) not in this component.
|
||||
|
||||
## Background Tasks / Schedulers (if applicable)
|
||||
- None; no polling.
|
||||
|
||||
## Key Design Considerations
|
||||
- Separates tabs to avoid heavy content-type loads unless needed.
|
||||
- Avoids assuming integration exists; handles absent integration gracefully.
|
||||
- Keeps SEO fields in formData for a single-save payload.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- When adding new site fields, extend `formData` initialization from `loadSite` and include inputs plus save payload.
|
||||
- Back the placeholder stats/content-types with real endpoints, ensuring they key off `siteId`.
|
||||
- Preserve query-param tab handling when adding new tabs.
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# Content Editor Page
|
||||
|
||||
## Purpose
|
||||
Display a single content record with full details for review/read-only inspection. Acts as the per-record viewer for content generated or managed by the Writer module.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Page: `frontend/src/pages/Writer/ContentView.tsx`
|
||||
- Template: `frontend/src/templates/ContentViewTemplate` (renders the actual layout/content fields)
|
||||
- API: `frontend/src/services/api` (`fetchContentById`)
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Fetch a specific content item by id from route param and render it via `ContentViewTemplate`.
|
||||
- Validate id parameter, handle not-found/error states, and provide back navigation to content list.
|
||||
|
||||
## Detailed Behavior
|
||||
- Route: `/writer/content/:id`.
|
||||
- On mount: validates `id` is numeric; on invalid, shows toast and redirects to `/writer/content`.
|
||||
- Fetches content via `fetchContentById(contentId)`; sets `content` state and clears `loading`.
|
||||
- Errors: shows toast (`Failed to load content`) and leaves `content` null.
|
||||
- Back action: `onBack` navigates to `/writer/content`.
|
||||
- Page metadata: sets document title/description via `PageMeta`.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- Content DTO from writer API (includes title, body/html, status, external_url, etc.; structure defined server-side).
|
||||
|
||||
## Execution Flow
|
||||
- `useEffect` → validate id → fetch content → update state → render template.
|
||||
- Template receives `{ content, loading, onBack }`.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Navigation back to writer drafts list; no direct cross-module calls.
|
||||
|
||||
## State Transitions
|
||||
- `loading` toggles during fetch; `content` set on success; invalid id triggers navigation away.
|
||||
|
||||
## Error Handling
|
||||
- Toast errors for missing/invalid id or fetch failure; console logs errors.
|
||||
|
||||
## Tenancy Rules
|
||||
- Backend enforces account/site/sector scoping; client only supplies id from route.
|
||||
|
||||
## Billing Rules (if applicable)
|
||||
- None within this view; generation/updates handled elsewhere.
|
||||
|
||||
## Background Tasks / Schedulers (if applicable)
|
||||
- None.
|
||||
|
||||
## Key Design Considerations
|
||||
- Strict id validation avoids bad requests.
|
||||
- Keeps view read-only; editing handled elsewhere (not in this component).
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- If adding inline editing, extend `ContentViewTemplate` and add PATCH/PUT calls; keep id validation and error handling intact.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# Image Editor Page (Images List & Generation)
|
||||
|
||||
## Purpose
|
||||
Manage generated images linked to writer content: list images grouped by content, filter/search, trigger generation, update statuses, and download/view images. Uses table template patterns similar to content/tasks.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Page: `frontend/src/pages/Writer/Images.tsx`
|
||||
- API: `frontend/src/services/api` (`fetchContentImages`, `fetchImageGenerationSettings`, `generateImages`, `bulkUpdateImagesStatus`, `deleteContent`, `bulkDeleteContent`)
|
||||
- Config: `frontend/src/config/pages/images.config` (columns/filters)
|
||||
- UI components: `frontend/src/components/common/ImageQueueModal`, `frontend/src/components/common/SingleRecordStatusUpdateModal`, `frontend/src/components/common/PageHeader`, `frontend/src/components/navigation/ModuleNavigationTabs`, `frontend/src/components/ui/modal`
|
||||
- Hooks: `frontend/src/hooks/useResourceDebug` (AI logs toggle), `frontend/src/hooks/useProgressModal` (via modal usage pattern)
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Fetch and render content-image groups with client-side filtering/search/sorting/pagination.
|
||||
- Trigger image generation for selected content with queue modal and provider/model selection.
|
||||
- Update image status in bulk and delete images/content.
|
||||
- Provide AI function log visibility when resource debug is enabled.
|
||||
|
||||
## Detailed Behavior
|
||||
- Data load: `loadImages` calls `fetchContentImages({})`, applies client-side search (`content_title`) and status filter (`overall_status`), sorts (default `content_title`), paginates client-side (page size 10), and adds `id` field mirroring `content_id` for selection.
|
||||
- Filters: search text; status dropdown; sort controls; pagination tracked in local state.
|
||||
- Actions:
|
||||
- Generate images: opens `ImageQueueModal`, builds queue items, calls `generateImages` with provider/model; tracks taskId/model/provider state; shows AI logs when resource debug enabled.
|
||||
- Bulk status update: `bulkUpdateImagesStatus` on selected ids.
|
||||
- Delete (single/bulk): uses `deleteContent`/`bulkDeleteContent`.
|
||||
- Download/view: handled by row actions in config (template-driven).
|
||||
- Navigation: writer tabs rendered via `ModuleNavigationTabs` (Queue/Drafts/Images/Review/Published).
|
||||
- Resource debug: AI logs captured only when `useResourceDebug` returns true; `addAiLog` appends logs for visibility.
|
||||
- Loading UX: `loading` + `showContent` gating; debounced search resets page as needed.
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- `ContentImagesGroup`: content_id, content_title, overall_status, images[].
|
||||
- `ContentImage`: individual image entries with URL/status/prompt (from API).
|
||||
- Generation settings: provider/model options from `fetchImageGenerationSettings`.
|
||||
|
||||
## Execution Flow
|
||||
- `useEffect` → `loadImages`.
|
||||
- Filters/sort/page changes → recompute client-side subsets.
|
||||
- Generate action → open modal → call `generateImages` → optionally log steps → reload images.
|
||||
- Status update/delete actions → call API → reload.
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Tied to writer content records; delete actions use writer content endpoints.
|
||||
- AI generation leverages shared API endpoints that consume credits server-side.
|
||||
|
||||
## State Transitions
|
||||
- `loading`/`showContent` manage render timing; modal open states for queue/status/image viewer.
|
||||
- `aiLogs` maintained only when debug is enabled.
|
||||
|
||||
## Error Handling
|
||||
- Toast errors for load/generate/update/delete; generation errors also recorded in AI logs when enabled.
|
||||
- Debounced search handles errors gracefully by keeping prior data until reload.
|
||||
|
||||
## Tenancy Rules
|
||||
- Backend enforces account/site/sector; client passes no explicit tenant fields beyond any default filters in API layer.
|
||||
|
||||
## Billing Rules (if applicable)
|
||||
- Image generation consumes credits on backend; page performs no credit gating.
|
||||
|
||||
## Background Tasks / Schedulers (if applicable)
|
||||
- None; generation is user-triggered, and polling is not used here.
|
||||
|
||||
## Key Design Considerations
|
||||
- Client-side pagination used because API returns grouped images; keeps UI responsive without extra endpoints.
|
||||
- Resource debug toggle avoids unnecessary log storage unless explicitly enabled.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- If server adds server-side pagination/filtering, remove client-side slicing and pass filters to API.
|
||||
- Extend row actions by updating `images.config` with handlers wired to new behaviors.
|
||||
- Keep generation flow in sync with backend provider/model options; surface credit estimates if backend exposes them.
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# Writer Main Page (Queue/Drafts/Images Navigation)
|
||||
|
||||
## Purpose
|
||||
Serve as the entry surface for writer workflows, routing users to task queue, drafts, images, review, and published content views. It relies on shared table templates and writer navigation tabs defined in the content/tasks/images pages.
|
||||
|
||||
## Code Locations (exact paths)
|
||||
- Key pages under Writer:
|
||||
- Tasks (queue): `frontend/src/pages/Writer/Tasks.tsx`
|
||||
- Content drafts/list: `frontend/src/pages/Writer/Content.tsx`
|
||||
- Images: `frontend/src/pages/Writer/Images.tsx`
|
||||
- Content view: `frontend/src/pages/Writer/ContentView.tsx`
|
||||
- Navigation tabs defined inside Tasks/Content/Images pages (`writerTabs`).
|
||||
|
||||
## High-Level Responsibilities
|
||||
- Present writer-specific navigation and headers.
|
||||
- Delegate to module pages that implement task creation, AI generation, content listing, and image management.
|
||||
|
||||
## Detailed Behavior
|
||||
- Writer pages use shared navigation tabs (`writerTabs`: Queue, Drafts, Images, Review, Published) rendered via `ModuleNavigationTabs`.
|
||||
- Each page sets a header (`PageHeader`) with badge icon and binds to the tab component for consistent navigation.
|
||||
- State (filters, pagination, selections) is managed within each page; there is no global writer-state container beyond shared stores (`useSectorStore`, `usePageSizeStore`).
|
||||
|
||||
## Data Structures / Models Involved (no code)
|
||||
- Task, Content, ContentImage DTOs from `frontend/src/services/api` (writer endpoints).
|
||||
|
||||
## Execution Flow
|
||||
- User enters writer area via route (e.g., `/writer/tasks` or `/writer/content`).
|
||||
- Navigation tabs switch routes; each route mounts its page and fetches data (tasks/content/images).
|
||||
|
||||
## Cross-Module Interactions
|
||||
- Sector/site scoping via `useSectorStore` and backend query params in API calls.
|
||||
- Optimization and image generation actions route into optimizer or image generation APIs.
|
||||
|
||||
## State Transitions
|
||||
- Per-page loading/filters; navigation changes unmount current page and mount target page.
|
||||
|
||||
## Error Handling
|
||||
- Each page uses toasts for API errors; no shared error surface beyond per-page banners.
|
||||
|
||||
## Tenancy Rules
|
||||
- Backend filters by account/site/sector; pages pass sector context via filters or rely on server defaults.
|
||||
|
||||
## Billing Rules (if applicable)
|
||||
- None on navigation; individual actions (AI generation) consume credits on backend.
|
||||
|
||||
## Background Tasks / Schedulers (if applicable)
|
||||
- None at the navigation level.
|
||||
|
||||
## Key Design Considerations
|
||||
- Tabs keep writer UX consistent; each page owns its data loading to avoid cross-coupling.
|
||||
|
||||
## How Developers Should Work With This Module
|
||||
- When adding a new writer view (e.g., “Outlines”), add a tab entry and a route in `App.tsx`, and implement the page with the same header/tab pattern.
|
||||
|
||||
Reference in New Issue
Block a user