# AdCenter data flow

Read this before changing how the DSP and AdCenter stay in step. Diagrams are in [AdCenter sync flow](admedia-sync-flow.md). Request and response JSON is in [AdMedia sync API](admedia-sync-api.md).

## The two stores

| Side     | Process                | Database               | What it owns                                                                                               |
| -------- | ---------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------- |
| DSP      | `api.dsp.com`          | Prisma `dsp_*` tables  | Advertisers, campaigns, line items, creatives, lists, payments, the id map                                 |
| AdCenter | `adcenter.admedia.com` | Legacy AdCenter tables | The account that serves, `campaign`, `creatives`, lists, pixels, `Advertiser_budget`, `Advertiser_billing` |

The DSP is the place the product UI writes. AdCenter is where search-text and display ads are served. Sync copies a slice of the DSP row into AdCenter at the moment of the write. It does not replicate the DSP schema.

Base URL is `ADMEDIA_API_BASE_URL` (default `https://apiad.admedia.com/v1`). AdCenter routes live in `adcenter.admedia.com/html/app/Config/Routes.php`.

## Switch

`configureAdminSync` in `src/modules/admedia-sync/runtime.ts` runs at startup.

| `ADMIN_SYNC_ENABLED` | What runs                                                                                                      |
| -------------------- | -------------------------------------------------------------------------------------------------------------- |
| off                  | `noopAdmediaEntitySyncService` and `skippedAdmediaProvision`. No HTTP. `isLineItemSyncLinked` returns true.    |
| on                   | Real client, provision service, entity sync. Signup's `onAdvertiserLinked` calls `flushDeferredForAdvertiser`. |

Domain modules must call `src/modules/admedia-sync/hooks.ts`. They should not construct the API client or write `dsp_admedia_entity_sync` themselves. The retargeting-pixel create path is the exception: it creates the remote pixel, then marks the sync row `LINKED`.

## Identity

Two DSP tables are the map. AdCenter does not store DSP ids.

`dsp_admedia_provision` — one row per DSP advertiser.

| Column              | Meaning                                                                   |
| ------------------- | ------------------------------------------------------------------------- |
| `dsp_advertiser_id` | DSP advertiser                                                            |
| `admedia_login`     | Username sent as `accountid`                                              |
| `admedia_adv_id`    | AdCenter advertiser id. Also copied onto `dsp_advertiser.admedia_adv_id`  |
| `admedia_api_key`   | Sent as `X-API-KEY`                                                       |
| `status`            | `PENDING` until create returns both `adv_id` and `api_key`, then `LINKED` |

`dsp_admedia_entity_sync` — one row per `(entity_type, dsp_entity_id)`.

| Column              | Meaning                                                                |
| ------------------- | ---------------------------------------------------------------------- |
| `entity_type`       | See the type table below                                               |
| `dsp_entity_id`     | Id in the DSP table for that type                                      |
| `admedia_entity_id` | AdCenter id. Null for money rows, and for a list after AdCenter delete |
| `status`            | `PENDING`, `LINKED`, `FAILED`, `DEFERRED`                              |
| `last_error`        | Last failure text, capped at 2000 characters                           |

| `entity_type`           | DSP id is                  | AdCenter id is                                  |
| ----------------------- | -------------------------- | ----------------------------------------------- |
| `PAYMENT`               | `dsp_payment.id`           | null. The comment `dsp-payment-{id}` is the key |
| `LINE_ITEM_FUNDING`     | `dsp_line_item.id`         | null. Comment `dsp-line-item-funding-{id}`      |
| `LINE_ITEM_ROLLOVER`    | `dsp_line_item.id`         | null. Comment `dsp-line-item-rollover-{id}`     |
| `SEARCH_TEXT_LINE_ITEM` | `dsp_line_item.id`         | `campaign.id`                                   |
| `DISPLAY_LINE_ITEM`     | `dsp_line_item.id`         | `campaign.id`                                   |
| `CREATIVE`              | `dsp_creative.id`          | `creatives.id`                                  |
| `KEYWORD_LIST`          | `dsp_keyword_list.id`      | keyword list id                                 |
| `DOMAIN_LIST`           | `dsp_domain_list.id`       | domain list id                                  |
| `SOURCE_LIST`           | `dsp_source_list.id`       | source list id                                  |
| `RETARGETING_PIXEL`     | `dsp_retargeting_pixel.id` | `Advertiser_retargeting_pixel.id`               |

One DSP line item has up to three sync rows: the campaign row (`SEARCH_TEXT_LINE_ITEM` or `DISPLAY_LINE_ITEM`), plus optional `LINE_ITEM_FUNDING` and `LINE_ITEM_ROLLOVER`. Those three must not be collapsed. Final-spend lookup uses only `SEARCH_TEXT_LINE_ITEM.admedia_entity_id`.

A missing API key on a linked provision is loaded with `GET /v1/advertisers/{adv_id}` and stored.

## Auth on the wire

| Call                                                   | Header                                                                              |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------- |
| Advertiser create, get, update, budget, billing        | `Authorization: Basic` from `ADMEDIA_API_BASIC_USER` / `ADMEDIA_API_BASIC_PASSWORD` |
| Campaigns, creatives, lists, pixels, channels, reports | `X-API-KEY` of that advertiser                                                      |

Do not send both. A report with `Authorization` is treated as admin impersonation and the advertiser key is rejected.

## Who starts a push

Hooks run after the DSP transaction commits. A thrown sync error does not roll the DSP row back, except funding and rollover, which rethrow after a 4xx or a transport failure. The payment activation hook catches the funding error and logs it.

| DSP action                                                             | Hook                                                                                       | AdCenter effect                                                 |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | --------------------------------------------------------------- |
| Admin advertiser verify (Verified)                                     | `provisionOnVerify`                                                                        | `POST /v1/advertisers`, then flush deferred rows                |
| Verified + not LINKED (failed verify or sync was off)                  | `sweepAdmediaProvisionRetries` cron                                                        | Same as verify; idempotent `provisionOnVerify` per advertiser   |
| Profile address change                                                 | `syncProfileAddress`                                                                       | `PATCH /v1/advertisers/{id}`                                    |
| Wallet payment reaches `PAID`                                          | `onPaymentPaid`                                                                            | Billing credit and budget credit                                |
| Search-text charge finalized                                           | `onTextLineItemFunded`                                                                     | Funding credit, then line-item reconcile                        |
| Rollover of a search-text flight                                       | `applyTextLineItemRolloverAdjustments`                                                     | One budget adjustment per line item                             |
| Line item update, archive, activate, pause                             | `reconcileAdmediaLineItem`                                                                 | Create, update, or pause the campaign                           |
| Campaign activate                                                      | `reconcileSearchTextLineItems`                                                             | Search-text line items only, then funding                       |
| Creative save, attach, detach, approval                                | `reconcileSearchTextLineItemsForCreative` or `reconcileAdmediaLineItem`                    | Every line item that uses the creative                          |
| Targeting profile save                                                 | `reconcileAdmediaLineItem`                                                                 | That line item                                                  |
| Text-ads conversion pixel change                                       | `reconcileAdmediaLineItem`                                                                 | That line item                                                  |
| Keyword, domain, or source list create / update / archive / membership | `reconcileSearchTextLineItemsForKeywordList`, `reconcileDomainList`, `reconcileSourceList` | The list, then every line item whose targeting uses it          |
| Retargeting pixel create                                               | pixel service, not a hook                                                                  | `POST /v1/pixels/retargeting`, then local insert, then `LINKED` |

`reconcileAdmediaLineItem` loads the line item and branches:

- `TEXT` and subtype `SEARCH_TEXT_AD` → `syncSearchTextLineItem`
- `DISPLAY` → `syncDisplayLineItem`
- anything else → return

`reconcileSearchTextLineItems` does not take that branch. It only calls `syncSearchTextLineItem`. Campaign activate uses that function, so a display line item that becomes active only because its parent campaign was activated is not pushed there. Display is pushed from the line-item, creative, targeting, and list hooks.

Campaign pause updates the DSP campaign status and does not call a hook. AdCenter changes when a later line-item reconcile runs. Search-text eligibility does include the parent campaign's status and dates, so that later reconcile can pause the remote campaign. Display's live check looks at the line item, not the parent campaign.

## Line-item push, in order

`syncLineItemCampaign` in `admedia-entity-sync.service.ts`.

1. `loadLineItemSyncContext`. Returns null if the line item or advertiser is missing. The predicate then drops the wrong channel.
2. If `admedia_adv_id` or the provision login is missing, or the API key cannot be resolved, upsert `DEFERRED` and return.
3. Decide `maintainRemote` and `remoteActive` (next section).
4. If the line item should not be maintained and no remote campaign exists, return without a write.
5. If it should not be maintained and a remote campaign exists, `PATCH` that campaign with `status: S` and no creatives or targeting, then `PATCH` each linked creative to `S`. Mark the line item `LINKED` again.
6. Otherwise `ensurePending`, then sync children, then create or update the campaign.

Child work, only on the maintain path:

| Child             | Rule                                                                                                                                                                                                                                                                                                                                       |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Keyword list      | Create or update. Name cut to 100 characters. `type` on the wire is always `broad`. `bid` is the line item bid when that bid is at least `0.007`, otherwise `0.007`. A list sync started from the list service, with no line item in hand, uses `0.007`. `NEGATIVE` lists go to `targeting.keyword_lists.exclude`. Others go to `include`. |
| Domain list       | Name cut to 100. `BLOCK` → `domain_lists.exclude`. Others → `include`.                                                                                                                                                                                                                                                                     |
| Source list       | Name cut to 100. Each member is `{ source, bid }`. Ids go to `targeting.source_lists` as a flat array.                                                                                                                                                                                                                                     |
| Retargeting pixel | No create here. Ids already on a `LINKED` row go to `targeting.retargeting.ids`. Logic defaults to `or`.                                                                                                                                                                                                                                   |
| Creative          | Approved only. Text: name, destination, title, description, display URL. Image: public asset URL and `{width}x{height}`. Status `A` when `remoteActive` is true, otherwise `S`. A failed creative is marked `FAILED` and omitted from `creatives`. The campaign can still be marked `LINKED`. The next reconcile tries the creative again. |

Archived keyword, domain, and source lists are deleted in AdCenter when a remote id exists, then the sync row is `LINKED` with a null remote id. They are not paused.

Campaign fields:

| AdCenter field           | DSP source                                                                                |
| ------------------------ | ----------------------------------------------------------------------------------------- |
| `name`                   | Line item name                                                                            |
| `type`                   | `text-search` or `display`                                                                |
| `bid`, `budget`          | Line item amounts, micros converted to dollars                                            |
| `status`                 | `S` when the line item is `PAUSED`, `ARCHIVED`, or `COMPLETED`. Otherwise `A`             |
| `start_date`, `end_date` | Line item dates, `YYYY-MM-DD`. A missing end date sends the start date                    |
| `creatives`              | Remote creative ids from this push                                                        |
| `targeting`              | Omitted when empty. `frequency` is always set when targeting is sent. `0` means unlimited |

Targeting value map (devices, browsers, OS, connection, environment, geo, pacing) is in the sync API doc. Countries are sent as alpha-3. Sync does not send `categories`, `makers`, `models`, `ron`, or `schedule`.

AdCenter `CampaignController::create` inserts `campaign`, links creatives, writes `campaign_targeting.json`, and copies `frequency` onto `campaign.freq_cap`. Serving reads `freq_cap`. `text-search` is stored as `campaign_type = 2`, `campaign_mode = CPC`. `display` is `campaign_type = 1`, `campaign_mode = CPM`. The DSP still `PATCH`es immediately after `POST` so the cap, including unlimited `0`, is stored.

Paused, archived, and completed line items are not deleted. `DELETE /v1/campaigns/{id}` exists on the client and is unused by entity sync.

## Gates

Search text (`isSearchTextAdLineItem`): channel `TEXT` and subtype `SEARCH_TEXT_AD`.

| Question                                     | Search text                                                                                                                                                                                                    | Display                                                                                                    |
| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| Create or keep updating the remote campaign? | `charged_at` is set                                                                                                                                                                                            | Channel activation is enabled, line item is `ACTIVE`, and at least one approved image creative is attached |
| Creative status `A`?                         | Funding is recorded, a targeting profile exists, an approved text creative exists, and `isLineItemEligibleToServe` is true (line item status, flight dates, parent campaign status and dates, channel enabled) | The maintain check above is true and the line item is not `PAUSED`                                         |
| Funding recorded?                            | `LINE_ITEM_FUNDING` is `LINKED`, or `charged_at` is set and `card_charged` is `0`                                                                                                                              | Not required                                                                                               |

`card_charged = 0` with `charged_at` set means the advertiser balance covered the flight. No funding credit is posted, and the campaign may still go active.

Channel activation off (`isChannelActivationEnabled`) blocks display from being maintained. Search text uses the same flag inside eligibility, so a funded search-text line item on a disabled channel is pushed with creatives at `S`.

## Money, in detail

Amounts are two-decimal dollar strings. Comments are exact. AdCenter does not dedupe on comment. A second credit inserts another `Advertiser_billing` row, and a second adjustment adds the amount to `Advertiser_budget` again. That is why a retry after an uncertain response is unsafe: the DSP lock is what stops the second post, not AdCenter.

| Event                                         | Calls                                                                                    | Amount                                                                                                                                                 | Comment                               |
| --------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- |
| `dsp_payment.status = PAID` and amount &gt; 0 | `POST .../billing/credits`, then `POST .../billing/adjustments` with `direction: credit` | Payment amount                                                                                                                                         | `dsp-payment-{paymentId}`             |
| Search-text line item just charged            | Same two calls                                                                           | `card_charged` when it is stored and &gt; 0. If `card_charged` is null, remaining budget. If `card_charged` is `0`, no call                            | `dsp-line-item-funding-{lineItemId}`  |
| Rollover                                      | Adjustments only                                                                         | Absolute value of overspend dollars minus unspent dollars. Positive net is `credit`. Negative net is `debit`. A net that formats as `0.00` is not sent | `dsp-line-item-rollover-{lineItemId}` |

AdCenter, `AdvertiserBudgetApiService`:

- A credit inserts `Advertiser_billing` as Terms extended. It does not add that amount to `Advertiser_budget`. The first credit inserts an `Advertiser_budget` row at `0` so the funds cron has a row.
- An adjustment updates `Advertiser_budget` and does not insert a billing row. A debit stops at zero (`clamped: true` is still success; sync logs a warning).
- The funds cron rebuilds `Advertiser_budget` from billing rows, so an adjustment alone lasts until that cron. The DSP posts the credit and the adjustment together so delivery can spend immediately and the ledger still has the credit.
- A credit against an advertiser that already has a prepaid balance is rejected (`MIXED_EXTENSION`).

`claimPending` is the once-only lock for the three money types:

- No row: insert `PENDING`, return true, then call AdCenter.
- Row is `DEFERRED`: move to `PENDING`, return true.
- Row is `PENDING`, `LINKED`, or `FAILED`: return false. The call is skipped.

`syncPayment` also returns immediately when the row is already `PENDING`, `LINKED`, or `FAILED`, before the claim.

After the HTTP calls succeed, the row becomes `LINKED` with a null remote id.

Failure:

| Result         | What the code does                                                                                                     | What a person should do                                                                                                                                                  |
| -------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| HTTP 4xx       | `FAILED` and `last_error`. Funding and rollover rethrow. Payment does not.                                             | Fix the cause. Do not post the same comment again until AdCenter shows whether the row landed. Clearing `FAILED` is what allows another attempt.                         |
| Timeout or 5xx | Row stays `PENDING`. Log says it must not be posted again until someone checks AdCenter. Funding and rollover rethrow. | Look up the comment in `Advertiser_billing` / `Advertiser_budget`. If the write landed, mark the DSP row `LINKED`. If it did not, that is the only time a retry is safe. |

Funding and rollover do not defer. If the advertiser is not linked, they return without a sync row. A later flush will not invent that credit. Payment does defer, and flush will post it after link.

`scripts/admedia-backfill-billing-sync.ts` marks `LINE_ITEM_FUNDING` and `LINE_ITEM_ROLLOVER` `LINKED` from comments already in `Advertiser_billing`. It does not call AdCenter and does not touch `PAYMENT`.

## Status

| Status     | How it is reached                                                    | Next reconcile                                                                                    |
| ---------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `DEFERRED` | Advertiser not linked, or API key missing                            | Flush after provision `LINKED`, or the next entity save once a key exists                         |
| `PENDING`  | Claimed for money, or `ensurePending` before a campaign or list call | Money: skipped. Campaigns and lists: the next save calls `ensurePending` again and retries        |
| `LINKED`   | AdCenter accepted the write                                          | Campaigns and lists are updated in place. Money is not posted again                               |
| `FAILED`   | 4xx, or a campaign/list/creative exception                           | Money: skipped until the row changes. Campaigns, lists, and creatives: the next reconcile retries |

`flushDeferredForAdvertiser` replays `DEFERRED` rows of type `PAYMENT`, `SEARCH_TEXT_LINE_ITEM`, `DISPLAY_LINE_ITEM`, `KEYWORD_LIST`, `DOMAIN_LIST`, and `SOURCE_LIST`. It then pushes active search-text and display line items that are not already `LINKED`. It does not replay `CREATIVE`, `RETARGETING_PIXEL`, `LINE_ITEM_FUNDING`, or `LINE_ITEM_ROLLOVER`. Creatives are created as part of the line-item push.

## Pull back into the DSP

These reads do not update AdCenter.

| Job              | Call                                                                                                                           | Writes                      | Notes                                                                                                                                                                                                        |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Dashboard pull   | `GET /v1/reports?format=campaigns,hourly`, then `GET /v1/reports/campaigns?format=daily` if hourly is rejected or has no hours | Dashboard stat rows         | `DASHBOARD_PULL_ENABLED` and crons on. About once an hour, Redis lock `dashboardReportingPull`. Rewrites the trailing 7 days because AdCenter revises recent days.                                           |
| Text final spend | `GET /v1/reports/campaigns/{admediaCampaignId}`                                                                                | `dsp_line_item_final_spend` | Uses the `SEARCH_TEXT_LINE_ITEM` remote id. If that id is missing, the capture returns `RETRY`. After the capture window the row is `MISSED`. Rollover then turns captured spend into the budget adjustment. |

Join path for a dashboard or spend number: DSP line item → `dsp_admedia_entity_sync` where `entity_type` is `SEARCH_TEXT_LINE_ITEM` or `DISPLAY_LINE_ITEM` → `admedia_entity_id` → AdCenter `campaign.id` on the report.

## Files

| Question                          | File                                                                                               |
| --------------------------------- | -------------------------------------------------------------------------------------------------- |
| Which service method runs?        | `src/modules/admedia-sync/hooks.ts`                                                                |
| Is sync installed?                | `src/modules/admedia-sync/runtime.ts`                                                              |
| Payload, order, money, flush      | `src/modules/admedia-entity-sync/admedia-entity-sync.service.ts`                                   |
| What "ready" means                | `src/modules/admedia-entity-sync/admedia-entity-sync.loader.ts`                                    |
| Dollar amounts and comments       | `src/modules/admedia-entity-sync/admedia-entity-sync.admin.ts`                                     |
| Sync row writes                   | `src/modules/admedia-entity-sync/admedia-entity-sync.collection.ts`                                |
| Targeting JSON                    | `src/modules/admedia-entity-sync/admedia-targeting.map.ts`                                         |
| HTTP                              | `src/modules/admedia-api/admedia-api.client.ts`                                                    |
| Verify-time provision and profile | `src/modules/admedia-provision/admedia-provision.service.ts`                                       |
| AdCenter routes                   | `adcenter.admedia.com/html/app/Config/Routes.php`                                                  |
| AdCenter campaign row             | `adcenter.admedia.com/html/app/Controllers/Api/CampaignController.php`, `Models/CampaignModel.php` |
| AdCenter balance                  | `adcenter.admedia.com/html/app/Services/Advertiser/AdvertiserBudgetApiService.php`                 |

## Do not assume

- A DSP campaign id is not an AdCenter campaign id. The line item id is not either. The AdCenter campaign id is `admedia_entity_id`.
- Native, video, social, pop, shopping, and zip lists are not part of this sync.
- Sync does not delete campaigns. It pauses them.
- Turning `ADMIN_SYNC_ENABLED` off does not fail activation. The no-op reports every line item as linked.
- Posting a money comment twice is worse than leaving a row `PENDING`. Check AdCenter before changing that row.
- `scripts/admedia-sync-reconciled-entities.ts` is a one-off for DSP advertisers 8–17. It clears old remote ids and pushes again. It is not the steady-state job.
