# Marketing

Campaign popups the merchant runs from Marketing. A campaign is a popup:
it asks what the visitor came for, takes
their email with their consent, and a welcome mail with a code follows. A
storefront does two things with it: it shows the popup to the right
visitors at the right moment, and it signs the person up through one door.
The platform does the rest: the customer, the consent, the intent tag, the
welcome mail.

## How the popup behaves

- **Who sees it and when** is the campaign's `targeting`: the pages, the
  delay or the scroll depth, exit intent, the device, the page views
  before it may open. The package's `<PromoPopup>` applies all of it in the
  browser.
- **Once per person.** A dismissal keeps the popup away for
  `frequency_cap_days`; a signup keeps it away for good, and a tab on the
  page's edge (`reopen_label`) brings it back for those who dismissed it.
  The package keeps both per browser.
- **The question screen** shows the campaign's `options`; the chosen
  answer's slug goes back as `intent` with the signup and becomes the
  customer's tag `intent:<slug>`, which the merchant's smart groups read.
  No options, no question screen.
- **Consent is explicit.** The email screen carries the consent box
  (`consent_text`), ticked by the person; a signup without `consent: true`
  is refused. The welcome mail and every later marketing mail depend on it,
  and the person can leave through the mail's unsubscribe link
  ([customers.md](customers.md), the unsubscribe door).
- **One arm of an experiment.** A campaign may name an `experiment`; show it
  to the visitors assigned that `variant` alone (`useExperiment(key)`), and
  to nobody else. Null shows it to everyone.
- **The discount to promise.** `welcome_email.discount` is what the welcome
  mail's code grants, read off the merchant's promotion; print it in the
  popup's words. Null when the mail carries no code.

## GET /api/store/marketing/campaigns: the live campaigns

- **Purpose**: the live campaigns with everything the popup needs.
- **Auth**: anon (`x-client-id` or the publishable key).
- **Request**: no params.
- **Response**:

```jsonc
{
  "campaigns": [
    {
      "id": "mcamp_01K…",
      "name": "October popup",             // for the storefront's own tracking
      "targeting": {
        "pages": { "mode": "all", "paths": [] },  // all | home | products | collections | paths
        "delay_seconds": 5,
        "scroll_percent": null,               // opens at this depth instead of the delay
        "exit_intent": false,
        "frequency_cap_days": 7,              // a dismissal keeps it away this long; 0 is every visit
        "device": "all",                      // all | mobile | desktop
        "min_page_views": 0
      },
      "copy": {                               // per locale code; pick yours, else the first
        "bg": {
          "heading": "За какво сте тук?",
          "body": null,
          "options": [                        // none skips the question screen
            { "label": "Суха кожа", "intent": "dry-skin" },
            { "label": "Подарък", "intent": "gift" }
          ],
          "dismiss_label": null,
          "email_heading": null,
          "email_body": null,
          "email_placeholder": null,
          "email_button": null,
          "consent_text": null,
          "thanks_heading": null,
          "thanks_body": null,
          "thanks_button": null,
          "reopen_label": null                // a null field: the package's own words
        }
      },
      "welcome_email": {
        "enabled": true,
        "discount": { "type": "percentage", "value": 10, "currency_code": null }  // or null
      },
      "experiment": null                      // or { "key": "popup-test", "variant": "soft" }
    }
  ]
}
```

- **Errors**: `400 missing_client_id`.
- **SDK**: `marketing.listCampaigns(client)` (`@cartbase/storefront/api/marketing`).
- **Components**: `<PromoPopup client />` (`@cartbase/storefront/marketing`)
  reads it once and shows the first campaign the visitor qualifies for
  ([components.md](components.md), family marketing); the unsubscribe
  link's page is `<UnsubscribePage client />` of the same family.

```bash
# The store's live campaigns: a list, empty while nothing is live.
BODY=$(curl -sf "$BASE/api/store/marketing/campaigns" -H "x-client-id: $CLIENT_ID")
echo "$BODY" | node -e 'const b=JSON.parse(require("fs").readFileSync(0,"utf8")); if(!Array.isArray(b.campaigns)) process.exit(1)'
```

## POST /api/store/marketing/signup: the signup door

- **Purpose**: the popup's submit.
- **Auth**: anon (`x-client-id` or the publishable key).
- **Request**:

```jsonc
{
  "campaign_id": "mcamp_01K…",
  "email": "maria@example.com",
  "intent": "dry-skin",        // optional: the chosen answer's slug
  "device": "mobile",          // optional: mobile | desktop
  "device_id": "4f6c…",        // optional: the visitor cookie, for the analytics profile
  "consent": true              // the ticked box; required
}
```

- **Response**: `{ "ok": true }`.
- What happens, in this order: the customer is found by the email or born
  as a guest; the consent becomes the customer's email marketing state,
  `subscribed`, source `signup` (a person who had unsubscribed and ticks the
  box has subscribed again); the intent becomes the tag `intent:<slug>`;
  one signup row per campaign per person; the welcome mail goes when the
  campaign has one, with its code. A second signup of the same person
  through the same campaign is answered ok and changes nothing, so the
  welcome never goes twice.
- A campaign that is not live (paused, archived, unknown) is answered ok
  and nothing is written: a stale popup is not the shopper's problem.
- Call it from the shopper's browser: a declared bot (any user agent that
  is not a browser's, a server or a script included) is answered and never
  written.
- **Errors**: `400 consent_required` (the box was not ticked), `400
  invalid_email`, `400 invalid_data` (a bad intent), `400 validation_failed`
  (a missing field), `429 rate_limited` (5 signups per email and 20 per
  address in 15 minutes), `400 missing_client_id`.
- **SDK**: `marketing.signup(client, { campaign_id, email, intent, device, device_id, consent })`.
- **Components**: `<PromoPopup client />` submits through it and shows the
  thanks screen on ok.

```bash
# A signup from a script (curl is a declared bot), or for a campaign nobody runs,
# is answered ok and nothing is written.
BODY=$(curl -sf -X POST "$BASE/api/store/marketing/signup" \
  -H "x-client-id: $CLIENT_ID" -H "content-type: application/json" \
  -d "{\"campaign_id\":\"mcamp_doc-$RUN\",\"email\":\"doc-$RUN@example.com\",\"consent\":true}")
echo "$BODY" | grep -q '"ok":true'
# Without the consent box, the door refuses.
STATUS=$(curl -s -o /dev/null -w '%{http_code}' -X POST "$BASE/api/store/marketing/signup" \
  -H "x-client-id: $CLIENT_ID" -H "content-type: application/json" \
  -d "{\"campaign_id\":\"mcamp_doc-$RUN\",\"email\":\"doc-$RUN@example.com\",\"consent\":false}")
test "$STATUS" = 400
```

## Settings

- **Marketing, Campaigns** (admin): the merchant writes the popup's words
  per locale, sets who sees it and when, chooses the promotion whose code
  the welcome mail carries, and flips the campaign live or paused. The
  consent itself lives on the customer ([customers.md](customers.md)).
