# Marketing: product feeds and the newsletter

The `Marketing` module builds product feeds (PLAN › Product feeds) and keeps the newsletter's consent.

## Product feeds

- `feeds` (`Models\Feed`): name, `preset` (`Data\FeedPreset`: google, meta, tiktok, compari, csv, json), a random
  40-character `token`, `locale`, `currency`, `category_ids` (null: everything), `in_stock_only`, `utm_source`,
  `is_active`, and what the last build left: `generated_at`, `items`, `skipped` (`counts` by reason, up to 100
  `examples`), `bytes`, `error`.
- `Feeds\BuildFeed` reads `Catalog\Contracts\FeedCatalog::after(afterId, limit, locale, categoryIds)` 200 products at a
  time (active, `CatalogViewer::public()`, plain-text descriptions cut at 5,000 characters, large image URLs, category
  path), prices each variant with `Pricing\Contracts\Prices` in `PriceContext::retail(currency)`, asks
  `Promotions\Contracts\Offers` for running price cuts, and `Inventory\Contracts\Stock::available()` for physical
  variants. The item's price is the list price; a lower public price list or price cut becomes the sale price (with the
  cut's dates). Gate: GTIN, or brand and MPN; an image; a description; a price (reasons `identifier`, `image`,
  `description`, `price`, plus `out_of_stock` for in-stock-only feeds). Items stream through a `Feeds\FeedWriter`
  (`GoogleWriter`, which also serves Meta and TikTok with "in stock" spelling; `CompariWriter`; `CsvWriter` with the
  formula guard; `JsonWriter`; `ChatGptWriter`, OpenAI's product feed schema as JSON Lines: `is_eligible_search` true,
  `is_eligible_checkout` false, `target_countries`/`store_country` RO, `seller_name` from `ShopCompany`, policy URLs
  from `Pages::legal()`, `group_id` prefixed `product-` so it never equals an `item_id`) to `feeds/{id}.{ext}.tmp` on the local disk, renamed over the old file when complete.
  A failure keeps the old file and records `error`.
- Links: `store.{locale}.product` with `varianta` (several variants), `utm_source` (feed's or the preset's) and
  `utm_medium=feed`.
- `marketing:feeds` builds every active feed (04:00); `--changed` (every 15 minutes) only feeds built before the last
  change: `Listeners\MarkFeedsStale` stores the time of `CatalogPageChanged` (products) and `VariantPriceChanged` in
  the cache, and `Inventory\Contracts\Stock::lastChange()` gives the newest `stock_levels.updated_at`.
- Admin: `Http\Controllers\FeedController` (`admin.feeds.*`, `feeds.manage`); saving, editing and **rebuild now**
  dispatch `Feeds\BuildFeedJob` (unique per feed). Changing the preset deletes the old file.
- Public: `GET /feeds/{token}.{xml|csv|json}` (`marketing.feed`, `Http\Controllers\PublicFeedController`), outside the
  `web` group (no session or cookies), throttled, `X-Robots-Tag: noindex`, `Cache-Control: public, max-age=900`.

Not built yet: pushing deltas through the Merchant Center Content API (needs the shop's Google credentials) and Meta's
Conversions API.


## Newsletter

- `newsletter_subscribers` (`Models\Subscriber`: e-mail unique case-insensitively, `locale`, `status`
  `Data\SubscriberStatus` pending | subscribed | unsubscribed, `source`, `customer_id`, a UUID `token` renewed with each
  request, `requested_at`, `confirmed_at`, `unsubscribed_at`, `synced_at`, `sync_error`) and `newsletter_events`
  (`Models\SubscriberEvent`: requested | confirmed | unsubscribed, source, HMAC of the IP with the app key, the
  `wording` agreed to; append-only by trigger).
- `Contracts\Newsletter` (`Newsletter\DatabaseNewsletter`): `subscribe(email, locale, source, ip, customerId, proven)`
  (a proven address, a signed-in shopper's own verified one, is subscribed at once; otherwise pending and
  `SubscriptionRequested`), `confirm(token, ip)` (pending, within 7 days), `unsubscribe(token, ip)`,
  `unsubscribeEmail(email, source)`, `find*`. Confirming and leaving raise `SubscriberChanged`; erasure raises it with
  only the address.
- `Contracts\NewsletterDriver` (`subscribe(email, locale, name, consentedAt)`, `unsubscribe(email)`), driver family
  `newsletter`: `Drivers\Newsman\NewsmanDriver` (API 1.2 REST, user id and key in the path, form posts to
  `subscriber.saveSubscribe.json` / `subscriber.saveUnsubscribe.json`, `{err, message}` errors, `list.all` for the
  connection test), `Drivers\Klaviyo\KlaviyoDriver` (revision `2024-10-15`, bulk subscribe job with
  `historical_import` and `consented_at`, bulk delete job to unsubscribe, `GET /lists/{id}` to test),
  `DemoNewsletterDriver` (registered, counts in the cache) and `FakeNewsletterDriver` (tests). Neither log keeps the
  address or the key. `Listeners\SyncChangedSubscriber` queues `Jobs\SyncSubscriber` (5 tries) for every enabled
  service.
- Storefront: `StoreContext::newsletter()` (a service on) shows the footer form (`newsletter.store`), the checkout box
  (`newsletter` in the checkout input, `CheckoutController::joinNewsletter()` after placing) and the account switch
  (`account.newsletter`); `newsletter/{token}` (`NewsletterController`) shows the page and confirms or unsubscribes only
  by POST. `Listeners\SendNewsletterConfirmation` sends `NewsletterMail`, at most three a day per address
  (`RateLimiter`, keyed by a hash of it). Impersonating staff cannot subscribe or unsubscribe for the customer.
- Admin: `Http\Controllers\NewsletterController` (`admin.newsletter.*`, `newsletter.manage`): list with counts,
  subscriber page with the events, unsubscribe on request and CSV export (both in the activity log).
- `Privacy\NewsletterPersonalData` (by customer id or the account's address) and `Privacy\NewsletterRetention`
  (pending after 30 days, unsubscribed 3 years after).

Not built: reading unsubscriptions made in the newsletter service back into the shop (the service stops writing to
them on its own).

Tests: `tests/Feature/Marketing/FeedsTest.php`, `tests/Feature/Marketing/NewsletterTest.php`.

