# Email variations: what is left

What is still to do on email variations (multilingual versions and A/B tests), and
what hasn't been checked. How variations work now is in `docs/email-variations.md`.

Items marked **Decision** need Adrian's answer first.

| # | Item | Size | Before 4.13 ships? |
|---|---|---|---|
| 1 | Verify what was never run | half a day | Yes |
| 2 | Tell someone when a broadcast test's second send fails | small | Yes |
| 3 | A variation's status can only be draft or ready | tiny | Yes |
| 4 | Housekeeping: `.pot`, dev test data | tiny | Yes |
| 5 | Editor UI for filter audiences, order and test weights | medium | No |
| 6 | Weglot | small | No, **Decision** |
| 7 | Variations for global blocks | n/a | Not doing, **Decision** |

## 1. Verify what was never run

These are the riskiest gaps, because some of them send email to real audiences.

- **Broadcast A/B end to end with real cron** on groundhogg.dev: a sample, the
  wait, the winner, the rest. Once with batching and once in the contact's local
  time. Check the rest excludes the sample and that cancelling the sample cancels
  the rest.
- **WPML and Polylang installed**, one at a time. So far only unit tests, with the
  plugins stubbed, have run:
  - the site's languages, the form's `gh_locale`, and the preferences page's
    language choice;
  - a send resolving the right variation, including the closest language (a fr_CA
    contact getting the fr_FR version);
  - a variation's footer coming out in its language;
  - managed pages (preferences, unsubscribe, browser view) opening in the contact's
    language, in a browser.
- **The 4.13 update on a site that hasn't had `parent_id` added by hand.**
  groundhogg.dev got the column manually, so the upgrade path is unexercised.
- **The editor's Variations panel in a browser**: the "blocks to check by hand"
  line, on a language variation with a global block or posts in it.
- **A plain-text email with accented text and another script, opened in a mail
  client.** Servers without mbstring still go through the old `iconv()` path, which
  garbles non-Latin scripts.
- **The block renderer's editor fixtures** (`tests/.../fixtures/email-blocks`) were
  last saved in the editor before borders given as one number worked. Their input
  was changed to match them, rather than saving them again in a browser.

Done when: each has been run and what was seen is written into
`docs/email-variations.md` (as a gotcha) or here (as something left), with any bug
found fixed or listed.

## 2. Tell someone when a broadcast test's second send fails

Today `Email_Variations::finish_broadcast_test()` catches the error, stores
`status: failed` with the message on the email's `variation_broadcast_test` meta,
and stops. Only the email's report shows it. Most of the audience gets nothing and
nobody is told.

The second send is a normal `Broadcast::schedule()`, so it fails for the reasons
any broadcast is refused. Most are not transient, so a blind retry would fail the
same way:

| Cause | Transient? |
|---|---|
| The email was set back to draft during the wait (`DraftException`) | No |
| The email was trashed during the wait | Not refused today, see below |
| A filter in the audience can't be applied any more | No |
| Nobody is left outside the sample who can receive it | No, and not really a failure |
| "Unable to schedule events" (queue insert failed) | Yes |
| The cron request died between `finishing` and the send | Yes, and it stays `finishing` |

`Broadcast::schedule()` refuses only a draft (`$email->is_draft()`), not a trashed
email. So if the email is trashed during the wait, the rest is scheduled and
recorded as `done`, and each event then fails because `Email::send()` sends only a
ready email. `finish_broadcast_test()` should check `is_ready()` itself before
scheduling and record `failed` with the reason.

Proposal:

1. **Notify.** On `failed`, add a notification for users who can schedule
   broadcasts, naming the email and the reason, and linking to its Variations panel.
   - Use `notices()->add_notification( $id, [ 'title', 'message', 'type' => 'error',
     'cap' => 'schedule_broadcasts', 'location' => 'both' ] )`. It is stored, and
     gated by the capability.
   - Not `notices()->add()`. That is a one-minute transient for the current
     request's user, so from a cron run nobody sees it.
   - Remove the notification on retry, or when the test is restarted.
   - Also email the user who scheduled the test. The record needs no new field:
     the sample's `Broadcast::get_scheduled_by_id()` already has that user.
2. **"Send the winner now."** A button in the Variations panel's A/B section,
   shown when the record is `failed` or stale `finishing`. It calls a new
   `Email_Variations::retry_broadcast_test( Email $email )` that re-runs the send
   half of `finish_broadcast_test()` with the stored winner, query and schedule.
   Route: `POST gh/v4/emails/{id}/variations/broadcast-test/retry`, `schedule_broadcasts`.
   Same thing for agents: an `action: retry` on `send-email-broadcast`'s `ab_test`
   is awkward, so prefer a line in `get-email-variation-report`'s output saying it
   failed and why, and let `send-email-broadcast` with the same audience be the retry.
3. **Recover a stuck `finishing`.** Store `finishing_at`. A `finishing` record
   older than 15 minutes is treated as `failed` with the reason "interrupted".
   Check it where the record is read (`editor_data()` and the report), not with
   another cron event.
4. **"No contacts left" is `done`,** not `failed`: catch `NoContactsException`
   separately and record `rest_broadcast_id: 0`.

Refactor first: split `finish_broadcast_test()` into "decide" (waiting, winner)
and "send the rest", so the retry reuses the second half.

Tests (`class-email-ab-tests.php`):

- A failed send leaves a notification and a record that can be retried.
- A retry sends to the audience minus the sample, exactly once.
- A stale `finishing` reads as failed.
- No contacts left reads as done.
- An email trashed during the wait reads as failed, with no broadcast scheduled.

## 3. A variation's status can only be draft or ready

`Email::sanitize_columns()` accepts `ready`, `draft`, `trash` and `global` for any
email (`includes/classes/email.php`, the `status` case). A REST update could put a
variation in the trash, where no screen shows it. Harmless today (it stops being
sent and is deleted with its parent), but it is a state the UI can't get out of.

Proposal: when `$this->is_variation()`, allow only `draft` and `ready`. One test.

## 4. Housekeeping

- Regenerate `languages/` (`.pot` and friends) once the strings from items 2 and 3
  are in. Newer strings, like the `not_translated` notes and "blocks to check by
  hand", aren't in it yet either. The workflow is in the project memory "i18n regen
  workflow".
- groundhogg.dev still has test emails #44 to #47. **Decision:** delete them, or
  keep them for the verification in item 1 and delete after.

## 5. Editor UI for filter audiences, order and test weights

Agents can already do all of this through `create-` and `update-email-variation`.
The editor's Variations panel can only add a language or an evenly split test
version; a filter audience shows as a label and can't be changed there.

Proposal, all inside the existing panel (`VariationsControls` and friends in
`assets/js/admin/emails/email-block-editor.js`):

- **Audience.** An Edit button on a non-test variation opens a modal: languages
  (multi-select of the site's languages) and filters (the same filter picker
  broadcasts and segments use). "Add a variation" gets the same modal, so a
  variation can be for a segment and not a language.
- **Order.** Audience variations resolve first match wins, by `variation_priority`.
  Show them in that order with drag handles; dropping saves priorities.
- **Test weights.** A number input per test version, the email's own share shown
  as the remainder, refused over 100, with a note that changing shares moves
  contacts between versions only for those not yet sent to.
- **REST.** `PATCH gh/v4/emails/{id}/variations/{variation_id}` to
  `Email_Variations::update()` (audience, priority, weight, locale), and
  `POST …/variations` accepts an audience. `edit_emails`, the parent's edit lock,
  errors from `update()` passed through as 400s.

`.min.js` is rebuilt by the PhpStorm watchers, which haven't always fired for this
file, so check the minified file's timestamp after saving.

Tests: REST tests for the new route (permission, validation, weights over 100,
a test version refusing an audience). The modal is checked by hand in Chrome on
groundhogg.dev.

## 6. Weglot (**Decision**)

Weglot isn't read today because it uses two-letter codes, not WordPress locales,
and it translates the page's output rather than loading translations, so
`get_locale()` never changes.

What variations need from it is small: the site's languages and the language a
form was shown in.

Proposal: an adapter in `Multilingual`, using Weglot's helpers (probably
`weglot_get_languages_available()` and `weglot_get_current_language()`) and a
code-to-locale map with a filter. Nothing more. Managed pages need nothing from
Weglot, because they switch from the contact's locale.

The helper names are **unverified**: Weglot isn't installed on any local site, and
plugins.trac.wordpress.org refuses automated reads.

Recommendation: do it only if a customer asks. The filters
(`groundhogg/multilingual/plugin`, `site_languages`, `current_locale`) already
let a site wire it up in a snippet, which could be a docs article instead.

## 7. Variations for global blocks (**Decision**, recommend no)

Adrian was leaning no, and the code agrees: `Email_Variations::create()` refuses
templates and global blocks. A variation is a full copy of the email, so a global
block inside a French variation is already the place to put French content, by
making a second global block. Per-language global blocks would need resolution
inside block rendering, a second place where "which version" is decided.

Recommendation: don't build it. Add one sentence to the email authoring guide
(`includes/abilities/guides/email.md`) saying to use a separate global block per
language.

## Open questions for Adrian

1. Item 2: is an admin notice enough, or should the scheduling user also get an email?
2. Item 4: delete test emails #44 to #47 now or after verification?
3. The work committed after the 4.13 version bump (managed pages, closest
   language, the footer, translation strings, plain text) isn't in a tagged release
   yet. Ship it in 4.13 once item 1 has checked it with Polylang active, or hold it
   for a 4.13.x?
4. Item 6: Weglot adapter, docs article, or nothing?
5. Item 7: confirm no.
6. A/B tests are in core and winners are never declared automatically for flows.
   Those were defaults: confirm them, or move A/B tests to premium beside the Split
   Test step, or auto-declare a flow's winner after N sends at a confidence
   threshold?
7. On a site with more than one language, should the footer also be built again for
   contacts in the default language? Today they get the saved footer, which is in
   the language of whoever saved the email.
8. Add-ons that load their translations into the `groundhogg` text domain: after a
   locale switch only the last one's folder is reloaded, so the others' strings
   stay in the site's language. Give add-ons their own text domains, or reload every
   folder?

## Conventions for whoever builds this

- PHP 7.4 syntax. Stale object: `pull()` first.
- Commit to `master`, only when Adrian asks. Don't push unprompted.
- No "Groundhogg" in UI copy (white label), and AI wording stays vendor neutral.
- Add-ons that count one `email_id` use `Email_Variations::get_family_ids()`.
