# Geo location data — simple guide (ADCM-242)

This guide explains:

1. What happens to **existing database records**
2. What the **migration** does (and does not do)
3. How to **update CSV files later** and load them into the DB

---

## 1. Existing DB records — what happens?

### Saved advertiser targeting (campaigns / profiles)

Tables like:

- `dsp_targeting_geo_country`
- `dsp_targeting_geo_state`
- `dsp_targeting_geo_city`
- `dsp_targeting_geo_dma`
- `dsp_targeting_geo_zip`

**Nothing changes here.**

- Old saved countries, states, cities, DMAs, ZIPs stay as they are.
- The loader **never** updates or deletes these rows.
- Existing campaigns and targeting profiles keep working.

### Location catalog (the dropdown / search lists)

Tables like:

- `dsp_ref_geo_country`
- `dsp_ref_geo_state`
- `dsp_ref_geo_city`
- `dsp_ref_geo_dma`
- `dsp_ref_geo_city_alias`

These are the **lists** advertisers search from.

| Change in CSV                                                 | What happens in DB                                         |
| ------------------------------------------------------------- | ---------------------------------------------------------- |
| **New** row                                                   | Inserted                                                   |
| **Updated** row (same id/code/`value`)                        | Updated (label, codes, etc.)                               |
| **Removed** from a full, valid CSV                            | Marked `is_active = false` (not deleted)                   |
| Original seed values (16 countries, 12 cities, 12 DMAs, etc.) | Kept with the **same `value`** so old profiles still match |

**Important:** We do **not** delete catalog rows. We only turn them off (`is_active = false`) if they disappear from a complete new file. Old profiles that already used them stay valid.

---

## 2. Migration — runtime risk?

Migration file: Prisma migration under `prisma/migrations/` for ADCM-242 geo columns.

### What migration does

- **Adds** new columns (example: `alpha2`, `geonames_id`, `country_code`, `population`, …)
- **Adds** indexes
- **Creates** `dsp_ref_geo_city_alias` if needed

### What migration does **not** do

- Does **not** drop targeting tables
- Does **not** truncate catalog tables
- Does **not** change saved profile geo selections
- Does **not** rename primary keys of existing targeting rows

### Runtime impact

- Migration is **additive** (safe for existing data).
- Brief lock time while `ALTER TABLE` runs — normal for MySQL; run in a maintenance window if the DB is large.
- After migration, until you run `npm run geo:load`, the app still works with the old seed-sized lists; new columns stay empty/null until load.

**Order:**

1. Run migration
2. Run geo load

Geo typeahead is DB-backed (max 20). No Redis geo cache (not in ADCM-242).

---

## 3. How data “syncs” with a new update

Think of it as: **CSV is the source → loader syncs catalog tables.**

Match keys (stable IDs — not names alone):

| Data    | Matched by                                                 |
| ------- | ---------------------------------------------------------- |
| Country | `value` (English name, e.g. `United States`)               |
| State   | `value` (e.g. `California`) + ISO `code` stored on the row |
| City    | `geonames_id` (preferred), else preserved `value`          |
| DMA     | `value` (DMA code, e.g. `501`)                             |

Flow:

```text
Edit / rebuild CSV
    → npm run geo:load:dry-run   (optional check)
    → npm run geo:load           (write to DB; typeahead reads DB live)
```

---

## 4. Future CSV updates — how to run

Work from **`api.dsp.com`** (not the UI repo).

### A. Only small CSV edits (countries / states / DMAs)

1. Edit the file in `data/geo/`:
   - `geo_countries.csv`
   - `geo_states.csv`
   - `geo_dmas.csv`
2. Dry run:

```bash
npm run geo:load:dry-run
```

3. Real load:

```bash
npm run geo:load
```

### B. Cities changed (or full rebuild from GeoNames)

1. Put fresh dumps in `data/geo/raw/` if needed (`cities5000.txt`, admin files).
2. Rebuild city CSVs:

```bash
npm run geo:build
```

Optional build settings (no code change to lower the threshold later):

```bash
# Use a denser GeoNames dump when you add it under data/geo/raw/
GEO_CITIES_FILE=cities1000.txt npm run geo:build -- cities

# Or keep cities5000 but drop rows below a population floor
GEO_CITY_MIN_POPULATION=1000 npm run geo:build -- cities
```

With the default `cities5000.txt` and no population floor, written rows must equal the source file row count (acceptance criterion).

3. Then:

```bash
npm run geo:load:dry-run
npm run geo:load
```

4. Restart the API.

### C. What each command means (simple words)

| Command                    | Meaning                                                       |
| -------------------------- | ------------------------------------------------------------- |
| `npm run geo:build`        | Rebuilds CSV files from raw GeoNames / Radar sources          |
| `npm run geo:load:dry-run` | Reads CSVs and reports what would change — **does not write** |
| `npm run geo:load`         | Writes catalog changes to the DB (safe upsert)                |

---

## 5. Add / update / delete in CSV — simple rules

### Add

- Add a new row with a **new** stable id (`value` / `geonames_id` / DMA code).
- Run `geo:load` → row is **inserted**.

### Update

- Keep the same stable id.
- Change label or other fields.
- Run `geo:load` → row is **updated**.

### Delete (remove from list)

- Remove the row from the CSV (file must still be **complete and valid**).
- Run `geo:load` → row is set to **`is_active = false`** (not hard-deleted).
- It will not show in new searches.
- Old profiles that already saved it are **not** broken.

**Never** hand-delete rows from `dsp_targeting_geo_*` for this feature.

---

## 6. Safety checklist before `geo:load`

- [ ] Migration already applied on this database
- [ ] CSV files look complete (especially cities count matches source when rebuilding)
- [ ] Ran `geo:load:dry-run` and counts look sensible
- [ ] Not deleting / truncating targeting profile tables
- [ ] Confirm Display/Video state/city pickers are US-only after load

---

## 7. Files in this folder

| File                         | Purpose                                                                |
| ---------------------------- | ---------------------------------------------------------------------- |
| `geo_countries.csv`          | All 249 ISO 3166-1 countries (US/CA/MX first; DV flag on those three)  |
| `geo_states.csv`             | Full ISO 3166-2 **top-level** subdivisions (includes all 50 US states) |
| `geo_states_us.csv`          | Jira checklist: exactly **50** US states (loader validates subset)     |
| `geo_dmas.csv`               | All US DMAs                                                            |
| `geo_cities.csv`             | Cities (GeoNames cities5000 + preserved seed values)                   |
| `geo_city_aliases.csv`       | Search aliases (e.g. NYC)                                              |
| `geo_admin1_iso_map.csv`     | GeoNames region → ISO code map (US/CA/MX)                              |
| `meta/dataset-versions.json` | Source version + row counts                                            |
| `raw/`                       | Optional download inputs for `geo:build`                               |

City data © [GeoNames](https://www.geonames.org/), [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).

---

## 8. Quick answers

**Will migration break existing records?**  
No. It only adds columns/tables. It does not rewrite saved targeting.

**Will `geo:load` change saved campaigns?**  
No. It only updates the **catalog** lists.

**Can we remove a city from the product?**  
Remove it from the CSV and load again. It becomes inactive in the catalog; existing saved values stay in profiles.

**Do we need to rebuild CSVs every time?**  
Only when you want a full refresh from GeoNames/Radar. For small list edits, change the CSV and run `geo:load`.
