# Module 23 — SEO, Website Analytics & AI Competitor Intelligence

API reference and honest delivery status. Everything listed under "Built" is
wired, permission-guarded and covered by the automated suite
(`php artisan test --filter=Seo` → 55 tests, 341 assertions, incl. the
phase-3 sub-modules in `SeoIntelligenceTest`).

## Honesty contract (enforced in code)

`App\Contracts\SeoDataProvider` documents two rules every provider must keep:

1. Everything a provider returns is an **estimate** from a third-party model —
   never first-party analytics and never Google Analytics data for a property
   the user has not authorised. Callers surface `estimated => true`.
2. A metric a provider cannot supply is returned as `null`, never a placeholder
   zero, so the UI says "Data unavailable from connected provider" instead of
   inventing a number.

The same rule runs through the module: `SeoProviderRegistry` throws
`SeoProviderNotConnected` ("SEO provider not connected.") rather than returning
fabricated metrics when no vendor adapter is wired.

## Built and tested

| Sub-module | What exists |
| --- | --- |
| 23.1 SEO Project / Website management | Full project CRUD (`/api/seo/projects`), multi-project, domain/industry/country/language targeting fields, status, notes, tags, activity via `license`-style event log, branch (tenant) scoping, dashboard KPIs (`/api/seo/dashboard`) with a 30-day `trend` series (daily GA4 sessions + Search Console clicks/impressions from `seo_traffic_daily`, null where a service recorded nothing) rendered as the dashboard's trend chart |
| 23.6 Provider architecture | `App\Contracts\SeoDataProvider` + `SeoProviderRegistry` (register/resolve/fallback points, connection checks, honest not-connected errors). Vendor adapters are registered in one map — adding a vendor never touches call sites |
| 23.6 Semrush adapter (built) | `App\Services\Seo\Providers\SemrushProvider` — real Semrush Analytics API v3 client: `domain_rank` (overview), `domain_organic` (ranking keywords/top pages), `phrase_this` (volume+difficulty, one 10-unit call serves both), `phrase_organic` (SERP), `phrase_related` (keyword ideas), and the `analytics/v1` backlinks reports. Semicolon-CSV parser keyed by column codes, unit-cost ledger (10 units/line v3, 40 backlinks), vendor `ERROR` responses and HTTP failures raise `SeoMetricUnavailable` — never invented data. Resolves through `seo_connections.api_key` (encrypted at rest) or the `seo_semrush_api_key` setting; regional database follows the project's country |
| 23.9 Keyword management | Keyword CRUD, groups, intent, volume/difficulty/CPC/competition, ranking position + URL, tags, priority, CSV export (`/api/seo/keywords*`) |
| 23.10 Rank tracking | `seo_keyword_ranks` history (engine/device/country/location), position history endpoints, improvements/drops detection, top-N segmentation, `seo:sync` console command for scheduled syncs |
| 23.7/23.8 Competitor management & intelligence | Competitor CRUD + dedupe (`/api/seo/competitors*`), SERP discovery (`POST /api/seo/projects/{id}/competitors/discover`), estimated-metric + ranking-keyword sync through the provider contract, per-competitor keyword rows, CSV export. All metrics stay `estimated: true` and null until synced |
| 23.11 Keyword gap | `GET /api/seo/keyword-gap` — missing/shared/mine-only/they-outrank/near-win/low-difficulty/high-volume buckets computed from real keyword rows (+ export) |
| 23.12 Content gap | `GET /api/seo/content/gap` — real crawl of the project's site (SiteCrawler) vs competitor keyword vocabulary: missing topics, questions, blog-presence note, transparent opportunity score |
| 23.14 SERP tracking | `GET/POST /api/seo/serp*`, `POST /api/seo/projects/{id}/serp` — stores full live SERP snapshots, own position, features only when the provider reports them (null otherwise) |
| 23.15 Backlinks (honest slice) | `GET /api/seo/backlink-gap` — estimated backlink/referring-domain totals per domain; row-level backlink lists need a provider adapter and stay null |
| 23.16 Site audit | `GET/POST /api/seo/audit*`, `POST /api/seo/projects/{id}/audit` — real crawler (meta titles/descriptions, H1s, alt text, canonical, noindex, broken links, robots.txt, sitemap.xml, schema, thin content), 100-point health score with visible deductions, persisted findings, export |
| 23.17/23.18 AI SEO & opportunities | `/api/seo/ai/*`, `/api/seo/content/opportunities` — runs on the ERP's existing `App\Services\Ai\AiClient` (no second generator). Available=false + reason when no AI provider is configured; opportunities are validated against real stored keywords so hallucinated rows are dropped |
| 23.17b AI meta + blog generation | `POST /api/seo/ai/generate/{metas\|blogs}` — the admin picks how many items to produce; every item is persisted in `seo_ai_generations` with its provider + model label, listed under the AI Recommendations screen and exportable as XLSX/CSV through `ReportExportService`. Unusable AI answers are refused (422 + reason), never repaired into fake content |
| 23.19 AI content briefs | `POST/GET /api/seo/content/briefs` — JSON brief from the configured AI provider, stored verbatim with its `ai_provider` label |
| 23.20/23.22 Existing content system bridge | `POST /api/seo/content/briefs/{id}/send-to-calendar` — creates a draft in the EXISTING Social Media module (`social_posts` + targets), one brief → one calendar item, approval flow untouched |
| 23.21 Internal linking | `GET /api/seo/internal-links`, `POST /api/seo/projects/{id}/internal-links/analyze`, `PUT /api/seo/internal-links/{id}` — orphan detection, keyword-overlap suggestions with derived anchors, accept/reject workflow |
| 23.23 Reports & exports | `GET /api/seo/reports` KPI hub (real keyword/audit numbers; GA4/GSC KPIs stay null until connected) + `GET /api/seo/reports/export?report=…` (keywords, rankings, competitors, competitor keywords, keyword gap, audit, SERP, internal links, briefs) as CSV/XLSX |
| 23.27 Automation engine | Five scheduled commands (`seo:sync`, `seo:sync-competitors`, `seo:sync-traffic`, `seo:gap-analysis`, `seo:audit`; cadences in `routes/console.php`, all `withoutOverlapping`) that skip projects without a connected provider instead of inventing data. Every run writes per-project result rows to the activity log | `GET /api/seo/automation` surfaces the health card (last run, next run, per-command results) |
| 23.28 API usage & cost | `seo_api_usage` table + `/api/seo/api-usage` (request count, provider, endpoint, cost, errors, response time, monthly usage); keyword sync, competitor sync, SERP capture and discovery all write the ledger |
| 23.31 Automation health | `GET /api/seo/automation` (`perm:seo.settings`) — per scheduled command: last run from the command's own activity-log rows (a failed audit reports `failed` with its reason), next run computed forward from the schedule's cron expression, and the five most recent per-project results. Rendered in Settings → SEO & Competitor |
| 23.29 Permissions & security | Reuses Sanctum + `perm:seo.*` (`seo.view/create/edit/delete/sync/keywords/reports/api/competitors/content/analytics/settings`), branch isolation, provider connections stored on `seo_connections` |
| Site SEO tooling | `GET /api/integrations/seo` (sitemap/robots status for backend + frontend), `POST /api/integrations/seo/generate` (regenerate, admin-only), `GET /api/integrations/seo/health`, Search Console sitemap submission (`gscStatus`/`gscSubmit` via `GoogleSearchConsoleService`, service-account JWT). Installer writes `public/sitemap.xml` + `public/robots.txt` for both apps at install time (covered by `InstallerSeoTest`) |

## Not built — scoped, not faked

These require real third-party credentials and/or budget decisions. Each reports
its absence honestly instead of inventing data.

| Sub-module | Why it is not built | What is needed to enable it |
| --- | --- | --- |
| 23.2 Google Account integration (OAuth), 23.3 GA4, 23.4 Search Console reporting, 23.5 Google Ads / Keyword Planner | Needs a Google Cloud project, OAuth consent screen, client ID/secret and per-customer property access; token handling must be audited before storing | Google OAuth client + scope review; then implement a `GoogleOAuthConnector` on `seo_connections` and GA4/GSC data adapters feeding the existing dashboard. The gap/audit/AI modules are fully built and become richer automatically once these feed first-party numbers |
| 23.6 Ahrefs adapter | **SHIPPED.** A real `Providers\AhrefsProvider` (Ahrefs API v3, Bearer auth) is registered in `SeoProviderRegistry::$providers` and resolves through a connected `seo_connections` row or the `seo_ahrefs_api_key` setting. Powers competitor sync (metrics, backlinks stats, domain rating), SERP capture (`serp-overview`), keyword sync (`keywords-explorer/overview`) and the keyword gap. Ahrefs meters API units (50-unit request floor; domain-rating is free — the connection probe uses it and costs nothing). A stored key on a paid plan now produces real estimated numbers with `estimated => true`; unavailable metrics stay `null` | — |
| 23.13 Competitor content monitoring | Needs scheduled re-crawls of competitor sites and a policy decision on scraping frequency | A scheduler entry reusing SiteCrawler against competitor domains |
| 23.24 Alerts & notifications | The detection inputs exist (rank history, audits, usage ledger); the notification channel wiring is not built | Reuse the existing notification system; wire detections to channels |
| 23.25 Google Sheets automation, 23.26 Google Calendar sync | Depends on 23.2 (Google OAuth) | Enable after Google integration; the content-calendar bridge (23.22) already goes through the Social module |
| 23.30 SEO settings pages | Partially exists: SEO & meta settings (titles, descriptions, OG/Twitter, verification, GSC domain) drive the public sites; provider/AI keys live in the existing Settings → AI store | Provider credential storage once adapters exist |

## Setup instructions

1. **Permissions** — assign the `seo.*` permissions from the existing role
   manager (they are part of the standard permission catalogue).
2. **Scheduler** — enable `php artisan seo:sync` daily (`schedule:run` is already
   wired through Laravel Scheduler; add the cadence in `routes/console.php` if a
   different frequency is wanted).
3. **Search Console sitemap submission** — set `GSC_SERVICE_ACCOUNT_JSON` to a
   service-account JSON key path and the verified domain under
   Settings → SEO & meta; then `POST /api/integrations/seo/gsc` submits the
   sitemap. Without credentials the endpoint answers 422 with the exact missing
   setup step.
4. **Connecting Semrush** — store the API key on a `seo_connections` row
   (`provider` = `semrush`, `service` = `semrush`, `status` = `connected`,
   `api_key` = the key; encrypted at rest) for the project's branch, or set the
   `seo_semrush_api_key` instance setting. From then on competitor sync, SERP
   capture, keyword sync, keyword gap and the usage ledger work for real.
   Costs follow Semrush's published pricing (10 API units per line on the v3
   analytics reports, 40 on the backlinks reports) and every request is
   itemised in `/api/seo/api-usage`. The regional database defaults to `us`;
   override per connection via `meta.database`.
5. **Adding another data provider** — implement `App\Contracts\SeoDataProvider`,
   register it in `SeoProviderRegistry::$providers`, store the connection on
   `seo_connections`, and every consumer (dashboard, keywords, competitors,
   SERP, gap reports, usage) picks it up without code changes.
6. **AI features** — the SEO AI endpoints reuse the ERP's existing AI store
   (Settings → AI: provider, key, model). No SEO-specific AI credentials exist.
7. **Site audit / internal linking / content gap** — these crawl the project's
   real website over HTTP from the server running the ERP; make sure outbound
   HTTP to the customer's own domain is allowed. Crawl size is capped (20 pages
   per run) so it completes inside one request.

   **Redirect OAuth (no Playground needed):** with the client ID + secret
   entered, press "Connect via Google (redirect)" — the backend mints a
   single-use state and Google's consent screen opens with
   `access_type=offline&prompt=consent`; approving returns a refresh token
   that is stored automatically. Register
   `{APP_URL}/oauth/google/callback` as an Authorized redirect URI on the
   OAuth client first. `FRONTEND_URL` must point at the SPA; the web callback
   forwards `?code=&state=` there and the SPA completes the exchange behind
   `perm:seo.settings`. The manual refresh-token paste and the
   Playground remain supported as alternatives.

   **Token health:** every connection row reports an honest health level
   (`ok` / `warning` / `error`) in Settings — a failed refresh or sync shows
   its verbatim error; an access token expiring within 48 h with no refresh
   token warns before the connection dies; a refresh token unused for six
   months (Google's revocation window) warns while a sync or Test can still
   keep it alive. The dashboard's connection tiles surface the same health
   via `data_state.*.token_health`. `seo_connections.refreshed_at` records
   real token usage (refresh or code exchange); row edits and creations
   never do.

## API quick reference (auth: Sanctum bearer token)

```
GET    /api/seo/dashboard                         perm:seo.view
GET    /api/seo/projects                          perm:seo.view
POST   /api/seo/projects                          perm:seo.create
GET    /api/seo/projects/{seoProject}             perm:seo.view
PUT    /api/seo/projects/{seoProject}             perm:seo.edit
DELETE /api/seo/projects/{seoProject}             perm:seo.delete
GET    /api/seo/keywords                          perm:seo.keywords
POST   /api/seo/keywords                          perm:seo.keywords
GET    /api/seo/keywords/export                   perm:seo.reports
PUT    /api/seo/keywords/{seoKeyword}             perm:seo.keywords
DELETE /api/seo/keywords/{seoKeyword}             perm:seo.keywords
GET    /api/seo/keywords/{seoKeyword}/ranks       perm:seo.keywords
POST   /api/seo/keywords/{seoKeyword}/ranks       perm:seo.keywords
POST   /api/seo/projects/{seoProject}/keywords/sync  perm:seo.sync
GET    /api/seo/api-usage                         perm:seo.api
POST   /api/seo/connections/google/oauth/start    perm:seo.settings
POST   /api/seo/connections/google/oauth/complete perm:seo.settings
GET    /api/seo/automation                        perm:seo.settings

GET    /api/seo/competitors                       perm:seo.competitors
POST   /api/seo/competitors                       perm:seo.competitors
GET    /api/seo/competitors/export                perm:seo.reports
PUT    /api/seo/competitors/{seoCompetitor}       perm:seo.competitors
DELETE /api/seo/competitors/{seoCompetitor}       perm:seo.competitors
GET    /api/seo/competitors/{seoCompetitor}/keywords  perm:seo.competitors
POST   /api/seo/projects/{seoProject}/competitors/sync     perm:seo.sync
POST   /api/seo/projects/{seoProject}/competitors/discover perm:seo.sync

GET    /api/seo/keyword-gap                       perm:seo.keywords
GET    /api/seo/keyword-gap/export                perm:seo.reports
GET    /api/seo/backlink-gap                      perm:seo.competitors

GET    /api/seo/content/gap                       perm:seo.content
GET    /api/seo/content/opportunities             perm:seo.content
GET    /api/seo/content/briefs                    perm:seo.content
POST   /api/seo/content/briefs                    perm:seo.content
POST   /api/seo/content/briefs/{seoContentBrief}/send-to-calendar  perm:seo.content
GET    /api/seo/content/social-accounts           perm:seo.content

GET    /api/seo/serp                              perm:seo.keywords
GET    /api/seo/serp/export                       perm:seo.reports
POST   /api/seo/projects/{seoProject}/serp        perm:seo.sync
GET    /api/seo/serp/{seoSerpSnapshot}            perm:seo.keywords

GET    /api/seo/audit                             perm:seo.analytics
GET    /api/seo/audit/export                      perm:seo.reports
POST   /api/seo/projects/{seoProject}/audit       perm:seo.analytics
GET    /api/seo/audit/{seoSiteAuditRun}           perm:seo.analytics

GET    /api/seo/internal-links                    perm:seo.content
POST   /api/seo/projects/{seoProject}/internal-links/analyze  perm:seo.content
PUT    /api/seo/internal-links/{seoInternalLinkSuggestion}    perm:seo.content
DELETE /api/seo/internal-links/{seoInternalLinkSuggestion}    perm:seo.content

GET    /api/seo/ai/status                         perm:seo.view
GET    /api/seo/ai/recommendations                perm:seo.content
GET    /api/seo/ai/keyword-analysis               perm:seo.content
POST   /api/seo/ai/generate/metas                 perm:seo.content   — admin picks the count (1-30)
POST   /api/seo/ai/generate/blogs                 perm:seo.content   — admin picks the count (1-10)
GET    /api/seo/ai/generations                    perm:seo.content   — history (?type=meta|blog)
GET    /api/seo/ai/generations/export             perm:seo.content   — ?format=xlsx|csv
DELETE /api/seo/ai/generations/{seoAiGeneration}  perm:seo.content

GET    /api/seo/reports                           perm:seo.reports
GET    /api/seo/reports/export                    perm:seo.reports
GET    /api/integrations/seo                      (admin session)
POST   /api/integrations/seo/generate             (admin session)
GET    /api/integrations/seo/health               (admin session)
GET    /api/integrations/seo/gsc                  (admin session)
POST   /api/integrations/seo/gsc                  (admin session)
GET    /sitemap.xml  /robots.txt                   (public)
```

Frontend reference: the Next.js app exposes the same SEO knobs at build time —
`NEXT_PUBLIC_SITE_URL` / `NEXT_PUBLIC_API_URL` bake `app/sitemap.ts`,
`app/robots.ts` and `app/llms.txt` into the compiled export during the
customer's install build, and runtime meta (titles, canonicals, OG/Twitter,
robots directives) comes from the backend `/api/settings` SEO fields.
