Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Track a business's Google Maps rankings across a local grid (#1021)
Carter Smith5a8d30517eab
diff --git a/.agents/PAPERCUTS.md b/.agents/PAPERCUTS.mdindex c87f9d4b..a73006fc 100644--- a/.agents/PAPERCUTS.md+++ b/.agents/PAPERCUTS.md@@ -10,6 +10,8 @@ data, or sensitive paths.## Open+- [ ] `2026-10-19T19:28:32Z` — `codex` — `pnpm cf-typegen` regenerates thousands of unrelated runtime types and changes `Env` inheritance, breaking existing Workflow fixtures and ambient bindings. Split binding generation from runtime updates so a new binding can be generated without an unrelated type migration; meanwhile declare new bindings in `src/env.d.ts`.+- [ ] `2026-10-06T04:32:17Z` — `claude` — `npm --prefix web run types:check` (the web-content skill's final check) fails on a fresh worktree with only `web/` deps installed: `web/tsconfig.json` includes `**/*.ts`, so it type-checks `web/tests/free-tool-verification.spec.ts`, which imports the root-only `@playwright/test` and reports TS2307 plus a dozen implicit-any errors unrelated to the change. Add `@playwright/test` to `web` devDependencies or exclude that spec from `web/tsconfig.json`.- [ ] `2026-09-30T23:24:29Z` — `claude` — An `ENV_PREVIEW` secret without `AUTH_MODE=local_noauth` makes the PR preview deploy fall back to `cloudflare_access`, which provisions a self-host Access app. The deploy then fails with "Could not read the Zero Trust organization: Unauthorized", because the CI token has no Access permissions. The error suggests `pnpm alchemy login --configure`, which cannot fix CI. Check `AUTH_MODE` in the workflow's "Derive preview URL" step, beside the existing `WORKERS_SUBDOMAIN` check.- [ ] `2026-09-30T22:10:17Z` — `claude` — Since #784 moved `@tanstack/react-start` to 1.168.60, `pnpm vite build` rewrites the committed `src/routeTree.gen.ts` with a new import order (about 1,000 changed lines, identical routes), which leaves every local build with a dirty tree. Commit the regenerated file on main once.diff --git a/.env.example b/.env.exampleindex 5eef40e8..278e415f 100644--- a/.env.example+++ b/.env.example@@ -4,6 +4,10 @@# Required for SEO data features. See docs/DATAFORSEO_API_KEY.md.# DATAFORSEO_API_KEY=+# Google Maps basemap for Local SEO. Server-only key for Map Tiles API.+# Set on the app server at runtime. See docs/GOOGLE_MAPS_SETUP.md.+# GOOGLE_MAPS_API_KEY=+# Optional app port# PORT=3001diff --git a/.github/workflows/deploy-production.yml b/.github/workflows/deploy-production.ymlindex 1a10c6fe..75681453 100644--- a/.github/workflows/deploy-production.yml+++ b/.github/workflows/deploy-production.yml@@ -68,6 +68,7 @@ jobs:DUB_API_KEY: ${{ secrets.DUB_API_KEY }}META_CONVERSIONS_API_TOKEN: ${{ secrets.META_CONVERSIONS_API_TOKEN }}GDPR_ERASURE_SECRET: ${{ secrets.GDPR_ERASURE_SECRET }}+ GOOGLE_MAPS_API_KEY: ${{ secrets.GOOGLE_MAPS_API_KEY }}run: |# Alchemy replaces the worker's complete var/secret set on every# deploy, and most values are optional-with-empty-default in the@@ -83,7 +84,7 @@ jobs:LOOPS_TRANSACTIONAL_INVITATION_IDAUTUMN_SECRET_KEY AUTUMN_WEBHOOK_SECRET)optional=(CONTEXT_API_KEY OPENROUTER_API_KEY DUB_API_KEY- META_CONVERSIONS_API_TOKEN GDPR_ERASURE_SECRET+ META_CONVERSIONS_API_TOKEN GDPR_ERASURE_SECRET GOOGLE_MAPS_API_KEYLOOPS_PRODUCT_UPDATES_LIST_ID META_PIXEL_IDPOSTHOG_PUBLIC_KEY POSTHOG_HOST OPENROUTER_MODELOPENSEO_TELEMETRY_DISABLED)@@ -143,3 +144,4 @@ jobs:DUB_API_KEY: ${{ secrets.DUB_API_KEY }}META_CONVERSIONS_API_TOKEN: ${{ secrets.META_CONVERSIONS_API_TOKEN }}GDPR_ERASURE_SECRET: ${{ secrets.GDPR_ERASURE_SECRET }}+ GOOGLE_MAPS_API_KEY: ${{ secrets.GOOGLE_MAPS_API_KEY }}diff --git a/deploy/.env.preview.example b/deploy/.env.preview.exampleindex 6cd327a3..d9088d8f 100644--- a/deploy/.env.preview.example+++ b/deploy/.env.preview.example@@ -20,6 +20,9 @@ AUTH_MODE=local_noauth# Optional.+# Local SEO basemap. Server-only Map Tiles API key; use a separate preview key.+# See docs/GOOGLE_MAPS_SETUP.md.+# GOOGLE_MAPS_API_KEY=# OPENROUTER_API_KEY=# OPENROUTER_MODEL=# POSTHOG_PUBLIC_KEY=diff --git a/deploy/.env.selfhost.example b/deploy/.env.selfhost.exampleindex 7e59f616..3d8e5277 100644--- a/deploy/.env.selfhost.example+++ b/deploy/.env.selfhost.example@@ -10,6 +10,10 @@ ACCESS_ALLOWED_EMAILS=# ---------- Optional — uncomment to use ----------+# Local SEO basemap. Server-only Map Tiles API key.+# See docs/GOOGLE_MAPS_SETUP.md.+# GOOGLE_MAPS_API_KEY=+# Google Search Console (all three together) — docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md# GOOGLE_CLIENT_ID=# GOOGLE_CLIENT_SECRET=diff --git a/deploy/alchemy/alchemy.run.ts b/deploy/alchemy/alchemy.run.tsindex de515c3a..7380b72c 100644--- a/deploy/alchemy/alchemy.run.ts+++ b/deploy/alchemy/alchemy.run.ts@@ -259,6 +259,7 @@ const dataEnv = {CRAWLER_ACCESS_SECRET: optionalSecret("CRAWLER_ACCESS_SECRET"),GOOGLE_CLIENT_ID: optionalVar("GOOGLE_CLIENT_ID"),GOOGLE_CLIENT_SECRET: optionalSecret("GOOGLE_CLIENT_SECRET"),+ GOOGLE_MAPS_API_KEY: optionalSecret("GOOGLE_MAPS_API_KEY"),OPENROUTER_API_KEY: optionalSecret("OPENROUTER_API_KEY"),OPENROUTER_MODEL: optionalVar("OPENROUTER_MODEL"),CONTEXT_API_KEY: optionalSecret("CONTEXT_API_KEY"),diff --git a/docs/GOOGLE_MAPS_SETUP.md b/docs/GOOGLE_MAPS_SETUP.mdnew file mode 100644index 00000000..1910593d--- /dev/null+++ b/docs/GOOGLE_MAPS_SETUP.md@@ -0,0 +1,94 @@+# Google Maps setup for Local SEO++Local SEO uses Google's Map Tiles API for its basemap. OpenSEO gets+the ranking results from DataForSEO. Viewing the map requests Google tiles;+running a ranking scan uses DataForSEO credits separately.++## Create the Google Cloud key++1. Select or create a project in [Google Cloud Console](https://console.cloud.google.com/).+2. [Enable billing](https://developers.google.com/maps/documentation/tile/usage-and-billing)+ for that project, then enable **Map Tiles API** in the API Library.+3. In **APIs & Services > Credentials**, create an API key.+4. Set its API restriction to **Map Tiles API** only and save it.+5. If your server has fixed outbound IP addresses, use the **IP addresses**+ application restriction to allow those addresses. Website referrer+ restrictions do not apply to this server integration. Cloudflare Workers+ do not provide a fixed outbound IP by default, so do not enter your app's+ domain or its inbound IP address here.+6. Set a daily tile-request quota in **Google Maps Platform > Quotas** that+ fits your usage. Use separate keys for development, previews, and production+ to keep their usage separate.++OpenSEO's server requests Google sessions, tiles, and viewport copyright+information. The browser loads tiles through an authenticated OpenSEO route;+the Google key and session tokens stay on the server. Follow Google's+[API-key security guidance](https://developers.google.com/maps/api-security-best-practices)+when setting restrictions. You only need Map Tiles API for the basemap.++## Configure OpenSEO++Add the key as `GOOGLE_MAPS_API_KEY` in the environment file for your app:++- Local development: `.env.local`.+- Hosted production: `.env.production`.+- Alchemy self-hosting: `.env.selfhost`.+- Preview deployments: `.env.preview`.++Set the variable to the key you created. It is a server secret and is not+included in the client build. The Google+OAuth client ID and secret used for Search Console are separate credentials.++Restart the development process after changing the key:++```sh+pnpm dev:agents+```++For Cloudflare deployments, the Alchemy deploy commands read the respective+environment file and install the key as a Worker secret. For deployments+managed outside Alchemy, set `GOOGLE_MAPS_API_KEY` as a runtime secret on the+app Worker. Docker reads it from `.env` when the container starts. Restart+or redeploy the server after changing the key; it does not need to be in the+Vite build environment.++Open a project's **Local SEO** screen and choose **Add Business** to select+its Google Maps listing and coverage grid. Enter the search terms you want to+track during setup, or use **Manage keywords** after saving.++**Check rankings** checks every tracked keyword at every grid point. The+confirmation shows the total searches and estimated cost. **Latest** shows the+current results for each keyword; **History** compares saved checks by date.+Select a keyword or a history cell to open its map.++A grid preview displays the basemap before you buy a ranking check. You should+see Google Maps branding, copyright information, and grid markers. The map+stays fitted to the grid. Click a completed point's marker to see the+businesses ranking there.++## Missing maps++- **Google Maps is not configured:** set the server key and restart or+ redeploy the app.+- **Request failed (403):** check billing, Map Tiles API enablement, and the+ key's API and server IP restrictions.+- **Request failed (429):** check the project's Maps quotas and usage.+- **Tiles could not load:** inspect requests to `/api/local-seo/maps/` in the+ browser's Network panel. Check that you are signed in and can access the+ project, then check server connectivity, key configuration, and quotas.+ Use the map's retry button after correcting the issue.++The **Points** view remains available when maps cannot load. OpenSEO renews+Google's session tokens and displays Google's attribution for the current+viewport. It streams tiles without storing them for offline use. Browser+caching follows Google's response headers; the proxy does not create a+shared tile cache.++## Billing and attribution++Google bills tile requests, and one map view makes several of them. Check Google's+[current pricing](https://developers.google.com/maps/billing-and-pricing/pricing)+and [Map Tiles API policies](https://developers.google.com/maps/documentation/tile/policies).+Keep the Google Maps logo and data copyright visible when customizing the+map. The bundled Google Maps logo comes unchanged from Google's official+attribution assets linked in those policies.diff --git a/docs/LOCAL_DEVELOPMENT.md b/docs/LOCAL_DEVELOPMENT.mdindex 64e907d6..c2593d10 100644--- a/docs/LOCAL_DEVELOPMENT.md+++ b/docs/LOCAL_DEVELOPMENT.md@@ -49,6 +49,10 @@ pnpm dev:agentsWhen using a git worktree, [portless](https://github.com/vercel-labs/portless) prefixes the branch name, for example `http://feature-name.open-seo.localhost:1355`.+Local SEO maps need a Google Maps server key. Follow+[Google Maps setup](./GOOGLE_MAPS_SETUP.md) to enable the Map Tiles API and set+`GOOGLE_MAPS_API_KEY`. The Points view works without a map key.+## Report share imagesTo test a real report end to end, run the app with `AUTH_MODE=hosted`, share adiff --git a/docs/maintainers/production-deployment.md b/docs/maintainers/production-deployment.mdindex 22dfc708..22548610 100644--- a/docs/maintainers/production-deployment.md+++ b/docs/maintainers/production-deployment.md@@ -33,6 +33,7 @@ deployment branches to `main`. Then add the following.| `CONTEXT_API_KEY` | Site audit JavaScript rendering fallback (optional) || `META_CONVERSIONS_API_TOKEN` | Meta ad signup attribution (optional) || `GDPR_ERASURE_SECRET` | `scripts/erase-user-data.ts` endpoint (optional) |+| `GOOGLE_MAPS_API_KEY` | Local SEO basemap tiles (optional) |Copy the current production values from the live worker before the first run.Alchemy replaces the worker's complete var and secret set on every deploy, so adiff --git a/drizzle/pg/0038_keen_bug.sql b/drizzle/pg/0038_keen_bug.sqlnew file mode 100644index 00000000..6a88ba85--- /dev/null+++ b/drizzle/pg/0038_keen_bug.sql@@ -0,0 +1,100 @@+CREATE TABLE "local_rank_businesses" (+ "id" text PRIMARY KEY NOT NULL,+ "scan_id" text NOT NULL,+ "identity" text NOT NULL,+ "title" text NOT NULL,+ "cid" text,+ "place_id" text,+ "address" text,+ "rating" double precision,+ "reviews" integer+);+--> statement-breakpoint+CREATE TABLE "local_rank_checks" (+ "id" text PRIMARY KEY NOT NULL,+ "project_id" text NOT NULL,+ "tracker_id" text NOT NULL,+ "status" text NOT NULL,+ "error" text,+ "created_at" text NOT NULL,+ "completed_at" text+);+--> statement-breakpoint+CREATE TABLE "local_rank_keywords" (+ "id" text PRIMARY KEY NOT NULL,+ "tracker_id" text NOT NULL,+ "keyword" text NOT NULL,+ "archived_at" text+);+--> statement-breakpoint+CREATE TABLE "local_rank_points" (+ "id" text PRIMARY KEY NOT NULL,+ "scan_id" text NOT NULL,+ "row" integer NOT NULL,+ "col" integer NOT NULL,+ "latitude" double precision NOT NULL,+ "longitude" double precision NOT NULL,+ "status" text NOT NULL,+ "rank" integer,+ "results_count" integer,+ "error" text,+ "collected_at" text+);+--> statement-breakpoint+CREATE TABLE "local_rank_results" (+ "id" text PRIMARY KEY NOT NULL,+ "point_id" text NOT NULL,+ "business_id" text NOT NULL,+ "rank" integer NOT NULL+);+--> statement-breakpoint+CREATE TABLE "local_rank_scans" (+ "id" text PRIMARY KEY NOT NULL,+ "check_id" text NOT NULL,+ "project_id" text NOT NULL,+ "tracker_id" text NOT NULL,+ "keyword_id" text NOT NULL,+ "status" text NOT NULL,+ "error" text,+ "created_at" text NOT NULL,+ "completed_at" text+);+--> statement-breakpoint+CREATE TABLE "local_rank_trackers" (+ "id" text PRIMARY KEY NOT NULL,+ "project_id" text NOT NULL,+ "title" text NOT NULL,+ "address" text,+ "cid" text,+ "place_id" text,+ "latitude" double precision NOT NULL,+ "longitude" double precision NOT NULL,+ "grid_size" integer NOT NULL,+ "spacing_km" double precision NOT NULL,+ "language_code" text NOT NULL,+ "created_at" text NOT NULL+);+--> statement-breakpoint+ALTER TABLE "local_rank_businesses" ADD CONSTRAINT "local_rank_businesses_scan_id_local_rank_scans_id_fk" FOREIGN KEY ("scan_id") REFERENCES "public"."local_rank_scans"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "local_rank_checks" ADD CONSTRAINT "local_rank_checks_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "local_rank_checks" ADD CONSTRAINT "local_rank_checks_tracker_id_local_rank_trackers_id_fk" FOREIGN KEY ("tracker_id") REFERENCES "public"."local_rank_trackers"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "local_rank_keywords" ADD CONSTRAINT "local_rank_keywords_tracker_id_local_rank_trackers_id_fk" FOREIGN KEY ("tracker_id") REFERENCES "public"."local_rank_trackers"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "local_rank_points" ADD CONSTRAINT "local_rank_points_scan_id_local_rank_scans_id_fk" FOREIGN KEY ("scan_id") REFERENCES "public"."local_rank_scans"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "local_rank_results" ADD CONSTRAINT "local_rank_results_point_id_local_rank_points_id_fk" FOREIGN KEY ("point_id") REFERENCES "public"."local_rank_points"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "local_rank_results" ADD CONSTRAINT "local_rank_results_business_id_local_rank_businesses_id_fk" FOREIGN KEY ("business_id") REFERENCES "public"."local_rank_businesses"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "local_rank_scans" ADD CONSTRAINT "local_rank_scans_check_id_local_rank_checks_id_fk" FOREIGN KEY ("check_id") REFERENCES "public"."local_rank_checks"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "local_rank_scans" ADD CONSTRAINT "local_rank_scans_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "local_rank_scans" ADD CONSTRAINT "local_rank_scans_tracker_id_local_rank_trackers_id_fk" FOREIGN KEY ("tracker_id") REFERENCES "public"."local_rank_trackers"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "local_rank_scans" ADD CONSTRAINT "local_rank_scans_keyword_id_local_rank_keywords_id_fk" FOREIGN KEY ("keyword_id") REFERENCES "public"."local_rank_keywords"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "local_rank_trackers" ADD CONSTRAINT "local_rank_trackers_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+CREATE UNIQUE INDEX "local_rank_businesses_scan_identity_idx" ON "local_rank_businesses" USING btree ("scan_id","identity");--> statement-breakpoint+CREATE INDEX "local_rank_checks_tracker_created_idx" ON "local_rank_checks" USING btree ("tracker_id","created_at");--> statement-breakpoint+CREATE UNIQUE INDEX "local_rank_checks_one_active_idx" ON "local_rank_checks" USING btree ("tracker_id") WHERE "local_rank_checks"."status" IN ('queued', 'running');--> statement-breakpoint+CREATE UNIQUE INDEX "local_rank_keywords_tracker_keyword_idx" ON "local_rank_keywords" USING btree ("tracker_id","keyword");--> statement-breakpoint+CREATE UNIQUE INDEX "local_rank_points_scan_position_idx" ON "local_rank_points" USING btree ("scan_id","row","col");--> statement-breakpoint+CREATE UNIQUE INDEX "local_rank_results_point_business_idx" ON "local_rank_results" USING btree ("point_id","business_id");--> statement-breakpoint+CREATE INDEX "local_rank_results_business_idx" ON "local_rank_results" USING btree ("business_id");--> statement-breakpoint+CREATE INDEX "local_rank_scans_tracker_created_idx" ON "local_rank_scans" USING btree ("tracker_id","created_at");--> statement-breakpoint+CREATE INDEX "local_rank_scans_project_idx" ON "local_rank_scans" USING btree ("project_id");--> statement-breakpoint+CREATE UNIQUE INDEX "local_rank_scans_check_keyword_idx" ON "local_rank_scans" USING btree ("check_id","keyword_id");--> statement-breakpoint+CREATE INDEX "local_rank_trackers_project_idx" ON "local_rank_trackers" USING btree ("project_id");\ No newline at end of filediff --git a/drizzle/pg/meta/0038_snapshot.json b/drizzle/pg/meta/0038_snapshot.jsonnew file mode 100644index 00000000..f95d5eba--- /dev/null+++ b/drizzle/pg/meta/0038_snapshot.json@@ -0,0 +1,6204 @@+{+ "id": "a156bda4-a81b-4021-a388-c42d8e1b6fc9",+ "prevId": "a2811087-9d43-412c-ac54-3a079a463e02",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.backlink_snapshots": {+ "name": "backlink_snapshots",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "rank": {+ "name": "rank",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "backlinks": {+ "name": "backlinks",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "referring_domains": {+ "name": "referring_domains",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "broken_backlinks": {+ "name": "broken_backlinks",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "new_backlinks": {+ "name": "new_backlinks",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "lost_backlinks": {+ "name": "lost_backlinks",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "new_referring_domains": {+ "name": "new_referring_domains",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "lost_referring_domains": {+ "name": "lost_referring_domains",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "captured_at": {+ "name": "captured_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "backlink_snapshots_project_captured_idx": {+ "name": "backlink_snapshots_project_captured_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "captured_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "backlink_snapshots_project_id_projects_id_fk": {+ "name": "backlink_snapshots_project_id_projects_id_fk",+ "tableFrom": "backlink_snapshots",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.crawler_credentials": {+ "name": "crawler_credentials",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "host": {+ "name": "host",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "signature_input": {+ "name": "signature_input",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "signature": {+ "name": "signature",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "crawler_credentials_project_host_idx": {+ "name": "crawler_credentials_project_host_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "host",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "crawler_credentials_project_id_projects_id_fk": {+ "name": "crawler_credentials_project_id_projects_id_fk",+ "tableFrom": "crawler_credentials",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.dashboard_step_dismissals": {+ "name": "dashboard_step_dismissals",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "step": {+ "name": "step",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "dashboard_step_dismissals_project_idx": {+ "name": "dashboard_step_dismissals_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "dashboard_step_dismissals_user_id_user_id_fk": {+ "name": "dashboard_step_dismissals_user_id_user_id_fk",+ "tableFrom": "dashboard_step_dismissals",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "dashboard_step_dismissals_project_id_projects_id_fk": {+ "name": "dashboard_step_dismissals_project_id_projects_id_fk",+ "tableFrom": "dashboard_step_dismissals",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "dashboard_step_dismissals_user_id_project_id_step_pk": {+ "name": "dashboard_step_dismissals_user_id_project_id_step_pk",+ "columns": [+ "user_id",+ "project_id",+ "step"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.data_refresh_claims": {+ "name": "data_refresh_claims",+ "schema": "",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "data_refresh_claims_organization_id_organization_id_fk": {+ "name": "data_refresh_claims_organization_id_organization_id_fk",+ "tableFrom": "data_refresh_claims",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.keyword_metrics": {+ "name": "keyword_metrics",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "search_volume": {+ "name": "search_volume",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "cpc": {+ "name": "cpc",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "competition": {+ "name": "competition",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "keyword_difficulty": {+ "name": "keyword_difficulty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "intent": {+ "name": "intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "monthly_searches": {+ "name": "monthly_searches",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "fetched_at": {+ "name": "fetched_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "keyword_metrics_unique_project_keyword_location_language": {+ "name": "keyword_metrics_unique_project_keyword_location_language",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "language_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "keyword_metrics_lookup_idx": {+ "name": "keyword_metrics_lookup_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "language_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "fetched_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "keyword_metrics_project_id_projects_id_fk": {+ "name": "keyword_metrics_project_id_projects_id_fk",+ "tableFrom": "keyword_metrics",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.organization_activation_state": {+ "name": "organization_activation_state",+ "schema": "",+ "columns": {+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "first_mcp_authorized_at": {+ "name": "first_mcp_authorized_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "first_mcp_tool_call_at": {+ "name": "first_mcp_tool_call_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_activation_state_organization_id_organization_id_fk": {+ "name": "organization_activation_state_organization_id_organization_id_fk",+ "tableFrom": "organization_activation_state",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_activation_state": {+ "name": "project_activation_state",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "competitor_step_clicked_at": {+ "name": "competitor_step_clicked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "keyword_step_clicked_at": {+ "name": "keyword_step_clicked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_card_dismissed_at": {+ "name": "mcp_card_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ga4_card_dismissed_at": {+ "name": "ga4_card_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_activation_state_project_id_projects_id_fk": {+ "name": "project_activation_state_project_id_projects_id_fk",+ "tableFrom": "project_activation_state",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.projects": {+ "name": "projects",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ai_research_keywords": {+ "name": "ai_research_keywords",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "indexnow_key": {+ "name": "indexnow_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "projects_one_default_per_organization_idx": {+ "name": "projects_one_default_per_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"projects\".\"name\" = 'Default' AND \"projects\".\"domain\" IS NULL AND \"projects\".\"archived_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "projects_organization_id_idx": {+ "name": "projects_organization_id_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "projects_organization_id_organization_id_fk": {+ "name": "projects_organization_id_organization_id_fk",+ "tableFrom": "projects",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.rank_check_runs": {+ "name": "rank_check_runs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "keywords_total": {+ "name": "keywords_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "keywords_checked": {+ "name": "keywords_checked",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "is_subset_run": {+ "name": "is_subset_run",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "rank_check_runs_config_idx": {+ "name": "rank_check_runs_config_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_check_runs_project_idx": {+ "name": "rank_check_runs_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_check_runs_one_active_per_config_idx": {+ "name": "rank_check_runs_one_active_per_config_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"rank_check_runs\".\"status\" IN ('pending', 'running')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "rank_check_runs_config_id_rank_tracking_configs_id_fk": {+ "name": "rank_check_runs_config_id_rank_tracking_configs_id_fk",+ "tableFrom": "rank_check_runs",+ "tableTo": "rank_tracking_configs",+ "columnsFrom": [+ "config_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "rank_check_runs_project_id_projects_id_fk": {+ "name": "rank_check_runs_project_id_projects_id_fk",+ "tableFrom": "rank_check_runs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.rank_snapshots": {+ "name": "rank_snapshots",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tracking_keyword_id": {+ "name": "tracking_keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "device": {+ "name": "device",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "serp_features": {+ "name": "serp_features",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "checked_at": {+ "name": "checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "rank_snapshots_keyword_device_idx": {+ "name": "rank_snapshots_keyword_device_idx",+ "columns": [+ {+ "expression": "tracking_keyword_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "device",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "checked_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_snapshots_run_keyword_device_idx": {+ "name": "rank_snapshots_run_keyword_device_idx",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "tracking_keyword_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "device",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "rank_snapshots_run_id_rank_check_runs_id_fk": {+ "name": "rank_snapshots_run_id_rank_check_runs_id_fk",+ "tableFrom": "rank_snapshots",+ "tableTo": "rank_check_runs",+ "columnsFrom": [+ "run_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.rank_tracking_configs": {+ "name": "rank_tracking_configs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "devices": {+ "name": "devices",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'both'"+ },+ "serp_depth": {+ "name": "serp_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "schedule_interval": {+ "name": "schedule_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'weekly'"+ },+ "location_name": {+ "name": "location_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "last_checked_at": {+ "name": "last_checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "next_check_at": {+ "name": "next_check_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_skip_reason": {+ "name": "last_skip_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "rank_tracking_configs_project_active_created_idx": {+ "name": "rank_tracking_configs_project_active_created_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "is_active",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_tracking_configs_national_idx": {+ "name": "rank_tracking_configs_national_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "domain",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "language_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"rank_tracking_configs\".\"location_name\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_tracking_configs_local_idx": {+ "name": "rank_tracking_configs_local_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "domain",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "language_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"rank_tracking_configs\".\"location_name\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "rank_tracking_configs_project_id_projects_id_fk": {+ "name": "rank_tracking_configs_project_id_projects_id_fk",+ "tableFrom": "rank_tracking_configs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.rank_tracking_keywords": {+ "name": "rank_tracking_keywords",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "match_case": {+ "name": "match_case",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "search_volume": {+ "name": "search_volume",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "keyword_difficulty": {+ "name": "keyword_difficulty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "cpc": {+ "name": "cpc",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "metrics_fetched_at": {+ "name": "metrics_fetched_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "pinned_at": {+ "name": "pinned_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "rank_tracking_keywords_config_keyword_idx": {+ "name": "rank_tracking_keywords_config_keyword_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "rank_tracking_keywords_config_id_rank_tracking_configs_id_fk": {+ "name": "rank_tracking_keywords_config_id_rank_tracking_configs_id_fk",+ "tableFrom": "rank_tracking_keywords",+ "tableTo": "rank_tracking_configs",+ "columnsFrom": [+ "config_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.saved_keyword_tag_assignments": {+ "name": "saved_keyword_tag_assignments",+ "schema": "",+ "columns": {+ "saved_keyword_id": {+ "name": "saved_keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "saved_keyword_tag_assignments_unique_idx": {+ "name": "saved_keyword_tag_assignments_unique_idx",+ "columns": [+ {+ "expression": "saved_keyword_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "tag_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "saved_keyword_tag_assignments_tag_idx": {+ "name": "saved_keyword_tag_assignments_tag_idx",+ "columns": [+ {+ "expression": "tag_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "saved_keyword_tag_assignments_saved_keyword_id_saved_keywords_id_fk": {+ "name": "saved_keyword_tag_assignments_saved_keyword_id_saved_keywords_id_fk",+ "tableFrom": "saved_keyword_tag_assignments",+ "tableTo": "saved_keywords",+ "columnsFrom": [+ "saved_keyword_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "saved_keyword_tag_assignments_tag_id_saved_keyword_tags_id_fk": {+ "name": "saved_keyword_tag_assignments_tag_id_saved_keyword_tags_id_fk",+ "tableFrom": "saved_keyword_tag_assignments",+ "tableTo": "saved_keyword_tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.saved_keyword_tags": {+ "name": "saved_keyword_tags",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "normalized_name": {+ "name": "normalized_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "saved_keyword_tags_project_normalized_name_idx": {+ "name": "saved_keyword_tags_project_normalized_name_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "normalized_name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "saved_keyword_tags_project_name_idx": {+ "name": "saved_keyword_tags_project_name_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "saved_keyword_tags_project_id_projects_id_fk": {+ "name": "saved_keyword_tags_project_id_projects_id_fk",+ "tableFrom": "saved_keyword_tags",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.saved_keywords": {+ "name": "saved_keywords",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "saved_keywords_unique_project_keyword_location_language": {+ "name": "saved_keywords_unique_project_keyword_location_language",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "language_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "saved_keywords_project_created_idx": {+ "name": "saved_keywords_project_created_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "saved_keywords_project_id_projects_id_fk": {+ "name": "saved_keywords_project_id_projects_id_fk",+ "tableFrom": "saved_keywords",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_onboarding_answers": {+ "name": "user_onboarding_answers",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "interested_features": {+ "name": "interested_features",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'"+ },+ "work_for": {+ "name": "work_for",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_website_count": {+ "name": "client_website_count",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "found_via": {+ "name": "found_via",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_setup_intent": {+ "name": "mcp_setup_intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gsc_nudge_dismissed_at": {+ "name": "gsc_nudge_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "user_onboarding_answers_organization_idx": {+ "name": "user_onboarding_answers_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_onboarding_answers_user_id_user_id_fk": {+ "name": "user_onboarding_answers_user_id_user_id_fk",+ "tableFrom": "user_onboarding_answers",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_onboarding_answers_organization_id_organization_id_fk": {+ "name": "user_onboarding_answers_organization_id_organization_id_fk",+ "tableFrom": "user_onboarding_answers",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_competitors": {+ "name": "project_competitors",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "project_competitors_project_domain_idx": {+ "name": "project_competitors_project_domain_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "domain",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_competitors_project_id_projects_id_fk": {+ "name": "project_competitors_project_id_projects_id_fk",+ "tableFrom": "project_competitors",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_context_sections": {+ "name": "project_context_sections",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_context_sections_project_id_projects_id_fk": {+ "name": "project_context_sections_project_id_projects_id_fk",+ "tableFrom": "project_context_sections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_context_sections_project_id_key_pk": {+ "name": "project_context_sections_project_id_key_pk",+ "columns": [+ "project_id",+ "key"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_key_pages": {+ "name": "project_key_pages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "topic": {+ "name": "topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "project_key_pages_project_url_idx": {+ "name": "project_key_pages_project_url_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "url",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_key_pages_project_id_projects_id_fk": {+ "name": "project_key_pages_project_id_projects_id_fk",+ "tableFrom": "project_key_pages",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_research_log": {+ "name": "project_research_log",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "entry_date": {+ "name": "entry_date",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "project_research_log_project_date_idx": {+ "name": "project_research_log_project_date_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "entry_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_research_log_project_id_projects_id_fk": {+ "name": "project_research_log_project_id_projects_id_fk",+ "tableFrom": "project_research_log",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.reports": {+ "name": "reports",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "html": {+ "name": "html",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "skill": {+ "name": "skill",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "template_id": {+ "name": "template_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "share_token": {+ "name": "share_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "shared_at": {+ "name": "shared_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "reports_project_updated_idx": {+ "name": "reports_project_updated_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "size_bytes",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "reports_share_token_idx": {+ "name": "reports_share_token_idx",+ "columns": [+ {+ "expression": "share_token",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "reports_project_id_projects_id_fk": {+ "name": "reports_project_id_projects_id_fk",+ "tableFrom": "reports",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.report_templates": {+ "name": "report_templates",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "instructions": {+ "name": "instructions",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "report_templates_project_name_idx": {+ "name": "report_templates_project_name_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "report_templates_project_id_projects_id_fk": {+ "name": "report_templates_project_id_projects_id_fk",+ "tableFrom": "report_templates",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audit_issues": {+ "name": "audit_issues",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "page_id": {+ "name": "page_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "page_url": {+ "name": "page_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "issue_type": {+ "name": "issue_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "severity": {+ "name": "severity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'info'"+ },+ "details_json": {+ "name": "details_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "audit_issues_audit_type_idx": {+ "name": "audit_issues_audit_type_idx",+ "columns": [+ {+ "expression": "audit_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audit_issues_page_id_idx": {+ "name": "audit_issues_page_id_idx",+ "columns": [+ {+ "expression": "page_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audit_issues_audit_id_audits_id_fk": {+ "name": "audit_issues_audit_id_audits_id_fk",+ "tableFrom": "audit_issues",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "audit_issues_page_id_audit_pages_id_fk": {+ "name": "audit_issues_page_id_audit_pages_id_fk",+ "tableFrom": "audit_issues",+ "tableTo": "audit_pages",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audit_lighthouse_results": {+ "name": "audit_lighthouse_results",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "page_id": {+ "name": "page_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "strategy": {+ "name": "strategy",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "performance_score": {+ "name": "performance_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "accessibility_score": {+ "name": "accessibility_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "best_practices_score": {+ "name": "best_practices_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "seo_score": {+ "name": "seo_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "lcp_ms": {+ "name": "lcp_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "cls": {+ "name": "cls",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "inp_ms": {+ "name": "inp_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "ttfb_ms": {+ "name": "ttfb_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "r2_key": {+ "name": "r2_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload_size_bytes": {+ "name": "payload_size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "audit_lighthouse_results_audit_id_idx": {+ "name": "audit_lighthouse_results_audit_id_idx",+ "columns": [+ {+ "expression": "audit_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audit_lighthouse_results_page_id_idx": {+ "name": "audit_lighthouse_results_page_id_idx",+ "columns": [+ {+ "expression": "page_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audit_lighthouse_results_audit_id_audits_id_fk": {+ "name": "audit_lighthouse_results_audit_id_audits_id_fk",+ "tableFrom": "audit_lighthouse_results",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "audit_lighthouse_results_page_id_audit_pages_id_fk": {+ "name": "audit_lighthouse_results_page_id_audit_pages_id_fk",+ "tableFrom": "audit_lighthouse_results",+ "tableTo": "audit_pages",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audit_pages": {+ "name": "audit_pages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status_code": {+ "name": "status_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "redirect_url": {+ "name": "redirect_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "meta_description": {+ "name": "meta_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "canonical_url": {+ "name": "canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "robots_meta": {+ "name": "robots_meta",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "og_title": {+ "name": "og_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "og_description": {+ "name": "og_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "og_image": {+ "name": "og_image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "h1_count": {+ "name": "h1_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h2_count": {+ "name": "h2_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h3_count": {+ "name": "h3_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h4_count": {+ "name": "h4_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h5_count": {+ "name": "h5_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h6_count": {+ "name": "h6_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "word_count": {+ "name": "word_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "images_total": {+ "name": "images_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "images_missing_alt": {+ "name": "images_missing_alt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "internal_link_count": {+ "name": "internal_link_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "external_link_count": {+ "name": "external_link_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "has_structured_data": {+ "name": "has_structured_data",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "is_indexable": {+ "name": "is_indexable",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "x_robots_tag": {+ "name": "x_robots_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "header_canonical_url": {+ "name": "header_canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "crawl_depth": {+ "name": "crawl_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "in_sitemap": {+ "name": "in_sitemap",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "content_hash": {+ "name": "content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "fetch_class": {+ "name": "fetch_class",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'ok'"+ },+ "response_time_ms": {+ "name": "response_time_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "audit_pages_audit_url_idx": {+ "name": "audit_pages_audit_url_idx",+ "columns": [+ {+ "expression": "audit_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "url",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audit_pages_audit_id_audits_id_fk": {+ "name": "audit_pages_audit_id_audits_id_fk",+ "tableFrom": "audit_pages",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audits": {+ "name": "audits",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "started_by_user_id": {+ "name": "started_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "start_url": {+ "name": "start_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'running'"+ },+ "workflow_instance_id": {+ "name": "workflow_instance_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'"+ },+ "pages_crawled": {+ "name": "pages_crawled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "pages_total": {+ "name": "pages_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "lighthouse_total": {+ "name": "lighthouse_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "lighthouse_completed": {+ "name": "lighthouse_completed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "lighthouse_failed": {+ "name": "lighthouse_failed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "current_phase": {+ "name": "current_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'discovery'"+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "error_detail": {+ "name": "error_detail",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "failed_phase": {+ "name": "failed_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "audits_project_id_idx": {+ "name": "audits_project_id_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audits_started_by_user_id_idx": {+ "name": "audits_started_by_user_id_idx",+ "columns": [+ {+ "expression": "started_by_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audits_project_id_projects_id_fk": {+ "name": "audits_project_id_projects_id_fk",+ "tableFrom": "audits",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.sam_sessions": {+ "name": "sam_sessions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'New chat'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "sam_sessions_project_updated_idx": {+ "name": "sam_sessions_project_updated_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "sam_sessions_project_id_projects_id_fk": {+ "name": "sam_sessions_project_id_projects_id_fk",+ "tableFrom": "sam_sessions",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "sam_sessions_user_id_user_id_fk": {+ "name": "sam_sessions_user_id_user_id_fk",+ "tableFrom": "sam_sessions",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "account_accountId_providerId_idx": {+ "name": "account_accountId_providerId_idx",+ "columns": [+ {+ "expression": "account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "account_google_grant_owner_idx": {+ "name": "account_google_grant_owner_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"account\".\"provider_id\" in ('google-search-console', 'google-analytics')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 60000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 120+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "invitation_organizationId_idx": {+ "name": "invitation_organizationId_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "invitation_organization_id_organization_id_fk": {+ "name": "invitation_organization_id_organization_id_fk",+ "tableFrom": "invitation",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": [+ "inviter_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.member": {+ "name": "member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "member_organizationId_idx": {+ "name": "member_organizationId_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "member_userId_idx": {+ "name": "member_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "member_organizationId_userId_uidx": {+ "name": "member_organizationId_userId_uidx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "member_organization_id_organization_id_fk": {+ "name": "member_organization_id_organization_id_fk",+ "tableFrom": "member",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "member_user_id_user_id_fk": {+ "name": "member_user_id_user_id_fk",+ "tableFrom": "member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.organization": {+ "name": "organization",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "organization_slug_uidx": {+ "name": "organization_slug_uidx",+ "columns": [+ {+ "expression": "slug",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "organization_slug_unique": {+ "name": "organization_slug_unique",+ "nullsNotDistinct": false,+ "columns": [+ "slug"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "analytics_opted_out": {+ "name": "analytics_opted_out",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "terms_accepted_version": {+ "name": "terms_accepted_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "terms_accepted_at": {+ "name": "terms_accepted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "product_updates_opt_in": {+ "name": "product_updates_opt_in",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "product_updates_changed_at": {+ "name": "product_updates_changed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_active_organization_id": {+ "name": "last_active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": [+ "email"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "verification_expiresAt_idx": {+ "name": "verification_expiresAt_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_customer_status": {+ "name": "billing_customer_status",+ "schema": "",+ "columns": {+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "is_paying": {+ "name": "is_paying",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "paid_plan_id": {+ "name": "paid_plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "paid_plan_status": {+ "name": "paid_plan_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "customer_json": {+ "name": "customer_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "synced_at": {+ "name": "synced_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "billing_customer_status_organization_id_organization_id_fk": {+ "name": "billing_customer_status_organization_id_organization_id_fk",+ "tableFrom": "billing_customer_status",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ga4_connections": {+ "name": "ga4_connections",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "property_id": {+ "name": "property_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "property_display_name": {+ "name": "property_display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "property_time_zone": {+ "name": "property_time_zone",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "property_currency_code": {+ "name": "property_currency_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "connected_by_user_id": {+ "name": "connected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "ga4_account_id": {+ "name": "ga4_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "connected_account_email": {+ "name": "connected_account_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "ga4_connections_project_idx": {+ "name": "ga4_connections_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ga4_connections_organization_idx": {+ "name": "ga4_connections_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ga4_connections_connector_idx": {+ "name": "ga4_connections_connector_idx",+ "columns": [+ {+ "expression": "connected_by_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "ga4_account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ga4_connections_project_id_projects_id_fk": {+ "name": "ga4_connections_project_id_projects_id_fk",+ "tableFrom": "ga4_connections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ga4_connections_organization_id_organization_id_fk": {+ "name": "ga4_connections_organization_id_organization_id_fk",+ "tableFrom": "ga4_connections",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.gsc_connections": {+ "name": "gsc_connections",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "site_url": {+ "name": "site_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "connected_by_user_id": {+ "name": "connected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "gsc_account_id": {+ "name": "gsc_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "connected_account_email": {+ "name": "connected_account_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "gsc_connections_project_idx": {+ "name": "gsc_connections_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "gsc_connections_organization_idx": {+ "name": "gsc_connections_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "gsc_connections_project_id_projects_id_fk": {+ "name": "gsc_connections_project_id_projects_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "gsc_connections_organization_id_organization_id_fk": {+ "name": "gsc_connections_organization_id_organization_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.telemetry_state": {+ "name": "telemetry_state",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "default": 1+ },+ "install_id": {+ "name": "install_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "installed_at": {+ "name": "installed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_heartbeat_at": {+ "name": "last_heartbeat_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_version": {+ "name": "last_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_tool_call_count": {+ "name": "mcp_tool_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_matches": {+ "name": "ai_matches",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "observation_id": {+ "name": "observation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "own": {+ "name": "own",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "mentioned": {+ "name": "mentioned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "cited": {+ "name": "cited",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "first_mention": {+ "name": "first_mention",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "ai_matches_observation_domain_idx": {+ "name": "ai_matches_observation_domain_idx",+ "columns": [+ {+ "expression": "observation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "domain",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ai_matches_observation_id_ai_observations_id_fk": {+ "name": "ai_matches_observation_id_ai_observations_id_fk",+ "tableFrom": "ai_matches",+ "tableTo": "ai_observations",+ "columnsFrom": [+ "observation_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_observations": {+ "name": "ai_observations",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prompt_id": {+ "name": "prompt_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "engine": {+ "name": "engine",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "branded": {+ "name": "branded",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "collected_at": {+ "name": "collected_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "answer_markdown": {+ "name": "answer_markdown",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "ai_observations_run_prompt_engine_idx": {+ "name": "ai_observations_run_prompt_engine_idx",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "prompt_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "engine",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ai_observations_prompt_idx": {+ "name": "ai_observations_prompt_idx",+ "columns": [+ {+ "expression": "prompt_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ai_observations_run_id_ai_runs_id_fk": {+ "name": "ai_observations_run_id_ai_runs_id_fk",+ "tableFrom": "ai_observations",+ "tableTo": "ai_runs",+ "columnsFrom": [+ "run_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ai_observations_prompt_id_ai_prompts_id_fk": {+ "name": "ai_observations_prompt_id_ai_prompts_id_fk",+ "tableFrom": "ai_observations",+ "tableTo": "ai_prompts",+ "columnsFrom": [+ "prompt_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_prompts": {+ "name": "ai_prompts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "tracker_id": {+ "name": "tracker_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "topic": {+ "name": "topic",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "text": {+ "name": "text",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "paused": {+ "name": "paused",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "archived": {+ "name": "archived",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "ai_prompts_tracker_idx": {+ "name": "ai_prompts_tracker_idx",+ "columns": [+ {+ "expression": "tracker_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ai_prompts_tracker_id_ai_trackers_id_fk": {+ "name": "ai_prompts_tracker_id_ai_trackers_id_fk",+ "tableFrom": "ai_prompts",+ "tableTo": "ai_trackers",+ "columnsFrom": [+ "tracker_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_runs": {+ "name": "ai_runs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "tracker_id": {+ "name": "tracker_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trigger": {+ "name": "trigger",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'queued'"+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "ai_runs_project_created_idx": {+ "name": "ai_runs_project_created_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ai_runs_one_active_idx": {+ "name": "ai_runs_one_active_idx",+ "columns": [+ {+ "expression": "tracker_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"ai_runs\".\"status\" IN ('queued', 'running')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ai_runs_tracker_id_ai_trackers_id_fk": {+ "name": "ai_runs_tracker_id_ai_trackers_id_fk",+ "tableFrom": "ai_runs",+ "tableTo": "ai_trackers",+ "columnsFrom": [+ "tracker_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ai_runs_project_id_projects_id_fk": {+ "name": "ai_runs_project_id_projects_id_fk",+ "tableFrom": "ai_runs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_sources": {+ "name": "ai_sources",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "observation_id": {+ "name": "observation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "ai_sources_observation_idx": {+ "name": "ai_sources_observation_idx",+ "columns": [+ {+ "expression": "observation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ai_sources_observation_id_ai_observations_id_fk": {+ "name": "ai_sources_observation_id_ai_observations_id_fk",+ "tableFrom": "ai_sources",+ "tableTo": "ai_observations",+ "columnsFrom": [+ "observation_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_trackers": {+ "name": "ai_trackers",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "chatgpt": {+ "name": "chatgpt",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "gemini": {+ "name": "gemini",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "claude": {+ "name": "claude",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "perplexity": {+ "name": "perplexity",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "google_ai_overview": {+ "name": "google_ai_overview",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "schedule_interval": {+ "name": "schedule_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'weekly'"+ },+ "next_check_at": {+ "name": "next_check_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_skip_reason": {+ "name": "last_skip_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "ai_trackers_project_idx": {+ "name": "ai_trackers_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ai_trackers_due_idx": {+ "name": "ai_trackers_due_idx",+ "columns": [+ {+ "expression": "enabled",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_check_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ai_trackers_project_id_projects_id_fk": {+ "name": "ai_trackers_project_id_projects_id_fk",+ "tableFrom": "ai_trackers",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.local_rank_businesses": {+ "name": "local_rank_businesses",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "scan_id": {+ "name": "scan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "identity": {+ "name": "identity",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "cid": {+ "name": "cid",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "place_id": {+ "name": "place_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "address": {+ "name": "address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "rating": {+ "name": "rating",+ "type": "double precision",+ "primaryKey": false,+ "notNull": false+ },+ "reviews": {+ "name": "reviews",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "local_rank_businesses_scan_identity_idx": {+ "name": "local_rank_businesses_scan_identity_idx",+ "columns": [+ {+ "expression": "scan_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "identity",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "local_rank_businesses_scan_id_local_rank_scans_id_fk": {+ "name": "local_rank_businesses_scan_id_local_rank_scans_id_fk",+ "tableFrom": "local_rank_businesses",+ "tableTo": "local_rank_scans",+ "columnsFrom": [+ "scan_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.local_rank_checks": {+ "name": "local_rank_checks",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tracker_id": {+ "name": "tracker_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "local_rank_checks_tracker_created_idx": {+ "name": "local_rank_checks_tracker_created_idx",+ "columns": [+ {+ "expression": "tracker_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "local_rank_checks_one_active_idx": {+ "name": "local_rank_checks_one_active_idx",+ "columns": [+ {+ "expression": "tracker_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"local_rank_checks\".\"status\" IN ('queued', 'running')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "local_rank_checks_project_id_projects_id_fk": {+ "name": "local_rank_checks_project_id_projects_id_fk",+ "tableFrom": "local_rank_checks",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "local_rank_checks_tracker_id_local_rank_trackers_id_fk": {+ "name": "local_rank_checks_tracker_id_local_rank_trackers_id_fk",+ "tableFrom": "local_rank_checks",+ "tableTo": "local_rank_trackers",+ "columnsFrom": [+ "tracker_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.local_rank_keywords": {+ "name": "local_rank_keywords",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "tracker_id": {+ "name": "tracker_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "local_rank_keywords_tracker_keyword_idx": {+ "name": "local_rank_keywords_tracker_keyword_idx",+ "columns": [+ {+ "expression": "tracker_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "local_rank_keywords_tracker_id_local_rank_trackers_id_fk": {+ "name": "local_rank_keywords_tracker_id_local_rank_trackers_id_fk",+ "tableFrom": "local_rank_keywords",+ "tableTo": "local_rank_trackers",+ "columnsFrom": [+ "tracker_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.local_rank_points": {+ "name": "local_rank_points",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "scan_id": {+ "name": "scan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "row": {+ "name": "row",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "col": {+ "name": "col",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "latitude": {+ "name": "latitude",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true+ },+ "longitude": {+ "name": "longitude",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "rank": {+ "name": "rank",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "results_count": {+ "name": "results_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "collected_at": {+ "name": "collected_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "local_rank_points_scan_position_idx": {+ "name": "local_rank_points_scan_position_idx",+ "columns": [+ {+ "expression": "scan_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "row",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "col",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "local_rank_points_scan_id_local_rank_scans_id_fk": {+ "name": "local_rank_points_scan_id_local_rank_scans_id_fk",+ "tableFrom": "local_rank_points",+ "tableTo": "local_rank_scans",+ "columnsFrom": [+ "scan_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.local_rank_results": {+ "name": "local_rank_results",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "point_id": {+ "name": "point_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "business_id": {+ "name": "business_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "rank": {+ "name": "rank",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "local_rank_results_point_business_idx": {+ "name": "local_rank_results_point_business_idx",+ "columns": [+ {+ "expression": "point_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "business_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "local_rank_results_business_idx": {+ "name": "local_rank_results_business_idx",+ "columns": [+ {+ "expression": "business_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "local_rank_results_point_id_local_rank_points_id_fk": {+ "name": "local_rank_results_point_id_local_rank_points_id_fk",+ "tableFrom": "local_rank_results",+ "tableTo": "local_rank_points",+ "columnsFrom": [+ "point_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "local_rank_results_business_id_local_rank_businesses_id_fk": {+ "name": "local_rank_results_business_id_local_rank_businesses_id_fk",+ "tableFrom": "local_rank_results",+ "tableTo": "local_rank_businesses",+ "columnsFrom": [+ "business_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.local_rank_scans": {+ "name": "local_rank_scans",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "check_id": {+ "name": "check_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tracker_id": {+ "name": "tracker_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword_id": {+ "name": "keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "local_rank_scans_tracker_created_idx": {+ "name": "local_rank_scans_tracker_created_idx",+ "columns": [+ {+ "expression": "tracker_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "local_rank_scans_project_idx": {+ "name": "local_rank_scans_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "local_rank_scans_check_keyword_idx": {+ "name": "local_rank_scans_check_keyword_idx",+ "columns": [+ {+ "expression": "check_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "local_rank_scans_check_id_local_rank_checks_id_fk": {+ "name": "local_rank_scans_check_id_local_rank_checks_id_fk",+ "tableFrom": "local_rank_scans",+ "tableTo": "local_rank_checks",+ "columnsFrom": [+ "check_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "local_rank_scans_project_id_projects_id_fk": {+ "name": "local_rank_scans_project_id_projects_id_fk",+ "tableFrom": "local_rank_scans",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "local_rank_scans_tracker_id_local_rank_trackers_id_fk": {+ "name": "local_rank_scans_tracker_id_local_rank_trackers_id_fk",+ "tableFrom": "local_rank_scans",+ "tableTo": "local_rank_trackers",+ "columnsFrom": [+ "tracker_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "local_rank_scans_keyword_id_local_rank_keywords_id_fk": {+ "name": "local_rank_scans_keyword_id_local_rank_keywords_id_fk",+ "tableFrom": "local_rank_scans",+ "tableTo": "local_rank_keywords",+ "columnsFrom": [+ "keyword_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.local_rank_trackers": {+ "name": "local_rank_trackers",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "address": {+ "name": "address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "cid": {+ "name": "cid",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "place_id": {+ "name": "place_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "latitude": {+ "name": "latitude",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true+ },+ "longitude": {+ "name": "longitude",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true+ },+ "grid_size": {+ "name": "grid_size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "spacing_km": {+ "name": "spacing_km",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "local_rank_trackers_project_idx": {+ "name": "local_rank_trackers_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "local_rank_trackers_project_id_projects_id_fk": {+ "name": "local_rank_trackers_project_id_projects_id_fk",+ "tableFrom": "local_rank_trackers",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/drizzle/pg/meta/_journal.json b/drizzle/pg/meta/_journal.jsonindex 9993fe1c..31d41697 100644--- a/drizzle/pg/meta/_journal.json+++ b/drizzle/pg/meta/_journal.json@@ -267,6 +267,13 @@"when": 1792089547475,"tag": "0037_smooth_lady_ursula","breakpoints": true+ },+ {+ "idx": 38,+ "version": "7",+ "when": 1792516807668,+ "tag": "0038_keen_bug",+ "breakpoints": true}]}\ No newline at end of filediff --git a/drizzle/sqlite/0060_reflective_wrecker.sql b/drizzle/sqlite/0060_reflective_wrecker.sqlnew file mode 100644index 00000000..be33f398--- /dev/null+++ b/drizzle/sqlite/0060_reflective_wrecker.sql@@ -0,0 +1,100 @@+CREATE TABLE `local_rank_businesses` (+ `id` text PRIMARY KEY NOT NULL,+ `scan_id` text NOT NULL,+ `identity` text NOT NULL,+ `title` text NOT NULL,+ `cid` text,+ `place_id` text,+ `address` text,+ `rating` real,+ `reviews` integer,+ FOREIGN KEY (`scan_id`) REFERENCES `local_rank_scans`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE UNIQUE INDEX `local_rank_businesses_scan_identity_idx` ON `local_rank_businesses` (`scan_id`,`identity`);--> statement-breakpoint+CREATE TABLE `local_rank_checks` (+ `id` text PRIMARY KEY NOT NULL,+ `project_id` text NOT NULL,+ `tracker_id` text NOT NULL,+ `status` text NOT NULL,+ `error` text,+ `created_at` text NOT NULL,+ `completed_at` text,+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`tracker_id`) REFERENCES `local_rank_trackers`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE INDEX `local_rank_checks_tracker_created_idx` ON `local_rank_checks` (`tracker_id`,`created_at`);--> statement-breakpoint+CREATE UNIQUE INDEX `local_rank_checks_one_active_idx` ON `local_rank_checks` (`tracker_id`) WHERE "local_rank_checks"."status" IN ('queued', 'running');--> statement-breakpoint+CREATE TABLE `local_rank_keywords` (+ `id` text PRIMARY KEY NOT NULL,+ `tracker_id` text NOT NULL,+ `keyword` text NOT NULL,+ `archived_at` text,+ FOREIGN KEY (`tracker_id`) REFERENCES `local_rank_trackers`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE UNIQUE INDEX `local_rank_keywords_tracker_keyword_idx` ON `local_rank_keywords` (`tracker_id`,`keyword`);--> statement-breakpoint+CREATE TABLE `local_rank_points` (+ `id` text PRIMARY KEY NOT NULL,+ `scan_id` text NOT NULL,+ `row` integer NOT NULL,+ `col` integer NOT NULL,+ `latitude` real NOT NULL,+ `longitude` real NOT NULL,+ `status` text NOT NULL,+ `rank` integer,+ `results_count` integer,+ `error` text,+ `collected_at` text,+ FOREIGN KEY (`scan_id`) REFERENCES `local_rank_scans`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE UNIQUE INDEX `local_rank_points_scan_position_idx` ON `local_rank_points` (`scan_id`,`row`,`col`);--> statement-breakpoint+CREATE TABLE `local_rank_results` (+ `id` text PRIMARY KEY NOT NULL,+ `point_id` text NOT NULL,+ `business_id` text NOT NULL,+ `rank` integer NOT NULL,+ FOREIGN KEY (`point_id`) REFERENCES `local_rank_points`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`business_id`) REFERENCES `local_rank_businesses`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE UNIQUE INDEX `local_rank_results_point_business_idx` ON `local_rank_results` (`point_id`,`business_id`);--> statement-breakpoint+CREATE INDEX `local_rank_results_business_idx` ON `local_rank_results` (`business_id`);--> statement-breakpoint+CREATE TABLE `local_rank_scans` (+ `id` text PRIMARY KEY NOT NULL,+ `check_id` text NOT NULL,+ `project_id` text NOT NULL,+ `tracker_id` text NOT NULL,+ `keyword_id` text NOT NULL,+ `status` text NOT NULL,+ `error` text,+ `created_at` text NOT NULL,+ `completed_at` text,+ FOREIGN KEY (`check_id`) REFERENCES `local_rank_checks`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`tracker_id`) REFERENCES `local_rank_trackers`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`keyword_id`) REFERENCES `local_rank_keywords`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE INDEX `local_rank_scans_tracker_created_idx` ON `local_rank_scans` (`tracker_id`,`created_at`);--> statement-breakpoint+CREATE INDEX `local_rank_scans_project_idx` ON `local_rank_scans` (`project_id`);--> statement-breakpoint+CREATE UNIQUE INDEX `local_rank_scans_check_keyword_idx` ON `local_rank_scans` (`check_id`,`keyword_id`);--> statement-breakpoint+CREATE TABLE `local_rank_trackers` (+ `id` text PRIMARY KEY NOT NULL,+ `project_id` text NOT NULL,+ `title` text NOT NULL,+ `address` text,+ `cid` text,+ `place_id` text,+ `latitude` real NOT NULL,+ `longitude` real NOT NULL,+ `grid_size` integer NOT NULL,+ `spacing_km` real NOT NULL,+ `language_code` text NOT NULL,+ `created_at` text NOT NULL,+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE INDEX `local_rank_trackers_project_idx` ON `local_rank_trackers` (`project_id`);\ No newline at end of filediff --git a/drizzle/sqlite/meta/0060_snapshot.json b/drizzle/sqlite/meta/0060_snapshot.jsonnew file mode 100644index 00000000..4703aaa6--- /dev/null+++ b/drizzle/sqlite/meta/0060_snapshot.json@@ -0,0 +1,5613 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "72d53aff-f5fc-4044-90cb-767c592684d6",+ "prevId": "f0ac6b52-7ab6-4917-9b76-b5588103339b",+ "tables": {+ "backlink_snapshots": {+ "name": "backlink_snapshots",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "rank": {+ "name": "rank",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "backlinks": {+ "name": "backlinks",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "referring_domains": {+ "name": "referring_domains",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "broken_backlinks": {+ "name": "broken_backlinks",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "new_backlinks": {+ "name": "new_backlinks",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "lost_backlinks": {+ "name": "lost_backlinks",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "new_referring_domains": {+ "name": "new_referring_domains",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "lost_referring_domains": {+ "name": "lost_referring_domains",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "captured_at": {+ "name": "captured_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "backlink_snapshots_project_captured_idx": {+ "name": "backlink_snapshots_project_captured_idx",+ "columns": [+ "project_id",+ "captured_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "backlink_snapshots_project_id_projects_id_fk": {+ "name": "backlink_snapshots_project_id_projects_id_fk",+ "tableFrom": "backlink_snapshots",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "crawler_credentials": {+ "name": "crawler_credentials",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "host": {+ "name": "host",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "signature_input": {+ "name": "signature_input",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "signature": {+ "name": "signature",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "crawler_credentials_project_host_idx": {+ "name": "crawler_credentials_project_host_idx",+ "columns": [+ "project_id",+ "host"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "crawler_credentials_project_id_projects_id_fk": {+ "name": "crawler_credentials_project_id_projects_id_fk",+ "tableFrom": "crawler_credentials",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "dashboard_step_dismissals": {+ "name": "dashboard_step_dismissals",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "step": {+ "name": "step",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "dashboard_step_dismissals_project_idx": {+ "name": "dashboard_step_dismissals_project_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "dashboard_step_dismissals_user_id_user_id_fk": {+ "name": "dashboard_step_dismissals_user_id_user_id_fk",+ "tableFrom": "dashboard_step_dismissals",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "dashboard_step_dismissals_project_id_projects_id_fk": {+ "name": "dashboard_step_dismissals_project_id_projects_id_fk",+ "tableFrom": "dashboard_step_dismissals",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "dashboard_step_dismissals_user_id_project_id_step_pk": {+ "columns": [+ "user_id",+ "project_id",+ "step"+ ],+ "name": "dashboard_step_dismissals_user_id_project_id_step_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "data_refresh_claims": {+ "name": "data_refresh_claims",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "data_refresh_claims_organization_id_organization_id_fk": {+ "name": "data_refresh_claims_organization_id_organization_id_fk",+ "tableFrom": "data_refresh_claims",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "keyword_metrics": {+ "name": "keyword_metrics",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "search_volume": {+ "name": "search_volume",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cpc": {+ "name": "cpc",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "competition": {+ "name": "competition",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "keyword_difficulty": {+ "name": "keyword_difficulty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "intent": {+ "name": "intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "monthly_searches": {+ "name": "monthly_searches",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fetched_at": {+ "name": "fetched_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "keyword_metrics_unique_project_keyword_location_language": {+ "name": "keyword_metrics_unique_project_keyword_location_language",+ "columns": [+ "project_id",+ "keyword",+ "location_code",+ "language_code"+ ],+ "isUnique": true+ },+ "keyword_metrics_lookup_idx": {+ "name": "keyword_metrics_lookup_idx",+ "columns": [+ "project_id",+ "keyword",+ "location_code",+ "language_code",+ "fetched_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "keyword_metrics_project_id_projects_id_fk": {+ "name": "keyword_metrics_project_id_projects_id_fk",+ "tableFrom": "keyword_metrics",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_activation_state": {+ "name": "organization_activation_state",+ "columns": {+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "first_mcp_authorized_at": {+ "name": "first_mcp_authorized_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "first_mcp_tool_call_at": {+ "name": "first_mcp_tool_call_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_activation_state_organization_id_organization_id_fk": {+ "name": "organization_activation_state_organization_id_organization_id_fk",+ "tableFrom": "organization_activation_state",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_activation_state": {+ "name": "project_activation_state",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "competitor_step_clicked_at": {+ "name": "competitor_step_clicked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "keyword_step_clicked_at": {+ "name": "keyword_step_clicked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mcp_card_dismissed_at": {+ "name": "mcp_card_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ga4_card_dismissed_at": {+ "name": "ga4_card_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_activation_state_project_id_projects_id_fk": {+ "name": "project_activation_state_project_id_projects_id_fk",+ "tableFrom": "project_activation_state",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "projects": {+ "name": "projects",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ai_research_keywords": {+ "name": "ai_research_keywords",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "indexnow_key": {+ "name": "indexnow_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "projects_one_default_per_organization_idx": {+ "name": "projects_one_default_per_organization_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": true,+ "where": "\"projects\".\"name\" = 'Default' AND \"projects\".\"domain\" IS NULL AND \"projects\".\"archived_at\" IS NULL"+ },+ "projects_organization_id_idx": {+ "name": "projects_organization_id_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "projects_organization_id_organization_id_fk": {+ "name": "projects_organization_id_organization_id_fk",+ "tableFrom": "projects",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "rank_check_runs": {+ "name": "rank_check_runs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "keywords_total": {+ "name": "keywords_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "keywords_checked": {+ "name": "keywords_checked",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "is_subset_run": {+ "name": "is_subset_run",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "rank_check_runs_config_idx": {+ "name": "rank_check_runs_config_idx",+ "columns": [+ "config_id",+ "started_at"+ ],+ "isUnique": false+ },+ "rank_check_runs_project_idx": {+ "name": "rank_check_runs_project_idx",+ "columns": [+ "project_id",+ "started_at"+ ],+ "isUnique": false+ },+ "rank_check_runs_one_active_per_config_idx": {+ "name": "rank_check_runs_one_active_per_config_idx",+ "columns": [+ "config_id"+ ],+ "isUnique": true,+ "where": "\"rank_check_runs\".\"status\" IN ('pending', 'running')"+ }+ },+ "foreignKeys": {+ "rank_check_runs_config_id_rank_tracking_configs_id_fk": {+ "name": "rank_check_runs_config_id_rank_tracking_configs_id_fk",+ "tableFrom": "rank_check_runs",+ "tableTo": "rank_tracking_configs",+ "columnsFrom": [+ "config_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "rank_check_runs_project_id_projects_id_fk": {+ "name": "rank_check_runs_project_id_projects_id_fk",+ "tableFrom": "rank_check_runs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "rank_snapshots": {+ "name": "rank_snapshots",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tracking_keyword_id": {+ "name": "tracking_keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "device": {+ "name": "device",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "serp_features": {+ "name": "serp_features",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "checked_at": {+ "name": "checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "rank_snapshots_keyword_device_idx": {+ "name": "rank_snapshots_keyword_device_idx",+ "columns": [+ "tracking_keyword_id",+ "device",+ "checked_at"+ ],+ "isUnique": false+ },+ "rank_snapshots_run_keyword_device_idx": {+ "name": "rank_snapshots_run_keyword_device_idx",+ "columns": [+ "run_id",+ "tracking_keyword_id",+ "device"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "rank_snapshots_run_id_rank_check_runs_id_fk": {+ "name": "rank_snapshots_run_id_rank_check_runs_id_fk",+ "tableFrom": "rank_snapshots",+ "tableTo": "rank_check_runs",+ "columnsFrom": [+ "run_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "rank_tracking_configs": {+ "name": "rank_tracking_configs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "devices": {+ "name": "devices",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'both'"+ },+ "serp_depth": {+ "name": "serp_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "schedule_interval": {+ "name": "schedule_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'weekly'"+ },+ "location_name": {+ "name": "location_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "last_checked_at": {+ "name": "last_checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "next_check_at": {+ "name": "next_check_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_skip_reason": {+ "name": "last_skip_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "rank_tracking_configs_project_active_created_idx": {+ "name": "rank_tracking_configs_project_active_created_idx",+ "columns": [+ "project_id",+ "is_active",+ "created_at"+ ],+ "isUnique": false+ },+ "rank_tracking_configs_national_idx": {+ "name": "rank_tracking_configs_national_idx",+ "columns": [+ "project_id",+ "domain",+ "location_code",+ "language_code"+ ],+ "isUnique": true,+ "where": "\"rank_tracking_configs\".\"location_name\" IS NULL"+ },+ "rank_tracking_configs_local_idx": {+ "name": "rank_tracking_configs_local_idx",+ "columns": [+ "project_id",+ "domain",+ "location_code",+ "language_code",+ "location_name"+ ],+ "isUnique": true,+ "where": "\"rank_tracking_configs\".\"location_name\" IS NOT NULL"+ }+ },+ "foreignKeys": {+ "rank_tracking_configs_project_id_projects_id_fk": {+ "name": "rank_tracking_configs_project_id_projects_id_fk",+ "tableFrom": "rank_tracking_configs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "rank_tracking_keywords": {+ "name": "rank_tracking_keywords",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "match_case": {+ "name": "match_case",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "search_volume": {+ "name": "search_volume",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "keyword_difficulty": {+ "name": "keyword_difficulty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cpc": {+ "name": "cpc",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metrics_fetched_at": {+ "name": "metrics_fetched_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pinned_at": {+ "name": "pinned_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "rank_tracking_keywords_config_keyword_idx": {+ "name": "rank_tracking_keywords_config_keyword_idx",+ "columns": [+ "config_id",+ "keyword"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "rank_tracking_keywords_config_id_rank_tracking_configs_id_fk": {+ "name": "rank_tracking_keywords_config_id_rank_tracking_configs_id_fk",+ "tableFrom": "rank_tracking_keywords",+ "tableTo": "rank_tracking_configs",+ "columnsFrom": [+ "config_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "saved_keyword_tag_assignments": {+ "name": "saved_keyword_tag_assignments",+ "columns": {+ "saved_keyword_id": {+ "name": "saved_keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "saved_keyword_tag_assignments_unique_idx": {+ "name": "saved_keyword_tag_assignments_unique_idx",+ "columns": [+ "saved_keyword_id",+ "tag_id"+ ],+ "isUnique": true+ },+ "saved_keyword_tag_assignments_tag_idx": {+ "name": "saved_keyword_tag_assignments_tag_idx",+ "columns": [+ "tag_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "saved_keyword_tag_assignments_saved_keyword_id_saved_keywords_id_fk": {+ "name": "saved_keyword_tag_assignments_saved_keyword_id_saved_keywords_id_fk",+ "tableFrom": "saved_keyword_tag_assignments",+ "tableTo": "saved_keywords",+ "columnsFrom": [+ "saved_keyword_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "saved_keyword_tag_assignments_tag_id_saved_keyword_tags_id_fk": {+ "name": "saved_keyword_tag_assignments_tag_id_saved_keyword_tags_id_fk",+ "tableFrom": "saved_keyword_tag_assignments",+ "tableTo": "saved_keyword_tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "saved_keyword_tags": {+ "name": "saved_keyword_tags",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "normalized_name": {+ "name": "normalized_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "saved_keyword_tags_project_normalized_name_idx": {+ "name": "saved_keyword_tags_project_normalized_name_idx",+ "columns": [+ "project_id",+ "normalized_name"+ ],+ "isUnique": true+ },+ "saved_keyword_tags_project_name_idx": {+ "name": "saved_keyword_tags_project_name_idx",+ "columns": [+ "project_id",+ "name"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "saved_keyword_tags_project_id_projects_id_fk": {+ "name": "saved_keyword_tags_project_id_projects_id_fk",+ "tableFrom": "saved_keyword_tags",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "saved_keywords": {+ "name": "saved_keywords",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "saved_keywords_unique_project_keyword_location_language": {+ "name": "saved_keywords_unique_project_keyword_location_language",+ "columns": [+ "project_id",+ "keyword",+ "location_code",+ "language_code"+ ],+ "isUnique": true+ },+ "saved_keywords_project_created_idx": {+ "name": "saved_keywords_project_created_idx",+ "columns": [+ "project_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "saved_keywords_project_id_projects_id_fk": {+ "name": "saved_keywords_project_id_projects_id_fk",+ "tableFrom": "saved_keywords",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user_onboarding_answers": {+ "name": "user_onboarding_answers",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "interested_features": {+ "name": "interested_features",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "work_for": {+ "name": "work_for",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "client_website_count": {+ "name": "client_website_count",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "found_via": {+ "name": "found_via",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mcp_setup_intent": {+ "name": "mcp_setup_intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "gsc_nudge_dismissed_at": {+ "name": "gsc_nudge_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "user_onboarding_answers_organization_idx": {+ "name": "user_onboarding_answers_organization_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "user_onboarding_answers_user_id_user_id_fk": {+ "name": "user_onboarding_answers_user_id_user_id_fk",+ "tableFrom": "user_onboarding_answers",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_onboarding_answers_organization_id_organization_id_fk": {+ "name": "user_onboarding_answers_organization_id_organization_id_fk",+ "tableFrom": "user_onboarding_answers",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_competitors": {+ "name": "project_competitors",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "project_competitors_project_domain_idx": {+ "name": "project_competitors_project_domain_idx",+ "columns": [+ "project_id",+ "domain"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "project_competitors_project_id_projects_id_fk": {+ "name": "project_competitors_project_id_projects_id_fk",+ "tableFrom": "project_competitors",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_context_sections": {+ "name": "project_context_sections",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_context_sections_project_id_projects_id_fk": {+ "name": "project_context_sections_project_id_projects_id_fk",+ "tableFrom": "project_context_sections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_context_sections_project_id_key_pk": {+ "columns": [+ "project_id",+ "key"+ ],+ "name": "project_context_sections_project_id_key_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_key_pages": {+ "name": "project_key_pages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "topic": {+ "name": "topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "project_key_pages_project_url_idx": {+ "name": "project_key_pages_project_url_idx",+ "columns": [+ "project_id",+ "url"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "project_key_pages_project_id_projects_id_fk": {+ "name": "project_key_pages_project_id_projects_id_fk",+ "tableFrom": "project_key_pages",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_research_log": {+ "name": "project_research_log",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "entry_date": {+ "name": "entry_date",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ }+ },+ "indexes": {+ "project_research_log_project_date_idx": {+ "name": "project_research_log_project_date_idx",+ "columns": [+ "project_id",+ "entry_date"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "project_research_log_project_id_projects_id_fk": {+ "name": "project_research_log_project_id_projects_id_fk",+ "tableFrom": "project_research_log",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "reports": {+ "name": "reports",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "html": {+ "name": "html",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "skill": {+ "name": "skill",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "template_id": {+ "name": "template_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "share_token": {+ "name": "share_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "shared_at": {+ "name": "shared_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ }+ },+ "indexes": {+ "reports_project_updated_idx": {+ "name": "reports_project_updated_idx",+ "columns": [+ "project_id",+ "updated_at",+ "id",+ "size_bytes"+ ],+ "isUnique": false+ },+ "reports_share_token_idx": {+ "name": "reports_share_token_idx",+ "columns": [+ "share_token"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "reports_project_id_projects_id_fk": {+ "name": "reports_project_id_projects_id_fk",+ "tableFrom": "reports",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "report_templates": {+ "name": "report_templates",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "instructions": {+ "name": "instructions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ }+ },+ "indexes": {+ "report_templates_project_name_idx": {+ "name": "report_templates_project_name_idx",+ "columns": [+ "project_id",+ "name"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "report_templates_project_id_projects_id_fk": {+ "name": "report_templates_project_id_projects_id_fk",+ "tableFrom": "report_templates",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_issues": {+ "name": "audit_issues",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_url": {+ "name": "page_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "issue_type": {+ "name": "issue_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "severity": {+ "name": "severity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'info'"+ },+ "details_json": {+ "name": "details_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_issues_audit_type_idx": {+ "name": "audit_issues_audit_type_idx",+ "columns": [+ "audit_id",+ "issue_type"+ ],+ "isUnique": false+ },+ "audit_issues_page_id_idx": {+ "name": "audit_issues_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_issues_audit_id_audits_id_fk": {+ "name": "audit_issues_audit_id_audits_id_fk",+ "tableFrom": "audit_issues",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "audit_issues_page_id_audit_pages_id_fk": {+ "name": "audit_issues_page_id_audit_pages_id_fk",+ "tableFrom": "audit_issues",+ "tableTo": "audit_pages",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_lighthouse_results": {+ "name": "audit_lighthouse_results",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "strategy": {+ "name": "strategy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "performance_score": {+ "name": "performance_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "accessibility_score": {+ "name": "accessibility_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "best_practices_score": {+ "name": "best_practices_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "seo_score": {+ "name": "seo_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "lcp_ms": {+ "name": "lcp_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cls": {+ "name": "cls",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "inp_ms": {+ "name": "inp_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ttfb_ms": {+ "name": "ttfb_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "r2_key": {+ "name": "r2_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "payload_size_bytes": {+ "name": "payload_size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_lighthouse_results_audit_id_idx": {+ "name": "audit_lighthouse_results_audit_id_idx",+ "columns": [+ "audit_id"+ ],+ "isUnique": false+ },+ "audit_lighthouse_results_page_id_idx": {+ "name": "audit_lighthouse_results_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_lighthouse_results_audit_id_audits_id_fk": {+ "name": "audit_lighthouse_results_audit_id_audits_id_fk",+ "tableFrom": "audit_lighthouse_results",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "audit_lighthouse_results_page_id_audit_pages_id_fk": {+ "name": "audit_lighthouse_results_page_id_audit_pages_id_fk",+ "tableFrom": "audit_lighthouse_results",+ "tableTo": "audit_pages",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_pages": {+ "name": "audit_pages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status_code": {+ "name": "status_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "redirect_url": {+ "name": "redirect_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "meta_description": {+ "name": "meta_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "canonical_url": {+ "name": "canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "robots_meta": {+ "name": "robots_meta",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "og_title": {+ "name": "og_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "og_description": {+ "name": "og_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "og_image": {+ "name": "og_image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "h1_count": {+ "name": "h1_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h2_count": {+ "name": "h2_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h3_count": {+ "name": "h3_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h4_count": {+ "name": "h4_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h5_count": {+ "name": "h5_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h6_count": {+ "name": "h6_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "word_count": {+ "name": "word_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "images_total": {+ "name": "images_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "images_missing_alt": {+ "name": "images_missing_alt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "internal_link_count": {+ "name": "internal_link_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "external_link_count": {+ "name": "external_link_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "has_structured_data": {+ "name": "has_structured_data",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "is_indexable": {+ "name": "is_indexable",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "x_robots_tag": {+ "name": "x_robots_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "header_canonical_url": {+ "name": "header_canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "crawl_depth": {+ "name": "crawl_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "in_sitemap": {+ "name": "in_sitemap",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "content_hash": {+ "name": "content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fetch_class": {+ "name": "fetch_class",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'ok'"+ },+ "response_time_ms": {+ "name": "response_time_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_pages_audit_url_idx": {+ "name": "audit_pages_audit_url_idx",+ "columns": [+ "audit_id",+ "url"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_pages_audit_id_audits_id_fk": {+ "name": "audit_pages_audit_id_audits_id_fk",+ "tableFrom": "audit_pages",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audits": {+ "name": "audits",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "started_by_user_id": {+ "name": "started_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "start_url": {+ "name": "start_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'running'"+ },+ "workflow_instance_id": {+ "name": "workflow_instance_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "pages_crawled": {+ "name": "pages_crawled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "pages_total": {+ "name": "pages_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "lighthouse_total": {+ "name": "lighthouse_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "lighthouse_completed": {+ "name": "lighthouse_completed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "lighthouse_failed": {+ "name": "lighthouse_failed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "current_phase": {+ "name": "current_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'discovery'"+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error_detail": {+ "name": "error_detail",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "failed_phase": {+ "name": "failed_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "audits_project_id_idx": {+ "name": "audits_project_id_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": false+ },+ "audits_started_by_user_id_idx": {+ "name": "audits_started_by_user_id_idx",+ "columns": [+ "started_by_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audits_project_id_projects_id_fk": {+ "name": "audits_project_id_projects_id_fk",+ "tableFrom": "audits",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "sam_sessions": {+ "name": "sam_sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'New chat'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "sam_sessions_project_updated_idx": {+ "name": "sam_sessions_project_updated_idx",+ "columns": [+ "project_id",+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "sam_sessions_project_id_projects_id_fk": {+ "name": "sam_sessions_project_id_projects_id_fk",+ "tableFrom": "sam_sessions",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "sam_sessions_user_id_user_id_fk": {+ "name": "sam_sessions_user_id_user_id_fk",+ "tableFrom": "sam_sessions",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "account": {+ "name": "account",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "account_accountId_providerId_idx": {+ "name": "account_accountId_providerId_idx",+ "columns": [+ "account_id",+ "provider_id"+ ],+ "isUnique": false+ },+ "account_google_grant_owner_idx": {+ "name": "account_google_grant_owner_idx",+ "columns": [+ "user_id",+ "provider_id",+ "account_id"+ ],+ "isUnique": true,+ "where": "\"account\".\"provider_id\" in ('google-search-console', 'google-analytics')"+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "apikey": {+ "name": "apikey",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "enabled": {+ "name": "enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 60000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 120+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_request": {+ "name": "last_request",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ "config_id"+ ],+ "isUnique": false+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ "reference_id"+ ],+ "isUnique": false+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ "key"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "invitation": {+ "name": "invitation",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "invitation_organizationId_idx": {+ "name": "invitation_organizationId_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ "email"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "invitation_organization_id_organization_id_fk": {+ "name": "invitation_organization_id_organization_id_fk",+ "tableFrom": "invitation",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": [+ "inviter_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "member": {+ "name": "member",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'member'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "member_organizationId_idx": {+ "name": "member_organizationId_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ },+ "member_userId_idx": {+ "name": "member_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "member_organizationId_userId_uidx": {+ "name": "member_organizationId_userId_uidx",+ "columns": [+ "organization_id",+ "user_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "member_organization_id_organization_id_fk": {+ "name": "member_organization_id_organization_id_fk",+ "tableFrom": "member",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "member_user_id_user_id_fk": {+ "name": "member_user_id_user_id_fk",+ "tableFrom": "member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization": {+ "name": "organization",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "organization_slug_unique": {+ "name": "organization_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ },+ "organization_slug_uidx": {+ "name": "organization_slug_uidx",+ "columns": [+ "slug"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "session_token_unique": {+ "name": "session_token_unique",+ "columns": [+ "token"+ ],+ "isUnique": true+ },+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user": {+ "name": "user",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email_verified": {+ "name": "email_verified",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "analytics_opted_out": {+ "name": "analytics_opted_out",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "terms_accepted_version": {+ "name": "terms_accepted_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "terms_accepted_at": {+ "name": "terms_accepted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "product_updates_opt_in": {+ "name": "product_updates_opt_in",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "product_updates_changed_at": {+ "name": "product_updates_changed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_active_organization_id": {+ "name": "last_active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "user_email_unique": {+ "name": "user_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "verification": {+ "name": "verification",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ "identifier"+ ],+ "isUnique": false+ },+ "verification_expiresAt_idx": {+ "name": "verification_expiresAt_idx",+ "columns": [+ "expires_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "billing_customer_status": {+ "name": "billing_customer_status",+ "columns": {+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "is_paying": {+ "name": "is_paying",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "paid_plan_id": {+ "name": "paid_plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "paid_plan_status": {+ "name": "paid_plan_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "customer_json": {+ "name": "customer_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "synced_at": {+ "name": "synced_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "billing_customer_status_organization_id_organization_id_fk": {+ "name": "billing_customer_status_organization_id_organization_id_fk",+ "tableFrom": "billing_customer_status",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ga4_connections": {+ "name": "ga4_connections",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "property_id": {+ "name": "property_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "property_display_name": {+ "name": "property_display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "property_time_zone": {+ "name": "property_time_zone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "property_currency_code": {+ "name": "property_currency_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "connected_by_user_id": {+ "name": "connected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ga4_account_id": {+ "name": "ga4_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "connected_account_email": {+ "name": "connected_account_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "ga4_connections_project_idx": {+ "name": "ga4_connections_project_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": true+ },+ "ga4_connections_organization_idx": {+ "name": "ga4_connections_organization_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ },+ "ga4_connections_connector_idx": {+ "name": "ga4_connections_connector_idx",+ "columns": [+ "connected_by_user_id",+ "ga4_account_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "ga4_connections_project_id_projects_id_fk": {+ "name": "ga4_connections_project_id_projects_id_fk",+ "tableFrom": "ga4_connections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ga4_connections_organization_id_organization_id_fk": {+ "name": "ga4_connections_organization_id_organization_id_fk",+ "tableFrom": "ga4_connections",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "gsc_connections": {+ "name": "gsc_connections",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "site_url": {+ "name": "site_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "connected_by_user_id": {+ "name": "connected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "gsc_account_id": {+ "name": "gsc_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "connected_account_email": {+ "name": "connected_account_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "gsc_connections_project_idx": {+ "name": "gsc_connections_project_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": true+ },+ "gsc_connections_organization_idx": {+ "name": "gsc_connections_organization_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "gsc_connections_project_id_projects_id_fk": {+ "name": "gsc_connections_project_id_projects_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "gsc_connections_organization_id_organization_id_fk": {+ "name": "gsc_connections_organization_id_organization_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "telemetry_state": {+ "name": "telemetry_state",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "install_id": {+ "name": "install_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "installed_at": {+ "name": "installed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_heartbeat_at": {+ "name": "last_heartbeat_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_version": {+ "name": "last_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mcp_tool_call_count": {+ "name": "mcp_tool_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ai_matches": {+ "name": "ai_matches",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "observation_id": {+ "name": "observation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "own": {+ "name": "own",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mentioned": {+ "name": "mentioned",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cited": {+ "name": "cited",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "first_mention": {+ "name": "first_mention",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "ai_matches_observation_domain_idx": {+ "name": "ai_matches_observation_domain_idx",+ "columns": [+ "observation_id",+ "domain"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "ai_matches_observation_id_ai_observations_id_fk": {+ "name": "ai_matches_observation_id_ai_observations_id_fk",+ "tableFrom": "ai_matches",+ "tableTo": "ai_observations",+ "columnsFrom": [+ "observation_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ai_observations": {+ "name": "ai_observations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "prompt_id": {+ "name": "prompt_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "engine": {+ "name": "engine",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "branded": {+ "name": "branded",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "collected_at": {+ "name": "collected_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "answer_markdown": {+ "name": "answer_markdown",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "ai_observations_run_prompt_engine_idx": {+ "name": "ai_observations_run_prompt_engine_idx",+ "columns": [+ "run_id",+ "prompt_id",+ "engine"+ ],+ "isUnique": true+ },+ "ai_observations_prompt_idx": {+ "name": "ai_observations_prompt_idx",+ "columns": [+ "prompt_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "ai_observations_run_id_ai_runs_id_fk": {+ "name": "ai_observations_run_id_ai_runs_id_fk",+ "tableFrom": "ai_observations",+ "tableTo": "ai_runs",+ "columnsFrom": [+ "run_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ai_observations_prompt_id_ai_prompts_id_fk": {+ "name": "ai_observations_prompt_id_ai_prompts_id_fk",+ "tableFrom": "ai_observations",+ "tableTo": "ai_prompts",+ "columnsFrom": [+ "prompt_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ai_prompts": {+ "name": "ai_prompts",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "tracker_id": {+ "name": "tracker_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "topic": {+ "name": "topic",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "text": {+ "name": "text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "paused": {+ "name": "paused",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "archived": {+ "name": "archived",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "ai_prompts_tracker_idx": {+ "name": "ai_prompts_tracker_idx",+ "columns": [+ "tracker_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "ai_prompts_tracker_id_ai_trackers_id_fk": {+ "name": "ai_prompts_tracker_id_ai_trackers_id_fk",+ "tableFrom": "ai_prompts",+ "tableTo": "ai_trackers",+ "columnsFrom": [+ "tracker_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ai_runs": {+ "name": "ai_runs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "tracker_id": {+ "name": "tracker_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "trigger": {+ "name": "trigger",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'queued'"+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "ai_runs_project_created_idx": {+ "name": "ai_runs_project_created_idx",+ "columns": [+ "project_id",+ "created_at"+ ],+ "isUnique": false+ },+ "ai_runs_one_active_idx": {+ "name": "ai_runs_one_active_idx",+ "columns": [+ "tracker_id"+ ],+ "isUnique": true,+ "where": "\"ai_runs\".\"status\" IN ('queued', 'running')"+ }+ },+ "foreignKeys": {+ "ai_runs_tracker_id_ai_trackers_id_fk": {+ "name": "ai_runs_tracker_id_ai_trackers_id_fk",+ "tableFrom": "ai_runs",+ "tableTo": "ai_trackers",+ "columnsFrom": [+ "tracker_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ai_runs_project_id_projects_id_fk": {+ "name": "ai_runs_project_id_projects_id_fk",+ "tableFrom": "ai_runs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ai_sources": {+ "name": "ai_sources",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "observation_id": {+ "name": "observation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "ai_sources_observation_idx": {+ "name": "ai_sources_observation_idx",+ "columns": [+ "observation_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "ai_sources_observation_id_ai_observations_id_fk": {+ "name": "ai_sources_observation_id_ai_observations_id_fk",+ "tableFrom": "ai_sources",+ "tableTo": "ai_observations",+ "columnsFrom": [+ "observation_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ai_trackers": {+ "name": "ai_trackers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "enabled": {+ "name": "enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "chatgpt": {+ "name": "chatgpt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "gemini": {+ "name": "gemini",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "claude": {+ "name": "claude",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "perplexity": {+ "name": "perplexity",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "google_ai_overview": {+ "name": "google_ai_overview",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "schedule_interval": {+ "name": "schedule_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'weekly'"+ },+ "next_check_at": {+ "name": "next_check_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_skip_reason": {+ "name": "last_skip_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "ai_trackers_project_idx": {+ "name": "ai_trackers_project_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": true+ },+ "ai_trackers_due_idx": {+ "name": "ai_trackers_due_idx",+ "columns": [+ "enabled",+ "next_check_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "ai_trackers_project_id_projects_id_fk": {+ "name": "ai_trackers_project_id_projects_id_fk",+ "tableFrom": "ai_trackers",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "local_rank_businesses": {+ "name": "local_rank_businesses",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "scan_id": {+ "name": "scan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "identity": {+ "name": "identity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cid": {+ "name": "cid",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "place_id": {+ "name": "place_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "address": {+ "name": "address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "rating": {+ "name": "rating",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "reviews": {+ "name": "reviews",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "local_rank_businesses_scan_identity_idx": {+ "name": "local_rank_businesses_scan_identity_idx",+ "columns": [+ "scan_id",+ "identity"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "local_rank_businesses_scan_id_local_rank_scans_id_fk": {+ "name": "local_rank_businesses_scan_id_local_rank_scans_id_fk",+ "tableFrom": "local_rank_businesses",+ "tableTo": "local_rank_scans",+ "columnsFrom": [+ "scan_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "local_rank_checks": {+ "name": "local_rank_checks",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tracker_id": {+ "name": "tracker_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "local_rank_checks_tracker_created_idx": {+ "name": "local_rank_checks_tracker_created_idx",+ "columns": [+ "tracker_id",+ "created_at"+ ],+ "isUnique": false+ },+ "local_rank_checks_one_active_idx": {+ "name": "local_rank_checks_one_active_idx",+ "columns": [+ "tracker_id"+ ],+ "isUnique": true,+ "where": "\"local_rank_checks\".\"status\" IN ('queued', 'running')"+ }+ },+ "foreignKeys": {+ "local_rank_checks_project_id_projects_id_fk": {+ "name": "local_rank_checks_project_id_projects_id_fk",+ "tableFrom": "local_rank_checks",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "local_rank_checks_tracker_id_local_rank_trackers_id_fk": {+ "name": "local_rank_checks_tracker_id_local_rank_trackers_id_fk",+ "tableFrom": "local_rank_checks",+ "tableTo": "local_rank_trackers",+ "columnsFrom": [+ "tracker_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "local_rank_keywords": {+ "name": "local_rank_keywords",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "tracker_id": {+ "name": "tracker_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "local_rank_keywords_tracker_keyword_idx": {+ "name": "local_rank_keywords_tracker_keyword_idx",+ "columns": [+ "tracker_id",+ "keyword"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "local_rank_keywords_tracker_id_local_rank_trackers_id_fk": {+ "name": "local_rank_keywords_tracker_id_local_rank_trackers_id_fk",+ "tableFrom": "local_rank_keywords",+ "tableTo": "local_rank_trackers",+ "columnsFrom": [+ "tracker_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "local_rank_points": {+ "name": "local_rank_points",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "scan_id": {+ "name": "scan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "row": {+ "name": "row",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "col": {+ "name": "col",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "latitude": {+ "name": "latitude",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "longitude": {+ "name": "longitude",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "rank": {+ "name": "rank",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "results_count": {+ "name": "results_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "collected_at": {+ "name": "collected_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "local_rank_points_scan_position_idx": {+ "name": "local_rank_points_scan_position_idx",+ "columns": [+ "scan_id",+ "row",+ "col"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "local_rank_points_scan_id_local_rank_scans_id_fk": {+ "name": "local_rank_points_scan_id_local_rank_scans_id_fk",+ "tableFrom": "local_rank_points",+ "tableTo": "local_rank_scans",+ "columnsFrom": [+ "scan_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "local_rank_results": {+ "name": "local_rank_results",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "point_id": {+ "name": "point_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "business_id": {+ "name": "business_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "rank": {+ "name": "rank",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "local_rank_results_point_business_idx": {+ "name": "local_rank_results_point_business_idx",+ "columns": [+ "point_id",+ "business_id"+ ],+ "isUnique": true+ },+ "local_rank_results_business_idx": {+ "name": "local_rank_results_business_idx",+ "columns": [+ "business_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "local_rank_results_point_id_local_rank_points_id_fk": {+ "name": "local_rank_results_point_id_local_rank_points_id_fk",+ "tableFrom": "local_rank_results",+ "tableTo": "local_rank_points",+ "columnsFrom": [+ "point_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "local_rank_results_business_id_local_rank_businesses_id_fk": {+ "name": "local_rank_results_business_id_local_rank_businesses_id_fk",+ "tableFrom": "local_rank_results",+ "tableTo": "local_rank_businesses",+ "columnsFrom": [+ "business_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "local_rank_scans": {+ "name": "local_rank_scans",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "check_id": {+ "name": "check_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tracker_id": {+ "name": "tracker_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword_id": {+ "name": "keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "local_rank_scans_tracker_created_idx": {+ "name": "local_rank_scans_tracker_created_idx",+ "columns": [+ "tracker_id",+ "created_at"+ ],+ "isUnique": false+ },+ "local_rank_scans_project_idx": {+ "name": "local_rank_scans_project_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": false+ },+ "local_rank_scans_check_keyword_idx": {+ "name": "local_rank_scans_check_keyword_idx",+ "columns": [+ "check_id",+ "keyword_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "local_rank_scans_check_id_local_rank_checks_id_fk": {+ "name": "local_rank_scans_check_id_local_rank_checks_id_fk",+ "tableFrom": "local_rank_scans",+ "tableTo": "local_rank_checks",+ "columnsFrom": [+ "check_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "local_rank_scans_project_id_projects_id_fk": {+ "name": "local_rank_scans_project_id_projects_id_fk",+ "tableFrom": "local_rank_scans",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "local_rank_scans_tracker_id_local_rank_trackers_id_fk": {+ "name": "local_rank_scans_tracker_id_local_rank_trackers_id_fk",+ "tableFrom": "local_rank_scans",+ "tableTo": "local_rank_trackers",+ "columnsFrom": [+ "tracker_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "local_rank_scans_keyword_id_local_rank_keywords_id_fk": {+ "name": "local_rank_scans_keyword_id_local_rank_keywords_id_fk",+ "tableFrom": "local_rank_scans",+ "tableTo": "local_rank_keywords",+ "columnsFrom": [+ "keyword_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "local_rank_trackers": {+ "name": "local_rank_trackers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "address": {+ "name": "address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cid": {+ "name": "cid",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "place_id": {+ "name": "place_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "latitude": {+ "name": "latitude",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "longitude": {+ "name": "longitude",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "grid_size": {+ "name": "grid_size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "spacing_km": {+ "name": "spacing_km",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "local_rank_trackers_project_idx": {+ "name": "local_rank_trackers_project_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "local_rank_trackers_project_id_projects_id_fk": {+ "name": "local_rank_trackers_project_id_projects_id_fk",+ "tableFrom": "local_rank_trackers",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}\ No newline at end of filediff --git a/drizzle/sqlite/meta/_journal.json b/drizzle/sqlite/meta/_journal.jsonindex 0de850f2..830b430c 100644--- a/drizzle/sqlite/meta/_journal.json+++ b/drizzle/sqlite/meta/_journal.json@@ -421,6 +421,13 @@"when": 1792089546917,"tag": "0059_thankful_aaron_stack","breakpoints": true+ },+ {+ "idx": 60,+ "version": "6",+ "when": 1792516807017,+ "tag": "0060_reflective_wrecker",+ "breakpoints": true}]}\ No newline at end of filediff --git a/package.json b/package.jsonindex d0957e09..09d22ad8 100644--- a/package.json+++ b/package.json@@ -106,6 +106,7 @@"fast-xml-parser": "^5.4.1","htmlparser2": "^10.1.0","jose": "^6.0.12",+ "leaflet": "^1.9.4","lucide-react": "^0.542.0","papaparse": "^5.5.3","postgres": "^3.4.9",@@ -113,6 +114,7 @@"posthog-node": "^5.38.6","react": "^19.0.0","react-dom": "^19.0.0",+ "react-leaflet": "^5.0.0","react-markdown": "^10.1.0","recharts": "^3.8.0","remark-gfm": "^4.0.1",@@ -136,6 +138,7 @@"@tailwindcss/vite": "^4.1.11","@tanstack/devtools-vite": "^0.6.1","@tanstack/react-devtools": "^0.10.12",+ "@types/leaflet": "^1.9.22","@types/node": "^22.18.13","@types/papaparse": "^5.5.2","@types/react": "^19.0.8",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d26c7ab0..db2a216a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -128,6 +128,9 @@ importers:jose:specifier: ^6.0.12version: 6.1.3+ leaflet:+ specifier: ^1.9.4+ version: 1.9.4lucide-react:specifier: ^0.542.0version: 0.542.0([email protected])@@ -149,6 +152,9 @@ importers:react-dom:specifier: ^19.0.0version: 19.2.4([email protected])+ react-leaflet:+ specifier: ^5.0.0react-markdown:specifier: ^10.1.0version: 10.1.0(@types/[email protected])([email protected])@@ -213,6 +219,9 @@ importers:'@tanstack/react-devtools':specifier: ^0.10.12version: 0.10.12(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])+ '@types/leaflet':+ specifier: ^1.9.22+ version: 1.9.22'@types/node':specifier: ^22.18.13version: 22.19.11@@ -2199,6 +2208,13 @@ packages:'@posthog/[email protected]':resolution: {integrity: sha512-ASwd7Nf4pViqdYRYaNRyPYRVKWa1CcHUAUWR0XeQJLGdNnsWACBwe0sSieb/cHnKsRXjRwO/23KIY83lm/Ccpw==}+ '@react-leaflet/[email protected]':+ resolution: {integrity: sha512-3EWmekh4Nz+pGcr+xjf0KNyYfC3U2JjnkWsh0zcqaexYqmmB5ZhH37kz41JXGmKzpaMZCnPofBBm64i+YrEvGQ==}+ peerDependencies:+ leaflet: ^1.9.0+ react: ^19.0.0+ react-dom: ^19.0.0+'@reduxjs/[email protected]':resolution: {integrity: sha512-Kd6kAHTA6/nUpp8mySPqj3en3dm0tdMIgbttnQ1xFMVpufoj+ADi8pXLBsd4xzTRHQa7t/Jv8W5UnCuW4kuWMQ==}peerDependencies:@@ -3072,6 +3088,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==}+'@types/[email protected]':resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}@@ -3081,6 +3100,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-h3lhECYEKDasG7LFHu+GiHqAvsgLuQvlJvVZzJDGONo3sEL+wUOqSFLnwkZlK0qVxnxbuGFW8iBlJNYs5wgndA==}+'@types/[email protected]':resolution: {integrity: sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==}@@ -4749,6 +4771,9 @@ packages:resolution: {integrity: sha512-QWBrQsMpH7gPr965dsKD/3cKWiNoTjpATQf++Xq63N6sKRGMwlVXz41O1IZTMfZQgBctD/K5Zt06+/I6pP6+HA==}+ resolution: {integrity: sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==}+resolution: {integrity: sha512-mu8aAWucZjTB5O/BtGXtW4e1agy7uHxNYG7zPthmmD1jU43LCDmSWZLN4JhflbdPXj3yDO4lxM1O9hLDgIOXDw==}@@ -5670,6 +5695,13 @@ packages:resolution: {integrity: sha512-XjBR15BhXuylgWGuslhDKqlSayuqvqBX91BP8pauG8kd1zY8kotkNWbXksTCNRarse4kuGbe2kIY05ARtwNIvw==}+ resolution: {integrity: sha512-CWbTpr5vcHw5bt9i4zSlPEVQdTVcML390TjeDG0cK59z1ylexpqC6M1PJFjV8jD7CF+ACBFsLIDs6DRMoLEofw==}+ peerDependencies:+ leaflet: ^1.9.0+ react: ^19.0.0+ react-dom: ^19.0.0+resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==}peerDependencies:@@ -8487,6 +8519,12 @@ snapshots:'@posthog/[email protected]': {}+ '@react-leaflet/[email protected]([email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ leaflet: 1.9.4+ react: 19.2.4+ react-dom: 19.2.4([email protected])+'@reduxjs/[email protected]([email protected](@types/[email protected])([email protected])([email protected]))([email protected])':dependencies:'@standard-schema/spec': 1.1.0@@ -9316,6 +9354,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:'@types/unist': 3.0.3@@ -9324,6 +9364,10 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/geojson': 7946.0.16+'@types/[email protected]':dependencies:'@types/unist': 3.0.3@@ -10922,6 +10966,8 @@ snapshots:picocolors: 1.1.1shell-quote: 1.9.0+ [email protected]: {}+dependencies:libsodium: 0.8.4@@ -12019,6 +12065,13 @@ snapshots:+ dependencies:+ '@react-leaflet/core': 3.0.0([email protected])([email protected]([email protected]))([email protected])+ leaflet: 1.9.4+ react: 19.2.4+ react-dom: 19.2.4([email protected])+dependencies:'@types/hast': 3.0.4diff --git a/scripts/erase-user-data.ts b/scripts/erase-user-data.tsindex 201733b0..10b6dfbf 100644--- a/scripts/erase-user-data.ts+++ b/scripts/erase-user-data.ts@@ -37,6 +37,7 @@ import {type GdprStorageErasurePayload,} from "../src/shared/gdpr-erasure";import { GSC_OAUTH_PROVIDER_ID } from "../src/shared/gsc";+import { LocalScanStatus } from "../src/shared/local-seo";import { loadLocalEnv, parseArgs } from "./cli-utils";// The Node-safe raw barrel (not ../src/db/schema, the provider-aware one,// which imports cloudflare:workers).@@ -268,6 +269,22 @@ async function buildInventory(db: Db, user: UserRow) {).orderBy(schema.aiRuns.id);+ const activeLocalRankWorkflows =+ projectIds.length === 0+ ? []+ : await db+ .select({ id: schema.localRankChecks.id })+ .from(schema.localRankChecks)+ .where(+ and(+ inArray(schema.localRankChecks.projectId, projectIds),+ inArray(schema.localRankChecks.status, [+ LocalScanStatus.Queued,+ LocalScanStatus.Running,+ ]),+ ),+ )+ .orderBy(schema.localRankChecks.id);// Any table with a `project_id`: the counts differ only in which table.const projectCount = async (table: PgTable & { projectId: PgColumn }) =>projectIds.length === 0@@ -349,6 +366,7 @@ async function buildInventory(db: Db, user: UserRow) {googleAccounts,activeAuditWorkflowIds: activeAuditWorkflows.map((row) => row.id),activeRankWorkflowIds: activeRankWorkflows.map((row) => row.id),+ activeLocalRankWorkflowIds: activeLocalRankWorkflows.map((row) => row.id),databaseCounts,};}@@ -632,6 +650,7 @@ async function main() {r2Objects: inventory.r2Keys.length,activeAuditWorkflows: inventory.activeAuditWorkflowIds.length,activeRankWorkflows: inventory.activeRankWorkflowIds.length,+ activeLocalRankWorkflows: inventory.activeLocalRankWorkflowIds.length,},external: {googleAccounts: inventory.googleAccounts.length,@@ -674,6 +693,7 @@ async function main() {activeAuditWorkflowIds: inventory.activeAuditWorkflowIds,activeRankWorkflowIds: inventory.activeRankWorkflowIds,activeAiVisibilityWorkflowIds: inventory.activeAiVisibilityWorkflowIds,+ activeLocalRankWorkflowIds: inventory.activeLocalRankWorkflowIds,aiVisibilityProjectIds: inventory.aiVisibilityProjectIds,r2Keys: inventory.r2Keys,googleAccounts: inventory.googleAccounts,diff --git a/src/client/features/local-seo/GoogleMapsTiles.tsx b/src/client/features/local-seo/GoogleMapsTiles.tsxnew file mode 100644index 00000000..3dfb7251--- /dev/null+++ b/src/client/features/local-seo/GoogleMapsTiles.tsx@@ -0,0 +1,80 @@+import { useState } from "react";+import { keepPreviousData, useQuery } from "@tanstack/react-query";+import type { Map } from "leaflet";+import { TileLayer, useMap, useMapEvents } from "react-leaflet";+import { QueryError } from "@/client/components/QueryState";+import { getLocalMapCopyright } from "@/serverFunctions/google-maps";+import type { GoogleMapsViewport } from "@/types/schemas/google-maps";+import googleMapsLogo from "./google-maps-logo.svg";++function readViewport(map: Map): GoogleMapsViewport {+ const bounds = map.getBounds();+ const southWest = map.wrapLatLng(bounds.getSouthWest());+ const northEast = map.wrapLatLng(bounds.getNorthEast());+ return {+ zoom: map.getZoom(),+ north: Math.min(85.0511287798, northEast.lat),+ south: Math.max(-85.0511287798, southWest.lat),+ east: northEast.lng,+ west: southWest.lng,+ };+}++export function GoogleMapsTiles({ projectId }: { projectId: string }) {+ const map = useMap();+ const [viewport, setViewport] = useState(() => readViewport(map));+ // The map only moves when its container resizes and the grid is refitted.+ useMapEvents({ moveend: () => setViewport(readViewport(map)) });+ const copyright = useQuery({+ queryKey: ["localSeo", projectId, "map-copyright", viewport],+ queryFn: () => getLocalMapCopyright({ data: { projectId, viewport } }),+ // Copyright is used only for the current viewport; do not retain old views,+ // but keep showing the last one so the tiles stay mounted while it loads.+ gcTime: 0,+ placeholderData: keepPreviousData,+ retry: false,+ });++ if (copyright.isError) {+ return (+ <div className="absolute inset-x-4 top-4 z-[1000]">+ <QueryError+ error={copyright.error}+ title="Google Maps unavailable"+ fallback="Map tiles could not load. Check the map key's access and quota, or view rankings in Points."+ onRetry={() => void copyright.refetch()}+ isRetrying={copyright.isFetching}+ />+ </div>+ );+ }+ if (copyright.isPending) {+ return (+ <div+ role="status"+ className="absolute inset-x-0 top-4 z-[1000] text-center text-sm"+ >+ Loading Google Maps…+ </div>+ );+ }++ return (+ <>+ <TileLayer+ url={`/api/local-seo/maps/${encodeURIComponent(projectId)}/{z}/{x}/{y}`}+ maxZoom={22}+ />+ <div className="leaflet-bottom leaflet-left">+ <div className="leaflet-control local-google-maps-logo">+ <img src={googleMapsLogo} alt="Google Maps" />+ </div>+ </div>+ <div className="leaflet-bottom leaflet-right local-google-maps-attribution">+ <div className="leaflet-control local-google-maps-copyright">+ {copyright.data}+ </div>+ </div>+ </>+ );+}diff --git a/src/client/features/local-seo/LocalKeywordMap.tsx b/src/client/features/local-seo/LocalKeywordMap.tsxnew file mode 100644index 00000000..30d42014--- /dev/null+++ b/src/client/features/local-seo/LocalKeywordMap.tsx@@ -0,0 +1,129 @@+import { useQuery } from "@tanstack/react-query";+import {+ getLocalScan,+ type getLocalTracker,+} from "@/serverFunctions/local-seo";+import { QueryError } from "@/client/components/QueryState";+import { EmptyState } from "@/client/components/EmptyState";+import { Button } from "@/client/components/ui/button";+import { Card } from "@/client/components/ui/card";+import {+ buildLocalGrid,+ isLocalScanActive,+ LocalPointStatus,+} from "@/shared/local-seo";+import { LocalRankGrid, type LocalGridDisplayPoint } from "./LocalRankGrid";+import { LocalPointResults } from "./LocalPointResults";+import type { LocalSeoSearch } from "@/types/schemas/local-seo-search";++type TrackerData = Awaited<ReturnType<typeof getLocalTracker>>;++export function LocalKeywordMap({+ projectId,+ tracker,+ keyword,+ selectedScan,+ historical,+ search,+ onSearchChange,+}: {+ projectId: string;+ tracker: TrackerData["tracker"];+ keyword: TrackerData["keywords"][number];+ selectedScan: TrackerData["scans"][number] | undefined;+ historical: boolean;+ search: LocalSeoSearch;+ onSearchChange: (search: LocalSeoSearch) => void;+}) {+ const query = useQuery({+ queryKey: ["localSeo", projectId, "scan", selectedScan?.id],+ queryFn: () =>+ getLocalScan({ data: { projectId, scanId: selectedScan!.id } }),+ enabled: Boolean(selectedScan),+ refetchInterval: (state) =>+ state.state.data && isLocalScanActive(state.state.data.scan.status)+ ? 4000+ : false,+ });+ const data = query.data;+ const points: LocalGridDisplayPoint[] =+ data?.points ??+ buildLocalGrid(tracker, tracker.gridSize, tracker.spacingKm).map(+ (point) => ({+ ...point,+ id: `${point.row}-${point.col}`,+ status: LocalPointStatus.Pending,+ rank: null,+ resultsCount: null,+ }),+ );+ const point =+ points.find((row) => row.id === search.point) ??+ points[Math.floor(points.length / 2)];+ return (+ <div className="space-y-3 border-t border-border p-4">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="space-y-1">+ <h3 className="text-sm font-semibold">{keyword.keyword}</h3>+ <p className="text-xs text-muted-foreground">+ {selectedScan+ ? `${historical ? "Saved check" : "Latest check"} · ${new Date(selectedScan.createdAt).toLocaleString()}`+ : "Grid preview"}+ </p>+ </div>+ {historical && (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => onSearchChange({ keyword: keyword.id })}+ >+ Back to latest+ </Button>+ )}+ </div>+ {data?.scan.error && <QueryError fallback={data.scan.error} />}+ {query.isError && (+ <QueryError+ error={query.error}+ fallback="Failed to load ranking results."+ onRetry={() => void query.refetch()}+ />+ )}+ <div className="grid auto-rows-[22rem] gap-4 lg:grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)]">+ <LocalRankGrid+ projectId={projectId}+ points={points}+ selectedPointId={point?.id}+ preview={!data}+ onSelect={(pointId) => {+ if (selectedScan && data)+ onSearchChange({+ ...search,+ keyword: keyword.id,+ scan: selectedScan.id,+ point: pointId,+ });+ }}+ />+ {data && selectedScan && point ? (+ <LocalPointResults+ point={point}+ results={data.results.filter(+ (result) => result.pointId === point.id,+ )}+ cid={tracker.cid}+ placeId={tracker.placeId}+ />+ ) : (+ <Card className="gap-0 py-0 shadow-none">+ <EmptyState+ variant="plain"+ title="Preview your coverage"+ description="Check rankings to see where this business appears for your tracked keywords. Select a point to see the businesses ranking there."+ />+ </Card>+ )}+ </div>+ </div>+ );+}diff --git a/src/client/features/local-seo/LocalKeywordsDialog.tsx b/src/client/features/local-seo/LocalKeywordsDialog.tsxnew file mode 100644index 00000000..57765b60--- /dev/null+++ b/src/client/features/local-seo/LocalKeywordsDialog.tsx@@ -0,0 +1,88 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { revalidateLogic } from "@tanstack/react-form";+import { z } from "zod";+import { FormDialog } from "@/client/components/FormDialog";+import { useAppForm } from "@/client/components/form/useAppForm";+import { QueryError } from "@/client/components/QueryState";+import { Button } from "@/client/components/ui/button";+import { parseKeywordInput } from "@/client/features/keywords/state/keywordControllerActions";+import { updateLocalKeywords } from "@/serverFunctions/local-seo";+import { localKeywordsSchema } from "@/types/schemas/local-seo";++export const localKeywordsTextSchema = z+ .string()+ .refine(+ (value) => localKeywordsSchema.safeParse(parseKeywordInput(value)).success,+ "Enter up to 20 keywords, up to 120 characters each.",+ );++export function LocalKeywordsDialog({+ projectId,+ trackerId,+ keywords,+ onClose,+}: {+ projectId: string;+ trackerId: string;+ keywords: { keyword: string }[];+ onClose: () => void;+}) {+ const queryClient = useQueryClient();+ const save = useMutation({+ mutationFn: (terms: string[]) =>+ updateLocalKeywords({ data: { projectId, trackerId, keywords: terms } }),+ onSuccess: async () => {+ await queryClient.invalidateQueries({+ queryKey: ["localSeo", projectId],+ });+ onClose();+ },+ });+ const form = useAppForm({+ defaultValues: { keywords: keywords.map((row) => row.keyword).join("\n") },+ validationLogic: revalidateLogic(),+ validators: {+ onDynamic: z.object({ keywords: localKeywordsTextSchema }),+ },+ onSubmit: async ({ value }) => {+ await save.mutateAsync(parseKeywordInput(value.keywords));+ },+ });+ return (+ <FormDialog+ title="Manage keywords"+ onClose={onClose}+ actions={+ <>+ <Button variant="outline" disabled={save.isPending} onClick={onClose}>+ Cancel+ </Button>+ <Button type="submit" form="local-keywords" pending={save.isPending}>+ Save keywords+ </Button>+ </>+ }+ >+ <form.AppForm>+ <form.Form id="local-keywords" className="space-y-4">+ <form.AppField name="keywords">+ {(field) => (+ <field.TextareaField+ label="Keywords to track"+ placeholder="One keyword per line"+ rows={6}+ description="Add, change, or remove search terms here. Each ranking check searches every keyword at each grid point. Saved results for removed terms are kept."+ />+ )}+ </form.AppField>+ </form.Form>+ </form.AppForm>+ {save.isError && (+ <QueryError+ error={save.error}+ fallback="Could not save these keywords."+ />+ )}+ </FormDialog>+ );+}diff --git a/src/client/features/local-seo/LocalKeywordsTable.tsx b/src/client/features/local-seo/LocalKeywordsTable.tsxnew file mode 100644index 00000000..d19a1059--- /dev/null+++ b/src/client/features/local-seo/LocalKeywordsTable.tsx@@ -0,0 +1,249 @@+import { useMemo, useState } from "react";+import type { ColumnDef, SortingState } from "@tanstack/react-table";+import { sort } from "remeda";+import { Button } from "@/client/components/ui/button";+import { Badge } from "@/client/components/ui/badge";+import { DataTable, useDataTable } from "@/client/components/table/DataTable";+import { SortableHeader } from "@/client/components/table/SortableHeader";+import { RANK_TRACKING_HEADER_CLASS } from "@/client/features/rank-tracking/RankTrackingColumns";+import { isLocalScanActive, LocalScanStatus } from "@/shared/local-seo";+import type { getLocalTracker } from "@/serverFunctions/local-seo";++type TrackerData = Awaited<ReturnType<typeof getLocalTracker>>;+type KeywordRow = TrackerData["keywords"][number] & {+ latest: TrackerData["scans"][number] | undefined;+};++const NO_SORTING: SortingState = [];++/** A keyword's newest scan with results, or its newest scan. */+export function latestKeywordScan(+ scans: TrackerData["scans"],+ keywordId: string,+) {+ const keywordScans = scans.filter((scan) => scan.keywordId === keywordId);+ return (+ keywordScans.find((scan) => (scan.summary?.completed ?? 0) > 0) ??+ keywordScans[0]+ );+}++export function LocalKeywordsTable({+ data,+ history,+ selectedKeywordId,+ selectedScanId,+ onSelect,+ onManage,+}: {+ data: TrackerData;+ history: boolean;+ selectedKeywordId?: string;+ selectedScanId?: string;+ onSelect: (keywordId: string, scanId?: string) => void;+ onManage: () => void;+}) {+ const { keywords, scans, checks } = data;+ const [sorting, setSorting] = useState<SortingState>([+ { id: "keyword", desc: false },+ ]);+ const rows = useMemo(+ () =>+ keywords.map((keyword) => ({+ ...keyword,+ latest: latestKeywordScan(scans, keyword.id),+ })),+ [keywords, scans],+ );+ const columns = useMemo<ColumnDef<KeywordRow>[]>(() => {+ const keywordColumn: ColumnDef<KeywordRow> = {+ id: "keyword",+ accessorKey: "keyword",+ header: ({ column }) =>+ history ? (+ "Keyword"+ ) : (+ <SortableHeader+ column={column}+ label="Keyword"+ className={RANK_TRACKING_HEADER_CLASS}+ />+ ),+ meta: { headerClassName: "w-1/3 min-w-48", cellClassName: "font-medium" },+ cell: ({ row }) => (+ <button+ type="button"+ className="text-left font-medium decoration-dotted underline-offset-2 hover:underline"+ aria-pressed={row.id === selectedKeywordId}+ title="View ranking map"+ onClick={(event) => {+ event.stopPropagation();+ onSelect(row.id);+ }}+ >+ {row.original.keyword}+ </button>+ ),+ };+ if (history)+ return [+ keywordColumn,+ ...sort(+ checks.filter((check) => !isLocalScanActive(check.status)),+ (a, b) => a.createdAt.localeCompare(b.createdAt),+ ).map(+ (check): ColumnDef<KeywordRow> => ({+ id: check.id,+ header: () => (+ <span title={new Date(check.createdAt).toLocaleString()}>+ {new Date(check.createdAt).toLocaleString(undefined, {+ month: "short",+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+ })}+ </span>+ ),+ meta: {+ headerClassName: "min-w-36 text-right",+ cellClassName: "text-right",+ },+ cell: ({ row }) => {+ const scan = scans.find(+ (candidate) =>+ candidate.checkId === check.id &&+ candidate.keywordId === row.id,+ );+ if (!scan)+ return <span className="text-muted-foreground">—</span>;+ return (+ <button+ type="button"+ className="font-mono text-xs decoration-dotted underline-offset-2 hover:underline aria-pressed:text-primary"+ aria-pressed={scan.id === selectedScanId}+ title={`View map for ${row.original.keyword}, ${new Date(check.createdAt).toLocaleString()}`}+ onClick={(event) => {+ event.stopPropagation();+ onSelect(row.id, scan.id);+ }}+ >+ {scan.status === LocalScanStatus.Failed+ ? "Failed"+ : (scan.summary?.averageRank ?? "—")}+ </button>+ );+ },+ }),+ ),+ ];+ return [+ keywordColumn,+ {+ id: "averageRank",+ accessorFn: (row) => row.latest?.summary?.averageRank ?? undefined,+ header: ({ column }) => (+ <SortableHeader+ column={column}+ label="Avg. rank"+ className={RANK_TRACKING_HEADER_CLASS}+ />+ ),+ cell: ({ row }) => row.original.latest?.summary?.averageRank ?? "—",+ meta: { cellClassName: "font-mono text-xs" },+ sortUndefined: "last",+ },+ {+ id: "top3Percent",+ accessorFn: (row) => row.latest?.summary?.top3Percent ?? undefined,+ header: ({ column }) => (+ <SortableHeader+ column={column}+ label="Top-3 coverage"+ className={RANK_TRACKING_HEADER_CLASS}+ />+ ),+ cell: ({ row }) =>+ row.original.latest?.summary?.top3Percent == null+ ? "—"+ : `${row.original.latest.summary.top3Percent}%`,+ meta: { cellClassName: "font-mono text-xs" },+ sortUndefined: "last",+ },+ {+ id: "pointsFound",+ accessorFn: (row) => row.latest?.summary?.found,+ header: ({ column }) => (+ <SortableHeader+ column={column}+ label="Points found"+ className={RANK_TRACKING_HEADER_CLASS}+ />+ ),+ cell: ({ row }) =>+ row.original.latest?.summary+ ? `${row.original.latest.summary.found}/${row.original.latest.summary.completed}`+ : "—",+ meta: { cellClassName: "font-mono text-xs" },+ sortUndefined: "last",+ },+ {+ id: "lastChecked",+ accessorFn: (row) => row.latest?.createdAt,+ header: ({ column }) => (+ <SortableHeader+ column={column}+ label="Last checked"+ className={RANK_TRACKING_HEADER_CLASS}+ />+ ),+ cell: ({ row }) => <LastChecked scan={row.original.latest} />,+ meta: { cellClassName: "text-xs text-muted-foreground" },+ sortUndefined: "last",+ },+ ];+ }, [history, checks, scans, onSelect, selectedKeywordId, selectedScanId]);+ const table = useDataTable({+ data: rows,+ columns,+ state: { sorting: history ? NO_SORTING : sorting },+ onSortingChange: setSorting,+ withSorting: true,+ enableSortingRemoval: false,+ getRowId: (row) => row.id,+ });+ return (+ <DataTable+ table={table}+ activeRowId={selectedKeywordId}+ onRowClick={(row) => onSelect(row.id)}+ empty={{+ title: "Add keywords to start tracking",+ description:+ "Enter the searches customers use to find this business. Then check its rankings across the map.",+ action: (+ <Button size="sm" onClick={onManage}>+ Add keywords+ </Button>+ ),+ }}+ />+ );+}++function LastChecked({ scan }: { scan: KeywordRow["latest"] }) {+ if (!scan) return "Not checked";+ return (+ <span className="flex flex-wrap items-center gap-2">+ {new Date(scan.createdAt).toLocaleString()}+ {scan.status !== LocalScanStatus.Completed && (+ <Badge+ variant={+ scan.status === LocalScanStatus.Failed ? "destructive" : "secondary"+ }+ >+ {scan.status === LocalScanStatus.Running ? "Checking" : scan.status}+ </Badge>+ )}+ </span>+ );+}diff --git a/src/client/features/local-seo/LocalPointResults.tsx b/src/client/features/local-seo/LocalPointResults.tsxnew file mode 100644index 00000000..36d31c17--- /dev/null+++ b/src/client/features/local-seo/LocalPointResults.tsx@@ -0,0 +1,97 @@+import type { getLocalScan } from "@/serverFunctions/local-seo";+import { EmptyState } from "@/client/components/EmptyState";+import { Card, CardHeader, CardTitle } from "@/client/components/ui/card";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/client/components/ui/table";+import { LocalPointStatus } from "@/shared/local-seo";+import type { LocalGridDisplayPoint } from "./LocalRankGrid";++type PointResult = Awaited<ReturnType<typeof getLocalScan>>["results"][number];++export function LocalPointResults({+ point,+ results,+ cid,+ placeId,+}: {+ point: LocalGridDisplayPoint;+ results: PointResult[];+ cid: string | null;+ placeId: string | null;+}) {+ return (+ <Card className="h-full min-h-0 min-w-0 gap-0 overflow-hidden py-0 shadow-none">+ <CardHeader className="shrink-0 px-4 py-3">+ <CardTitle className="text-sm">+ Row {point.row + 1}, column {point.col + 1}+ </CardTitle>+ </CardHeader>+ <div className="min-h-0 flex-1 overflow-y-auto border-t border-border">+ {point.status !== LocalPointStatus.Completed ? (+ <EmptyState+ variant="plain"+ title={+ point.status === LocalPointStatus.Pending+ ? "Search pending"+ : "Search failed"+ }+ description={+ point.status === LocalPointStatus.Pending+ ? "The saved scan will update when results arrive."+ : "This point has no ranking result. Other points remain available."+ }+ />+ ) : results.length === 0 ? (+ <EmptyState+ variant="plain"+ title="No listings returned"+ description="Google Maps returned no businesses at this coordinate."+ />+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Rank</TableHead>+ <TableHead>Business</TableHead>+ <TableHead>Reviews</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {results.map((result) => (+ <TableRow+ key={result.id}+ data-state={+ (cid != null && result.cid === cid) ||+ (placeId != null && result.placeId === placeId)+ ? "selected"+ : undefined+ }+ >+ <TableCell className="font-mono">{result.rank}</TableCell>+ <TableCell>+ <p className="font-medium">{result.title}</p>+ <p className="text-xs text-muted-foreground">+ {result.address}+ </p>+ </TableCell>+ <TableCell className="text-xs">+ <p>{result.rating == null ? "—" : `${result.rating} ★`}</p>+ <p className="text-muted-foreground">+ {result.reviews?.toLocaleString() ?? "—"}+ </p>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )}+ </div>+ </Card>+ );+}diff --git a/src/client/features/local-seo/LocalRankGrid.tsx b/src/client/features/local-seo/LocalRankGrid.tsxnew file mode 100644index 00000000..28eaf923--- /dev/null+++ b/src/client/features/local-seo/LocalRankGrid.tsx@@ -0,0 +1,149 @@+import { lazy, Suspense, useState } from "react";+import { ClientOnly } from "@tanstack/react-router";+import { Map, List } from "lucide-react";+import {+ type LocalPointStatus,+ localPointLabel,+ type LocalGridPoint,+} from "@/shared/local-seo";+import { SegmentedToggle } from "@/client/components/SegmentedToggle";+import { Button } from "@/client/components/ui/button";+import {+ Card,+ CardAction,+ CardHeader,+ CardTitle,+} from "@/client/components/ui/card";+import { Skeleton } from "@/client/components/ui/skeleton";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/client/components/ui/table";++const MapView = lazy(() => import("./LocalRankMap"));+export type LocalGridDisplayPoint = LocalGridPoint & {+ id: string;+ status: LocalPointStatus;+ rank: number | null;+ resultsCount: number | null;+};++export function LocalRankGrid({+ projectId,+ points,+ selectedPointId,+ onSelect,+ preview,+}: {+ projectId: string;+ points: LocalGridDisplayPoint[];+ selectedPointId?: string;+ onSelect: (id: string) => void;+ preview: boolean;+}) {+ const [tableView, setTableView] = useState(false);+ return (+ <Card className="h-full min-h-0 min-w-0 gap-0 overflow-hidden py-0 shadow-none">+ <CardHeader className="shrink-0 items-center gap-2 px-4 py-3">+ <CardTitle className="text-sm">+ {preview ? "Grid preview" : "Maps rankings"}+ </CardTitle>+ <CardAction>+ <SegmentedToggle+ showLabels+ items={[+ {+ value: "map",+ icon: <Map className="size-3.5" />,+ label: "Map",+ },+ {+ value: "points",+ icon: <List className="size-3.5" />,+ label: "Points",+ },+ ]}+ value={tableView ? "points" : "map"}+ onChange={(value) => setTableView(value === "points")}+ />+ </CardAction>+ </CardHeader>+ <div className="min-h-0 flex-1 overflow-hidden border-t border-border">+ {tableView ? (+ <div className="h-full overflow-y-auto">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Point</TableHead>+ <TableHead>Coordinates</TableHead>+ <TableHead>Rank</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {points.map((point) => (+ <TableRow+ key={point.id}+ data-state={+ point.id === selectedPointId ? "selected" : undefined+ }+ >+ <TableCell>+ <Button+ size="sm"+ variant="link"+ onClick={() => onSelect(point.id)}+ >+ Row {point.row + 1}, col {point.col + 1}+ </Button>+ </TableCell>+ <TableCell className="font-mono text-xs">+ {point.latitude.toFixed(5)}, {point.longitude.toFixed(5)}+ </TableCell>+ <TableCell>+ {preview ? "Not checked" : localPointLabel(point)}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ ) : (+ <ClientOnly fallback={<Skeleton className="h-full rounded-none" />}>+ <Suspense fallback={<Skeleton className="h-full rounded-none" />}>+ <MapView+ key={points.map((point) => point.id).join(",")}+ projectId={projectId}+ points={points}+ selectedPointId={selectedPointId}+ onSelect={onSelect}+ preview={preview}+ />+ </Suspense>+ </ClientOnly>+ )}+ </div>+ {!tableView && (+ <div className="flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-t border-border px-4 py-3 text-xs text-muted-foreground">+ <span>+ <span className="mr-1 inline-block size-2 rounded-full bg-green-600" />+ 1–3+ </span>+ <span>+ <span className="mr-1 inline-block size-2 rounded-full bg-amber-600" />+ 4–10+ </span>+ <span>+ <span className="mr-1 inline-block size-2 rounded-full bg-red-600" />+ 11–20+ </span>+ <span>– Not found</span>+ <span>! Failed</span>+ </div>+ )}+ </Card>+ );+}diff --git a/src/client/features/local-seo/LocalRankMap.tsx b/src/client/features/local-seo/LocalRankMap.tsxnew file mode 100644index 00000000..10025771--- /dev/null+++ b/src/client/features/local-seo/LocalRankMap.tsx@@ -0,0 +1,99 @@+import {+ CircleMarker,+ MapContainer,+ Tooltip,+ useMap,+ useMapEvents,+} from "react-leaflet";+import type { LatLngBoundsExpression } from "leaflet";+import { LocalPointStatus } from "@/shared/local-seo";+import { GoogleMapsTiles } from "./GoogleMapsTiles";+import type { LocalGridDisplayPoint } from "./LocalRankGrid";++const GRID_PADDING = { padding: [38, 38] as [number, number] };++/** Keeps the whole grid in view when the map's container changes size. */+function FitGridOnResize({ bounds }: { bounds: LatLngBoundsExpression }) {+ const map = useMap();+ useMapEvents({ resize: () => map.fitBounds(bounds, GRID_PADDING) });+ return null;+}++export default function LocalRankMap({+ projectId,+ points,+ selectedPointId,+ onSelect,+ preview,+}: {+ projectId: string;+ points: LocalGridDisplayPoint[];+ selectedPointId?: string;+ onSelect: (id: string) => void;+ preview: boolean;+}) {+ const bounds: LatLngBoundsExpression = points.map((point) => [+ point.latitude,+ point.longitude,+ ]);+ return (+ // The view is fixed to the grid: no panning or zooming.+ <MapContainer+ bounds={bounds}+ boundsOptions={GRID_PADDING}+ dragging={false}+ zoomControl={false}+ scrollWheelZoom={false}+ doubleClickZoom={false}+ touchZoom={false}+ boxZoom={false}+ keyboard={false}+ attributionControl={false}+ className="z-0 h-full w-full"+ aria-label="Local search ranking grid on a Google Maps basemap"+ >+ <FitGridOnResize bounds={bounds} />+ <GoogleMapsTiles projectId={projectId} />+ {points.map((point) => {+ const color =+ point.status !== LocalPointStatus.Completed || point.rank == null+ ? "#64748b"+ : point.rank <= 3+ ? "#16a34a"+ : point.rank <= 10+ ? "#d97706"+ : "#dc2626";+ const label = preview+ ? "·"+ : point.status === LocalPointStatus.Pending+ ? "…"+ : point.status === LocalPointStatus.Failed+ ? "!"+ : (point.rank ?? "–");+ return (+ <CircleMarker+ key={point.id}+ center={[point.latitude, point.longitude]}+ radius={19}+ pathOptions={{+ fillColor: color,+ fillOpacity: 1,+ color: selectedPointId === point.id ? "#0f172a" : "#ffffff",+ weight: selectedPointId === point.id ? 4 : 2,+ }}+ eventHandlers={{ click: () => onSelect(point.id) }}+ >+ <Tooltip+ permanent+ direction="center"+ className="local-rank-label"+ opacity={1}+ >+ {label}+ </Tooltip>+ </CircleMarker>+ );+ })}+ </MapContainer>+ );+}diff --git a/src/client/features/local-seo/LocalTrackerDetail.tsx b/src/client/features/local-seo/LocalTrackerDetail.tsxnew file mode 100644index 00000000..20d5216b--- /dev/null+++ b/src/client/features/local-seo/LocalTrackerDetail.tsx@@ -0,0 +1,241 @@+import { useState } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { CalendarDays, List, Pencil, Play } from "lucide-react";+import { getLocalTracker, startLocalCheck } from "@/serverFunctions/local-seo";+import { QueryError, QueryState } from "@/client/components/QueryState";+import { ConfirmDialog } from "@/client/components/ConfirmDialog";+import { SegmentedToggle } from "@/client/components/SegmentedToggle";+import { Button } from "@/client/components/ui/button";+import { Card } from "@/client/components/ui/card";+import { isLocalScanActive, LocalScanStatus } from "@/shared/local-seo";+import { LocalKeywordMap } from "./LocalKeywordMap";+import { LocalKeywordsDialog } from "./LocalKeywordsDialog";+import { LocalKeywordsTable, latestKeywordScan } from "./LocalKeywordsTable";+import type { LocalSeoSearch } from "@/types/schemas/local-seo-search";++type TrackerData = Awaited<ReturnType<typeof getLocalTracker>>;++export function LocalTrackerDetail({+ projectId,+ trackerId,+ search,+ onSearchChange,+}: {+ projectId: string;+ trackerId: string;+ search: LocalSeoSearch;+ onSearchChange: (search: LocalSeoSearch) => void;+}) {+ const query = useQuery({+ queryKey: ["localSeo", projectId, "tracker", trackerId],+ queryFn: () => getLocalTracker({ data: { projectId, trackerId } }),+ refetchInterval: (state) =>+ state.state.data?.checks.some((check) => isLocalScanActive(check.status))+ ? 4000+ : false,+ });+ return (+ <QueryState query={query} errorFallback="Failed to load local tracking">+ {(data) => (+ <TrackerContent+ projectId={projectId}+ data={data}+ search={search}+ onSearchChange={onSearchChange}+ />+ )}+ </QueryState>+ );+}++function TrackerContent({+ projectId,+ data,+ search,+ onSearchChange,+}: {+ projectId: string;+ data: TrackerData;+ search: LocalSeoSearch;+ onSearchChange: (search: LocalSeoSearch) => void;+}) {+ const { tracker, keywords, checks, scans, estimate } = data;+ const queryClient = useQueryClient();+ const [confirm, setConfirm] = useState<string | null>(null);+ const [managingKeywords, setManagingKeywords] = useState(false);+ const keyword =+ keywords.find((row) => row.id === search.keyword) ?? keywords[0];+ const latestScan = keyword && latestKeywordScan(scans, keyword.id);+ const selectedScan =+ scans.find(+ (scan) => scan.keywordId === keyword?.id && scan.id === search.scan,+ ) ?? latestScan;+ const start = useMutation({+ mutationFn: (requestId: string) =>+ startLocalCheck({+ data: {+ projectId,+ trackerId: tracker.id,+ requestId,+ maxCostCredits: estimate.costCredits,+ },+ }),+ onSuccess: async () => {+ setConfirm(null);+ onSearchChange({ keyword: keyword?.id });+ await queryClient.invalidateQueries({+ queryKey: ["localSeo", projectId],+ });+ },+ });+ const active = checks.find((check) => isLocalScanActive(check.status));+ // Latest falls back to each keyword's newest results, so say when the map+ // shows an older check because the newest one returned none.+ const failed =+ checks[0]?.status === LocalScanStatus.Failed &&+ selectedScan?.checkId !== checks[0].id &&+ checks[0];+ const historyAvailable =+ checks.filter((check) => !isLocalScanActive(check.status)).length >= 2;+ const history = historyAvailable && search.view === "history";+ return (+ <div className="space-y-3">+ <Card className="min-w-0 gap-0 py-0">+ <div className="flex flex-col justify-between gap-2 px-4 pt-4 pb-3 sm:flex-row sm:items-start">+ <div className="min-w-0 space-y-1">+ <h2 className="text-lg font-semibold">{tracker.title}</h2>+ <p className="text-xs text-muted-foreground">{tracker.address}</p>+ <p className="text-xs text-muted-foreground">+ {tracker.gridSize}×{tracker.gridSize} grid · {tracker.spacingKm}{" "}+ km spacing · Mobile · Manual checks+ </p>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <Button+ size="sm"+ variant="outline"+ disabled={Boolean(active)}+ onClick={() => setManagingKeywords(true)}+ >+ <Pencil data-icon="inline-start" />+ Manage keywords+ </Button>+ <Button+ size="sm"+ disabled={!keywords.length || Boolean(active)}+ pending={start.isPending}+ onClick={() => setConfirm(crypto.randomUUID())}+ >+ <Play data-icon="inline-start" />+ {active ? "Checking rankings…" : "Check rankings"}+ </Button>+ </div>+ </div>+ {failed && (+ <div className="px-4 pb-3">+ <QueryError+ fallback={+ failed.error ??+ "The last check returned no rankings. Earlier results are shown below."+ }+ />+ </div>+ )}+ {keyword && (+ <LocalKeywordMap+ projectId={projectId}+ tracker={tracker}+ keyword={keyword}+ selectedScan={selectedScan}+ historical={selectedScan?.id !== latestScan?.id}+ search={search}+ onSearchChange={onSearchChange}+ />+ )}+ <div className="flex flex-wrap items-center gap-2 border-y border-border px-4 py-2">+ {historyAvailable && (+ <SegmentedToggle+ showLabels+ items={[+ {+ value: "latest",+ icon: <List className="size-3.5" />,+ label: "Latest",+ },+ {+ value: "history",+ icon: <CalendarDays className="size-3.5" />,+ label: "History",+ },+ ]}+ value={history ? "history" : "latest"}+ onChange={(value) =>+ onSearchChange({+ keyword: keyword?.id,+ view: value === "history" ? "history" : undefined,+ })+ }+ />+ )}+ <span className="text-sm text-muted-foreground">+ {active+ ? `Checking ${estimate.keywords} keyword${estimate.keywords === 1 ? "" : "s"} across ${estimate.points} points`+ : `${keywords.length} keyword${keywords.length === 1 ? "" : "s"}`}+ </span>+ {history && (+ <span className="ml-auto text-xs text-muted-foreground">+ Average rank where found+ </span>+ )}+ </div>+ <div className="p-4">+ <LocalKeywordsTable+ data={data}+ history={history}+ selectedKeywordId={keyword?.id}+ selectedScanId={selectedScan?.id}+ onSelect={(keywordId, scanId) =>+ onSearchChange({+ view: search.view,+ keyword: keywordId,+ scan: scanId,+ })+ }+ onManage={() => setManagingKeywords(true)}+ />+ </div>+ </Card>+ {managingKeywords && (+ <LocalKeywordsDialog+ projectId={projectId}+ trackerId={tracker.id}+ keywords={keywords}+ onClose={() => setManagingKeywords(false)}+ />+ )}+ {confirm && (+ <ConfirmDialog+ title={`Check ${estimate.keywords} keyword${estimate.keywords === 1 ? "" : "s"}?`}+ confirmLabel="Run now"+ pending={start.isPending}+ onConfirm={() => start.mutate(confirm)}+ onClose={() => setConfirm(null)}+ >+ {estimate.keywords} keyword{estimate.keywords === 1 ? "" : "s"}{" "}+ × {estimate.points} grid points = {estimate.searches} Google+ Maps searches on mobile. Costs up to{" "}+ <span className="font-mono font-semibold text-foreground">+ {/* Credits are $0.001, so three decimals show the exact maximum. */}+ {estimate.costUsd.toLocaleString("en-US", {+ style: "currency",+ currency: "USD",+ minimumFractionDigits: 2,+ maximumFractionDigits: 3,+ })}+ </span>+ .+ </ConfirmDialog>+ )}+ </div>+ );+}diff --git a/src/client/features/local-seo/LocalTrackerDialog.tsx b/src/client/features/local-seo/LocalTrackerDialog.tsxnew file mode 100644index 00000000..0b0f4d5d--- /dev/null+++ b/src/client/features/local-seo/LocalTrackerDialog.tsx@@ -0,0 +1,267 @@+import { useState } from "react";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { z } from "zod";+import { revalidateLogic } from "@tanstack/react-form";+import { useAppForm } from "@/client/components/form/useAppForm";+import { FormDialog } from "@/client/components/FormDialog";+import { Button } from "@/client/components/ui/button";+import { QueryError } from "@/client/components/QueryState";+import {+ createLocalTracker,+ lookupLocalBusiness,+} from "@/serverFunctions/local-seo";+import { parseKeywordInput } from "@/client/features/keywords/state/keywordControllerActions";+import type { LocalBusiness } from "@/types/schemas/local-seo";+import { localKeywordsTextSchema } from "./LocalKeywordsDialog";++export function LocalTrackerDialog({+ projectId,+ onClose,+ onCreated,+}: {+ projectId: string;+ onClose: () => void;+ onCreated: (id: string) => void;+}) {+ const [business, setBusiness] = useState<LocalBusiness | null>(null);+ return business ? (+ <TrackerSettings+ projectId={projectId}+ business={business}+ onClose={onClose}+ onCreated={onCreated}+ />+ ) : (+ <ListingLookup+ projectId={projectId}+ onClose={onClose}+ onSelect={setBusiness}+ />+ );+}++function ListingLookup({+ projectId,+ onClose,+ onSelect,+}: {+ projectId: string;+ onClose: () => void;+ onSelect: (business: LocalBusiness) => void;+}) {+ const lookup = useMutation({+ mutationFn: (query: string) =>+ lookupLocalBusiness({ data: { projectId, query } }),+ });+ const form = useAppForm({+ defaultValues: { query: "" },+ validationLogic: revalidateLogic(),+ validators: {+ onDynamic: z.object({+ query: z+ .string()+ .trim()+ .min(2, "Enter a business name and city.")+ .max(200),+ }),+ },+ onSubmit: async ({ value }) => {+ await lookup.mutateAsync(value.query);+ },+ });+ return (+ <FormDialog+ title="Add business"+ onClose={onClose}+ actions={+ <>+ <Button variant="outline" onClick={onClose}>+ Cancel+ </Button>+ <Button+ type="submit"+ form="local-business-lookup"+ pending={lookup.isPending}+ >+ Find listing+ </Button>+ </>+ }+ >+ <form.AppForm>+ <form.Form id="local-business-lookup" className="space-y-4">+ <form.AppField name="query">+ {(field) => (+ <field.TextField+ label="Business name and city"+ placeholder="Business name, street, city"+ description="Finding a listing uses a small amount of credits."+ />+ )}+ </form.AppField>+ </form.Form>+ </form.AppForm>+ {lookup.isError && (+ <QueryError+ error={lookup.error}+ fallback="Could not find this business."+ />+ )}+ {lookup.isSuccess &&+ (lookup.data ? (+ <div className="space-y-3 rounded-lg border border-border p-4">+ <div>+ <p className="text-sm font-medium">{lookup.data.title}</p>+ <p className="text-sm text-muted-foreground">+ {lookup.data.address}+ </p>+ </div>+ <p className="text-xs text-muted-foreground">+ Confirm this is the correct branch before continuing.+ </p>+ <Button+ size="sm"+ onClick={() => {+ if (lookup.data) onSelect(lookup.data);+ }}+ >+ Use this listing+ </Button>+ </div>+ ) : (+ <p className="text-sm text-muted-foreground">+ No matching listing found. Try the business name and full address.+ </p>+ ))}+ </FormDialog>+ );+}++const settingsSchema = z.object({+ keywords: localKeywordsTextSchema,+ gridSize: z.union([z.literal(3), z.literal(5)]),+ spacingKm: z+ .string()+ .refine(+ (value) =>+ value.trim() !== "" && Number(value) >= 0.25 && Number(value) <= 10,+ "Enter a spacing between 0.25 and 10 km.",+ ),+});++function TrackerSettings({+ projectId,+ business,+ onClose,+ onCreated,+}: {+ projectId: string;+ business: LocalBusiness;+ onClose: () => void;+ onCreated: (id: string) => void;+}) {+ const queryClient = useQueryClient();+ const create = useMutation({+ mutationFn: (input: Parameters<typeof createLocalTracker>[0]["data"]) =>+ createLocalTracker({ data: input }),+ onSuccess: (tracker) => {+ void queryClient.invalidateQueries({ queryKey: ["localSeo", projectId] });+ onCreated(tracker.id);+ },+ });+ const form = useAppForm({+ defaultValues: {+ keywords: "",+ gridSize: 3 as 3 | 5,+ spacingKm: "2",+ },+ validationLogic: revalidateLogic(),+ validators: { onDynamic: settingsSchema },+ onSubmit: async ({ value }) => {+ await create.mutateAsync({+ projectId,+ business,+ keywords: parseKeywordInput(value.keywords),+ gridSize: value.gridSize,+ spacingKm: Number(value.spacingKm),+ });+ },+ });+ return (+ <FormDialog+ title="Set up local tracking"+ onClose={onClose}+ actions={+ <>+ <Button+ variant="outline"+ disabled={create.isPending}+ onClick={onClose}+ >+ Cancel+ </Button>+ <Button+ type="submit"+ form="local-tracker-settings"+ pending={create.isPending}+ >+ Save business+ </Button>+ </>+ }+ >+ <div>+ <p className="text-sm font-medium">{business.title}</p>+ <p className="text-sm text-muted-foreground">{business.address}</p>+ </div>+ <form.AppForm>+ <form.Form id="local-tracker-settings" className="space-y-4">+ <form.AppField name="keywords">+ {(field) => (+ <field.TextareaField+ label="Keywords to track (optional)"+ placeholder="One keyword per line"+ rows={3}+ description="Enter the searches customers use to find this business. You can manage this list after saving."+ />+ )}+ </form.AppField>+ <div className="grid grid-cols-2 gap-3">+ <form.AppField name="gridSize">+ {(field) => (+ <field.SelectField+ label="Grid size"+ items={[+ { value: 3, label: "3×3 · 9 points" },+ { value: 5, label: "5×5 · 25 points" },+ ]}+ />+ )}+ </form.AppField>+ <form.AppField name="spacingKm">+ {(field) => (+ <field.TextField+ label="Spacing (km)"+ type="number"+ min="0.25"+ max="10"+ step="0.25"+ />+ )}+ </form.AppField>+ </div>+ <p className="text-xs text-muted-foreground">+ The grid is centered on this listing’s pin. Saving does not start a+ ranking check.+ </p>+ </form.Form>+ </form.AppForm>+ {create.isError && (+ <QueryError+ error={create.error}+ fallback="Could not save this business."+ />+ )}+ </FormDialog>+ );+}diff --git a/src/client/features/local-seo/LocalTrackerList.tsx b/src/client/features/local-seo/LocalTrackerList.tsxnew file mode 100644index 00000000..e8c5ea54--- /dev/null+++ b/src/client/features/local-seo/LocalTrackerList.tsx@@ -0,0 +1,87 @@+import { useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { ChevronRight, MapPin, Plus } from "lucide-react";+import { listLocalTrackers } from "@/serverFunctions/local-seo";+import {+ Card,+ CardAction,+ CardHeader,+ CardTitle,+} from "@/client/components/ui/card";+import { Button } from "@/client/components/ui/button";+import { EmptyState } from "@/client/components/EmptyState";+import { QueryState } from "@/client/components/QueryState";+import { Skeleton } from "@/client/components/ui/skeleton";++export function LocalTrackerList({+ projectId,+ onAdd,+}: {+ projectId: string;+ onAdd: () => void;+}) {+ const query = useQuery({+ queryKey: ["localSeo", projectId, "trackers"],+ queryFn: () => listLocalTrackers({ data: { projectId } }),+ });+ return (+ <Card className="gap-0 py-0">+ <CardHeader className="px-5 pt-4 pb-3">+ <CardTitle>+ <h2 className="text-sm font-semibold">Tracked Businesses</h2>+ </CardTitle>+ <CardAction className="self-center">+ <Button size="sm" onClick={onAdd}>+ <Plus data-icon="inline-start" />+ Add Business+ </Button>+ </CardAction>+ </CardHeader>+ <div className="divide-y divide-border border-t border-border">+ <QueryState+ query={query}+ errorFallback="Failed to load tracked businesses"+ loading={+ <div className="space-y-3 p-5">+ <Skeleton className="h-4 w-48" />+ <Skeleton className="h-3 w-64" />+ </div>+ }+ >+ {(trackers) =>+ trackers.length === 0 ? (+ <EmptyState+ variant="plain"+ icon={MapPin}+ title="No tracked businesses yet"+ description="Add a Google Maps listing to check keyword rankings across the surrounding area."+ />+ ) : (+ trackers.map((tracker) => (+ <Link+ key={tracker.id}+ to="/p/$projectId/local-seo/$trackerId"+ params={{ projectId, trackerId: tracker.id }}+ search={{}}+ className="flex w-full items-center gap-4 px-5 py-3.5 transition-colors hover:bg-foreground/[0.03]"+ >+ <div className="min-w-0 flex-1">+ <p className="truncate font-medium">{tracker.title}</p>+ <p className="truncate text-xs text-muted-foreground">+ {tracker.address}+ </p>+ <p className="text-xs text-muted-foreground">+ {tracker.gridSize}×{tracker.gridSize} grid ·{" "}+ {tracker.spacingKm} km spacing · Mobile+ </p>+ </div>+ <ChevronRight className="size-4 shrink-0 text-muted-foreground" />+ </Link>+ ))+ )+ }+ </QueryState>+ </div>+ </Card>+ );+}diff --git a/src/client/features/local-seo/google-maps-logo.svg b/src/client/features/local-seo/google-maps-logo.svgnew file mode 100644index 00000000..cd8721b4--- /dev/null+++ b/src/client/features/local-seo/google-maps-logo.svg@@ -0,0 +1,50 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Generator: Adobe Illustrator 26.5.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"+ width="98px" height="18px" viewBox="0 0 98 18" enable-background="new 0 0 98 18" xml:space="preserve">+<g>+ <path fill="#1F1F1F" d="M7.08,13.96c-1.93,0-3.59-0.68-4.99-2.05C0.7,10.54,0,8.9,0,6.98c0-1.92,0.7-3.56,2.09-4.93+ C3.49,0.68,5.15,0,7.08,0c1.85,0,3.45,0.64,4.79,1.92l-1.35,1.35C9.56,2.36,8.41,1.91,7.08,1.91c-1.4,0-2.58,0.49-3.55,1.48+ C2.56,4.38,2.08,5.57,2.08,6.98c0,1.41,0.49,2.61,1.46,3.59c0.97,0.99,2.15,1.48,3.55,1.48c1.42,0,2.59-0.47,3.53-1.4+ c0.56-0.56,0.9-1.36,1.04-2.4H7.08V6.35h6.42c0.07,0.34,0.1,0.74,0.1,1.19c0,1.87-0.55,3.36-1.65,4.46+ C10.71,13.31,9.08,13.96,7.08,13.96z M22,12.68c-0.87,0.86-1.94,1.29-3.2,1.29c-1.26,0-2.33-0.43-3.2-1.29+ c-0.87-0.86-1.31-1.93-1.31-3.21c0-1.28,0.44-2.35,1.31-3.21c0.87-0.86,1.94-1.29,3.2-1.29c1.26,0,2.33,0.43,3.2,1.29+ c0.87,0.86,1.31,1.93,1.31,3.21C23.31,10.75,22.88,11.82,22,12.68z M17.01,11.42c0.5,0.52,1.1,0.77,1.79,0.77+ c0.69,0,1.29-0.26,1.79-0.77c0.5-0.52,0.75-1.17,0.75-1.95c0-0.79-0.25-1.45-0.74-1.96C20.1,7,19.5,6.74,18.8,6.74+ c-0.7,0-1.3,0.26-1.8,0.77c-0.49,0.51-0.74,1.16-0.74,1.96C16.26,10.25,16.51,10.9,17.01,11.42z M31.85,12.68+ c-0.87,0.86-1.94,1.29-3.2,1.29s-2.33-0.43-3.2-1.29c-0.87-0.86-1.31-1.93-1.31-3.21c0-1.28,0.44-2.35,1.31-3.21+ c0.87-0.86,1.94-1.29,3.2-1.29s2.33,0.43,3.2,1.29c0.87,0.86,1.31,1.93,1.31,3.21C33.16,10.75,32.72,11.82,31.85,12.68z+ M26.86,11.42c0.5,0.52,1.1,0.77,1.79,0.77c0.69,0,1.29-0.26,1.79-0.77c0.5-0.52,0.75-1.17,0.75-1.95c0-0.79-0.25-1.45-0.74-1.96+ s-1.09-0.77-1.8-0.77c-0.7,0-1.3,0.26-1.8,0.77c-0.49,0.51-0.74,1.16-0.74,1.96C26.11,10.25,26.36,10.9,26.86,11.42z M38.32,18+ c-1,0-1.84-0.27-2.52-0.8c-0.68-0.53-1.17-1.15-1.46-1.86l1.72-0.72c0.18,0.43,0.47,0.81,0.85,1.12c0.39,0.32,0.86,0.48,1.41,0.48+ c0.75,0,1.34-0.23,1.76-0.68c0.43-0.45,0.64-1.11,0.64-1.96v-0.65h-0.07c-0.56,0.68-1.35,1.02-2.37,1.02+ c-1.15,0-2.15-0.44-3.01-1.31c-0.86-0.87-1.29-1.93-1.29-3.17c0-1.25,0.43-2.31,1.29-3.19c0.86-0.88,1.87-1.32,3.01-1.32+ c0.51,0,0.97,0.1,1.39,0.29c0.41,0.19,0.74,0.43,0.98,0.72h0.07V5.25h1.87v8.07c0,1.57-0.4,2.74-1.2,3.52+ C40.59,17.61,39.57,18,38.32,18z M38.45,12.19c0.68,0,1.25-0.26,1.71-0.77c0.46-0.52,0.69-1.16,0.69-1.93+ c0-0.78-0.23-1.44-0.69-1.96C39.7,7,39.13,6.74,38.45,6.74c-0.69,0-1.28,0.26-1.77,0.78c-0.49,0.52-0.73,1.18-0.73,1.96+ c0,0.77,0.24,1.42,0.73,1.93C37.17,11.93,37.76,12.19,38.45,12.19z M45.93,0.48v13.21h-1.98V0.48H45.93z M51.34,13.96+ c-1.27,0-2.33-0.43-3.18-1.29c-0.85-0.86-1.28-1.93-1.28-3.2c0-1.32,0.41-2.4,1.23-3.24c0.82-0.84,1.82-1.26,3.01-1.26+ c0.55,0,1.05,0.1,1.52,0.3c0.47,0.2,0.85,0.45,1.16,0.77c0.31,0.31,0.55,0.62,0.73,0.91c0.18,0.3,0.33,0.59,0.44,0.89l0.2,0.51+ l-6.01,2.49c0.47,0.91,1.19,1.36,2.18,1.36c0.91,0,1.65-0.41,2.21-1.24l1.53,1.02c-0.34,0.51-0.82,0.97-1.45,1.38+ C53.02,13.76,52.25,13.96,51.34,13.96z M48.84,9.33l4.02-1.67c-0.11-0.28-0.32-0.51-0.63-0.69c-0.31-0.18-0.65-0.26-1.04-0.26+ c-0.58,0-1.12,0.24-1.63,0.72C49.06,7.9,48.82,8.54,48.84,9.33z"/>+ <path fill="#1F1F1F" d="M60.05,13.69V1.5h1.57l4.24,7.42h0.07l4.24-7.42h1.57v12.19h-1.57V6.45l0.07-2.04h-0.07l-3.81,6.69h-0.92+ l-3.81-6.69h-0.07l0.07,2.04v7.24H60.05z M76.36,13.96c-0.89,0-1.63-0.26-2.22-0.77c-0.6-0.51-0.89-1.19-0.89-2.03+ c0-0.91,0.35-1.62,1.06-2.14c0.7-0.52,1.57-0.77,2.61-0.77c0.92,0,1.67,0.17,2.26,0.51V8.53c0-0.61-0.21-1.1-0.63-1.47+ c-0.42-0.37-0.94-0.55-1.55-0.55c-0.45,0-0.87,0.11-1.23,0.32C75.39,7.04,75.13,7.34,75,7.71L73.57,7.1+ c0.19-0.5,0.57-0.96,1.14-1.39c0.57-0.43,1.32-0.64,2.25-0.64c1.07,0,1.95,0.31,2.66,0.94c0.7,0.62,1.06,1.5,1.06,2.64v5.04h-1.5+ v-1.16H79.1C78.48,13.49,77.56,13.96,76.36,13.96z M76.61,12.53c0.65,0,1.23-0.24,1.76-0.72c0.53-0.48,0.79-1.05,0.79-1.71+ c-0.44-0.36-1.11-0.54-1.99-0.54c-0.76,0-1.33,0.16-1.72,0.49c-0.39,0.33-0.58,0.72-0.58,1.16c0,0.41,0.18,0.73,0.53,0.97+ C75.76,12.41,76.16,12.53,76.61,12.53z M86.58,13.96c-0.64,0-1.21-0.14-1.71-0.41c-0.51-0.27-0.88-0.61-1.13-1.02h-0.07l0.07,1.16+ v3.68h-1.57V5.35h1.5v1.16h0.07c0.25-0.41,0.63-0.75,1.13-1.02c0.51-0.27,1.08-0.41,1.71-0.41c1.08,0,2.01,0.43,2.79,1.28+ c0.78,0.85,1.18,1.91,1.18,3.17c0,1.26-0.39,2.32-1.18,3.17C88.59,13.54,87.66,13.96,86.58,13.96z M86.32,12.53+ c0.73,0,1.35-0.28,1.87-0.83c0.52-0.55,0.78-1.28,0.78-2.19c0-0.91-0.26-1.64-0.78-2.19c-0.52-0.55-1.15-0.83-1.87-0.83+ c-0.74,0-1.37,0.27-1.88,0.82c-0.52,0.54-0.77,1.28-0.77,2.2s0.26,1.65,0.77,2.2C84.96,12.26,85.58,12.53,86.32,12.53z+ M94.71,13.96c-0.93,0-1.7-0.23-2.31-0.68c-0.61-0.45-1.05-1.02-1.34-1.7l1.4-0.58c0.44,1.04,1.2,1.57,2.26,1.57+ c0.49,0,0.89-0.11,1.2-0.32c0.31-0.22,0.47-0.5,0.47-0.85c0-0.54-0.38-0.91-1.14-1.11l-1.69-0.41c-0.53-0.14-1.04-0.39-1.52-0.77+ c-0.48-0.38-0.72-0.89-0.72-1.54c0-0.74,0.33-1.34,0.98-1.8c0.65-0.46,1.43-0.69,2.32-0.69c0.74,0,1.4,0.17,1.98,0.5+ c0.58,0.34,0.99,0.81,1.24,1.44L96.5,7.58c-0.31-0.74-0.94-1.11-1.91-1.11c-0.47,0-0.86,0.1-1.18,0.29+ c-0.32,0.19-0.48,0.45-0.48,0.78c0,0.48,0.37,0.8,1.11,0.97l1.65,0.39c0.78,0.18,1.36,0.49,1.74,0.94c0.37,0.44,0.56,0.94,0.56,1.5+ c0,0.75-0.31,1.37-0.92,1.87C96.47,13.71,95.68,13.96,94.71,13.96z"/>+</g>+</svg>diff --git a/src/client/features/local-seo/local-rank-map.css b/src/client/features/local-seo/local-rank-map.cssnew file mode 100644index 00000000..d6ed65e4--- /dev/null+++ b/src/client/features/local-seo/local-rank-map.css@@ -0,0 +1,36 @@+.leaflet-tooltip.local-rank-label {+ border: 0;+ background: transparent;+ color: white;+ box-shadow: none;+ font-size: 14px;+ font-weight: 600;+}+.leaflet-tooltip.local-rank-label::before {+ display: none;+}++.leaflet-control.local-google-maps-logo {+ margin: 0;+ padding: 10px 10px 5px;+ background: white;+}+.local-google-maps-logo img {+ height: 16px;+ width: auto;+ max-width: none;+}+.local-google-maps-attribution {+ max-width: calc(100% - 130px);+}+.leaflet-control.local-google-maps-copyright {+ margin: 0;+ max-width: 100%;+ padding: 2px 5px;+ background: white;+ color: #333;+ font:+ 11px/1.5 Arial,+ sans-serif;+ overflow-wrap: anywhere;+}diff --git a/src/client/navigation/items.ts b/src/client/navigation/items.tsindex d86bccdf..7f89ed72 100644--- a/src/client/navigation/items.ts+++ b/src/client/navigation/items.ts@@ -8,6 +8,7 @@ import {Globe,LayoutDashboard,Link2,+ MapPin,MessageSquare,Search,TrendingUp,@@ -39,6 +40,11 @@ const projectNavItems = [label: "Rank Tracking",icon: TrendingUp,},+ {+ to: "/p/$projectId/local-seo" as const,+ label: "Local SEO",+ icon: MapPin,+ },{to: "/p/$projectId/search-performance" as const,label: "GSC Insights",@@ -145,6 +151,7 @@ export function getProjectNavGroups(projectId: string) {items: [byPath("/p/$projectId/search-performance"),byPath("/p/$projectId/rank-tracking"),+ byPath("/p/$projectId/local-seo"),byPath("/p/$projectId/saved"),byPath("/p/$projectId/audit"),],diff --git a/src/db/d1/schema.ts b/src/db/d1/schema.tsindex df6f1878..87e6199d 100644--- a/src/db/d1/schema.ts+++ b/src/db/d1/schema.ts@@ -13,3 +13,4 @@ export * from "../ga4.schema";export * from "../gsc.schema";export * from "../telemetry.schema";export * from "../ai-visibility.schema";+export * from "../local-seo.schema";diff --git a/src/db/local-seo.schema.ts b/src/db/local-seo.schema.tsnew file mode 100644index 00000000..e8e3d3eb--- /dev/null+++ b/src/db/local-seo.schema.ts@@ -0,0 +1,199 @@+import { sql } from "drizzle-orm";+import {+ index,+ integer,+ real,+ sqliteTable,+ text,+ uniqueIndex,+} from "drizzle-orm/sqlite-core";+import { projects } from "./app.schema";+import { LocalPointStatus, LocalScanStatus } from "@/shared/local-seo";++export const localRankTrackers = sqliteTable(+ "local_rank_trackers",+ {+ id: text("id").primaryKey(),+ projectId: text("project_id")+ .notNull()+ .references(() => projects.id, { onDelete: "cascade" }),+ title: text("title").notNull(),+ address: text("address"),+ cid: text("cid"),+ placeId: text("place_id"),+ latitude: real("latitude").notNull(),+ longitude: real("longitude").notNull(),+ gridSize: integer("grid_size").notNull(),+ spacingKm: real("spacing_km").notNull(),+ languageCode: text("language_code").notNull(),+ createdAt: text("created_at").notNull(),+ },+ (t) => [index("local_rank_trackers_project_idx").on(t.projectId)],+);++export const localRankKeywords = sqliteTable(+ "local_rank_keywords",+ {+ id: text("id").primaryKey(),+ trackerId: text("tracker_id")+ .notNull()+ .references(() => localRankTrackers.id, { onDelete: "cascade" }),+ keyword: text("keyword").notNull(),+ archivedAt: text("archived_at"),+ },+ (t) => [+ uniqueIndex("local_rank_keywords_tracker_keyword_idx").on(+ t.trackerId,+ t.keyword,+ ),+ ],+);++export const localRankChecks = sqliteTable(+ "local_rank_checks",+ {+ id: text("id").primaryKey(),+ projectId: text("project_id")+ .notNull()+ .references(() => projects.id, { onDelete: "cascade" }),+ trackerId: text("tracker_id")+ .notNull()+ .references(() => localRankTrackers.id, { onDelete: "cascade" }),+ status: text("status", {+ enum: [+ LocalScanStatus.Queued,+ LocalScanStatus.Running,+ LocalScanStatus.Completed,+ LocalScanStatus.Partial,+ LocalScanStatus.Failed,+ ],+ }).notNull(),+ error: text("error"),+ createdAt: text("created_at").notNull(),+ completedAt: text("completed_at"),+ },+ (t) => [+ index("local_rank_checks_tracker_created_idx").on(t.trackerId, t.createdAt),+ uniqueIndex("local_rank_checks_one_active_idx")+ .on(t.trackerId)+ .where(sql`${t.status} IN ('queued', 'running')`),+ ],+);++export const localRankScans = sqliteTable(+ "local_rank_scans",+ {+ id: text("id").primaryKey(),+ checkId: text("check_id")+ .notNull()+ .references(() => localRankChecks.id, { onDelete: "cascade" }),+ projectId: text("project_id")+ .notNull()+ .references(() => projects.id, { onDelete: "cascade" }),+ trackerId: text("tracker_id")+ .notNull()+ .references(() => localRankTrackers.id, { onDelete: "cascade" }),+ keywordId: text("keyword_id")+ .notNull()+ .references(() => localRankKeywords.id, { onDelete: "cascade" }),+ status: text("status", {+ enum: [+ LocalScanStatus.Queued,+ LocalScanStatus.Running,+ LocalScanStatus.Completed,+ LocalScanStatus.Partial,+ LocalScanStatus.Failed,+ ],+ }).notNull(),+ error: text("error"),+ createdAt: text("created_at").notNull(),+ completedAt: text("completed_at"),+ },+ (t) => [+ index("local_rank_scans_tracker_created_idx").on(t.trackerId, t.createdAt),+ index("local_rank_scans_project_idx").on(t.projectId),+ uniqueIndex("local_rank_scans_check_keyword_idx").on(+ t.checkId,+ t.keywordId,+ ),+ ],+);++export const localRankPoints = sqliteTable(+ "local_rank_points",+ {+ id: text("id").primaryKey(),+ scanId: text("scan_id")+ .notNull()+ .references(() => localRankScans.id, { onDelete: "cascade" }),+ row: integer("row").notNull(),+ col: integer("col").notNull(),+ latitude: real("latitude").notNull(),+ longitude: real("longitude").notNull(),+ status: text("status", {+ enum: [+ LocalPointStatus.Pending,+ LocalPointStatus.Completed,+ LocalPointStatus.Failed,+ ],+ }).notNull(),+ rank: integer("rank"),+ resultsCount: integer("results_count"),+ error: text("error"),+ collectedAt: text("collected_at"),+ },+ (t) => [+ uniqueIndex("local_rank_points_scan_position_idx").on(+ t.scanId,+ t.row,+ t.col,+ ),+ ],+);++// One business snapshot per scan; point rankings reference it rather than+// duplicating profile data at every coordinate.+export const localRankBusinesses = sqliteTable(+ "local_rank_businesses",+ {+ id: text("id").primaryKey(),+ scanId: text("scan_id")+ .notNull()+ .references(() => localRankScans.id, { onDelete: "cascade" }),+ identity: text("identity").notNull(),+ title: text("title").notNull(),+ cid: text("cid"),+ placeId: text("place_id"),+ address: text("address"),+ rating: real("rating"),+ reviews: integer("reviews"),+ },+ (t) => [+ uniqueIndex("local_rank_businesses_scan_identity_idx").on(+ t.scanId,+ t.identity,+ ),+ ],+);++export const localRankResults = sqliteTable(+ "local_rank_results",+ {+ id: text("id").primaryKey(),+ pointId: text("point_id")+ .notNull()+ .references(() => localRankPoints.id, { onDelete: "cascade" }),+ businessId: text("business_id")+ .notNull()+ .references(() => localRankBusinesses.id, { onDelete: "cascade" }),+ rank: integer("rank").notNull(),+ },+ (t) => [+ uniqueIndex("local_rank_results_point_business_idx").on(+ t.pointId,+ t.businessId,+ ),+ // Deleting a scan's businesses cascades through this column.+ index("local_rank_results_business_idx").on(t.businessId),+ ],+);diff --git a/src/db/pg/local-seo.schema.ts b/src/db/pg/local-seo.schema.tsnew file mode 100644index 00000000..50c5c54d--- /dev/null+++ b/src/db/pg/local-seo.schema.ts@@ -0,0 +1,197 @@+import { sql } from "drizzle-orm";+import {+ doublePrecision,+ index,+ integer,+ pgTable,+ text,+ uniqueIndex,+} from "drizzle-orm/pg-core";+import { projects } from "./app.schema";+import { LocalPointStatus, LocalScanStatus } from "@/shared/local-seo";++export const localRankTrackers = pgTable(+ "local_rank_trackers",+ {+ id: text("id").primaryKey(),+ projectId: text("project_id")+ .notNull()+ .references(() => projects.id, { onDelete: "cascade" }),+ title: text("title").notNull(),+ address: text("address"),+ cid: text("cid"),+ placeId: text("place_id"),+ latitude: doublePrecision("latitude").notNull(),+ longitude: doublePrecision("longitude").notNull(),+ gridSize: integer("grid_size").notNull(),+ spacingKm: doublePrecision("spacing_km").notNull(),+ languageCode: text("language_code").notNull(),+ createdAt: text("created_at").notNull(),+ },+ (t) => [index("local_rank_trackers_project_idx").on(t.projectId)],+);++export const localRankKeywords = pgTable(+ "local_rank_keywords",+ {+ id: text("id").primaryKey(),+ trackerId: text("tracker_id")+ .notNull()+ .references(() => localRankTrackers.id, { onDelete: "cascade" }),+ keyword: text("keyword").notNull(),+ archivedAt: text("archived_at"),+ },+ (t) => [+ uniqueIndex("local_rank_keywords_tracker_keyword_idx").on(+ t.trackerId,+ t.keyword,+ ),+ ],+);++export const localRankChecks = pgTable(+ "local_rank_checks",+ {+ id: text("id").primaryKey(),+ projectId: text("project_id")+ .notNull()+ .references(() => projects.id, { onDelete: "cascade" }),+ trackerId: text("tracker_id")+ .notNull()+ .references(() => localRankTrackers.id, { onDelete: "cascade" }),+ status: text("status", {+ enum: [+ LocalScanStatus.Queued,+ LocalScanStatus.Running,+ LocalScanStatus.Completed,+ LocalScanStatus.Partial,+ LocalScanStatus.Failed,+ ],+ }).notNull(),+ error: text("error"),+ createdAt: text("created_at").notNull(),+ completedAt: text("completed_at"),+ },+ (t) => [+ index("local_rank_checks_tracker_created_idx").on(t.trackerId, t.createdAt),+ uniqueIndex("local_rank_checks_one_active_idx")+ .on(t.trackerId)+ .where(sql`${t.status} IN ('queued', 'running')`),+ ],+);++export const localRankScans = pgTable(+ "local_rank_scans",+ {+ id: text("id").primaryKey(),+ checkId: text("check_id")+ .notNull()+ .references(() => localRankChecks.id, { onDelete: "cascade" }),+ projectId: text("project_id")+ .notNull()+ .references(() => projects.id, { onDelete: "cascade" }),+ trackerId: text("tracker_id")+ .notNull()+ .references(() => localRankTrackers.id, { onDelete: "cascade" }),+ keywordId: text("keyword_id")+ .notNull()+ .references(() => localRankKeywords.id, { onDelete: "cascade" }),+ status: text("status", {+ enum: [+ LocalScanStatus.Queued,+ LocalScanStatus.Running,+ LocalScanStatus.Completed,+ LocalScanStatus.Partial,+ LocalScanStatus.Failed,+ ],+ }).notNull(),+ error: text("error"),+ createdAt: text("created_at").notNull(),+ completedAt: text("completed_at"),+ },+ (t) => [+ index("local_rank_scans_tracker_created_idx").on(t.trackerId, t.createdAt),+ index("local_rank_scans_project_idx").on(t.projectId),+ uniqueIndex("local_rank_scans_check_keyword_idx").on(+ t.checkId,+ t.keywordId,+ ),+ ],+);++export const localRankPoints = pgTable(+ "local_rank_points",+ {+ id: text("id").primaryKey(),+ scanId: text("scan_id")+ .notNull()+ .references(() => localRankScans.id, { onDelete: "cascade" }),+ row: integer("row").notNull(),+ col: integer("col").notNull(),+ latitude: doublePrecision("latitude").notNull(),+ longitude: doublePrecision("longitude").notNull(),+ status: text("status", {+ enum: [+ LocalPointStatus.Pending,+ LocalPointStatus.Completed,+ LocalPointStatus.Failed,+ ],+ }).notNull(),+ rank: integer("rank"),+ resultsCount: integer("results_count"),+ error: text("error"),+ collectedAt: text("collected_at"),+ },+ (t) => [+ uniqueIndex("local_rank_points_scan_position_idx").on(+ t.scanId,+ t.row,+ t.col,+ ),+ ],+);++export const localRankBusinesses = pgTable(+ "local_rank_businesses",+ {+ id: text("id").primaryKey(),+ scanId: text("scan_id")+ .notNull()+ .references(() => localRankScans.id, { onDelete: "cascade" }),+ identity: text("identity").notNull(),+ title: text("title").notNull(),+ cid: text("cid"),+ placeId: text("place_id"),+ address: text("address"),+ rating: doublePrecision("rating"),+ reviews: integer("reviews"),+ },+ (t) => [+ uniqueIndex("local_rank_businesses_scan_identity_idx").on(+ t.scanId,+ t.identity,+ ),+ ],+);++export const localRankResults = pgTable(+ "local_rank_results",+ {+ id: text("id").primaryKey(),+ pointId: text("point_id")+ .notNull()+ .references(() => localRankPoints.id, { onDelete: "cascade" }),+ businessId: text("business_id")+ .notNull()+ .references(() => localRankBusinesses.id, { onDelete: "cascade" }),+ rank: integer("rank").notNull(),+ },+ (t) => [+ uniqueIndex("local_rank_results_point_business_idx").on(+ t.pointId,+ t.businessId,+ ),+ // Deleting a scan's businesses cascades through this column.+ index("local_rank_results_business_idx").on(t.businessId),+ ],+);diff --git a/src/db/pg/schema.ts b/src/db/pg/schema.tsindex 92954848..14b503af 100644--- a/src/db/pg/schema.ts+++ b/src/db/pg/schema.ts@@ -10,3 +10,4 @@ export * from "./ga4.schema";export * from "./gsc.schema";export * from "./telemetry.schema";export * from "./ai-visibility.schema";+export * from "./local-seo.schema";diff --git a/src/db/schema-parity.test.ts b/src/db/schema-parity.test.tsindex 95f9a2fd..a6b46ab4 100644--- a/src/db/schema-parity.test.ts+++ b/src/db/schema-parity.test.ts@@ -17,6 +17,7 @@ import * as sqliteGa4 from "./ga4.schema";import * as sqliteGsc from "./gsc.schema";import * as sqliteTelemetry from "./telemetry.schema";import * as sqliteAiVisibility from "./ai-visibility.schema";+import * as sqliteLocalSeo from "./local-seo.schema";import * as pgApp from "./pg/app.schema";import * as pgProjectContext from "./pg/project-context.schema";import * as pgReports from "./pg/reports.schema";@@ -29,6 +30,7 @@ import * as pgGa4 from "./pg/ga4.schema";import * as pgGsc from "./pg/gsc.schema";import * as pgTelemetry from "./pg/telemetry.schema";import * as pgAiVisibility from "./pg/ai-visibility.schema";+import * as pgLocalSeo from "./pg/local-seo.schema";// Guards the ONE structural artifact `db:generate` does not regenerate: the// hand-written Postgres schema. The provider-aware `db`/`@/db/schema` barrel@@ -162,6 +164,7 @@ const sqliteAppTables = tablesFrom(sqliteGsc,sqliteTelemetry,sqliteAiVisibility,+ sqliteLocalSeo,);const pgAppTables = tablesFrom(pgApp,@@ -175,6 +178,7 @@ const pgAppTables = tablesFrom(pgGsc,pgTelemetry,pgAiVisibility,+ pgLocalSeo,);const sqliteAuthTables = tablesFrom(sqliteAuth);const pgAuthTables = tablesFrom(pgAuth);diff --git a/src/db/schema.ts b/src/db/schema.tsindex f95a9d6d..ff926070 100644--- a/src/db/schema.ts+++ b/src/db/schema.ts@@ -11,6 +11,7 @@ import * as sqliteGa4 from "./ga4.schema";import * as sqliteGsc from "./gsc.schema";import * as sqliteTelemetry from "./telemetry.schema";import * as sqliteAiVisibility from "./ai-visibility.schema";+import * as sqliteLocalSeo from "./local-seo.schema";import * as pgApp from "./pg/app.schema";import * as pgProjectContext from "./pg/project-context.schema";import * as pgReports from "./pg/reports.schema";@@ -23,6 +24,7 @@ import * as pgGa4 from "./pg/ga4.schema";import * as pgGsc from "./pg/gsc.schema";import * as pgTelemetry from "./pg/telemetry.schema";import * as pgAiVisibility from "./pg/ai-visibility.schema";+import * as pgLocalSeo from "./pg/local-seo.schema";// Canonical schema barrel. Repositories import their tables from here and the// provider-aware `db` from "@/db", so each repository is written ONCE for both@@ -45,7 +47,8 @@ type AppSchema = typeof sqliteApp &typeof sqliteGa4 &typeof sqliteGsc &typeof sqliteTelemetry &- typeof sqliteAiVisibility;+ typeof sqliteAiVisibility &+ typeof sqliteLocalSeo;const runtimeSchema =getDatabaseProvider() === "postgres"@@ -62,6 +65,7 @@ const runtimeSchema =...pgGsc,...pgTelemetry,...pgAiVisibility,+ ...pgLocalSeo,}: {...sqliteApp,@@ -76,6 +80,7 @@ const runtimeSchema =...sqliteGsc,...sqliteTelemetry,...sqliteAiVisibility,+ ...sqliteLocalSeo,};// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- guarded by schema-parity.test.ts@@ -127,4 +132,11 @@ export const {aiObservations,aiSources,aiMatches,+ localRankTrackers,+ localRankChecks,+ localRankKeywords,+ localRankScans,+ localRankPoints,+ localRankBusinesses,+ localRankResults,} = schema;diff --git a/src/env.d.ts b/src/env.d.tsindex 05607da8..7eded92f 100644--- a/src/env.d.ts+++ b/src/env.d.ts@@ -45,6 +45,7 @@ declare namespace Cloudflare {};GOOGLE_CLIENT_ID?: string;GOOGLE_CLIENT_SECRET?: string;+ GOOGLE_MAPS_API_KEY?: string;LOOPS_API_KEY?: string;LOOPS_TRANSACTIONAL_VERIFY_EMAIL_ID?: string;LOOPS_TRANSACTIONAL_RESET_PASSWORD_ID?: string;@@ -71,6 +72,12 @@ declare namespace Cloudflare {// DataForSEO API Basic auth value (base64 of login:password)DATAFORSEO_API_KEY: string;+ LOCAL_RANK_WORKFLOW: Workflow<+ Parameters<+ // oxlint-disable-next-line typescript-eslint/consistent-type-imports -- preserve ambient Env augmentation+ import("./server").LocalRankWorkflow["run"]+ >[0]["payload"]+ >;AI_VISIBILITY_WORKFLOW: Workflow<(| { runId: string }diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.tsindex 3ba67832..5cc3e0ed 100644--- a/src/routeTree.gen.ts+++ b/src/routeTree.gen.ts@@ -51,6 +51,7 @@ import { Route as AppPProjectIdBrandLookupRouteImport } from './routes/_app/p/$pimport { Route as AppPProjectIdContextRouteImport } from './routes/_app/p/$projectId/context'import { Route as AppPProjectIdDomainRouteImport } from './routes/_app/p/$projectId/domain'import { Route as AppPProjectIdKeywordsRouteImport } from './routes/_app/p/$projectId/keywords'+import { Route as AppPProjectIdLocalSeoRouteImport } from './routes/_app/p/$projectId/local-seo'import { Route as AppPProjectIdPromptExplorerRouteImport } from './routes/_app/p/$projectId/prompt-explorer'import { Route as AppPProjectIdRankTrackingRouteImport } from './routes/_app/p/$projectId/rank-tracking'import { Route as AppPProjectIdSamRouteImport } from './routes/_app/p/$projectId/sam'@@ -62,6 +63,8 @@ import { Route as ApiGscOauthCallbackRouteImport } from './routes/api/gsc/oauth/import { Route as AppPProjectIdAiVisibilityIndexRouteImport } from './routes/_app/p/$projectId/ai-visibility/index'import { Route as AppPProjectIdAiVisibilityResearchRouteImport } from './routes/_app/p/$projectId/ai-visibility/research'import { Route as AppPProjectIdAuditIndexRouteImport } from './routes/_app/p/$projectId/audit/index'+import { Route as AppPProjectIdLocalSeoIndexRouteImport } from './routes/_app/p/$projectId/local-seo/index'+import { Route as AppPProjectIdLocalSeoTrackerIdRouteImport } from './routes/_app/p/$projectId/local-seo/$trackerId'import { Route as AppPProjectIdRankTrackingIndexRouteImport } from './routes/_app/p/$projectId/rank-tracking/index'import { Route as AppPProjectIdRankTrackingConfigIdRouteImport } from './routes/_app/p/$projectId/rank-tracking/$configId'import { Route as AppPProjectIdReportsIndexRouteImport } from './routes/_app/p/$projectId/reports/index'@@ -72,6 +75,7 @@ import { Route as AppPProjectIdSettingsContextRouteImport } from './routes/_app/import { Route as AppPProjectIdSettingsIntegrationsRouteImport } from './routes/_app/p/$projectId/settings/integrations'import { Route as AppPProjectIdAiVisibilityPromptsPromptIdRouteImport } from './routes/_app/p/$projectId/ai-visibility/prompts/$promptId'import { Route as AppPProjectIdAuditIssuesResultIdRouteImport } from './routes/_app/p/$projectId/audit/issues/$resultId'+import { Route as ApiLocalSeoMapsProjectIdZXYRouteImport } from './routes/api/local-seo/maps/$projectId/$z/$x/$y'const AppRouteRoute = AppRouteRouteImport.update({id: '/_app',@@ -285,6 +289,11 @@ const AppPProjectIdKeywordsRoute = AppPProjectIdKeywordsRouteImport.update({path: '/keywords',getParentRoute: () => AppPProjectIdRouteRoute,} as any)+const AppPProjectIdLocalSeoRoute = AppPProjectIdLocalSeoRouteImport.update({+ id: '/local-seo',+ path: '/local-seo',+ getParentRoute: () => AppPProjectIdRouteRoute,+} as any)const AppPProjectIdPromptExplorerRoute =AppPProjectIdPromptExplorerRouteImport.update({id: '/prompt-explorer',@@ -345,6 +354,18 @@ const AppPProjectIdAuditIndexRoute = AppPProjectIdAuditIndexRouteImport.update({path: '/audit/',getParentRoute: () => AppPProjectIdRouteRoute,} as any)+const AppPProjectIdLocalSeoIndexRoute =+ AppPProjectIdLocalSeoIndexRouteImport.update({+ id: '/',+ path: '/',+ getParentRoute: () => AppPProjectIdLocalSeoRoute,+ } as any)+const AppPProjectIdLocalSeoTrackerIdRoute =+ AppPProjectIdLocalSeoTrackerIdRouteImport.update({+ id: '/$trackerId',+ path: '/$trackerId',+ getParentRoute: () => AppPProjectIdLocalSeoRoute,+ } as any)const AppPProjectIdRankTrackingIndexRoute =AppPProjectIdRankTrackingIndexRouteImport.update({id: '/',@@ -405,6 +426,12 @@ const AppPProjectIdAuditIssuesResultIdRoute =path: '/audit/issues/$resultId',getParentRoute: () => AppPProjectIdRouteRoute,} as any)+const ApiLocalSeoMapsProjectIdZXYRoute =+ ApiLocalSeoMapsProjectIdZXYRouteImport.update({+ id: '/api/local-seo/maps/$projectId/$z/$x/$y',+ path: '/api/local-seo/maps/$projectId/$z/$x/$y',+ getParentRoute: () => rootRouteImport,+ } as any)export interface FileRoutesByFullPath {'/': typeof AppIndexRoute@@ -445,6 +472,7 @@ export interface FileRoutesByFullPath {'/p/$projectId/context': typeof AppPProjectIdContextRoute'/p/$projectId/domain': typeof AppPProjectIdDomainRoute'/p/$projectId/keywords': typeof AppPProjectIdKeywordsRoute+ '/p/$projectId/local-seo': typeof AppPProjectIdLocalSeoRouteWithChildren'/p/$projectId/prompt-explorer': typeof AppPProjectIdPromptExplorerRoute'/p/$projectId/rank-tracking': typeof AppPProjectIdRankTrackingRouteWithChildren'/p/$projectId/sam': typeof AppPProjectIdSamRoute@@ -455,6 +483,7 @@ export interface FileRoutesByFullPath {'/api/gsc/oauth/callback': typeof ApiGscOauthCallbackRoute'/p/$projectId/': typeof AppPProjectIdIndexRoute'/p/$projectId/ai-visibility/research': typeof AppPProjectIdAiVisibilityResearchRoute+ '/p/$projectId/local-seo/$trackerId': typeof AppPProjectIdLocalSeoTrackerIdRoute'/p/$projectId/rank-tracking/$configId': typeof AppPProjectIdRankTrackingConfigIdRoute'/p/$projectId/reports/$reportId': typeof AppPProjectIdReportsReportIdRoute'/p/$projectId/reports/templates': typeof AppPProjectIdReportsTemplatesRoute@@ -462,11 +491,13 @@ export interface FileRoutesByFullPath {'/p/$projectId/settings/integrations': typeof AppPProjectIdSettingsIntegrationsRoute'/p/$projectId/ai-visibility/': typeof AppPProjectIdAiVisibilityIndexRoute'/p/$projectId/audit/': typeof AppPProjectIdAuditIndexRoute+ '/p/$projectId/local-seo/': typeof AppPProjectIdLocalSeoIndexRoute'/p/$projectId/rank-tracking/': typeof AppPProjectIdRankTrackingIndexRoute'/p/$projectId/reports/': typeof AppPProjectIdReportsIndexRoute'/p/$projectId/settings/': typeof AppPProjectIdSettingsIndexRoute'/p/$projectId/ai-visibility/prompts/$promptId': typeof AppPProjectIdAiVisibilityPromptsPromptIdRoute'/p/$projectId/audit/issues/$resultId': typeof AppPProjectIdAuditIssuesResultIdRoute+ '/api/local-seo/maps/$projectId/$z/$x/$y': typeof ApiLocalSeoMapsProjectIdZXYRoute}export interface FileRoutesByTo {'/': typeof AppIndexRoute@@ -512,6 +543,7 @@ export interface FileRoutesByTo {'/api/gsc/oauth/callback': typeof ApiGscOauthCallbackRoute'/p/$projectId': typeof AppPProjectIdIndexRoute'/p/$projectId/ai-visibility/research': typeof AppPProjectIdAiVisibilityResearchRoute+ '/p/$projectId/local-seo/$trackerId': typeof AppPProjectIdLocalSeoTrackerIdRoute'/p/$projectId/rank-tracking/$configId': typeof AppPProjectIdRankTrackingConfigIdRoute'/p/$projectId/reports/$reportId': typeof AppPProjectIdReportsReportIdRoute'/p/$projectId/reports/templates': typeof AppPProjectIdReportsTemplatesRoute@@ -519,11 +551,13 @@ export interface FileRoutesByTo {'/p/$projectId/settings/integrations': typeof AppPProjectIdSettingsIntegrationsRoute'/p/$projectId/ai-visibility': typeof AppPProjectIdAiVisibilityIndexRoute'/p/$projectId/audit': typeof AppPProjectIdAuditIndexRoute+ '/p/$projectId/local-seo': typeof AppPProjectIdLocalSeoIndexRoute'/p/$projectId/rank-tracking': typeof AppPProjectIdRankTrackingIndexRoute'/p/$projectId/reports': typeof AppPProjectIdReportsIndexRoute'/p/$projectId/settings': typeof AppPProjectIdSettingsIndexRoute'/p/$projectId/ai-visibility/prompts/$promptId': typeof AppPProjectIdAiVisibilityPromptsPromptIdRoute'/p/$projectId/audit/issues/$resultId': typeof AppPProjectIdAuditIssuesResultIdRoute+ '/api/local-seo/maps/$projectId/$z/$x/$y': typeof ApiLocalSeoMapsProjectIdZXYRoute}export interface FileRoutesById {__root__: typeof rootRouteImport@@ -568,6 +602,7 @@ export interface FileRoutesById {'/_app/p/$projectId/context': typeof AppPProjectIdContextRoute'/_app/p/$projectId/domain': typeof AppPProjectIdDomainRoute'/_app/p/$projectId/keywords': typeof AppPProjectIdKeywordsRoute+ '/_app/p/$projectId/local-seo': typeof AppPProjectIdLocalSeoRouteWithChildren'/_app/p/$projectId/prompt-explorer': typeof AppPProjectIdPromptExplorerRoute'/_app/p/$projectId/rank-tracking': typeof AppPProjectIdRankTrackingRouteWithChildren'/_app/p/$projectId/sam': typeof AppPProjectIdSamRoute@@ -578,6 +613,7 @@ export interface FileRoutesById {'/api/gsc/oauth/callback': typeof ApiGscOauthCallbackRoute'/_app/p/$projectId/': typeof AppPProjectIdIndexRoute'/_app/p/$projectId/ai-visibility/research': typeof AppPProjectIdAiVisibilityResearchRoute+ '/_app/p/$projectId/local-seo/$trackerId': typeof AppPProjectIdLocalSeoTrackerIdRoute'/_app/p/$projectId/rank-tracking/$configId': typeof AppPProjectIdRankTrackingConfigIdRoute'/_app/p/$projectId/reports/$reportId': typeof AppPProjectIdReportsReportIdRoute'/_app/p/$projectId/reports/templates': typeof AppPProjectIdReportsTemplatesRoute@@ -585,11 +621,13 @@ export interface FileRoutesById {'/_app/p/$projectId/settings/integrations': typeof AppPProjectIdSettingsIntegrationsRoute'/_app/p/$projectId/ai-visibility/': typeof AppPProjectIdAiVisibilityIndexRoute'/_app/p/$projectId/audit/': typeof AppPProjectIdAuditIndexRoute+ '/_app/p/$projectId/local-seo/': typeof AppPProjectIdLocalSeoIndexRoute'/_app/p/$projectId/rank-tracking/': typeof AppPProjectIdRankTrackingIndexRoute'/_app/p/$projectId/reports/': typeof AppPProjectIdReportsIndexRoute'/_app/p/$projectId/settings/': typeof AppPProjectIdSettingsIndexRoute'/_app/p/$projectId/ai-visibility/prompts/$promptId': typeof AppPProjectIdAiVisibilityPromptsPromptIdRoute'/_app/p/$projectId/audit/issues/$resultId': typeof AppPProjectIdAuditIssuesResultIdRoute+ '/api/local-seo/maps/$projectId/$z/$x/$y': typeof ApiLocalSeoMapsProjectIdZXYRoute}export interface FileRouteTypes {fileRoutesByFullPath: FileRoutesByFullPath@@ -632,6 +670,7 @@ export interface FileRouteTypes {| '/p/$projectId/context'| '/p/$projectId/domain'| '/p/$projectId/keywords'+ | '/p/$projectId/local-seo'| '/p/$projectId/prompt-explorer'| '/p/$projectId/rank-tracking'| '/p/$projectId/sam'@@ -642,6 +681,7 @@ export interface FileRouteTypes {| '/api/gsc/oauth/callback'| '/p/$projectId/'| '/p/$projectId/ai-visibility/research'+ | '/p/$projectId/local-seo/$trackerId'| '/p/$projectId/rank-tracking/$configId'| '/p/$projectId/reports/$reportId'| '/p/$projectId/reports/templates'@@ -649,11 +689,13 @@ export interface FileRouteTypes {| '/p/$projectId/settings/integrations'| '/p/$projectId/ai-visibility/'| '/p/$projectId/audit/'+ | '/p/$projectId/local-seo/'| '/p/$projectId/rank-tracking/'| '/p/$projectId/reports/'| '/p/$projectId/settings/'| '/p/$projectId/ai-visibility/prompts/$promptId'| '/p/$projectId/audit/issues/$resultId'+ | '/api/local-seo/maps/$projectId/$z/$x/$y'fileRoutesByTo: FileRoutesByToto:| '/'@@ -699,6 +741,7 @@ export interface FileRouteTypes {| '/api/gsc/oauth/callback'| '/p/$projectId'| '/p/$projectId/ai-visibility/research'+ | '/p/$projectId/local-seo/$trackerId'| '/p/$projectId/rank-tracking/$configId'| '/p/$projectId/reports/$reportId'| '/p/$projectId/reports/templates'@@ -706,11 +749,13 @@ export interface FileRouteTypes {| '/p/$projectId/settings/integrations'| '/p/$projectId/ai-visibility'| '/p/$projectId/audit'+ | '/p/$projectId/local-seo'| '/p/$projectId/rank-tracking'| '/p/$projectId/reports'| '/p/$projectId/settings'| '/p/$projectId/ai-visibility/prompts/$promptId'| '/p/$projectId/audit/issues/$resultId'+ | '/api/local-seo/maps/$projectId/$z/$x/$y'id:| '__root__'| '/_app'@@ -754,6 +799,7 @@ export interface FileRouteTypes {| '/_app/p/$projectId/context'| '/_app/p/$projectId/domain'| '/_app/p/$projectId/keywords'+ | '/_app/p/$projectId/local-seo'| '/_app/p/$projectId/prompt-explorer'| '/_app/p/$projectId/rank-tracking'| '/_app/p/$projectId/sam'@@ -764,6 +810,7 @@ export interface FileRouteTypes {| '/api/gsc/oauth/callback'| '/_app/p/$projectId/'| '/_app/p/$projectId/ai-visibility/research'+ | '/_app/p/$projectId/local-seo/$trackerId'| '/_app/p/$projectId/rank-tracking/$configId'| '/_app/p/$projectId/reports/$reportId'| '/_app/p/$projectId/reports/templates'@@ -771,11 +818,13 @@ export interface FileRouteTypes {| '/_app/p/$projectId/settings/integrations'| '/_app/p/$projectId/ai-visibility/'| '/_app/p/$projectId/audit/'+ | '/_app/p/$projectId/local-seo/'| '/_app/p/$projectId/rank-tracking/'| '/_app/p/$projectId/reports/'| '/_app/p/$projectId/settings/'| '/_app/p/$projectId/ai-visibility/prompts/$promptId'| '/_app/p/$projectId/audit/issues/$resultId'+ | '/api/local-seo/maps/$projectId/$z/$x/$y'fileRoutesById: FileRoutesById}export interface RootRouteChildren {@@ -798,6 +847,7 @@ export interface RootRouteChildren {STokenIndexRoute: typeof STokenIndexRouteApiGa4OauthCallbackRoute: typeof ApiGa4OauthCallbackRouteApiGscOauthCallbackRoute: typeof ApiGscOauthCallbackRoute+ ApiLocalSeoMapsProjectIdZXYRoute: typeof ApiLocalSeoMapsProjectIdZXYRoute}declare module '@tanstack/react-router' {@@ -1096,6 +1146,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AppPProjectIdKeywordsRouteImportparentRoute: typeof AppPProjectIdRouteRoute}+ '/_app/p/$projectId/local-seo': {+ id: '/_app/p/$projectId/local-seo'+ path: '/local-seo'+ fullPath: '/p/$projectId/local-seo'+ preLoaderRoute: typeof AppPProjectIdLocalSeoRouteImport+ parentRoute: typeof AppPProjectIdRouteRoute+ }'/_app/p/$projectId/prompt-explorer': {id: '/_app/p/$projectId/prompt-explorer'path: '/prompt-explorer'@@ -1173,6 +1230,20 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AppPProjectIdAuditIndexRouteImportparentRoute: typeof AppPProjectIdRouteRoute}+ '/_app/p/$projectId/local-seo/': {+ id: '/_app/p/$projectId/local-seo/'+ path: '/'+ fullPath: '/p/$projectId/local-seo/'+ preLoaderRoute: typeof AppPProjectIdLocalSeoIndexRouteImport+ parentRoute: typeof AppPProjectIdLocalSeoRoute+ }+ '/_app/p/$projectId/local-seo/$trackerId': {+ id: '/_app/p/$projectId/local-seo/$trackerId'+ path: '/$trackerId'+ fullPath: '/p/$projectId/local-seo/$trackerId'+ preLoaderRoute: typeof AppPProjectIdLocalSeoTrackerIdRouteImport+ parentRoute: typeof AppPProjectIdLocalSeoRoute+ }'/_app/p/$projectId/rank-tracking/': {id: '/_app/p/$projectId/rank-tracking/'path: '/'@@ -1243,6 +1314,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AppPProjectIdAuditIssuesResultIdRouteImportparentRoute: typeof AppPProjectIdRouteRoute}+ '/api/local-seo/maps/$projectId/$z/$x/$y': {+ id: '/api/local-seo/maps/$projectId/$z/$x/$y'+ path: '/api/local-seo/maps/$projectId/$z/$x/$y'+ fullPath: '/api/local-seo/maps/$projectId/$z/$x/$y'+ preLoaderRoute: typeof ApiLocalSeoMapsProjectIdZXYRouteImport+ parentRoute: typeof rootRouteImport+ }}}@@ -1280,6 +1358,21 @@ const AppPProjectIdAiVisibilityRouteWithChildren =AppPProjectIdAiVisibilityRouteChildren,)+interface AppPProjectIdLocalSeoRouteChildren {+ AppPProjectIdLocalSeoTrackerIdRoute: typeof AppPProjectIdLocalSeoTrackerIdRoute+ AppPProjectIdLocalSeoIndexRoute: typeof AppPProjectIdLocalSeoIndexRoute+}++const AppPProjectIdLocalSeoRouteChildren: AppPProjectIdLocalSeoRouteChildren = {+ AppPProjectIdLocalSeoTrackerIdRoute: AppPProjectIdLocalSeoTrackerIdRoute,+ AppPProjectIdLocalSeoIndexRoute: AppPProjectIdLocalSeoIndexRoute,+}++const AppPProjectIdLocalSeoRouteWithChildren =+ AppPProjectIdLocalSeoRoute._addFileChildren(+ AppPProjectIdLocalSeoRouteChildren,+ )+interface AppPProjectIdRankTrackingRouteChildren {AppPProjectIdRankTrackingConfigIdRoute: typeof AppPProjectIdRankTrackingConfigIdRouteAppPProjectIdRankTrackingIndexRoute: typeof AppPProjectIdRankTrackingIndexRoute@@ -1322,6 +1415,7 @@ interface AppPProjectIdRouteRouteChildren {AppPProjectIdContextRoute: typeof AppPProjectIdContextRouteAppPProjectIdDomainRoute: typeof AppPProjectIdDomainRouteAppPProjectIdKeywordsRoute: typeof AppPProjectIdKeywordsRoute+ AppPProjectIdLocalSeoRoute: typeof AppPProjectIdLocalSeoRouteWithChildrenAppPProjectIdPromptExplorerRoute: typeof AppPProjectIdPromptExplorerRouteAppPProjectIdRankTrackingRoute: typeof AppPProjectIdRankTrackingRouteWithChildrenAppPProjectIdSamRoute: typeof AppPProjectIdSamRoute@@ -1343,6 +1437,7 @@ const AppPProjectIdRouteRouteChildren: AppPProjectIdRouteRouteChildren = {AppPProjectIdContextRoute: AppPProjectIdContextRoute,AppPProjectIdDomainRoute: AppPProjectIdDomainRoute,AppPProjectIdKeywordsRoute: AppPProjectIdKeywordsRoute,+ AppPProjectIdLocalSeoRoute: AppPProjectIdLocalSeoRouteWithChildren,AppPProjectIdPromptExplorerRoute: AppPProjectIdPromptExplorerRoute,AppPProjectIdRankTrackingRoute: AppPProjectIdRankTrackingRouteWithChildren,AppPProjectIdSamRoute: AppPProjectIdSamRoute,@@ -1441,6 +1536,7 @@ const rootRouteChildren: RootRouteChildren = {STokenIndexRoute: STokenIndexRoute,ApiGa4OauthCallbackRoute: ApiGa4OauthCallbackRoute,ApiGscOauthCallbackRoute: ApiGscOauthCallbackRoute,+ ApiLocalSeoMapsProjectIdZXYRoute: ApiLocalSeoMapsProjectIdZXYRoute,}export const routeTree = rootRouteImport._addFileChildren(rootRouteChildren)diff --git a/src/routes/_app/p/$projectId/local-seo.tsx b/src/routes/_app/p/$projectId/local-seo.tsxnew file mode 100644index 00000000..3cb6743c--- /dev/null+++ b/src/routes/_app/p/$projectId/local-seo.tsx@@ -0,0 +1,35 @@+import { createFileRoute, Outlet, useParams } from "@tanstack/react-router";+import { BackLink, PageHeader } from "@/client/components/PageHeader";+import leafletCss from "leaflet/dist/leaflet.css?url";+import localRankMapCss from "@/client/features/local-seo/local-rank-map.css?url";++export const Route = createFileRoute("/_app/p/$projectId/local-seo")({+ head: () => ({+ links: [+ { rel: "stylesheet", href: leafletCss },+ { rel: "stylesheet", href: localRankMapCss },+ ],+ }),+ component: LocalSeoLayout,+});+function LocalSeoLayout() {+ const { projectId, trackerId } = useParams({ strict: false });+ return (+ <div className="px-4 py-4 pb-24 overflow-auto md:px-6 md:py-6 md:pb-8">+ <div className="mx-auto max-w-7xl space-y-4">+ <PageHeader+ title="Local SEO"+ description="Track Google Maps rankings across your local area"+ backLink={+ projectId && trackerId ? (+ <BackLink to="/p/$projectId/local-seo" params={{ projectId }}>+ Tracked businesses+ </BackLink>+ ) : undefined+ }+ />+ <Outlet />+ </div>+ </div>+ );+}diff --git a/src/routes/_app/p/$projectId/local-seo/$trackerId.tsx b/src/routes/_app/p/$projectId/local-seo/$trackerId.tsxnew file mode 100644index 00000000..d95a089c--- /dev/null+++ b/src/routes/_app/p/$projectId/local-seo/$trackerId.tsx@@ -0,0 +1,23 @@+import { createFileRoute, useNavigate } from "@tanstack/react-router";+import { LocalTrackerDetail } from "@/client/features/local-seo/LocalTrackerDetail";+import { localSeoSearchSchema } from "@/types/schemas/local-seo-search";++export const Route = createFileRoute("/_app/p/$projectId/local-seo/$trackerId")(+ { validateSearch: localSeoSearchSchema, component: LocalSeoDetailRoute },+);+function LocalSeoDetailRoute() {+ const { projectId, trackerId } = Route.useParams();+ const search = Route.useSearch();+ const navigate = useNavigate();+ return (+ <LocalTrackerDetail+ key={trackerId}+ projectId={projectId}+ trackerId={trackerId}+ search={search}+ onSearchChange={(next) =>+ void navigate({ from: Route.fullPath, search: next, replace: true })+ }+ />+ );+}diff --git a/src/routes/_app/p/$projectId/local-seo/index.tsx b/src/routes/_app/p/$projectId/local-seo/index.tsxnew file mode 100644index 00000000..9bee2250--- /dev/null+++ b/src/routes/_app/p/$projectId/local-seo/index.tsx@@ -0,0 +1,33 @@+import { useState } from "react";+import { createFileRoute, useNavigate } from "@tanstack/react-router";+import { LocalTrackerList } from "@/client/features/local-seo/LocalTrackerList";+import { LocalTrackerDialog } from "@/client/features/local-seo/LocalTrackerDialog";++export const Route = createFileRoute("/_app/p/$projectId/local-seo/")({+ remountDeps: ({ params }) => params.projectId,+ component: LocalSeoIndex,+});+function LocalSeoIndex() {+ const { projectId } = Route.useParams();+ const navigate = useNavigate();+ const [adding, setAdding] = useState(false);+ return (+ <>+ <LocalTrackerList projectId={projectId} onAdd={() => setAdding(true)} />+ {adding && (+ <LocalTrackerDialog+ projectId={projectId}+ onClose={() => setAdding(false)}+ onCreated={(trackerId) => {+ setAdding(false);+ void navigate({+ to: "/p/$projectId/local-seo/$trackerId",+ params: { projectId, trackerId },+ search: {},+ });+ }}+ />+ )}+ </>+ );+}diff --git a/src/routes/api/local-seo/maps/$projectId/$z/$x/$y.ts b/src/routes/api/local-seo/maps/$projectId/$z/$x/$y.tsnew file mode 100644index 00000000..8548def2--- /dev/null+++ b/src/routes/api/local-seo/maps/$projectId/$z/$x/$y.ts@@ -0,0 +1,51 @@+import { createFileRoute } from "@tanstack/react-router";+import { z } from "zod";+import { resolveUserContextFromHeaders } from "@/middleware/ensure-user/resolve";+import { ProjectRepository } from "@/server/features/projects/repositories/ProjectRepository";+import { GoogleMapsService } from "@/server/features/local-seo/services/GoogleMapsService";+import { AppError } from "@/server/lib/errors";+import { responseForAppError } from "@/server/lib/http-errors";++const tileParamsSchema = z+ .object({+ projectId: z.uuid(),+ z: z.coerce.number().int().min(0).max(22),+ x: z.coerce.number().int().min(0),+ y: z.coerce.number().int().min(0),+ })+ .refine(({ z: zoom, x, y }) => x < 2 ** zoom && y < 2 ** zoom);++export const Route = createFileRoute("/api/local-seo/maps/$projectId/$z/$x/$y")(+ {+ server: {+ handlers: {+ GET: async ({ params, request }) => {+ try {+ if (request.headers.get("Sec-Fetch-Site") === "cross-site")+ throw new AppError("FORBIDDEN");+ const parsed = tileParamsSchema.safeParse(params);+ if (!parsed.success)+ throw new AppError("VALIDATION_ERROR", "Invalid map tile.");+ const tile = parsed.data;+ const context = await resolveUserContextFromHeaders(+ request.headers,+ );+ const project = await ProjectRepository.getProjectForOrganization(+ tile.projectId,+ context.organizationId,+ );+ if (!project) throw new AppError("NOT_FOUND");+ return await GoogleMapsService.getTile(tile.z, tile.x, tile.y);+ } catch (error) {+ const response = responseForAppError(+ error,+ "Google Maps unavailable.",+ );+ response.headers.set("Cache-Control", "private, no-store");+ return response;+ }+ },+ },+ },+ },+);diff --git a/src/server.ts b/src/server.tsindex 82496876..a3615db2 100644--- a/src/server.ts+++ b/src/server.ts@@ -190,6 +190,7 @@ function handleFetch(// (src/audit-worker.ts); this worker reaches them via cross-script bindings.export { RankCheckWorkflow } from "./server/workflows/RankCheckWorkflow";export { AiVisibilityWorkflow } from "./server/workflows/AiVisibilityWorkflow";+export { LocalRankWorkflow } from "./server/workflows/LocalRankWorkflow";// Durable Object class for the SAM in-app agent (Agents SDK).export { SamChatAgent } from "./server/features/sam/SamChatAgent";diff --git a/src/server/features/local-seo/repositories/LocalSeoRepository.ts b/src/server/features/local-seo/repositories/LocalSeoRepository.tsnew file mode 100644index 00000000..b5b7dbe5--- /dev/null+++ b/src/server/features/local-seo/repositories/LocalSeoRepository.ts@@ -0,0 +1,362 @@+import { and, asc, desc, eq, inArray, sql } from "drizzle-orm";+import { db } from "@/db";+import { getKeywords, saveKeywords } from "./localKeywordQueries";+import { runBatch } from "@/db/runBatch";+import {+ localRankBusinesses,+ localRankChecks,+ localRankKeywords,+ localRankPoints,+ localRankResults,+ localRankScans,+ localRankTrackers,+} from "@/db/schema";+import { LocalPointStatus, LocalScanStatus } from "@/shared/local-seo";++export type LocalTrackerRow = typeof localRankTrackers.$inferSelect;+type LocalScanRow = typeof localRankScans.$inferSelect;+export type LocalCheckRow = typeof localRankChecks.$inferSelect;+export type LocalPointRow = typeof localRankPoints.$inferSelect;+type BusinessRow = typeof localRankBusinesses.$inferInsert;++async function listTrackers(projectId: string) {+ return db+ .select()+ .from(localRankTrackers)+ .where(eq(localRankTrackers.projectId, projectId))+ .orderBy(desc(localRankTrackers.createdAt));+}++async function getTracker(projectId: string, trackerId: string) {+ return (+ (+ await db+ .select()+ .from(localRankTrackers)+ .where(+ and(+ eq(localRankTrackers.projectId, projectId),+ eq(localRankTrackers.id, trackerId),+ ),+ )+ .limit(1)+ )[0] ?? null+ );+}++async function createTracker(+ tracker: typeof localRankTrackers.$inferInsert,+ keywords: (typeof localRankKeywords.$inferInsert)[],+) {+ await runBatch((tx) => [+ tx.insert(localRankTrackers).values(tracker),+ ...keywords.map((keyword) => tx.insert(localRankKeywords).values(keyword)),+ ]);+}++async function listChecks(projectId: string, trackerId: string) {+ return db+ .select()+ .from(localRankChecks)+ .where(+ and(+ eq(localRankChecks.projectId, projectId),+ eq(localRankChecks.trackerId, trackerId),+ ),+ )+ .orderBy(desc(localRankChecks.createdAt), desc(localRankChecks.id))+ .limit(14);+}++async function getCheck(projectId: string, checkId: string) {+ return (+ (+ await db+ .select()+ .from(localRankChecks)+ .where(+ and(+ eq(localRankChecks.projectId, projectId),+ eq(localRankChecks.id, checkId),+ ),+ )+ .limit(1)+ )[0] ?? null+ );+}++async function getScansForCheck(projectId: string, checkId: string) {+ return db+ .select()+ .from(localRankScans)+ .where(+ and(+ eq(localRankScans.projectId, projectId),+ eq(localRankScans.checkId, checkId),+ ),+ )+ .orderBy(asc(localRankScans.keywordId));+}++async function listScans(+ projectId: string,+ trackerId: string,+ checkIds: string[],+) {+ if (!checkIds.length) return [];+ return db+ .select()+ .from(localRankScans)+ .where(+ and(+ eq(localRankScans.projectId, projectId),+ eq(localRankScans.trackerId, trackerId),+ inArray(localRankScans.checkId, checkIds),+ ),+ )+ .orderBy(desc(localRankScans.createdAt), desc(localRankScans.id));+}++async function getScanSummaries(+ projectId: string,+ trackerId: string,+ checkIds: string[],+) {+ if (!checkIds.length) return [];+ return db+ .select({+ scanId: localRankScans.id,+ total: sql<number>`count(${localRankPoints.id})`.mapWith(Number),+ completed:+ sql<number>`sum(case when ${localRankPoints.status} = 'completed' then 1 else 0 end)`.mapWith(+ Number,+ ),+ found:+ sql<number>`sum(case when ${localRankPoints.status} = 'completed' and ${localRankPoints.rank} is not null then 1 else 0 end)`.mapWith(+ Number,+ ),+ top3: sql<number>`sum(case when ${localRankPoints.status} = 'completed' and ${localRankPoints.rank} <= 3 then 1 else 0 end)`.mapWith(+ Number,+ ),+ rankTotal:+ sql<number>`sum(case when ${localRankPoints.status} = 'completed' then coalesce(${localRankPoints.rank}, 0) else 0 end)`.mapWith(+ Number,+ ),+ })+ .from(localRankScans)+ .leftJoin(localRankPoints, eq(localRankPoints.scanId, localRankScans.id))+ .where(+ and(+ eq(localRankScans.projectId, projectId),+ eq(localRankScans.trackerId, trackerId),+ inArray(localRankScans.checkId, checkIds),+ ),+ )+ .groupBy(localRankScans.id);+}++async function getScan(projectId: string, scanId: string) {+ return (+ (+ await db+ .select()+ .from(localRankScans)+ .where(+ and(+ eq(localRankScans.projectId, projectId),+ eq(localRankScans.id, scanId),+ ),+ )+ .limit(1)+ )[0] ?? null+ );+}++async function getActiveCheck(projectId: string, trackerId: string) {+ return (+ (+ await db+ .select()+ .from(localRankChecks)+ .where(+ and(+ eq(localRankChecks.projectId, projectId),+ eq(localRankChecks.trackerId, trackerId),+ inArray(localRankChecks.status, [+ LocalScanStatus.Queued,+ LocalScanStatus.Running,+ ]),+ ),+ )+ .limit(1)+ )[0] ?? null+ );+}++async function createCheck(+ check: typeof localRankChecks.$inferInsert,+ scans: (typeof localRankScans.$inferInsert)[],+ points: (typeof localRankPoints.$inferInsert)[],+) {+ await runBatch((tx) => [+ tx.insert(localRankChecks).values(check),+ ...scans.map((scan) => tx.insert(localRankScans).values(scan)),+ ...points.map((point) => tx.insert(localRankPoints).values(point)),+ ]);+}++async function updateCheck(+ projectId: string,+ checkId: string,+ updates: Partial<Pick<LocalCheckRow, "status" | "error" | "completedAt">>,+) {+ await db+ .update(localRankChecks)+ .set(updates)+ .where(+ and(+ eq(localRankChecks.projectId, projectId),+ eq(localRankChecks.id, checkId),+ inArray(localRankChecks.status, [+ LocalScanStatus.Queued,+ LocalScanStatus.Running,+ ]),+ ),+ );+}++async function updateScan(+ projectId: string,+ scanId: string,+ updates: Partial<Pick<LocalScanRow, "status" | "error" | "completedAt">>,+) {+ await db+ .update(localRankScans)+ .set(updates)+ .where(+ and(+ eq(localRankScans.projectId, projectId),+ eq(localRankScans.id, scanId),+ inArray(localRankScans.status, [+ LocalScanStatus.Queued,+ LocalScanStatus.Running,+ ]),+ ),+ );+}++async function getPoints(scanId: string) {+ return db+ .select()+ .from(localRankPoints)+ .where(eq(localRankPoints.scanId, scanId))+ .orderBy(asc(localRankPoints.row), asc(localRankPoints.col));+}++async function savePoint(+ point: LocalPointRow,+ businesses: BusinessRow[],+ rankings: { businessId: string; rank: number }[],+ rank: number | null,+ resultsCount: number,+) {+ await runBatch((tx) => [+ ...businesses.map((business) =>+ tx.insert(localRankBusinesses).values(business).onConflictDoNothing(),+ ),+ ...rankings.map((result) =>+ tx+ .insert(localRankResults)+ .values({ id: crypto.randomUUID(), pointId: point.id, ...result }),+ ),+ tx+ .update(localRankPoints)+ .set({+ status: LocalPointStatus.Completed,+ rank,+ resultsCount,+ error: null,+ collectedAt: new Date().toISOString(),+ })+ .where(eq(localRankPoints.id, point.id)),+ ]);+}++async function failPoint(pointId: string, error: string) {+ await db+ .update(localRankPoints)+ .set({ status: LocalPointStatus.Failed, error })+ .where(+ and(+ eq(localRankPoints.id, pointId),+ eq(localRankPoints.status, LocalPointStatus.Pending),+ ),+ );+}++async function failPendingPoints(scanId: string, error: string) {+ await db+ .update(localRankPoints)+ .set({ status: LocalPointStatus.Failed, error })+ .where(+ and(+ eq(localRankPoints.scanId, scanId),+ eq(localRankPoints.status, LocalPointStatus.Pending),+ ),+ );+}++async function getScanResults(projectId: string, scanId: string) {+ return db+ .select({+ pointId: localRankResults.pointId,+ id: localRankBusinesses.id,+ title: localRankBusinesses.title,+ cid: localRankBusinesses.cid,+ placeId: localRankBusinesses.placeId,+ address: localRankBusinesses.address,+ rating: localRankBusinesses.rating,+ reviews: localRankBusinesses.reviews,+ rank: localRankResults.rank,+ })+ .from(localRankResults)+ .innerJoin(+ localRankPoints,+ eq(localRankPoints.id, localRankResults.pointId),+ )+ .innerJoin(localRankScans, eq(localRankScans.id, localRankPoints.scanId))+ .innerJoin(+ localRankBusinesses,+ eq(localRankBusinesses.id, localRankResults.businessId),+ )+ .where(+ and(+ eq(localRankScans.projectId, projectId),+ eq(localRankScans.id, scanId),+ ),+ )+ .orderBy(asc(localRankResults.rank));+}++export const LocalSeoRepository = {+ listTrackers,+ getTracker,+ createTracker,+ getKeywords,+ saveKeywords,+ listChecks,+ getCheck,+ getScansForCheck,+ getScanSummaries,+ listScans,+ getScan,+ getActiveCheck,+ createCheck,+ updateCheck,+ updateScan,+ getPoints,+ savePoint,+ failPoint,+ failPendingPoints,+ getScanResults,+};diff --git a/src/server/features/local-seo/repositories/localKeywordQueries.ts b/src/server/features/local-seo/repositories/localKeywordQueries.tsnew file mode 100644index 00000000..5daa66b1--- /dev/null+++ b/src/server/features/local-seo/repositories/localKeywordQueries.ts@@ -0,0 +1,48 @@+import { and, asc, eq, inArray, isNull } from "drizzle-orm";+import { db } from "@/db";+import { runBatch } from "@/db/runBatch";+import { localRankKeywords } from "@/db/schema";++export async function getKeywords(trackerId: string, includeArchived = false) {+ return db+ .select()+ .from(localRankKeywords)+ .where(+ and(+ eq(localRankKeywords.trackerId, trackerId),+ includeArchived ? undefined : isNull(localRankKeywords.archivedAt),+ ),+ )+ .orderBy(asc(localRankKeywords.keyword));+}++export async function saveKeywords(+ trackerId: string,+ keywords: (typeof localRankKeywords.$inferInsert)[],+ removedIds: string[],+) {+ await runBatch((tx) => [+ ...keywords.map((keyword) =>+ tx+ .insert(localRankKeywords)+ .values(keyword)+ .onConflictDoUpdate({+ target: [localRankKeywords.trackerId, localRankKeywords.keyword],+ set: { archivedAt: null },+ }),+ ),+ ...(removedIds.length+ ? [+ tx+ .update(localRankKeywords)+ .set({ archivedAt: new Date().toISOString() })+ .where(+ and(+ eq(localRankKeywords.trackerId, trackerId),+ inArray(localRankKeywords.id, removedIds),+ ),+ ),+ ]+ : []),+ ]);+}diff --git a/src/server/features/local-seo/services/GoogleMapsService.ts b/src/server/features/local-seo/services/GoogleMapsService.tsnew file mode 100644index 00000000..d56185f4--- /dev/null+++ b/src/server/features/local-seo/services/GoogleMapsService.ts@@ -0,0 +1,118 @@+import { z } from "zod";+import { AppError } from "@/server/lib/errors";+import { getOptionalEnvValue } from "@/server/lib/runtime-env";+import type { GoogleMapsViewport } from "@/types/schemas/google-maps";++const sessionSchema = z.object({+ session: z.string().min(1),+ expiry: z.string().regex(/^\d+$/).transform(Number),+ tileWidth: z.number().int().positive(),+ tileHeight: z.number().int().positive(),+});+type MapSession = z.infer<typeof sessionSchema>;+const SESSION_REFRESH_MARGIN_MS = 60_000;++// Session tokens are reusable. Keep them on the server and renew before expiry.+let cachedSession: MapSession | null = null;++async function googleRequest(path: string, init: RequestInit = {}) {+ const apiKey = (await getOptionalEnvValue("GOOGLE_MAPS_API_KEY"))?.trim();+ if (!apiKey)+ throw new AppError(+ "UPSTREAM_UNAVAILABLE",+ "Google Maps is not configured.",+ );+ const url = new URL(path, "https://tile.googleapis.com");+ url.searchParams.set("key", apiKey);+ // Never forward browser credentials or Google's error bodies/URLs to clients.+ return fetch(url, {+ ...init,+ redirect: "manual",+ signal: AbortSignal.timeout(10_000),+ });+}++async function googleJson(path: string, init?: RequestInit) {+ const response = await googleRequest(path, init);+ if (!response.ok) {+ await response.body?.cancel();+ throw new AppError(+ "UPSTREAM_UNAVAILABLE",+ `Google Maps request failed (${response.status}).`,+ );+ }+ return response.json();+}++async function getSession() {+ if (+ cachedSession &&+ cachedSession.expiry * 1000 > Date.now() + SESSION_REFRESH_MARGIN_MS+ ) {+ return cachedSession;+ }+ const session = sessionSchema.parse(+ await googleJson("/v1/createSession", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ mapType: "roadmap",+ language: "en-US",+ region: "US",+ }),+ }),+ );+ cachedSession = session;+ return session;+}++async function getCopyright(viewport: GoogleMapsViewport) {+ const session = await getSession();+ const params = new URLSearchParams({ session: session.session });+ for (const [name, value] of Object.entries(viewport))+ params.set(name, String(value));+ const data = z+ .object({ copyright: z.string().min(1) })+ .parse(await googleJson(`/tile/v1/viewport?${params}`));+ return data.copyright;+}++async function getTile(zoom: number, x: number, y: number) {+ const session = await getSession();+ const params = new URLSearchParams({ session: session.session });+ const response = await googleRequest(+ `/v1/2dtiles/${zoom}/${x}/${y}?${params}`,+ );+ if (!response.ok) {+ await response.body?.cancel();+ return new Response("Google Maps tile unavailable.", {+ status: response.status,+ headers: { "Cache-Control": "private, no-store" },+ });+ }+ const contentType = response.headers.get("Content-Type") ?? "";+ if (!["image/png", "image/jpeg", "image/webp"].includes(contentType)) {+ await response.body?.cancel();+ throw new AppError(+ "UPSTREAM_UNAVAILABLE",+ "Google Maps returned an invalid tile.",+ );+ }+ // Keep Google's browser freshness window without creating a shared CDN cache+ // or storing imagery ourselves.+ const maxAge = /max-age=(\d+)/.exec(+ response.headers.get("Cache-Control") ?? "",+ )?.[1];+ return new Response(response.body, {+ headers: {+ "Content-Type": contentType,+ "Cache-Control": maxAge+ ? `private, max-age=${maxAge}`+ : "private, no-store",+ Vary: "Cookie",+ "X-Content-Type-Options": "nosniff",+ },+ });+}++export const GoogleMapsService = { getCopyright, getTile };diff --git a/src/server/features/local-seo/services/LocalSeoService.test.ts b/src/server/features/local-seo/services/LocalSeoService.test.tsnew file mode 100644index 00000000..aa85c5b5--- /dev/null+++ b/src/server/features/local-seo/services/LocalSeoService.test.ts@@ -0,0 +1,325 @@+import { readFileSync } from "node:fs";+import type { Client, InValue } from "@libsql/client";+import type { LibSQLDatabase } from "drizzle-orm/libsql";+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";+import { LocalSeoService } from "./LocalSeoService";+import {+ finalizeLocalCheck,+ prepareLocalCheck,+ searchLocalPoints,+} from "./localSeoCollection";+import { LocalSeoRepository as repo } from "../repositories/LocalSeoRepository";+import {+ LocalPointStatus,+ LocalScanStatus,+ localPointLabel,+} from "@/shared/local-seo";++const mocks = vi.hoisted(() => ({+ client: null as Client | null,+ database: null as LibSQLDatabase | null,+ createWorkflow: vi.fn(),+ workflowStatus: vi.fn(),+ search: vi.fn(),+ hosted: vi.fn(),+ credits: vi.fn(),+}));++vi.mock("@/db", async () => {+ const { createClient } = await import("@libsql/client");+ const { drizzle } = await import("drizzle-orm/libsql");+ mocks.client = createClient({ url: "file::memory:" });+ mocks.database = drizzle(mocks.client);+ return { db: mocks.database };+});+vi.mock("@/db/runBatch", () => ({+ runBatch: async (+ build: (+ tx: Pick<LibSQLDatabase, "insert" | "update" | "delete">,+ ) => { toSQL: () => { sql: string; params: InValue[] } }[],+ ) => {+ if (!mocks.database || !mocks.client)+ throw new Error("Database not initialized");+ await mocks.client.batch(+ build(mocks.database).map((query) => {+ const { sql, params } = query.toSQL();+ return { sql, args: params };+ }),+ "write",+ );+ },+}));+vi.mock("cloudflare:workers", () => ({+ env: {+ LOCAL_RANK_WORKFLOW: {+ create: mocks.createWorkflow,+ get: async () => ({ status: mocks.workflowStatus }),+ },+ },+}));+vi.mock("@/server/lib/dataforseo", () => ({+ createDataforseoClient: () => ({ serp: { localBatch: mocks.search } }),+}));+vi.mock("@/server/lib/runtime-env", () => ({+ isHostedServerAuthMode: mocks.hosted,+}));+vi.mock("@/server/billing/subscription", () => ({+ getOrCreateOrganizationCustomer: async (customer: {+ organizationId: string;+ }) => ({ id: customer.organizationId }),+ getUsageCreditsRemaining: mocks.credits,+}));++const customer = {+ projectId: "project-a",+ organizationId: "org-a",+ userId: "user-a",+ userEmail: "[email protected]",+};+const business = {+ title: "Branch Books",+ address: "Portland",+ cid: "own-listing",+ placeId: null,+ latitude: 45.52,+ longitude: -122.68,+};+const client = mocks.client;+if (!client) throw new Error("Database not initialized");++beforeAll(async () => {+ await client.executeMultiple(`+ PRAGMA foreign_keys = ON;+ CREATE TABLE projects (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, archived_at TEXT);+ ${readFileSync("drizzle/sqlite/0060_reflective_wrecker.sql", "utf8")}+ `);+});+afterAll(() => client.close());+beforeEach(async () => {+ mocks.createWorkflow.mockResolvedValue({ id: "workflow" });+ mocks.workflowStatus.mockResolvedValue({ status: "running" });+ mocks.search.mockImplementation(async (searches: unknown[]) =>+ searches.map(() => ({ status: "fulfilled", value: [] })),+ );+ mocks.hosted.mockResolvedValue(false);+ mocks.credits.mockResolvedValue({ monthlyRemaining: 0, topupRemaining: 0 });+ await client.executeMultiple(+ "DELETE FROM projects; INSERT INTO projects VALUES ('project-a', 'org-a', NULL), ('project-b', 'org-b', NULL);",+ );+});++async function trackerAndInput(gridSize: 3 | 5 = 3, keywords = ["bookstore"]) {+ const tracker = await LocalSeoService.createTracker(+ {+ projectId: customer.projectId,+ business,+ keywords,+ gridSize,+ spacingKm: 2,+ },+ "en",+ );+ const state = await LocalSeoService.getTracker(+ customer.projectId,+ tracker.id,+ );+ return {+ tracker,+ input: {+ projectId: customer.projectId,+ trackerId: tracker.id,+ requestId: crypto.randomUUID(),+ maxCostCredits: state.estimate.costCredits,+ },+ };+}++async function startedScan() {+ const { input } = await trackerAndInput();+ const check = await LocalSeoService.startCheck(input, customer);+ const [scan] = await repo.getScansForCheck(customer.projectId, check.id);+ return scan;+}++async function searchedScan() {+ const scan = await startedScan();+ const [plan] = await prepareLocalCheck(customer.projectId, scan.checkId);+ await searchLocalPoints(plan, plan.points, customer);+ return scan;+}++describe("saved local SEO scans", () => {+ it.each([3, 5] as const)(+ "checks all keywords once for grid width %s across repeated requests",+ async (gridSize) => {+ const { input } = await trackerAndInput(gridSize, [+ "bookstore",+ "used books",+ ]);+ const first = await LocalSeoService.startCheck(input, customer);+ const same = await LocalSeoService.startCheck(input, customer);+ const otherClick = await LocalSeoService.startCheck(+ { ...input, requestId: crypto.randomUUID() },+ customer,+ );+ expect([same.id, otherClick.id]).toEqual([first.id, first.id]);+ expect(mocks.createWorkflow).toHaveBeenCalledTimes(1);+ const state = await LocalSeoService.getTracker(+ customer.projectId,+ input.trackerId,+ );+ expect(state.scans.map((scan) => scan.keywordId)).toEqual(+ expect.arrayContaining(state.keywords.map((keyword) => keyword.id)),+ );+ expect(state.scans).toHaveLength(2);+ const saved = await LocalSeoService.getScan(+ customer.projectId,+ state.scans[0].id,+ );+ expect(saved.points).toHaveLength(gridSize ** 2);+ expect(saved.points[Math.floor(saved.points.length / 2)]).toMatchObject({+ latitude: business.latitude,+ longitude: business.longitude,+ status: LocalPointStatus.Pending,+ });+ },+ );++ it("prevents another project from reading or starting a tracker or scan", async () => {+ const { input } = await trackerAndInput();+ const check = await LocalSeoService.startCheck(input, customer);+ const [scan] = await repo.getScansForCheck(customer.projectId, check.id);+ await expect(+ LocalSeoService.getTracker("project-b", input.trackerId),+ ).rejects.toThrow("not found in this project");+ await expect(LocalSeoService.getScan("project-b", scan.id)).rejects.toThrow(+ "not found in this project",+ );+ await expect(+ LocalSeoService.startCheck(+ { ...input, projectId: "project-b" },+ { ...customer, projectId: "project-b", organizationId: "org-b" },+ ),+ ).rejects.toThrow("not found in this project");+ expect(await LocalSeoService.listTrackers("project-b")).toEqual([]);+ });++ it("rejects a lower credit approval before submitting paid searches", async () => {+ const { input } = await trackerAndInput(3, ["bookstore", "used books"]);+ const belowTotal = input.maxCostCredits - 1;+ await expect(+ LocalSeoService.startCheck(+ { ...input, maxCostCredits: belowTotal },+ customer,+ ),+ ).rejects.toThrow("estimate changed");+ expect(mocks.createWorkflow).not.toHaveBeenCalled();+ });++ it("matches the exact listing and stores competitors once", async () => {+ const items = [+ { title: business.title, cid: "other-branch", rank_absolute: 1 },+ {+ title: business.title,+ cid: business.cid,+ rank_absolute: 7,+ rating: { value: 4.8, votes_count: 50 },+ },+ { title: business.title, cid: business.cid, rank_absolute: 8 },+ ];+ mocks.search.mockImplementation(async (searches: unknown[]) =>+ searches.map(() => ({ status: "fulfilled", value: items })),+ );+ const scan = await searchedScan();+ await finalizeLocalCheck(customer.projectId, scan.checkId);+ const saved = await LocalSeoService.getScan(customer.projectId, scan.id);+ expect(saved.scan.status).toBe(LocalScanStatus.Completed);+ const state = await LocalSeoService.getTracker(+ customer.projectId,+ scan.trackerId,+ );+ expect(state.scans.find((row) => row.id === scan.id)).toMatchObject({+ summary: { completed: 9, found: 9, averageRank: 7, top3Percent: 0 },+ });+ const point = saved.points[0];+ expect(+ saved.results.filter((result) => result.pointId === point.id),+ ).toMatchObject([+ { cid: "other-branch", rank: 1 },+ { cid: business.cid, rank: 7, rating: 4.8, reviews: 50 },+ ]);+ expect(+ (+ await client.execute(+ "SELECT count(*) AS count FROM local_rank_businesses",+ )+ ).rows[0]?.count,+ ).toBe(2);+ });++ it("distinguishes sparse results from failed searches and excludes failures from coverage", async () => {+ const values = [+ [+ {+ title: business.title,+ cid: business.cid,+ rank_absolute: null,+ rank_group: 2,+ },+ ],+ // An unusable result fails only its own point.+ [{ cid: "untitled" }],+ ];+ mocks.search.mockImplementation(async (searches: unknown[]) =>+ searches.map((_, index) =>+ index === 0+ ? { status: "rejected", reason: new Error("Provider failure") }+ : { status: "fulfilled", value: values[index - 1] ?? [] },+ ),+ );+ const scan = await searchedScan();+ await finalizeLocalCheck(customer.projectId, scan.checkId);+ const saved = await LocalSeoService.getScan(customer.projectId, scan.id);+ expect(saved.scan.status).toBe(LocalScanStatus.Partial);+ const state = await LocalSeoService.getTracker(+ customer.projectId,+ scan.trackerId,+ );+ expect(state.scans.find((row) => row.id === scan.id)).toMatchObject({+ summary: { completed: 7, found: 1, averageRank: 2, top3Percent: 14 },+ });+ expect(saved.points.slice(0, 4).map(localPointLabel)).toEqual([+ "Search failed",+ "#2",+ "Search failed",+ "Not found · 0 listings returned",+ ]);+ });++ it("rejects insufficient hosted credits before queuing a scan", async () => {+ const { input } = await trackerAndInput();+ mocks.hosted.mockResolvedValue(true);+ await expect(LocalSeoService.startCheck(input, customer)).rejects.toThrow(+ "INSUFFICIENT_CREDITS",+ );+ expect(mocks.createWorkflow).not.toHaveBeenCalled();+ });++ it("marks unfinished points as failed when the workflow stops", async () => {+ const scan = await startedScan();+ mocks.workflowStatus.mockResolvedValue({ status: "errored" });+ const saved = await LocalSeoService.getScan(customer.projectId, scan.id);+ expect(saved.scan.status).toBe(LocalScanStatus.Failed);+ expect(+ saved.points.every((point) => point.status === LocalPointStatus.Failed),+ ).toBe(true);+ });+});diff --git a/src/server/features/local-seo/services/LocalSeoService.ts b/src/server/features/local-seo/services/LocalSeoService.tsnew file mode 100644index 00000000..a7abf5ba--- /dev/null+++ b/src/server/features/local-seo/services/LocalSeoService.ts@@ -0,0 +1,339 @@+import { env } from "cloudflare:workers";+import { z } from "zod";+import { createDataforseoClient } from "@/server/lib/dataforseo";+import { dataforseoPricing } from "@/server/lib/dataforseo/pricing";+import {+ getOrCreateOrganizationCustomer,+ getUsageCreditsRemaining,+ type BillingCustomerContext,+} from "@/server/billing/subscription";+import { isHostedServerAuthMode } from "@/server/lib/runtime-env";+import { AppError } from "@/server/lib/errors";+import {+ creditsForProviderUsd,+ autumnSeoDataCreditsToUsd,+} from "@/shared/billing";+import {+ buildLocalGrid,+ isLocalScanActive,+ LocalPointStatus,+ LocalScanStatus,+} from "@/shared/local-seo";+import {+ localBusinessSchema,+ type createLocalTrackerSchema,+ type startLocalCheckSchema,+ type updateLocalKeywordsSchema,+} from "@/types/schemas/local-seo";+import {+ LocalSeoRepository as repo,+ type LocalCheckRow,+ type LocalTrackerRow,+} from "../repositories/LocalSeoRepository";+import { finalizeLocalCheck, localPointSearch } from "./localSeoCollection";++const profileSchema = z.object({+ title: z.string(),+ cid: z.string().nullish(),+ place_id: z.string().nullish(),+ address: z.string().nullish(),+ latitude: z.number(),+ longitude: z.number(),+});++async function lookupBusiness(+ query: string,+ market: { locationCode: number; languageCode: string },+ customer: BillingCustomerContext,+) {+ const profile = await createDataforseoClient(+ customer,+ ).business.myBusinessInfo({ keyword: query, ...market });+ if (!profile) return null;+ const parsed = profileSchema.safeParse(profile);+ if (!parsed.success)+ throw new AppError(+ "UPSTREAM_UNAVAILABLE",+ "This listing did not include usable map coordinates. Try its business name and full address.",+ );+ const row = parsed.data;+ return localBusinessSchema.parse({+ title: row.title,+ cid: row.cid ?? null,+ placeId: row.place_id ?? null,+ address: row.address ?? null,+ latitude: row.latitude,+ longitude: row.longitude,+ });+}++async function requireTracker(projectId: string, trackerId: string) {+ const tracker = await repo.getTracker(projectId, trackerId);+ if (!tracker)+ throw new AppError(+ "VALIDATION_ERROR",+ "Local SEO tracker not found in this project.",+ );+ return tracker;+}++async function createTracker(+ input: z.infer<typeof createLocalTrackerSchema>,+ languageCode: string,+) {+ const keywords = [...new Set(input.keywords)];+ const tracker = {+ id: crypto.randomUUID(),+ projectId: input.projectId,+ ...input.business,+ gridSize: input.gridSize,+ spacingKm: input.spacingKm,+ languageCode,+ createdAt: new Date().toISOString(),+ };+ // Validate generated coordinates before storing an unusable tracker.+ for (const point of buildLocalGrid(+ tracker,+ tracker.gridSize,+ tracker.spacingKm,+ )) {+ if (Math.abs(point.latitude) > 85 || Math.abs(point.longitude) > 180)+ throw new AppError(+ "VALIDATION_ERROR",+ "This grid extends beyond the map. Choose a smaller grid or spacing.",+ );+ }+ await repo.createTracker(+ tracker,+ keywords.map((keyword) => ({+ id: crypto.randomUUID(),+ trackerId: tracker.id,+ keyword,+ })),+ );+ return tracker;+}++/** Matches the per-search credit holds the check's live searches reserve. */+function checkCostCredits(tracker: LocalTrackerRow, keywords: number) {+ const search = localPointSearch(tracker, "", tracker);+ return (+ keywords *+ tracker.gridSize ** 2 *+ creditsForProviderUsd(dataforseoPricing.serp.local(search))+ );+}++async function reconcileCheck(check: LocalCheckRow) {+ if (!isLocalScanActive(check.status)) return check;+ let status: { status: string } | null = null;+ try {+ status = await (await env.LOCAL_RANK_WORKFLOW.get(check.id)).status();+ } catch {+ /* Startup and a missing workflow share this grace period. */+ }+ if (+ status &&+ ["running", "queued", "waiting", "waitingForPause", "paused"].includes(+ status.status,+ )+ )+ return check;+ if (+ (!status || status.status === "unknown") &&+ Date.now() - new Date(check.createdAt).getTime() < 60_000+ )+ return check;+ const error =+ "The check stopped before all results were saved. Completed points remain available; a new check uses credits.";+ await finalizeLocalCheck(check.projectId, check.id, error);+ return (await repo.getCheck(check.projectId, check.id)) ?? check;+}++async function getTracker(projectId: string, trackerId: string) {+ const tracker = await requireTracker(projectId, trackerId);+ const [keywords, checks] = await Promise.all([+ repo.getKeywords(trackerId),+ repo.listChecks(projectId, trackerId),+ ]);+ const reconciled = await Promise.all(checks.map(reconcileCheck));+ const checkIds = checks.map((check) => check.id);+ const [scans, summaries] = await Promise.all([+ repo.listScans(projectId, trackerId, checkIds),+ repo.getScanSummaries(projectId, trackerId, checkIds),+ ]);+ const summaryByScan = new Map(+ summaries.map((row) => [+ row.scanId,+ {+ total: row.total,+ completed: row.completed,+ found: row.found,+ top3: row.top3,+ top3Percent: row.completed+ ? Math.round((row.top3 / row.completed) * 100)+ : null,+ averageRank: row.found+ ? Number((row.rankTotal / row.found).toFixed(1))+ : null,+ },+ ]),+ );+ const costCredits = checkCostCredits(tracker, keywords.length);+ return {+ tracker,+ keywords,+ checks: reconciled,+ scans: scans.map((scan) => ({+ ...scan,+ summary: summaryByScan.get(scan.id),+ })),+ estimate: {+ costCredits,+ costUsd: autumnSeoDataCreditsToUsd(costCredits),+ keywords: keywords.length,+ points: tracker.gridSize ** 2,+ searches: keywords.length * tracker.gridSize ** 2,+ },+ };+}++async function updateKeywords(+ input: z.infer<typeof updateLocalKeywordsSchema>,+) {+ await requireTracker(input.projectId, input.trackerId);+ const active = await repo.getActiveCheck(input.projectId, input.trackerId);+ if (active && isLocalScanActive((await reconcileCheck(active)).status))+ throw new AppError(+ "VALIDATION_ERROR",+ "Wait for the current check to finish before changing keywords.",+ );+ const existing = await repo.getKeywords(input.trackerId, true);+ const keywords = [...new Set(input.keywords)];+ await repo.saveKeywords(+ input.trackerId,+ keywords.map((keyword) => ({+ id:+ existing.find((row) => row.keyword === keyword)?.id ??+ crypto.randomUUID(),+ trackerId: input.trackerId,+ keyword,+ archivedAt: null,+ })),+ existing+ .filter((row) => !row.archivedAt && !keywords.includes(row.keyword))+ .map((row) => row.id),+ );+}++async function startCheck(+ input: z.infer<typeof startLocalCheckSchema>,+ customer: BillingCustomerContext,+) {+ const tracker = await requireTracker(input.projectId, input.trackerId);+ const keywords = await repo.getKeywords(tracker.id);+ if (!keywords.length)+ throw new AppError(+ "VALIDATION_ERROR",+ "Add keywords before checking rankings.",+ );+ const existing = await repo.getCheck(input.projectId, input.requestId);+ if (existing) return existing;+ const active = await repo.getActiveCheck(input.projectId, tracker.id);+ if (active && isLocalScanActive((await reconcileCheck(active)).status))+ return active;+ const costCredits = checkCostCredits(tracker, keywords.length);+ if (costCredits > input.maxCostCredits)+ throw new AppError(+ "VALIDATION_ERROR",+ "The check estimate changed. Review the new cost before checking rankings.",+ );+ if (await isHostedServerAuthMode()) {+ const { id } = await getOrCreateOrganizationCustomer(customer);+ const credits = await getUsageCreditsRemaining(id);+ if (+ Math.max(credits.monthlyRemaining, 0) ++ Math.max(credits.topupRemaining, 0) <+ costCredits+ )+ throw new AppError("INSUFFICIENT_CREDITS");+ }+ const check: LocalCheckRow = {+ id: input.requestId,+ projectId: input.projectId,+ trackerId: tracker.id,+ status: LocalScanStatus.Queued,+ error: null,+ createdAt: new Date().toISOString(),+ completedAt: null,+ };+ const scans = keywords.map((keyword) => ({+ ...check,+ id: crypto.randomUUID(),+ checkId: check.id,+ keywordId: keyword.id,+ }));+ try {+ await repo.createCheck(+ check,+ scans,+ scans.flatMap((scan) =>+ buildLocalGrid(tracker, tracker.gridSize, tracker.spacingKm).map(+ (point) => ({+ id: crypto.randomUUID(),+ scanId: scan.id,+ ...point,+ status: LocalPointStatus.Pending,+ }),+ ),+ ),+ );+ } catch (error) {+ const blocker = await repo.getActiveCheck(input.projectId, tracker.id);+ if (blocker) return blocker;+ throw error;+ }+ try {+ await env.LOCAL_RANK_WORKFLOW.create({+ id: check.id,+ params: { checkId: check.id, customer },+ });+ } catch (error) {+ // A lost create response is ambiguous. Do not start another workflow or+ // post paid tasks here; reconciliation checks the same instance later.+ console.error("[local-seo] workflow start failed:", error);+ }+ return check;+}++async function getScan(projectId: string, scanId: string) {+ const scan = await repo.getScan(projectId, scanId);+ if (!scan)+ throw new AppError(+ "VALIDATION_ERROR",+ "Local SEO scan not found in this project.",+ );+ const check = await repo.getCheck(projectId, scan.checkId);+ if (check) await reconcileCheck(check);+ // Every point's businesses come with the scan (at most 25 × 20 rows), so+ // switching points never waits on a request.+ const [points, results] = await Promise.all([+ repo.getPoints(scan.id),+ repo.getScanResults(projectId, scan.id),+ ]);+ return {+ scan: (await repo.getScan(projectId, scanId)) ?? scan,+ points,+ results,+ };+}++export const LocalSeoService = {+ listTrackers: repo.listTrackers,+ lookupBusiness,+ createTracker,+ getTracker,+ updateKeywords,+ startCheck,+ getScan,+};diff --git a/src/server/features/local-seo/services/localSeoCollection.ts b/src/server/features/local-seo/services/localSeoCollection.tsnew file mode 100644index 00000000..b868054d--- /dev/null+++ b/src/server/features/local-seo/services/localSeoCollection.ts@@ -0,0 +1,230 @@+import { z } from "zod";+import { createDataforseoClient } from "@/server/lib/dataforseo";+import type { BillingCustomerContext } from "@/server/billing/subscription";+import { AppError } from "@/server/lib/errors";+import {+ isLocalScanActive,+ localGridZoom,+ LOCAL_RANK_DEPTH,+ LocalPointStatus,+ LocalScanStatus,+} from "@/shared/local-seo";+import {+ LocalSeoRepository as repo,+ type LocalPointRow,+ type LocalTrackerRow,+} from "../repositories/LocalSeoRepository";++const resultSchema = z.object({+ title: z.string(),+ cid: z.string().nullish(),+ place_id: z.string().nullish(),+ address: z.string().nullish(),+ rank_absolute: z.number().int().positive().nullish(),+ rank_group: z.number().int().positive().nullish(),+ rating: z+ .object({+ value: z.number().nullish(),+ votes_count: z.number().int().nullish(),+ })+ .nullish(),+});++const SEARCH_FAILED = "The search provider could not complete this point.";++/** The live Maps search for one grid point. */+export function localPointSearch(+ tracker: LocalTrackerRow,+ keyword: string,+ point: { latitude: number; longitude: number },+) {+ const zoom = localGridZoom(tracker.spacingKm, tracker.latitude);+ return {+ keyword,+ locationCoordinate: `${point.latitude},${point.longitude},${zoom}z`,+ languageCode: tracker.languageCode,+ searchType: "maps" as const,+ device: "mobile" as const,+ depth: LOCAL_RANK_DEPTH,+ searchPlaces: false,+ };+}++export async function prepareLocalCheck(projectId: string, checkId: string) {+ const check = await repo.getCheck(projectId, checkId);+ if (!check || !isLocalScanActive(check.status))+ throw new AppError(+ "VALIDATION_ERROR",+ "This check is no longer available.",+ );+ // Archived keywords are included: a keyword removed after the check+ // started is still searched as queued.+ const [tracker, keywords, scans] = await Promise.all([+ repo.getTracker(projectId, check.trackerId),+ repo.getKeywords(check.trackerId, true),+ repo.getScansForCheck(projectId, checkId),+ ]);+ if (!tracker)+ throw new AppError(+ "VALIDATION_ERROR",+ "The scan configuration is no longer available.",+ );+ const plans = await Promise.all(+ scans.map(async (scan) => {+ const keyword = keywords.find((row) => row.id === scan.keywordId);+ if (!keyword)+ throw new AppError(+ "VALIDATION_ERROR",+ "The scan configuration is no longer available.",+ );+ await repo.updateScan(projectId, scan.id, {+ status: LocalScanStatus.Running,+ });+ return {+ scanId: scan.id,+ tracker,+ keyword: keyword.keyword,+ points: await repo.getPoints(scan.id),+ };+ }),+ );+ await repo.updateCheck(projectId, checkId, {+ status: LocalScanStatus.Running,+ });+ return plans;+}++type LocalScanPlan = Awaited<ReturnType<typeof prepareLocalCheck>>[number];++/** Runs one paid live search per point and saves each point as it returns. */+export async function searchLocalPoints(+ plan: LocalScanPlan,+ points: LocalPointRow[],+ customer: BillingCustomerContext,+) {+ const outcomes = await createDataforseoClient(customer).serp.localBatch(+ points.map((point) => localPointSearch(plan.tracker, plan.keyword, point)),+ );+ await Promise.all(+ outcomes.map((outcome, index) => {+ const point = points[index];+ // One unusable point must not discard the batch's other paid results.+ const saved =+ outcome.status === "fulfilled"+ ? savePointResults(plan.tracker, point, outcome.value)+ : Promise.reject(outcome.reason);+ return saved.catch((error: unknown) => {+ console.warn(`[local-seo] point ${point.id} failed:`, error);+ return repo.failPoint(point.id, SEARCH_FAILED);+ });+ }),+ );+}++export async function failLocalPoints(points: LocalPointRow[]) {+ await Promise.all(+ points.map((point) => repo.failPoint(point.id, SEARCH_FAILED)),+ );+}++async function savePointResults(+ tracker: LocalTrackerRow,+ point: LocalPointRow,+ items: Record<string, unknown>[],+) {+ const parsedRows = items.map((item, index) => {+ const row = resultSchema.parse(item);+ const rank = row.rank_absolute ?? row.rank_group ?? index + 1;+ const identity = row.cid+ ? `cid:${row.cid}`+ : row.place_id+ ? `place:${row.place_id}`+ : `point:${point.id}:${rank}`;+ return {+ id: `${point.scanId}:${identity}`,+ scanId: point.scanId,+ identity,+ title: row.title,+ cid: row.cid ?? null,+ placeId: row.place_id ?? null,+ address: row.address ?? null,+ rating: row.rating?.value ?? null,+ reviews: row.rating?.votes_count ?? null,+ rank,+ };+ });+ const rows = parsedRows.filter(+ (row, index) =>+ parsedRows.findIndex((other) => other.identity === row.identity) ===+ index,+ );+ const target = rows.find(+ (row) =>+ (tracker.cid != null && row.cid === tracker.cid) ||+ (tracker.placeId != null && row.placeId === tracker.placeId),+ );+ await repo.savePoint(+ point,+ rows,+ rows.map((row) => ({ businessId: row.id, rank: row.rank })),+ target?.rank ?? null,+ items.length,+ );+}++async function finalizeLocalScan(+ projectId: string,+ scanId: string,+ error?: string,+) {+ await repo.failPendingPoints(+ scanId,+ error ??+ "This point did not finish in time. The search may still have used credits.",+ );+ const points = await repo.getPoints(scanId);+ const completed = points.filter(+ (p) => p.status === LocalPointStatus.Completed,+ ).length;+ await repo.updateScan(projectId, scanId, {+ status:+ completed === points.length && completed > 0+ ? LocalScanStatus.Completed+ : completed > 0+ ? LocalScanStatus.Partial+ : LocalScanStatus.Failed,+ error: error ?? null,+ completedAt: new Date().toISOString(),+ });+}++export async function finalizeLocalCheck(+ projectId: string,+ checkId: string,+ error?: string,+) {+ let scans = await repo.getScansForCheck(projectId, checkId);+ for (const scan of scans) {+ if (isLocalScanActive(scan.status))+ await finalizeLocalScan(projectId, scan.id, error);+ }+ scans = await repo.getScansForCheck(projectId, checkId);+ const completed = scans.filter(+ (scan) => scan.status === LocalScanStatus.Completed,+ ).length;+ const hasResults = scans.some(+ (scan) =>+ scan.status === LocalScanStatus.Completed ||+ scan.status === LocalScanStatus.Partial,+ );+ await repo.updateCheck(projectId, checkId, {+ status:+ completed === scans.length && completed > 0+ ? LocalScanStatus.Completed+ : hasResults+ ? LocalScanStatus.Partial+ : LocalScanStatus.Failed,+ completedAt: new Date().toISOString(),+ error: error ?? null,+ });+}diff --git a/src/server/gdpr/storage-erasure.ts b/src/server/gdpr/storage-erasure.tsindex be653adb..93a65dda 100644--- a/src/server/gdpr/storage-erasure.ts+++ b/src/server/gdpr/storage-erasure.ts@@ -188,6 +188,10 @@ async function eraseStorage(env: Env, payload: GdprStorageErasurePayload) {),],);+ const localRankWorkflowsTerminated = await terminateWorkflows(+ env.LOCAL_RANK_WORKFLOW,+ payload.activeLocalRankWorkflowIds,+ );const googleRevocations: GoogleRevocationResult[] = [];for (const account of payload.googleAccounts) {@@ -250,6 +254,7 @@ async function eraseStorage(env: Env, payload: GdprStorageErasurePayload) {auditTerminated: auditWorkflowsTerminated,rankTerminated: rankWorkflowsTerminated,aiVisibilityTerminated: aiWorkflowsTerminated,+ localRankTerminated: localRankWorkflowsTerminated,},durableObjects: {sam: payload.samSessionIds.length,diff --git a/src/server/lib/dataforseo/client.ts b/src/server/lib/dataforseo/client.tsindex f75d05b7..8163531d 100644--- a/src/server/lib/dataforseo/client.ts+++ b/src/server/lib/dataforseo/client.ts@@ -233,6 +233,17 @@ export function createDataforseoClient(customer: BillingCustomerContext) {dataforseoPricing.serp.local,"local_seo",),+ // Live Maps searches for a Local SEO check, one per grid point; one+ // credit hold covers the batch.+ localBatch: (inputs: Parameters<typeof fetchLocalSerp>[0][]) =>+ meterDataforseoCalls(+ customer,+ inputs.map((input) => () => fetchLocalSerp(input)),+ inputs.map((input) =>+ creditsForProviderUsd(dataforseoPricing.serp.local(input)),+ ),+ "local_seo",+ ),// One queued Maps task per rank grid point; one metered charge covers// them all (DataForSEO bills task_post, collection is free).localTaskPost: meter(diff --git a/src/server/mcp/tools/local-seo-tools.ts b/src/server/mcp/tools/local-seo-tools.tsindex 2e4efa70..11acb810 100644--- a/src/server/mcp/tools/local-seo-tools.ts+++ b/src/server/mcp/tools/local-seo-tools.ts@@ -1,5 +1,10 @@/* eslint-disable max-lines */import { z } from "zod";+import {+ buildLocalGrid,+ localGridZoom,+ LOCAL_RANK_DEPTH,+} from "@/shared/local-seo";import {createDataforseoClient,fetchBusinessDataTaskResult,@@ -692,12 +697,6 @@ export const listBusinessCategoriesTool = {// get_local_rank_grid// ----------------------------------------------------------------------------// Degrees per kilometre. Longitude degrees shrink with latitude; the cosine is-// floored so a near-polar center can't blow the spacing up.-const KM_PER_DEGREE_LATITUDE = 110.574;-const KM_PER_DEGREE_LONGITUDE = 111.32;-const MIN_LONGITUDE_COSINE = 0.01;-const RANK_GRID_DEPTH = 20;// The grid's searches run as queued Maps tasks (~5-40 s each, in parallel at// DataForSEO). Polling stops 40 s into the call so it answers inside the 60 s// many MCP clients wait; tasks still running are collected by the next call.@@ -708,29 +707,6 @@ const RANK_GRID_POLL_INTERVAL_MS = 5000;// that lost the response, or got "processing", can simply call again.const RANK_GRID_RECEIPT_TTL_SECONDS = 60 * 60;const rankGridReceiptSchema = z.array(z.string().nullable());-// Without an explicit zoom DataForSEO infers one per coordinate, which yields-// "No Search Results" for some points and makes ranks incomparable across the-// grid. A fixed zoom fails the other way: a mobile viewport at zoom 14 spans-// only ~±1.5 km east-west at mid latitudes, so a business one 2-3 km grid step-// to the side falls outside the viewport and reads as "not ranked" (verified-// live: a rank-3 business vanished at zoom 14 and reappeared at zoom 12).-// Derive the zoom from the spacing instead: a world tile is 40075·cos(lat)/2^z-// km wide and a portrait viewport ~1.5 tiles, so the largest zoom whose-// viewport still spans ~1.25× the spacing is log2(24045·cos(lat)/spacing).-const RANK_GRID_ZOOM_NUMERATOR_KM = 24045;-const MIN_RANK_GRID_ZOOM = 4;-const MAX_RANK_GRID_ZOOM = 18;--function rankGridZoom(spacingKm: number, latitude: number): number {- const cosine = Math.max(- Math.abs(Math.cos((latitude * Math.PI) / 180)),- MIN_LONGITUDE_COSINE,- );- const zoom = Math.floor(- Math.log2((RANK_GRID_ZOOM_NUMERATOR_KM * cosine) / spacingKm),- );- return Math.min(MAX_RANK_GRID_ZOOM, Math.max(MIN_RANK_GRID_ZOOM, zoom));-}const getLocalRankGridInputSchema = {projectId: projectIdSchema,@@ -830,40 +806,6 @@ type GridPointResult = GridPoint & {error?: boolean;};-function buildRankGridPoints(- center: { latitude: number; longitude: number },- gridSize: number,- spacingKm: number,-): GridPoint[] {- const middle = (gridSize - 1) / 2;- const latitudeStep = spacingKm / KM_PER_DEGREE_LATITUDE;- const longitudeStep =- spacingKm /- (KM_PER_DEGREE_LONGITUDE *- Math.max(- Math.abs(Math.cos((center.latitude * Math.PI) / 180)),- MIN_LONGITUDE_COSINE,- ));-- const points: GridPoint[] = [];- for (let row = 0; row < gridSize; row++) {- for (let col = 0; col < gridSize; col++) {- points.push({- row,- col,- // Row 0 is the northernmost line so the rendered grid reads like a map.- latitude: Number(- (center.latitude + (middle - row) * latitudeStep).toFixed(7),- ),- longitude: Number(- (center.longitude + (col - middle) * longitudeStep).toFixed(7),- ),- });- }- }- return points;-}-function matchGridItem(items: unknown[],target: { cid?: string; placeId?: string; name?: string },@@ -911,7 +853,7 @@ async function collectRankGridTask(function renderGrid(results: GridPointResult[], gridSize: number): string {const lines: string[] = [];for (let row = 0; row < gridSize; row++) {- // buildRankGridPoints emits row-major order and results keep it.+ // buildLocalGrid emits row-major order and results keep it.const cells = results.slice(row * gridSize, (row + 1) * gridSize).map((point) =>@@ -1022,10 +964,10 @@ export const getLocalRankGridTool = {const deadline = Date.now() + RANK_GRID_COLLECT_MS;const gridSize = args.gridSize ?? 3;const spacingKm = args.spacingKm ?? 2;- const zoom = args.zoom ?? rankGridZoom(spacingKm, args.center.latitude);+ const zoom = args.zoom ?? localGridZoom(spacingKm, args.center.latitude);const device = args.device ?? "mobile";const languageCode = args.languageCode ?? context.project.languageCode;- const points = buildRankGridPoints(args.center, gridSize, spacingKm);+ const points = buildLocalGrid(args.center, gridSize, spacingKm);// The target is not part of the key: it only filters the collected rows.const receiptKey = await buildCacheKey("mcp:local-rank-grid", {@@ -1057,7 +999,7 @@ export const getLocalRankGridTool = {),languageCode,device,- depth: RANK_GRID_DEPTH,+ depth: LOCAL_RANK_DEPTH,});// The searches are already paid for, so a failed receipt write must not// fail this call; it only means a repeat would buy them again.@@ -1155,7 +1097,7 @@ export const getLocalRankGridTool = {};const text = [- `Local rank grid for "${args.keyword}" (${gridSize}x${gridSize}, ${spacingKm} km spacing, zoom ${zoom}, top ${RANK_GRID_DEPTH} checked).`,+ `Local rank grid for "${args.keyword}" (${gridSize}x${gridSize}, ${spacingKm} km spacing, zoom ${zoom}, top ${LOCAL_RANK_DEPTH} checked).`,formatMatchedBusiness(matchedBusiness),`Rank per point, north at the top ("–" = not among the results returned there, "x" = search failed but may still be charged):`,renderGrid(grid, gridSize),diff --git a/src/server/workflows/LocalRankWorkflow.ts b/src/server/workflows/LocalRankWorkflow.tsnew file mode 100644index 00000000..de059dad--- /dev/null+++ b/src/server/workflows/LocalRankWorkflow.ts@@ -0,0 +1,77 @@+import {+ WorkflowEntrypoint,+ type WorkflowEvent,+ type WorkflowStep,+} from "cloudflare:workers";+import type { BillingCustomerContext } from "@/server/billing/subscription";+import {+ failLocalPoints,+ finalizeLocalCheck,+ prepareLocalCheck,+ searchLocalPoints,+} from "@/server/features/local-seo/services/localSeoCollection";+import { pgStep } from "./pgStep";++type LocalRankPayload = {+ checkId: string;+ customer: BillingCustomerContext;+};+const ONCE = {+ retries: { limit: 0, delay: "1 second" as const },+ timeout: "2 minutes" as const,+};+// A Worker keeps six outbound connections open at once, so one step's live+// searches run in a single wave (~3-5 s each).+const SEARCHES_PER_STEP = 6;++export class LocalRankWorkflow extends WorkflowEntrypoint<+ Env,+ LocalRankPayload+> {+ async run(event: WorkflowEvent<LocalRankPayload>, step: WorkflowStep) {+ const { checkId, customer } = event.payload;+ const projectId = customer.projectId;+ if (!projectId) return;+ try {+ const plans = await pgStep(step, "prepare", undefined, () =>+ prepareLocalCheck(projectId, checkId),+ );+ for (const plan of plans) {+ for (+ let offset = 0;+ offset < plan.points.length;+ offset += SEARCHES_PER_STEP+ ) {+ const points = plan.points.slice(offset, offset + SEARCHES_PER_STEP);+ try {+ // Paid searches run once; a failed step fails its points instead+ // of buying the same searches again.+ await pgStep(step, `search-${plan.scanId}-${offset}`, ONCE, () =>+ searchLocalPoints(plan, points, customer),+ );+ } catch (error) {+ console.error(+ `[local-seo] keyword ${plan.scanId} points ${offset}+ failed:`,+ error,+ );+ await pgStep(step, `fail-${plan.scanId}-${offset}`, undefined, () =>+ failLocalPoints(points),+ );+ }+ }+ }+ await pgStep(step, "complete", undefined, () =>+ finalizeLocalCheck(projectId, checkId),+ );+ } catch (error) {+ console.error(`[local-seo] check ${checkId} failed:`, error);+ await pgStep(step, "fail", undefined, () =>+ finalizeLocalCheck(+ projectId,+ checkId,+ "The check could not finish. Saved points remain available. Submitted searches may still use credits.",+ ),+ );+ }+ }+}diff --git a/src/serverFunctions/google-maps.ts b/src/serverFunctions/google-maps.tsnew file mode 100644index 00000000..dfa4ddfe--- /dev/null+++ b/src/serverFunctions/google-maps.ts@@ -0,0 +1,10 @@+import { createServerFn } from "@tanstack/react-start";+import { requireProjectContext } from "./middleware";+import { GoogleMapsService } from "@/server/features/local-seo/services/GoogleMapsService";+import { localProjectSchema } from "@/types/schemas/local-seo";+import { googleMapsViewportSchema } from "@/types/schemas/google-maps";++export const getLocalMapCopyright = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(localProjectSchema.extend({ viewport: googleMapsViewportSchema }))+ .handler(({ data }) => GoogleMapsService.getCopyright(data.viewport));diff --git a/src/serverFunctions/local-seo.ts b/src/serverFunctions/local-seo.tsnew file mode 100644index 00000000..6be61748--- /dev/null+++ b/src/serverFunctions/local-seo.ts@@ -0,0 +1,59 @@+import { createServerFn } from "@tanstack/react-start";+import { LocalSeoService } from "@/server/features/local-seo/services/LocalSeoService";+import { requireProjectContext } from "./middleware";+import {+ createLocalTrackerSchema,+ localLookupSchema,+ localProjectSchema,+ localScanIdSchema,+ localTrackerIdSchema,+ startLocalCheckSchema,+ updateLocalKeywordsSchema,+} from "@/types/schemas/local-seo";++export const listLocalTrackers = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(localProjectSchema)+ .handler(({ context }) => LocalSeoService.listTrackers(context.projectId));+export const lookupLocalBusiness = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(localLookupSchema)+ .handler(({ data, context }) =>+ LocalSeoService.lookupBusiness(data.query, context.project, context),+ );+export const createLocalTracker = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(createLocalTrackerSchema)+ .handler(({ data, context }) =>+ LocalSeoService.createTracker(+ { ...data, projectId: context.projectId },+ context.project.languageCode,+ ),+ );+export const getLocalTracker = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(localTrackerIdSchema)+ .handler(({ data, context }) =>+ LocalSeoService.getTracker(context.projectId, data.trackerId),+ );+export const updateLocalKeywords = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(updateLocalKeywordsSchema)+ .handler(({ data, context }) =>+ LocalSeoService.updateKeywords({ ...data, projectId: context.projectId }),+ );+export const startLocalCheck = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(startLocalCheckSchema)+ .handler(({ data, context }) =>+ LocalSeoService.startCheck(+ { ...data, projectId: context.projectId },+ { ...context, projectId: context.projectId },+ ),+ );+export const getLocalScan = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(localScanIdSchema)+ .handler(({ data, context }) =>+ LocalSeoService.getScan(context.projectId, data.scanId),+ );diff --git a/src/shared/gdpr-erasure.ts b/src/shared/gdpr-erasure.tsindex b3d8342e..2474b7f0 100644--- a/src/shared/gdpr-erasure.ts+++ b/src/shared/gdpr-erasure.ts@@ -17,6 +17,7 @@ export const gdprStorageErasurePayloadSchema = zactiveAuditWorkflowIds: boundedIds,activeRankWorkflowIds: boundedIds,activeAiVisibilityWorkflowIds: boundedIds.default([]),+ activeLocalRankWorkflowIds: boundedIds.default([]),aiVisibilityProjectIds: boundedIds.default([]),r2Keys: boundedIds,googleAccounts: zdiff --git a/src/shared/local-seo.ts b/src/shared/local-seo.tsnew file mode 100644index 00000000..db92eb39--- /dev/null+++ b/src/shared/local-seo.ts@@ -0,0 +1,91 @@+export enum LocalScanStatus {+ Queued = "queued",+ Running = "running",+ Completed = "completed",+ Partial = "partial",+ Failed = "failed",+}++export enum LocalPointStatus {+ Pending = "pending",+ Completed = "completed",+ Failed = "failed",+}++export const LOCAL_RANK_DEPTH = 20;++export function isLocalScanActive(status: LocalScanStatus) {+ return (+ status === LocalScanStatus.Queued || status === LocalScanStatus.Running+ );+}++export type LocalGridPoint = {+ row: number;+ col: number;+ latitude: number;+ longitude: number;+};++/**+ * Keep the same viewport at every point, wide enough for the grid spacing.+ *+ * Without an explicit zoom DataForSEO infers one per coordinate, which yields+ * "No Search Results" for some points and makes ranks incomparable across the+ * grid. A fixed zoom fails the other way: a mobile viewport at zoom 14 spans+ * only ~±1.5 km east-west at mid latitudes, so a business one 2-3 km grid step+ * to the side falls outside the viewport and reads as "not ranked". A world+ * tile is 40075·cos(lat)/2^z km wide and a portrait viewport ~1.5 tiles, so+ * the largest zoom whose viewport still spans ~1.25× the spacing is+ * log2(24045·cos(lat)/spacing).+ */+export function localGridZoom(spacingKm: number, latitude: number) {+ const cosine = Math.max(Math.abs(Math.cos((latitude * Math.PI) / 180)), 0.01);+ return Math.min(+ 18,+ Math.max(4, Math.floor(Math.log2((24045 * cosine) / spacingKm))),+ );+}++/** Row zero is the northern edge; points are in row-major order. */+export function buildLocalGrid(+ center: { latitude: number; longitude: number },+ gridSize: number,+ spacingKm: number,+): LocalGridPoint[] {+ const middle = (gridSize - 1) / 2;+ const latitudeStep = spacingKm / 110.574;+ const longitudeStep =+ spacingKm /+ (111.32 *+ Math.max(Math.abs(Math.cos((center.latitude * Math.PI) / 180)), 0.01));+ return Array.from({ length: gridSize * gridSize }, (_, index) => {+ const row = Math.floor(index / gridSize);+ const col = index % gridSize;+ return {+ row,+ col,+ latitude: Number(+ (center.latitude + (middle - row) * latitudeStep).toFixed(7),+ ),+ longitude: Number(+ (center.longitude + (col - middle) * longitudeStep).toFixed(7),+ ),+ };+ });+}++type RankedPoint = {+ status: LocalPointStatus;+ rank: number | null;+ resultsCount: number | null;+};++export function localPointLabel(point: RankedPoint) {+ if (point.status === LocalPointStatus.Pending) return "Pending";+ if (point.status === LocalPointStatus.Failed) return "Search failed";+ if (point.rank != null) return `#${point.rank}`;+ return (point.resultsCount ?? 0) >= LOCAL_RANK_DEPTH+ ? "Not in returned top 20"+ : `Not found · ${point.resultsCount ?? 0} listings returned`;+}diff --git a/src/types/schemas/google-maps.ts b/src/types/schemas/google-maps.tsnew file mode 100644index 00000000..3322e0e0--- /dev/null+++ b/src/types/schemas/google-maps.ts@@ -0,0 +1,13 @@+import { z } from "zod";++export const googleMapsViewportSchema = z+ .object({+ zoom: z.number().int().min(0).max(22),+ north: z.number().min(-85.0511287798).max(85.0511287798),+ south: z.number().min(-85.0511287798).max(85.0511287798),+ east: z.number().min(-180).max(180),+ west: z.number().min(-180).max(180),+ })+ .refine((viewport) => viewport.north >= viewport.south);++export type GoogleMapsViewport = z.infer<typeof googleMapsViewportSchema>;diff --git a/src/types/schemas/local-seo-search.ts b/src/types/schemas/local-seo-search.tsnew file mode 100644index 00000000..8fecf5bf--- /dev/null+++ b/src/types/schemas/local-seo-search.ts@@ -0,0 +1,9 @@+import { z } from "zod";++export const localSeoSearchSchema = z.object({+ view: z.literal("history").optional().catch(undefined),+ keyword: z.uuid().optional(),+ scan: z.uuid().optional(),+ point: z.uuid().optional(),+});+export type LocalSeoSearch = z.infer<typeof localSeoSearchSchema>;diff --git a/src/types/schemas/local-seo.ts b/src/types/schemas/local-seo.tsnew file mode 100644index 00000000..5d8c88c3--- /dev/null+++ b/src/types/schemas/local-seo.ts@@ -0,0 +1,45 @@+import { z } from "zod";++const projectId = z.string().min(1);+export const localBusinessSchema = z+ .object({+ title: z.string().trim().min(1).max(300),+ cid: z.string().min(1).max(64).nullable(),+ placeId: z.string().min(1).max(256).nullable(),+ address: z.string().max(1000).nullable(),+ latitude: z.number().min(-85).max(85),+ longitude: z.number().min(-180).max(180),+ })+ .refine(+ (value) => value.cid != null || value.placeId != null,+ "Choose a Google Maps listing with a CID or place ID.",+ );++export type LocalBusiness = z.infer<typeof localBusinessSchema>;++export const localProjectSchema = z.object({ projectId });+export const localTrackerIdSchema = localProjectSchema.extend({+ trackerId: z.uuid(),+});+export const localScanIdSchema = localProjectSchema.extend({+ scanId: z.uuid(),+});+export const localLookupSchema = localProjectSchema.extend({+ query: z.string().trim().min(2).max(200),+});+export const localKeywordsSchema = z+ .array(z.string().trim().min(1).max(120))+ .max(20);+export const updateLocalKeywordsSchema = localTrackerIdSchema.extend({+ keywords: localKeywordsSchema,+});+export const createLocalTrackerSchema = localProjectSchema.extend({+ business: localBusinessSchema,+ keywords: localKeywordsSchema,+ gridSize: z.union([z.literal(3), z.literal(5)]),+ spacingKm: z.number().min(0.25).max(10),+});+export const startLocalCheckSchema = localTrackerIdSchema.extend({+ requestId: z.uuid(),+ maxCostCredits: z.number().int().nonnegative(),+});diff --git a/wrangler.jsonc b/wrangler.jsoncindex f7f03398..cbb84ba9 100644--- a/wrangler.jsonc+++ b/wrangler.jsonc@@ -43,6 +43,11 @@"binding": "AI_VISIBILITY_WORKFLOW","class_name": "AiVisibilityWorkflow",},+ {+ "name": "local-rank-workflow",+ "binding": "LOCAL_RANK_WORKFLOW",+ "class_name": "LocalRankWorkflow",+ },],// Durable Object backing the SAM in-app agent (Agents SDK AIChatAgent). One// instance per chat session; messages persist in the DO's SQLite.