videogen/docs/plans/INTEGRATIONS-2026-10-06.md
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

164 lines
14 KiB
Markdown

# Integrations settings area (Creatify parity) - plan, 2026-10-06
Branch `integrations-2026-10-06` (from main `dcf62532`). Code and tests only:
no deploy, no push, no sign-ups, $0. Ad Clone (separate branch) and the
render-engine adapters are not touched.
## 1. What Menivor already has (reused, not duplicated)
| Need | Existing code | How this branch uses it |
|---|---|---|
| Token encryption at rest | `app/services/crypto_tokens.py` (Fernet, `SOCIAL_TOKEN_KEY`) | Every ad, Slack and store token is stored only as `crypto_tokens.encrypt(...)` output. |
| Meta / TikTok ads OAuth + clients | `app/domains/ads/{meta_client,tiktok_client,config}.py` (per-user, one account, launch/optimize flow) | Same env keys (`MENIVOR_META_APP_ID/SECRET`, `MENIVOR_TIKTOK_APP_ID/SECRET`), same Graph API version helper and Meta `appsecret_proof`. The new connectors add multi-account listing, workspace scope and a reporting pull; the paid-ads launch flow is unchanged. |
| Social publishing (TikTok, Instagram, YouTube) | `app/domains/multipost` (accounts shared to a workspace, OAuth, pacing, queue), `packages/publishing-connectors`, `/connections` | The "Social accounts" section is a read-only summary over `multipost` accounts + providers; connect/disconnect buttons call the existing `/multipost/connect/...` routes. No new publishing code. |
| Approval gate | `app/domains/approvals` (`approval_items`, guarded claim, idempotent decide, adapters) | New source `ad_action`. Proposals are enqueued as approval items; only `approvals.service.decide(..., "approve")` runs the adapter that calls the ad platform. The web page, the `/approvals` feed and Slack buttons all use that one API. |
| Credit ledger | `credit_ledger` + `CreditRepository.grant / workspace_grant` | Onboarding credits are ledger grants (workspace pool for a workspace, personal pool otherwise), guarded by a unique `(owner_scope, step)` row. |
| Brand spaces | Brand kits = `user_presets` rows (`workspace_id` = shared to a team) | A Brand space is a brand kit id. Ad accounts are assigned to brand kits in the new `integration_ad_account_brands` table. |
| Products / catalog | `store_catalog_imports` / `store_catalog_products` + `adstudio/store_catalog` (public Shopify `products.json`, WooCommerce Store API) feeding Ad Studio (URL to Video / Image Ad) | New sources write through the same `record_import(...)`, so imported products show up in the existing catalog and project flow. Migration widens the provider check to `medusa` and `csv`. |
| LLM | `app/services/llm._generate_response` (Railyard Relay first, then configured provider, then free fallbacks) | The ads agent calls this; no new paid LLM service. |
| Plan tiers | `entitlements.active_plan_key` (workspace) and `creator_subscriptions` (personal) | Agent + Slack gate: Pro and above (`pro`, `agency`, `enterprise`). |
## 2. What to build, in order
1. **Models + migration** (`app/domains/integrations/models.py`, migration after head `e3a5c7d9f1b2`):
`integration_connections` (one per scope + provider; kinds `ads`, `slack`, `product_source`),
`integration_oauth_states` (hashed, single use, 15 min), `integration_ad_accounts`,
`integration_ad_account_brands`, `integration_ad_metrics` (common daily per-creative
metrics), `integration_onboarding_grants`.
2. **Scope + visibility** (`scope.py`): workspace scope (`ws:<id>`, members read,
owner/admin manage) or personal scope (`user:<id>`). With a Brand space selected
only the ad accounts assigned to it are visible; without one the workspace sees all.
3. **Connectors** (`connectors/`), one class per provider behind one injectable
`Transport` (the multipost seam): authorize URL, code exchange, refresh, list
accounts, metrics pull normalized to `MetricRow`, and `execute` for delivery actions.
4. **Service** (`service.py`): connect/callback/disconnect, account sync, brand-space
assignment, reporting pull into `integration_ad_metrics`, refresh on use.
5. **Approval gate** (`actions.py`): `propose_action` enqueues `ad_action` items;
the adapter executes only on approve and re-checks the scope.
6. **Ads agent** (`agent.py`) + **contract** (`contract.py`): tool API and the two
functions the Brand Agent branch consumes (section 5).
7. **Onboarding credits** (`onboarding.py`).
8. **Slack** (`slack.py`): OAuth install, signature check, slash command, app mention,
approve/reject buttons.
9. **Product sources** (`product_sources.py`): Shopify Admin token, Medusa Store API,
CSV text or CSV URL (Shopier exports).
10. **HTTP router** (`router.py`) and **web page** `/settings/integrations`.
## 3. Ad account providers: API, scopes, app review
All are official APIs. Reporting is read only. Delivery (pause / resume) only runs
after an approval. "Owner action" = what the owner must do before live use.
| Provider | Auth | Scopes / access | Reporting call | Delivery call | Owner action |
|---|---|---|---|---|---|
| Meta | OAuth (`facebook.com/<v>/dialog/oauth`), long-lived 60-day token, re-extended with `fb_exchange_token` | `ads_read` (reporting), `ads_management` (pause/resume), `business_management` | `GET act_<id>/insights?level=ad&time_increment=1` | `POST /<ad_id> status=PAUSED/ACTIVE` | App at https://developers.facebook.com/apps (type Business), add Marketing API, Business Verification, App Review for Advanced Access to `ads_read` + `ads_management`. Same app as the existing paid-ads flow. |
| Google Ads (Search, PMax, Display) | OAuth Google, refresh token, `access_type=offline` | `https://www.googleapis.com/auth/adwords` + developer token (+ optional login-customer-id) | `POST customers/<id>/googleAds:searchStream` (GAQL over `ad_group_ad`, plus campaign rows for PMax) | `adGroupAds:mutate` status update | Developer token in a manager account (https://ads.google.com/aw/apicenter), apply for Basic Access; OAuth client at https://console.cloud.google.com/apis/credentials; OAuth consent verification for the sensitive `adwords` scope. API version env `GOOGLE_ADS_API_VERSION` (default `v25`). |
| TikTok Ads (Spark Ads, creative metrics) | TikTok for Business OAuth (`business-api.tiktok.com/portal/auth`), non-expiring token | Ad account management + Reporting (Spark Ads covered by ads reporting) | `GET report/integrated/get/` (`AUCTION_AD`, `ad_id` x `stat_time_day`) | `POST ad/status/update/` | App at https://business-api.tiktok.com/portal/apps, request Marketing API scopes, wait for approval. Same app as the existing paid-ads flow. |
| Snapchat Ads | OAuth (`accounts.snapchat.com`), 30-min token + refresh | `snapchat-marketing-api` | `GET adaccounts/<id>/stats?breakdown=ad&granularity=DAY` (micro-currency) | Not offered this round (Snap's ad update needs the full ad object; read only) | OAuth app in Snapchat Business Manager https://business.snapchat.com (Business Details > OAuth Apps); Marketing API access is approved per app. |
| Reddit Ads | OAuth (`reddit.com/api/v1/authorize`, `duration=permanent`), 1-hour token + refresh | `adsread`, `adsedit` | `POST ads-api.reddit.com/api/v3/ad_accounts/<id>/reports` (`AD_ID` x `DATE`) | `PATCH /api/v3/ads/<id>` `configured_status` | Create an app at https://www.reddit.com/prefs/apps and request Ads API access at https://ads.reddit.com (Reddit approves developer access). Report body shape is from public connector docs and is unverified live. |
| AppLovin (AppDiscovery / Axon) | API key (Report Key), pasted per workspace, encrypted | Report key from the AppLovin dashboard (Account > Keys) | `GET https://r.applovin.com/report?report_type=advertiser` | Not offered (campaign management API is separate, partner-gated) | No app review; the advertiser pastes their own Report Key. |
| OpenAI Ads (ChatGPT ads) | API key: ad-account-scoped Advertiser API key, pasted per workspace, encrypted | Key from https://ads.openai.com (self-serve Ads Manager, beta since May 2026) | `GET https://api.ads.openai.com/v1/ad_account/insights?aggregation_level=ad&time_granularity=daily` (spend in currency units) | `POST /v1/ad_groups/<id>` `status` (ad-group level) | No app review; the advertiser creates an Advertiser API key. A public API exists (developers.openai.com/ads), so this is a real connector, not "Coming soon". Conversions on the ad-level insights call are not documented, so conversions/ROAS are shown as "not reported". |
Metric rules (common table): spend and conversion value in account-currency minor
units; CTR = clicks / impressions, CPA = spend / conversions, ROAS = value / spend.
A metric the platform did not report is `null`, never an invented 0.
## 4. Ads agent ("Ads agent", not "Max")
"Max" is a common product name (and Creatify's), so the agent is just called
**Ads agent** in UI and code. It is a backend service, not a chat shell (the Brand
Agent branch owns the chat UI). The Integrations page has a small Q&A panel only.
Tool API (`app/domains/integrations/agent.py`):
- `ask_campaign_question(scope, question, llm=None)` - answers from the stored
metrics through `_generate_response` (Relay). Returns answer + the facts used +
rule-based suggestions. Never executes anything.
- `pull_report(scope, ad_account_id=None, days=7)` - totals and per-creative rows.
- `propose_optimization(scope, ad_account_id=None, days=7)` - deterministic rules
(pause creatives that spent >= 2x the account CPA with no conversions, or whose
CPA is > 2x the account CPA) -> approval items.
- `approve(scope, item_id)` / `reject(scope, item_id)` - the approvals API.
Plan gate: Pro and above (workspace plan `pro`/`enterprise`, personal plan
`pro`/`agency`), checked for the agent and the Slack install.
Slack: `slack.com/oauth/v2/authorize` with `commands,app_mentions:read,chat:write`;
`/menivor-ads <question>`; `@app` mentions; proposal messages carry Approve/Reject
buttons that call `approvals.service.decide(via="slack")`. Every request is checked
with the Slack signing secret (`v0` HMAC, 5-minute window). Only Slack users on the
install's approver list (the installer by default) may approve. Owner action:
create the app at https://api.slack.com/apps, set the redirect URL, slash command
`/menivor-ads` -> `/api/v1/integrations/slack/commands`, Event Subscriptions
(`app_mention`) -> `/api/v1/integrations/slack/events`, Interactivity ->
`/api/v1/integrations/slack/interactions`; env `SLACK_CLIENT_ID`,
`SLACK_CLIENT_SECRET`, `SLACK_SIGNING_SECRET`. No Slack review is needed for a
private (non-directory) app.
Onboarding credits (once per workspace, or once per user without a workspace):
connect ad accounts +50, first question +10, first approved action +10.
## 5. Contract for the Brand Agent branch
`app/domains/integrations/contract.py` (pure functions, no HTTP):
```python
list_connected_accounts(user_id, *, workspace_id=None, brand_space_id=None) -> list[ConnectedAccount]
top_performing_creatives(user_id, ad_account_id, *, period_days=7, limit=10,
workspace_id=None, brand_space_id=None) -> list[CreativePerformance]
ask_campaign_question / pull_report / propose_optimization / approve / reject
```
`ConnectedAccount` and `CreativePerformance` are frozen dataclasses with
`as_dict()`. Both functions apply the same scope and Brand-space visibility rules
as the HTTP API. The Brand Agent's Connectors view lists accounts; Inspirations
reads top creatives.
## 6. Social accounts and product sources
- Social: `GET /integrations/social` returns, per platform (TikTok, Instagram,
YouTube), the server state from `multipost.settings.provider_overview` and the
one account shared to the workspace (or the caller's own). Connect uses the
existing multipost OAuth with `workspace_id`.
- Shopify: Admin API custom-app token (`X-Shopify-Access-Token`, scope
`read_products`), `GET /admin/api/<ver>/products.json`. Owner/merchant action:
Shopify admin > Settings > Apps > Develop apps > create app > Admin API scope
`read_products` > install > copy token. OAuth (public app) is not built; it
needs a Shopify Partner app review.
- Medusa (Oxhan Atelier, Medusa 2.21): Store API `GET /store/regions`,
`GET /store/products?region_id=...&fields=*variants.calculated_price` with
`x-publishable-api-key`. Product link = `<storefront_url>/products/<handle>`
(for Oxhan pass the country path, e.g. `https://<store>/tr`).
- CSV / URL: CSV text or a CSV URL (fetched through the Ad Studio SSRF guard).
Columns are matched by name in English or Turkish (Shopier exports).
## 7. Not done / owner items
- No live call to any provider was made; every connector is tested with mocked HTTP.
- Provider developer apps and reviews in section 3; Slack app in section 4.
- Background metric pulls (Celery beat) are not scheduled; pulls run on demand
("Refresh reports" on the Ad Accounts section, or `POST /integrations/ads/refresh`).
The agent answers from whatever was last pulled.
## 8. HTTP surface (all under `/api/v1`)
`GET /integrations` (overview), `POST /integrations/ads/{provider}/connect|key`,
`POST /integrations/callback` (ad platforms and Slack), `DELETE /integrations/ads/{provider}`,
`PUT /integrations/ad-accounts/{id}/brand-spaces`, `POST /integrations/ads/refresh`,
`GET /integrations/ads/report`, `POST /integrations/agent/ask|propose`,
`GET /integrations/agent/proposals`, `POST /integrations/agent/proposals/{id}/approve|reject`,
`POST /integrations/slack/install`, `PUT /integrations/slack/approvers`, `DELETE /integrations/slack`,
Slack-signed `POST /integrations/slack/commands|events|interactions`, `GET /integrations/social`,
`POST /integrations/products/shopify|medusa|csv`, `POST|DELETE /integrations/products/{provider}[/resync]`.
Web: `/settings/integrations` (+ `/settings/integrations/callback`).
## 9. Env names (owner sets; never in code)
`SOCIAL_TOKEN_KEY` (already used), `MENIVOR_INTEGRATIONS_REDIRECT_URL` (default
`<MENIVOR_WEB_URL>/settings/integrations/callback`), `MENIVOR_META_APP_ID/SECRET`,
`MENIVOR_TIKTOK_APP_ID/SECRET`, `GOOGLE_ADS_CLIENT_ID/SECRET`, `GOOGLE_ADS_DEVELOPER_TOKEN`,
`GOOGLE_ADS_LOGIN_CUSTOMER_ID` (optional), `GOOGLE_ADS_API_VERSION` (default v25),
`SNAPCHAT_ADS_CLIENT_ID/SECRET`, `REDDIT_ADS_CLIENT_ID/SECRET`, `SLACK_CLIENT_ID`,
`SLACK_CLIENT_SECRET`, `SLACK_SIGNING_SECRET`, `SHOPIFY_ADMIN_API_VERSION` (default 2025-10).
Every provider's redirect URL must be registered as the value of
`MENIVOR_INTEGRATIONS_REDIRECT_URL`.