# WebCrawlers SEO Automation Platform

An AI-powered SEO automation platform built on CodeIgniter 4. Logged-in users manage website projects, run technical audits, track rankings, research keywords, generate and review AI content, and measure performance. The dashboard renders server-side and hydrates itself through a versioned REST API that mobile apps and public integrations can reuse.

---

## Table of Contents

1. [How This Repo Works](#how-this-repo-works)
2. [Developer Setup](#developer-setup)
3. [URL Structure](#url-structure)
4. [Environment Detection](#environment-detection)
5. [Configuration & Secrets](#configuration--secrets)
6. [Database](#database)
7. [Background Jobs](#background-jobs)
8. [Authentication & Authorization](#authentication--authorization)
9. [Project Architecture](#project-architecture)
10. [Folder Structure](#folder-structure)
11. [Adding a New Dashboard Page](#adding-a-new-dashboard-page)
12. [Adding a New API Endpoint](#adding-a-new-api-endpoint)
13. [Design Assets](#design-assets)
14. [External Integrations](#external-integrations)
15. [Feature Status](#feature-status)
16. [Known Gaps](#known-gaps)
17. [Related Documents](#related-documents)

---

## How This Repo Works

The project runs on a **shared dev server** at `/var/www/php85/<username>/webcrawlers_latest.com/`. Multiple developers work on the same box; each clones into their own home directory under `/var/www/php85/<username>/`.

The server is already configured with PHP 8.5 and MySQL. There is **no Docker and no local install step**. You edit files directly on the server (via SSH, SFTP, or an IDE with remote support) and hit the URL in your browser to test.

There is **no `.env` file** — config lives in tracked PHP files so every developer shares the same settings after a `git pull`. See [Configuration & Secrets](#configuration--secrets) for why that needs to change before production.

---

## Developer Setup

### 1. Clone the repo

```bash
cd /var/www/php85/<your-username>/
git clone <repo-url> webcrawlers_latest.com
cd webcrawlers_latest.com
```

### 2. Install dependencies

`vendor/` is **committed to the repo**, so a fresh clone is already runnable and
this step is normally unnecessary. Run it only after a `composer.json` change:

```bash
php8.5 /usr/bin/composer install
```

### 3. Set folder permissions

```bash
chmod -R 775 writable/
```

### 4. Set up the database

Run the migrations and seeds — see [Database](#database). On the shared dev server the credentials resolve automatically, so this is usually just:

```bash
php8.5 spark migrate
php8.5 spark db:seed DatabaseSeeder
```

[schema.md](schema.md) has the full runbook, including the staging/production procedure and the verification queries.

### 5. Access the site

| Path | URL |
|---|---|
| Public website | `http://192.168.30.106/php85/<your-username>/webcrawlers_latest.com/public/` |
| Dashboard | `http://192.168.30.106/php85/<your-username>/webcrawlers_latest.com/public/?/dashboard` |
| API | `http://192.168.30.106/php85/<your-username>/webcrawlers_latest.com/public/?/api/v1/dashboard` |

> The `?/` prefix is the query-string router used on the shared dev server, which has no rewrite rules. `App::__construct()` detects the sandbox path and sets `indexPage = '?'` automatically, so `site_url()` and `url_to()` produce working links without any manual config.

### 6. Fill in API keys

Open `app/Config/Constants.php` and set the `WC_*` constants — see [Configuration & Secrets](#configuration--secrets). On the shared dev server these are already populated.

---

## URL Structure

```
webcrawlers.com/              ← public marketing site   (Pages, Blog, Auth, Lead)
webcrawlers.com/<module>      ← logged-in dashboard UI  (one controller per module)
webcrawlers.com/api/v1/       ← REST API                (Api\V1\* controllers)
webcrawlers.com/px/*          ← tracking pixel ingest   (public, CORS)
webcrawlers.com/webhooks/*    ← DataForSEO pingbacks    (public)
```

**Dashboard routes are flat, not nested under `/dashboard`.** Each module is a top-level path with its own controller and its own `['filter' => 'auth']`:

```php
$routes->get('competitors',  'CompetitorsController::index',  ['filter' => 'auth']);
$routes->get('rank-tracking','RankTrackingController::index',  ['filter' => 'auth']);
$routes->get('settings/users','UserController::index',         ['filter' => 'auth']);
```

Only `/dashboard` itself maps to the `Dashboard` controller (the home page). There is no route group for the UI — the filter is declared per route. All `/api/v1/*` routes **are** in a group, protected by `apiauth`.

The full route list is in [app/Config/Routes.php](app/Config/Routes.php).

---

## Environment Detection

`CI_ENVIRONMENT` is set in `public/index.php` before CI4 boots, and `App::__construct()` applies matching URL config:

| Runtime context | `CI_ENVIRONMENT` | `baseURL` / `indexPage` |
|---|---|---|
| `/var/www/phpNN/...` (any dev sandbox) | `development` | Host + sandbox path + `/public/`, `indexPage = '?'` |
| `staging.webcrawlers.com` | `development` | Follows request scheme |
| `dev.webcrawlers.com` | `development` | Follows request scheme |
| `192.168.*`, `127.*`, `localhost` | `development` | Follows request scheme |
| anything else | `production` | Declared `$baseURL` |

Note that staging currently resolves to `development`, not `testing` — errors and the debug toolbar behave as they do in dev there. Only unrecognised hosts fall through to `production`.

Setting `CI_ENVIRONMENT` in the server environment or on the CLI overrides all of the above; the detection block only runs when it is unset. That is why the CLI examples in [schema.md](schema.md) prefix commands with `CI_ENVIRONMENT=development`.

---

## Configuration & Secrets

**No `.env` file is used.** All values live in `app/Config/Constants.php` so they are shared across the team via Git.

> ⚠️ **These are live credentials in a tracked file.** Google OAuth, DataForSEO, OpenAI, Gemini, Sticky.io and ZeptoMail secrets are in Git history and must be treated as compromised. Before production: rotate every key, move the values to the server environment or a `.gitignore`d `.env`, and restore empty defaults here.

| Constant | Purpose |
|---|---|
| `WC_ENCRYPTION_KEY` | Signs API tokens (HMAC-SHA256). Generate with `php -r "echo bin2hex(random_bytes(32));"` |
| `WC_OPENAI_API_KEY` / `WC_OPENAI_MODEL` | OpenAI — content generation, analysis |
| `WC_GEMINI_API_KEY` / `WC_GEMINI_MODEL` | Gemini — fallback content provider |
| `WC_DATAFORSEO_LOGIN` / `_PASSWORD` / `_API_KEY` | DataForSEO account credentials |
| `WC_GOOGLE_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` | Google OAuth2 (GSC / GA4 / GBP) |
| `WC_STICKY_API_URL` / `_URL_V2` / `_USERNAME` / `_PASSWORD` | Sticky.io subscription billing gateway |
| `ZEPTOMAIL_API_URL` / `ZEPTOMAIL_API_KEY` | Transactional email (OTP, invites, receipts) |

`WC_HUBSPOT_API_KEY` and `WC_FRESHDESK_*` are present but commented out — no CRM integration is wired up yet.

`Encryption.php` references `WC_ENCRYPTION_KEY` directly so the CI4 encryption service and HMAC token signing always use the same key. Changing it invalidates every issued API token.

**Database credentials** come from `MSACOMMON_PATH . 'dbConstants.php'` — a shared library on the dev server. `Database.php` reads `MSACOMMON_DB_HOST_CMS`, `MSACOMMON_DB_USER_CMS` and `MSACOMMON_DB_PASS_CMS` from it automatically.

---

## Database

- **Driver:** MySQL 5.7 via MySQLi
- **Collation:** `utf8mb4_unicode_ci` on every table and column (8.0-only collations are unavailable)
- **Migrations:** `app/Database/Migrations/` — 44 migrations (consolidated first-run baseline through `000041`)
- **Seeds:** `app/Database/Seeds/` — countries, modules, module permissions, plans, owner accounts
- **Dev data dump:** `dev-data/` — see `dev-data/README.md`

**[schema.md](schema.md) is the authoritative schema reference.** It documents all 65 tables (64 `wc_*` tables plus `migrations`) with indices, foreign keys, the migration-to-table map, and a full sysadmin runbook for staging and production. Do not use `TASKS.md` for column definitions — it predates the current schema.

```bash
php8.5 spark migrate         # apply all migrations
php8.5 spark migrate:status  # 44 migrations across batches, on a fresh DB
php8.5 spark db:seed DatabaseSeeder
```

Migration order is load-bearing: `wc_users` / `wc_countries` come first because everything keys off them, and `wc_websites` must exist before `wc_automation_queue` (foreign key). Never run them individually or out of order.

> All tables are fully migrated, including `wc_evidence`, `wc_evidence_services`, `wc_evidence_reviews`, and `wc_change_plan_requests` via `2026-08-25-000018_CreateEvidenceAndPlanRequestTables.php`.

---

## Background Jobs

**No Redis, no Supervisor** — both need sudo and are unavailable on the shared dev server. Async work uses a **DB-backed queue** in `wc_automation_queue`.

### How it runs

Statuses move `pending → processing → completed`, with automatic retry up to 3 times before `failed`. Last run time per site is tracked in `wc_websites.last_automation_run`.

**Cron (recommended).** `webcrawlers_cron.sh` queues due recurring crawl schedules, then processes pending jobs. Schedule start times are UTC; the script should run at least every five minutes and appends output to `writable/logs/automation_queue.log`:

```bash
*/5 * * * * /home/<username>/webcrawlers_cron.sh
```

Or call both commands directly:

```bash
php8.5 spark automation:schedule --limit=100
php8.5 spark automation:process --limit=10
```

The optional `POST /api/v1/automation/process` endpoint can also process pending jobs on demand.

### Inspecting the queue

```sql
SELECT * FROM wc_automation_queue WHERE status = 'pending';
```

Recurring schedules expose `next_run_at` and `last_run_at` in UTC. A schedule is queued only when its due time has passed and the website's automation setting is enabled.

### What the processor does

`AutomationProcess` (`app/Commands/AutomationProcess.php`) and `Api\V1\AutomationController` claim pending rows and dispatch by job type — audit crawls via `AuditSyncService`, opportunity generation, rank syncing. There is no separate job-class directory; the work lives in the service classes under `app/Libraries/`.

`crawl:schedule` is an alternative crawl-only dispatcher using the same due-schedule queue and atomic worker claims. It respects active website/automation/schedule flags. Team members share the website schedule; saving settings preserves pending or processing jobs. Normally choose either this dispatcher or the repository script rather than installing redundant dispatch cron entries.

Preview without changing jobs or calling DataForSEO:

```bash
php8.5 spark crawl:schedule --dry-run --limit=10
php8.5 spark crawl:poll --dry-run --limit=20
```

`crawl:poll` refreshes running DataForSEO crawls without an open browser. For independent background updates, run `php8.5 spark crawl:poll --limit=20` every five minutes; the repository script only queues and dispatches jobs. Unlike its dry run, polling calls DataForSEO and persists crawl progress. The crawl-only scheduler also polls after dispatching.

> There is no general-purpose `queue_jobs` table and no `spark queue:work` command.

---

## Authentication & Authorization

### Dashboard UI (session-based)

- Sign in → OTP → `session()->set(['user_id' => ..., 'logged_in' => true])`
- `AuthFilter` runs on every route carrying `['filter' => 'auth']`: it checks `session('logged_in')`, reloads the user row, and redirects to `/signin` if either fails.
- It then enforces plan state via `PlanAccess::requiresCheckout()` — users owing checkout are redirected to `/payment` unless they are already on a checkout page. Members waiting on an admin get an explanatory flash message.

### API (Bearer token or session)

`ApiAuthFilter` accepts either:

- **Bearer token** — `base64(JSON{uid, iat}) . "." . HMAC-SHA256(payload, WC_ENCRYPTION_KEY)`, valid for 24 hours, compared with `hash_equals()`.
- **Session** — falls back to `session('logged_in')` when no `Authorization` header is present, which is what same-origin dashboard calls use.

Either way it reloads the user and applies the same `PlanAccess` checkout gate, returning `401` for auth failures and `403` for plan-denied requests.

Tokens are minted per page render by `DashboardModule::generateApiToken()` and published to the browser as `<meta name="api-token">`. `window.wcFetch()` (defined in `layout/bottom.php`) attaches the Bearer header and the CSRF header to every call.

This means the same API serves dashboard JS (session or token), future mobile apps (token only), and a future public API.

### CSRF

`CsrfFilter` extends the framework filter and, instead of throwing, regenerates the token and redirects back with the input preserved so the user can resubmit immediately. It applies globally to POST/PUT/PATCH/DELETE, with these paths excepted in `Config/Filters.php`: `api/*`, `webhooks/*`, `keyword-research/*`, `px/*`.

### Roles, teams and plans

- `TeamAccess` resolves which user IDs a given user may see; models call `visibleUserIds()` so team members share a workspace's data.
- `PlanAccess` and `Config/SubscriptionPlans.php` define per-plan limits (domains, pages crawled, AI drafts, locations, team seats) for Beta Partner, Managed Growth and Enterprise.
- `wc_modules` / `wc_module_permission_mapping` gate sidebar entries — each nav item in `layout/nav.php` carries a `module` key matching `wc_modules.code`.

---

## Project Architecture

```
Public marketing site
        │
        ▼
  Pages / Blog / Auth / Lead controllers
        │
        ▼
Dashboard module controllers  ──────►  flat /<module> routes (HTML, AuthFilter)
  extends DashboardModule                     │
        │                                     ▼
        │                          layout/top + view + layout/bottom
        │                          JS calls wcFetch() on load
        ▼
API v1 controllers  ────────────────►  /api/v1/*  (JSON, ApiAuthFilter)
  extends BaseApiController
        │
        ▼
  Service Layer  (app/Libraries/)
  ┌──────────────────────────────────────────────────┐
  │  DataForSeo             SiteOverviewService      │
  │  AuditSyncService       OwnCrawlAuditService     │
  │  CrawlEngine            CrawlNotifier           │
  │  RankTrackingService    KeywordResearchService  │
  │  AiContentService       AiContentAnalyzerService │
  │  ContentScoringService  GoogleApiService         │
  │  EvidenceService        EvidenceServicesService  │
  │  EvidenceReviewsService GoogleBusinessReviews…   │
  │  StickyLibrary          Otp                      │
  │  PlanAccess             TeamAccess               │
  │  *ExportService (CSV / XLSX / PDF)               │
  └──────────────────────────────────────────────────┘
        │
        ▼
     Models (app/Models/)  ──►  MySQL (wc_* tables)
                                     │
                                     ▼
                            wc_automation_queue
                                     │
                                     ▼
                    php8.5 spark automation:process (cron / API trigger)
        │
        ▼
  ┌──────────────────────────────────────────────────┐
  │  DataForSEO  (OnPage · Keywords · SERP · Labs)   │
  │  OpenAI + Gemini  (content generation, analysis) │
  │  Google APIs  (GSC · GA4 · GBP, via OAuth2)      │
  │  Sticky.io  (subscription billing)               │
  │  ZeptoMail  (transactional email)                │
  │  Own CrawlEngine  (in-house technical crawl)     │
  └──────────────────────────────────────────────────┘
```

**The pattern is Controller → Library → Model → MySQL.** Controllers stay thin: they resolve the user and selected website, call a service, shape the result for the view, and render. Business logic, external API calls and caching belong in `app/Libraries/`. [CompetitorsController.php](app/Controllers/CompetitorsController.php) is a good short example.

---

## Folder Structure

```
app/
  Commands/
    AutomationProcess.php     spark automation:process — general automation worker
    CrawlSchedule.php         spark crawl:schedule — crawl-only scheduler/worker
    CrawlPoll.php             spark crawl:poll — refresh running DataForSEO crawls
  Config/
    App.php                   baseURL + indexPage detection per environment
    Constants.php             WC_* API keys and secrets
    Encryption.php            references WC_ENCRYPTION_KEY
    Filters.php               filter aliases + global CSRF with exceptions
    Routes.php                all routes — public, dashboard, api/v1, px, webhooks
    SubscriptionPlans.php     plan codes, prices and per-plan limits
    OnPageChecks.php          audit check definitions
  Controllers/
    BaseController.php        framework base
    DashboardModule.php       base for every dashboard page — render(), token minting
    Auth.php                  sign-up, sign-in, OTP, password reset
    Pages.php  Blog.php  Lead.php            public site
    Dashboard.php                             dashboard home
    <Module>Controller.php                    one per dashboard module (53 files at root)
    Api/
      KeywordResearchController.php           /api/keyword-research/*
      KeywordListsController.php              /api/keyword-lists/*
      V1/
        BaseApiController.php                 token decode + ok/created/error/notFound
        <Resource>Controller.php              19 REST resources
  Database/
    Migrations/               44 database migrations (baseline + feature migrations)
    Seeds/                    DatabaseSeeder + country, module, plan, user seeders
  Filters/
    AuthFilter.php            session + plan guard for dashboard routes
    ApiAuthFilter.php         Bearer token or session + plan guard for /api/v1/*
    CsrfFilter.php            CSRF with graceful recovery
  Libraries/                  the service layer — 23 classes, see architecture above
  Models/                     33 models over the wc_* tables
  Views/
    layouts/                  public site layouts (main, auth)
    includes/                 public site header, footer, menus, scripts
    dashboard/
      layout/
        top.php               HTML shell — sidebar, topbar, meta tags, extra_css
        bottom.php            closing tags, wcFetch() bootstrap, extra_js
        nav.php               sidebar map; `module` keys gate by plan
        components.php        dash_*() render helpers
      index.php               dashboard home
      <module>.php            one view per module (44 files incl. index and stub)
      stub.php                placeholder for pages not yet built
    <public-page>.php         marketing, auth, pricing, payment views

public/
  index.php                   entry point — sets CI_ENVIRONMENT, boots CI4
  px.js                       tracking pixel served to client websites
  assets/                     ← the LIVE assets the app actually loads
    css/                      dashboard.css + one file per page (82 files)
    js/                       dashboard.js + one file per page (64 files)
    img/  video/
  webcrawlers-dashboard-assets/   ← design reference only, not served
    *.php                     original design files
    includes/                 original layout includes
    assets/                   stale copies of css/js — do NOT edit these

schema.md                     authoritative database reference + deploy runbook
webcrawlers_cron.sh           automation queue cron entry point
dev-data/                     dev database dump + generator
```

---

## Adding a New Dashboard Page

1. **Add a flat route** in [app/Config/Routes.php](app/Config/Routes.php) with the auth filter — not inside a group:

   ```php
   $routes->get('my-page', 'MyPageController::index', ['filter' => 'auth']);
   ```

2. **Create the controller** in `app/Controllers/`, extending `DashboardModule`:

   ```php
   class MyPageController extends DashboardModule
   {
       public function index(): string
       {
           $userId   = (int) session()->get('user_id');
           $websites = (new WebsiteModel())->getForUser($userId);

           return $this->render('dashboard/my-page', [
               'active'       => 'my-page',    // matches the key in nav.php
               'page_title'   => 'My Page',
               'page_kicker'  => 'Site',       // breadcrumb group label
               'extra_css'    => ['my-page'],  // loads assets/css/my-page.css
               'extra_js'     => ['my-page'],  // loads assets/js/my-page.js
               'extra_cdn_js' => [],           // full URLs, e.g. Chart.js
               'websites'     => $websites,
           ]);
       }
   }
   ```

   `render()` composes `layout/top` + your view + `layout/bottom` and injects `user`, `api_token`, `csrf_token` and `csrf_hash` automatically.

3. **Add the nav entry** in `app/Views/dashboard/layout/nav.php` if it needs a sidebar link. The `module` key must match a `wc_modules.code` row, or the item will be hidden for every plan.

4. **Create the view** at `app/Views/dashboard/my-page.php`. Use the design reference at `public/webcrawlers-dashboard-assets/<page>.php` as the template: take everything between the `layout-top.php` and `layout-bottom.php` includes, point hrefs at `site_url('...')`, and use the `dash_*()` helpers from `layout/components.php`.

   Until the view file exists the page renders `stub.php`, so nothing crashes.

5. **Add a service and API endpoint** if the page needs data beyond the initial render — see below. Keep queries and external calls out of the controller.

---

## Adding a New API Endpoint

1. **Create a controller** in `app/Controllers/Api/V1/` extending `BaseApiController`:

   ```php
   class MyController extends BaseApiController
   {
       public function index(): ResponseInterface
       {
           // $this->apiUserId is the authenticated user
           $data = (new MyService())->list($this->apiUserId);

           return $this->ok(['items' => $data]);
       }
   }
   ```

   `BaseApiController` provides `ok()`, `created()`, `error($message, $status)` and `notFound()`. Use these rather than building responses by hand across all API controllers (all controllers in `app/Controllers/Api/V1/`, including `AutomationController`, standardize on `BaseApiController`).

2. **Register the route** inside the `api/v1` group in [app/Config/Routes.php](app/Config/Routes.php):

   ```php
   $routes->get('my-resource', 'MyController::index');
   ```

   Order matters: declare specific paths **before** wildcards, or `(:num)` routes will swallow them. The `websites/plan` and `websites/(:num)` pairs in the group show the required ordering.

3. **Call it from the page JS** with `wcFetch()`, which attaches the Bearer token and CSRF header:

   ```js
   wcFetch('my-resource')
     .then(r => r.json())
     .then(data => { /* render */ });
   ```

Note the API group is exempt from CSRF (`Config/Filters.php`) because token regeneration breaks repeated polling POSTs; authentication is the Bearer token or session instead.

---

## Design Assets

The UI design lives in `public/webcrawlers-dashboard-assets/`. The `*.php` files and `includes/` are **reference only** — they are not CI4 views and are not routed. They exist so developers can open the intended design in a browser without logging in.

This reference directory is deleted before production release. Never include,
require, link to, or load assets from it in application code. Copy page markup
into `app/Views/`, shared PHP helpers into `app/Helpers/`, and runtime assets into
`public/assets/`. Top Pages uses `app/Views/dashboard/top-pages.php` and the
`research` helper; neither depends on the reference directory.

The original dated Top Pages design generates demo reports in JavaScript.
Use the authenticated `top-pages` application route for backend reports, not a
direct design PHP URL. Production research utilities do not contain demo-data
generators; report values come from the cached Top Pages API and its explicit
refresh endpoint.

| Asset | Path | Live? |
|---|---|---|
| Page designs | `public/webcrawlers-dashboard-assets/*.php` | No |
| Reference layout shell | `public/webcrawlers-dashboard-assets/includes/` | No |
| Reference CSS/JS copies | `public/webcrawlers-dashboard-assets/assets/` | No |
| **Dashboard CSS** | `public/assets/css/` | **Yes** |
| **Dashboard JS** | `public/assets/js/` | **Yes** |

**Edit the files under `public/assets/`, not the copies under `webcrawlers-dashboard-assets/assets/`.** `extra_css => ['competitors']` resolves to `base_url('assets/css/competitors.css')`, i.e. `public/assets/css/competitors.css`. Both trees contain a `competitors.css`; only the first is served. Each is cache-busted with `filemtime()`.

When building a view, open the matching design file side by side; `layout/top.php` and `layout/bottom.php` already emit the same HTML shell as the design's `layout-top.php` / `layout-bottom.php`.

---

## External Integrations

| Capability | Service | Constants | Implemented by |
|---|---|---|---|
| Technical audit / crawl | DataForSEO OnPage | `WC_DATAFORSEO_*` | `DataForSeo`, `AuditSyncService` |
| In-house crawl | own PHP crawler | — | `CrawlEngine`, `OwnCrawlAuditService` |
| Keyword research, gap analysis | DataForSEO Keywords / Labs | `WC_DATAFORSEO_*` | `KeywordResearchService` |
| Rank tracking | DataForSEO SERP + pingbacks | `WC_DATAFORSEO_*` | `RankTrackingService` |
| Site overview, competitors, backlinks | DataForSEO Labs | `WC_DATAFORSEO_*` | `SiteOverviewService` |
| Content briefs and scoring | DataForSEO + LLM | both | `ContentScoringService` |
| AI content generation | OpenAI, Gemini fallback | `WC_OPENAI_*`, `WC_GEMINI_*` | `AiContentService` |
| AI page analysis and suggestions | OpenAI | `WC_OPENAI_*` | `AiContentAnalyzerService` |
| Search Console / GA4 / Business Profile | Google APIs (OAuth2) | `WC_GOOGLE_*` | `GoogleApiService`, `GoogleOAuthController` |
| Subscription billing | Sticky.io | `WC_STICKY_*` | `StickyLibrary` |
| Transactional email | ZeptoMail | `ZEPTOMAIL_*` | `Otp`, invite and receipt flows |
| Conversion / vitals tracking | own pixel | — | `PixelController`, `public/px.js` |
| CRM (leads, demos) | not integrated | commented out | leads stored in `wc_leads` only |

Every DataForSEO call is logged to `wc_dataforseo_logs` via `DataForSeo::withLogContext()`, which is the first place to look when an audit or ranking refresh misbehaves.

Google integrations are **built and routed**, not deferred.

---

## Feature Status

Grouped as the sidebar groups them. "Built" means the page is backed by a
service and API endpoints; "UI only" means the controller renders a static view
and no API route or service exists behind it yet.

| Group | Module | State |
|---|---|---|
| Home | Dashboard | Built |
| Site | Website, Crawl Monitoring, Page Inventory, Technical Issues, Crawl History | Built |
| Site Overview | Site Explorer | Built (DataForSEO Labs, DB-cached; existing `site-overview` route) |
| Site Overview | Top Pages | Built (saved websites; DB-cached DataForSEO Labs report with explicit 24-hour refresh) |
| Keywords | Keywords, Rank Tracking, Keyword Research & Gap Analysis | Built |
| AI Content | Generation, History, Content Scoring & Briefs, Content Analyzer | Built |
| Discover | SEO Automation | Built |
| Discover | Competitors | Built |
| Discover | Opportunity Queue | **UI only** |
| Evidence | Library, Services, Reviews | Built — full API + services, fully migrated (`2026-08-25-000018`) |
| Evidence | Brand Rules | **UI only** |
| Publish | Review Queue, Scheduler, Deployments | **UI only** |
| Measure | Search Performance, Conversions, Attribution, Locations, AI Visibility | Built (saved rankings/pixel events/AI responses, optional Google reports) |
| Reports | Audit reports, exports (CSV / XLSX / PDF), sharing | Built |
| Operations | Notifications | Built (SUB-25) |
| Operations | Audit History | Built (hydrates from `GET /api/v1/reports`) |
| Operations | Job Health | **UI only** |
| Settings | Users & Roles, Modules, Connections, Billing, Leads | Built |
| Settings | Workspace | **UI only** |
| Billing | Payment, checkout, subscription, history, cancel, change plan | Built via Sticky.io |

Top Pages is available at `GET /top-pages` with a selector of active websites
visible to the signed-in user's team, using `WebsiteModel` like Site Overview.
The initial landing UI lets users choose a saved website and database; Search
opens the second (report) UI. Back returns to the
landing without fetching data. Both website selectors use the same saved list.
The report's Analyze button reads cache only; Refresh data remains a separate
billable action. Breadcrumbs and header search follow Site Overview → Site
Explorer / Top Pages. Dates use the design's dropdown menu with actual saved
snapshot dates. The device dropdown shows All devices; Desktop/Mobile are
disabled because the Labs data is not device-segmented.
`POST /api/v1/top-pages/search` reads cached results only; the request fields are
`website_id` (a saved, accessible website ID) and `country` (an active ISO2
country with a configured DataForSEO location). Arbitrary targets are not used.
`POST /api/v1/top-pages/refresh` accepts the same fields and explicitly fetches
DataForSEO data, with a server-enforced 24-hour dataset freshness window.
Normal page loads and website/database changes never call DataForSEO, even
when the cache is missing or expired. No saved websites redirects to setup.
The existing `wc_site_overview_cache` stores the raw provider response and
derived report under section `top_pages`, keyed by website/country/language.
The UI shows the saved timestamp and next allowed refresh time.
New reports use the shared Relevant Pages dataset (100 organic pages ordered by
estimated traffic), not an aggregation of 1,000 keywords. Each page's traffic
and keyword counts come from its provider metrics. Summary traffic is the sum
of returned pages, not domain traffic; traffic share uses that same denominator.
The summary distinguishes returned pages from the provider's total ranking-page
count. Missing keyword details, backlink fields and AI metrics remain N/A.
Older keyword-sample reports remain readable.
The latest 36 observed report snapshots are retained
in the existing payload. A read may project an already-saved shared dataset into
this payload, without calling DFS or changing the dataset observation time.
The report date selector, period tabs, and traffic/page
trend chart use only those saved snapshots. New/Lost tabs and traffic differences
compare consecutive returned samples, not confirmed ranking or indexing changes.
Comparisons require two compatible snapshots; a source/account/request change
starts a new series and does not produce false traffic differences or New/Lost.
Historical dates remain selectable; no historical points are fabricated.
A single snapshot is displayed as observed-value dots with a tracking-start
label. Earlier dates are uncollected data, never zero-filled; lines appear once
two or more snapshots are available in the selected period.
Legacy page-level referring domains retain the most recently updated backlink
information returned for that URL. Relevant Pages does not supply the current
keyword/backlink fields. Compatible saved keyword responses may supplement them
without changing organic metrics. Citation keywords and scanned prompt counts
come from separately dated saved sources, not from Relevant Pages.
Device segmentation remains unavailable. A refresh is billable
only when no fresh matching shared dataset exists; use controlled responses for
tests. Reads do not rewrite the dashboard's
`?/top-pages` route.

### Shared DataForSEO datasets

`DfsDatasetService` and `wc_dfs_datasets` share Relevant Pages, selected ranked-keyword
samples and domain overviews between Top Pages and Site Explorer. Apply migrations with
`php8.5 spark migrate` before deploying these consumers. See
[the detailed rollout plan](docs/DFS-plan.md).

Dataset identity includes website ID, a non-secret provider-account hash,
endpoint, schema version and every effective request option. Different limits,
filters, ordering, locations and languages never share a response implicitly.
Authorization still runs in controllers; website-scoped sharing does not grant
cross-customer access. Unmigrated callers retain their existing caches.

Both modules use the same unfiltered Relevant Pages request. Site Explorer's
filtered >=20-keyword count remains a separate limit-1 request. Its other provider
datasets remain distinct unless exact effective requests match. Saved data is usable after expiration; only explicit refresh
may fetch. A matching fresh dataset is reused across module refreshes for 24 hours.

MySQL named locks serialize each exact request without holding a transaction
across the network. A concurrent refresh receives HTTP 409. Provider failures
preserve the last successful response and expose/log the error. A five-minute
attempt guard prevents immediate retries after failures or interrupted requests;
this is not provider-side idempotency, and an ambiguous billable outcome may need
operator investigation. Existing module credit policies are not changed.

The shared row retains the latest successful raw envelope, UTC timestamps, task
ID, reported cost, returned/total counts and separate last-attempt metadata.
Diagnostics remain in DFS logs. The shared store is latest-only; module snapshots
retain history. No automatic log import, retention deletion, extra keyword fetch,
or paid refresh is performed during deployment.

No-network checks when PHPUnit is unavailable:

```bash
php8.5 tests/standalone/dfs-datasets.php
php8.5 tests/standalone/top-pages-enrichment.php
php8.5 tests/standalone/top-pages-citation-refresh.php
php8.5 tests/standalone/site-overview-refresh.php
php8.5 tests/standalone/measure.php
php8.5 tests/standalone/crawl-coverage.php
node tests/standalone/top-pages-reload.js
# Explicit local MySQL check: temporary controlled rows are removed afterward.
php8.5 tests/standalone/dfs-datasets-database.php
```

### Site Explorer scoped refresh

Ordinary reads and exports are cache-only. `POST /api/v1/site-overview/refresh`
accepts `refresh_scope`, defaulting to `overview` (core summary only). The service
also defaults to this scope. The previous behavior of refreshing every report
is now an explicit `all` action, not an implicit side effect of the refresh icon.

| Scope | Data updated |
|---|---|
| `overview` | Domain overview and domain backlinks summary |
| `signals` | Google AI Overview count, brand signal/mentions, homepage rank |
| `content` | Relevant Pages totals, keyword-rich page count, competitor benchmark |
| `history` | Historical rankings |
| `countries` | Country distribution |
| `serp_features` | Featured snippet, local pack and AI Overview counts |
| `organic` / `ppc` | Respective keyword and competitor research |
| `backlinks` | Detailed backlink research |
| `all` | Every expired/missing section above; fresh sections are skipped |

The UI selects the scope and confirms potential paid requests. Every section has
its own 24-hour cooldown; other reports and their timestamps remain unchanged.
Responses retain existing fields and add `section_refresh`, `refresh_scope` and
`refreshed_sections`. Source dates are shown in the expandable disclosure.
Legacy signals/content embedded in metrics remain readable with their original
enrichment date; a core-only refresh does not relabel them as newly observed.
Missing optional signals display a dash rather than a fabricated zero.
No migration or credit-policy change is required.

Core summary makes at most **two provider requests** on an eligible refresh (a
fresh shared domain overview reduces this to one). Fresh repeated core refresh
and ordinary reads make zero. Optional sections are not purchased automatically.
Country requests now reuse exact shared domain overviews, including the selected
country. AI Overview count consumers share the same 30-observation dataset used
by Top Pages citations, not separate limit-1 samples. Normal Site Explorer reads
still do not purchase citations or run AI Visibility scans.

Controlled full-refresh fixtures with ten countries, organic metrics and a
competitor make **31 provider HTTP requests** in total. Full refresh remains
expensive and depends on available countries/data; it is deliberately opt-in.
The country batch helper actually sends one HTTP request per task, not one HTTP
request for all countries. Backlink summaries with different rank scales/status
options and competitor requests with different limits are intentionally not
merged. These are counts, not monetary price estimates.

### Site Explorer design alignment

The live overview uses a compact domain header and the reference design's
desktop Search Type / Brand Insights split, stacking on narrower screens. Source
dates remain available in a full-width bottom-row header disclosure; scoped paid-refresh controls,
copy/open actions, exports and real provider values are preserved. Page-local
styling removes oversized card shadows without changing other modules. Domain
Authority uses DFS backlink rank; its tooltip clarifies that it is not Moz DA or Ahrefs DR.

Brand Insights reads the existing `ai-visibility/summary` API with
`action: "summary"` for the selected website. This adds one local saved-analytics
request per overview load, **not** a DFS/model request or scan. It displays actual
sample visibility, heuristic sentiment and response date/count. AI project
location is distinct from the selected DFS country; this boundary is disclosed.
Empty results link to AI Visibility without fake percentages, upgrade badges or
unsupported platform claims. Failed reads clear stale rows and show an explicit
message; late results from an older selection are discarded.

Validation:
`node tests/standalone/site-overview-brand.js` covers empty/error states, genuine
zeroes, escaped labels and out-of-order responses. The controlled refresh
regressions remain in `tests/standalone/site-overview-refresh.php`.

### Saved Top Pages enrichment

The additive `enrichment` response field contains current saved observations,
not modified historical organic snapshots:

- Google AI Overview: own-site URLs and distinct citation keywords from the saved
  country/language sample. Legacy empty caches without a successful-fetch marker
  are unverified, not confirmed zero. Failed refreshes preserve previous data.
- AI Visibility: own-site citations from up to 1,000 successful responses in the
  latest completed non-simulated matching-context run. Prompt counts deduplicate
  query IDs across platforms and repeated links. They are counts of scanned
  prompts, not total prompts across an LLM. Project context is current; existing
  run records do not snapshot historical country/language configuration.
- Keyword details/backlinks: reuse the exact saved 50-organic-keyword sample;
  never add its traffic to Relevant Pages or replace page keyword totals.
- Domain overview: show saved domain totals separately from returned-page totals.

The source panel displays dates, stale/missing/unverified/error states and sample
coverage. Optional-source errors are logged and surfaced without breaking the
main report. Current citations remain explicitly separate when an older organic
report is selected; current per-row enrichment is not applied to historical rows.

Site Explorer's selected domain/organic/paid refreshes populate shared datasets.
Its overview refresh does not fetch the separate Google AI Overview citation sample.
Top Pages provides **Refresh Google citations** through authenticated
`POST /api/v1/top-pages/citations/refresh`, using the same authorized website and
country resolution as report reads. It explicitly invokes the citation-fetching
service and reloads current enrichment without purchasing organic pages or
changing organic history. It is independent of the organic refresh cooldown.
The action requires browser confirmation: a fresh exact-context sample is reused
for 24 hours; otherwise it may purchase one DFS ranked-keyword request with
`item_types: ["ai_overview_reference"]`, limit 30. A successful empty sample is a
valid zero, not a guarantee of cited pages. This does not run AI Visibility scans,
fetch domain/keyword detail, or buy backlinks. Failed citation refreshes surface
an error and preserve stored observations; Analyze can reload the saved report.
Shared locking and failed-attempt retry guards still apply.

No read purchases missing enrichment. Top Pages returns a free
`refresh_preview`; an anticipated paid refresh requires browser confirmation.
No monetary cost is guessed, and server-side freshness checks remain authoritative.

Operators can run `php8.5 spark dfs:datasets` without provider calls. It reports
fresh/stale datasets, failed attempts, and **latest stored response costs, not
lifetime spend**. Read/miss, dispatch, fresh-refresh reuse and lock conflicts are
logged at info level when enabled. Full cost dashboards, pricing estimates,
budget enforcement and new credit policies remain separate work.

### Measure data contracts

Measure pages hydrate through authenticated `/api/v1/` endpoints. Explicit
website IDs must be visible to the caller; an unknown/inaccessible ID returns
404 instead of falling back to the first website. Conversions accepts both
`website_id` and the older `websiteId` spelling.

- Search Performance prefers GSC, including successful empty reports. Its
  7/28/90-day presets end three days ago; custom `date_from` / `date_to`
  (inclusive `YYYY-MM-DD`) are supported. GSC totals cover at most 250 returned
  queries, not the whole property. Without usable GSC, the latest saved tracking
  snapshot is explicitly labelled `period_applied: false`; date controls are
  disabled rather than implying historical totals. The design-aligned toolbar
  combines periods, saved website and device; source details are expandable
  (automatically expanded on errors). Query badges, numeric alignment,
  keyboard-accessible sorting, filtering and pagination operate on returned rows
  only. No mock totals, comparison deltas or unsupported country/page filters
  are copied from the design.
- Conversions counts recorded pixel events, not unique/qualified leads.
  `revenue_by_currency` contains separate `{currency, value}` entries. Legacy
  scalar `revenue` is populated only for one known currency, accompanied by
  `currency`; mixed or unknown currencies must not be summed or shown as USD.
  `completeness` is value coverage, not CRM matching. Missing revenue stays null;
  genuine zero stays zero. Presets cover complete days ending yesterday and
  custom inclusive dates are supported. GA4 key events remain a separate sample.
- Attribution uses the historical ranking URL, preserving host, path/query case
  and trailing slash; root-relative deployments resolve against the website
  domain. HTTP/HTTPS are treated as the same page. The deployment day and
  incomplete current day are excluded. Both 14-day windows use paired
  keyword/device cohorts with per-keyword daily averages, not raw ETV sums.
  Fewer than seven observed days per keyword on either side is low confidence;
  high requires all 14 days on both sides, a completed window and no overlapping
  deployment. "Measured" counts only comparable rows. Aggregate traffic changes
  require adequate ETV coverage too. This is correlation, not causal attribution.
- Locations uses latest saved rank-tracking locations, not branch attribution.
  Its optional GA4 city report covers the last 28 complete days. Bars are
  explicitly relative to the strongest location/city, not percentages of totals.
- AI Visibility describes sampled API answers and heuristic sentiment, not a
  census of consumer search interfaces. Reports is an audit-results/export page,
  not a consolidated monthly traffic or revenue report. Failed crawl-status
  refreshes are logged and surfaced as stale saved results.

`MeasureGoogleSource` caches the three Measure Google report projections for one
hour using website, integration/property/connection identity, report, device and
exact dates. A failed refresh preserves a previously successful report and
labels it stale for up to seven days; failures have a five-minute retry cooldown.
Source states distinguish missing, empty, ready, stale and error, with
observation/expiry dates.
The existing CI cache backend stores these envelopes; they are not DFS datasets,
and clearing the application cache removes them. Dashboard/other existing Google
consumers keep their existing live-read/null-fallback contracts. No automatic
paid DFS or AI refresh is added.

Focused no-network regression commands:

```bash
php8.5 tests/standalone/measure.php
php8.5 tests/standalone/measure-google-cache.php
```

`php8.5 tests/standalone/measure-database.php` runs real MySQL/controller checks
using transactional pixel-event fixtures, then rolls them back. It explicitly
uses the local default database configuration and makes no provider calls.

Thin UI controllers do not imply static pages: check their API routes and any
shared JavaScript request helpers as well as direct `wcFetch()` calls.

Do not read a thin controller as unfinished on its own — `RankTrackingController`
is 20 lines because the page hydrates through `Api\V1\RankTrackingController`
and `RankTrackingService`. Thin controller **plus** no API route is the signal.

`TASKS.md` and `JIRA_TICKETS.md` hold the original per-ticket breakdown. Both predate much of the above — treat the code and this table as authoritative.

---

## Known Gaps

Live issues a new developer should know about, rather than rediscover:

1. **Secrets are committed.** See the warning in [Configuration & Secrets](#configuration--secrets). Rotation is required before any public deployment.

2. **Test coverage is incomplete.** Focused standalone service/cache regressions exist under `tests/standalone/`, alongside PHPUnit tests, but these do not constitute full application coverage. The PHPUnit runner is unavailable in the current checkout. `phpstan.neon` and `psalm.xml` are also configured.

3. **Staging runs as `development`.** `public/index.php` maps `staging.webcrawlers.com` to the `development` environment, so error display and the toolbar behave as they do in dev. Intentional or not, it is worth knowing before debugging there.

---

## Related Documents

| Document | What it is | Current? |
|---|---|---|
| [schema.md](schema.md) | Full database reference + staging/production deploy runbook | Yes — authoritative |
| [docs/project.md](docs/project.md) | Full technical architecture, modules, background jobs & integration guide | Yes — authoritative |
| `dev-data/README.md` | Dev database dump and how to regenerate it | Yes |
| [docs/DFS-plan.md](docs/DFS-plan.md) | DataForSEO shared datasets rollout plan | Yes |
| [docs/DFS-dependency-reduction-roadmap.md](docs/DFS-dependency-reduction-roadmap.md) | External provider dependency reduction plan | Yes |
| `TASKS.md`, `JIRA_TICKETS.md` | Original per-ticket task breakdown | Partly superseded |
