# Admedia API (v1.0.0-oas3)

## Public website inquiries

Website enquiry notification emails are disabled by default. Only
`WEBSITE_INQUIRY_EMAIL_ENABLED=true` enables sending for new submissions; false,
empty, or an absent key keeps them disabled. Other values are rejected at
configuration validation. Set `WEBSITE_INQUIRY_TO_EMAIL` for the primary inbox
and `WEBSITE_INQUIRY_CC_EMAILS` for comma-separated enquiry-only CC recipients.
Restart/reload the backend after changing these values. Disabling notifications
does not disable local persistence, HubSpot delivery/retries, or other DSP emails.
Enabling them later does not send notifications for previously saved enquiries.
HubSpot-managed email workflows are separate and must be controlled in HubSpot.

The DSP endpoint `POST /public/inquiries` is separate from the Advertisers API
documented below. Supported inquiry types are `home`, `agencies`,
`contact_advertiser`, `contact_agency`, `blog_demo`, `chat_advertiser`, and
`chat_agency`; all are eligible for HubSpot sync. Chat allows missing company and
surname and does not require spend, country, goal, or message. Other forms keep
their required fields. First/last names are capped at 100 characters; blog phone
numbers allow international formatting with 7-15 digits and are normalized.

Deploy this API before the corresponding chat frontend. The HubSpot portal must
have the existing attribution properties plus string properties
`adc_last_utm_term` and `adc_last_utm_content`. The mapper sends all five
first/last-touch UTMs, phone, and lead type, and sets `hs_lead_status=NEW` only
when the existing contact's status is blank. Company Name workflow behavior is
unchanged. Chat does not create an unnamed company or erase existing company/
surname values when those answers were not collected.

`cta_type` is a HubSpot dropdown with one option per ad.com CTA; first match wins:

| Lead                                                                 | `cta_type` value        | Label                    |
| -------------------------------------------------------------------- | ----------------------- | ------------------------ |
| Blog demo form                                                       | `request_demo`          | Request a demo           |
| An offer, or a Claim Offer CTA (`*-claim-offer`)                     | `claim_offer`           | Claim offer              |
| Chat widget (`chat_advertiser` / `chat_agency`)                      | `schedule_meeting`      | Schedule a meeting       |
| About Request a Demo (`about-request-demo`, `about-advertiser-demo`) | `request_demo`          | Request a demo           |
| Header Book a meeting (`header-book-meeting`)                        | `book_meeting`          | Book a meeting           |
| Page Talk to an expert (`*-talk-expert`)                             | `talk_to_expert`        | Talk to an expert        |
| Plan your campaign (`*-plan-campaign`)                               | `plan_campaign`         | Plan your campaign       |
| Plan your video campaign (`video-plan-video-campaign`)               | `plan_video_campaign`   | Plan your video campaign |
| Agencies Get started (`agencies-get-started*`)                       | `get_started`           | Get started              |
| Agencies Plan client campaigns                                       | `plan_client_campaigns` | Plan client campaigns    |
| Contact page with no CTA, or the footer Contact link                 | `request_consultation`  | Request a consultation   |
| Anything else                                                        | `contact_form`          | Send message             |

Every value must be an option on the portal's `cta_type` property before this is
deployed, or HubSpot rejects the contact update and the enquiry is marked
`failed`. `npm run hubspot:cta-type-options` adds the missing options (dry run
unless `-- --confirm`; needs `crm.schemas.contacts.write`) and never removes or
renames existing ones. The exact button is kept in `adc_cta_id` and
`ctx_placement`.

Contacts synced before this mapping keep "Send message" until they submit again.
`npm run hubspot:cta-type-backfill` re-maps them from each contact's newest synced
enquiry, writing only `cta_type` and only where it differs. It is a dry run unless
`-- --confirm` is passed; it needs `DATABASE_URL` and `HUBSPOT_ACCESS_TOKEN`.

Every enquiry also sends the shared lead context `ctx_*` (the same five text
properties every portal's forms fill in): `ctx_topic=sales`, `ctx_role=advertiser`,
`ctx_placement` (the CTA id, else `contact_page_direct` or `{formSource}_direct`),
`ctx_origin_page` (same as `adc_conversion_page`) and `ctx_product`. `ctx_product`
is `ad.com` for leads submitted on `ad.com`/`www.ad.com` and the submitting host
otherwise (for example `staging.ad.com`, `localhost`), taken from the browser
`Origin` header and stored as `site_host`; sales reports filter on
`ctx_product = ad.com` to leave test leads out. Older records without a stored
host omit `ctx_product`. New contacts are created with `lifecyclestage=lead`;
existing contacts keep their stage. Create the `ctx_*` properties once per portal,
before deploying, with the create-only script (run it twice: the second run must
only report `exists`):

```bash
HUBSPOT_ACCESS_TOKEN="$HUBSPOT_ACCESS_TOKEN" npm run hubspot:ctx-fields
```

Repeated enquiries use the real email by default
(`HUBSPOT_EMAIL_PREFIX_ENABLED=false`, including when the key is absent).
New enquiries search for and reuse the same HubSpot contact. Every distinct
submission creates its own associated timeline note containing the submitted
answers and attribution; contact properties show current values, not separate
enquiry records. First-touch fields and an existing lead status are preserved.
Retries retain the submission marker and contact/note checkpoints. If concurrent
submissions race to create a contact, an HTTP 409 is resolved by reading the
contact by email and updating it without overwriting its email or first touch.
These are Notes, not native HubSpot Forms submissions.

Rollback: set `HUBSPOT_EMAIL_PREFIX_ENABLED=true` and restart/reload the API with
the updated environment. The first local inquiry for an email keeps
the original HubSpot email. A later inquiry with the same email uses
`v{inquiryId}-{originalEmail}` for the HubSpot contact only. Earlier means a lower
local inquiry ID, regardless of sync status; retries of the same inquiry do not
count as new inquiries. Local records, notification reply-to addresses, company
domain selection, and the original email in submission notes remain unchanged.
Notes also include `hubspotEmail` when an alias is used; no custom contact
property is required. Checkpointed contacts retain their existing identity in
both modes, including historical prefixed contacts. Changing the flag does not
merge old contacts, move existing notes, or replay completed enquiries.

These are synthetic addresses, not verified customer mailboxes. Exclude these
contacts from outbound email and marketing workflows before enabling this
workaround in production. A `v{id}-` prefix is not a reserved namespace and cannot
guarantee no collision with real addresses. An existing alias without a saved
contact checkpoint is rejected for manual reconciliation rather than updating an
unrelated contact. Overlength addresses fail explicitly. Keep local inquiry
history for stable alias selection. This workaround does not fix missing HubSpot
properties; the UTM properties above are still required. Historical failed
inquiries are not automatically requeued.

The existing custom properties `adc_last_utm_term` and `adc_last_utm_content`
must exist as string/text contact properties. They can be provisioned once with
`POST /crm/v3/properties/contacts` using a private-app token authorized to write
contact schemas; normal enquiry delivery does not require schema-write access.
No new enquiry-specific custom property is needed: the full per-enquiry snapshot
is stored in the associated note.

To verify: submit three new enquiries using the same real email and distinct
answers. Expect three local records, one real-email HubSpot contact, and three
notes. Retrying the same submission key must not add another note. Test with
an email without earlier prefixed/checkpointed test enquiries for a clean count.

`HUBSPOT_SYNC_ENABLED` enables immediate delivery. Retries also require
`HUBSPOT_CRON_ENABLED`, global `CRONS_ENABLED`, and a configured access token.
The retry worker includes historical `blog_demo` records marked `skipped`, so
these are claimed and delivered once after deployment without a database
migration. Existing `failed` records are not automatically requeued. Sync is
disabled in the test environment.

HTTP 201 confirms local persistence. `data.hubspotPending=true` explicitly
indicates that HubSpot delivery is incomplete. Inspect the inquiry's
`hubspotSyncStatus`, `hubspotLastError`, and `hubspotNextRetryAt` when diagnosing
delivery; a successful browser response alone is not proof of CRM delivery.
Attribution fields are `firstTouch` and `lastTouch` (camelCase UTMs, max 512
characters), `dataCtaId`, `ctaPage`, and `submissionPage`.

## DSP pixel diagnostics

The DSP backend uses Fastify/Pino structured logs, not browser `console.log` calls.
With `LOG_LEVEL=info`, pixel script requests, recorded site beacons, pixel
creation/reuse, settings saves, verification outcomes, and conversion piggyback
scripts are visible. Warnings identify ignored beacons, unknown conversion
pixels, and inconclusive verification (status `UNVERIFIED`, not blocking).
Conversion fires are recorded via `GET /pixel/conversion/v1/{publicId}/beacon`
when the hosted wrapper runs in the browser (`conversion_pixel.fire_recorded`).
Unexpected verification errors are logged at error level.

After deploying the updated PM2 configuration, use
`pm2 startOrReload ecosystem.config.cjs --update-env` and
`pm2 logs api.dsp.com --lines 100`. Stdout is retained in `logs/pm2-out.log`
and stderr in `logs/pm2-error.log`; configure log rotation on the server for
high-traffic deployments. Set `LOG_LEVEL=info` (or `debug`) in the deployment
environment to include these events.

Filter structured events by the `site_pixel.` and `conversion_pixel.` prefixes.
Logs include pixel/entity IDs and request IDs where available, without adding
visitor IPs, user agents, full verification page URLs, or script contents to these
diagnostic events. Existing HTTP access/error logging is unchanged. A script
being served is not proof that AdMedia recorded a conversion. The conversion
wrapper injects `https://pixel.admedia.com/w.php` in the browser so the
visitor's AdMedia cookie is sent; the API does not fetch that script.

Advertisers API. Contact: developers@admedia.com

- **Base URL:** `https://apiad.admedia.com/v1`
- **Auth:** every endpoint needs an API key in the `X-API-KEY` header.

The DSP sync client uses a subset of this API plus Basic-auth advertiser and billing routes. Request and response bodies for those calls are in [AdMedia sync API](../admedia-sync-api.md). The 27–29 Oct payment and budget changes are in [Recent payment and budget changes](../admedia-billing-context.md).

## Sections

| Doc                                       | Endpoints                                                                    |
| ----------------------------------------- | ---------------------------------------------------------------------------- |
| [Campaigns](campaigns.md)                 | `/campaigns`, `/campaigns/{campaignId}`, `/campaigns/{campaignId}/creatives` |
| [Creatives](creatives.md)                 | `/creatives`, `/creatives/{creativeId}`, `/creatives/sizes`                  |
| [Reports](reports.md)                     | `/reports/summary`, `/reports/campaigns`, `/reports/creatives`               |
| [Domains Lists](domains-lists.md)         | `/lists/domains`                                                             |
| [Keywords Lists](keywords-lists.md)       | `/lists/keywords`                                                            |
| [Sources Lists](sources-lists.md)         | `/lists/sources`                                                             |
| [Retargeting Pixel](retargeting-pixel.md) | `/pixels/retargeting`                                                        |
| [Channels](channels.md)                   | `/channels`                                                                  |
| [Schemas](schemas.md)                     | Data models                                                                  |

## Common list query params

`search` (keyword), `order` (`field:asc|desc,...`, e.g. `name:asc,bid:desc`), `offset` (default 0), `limit` (default 20).

## Common error codes

| Code | Meaning                                                |
| ---- | ------------------------------------------------------ |
| 400  | Request cannot be fulfilled due to errors / invalid ID |
| 404  | Resource not found                                     |
| 405  | Validation exception                                   |
| 422  | Unprocessable entity                                   |
