# AdCenter sync flow

How a change in the DSP becomes a row AdCenter can serve, and how spend comes back.

The HTTP bodies are in [AdMedia sync API](admedia-sync-api.md). The trigger list, gates, and id map are in [AdCenter data flow](admedia-sync-data-flow.md).

A DSP **line item** is an AdCenter **campaign**. The DSP campaign is only a parent. AdCenter never sees it.

## Systems

```mermaid
flowchart LR
  UI["DSP UI"] --> API["api.dsp.com"]
  API --> DSPDB[("DSP MySQL<br/>dsp_*")]
  API -->|"push, same request"| AC["AdCenter v1<br/>adcenter.admedia.com"]
  AC --> ACDB[("AdCenter MySQL<br/>campaign, creatives,<br/>lists, Advertiser_budget")]
  AC -->|"reports"| API
  API --> DSPDB
```

Push is synchronous. The request that saved the DSP row calls AdCenter before it returns. There is no sync queue.

`ADMIN_SYNC_ENABLED` off installs a no-op. Writes stay in the DSP and nothing is posted. `isLineItemSyncLinked` then returns true, so local activation is not blocked on a remote id.

## Advertiser first

Entity calls need an AdCenter advertiser and that advertiser's `X-API-KEY`. Admin **advertiser verification** (Verified) creates the AdCenter account. Until then, entity writes wait in `dsp_admedia_entity_sync` as `DEFERRED`.

```mermaid
flowchart TD
  signup["DSP signup"] --> dspOnly["DSP advertiser only<br/>no admedia_adv_id"]
  verify["Admin verify advertiser"] --> pending["dsp_admedia_provision PENDING"]
  pending --> create["POST /v1/advertisers<br/>Basic auth"]
  create --> store["Store adv_id + api_key<br/>provision LINKED<br/>dsp_advertiser.admedia_adv_id"]
  store --> flush["flushDeferredForAdvertiser"]
  flush --> replay["Replay DEFERRED payments,<br/>lists, and line items"]
  profile["DSP profile address change"] --> patch["PATCH /v1/advertisers/{id}<br/>Basic auth"]
```

Username collision retries as `{company}-{dspAdvertiserId}`. Profile patch is not a row in `dsp_admedia_entity_sync`.

## What a line item pushes

Search text (`TEXT` + `SEARCH_TEXT_AD`) becomes campaign type `text-search`. Display becomes `display`. Other channels are not pushed.

Children are created or updated first. The campaign body then points at their AdCenter ids.

```mermaid
flowchart TD
  change["DSP save<br/>line item, creative, list, or targeting"] --> hook["admedia-sync/hooks.ts"]
  hook --> load["Load line item, approved creatives,<br/>targeting, provision"]
  load --> linked{"Advertiser LINKED<br/>and API key present?"}
  linked -->|no| defer["Mark line item DEFERRED"]
  linked -->|yes| children["Sync children"]
  children --> kw["Keyword lists"]
  children --> dom["Domain lists"]
  children --> src["Source lists"]
  children --> px["Retargeting pixels<br/>ids only, already created"]
  children --> cr["Approved creatives"]
  kw --> camp["POST or PATCH /v1/campaigns"]
  dom --> camp
  src --> camp
  px --> camp
  cr --> camp
  camp --> again["New campaign: PATCH the same body<br/>so freq_cap is stored"]
  again --> mark["SEARCH_TEXT_LINE_ITEM or<br/>DISPLAY_LINE_ITEM = LINKED<br/>admedia_entity_id = campaign.id"]
```

Order inside one line-item push:

1. Keyword lists, then domain lists, then source lists.
2. Look up retargeting pixel ids. Pixels are created earlier, in the pixel service, not here.
3. Approved creatives. Text ads send `type: text`. Display sends `type: image` and a public `image_url`.
4. Build targeting from those remote ids.
5. Create or update the campaign.
6. On create, update the campaign again with the same body. Serving reads `campaign.freq_cap`. The follow-up write stores the cap, including `0` for unlimited.

A line item that should no longer stay live is paused (`status: S`). The campaign is not deleted. Linked creatives are paused the same way.

## When the remote campaign is kept

```mermaid
flowchart TD
  item["Line item reconcile"] --> kind{"Channel"}
  kind -->|"TEXT + SEARCH_TEXT_AD"| charged{"charged_at set?"}
  kind -->|DISPLAY| live{"ACTIVE, channel enabled,<br/>approved image creative?"}
  kind -->|other| stop["Return. No remote write."]
  charged -->|no, and no remote id yet| skip["Do not create a campaign"]
  charged -->|no, remote id exists| pause["PATCH campaign and creatives to S"]
  charged -->|yes| push["Push campaign"]
  live -->|no, remote id exists| pause
  live -->|yes| push
  push --> active{"Allowed to serve now?"}
  active -->|yes| on["Creative status A<br/>Campaign A unless the line item<br/>is paused, archived, or completed"]
  active -->|no| off["Creative status S"]
```

Search text is allowed to serve only when funding is recorded, a targeting profile exists, an approved text creative exists, and the line item is eligible (status, dates, campaign window, channel enabled). Funding is recorded when `LINE_ITEM_FUNDING` is `LINKED`, or when `charged_at` is set and `card_charged` is `0` (the advertiser balance covered the flight, so no card credit was posted).

Display does not wait on that funding row. It stays live while the line item is active, the channel can be activated, and an approved image creative is attached.

## Money

Billing and delivery are different AdCenter tables. A credit writes `Advertiser_billing` and does not add to the spendable balance. An adjustment writes `Advertiser_budget`, which ads spend. A payment and a card-funded line item post both, with the same amount and comment.

```mermaid
flowchart TD
  paid["Wallet payment becomes PAID"] --> pay["syncPayment"]
  pay --> both1["POST billing/credits<br/>then POST billing/adjustments credit<br/>comment dsp-payment-{id}"]

  fund["Search-text card charge finalized"] --> funding["syncTextLineItemFunding"]
  funding --> both2["Same two calls<br/>comment dsp-line-item-funding-{id}<br/>amount = card charge"]
  funding --> recon["Then reconcile the line item<br/>so creatives can go active"]

  roll["Flight rollover"] --> adj["POST billing/adjustments only<br/>comment dsp-line-item-rollover-{id}"]
  adj --> net{"overspend minus unspent"}
  net -->|positive| credit["direction credit"]
  net -->|negative| debit["direction debit"]
  net -->|zero dollars| none["No call"]
```

Money is posted once. `claimPending` allows the call only when the sync row is missing or `DEFERRED`. A later `LINKED`, `PENDING`, or `FAILED` row is left alone. A 4xx marks `FAILED`. A timeout or 5xx leaves the row `PENDING` and must be checked in AdCenter before anyone posts that comment again.

## Back from AdCenter

```mermaid
flowchart LR
  cron["Dashboard pull<br/>about once an hour"] --> rep["GET /v1/reports<br/>X-API-KEY only"]
  rep --> stats["DSP dashboard stats<br/>trailing 7 days rewritten"]

  end["Search-text flight ended"] --> spent["GET /v1/reports/campaigns/{admediaCampaignId}"]
  spent --> final["dsp_line_item_final_spend"]
  final --> rollover["Rollover uses that spend<br/>then the budget adjustment above"]
```

Report calls send `X-API-KEY` only. An `Authorization` header switches AdCenter into admin impersonation and rejects the advertiser key.

The campaign id on the report is `dsp_admedia_entity_sync.admedia_entity_id` for `SEARCH_TEXT_LINE_ITEM`, not the DSP line item id.
