mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-25 00:07:07 +00:00
feat: add a Review tab to every campaign email step that shows each lead's real copy with AI parts written ahead, an Approve before sending hold with approve and bulk approve, a lead preview stepper in the step editor, and a review panel on Steps when no email step is left
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/fleetjoin"
|
||||
"github.com/warmbly/warmbly/internal/app/fleetmetrics"
|
||||
"github.com/warmbly/warmbly/internal/app/fleetscale"
|
||||
"github.com/warmbly/warmbly/internal/app/leadreview"
|
||||
"github.com/warmbly/warmbly/internal/app/mailpush"
|
||||
"log"
|
||||
"net/http"
|
||||
@@ -235,6 +236,7 @@ func main() {
|
||||
var cloudLinkService cloudlink.Service
|
||||
var cliAuthService cliauth.Service
|
||||
var campaignService campaign.CampaignService
|
||||
var leadReviewService *leadreview.Service
|
||||
var analyticsService analytics.AnalyticsService
|
||||
var rateLimitService ratelimit.RateLimitService
|
||||
var sequenceService sequence.SequenceService
|
||||
@@ -2078,6 +2080,21 @@ func main() {
|
||||
// returning a clean "not available".
|
||||
tasksService.SetAI(aiProvider, creditService)
|
||||
|
||||
// The Review tab, and the per-lead copies the send path reads.
|
||||
campaignReviewRepository := repository.NewCampaignReviewRepository(primaryDB.Pool)
|
||||
if aware, ok := tasksService.(tasks.LeadReviewAware); ok {
|
||||
aware.WireLeadReview(campaignReviewRepository)
|
||||
}
|
||||
if emails, ok := tasksService.(tasks.LeadEmailsService); ok {
|
||||
leadReviewService = &leadreview.Service{
|
||||
Campaigns: campaignService,
|
||||
Repo: campaignReviewRepository,
|
||||
Emails: emails,
|
||||
Steps: tasksService,
|
||||
Undeliverable: campaignProgressRepository,
|
||||
}
|
||||
}
|
||||
|
||||
// Client connect links: a client connects mailboxes into a workspace through the same connect paths.
|
||||
connectLinkService = connectlink.New(connectlink.Deps{
|
||||
Repo: repository.NewClientConnectLinkRepository(primaryDB),
|
||||
@@ -2378,6 +2395,11 @@ func main() {
|
||||
// just new mail. Walks the table once, then returns.
|
||||
elector.Go("unibox_body_backfill", uniboxService.StartBodyTextBackfill)
|
||||
|
||||
// Writes every active campaign's first-email AI copy ahead of its send, like a generated column.
|
||||
if leadReviewService != nil {
|
||||
elector.Go("lead_ai_write_ahead", leadReviewService.StartAIWriteAhead)
|
||||
}
|
||||
|
||||
// Automation signing secrets live in each connection's sealed config.
|
||||
if m, ok := integrationServiceForHandler.(interface{ StartSigningSecretMigration(context.Context) }); ok {
|
||||
elector.Go("signing_secret_migration", m.StartSigningSecretMigration)
|
||||
@@ -2963,6 +2985,10 @@ func main() {
|
||||
// a database.
|
||||
AuditService: auditService,
|
||||
}
|
||||
if leadReviewService != nil {
|
||||
leadReviewService.Contacts = h.ReviewContacts()
|
||||
h.LeadReview = leadReviewService
|
||||
}
|
||||
// Agency keys on the MCP server see the agency tools, migrations included.
|
||||
if agencyService != nil {
|
||||
h.AgencyTools = aitools.BuildAgencyRegistry(aitools.AgencyDeps{
|
||||
|
||||
@@ -147,6 +147,16 @@ Campaigns, steps and activity logs are scoped to the selected organization for s
|
||||
| GET | `/campaigns/:id/leads/:contactId/cc` | `READ_CAMPAIGNS` + `READ_CONTACTS` |
|
||||
| PUT | `/campaigns/:id/leads/:contactId/cc` | `WRITE_CAMPAIGNS` + `READ_CONTACTS` |
|
||||
| GET | `/campaigns/:id/leads/:contactId/cc/suggestions` | `READ_CAMPAIGNS` + `READ_CONTACTS` |
|
||||
| GET | `/campaigns/:id/review` | `READ_CAMPAIGNS` |
|
||||
| PUT | `/campaigns/:id/review` | `WRITE_CAMPAIGNS` (+ `SEND_CAMPAIGNS` to turn it off) |
|
||||
| GET | `/campaigns/:id/review/leads` | `READ_CAMPAIGNS` + `READ_CONTACTS` |
|
||||
| POST | `/campaigns/:id/review/approve` | `SEND_CAMPAIGNS` |
|
||||
| POST | `/campaigns/:id/review/reopen` | `WRITE_CAMPAIGNS` |
|
||||
| POST | `/campaigns/:id/review/write` | `WRITE_CAMPAIGNS` (org `use_ai`) |
|
||||
| GET | `/campaigns/:id/leads/:contactId/emails` | `READ_CAMPAIGNS` + `READ_CONTACTS` |
|
||||
| PUT | `/campaigns/:id/leads/:contactId/emails/:stepId` | `WRITE_CAMPAIGNS` + `READ_CONTACTS` |
|
||||
| DELETE | `/campaigns/:id/leads/:contactId/emails/:stepId` | `WRITE_CAMPAIGNS` + `READ_CONTACTS` |
|
||||
| POST | `/campaigns/:id/leads/:contactId/emails/:stepId/write` | `WRITE_CAMPAIGNS` + `READ_CONTACTS` (org `use_ai`) |
|
||||
| GET | `/campaigns/:id/logs` | `READ_CAMPAIGNS` |
|
||||
| GET | `/campaigns/:id/send-plan` | `READ_CAMPAIGNS` |
|
||||
| GET | `/campaigns/:id/lead-timezones` | `READ_CAMPAIGNS` |
|
||||
|
||||
@@ -1128,6 +1128,7 @@ A few conflicts carry their own `code`. The mailbox import's are under [mailbox
|
||||
| `contact_email_taken` | 409 | The address given to [update a contact](/api/reference/contacts/#update-a-contact) already belongs to another contact |
|
||||
| `lead_cc_lead_is_copied` | 409 | [Set a lead's CC](/api/reference/campaigns/#set-a-leads-cc) on a lead that is itself copied on another lead in the campaign, so it sends nothing of its own to copy anyone on |
|
||||
| `lead_cc_has_copies` | 409 | [Set a lead's CC](/api/reference/campaigns/#set-a-leads-cc) names a contact that has copies of their own in the campaign |
|
||||
| `lead_step_sent` | 409 | [Personalize](/api/reference/campaigns/#personalize-one-email-for-one-lead), [reset](/api/reference/campaigns/#reset-one-leads-email) or [rewrite the AI copy of](/api/reference/campaigns/#write-one-leads-ai-copy-now) one lead's email after the lead already received it. Nothing changed |
|
||||
| `mailbox_is_seed` | 409 | Warmup was started or resumed on a placement seed inbox. See [placement test refusals](#placement-test-refusals) |
|
||||
| `mailbox_not_google_signin` | 409 | `POST /emails/onboarding/app-password/:id` on a mailbox that is not a Google mailbox on its own sign-in or an admin grant. See [app password switch refusals](#app-password-switch-refusals) |
|
||||
| `scheduled_send_not_pending` | 409 | [Cancel a scheduled send](/api/reference/unibox/#cancel-a-scheduled-send) named a send that is no longer pending: it has started sending, was sent, failed, or was already cancelled. Nothing changed |
|
||||
@@ -1217,6 +1218,8 @@ Every endpoint that checks a password, an emailed or two-factor code, or a sign-
|
||||
}
|
||||
```
|
||||
|
||||
Writing one lead's AI copy ahead ([write one lead's AI copy now](/api/reference/campaigns/#write-one-leads-ai-copy-now)) answers `ai_unavailable` on an instance with no AI provider and `ai_generation_failed` when the provider did not answer; neither charges anything.
|
||||
|
||||
Other temporary failures answer the generic form:
|
||||
|
||||
**Example:**
|
||||
|
||||
@@ -922,7 +922,7 @@ Read whether one contact's flow inside this campaign is currently held. A hold p
|
||||
}
|
||||
```
|
||||
|
||||
`hold` is absent when the lead is not held, including for a dated hold that has since expired. `until` is absent when the hold has no end, in which case only a resume lifts it. `source` is `out_of_office`, `inbox_tagging` (a classified reply, or with `reply_intent.stop_all_campaigns_on_reply` on, a reply to another campaign), `manual`, or `cc` while the contact is [copied on another lead's emails](#set-a-leads-cc) in this campaign; a `cc` hold's `reason` is that lead's address.
|
||||
`hold` is absent when the lead is not held, including for a dated hold that has since expired. `until` is absent when the hold has no end, in which case only a resume lifts it. `source` is `out_of_office`, `inbox_tagging` (a classified reply, or with `reply_intent.stop_all_campaigns_on_reply` on, a reply to another campaign), `manual`, `crm`, `review` while a [review campaign](#turn-review-mode-on-or-off) waits for someone to approve the lead (shown ahead of any other hold the lead has), or `cc` while the contact is [copied on another lead's emails](#set-a-leads-cc) in this campaign; a `cc` hold's `reason` is that lead's address.
|
||||
|
||||
### Errors
|
||||
|
||||
@@ -945,7 +945,7 @@ The request states an absolute hold rather than applying a delta, and replacing
|
||||
| `until` | body | string | RFC 3339 timestamp the hold lifts at. Must be in the future and within a year. Omit or send `null` for a hold with no end, which only a resume lifts. |
|
||||
| `reason` | body | string | Optional note shown next to the hold in the dashboard. Trimmed and capped at 200 characters. |
|
||||
|
||||
A manual pause always wins: it replaces a hold an out-of-office auto-reply wrote, and a later auto-reply never shortens it or takes it over.
|
||||
A manual pause wins over an automatic hold: it replaces a hold an out-of-office auto-reply wrote, and a later auto-reply never shortens it or takes it over. Pausing a lead waiting for review leaves it waiting; only an approval releases it.
|
||||
|
||||
### Request body
|
||||
|
||||
@@ -970,7 +970,7 @@ Same shape as [get a lead's hold](#get-a-leads-hold).
|
||||
|
||||
Lift the hold now. The held time is dropped rather than carried, so the step returns to the schedule it would have had without the hold: the campaign's next pass when that moment has already passed, otherwise when the step's own wait elapses. The campaign's own wakeup is pulled forward with it, and a campaign that had finished while the lead was held is restarted through the usual launch checks. **Scope** `WRITE_CAMPAIGNS` · **Org permission** `manage_campaigns`.
|
||||
|
||||
Resuming a lead that is not held succeeds and changes nothing, so a retry is safe.
|
||||
Resuming a lead that is not held succeeds and changes nothing, so a retry is safe. Resuming never approves a lead waiting for review; use [approve waiting leads](#approve-waiting-leads). It lifts any other hold on that lead, which keeps waiting for review.
|
||||
|
||||
| Parameter | In | Type | Description |
|
||||
| --- | --- | --- | --- |
|
||||
@@ -1093,6 +1093,255 @@ Up to eight contacts who look like the lead's colleagues: the same company name,
|
||||
|
||||
`reason` is `company` when the company names match and `domain` when only the email domain does. Company matches come first.
|
||||
|
||||
## Get a campaign's readiness report
|
||||
|
||||
`GET /campaigns/:id/review`
|
||||
|
||||
What the top of an email step's Review tab shows: how its leads split by review state, the merge fields some leads not yet emailed would leave blank, what sending skips, steps whose copy does not render, and how much of the first email's AI copy is written ahead. **Scope** `READ_CAMPAIGNS` · **Org permission** `view_campaigns`.
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"campaign_id": "8f1d6b2e-2b7a-4c9e-9a1f-0e6d4c3b2a10",
|
||||
"review_leads": true,
|
||||
"counts": { "total": 240, "waiting": 180, "ready": 12, "held": 3, "started": 45, "personalized": 7 },
|
||||
"missing": [{ "field": "FirstName", "leads": 14 }],
|
||||
"undeliverable": 2,
|
||||
"unsubscribed": 1,
|
||||
"ai": { "step_id": "5c2e7a10-9b1d-4f3e-8a6c-2d4b0e1f7a93", "blocks": 1, "written": 40, "pending": 155, "estimated_cost_usd": 1.55, "auto": true },
|
||||
"template_errors": []
|
||||
}
|
||||
```
|
||||
|
||||
`counts` splits every lead: `waiting` for review, `ready` (not emailed yet, nothing holding them), `held` (not emailed yet, paused for another reason) and `started` (emailed, or a send in flight). `missing` counts unstarted, subscribed leads with a field empty that an email step prints with nothing to fall back on (outside an `{{if}}` and without `default`), largest first. `ai` covers the first email step's AI blocks: leads not yet emailed whose copy is written ahead, the ones still to write, and about what writing them costs at the per-block estimate the balance check reserves. `auto` is true while the campaign is active and the instance can write AI copy: the pending leads are then written in the background without any call. A lead with its own copy of the step needs none.
|
||||
|
||||
## Turn review mode on or off
|
||||
|
||||
`PUT /campaigns/:id/review`
|
||||
|
||||
On, every lead not yet emailed, and every lead enrolled later by any path, waits until a member approves it: its first email is held, and follow-ups after it go out on their own. Off approves every waiting lead, so it also needs `SEND_CAMPAIGNS` and `send_campaigns`. **Scope** `WRITE_CAMPAIGNS` · **Org permission** `manage_campaigns`.
|
||||
|
||||
Only a change moves leads. Sending the mode the campaign already has changes nothing, so a retry is safe and no `Idempotency-Key` is needed. A lead not yet emailed that is paused for another reason waits for review too, and keeps that pause after it is approved. Waiting for review is held apart from other holds: resuming a pause, an away message ending, a CRM rule or removing a CC copy never releases it.
|
||||
|
||||
| Parameter | In | Type | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `id` | path | uuid | Campaign id. |
|
||||
| `enabled` | body | boolean | Required. |
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{ "campaign_id": "8f1d6b2e-2b7a-4c9e-9a1f-0e6d4c3b2a10", "review_leads": true, "held": 192, "released": 0 }
|
||||
```
|
||||
|
||||
`held` counts leads put into review and `released` counts leads approved by turning it off. The campaign object carries `review_leads` too.
|
||||
|
||||
### Errors
|
||||
|
||||
| Status | Code | When |
|
||||
| --- | --- | --- |
|
||||
| `400` | `bad_request` | `enabled` is missing. |
|
||||
| `403` | `forbidden` | Turning review off without `SEND_CAMPAIGNS` and `send_campaigns`. |
|
||||
| `404` | `not_found` | The campaign is not the caller's organization's. |
|
||||
|
||||
## List leads by review state
|
||||
|
||||
`GET /campaigns/:id/review/leads`
|
||||
|
||||
The campaign's leads ordered by email, each with its review state. **Scope** `READ_CAMPAIGNS` and `READ_CONTACTS` · **Org permission** `view_campaigns` and `view_contacts`.
|
||||
|
||||
| Parameter | In | Type | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `id` | path | uuid | Campaign id. |
|
||||
| `status` | query | string | `all` (default), `waiting`, `ready`, `held` or `started`. |
|
||||
| `missing` | query | string | Only leads with this field empty: `FirstName`, `LastName`, `Company` or `Phone`. |
|
||||
| `q` | query | string | Matches email, name or company. |
|
||||
| `cursor` | query | string | Opaque cursor from the previous page's `pagination.next_cursor`. |
|
||||
| `limit` | query | integer | `1` to `200`, default `50`. |
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"contact_id": "3a5e9c71-4f2b-4d88-9a0c-1b7e5d2f6c34",
|
||||
"email": "ana@acme.example",
|
||||
"first_name": "",
|
||||
"last_name": "Ruiz",
|
||||
"company": "Acme",
|
||||
"status": "waiting",
|
||||
"hold": { "since": "2026-11-14T10:02:00Z", "source": "review" },
|
||||
"personalized": 1,
|
||||
"missing": ["FirstName"],
|
||||
"added_at": "2026-11-14T10:02:00Z"
|
||||
}
|
||||
],
|
||||
"pagination": { "next_cursor": "YW5hQGFjbWUuZXhhbXBsZR8zYTVl...", "has_more": true }
|
||||
}
|
||||
```
|
||||
|
||||
`personalized` counts the steps with this lead's own copy. `missing` lists the fields the campaign's emails print that this lead has empty.
|
||||
|
||||
### Errors
|
||||
|
||||
| Status | Code | When |
|
||||
| --- | --- | --- |
|
||||
| `400` | `bad_request` | An unknown `status` or `missing`, a `limit` out of range, or an invalid `cursor`. |
|
||||
| `404` | `not_found` | The campaign is not the caller's organization's. |
|
||||
|
||||
## Approve waiting leads
|
||||
|
||||
`POST /campaigns/:id/review/approve`
|
||||
|
||||
Release leads waiting for review. Their first email goes out under the campaign's schedule, daily limits, spacing and every other sending rule, exactly as without review, and the campaign's wakeup is pulled forward. **Scope** `SEND_CAMPAIGNS` · **Org permission** `send_campaigns`.
|
||||
|
||||
Approving a lead that is not waiting changes nothing, so a retry is safe and no `Idempotency-Key` is needed. Only this endpoint and turning review off release a waiting lead. A lead also paused for another reason keeps that pause until it lifts.
|
||||
|
||||
| Parameter | In | Type | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `id` | path | uuid | Campaign id. |
|
||||
| `contact_ids` | body | array of uuid | Leads to approve, at most `500`. |
|
||||
| `all` | body | boolean | Approve every waiting lead. Send this or `contact_ids`, not both. |
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{ "campaign_id": "8f1d6b2e-2b7a-4c9e-9a1f-0e6d4c3b2a10", "review_leads": true, "held": 0, "released": 25 }
|
||||
```
|
||||
|
||||
### Errors
|
||||
|
||||
| Status | Code | When |
|
||||
| --- | --- | --- |
|
||||
| `400` | `bad_request` | Neither or both of `contact_ids` and `all`, or more than `500` ids. |
|
||||
| `404` | `not_found` | The campaign is not the caller's organization's. |
|
||||
|
||||
## Send leads back to review
|
||||
|
||||
`POST /campaigns/:id/review/reopen`
|
||||
|
||||
Hold the listed leads for review again. A lead already emailed, or paused for another reason, is left as it is, and a lead already waiting stays waiting, so a retry is safe. **Scope** `WRITE_CAMPAIGNS` · **Org permission** `manage_campaigns`.
|
||||
|
||||
| Parameter | In | Type | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `id` | path | uuid | Campaign id. |
|
||||
| `contact_ids` | body | array of uuid | Required, at most `500`. |
|
||||
|
||||
### Response
|
||||
|
||||
Same shape as [approve waiting leads](#approve-waiting-leads); `held` counts the leads put back.
|
||||
|
||||
## Write AI copy ahead
|
||||
|
||||
`POST /campaigns/:id/review/write`
|
||||
|
||||
Write the AI blocks of the first email step, or `step_id`, for up to ten leads not yet emailed that still miss one, so they can be read before they go out. Each block is charged to the balance exactly as it would be at send time and cached where the send reads it, so the send reuses it and nothing is charged twice. **Scope** `WRITE_CAMPAIGNS` · **Org permission** `manage_campaigns` and `use_ai`.
|
||||
|
||||
Call it again with the `next` it returned as `after` while `remaining` is above zero. The cursor moves past every lead a pass tried, so a lead that keeps failing cannot stall the run. A pass that runs out of balance or reaches a spend limit stops early with `stopped`, keeps what it wrote, and hands back a `next` that resumes where it began. A lead with its own copy of the step is skipped.
|
||||
|
||||
| Parameter | In | Type | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `id` | path | uuid | Campaign id. |
|
||||
| `step_id` | body | uuid | An email step. Default the first one. |
|
||||
| `contact_ids` | body | array of uuid | Only these leads, at most `500`. |
|
||||
| `waiting_only` | body | boolean | Without `contact_ids`, only leads waiting for review. Without either, every lead not yet emailed. |
|
||||
| `after` | body | string | The previous pass's `next`. |
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{ "written": 10, "failed": 0, "remaining": 145, "next": "YW5hQGFjbWUuZXhhbXBsZR8zYTVl..." }
|
||||
```
|
||||
|
||||
`stopped` is `insufficient_credits` or `usage_cap_exceeded` when the pass ended early. A failed lead is written at send time instead.
|
||||
|
||||
## Get one lead's emails
|
||||
|
||||
`GET /campaigns/:id/leads/:contact_id/emails`
|
||||
|
||||
Every email step rendered for one lead the way the send will: their own copy or the A/B variant drawn for them, merge fields, spintax (the same choice every time for a lead and step), the AI copy written so far, the signature of the mailbox already writing to them, and the opt-out footer. Nothing is written or charged. **Scope** `READ_CAMPAIGNS` and `READ_CONTACTS` · **Org permission** `view_campaigns` and `view_contacts`.
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"campaign_id": "8f1d6b2e-2b7a-4c9e-9a1f-0e6d4c3b2a10",
|
||||
"lead": { "contact_id": "3a5e9c71-4f2b-4d88-9a0c-1b7e5d2f6c34", "email": "ana@acme.example", "status": "waiting", "personalized": 0, "missing": ["FirstName"] },
|
||||
"steps": [
|
||||
{
|
||||
"step_id": "5c2e7a10-9b1d-4f3e-8a6c-2d4b0e1f7a93",
|
||||
"position": 1,
|
||||
"name": "Step 1",
|
||||
"subject": "Quick question about Acme",
|
||||
"body_html": "<p>Hi there, …</p>",
|
||||
"body_plain": "Hi there, …",
|
||||
"source": { "subject": "Quick question about {{.Company}}", "body_html": "<p>Hi {{.FirstName | default \"there\"}}, …</p>", "body_plain": "" },
|
||||
"threaded": false,
|
||||
"personalized": false,
|
||||
"step_changed": false,
|
||||
"ai_blocks": [{ "id": "opener", "name": "Opener", "written": false }],
|
||||
"sent": false
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`from` is present once a mailbox has written to the lead. `source` is the template the copy renders from, which a personalization starts from. `threaded` marks a follow-up replying in the lead's thread, whose subject is the conversation's. In `body_html`, written AI copy is wrapped in `<span data-ai-block="ID">` and a block not yet written is an empty `<span data-ai-pending="ID" data-ai-name="...">`, so a preview can mark them; the plain text shows `[AI: name]` for an unwritten block. These markers are never sent. `step_changed` marks a personalized step whose shared copy was edited after it.
|
||||
|
||||
### Errors
|
||||
|
||||
| Status | Code | When |
|
||||
| --- | --- | --- |
|
||||
| `404` | `not_found` | The campaign is not the caller's organization's, or the contact is not a lead of it. |
|
||||
|
||||
## Personalize one email for one lead
|
||||
|
||||
`PUT /campaigns/:id/leads/:contact_id/emails/:step_id`
|
||||
|
||||
Store this lead's own copy of one email step. It replaces the step's copy, and any A/B variant, for this lead only. Merge fields, spintax and AI blocks in it still resolve when it sends, and it is checked like a step's copy. Later edits to the step do not change it. **Scope** `WRITE_CAMPAIGNS` and `READ_CONTACTS` · **Org permission** `manage_campaigns` and `view_contacts`.
|
||||
|
||||
The body replaces the whole copy, so a retry lands on the same row and no `Idempotency-Key` is needed.
|
||||
|
||||
| Parameter | In | Type | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `subject` | body | string | Up to 998 characters. Ignored on a follow-up that replies in the lead's thread. |
|
||||
| `body_html` | body | string | Send this, `body_plain`, or both. |
|
||||
| `body_plain` | body | string | |
|
||||
|
||||
### Errors
|
||||
|
||||
| Status | Code | When |
|
||||
| --- | --- | --- |
|
||||
| `400` | `bad_request` | No body, or the email is too long. |
|
||||
| `400` | `invalid_template` | The copy does not render as written. |
|
||||
| `404` | `not_found` | The campaign, the lead or the email step is not found. |
|
||||
| `409` | `lead_step_sent` | This lead already received this email. |
|
||||
|
||||
## Reset one lead's email
|
||||
|
||||
`DELETE /campaigns/:id/leads/:contact_id/emails/:step_id`
|
||||
|
||||
Drop this lead's own copy, so the step's copy goes out again. Deleting a copy that is not there succeeds with `204`. **Scope** `WRITE_CAMPAIGNS` and `READ_CONTACTS` · **Org permission** `manage_campaigns` and `view_contacts`. Answers `409 lead_step_sent` once the lead received the email.
|
||||
|
||||
## Write one lead's AI copy now
|
||||
|
||||
`POST /campaigns/:id/leads/:contact_id/emails/:step_id/write`
|
||||
|
||||
Write the step's AI blocks for this lead now instead of at send time, and answer the lead's emails as [get one lead's emails](#get-one-leads-emails) does. Charged and cached as in [write AI copy ahead](#write-ai-copy-ahead), so a retry writes and charges nothing more. Send `{"rewrite": true}` to replace copy already written with a new generation, which is charged again. **Scope** `WRITE_CAMPAIGNS` and `READ_CONTACTS` · **Org permission** `manage_campaigns`, `use_ai` and `view_contacts`.
|
||||
|
||||
### Errors
|
||||
|
||||
| Status | Code | When |
|
||||
| --- | --- | --- |
|
||||
| `402` | `insufficient_credits` | The balance is too low. Nothing is charged. |
|
||||
| `404` | `not_found` | The campaign, the lead or the email step is not found. |
|
||||
| `409` | `lead_step_sent` | A rewrite of an email the lead already received. |
|
||||
| `429` | `usage_cap_exceeded` | The workspace reached its AI spend limit. |
|
||||
| `503` | `ai_unavailable` | The instance has no AI provider. |
|
||||
| `503` | `ai_generation_failed` | The provider did not answer. Nothing is charged; try again. |
|
||||
|
||||
## Get campaign logs
|
||||
|
||||
`GET /campaigns/:id/logs`
|
||||
@@ -1549,6 +1798,8 @@ Render subject and body templates for a contact exactly as the send path would,
|
||||
|
||||
A `TemplatePreview` object. `errors` lists template parse errors that would block sending, `unresolved` lists literal tokens left after render. `from` is present when `account_id` was given, `attachments` when `campaign_id` was given and there are files on the send (the campaign-wide ones plus `step_id`'s own). All four are omitted when empty.
|
||||
|
||||
The body's [AI blocks](/guides/ai-variables/) are never generated here. Each is replaced by a `<span data-ai-pending="ID" data-ai-name="Name">` marker, or, when `contact_id` is a lead of `campaign_id` and `step_id` is given, by the copy already written for that lead in `<span data-ai-block="ID">`; in `subject` and `body_plain` the written text or `[AI: Name]` stands in. `ai_blocks` lists each block as `{ "id", "name", "written" }`. `lead` is `true` when the contact is a lead of the campaign, and `personalized` is `true` when that lead has their own copy of the step, which they get instead of the copy previewed. The three are omitted when empty or false.
|
||||
|
||||
```json
|
||||
{
|
||||
"subject": "Hi Sam at Globex",
|
||||
|
||||
@@ -124,7 +124,7 @@ Remie keeps a core set of tools in view and finds the rest on demand by searchin
|
||||
|
||||
When no dedicated tool covers a request (reply templates, A/B variants, sending domains, lead searches, imports, integration settings and so on), Remie looks up the matching [API endpoint](/api/), reads its documentation, and calls it as you. The call goes through the same checks as the dashboard: your role's permissions, your workspace, your rate limits. Reads run on their own; every change asks, and **Always allow** is never offered for it.
|
||||
|
||||
Some things stay out of reach on purpose. Remie cannot send mail, start a campaign or run a placement test this way (each has its own tool, which shows you exactly what goes out), sign in or change account security, manage API keys, webhooks or OAuth apps, upload files, or enter a credential such as a password or API key, which belongs in the dashboard where it is sealed. Fields that hold a credential are withheld from anything Remie reads.
|
||||
Some things stay out of reach on purpose. Remie cannot send mail, start a campaign or run a placement test this way (each has its own tool, which shows you exactly what goes out), approve leads waiting for [review](/guides/campaigns/#review-before-sending) or turn review off (do that on the campaign's Review tab), sign in or change account security, manage API keys, webhooks or OAuth apps, upload files, or enter a credential such as a password or API key, which belongs in the dashboard where it is sealed. Fields that hold a credential are withheld from anything Remie reads.
|
||||
|
||||
</Fold>
|
||||
|
||||
|
||||
@@ -21,12 +21,18 @@ The block always uses the model configured for your workspace; there is no separ
|
||||
|
||||
Use the editor's preview to see the block written for a built-in sample contact, shown inside the whole message so you can check it reads naturally where it lands. A preview costs the same as a send-time resolution, because it runs the same generation, and the editor shows what that example actually cost.
|
||||
|
||||
A step's **Preview** shows each AI block as a marked slot for the sample contact. Pick one of the campaign's leads, or step through them with the arrows, to see the copy AI wrote for that lead with a soft highlight. A saved step writes a lead's blocks as soon as you preview them, the same as opening them on the step's [Review tab](/guides/campaigns/#review-before-sending), and costs the same as writing them at send time. A lead with their own copy of the step is marked, with a link that opens it on the Review tab.
|
||||
|
||||
## How it resolves at send time
|
||||
|
||||
When the campaign sends to a contact, each AI variable in that email is generated for that contact just before tracking and signature are added, so the AI copy is tracked and styled like the rest of the email. The result is cached per contact and step: if a send is retried, the same snippet is reused instead of generating (and charging) again. Different contacts always get their own copy.
|
||||
|
||||
A block whose instruction renders empty for a contact resolves to nothing and costs nothing. A block with a malformed configuration is skipped rather than blocking the send. If the AI provider fails, that recipient's send is retried later with the cached result, so you are never charged for output you did not receive.
|
||||
|
||||
## Writing ahead to read first
|
||||
|
||||
While a campaign runs, Warmbly writes the first email's AI blocks for every lead not yet emailed ahead of their send, and for each lead added later, so the copy is ready and readable on the step's [Review tab](/guides/campaigns/#review-before-sending) before it goes out. Before launch, the Review tab writes a lead's blocks as soon as you open them, and the next few leads' in the background; **Write all now** writes every lead at once, and **Rewrite** asks for another version of one. Writing ahead costs exactly what writing at send time does, and the send reuses the result, so a block is never charged twice; a rewrite is charged again. A lead whose email you edited on the Review tab keeps the AI blocks you left in it.
|
||||
|
||||
## Cost and safety
|
||||
|
||||
- A block is billed by usage: the model and the tokens each snippet uses, plus the web search when it is on. See [Balance and usage](/guides/ai-credits/) for how usage is priced.
|
||||
|
||||
@@ -50,6 +50,7 @@ On **Review**, check the finish date, then choose **Launch** or **Save as draft*
|
||||
- A lead's follow-ups normally go out from the mailbox that sent their first email. They wait for that mailbox through a provider pause that ends within 45 minutes, and move to another one only when it is held, paused for longer, or gone.
|
||||
- Launch checks your list first and refuses one that is known to be largely undeliverable.
|
||||
- Nothing sends until the campaign launches. Closing the flow with anything filled in saves a draft.
|
||||
- Each email step has a **Review** tab that shows that email exactly as each lead gets it and lets you edit one lead's copy. Every lead's AI copy is written ahead once the campaign runs, and leads can be held until you approve their first email. See [Review before sending](#review-before-sending).
|
||||
|
||||
<Fold>
|
||||
|
||||
@@ -132,6 +133,65 @@ After ten minutes Warmbly isolates an authorized campaign send whose outcome is
|
||||
|
||||
<Fold>
|
||||
|
||||
## Review before sending
|
||||
|
||||
Every email step has a **Review** tab next to its **Email** tab: open the step on the campaign's **Steps** tab and switch to it. It shows that email exactly as each lead gets it and says whether the campaign is ready to send. It can also hold each lead until someone approves their first email. Only email steps have one, since other steps send nothing. A link to a campaign's old Review page opens the first email's Review tab. If no step sends an email while leads wait for approval, the Steps tab shows how many wait, and **Review** opens them in a panel of their own.
|
||||
|
||||
### The layout
|
||||
|
||||
The step's panel widens to fit it: a line of checks on top, the leads on the left and the open lead's copy of the email on the right. The open lead's position (`3 of 40`) shows above their email, the arrows next to it move to the previous and next lead, and `J` and `K` do the same from the keyboard.
|
||||
|
||||
The first chip on the top line says whether the campaign is ready to send. Click it to see what to fix first:
|
||||
|
||||
- **Blank merge fields.** A field an email prints with nothing to fall back on (`{{.FirstName}}` outside an `{{if}}` and without `default`), counted over the leads not yet emailed. **Show them** lists those leads, so you can fill the field in or edit their email.
|
||||
- **Steps that will not render** as written, with a link to fix them.
|
||||
- **Unsubscribed leads**, which sending skips, and **addresses that failed verification**, which the [launch check](#the-launch-check-on-your-list) counts against the list.
|
||||
|
||||
When the first email has [AI blocks](/guides/ai-variables/), a second chip shows how many leads not yet emailed have theirs written. Click it for the details and, before launch, **Write all now** with about what it costs.
|
||||
|
||||
The menu next to the search picks which leads the list shows, with a count for each:
|
||||
|
||||
| State | Meaning |
|
||||
|-------|---------|
|
||||
| Waiting | Held until someone approves their first email. Listed when approval is on, or someone still waits |
|
||||
| Ready | Not emailed yet; their first email goes out on schedule |
|
||||
| Paused | Not emailed yet, and paused for another reason, such as an away message. Listed when someone is |
|
||||
| Started | Already emailed, or an email to them is on its way |
|
||||
|
||||
### Each lead's emails
|
||||
|
||||
Pick a lead to read every email step as it will be sent to them: their fields filled in, the A/B variant they get, spintax resolved, the AI copy written so far, the signature of the mailbox already writing to them and the opt-out footer. A follow-up that replies in the thread shows the first email's subject, which is what the lead sees. Spintax picks the same option for one lead and step every time, so what you read is what goes out, and a retried send carries the same wording. Different leads still get different options.
|
||||
|
||||
Once the campaign is running, Warmbly writes the first email's [AI blocks](/guides/ai-variables/) for every lead not yet emailed on its own, and for each lead added later, so their copy is ready before it goes out and you never have to start it. The AI chip at the top of the tab shows how far it has got. Before launch, a lead's AI blocks are written the moment you open them: a shimmering line holds their place in the email while Remie writes, then the text fades in. AI-written text keeps a soft highlight in the preview, so you can see what AI wrote; the recipient gets plain text. While you read one lead, the next two in the list are written in the background, so moving on shows theirs already written. **Rewrite** asks for another version.
|
||||
|
||||
Writing ahead is charged to the balance exactly as writing at send time is, and the send reuses what was written, so nothing is charged twice. A rewrite is a new generation and is charged again. Before launch, **Write all now** under the AI chip writes every lead not yet emailed, or the leads you selected, a few at a time; it stops when the balance runs out or you press **Stop**, and keeps what it wrote. Writing on its own pauses while the balance is too low and resumes when it is topped up. A lead removed or unsubscribed before their first email keeps the charge for copy already written for them. Follow-ups' AI blocks are written when they send, or when you open the lead. A member without the **Use AI** permission sees a marked slot instead, written when the email sends, and so does everyone when the balance is too low or the instance has no AI provider.
|
||||
|
||||
### Editing one lead's email
|
||||
|
||||
**Edit for this lead** opens the step's editor with this lead's copy. Saving keeps a copy for this lead only. It replaces the step's copy, and any A/B variant, for them. Merge fields, spintax and AI blocks in it still fill in when it sends. A follow-up that replies in the thread keeps the conversation's subject. Later edits to the step do not change a personalized copy; the email says when the step changed since, and **Use the step's copy** goes back to it. Once the lead has received an email, that email can no longer change.
|
||||
|
||||
Personalized emails are marked with a pencil in the list and on the step's tab.
|
||||
|
||||
### Approving leads first
|
||||
|
||||
By default leads start on schedule without anyone approving them. To approve each lead first, turn on **Approve before sending** at the top right of any email step's Review tab. From then on, every lead not yet emailed waits for approval. So does every lead added later, whichever way they arrive: a linked list, an import, the API, a form or an automation. Follow-ups after the first email go out on their own.
|
||||
|
||||
- Approve the lead you are reading, several from the selection bar, or **Approve all**. On the Review tab, `A` approves the open lead and `J` and `K` move between leads.
|
||||
- An approved lead starts under the campaign's schedule, daily limits, spacing and every other sending rule, exactly as without review.
|
||||
- **Back to review** holds a lead who has not been emailed yet again.
|
||||
- A waiting lead shows **Waiting for review** in the Leads list and in the contact's Activity, where **Approve** releases them.
|
||||
- A lead that was also paused for another reason, such as an away message or a pause you set, waits for both: approving it leaves that pause in place until it lifts.
|
||||
- Approving needs the **Send campaigns** permission, like starting a campaign. Turning review off approves everyone waiting, so it needs the same permission and asks first.
|
||||
- Only an approval, or turning review off, releases a waiting lead. Resuming a pause, an away message ending, a CRM rule or removing a CC copy never does.
|
||||
- While leads wait, every other tab of the campaign shows how many, with a link here.
|
||||
- A campaign's estimate counts every lead, as if you approve them all.
|
||||
|
||||
Changes on the tab reach teammates live, and approvals appear in the activity log.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Images in the editor
|
||||
|
||||
Warmbly loads external images through a display-only preview service while you edit. The image must be publicly reachable over HTTPS and 5 MiB or smaller. Images behind a login, private-network images and unavailable images show an unavailable preview. Uploaded images are read directly from the instance's object store.
|
||||
|
||||
@@ -217,6 +217,8 @@ Alternatives in single braces separated by pipes, so a batch of sends does not l
|
||||
{Hi|Hey|Hello} {{.FirstName}}, {hope you're well|hope things are good}.
|
||||
```
|
||||
|
||||
Each lead gets one option per group, and the same lead gets the same option every time a step renders for them: on a step's [Review tab](/guides/campaigns/#review-before-sending), in a retried send, and in the HTML and plain-text parts alike. Different leads get different options.
|
||||
|
||||
<Callout type="warn" title="Spintax rules">
|
||||
Campaign subject and body only; it does not run in automations. Use **single** braces, not the double braces of merge fields. Only groups containing a pipe count, so a brace run without one (CSS or JSON in an HTML email) is left exactly as written.
|
||||
</Callout>
|
||||
|
||||
@@ -81,7 +81,7 @@ The data is split into groups. Every export includes **Workspace**; the rest are
|
||||
|-------|----------|
|
||||
| Workspace | The organization, members with their [access scope](/guides/team-roles/#access-scope) and mailbox grants, roles, teams, mailboxes and their profile photos, mailbox tags, the column mappings saved by [mailbox imports](/guides/mailbox-import/), inbox vendor connections, [root redirects](/guides/sending-domains/#root-redirects), API keys, webhooks, and settings, including the website tracking site key. Always included |
|
||||
| Contacts | Contacts, labels, the column mappings saved by [contact imports](/guides/contacts-crm/#importing), [lead finder](/guides/lead-finder/) leads, the people found at them, and searches (a search reopens from its first page), segments with their manual overrides, forms with their images, submissions, personalized link tickets and funnel events, notes, activities, the suppression list, and each contact's [HubSpot](/guides/hubspot/) record id, owner, lifecycle stage, lead status and company |
|
||||
| Campaigns | Campaigns, folders, restricted members' campaign and folder grants, sequences, senders, linked segments, attachments, the email image library, per-campaign settings, each lead's step progress with its per-link clicks and per-event opens, the colleagues [copied on each lead](/guides/campaigns/#copying-colleagues-on-one-lead), [placement monitors](/guides/placement-tests/#campaign-placement-monitors), [client reports](/guides/client-reports/) (without their share links), and the [unsubscribe links](/guides/unsubscribe/) already in recipients' inboxes |
|
||||
| Campaigns | Campaigns, folders, restricted members' campaign and folder grants, sequences, senders, linked segments, attachments, the email image library, per-campaign settings, each lead's step progress with its per-link clicks and per-event opens, the colleagues [copied on each lead](/guides/campaigns/#copying-colleagues-on-one-lead), each lead's [personalized emails](/guides/campaigns/#editing-one-leads-email) and whether they are waiting for review, [placement monitors](/guides/placement-tests/#campaign-placement-monitors), [client reports](/guides/client-reports/) (without their share links), and the [unsubscribe links](/guides/unsubscribe/) already in recipients' inboxes |
|
||||
| CRM | Pipelines, deals, tasks, and meeting bookings |
|
||||
| Automations | Automations, connected integrations (including [Clay](/guides/clay/) defaults and events), saved [Apollo](/guides/apollo/) imports, lead sync sources, and the workspace's CRM mode: whether it runs on [HubSpot](/guides/hubspot/), its setup choices, the owner matches, and which Warmbly record is which HubSpot record |
|
||||
| Assistant | Remie sessions and messages (including conversations held in [Slack](/guides/slack/)), skills, MCP servers, and AI settings |
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,376 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/leadreview"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
// reviewContacts loads contacts for the review service through the handler's org-scoped lookup.
|
||||
type reviewContacts struct{ h *Handler }
|
||||
|
||||
func (r reviewContacts) Load(ctx context.Context, orgID, contactID uuid.UUID) (*models.Contact, *errx.Error) {
|
||||
c, xerr := r.h.orgContact(ctx, orgID, contactID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
if c.CustomFields == nil {
|
||||
c.CustomFields = map[string]string{}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// ReviewContacts is the contact loader the review service is built with.
|
||||
func (h *Handler) ReviewContacts() leadreview.Contacts { return reviewContacts{h: h} }
|
||||
|
||||
func (h *Handler) reviewReady(c *gin.Context) (uuid.UUID, uuid.UUID, bool) {
|
||||
if h.LeadReview == nil {
|
||||
errx.JSON(c, errx.InternalError())
|
||||
return uuid.Nil, uuid.Nil, false
|
||||
}
|
||||
orgID, ok := requireOrgID(c)
|
||||
if !ok {
|
||||
return uuid.Nil, uuid.Nil, false
|
||||
}
|
||||
campaignID, ok := parseUUIDParam(c, "id")
|
||||
return orgID, campaignID, ok
|
||||
}
|
||||
|
||||
// GetCampaignReview answers the Review tab's readiness report.
|
||||
//
|
||||
// GET /campaigns/:id/review
|
||||
func (h *Handler) GetCampaignReview(c *gin.Context) {
|
||||
orgID, campaignID, ok := h.reviewReady(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
out, xerr := h.LeadReview.Summary(c.Request.Context(), orgID, campaignID)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
type setReviewRequest struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// SetCampaignReview turns review mode on or off. Turning it off approves every
|
||||
// waiting lead, which puts mail in motion, so it takes the send permission.
|
||||
// It states an absolute mode, so a retry changes nothing more.
|
||||
//
|
||||
// PUT /campaigns/:id/review
|
||||
func (h *Handler) SetCampaignReview(c *gin.Context) {
|
||||
orgID, campaignID, ok := h.reviewReady(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req setReviewRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
if req.Enabled == nil {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "enabled is required"))
|
||||
return
|
||||
}
|
||||
if !*req.Enabled {
|
||||
if xerr := h.hasAccess(c, models.PermSendCampaigns, models.APIPermSendCampaigns); xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
}
|
||||
out, xerr := h.LeadReview.SetReview(c.Request.Context(), orgID, campaignID, *req.Enabled)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityCampaign, &campaignID, map[string]string{
|
||||
"review_leads": strconv.FormatBool(*req.Enabled),
|
||||
}, map[string]string{
|
||||
"held": strconv.Itoa(out.Held),
|
||||
"released": strconv.Itoa(out.Released),
|
||||
})
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// ListCampaignReviewLeads pages the campaign's leads with their review state.
|
||||
//
|
||||
// GET /campaigns/:id/review/leads?status=&missing=&q=&cursor=&limit=
|
||||
func (h *Handler) ListCampaignReviewLeads(c *gin.Context) {
|
||||
orgID, campaignID, ok := h.reviewReady(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
f := models.CampaignReviewLeadsFilter{
|
||||
Status: strings.TrimSpace(c.Query("status")),
|
||||
Missing: strings.TrimSpace(c.Query("missing")),
|
||||
Search: c.Query("q"),
|
||||
}
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "limit must be a number"))
|
||||
return
|
||||
}
|
||||
f.Limit = n
|
||||
}
|
||||
if raw := c.Query("cursor"); raw != "" {
|
||||
cur, err := leadreview.DecodeCursor(raw)
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "invalid cursor"))
|
||||
return
|
||||
}
|
||||
f.Cursor = cur
|
||||
}
|
||||
out, xerr := h.LeadReview.ListLeads(c.Request.Context(), orgID, campaignID, f)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
type reviewLeadsRequest struct {
|
||||
ContactIDs []uuid.UUID `json:"contact_ids"`
|
||||
All bool `json:"all"`
|
||||
}
|
||||
|
||||
// ApproveCampaignReviewLeads releases waiting leads so their first email can
|
||||
// go out. Approving a lead that is not waiting changes nothing, so a retry is safe.
|
||||
//
|
||||
// POST /campaigns/:id/review/approve
|
||||
func (h *Handler) ApproveCampaignReviewLeads(c *gin.Context) {
|
||||
orgID, campaignID, ok := h.reviewReady(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req reviewLeadsRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
out, xerr := h.LeadReview.Approve(c.Request.Context(), orgID, campaignID, req.ContactIDs, req.All)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
h.auditReviewLeads(c, models.AuditActionApprove, campaignID, req, out.Released)
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// ReopenCampaignReviewLeads puts leads not yet emailed back into review.
|
||||
// Reopening a lead already waiting changes nothing, so a retry is safe.
|
||||
//
|
||||
// POST /campaigns/:id/review/reopen
|
||||
func (h *Handler) ReopenCampaignReviewLeads(c *gin.Context) {
|
||||
orgID, campaignID, ok := h.reviewReady(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req reviewLeadsRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
if req.All {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "reopen takes contact_ids; turn review mode on to hold every lead"))
|
||||
return
|
||||
}
|
||||
out, xerr := h.LeadReview.Reopen(c.Request.Context(), orgID, campaignID, req.ContactIDs)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
h.auditReviewLeads(c, models.AuditActionPause, campaignID, req, out.Held)
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// auditReviewLeads records a review write: per lead for one lead, as one campaign entry for a batch.
|
||||
func (h *Handler) auditReviewLeads(c *gin.Context, action models.AuditAction, campaignID uuid.UUID, req reviewLeadsRequest, moved int) {
|
||||
meta := map[string]string{"campaign_id": campaignID.String(), "source": "review", "leads": strconv.Itoa(moved)}
|
||||
if len(req.ContactIDs) == 1 {
|
||||
id := req.ContactIDs[0]
|
||||
h.auditOrg(c, action, models.AuditEntityCampaignLead, &id, nil, meta)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, action, models.AuditEntityCampaignLead, nil, nil, meta)
|
||||
}
|
||||
|
||||
func leadStepParams(c *gin.Context, withStep bool) (contactID, stepID uuid.UUID, ok bool) {
|
||||
if contactID, ok = parseUUIDParam(c, "contactId"); !ok {
|
||||
return
|
||||
}
|
||||
if withStep {
|
||||
stepID, ok = parseUUIDParam(c, "stepId")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GetCampaignLeadEmails renders every email step for one lead as it will be sent.
|
||||
//
|
||||
// GET /campaigns/:id/leads/:contactId/emails
|
||||
func (h *Handler) GetCampaignLeadEmails(c *gin.Context) {
|
||||
orgID, campaignID, ok := h.reviewReady(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
contactID, _, ok := leadStepParams(c, false)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
out, xerr := h.LeadReview.LeadEmails(c.Request.Context(), orgID, campaignID, contactID)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// PutCampaignLeadEmail stores this lead's own copy of one email step. It
|
||||
// replaces the copy as a whole, so a retry lands on the same row.
|
||||
//
|
||||
// PUT /campaigns/:id/leads/:contactId/emails/:stepId
|
||||
func (h *Handler) PutCampaignLeadEmail(c *gin.Context) {
|
||||
orgID, campaignID, ok := h.reviewReady(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
contactID, stepID, ok := leadStepParams(c, true)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req models.LeadStepOverrideInput
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
var editor *uuid.UUID
|
||||
if id, err := middleware.GetUserUUID(c); err == nil && id != uuid.Nil {
|
||||
editor = &id
|
||||
}
|
||||
out, xerr := h.LeadReview.Personalize(c.Request.Context(), orgID, campaignID, contactID, stepID, editor, req)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityCampaignLead, &contactID, nil, map[string]string{
|
||||
"campaign_id": campaignID.String(), "step_id": stepID.String(), "personalized": "true",
|
||||
})
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// DeleteCampaignLeadEmail drops this lead's own copy, so the step's copy goes
|
||||
// out again. Deleting a copy that is not there is a success.
|
||||
//
|
||||
// DELETE /campaigns/:id/leads/:contactId/emails/:stepId
|
||||
func (h *Handler) DeleteCampaignLeadEmail(c *gin.Context) {
|
||||
orgID, campaignID, ok := h.reviewReady(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
contactID, stepID, ok := leadStepParams(c, true)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
removed, xerr := h.LeadReview.ResetPersonalization(c.Request.Context(), orgID, campaignID, contactID, stepID)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
if removed {
|
||||
h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityCampaignLead, &contactID, nil, map[string]string{
|
||||
"campaign_id": campaignID.String(), "step_id": stepID.String(), "personalized": "false",
|
||||
})
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// WriteCampaignLeadEmailAI writes one lead's AI copy for one step now. The
|
||||
// copy is cached where the send reads it, so a retry writes and charges nothing
|
||||
// more; rewrite: true replaces it on purpose and is charged again.
|
||||
//
|
||||
// POST /campaigns/:id/leads/:contactId/emails/:stepId/write
|
||||
func (h *Handler) WriteCampaignLeadEmailAI(c *gin.Context) {
|
||||
orgID, campaignID, ok := h.reviewReady(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
contactID, stepID, ok := leadStepParams(c, true)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
// Rewrite replaces copy already written; it is charged again.
|
||||
Rewrite bool `json:"rewrite"`
|
||||
}
|
||||
if c.Request.ContentLength != 0 {
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
if xerr := h.LeadReview.WriteAI(c.Request.Context(), orgID, campaignID, contactID, stepID, req.Rewrite); xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
out, xerr := h.LeadReview.LeadEmails(c.Request.Context(), orgID, campaignID, contactID)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
type writeReviewAIRequest struct {
|
||||
StepID *uuid.UUID `json:"step_id"`
|
||||
ContactIDs []uuid.UUID `json:"contact_ids"`
|
||||
// WaitingOnly limits the pass to leads waiting for review.
|
||||
WaitingOnly bool `json:"waiting_only"`
|
||||
// After is the previous pass's next cursor.
|
||||
After string `json:"after"`
|
||||
}
|
||||
|
||||
// WriteCampaignReviewAI writes AI copy ahead for one pass of leads still
|
||||
// missing it. Each pass skips what is already written, so a retry charges
|
||||
// nothing twice; call it again with the returned next as after while remaining is above zero.
|
||||
//
|
||||
// POST /campaigns/:id/review/write
|
||||
func (h *Handler) WriteCampaignReviewAI(c *gin.Context) {
|
||||
orgID, campaignID, ok := h.reviewReady(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req writeReviewAIRequest
|
||||
if c.Request.ContentLength != 0 {
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
var after *models.CampaignReviewCursor
|
||||
if req.After != "" {
|
||||
cur, err := leadreview.DecodeCursor(req.After)
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "invalid after cursor"))
|
||||
return
|
||||
}
|
||||
after = cur
|
||||
}
|
||||
out, xerr := h.LeadReview.WriteAIBatch(c.Request.Context(), orgID, campaignID, req.StepID, req.ContactIDs, req.WaitingOnly, after)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
@@ -54,6 +54,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/integration"
|
||||
"github.com/warmbly/warmbly/internal/app/keystatus"
|
||||
"github.com/warmbly/warmbly/internal/app/leadfinder"
|
||||
"github.com/warmbly/warmbly/internal/app/leadreview"
|
||||
"github.com/warmbly/warmbly/internal/app/leadsync"
|
||||
"github.com/warmbly/warmbly/internal/app/mailboxconnect"
|
||||
"github.com/warmbly/warmbly/internal/app/mailboximport"
|
||||
@@ -170,9 +171,11 @@ type Handler struct {
|
||||
TagService group.GroupService
|
||||
CategoryService group.GroupService
|
||||
|
||||
TzService tz.TzService
|
||||
SocketService socket.SocketService
|
||||
TasksService tasks.TasksService
|
||||
TzService tz.TzService
|
||||
SocketService socket.SocketService
|
||||
TasksService tasks.TasksService
|
||||
// LeadReview is the campaign Review tab: readiness, per-lead emails and approvals.
|
||||
LeadReview *leadreview.Service
|
||||
NotificationService notification.Service
|
||||
TwoFAService twofa.Service
|
||||
// ViewPreferencesService keeps each member's saved list layouts.
|
||||
|
||||
@@ -897,6 +897,22 @@ func Run(
|
||||
// safe.
|
||||
campaigns.GET("/:id/leads/:contactId/cc", m.RequireOrganization(), m.RequireAccess(models.PermViewCampaigns, models.APIPermReadCampaigns), m.RequireAccess(models.PermViewContacts, models.APIPermReadContacts), h.GetCampaignLeadCC)
|
||||
campaigns.PUT("/:id/leads/:contactId/cc", m.RequireOrganization(), m.RequireAccess(models.PermManageCampaigns, models.APIPermWriteCampaigns), m.RequireAccess(models.PermViewContacts, models.APIPermReadContacts), h.SetCampaignLeadCC)
|
||||
// Review: the readiness report, each lead's emails as they will
|
||||
// be sent, per-lead copies, and approving leads before their
|
||||
// first email. Every write states an absolute state or is a
|
||||
// cached write-ahead, so retries are safe without an
|
||||
// Idempotency-Key. Approving puts mail in motion, hence the send gate.
|
||||
readContacts := m.RequireAccess(models.PermViewContacts, models.APIPermReadContacts)
|
||||
campaigns.GET("/:id/review", m.RequireOrganization(), m.RequireAccess(models.PermViewCampaigns, models.APIPermReadCampaigns), h.GetCampaignReview)
|
||||
campaigns.PUT("/:id/review", m.RequireOrganization(), m.RequireAccess(models.PermManageCampaigns, models.APIPermWriteCampaigns), h.SetCampaignReview)
|
||||
campaigns.GET("/:id/review/leads", m.RequireOrganization(), m.RequireAccess(models.PermViewCampaigns, models.APIPermReadCampaigns), readContacts, h.ListCampaignReviewLeads)
|
||||
campaigns.POST("/:id/review/approve", m.RequireOrganization(), m.RequireAccess(models.PermSendCampaigns, models.APIPermSendCampaigns), h.ApproveCampaignReviewLeads)
|
||||
campaigns.POST("/:id/review/reopen", m.RequireOrganization(), m.RequireAccess(models.PermManageCampaigns, models.APIPermWriteCampaigns), h.ReopenCampaignReviewLeads)
|
||||
campaigns.POST("/:id/review/write", m.RequireOrganization(), m.RequireAccess(models.PermManageCampaigns, models.APIPermWriteCampaigns), m.RequireAccess(models.PermUseAI, models.APIPermWriteCampaigns), h.WriteCampaignReviewAI)
|
||||
campaigns.GET("/:id/leads/:contactId/emails", m.RequireOrganization(), m.RequireAccess(models.PermViewCampaigns, models.APIPermReadCampaigns), readContacts, h.GetCampaignLeadEmails)
|
||||
campaigns.PUT("/:id/leads/:contactId/emails/:stepId", m.RequireOrganization(), m.RequireAccess(models.PermManageCampaigns, models.APIPermWriteCampaigns), readContacts, h.PutCampaignLeadEmail)
|
||||
campaigns.DELETE("/:id/leads/:contactId/emails/:stepId", m.RequireOrganization(), m.RequireAccess(models.PermManageCampaigns, models.APIPermWriteCampaigns), readContacts, h.DeleteCampaignLeadEmail)
|
||||
campaigns.POST("/:id/leads/:contactId/emails/:stepId/write", m.RequireOrganization(), m.RequireAccess(models.PermManageCampaigns, models.APIPermWriteCampaigns), m.RequireAccess(models.PermUseAI, models.APIPermWriteCampaigns), readContacts, h.WriteCampaignLeadEmailAI)
|
||||
campaigns.GET("/:id/leads/:contactId/cc/suggestions", m.RequireOrganization(), m.RequireAccess(models.PermViewCampaigns, models.APIPermReadCampaigns), m.RequireAccess(models.PermViewContacts, models.APIPermReadContacts), h.SuggestCampaignLeadCC)
|
||||
|
||||
sequences := campaigns.Group("/:id/steps")
|
||||
|
||||
@@ -970,6 +970,16 @@ func pickVariantDeterministic(variants []models.CampaignABVariant, seed string)
|
||||
}
|
||||
|
||||
func (s *service) SelectVariant(ctx context.Context, organizationID, campaignID, contactID, sequenceID uuid.UUID, subject, bodyHTML, bodyPlain string) (*models.VariantSelection, *errx.Error) {
|
||||
return s.selectVariant(ctx, organizationID, campaignID, contactID, sequenceID, subject, bodyHTML, bodyPlain, true)
|
||||
}
|
||||
|
||||
// PeekVariant is SelectVariant without recording a campaign-level assignment,
|
||||
// for a preview: a contact with none yet is shown the step's own copy.
|
||||
func (s *service) PeekVariant(ctx context.Context, organizationID, campaignID, contactID, sequenceID uuid.UUID, subject, bodyHTML, bodyPlain string) (*models.VariantSelection, *errx.Error) {
|
||||
return s.selectVariant(ctx, organizationID, campaignID, contactID, sequenceID, subject, bodyHTML, bodyPlain, false)
|
||||
}
|
||||
|
||||
func (s *service) selectVariant(ctx context.Context, organizationID, campaignID, contactID, sequenceID uuid.UUID, subject, bodyHTML, bodyPlain string, assign bool) (*models.VariantSelection, *errx.Error) {
|
||||
settings, xerr := s.effectiveSettings(ctx, organizationID, campaignID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
@@ -1025,7 +1035,7 @@ func (s *service) SelectVariant(ctx context.Context, organizationID, campaignID,
|
||||
}
|
||||
if assigned != nil && assigned.IsActive && assigned.SequenceID == nil {
|
||||
selected = assigned
|
||||
} else {
|
||||
} else if assign {
|
||||
selected = pickVariantWeightedRandom(campaignVariants)
|
||||
if selected != nil {
|
||||
_ = s.repo.AssignVariant(ctx, campaignID, contactID, selected.ID)
|
||||
|
||||
@@ -21,6 +21,8 @@ var sendOperations = map[string]string{
|
||||
"POST /unibox/agent-drafts/{id}/approve": "sends an inbox agent draft; approve it in the inbox",
|
||||
"POST /campaigns/{id}/test-email": "sends mail; send a test from the campaign editor",
|
||||
"POST /campaigns/{id}/start": "starts sending; use set_campaign_status",
|
||||
"POST /campaigns/{id}/review/approve": "starts sending to the approved leads; approve them in the campaign's Review tab",
|
||||
"PUT /campaigns/{id}/review": "turning review off approves every waiting lead; change it in the campaign's Review tab",
|
||||
"POST /placement/tests": "sends to seed inboxes; use run_placement_test",
|
||||
"POST /placement/batches": "sends to seed inboxes; use run_placement_batch",
|
||||
"POST /integrations/connections/{id}/rotate-inbound-url": "returns a secret inbound URL; rotate it in the dashboard",
|
||||
|
||||
@@ -1391,8 +1391,17 @@ func (s *campaignService) PauseLead(ctx context.Context, orgID, campaignID, cont
|
||||
return nil, errx.InternalError()
|
||||
}
|
||||
if hold == nil {
|
||||
// A manual pause is never refused by the guard, so no row means the
|
||||
// contact is not a lead of this campaign.
|
||||
// The guard refuses only a lead waiting for review, which stays held as it is.
|
||||
current, gerr := s.campaignProgressRepo.GetLeadHold(ctx, campaignID, contactID)
|
||||
if errors.Is(gerr, repository.ErrLeadNotInCampaign) {
|
||||
return nil, errx.New(errx.NotFound, "contact is not a lead of this campaign")
|
||||
}
|
||||
if gerr != nil {
|
||||
return nil, errx.InternalError()
|
||||
}
|
||||
if current != nil && current.Source == models.LeadHoldSourceReview {
|
||||
return current, nil
|
||||
}
|
||||
return nil, errx.New(errx.NotFound, "contact is not a lead of this campaign")
|
||||
}
|
||||
return hold, nil
|
||||
|
||||
@@ -138,6 +138,8 @@ func holdCopy(hold *models.LeadHold) string {
|
||||
return "Copied on the emails to " + r + ", so none of their own are sent"
|
||||
}
|
||||
return "Copied on another lead's emails, so none of their own are sent"
|
||||
case models.LeadHoldSourceReview:
|
||||
return "Waiting for review: their first email goes out once someone approves it"
|
||||
case models.LeadHoldSourceCRM:
|
||||
// The reason already reads "Salesforce: ...", naming the rule that held it.
|
||||
if r := strings.TrimSpace(hold.Reason); r != "" {
|
||||
|
||||
@@ -0,0 +1,571 @@
|
||||
// Package leadreview is the Review tab: a campaign's readiness report, each
|
||||
// lead's emails as they will be sent, per-lead copies, and approving leads
|
||||
// before their first email when the campaign reviews leads.
|
||||
package leadreview
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/credits"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/pkg/tmplvars"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
"github.com/warmbly/warmbly/internal/tasks"
|
||||
)
|
||||
|
||||
const (
|
||||
// MaxBatch bounds the leads one approve, reopen or write call names.
|
||||
MaxBatch = 500
|
||||
// WritePassSize is how many leads one write-ahead pass handles.
|
||||
WritePassSize = 10
|
||||
writeParallel = 4
|
||||
|
||||
defaultListLimit = 50
|
||||
maxListLimit = 200
|
||||
)
|
||||
|
||||
// Campaigns is the slice of the campaign service this package uses.
|
||||
type Campaigns interface {
|
||||
Get(ctx context.Context, orgID, id string) (*models.Campaign, *errx.Error)
|
||||
WakeCampaigns(ctx context.Context, orgID uuid.UUID, campaignIDs []string)
|
||||
}
|
||||
|
||||
// Contacts loads one organization's contacts.
|
||||
type Contacts interface {
|
||||
Load(ctx context.Context, orgID, contactID uuid.UUID) (*models.Contact, *errx.Error)
|
||||
}
|
||||
|
||||
// Undeliverable counts leads verification rejected.
|
||||
type Undeliverable interface {
|
||||
CountUndeliverableLeads(ctx context.Context, campaignID uuid.UUID) (int, error)
|
||||
}
|
||||
|
||||
// Steps lists a campaign's steps in position order.
|
||||
type Steps interface {
|
||||
GetCampaignSequences(ctx context.Context, campaignID uuid.UUID) ([]models.Sequence, error)
|
||||
}
|
||||
|
||||
// Service is the Review tab's backend.
|
||||
type Service struct {
|
||||
Campaigns Campaigns
|
||||
Contacts Contacts
|
||||
Repo repository.CampaignReviewRepository
|
||||
Emails tasks.LeadEmailsService
|
||||
Steps Steps
|
||||
Undeliverable Undeliverable
|
||||
}
|
||||
|
||||
func (s *Service) campaign(ctx context.Context, orgID, campaignID uuid.UUID) (*models.Campaign, *errx.Error) {
|
||||
c, xerr := s.Campaigns.Get(ctx, orgID.String(), campaignID.String())
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
// Get is scoped to orgID but leaves OrganizationID unset; AI writing and billing need it.
|
||||
c.OrganizationID = &orgID
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func emailSteps(all []models.Sequence) []models.Sequence {
|
||||
out := make([]models.Sequence, 0, len(all))
|
||||
for _, st := range all {
|
||||
if st.Kind == "" || st.Kind == "email" {
|
||||
out = append(out, st)
|
||||
}
|
||||
}
|
||||
sort.SliceStable(out, func(a, b int) bool { return out[a].Position < out[b].Position })
|
||||
return out
|
||||
}
|
||||
|
||||
// gaps is every built-in field the campaign's emails print with nothing to fall back on.
|
||||
func gaps(steps []models.Sequence) []string {
|
||||
seen := map[string]bool{}
|
||||
for _, st := range steps {
|
||||
for _, part := range []string{st.Subject, st.BodyHTML, st.BodyPlain} {
|
||||
g, ok := tmplvars.BlankGaps(part)
|
||||
if !ok {
|
||||
g = tmplvars.References(part)
|
||||
}
|
||||
for k := range g {
|
||||
seen[k] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
var out []string
|
||||
for _, f := range models.MissingFieldNames {
|
||||
if seen[f] {
|
||||
out = append(out, f)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Service) steps(ctx context.Context, campaignID uuid.UUID) ([]models.Sequence, *errx.Error) {
|
||||
all, err := s.Steps.GetCampaignSequences(ctx, campaignID)
|
||||
if err != nil {
|
||||
return nil, errx.InternalError()
|
||||
}
|
||||
return emailSteps(all), nil
|
||||
}
|
||||
|
||||
// Summary is the readiness report: how leads split by review state, the merge
|
||||
// fields some of them would leave blank, what sending will skip, and how much
|
||||
// of the first email's AI copy is written ahead.
|
||||
func (s *Service) Summary(ctx context.Context, orgID, campaignID uuid.UUID) (*models.CampaignReviewSummary, *errx.Error) {
|
||||
campaign, xerr := s.campaign(ctx, orgID, campaignID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
steps, xerr := s.steps(ctx, campaignID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
counts, err := s.Repo.Counts(ctx, campaignID)
|
||||
if err != nil {
|
||||
return nil, errx.InternalError()
|
||||
}
|
||||
out := &models.CampaignReviewSummary{CampaignID: campaignID, ReviewLeads: campaign.ReviewLeads, Counts: *counts, Missing: []models.CampaignMissingField{}}
|
||||
|
||||
missing, err := s.Repo.MissingCounts(ctx, campaignID, gaps(steps))
|
||||
if err != nil {
|
||||
return nil, errx.InternalError()
|
||||
}
|
||||
for f, n := range missing {
|
||||
if n > 0 {
|
||||
out.Missing = append(out.Missing, models.CampaignMissingField{Field: f, Leads: n})
|
||||
}
|
||||
}
|
||||
sort.Slice(out.Missing, func(a, b int) bool {
|
||||
if out.Missing[a].Leads != out.Missing[b].Leads {
|
||||
return out.Missing[a].Leads > out.Missing[b].Leads
|
||||
}
|
||||
return out.Missing[a].Field < out.Missing[b].Field
|
||||
})
|
||||
|
||||
for _, st := range steps {
|
||||
if err := tmplvars.CheckCopy(
|
||||
tmplvars.Part{Name: "subject", Text: st.Subject},
|
||||
tmplvars.Part{Name: "body", Text: st.BodyHTML, HTML: true},
|
||||
tmplvars.Part{Name: "plain text", Text: st.BodyPlain},
|
||||
); err != nil {
|
||||
out.TemplateErrors = append(out.TemplateErrors, models.CampaignStepIssue{StepID: st.ID, Position: st.Position, Message: err.Error()})
|
||||
}
|
||||
}
|
||||
|
||||
if s.Undeliverable != nil {
|
||||
if n, err := s.Undeliverable.CountUndeliverableLeads(ctx, campaignID); err == nil {
|
||||
out.Undeliverable = n
|
||||
}
|
||||
}
|
||||
if n, err := s.Repo.UnsubscribedCount(ctx, campaignID); err == nil {
|
||||
out.Unsubscribed = n
|
||||
}
|
||||
|
||||
if len(steps) > 0 {
|
||||
first := steps[0]
|
||||
blocks := s.Emails.AIBlockIDs(first.BodyHTML)
|
||||
if len(blocks) > 0 {
|
||||
ids := blockIDs(blocks)
|
||||
written, pending, err := s.Repo.AIProgress(ctx, campaignID, first.ID, ids)
|
||||
if err != nil {
|
||||
return nil, errx.InternalError()
|
||||
}
|
||||
var per models.Micro
|
||||
for _, b := range blocks {
|
||||
if b.Research {
|
||||
per += credits.EstimateResearchRun
|
||||
} else {
|
||||
per += credits.EstimateWritingAssistant
|
||||
}
|
||||
}
|
||||
id := first.ID
|
||||
out.AI = models.CampaignAIReadiness{
|
||||
StepID: &id, Blocks: len(blocks), Written: written, Pending: pending,
|
||||
EstimatedCostUSD: (per * models.Micro(pending)).USD(),
|
||||
Auto: campaign.Status == "active" && s.Emails.AIAvailable(),
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func blockIDs(blocks []tasks.AIBlockRef) []string {
|
||||
ids := make([]string, len(blocks))
|
||||
for i, b := range blocks {
|
||||
ids[i] = b.ID
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// EncodeCursor and DecodeCursor make the review list's keyset position opaque.
|
||||
func EncodeCursor(c models.CampaignReviewCursor) string {
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(c.Email + "\x1f" + c.ContactID.String()))
|
||||
}
|
||||
|
||||
// ErrInvalidCursor is a cursor this package did not issue.
|
||||
var ErrInvalidCursor = errors.New("invalid cursor")
|
||||
|
||||
func DecodeCursor(raw string) (*models.CampaignReviewCursor, error) {
|
||||
b, err := base64.RawURLEncoding.DecodeString(raw)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidCursor
|
||||
}
|
||||
email, id, ok := strings.Cut(string(b), "\x1f")
|
||||
if !ok {
|
||||
return nil, ErrInvalidCursor
|
||||
}
|
||||
contactID, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidCursor
|
||||
}
|
||||
return &models.CampaignReviewCursor{Email: email, ContactID: contactID}, nil
|
||||
}
|
||||
|
||||
// ListLeads pages the campaign's leads with their review state.
|
||||
func (s *Service) ListLeads(ctx context.Context, orgID, campaignID uuid.UUID, f models.CampaignReviewLeadsFilter) (*models.CampaignReviewLeadsResult, *errx.Error) {
|
||||
if _, xerr := s.campaign(ctx, orgID, campaignID); xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
if !models.ReviewStatusFilters[f.Status] {
|
||||
return nil, errx.New(errx.BadRequest, "status must be one of all, waiting, ready, held or started")
|
||||
}
|
||||
if f.Missing != "" && !contains(models.MissingFieldNames, f.Missing) {
|
||||
return nil, errx.New(errx.BadRequest, "missing must be one of "+strings.Join(models.MissingFieldNames, ", "))
|
||||
}
|
||||
if f.Limit == 0 {
|
||||
f.Limit = defaultListLimit
|
||||
}
|
||||
if f.Limit < 1 || f.Limit > maxListLimit {
|
||||
return nil, errx.New(errx.BadRequest, "limit must be between 1 and 200")
|
||||
}
|
||||
steps, xerr := s.steps(ctx, campaignID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
f.Gaps = gaps(steps)
|
||||
rows, more, err := s.Repo.ListLeads(ctx, campaignID, f)
|
||||
if err != nil {
|
||||
return nil, errx.InternalError()
|
||||
}
|
||||
out := &models.CampaignReviewLeadsResult{Data: rows, Pagination: models.CPagination{HasMore: more}}
|
||||
if more && len(rows) > 0 {
|
||||
last := rows[len(rows)-1]
|
||||
next := EncodeCursor(models.CampaignReviewCursor{Email: last.Email, ContactID: last.ContactID})
|
||||
out.Pagination.NextCursor = &next
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func contains(list []string, v string) bool {
|
||||
for _, x := range list {
|
||||
if x == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetReview turns review mode on or off. Off approves every waiting lead, so
|
||||
// the caller gates it on the send permission.
|
||||
func (s *Service) SetReview(ctx context.Context, orgID, campaignID uuid.UUID, enabled bool) (*models.CampaignReviewChange, *errx.Error) {
|
||||
if _, xerr := s.campaign(ctx, orgID, campaignID); xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
held, released, err := s.Repo.SetReviewLeads(ctx, campaignID, enabled)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("campaign_id", campaignID.String()).Msg("set review mode failed")
|
||||
return nil, errx.InternalError()
|
||||
}
|
||||
if released > 0 {
|
||||
s.Campaigns.WakeCampaigns(ctx, orgID, []string{campaignID.String()})
|
||||
}
|
||||
return &models.CampaignReviewChange{CampaignID: campaignID, ReviewLeads: enabled, Held: held, Released: released}, nil
|
||||
}
|
||||
|
||||
// Approve releases waiting leads, the listed ones or all of them.
|
||||
func (s *Service) Approve(ctx context.Context, orgID, campaignID uuid.UUID, ids []uuid.UUID, all bool) (*models.CampaignReviewChange, *errx.Error) {
|
||||
campaign, xerr := s.campaign(ctx, orgID, campaignID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
if xerr := checkBatch(ids, all); xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
n, err := s.Repo.ApproveLeads(ctx, campaignID, ids, all)
|
||||
if err != nil {
|
||||
return nil, errx.InternalError()
|
||||
}
|
||||
if n > 0 {
|
||||
s.Campaigns.WakeCampaigns(ctx, orgID, []string{campaignID.String()})
|
||||
}
|
||||
return &models.CampaignReviewChange{CampaignID: campaignID, ReviewLeads: campaign.ReviewLeads, Released: n}, nil
|
||||
}
|
||||
|
||||
// Reopen sends leads not yet emailed back to waiting for review.
|
||||
func (s *Service) Reopen(ctx context.Context, orgID, campaignID uuid.UUID, ids []uuid.UUID) (*models.CampaignReviewChange, *errx.Error) {
|
||||
campaign, xerr := s.campaign(ctx, orgID, campaignID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
if xerr := checkBatch(ids, false); xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
n, err := s.Repo.ReopenLeads(ctx, campaignID, ids)
|
||||
if err != nil {
|
||||
return nil, errx.InternalError()
|
||||
}
|
||||
return &models.CampaignReviewChange{CampaignID: campaignID, ReviewLeads: campaign.ReviewLeads, Held: n}, nil
|
||||
}
|
||||
|
||||
func checkBatch(ids []uuid.UUID, all bool) *errx.Error {
|
||||
if all && len(ids) > 0 {
|
||||
return errx.New(errx.BadRequest, "send either contact_ids or all, not both")
|
||||
}
|
||||
if !all && len(ids) == 0 {
|
||||
return errx.New(errx.BadRequest, "contact_ids is required")
|
||||
}
|
||||
if len(ids) > MaxBatch {
|
||||
return errx.New(errx.BadRequest, "at most 500 contact_ids per request")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) lead(ctx context.Context, orgID, campaignID, contactID uuid.UUID) (*models.Campaign, *models.Contact, *models.CampaignReviewLead, *errx.Error) {
|
||||
campaign, xerr := s.campaign(ctx, orgID, campaignID)
|
||||
if xerr != nil {
|
||||
return nil, nil, nil, xerr
|
||||
}
|
||||
lead, err := s.Repo.GetLead(ctx, campaignID, contactID)
|
||||
if errors.Is(err, repository.ErrLeadNotInCampaign) {
|
||||
return nil, nil, nil, errx.New(errx.NotFound, "contact is not a lead of this campaign")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, nil, errx.InternalError()
|
||||
}
|
||||
contact, xerr := s.Contacts.Load(ctx, orgID, contactID)
|
||||
if xerr != nil {
|
||||
return nil, nil, nil, xerr
|
||||
}
|
||||
return campaign, contact, lead, nil
|
||||
}
|
||||
|
||||
// LeadEmails renders every email step for one lead, the way it will be sent.
|
||||
func (s *Service) LeadEmails(ctx context.Context, orgID, campaignID, contactID uuid.UUID) (*models.LeadEmails, *errx.Error) {
|
||||
campaign, contact, lead, xerr := s.lead(ctx, orgID, campaignID, contactID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
steps, from, xerr := s.Emails.LeadEmails(ctx, orgID, campaign, contact)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, st := range steps {
|
||||
for _, m := range st.Missing {
|
||||
if !seen[m] {
|
||||
seen[m] = true
|
||||
lead.Missing = append(lead.Missing, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
return &models.LeadEmails{CampaignID: campaignID, Lead: *lead, From: from, Steps: steps}, nil
|
||||
}
|
||||
|
||||
func (s *Service) emailStep(ctx context.Context, campaignID, stepID uuid.UUID) (*models.Sequence, *errx.Error) {
|
||||
steps, xerr := s.steps(ctx, campaignID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
for i := range steps {
|
||||
if steps[i].ID == stepID {
|
||||
return &steps[i], nil
|
||||
}
|
||||
}
|
||||
return nil, errx.New(errx.NotFound, "email step not found in this campaign")
|
||||
}
|
||||
|
||||
// errStepSent refuses a change to an email this lead already received.
|
||||
func errStepSent() *errx.Error {
|
||||
return errx.NewWithIdentifier(errx.Conflict, "lead_step_sent", "This lead already received this email, so its copy can no longer change.")
|
||||
}
|
||||
|
||||
func (s *Service) stepSent(ctx context.Context, orgID uuid.UUID, campaign *models.Campaign, contact *models.Contact, stepID uuid.UUID) (bool, *errx.Error) {
|
||||
steps, _, xerr := s.Emails.LeadEmails(ctx, orgID, campaign, contact)
|
||||
if xerr != nil {
|
||||
return false, xerr
|
||||
}
|
||||
for _, st := range steps {
|
||||
if st.StepID == stepID {
|
||||
return st.Sent, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Personalize stores this lead's own copy of one email step. It is checked
|
||||
// like a step's copy and replaces the step, and any A/B variant, for this lead.
|
||||
func (s *Service) Personalize(ctx context.Context, orgID, campaignID, contactID, stepID uuid.UUID, editor *uuid.UUID, in models.LeadStepOverrideInput) (*models.LeadStepOverride, *errx.Error) {
|
||||
campaign, contact, _, xerr := s.lead(ctx, orgID, campaignID, contactID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
if _, xerr := s.emailStep(ctx, campaignID, stepID); xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
if strings.TrimSpace(in.BodyHTML) == "" && strings.TrimSpace(in.BodyPlain) == "" {
|
||||
return nil, errx.New(errx.BadRequest, "the email needs a body")
|
||||
}
|
||||
if len([]rune(in.Subject)) > 998 || len(in.BodyHTML) > 524288 || len(in.BodyPlain) > 262144 {
|
||||
return nil, errx.New(errx.BadRequest, "the email is too long")
|
||||
}
|
||||
if err := tmplvars.CheckCopy(
|
||||
tmplvars.Part{Name: "subject", Text: in.Subject},
|
||||
tmplvars.Part{Name: "body", Text: in.BodyHTML, HTML: true},
|
||||
tmplvars.Part{Name: "plain text", Text: in.BodyPlain},
|
||||
); err != nil {
|
||||
return nil, errx.InvalidTemplate(err)
|
||||
}
|
||||
sent, xerr := s.stepSent(ctx, orgID, campaign, contact, stepID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
if sent {
|
||||
return nil, errStepSent()
|
||||
}
|
||||
o, err := s.Repo.UpsertOverride(ctx, models.LeadStepOverride{
|
||||
CampaignID: campaignID, ContactID: contactID, StepID: stepID,
|
||||
Subject: in.Subject, BodyHTML: in.BodyHTML, BodyPlain: in.BodyPlain, EditedBy: editor,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errx.InternalError()
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
// ResetPersonalization drops this lead's own copy, so the step's copy goes out again.
|
||||
func (s *Service) ResetPersonalization(ctx context.Context, orgID, campaignID, contactID, stepID uuid.UUID) (bool, *errx.Error) {
|
||||
campaign, contact, _, xerr := s.lead(ctx, orgID, campaignID, contactID)
|
||||
if xerr != nil {
|
||||
return false, xerr
|
||||
}
|
||||
if _, xerr := s.emailStep(ctx, campaignID, stepID); xerr != nil {
|
||||
return false, xerr
|
||||
}
|
||||
sent, xerr := s.stepSent(ctx, orgID, campaign, contact, stepID)
|
||||
if xerr != nil {
|
||||
return false, xerr
|
||||
}
|
||||
if sent {
|
||||
return false, errStepSent()
|
||||
}
|
||||
removed, err := s.Repo.DeleteOverride(ctx, campaignID, contactID, stepID)
|
||||
if err != nil {
|
||||
return false, errx.InternalError()
|
||||
}
|
||||
return removed, nil
|
||||
}
|
||||
|
||||
// WriteAI writes one lead's AI copy for one step now, charged as it would be at
|
||||
// send time; rewrite replaces copy already written, and is charged again.
|
||||
func (s *Service) WriteAI(ctx context.Context, orgID, campaignID, contactID, stepID uuid.UUID, rewrite bool) *errx.Error {
|
||||
campaign, contact, _, xerr := s.lead(ctx, orgID, campaignID, contactID)
|
||||
if xerr != nil {
|
||||
return xerr
|
||||
}
|
||||
return s.Emails.WriteLeadAI(ctx, orgID, campaign, contact, stepID, rewrite)
|
||||
}
|
||||
|
||||
// WriteAIBatch writes the first email's AI copy (or the named step's) for one
|
||||
// pass of leads still missing it: the listed leads, else every waiting lead
|
||||
// when waitingOnly, else every lead not yet emailed. A caller repeats it until
|
||||
// Remaining is zero, so a closed tab or a low balance loses nothing written.
|
||||
func (s *Service) WriteAIBatch(ctx context.Context, orgID, campaignID uuid.UUID, stepID *uuid.UUID, ids []uuid.UUID, waitingOnly bool, after *models.CampaignReviewCursor) (*models.LeadAIBatchResult, *errx.Error) {
|
||||
campaign, xerr := s.campaign(ctx, orgID, campaignID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
if len(ids) > MaxBatch {
|
||||
return nil, errx.New(errx.BadRequest, "at most 500 contact_ids per request")
|
||||
}
|
||||
steps, xerr := s.steps(ctx, campaignID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
if len(steps) == 0 {
|
||||
return &models.LeadAIBatchResult{}, nil
|
||||
}
|
||||
step := &steps[0]
|
||||
if stepID != nil {
|
||||
if step, xerr = s.emailStep(ctx, campaignID, *stepID); xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
}
|
||||
blocks := blockIDs(s.Emails.AIBlockIDs(step.BodyHTML))
|
||||
if len(blocks) == 0 {
|
||||
return &models.LeadAIBatchResult{}, nil
|
||||
}
|
||||
pass, total, err := s.Repo.PendingAILeads(ctx, campaignID, step.ID, blocks, ids, waitingOnly, after, WritePassSize)
|
||||
if err != nil {
|
||||
return nil, errx.InternalError()
|
||||
}
|
||||
|
||||
out := &models.LeadAIBatchResult{}
|
||||
var mu sync.Mutex
|
||||
stop := ""
|
||||
sem := make(chan struct{}, writeParallel)
|
||||
var wg sync.WaitGroup
|
||||
for _, lead := range pass {
|
||||
id := lead.ContactID
|
||||
mu.Lock()
|
||||
halted := stop != ""
|
||||
mu.Unlock()
|
||||
if halted {
|
||||
break
|
||||
}
|
||||
sem <- struct{}{}
|
||||
wg.Add(1)
|
||||
go func(contactID uuid.UUID) {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
contact, xerr := s.Contacts.Load(ctx, orgID, contactID)
|
||||
if xerr == nil {
|
||||
xerr = s.Emails.WriteLeadAI(ctx, orgID, campaign, contact, step.ID, false)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
switch {
|
||||
case xerr == nil:
|
||||
out.Written++
|
||||
case xerr.ResponseCode() == "insufficient_credits" || xerr.ResponseCode() == "usage_cap_exceeded":
|
||||
stop = xerr.ResponseCode()
|
||||
default:
|
||||
out.Failed++
|
||||
}
|
||||
}(id)
|
||||
}
|
||||
wg.Wait()
|
||||
out.Stopped = stop
|
||||
// A stopped pass resumes where it began, so nothing it did not reach is
|
||||
// skipped; a finished one moves past every lead it tried, failed ones included.
|
||||
if stop == "" && len(pass) > 0 {
|
||||
out.Next = EncodeCursor(pass[len(pass)-1])
|
||||
out.Remaining = total - len(pass)
|
||||
} else {
|
||||
if after != nil {
|
||||
out.Next = EncodeCursor(*after)
|
||||
}
|
||||
out.Remaining = total - out.Written
|
||||
}
|
||||
if out.Remaining < 0 {
|
||||
out.Remaining = 0
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package leadreview
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
func TestCursorRoundTrip(t *testing.T) {
|
||||
in := models.CampaignReviewCursor{Email: "a+b@example.com", ContactID: uuid.New()}
|
||||
out, err := DecodeCursor(EncodeCursor(in))
|
||||
if err != nil || *out != in {
|
||||
t.Fatalf("round trip = %+v, %v", out, err)
|
||||
}
|
||||
for _, bad := range []string{"%%%", "bm90LWEtY3Vyc29y", EncodeCursor(in) + "x"} {
|
||||
if _, err := DecodeCursor(bad); err == nil {
|
||||
t.Errorf("DecodeCursor(%q) accepted a cursor it did not issue", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGapsSkipFieldsWithAFallback(t *testing.T) {
|
||||
steps := []models.Sequence{
|
||||
{Subject: "Quick question, {{.FirstName}}", BodyHTML: `<p>{{if .Company}}{{.Company}}{{end}}</p>`},
|
||||
{Kind: "email", BodyPlain: `{{.Phone | default "you"}}`},
|
||||
}
|
||||
got := gaps(emailSteps(steps))
|
||||
if len(got) != 1 || got[0] != "FirstName" {
|
||||
t.Fatalf("gaps = %v, want [FirstName]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckBatch(t *testing.T) {
|
||||
id := uuid.New()
|
||||
cases := []struct {
|
||||
ids []uuid.UUID
|
||||
all bool
|
||||
fail bool
|
||||
}{
|
||||
{nil, true, false},
|
||||
{[]uuid.UUID{id}, false, false},
|
||||
{nil, false, true},
|
||||
{[]uuid.UUID{id}, true, true},
|
||||
{make([]uuid.UUID, MaxBatch+1), false, true},
|
||||
}
|
||||
for i, c := range cases {
|
||||
if got := checkBatch(c.ids, c.all) != nil; got != c.fail {
|
||||
t.Errorf("case %d: refused = %v, want %v", i, got, c.fail)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package leadreview
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
const (
|
||||
writeAheadTick = 30 * time.Second
|
||||
// writeAheadPasses bounds one campaign's passes per tick, so one big list cannot starve the rest.
|
||||
writeAheadPasses = 5
|
||||
writeAheadCampaign = 100
|
||||
)
|
||||
|
||||
// StartAIWriteAhead writes the first email's AI copy for every lead of an active
|
||||
// campaign before it is due, so the Review tab shows it and the send reuses it.
|
||||
// It runs on one backend (leader loop) and keeps each campaign's cursor in memory.
|
||||
func (s *Service) StartAIWriteAhead(ctx context.Context) {
|
||||
cursors := map[uuid.UUID]*models.CampaignReviewCursor{}
|
||||
t := time.NewTicker(writeAheadTick)
|
||||
defer t.Stop()
|
||||
for {
|
||||
s.writeAheadTick(ctx, cursors)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) writeAheadTick(ctx context.Context, cursors map[uuid.UUID]*models.CampaignReviewCursor) {
|
||||
if !s.Emails.AIAvailable() {
|
||||
return
|
||||
}
|
||||
seen := map[uuid.UUID]bool{}
|
||||
stopped := map[uuid.UUID]bool{}
|
||||
var after uuid.UUID
|
||||
for ctx.Err() == nil {
|
||||
page, err := s.Repo.ActiveAICampaigns(ctx, after, writeAheadCampaign)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("AI write-ahead: list campaigns")
|
||||
return
|
||||
}
|
||||
for _, c := range page {
|
||||
seen[c.CampaignID] = true
|
||||
if !stopped[c.OrgID] && !s.writeAheadCampaign(ctx, c.OrgID, c.CampaignID, cursors) {
|
||||
stopped[c.OrgID] = true
|
||||
}
|
||||
}
|
||||
if len(page) < writeAheadCampaign {
|
||||
break
|
||||
}
|
||||
after = page[len(page)-1].CampaignID
|
||||
}
|
||||
for id := range cursors {
|
||||
if !seen[id] {
|
||||
delete(cursors, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// writeAheadCampaign runs a few passes and reports false when the organization's balance or cap stopped it.
|
||||
func (s *Service) writeAheadCampaign(ctx context.Context, orgID, campaignID uuid.UUID, cursors map[uuid.UUID]*models.CampaignReviewCursor) bool {
|
||||
for i := 0; i < writeAheadPasses && ctx.Err() == nil; i++ {
|
||||
res, xerr := s.WriteAIBatch(ctx, orgID, campaignID, nil, nil, false, cursors[campaignID])
|
||||
if xerr != nil {
|
||||
log.Warn().Str("campaign_id", campaignID.String()).Str("code", xerr.ResponseCode()).Msg("AI write-ahead: pass failed")
|
||||
return true
|
||||
}
|
||||
if res.Stopped != "" {
|
||||
return false
|
||||
}
|
||||
// The end of the list wraps to the start, so a lead that failed is tried again next tick.
|
||||
if res.Remaining == 0 || res.Next == "" {
|
||||
delete(cursors, campaignID)
|
||||
return true
|
||||
}
|
||||
next, err := DecodeCursor(res.Next)
|
||||
if err != nil {
|
||||
delete(cursors, campaignID)
|
||||
return true
|
||||
}
|
||||
cursors[campaignID] = next
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package leadreview
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
"github.com/warmbly/warmbly/internal/tasks"
|
||||
)
|
||||
|
||||
type aheadRepo struct {
|
||||
repository.CampaignReviewRepository
|
||||
campaigns []repository.CampaignOrg
|
||||
mu sync.Mutex
|
||||
// pending holds each campaign's leads still missing their AI copy, by email.
|
||||
pending map[uuid.UUID][]models.CampaignReviewCursor
|
||||
}
|
||||
|
||||
func (r *aheadRepo) ActiveAICampaigns(_ context.Context, after uuid.UUID, limit int) ([]repository.CampaignOrg, error) {
|
||||
var out []repository.CampaignOrg
|
||||
for _, c := range r.campaigns {
|
||||
if c.CampaignID.String() > after.String() && len(out) < limit {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *aheadRepo) PendingAILeads(_ context.Context, campaignID, _ uuid.UUID, _ []string, _ []uuid.UUID, _ bool, after *models.CampaignReviewCursor, limit int) ([]models.CampaignReviewCursor, int, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
var rest []models.CampaignReviewCursor
|
||||
for _, l := range r.pending[campaignID] {
|
||||
if after == nil || l.Email > after.Email {
|
||||
rest = append(rest, l)
|
||||
}
|
||||
}
|
||||
if len(rest) > limit {
|
||||
return rest[:limit], len(rest), nil
|
||||
}
|
||||
return rest, len(rest), nil
|
||||
}
|
||||
|
||||
func (r *aheadRepo) written(campaignID, contactID uuid.UUID) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
list := r.pending[campaignID]
|
||||
for i, l := range list {
|
||||
if l.ContactID == contactID {
|
||||
r.pending[campaignID] = append(list[:i:i], list[i+1:]...)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type aheadEmails struct {
|
||||
tasks.LeadEmailsService
|
||||
repo *aheadRepo
|
||||
broke map[uuid.UUID]bool // orgs out of balance
|
||||
failed map[uuid.UUID]bool // contacts whose writing fails
|
||||
mu sync.Mutex
|
||||
calls map[uuid.UUID]int
|
||||
}
|
||||
|
||||
func (e *aheadEmails) AIAvailable() bool { return true }
|
||||
|
||||
func (e *aheadEmails) AIBlockIDs(string) []tasks.AIBlockRef {
|
||||
return []tasks.AIBlockRef{{ID: "b1"}}
|
||||
}
|
||||
|
||||
func (e *aheadEmails) WriteLeadAI(_ context.Context, orgID uuid.UUID, c *models.Campaign, contact *models.Contact, _ uuid.UUID, _ bool) *errx.Error {
|
||||
e.mu.Lock()
|
||||
e.calls[contact.ID]++
|
||||
e.mu.Unlock()
|
||||
// The real writer refuses a campaign without its organization.
|
||||
if c.OrganizationID == nil || *c.OrganizationID != orgID {
|
||||
return errx.NewWithIdentifier(errx.ServiceUnavailable, "ai_generation_failed", "no organization")
|
||||
}
|
||||
if e.broke[orgID] {
|
||||
return errx.NewWithIdentifier(errx.PaymentRequired, "insufficient_credits", "balance")
|
||||
}
|
||||
if e.failed[contact.ID] {
|
||||
return errx.NewWithIdentifier(errx.ServiceUnavailable, "ai_generation_failed", "failed")
|
||||
}
|
||||
e.repo.written(c.ID, contact.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
type aheadCampaigns struct{}
|
||||
|
||||
func (aheadCampaigns) Get(_ context.Context, orgID, id string) (*models.Campaign, *errx.Error) {
|
||||
return &models.Campaign{ID: uuid.MustParse(id), Status: "active"}, nil
|
||||
}
|
||||
func (aheadCampaigns) WakeCampaigns(context.Context, uuid.UUID, []string) {}
|
||||
|
||||
type aheadContacts struct{}
|
||||
|
||||
func (aheadContacts) Load(_ context.Context, _, id uuid.UUID) (*models.Contact, *errx.Error) {
|
||||
return &models.Contact{ID: id}, nil
|
||||
}
|
||||
|
||||
type aheadSteps struct{}
|
||||
|
||||
func (aheadSteps) GetCampaignSequences(context.Context, uuid.UUID) ([]models.Sequence, error) {
|
||||
return []models.Sequence{{ID: uuid.New(), Kind: "email", BodyHTML: `<span data-ai-var="b1"></span>`}}, nil
|
||||
}
|
||||
|
||||
func leads(n int) []models.CampaignReviewCursor {
|
||||
out := make([]models.CampaignReviewCursor, n)
|
||||
for i := range out {
|
||||
out[i] = models.CampaignReviewCursor{Email: fmt.Sprintf("lead%03d@example.com", i), ContactID: uuid.New()}
|
||||
}
|
||||
sort.Slice(out, func(a, b int) bool { return out[a].Email < out[b].Email })
|
||||
return out
|
||||
}
|
||||
|
||||
// Every lead of an active campaign gets written over a few ticks, a lead that
|
||||
// keeps failing neither stalls the rest nor is given up on, and a workspace out
|
||||
// of balance stops after one attempt per tick.
|
||||
func TestWriteAheadWritesEveryLeadAndStopsAtTheBalance(t *testing.T) {
|
||||
paying, broke := uuid.New(), uuid.New()
|
||||
big, small, unpaid := uuid.New(), uuid.New(), uuid.New()
|
||||
bigLeads, smallLeads, unpaidLeads := leads(75), leads(3), leads(20)
|
||||
repo := &aheadRepo{
|
||||
campaigns: []repository.CampaignOrg{{CampaignID: big, OrgID: paying}, {CampaignID: small, OrgID: paying}, {CampaignID: unpaid, OrgID: broke}},
|
||||
pending: map[uuid.UUID][]models.CampaignReviewCursor{
|
||||
big: append([]models.CampaignReviewCursor(nil), bigLeads...), small: smallLeads, unpaid: unpaidLeads,
|
||||
},
|
||||
}
|
||||
sort.Slice(repo.campaigns, func(a, b int) bool {
|
||||
return repo.campaigns[a].CampaignID.String() < repo.campaigns[b].CampaignID.String()
|
||||
})
|
||||
stuck := bigLeads[0].ContactID
|
||||
emails := &aheadEmails{repo: repo, broke: map[uuid.UUID]bool{broke: true}, failed: map[uuid.UUID]bool{stuck: true}, calls: map[uuid.UUID]int{}}
|
||||
s := &Service{Campaigns: aheadCampaigns{}, Contacts: aheadContacts{}, Repo: repo, Emails: emails, Steps: aheadSteps{}}
|
||||
|
||||
cursors := map[uuid.UUID]*models.CampaignReviewCursor{}
|
||||
s.writeAheadTick(context.Background(), cursors)
|
||||
if got := len(repo.pending[small]); got != 0 {
|
||||
t.Fatalf("small campaign has %d leads unwritten after one tick", got)
|
||||
}
|
||||
if got := len(repo.pending[big]); got != 75-writeAheadPasses*WritePassSize+1 {
|
||||
t.Fatalf("big campaign has %d unwritten after one tick, want one tick's worth written", got)
|
||||
}
|
||||
for tick := 0; tick < 3; tick++ {
|
||||
s.writeAheadTick(context.Background(), cursors)
|
||||
}
|
||||
if got := len(repo.pending[big]); got != 1 || repo.pending[big][0].ContactID != stuck {
|
||||
t.Fatalf("big campaign pending = %v, want only the failing lead", repo.pending[big])
|
||||
}
|
||||
if emails.calls[stuck] < 2 {
|
||||
t.Fatalf("a failing lead was tried %d times; the list should wrap and retry it", emails.calls[stuck])
|
||||
}
|
||||
unpaidCalls := 0
|
||||
for _, l := range unpaidLeads {
|
||||
unpaidCalls += emails.calls[l.ContactID]
|
||||
}
|
||||
if len(repo.pending[unpaid]) != 20 || unpaidCalls > 4*WritePassSize {
|
||||
t.Fatalf("workspace without balance: %d pending, %d attempts over 4 ticks", len(repo.pending[unpaid]), unpaidCalls)
|
||||
}
|
||||
|
||||
// A campaign that stops being active loses its cursor.
|
||||
repo.campaigns = nil
|
||||
s.writeAheadTick(context.Background(), cursors)
|
||||
if len(cursors) != 0 {
|
||||
t.Fatalf("cursors kept for inactive campaigns: %v", cursors)
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,10 @@ func (s *service) ImportFrom(
|
||||
if _, err := tx.Exec(ctx, `SET LOCAL statement_timeout = 0`); err != nil {
|
||||
return nil, fmt.Errorf("lift statement timeout: %w", err)
|
||||
}
|
||||
// Imported leads keep the hold they had; a review campaign does not re-hold them on insert.
|
||||
if _, err := tx.Exec(ctx, `SELECT set_config('warmbly.org_import', 'on', true)`); err != nil {
|
||||
return nil, fmt.Errorf("mark import transaction: %w", err)
|
||||
}
|
||||
|
||||
report(6, "applying workspace settings")
|
||||
if err := s.mergeOrganization(ctx, tx, orgID, manifest); err != nil {
|
||||
|
||||
@@ -643,6 +643,12 @@ var Tables = []Table{
|
||||
Scope: `campaign_id IN ` + orgCampaigns,
|
||||
Note: "Must travel with the leads, or a copied contact held on their own lead is released into a second sequence.",
|
||||
},
|
||||
{
|
||||
// Below campaign_leads and sequences, which it references.
|
||||
Name: "campaign_lead_step_overrides", Group: models.OrgDataGroupCampaigns,
|
||||
Scope: `campaign_id IN ` + orgCampaigns,
|
||||
Note: "Must travel, or a lead someone personalized an email for receives the step's shared copy instead.",
|
||||
},
|
||||
{
|
||||
Name: "campaign_lead_removals", Group: models.OrgDataGroupCampaigns,
|
||||
Scope: `campaign_id IN ` + orgCampaigns,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
DROP TRIGGER IF EXISTS campaign_lead_enrol_review_hold ON public.campaign_leads;
|
||||
DROP FUNCTION IF EXISTS public.campaign_lead_enrol_review_hold();
|
||||
|
||||
-- 000230's cc hold as it was.
|
||||
CREATE OR REPLACE FUNCTION public.campaign_lead_cc_hold() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
UPDATE campaign_leads cl
|
||||
SET paused_at = CASE
|
||||
WHEN cl.paused_at IS NOT NULL AND (cl.paused_until IS NULL OR cl.paused_until > NOW())
|
||||
THEN cl.paused_at ELSE NOW() END,
|
||||
paused_until = NULL,
|
||||
pause_reason = (SELECT c.email FROM contacts c WHERE c.id = NEW.contact_id),
|
||||
pause_source = 'cc'
|
||||
WHERE cl.campaign_id = NEW.campaign_id
|
||||
AND cl.contact_id = NEW.cc_contact_id
|
||||
AND NOT (cl.pause_source = 'manual' AND cl.paused_at IS NOT NULL
|
||||
AND (cl.paused_until IS NULL OR cl.paused_until > NOW()));
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
UPDATE campaign_leads cl
|
||||
SET paused_at = NULL, paused_until = NULL, pause_reason = NULL, pause_source = NULL
|
||||
WHERE cl.campaign_id = OLD.campaign_id
|
||||
AND cl.contact_id = OLD.cc_contact_id
|
||||
AND cl.pause_source = 'cc'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM campaign_lead_cc x
|
||||
WHERE x.campaign_id = OLD.campaign_id AND x.cc_contact_id = OLD.cc_contact_id
|
||||
);
|
||||
RETURN OLD;
|
||||
END;
|
||||
$$;
|
||||
|
||||
DROP FUNCTION IF EXISTS public.campaign_review_lock_key(uuid);
|
||||
DROP FUNCTION IF EXISTS public.campaign_lead_attempted(uuid, uuid);
|
||||
DROP TABLE IF EXISTS public.campaign_lead_step_overrides;
|
||||
|
||||
-- A lead still waiting for review stays held, as a member's pause, rather than
|
||||
-- being released unreviewed. A live hold of another kind is left in its place.
|
||||
UPDATE public.campaign_leads
|
||||
SET paused_at = COALESCE(paused_at, review_pending_at), paused_until = NULL,
|
||||
pause_source = 'manual', pause_reason = 'Waiting for review'
|
||||
WHERE pause_source = 'review'
|
||||
OR (review_pending_at IS NOT NULL
|
||||
AND (paused_at IS NULL OR (paused_until IS NOT NULL AND paused_until <= NOW())));
|
||||
ALTER TABLE public.campaign_leads DROP COLUMN IF EXISTS review_pending_at;
|
||||
|
||||
ALTER TABLE public.campaign_leads DROP CONSTRAINT IF EXISTS campaign_leads_pause_source_check;
|
||||
ALTER TABLE public.campaign_leads
|
||||
ADD CONSTRAINT campaign_leads_pause_source_check
|
||||
CHECK (pause_source IS NULL OR pause_source IN ('manual', 'out_of_office', 'inbox_tagging', 'cc', 'crm')) NOT VALID;
|
||||
|
||||
ALTER TABLE public.campaigns DROP COLUMN IF EXISTS review_leads;
|
||||
@@ -0,0 +1,128 @@
|
||||
SET LOCAL lock_timeout = '10s';
|
||||
|
||||
-- Review mode: a lead's first email waits until a member approves the lead.
|
||||
ALTER TABLE public.campaigns ADD COLUMN review_leads boolean NOT NULL DEFAULT false;
|
||||
|
||||
-- When a lead started waiting for review; cleared only by an approval or by
|
||||
-- turning review off. Routing and the send gate read it as a hold, and no other
|
||||
-- hold's writes touch it.
|
||||
ALTER TABLE public.campaign_leads ADD COLUMN review_pending_at timestamptz;
|
||||
|
||||
-- A waiting lead whose hold slot is free also carries a 'review' hold there,
|
||||
-- so a release that predates review_pending_at still skips it during a deploy
|
||||
-- or after a rollback.
|
||||
ALTER TABLE public.campaign_leads DROP CONSTRAINT IF EXISTS campaign_leads_pause_source_check;
|
||||
-- NOT VALID: 000402 validates it in its own transaction.
|
||||
ALTER TABLE public.campaign_leads
|
||||
ADD CONSTRAINT campaign_leads_pause_source_check
|
||||
CHECK (pause_source IS NULL OR pause_source IN ('manual', 'out_of_office', 'inbox_tagging', 'cc', 'crm', 'review')) NOT VALID;
|
||||
|
||||
-- One lead's own copy of one email step. It replaces the step's copy for that
|
||||
-- lead only and is sent as written, without A/B variants or AI blocks.
|
||||
CREATE TABLE public.campaign_lead_step_overrides (
|
||||
campaign_id uuid NOT NULL,
|
||||
contact_id uuid NOT NULL,
|
||||
sequence_id uuid NOT NULL REFERENCES public.sequences (id) ON DELETE CASCADE,
|
||||
subject text NOT NULL DEFAULT '',
|
||||
body_html text NOT NULL DEFAULT '',
|
||||
body_plain text NOT NULL DEFAULT '',
|
||||
edited_by uuid REFERENCES public.users (id) ON DELETE SET NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (campaign_id, contact_id, sequence_id),
|
||||
FOREIGN KEY (campaign_id, contact_id) REFERENCES public.campaign_leads (campaign_id, contact_id) ON DELETE CASCADE,
|
||||
CONSTRAINT campaign_lead_step_overrides_size CHECK (
|
||||
char_length(subject) <= 998
|
||||
AND octet_length(body_html) <= 524288
|
||||
AND octet_length(body_plain) <= 262144
|
||||
)
|
||||
);
|
||||
|
||||
-- Serves the sequences FK's cascade.
|
||||
CREATE INDEX idx_campaign_lead_step_overrides_sequence ON public.campaign_lead_step_overrides (sequence_id);
|
||||
|
||||
-- Whether a lead has been emailed in a campaign, or has a send in flight.
|
||||
CREATE FUNCTION public.campaign_lead_attempted(p_campaign uuid, p_contact uuid) RETURNS boolean
|
||||
LANGUAGE sql STABLE AS $$
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM public.campaign_contact_progress p
|
||||
WHERE p.campaign_id = p_campaign AND p.contact_id = p_contact
|
||||
AND (p.sent_at IS NOT NULL OR p.dispatched_at IS NOT NULL)
|
||||
)
|
||||
$$;
|
||||
|
||||
-- Serializes enrolment with turning review on: enrolments share this lock and
|
||||
-- the toggle takes it exclusively, so no lead is enrolled against a stale flag.
|
||||
CREATE FUNCTION public.campaign_review_lock_key(p_campaign uuid) RETURNS bigint
|
||||
LANGUAGE sql IMMUTABLE AS $$
|
||||
SELECT hashtextextended('campaign_review:' || p_campaign::text, 0)
|
||||
$$;
|
||||
|
||||
-- A trigger rather than callers, so every path that enrols a lead (segments,
|
||||
-- imports, the API, automations) waits for review the same way. An org
|
||||
-- transfer import sets warmbly.org_import so each lead keeps the state it had.
|
||||
CREATE FUNCTION public.campaign_lead_enrol_review_hold() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
reviewing boolean;
|
||||
BEGIN
|
||||
IF COALESCE(current_setting('warmbly.org_import', true), '') = 'on' THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
PERFORM pg_advisory_xact_lock_shared(public.campaign_review_lock_key(NEW.campaign_id));
|
||||
SELECT c.review_leads INTO reviewing FROM public.campaigns c WHERE c.id = NEW.campaign_id;
|
||||
IF reviewing THEN
|
||||
NEW.review_pending_at := COALESCE(NEW.review_pending_at, NOW());
|
||||
IF NEW.paused_at IS NULL THEN
|
||||
NEW.paused_at := NOW();
|
||||
NEW.paused_until := NULL;
|
||||
NEW.pause_reason := NULL;
|
||||
NEW.pause_source := 'review';
|
||||
END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Fires after campaign_lead_enrol_cc_hold (triggers run in name order), so a
|
||||
-- copied contact keeps its cc hold.
|
||||
CREATE TRIGGER campaign_lead_enrol_review_hold
|
||||
BEFORE INSERT ON public.campaign_leads
|
||||
FOR EACH ROW EXECUTE FUNCTION public.campaign_lead_enrol_review_hold();
|
||||
|
||||
-- 000230's cc hold, except that a released copy still waiting for review gets
|
||||
-- its 'review' hold back for releases that read only the hold slot.
|
||||
CREATE OR REPLACE FUNCTION public.campaign_lead_cc_hold() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
-- A member's own live pause outranks this; anything else is replaced.
|
||||
UPDATE campaign_leads cl
|
||||
SET paused_at = CASE
|
||||
WHEN cl.paused_at IS NOT NULL AND (cl.paused_until IS NULL OR cl.paused_until > NOW())
|
||||
THEN cl.paused_at ELSE NOW() END,
|
||||
paused_until = NULL,
|
||||
pause_reason = (SELECT c.email FROM contacts c WHERE c.id = NEW.contact_id),
|
||||
pause_source = 'cc'
|
||||
WHERE cl.campaign_id = NEW.campaign_id
|
||||
AND cl.contact_id = NEW.cc_contact_id
|
||||
AND NOT (cl.pause_source = 'manual' AND cl.paused_at IS NOT NULL
|
||||
AND (cl.paused_until IS NULL OR cl.paused_until > NOW()));
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
-- Released once no lead in the campaign copies them any more.
|
||||
UPDATE campaign_leads cl
|
||||
SET paused_at = CASE WHEN cl.review_pending_at IS NOT NULL THEN NOW() END,
|
||||
paused_until = NULL,
|
||||
pause_reason = NULL,
|
||||
pause_source = CASE WHEN cl.review_pending_at IS NOT NULL THEN 'review' END
|
||||
WHERE cl.campaign_id = OLD.campaign_id
|
||||
AND cl.contact_id = OLD.cc_contact_id
|
||||
AND cl.pause_source = 'cc'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM campaign_lead_cc x
|
||||
WHERE x.campaign_id = OLD.campaign_id AND x.cc_contact_id = OLD.cc_contact_id
|
||||
);
|
||||
RETURN OLD;
|
||||
END;
|
||||
$$;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- A validated constraint has no unvalidated form to return to; 000401's down
|
||||
-- migration replaces it.
|
||||
SELECT 1;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Validates the pause_source CHECK 000401 re-added NOT VALID. A VALIDATE only
|
||||
-- takes a SHARE UPDATE EXCLUSIVE lock, so writes continue while it scans.
|
||||
ALTER TABLE public.campaign_leads VALIDATE CONSTRAINT campaign_leads_pause_source_check;
|
||||
@@ -23,6 +23,7 @@ const (
|
||||
AuditActionStop AuditAction = "stop"
|
||||
AuditActionPause AuditAction = "pause"
|
||||
AuditActionResume AuditAction = "resume"
|
||||
AuditActionApprove AuditAction = "approve"
|
||||
AuditActionSend AuditAction = "send"
|
||||
AuditActionDuplicate AuditAction = "duplicate"
|
||||
AuditActionDisconnect AuditAction = "disconnect"
|
||||
|
||||
@@ -159,6 +159,10 @@ type Campaign struct {
|
||||
// and the campaign ramp as its only volume limits.
|
||||
WarmupGraduation bool `json:"warmup_graduation"`
|
||||
|
||||
// ReviewLeads holds each new lead until a member approves its first email.
|
||||
// Changed through PUT /campaigns/:id/review, which holds or releases leads.
|
||||
ReviewLeads bool `json:"review_leads"`
|
||||
|
||||
// ESP/provider matching: off | prefer | strict.
|
||||
ESPMatchMode string `json:"esp_match_mode"`
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Review states of one lead, derived from its hold and whether it was emailed.
|
||||
const (
|
||||
// LeadReviewWaiting is held for review: nothing goes out until it is approved.
|
||||
LeadReviewWaiting = "waiting"
|
||||
// LeadReviewReady has not been emailed yet and nothing keeps it from starting.
|
||||
LeadReviewReady = "ready"
|
||||
// LeadReviewHeld has not been emailed yet and is paused for another reason.
|
||||
LeadReviewHeld = "held"
|
||||
// LeadReviewStarted has been emailed, or has a send in flight.
|
||||
LeadReviewStarted = "started"
|
||||
)
|
||||
|
||||
// ReviewStatusFilters are the values ?status= accepts on the review lead list.
|
||||
var ReviewStatusFilters = map[string]bool{
|
||||
"": true, "all": true, LeadReviewWaiting: true, LeadReviewReady: true, LeadReviewHeld: true, LeadReviewStarted: true,
|
||||
}
|
||||
|
||||
// MissingFieldNames are the contact fields the readiness check counts blanks of.
|
||||
var MissingFieldNames = []string{"FirstName", "LastName", "Company", "Phone"}
|
||||
|
||||
// CampaignReviewLead is one row of the review list.
|
||||
type CampaignReviewLead struct {
|
||||
ContactID uuid.UUID `json:"contact_id"`
|
||||
Email string `json:"email"`
|
||||
FirstName string `json:"first_name"`
|
||||
LastName string `json:"last_name"`
|
||||
Company string `json:"company"`
|
||||
Status string `json:"status"`
|
||||
Hold *LeadHold `json:"hold,omitempty"`
|
||||
// Personalized counts the steps with this lead's own copy.
|
||||
Personalized int `json:"personalized"`
|
||||
// Missing lists the fields the campaign's emails print that this lead has empty.
|
||||
Missing []string `json:"missing,omitempty"`
|
||||
AddedAt *time.Time `json:"added_at,omitempty"`
|
||||
}
|
||||
|
||||
// CampaignReviewLeadsResult is the paginated review list.
|
||||
type CampaignReviewLeadsResult struct {
|
||||
Data []CampaignReviewLead `json:"data"`
|
||||
Pagination CPagination `json:"pagination"`
|
||||
}
|
||||
|
||||
// CampaignReviewLeadsFilter narrows the review list.
|
||||
type CampaignReviewLeadsFilter struct {
|
||||
Status string
|
||||
// Missing keeps leads with this field empty; one of MissingFieldNames.
|
||||
Missing string
|
||||
Search string
|
||||
// Gaps are the fields the emails print with no fallback, which decide Missing on each row.
|
||||
Gaps []string
|
||||
Cursor *CampaignReviewCursor
|
||||
Limit int
|
||||
}
|
||||
|
||||
// CampaignReviewCursor is the keyset position of the review list: email, then contact id.
|
||||
type CampaignReviewCursor struct {
|
||||
Email string
|
||||
ContactID uuid.UUID
|
||||
}
|
||||
|
||||
// CampaignReviewCounts is how the campaign's leads split by review state.
|
||||
type CampaignReviewCounts struct {
|
||||
Total int `json:"total"`
|
||||
Waiting int `json:"waiting"`
|
||||
Ready int `json:"ready"`
|
||||
Held int `json:"held"`
|
||||
Started int `json:"started"`
|
||||
Personalized int `json:"personalized"`
|
||||
}
|
||||
|
||||
// CampaignMissingField is one field the emails print that some unstarted leads have empty.
|
||||
type CampaignMissingField struct {
|
||||
Field string `json:"field"`
|
||||
Leads int `json:"leads"`
|
||||
}
|
||||
|
||||
// CampaignAIReadiness is how much of the first email's AI copy is written ahead.
|
||||
type CampaignAIReadiness struct {
|
||||
StepID *uuid.UUID `json:"step_id,omitempty"`
|
||||
// Blocks is how many AI blocks the first email has.
|
||||
Blocks int `json:"blocks"`
|
||||
// Written counts unstarted leads whose first email has every block written.
|
||||
Written int `json:"written"`
|
||||
// Pending counts unstarted leads with at least one block still to write.
|
||||
Pending int `json:"pending"`
|
||||
// EstimatedCostUSD is about what writing the pending blocks costs, at the per-block estimate the balance check reserves.
|
||||
EstimatedCostUSD float64 `json:"estimated_cost_usd"`
|
||||
// Auto is true while the instance writes the pending leads on its own (an active campaign with AI available).
|
||||
Auto bool `json:"auto"`
|
||||
}
|
||||
|
||||
// CampaignReviewSummary is the Review tab's readiness report.
|
||||
type CampaignReviewSummary struct {
|
||||
CampaignID uuid.UUID `json:"campaign_id"`
|
||||
ReviewLeads bool `json:"review_leads"`
|
||||
Counts CampaignReviewCounts `json:"counts"`
|
||||
Missing []CampaignMissingField `json:"missing"`
|
||||
// Undeliverable counts leads whose address verification rejected.
|
||||
Undeliverable int `json:"undeliverable"`
|
||||
// Unsubscribed counts leads who opted out; sending skips them.
|
||||
Unsubscribed int `json:"unsubscribed"`
|
||||
AI CampaignAIReadiness `json:"ai"`
|
||||
// TemplateErrors names email steps whose copy does not render as written.
|
||||
TemplateErrors []CampaignStepIssue `json:"template_errors,omitempty"`
|
||||
}
|
||||
|
||||
// CampaignStepIssue names a step and what is wrong with it.
|
||||
type CampaignStepIssue struct {
|
||||
StepID uuid.UUID `json:"step_id"`
|
||||
Position int `json:"position"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// CampaignReviewChange is the answer to a review write: how many leads moved.
|
||||
type CampaignReviewChange struct {
|
||||
CampaignID uuid.UUID `json:"campaign_id"`
|
||||
ReviewLeads bool `json:"review_leads"`
|
||||
// Held counts leads put into review; Released counts leads approved.
|
||||
Held int `json:"held"`
|
||||
Released int `json:"released"`
|
||||
}
|
||||
|
||||
// LeadStepOverride is one lead's own copy of one email step.
|
||||
type LeadStepOverride struct {
|
||||
CampaignID uuid.UUID `json:"campaign_id"`
|
||||
ContactID uuid.UUID `json:"contact_id"`
|
||||
StepID uuid.UUID `json:"step_id"`
|
||||
Subject string `json:"subject"`
|
||||
BodyHTML string `json:"body_html"`
|
||||
BodyPlain string `json:"body_plain"`
|
||||
EditedBy *uuid.UUID `json:"edited_by,omitempty"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// LeadStepOverrideInput is the body of PUT .../emails/:stepId.
|
||||
type LeadStepOverrideInput struct {
|
||||
Subject string `json:"subject"`
|
||||
BodyHTML string `json:"body_html"`
|
||||
BodyPlain string `json:"body_plain"`
|
||||
}
|
||||
|
||||
// LeadEmailAIBlock is one AI block in a step, and whether its copy is written yet.
|
||||
type LeadEmailAIBlock struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Written bool `json:"written"`
|
||||
}
|
||||
|
||||
// LeadEmailFrom is the mailbox a lead's emails go out from, when it is known.
|
||||
type LeadEmailFrom struct {
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
// LeadEmailStep is one email step rendered for one lead.
|
||||
type LeadEmailStep struct {
|
||||
StepID uuid.UUID `json:"step_id"`
|
||||
Position int `json:"position"`
|
||||
Name string `json:"name"`
|
||||
Subject string `json:"subject"`
|
||||
BodyHTML string `json:"body_html"`
|
||||
BodyPlain string `json:"body_plain"`
|
||||
// Source is the template this lead's copy renders from: their own copy, the
|
||||
// A/B arm drawn for them, or the step's. What a personalization starts from.
|
||||
Source LeadStepOverrideInput `json:"source"`
|
||||
// Threaded is a follow-up that replies in the lead's thread, so its subject is the conversation's.
|
||||
Threaded bool `json:"threaded"`
|
||||
// Personalized is this lead's own copy, which replaces the step's.
|
||||
Personalized bool `json:"personalized"`
|
||||
EditedAt *time.Time `json:"edited_at,omitempty"`
|
||||
// StepChanged is a personalized step whose shared copy was edited after it.
|
||||
StepChanged bool `json:"step_changed"`
|
||||
// VariantID is the A/B variant this lead gets, absent for the step's own copy.
|
||||
VariantID *uuid.UUID `json:"variant_id,omitempty"`
|
||||
AIBlocks []LeadEmailAIBlock `json:"ai_blocks,omitempty"`
|
||||
// Missing lists fields the copy prints that this lead has empty.
|
||||
Missing []string `json:"missing,omitempty"`
|
||||
Errors []string `json:"errors,omitempty"`
|
||||
Sent bool `json:"sent"`
|
||||
SentAt *time.Time `json:"sent_at,omitempty"`
|
||||
}
|
||||
|
||||
// LeadEmails is every email step of a campaign rendered for one lead.
|
||||
type LeadEmails struct {
|
||||
CampaignID uuid.UUID `json:"campaign_id"`
|
||||
Lead CampaignReviewLead `json:"lead"`
|
||||
From *LeadEmailFrom `json:"from,omitempty"`
|
||||
Steps []LeadEmailStep `json:"steps"`
|
||||
}
|
||||
|
||||
// LeadAIBatchResult is one pass of writing AI copy ahead for several leads.
|
||||
type LeadAIBatchResult struct {
|
||||
Written int `json:"written"`
|
||||
Failed int `json:"failed"`
|
||||
// Remaining counts leads in the request's scope still to write after this pass.
|
||||
Remaining int `json:"remaining"`
|
||||
// Stopped names why the pass ended early: insufficient_credits or usage_cap_exceeded.
|
||||
Stopped string `json:"stopped,omitempty"`
|
||||
// Next is the cursor the following pass sends as after, so leads that failed are not retried in a loop.
|
||||
Next string `json:"next,omitempty"`
|
||||
}
|
||||
@@ -147,6 +147,9 @@ const (
|
||||
// LeadHoldSourceCRM is a hold a CRM rule wrote: a lead status, a
|
||||
// conversion or an open opportunity in Salesforce.
|
||||
LeadHoldSourceCRM = "crm"
|
||||
// LeadHoldSourceReview is a lead in a review campaign that a member has
|
||||
// not approved yet. Only an approval or turning review off lifts it.
|
||||
LeadHoldSourceReview = "review"
|
||||
)
|
||||
|
||||
// Lead status constants for ContactCampaignProgress.Status.
|
||||
|
||||
@@ -2,25 +2,35 @@ package repository
|
||||
|
||||
const campaignRecoveryReason = "Waiting for send confirmation. Warmbly will continue this contact automatically when the outcome is confirmed."
|
||||
|
||||
// reviewPendingSQL is a lead in a review campaign that nobody has approved yet.
|
||||
// Like the recovery hold it is its own column, so no other hold's write lifts it.
|
||||
func reviewPendingSQL(alias string) string {
|
||||
return alias + ".review_pending_at IS NOT NULL"
|
||||
}
|
||||
|
||||
func effectiveLeadHold(alias string) string {
|
||||
return "(" + liveHold(alias) + " OR " + recoveryPausedLeadSQL(alias) + ")"
|
||||
return "(" + liveHold(alias) + " OR " + recoveryPausedLeadSQL(alias) + " OR " + reviewPendingSQL(alias) + ")"
|
||||
}
|
||||
|
||||
func recoveryLeadSinceSQL(alias string) string {
|
||||
return alias + ".send_outcome_pending_at"
|
||||
}
|
||||
|
||||
// effectiveLeadHoldColumns projects the hold routing reads: a send recovery
|
||||
// first, then waiting for review, then the hold slot.
|
||||
func effectiveLeadHoldColumns(alias string) string {
|
||||
recovery := recoveryPausedLeadSQL(alias)
|
||||
return `CASE WHEN ` + recovery + ` THEN ` + recoveryLeadSinceSQL(alias) + ` ELSE ` + alias + `.paused_at END,
|
||||
CASE WHEN ` + recovery + ` THEN NULL::timestamptz ELSE ` + alias + `.paused_until END,
|
||||
CASE WHEN ` + recovery + ` THEN '` + campaignRecoveryReason + `' ELSE COALESCE(` + alias + `.pause_reason,'') END,
|
||||
CASE WHEN ` + recovery + ` THEN 'send_recovery' ELSE COALESCE(` + alias + `.pause_source,'') END`
|
||||
review := reviewPendingSQL(alias)
|
||||
return `CASE WHEN ` + recovery + ` THEN ` + recoveryLeadSinceSQL(alias) + ` WHEN ` + review + ` THEN ` + alias + `.review_pending_at ELSE ` + alias + `.paused_at END,
|
||||
CASE WHEN ` + recovery + ` OR ` + review + ` THEN NULL::timestamptz ELSE ` + alias + `.paused_until END,
|
||||
CASE WHEN ` + recovery + ` THEN '` + campaignRecoveryReason + `' WHEN ` + review + ` THEN '' ELSE COALESCE(` + alias + `.pause_reason,'') END,
|
||||
CASE WHEN ` + recovery + ` THEN 'send_recovery' WHEN ` + review + ` THEN 'review' ELSE COALESCE(` + alias + `.pause_source,'') END`
|
||||
}
|
||||
|
||||
func effectiveLeadHoldJSON(alias string) string {
|
||||
return `CASE WHEN ` + recoveryPausedLeadSQL(alias) + ` THEN json_build_object(
|
||||
'since',` + recoveryLeadSinceSQL(alias) + `,'until',NULL,'reason','` + campaignRecoveryReason + `','source','send_recovery')
|
||||
WHEN ` + reviewPendingSQL(alias) + ` THEN json_build_object('since',` + alias + `.review_pending_at,'until',NULL,'reason','','source','review')
|
||||
WHEN ` + liveHold(alias) + ` THEN json_build_object('since',` + alias + `.paused_at,'until',` + alias + `.paused_until,
|
||||
'reason',COALESCE(` + alias + `.pause_reason,''),'source',COALESCE(` + alias + `.pause_source,'')) END`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
// Review mode holds every lead not yet emailed, and every lead enrolled later,
|
||||
// through the same hold column routing already skips; nothing but an approval
|
||||
// or turning review off releases one.
|
||||
//
|
||||
// WARMBLY_TEST_DB=postgres://warmbly:warmbly@localhost:15432/<db>?sslmode=disable \
|
||||
// go test ./internal/repository/ -run LiveCampaignReview -v
|
||||
func TestLiveCampaignReviewHoldsUntilApproved(t *testing.T) {
|
||||
handle, pool := liveContactDB(t)
|
||||
f := newSharedOrgFixture(t, pool)
|
||||
ctx := context.Background()
|
||||
review := NewCampaignReviewRepository(pool)
|
||||
progress := NewCampaignProgressRepository(handle.Pool)
|
||||
|
||||
pending := func(contact uuid.UUID) bool {
|
||||
t.Helper()
|
||||
var at *time.Time
|
||||
if err := pool.QueryRow(ctx, `SELECT review_pending_at FROM campaign_leads WHERE campaign_id = $1 AND contact_id = $2`, f.campaign, contact).Scan(&at); err != nil {
|
||||
t.Fatalf("read review: %v", err)
|
||||
}
|
||||
return at != nil
|
||||
}
|
||||
source := func(contact uuid.UUID) string {
|
||||
t.Helper()
|
||||
var s *string
|
||||
if err := pool.QueryRow(ctx, `SELECT pause_source FROM campaign_leads WHERE campaign_id = $1 AND contact_id = $2`, f.campaign, contact).Scan(&s); err != nil {
|
||||
t.Fatalf("read hold: %v", err)
|
||||
}
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
return *s
|
||||
}
|
||||
step := uuid.New()
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO sequences (id, campaign_id, organization_id, name, subject, body_plain, body_html, wait_after, position, kind)
|
||||
VALUES ($1, $2, $3, 'Intro', 'Hi {{.FirstName}}', 'Hello', '<p>Hello</p>', 0, 1, 'email')`, step, f.campaign, f.org); err != nil {
|
||||
t.Fatalf("step: %v", err)
|
||||
}
|
||||
|
||||
before := addLead(t, f, "before-"+uuid.New().String()[:6]+"@test.local", "valid", true)
|
||||
emailed := addLead(t, f, "emailed-"+uuid.New().String()[:6]+"@test.local", "valid", true)
|
||||
paused := addLead(t, f, "paused-"+uuid.New().String()[:6]+"@test.local", "valid", true)
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO campaign_contact_progress (campaign_id, contact_id, sequence_id, sent_at) VALUES ($1, $2, $3, NOW())`, f.campaign, emailed, step); err != nil {
|
||||
t.Fatalf("progress: %v", err)
|
||||
}
|
||||
if _, err := progress.HoldLead(ctx, f.campaign, paused, nil, "by hand", models.LeadHoldSourceManual); err != nil {
|
||||
t.Fatalf("pause: %v", err)
|
||||
}
|
||||
|
||||
held, released, err := review.SetReviewLeads(ctx, f.campaign, true)
|
||||
if err != nil || held != 2 || released != 0 {
|
||||
t.Fatalf("enable = %d held, %d released, %v; want both leads not yet emailed", held, released, err)
|
||||
}
|
||||
if !pending(before) || source(before) != "review" {
|
||||
t.Fatalf("lead enrolled before review: pending %v, slot %q", pending(before), source(before))
|
||||
}
|
||||
// A paused lead waits too, and keeps its pause in the slot.
|
||||
if !pending(paused) || source(paused) != "manual" {
|
||||
t.Fatalf("paused lead: pending %v, slot %q", pending(paused), source(paused))
|
||||
}
|
||||
if pending(emailed) || source(emailed) != "" {
|
||||
t.Fatalf("emailed lead was touched")
|
||||
}
|
||||
// Enabling again moves nothing, so an approval is never undone by a retry.
|
||||
if held, _, _ := review.SetReviewLeads(ctx, f.campaign, true); held != 0 {
|
||||
t.Fatalf("repeat enable held %d", held)
|
||||
}
|
||||
|
||||
// Every enrolment path goes through the trigger.
|
||||
later := addLead(t, f, "later-"+uuid.New().String()[:6]+"@test.local", "valid", true)
|
||||
if !pending(later) || source(later) != "review" {
|
||||
t.Fatalf("lead enrolled in a review campaign: pending %v, slot %q", pending(later), source(later))
|
||||
}
|
||||
if hold, err := progress.GetLeadHold(ctx, f.campaign, later); err != nil || hold == nil || hold.Source != models.LeadHoldSourceReview {
|
||||
t.Fatalf("hold of a waiting lead = %+v, %v", hold, err)
|
||||
}
|
||||
|
||||
// A member's pause cannot replace the review hold.
|
||||
if hold, err := progress.HoldLead(ctx, f.campaign, later, nil, "", models.LeadHoldSourceManual); err != nil || hold != nil {
|
||||
t.Fatalf("manual pause over review = %+v, %v; want refused", hold, err)
|
||||
}
|
||||
// Nor can an out-of-office hold.
|
||||
if held, err := progress.HoldLeadEverywhere(ctx, later, nil, "away", models.LeadHoldSourceOutOfOffice); err != nil || len(held) != 0 {
|
||||
t.Fatalf("automatic hold over review = %v, %v; want refused", held, err)
|
||||
}
|
||||
|
||||
// A copied contact is held as cc, and goes back to review when the copy is removed.
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO campaign_lead_cc (campaign_id, contact_id, cc_contact_id) VALUES ($1, $2, $3)`, f.campaign, emailed, later); err != nil {
|
||||
t.Fatalf("cc: %v", err)
|
||||
}
|
||||
if got := source(later); got != "cc" {
|
||||
t.Fatalf("copied lead = %q, want cc", got)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `DELETE FROM campaign_lead_cc WHERE campaign_id = $1 AND cc_contact_id = $2`, f.campaign, later); err != nil {
|
||||
t.Fatalf("uncc: %v", err)
|
||||
}
|
||||
if !pending(later) || source(later) != "review" {
|
||||
t.Fatalf("lead released from cc in a review campaign: pending %v, slot %q", pending(later), source(later))
|
||||
}
|
||||
|
||||
// Resuming lifts the pause and nothing else: the lead still waits for review.
|
||||
if _, err := progress.ResumeLead(ctx, f.campaign, paused); err != nil {
|
||||
t.Fatalf("resume: %v", err)
|
||||
}
|
||||
if !pending(paused) || source(paused) != "" {
|
||||
t.Fatalf("resumed lead: pending %v, slot %q", pending(paused), source(paused))
|
||||
}
|
||||
// Resuming a lead that only waits for review approves nothing.
|
||||
if lifted, err := progress.ResumeLead(ctx, f.campaign, later); err != nil || lifted || !pending(later) || source(later) != "review" {
|
||||
t.Fatalf("resume of a waiting lead lifted %v (%v): pending %v, slot %q", lifted, err, pending(later), source(later))
|
||||
}
|
||||
|
||||
counts, err := review.Counts(ctx, f.campaign)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if counts.Total != 4 || counts.Waiting != 3 || counts.Started != 1 {
|
||||
t.Fatalf("counts = %+v, want 3 waiting and 1 started", counts)
|
||||
}
|
||||
missing, err := review.MissingCounts(ctx, f.campaign, []string{"FirstName", "Company", "bogus"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if missing["Company"] != 3 || missing["FirstName"] != 0 {
|
||||
t.Fatalf("missing = %v; want company blank on the 3 unstarted leads", missing)
|
||||
}
|
||||
|
||||
rows, more, err := review.ListLeads(ctx, f.campaign, models.CampaignReviewLeadsFilter{Status: models.LeadReviewWaiting, Limit: 2, Gaps: []string{"Company"}})
|
||||
if err != nil || len(rows) != 2 || !more {
|
||||
t.Fatalf("first page = %d rows, more %v, %v", len(rows), more, err)
|
||||
}
|
||||
if rows[0].Hold == nil || rows[0].Hold.Source != models.LeadHoldSourceReview || len(rows[0].Missing) != 1 {
|
||||
t.Fatalf("row = %+v", rows[0])
|
||||
}
|
||||
next, _, err := review.ListLeads(ctx, f.campaign, models.CampaignReviewLeadsFilter{Status: models.LeadReviewWaiting, Limit: 2,
|
||||
Cursor: &models.CampaignReviewCursor{Email: rows[1].Email, ContactID: rows[1].ContactID}})
|
||||
if err != nil || len(next) != 1 || next[0].ContactID == rows[0].ContactID || next[0].ContactID == rows[1].ContactID {
|
||||
t.Fatalf("second page = %+v, %v", next, err)
|
||||
}
|
||||
|
||||
// Routing reads waiting for review as a hold even with the slot emptied, as
|
||||
// a release that predates review_pending_at would leave it.
|
||||
if _, err := pool.Exec(ctx, `UPDATE campaign_leads SET paused_at = NULL, pause_source = NULL WHERE campaign_id = $1 AND contact_id = $2`, f.campaign, later); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if route, err := progress.RouteContact(ctx, f.campaign, later); err != nil || route == nil || route.Hold == nil || route.Hold.Source != models.LeadHoldSourceReview {
|
||||
t.Fatalf("route of a waiting lead with an empty slot = %+v, %v; want held for review", route, err)
|
||||
}
|
||||
|
||||
// Per-lead copy round trip, removed with the lead.
|
||||
o, err := review.UpsertOverride(ctx, models.LeadStepOverride{CampaignID: f.campaign, ContactID: later, StepID: step, Subject: "Mine", BodyHTML: "<p>Only you</p>"})
|
||||
if err != nil || o.Subject != "Mine" {
|
||||
t.Fatalf("upsert = %+v, %v", o, err)
|
||||
}
|
||||
if got, _ := review.GetOverride(ctx, f.campaign, later, step); got == nil || got.BodyHTML != "<p>Only you</p>" {
|
||||
t.Fatalf("get = %+v", got)
|
||||
}
|
||||
|
||||
// AI written ahead: a lead with every block cached counts as written.
|
||||
if err := progress.SaveResolvedAIVariable(ctx, f.campaign, before, step, "b1", "text"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
written, toWrite, err := review.AIProgress(ctx, f.campaign, step, []string{"b1"})
|
||||
if err != nil || written != 1 || toWrite != 1 {
|
||||
t.Fatalf("ai progress = %d written, %d to write, %v; want 1 and 1 (the personalized lead needs none)", written, toWrite, err)
|
||||
}
|
||||
ids, total, err := review.PendingAILeads(ctx, f.campaign, step, []string{"b1"}, nil, true, nil, 10)
|
||||
if err != nil || total != 1 || len(ids) != 1 || ids[0].ContactID != paused {
|
||||
t.Fatalf("pending = %v of %d, %v", ids, total, err)
|
||||
}
|
||||
|
||||
// Approving one lead releases only it; reopening puts it back.
|
||||
if n, err := review.ApproveLeads(ctx, f.campaign, []uuid.UUID{before}, false); err != nil || n != 1 {
|
||||
t.Fatalf("approve = %d, %v", n, err)
|
||||
}
|
||||
if pending(before) || source(before) != "" {
|
||||
t.Fatalf("approved lead: pending %v, slot %q", pending(before), source(before))
|
||||
}
|
||||
if n, err := review.ReopenLeads(ctx, f.campaign, []uuid.UUID{before, emailed}); err != nil || n != 1 {
|
||||
t.Fatalf("reopen = %d, %v; want only the lead not yet emailed", n, err)
|
||||
}
|
||||
|
||||
// Off approves everyone waiting.
|
||||
_, released, err = review.SetReviewLeads(ctx, f.campaign, false)
|
||||
if err != nil || released != 3 {
|
||||
t.Fatalf("disable released %d, %v; want 3", released, err)
|
||||
}
|
||||
if if2 := addLead(t, f, "after-"+uuid.New().String()[:6]+"@test.local", "valid", true); source(if2) != "" {
|
||||
t.Fatalf("lead enrolled after review was turned off is held")
|
||||
}
|
||||
}
|
||||
|
||||
// An org transfer import keeps each lead's hold as it was exported.
|
||||
func TestLiveCampaignReviewImportKeepsHolds(t *testing.T) {
|
||||
_, pool := liveContactDB(t)
|
||||
f := newSharedOrgFixture(t, pool)
|
||||
ctx := context.Background()
|
||||
if _, err := pool.Exec(ctx, `UPDATE campaigns SET review_leads = true WHERE id = $1`, f.campaign); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
contact := uuid.New()
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO contacts (id, user_id, organization_id, email, first_name, last_name, company, phone, custom_fields)
|
||||
VALUES ($1, $2, $3, $4, 'A', 'B', '', '', '{}'::jsonb)`, contact, f.owner, f.org, "imported-"+contact.String()[:6]+"@test.local"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err := tx.Exec(ctx, `SELECT set_config('warmbly.org_import', 'on', true)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO campaign_leads (campaign_id, contact_id) VALUES ($1, $2)`, f.campaign, contact); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var source *string
|
||||
if err := tx.QueryRow(ctx, `SELECT pause_source FROM campaign_leads WHERE campaign_id = $1 AND contact_id = $2`, f.campaign, contact).Scan(&source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if source != nil {
|
||||
t.Fatalf("imported lead was held with %q", *source)
|
||||
}
|
||||
}
|
||||
@@ -181,7 +181,7 @@ const CAMPAIGN_SELECT = `id, name, description, status,
|
||||
utm_tracking, utm_source, utm_medium, utm_campaign,
|
||||
unsubscribe_mode,
|
||||
continuous, idle_since, stop_on_meeting,
|
||||
follow_up_sender, timezone_mode, warmup_graduation`
|
||||
follow_up_sender, timezone_mode, warmup_graduation, review_leads`
|
||||
|
||||
func getCampaign(rows db.Scannable, campaign *models.Campaign, extra ...any) error {
|
||||
var dest []any = []any{
|
||||
@@ -203,7 +203,7 @@ func getCampaign(rows db.Scannable, campaign *models.Campaign, extra ...any) err
|
||||
&campaign.UTMTracking, &campaign.UTMSource, &campaign.UTMMedium, &campaign.UTMCampaign,
|
||||
&campaign.UnsubscribeMode,
|
||||
&campaign.Continuous, &campaign.IdleSince, &campaign.StopOnMeeting,
|
||||
&campaign.FollowUpSender, &campaign.TimezoneMode, &campaign.WarmupGraduation,
|
||||
&campaign.FollowUpSender, &campaign.TimezoneMode, &campaign.WarmupGraduation, &campaign.ReviewLeads,
|
||||
}
|
||||
dest = append(dest, extra...)
|
||||
return rows.Scan(
|
||||
@@ -230,7 +230,7 @@ const CAMPAIGN_SELECT_FULL = `
|
||||
c.utm_tracking, c.utm_source, c.utm_medium, c.utm_campaign,
|
||||
c.unsubscribe_mode,
|
||||
c.continuous, c.idle_since, c.stop_on_meeting,
|
||||
c.follow_up_sender, c.timezone_mode, c.warmup_graduation,
|
||||
c.follow_up_sender, c.timezone_mode, c.warmup_graduation, c.review_leads,
|
||||
COALESCE(array_agg(cet.tag_id) FILTER (WHERE cet.tag_id IS NOT NULL), '{}') AS email_tag_ids,
|
||||
COALESCE(array_agg(cec.folder_id) FILTER (WHERE cec.folder_id IS NOT NULL), '{}') AS email_folder_ids
|
||||
`
|
||||
@@ -1520,7 +1520,7 @@ func (r *campaignRepository) GetByID(ctx context.Context, campaignID uuid.UUID)
|
||||
&campaign.UTMTracking, &campaign.UTMSource, &campaign.UTMMedium, &campaign.UTMCampaign,
|
||||
&campaign.UnsubscribeMode,
|
||||
&campaign.Continuous, &campaign.IdleSince, &campaign.StopOnMeeting,
|
||||
&campaign.FollowUpSender, &campaign.TimezoneMode, &campaign.WarmupGraduation,
|
||||
&campaign.FollowUpSender, &campaign.TimezoneMode, &campaign.WarmupGraduation, &campaign.ReviewLeads,
|
||||
&campaign.EmailTags, &campaign.Folders,
|
||||
)
|
||||
if err != nil {
|
||||
|
||||
@@ -116,7 +116,7 @@ func (r *campaignRepository) Duplicate(ctx context.Context, in DuplicateCampaign
|
||||
cc_addr, bcc_addr,
|
||||
start_date, end_date, timezone, timezone_mode, days, start_time, end_time, schedule_windows,
|
||||
contact_order_by, contact_order_dir, contact_order_field,
|
||||
sender_strategy, rotation_mode, follow_up_sender, warmup_graduation,
|
||||
sender_strategy, rotation_mode, follow_up_sender, warmup_graduation, review_leads,
|
||||
ramp_enabled, ramp_start, ramp_increment, ramp_ceiling, ramp_level, ramp_level_date,
|
||||
esp_match_mode, max_new_leads_per_day, prioritize_new_leads, continuous, entry_delay_minutes,
|
||||
tracking_domain, tracking_domain_verified, tracking_domain_verified_at,
|
||||
@@ -135,7 +135,7 @@ func (r *campaignRepository) Duplicate(ctx context.Context, in DuplicateCampaign
|
||||
CASE WHEN end_date > NOW() THEN end_date END,
|
||||
timezone, timezone_mode, days, start_time, end_time, schedule_windows,
|
||||
contact_order_by, contact_order_dir, contact_order_field,
|
||||
sender_strategy, rotation_mode, follow_up_sender, warmup_graduation,
|
||||
sender_strategy, rotation_mode, follow_up_sender, warmup_graduation, review_leads,
|
||||
ramp_enabled, ramp_start, ramp_increment, ramp_ceiling, 0, NULL,
|
||||
esp_match_mode, max_new_leads_per_day, prioritize_new_leads, continuous, entry_delay_minutes,
|
||||
tracking_domain, tracking_domain_verified, tracking_domain_verified_at,
|
||||
|
||||
@@ -2561,6 +2561,13 @@ func crmHoldGuard(alias string) string {
|
||||
AND (NOT (` + liveHold(alias) + `) OR ` + alias + `.pause_source IN ('out_of_office', 'inbox_tagging'))`
|
||||
}
|
||||
|
||||
// reviewHoldGuard keeps a member's pause from replacing a review hold, which
|
||||
// would let the lead start unreviewed once the pause is lifted.
|
||||
func reviewHoldGuard(alias string) string {
|
||||
return `
|
||||
AND ` + alias + `.pause_source IS DISTINCT FROM 'review'`
|
||||
}
|
||||
|
||||
// automaticHoldSource reports a hold the system wrote, which a member's own
|
||||
// pause always outranks and a longer automatic hold is never cut short by.
|
||||
func automaticHoldSource(source string) bool {
|
||||
@@ -2582,6 +2589,8 @@ func (r *campaignProgressRepository) HoldLead(ctx context.Context, campaignID, c
|
||||
guard = automaticHoldGuard("campaign_leads", "$3")
|
||||
} else if source == models.LeadHoldSourceCRM {
|
||||
guard = crmHoldGuard("campaign_leads")
|
||||
} else {
|
||||
guard = reviewHoldGuard("campaign_leads")
|
||||
}
|
||||
now := time.Now()
|
||||
hold, err := scanHold(resultDB(ctx, r.db).QueryRow(ctx, `
|
||||
@@ -2629,6 +2638,8 @@ func (r *campaignProgressRepository) HoldLeadElsewhere(ctx context.Context, cont
|
||||
guard = automaticHoldGuard("cl", "$2")
|
||||
} else if source == models.LeadHoldSourceCRM {
|
||||
guard = crmHoldGuard("cl")
|
||||
} else {
|
||||
guard = reviewHoldGuard("cl")
|
||||
}
|
||||
rows, err := resultDB(ctx, r.db).Query(ctx, `
|
||||
UPDATE campaign_leads cl
|
||||
@@ -2664,20 +2675,26 @@ func (r *campaignProgressRepository) HoldLeadElsewhere(ctx context.Context, cont
|
||||
// on its own. Reports whether a hold was actually lifted, and
|
||||
// ErrLeadNotInCampaign when the contact is not a lead of the campaign, so a
|
||||
// resume that changed nothing is not mistaken for one that did.
|
||||
//
|
||||
// It never approves a lead waiting for review: that is its own column, and the
|
||||
// 'review' hold kept in the slot for older releases is left in place.
|
||||
func (r *campaignProgressRepository) ResumeLead(ctx context.Context, campaignID, contactID uuid.UUID) (bool, error) {
|
||||
// RETURNING sees the row AFTER the update, so whether there was a hold to
|
||||
// lift is read from the pre-update snapshot the CTE holds.
|
||||
var held bool
|
||||
err := resultDB(ctx, r.db).QueryRow(ctx, `
|
||||
WITH prev AS (
|
||||
SELECT paused_at FROM campaign_leads WHERE campaign_id = $1 AND contact_id = $2
|
||||
SELECT paused_at, pause_source FROM campaign_leads WHERE campaign_id = $1 AND contact_id = $2
|
||||
), lifted AS (
|
||||
UPDATE campaign_leads
|
||||
SET paused_at = NULL, paused_until = NULL, pause_reason = NULL, pause_source = NULL
|
||||
SET paused_at = CASE WHEN pause_source = 'review' THEN paused_at END,
|
||||
paused_until = CASE WHEN pause_source = 'review' THEN paused_until END,
|
||||
pause_reason = CASE WHEN pause_source = 'review' THEN pause_reason END,
|
||||
pause_source = CASE WHEN pause_source = 'review' THEN pause_source END
|
||||
WHERE campaign_id = $1 AND contact_id = $2
|
||||
RETURNING 1
|
||||
)
|
||||
SELECT (SELECT paused_at IS NOT NULL FROM prev) FROM lifted
|
||||
SELECT (SELECT paused_at IS NOT NULL AND pause_source IS DISTINCT FROM 'review' FROM prev) FROM lifted
|
||||
`, campaignID, contactID).Scan(&held)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, ErrLeadNotInCampaign
|
||||
@@ -2692,8 +2709,13 @@ func (r *campaignProgressRepository) ResumeLead(ctx context.Context, campaignID,
|
||||
// so the caller can answer 404 rather than 200 for a contact that was never in
|
||||
// the campaign.
|
||||
func (r *campaignProgressRepository) GetLeadHold(ctx context.Context, campaignID, contactID uuid.UUID) (*models.LeadHold, error) {
|
||||
hold, err := scanHold(resultDB(ctx, r.db).QueryRow(ctx,
|
||||
`SELECT `+holdColumns+` FROM campaign_leads WHERE campaign_id = $1 AND contact_id = $2`,
|
||||
// Waiting for review reads as the lead's hold, ahead of whatever is in the slot.
|
||||
hold, err := scanHold(resultDB(ctx, r.db).QueryRow(ctx, `
|
||||
SELECT CASE WHEN `+reviewPendingSQL("cl")+` THEN cl.review_pending_at ELSE cl.paused_at END,
|
||||
CASE WHEN `+reviewPendingSQL("cl")+` THEN NULL::timestamptz ELSE cl.paused_until END,
|
||||
CASE WHEN `+reviewPendingSQL("cl")+` THEN '' ELSE COALESCE(cl.pause_reason, '') END,
|
||||
CASE WHEN `+reviewPendingSQL("cl")+` THEN 'review' ELSE COALESCE(cl.pause_source, '') END
|
||||
FROM campaign_leads cl WHERE cl.campaign_id = $1 AND cl.contact_id = $2`,
|
||||
campaignID, contactID), time.Now())
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrLeadNotInCampaign
|
||||
@@ -2709,7 +2731,7 @@ func (r *campaignProgressRepository) CountHeldLeads(ctx context.Context, campaig
|
||||
var n int
|
||||
err := resultDB(ctx, r.db).QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM campaign_leads cl
|
||||
WHERE cl.campaign_id = $1 AND (`+recoveryPausedLeadSQL("cl")+` OR (`+liveHold("cl")+`
|
||||
WHERE cl.campaign_id = $1 AND (`+recoveryPausedLeadSQL("cl")+` OR `+reviewPendingSQL("cl")+` OR (`+liveHold("cl")+`
|
||||
-- Reached in another lead's thread: nothing is left to wait for.
|
||||
AND cl.pause_source IS DISTINCT FROM 'cc'))`,
|
||||
campaignID).Scan(&n)
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/infrastructure/db"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
// CampaignReviewRepository holds the review state of campaign leads and their
|
||||
// per-lead copies of email steps.
|
||||
type CampaignReviewRepository interface {
|
||||
// SetReviewLeads turns review mode on or off. Only a change moves leads:
|
||||
// on holds every lead not yet emailed, off approves every waiting lead.
|
||||
SetReviewLeads(ctx context.Context, campaignID uuid.UUID, enabled bool) (held, released int, err error)
|
||||
// ApproveLeads lifts review holds, on the listed leads or on all of them.
|
||||
ApproveLeads(ctx context.Context, campaignID uuid.UUID, contactIDs []uuid.UUID, all bool) (int, error)
|
||||
// ReopenLeads puts unheld leads not yet emailed back into review.
|
||||
ReopenLeads(ctx context.Context, campaignID uuid.UUID, contactIDs []uuid.UUID) (int, error)
|
||||
|
||||
Counts(ctx context.Context, campaignID uuid.UUID) (*models.CampaignReviewCounts, error)
|
||||
// MissingCounts counts unstarted, subscribed leads with each field empty.
|
||||
MissingCounts(ctx context.Context, campaignID uuid.UUID, fields []string) (map[string]int, error)
|
||||
UnsubscribedCount(ctx context.Context, campaignID uuid.UUID) (int, error)
|
||||
ListLeads(ctx context.Context, campaignID uuid.UUID, f models.CampaignReviewLeadsFilter) ([]models.CampaignReviewLead, bool, error)
|
||||
GetLead(ctx context.Context, campaignID, contactID uuid.UUID) (*models.CampaignReviewLead, error)
|
||||
|
||||
// AIProgress counts unstarted leads whose copy of the step has every block written, and the rest.
|
||||
AIProgress(ctx context.Context, campaignID, stepID uuid.UUID, blockIDs []string) (written, pending int, err error)
|
||||
// PendingAILeads lists up to limit unstarted leads still missing a block of the
|
||||
// step, within contactIDs when given (else waiting leads only when waitingOnly),
|
||||
// after the cursor, and how many such leads there are from the cursor on.
|
||||
PendingAILeads(ctx context.Context, campaignID, stepID uuid.UUID, blockIDs []string, contactIDs []uuid.UUID, waitingOnly bool, after *models.CampaignReviewCursor, limit int) ([]models.CampaignReviewCursor, int, error)
|
||||
|
||||
// ActiveAICampaigns lists active campaigns with an AI block in an email step, after the given id.
|
||||
ActiveAICampaigns(ctx context.Context, after uuid.UUID, limit int) ([]CampaignOrg, error)
|
||||
|
||||
// ClearResolvedAIVariables drops a lead's written copy of the listed AI blocks of one step.
|
||||
ClearResolvedAIVariables(ctx context.Context, campaignID, contactID, stepID uuid.UUID, ids []string) error
|
||||
|
||||
GetOverride(ctx context.Context, campaignID, contactID, stepID uuid.UUID) (*models.LeadStepOverride, error)
|
||||
ListOverrides(ctx context.Context, campaignID, contactID uuid.UUID) ([]models.LeadStepOverride, error)
|
||||
UpsertOverride(ctx context.Context, o models.LeadStepOverride) (*models.LeadStepOverride, error)
|
||||
DeleteOverride(ctx context.Context, campaignID, contactID, stepID uuid.UUID) (bool, error)
|
||||
}
|
||||
|
||||
type campaignReviewRepository struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewCampaignReviewRepository creates the review repository.
|
||||
func NewCampaignReviewRepository(pool *pgxpool.Pool) CampaignReviewRepository {
|
||||
return &campaignReviewRepository{db: pool}
|
||||
}
|
||||
|
||||
// reviewStatusSQL derives a lead's review state on alias cl; one definition
|
||||
// for the list, the counts and the filters.
|
||||
const reviewStatusSQL = `CASE
|
||||
WHEN cl.review_pending_at IS NOT NULL THEN 'waiting'
|
||||
WHEN campaign_lead_attempted(cl.campaign_id, cl.contact_id) THEN 'started'
|
||||
WHEN cl.paused_at IS NOT NULL AND (cl.paused_until IS NULL OR cl.paused_until > NOW()) THEN 'held'
|
||||
ELSE 'ready' END`
|
||||
|
||||
// missingColumn maps a field name to its contacts column; the map is the whitelist.
|
||||
var missingColumn = map[string]string{
|
||||
"FirstName": "first_name",
|
||||
"LastName": "last_name",
|
||||
"Company": "company",
|
||||
"Phone": "phone",
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) SetReviewLeads(ctx context.Context, campaignID uuid.UUID, enabled bool) (int, int, error) {
|
||||
tx, err := r.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
// Waits for enrolments in flight, and holds new ones until this commits, so
|
||||
// none is inserted against the flag as it was.
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(campaign_review_lock_key($1))`, campaignID); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
var changed bool
|
||||
err = tx.QueryRow(ctx, `
|
||||
UPDATE campaigns SET review_leads = $2, updated_at = NOW()
|
||||
WHERE id = $1 AND review_leads IS DISTINCT FROM $2
|
||||
RETURNING true`, campaignID, enabled).Scan(&changed)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return 0, 0, tx.Commit(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
var n int
|
||||
if enabled {
|
||||
n, err = holdForReview(ctx, tx, campaignID, nil)
|
||||
} else {
|
||||
n, err = releaseReview(ctx, tx, campaignID, nil, true)
|
||||
}
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
if enabled {
|
||||
return n, 0, tx.Commit(ctx)
|
||||
}
|
||||
return 0, n, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
type execer interface {
|
||||
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
|
||||
}
|
||||
|
||||
// holdForReview marks leads not yet emailed as waiting (all of them, or the
|
||||
// listed ones), and gives each whose hold slot is free the 'review' hold
|
||||
// older releases read.
|
||||
func holdForReview(ctx context.Context, q execer, campaignID uuid.UUID, ids []uuid.UUID) (int, error) {
|
||||
filter, args := "", []any{campaignID}
|
||||
if ids != nil {
|
||||
filter, args = " AND cl.contact_id = ANY($2)", append(args, ids)
|
||||
}
|
||||
cmd, err := q.Exec(ctx, `
|
||||
UPDATE campaign_leads cl
|
||||
SET review_pending_at = NOW(),
|
||||
paused_at = CASE WHEN `+freeSlotSQL+` THEN NOW() ELSE cl.paused_at END,
|
||||
paused_until = CASE WHEN `+freeSlotSQL+` THEN NULL ELSE cl.paused_until END,
|
||||
pause_reason = CASE WHEN `+freeSlotSQL+` THEN NULL ELSE cl.pause_reason END,
|
||||
pause_source = CASE WHEN `+freeSlotSQL+` THEN 'review' ELSE cl.pause_source END
|
||||
WHERE cl.campaign_id = $1 AND cl.review_pending_at IS NULL
|
||||
AND NOT campaign_lead_attempted(cl.campaign_id, cl.contact_id)`+filter, args...)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(cmd.RowsAffected()), nil
|
||||
}
|
||||
|
||||
// freeSlotSQL is a hold slot holding nothing live, on alias cl.
|
||||
const freeSlotSQL = `(cl.paused_at IS NULL OR (cl.paused_until IS NOT NULL AND cl.paused_until <= NOW()))`
|
||||
|
||||
// releaseReview approves waiting leads (all, or the listed ones) and clears the
|
||||
// 'review' hold kept for older releases.
|
||||
func releaseReview(ctx context.Context, q execer, campaignID uuid.UUID, ids []uuid.UUID, all bool) (int, error) {
|
||||
filter, args := "", []any{campaignID}
|
||||
if !all {
|
||||
filter, args = " AND contact_id = ANY($2)", append(args, ids)
|
||||
}
|
||||
cmd, err := q.Exec(ctx, `
|
||||
UPDATE campaign_leads
|
||||
SET review_pending_at = NULL,
|
||||
paused_at = CASE WHEN pause_source = 'review' THEN NULL ELSE paused_at END,
|
||||
paused_until = CASE WHEN pause_source = 'review' THEN NULL ELSE paused_until END,
|
||||
pause_reason = CASE WHEN pause_source = 'review' THEN NULL ELSE pause_reason END,
|
||||
pause_source = CASE WHEN pause_source = 'review' THEN NULL ELSE pause_source END
|
||||
WHERE campaign_id = $1 AND (review_pending_at IS NOT NULL OR pause_source = 'review')`+filter, args...)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(cmd.RowsAffected()), nil
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) ApproveLeads(ctx context.Context, campaignID uuid.UUID, contactIDs []uuid.UUID, all bool) (int, error) {
|
||||
if !all && len(contactIDs) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
return releaseReview(ctx, r.db, campaignID, contactIDs, all)
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) ReopenLeads(ctx context.Context, campaignID uuid.UUID, contactIDs []uuid.UUID) (int, error) {
|
||||
if len(contactIDs) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
return holdForReview(ctx, r.db, campaignID, contactIDs)
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) Counts(ctx context.Context, campaignID uuid.UUID) (*models.CampaignReviewCounts, error) {
|
||||
var out models.CampaignReviewCounts
|
||||
query := `
|
||||
WITH s AS (SELECT ` + reviewStatusSQL + ` AS status FROM campaign_leads cl WHERE cl.campaign_id = $1)
|
||||
SELECT COUNT(*),
|
||||
COUNT(*) FILTER (WHERE status = 'waiting'),
|
||||
COUNT(*) FILTER (WHERE status = 'ready'),
|
||||
COUNT(*) FILTER (WHERE status = 'held'),
|
||||
COUNT(*) FILTER (WHERE status = 'started'),
|
||||
(SELECT COUNT(DISTINCT o.contact_id) FROM campaign_lead_step_overrides o WHERE o.campaign_id = $1)
|
||||
FROM s`
|
||||
err := r.db.QueryRow(ctx, query, campaignID).Scan(&out.Total, &out.Waiting, &out.Ready, &out.Held, &out.Started, &out.Personalized)
|
||||
if err != nil {
|
||||
db.CaptureError(err, query, []any{campaignID}, "queryrow")
|
||||
return nil, err
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) MissingCounts(ctx context.Context, campaignID uuid.UUID, fields []string) (map[string]int, error) {
|
||||
out := map[string]int{}
|
||||
var cols []string
|
||||
var names []string
|
||||
for _, f := range fields {
|
||||
col, ok := missingColumn[f]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
cols = append(cols, fmt.Sprintf("COUNT(*) FILTER (WHERE btrim(c.%s) = '')", col))
|
||||
names = append(names, f)
|
||||
}
|
||||
if len(cols) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
query := `
|
||||
SELECT ` + strings.Join(cols, ", ") + `
|
||||
FROM campaign_leads cl JOIN contacts c ON c.id = cl.contact_id
|
||||
WHERE cl.campaign_id = $1 AND c.subscribed IS NOT FALSE
|
||||
AND NOT campaign_lead_attempted(cl.campaign_id, cl.contact_id)`
|
||||
counts := make([]int, len(cols))
|
||||
dest := make([]any, len(cols))
|
||||
for i := range counts {
|
||||
dest[i] = &counts[i]
|
||||
}
|
||||
if err := r.db.QueryRow(ctx, query, campaignID).Scan(dest...); err != nil {
|
||||
db.CaptureError(err, query, []any{campaignID}, "queryrow")
|
||||
return nil, err
|
||||
}
|
||||
for i, n := range names {
|
||||
out[n] = counts[i]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) UnsubscribedCount(ctx context.Context, campaignID uuid.UUID) (int, error) {
|
||||
var n int
|
||||
err := r.db.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM campaign_leads cl JOIN contacts c ON c.id = cl.contact_id
|
||||
WHERE cl.campaign_id = $1 AND c.subscribed IS FALSE`, campaignID).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
const reviewLeadColumns = `cl.contact_id, c.email, c.first_name, c.last_name, c.company, c.phone,
|
||||
` + reviewStatusSQL + ` AS status,
|
||||
CASE WHEN cl.review_pending_at IS NOT NULL THEN cl.review_pending_at ELSE cl.paused_at END,
|
||||
CASE WHEN cl.review_pending_at IS NOT NULL THEN NULL::timestamptz ELSE cl.paused_until END,
|
||||
CASE WHEN cl.review_pending_at IS NOT NULL THEN '' ELSE COALESCE(cl.pause_reason, '') END,
|
||||
CASE WHEN cl.review_pending_at IS NOT NULL THEN 'review' ELSE COALESCE(cl.pause_source, '') END,
|
||||
(SELECT COUNT(*) FROM campaign_lead_step_overrides o WHERE o.campaign_id = cl.campaign_id AND o.contact_id = cl.contact_id),
|
||||
cl.added_at`
|
||||
|
||||
func scanReviewLead(row pgx.Row, gaps []string, now time.Time) (models.CampaignReviewLead, error) {
|
||||
var l models.CampaignReviewLead
|
||||
var phone string
|
||||
var pausedAt, until *time.Time
|
||||
var reason, source string
|
||||
if err := row.Scan(&l.ContactID, &l.Email, &l.FirstName, &l.LastName, &l.Company, &phone,
|
||||
&l.Status, &pausedAt, &until, &reason, &source, &l.Personalized, &l.AddedAt); err != nil {
|
||||
return l, err
|
||||
}
|
||||
if pausedAt != nil && (until == nil || until.After(now)) {
|
||||
l.Hold = &models.LeadHold{Since: *pausedAt, Until: until, Reason: reason, Source: source}
|
||||
}
|
||||
values := map[string]string{"FirstName": l.FirstName, "LastName": l.LastName, "Company": l.Company, "Phone": phone}
|
||||
for _, g := range gaps {
|
||||
if v, ok := values[g]; ok && strings.TrimSpace(v) == "" {
|
||||
l.Missing = append(l.Missing, g)
|
||||
}
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) ListLeads(ctx context.Context, campaignID uuid.UUID, f models.CampaignReviewLeadsFilter) ([]models.CampaignReviewLead, bool, error) {
|
||||
where := []string{"cl.campaign_id = $1"}
|
||||
args := []any{campaignID}
|
||||
add := func(v any) string {
|
||||
args = append(args, v)
|
||||
return fmt.Sprintf("$%d", len(args))
|
||||
}
|
||||
if f.Status != "" && f.Status != "all" {
|
||||
where = append(where, "("+reviewStatusSQL+") = "+add(f.Status))
|
||||
}
|
||||
if col, ok := missingColumn[f.Missing]; ok {
|
||||
where = append(where, "btrim(c."+col+") = ''")
|
||||
}
|
||||
if q := strings.TrimSpace(f.Search); q != "" {
|
||||
p := add("%" + escapeLike(q) + "%")
|
||||
where = append(where, "(c.email ILIKE "+p+" OR c.first_name ILIKE "+p+" OR c.last_name ILIKE "+p+" OR c.company ILIKE "+p+")")
|
||||
}
|
||||
if f.Cursor != nil {
|
||||
where = append(where, "(c.email, cl.contact_id) > ("+add(f.Cursor.Email)+", "+add(f.Cursor.ContactID)+")")
|
||||
}
|
||||
limit := f.Limit
|
||||
query := `SELECT ` + reviewLeadColumns + `
|
||||
FROM campaign_leads cl JOIN contacts c ON c.id = cl.contact_id
|
||||
WHERE ` + strings.Join(where, " AND ") + `
|
||||
ORDER BY c.email, cl.contact_id
|
||||
LIMIT ` + add(limit+1)
|
||||
rows, err := r.db.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
db.CaptureError(err, query, nil, "query")
|
||||
return nil, false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
now := time.Now()
|
||||
out := make([]models.CampaignReviewLead, 0, limit)
|
||||
for rows.Next() {
|
||||
l, err := scanReviewLead(rows, f.Gaps, now)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
out = append(out, l)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
more := len(out) > limit
|
||||
if more {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, more, nil
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) GetLead(ctx context.Context, campaignID, contactID uuid.UUID) (*models.CampaignReviewLead, error) {
|
||||
query := `SELECT ` + reviewLeadColumns + `
|
||||
FROM campaign_leads cl JOIN contacts c ON c.id = cl.contact_id
|
||||
WHERE cl.campaign_id = $1 AND cl.contact_id = $2`
|
||||
l, err := scanReviewLead(r.db.QueryRow(ctx, query, campaignID, contactID), nil, time.Now())
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrLeadNotInCampaign
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &l, nil
|
||||
}
|
||||
|
||||
// pendingAIScope is the unstarted, subscribed leads whose copy of step $2 still
|
||||
// misses one of blocks $3 and that have no personalized copy of it.
|
||||
const pendingAIScope = `
|
||||
FROM campaign_leads cl
|
||||
JOIN contacts c ON c.id = cl.contact_id
|
||||
LEFT JOIN campaign_contact_progress p
|
||||
ON p.campaign_id = cl.campaign_id AND p.contact_id = cl.contact_id AND p.sequence_id = $2
|
||||
WHERE cl.campaign_id = $1 AND c.subscribed IS NOT FALSE
|
||||
AND NOT campaign_lead_attempted(cl.campaign_id, cl.contact_id)
|
||||
AND NOT EXISTS (SELECT 1 FROM campaign_lead_step_overrides o
|
||||
WHERE o.campaign_id = cl.campaign_id AND o.contact_id = cl.contact_id AND o.sequence_id = $2)`
|
||||
|
||||
func (r *campaignReviewRepository) AIProgress(ctx context.Context, campaignID, stepID uuid.UUID, blockIDs []string) (int, int, error) {
|
||||
if len(blockIDs) == 0 {
|
||||
return 0, 0, nil
|
||||
}
|
||||
var written, pending int
|
||||
err := r.db.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FILTER (WHERE COALESCE(p.ai_variables_resolved, '{}'::jsonb) ?& $3::text[]),
|
||||
COUNT(*) FILTER (WHERE NOT COALESCE(p.ai_variables_resolved, '{}'::jsonb) ?& $3::text[])
|
||||
`+pendingAIScope, campaignID, stepID, blockIDs).Scan(&written, &pending)
|
||||
return written, pending, err
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) PendingAILeads(ctx context.Context, campaignID, stepID uuid.UUID, blockIDs []string, contactIDs []uuid.UUID, waitingOnly bool, after *models.CampaignReviewCursor, limit int) ([]models.CampaignReviewCursor, int, error) {
|
||||
if len(blockIDs) == 0 {
|
||||
return nil, 0, nil
|
||||
}
|
||||
scope := pendingAIScope + ` AND NOT COALESCE(p.ai_variables_resolved, '{}'::jsonb) ?& $3::text[]`
|
||||
args := []any{campaignID, stepID, blockIDs}
|
||||
if len(contactIDs) > 0 {
|
||||
args = append(args, contactIDs)
|
||||
scope += fmt.Sprintf(` AND cl.contact_id = ANY($%d)`, len(args))
|
||||
} else if waitingOnly {
|
||||
scope += ` AND cl.review_pending_at IS NOT NULL`
|
||||
}
|
||||
// The cursor moves a run past leads that failed, so they cannot stall it.
|
||||
if after != nil {
|
||||
args = append(args, after.Email, after.ContactID)
|
||||
scope += fmt.Sprintf(` AND (c.email, cl.contact_id) > ($%d, $%d)`, len(args)-1, len(args))
|
||||
}
|
||||
var total int
|
||||
if err := r.db.QueryRow(ctx, `SELECT COUNT(*) `+scope, args...).Scan(&total); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
rows, err := r.db.Query(ctx, `SELECT c.email, cl.contact_id `+scope+fmt.Sprintf(` ORDER BY c.email, cl.contact_id LIMIT %d`, limit), args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []models.CampaignReviewCursor
|
||||
for rows.Next() {
|
||||
var c models.CampaignReviewCursor
|
||||
if err := rows.Scan(&c.Email, &c.ContactID); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, total, rows.Err()
|
||||
}
|
||||
|
||||
// CampaignOrg names a campaign and the organization that owns it.
|
||||
type CampaignOrg struct {
|
||||
CampaignID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) ActiveAICampaigns(ctx context.Context, after uuid.UUID, limit int) ([]CampaignOrg, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT c.id, c.organization_id FROM campaigns c
|
||||
WHERE c.status = 'active' AND c.organization_id IS NOT NULL AND c.id > $1
|
||||
AND EXISTS (SELECT 1 FROM sequences s
|
||||
WHERE s.campaign_id = c.id AND s.kind = 'email'
|
||||
AND s.body_html LIKE '%data-ai-var%')
|
||||
ORDER BY c.id LIMIT $2`, after, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []CampaignOrg
|
||||
for rows.Next() {
|
||||
var c CampaignOrg
|
||||
if err := rows.Scan(&c.CampaignID, &c.OrgID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
const overrideColumns = `campaign_id, contact_id, sequence_id, subject, body_html, body_plain, edited_by, updated_at`
|
||||
|
||||
func scanOverride(row pgx.Row) (*models.LeadStepOverride, error) {
|
||||
var o models.LeadStepOverride
|
||||
if err := row.Scan(&o.CampaignID, &o.ContactID, &o.StepID, &o.Subject, &o.BodyHTML, &o.BodyPlain, &o.EditedBy, &o.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &o, nil
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) GetOverride(ctx context.Context, campaignID, contactID, stepID uuid.UUID) (*models.LeadStepOverride, error) {
|
||||
o, err := scanOverride(r.db.QueryRow(ctx, `SELECT `+overrideColumns+` FROM campaign_lead_step_overrides
|
||||
WHERE campaign_id = $1 AND contact_id = $2 AND sequence_id = $3`, campaignID, contactID, stepID))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return o, err
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) ListOverrides(ctx context.Context, campaignID, contactID uuid.UUID) ([]models.LeadStepOverride, error) {
|
||||
rows, err := r.db.Query(ctx, `SELECT `+overrideColumns+` FROM campaign_lead_step_overrides
|
||||
WHERE campaign_id = $1 AND contact_id = $2`, campaignID, contactID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []models.LeadStepOverride
|
||||
for rows.Next() {
|
||||
o, err := scanOverride(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, *o)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) UpsertOverride(ctx context.Context, o models.LeadStepOverride) (*models.LeadStepOverride, error) {
|
||||
return scanOverride(r.db.QueryRow(ctx, `
|
||||
INSERT INTO campaign_lead_step_overrides (campaign_id, contact_id, sequence_id, subject, body_html, body_plain, edited_by)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (campaign_id, contact_id, sequence_id) DO UPDATE
|
||||
SET subject = EXCLUDED.subject, body_html = EXCLUDED.body_html, body_plain = EXCLUDED.body_plain,
|
||||
edited_by = EXCLUDED.edited_by, updated_at = NOW()
|
||||
RETURNING `+overrideColumns,
|
||||
o.CampaignID, o.ContactID, o.StepID, o.Subject, o.BodyHTML, o.BodyPlain, o.EditedBy))
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) DeleteOverride(ctx context.Context, campaignID, contactID, stepID uuid.UUID) (bool, error) {
|
||||
cmd, err := r.db.Exec(ctx, `DELETE FROM campaign_lead_step_overrides
|
||||
WHERE campaign_id = $1 AND contact_id = $2 AND sequence_id = $3`, campaignID, contactID, stepID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return cmd.RowsAffected() > 0, nil
|
||||
}
|
||||
|
||||
func (r *campaignReviewRepository) ClearResolvedAIVariables(ctx context.Context, campaignID, contactID, stepID uuid.UUID, ids []string) error {
|
||||
_, err := r.db.Exec(ctx, `
|
||||
UPDATE campaign_contact_progress
|
||||
SET ai_variables_resolved = COALESCE(ai_variables_resolved, '{}'::jsonb) - $4::text[]
|
||||
WHERE campaign_id = $1 AND contact_id = $2 AND sequence_id = $3
|
||||
AND sent_at IS NULL AND dispatched_at IS NULL`, campaignID, contactID, stepID, ids)
|
||||
return err
|
||||
}
|
||||
@@ -632,12 +632,14 @@ func (r *crmProviderRepository) CampaignOptions(ctx context.Context, orgID uuid.
|
||||
}
|
||||
|
||||
// ResumeHeldEverywhere lifts every hold on a contact's leads in the workspace.
|
||||
// Waiting for review is not a hold it lifts: only an approval does.
|
||||
func (r *crmProviderRepository) ResumeHeldEverywhere(ctx context.Context, orgID, contactID uuid.UUID) (int64, error) {
|
||||
tag, err := r.db.Exec(ctx, `
|
||||
UPDATE campaign_leads cl
|
||||
SET paused_at = NULL, paused_until = NULL, pause_reason = NULL, pause_source = NULL
|
||||
FROM campaigns c
|
||||
WHERE cl.contact_id = $2 AND c.id = cl.campaign_id AND c.organization_id = $1 AND cl.paused_at IS NOT NULL`,
|
||||
WHERE cl.contact_id = $2 AND c.id = cl.campaign_id AND c.organization_id = $1 AND cl.paused_at IS NOT NULL
|
||||
AND cl.pause_source IS DISTINCT FROM 'review'`,
|
||||
orgID, contactID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
|
||||
@@ -446,7 +446,7 @@ func seedMailboxes(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
warmup, warmup_tag, warmup_pool_type, warmup_reply_rate,
|
||||
warmup_base, warmup_increase, warmup_max,
|
||||
warmup_start_time, warmup_end_time, warmup_paused_at,
|
||||
created_at
|
||||
test_mode, created_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4,
|
||||
$5, $6, $7, $8,
|
||||
@@ -455,10 +455,11 @@ func seedMailboxes(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
NOW() - make_interval(days => $9), 'sandbox', 'premium', $10,
|
||||
$11, $12, $13,
|
||||
'00:01', '23:59', CASE WHEN $14 THEN NOW() - INTERVAL '2 days' END,
|
||||
NOW() - make_interval(days => $15)
|
||||
'legacy', NOW() - make_interval(days => $15)
|
||||
)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
worker_id = EXCLUDED.worker_id,
|
||||
test_mode = EXCLUDED.test_mode,
|
||||
status = 'active',
|
||||
signature_plain = EXCLUDED.signature_plain,
|
||||
signature_html = EXCLUDED.signature_html,
|
||||
|
||||
@@ -44,6 +44,25 @@ const (
|
||||
aiVarResearchTimeout = 45 * time.Second
|
||||
)
|
||||
|
||||
type aiVarKeySuffixKey struct{}
|
||||
|
||||
// withAIVarRewrite marks a deliberate rewrite, so its generation and charge get
|
||||
// keys of their own instead of being taken for a retry of the first one.
|
||||
func withAIVarRewrite(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, aiVarKeySuffixKey{}, ":rewrite:"+uuid.NewString())
|
||||
}
|
||||
|
||||
func aiVarKeySuffix(ctx context.Context) string {
|
||||
s, _ := ctx.Value(aiVarKeySuffixKey{}).(string)
|
||||
return s
|
||||
}
|
||||
|
||||
// ErrAIVarBalance and ErrAIVarCap are the two refusals a caller words for the member.
|
||||
var (
|
||||
ErrAIVarBalance = errors.New("the workspace balance is too low for this AI variable")
|
||||
ErrAIVarCap = errors.New("AI usage cap reached; try again later")
|
||||
)
|
||||
|
||||
// errAIVarNoTools signals the tool registry exposed no usable web tools, so the
|
||||
// caller falls back to the single-completion path.
|
||||
var errAIVarNoTools = errors.New("no web tools available for research")
|
||||
@@ -141,7 +160,7 @@ func (s *tasksService) resolveAIVariables(ctx context.Context, campaign *models.
|
||||
// Give the model the surrounding email so the fragment flows with it.
|
||||
before, after := aiVarSurrounding(bodyPlain, "[[ai:"+ref.id+"]]")
|
||||
text, gerr := s.generateAIVariable(ctx, *campaign.OrganizationID, contact, cfg, rendered, before, after,
|
||||
fmt.Sprintf("seq_ai_var:%s:%s:%s:%s", campaign.ID, contact.ID, sequenceID, ref.id))
|
||||
fmt.Sprintf("seq_ai_var:%s:%s:%s:%s%s", campaign.ID, contact.ID, sequenceID, ref.id, aiVarKeySuffix(ctx)))
|
||||
if gerr != nil {
|
||||
// A provider/credit failure fails the send so the task retries (the
|
||||
// charge was already refunded inside generateAIVariable).
|
||||
@@ -218,9 +237,9 @@ func (s *tasksService) generateAIVariable(ctx context.Context, orgID uuid.UUID,
|
||||
if cerr := s.aiCredits.Reserve(ctx, orgID, estimate); cerr != nil {
|
||||
switch {
|
||||
case errors.Is(cerr, credits.ErrInsufficientCredits):
|
||||
return "", errors.New("the workspace balance is too low for this AI variable")
|
||||
return "", ErrAIVarBalance
|
||||
case errors.Is(cerr, credits.ErrCapExceeded):
|
||||
return "", errors.New("AI usage cap reached; try again later")
|
||||
return "", ErrAIVarCap
|
||||
default:
|
||||
return "", cerr
|
||||
}
|
||||
|
||||
@@ -613,6 +613,22 @@ func (s *tasksService) HandleCampaignTask(task *proto.ProcessTask) (result *errx
|
||||
if threadSubject != "" {
|
||||
rawSubject = threadSubject
|
||||
}
|
||||
// A lead's own copy of the step replaces it, A/B variants included. Fail
|
||||
// closed: sending the shared copy to a lead someone personalized for is wrong.
|
||||
override, oerr := s.leadOverride(ctx, campaign.ID, contact.ID, sequence.ID)
|
||||
if oerr != nil {
|
||||
errs.CaptureException(oerr)
|
||||
s.taskRepo.RecordTaskFailure(ctx, taskID, "Could not read the lead's own copy of this step", oerr.Error())
|
||||
s.retryCampaignTickLater(ctx, taskRecord)
|
||||
executionStatus = "failed"
|
||||
return errx.InternalError()
|
||||
}
|
||||
if override != nil {
|
||||
rawBodyHTML, rawBodyPlain = override.BodyHTML, override.BodyPlain
|
||||
if threadSubject == "" {
|
||||
rawSubject = override.Subject
|
||||
}
|
||||
}
|
||||
s.resolveFormLinks(ctx, orgID, campaign, contact, &rawSubject, &rawBodyHTML, &rawBodyPlain)
|
||||
|
||||
// STEP 9.75: The recipient's opt-out. The link (when the instance can
|
||||
@@ -633,7 +649,11 @@ func (s *tasksService) HandleCampaignTask(task *proto.ProcessTask) (result *errx
|
||||
// once and expand any {a|b|c} spintax per-recipient. Rendering happens after
|
||||
// the variant pick so a contact value is never parsed as template text.
|
||||
resolveLinks := func(parts ...*string) { s.resolveFormLinks(ctx, orgID, campaign, contact, parts...) }
|
||||
rendered, sxerr := s.selectAndRender(ctx, orgID, campaign.ID, sequence.ID, *contact, extra, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain, resolveLinks)
|
||||
var picker variantSelector
|
||||
if s.advanced != nil && override == nil {
|
||||
picker = s.advanced
|
||||
}
|
||||
rendered, sxerr := selectAndRender(ctx, picker, orgID, campaign.ID, sequence.ID, *contact, extra, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain, resolveLinks)
|
||||
if sxerr != nil {
|
||||
return sxerr
|
||||
}
|
||||
@@ -1268,7 +1288,7 @@ func HeldLeadsMessage(n int) string {
|
||||
if n != 1 {
|
||||
lead = "leads are"
|
||||
}
|
||||
return fmt.Sprintf("Waiting: %d %s paused. The campaign stays active and continues when they resume.", n, lead)
|
||||
return fmt.Sprintf("Waiting: %d %s paused or waiting for review. The campaign stays active and continues when they resume or are approved.", n, lead)
|
||||
}
|
||||
|
||||
// CampaignHeldEventType is the activity log entry for a campaign waiting on
|
||||
@@ -1931,14 +1951,7 @@ type renderedCopy struct {
|
||||
|
||||
// selectAndRender picks the step's copy or an A/B variant from template text, then renders it once.
|
||||
// resolveLinks resolves form-link markers in the chosen copy, which a variant brings unresolved.
|
||||
func (s *tasksService) selectAndRender(ctx context.Context, orgID, campaignID, sequenceID uuid.UUID, contact models.Contact, extra TemplateContext, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain string, resolveLinks func(...*string)) (renderedCopy, *errx.Error) {
|
||||
var picker variantSelector
|
||||
if s.advanced != nil {
|
||||
picker = s.advanced
|
||||
}
|
||||
return selectAndRender(ctx, picker, orgID, campaignID, sequenceID, contact, extra, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain, resolveLinks)
|
||||
}
|
||||
|
||||
// A nil picker sends the copy as given.
|
||||
func selectAndRender(ctx context.Context, picker variantSelector, orgID, campaignID, sequenceID uuid.UUID, contact models.Contact, extra TemplateContext, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain string, resolveLinks func(...*string)) (renderedCopy, *errx.Error) {
|
||||
var arm *models.StepABArm
|
||||
if picker != nil {
|
||||
@@ -1958,12 +1971,8 @@ func selectAndRender(ctx context.Context, picker variantSelector, orgID, campaig
|
||||
if resolveLinks != nil {
|
||||
resolveLinks(&rawSubject, &rawBodyHTML, &rawBodyPlain)
|
||||
}
|
||||
out := renderedCopy{
|
||||
Subject: expandSpintax(RenderTemplateWith(rawSubject, contact, extra)),
|
||||
BodyHTML: expandSpintax(RenderHTMLTemplateWith(rawBodyHTML, contact, extra)),
|
||||
BodyPlain: expandSpintax(RenderTemplateWith(rawBodyPlain, contact, extra)),
|
||||
Arm: arm,
|
||||
}
|
||||
out := renderedCopy{Arm: arm}
|
||||
out.Subject, out.BodyHTML, out.BodyPlain = renderLeadCopy(campaignID, sequenceID, contact, extra, rawSubject, rawBodyHTML, rawBodyPlain)
|
||||
if out.BodyPlain == "" && out.BodyHTML != "" {
|
||||
out.BodyPlain = ExtractPlainTextFromHTML(out.BodyHTML)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
package tasks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"hash/fnv"
|
||||
"html"
|
||||
"math/rand"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/unsublink"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/pkg/tmplvars"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
// LeadReviewAware is implemented by a TasksService that can read per-lead copy.
|
||||
type LeadReviewAware interface {
|
||||
WireLeadReview(repo repository.CampaignReviewRepository)
|
||||
}
|
||||
|
||||
// LeadEmailsService renders and prepares one lead's emails ahead of sending.
|
||||
type LeadEmailsService interface {
|
||||
LeadEmails(ctx context.Context, orgID uuid.UUID, campaign *models.Campaign, contact *models.Contact) ([]models.LeadEmailStep, *models.LeadEmailFrom, *errx.Error)
|
||||
// WriteLeadAI writes the step's AI copy for the lead; rewrite replaces what was written.
|
||||
WriteLeadAI(ctx context.Context, orgID uuid.UUID, campaign *models.Campaign, contact *models.Contact, stepID uuid.UUID, rewrite bool) *errx.Error
|
||||
// AIBlockIDs lists the AI blocks in a step's own copy.
|
||||
AIBlockIDs(bodyHTML string) []AIBlockRef
|
||||
// AIAvailable reports whether this instance can write AI copy at all.
|
||||
AIAvailable() bool
|
||||
}
|
||||
|
||||
func (s *tasksService) AIAvailable() bool {
|
||||
return s.aiProvider != nil && s.aiCredits != nil
|
||||
}
|
||||
|
||||
// AIBlockRef is one AI block in a step: its id, its author's name for it, and whether it researches the web.
|
||||
type AIBlockRef struct {
|
||||
ID string
|
||||
Name string
|
||||
Research bool
|
||||
}
|
||||
|
||||
func (s *tasksService) WireLeadReview(repo repository.CampaignReviewRepository) {
|
||||
s.leadReview = repo
|
||||
}
|
||||
|
||||
// leadOverride reads a lead's own copy of a step, nil when there is none.
|
||||
func (s *tasksService) leadOverride(ctx context.Context, campaignID, contactID, stepID uuid.UUID) (*models.LeadStepOverride, error) {
|
||||
if s.leadReview == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return s.leadReview.GetOverride(ctx, campaignID, contactID, stepID)
|
||||
}
|
||||
|
||||
// spintaxRand picks spintax options the same way for one lead, step and part
|
||||
// every time, so a preview and a retried send carry the copy the send does.
|
||||
// The HTML and plain parts share a seed so they agree on each choice.
|
||||
func spintaxRand(campaignID, contactID, stepID uuid.UUID, part string) *rand.Rand {
|
||||
h := fnv.New64a()
|
||||
_, _ = h.Write(campaignID[:])
|
||||
_, _ = h.Write(contactID[:])
|
||||
_, _ = h.Write(stepID[:])
|
||||
_, _ = h.Write([]byte(part))
|
||||
return rand.New(rand.NewSource(int64(h.Sum64())))
|
||||
}
|
||||
|
||||
func expandSpintaxWith(s string, rng *rand.Rand) string {
|
||||
return ResolveSpintax(s, func(opts []string) string { return opts[rng.Intn(len(opts))] })
|
||||
}
|
||||
|
||||
// renderLeadCopy renders a step's chosen copy for one lead: merge fields once,
|
||||
// then spintax seeded by lead and step. The send path and the preview share it.
|
||||
func renderLeadCopy(campaignID, stepID uuid.UUID, contact models.Contact, extra TemplateContext, subject, bodyHTML, bodyPlain string) (string, string, string) {
|
||||
out := []string{
|
||||
expandSpintaxWith(RenderTemplateWith(subject, contact, extra), spintaxRand(campaignID, contact.ID, stepID, "subject")),
|
||||
expandSpintaxWith(RenderHTMLTemplateWith(bodyHTML, contact, extra), spintaxRand(campaignID, contact.ID, stepID, "body")),
|
||||
expandSpintaxWith(RenderTemplateWith(bodyPlain, contact, extra), spintaxRand(campaignID, contact.ID, stepID, "body")),
|
||||
}
|
||||
return out[0], out[1], out[2]
|
||||
}
|
||||
|
||||
func (s *tasksService) AIBlockIDs(bodyHTML string) []AIBlockRef {
|
||||
refs := findAIVarRefs(bodyHTML)
|
||||
out := make([]AIBlockRef, 0, len(refs))
|
||||
for _, r := range refs {
|
||||
ref := AIBlockRef{ID: r.id}
|
||||
if cfg, ok := decodeAIVarConfig(r.config); ok {
|
||||
ref.Name = strings.TrimSpace(cfg.Name)
|
||||
ref.Research = strings.EqualFold(strings.TrimSpace(cfg.Mode), "research")
|
||||
}
|
||||
out = append(out, ref)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// variantPeeker is the read-only half of A/B selection a preview uses.
|
||||
type variantPeeker interface {
|
||||
PeekVariant(ctx context.Context, organizationID, campaignID, contactID, sequenceID uuid.UUID, subject, bodyHTML, bodyPlain string) (*models.VariantSelection, *errx.Error)
|
||||
}
|
||||
|
||||
// leadStepSource is the raw copy a step sends one lead: their own copy when
|
||||
// they have one, otherwise the step's or the A/B arm drawn for them.
|
||||
type leadStepSource struct {
|
||||
subject, bodyHTML, bodyPlain string
|
||||
override *models.LeadStepOverride
|
||||
variantID *uuid.UUID
|
||||
}
|
||||
|
||||
func (s *tasksService) leadStepCopy(ctx context.Context, orgID, campaignID uuid.UUID, contactID uuid.UUID, step *models.Sequence, peek bool) (leadStepSource, error) {
|
||||
src := leadStepSource{subject: step.Subject, bodyHTML: step.BodyHTML, bodyPlain: step.BodyPlain}
|
||||
o, err := s.leadOverride(ctx, campaignID, contactID, step.ID)
|
||||
if err != nil {
|
||||
return src, err
|
||||
}
|
||||
if o != nil {
|
||||
src.subject, src.bodyHTML, src.bodyPlain, src.override = o.Subject, o.BodyHTML, o.BodyPlain, o
|
||||
return src, nil
|
||||
}
|
||||
if s.advanced == nil {
|
||||
return src, nil
|
||||
}
|
||||
var sel *models.VariantSelection
|
||||
var xerr *errx.Error
|
||||
if peeker, ok := s.advanced.(variantPeeker); ok && peek {
|
||||
sel, xerr = peeker.PeekVariant(ctx, orgID, campaignID, contactID, step.ID, src.subject, src.bodyHTML, src.bodyPlain)
|
||||
} else {
|
||||
sel, xerr = s.advanced.SelectVariant(ctx, orgID, campaignID, contactID, step.ID, src.subject, src.bodyHTML, src.bodyPlain)
|
||||
}
|
||||
if xerr != nil {
|
||||
return src, xerr
|
||||
}
|
||||
if sel != nil {
|
||||
src.subject, src.bodyHTML, src.bodyPlain = sel.Subject, sel.BodyHTML, sel.BodyPlain
|
||||
if sel.StepArm != nil {
|
||||
src.variantID = sel.StepArm.VariantID
|
||||
} else {
|
||||
src.variantID = sel.VariantID
|
||||
}
|
||||
}
|
||||
return src, nil
|
||||
}
|
||||
|
||||
func isEmailStep(step *models.Sequence) bool {
|
||||
return step.Kind == "" || step.Kind == "email"
|
||||
}
|
||||
|
||||
// LeadEmails renders every email step of the campaign for one lead, the way
|
||||
// the send path will: their own copy or A/B arm, merge fields, spintax, the AI
|
||||
// copy written so far, signature and opt-out. Nothing is written or charged.
|
||||
func (s *tasksService) LeadEmails(ctx context.Context, orgID uuid.UUID, campaign *models.Campaign, contact *models.Contact) ([]models.LeadEmailStep, *models.LeadEmailFrom, *errx.Error) {
|
||||
steps, err := s.campaignRepo.GetSequencesByCampaignID(ctx, campaign.ID)
|
||||
if err != nil {
|
||||
return nil, nil, errx.InternalError()
|
||||
}
|
||||
progress, err := s.campaignProgressRepo.GetContactProgress(ctx, campaign.ID, contact.ID)
|
||||
if err != nil {
|
||||
return nil, nil, errx.InternalError()
|
||||
}
|
||||
sent := map[uuid.UUID]repository.CampaignContactProgress{}
|
||||
for _, p := range progress {
|
||||
if p.SentAt != nil {
|
||||
sent[p.SequenceID] = p
|
||||
}
|
||||
}
|
||||
|
||||
// The mailbox already writing to this lead, when there is one.
|
||||
var account *models.Email
|
||||
if last, lerr := s.campaignProgressRepo.LastSenderForLead(ctx, campaign.ID, contact.ID); lerr == nil && last != nil {
|
||||
if acc, xerr := s.emailRepo.GetByID(ctx, *last); xerr == nil {
|
||||
account = acc
|
||||
}
|
||||
}
|
||||
parent, _ := s.campaignProgressRepo.ThreadParentForLead(ctx, campaign.ID, contact.ID)
|
||||
|
||||
unsubURL := PreviewUnsubscribeLink
|
||||
if s.unsubLinks != nil && s.unsubLinks.Enabled() {
|
||||
unsubURL = s.unsubLinks.TicketURL("", unsublink.ExampleTicket)
|
||||
}
|
||||
optOut := s.resolveOptOut(ctx, orgID, campaign)
|
||||
extra := templateContext(account, unsubURL)
|
||||
values := map[string]string{"FirstName": contact.FirstName, "LastName": contact.LastName, "Company": contact.Company, "Phone": contact.Phone, "Email": contact.Email}
|
||||
|
||||
out := []models.LeadEmailStep{}
|
||||
firstSubject := ""
|
||||
for i := range steps {
|
||||
step := &steps[i]
|
||||
if !isEmailStep(step) {
|
||||
continue
|
||||
}
|
||||
src, serr := s.leadStepCopy(ctx, orgID, campaign.ID, contact.ID, step, true)
|
||||
if serr != nil {
|
||||
log.Warn().Err(serr).Str("campaign_id", campaign.ID.String()).Msg("lead emails: could not read the lead's copy")
|
||||
return nil, nil, errx.InternalError()
|
||||
}
|
||||
item := models.LeadEmailStep{StepID: step.ID, Position: step.Position, Name: step.Name, VariantID: src.variantID,
|
||||
Source: models.LeadStepOverrideInput{Subject: src.subject, BodyHTML: src.bodyHTML, BodyPlain: src.bodyPlain}}
|
||||
if src.override != nil {
|
||||
item.Personalized = true
|
||||
edited := src.override.UpdatedAt
|
||||
item.EditedAt = &edited
|
||||
item.StepChanged = step.UpdatedAt.After(edited)
|
||||
}
|
||||
for _, part := range []tmplvars.Part{{Name: "subject", Text: src.subject}, {Name: "body", Text: src.bodyHTML, HTML: true}, {Name: "plain text", Text: src.bodyPlain}} {
|
||||
if cerr := tmplvars.CheckCopy(part); cerr != nil {
|
||||
item.Errors = append(item.Errors, cerr.Error())
|
||||
}
|
||||
}
|
||||
item.Missing = missingFor(values, src.subject, src.bodyHTML, src.bodyPlain)
|
||||
|
||||
subject, bodyHTML, bodyPlain := renderLeadCopy(campaign.ID, step.ID, *contact, extra, src.subject, src.bodyHTML, src.bodyPlain)
|
||||
// A follow-up replying in the thread carries the conversation's subject.
|
||||
if step.ThreadReply && firstSubject != "" {
|
||||
item.Threaded = true
|
||||
subject = firstSubject
|
||||
if parent != nil && parent.Subject != "" {
|
||||
subject = parent.Subject
|
||||
if !parent.SubjectSent {
|
||||
// As the send renders an unrecorded conversation subject: merge fields, then this step's spintax.
|
||||
subject, _, _ = renderLeadCopy(campaign.ID, step.ID, *contact, extra, parent.Subject, "", "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resolved, _ := s.campaignProgressRepo.GetResolvedAIVariables(ctx, campaign.ID, contact.ID, step.ID)
|
||||
blocks := s.AIBlockIDs(src.bodyHTML)
|
||||
for _, b := range blocks {
|
||||
_, ok := resolved[b.ID]
|
||||
item.AIBlocks = append(item.AIBlocks, models.LeadEmailAIBlock{ID: b.ID, Name: b.Name, Written: ok})
|
||||
}
|
||||
subject, bodyHTML, bodyPlain = previewAIVariables(subject, bodyHTML, bodyPlain, resolved, blocks)
|
||||
bodyHTML, bodyPlain = finishBody(bodyHTML, bodyPlain, campaign.TextOnly, account, &optOut, unsubURL)
|
||||
item.Subject, item.BodyHTML, item.BodyPlain = subject, bodyHTML, bodyPlain
|
||||
if firstSubject == "" {
|
||||
firstSubject = subject
|
||||
}
|
||||
if p, ok := sent[step.ID]; ok {
|
||||
item.Sent = true
|
||||
item.SentAt = p.SentAt
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
sort.SliceStable(out, func(a, b int) bool { return out[a].Position < out[b].Position })
|
||||
|
||||
var from *models.LeadEmailFrom
|
||||
if account != nil {
|
||||
from = &models.LeadEmailFrom{Name: extra.Sender.Name, Email: extra.Sender.Email}
|
||||
}
|
||||
return out, from, nil
|
||||
}
|
||||
|
||||
// aiPendingPlaceholder stands in for an unwritten AI block in plain text and the subject.
|
||||
func aiPendingPlaceholder(name string) string {
|
||||
if name == "" {
|
||||
return "[AI copy]"
|
||||
}
|
||||
return "[AI: " + name + "]"
|
||||
}
|
||||
|
||||
// previewAIVariables substitutes AI blocks for a preview: written copy wrapped
|
||||
// in a span naming its block, so the dashboard can mark what AI wrote, and an
|
||||
// empty marker where copy is still to be written. Never used on a send.
|
||||
func previewAIVariables(subject, bodyHTML, bodyPlain string, resolved map[string]string, blocks []AIBlockRef) (string, string, string) {
|
||||
names := map[string]string{}
|
||||
for _, b := range blocks {
|
||||
names[b.ID] = b.Name
|
||||
}
|
||||
bodyHTML = aiVarSpanRE.ReplaceAllStringFunc(bodyHTML, func(span string) string {
|
||||
m := aiVarSpanRE.FindStringSubmatch(span)
|
||||
if len(m) < 2 {
|
||||
return ""
|
||||
}
|
||||
id := html.EscapeString(m[1])
|
||||
if text, ok := resolved[m[1]]; ok {
|
||||
return `<span data-ai-block="` + id + `">` + html.EscapeString(text) + `</span>`
|
||||
}
|
||||
return `<span data-ai-pending="` + id + `" data-ai-name="` + html.EscapeString(names[m[1]]) + `"></span>`
|
||||
})
|
||||
plainShown := map[string]string{}
|
||||
for _, b := range blocks {
|
||||
if text, ok := resolved[b.ID]; ok {
|
||||
plainShown[b.ID] = text
|
||||
} else {
|
||||
plainShown[b.ID] = aiPendingPlaceholder(b.Name)
|
||||
}
|
||||
}
|
||||
return replaceAIVarTokens(subject, plainShown), bodyHTML, replaceAIVarTokens(bodyPlain, plainShown)
|
||||
}
|
||||
|
||||
// missingFor lists the built-in fields the copy prints with no fallback that this lead has empty.
|
||||
func missingFor(values map[string]string, parts ...string) []string {
|
||||
gaps := map[string]bool{}
|
||||
for _, p := range parts {
|
||||
g, ok := tmplvars.BlankGaps(p)
|
||||
if !ok {
|
||||
g = tmplvars.References(p)
|
||||
}
|
||||
for k := range g {
|
||||
gaps[k] = true
|
||||
}
|
||||
}
|
||||
var out []string
|
||||
for _, f := range models.MissingFieldNames {
|
||||
if gaps[f] && strings.TrimSpace(values[f]) == "" {
|
||||
out = append(out, f)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ErrLeadStepNotEmail is a write-ahead asked for on a step that sends no email.
|
||||
var ErrLeadStepNotEmail = errors.New("step is not an email step")
|
||||
|
||||
// WriteLeadAI writes a step's AI copy for one lead now rather than at send
|
||||
// time, so it can be read before it goes out. It is cached exactly where the
|
||||
// send reads it, so the send reuses it and nothing is charged twice.
|
||||
func (s *tasksService) WriteLeadAI(ctx context.Context, orgID uuid.UUID, campaign *models.Campaign, contact *models.Contact, stepID uuid.UUID, rewrite bool) *errx.Error {
|
||||
if s.aiProvider == nil || s.aiCredits == nil {
|
||||
return errx.NewWithIdentifier(errx.ServiceUnavailable, "ai_unavailable", "AI is not available on this instance.")
|
||||
}
|
||||
steps, err := s.campaignRepo.GetSequencesByCampaignID(ctx, campaign.ID)
|
||||
if err != nil {
|
||||
return errx.InternalError()
|
||||
}
|
||||
var step *models.Sequence
|
||||
for i := range steps {
|
||||
if steps[i].ID == stepID {
|
||||
step = &steps[i]
|
||||
}
|
||||
}
|
||||
if step == nil {
|
||||
return errx.New(errx.NotFound, "step not found in this campaign")
|
||||
}
|
||||
if !isEmailStep(step) {
|
||||
return errx.New(errx.BadRequest, ErrLeadStepNotEmail.Error())
|
||||
}
|
||||
src, serr := s.leadStepCopy(ctx, orgID, campaign.ID, contact.ID, step, false)
|
||||
if serr != nil {
|
||||
return errx.InternalError()
|
||||
}
|
||||
refs := findAIVarRefs(src.bodyHTML)
|
||||
if len(refs) == 0 {
|
||||
return nil
|
||||
}
|
||||
if rewrite {
|
||||
// Once the email is on its way, the copy it carried is the copy.
|
||||
if sentAt, err := s.campaignProgressRepo.GetStepSentAt(ctx, campaign.ID, contact.ID, step.ID); err != nil {
|
||||
return errx.InternalError()
|
||||
} else if sentAt != nil {
|
||||
return errx.NewWithIdentifier(errx.Conflict, "lead_step_sent", "This lead already received this email, so its copy can no longer change.")
|
||||
}
|
||||
if s.leadReview == nil {
|
||||
return errx.InternalError()
|
||||
}
|
||||
ids := make([]string, len(refs))
|
||||
for i, r := range refs {
|
||||
ids[i] = r.id
|
||||
}
|
||||
if err := s.leadReview.ClearResolvedAIVariables(ctx, campaign.ID, contact.ID, step.ID, ids); err != nil {
|
||||
return errx.InternalError()
|
||||
}
|
||||
ctx = withAIVarRewrite(ctx)
|
||||
}
|
||||
extra := templateContext(nil, PreviewUnsubscribeLink)
|
||||
subject, bodyHTML, bodyPlain := renderLeadCopy(campaign.ID, step.ID, *contact, extra, src.subject, src.bodyHTML, src.bodyPlain)
|
||||
if _, _, _, aerr := s.resolveAIVariables(ctx, campaign, contact, step.ID, subject, bodyHTML, bodyPlain); aerr != nil {
|
||||
switch {
|
||||
case errors.Is(aerr, ErrAIVarBalance):
|
||||
return errx.NewWithIdentifier(errx.PaymentRequired, "insufficient_credits", "The workspace balance is too low. Add money under Billing to keep going.")
|
||||
case errors.Is(aerr, ErrAIVarCap):
|
||||
return errx.NewWithIdentifier(errx.TooManyRequests, "usage_cap_exceeded", "The workspace reached its spend limit for now.")
|
||||
}
|
||||
log.Warn().Err(aerr).Str("campaign_id", campaign.ID.String()).Str("step_id", step.ID.String()).Msg("write AI copy ahead failed")
|
||||
return errx.NewWithIdentifier(errx.ServiceUnavailable, "ai_generation_failed", "The AI copy could not be written. Try again in a moment.")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package tasks
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
// A lead's preview and every send to them carry the same spintax choices.
|
||||
func TestRenderLeadCopyIsStablePerLeadAndStep(t *testing.T) {
|
||||
campaign, step := uuid.New(), uuid.New()
|
||||
contact := models.Contact{ID: uuid.New(), FirstName: "Ada"}
|
||||
subject := "{Hi|Hello|Hey} {{.FirstName}}"
|
||||
html := "<p>{one|two|three|four|five|six}</p>"
|
||||
plain := "{one|two|three|four|five|six}"
|
||||
|
||||
s1, h1, p1 := renderLeadCopy(campaign, step, contact, TemplateContext{}, subject, html, plain)
|
||||
for i := 0; i < 20; i++ {
|
||||
s2, h2, p2 := renderLeadCopy(campaign, step, contact, TemplateContext{}, subject, html, plain)
|
||||
if s1 != s2 || h1 != h2 || p1 != p2 {
|
||||
t.Fatalf("render %d differs: %q/%q/%q vs %q/%q/%q", i, s1, h1, p1, s2, h2, p2)
|
||||
}
|
||||
}
|
||||
if "<p>"+p1+"</p>" != h1 {
|
||||
t.Fatalf("HTML and plain parts chose differently: %q vs %q", h1, p1)
|
||||
}
|
||||
|
||||
// Across leads the choices still vary.
|
||||
seen := map[string]bool{}
|
||||
for i := 0; i < 40; i++ {
|
||||
other := models.Contact{ID: uuid.New(), FirstName: "Ada"}
|
||||
_, _, p := renderLeadCopy(campaign, step, other, TemplateContext{}, subject, html, plain)
|
||||
seen[p] = true
|
||||
}
|
||||
if len(seen) < 3 {
|
||||
t.Fatalf("spintax barely varies across leads: %v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingForListsOnlyUnguardedEmptyFields(t *testing.T) {
|
||||
values := map[string]string{"FirstName": "", "Company": "", "LastName": "Lovelace"}
|
||||
got := missingFor(values,
|
||||
"Hi {{.FirstName}} at {{.LastName}}",
|
||||
`{{if .Company}}About {{.Company}}{{end}}`,
|
||||
)
|
||||
if want := []string{"FirstName"}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("missingFor = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A preview marks written AI copy and leaves a marker where copy is still to come.
|
||||
func TestPreviewAIVariablesMarksWrittenAndPending(t *testing.T) {
|
||||
body := `<p><span data-ai-var="a" data-ai-config="e30=">[[ai:a]]</span> <span data-ai-var="b" data-ai-config="e30=">[[ai:b]]</span></p>`
|
||||
_, html, plain := previewAIVariables("", body, "[[ai:a]] [[ai:b]]", map[string]string{"a": "Loved the <launch>"},
|
||||
[]AIBlockRef{{ID: "a", Name: "Opener"}, {ID: "b", Name: "Hook"}})
|
||||
if want := `<p><span data-ai-block="a">Loved the <launch></span> <span data-ai-pending="b" data-ai-name="Hook"></span></p>`; html != want {
|
||||
t.Fatalf("html = %q, want %q", html, want)
|
||||
}
|
||||
if plain != "Loved the <launch> [AI: Hook]" {
|
||||
t.Fatalf("plain = %q", plain)
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,12 @@ type EmailPreview struct {
|
||||
TemplatePreview
|
||||
From *EmailPreviewFrom `json:"from,omitempty"`
|
||||
Attachments []EmailPreviewAttachment `json:"attachments,omitempty"`
|
||||
// AIBlocks lists the copy's AI blocks and whether this contact's is written.
|
||||
AIBlocks []models.LeadEmailAIBlock `json:"ai_blocks,omitempty"`
|
||||
// Lead reports the contact is a lead of the campaign, so its AI copy can be written ahead.
|
||||
Lead bool `json:"lead,omitempty"`
|
||||
// Personalized reports the lead has their own copy of this step, which they get instead.
|
||||
Personalized bool `json:"personalized,omitempty"`
|
||||
}
|
||||
|
||||
// PreviewEmail renders a step the way the send path assembles it for one
|
||||
@@ -72,6 +78,13 @@ func (s *tasksService) PreviewEmail(ctx context.Context, orgID uuid.UUID, in Ema
|
||||
|
||||
context := templateContext(in.Account, unsubURL)
|
||||
out := &EmailPreview{TemplatePreview: previewTemplatesWith(in.Subject, in.BodyHTML, in.BodyPlain, in.Contact, context)}
|
||||
resolved := s.previewLead(ctx, out, in)
|
||||
blocks := s.AIBlockIDs(in.BodyHTML)
|
||||
for _, b := range blocks {
|
||||
_, ok := resolved[b.ID]
|
||||
out.AIBlocks = append(out.AIBlocks, models.LeadEmailAIBlock{ID: b.ID, Name: b.Name, Written: ok})
|
||||
}
|
||||
out.Subject, out.BodyHTML, out.BodyPlain = previewAIVariables(out.Subject, out.BodyHTML, out.BodyPlain, resolved, blocks)
|
||||
out.BodyHTML, out.BodyPlain = finishBody(out.BodyHTML, out.BodyPlain, textOnly, in.Account, optOut, unsubURL)
|
||||
// Linted on what the author wrote, sized on what ships: the findings have
|
||||
// to name the markup they can go and fix, but Gmail measures the wire. A
|
||||
@@ -96,6 +109,27 @@ func (s *tasksService) PreviewEmail(ctx context.Context, orgID uuid.UUID, in Ema
|
||||
return out
|
||||
}
|
||||
|
||||
// previewLead reads what a real lead of the campaign has for the step: whether
|
||||
// they have their own copy, and the AI copy already written for them.
|
||||
func (s *tasksService) previewLead(ctx context.Context, out *EmailPreview, in EmailPreviewInput) map[string]string {
|
||||
if in.Campaign == nil || in.Contact.ID == uuid.Nil || in.SequenceID == uuid.Nil || s.leadReview == nil {
|
||||
return nil
|
||||
}
|
||||
if _, err := s.leadReview.GetLead(ctx, in.Campaign.ID, in.Contact.ID); err != nil {
|
||||
return nil
|
||||
}
|
||||
out.Lead = true
|
||||
if o, err := s.leadOverride(ctx, in.Campaign.ID, in.Contact.ID, in.SequenceID); err == nil && o != nil {
|
||||
out.Personalized = true
|
||||
}
|
||||
resolved, err := s.campaignProgressRepo.GetResolvedAIVariables(ctx, in.Campaign.ID, in.Contact.ID, in.SequenceID)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("campaign_id", in.Campaign.ID.String()).Msg("preview: read written AI copy failed")
|
||||
return nil
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
// dropBlankHTMLPart removes an HTML alternative that would render nothing.
|
||||
//
|
||||
// An empty HTML part is worse than no HTML part: every modern client prefers
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
func TestPreviewEmailUsesSelectedSender(t *testing.T) {
|
||||
@@ -113,3 +114,69 @@ func TestFinishBodyKeepsAnEmptyHTMLPartWhenThereIsNoPlainText(t *testing.T) {
|
||||
t.Error("dropped the only part the message had")
|
||||
}
|
||||
}
|
||||
|
||||
type previewReviewRepo struct {
|
||||
repository.CampaignReviewRepository
|
||||
lead, own bool
|
||||
}
|
||||
|
||||
func (r previewReviewRepo) GetLead(context.Context, uuid.UUID, uuid.UUID) (*models.CampaignReviewLead, error) {
|
||||
if !r.lead {
|
||||
return nil, repository.ErrLeadNotInCampaign
|
||||
}
|
||||
return &models.CampaignReviewLead{}, nil
|
||||
}
|
||||
|
||||
func (r previewReviewRepo) GetOverride(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (*models.LeadStepOverride, error) {
|
||||
if !r.own {
|
||||
return nil, nil
|
||||
}
|
||||
return &models.LeadStepOverride{}, nil
|
||||
}
|
||||
|
||||
type previewProgressRepo struct {
|
||||
repository.CampaignProgressRepository
|
||||
written map[string]string
|
||||
}
|
||||
|
||||
func (r previewProgressRepo) GetResolvedAIVariables(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (map[string]string, error) {
|
||||
return r.written, nil
|
||||
}
|
||||
|
||||
// The step preview never shows an AI block's raw token or config: a lead gets
|
||||
// the copy already written for them, anyone else a labelled slot.
|
||||
func TestPreviewEmailShowsAICopyForTheLead(t *testing.T) {
|
||||
cfg := "eyJuYW1lIjoiT3BlbmVyIiwicHJvbXB0IjoiaGkifQ==" // {"name":"Opener","prompt":"hi"}
|
||||
body := `<p>Hi</p><p><span data-ai-var="opener" data-ai-config="` + cfg + `">[[ai:opener]]</span></p>`
|
||||
campaign := &models.Campaign{ID: uuid.New()}
|
||||
step := uuid.New()
|
||||
render := func(s *tasksService, contact models.Contact) *EmailPreview {
|
||||
return s.PreviewEmail(context.Background(), uuid.Nil, EmailPreviewInput{
|
||||
Subject: "x", BodyHTML: body, BodyPlain: "Hi\n\n[[ai:opener]]", Contact: contact, Campaign: campaign, SequenceID: step,
|
||||
})
|
||||
}
|
||||
written := previewProgressRepo{written: map[string]string{"opener": "Loved the Acme launch."}}
|
||||
|
||||
p := render(&tasksService{leadReview: previewReviewRepo{}, campaignProgressRepo: written}, models.Contact{FirstName: "Alex"})
|
||||
if strings.Contains(p.BodyHTML, "[[ai:") || strings.Contains(p.BodyHTML, "data-ai-config") || !strings.Contains(p.BodyHTML, `data-ai-pending="opener" data-ai-name="Opener"`) {
|
||||
t.Fatalf("sample preview should show a labelled AI slot: %q", p.BodyHTML)
|
||||
}
|
||||
if p.Lead || len(p.AIBlocks) != 1 || p.AIBlocks[0].Written || strings.Contains(p.BodyPlain, "[[ai:") {
|
||||
t.Fatalf("sample preview: %+v", p)
|
||||
}
|
||||
|
||||
lead := models.Contact{ID: uuid.New(), FirstName: "Jonas"}
|
||||
p = render(&tasksService{leadReview: previewReviewRepo{lead: true, own: true}, campaignProgressRepo: written}, lead)
|
||||
if !strings.Contains(p.BodyHTML, `<span data-ai-block="opener">Loved the Acme launch.</span>`) || !strings.Contains(p.BodyPlain, "Loved the Acme launch.") {
|
||||
t.Fatalf("lead preview should carry their written AI copy: %q / %q", p.BodyHTML, p.BodyPlain)
|
||||
}
|
||||
if !p.Lead || !p.Personalized || !p.AIBlocks[0].Written {
|
||||
t.Fatalf("lead preview flags: %+v", p)
|
||||
}
|
||||
|
||||
// A contact outside the campaign reads nothing the campaign wrote.
|
||||
p = render(&tasksService{leadReview: previewReviewRepo{}, campaignProgressRepo: written}, lead)
|
||||
if p.Lead || strings.Contains(p.BodyHTML, "Loved the Acme launch.") {
|
||||
t.Fatalf("non-lead preview read campaign copy: %+v", p)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,8 +155,10 @@ type tasksService struct {
|
||||
campaignLogRepo repository.CampaignLogRepository
|
||||
// orgRiskRepo bars a restricted organization from the paid warmup pool.
|
||||
// Optional/nil-safe.
|
||||
orgRiskRepo repository.OrgRiskRepository
|
||||
attachmentRepo repository.AttachmentRepository
|
||||
orgRiskRepo repository.OrgRiskRepository
|
||||
attachmentRepo repository.AttachmentRepository
|
||||
// leadReview reads a lead's own copy of a step; nil sends every lead the step's copy.
|
||||
leadReview repository.CampaignReviewRepository
|
||||
trackedLinkRepo repository.TrackedLinkRepository
|
||||
|
||||
// automationRunner launches automations from a campaign "run_automation" step.
|
||||
|
||||
@@ -486,3 +486,10 @@ Apply `fixtures/agency.sql`, then `fixtures/agency-client-view.sql` (two roles i
|
||||
view has roles to be drawn for), to this worktree's isolated rich-seed database. Run
|
||||
`QA_AGENCY_FIXTURES=1 pnpm proof agency-client-view` and `QA_AGENCY_FIXTURES=1 pnpm proof agency-branding-tour`.
|
||||
The branding tour saves a look on the seeded agency, so the client view flow records in that brand afterwards.
|
||||
|
||||
## Campaign review proof fixtures
|
||||
|
||||
`flows/campaign-review.flow.ts` is opt-in: apply `fixtures/campaign-review.sql` to this worktree's isolated
|
||||
rich-seed database before each recording. It moves one seeded campaign into the dev workspace as a draft with
|
||||
synthetic leads (two without a first name), an AI block and one personalized email, and resets review mode to
|
||||
off so the flow can turn it on. Run `QA_CAMPAIGN_REVIEW_FIXTURES=1 pnpm proof campaign-review`.
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
-- Review tab proof: turns the rich seed's "Beta Cold Outreach Q1" into a
|
||||
-- campaign worth reviewing, in dev@warmbly.com's workspace. Synthetic people on .test domains only. Apply to
|
||||
-- this worktree's own stack database, never anything shared or real.
|
||||
BEGIN;
|
||||
|
||||
-- Into the signed-in account's workspace, under a clearer name.
|
||||
UPDATE campaigns SET organization_id = '22222222-0000-0000-0000-000000000001', name = 'Founders outreach - Q4'
|
||||
WHERE id = '44444444-0000-0000-0000-000000000001';
|
||||
UPDATE sequences SET organization_id = '22222222-0000-0000-0000-000000000001'
|
||||
WHERE campaign_id = '44444444-0000-0000-0000-000000000001';
|
||||
UPDATE contacts SET organization_id = '22222222-0000-0000-0000-000000000001'
|
||||
WHERE id IN (SELECT contact_id FROM campaign_leads WHERE campaign_id = '44444444-0000-0000-0000-000000000001');
|
||||
|
||||
UPDATE sequences SET position = 1, name = 'Intro',
|
||||
subject = '{Quick question|A thought} for {{.Company}}',
|
||||
body_html = '<p>Hi {{.FirstName}},</p><p><span data-ai-var="opener" data-ai-config="eyJtb2RlIjoiaW5zdGFudCIsInByb21wdCI6Ik9uZSBmcmllbmRseSBsaW5lIGFib3V0IHNvbWV0aGluZyBzcGVjaWZpYyB0byB7ey5Db21wYW55fX0iLCJuYW1lIjoiT3BlbmVyIiwidG9uZSI6Indhcm0ifQ==">[[ai:opener]]</span></p><p>We help teams like {{.Company}} {cut the time spent chasing replies|stop losing warm replies in shared inboxes}. Worth a 15 minute look next week?</p><p>Best,<br>Sam</p>',
|
||||
body_plain = ''
|
||||
WHERE id = '55555555-0000-0000-0000-000000000001';
|
||||
|
||||
UPDATE sequences SET position = 2, name = 'Follow-up', subject = '',
|
||||
body_html = '<p>Hi {{.FirstName | default "there"}}, just bumping this in case it got buried. Happy to send a two minute video instead if that is easier.</p>',
|
||||
body_plain = ''
|
||||
WHERE id = '55555555-0000-0000-0000-000000000002';
|
||||
|
||||
-- Realistic names and companies; two leads with no first name.
|
||||
UPDATE contacts ct SET first_name = v.first, last_name = v.last, company = v.company, email = v.email
|
||||
FROM (VALUES
|
||||
('lead1@prospect.test', 'Ana', 'Ruiz', 'Northwind Analytics', 'ana.ruiz@northwind.test'),
|
||||
('lead2@prospect.test', 'Jonas', 'Weber', 'Acme Robotics', 'jonas@acme-robotics.test'),
|
||||
('lead3@prospect.test', '', 'Okafor', 'Brightline Health', 'ops@brightline.test'),
|
||||
('lead4@prospect.test', 'Priya', 'Natarajan', 'Lumen Logistics', 'priya@lumenlogistics.test'),
|
||||
('lead5@prospect.test', 'Marco', 'Bianchi', 'Fiore Studio', 'marco@fiorestudio.test'),
|
||||
('lead6@prospect.test', 'Sofia', 'Lindqvist', 'Nordhavn Freight', 'sofia@nordhavn.test'),
|
||||
('lead7@prospect.test', '', 'Tanaka', 'Kumo Cloud', 'hello@kumocloud.test'),
|
||||
('lead8@prospect.test', 'Daniel', 'Moore', 'Harbor Legal', 'daniel@harborlegal.test'),
|
||||
('lead9@prospect.test', 'Leila', 'Haddad', 'Cedar Finance', 'leila@cedarfinance.test'),
|
||||
('lead10@prospect.test', 'Tom', 'Fischer', 'Alpenblick Hotels', 'tom@alpenblick.test')
|
||||
) AS v(old, first, last, company, email)
|
||||
WHERE ct.email IN (v.old, v.email) AND ct.id IN (SELECT contact_id FROM campaign_leads WHERE campaign_id = '44444444-0000-0000-0000-000000000001');
|
||||
|
||||
-- One lead already has an email personalized for them.
|
||||
INSERT INTO campaign_lead_step_overrides (campaign_id, contact_id, sequence_id, subject, body_html, body_plain)
|
||||
SELECT cl.campaign_id, cl.contact_id, '55555555-0000-0000-0000-000000000001',
|
||||
'Ana, loved the Northwind data talk',
|
||||
'<p>Hi Ana,</p><p>Your talk on cleaning up pipeline data stuck with me, especially the part about reply tracking.</p><p>We help teams like Northwind stop losing warm replies in shared inboxes. Worth a 15 minute look next week?</p><p>Best,<br>Sam</p>',
|
||||
''
|
||||
FROM campaign_leads cl JOIN contacts ct ON ct.id = cl.contact_id
|
||||
WHERE ct.email = 'ana.ruiz@northwind.test'
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- A draft about to launch, with a clean, verified list.
|
||||
UPDATE campaigns SET status = 'draft' WHERE id = '44444444-0000-0000-0000-000000000001';
|
||||
UPDATE contacts SET verification_status = 'valid', subscribed = true
|
||||
WHERE id IN (SELECT contact_id FROM campaign_leads WHERE campaign_id = '44444444-0000-0000-0000-000000000001');
|
||||
|
||||
-- Start from review off with nobody waiting, so the flow can turn it on.
|
||||
UPDATE campaigns SET review_leads = false WHERE id = '44444444-0000-0000-0000-000000000001';
|
||||
UPDATE campaign_leads
|
||||
SET review_pending_at = NULL,
|
||||
paused_at = CASE WHEN pause_source = 'review' THEN NULL ELSE paused_at END,
|
||||
pause_source = CASE WHEN pause_source = 'review' THEN NULL ELSE pause_source END
|
||||
WHERE campaign_id = '44444444-0000-0000-0000-000000000001';
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,141 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "../lib/proof.ts";
|
||||
|
||||
const CAMPAIGN = "44444444-0000-0000-0000-000000000001";
|
||||
|
||||
// Report the product tour as finished, so a freshly seeded account never covers the page with it.
|
||||
async function skipTour(page: Page) {
|
||||
await page.route("**/v1/auth/me", async (route) => {
|
||||
const response = await route.fetch();
|
||||
await route.fulfill({ response, json: { ...await response.json(), product_tour_completed_at: "2026-01-01T00:00:00Z" } });
|
||||
});
|
||||
}
|
||||
|
||||
// The stack has no AI provider, so writing AI copy ahead is answered here: the
|
||||
// lead's real emails after a pause, with the opener filled in. Everything else
|
||||
// on screen is the real dashboard and API.
|
||||
const OPENERS: Record<string, string> = {
|
||||
"jonas@acme-robotics.test": "Saw Acme Robotics opened its second assembly line in Lyon this spring, congrats on the growth.",
|
||||
"leila@cedarfinance.test": "Your post on cutting month-end close to three days was a great read.",
|
||||
"marco@fiorestudio.test": "The Fiore Studio rebrand for the Milan design week caught my eye.",
|
||||
};
|
||||
const REWRITE = "Congrats on the Lyon line; doubling capacity in a year is no small thing.";
|
||||
|
||||
async function standInForAI(page: Page) {
|
||||
let rewrites = 0;
|
||||
await page.route(/\/v1\/campaigns\/[^/]+\/leads\/[^/]+\/emails\/[^/]+\/write$/, async (route) => {
|
||||
const url = route.request().url();
|
||||
const rewrite = (route.request().postData() ?? "").includes("rewrite");
|
||||
await new Promise((r) => setTimeout(r, 4500));
|
||||
const response = await route.fetch({ url: url.replace(/\/[^/]+\/write$/, ""), method: "GET", postData: undefined });
|
||||
const data = await response.json();
|
||||
const text = rewrite ? REWRITE : (OPENERS[data.lead.email] ?? `Loved what ${data.lead.company} has been shipping lately.`);
|
||||
if (rewrite) rewrites++;
|
||||
for (const step of data.steps) {
|
||||
step.body_html = step.body_html.replace(/<span data-ai-pending="([^"]+)"[^>]*><\/span>/g, `<span data-ai-block="$1">${text}</span>`);
|
||||
for (const b of step.ai_blocks ?? []) b.written = true;
|
||||
}
|
||||
await route.fulfill({ status: 200, json: data });
|
||||
});
|
||||
return () => rewrites;
|
||||
}
|
||||
|
||||
test.skip(process.env.QA_CAMPAIGN_REVIEW_FIXTURES !== "1", "Apply qa/fixtures/campaign-review.sql to this stack's rich-seed database and set QA_CAMPAIGN_REVIEW_FIXTURES=1.");
|
||||
|
||||
test("review every lead's emails, then approve them before they go out", async ({ page, proof }) => {
|
||||
await skipTour(page);
|
||||
await standInForAI(page);
|
||||
|
||||
// Hold the first readiness read so the loading frame stays on screen for its shot.
|
||||
let release = () => {};
|
||||
const held = new Promise<void>((r) => (release = r));
|
||||
let first = true;
|
||||
await page.route(/\/v1\/campaigns\/[^/]+\/review$/, async (route) => {
|
||||
if (first && route.request().method() === "GET") {
|
||||
first = false;
|
||||
await held;
|
||||
}
|
||||
await route.continue();
|
||||
});
|
||||
await page.goto(`/app/campaigns/${CAMPAIGN}/review`);
|
||||
await expect(page.getByRole("status", { name: "Loading emails" })).toBeVisible();
|
||||
await proof.chapter("Review tab", "It opens in the dashboard's own outline while the data loads");
|
||||
await proof.dwell(1600);
|
||||
await proof.shot("review-loading", { caption: "Loading: the tab's own frame in outline, lit by the shared sweep" });
|
||||
release();
|
||||
|
||||
const toggle = page.getByRole("switch", { name: "Approve before sending" });
|
||||
await expect(toggle).toBeVisible();
|
||||
await expect(page.getByText(/Personalized for this lead/)).toBeVisible();
|
||||
await proof.dwell();
|
||||
await proof.shot("review-readiness", { caption: "One line of checks on top; the leads and each one's emails exactly as they will be sent below" });
|
||||
|
||||
await toggle.click();
|
||||
await expect(page.getByText(/Review is on/)).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: /^Approve all/ })).toBeVisible();
|
||||
await proof.dwell();
|
||||
await proof.shot("review-on", { caption: "Review on: every lead not yet emailed waits here for approval" });
|
||||
|
||||
await proof.chapter("AI writes as you read", "Opening a lead writes its AI copy on the spot");
|
||||
await page.getByRole("button", { name: /Jonas Weber/ }).first().click();
|
||||
await expect(page.getByText(/Writing Jonas's opener|Reading about Acme Robotics/)).toBeVisible();
|
||||
await proof.dwell(1600);
|
||||
await proof.shot("ai-writing", { caption: "Opening Jonas writes his opener right away, where it will sit in the email" });
|
||||
await expect(page.getByText(/AI wrote the highlighted part for Jonas/)).toBeVisible({ timeout: 15_000 });
|
||||
await proof.dwell(1400);
|
||||
await proof.shot("ai-written", { caption: "It fades in, highlighted so you can see what AI wrote; Rewrite asks for another" });
|
||||
|
||||
await page.getByRole("button", { name: "Rewrite" }).click();
|
||||
await expect(page.getByText(/Writing Jonas's opener|Reading about Acme Robotics/)).toBeVisible();
|
||||
await expect(page.getByText(/Congrats on the Lyon line/)).toHaveCount(0);
|
||||
await expect(page.getByText(/AI wrote the highlighted part for Jonas/)).toBeVisible({ timeout: 15_000 });
|
||||
await proof.dwell(1200);
|
||||
|
||||
await page.keyboard.press("j");
|
||||
await expect(page.getByText("leila@cedarfinance.test").last()).toBeVisible();
|
||||
await expect(page.getByText(/AI wrote the highlighted part for Leila/)).toBeVisible({ timeout: 15_000 });
|
||||
await proof.dwell(800);
|
||||
await proof.shot("ai-prewritten", { caption: "Press J: the next leads were written in the background, so Leila's is already there" });
|
||||
|
||||
await page.getByRole("button", { name: /to check$/ }).click();
|
||||
await page.getByRole("button", { name: "Show them" }).first().click();
|
||||
await expect(page.getByText("No first name", { exact: true })).toBeVisible();
|
||||
await proof.dwell(600);
|
||||
await proof.shot("missing-first-name", { caption: "Show them lists the leads whose emails would print a blank first name" });
|
||||
await page.getByRole("button", { name: "Clear filter" }).click();
|
||||
await page.getByRole("button", { name: /^Showing:/ }).click();
|
||||
await page.getByRole("menuitem", { name: /^Waiting/ }).click();
|
||||
|
||||
await page.getByRole("button", { name: /Jonas Weber/ }).first().click();
|
||||
await expect(page.getByText("jonas@acme-robotics.test").last()).toBeVisible();
|
||||
await page.getByRole("button", { name: /^Follow-up/ }).click();
|
||||
await expect(page.getByText("replies in the thread", { exact: true })).toBeVisible();
|
||||
await proof.dwell(600);
|
||||
await proof.shot("lead-follow-up", { caption: "The follow-up replies in the thread, so it carries the first email's subject" });
|
||||
|
||||
await page.getByRole("button", { name: /Ana Ruiz/ }).first().click();
|
||||
await expect(page.getByText(/Personalized for this lead/)).toBeVisible();
|
||||
await page.getByRole("button", { name: "Edit for this lead" }).click();
|
||||
await expect(page.getByRole("button", { name: "Save for this lead" })).toBeVisible();
|
||||
await proof.dwell();
|
||||
await proof.shot("lead-edit", { caption: "Edit for this lead: the step's full editor, saved for one lead" });
|
||||
await page.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
|
||||
await page.getByRole("button", { name: /Jonas Weber/ }).first().click();
|
||||
await expect(page.getByText("jonas@acme-robotics.test").last()).toBeVisible();
|
||||
await page.getByRole("button", { name: "Approve", exact: true }).first().click();
|
||||
await expect(page.getByText(/Approved\. Their first email goes out on schedule/)).toBeVisible();
|
||||
await proof.dwell();
|
||||
await proof.shot("approved", { caption: "Approve (or press A): Jonas leaves the list and the next waiting lead slides in" });
|
||||
|
||||
await page.getByRole("checkbox", { name: /Select Priya Natarajan/ }).check();
|
||||
await page.getByRole("checkbox", { name: /Select Sofia Lindqvist/ }).check();
|
||||
await page.getByRole("checkbox", { name: /Select Tom Fischer/ }).check();
|
||||
await expect(page.getByText("3 selected")).toBeVisible();
|
||||
await proof.shot("bulk-select", { caption: "Approve several at once, write their AI copy, or send them back to review" });
|
||||
|
||||
await page.getByRole("link", { name: "Overview" }).click();
|
||||
await expect(page.getByText(/waiting for review\. Nothing goes to them/)).toBeVisible();
|
||||
await proof.chapter("Everywhere else", "Waiting leads are visible from every tab of the campaign");
|
||||
await proof.shot("waiting-banner", { caption: "Every other tab says how many leads wait, with a way back to Review" });
|
||||
});
|
||||
@@ -23,6 +23,9 @@ import { useConfirm } from "@/hooks/context/confirm";
|
||||
import LaunchCampaignDialog from "@/components/app/campaigns/LaunchCampaignDialog";
|
||||
import CampaignActionsMenu from "@/components/app/campaigns/CampaignActionsMenu";
|
||||
import UndeliverableBanner from "@/components/app/campaigns/UndeliverableBanner";
|
||||
import ReviewWaitingBanner from "@/components/app/campaigns/review/ReviewWaitingBanner";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { sequencesQuery } from "@/lib/api/hooks/app/campaigns/sequences/useSequences";
|
||||
import { canStartCampaign } from "@/components/app/campaigns/useCampaignActions";
|
||||
import toast from "react-hot-toast/headless";
|
||||
import { CAMPAIGN_DELETED_EVENT, type CampaignDeletedDetail } from "@/lib/realtime/campaignDeleted";
|
||||
@@ -60,6 +63,9 @@ export default function CampaignLayout() {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const canSend = usePermission("SEND_CAMPAIGNS");
|
||||
const restricted = useAccessRestricted();
|
||||
const onSteps = pathname.replace(/\/$/, "").endsWith("/steps");
|
||||
const { data: steps } = useQuery({ ...sequencesQuery(id), enabled: onSteps });
|
||||
const hasEmailStep = (steps ?? []).some((s) => s.kind === "email");
|
||||
const launchRequested = searchParams.get("launch") === "1";
|
||||
const loadedStatus = campaignData.data?.status;
|
||||
|
||||
@@ -205,6 +211,11 @@ export default function CampaignLayout() {
|
||||
</div>
|
||||
|
||||
<UndeliverableBanner campaignId={campaign.id} status={status} />
|
||||
<ReviewWaitingBanner
|
||||
campaignId={campaign.id}
|
||||
// On Steps, each email step's Review tab already lists who waits, when there is one.
|
||||
enabled={!!campaign.review_leads && !restricted && !(onSteps && hasEmailStep)}
|
||||
/>
|
||||
|
||||
<div className="shrink-0 px-3 flex items-center gap-1 border-b border-slate-200 overflow-x-auto no-scrollbar">
|
||||
{TABS.filter((t) => t.scoped || !restricted).map(({ label, to, Icon }) => (
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
import React from "react";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { CheckIcon, SparklesIcon, UndoIcon, UsersIcon, XIcon } from "lucide-react";
|
||||
import toast from "react-hot-toast/headless";
|
||||
import { useConfirm } from "@/hooks/context/confirm";
|
||||
import { usePermission } from "@/hooks/usePermission";
|
||||
import {
|
||||
openingReviewStatus,
|
||||
writeLeadAIOnce,
|
||||
useLeadsBeingWritten,
|
||||
useApproveLeads,
|
||||
useCampaignReview,
|
||||
useReopenLeads,
|
||||
useReviewLeads,
|
||||
useSetReview,
|
||||
} from "@/lib/api/hooks/app/campaigns/useCampaignReview";
|
||||
import type { MissingField, ReviewStatus } from "@/lib/api/models/app/campaigns/Review";
|
||||
import type { AppError } from "@/lib/api/client/normalizeError";
|
||||
import buildError from "@/lib/helper/buildError";
|
||||
import { fmtUsd } from "@/lib/money";
|
||||
import ReviewToolbar from "./ReviewToolbar";
|
||||
import ReviewLeadList from "./ReviewLeadList";
|
||||
import LeadEmailsPane from "./LeadEmailsPane";
|
||||
import { useBulkAIWrite } from "./useBulkAIWrite";
|
||||
import { ReviewSkeleton, RunningGrid } from "./reviewLook";
|
||||
import { filterCount } from "./reviewStatus";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const DISCARD = "Discard your changes to this lead's email?";
|
||||
|
||||
function typing(target: EventTarget | null): boolean {
|
||||
const el = target as HTMLElement | null;
|
||||
if (!el) return false;
|
||||
return el.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(el.tagName) || !!el.closest("[role='dialog'],[role='alertdialog'],[data-floating]");
|
||||
}
|
||||
|
||||
// The leads of a campaign and each one's emails, inside an email step's panel:
|
||||
// stepId shows that step only and initialLead opens one lead first.
|
||||
export default function CampaignReviewView({ campaignId, stepId, initialLead }: { campaignId: string; stepId?: string; initialLead?: string }) {
|
||||
const confirm = useConfirm();
|
||||
const canSend = usePermission("SEND_CAMPAIGNS");
|
||||
const canEdit = usePermission("MANAGE_CAMPAIGNS");
|
||||
const canAI = usePermission("USE_AI");
|
||||
const summary = useCampaignReview(campaignId);
|
||||
const reviewMode = summary.data?.review_leads ?? false;
|
||||
|
||||
// A link can open one lead, shown whatever the list's filter.
|
||||
const linked = initialLead ?? null;
|
||||
const [status, setStatus] = React.useState<"all" | ReviewStatus | null>(linked ? "all" : null);
|
||||
const [missing, setMissing] = React.useState<MissingField | undefined>();
|
||||
const [search, setSearch] = React.useState("");
|
||||
const [q, setQ] = React.useState("");
|
||||
const [activeId, setActiveId] = React.useState<string | null>(linked);
|
||||
const [selected, setSelected] = React.useState<Set<string>>(new Set());
|
||||
const [mobilePane, setMobilePane] = React.useState(!!linked);
|
||||
const dirtyRef = React.useRef(false);
|
||||
|
||||
// The list opens where the work is: waiting leads in review mode, otherwise leads not yet emailed.
|
||||
const effectiveStatus: "all" | ReviewStatus = status ?? (summary.data ? openingReviewStatus(summary.data) : "waiting");
|
||||
|
||||
React.useEffect(() => {
|
||||
const t = setTimeout(() => setQ(search), 250);
|
||||
return () => clearTimeout(t);
|
||||
}, [search]);
|
||||
|
||||
const list = useReviewLeads(campaignId, { status: effectiveStatus, missing, q });
|
||||
const leads = list.leads;
|
||||
const approve = useApproveLeads(campaignId);
|
||||
const reopen = useReopenLeads(campaignId);
|
||||
const setReview = useSetReview(campaignId);
|
||||
const bulk = useBulkAIWrite(campaignId);
|
||||
const writingLeads = useLeadsBeingWritten(campaignId);
|
||||
|
||||
// Keep a lead open: the first one once the list loads, and the next one when the open one leaves the filter.
|
||||
const index = leads.findIndex((l) => l.contact_id === activeId);
|
||||
React.useEffect(() => {
|
||||
if (list.isLoading) return;
|
||||
if (activeId === null && leads.length > 0) setActiveId(leads[0].contact_id);
|
||||
}, [list.isLoading, leads, activeId]);
|
||||
|
||||
// The direction the pane slides when another lead opens.
|
||||
const [direction, setDirection] = React.useState(1);
|
||||
const guarded = (fn: () => void) => {
|
||||
if (dirtyRef.current) confirm.show(DISCARD, async () => {
|
||||
dirtyRef.current = false;
|
||||
fn();
|
||||
});
|
||||
else fn();
|
||||
};
|
||||
const open = (id: string) =>
|
||||
guarded(() => {
|
||||
const to = leads.findIndex((l) => l.contact_id === id);
|
||||
if (to >= 0 && index >= 0) setDirection(to >= index ? 1 : -1);
|
||||
setActiveId(id);
|
||||
setMobilePane(true);
|
||||
});
|
||||
const move = (delta: number) => {
|
||||
const next = leads[index + delta];
|
||||
if (!next) return;
|
||||
setDirection(delta > 0 ? 1 : -1);
|
||||
open(next.contact_id);
|
||||
};
|
||||
|
||||
// The next leads' AI copy is written in the background while one is read,
|
||||
// so moving on shows it written. One at a time, each lead once.
|
||||
const qc = useQueryClient();
|
||||
const aiStep = summary.data?.ai.blocks ? summary.data.ai.step_id : undefined;
|
||||
const prewritten = React.useRef(new Set<string>());
|
||||
const canPrewrite = canAI && canEdit && !!aiStep && (summary.data?.ai.pending ?? 0) > 0 && !bulk.running;
|
||||
const upcoming = index >= 0 ? leads.slice(index + 1, index + 3).filter((l) => l.status !== "started").map((l) => l.contact_id) : [];
|
||||
const upcomingKey = upcoming.join(",");
|
||||
React.useEffect(() => {
|
||||
if (!canPrewrite || !aiStep || !upcomingKey) return;
|
||||
let stopped = false;
|
||||
void (async () => {
|
||||
for (const id of upcomingKey.split(",")) {
|
||||
if (stopped || prewritten.current.has(id)) continue;
|
||||
prewritten.current.add(id);
|
||||
try {
|
||||
await writeLeadAIOnce(qc, campaignId, id, aiStep);
|
||||
} catch (err) {
|
||||
// Out of balance or over the limit: stop reaching ahead; the open lead says why.
|
||||
const code = (err as AppError).code;
|
||||
if (code === "insufficient_credits" || code === "usage_cap_exceeded" || code === "ai_unavailable") return;
|
||||
}
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
stopped = true;
|
||||
};
|
||||
}, [canPrewrite, aiStep, upcomingKey, qc, campaignId]);
|
||||
|
||||
const approveOne = async () => {
|
||||
if (!activeId) return;
|
||||
const following = leads[index + 1]?.contact_id ?? leads[index - 1]?.contact_id ?? null;
|
||||
try {
|
||||
await approve.mutateAsync({ contact_ids: [activeId] });
|
||||
toast.success("Approved. Their first email goes out on schedule.");
|
||||
if (effectiveStatus === "waiting" && following) {
|
||||
setDirection(1);
|
||||
setActiveId(following);
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error(buildError(err as AppError));
|
||||
}
|
||||
};
|
||||
const reopenOne = async () => {
|
||||
if (!activeId) return;
|
||||
try {
|
||||
await reopen.mutateAsync([activeId]);
|
||||
toast.success("Back to review");
|
||||
} catch (err) {
|
||||
toast.error(buildError(err as AppError));
|
||||
}
|
||||
};
|
||||
|
||||
// Keyboard: J/K move through leads, A approves the open lead.
|
||||
React.useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.metaKey || e.ctrlKey || e.altKey || typing(e.target)) return;
|
||||
if (e.key === "j") move(1);
|
||||
else if (e.key === "k") move(-1);
|
||||
else if (e.key === "a" && canSend && !dirtyRef.current && leads[index]?.status === "waiting") void approveOne();
|
||||
else return;
|
||||
e.preventDefault();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
});
|
||||
|
||||
const pickStatus = (s: "all" | ReviewStatus) => {
|
||||
setStatus(s);
|
||||
setSelected(new Set());
|
||||
setActiveId(null);
|
||||
};
|
||||
const pickMissing = (f: MissingField) => {
|
||||
setMissing(f);
|
||||
setStatus("all");
|
||||
setSelected(new Set());
|
||||
setActiveId(null);
|
||||
};
|
||||
|
||||
const toggleReview = (enabled: boolean) => {
|
||||
const waiting = summary.data?.counts.waiting ?? 0;
|
||||
const run = async () => {
|
||||
try {
|
||||
const res = await setReview.mutateAsync(enabled);
|
||||
toast.success(
|
||||
enabled
|
||||
? `Review is on. ${res.held.toLocaleString()} lead${res.held === 1 ? " waits" : "s wait"} for approval.`
|
||||
: `Review is off. ${res.released.toLocaleString()} lead${res.released === 1 ? "" : "s"} approved.`,
|
||||
);
|
||||
setStatus(null);
|
||||
setActiveId(null);
|
||||
} catch (err) {
|
||||
toast.error(buildError(err as AppError));
|
||||
}
|
||||
};
|
||||
if (!enabled && waiting > 0) {
|
||||
if (!canSend) {
|
||||
toast.error("Turning review off approves every waiting lead, which needs the Send campaigns permission.");
|
||||
return;
|
||||
}
|
||||
confirm.show(`Turn review off? The ${waiting.toLocaleString()} waiting lead${waiting === 1 ? " is" : "s are"} approved and start on schedule.`, run);
|
||||
} else {
|
||||
void run();
|
||||
}
|
||||
};
|
||||
|
||||
const writeAll = () => {
|
||||
const s = summary.data;
|
||||
if (!s) return;
|
||||
const scope = selected.size > 0 ? `${selected.size.toLocaleString()} selected lead${selected.size === 1 ? "" : "s"}` : `${s.ai.pending.toLocaleString()} leads`;
|
||||
const cost = selected.size > 0 && s.ai.pending > 0 ? (s.ai.estimated_cost_usd / s.ai.pending) * selected.size : s.ai.estimated_cost_usd;
|
||||
confirm.show(
|
||||
`Write the first email's AI copy now for ${scope}? It costs about ${fmtUsd(cost)} from the balance, the same as writing it at send time, and is not charged again when it sends.`,
|
||||
async () => {
|
||||
void bulk.run(selected.size > 0 ? { contact_ids: [...selected] } : {});
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const bulkApprove = () => {
|
||||
const ids = [...selected];
|
||||
confirm.show(`Approve ${ids.length.toLocaleString()} lead${ids.length === 1 ? "" : "s"}? Their first emails go out on schedule.`, async () => {
|
||||
try {
|
||||
const res = await approve.mutateAsync({ contact_ids: ids });
|
||||
toast.success(`${res.released.toLocaleString()} approved`);
|
||||
setSelected(new Set());
|
||||
} catch (err) {
|
||||
toast.error(buildError(err as AppError));
|
||||
}
|
||||
});
|
||||
};
|
||||
const approveEverything = () => {
|
||||
const n = summary.data?.counts.waiting ?? 0;
|
||||
confirm.show(`Approve all ${n.toLocaleString()} waiting leads? Their first emails go out on schedule.`, async () => {
|
||||
try {
|
||||
const res = await approve.mutateAsync({ all: true });
|
||||
toast.success(`${res.released.toLocaleString()} approved`);
|
||||
} catch (err) {
|
||||
toast.error(buildError(err as AppError));
|
||||
}
|
||||
});
|
||||
};
|
||||
const bulkReopen = async () => {
|
||||
try {
|
||||
const res = await reopen.mutateAsync([...selected]);
|
||||
toast.success(`${res.held.toLocaleString()} sent back to review`);
|
||||
setSelected(new Set());
|
||||
} catch (err) {
|
||||
toast.error(buildError(err as AppError));
|
||||
}
|
||||
};
|
||||
|
||||
if (summary.isLoading) return <ReviewSkeleton />;
|
||||
if (summary.isError || !summary.data) {
|
||||
return (
|
||||
<div className="flex-1 flex flex-col items-center justify-center gap-2 p-10 text-[12.5px] text-slate-500">
|
||||
Could not load the review.
|
||||
<button type="button" onClick={() => void summary.refetch()} className="text-sky-700 font-medium">
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (summary.data.counts.total === 0) {
|
||||
return (
|
||||
<div className="flex-1 flex flex-col items-center justify-center gap-2 p-10 text-center">
|
||||
<UsersIcon className="w-5 h-5 text-slate-400" />
|
||||
<p className="text-[12.5px] text-slate-600">No leads yet. Add leads, then read this email as each one gets it here before it goes out.</p>
|
||||
<Link to="/app/campaigns/$id/leads" params={{ id: campaignId }} className="text-[12.5px] text-sky-700 hover:text-sky-800 font-medium">
|
||||
Go to Leads
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const waiting = summary.data.counts.waiting;
|
||||
const emptyText =
|
||||
effectiveStatus === "waiting"
|
||||
? "Nobody is waiting for review."
|
||||
: missing
|
||||
? "No leads match."
|
||||
: q
|
||||
? "No leads match your search."
|
||||
: "No leads here.";
|
||||
|
||||
return (
|
||||
<div className="h-full min-h-0 bg-white overflow-hidden flex flex-col">
|
||||
<ReviewToolbar
|
||||
campaignId={campaignId}
|
||||
summary={summary.data}
|
||||
canToggle={canEdit}
|
||||
toggling={setReview.isPending}
|
||||
onToggleReview={toggleReview}
|
||||
onMissing={pickMissing}
|
||||
canApproveAll={reviewMode && waiting > 0 && canSend}
|
||||
onApproveAll={approveEverything}
|
||||
canWriteAI={canAI && canEdit}
|
||||
aiProgress={bulk.progress}
|
||||
onWriteAI={writeAll}
|
||||
onStopAI={bulk.stop}
|
||||
/>
|
||||
<div className="flex-1 min-h-0 flex">
|
||||
<div className={cn("w-full md:w-[270px] lg:w-[290px] shrink-0 md:border-r border-slate-200 min-h-0", mobilePane ? "hidden md:block" : "block")}>
|
||||
<ReviewLeadList
|
||||
writing={writingLeads}
|
||||
leads={leads}
|
||||
loading={list.isLoading}
|
||||
hasMore={!!list.hasNextPage}
|
||||
loadingMore={list.isFetchingNextPage}
|
||||
onLoadMore={() => void list.fetchNextPage()}
|
||||
activeId={activeId}
|
||||
onOpen={open}
|
||||
selected={selected}
|
||||
onToggle={(id) =>
|
||||
setSelected((cur) => {
|
||||
const next = new Set(cur);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
})
|
||||
}
|
||||
onToggleAll={(all) => setSelected(all ? new Set(leads.map((l) => l.contact_id)) : new Set())}
|
||||
search={search}
|
||||
onSearch={setSearch}
|
||||
status={effectiveStatus}
|
||||
onStatus={pickStatus}
|
||||
counts={summary.data.counts}
|
||||
reviewMode={reviewMode}
|
||||
missing={missing}
|
||||
onClearMissing={() => {
|
||||
setMissing(undefined);
|
||||
setActiveId(null);
|
||||
}}
|
||||
emptyText={emptyText}
|
||||
/>
|
||||
</div>
|
||||
<div className={cn("relative flex-1 min-w-0 min-h-0 overflow-hidden", mobilePane ? "block" : "hidden md:block")}>
|
||||
<AnimatePresence initial={false} custom={direction} mode="popLayout">
|
||||
{activeId ? (
|
||||
<motion.div
|
||||
key={activeId}
|
||||
custom={direction}
|
||||
variants={{
|
||||
enter: (d: number) => ({ opacity: 0, y: d * 14 }),
|
||||
center: { opacity: 1, y: 0 },
|
||||
exit: (d: number) => ({ opacity: 0, y: d * -10 }),
|
||||
}}
|
||||
initial="enter"
|
||||
animate="center"
|
||||
exit="exit"
|
||||
transition={{ duration: 0.2, ease: "easeOut" }}
|
||||
className="absolute inset-0"
|
||||
>
|
||||
<LeadEmailsPane
|
||||
key={activeId}
|
||||
campaignId={campaignId}
|
||||
contactId={activeId}
|
||||
lockedStep={stepId}
|
||||
reviewMode={reviewMode}
|
||||
canSend={canSend}
|
||||
canEdit={canEdit}
|
||||
canAI={canAI}
|
||||
onApprove={approveOne}
|
||||
onReopen={reopenOne}
|
||||
position={index >= 0 ? index + 1 : undefined}
|
||||
total={filterCount(summary.data.counts, effectiveStatus)}
|
||||
onPrev={index > 0 ? () => move(-1) : undefined}
|
||||
onNext={index >= 0 && index < leads.length - 1 ? () => move(1) : undefined}
|
||||
onBack={() => guarded(() => setMobilePane(false))}
|
||||
onDirtyChange={(d) => {
|
||||
dirtyRef.current = d;
|
||||
}}
|
||||
/>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div key="none" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="h-full flex items-center justify-center text-[12.5px] text-slate-500 p-6 text-center">
|
||||
{list.isLoading ? "" : "Pick a lead to read their emails as they will be sent."}
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selected.size > 0 && (
|
||||
<div className="fixed bottom-4 left-1/2 -translate-x-1/2 z-30 flex items-center max-w-[calc(100vw-16px)] flex-wrap justify-center md:max-w-none md:flex-nowrap gap-1.5 rounded-md border border-slate-200 bg-white shadow-[0_6px_20px_-4px_rgba(15,23,42,0.12),0_2px_4px_rgba(15,23,42,0.04)] px-2 py-1.5">
|
||||
<div className="inline-flex items-center gap-1.5 px-2 h-7 rounded bg-sky-50 text-sky-700 text-[12px] font-medium">
|
||||
<CheckIcon className="w-3 h-3" />
|
||||
<span>{selected.size.toLocaleString()} selected</span>
|
||||
</div>
|
||||
{canSend && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={bulkApprove}
|
||||
disabled={approve.isPending}
|
||||
className="h-7 px-2.5 rounded text-[12px] text-slate-700 hover:text-slate-900 hover:bg-slate-100 font-medium inline-flex items-center gap-1.5 disabled:opacity-60"
|
||||
>
|
||||
{approve.isPending ? <RunningGrid className="text-sky-600" /> : <CheckIcon className="w-3 h-3" />}
|
||||
Approve
|
||||
</button>
|
||||
)}
|
||||
{canAI && canEdit && summary.data.ai.blocks > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={writeAll}
|
||||
disabled={bulk.running}
|
||||
className="h-7 px-2.5 rounded text-[12px] text-slate-700 hover:text-slate-900 hover:bg-slate-100 font-medium inline-flex items-center gap-1.5 disabled:opacity-60"
|
||||
>
|
||||
{bulk.running ? <RunningGrid className="text-sky-600" /> : <SparklesIcon className="w-3 h-3" />}
|
||||
<span className="hidden sm:inline">{bulk.running ? "Writing AI copy" : "Write AI copy"}</span>
|
||||
</button>
|
||||
)}
|
||||
{reviewMode && canEdit && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void bulkReopen()}
|
||||
disabled={reopen.isPending}
|
||||
className="h-7 px-2.5 rounded text-[12px] text-slate-700 hover:text-slate-900 hover:bg-slate-100 font-medium inline-flex items-center gap-1.5 disabled:opacity-60"
|
||||
>
|
||||
{reopen.isPending ? <RunningGrid className="text-sky-600" /> : <UndoIcon className="w-3 h-3" />}
|
||||
<span className="hidden sm:inline">Back to review</span>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelected(new Set())}
|
||||
aria-label="Clear selection"
|
||||
className="size-7 rounded text-slate-500 hover:text-slate-800 hover:bg-slate-100 inline-flex items-center justify-center"
|
||||
>
|
||||
<XIcon className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,543 @@
|
||||
import React from "react";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import {
|
||||
AlertTriangleIcon,
|
||||
ArrowLeftIcon,
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronUpIcon,
|
||||
CornerUpLeftIcon,
|
||||
FlaskConicalIcon,
|
||||
MailCheckIcon,
|
||||
PencilLineIcon,
|
||||
RefreshCwIcon,
|
||||
RotateCcwIcon,
|
||||
SparklesIcon,
|
||||
UndoIcon,
|
||||
} from "lucide-react";
|
||||
import toast from "react-hot-toast/headless";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import ScrollStrip from "@/components/ui/scroll-strip";
|
||||
import EmailBody from "@/components/app/unibox/EmailBody";
|
||||
import EmailContentEditor from "@/components/app/campaigns/sequences/EmailContentEditor";
|
||||
import { useConfirm } from "@/hooks/context/confirm";
|
||||
import {
|
||||
aiWriteRunning,
|
||||
useLeadsBeingWritten,
|
||||
useLeadEmails,
|
||||
usePersonalizeLeadEmail,
|
||||
useResetLeadEmail,
|
||||
writeLeadAIOnce,
|
||||
} from "@/lib/api/hooks/app/campaigns/useCampaignReview";
|
||||
import type { LeadEmailStep } from "@/lib/api/models/app/campaigns/Review";
|
||||
import { MISSING_FIELD_LABEL, leadName } from "@/lib/api/models/app/campaigns/Review";
|
||||
import type { AppError } from "@/lib/api/client/normalizeError";
|
||||
import buildError from "@/lib/helper/buildError";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { STATUS_PILL } from "./reviewStatus";
|
||||
import { EmailPaneSkeleton, RunningGrid, RunningLabel } from "./reviewLook";
|
||||
import { aiPreviewCss } from "./aiPreviewCss";
|
||||
|
||||
// One left edge for the header, tabs, notices and email; the email keeps a readable width.
|
||||
const EDGE = "w-full px-5";
|
||||
const COLUMN = "w-full max-w-[820px] px-5";
|
||||
|
||||
type AIState = "writing" | "error" | "balance" | "cap" | "unavailable";
|
||||
|
||||
const fmtDate = (v?: string | null) =>
|
||||
v ? new Date(v).toLocaleString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }) : "";
|
||||
|
||||
function Notice({ tone, icon: Icon, children }: { tone: "amber" | "sky" | "violet" | "slate" | "rose"; icon: React.ElementType; children: React.ReactNode }) {
|
||||
const tones = {
|
||||
amber: "bg-amber-50 text-amber-800 border-amber-200",
|
||||
sky: "bg-sky-50 text-sky-800 border-sky-200",
|
||||
violet: "bg-violet-50 text-violet-800 border-violet-200",
|
||||
slate: "bg-slate-50 text-slate-700 border-slate-200",
|
||||
rose: "bg-rose-50 text-rose-800 border-rose-200",
|
||||
};
|
||||
return (
|
||||
<motion.div
|
||||
layout
|
||||
initial={{ opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -4 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className={cn("px-2.5 py-1.5 rounded-md border text-[12px] leading-relaxed flex items-start gap-2", tones[tone])}
|
||||
>
|
||||
<Icon className="w-3.5 h-3.5 shrink-0 mt-[3px]" />
|
||||
<div className="min-w-0 flex-1">{children}</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function LeadEmailsPane({
|
||||
campaignId,
|
||||
contactId,
|
||||
reviewMode,
|
||||
canSend,
|
||||
canEdit,
|
||||
canAI,
|
||||
onApprove,
|
||||
onReopen,
|
||||
lockedStep,
|
||||
position,
|
||||
total,
|
||||
onPrev,
|
||||
onNext,
|
||||
onBack,
|
||||
onDirtyChange,
|
||||
}: {
|
||||
campaignId: string;
|
||||
contactId: string;
|
||||
reviewMode: boolean;
|
||||
canSend: boolean;
|
||||
canEdit: boolean;
|
||||
canAI: boolean;
|
||||
onApprove: () => Promise<void>;
|
||||
onReopen: () => Promise<void>;
|
||||
// Shows only this step, for the Review tab of a step's panel.
|
||||
lockedStep?: string;
|
||||
// Where this lead sits in the list, for the "3 of 40" next to the arrows.
|
||||
position?: number;
|
||||
total?: number;
|
||||
onPrev?: () => void;
|
||||
onNext?: () => void;
|
||||
onBack: () => void;
|
||||
onDirtyChange: (dirty: boolean) => void;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const confirm = useConfirm();
|
||||
const emails = useLeadEmails(campaignId, contactId);
|
||||
const personalize = usePersonalizeLeadEmail(campaignId, contactId);
|
||||
const reset = useResetLeadEmail(campaignId, contactId);
|
||||
const [stepId, setStepId] = React.useState<string | null>(lockedStep ?? null);
|
||||
const [draft, setDraft] = React.useState<{ subject: string; html: string; plain: string } | null>(null);
|
||||
const [dirty, setDirty] = React.useState(false);
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
const [ai, setAI] = React.useState<Record<string, AIState>>({});
|
||||
const [fresh, setFresh] = React.useState<Record<string, string[]>>({});
|
||||
const attempted = React.useRef(new Set<string>());
|
||||
// Re-render when a background write for this lead starts or ends.
|
||||
useLeadsBeingWritten(campaignId);
|
||||
|
||||
const data = emails.data;
|
||||
const steps = React.useMemo(() => data?.steps ?? [], [data]);
|
||||
const step: LeadEmailStep | undefined = steps.find((s) => s.step_id === stepId) ?? steps.find((s) => !s.sent) ?? steps[0];
|
||||
const canWrite = canAI && canEdit;
|
||||
const pending = step && !step.sent ? (step.ai_blocks ?? []).filter((b) => !b.written) : [];
|
||||
const aiState = step ? ai[step.step_id] : undefined;
|
||||
const writing = aiState === "writing" || (!!step && pending.length > 0 && aiWriteRunning(campaignId, contactId, step.step_id));
|
||||
|
||||
React.useEffect(() => onDirtyChange(dirty), [dirty, onDirtyChange]);
|
||||
|
||||
const write = React.useCallback(
|
||||
async (target: LeadEmailStep, rewrite: boolean) => {
|
||||
const ids = (target.ai_blocks ?? []).map((b) => b.id);
|
||||
setAI((s) => ({ ...s, [target.step_id]: "writing" }));
|
||||
try {
|
||||
await writeLeadAIOnce(qc, campaignId, contactId, target.step_id, rewrite);
|
||||
setFresh((f) => ({ ...f, [target.step_id]: ids }));
|
||||
setAI((s) => {
|
||||
const next = { ...s };
|
||||
delete next[target.step_id];
|
||||
return next;
|
||||
});
|
||||
} catch (err) {
|
||||
const code = (err as AppError).code;
|
||||
const state: AIState =
|
||||
code === "insufficient_credits" ? "balance" : code === "usage_cap_exceeded" ? "cap" : code === "ai_unavailable" ? "unavailable" : "error";
|
||||
setAI((s) => ({ ...s, [target.step_id]: state }));
|
||||
}
|
||||
},
|
||||
[qc, campaignId, contactId],
|
||||
);
|
||||
|
||||
// AI copy is written the moment an email is opened, so a reviewer reads the real thing.
|
||||
const pendingKey = pending.map((b) => b.id).join(",");
|
||||
React.useEffect(() => {
|
||||
if (!step || !canWrite || !pendingKey) return;
|
||||
if (attempted.current.has(step.step_id)) return;
|
||||
attempted.current.add(step.step_id);
|
||||
void write(step, false);
|
||||
}, [step, canWrite, pendingKey, write]);
|
||||
|
||||
const stopEditing = () => {
|
||||
setDraft(null);
|
||||
setDirty(false);
|
||||
};
|
||||
const requestStopEditing = () => {
|
||||
if (dirty) confirm.show("Discard your changes to this lead's email?", async () => stopEditing());
|
||||
else stopEditing();
|
||||
};
|
||||
const pickStep = (id: string) => {
|
||||
if (id === step?.step_id) return;
|
||||
const go = () => {
|
||||
stopEditing();
|
||||
setStepId(id);
|
||||
};
|
||||
if (dirty) confirm.show("Discard your changes to this lead's email?", async () => go());
|
||||
else go();
|
||||
};
|
||||
const startEditing = () => {
|
||||
if (!step) return;
|
||||
setDraft({ subject: step.source.subject, html: step.source.body_html, plain: step.source.body_plain });
|
||||
setDirty(false);
|
||||
};
|
||||
const save = async () => {
|
||||
if (!step || !draft) return;
|
||||
try {
|
||||
await personalize.mutateAsync({ stepId: step.step_id, subject: draft.subject, body_html: draft.html, body_plain: draft.plain });
|
||||
toast.success("Saved for this lead");
|
||||
stopEditing();
|
||||
attempted.current.delete(step.step_id);
|
||||
} catch (err) {
|
||||
toast.error(buildError(err as AppError));
|
||||
}
|
||||
};
|
||||
const resetCopy = () => {
|
||||
if (!step) return;
|
||||
confirm.show("Go back to the step's copy for this lead? Your edits to this email are removed.", async () => {
|
||||
try {
|
||||
await reset.mutateAsync(step.step_id);
|
||||
attempted.current.delete(step.step_id);
|
||||
toast.success("Back to the step's copy");
|
||||
} catch (err) {
|
||||
toast.error(buildError(err as AppError));
|
||||
}
|
||||
});
|
||||
};
|
||||
const act = async (fn: () => Promise<void>) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (emails.isLoading) return <EmailPaneSkeleton />;
|
||||
if (emails.isError || !data) {
|
||||
return (
|
||||
<div className="h-full flex flex-col items-center justify-center gap-2 text-[12.5px] text-slate-500">
|
||||
Could not load this lead's emails.
|
||||
<button type="button" onClick={() => void emails.refetch()} className="text-sky-700 hover:text-sky-800 font-medium">
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const lead = data.lead;
|
||||
const pill = STATUS_PILL[lead.status];
|
||||
const editable = !!step && !step.sent && canEdit;
|
||||
const firstName = lead.first_name?.trim() || leadName(lead);
|
||||
const blockName = (pending[0]?.name || step?.ai_blocks?.[0]?.name || "").toLowerCase();
|
||||
const written = !!step && (step.ai_blocks?.length ?? 0) > 0 && pending.length === 0;
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col min-h-0">
|
||||
<div className="shrink-0 border-b border-slate-200">
|
||||
<div className={cn(EDGE, "h-12 flex items-center gap-2.5")}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onBack}
|
||||
className="md:hidden h-7 px-1.5 -ml-1.5 rounded text-[12px] text-slate-600 hover:bg-slate-100 inline-flex items-center gap-1"
|
||||
>
|
||||
<ArrowLeftIcon className="w-3.5 h-3.5" />
|
||||
Leads
|
||||
</button>
|
||||
<div className="min-w-0 flex-1 flex items-center gap-2">
|
||||
<span className="shrink-0 max-w-[50%] text-[13.5px] font-semibold text-slate-900 truncate">{leadName(lead)}</span>
|
||||
<span className={cn("shrink-0 h-5 px-1.5 rounded border text-[10.5px] font-medium inline-flex items-center", pill.className)}>{pill.label}</span>
|
||||
<span className="hidden sm:block min-w-0 text-[12px] text-slate-500 truncate">
|
||||
{lead.email}
|
||||
{lead.company ? ` · ${lead.company}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="hidden md:flex items-center gap-0.5">
|
||||
{position !== undefined && total !== undefined && (
|
||||
<span className="mr-1.5 text-[11.5px] tabular-nums text-slate-400">
|
||||
{position.toLocaleString()} of {total.toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
<button type="button" onClick={onPrev} disabled={!onPrev} title="Previous lead (K)" aria-label="Previous lead" className="size-7 rounded-md border border-slate-200 text-slate-500 hover:text-slate-800 hover:border-slate-300 disabled:opacity-30 disabled:pointer-events-none flex items-center justify-center">
|
||||
<ChevronUpIcon className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<button type="button" onClick={onNext} disabled={!onNext} title="Next lead (J)" aria-label="Next lead" className="size-7 rounded-md border border-slate-200 text-slate-500 hover:text-slate-800 hover:border-slate-300 disabled:opacity-30 disabled:pointer-events-none flex items-center justify-center">
|
||||
<ChevronDownIcon className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
{lead.status === "waiting" && canSend && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || dirty}
|
||||
title={dirty ? "Save or discard your edit first" : "Approve this lead (A)"}
|
||||
onClick={() => void act(onApprove)}
|
||||
className="h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5 shadow-sm disabled:opacity-60 transition-colors"
|
||||
>
|
||||
{busy ? <RunningGrid /> : <CheckIcon className="w-3.5 h-3.5" />}
|
||||
Approve
|
||||
</button>
|
||||
)}
|
||||
{lead.status === "ready" && reviewMode && canEdit && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void act(onReopen)}
|
||||
title="Hold this lead for review again"
|
||||
className="h-7 px-2.5 rounded-md border border-slate-200 text-slate-700 hover:bg-slate-50 text-[12px] inline-flex items-center gap-1.5 disabled:opacity-60"
|
||||
>
|
||||
{busy ? <RunningGrid className="text-sky-600" /> : <UndoIcon className="w-3.5 h-3.5" />}
|
||||
<span className="hidden sm:inline">Back to review</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{steps.length === 0 ? (
|
||||
<p className="p-6 text-center text-[12.5px] text-slate-500">This campaign has no email steps yet.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className={cn("shrink-0 border-b border-slate-200", lockedStep && "hidden")}>
|
||||
<ScrollStrip activeKey={step?.step_id} innerClassName={cn(EDGE, "px-3 flex items-center gap-1")}>
|
||||
{steps.map((s, i) => {
|
||||
const active = s.step_id === step?.step_id;
|
||||
const aiPending = !s.sent && (s.ai_blocks ?? []).some((b) => !b.written);
|
||||
return (
|
||||
<button
|
||||
key={s.step_id}
|
||||
type="button"
|
||||
data-active={active}
|
||||
onClick={() => pickStep(s.step_id)}
|
||||
className={cn(
|
||||
"relative h-9 px-2 inline-flex items-center gap-1.5 text-[12.5px] whitespace-nowrap transition-colors",
|
||||
active ? "text-slate-900 font-medium" : "text-slate-500 hover:text-slate-800",
|
||||
)}
|
||||
>
|
||||
{s.sent ? <MailCheckIcon className="w-3.5 h-3.5 text-emerald-600" /> : s.threaded ? <CornerUpLeftIcon className="w-3.5 h-3.5" /> : null}
|
||||
{s.name?.trim() || `Email ${i + 1}`}
|
||||
{s.personalized && <PencilLineIcon className="w-3 h-3 text-sky-600" />}
|
||||
{aiPending &&
|
||||
(ai[s.step_id] === "writing" || aiWriteRunning(campaignId, contactId, s.step_id) ? (
|
||||
<RunningGrid className="text-sky-600" />
|
||||
) : (
|
||||
<SparklesIcon className="w-3 h-3 text-violet-500" />
|
||||
))}
|
||||
{active && (
|
||||
<motion.span
|
||||
layoutId={`review-step-${contactId}`}
|
||||
className="absolute left-1 right-1 -bottom-px h-0.5 rounded-full bg-sky-600"
|
||||
transition={{ type: "spring", duration: 0.3, bounce: 0.15 }}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</ScrollStrip>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
{step && draft ? (
|
||||
<div className={cn(COLUMN, "py-4 flex flex-col gap-3")}>
|
||||
<p className="text-[12px] text-slate-500">
|
||||
Editing this email for {leadName(lead)} only. Merge fields and AI blocks still fill in when it sends.
|
||||
</p>
|
||||
<EmailContentEditor
|
||||
key={`${contactId}:${step.step_id}`}
|
||||
subject={draft.subject}
|
||||
onSubjectChange={(v) => {
|
||||
setDraft((d) => d && { ...d, subject: v });
|
||||
setDirty(true);
|
||||
}}
|
||||
bodyHtml={draft.html}
|
||||
onBodyChange={(html, plain) => {
|
||||
setDraft((d) => d && { ...d, html, plain });
|
||||
setDirty(true);
|
||||
}}
|
||||
subjectLocked={step.threaded ? { subject: step.subject, note: "Replies in the lead's thread, so it carries the conversation's subject." } : undefined}
|
||||
campaignId={campaignId}
|
||||
stepId={step.step_id}
|
||||
/>
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<button type="button" onClick={requestStopEditing} className="h-8 px-3 rounded-md border border-slate-200 text-[12.5px] text-slate-700 hover:bg-slate-50">
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void save()}
|
||||
disabled={personalize.isPending || !dirty}
|
||||
className="h-8 px-3 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12.5px] font-medium inline-flex items-center gap-1.5 disabled:opacity-60"
|
||||
>
|
||||
{personalize.isPending && <RunningGrid />}
|
||||
Save for this lead
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : step ? (
|
||||
<motion.div
|
||||
key={step.step_id}
|
||||
initial={{ opacity: 0, y: 6 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.2, ease: "easeOut" }}
|
||||
className={cn(COLUMN, "py-3 flex flex-col gap-2")}
|
||||
>
|
||||
<AnimatePresence initial={false}>
|
||||
{step.sent && (
|
||||
<Notice key="sent" tone="slate" icon={MailCheckIcon}>
|
||||
Sent {fmtDate(step.sent_at)}. This is the current copy, which can no longer change for this lead.
|
||||
</Notice>
|
||||
)}
|
||||
{(step.errors ?? []).map((e) => (
|
||||
<Notice key={e} tone="rose" icon={AlertTriangleIcon}>
|
||||
{e}
|
||||
</Notice>
|
||||
))}
|
||||
{(step.missing?.length ?? 0) > 0 && (
|
||||
<Notice key="missing" tone="amber" icon={AlertTriangleIcon}>
|
||||
This lead has no {step.missing!.map((m) => MISSING_FIELD_LABEL[m] ?? m).join(" or ")}, and this email prints it with nothing in its place.
|
||||
{editable && " Fill it in on the contact, or edit this email for them."}
|
||||
</Notice>
|
||||
)}
|
||||
{step.personalized && (
|
||||
<Notice key="personal" tone="sky" icon={PencilLineIcon}>
|
||||
Personalized for this lead{step.edited_at ? ` on ${fmtDate(step.edited_at)}` : ""}.
|
||||
{step.step_changed && " The step's copy changed since, and this lead still gets this version."}
|
||||
</Notice>
|
||||
)}
|
||||
{step.variant_id && !step.personalized && (
|
||||
<Notice key="variant" tone="slate" icon={FlaskConicalIcon}>
|
||||
This lead is in an A/B variant of this step.
|
||||
</Notice>
|
||||
)}
|
||||
{pending.length > 0 && aiState === "balance" && (
|
||||
<Notice key="ai-balance" tone="amber" icon={SparklesIcon}>
|
||||
The balance is too low to write the AI part now, so it is written when the email sends.{" "}
|
||||
<Link to="/app/settings/billing/{-$tab}" params={{ tab: "balance" }} className="font-medium underline underline-offset-2">
|
||||
Add money
|
||||
</Link>
|
||||
</Notice>
|
||||
)}
|
||||
{pending.length > 0 && aiState === "cap" && (
|
||||
<Notice key="ai-cap" tone="amber" icon={SparklesIcon}>
|
||||
The workspace reached its AI spend limit, so the AI part is written when the email sends.
|
||||
</Notice>
|
||||
)}
|
||||
{pending.length > 0 && aiState === "unavailable" && (
|
||||
<Notice key="ai-off" tone="slate" icon={SparklesIcon}>
|
||||
This instance has no AI provider set up, so the marked part cannot be written. An operator can connect one in the instance settings.
|
||||
</Notice>
|
||||
)}
|
||||
{pending.length > 0 && aiState === "error" && (
|
||||
<Notice key="ai-error" tone="rose" icon={SparklesIcon}>
|
||||
The AI part could not be written just now.{" "}
|
||||
<button type="button" onClick={() => void write(step, false)} className="font-medium underline underline-offset-2">
|
||||
Try again
|
||||
</button>
|
||||
</Notice>
|
||||
)}
|
||||
{pending.length > 0 && !canWrite && (
|
||||
<Notice key="ai-later" tone="slate" icon={SparklesIcon}>
|
||||
AI writes the marked part for {firstName} when the email sends.
|
||||
</Notice>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<div className="rounded-lg border border-slate-200 bg-white shadow-[0_1px_2px_rgba(15,23,42,0.04)] overflow-hidden">
|
||||
<dl className="px-4 py-3 border-b border-slate-100 grid grid-cols-[60px_1fr] gap-y-1 text-[12.5px]">
|
||||
<dt className="text-slate-400">From</dt>
|
||||
<dd className="text-slate-700 truncate">
|
||||
{data.from ? `${data.from.name} <${data.from.email}>` : <span className="text-slate-500">The mailbox the campaign picks when it sends</span>}
|
||||
</dd>
|
||||
<dt className="text-slate-400">To</dt>
|
||||
<dd className="text-slate-700 truncate">{lead.email}</dd>
|
||||
<dt className="text-slate-400">Subject</dt>
|
||||
<dd className="text-slate-900 font-medium truncate">
|
||||
{step.subject || <span className="text-slate-400 font-normal">No subject</span>}
|
||||
{step.threaded && <span className="ml-1.5 text-[11px] font-normal text-slate-400">replies in the thread</span>}
|
||||
</dd>
|
||||
</dl>
|
||||
<div className="px-4 py-3.5">
|
||||
<EmailBody
|
||||
html={step.body_html}
|
||||
plain={step.body_plain}
|
||||
extraCss={aiPreviewCss({ writing: writing || (canWrite && pending.length > 0 && !aiState), justWritten: fresh[step.step_id] ?? [] })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 flex-wrap min-h-8">
|
||||
<AnimatePresence mode="wait" initial={false}>
|
||||
{writing ? (
|
||||
<motion.div
|
||||
key="writing"
|
||||
initial={{ opacity: 0, y: 4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -4 }}
|
||||
transition={{ duration: 0.16 }}
|
||||
>
|
||||
<RunningLabel
|
||||
labels={[
|
||||
`Reading about ${lead.company || firstName}`,
|
||||
`Writing ${firstName}'s ${blockName || "AI part"}`,
|
||||
"Matching your voice",
|
||||
]}
|
||||
/>
|
||||
</motion.div>
|
||||
) : written && !step.sent ? (
|
||||
<motion.span
|
||||
key="written"
|
||||
initial={{ opacity: 0, y: 4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -4 }}
|
||||
transition={{ duration: 0.16 }}
|
||||
className="text-[12px] text-slate-500 inline-flex items-center gap-1.5"
|
||||
>
|
||||
<SparklesIcon className="w-3.5 h-3.5 text-violet-500" />
|
||||
AI wrote the highlighted part for {firstName}.
|
||||
{canWrite && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void write(step, true)}
|
||||
disabled={writing}
|
||||
title="Write it again; charged like the first time"
|
||||
className="ml-0.5 inline-flex items-center gap-1 font-medium text-sky-700 hover:text-sky-800 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCwIcon className="w-3 h-3" />
|
||||
Rewrite
|
||||
</button>
|
||||
)}
|
||||
</motion.span>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
{editable && (
|
||||
<div className="ml-auto flex items-center gap-1.5">
|
||||
{step.personalized && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={resetCopy}
|
||||
className="h-8 px-2.5 rounded-md text-[12.5px] text-slate-600 hover:bg-slate-100 inline-flex items-center gap-1.5"
|
||||
>
|
||||
<RotateCcwIcon className="w-3.5 h-3.5" />
|
||||
Use the step's copy
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={startEditing}
|
||||
className="h-8 px-3 rounded-md border border-slate-200 bg-white text-[12.5px] text-slate-700 hover:bg-slate-50 inline-flex items-center gap-1.5"
|
||||
>
|
||||
<PencilLineIcon className="w-3.5 h-3.5" />
|
||||
Edit for this lead
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import React from "react";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { AlertTriangleIcon, CheckIcon, ListFilterIcon, PencilLineIcon, XIcon } from "lucide-react";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { SearchInput } from "@/components/ui/field";
|
||||
import { PopoverMenu, PopoverMenuContent, PopoverMenuItem, PopoverMenuTrigger, SelectButton } from "@/components/ui/popover-menu";
|
||||
import type { CampaignReviewSummary, MissingField, ReviewLead, ReviewStatus } from "@/lib/api/models/app/campaigns/Review";
|
||||
import { MISSING_FIELD_LABEL, leadName } from "@/lib/api/models/app/campaigns/Review";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { STATUS_PILL, filterCount } from "./reviewStatus";
|
||||
import { LeadRowsSkeleton, RunningGrid } from "./reviewLook";
|
||||
|
||||
type Filter = "all" | ReviewStatus;
|
||||
|
||||
const FILTERS: { key: Filter; label: string; hint: string }[] = [
|
||||
{ key: "waiting", label: "Waiting", hint: "Waiting for someone to approve their first email" },
|
||||
{ key: "ready", label: "Ready", hint: "Not emailed yet; their first email goes out on schedule" },
|
||||
{ key: "started", label: "Started", hint: "Already received their first email" },
|
||||
{ key: "held", label: "Paused", hint: "Not emailed yet, and paused for another reason" },
|
||||
{ key: "all", label: "All leads", hint: "Every lead in the campaign" },
|
||||
];
|
||||
|
||||
export default function ReviewLeadList({
|
||||
leads,
|
||||
loading,
|
||||
hasMore,
|
||||
loadingMore,
|
||||
onLoadMore,
|
||||
activeId,
|
||||
onOpen,
|
||||
selected,
|
||||
onToggle,
|
||||
onToggleAll,
|
||||
search,
|
||||
onSearch,
|
||||
status,
|
||||
onStatus,
|
||||
counts,
|
||||
reviewMode,
|
||||
missing,
|
||||
onClearMissing,
|
||||
emptyText,
|
||||
writing,
|
||||
}: {
|
||||
leads: ReviewLead[];
|
||||
loading: boolean;
|
||||
hasMore: boolean;
|
||||
loadingMore: boolean;
|
||||
onLoadMore: () => void;
|
||||
activeId: string | null;
|
||||
onOpen: (id: string) => void;
|
||||
selected: Set<string>;
|
||||
onToggle: (id: string) => void;
|
||||
onToggleAll: (all: boolean) => void;
|
||||
search: string;
|
||||
onSearch: (v: string) => void;
|
||||
status: Filter;
|
||||
onStatus: (s: Filter) => void;
|
||||
counts: CampaignReviewSummary["counts"];
|
||||
reviewMode: boolean;
|
||||
missing?: MissingField;
|
||||
onClearMissing: () => void;
|
||||
emptyText: string;
|
||||
writing: Set<string>;
|
||||
}) {
|
||||
const sentinel = React.useRef<HTMLDivElement | null>(null);
|
||||
React.useEffect(() => {
|
||||
const el = sentinel.current;
|
||||
if (!el || !hasMore) return;
|
||||
const io = new IntersectionObserver((entries) => {
|
||||
if (entries.some((e) => e.isIntersecting) && !loadingMore) onLoadMore();
|
||||
});
|
||||
io.observe(el);
|
||||
return () => io.disconnect();
|
||||
}, [hasMore, loadingMore, onLoadMore]);
|
||||
|
||||
// Keep the open lead in view as J and K move through the list, and once the list loads.
|
||||
const listRef = React.useRef<HTMLUListElement | null>(null);
|
||||
React.useEffect(() => {
|
||||
listRef.current?.querySelector<HTMLElement>("[data-active='true']")?.scrollIntoView({ block: "nearest", behavior: "smooth" });
|
||||
}, [activeId, loading]);
|
||||
|
||||
const allSelected = leads.length > 0 && leads.every((l) => selected.has(l.contact_id));
|
||||
// Waiting only means something with approval on; Paused only when someone is.
|
||||
const filters = FILTERS.filter((f) => (f.key === "waiting" ? reviewMode || counts.waiting > 0 : f.key === "held" ? counts.held > 0 : true));
|
||||
const current = FILTERS.find((f) => f.key === status) ?? FILTERS[4];
|
||||
const total = filterCount(counts, status);
|
||||
const at = leads.findIndex((l) => l.contact_id === activeId);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col min-h-0 h-full">
|
||||
<div className="shrink-0 px-3 py-2 flex items-center gap-2 border-b border-slate-200">
|
||||
<Checkbox aria-label="Select all shown" checked={allSelected} onChange={(e) => onToggleAll(e.target.checked)} disabled={leads.length === 0} />
|
||||
<SearchInput value={search} onChange={onSearch} placeholder="Search leads" className="flex-1 min-w-0" />
|
||||
<PopoverMenu align="end">
|
||||
<PopoverMenuTrigger asChild>
|
||||
<SelectButton
|
||||
icon={<ListFilterIcon className="w-3.5 h-3.5" />}
|
||||
label={`${current.label} ${total.toLocaleString()}`}
|
||||
aria-label={`Showing: ${current.label}`}
|
||||
title="Which leads to show"
|
||||
/>
|
||||
</PopoverMenuTrigger>
|
||||
<PopoverMenuContent minWidth={220} className="p-1">
|
||||
{filters.map((f) => (
|
||||
<PopoverMenuItem
|
||||
key={f.key}
|
||||
selected={f.key === status}
|
||||
onSelect={() => onStatus(f.key)}
|
||||
description={f.hint}
|
||||
trailing={
|
||||
<span className="inline-flex items-center gap-1.5 tabular-nums text-[11px] text-slate-400">
|
||||
{filterCount(counts, f.key).toLocaleString()}
|
||||
<CheckIcon className={cn("w-3 h-3 text-sky-600", f.key !== status && "invisible")} />
|
||||
</span>
|
||||
}
|
||||
>
|
||||
{f.label}
|
||||
</PopoverMenuItem>
|
||||
))}
|
||||
</PopoverMenuContent>
|
||||
</PopoverMenu>
|
||||
</div>
|
||||
<AnimatePresence initial={false}>
|
||||
{missing && (
|
||||
<motion.div
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: "auto", opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className="shrink-0 overflow-hidden border-b border-slate-200 bg-amber-50/70"
|
||||
>
|
||||
<div className="h-8 px-3 flex items-center gap-2 text-[12px] text-amber-800">
|
||||
<AlertTriangleIcon className="w-3.5 h-3.5" />
|
||||
<span className="flex-1 min-w-0 truncate">No {MISSING_FIELD_LABEL[missing] ?? missing}</span>
|
||||
<button type="button" onClick={onClearMissing} aria-label="Clear filter" className="size-6 rounded-md hover:bg-amber-100 flex items-center justify-center">
|
||||
<XIcon className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
{loading ? (
|
||||
<LeadRowsSkeleton />
|
||||
) : leads.length === 0 ? (
|
||||
<motion.p initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="p-8 text-center text-[12.5px] text-slate-500">
|
||||
{emptyText}
|
||||
</motion.p>
|
||||
) : (
|
||||
<ul ref={listRef}>
|
||||
<AnimatePresence initial={false}>
|
||||
{leads.map((l) => {
|
||||
const pill = STATUS_PILL[l.status];
|
||||
const active = l.contact_id === activeId;
|
||||
const working = writing.has(l.contact_id);
|
||||
return (
|
||||
<motion.li
|
||||
key={l.contact_id}
|
||||
layout="position"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0, x: 24, height: 0, transition: { duration: 0.22, ease: "easeIn" } }}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
data-active={active}
|
||||
title={l.email}
|
||||
onClick={() => onOpen(l.contact_id)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") onOpen(l.contact_id);
|
||||
}}
|
||||
className={cn(
|
||||
"group relative h-10 pl-3 pr-3 flex items-center gap-2.5 cursor-pointer outline-none transition-colors focus-visible:bg-slate-50",
|
||||
active ? "bg-sky-50/80" : working ? "bg-sky-50/30 hover:bg-sky-50/60" : "hover:bg-slate-50",
|
||||
)}
|
||||
>
|
||||
{active && <motion.span layoutId="review-active-row" className="absolute left-0 top-1 bottom-1 w-0.5 rounded-full bg-sky-600" />}
|
||||
{working && (
|
||||
<span aria-hidden className="absolute inset-x-0 bottom-0 h-px overflow-hidden">
|
||||
<span className="absolute inset-y-0 w-1/3 bg-gradient-to-r from-transparent via-sky-400 to-transparent progress-sweep" />
|
||||
</span>
|
||||
)}
|
||||
<span onClick={(e) => e.stopPropagation()} className="flex">
|
||||
<Checkbox aria-label={`Select ${leadName(l)}`} checked={selected.has(l.contact_id)} onChange={() => onToggle(l.contact_id)} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 flex items-baseline gap-1.5">
|
||||
<span className={cn("text-[12.5px] truncate", active ? "font-semibold text-slate-900" : "font-medium text-slate-800")}>{leadName(l)}</span>
|
||||
{l.company && <span className="text-[11.5px] text-slate-400 truncate">{l.company}</span>}
|
||||
</span>
|
||||
{l.personalized > 0 && <PencilLineIcon className="w-3 h-3 text-sky-600 shrink-0" aria-label="Personalized" />}
|
||||
{(l.missing?.length ?? 0) > 0 && (
|
||||
<span title={`No ${l.missing!.map((m) => MISSING_FIELD_LABEL[m] ?? m).join(", ")}`} className="flex">
|
||||
<AlertTriangleIcon className="w-3 h-3 text-amber-500 shrink-0" />
|
||||
</span>
|
||||
)}
|
||||
{working ? (
|
||||
<span title="AI is writing this lead's copy" className="flex">
|
||||
<RunningGrid className="text-sky-600" />
|
||||
</span>
|
||||
) : (
|
||||
<span title={pill.label} aria-label={pill.label} className={cn("shrink-0 size-1.5 rounded-full", pill.dot)} />
|
||||
)}
|
||||
</div>
|
||||
</motion.li>
|
||||
);
|
||||
})}
|
||||
</AnimatePresence>
|
||||
</ul>
|
||||
)}
|
||||
{hasMore && (
|
||||
<div ref={sentinel}>
|
||||
{loadingMore ? (
|
||||
<LeadRowsSkeleton rows={3} />
|
||||
) : (
|
||||
<div className="p-3 flex justify-center">
|
||||
<button type="button" onClick={onLoadMore} className="text-[12px] text-sky-700 hover:text-sky-800">
|
||||
Load more
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="shrink-0 h-8 px-3 flex items-center gap-2 border-t border-slate-200 text-[11px] text-slate-400">
|
||||
<span className="tabular-nums">
|
||||
{at >= 0 ? `${(at + 1).toLocaleString()} of ${total.toLocaleString()}` : `${total.toLocaleString()} ${total === 1 ? "lead" : "leads"}`}
|
||||
</span>
|
||||
<span className="ml-auto hidden md:inline-flex items-center gap-1">
|
||||
<Kbd>J</Kbd>
|
||||
<Kbd>K</Kbd> to move
|
||||
{reviewMode && (
|
||||
<>
|
||||
<span className="mx-1">·</span>
|
||||
<Kbd>A</Kbd> to approve
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Kbd({ children }: { children: React.ReactNode }) {
|
||||
return <kbd className="min-w-4 h-4 px-1 rounded border border-slate-200 bg-white font-sans text-[10px] text-slate-500 inline-flex items-center justify-center">{children}</kbd>;
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import React from "react";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { motion } from "framer-motion";
|
||||
import { AlertTriangleIcon, CheckCircle2Icon, CheckIcon, FileWarningIcon, MailXIcon, SparklesIcon, UserXIcon } from "lucide-react";
|
||||
import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox";
|
||||
import { PopoverMenu, PopoverMenuContent, PopoverMenuTrigger } from "@/components/ui/popover-menu";
|
||||
import type { CampaignReviewSummary, MissingField } from "@/lib/api/models/app/campaigns/Review";
|
||||
import { MISSING_FIELD_LABEL } from "@/lib/api/models/app/campaigns/Review";
|
||||
import { fmtUsd } from "@/lib/money";
|
||||
import type { BulkAIProgress } from "./useBulkAIWrite";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { RunningGrid } from "./reviewLook";
|
||||
|
||||
const plural = (n: number, one: string, many = one + "s") => `${n.toLocaleString()} ${n === 1 ? one : many}`;
|
||||
|
||||
type Check = { key: string; icon: React.ElementType; tone: string; text: React.ReactNode; action?: React.ReactNode; blocking?: boolean; warn?: boolean };
|
||||
|
||||
const CHIP = "h-7 px-2 rounded-md border inline-flex items-center gap-1.5 text-[12px] font-medium whitespace-nowrap transition-colors";
|
||||
const ACTION = "shrink-0 h-6 px-2 rounded text-[11.5px] font-medium text-sky-700 hover:bg-sky-50 transition-colors";
|
||||
|
||||
// One line above the leads: what to check before sending, the AI copy's progress, and whether leads wait for approval.
|
||||
export default function ReviewToolbar({
|
||||
campaignId,
|
||||
summary,
|
||||
canToggle,
|
||||
toggling,
|
||||
onToggleReview,
|
||||
onMissing,
|
||||
canApproveAll,
|
||||
onApproveAll,
|
||||
canWriteAI,
|
||||
aiProgress,
|
||||
onWriteAI,
|
||||
onStopAI,
|
||||
}: {
|
||||
campaignId: string;
|
||||
summary: CampaignReviewSummary;
|
||||
canToggle: boolean;
|
||||
toggling: boolean;
|
||||
onToggleReview: (enabled: boolean) => void;
|
||||
onMissing: (f: MissingField) => void;
|
||||
canApproveAll: boolean;
|
||||
onApproveAll: () => void;
|
||||
canWriteAI: boolean;
|
||||
aiProgress: BulkAIProgress | null;
|
||||
onWriteAI: () => void;
|
||||
onStopAI: () => void;
|
||||
}) {
|
||||
const { ai } = summary;
|
||||
const [checksOpen, setChecksOpen] = React.useState(false);
|
||||
|
||||
const checks: Check[] = [];
|
||||
for (const e of summary.template_errors ?? []) {
|
||||
checks.push({
|
||||
key: `err-${e.step_id}`,
|
||||
icon: FileWarningIcon,
|
||||
tone: "text-rose-600",
|
||||
blocking: true,
|
||||
text: <>Email {e.position} will not render as written: {e.message}.</>,
|
||||
action: (
|
||||
<Link to="/app/campaigns/$id/steps" params={{ id: campaignId }} className={ACTION}>
|
||||
Fix in Steps
|
||||
</Link>
|
||||
),
|
||||
});
|
||||
}
|
||||
for (const m of summary.missing) {
|
||||
checks.push({
|
||||
key: `missing-${m.field}`,
|
||||
icon: AlertTriangleIcon,
|
||||
tone: "text-amber-500",
|
||||
warn: true,
|
||||
text: (
|
||||
<>
|
||||
{plural(m.leads, "lead")} {m.leads === 1 ? "has" : "have"} no {MISSING_FIELD_LABEL[m.field] ?? m.field}, and the emails print it with nothing in its place.
|
||||
</>
|
||||
),
|
||||
action: (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setChecksOpen(false);
|
||||
onMissing(m.field);
|
||||
}}
|
||||
className={ACTION}
|
||||
>
|
||||
Show them
|
||||
</button>
|
||||
),
|
||||
});
|
||||
}
|
||||
if (summary.unsubscribed > 0) {
|
||||
checks.push({ key: "unsub", icon: UserXIcon, tone: "text-slate-400", text: <>{plural(summary.unsubscribed, "lead")} unsubscribed. Sending skips them.</> });
|
||||
}
|
||||
if (summary.undeliverable > 0) {
|
||||
checks.push({
|
||||
key: "undeliverable",
|
||||
icon: MailXIcon,
|
||||
tone: "text-slate-400",
|
||||
text: <>{plural(summary.undeliverable, "address", "addresses")} failed verification. The launch check counts them against the list.</>,
|
||||
});
|
||||
}
|
||||
const blocking = checks.filter((c) => c.blocking).length;
|
||||
const warnings = checks.filter((c) => c.warn).length;
|
||||
|
||||
const chip =
|
||||
blocking > 0
|
||||
? { tone: "border-rose-200 bg-rose-50 text-rose-700 hover:bg-rose-100/70", icon: FileWarningIcon, label: plural(blocking, "problem") }
|
||||
: warnings > 0
|
||||
? { tone: "border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-100/70", icon: AlertTriangleIcon, label: `${plural(warnings, "thing")} to check` }
|
||||
: checks.length > 0
|
||||
? { tone: "border-slate-200 bg-white text-slate-600 hover:border-slate-300", icon: CheckCircle2Icon, label: `Ready · ${plural(checks.length, "note")}` }
|
||||
: { tone: "border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100/70", icon: CheckCircle2Icon, label: "Ready to send" };
|
||||
|
||||
const total = ai.written + ai.pending;
|
||||
const busy = !!aiProgress || (!!ai.auto && ai.pending > 0);
|
||||
const done = aiProgress ? aiProgress.written : ai.written;
|
||||
const of = aiProgress ? aiProgress.written + aiProgress.remaining : total;
|
||||
const share = of > 0 ? done / of : 1;
|
||||
const aiText = aiProgress
|
||||
? `Writing AI copy now: ${aiProgress.written.toLocaleString()} done, ${aiProgress.remaining.toLocaleString()} to go.`
|
||||
: ai.pending === 0
|
||||
? ai.written > 0
|
||||
? `AI copy in the first email is written for all ${ai.written.toLocaleString()} leads not yet emailed.`
|
||||
: "Every lead has received the first email, so there is no AI copy left to write."
|
||||
: ai.auto
|
||||
? `Writing every lead's AI copy in the background: ${ai.written.toLocaleString()} of ${total.toLocaleString()} done.`
|
||||
: `AI copy is written for every lead once the campaign runs: ${ai.written.toLocaleString()} of ${total.toLocaleString()} written so far.`;
|
||||
|
||||
return (
|
||||
<div className="shrink-0 px-3 py-2 flex flex-wrap items-center gap-2 border-b border-slate-200 bg-slate-50/50">
|
||||
<PopoverMenu open={checksOpen} onOpenChange={setChecksOpen}>
|
||||
<PopoverMenuTrigger asChild>
|
||||
<button type="button" className={cn(CHIP, chip.tone)} title="What sending will do with these leads">
|
||||
<chip.icon className="w-3.5 h-3.5" />
|
||||
{chip.label}
|
||||
</button>
|
||||
</PopoverMenuTrigger>
|
||||
<PopoverMenuContent minWidth={340} className="p-1 max-w-[min(420px,calc(100vw-32px))]">
|
||||
{checks.length === 0 ? (
|
||||
<div className="px-2.5 py-2 flex items-start gap-2 text-[12px] text-emerald-700">
|
||||
<CheckCircle2Icon className="mt-px w-3.5 h-3.5 shrink-0" />
|
||||
Every lead not yet emailed has everything its emails print.
|
||||
</div>
|
||||
) : (
|
||||
<ul className="divide-y divide-slate-100">
|
||||
{checks.map((c) => (
|
||||
<li key={c.key} className="px-2.5 py-2 flex items-start gap-2 text-[12px] leading-relaxed text-slate-700">
|
||||
<c.icon className={cn("mt-[3px] w-3.5 h-3.5 shrink-0", c.tone)} />
|
||||
<span className="min-w-0 flex-1">{c.text}</span>
|
||||
{c.action}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</PopoverMenuContent>
|
||||
</PopoverMenu>
|
||||
|
||||
{ai.blocks > 0 && (
|
||||
<PopoverMenu>
|
||||
<PopoverMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(CHIP, "border-slate-200 bg-white text-slate-700 hover:border-slate-300")}
|
||||
title={aiText}
|
||||
>
|
||||
{busy ? <RunningGrid className="text-sky-600" /> : <SparklesIcon className="w-3.5 h-3.5 text-violet-500" />}
|
||||
{!busy && ai.pending === 0 ? (
|
||||
<>
|
||||
AI copy written
|
||||
<CheckIcon className="w-3 h-3 text-emerald-600" />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className={cn(busy && "text-shimmer text-sky-800")}>
|
||||
AI copy {done.toLocaleString()}/{of.toLocaleString()}
|
||||
</span>
|
||||
<span aria-hidden className="relative h-1 w-10 rounded-full bg-slate-100 overflow-hidden">
|
||||
<motion.span
|
||||
className="absolute inset-y-0 left-0 rounded-full bg-sky-500"
|
||||
initial={false}
|
||||
animate={{ width: `${Math.round(share * 100)}%` }}
|
||||
transition={{ duration: 0.4, ease: "easeOut" }}
|
||||
/>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</PopoverMenuTrigger>
|
||||
<PopoverMenuContent minWidth={300} className="p-2.5 max-w-[min(380px,calc(100vw-32px))]">
|
||||
<p className="text-[12px] leading-relaxed text-slate-700">{aiText}</p>
|
||||
{aiProgress ? (
|
||||
<button type="button" onClick={onStopAI} className="mt-2 h-7 px-2.5 rounded-md border border-slate-200 text-[12px] text-slate-700 hover:bg-slate-50">
|
||||
Stop
|
||||
</button>
|
||||
) : ai.pending > 0 && canWriteAI && !ai.auto ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onWriteAI}
|
||||
title="Charged the same as writing it at send time, and never twice"
|
||||
className="mt-2 h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5"
|
||||
>
|
||||
Write all now
|
||||
<span className="font-normal text-sky-100">about {fmtUsd(ai.estimated_cost_usd)}</span>
|
||||
</button>
|
||||
) : null}
|
||||
</PopoverMenuContent>
|
||||
</PopoverMenu>
|
||||
)}
|
||||
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
{canApproveAll && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onApproveAll}
|
||||
className="h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5 shadow-sm transition-colors"
|
||||
>
|
||||
<CheckIcon className="w-3.5 h-3.5" />
|
||||
Approve all {summary.counts.waiting.toLocaleString()}
|
||||
</button>
|
||||
)}
|
||||
<div
|
||||
className="h-7 pl-2 pr-1 rounded-md inline-flex items-center gap-2 text-[12px] text-slate-600"
|
||||
title={
|
||||
summary.review_leads
|
||||
? "New leads wait here until you approve them. Follow-ups after the first email go out on their own."
|
||||
: "Off: every lead starts on schedule. You can still read and personalize each lead's emails."
|
||||
}
|
||||
>
|
||||
<span className="hidden sm:inline">Approve before sending</span>
|
||||
<Toggle
|
||||
value={summary.review_leads}
|
||||
onChange={onToggleReview}
|
||||
disabled={!canToggle || toggling}
|
||||
ariaLabel="Approve before sending"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Shown on every campaign tab while leads wait for approval, so a review campaign
|
||||
// that looks stalled says why and where to go: the first email's Review tab.
|
||||
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { ClipboardCheckIcon } from "lucide-react";
|
||||
import { useCampaignReview } from "@/lib/api/hooks/app/campaigns/useCampaignReview";
|
||||
|
||||
export default function ReviewWaitingBanner({ campaignId, enabled }: { campaignId: string; enabled: boolean }) {
|
||||
const summary = useCampaignReview(enabled ? campaignId : "");
|
||||
const waiting = enabled ? (summary.data?.counts.waiting ?? 0) : 0;
|
||||
return (
|
||||
<AnimatePresence initial={false}>
|
||||
{waiting > 0 && (
|
||||
<motion.div
|
||||
key="review-waiting"
|
||||
initial={{ opacity: 0, y: -8, height: 0 }}
|
||||
animate={{ opacity: 1, y: 0, height: "auto" }}
|
||||
exit={{ opacity: 0, y: -8, height: 0 }}
|
||||
transition={{ type: "spring", duration: 0.4, bounce: 0.2 }}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<div className="mx-3 sm:mx-5 mb-3 rounded-md border border-sky-200 bg-sky-50/70 px-3.5 py-2.5 flex items-center gap-3">
|
||||
<span className="shrink-0 w-7 h-7 rounded-md bg-sky-100 text-sky-700 inline-flex items-center justify-center">
|
||||
<ClipboardCheckIcon className="w-4 h-4" />
|
||||
</span>
|
||||
<p className="min-w-0 flex-1 text-[12.5px] text-sky-900">
|
||||
{waiting.toLocaleString()} lead{waiting === 1 ? " is" : "s are"} waiting for review. Nothing goes to them until someone approves.
|
||||
</p>
|
||||
<Link
|
||||
to="/app/campaigns/$id/steps"
|
||||
params={{ id: campaignId }}
|
||||
search={{ review: "1" }}
|
||||
className="shrink-0 h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center transition-colors"
|
||||
>
|
||||
Review
|
||||
</Link>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// Styles inside the email preview. Written AI copy carries a soft highlighter
|
||||
// so a reviewer sees what AI wrote; copy being written is a shimmering line
|
||||
// pair; copy just written fades in. Unwritten copy a member cannot write
|
||||
// shows as a quiet labelled slot.
|
||||
export function aiPreviewCss({ writing, justWritten }: { writing: boolean; justWritten: string[] }): string {
|
||||
const fresh = justWritten.map((id) => `[data-ai-block="${CSS.escape(id)}"]`).join(",");
|
||||
return `
|
||||
[data-ai-block] {
|
||||
background: linear-gradient(transparent 58%, rgba(14, 165, 233, 0.13) 58%);
|
||||
border-radius: 2px;
|
||||
box-decoration-break: clone;
|
||||
-webkit-box-decoration-break: clone;
|
||||
}
|
||||
[data-ai-pending] {
|
||||
display: block;
|
||||
position: relative;
|
||||
width: min(100%, 460px);
|
||||
height: 0.75em;
|
||||
margin: 0.5em 0 2em;
|
||||
border-radius: 4px;
|
||||
background: #f1f5f9;
|
||||
}
|
||||
[data-ai-pending]::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 1.3em;
|
||||
width: 62%;
|
||||
height: 100%;
|
||||
border-radius: 4px;
|
||||
background: inherit;
|
||||
}
|
||||
${
|
||||
writing
|
||||
? `
|
||||
[data-ai-pending], [data-ai-pending]::after {
|
||||
background: linear-gradient(90deg, #eef2f7 0%, #eef2f7 35%, #dbeefc 50%, #eef2f7 65%, #eef2f7 100%);
|
||||
background-size: 220% 100%;
|
||||
animation: ai-writing-sweep 1.3s ease-in-out infinite;
|
||||
}
|
||||
`
|
||||
: `
|
||||
[data-ai-pending] {
|
||||
display: inline-block; width: auto; height: auto; padding: 1px 8px; margin: 0;
|
||||
border: 1px dashed #cbd5e1; background: transparent;
|
||||
color: #64748b; font-size: 12px;
|
||||
}
|
||||
[data-ai-pending]::before { content: "AI " attr(data-ai-name); }
|
||||
[data-ai-pending]::after { display: none; }`
|
||||
}
|
||||
${
|
||||
fresh
|
||||
? `
|
||||
${fresh} { animation: ai-reveal 1.1s ease-out both; }`
|
||||
: ""
|
||||
}
|
||||
@keyframes ai-writing-sweep { from { background-position: 160% 0; } to { background-position: -60% 0; } }
|
||||
@keyframes ai-reveal {
|
||||
from { opacity: 0; filter: blur(3px); background-color: rgba(14, 165, 233, 0.22); }
|
||||
60% { opacity: 1; filter: blur(0); }
|
||||
to { background-color: transparent; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-ai-pending], [data-ai-pending]::after, [data-ai-block] { animation: none !important; }
|
||||
}
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
// The Review tab's loading frames and the styles its email preview adds for AI copy.
|
||||
|
||||
import React, { type CSSProperties } from "react";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const RISE = "animate-in fade-in slide-in-from-bottom-1 duration-500 fill-mode-both motion-reduce:animate-none";
|
||||
const rise = (i: number): CSSProperties => ({ animationDelay: `${60 + i * 35}ms` });
|
||||
|
||||
// Fixed widths so the outline reads as real names and never reshuffles.
|
||||
const NAME_WIDTHS = [92, 118, 76, 104, 88, 126, 70, 98, 112, 84];
|
||||
|
||||
function Bar({ className, style }: { className?: string; style?: CSSProperties }) {
|
||||
return <div className={cn("skeleton-sync rounded", className)} style={style} />;
|
||||
}
|
||||
|
||||
export function LeadRowsSkeleton({ rows = 8, offset = 0 }: { rows?: number; offset?: number }) {
|
||||
return (
|
||||
<div role="status" aria-label="Loading leads">
|
||||
{Array.from({ length: rows }, (_, i) => (
|
||||
<div key={i} className={cn("h-10 px-3 flex items-center gap-2.5", RISE)} style={rise(offset + i)}>
|
||||
<Bar className="size-3.5 rounded-[4px]" />
|
||||
<div className="flex-1 min-w-0 flex items-center gap-2">
|
||||
<Bar className="h-3" style={{ width: NAME_WIDTHS[i % NAME_WIDTHS.length] }} />
|
||||
<Bar className="h-2.5" style={{ width: NAME_WIDTHS[(i + 3) % NAME_WIDTHS.length] * 0.7 }} />
|
||||
</div>
|
||||
<Bar className="size-1.5 rounded-full" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmailPaneSkeleton() {
|
||||
return (
|
||||
<div className="h-full flex flex-col" role="status" aria-label="Loading emails">
|
||||
<div className="shrink-0 h-12 border-b border-slate-200">
|
||||
<div className={cn("h-full px-5 flex items-center gap-2.5", RISE)} style={rise(0)}>
|
||||
<Bar className="h-3.5 w-32" />
|
||||
<Bar className="h-2.5 w-48" />
|
||||
<Bar className="ml-auto h-7 w-24 rounded-md" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="shrink-0 h-9 border-b border-slate-200">
|
||||
<div className={cn("h-full px-5 flex items-center gap-4", RISE)} style={rise(1)}>
|
||||
<Bar className="h-3 w-14" />
|
||||
<Bar className="h-3 w-20" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 overflow-hidden">
|
||||
<div className="max-w-[820px] px-5 py-3">
|
||||
<div className={cn("rounded-lg border border-slate-200 overflow-hidden", RISE)} style={rise(2)}>
|
||||
<div className="px-5 py-3.5 border-b border-slate-100 space-y-2.5">
|
||||
<Bar className="h-2.5 w-64" />
|
||||
<Bar className="h-2.5 w-48" />
|
||||
<Bar className="h-3 w-80 max-w-full" />
|
||||
</div>
|
||||
<div className="px-5 py-5 space-y-3">
|
||||
{[38, 92, 84, 96, 60, 28].map((w, i) => (
|
||||
<Bar key={i} className={cn("h-3", RISE)} style={{ width: `${w}%`, ...rise(3 + i) }} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReviewSkeleton() {
|
||||
return (
|
||||
<div className={cn("h-full overflow-hidden flex flex-col", RISE)} role="status" aria-label="Loading">
|
||||
<div className="shrink-0 px-3 py-2 flex items-center gap-2 border-b border-slate-200 bg-slate-50/50">
|
||||
<Bar className="h-7 w-28 rounded-md" />
|
||||
<Bar className="h-7 w-32 rounded-md" />
|
||||
<Bar className="ml-auto h-[18px] w-40 rounded-full" />
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 flex">
|
||||
<div className="w-full md:w-[270px] lg:w-[290px] shrink-0 md:border-r border-slate-200">
|
||||
<div className="px-3 py-2 flex items-center gap-2 border-b border-slate-200">
|
||||
<Bar className="size-3.5 rounded-[4px]" />
|
||||
<Bar className="h-7 flex-1 rounded-md" />
|
||||
<Bar className="h-7 w-20 rounded-md" />
|
||||
</div>
|
||||
<LeadRowsSkeleton rows={12} offset={1} />
|
||||
</div>
|
||||
<div className="hidden md:block flex-1 min-w-0">
|
||||
<EmailPaneSkeleton />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// The dot grid a running campaign shows, for work in progress on this tab.
|
||||
export function RunningGrid({ className }: { className?: string }) {
|
||||
return <span className={cn("campaign-grid shrink-0", className)} aria-hidden />;
|
||||
}
|
||||
|
||||
// The running grid with a label that steps through what is happening.
|
||||
export function RunningLabel({ labels, className }: { labels: string[]; className?: string }) {
|
||||
const [stage, setStage] = React.useState(0);
|
||||
React.useEffect(() => {
|
||||
if (labels.length < 2) return;
|
||||
const t = setInterval(() => setStage((s) => Math.min(s + 1, labels.length - 1)), 1500);
|
||||
return () => clearInterval(t);
|
||||
}, [labels.length]);
|
||||
const label = labels[Math.min(stage, labels.length - 1)];
|
||||
return (
|
||||
<span role="status" className={cn("h-8 pl-3 pr-3.5 rounded-full border border-sky-200 bg-sky-50 inline-flex items-center gap-2 text-sky-600", className)}>
|
||||
<RunningGrid />
|
||||
<AnimatePresence mode="wait" initial={false}>
|
||||
<motion.span
|
||||
key={label}
|
||||
initial={{ opacity: 0, y: 3 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -3 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
className="text-shimmer whitespace-nowrap text-[12px] font-medium text-sky-800"
|
||||
>
|
||||
{label}
|
||||
</motion.span>
|
||||
</AnimatePresence>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { CampaignReviewSummary, ReviewStatus } from "@/lib/api/models/app/campaigns/Review";
|
||||
|
||||
export const STATUS_PILL: Record<ReviewStatus, { label: string; className: string; dot: string }> = {
|
||||
waiting: { label: "Waiting", className: "bg-amber-50 text-amber-700 border-amber-200", dot: "bg-amber-500" },
|
||||
ready: { label: "Ready", className: "bg-sky-50 text-sky-700 border-sky-200", dot: "bg-sky-500" },
|
||||
held: { label: "Paused", className: "bg-violet-50 text-violet-700 border-violet-200", dot: "bg-violet-500" },
|
||||
started: { label: "Started", className: "bg-slate-100 text-slate-600 border-slate-200", dot: "bg-slate-300" },
|
||||
};
|
||||
|
||||
// How many leads a list filter holds.
|
||||
export const filterCount = (counts: CampaignReviewSummary["counts"], f: "all" | ReviewStatus) => (f === "all" ? counts.total : counts[f]);
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import toast from "react-hot-toast/headless";
|
||||
import { useWriteReviewAIPass, refreshReview } from "@/lib/api/hooks/app/campaigns/useCampaignReview";
|
||||
import type { AppError } from "@/lib/api/client/normalizeError";
|
||||
import buildError from "@/lib/helper/buildError";
|
||||
|
||||
export interface BulkAIProgress {
|
||||
written: number;
|
||||
failed: number;
|
||||
remaining: number;
|
||||
}
|
||||
|
||||
// Writes AI copy ahead in server-sized passes until nothing is left, the
|
||||
// balance runs out, or the member stops it. Each pass hands back a cursor past
|
||||
// the leads it tried, so a lead that keeps failing cannot stall the run.
|
||||
export function useBulkAIWrite(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
const pass = useWriteReviewAIPass(campaignId);
|
||||
const [progress, setProgress] = useState<BulkAIProgress | null>(null);
|
||||
const stopRef = useRef(false);
|
||||
|
||||
const run = useCallback(
|
||||
async (body: { contact_ids?: string[]; waiting_only?: boolean; step_id?: string }) => {
|
||||
stopRef.current = false;
|
||||
const total: BulkAIProgress = { written: 0, failed: 0, remaining: 0 };
|
||||
setProgress({ ...total });
|
||||
let after: string | undefined;
|
||||
try {
|
||||
for (;;) {
|
||||
const res = await pass.mutateAsync({ ...body, after });
|
||||
after = res.next || after;
|
||||
total.written += res.written;
|
||||
total.failed += res.failed;
|
||||
total.remaining = res.remaining;
|
||||
setProgress({ ...total });
|
||||
if (res.stopped === "insufficient_credits") {
|
||||
toast.error("The balance ran out. What was written is saved; add money under Billing to write the rest.");
|
||||
break;
|
||||
}
|
||||
if (res.stopped === "usage_cap_exceeded") {
|
||||
toast.error("The workspace reached its AI spend limit. What was written is saved.");
|
||||
break;
|
||||
}
|
||||
if (stopRef.current || res.remaining === 0 || res.written + res.failed === 0) break;
|
||||
}
|
||||
if (total.failed > 0) {
|
||||
toast.error(`${total.failed.toLocaleString()} could not be written. They are written when they send instead.`);
|
||||
} else if (total.written > 0) {
|
||||
toast.success(`AI copy written for ${total.written.toLocaleString()} lead${total.written === 1 ? "" : "s"}`);
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error(buildError(err as AppError));
|
||||
} finally {
|
||||
setProgress(null);
|
||||
refreshReview(qc, campaignId);
|
||||
void qc.invalidateQueries({ queryKey: ["subscription", "credits"] });
|
||||
}
|
||||
},
|
||||
[pass, qc, campaignId],
|
||||
);
|
||||
|
||||
const stop = useCallback(() => {
|
||||
stopRef.current = true;
|
||||
}, []);
|
||||
|
||||
return { run, stop, progress, running: progress !== null };
|
||||
}
|
||||
@@ -7,8 +7,10 @@
|
||||
// is made.
|
||||
|
||||
import React from "react";
|
||||
import { AnimatePresence } from "framer-motion";
|
||||
import { ArrowDownIcon, ArrowUpIcon, FlagIcon, GitBranchIcon, PlusIcon, Trash2Icon } from "lucide-react";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { ArrowDownIcon, ArrowUpIcon, ClipboardCheckIcon, FlagIcon, GitBranchIcon, MailIcon, PlusIcon, Trash2Icon } from "lucide-react";
|
||||
import { useNavigate, useSearch } from "@tanstack/react-router";
|
||||
import type { SearchParams } from "@/lib/routerSearch";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import toast from "react-hot-toast/headless";
|
||||
import type Sequence from "@/lib/api/models/app/campaigns/sequences/Sequence";
|
||||
@@ -43,6 +45,8 @@ import { DirtyContext, useDirtyRegistry } from "@/components/app/flow/dirty";
|
||||
import { layoutFlow, type InsertPoint, type PlacedEdge } from "@/components/app/flow/tree";
|
||||
import { cn } from "@/lib/utils";
|
||||
import StepEmailArms from "./StepEmailArms";
|
||||
|
||||
const CampaignReviewView = React.lazy(() => import("@/components/app/campaigns/review/CampaignReviewView"));
|
||||
import { conversationOpenerFor, conversationSubjectFor, earlierEmailsFor } from "./threading";
|
||||
import { ActionEditor, NodeTypeSwitcher, PathEditor, ReplyStopWarning, StopOnReplyToggle } from "./CampaignEditors";
|
||||
import { defaultActionFor } from "./campaignActions";
|
||||
@@ -77,7 +81,7 @@ const SEQ_KEY = (id: string) => ["campaigns", id, "sequences"] as const;
|
||||
const POSITIVE_REPLY_FIELDS = ["replied", "reply_positive", "reply_negative", "reply_neutral", "reply_automated"];
|
||||
|
||||
// A path with a draft is a new condition not saved yet.
|
||||
type Selection = { kind: "entry" } | { kind: "step"; id: string } | { kind: "path"; stepId: string; port: string; draft?: SequenceBranch } | null;
|
||||
type Selection = { kind: "entry" } | { kind: "review" } | { kind: "step"; id: string } | { kind: "path"; stepId: string; port: string; draft?: SequenceBranch } | null;
|
||||
type Choice = "email" | "router" | SequenceActionType;
|
||||
|
||||
const sizeOf = (id: string) => (isStopId(id) ? { w: TERMINAL_W, h: TERMINAL_H } : { w: STEP_W, h: STEP_H });
|
||||
@@ -128,6 +132,34 @@ export default function CampaignFlow({ campaignId }: { campaignId: string }) {
|
||||
[confirm, dirty],
|
||||
);
|
||||
|
||||
// A link (?review=1, optionally &step= and &lead=) opens an email step on its Review tab, then leaves the URL.
|
||||
const navigate = useNavigate();
|
||||
const search = useSearch({ strict: false }) as SearchParams;
|
||||
const [review, setReview] = React.useState<{ stepId: string; lead?: string; at: number } | null>(null);
|
||||
const applied = React.useRef("");
|
||||
React.useEffect(() => {
|
||||
if (search.review !== "1") {
|
||||
applied.current = "";
|
||||
return;
|
||||
}
|
||||
// Once per link: steps refetch after every save, and that must not pull the panel back.
|
||||
const key = `${search.step ?? ""}|${search.lead ?? ""}`;
|
||||
if (!sequences || applied.current === key) return;
|
||||
applied.current = key;
|
||||
// Steps come in send order, so the first email step is the opening email.
|
||||
const emails = steps.filter((s) => s.kind === "email");
|
||||
const target = emails.find((s) => s.id === search.step) ?? emails[0];
|
||||
if (target) {
|
||||
select({ kind: "step", id: target.id });
|
||||
setReview({ stepId: target.id, lead: search.lead, at: Date.now() });
|
||||
} else {
|
||||
// Leads can wait for approval with no email step left, and still need a way out.
|
||||
select({ kind: "review" });
|
||||
setReview({ stepId: "", lead: search.lead, at: Date.now() });
|
||||
}
|
||||
void navigate({ to: "/app/campaigns/$id/steps", params: { id: campaignId }, search: {}, replace: true });
|
||||
}, [search.review, search.step, search.lead, sequences, steps, select, navigate, campaignId]);
|
||||
|
||||
// ── Derived ──────────────────────────────────────────────────────────────
|
||||
const byId = React.useMemo(() => new Map(steps.map((s) => [s.id, s])), [steps]);
|
||||
const indexOf = React.useMemo(() => new Map(steps.map((s, i) => [s.id, i])), [steps]);
|
||||
@@ -322,7 +354,7 @@ export default function CampaignFlow({ campaignId }: { campaignId: string }) {
|
||||
await deleteSequence.mutateAsync(id);
|
||||
// Only the panel of the step being deleted loses its unsaved edits.
|
||||
const cur = selectionRef.current;
|
||||
if (cur && cur.kind !== "entry" && (cur.kind === "step" ? cur.id : cur.stepId) === id) {
|
||||
if (cur && (cur.kind === "step" || cur.kind === "path") && (cur.kind === "step" ? cur.id : cur.stepId) === id) {
|
||||
dirty.clear();
|
||||
setSelection(null);
|
||||
}
|
||||
@@ -515,6 +547,13 @@ export default function CampaignFlow({ campaignId }: { campaignId: string }) {
|
||||
</div>
|
||||
</FlowPanel>
|
||||
)}
|
||||
{selection?.kind === "review" && (
|
||||
<FlowPanel key="review" icon={<ClipboardCheckIcon />} tone="sky" kicker="Review" title="Leads waiting for review" onClose={() => select(null)} xwide fill>
|
||||
<React.Suspense fallback={null}>
|
||||
<CampaignReviewView key={review?.at ?? 0} campaignId={campaignId} initialLead={review?.lead} />
|
||||
</React.Suspense>
|
||||
</FlowPanel>
|
||||
)}
|
||||
{panelStep && (
|
||||
<StepPanel
|
||||
key={panelStep.id}
|
||||
@@ -532,6 +571,7 @@ export default function CampaignFlow({ campaignId }: { campaignId: string }) {
|
||||
const draft = draftCondition(DEFAULT_CONDITION);
|
||||
select({ kind: "path", stepId: panelStep.id, port: `b:${draft.branch_id}`, draft });
|
||||
}}
|
||||
review={review?.stepId === panelStep.id ? review : null}
|
||||
/>
|
||||
)}
|
||||
{pathStep && selection?.kind === "path" && (
|
||||
@@ -628,6 +668,7 @@ function StepPanel({
|
||||
onDelete,
|
||||
onSelectPath,
|
||||
onAddCondition,
|
||||
review,
|
||||
}: {
|
||||
campaignId: string;
|
||||
step: Sequence;
|
||||
@@ -640,7 +681,17 @@ function StepPanel({
|
||||
onDelete: () => void;
|
||||
onSelectPath: (port: string) => void;
|
||||
onAddCondition: () => void;
|
||||
// Set when a link asked for this step's Review tab, with the lead to open.
|
||||
review?: { lead?: string; at: number } | null;
|
||||
}) {
|
||||
const [tab, setTab] = React.useState<"email" | "review">(review ? "review" : "email");
|
||||
React.useEffect(() => {
|
||||
if (review) setTab("review");
|
||||
}, [review]);
|
||||
// A step switched to another type, here or by a teammate, comes back as an email on its Email tab.
|
||||
React.useEffect(() => {
|
||||
if (step.kind !== "email") setTab("email");
|
||||
}, [step.kind]);
|
||||
// Parses earlier bodies; kept stable so the editor's AI context is too.
|
||||
const earlierEmails = React.useMemo(() => earlierEmailsFor(steps, index), [steps, index]);
|
||||
const footer = canEdit ? (
|
||||
@@ -684,23 +735,78 @@ function StepPanel({
|
||||
</FlowPanel>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<FlowPanel readOnly={!canEdit} icon={view.icon} tone={view.tone} kicker={view.kicker} title={view.title} onClose={onClose} footer={footer} wide={step.kind === "email"}>
|
||||
<div className="p-3">
|
||||
<NodeTypeSwitcher campaignId={campaignId} sequence={step} onChanged={onChanged} />
|
||||
{step.kind === "email" ? (
|
||||
<StepEmailArms
|
||||
campaignId={campaignId}
|
||||
sequence={step}
|
||||
index={index}
|
||||
conversationSubject={conversationSubjectFor(steps, index)}
|
||||
conversationOpener={conversationOpenerFor(steps, index)}
|
||||
earlierEmails={earlierEmails}
|
||||
/>
|
||||
) : (
|
||||
if (step.kind !== "email") {
|
||||
return (
|
||||
<FlowPanel readOnly={!canEdit} icon={view.icon} tone={view.tone} kicker={view.kicker} title={view.title} onClose={onClose} footer={footer}>
|
||||
<div className="p-3">
|
||||
<NodeTypeSwitcher campaignId={campaignId} sequence={step} onChanged={onChanged} />
|
||||
<ActionEditor campaignId={campaignId} sequence={step} onSaved={onChanged} />
|
||||
)}
|
||||
</div>
|
||||
</FlowPanel>
|
||||
);
|
||||
}
|
||||
const tabs = (
|
||||
<div className="shrink-0 flex items-center gap-1 border-b border-slate-200 px-3" role="tablist" aria-label="Step">
|
||||
{(
|
||||
[
|
||||
{ key: "email", label: "Email", icon: MailIcon },
|
||||
{ key: "review", label: "Review", icon: ClipboardCheckIcon },
|
||||
] as const
|
||||
).map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === t.key}
|
||||
onClick={() => setTab(t.key)}
|
||||
title={t.key === "review" ? "Read this email as each lead gets it, and approve leads" : undefined}
|
||||
className={cn(
|
||||
"relative inline-flex h-10 items-center gap-1.5 px-2.5 text-[12.5px] transition-colors",
|
||||
tab === t.key ? "font-medium text-slate-900" : "text-slate-500 hover:text-slate-800",
|
||||
)}
|
||||
>
|
||||
<t.icon className="h-3.5 w-3.5" />
|
||||
{t.label}
|
||||
{tab === t.key && <motion.span layoutId={`step-tab-${step.id}`} className="absolute inset-x-1 -bottom-px h-0.5 rounded-full bg-sky-600" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<FlowPanel
|
||||
readOnly={!canEdit}
|
||||
icon={view.icon}
|
||||
tone={view.tone}
|
||||
kicker={view.kicker}
|
||||
title={view.title}
|
||||
onClose={onClose}
|
||||
tabs={tabs}
|
||||
footer={tab === "email" ? footer : undefined}
|
||||
wide={tab === "email"}
|
||||
xwide={tab === "review"}
|
||||
fill
|
||||
>
|
||||
{/* The editor stays mounted on the Review tab, so unsaved edits survive the switch. */}
|
||||
<div className={cn("h-full overflow-y-auto", tab !== "email" && "hidden")}>
|
||||
<fieldset disabled={!canEdit} className="contents">
|
||||
<div className="p-3">
|
||||
<NodeTypeSwitcher campaignId={campaignId} sequence={step} onChanged={onChanged} />
|
||||
<StepEmailArms
|
||||
campaignId={campaignId}
|
||||
sequence={step}
|
||||
index={index}
|
||||
conversationSubject={conversationSubjectFor(steps, index)}
|
||||
conversationOpener={conversationOpenerFor(steps, index)}
|
||||
earlierEmails={earlierEmails}
|
||||
/>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
{tab === "review" && (
|
||||
<React.Suspense fallback={null}>
|
||||
<CampaignReviewView key={review?.at ?? 0} campaignId={campaignId} stepId={step.id} initialLead={review?.lead} />
|
||||
</React.Suspense>
|
||||
)}
|
||||
</FlowPanel>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,10 @@ import type { TemplatePreview } from "@/lib/api/client/app/campaigns/previewTemp
|
||||
import type Contact from "@/lib/api/models/app/contacts/Contact";
|
||||
import type Inbox from "@/lib/api/models/app/emails/Inbox";
|
||||
import formatBytes from "@/lib/helper/formatBytes";
|
||||
import { PlacementTestButton, PreviewContactPicker, PreviewMailboxPicker, SendTestButton } from "./PreviewControls";
|
||||
import { PlacementTestButton, PreviewContactPicker, PreviewLeadStepper, PreviewMailboxPicker, SendTestButton } from "./PreviewControls";
|
||||
import PreviewLeadNotes from "./PreviewLeadNotes";
|
||||
import { usePreviewLeadAI } from "./usePreviewLeadAI";
|
||||
import { aiPreviewCss } from "../review/aiPreviewCss";
|
||||
import { SAMPLE_CONTACT_LABEL, contactLabel, useCampaignSenderInboxes } from "./previewContext";
|
||||
import { Label, TextInput } from "@/components/ui/field";
|
||||
import {
|
||||
@@ -165,6 +168,8 @@ export default function EmailContentEditor({
|
||||
// must read. The step's own stored subject is not what gets sent.
|
||||
const shownSubject = subjectLocked ? subjectLocked.subject : subject;
|
||||
|
||||
// Bumped after AI copy is written, so the preview renders it.
|
||||
const [rendered, setRendered] = React.useState(0);
|
||||
const previewMut = useTemplatePreview();
|
||||
const runPreview = previewMut.mutateAsync;
|
||||
React.useEffect(() => {
|
||||
@@ -202,7 +207,25 @@ export default function EmailContentEditor({
|
||||
clearTimeout(t);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tab, code, shownSubject, bodyHtml, previewContact?.id, campaignId, previewMailbox?.id, stepId]);
|
||||
}, [tab, code, shownSubject, bodyHtml, previewContact?.id, campaignId, previewMailbox?.id, stepId, rendered]);
|
||||
|
||||
// The preview sits low in a step's panel, so opening it brings the email into view.
|
||||
const previewRef = React.useRef<HTMLDivElement>(null);
|
||||
React.useEffect(() => {
|
||||
if (tab === "preview") previewRef.current?.scrollIntoView({ block: "start", behavior: "smooth" });
|
||||
}, [tab]);
|
||||
|
||||
// Only the step's own copy previews lead by lead; an A/B arm or a lead's own copy is not what every lead gets.
|
||||
const leadPreview = !!campaignId && !!stepId && !!canSendTest;
|
||||
const rerender = React.useCallback(() => setRendered((n) => n + 1), []);
|
||||
const leadAI = usePreviewLeadAI({
|
||||
campaignId,
|
||||
stepId,
|
||||
contactId: previewContact?.id,
|
||||
preview: serverPreview,
|
||||
enabled: leadPreview && tab === "preview" && !dirty,
|
||||
onWritten: rerender,
|
||||
});
|
||||
|
||||
const bodyPlain = htmlToPlain(bodyHtml);
|
||||
const aiContext = React.useMemo(
|
||||
@@ -463,11 +486,12 @@ export default function EmailContentEditor({
|
||||
<HtmlFindings findings={serverPreview?.html_findings ?? []} />
|
||||
</>
|
||||
) : (
|
||||
<div className="rounded-md border border-slate-200 bg-white">
|
||||
<div ref={previewRef} className="scroll-mt-3 rounded-md border border-slate-200 bg-white">
|
||||
{campaignId && (
|
||||
<div className="flex flex-wrap items-center gap-1.5 border-b border-slate-200/70 px-2 py-1.5">
|
||||
<span className="px-1 text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium">Preview as</span>
|
||||
<PreviewContactPicker campaignId={campaignId} value={previewContact} onChange={setPreviewContact} />
|
||||
{leadPreview && <PreviewLeadStepper campaignId={campaignId} value={previewContact} onChange={setPreviewContact} />}
|
||||
<PreviewMailboxPicker inboxes={senders.inboxes} value={previewMailbox} onChange={setPreviewMailbox} />
|
||||
{stepId && canSendTest && (
|
||||
<div className="ml-auto flex flex-wrap items-center gap-1.5">
|
||||
@@ -483,6 +507,9 @@ export default function EmailContentEditor({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{leadPreview && (
|
||||
<PreviewLeadNotes campaignId={campaignId!} stepId={stepId!} contact={previewContact} preview={serverPreview} dirty={dirty} ai={leadAI} />
|
||||
)}
|
||||
{serverPreview?.from && (
|
||||
<div className="border-b border-slate-200/70 px-3 py-2 text-[12.5px]">
|
||||
<span className="text-slate-400">From: </span>
|
||||
@@ -507,6 +534,7 @@ export default function EmailContentEditor({
|
||||
<EmailBody
|
||||
html={serverPreview?.body_html ?? linkifyUnsubscribe(renderPreview(bodyHtml))}
|
||||
plain={serverPreview?.body_plain}
|
||||
extraCss={aiPreviewCss({ writing: leadAI.state === "writing", justWritten: leadAI.fresh })}
|
||||
/>
|
||||
</div>
|
||||
{(serverPreview?.attachments?.length ?? 0) > 0 && (
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// variants so every arm previews against the same lead and sender.
|
||||
|
||||
import React from "react";
|
||||
import { Loader2Icon, MailCheckIcon, MailIcon, SendIcon, UserRoundIcon } from "lucide-react";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, Loader2Icon, MailCheckIcon, MailIcon, SendIcon, UserRoundIcon } from "lucide-react";
|
||||
import toast from "react-hot-toast/headless";
|
||||
import type Contact from "@/lib/api/models/app/contacts/Contact";
|
||||
import type Inbox from "@/lib/api/models/app/emails/Inbox";
|
||||
@@ -59,7 +59,14 @@ export function PreviewContactPicker({
|
||||
const contacts = search.contacts ?? [];
|
||||
|
||||
return (
|
||||
<PopoverMenu open={open} onOpenChange={setOpen}>
|
||||
<PopoverMenu
|
||||
open={open}
|
||||
onOpenChange={(o) => {
|
||||
setOpen(o);
|
||||
// Each open starts a fresh search.
|
||||
if (!o) setQuery("");
|
||||
}}
|
||||
>
|
||||
<PopoverMenuTrigger asChild>
|
||||
<SelectButton
|
||||
icon={<UserRoundIcon className="w-3.5 h-3.5" />}
|
||||
@@ -103,6 +110,47 @@ export function PreviewContactPicker({
|
||||
);
|
||||
}
|
||||
|
||||
// Steps the preview through the campaign's leads, in the picker's order.
|
||||
export function PreviewLeadStepper({
|
||||
campaignId,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
campaignId: string;
|
||||
value: Contact | null;
|
||||
onChange: (c: Contact) => void;
|
||||
}) {
|
||||
const list = useSearchContacts({
|
||||
options: { query: "", custom_field_filters: [], campaign_ids: [campaignId], sort_by: "updated_at", reverse: false },
|
||||
limit: 50,
|
||||
keepPrevious: true,
|
||||
});
|
||||
const leads = list.contacts ?? [];
|
||||
const at = value ? leads.findIndex((c) => c.id === value.id) : -1;
|
||||
const { hasNextPage, isFetchingNextPage, fetchNextPage } = list;
|
||||
const lastLoaded = at >= 0 && at === leads.length - 1;
|
||||
// Load the next page as the last loaded lead opens, so Next keeps going.
|
||||
React.useEffect(() => {
|
||||
if (lastLoaded && hasNextPage && !isFetchingNextPage) void fetchNextPage();
|
||||
}, [lastLoaded, hasNextPage, isFetchingNextPage, fetchNextPage]);
|
||||
if (leads.length === 0) return null;
|
||||
|
||||
const prev = at > 0 ? leads[at - 1] : null;
|
||||
const next = at < 0 ? leads[0] : (leads[at + 1] ?? null);
|
||||
const btn =
|
||||
"h-7 w-7 inline-flex items-center justify-center rounded-md border border-slate-200 bg-white text-slate-500 transition-colors hover:border-slate-300 hover:text-slate-800 disabled:opacity-40 disabled:pointer-events-none";
|
||||
return (
|
||||
<div className="inline-flex items-center gap-0.5">
|
||||
<button type="button" className={btn} disabled={!prev} onClick={() => prev && onChange(prev)} title="Previous lead" aria-label="Previous lead">
|
||||
<ChevronLeftIcon className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<button type="button" className={btn} disabled={!next} onClick={() => next && onChange(next)} title="Next lead" aria-label="Next lead">
|
||||
<ChevronRightIcon className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PreviewMailboxPicker({
|
||||
inboxes,
|
||||
value,
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { ArrowRightIcon, SparklesIcon, UserPenIcon } from "lucide-react";
|
||||
import type Contact from "@/lib/api/models/app/contacts/Contact";
|
||||
import type { TemplatePreview } from "@/lib/api/client/app/campaigns/previewTemplate";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { PreviewAIState } from "./usePreviewLeadAI";
|
||||
|
||||
function Note({ tone, icon: Icon, children }: { tone: "sky" | "amber" | "slate" | "rose"; icon: React.ElementType; children: React.ReactNode }) {
|
||||
const tones = {
|
||||
sky: "bg-sky-50/70 text-sky-800",
|
||||
amber: "bg-amber-50 text-amber-800",
|
||||
slate: "bg-slate-50 text-slate-600",
|
||||
rose: "bg-rose-50 text-rose-800",
|
||||
};
|
||||
return (
|
||||
<div className={cn("flex items-start gap-1.5 border-b border-slate-200/70 px-3 py-1.5 text-[11.5px] leading-relaxed", tones[tone])}>
|
||||
<Icon className="mt-[3px] w-3 h-3 shrink-0" />
|
||||
<div className="min-w-0 flex-1">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// What the step preview cannot show on its own: a lead's own copy, and AI copy
|
||||
// that is written per lead.
|
||||
export default function PreviewLeadNotes({
|
||||
campaignId,
|
||||
stepId,
|
||||
contact,
|
||||
preview,
|
||||
dirty,
|
||||
ai,
|
||||
}: {
|
||||
campaignId: string;
|
||||
stepId: string;
|
||||
contact: Contact | null;
|
||||
preview: TemplatePreview | null;
|
||||
dirty?: boolean;
|
||||
ai: { state?: PreviewAIState; pending: { id: string; name: string }[]; canWrite: boolean; write: () => void };
|
||||
}) {
|
||||
if (!preview) return null;
|
||||
const first = contact?.first_name?.trim() || "This lead";
|
||||
const blocks = preview.ai_blocks ?? [];
|
||||
const review = contact && (
|
||||
<Link
|
||||
to="/app/campaigns/$id/steps"
|
||||
params={{ id: campaignId }}
|
||||
search={{ review: "1", step: stepId, lead: contact.id }}
|
||||
className="ml-1 inline-flex items-center gap-0.5 font-medium underline-offset-2 hover:underline"
|
||||
>
|
||||
Open on the Review tab <ArrowRightIcon className="w-3 h-3" />
|
||||
</Link>
|
||||
);
|
||||
|
||||
if (contact && preview.personalized) {
|
||||
return (
|
||||
<Note tone="amber" icon={UserPenIcon}>
|
||||
{first} has their own copy of this email, so they get that instead of this one.{review}
|
||||
</Note>
|
||||
);
|
||||
}
|
||||
if (blocks.length === 0) return null;
|
||||
if (!contact) {
|
||||
return (
|
||||
<Note tone="slate" icon={SparklesIcon}>
|
||||
AI writes the marked part for each lead. Pick a lead above to see theirs.
|
||||
</Note>
|
||||
);
|
||||
}
|
||||
if (!preview.lead) {
|
||||
return (
|
||||
<Note tone="slate" icon={SparklesIcon}>
|
||||
AI copy is written only for this campaign's leads, so the marked part stays empty here.
|
||||
</Note>
|
||||
);
|
||||
}
|
||||
if (ai.pending.length === 0) {
|
||||
return (
|
||||
<Note tone="sky" icon={SparklesIcon}>
|
||||
The highlighted part is what AI wrote for {first}.{review}
|
||||
</Note>
|
||||
);
|
||||
}
|
||||
if (ai.state === "writing") {
|
||||
return (
|
||||
<Note tone="sky" icon={SparklesIcon}>
|
||||
<span className="text-shimmer">AI is writing the marked part for {first}…</span>
|
||||
</Note>
|
||||
);
|
||||
}
|
||||
if (ai.state === "balance") {
|
||||
return (
|
||||
<Note tone="amber" icon={SparklesIcon}>
|
||||
The AI balance is used up, so the marked part is written when the email sends, once there is balance.
|
||||
</Note>
|
||||
);
|
||||
}
|
||||
if (ai.state === "cap") {
|
||||
return (
|
||||
<Note tone="amber" icon={SparklesIcon}>
|
||||
The workspace reached its AI spend limit, so the marked part is written when the email sends.
|
||||
</Note>
|
||||
);
|
||||
}
|
||||
if (ai.state === "unavailable") {
|
||||
return (
|
||||
<Note tone="slate" icon={SparklesIcon}>
|
||||
This instance has no AI provider set up, so the marked part cannot be written.
|
||||
</Note>
|
||||
);
|
||||
}
|
||||
if (ai.state === "error") {
|
||||
return (
|
||||
<Note tone="rose" icon={SparklesIcon}>
|
||||
The marked part could not be written for {first} just now.{" "}
|
||||
<button type="button" onClick={ai.write} className="font-medium underline underline-offset-2">
|
||||
Try again
|
||||
</button>
|
||||
</Note>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Note tone="slate" icon={SparklesIcon}>
|
||||
{dirty
|
||||
? `Save the step to see what AI writes for ${first}.`
|
||||
: ai.canWrite
|
||||
? `AI writes the marked part for ${first} before this email sends.`
|
||||
: `AI writes the marked part for ${first} when the email sends.`}
|
||||
</Note>
|
||||
);
|
||||
}
|
||||
@@ -32,7 +32,8 @@ vi.mock("./RichTextEditor", () => ({
|
||||
vi.mock("./StepAttachments", () => ({ default: () => null }));
|
||||
vi.mock("@/components/ui/scroll-strip", () => ({ default: ({ children }: { children: React.ReactNode }) => <div>{children}</div> }));
|
||||
vi.mock("../ContentScore", () => ({ default: () => null }));
|
||||
vi.mock("./PreviewControls", () => ({ PlacementTestButton: () => null, PreviewContactPicker: () => null, PreviewMailboxPicker: () => null, SendTestButton: () => null }));
|
||||
vi.mock("./PreviewControls", () => ({ PlacementTestButton: () => null, PreviewContactPicker: () => null, PreviewLeadStepper: () => null, PreviewMailboxPicker: () => null, SendTestButton: () => null }));
|
||||
vi.mock("./usePreviewLeadAI", () => ({ usePreviewLeadAI: () => ({ pending: [], fresh: [], canWrite: false, write: vi.fn() }) }));
|
||||
vi.mock("./EmailAIWriter", () => ({ WriteEmailWithAI: () => null, SubjectAI: () => null }));
|
||||
vi.mock("@/lib/api/hooks/app/emails/useEmails", () => ({ default: () => ({ emails: [] }) }));
|
||||
vi.mock("./useEmailAIWriter", () => ({ useEmailAIWriter: () => ({ phase: "idle", busyLabels: [] }) }));
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import React from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { writeLeadAIOnce } from "@/lib/api/hooks/app/campaigns/useCampaignReview";
|
||||
import type { TemplatePreview } from "@/lib/api/client/app/campaigns/previewTemplate";
|
||||
import type { AppError } from "@/lib/api/client/normalizeError";
|
||||
import { usePermission } from "@/hooks/usePermission";
|
||||
|
||||
export type PreviewAIState = "writing" | "balance" | "cap" | "unavailable" | "error";
|
||||
|
||||
// Writes the previewed lead's AI copy for a saved step as the preview opens on
|
||||
// them, as the Review tab does, so the preview shows what they will get.
|
||||
export function usePreviewLeadAI({
|
||||
campaignId,
|
||||
stepId,
|
||||
contactId,
|
||||
preview,
|
||||
enabled,
|
||||
onWritten,
|
||||
}: {
|
||||
campaignId?: string;
|
||||
stepId?: string;
|
||||
contactId?: string;
|
||||
preview: TemplatePreview | null;
|
||||
// Off while the step has unsaved edits: the write reads the saved step.
|
||||
enabled: boolean;
|
||||
onWritten: () => void;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const canAI = usePermission("USE_AI");
|
||||
const canEdit = usePermission("MANAGE_CAMPAIGNS");
|
||||
const canWrite = canAI && canEdit;
|
||||
const [state, setState] = React.useState<PreviewAIState | undefined>();
|
||||
const [fresh, setFresh] = React.useState<string[]>([]);
|
||||
const attempted = React.useRef(new Set<string>());
|
||||
|
||||
const key = campaignId && stepId && contactId ? `${contactId}:${stepId}` : "";
|
||||
React.useEffect(() => {
|
||||
setState(undefined);
|
||||
setFresh([]);
|
||||
}, [key]);
|
||||
|
||||
const pending = preview?.lead ? (preview.ai_blocks ?? []).filter((b) => !b.written) : [];
|
||||
const blockIds = (preview?.ai_blocks ?? []).map((b) => b.id).join(",");
|
||||
|
||||
const write = React.useCallback(async () => {
|
||||
if (!campaignId || !stepId || !contactId) return;
|
||||
setState("writing");
|
||||
try {
|
||||
await writeLeadAIOnce(qc, campaignId, contactId, stepId);
|
||||
setFresh(blockIds ? blockIds.split(",") : []);
|
||||
setState(undefined);
|
||||
onWritten();
|
||||
} catch (err) {
|
||||
const code = (err as AppError).code;
|
||||
setState(code === "insufficient_credits" ? "balance" : code === "usage_cap_exceeded" ? "cap" : code === "ai_unavailable" ? "unavailable" : "error");
|
||||
}
|
||||
}, [qc, campaignId, stepId, contactId, blockIds, onWritten]);
|
||||
|
||||
const pendingKey = pending.map((b) => b.id).join(",");
|
||||
React.useEffect(() => {
|
||||
if (!enabled || !key || !pendingKey || !canWrite || preview?.personalized) return;
|
||||
// Once per lead and step, so a block the write cannot fill is not retried in a loop.
|
||||
if (attempted.current.has(key)) return;
|
||||
attempted.current.add(key);
|
||||
void write();
|
||||
}, [enabled, key, pendingKey, canWrite, preview?.personalized, write]);
|
||||
|
||||
return { state, fresh, pending, canWrite, write };
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
// parent passes `current_campaign` and the topbar collapses to a
|
||||
// section header so it nests cleanly under the campaign view.
|
||||
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import React from "react";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { useSearchParams } from "@/hooks/useSearchParams";
|
||||
@@ -43,7 +44,9 @@ import {
|
||||
} from "lucide-react";
|
||||
|
||||
import { useConfirm } from "@/hooks/context/confirm";
|
||||
import { useWriteGuard } from "@/hooks/usePermission";
|
||||
import { usePermission, useWriteGuard } from "@/hooks/usePermission";
|
||||
import { approveCampaignLeads } from "@/lib/api/client/app/campaigns/review";
|
||||
import { refreshReview } from "@/lib/api/hooks/app/campaigns/useCampaignReview";
|
||||
import useSearchContacts from "@/lib/api/hooks/app/contacts/useSearchContacts";
|
||||
import type SearchContacts from "@/lib/api/models/app/contacts/SearchContacts";
|
||||
import useDeleteContacts from "@/lib/api/hooks/app/contacts/useDeleteContacts";
|
||||
@@ -639,16 +642,30 @@ export default function ContactsTable({
|
||||
// resuming is one call, so the row acts straight away.
|
||||
const [pauseTarget, setPauseTarget] = React.useState<{ id: string; name: string } | null>(null);
|
||||
const resumeLead = useResumeLead();
|
||||
const canSend = usePermission("SEND_CAMPAIGNS");
|
||||
const queryClient = useQueryClient();
|
||||
const resumeOne = React.useCallback(
|
||||
(contactId: string, copied?: boolean) => {
|
||||
(contactId: string, source?: string) => {
|
||||
if (!current_campaign) return;
|
||||
// A lead waiting for review is released by an approval, which needs the send permission.
|
||||
if (source === "review" && !canSend) {
|
||||
toast.error("Approving a lead needs the Send campaigns permission.");
|
||||
return;
|
||||
}
|
||||
const run = async () => {
|
||||
try {
|
||||
await toast.promise(
|
||||
resumeLead.mutateAsync({ campaignId: current_campaign.id, contactId }),
|
||||
(async () => {
|
||||
if (source === "review") {
|
||||
await approveCampaignLeads(current_campaign.id, { contact_ids: [contactId] });
|
||||
refreshReview(queryClient, current_campaign.id);
|
||||
} else {
|
||||
await resumeLead.mutateAsync({ campaignId: current_campaign.id, contactId });
|
||||
}
|
||||
})(),
|
||||
{
|
||||
loading: "Resuming lead…",
|
||||
success: "Lead resumed",
|
||||
loading: source === "review" ? "Approving lead…" : "Resuming lead…",
|
||||
success: source === "review" ? "Approved" : "Lead resumed",
|
||||
error: (err: AppError) => buildError(err),
|
||||
},
|
||||
);
|
||||
@@ -656,10 +673,10 @@ export default function ContactsTable({
|
||||
/* toast.promise already surfaced it */
|
||||
}
|
||||
};
|
||||
if (copied) confirm.show(CC_RESUME_CONFIRM, run);
|
||||
if (source === "cc") confirm.show(CC_RESUME_CONFIRM, run);
|
||||
else void run();
|
||||
},
|
||||
[current_campaign, resumeLead, confirm],
|
||||
[current_campaign, resumeLead, confirm, canSend, queryClient],
|
||||
);
|
||||
|
||||
// Leads-view scope chips write straight into the search request, so the
|
||||
@@ -1330,7 +1347,7 @@ function ContactsTableBody({
|
||||
// member without campaign write access, which takes the control off the
|
||||
// row rather than offering one that fails.
|
||||
onPauseLead?: (id: string, name: string) => void;
|
||||
onResumeLead?: (id: string, copied?: boolean) => void;
|
||||
onResumeLead?: (id: string, source?: string) => void;
|
||||
emptyTitle: string;
|
||||
emptyBody: string;
|
||||
emptyCta: React.ReactNode;
|
||||
@@ -1548,9 +1565,9 @@ function ContactsTableBody({
|
||||
{lead?.hold && onResumeLead ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Resume lead"
|
||||
title={`${holdSummary(lead.hold)}. Resume now`}
|
||||
onClick={() => onResumeLead(c.id, lead.hold?.source === "cc")}
|
||||
aria-label={lead.hold.source === "review" ? "Approve lead" : "Resume lead"}
|
||||
title={`${holdSummary(lead.hold)}. ${lead.hold.source === "review" ? "Approve now" : "Resume now"}`}
|
||||
onClick={() => onResumeLead(c.id, lead.hold?.source)}
|
||||
className="size-6 rounded text-violet-500 hover:text-violet-700 hover:bg-violet-50 flex items-center justify-center transition-colors"
|
||||
>
|
||||
<PlayIcon className="w-3 h-3" />
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Loader2Icon, PauseIcon, PlayIcon } from "lucide-react";
|
||||
import toast from "react-hot-toast/headless";
|
||||
import PauseLeadDialog from "./PauseLeadDialog";
|
||||
import { useResumeLead } from "@/lib/api/hooks/app/campaigns/useLeadHold";
|
||||
import { useApproveLeads } from "@/lib/api/hooks/app/campaigns/useCampaignReview";
|
||||
import { useConfirm } from "@/hooks/context/confirm";
|
||||
import type { AppError } from "@/lib/api/client/normalizeError";
|
||||
import buildError from "@/lib/helper/buildError";
|
||||
@@ -42,6 +43,7 @@ export function ResumeLeadButton({
|
||||
disabled = false,
|
||||
onBusyChange,
|
||||
confirmText,
|
||||
approve = false,
|
||||
}: {
|
||||
campaignId: string;
|
||||
contactId: string;
|
||||
@@ -50,17 +52,26 @@ export function ResumeLeadButton({
|
||||
onBusyChange?: (busy: boolean) => void;
|
||||
// Asked first when resuming has a consequence worth a second look.
|
||||
confirmText?: string;
|
||||
// The lead waits for review, which only an approval lifts.
|
||||
approve?: boolean;
|
||||
}) {
|
||||
const resume = useResumeLead();
|
||||
const approveLeads = useApproveLeads(campaignId);
|
||||
const confirm = useConfirm();
|
||||
async function run() {
|
||||
onBusyChange?.(true);
|
||||
try {
|
||||
await toast.promise(resume.mutateAsync({ campaignId, contactId }), {
|
||||
loading: "Resuming lead…",
|
||||
success: "Lead resumed",
|
||||
error: (err: AppError) => buildError(err),
|
||||
});
|
||||
await toast.promise(
|
||||
(async () => {
|
||||
if (approve) await approveLeads.mutateAsync({ contact_ids: [contactId] });
|
||||
else await resume.mutateAsync({ campaignId, contactId });
|
||||
})(),
|
||||
{
|
||||
loading: approve ? "Approving lead…" : "Resuming lead…",
|
||||
success: approve ? "Approved. Their first email goes out on schedule." : "Lead resumed",
|
||||
error: (err: AppError) => buildError(err),
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
/* toast.promise already surfaced it */
|
||||
} finally {
|
||||
@@ -71,11 +82,11 @@ export function ResumeLeadButton({
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => (confirmText ? confirm.show(confirmText, run) : void run())}
|
||||
disabled={disabled || resume.isPending}
|
||||
title="Lift the pause now; the flow picks up where it stopped"
|
||||
disabled={disabled || resume.isPending || approveLeads.isPending}
|
||||
title={approve ? "Approve this lead; their first email goes out on schedule" : "Lift the pause now; the flow picks up where it stopped"}
|
||||
className="h-6 px-2 rounded-md bg-white border border-violet-200 text-[11px] font-medium text-violet-700 hover:bg-violet-100 inline-flex items-center gap-1 transition-colors disabled:opacity-60 shrink-0"
|
||||
>
|
||||
{resume.isPending ? <Loader2Icon className="w-2.5 h-2.5 animate-spin" /> : <PlayIcon className="w-2.5 h-2.5" />}
|
||||
{resume.isPending || approveLeads.isPending ? <Loader2Icon className="w-2.5 h-2.5 animate-spin" /> : <PlayIcon className="w-2.5 h-2.5" />}
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
|
||||
@@ -68,7 +68,7 @@ import LeadCCBar from "./LeadCCBar";
|
||||
import toast from "react-hot-toast/headless";
|
||||
import type { AppError } from "@/lib/api/client/normalizeError";
|
||||
import buildError from "@/lib/helper/buildError";
|
||||
import { useWriteGuard } from "@/hooks/usePermission";
|
||||
import { usePermission, useWriteGuard } from "@/hooks/usePermission";
|
||||
import useClickOutside from "@/hooks/useClickOutside";
|
||||
import { useFlipAlignment } from "@/hooks/useFlipPlacement";
|
||||
import { fmtAbsolute, fmtRelative } from "./format";
|
||||
@@ -446,6 +446,7 @@ function HoldBar({
|
||||
hold: LeadHold;
|
||||
}) {
|
||||
const write = useWriteGuard("MANAGE_CAMPAIGNS");
|
||||
const canSend = usePermission("SEND_CAMPAIGNS");
|
||||
const pause = usePauseLead();
|
||||
const [resuming, setResuming] = React.useState(false);
|
||||
|
||||
@@ -464,11 +465,12 @@ function HoldBar({
|
||||
{holdSummary(hold)}
|
||||
</span>
|
||||
<div className="ml-auto flex items-center gap-1 shrink-0">
|
||||
{write.allowed && (
|
||||
{(hold.source === "review" ? canSend : write.allowed) && (
|
||||
<ResumeLeadButton
|
||||
campaignId={campaignId}
|
||||
contactId={contactId}
|
||||
label={hold.source === "cc" ? "Send their own too" : "Resume now"}
|
||||
approve={hold.source === "review"}
|
||||
label={hold.source === "cc" ? "Send their own too" : hold.source === "review" ? "Approve" : "Resume now"}
|
||||
confirmText={hold.source === "cc" ? CC_RESUME_CONFIRM : undefined}
|
||||
disabled={pause.isPending}
|
||||
onBusyChange={setResuming}
|
||||
|
||||
@@ -18,6 +18,8 @@ export default function FlowPanel({
|
||||
tabs,
|
||||
footer,
|
||||
wide,
|
||||
xwide,
|
||||
fill,
|
||||
bare,
|
||||
readOnly,
|
||||
children,
|
||||
@@ -31,6 +33,10 @@ export default function FlowPanel({
|
||||
tabs?: React.ReactNode;
|
||||
footer?: React.ReactNode;
|
||||
wide?: boolean;
|
||||
// Wider still, for a list beside a preview.
|
||||
xwide?: boolean;
|
||||
// Children fill the body and scroll themselves; they handle their own permissions.
|
||||
fill?: boolean;
|
||||
// Children bring their own header and scrolling.
|
||||
bare?: boolean;
|
||||
// Members who may not edit see every control in the panel disabled.
|
||||
@@ -45,7 +51,7 @@ export default function FlowPanel({
|
||||
transition={{ duration: 0.12, ease: "easeOut" }}
|
||||
className={cn(
|
||||
"absolute inset-0 z-20 flex min-h-0 flex-col bg-white md:static md:inset-auto md:z-auto md:shrink-0 md:border-l md:border-slate-200",
|
||||
wide ? "md:w-[min(760px,62vw)]" : "md:w-[400px]",
|
||||
xwide ? "md:w-[min(1120px,78vw)]" : wide ? "md:w-[min(760px,62vw)]" : "md:w-[400px]",
|
||||
)}
|
||||
>
|
||||
{bare ? (
|
||||
@@ -76,11 +82,15 @@ export default function FlowPanel({
|
||||
)}
|
||||
</div>
|
||||
{tabs}
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">
|
||||
<fieldset disabled={readOnly} className="contents">
|
||||
{children}
|
||||
</fieldset>
|
||||
</div>
|
||||
{fill ? (
|
||||
<div className="min-h-0 flex-1 overflow-hidden">{children}</div>
|
||||
) : (
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">
|
||||
<fieldset disabled={readOnly} className="contents">
|
||||
{children}
|
||||
</fieldset>
|
||||
</div>
|
||||
)}
|
||||
{footer && <div className="shrink-0 border-t border-slate-200 px-3 py-2">{footer}</div>}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -29,6 +29,8 @@ interface EmailBodyProps {
|
||||
// Hold back remote content until the reader loads it. Set for mail other
|
||||
// people wrote; previews of the user's own drafts leave it off.
|
||||
blockRemote?: boolean;
|
||||
// App styles for markers a preview adds to its own copy, after the defaults.
|
||||
extraCss?: string;
|
||||
}
|
||||
|
||||
const CSP_BASE = "default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
|
||||
@@ -135,12 +137,12 @@ const isDesignedEmail = (body: string) => DESIGNED.test(body);
|
||||
// recipient will never see. Its own <head> gets our shell instead.
|
||||
const DOCUMENT_ROOT = /^\s*(?:<!--[\s\S]*?-->\s*)*(?:<!doctype\s+html|<html[\s>])/i;
|
||||
|
||||
function shell(csp: string, dark: boolean): string {
|
||||
function shell(csp: string, dark: boolean, extraCss = ""): string {
|
||||
// The policy must precede everything else in the head to govern it.
|
||||
return (
|
||||
`<meta http-equiv="Content-Security-Policy" content="${csp}">` +
|
||||
`<meta charset="utf-8"><meta name="referrer" content="no-referrer">` +
|
||||
`<base target="_blank"><style>${DOCUMENT_CSS}${dark ? DARK_DOCUMENT_CSS : ""}</style>`
|
||||
`<base target="_blank"><style>${DOCUMENT_CSS}${dark ? DARK_DOCUMENT_CSS : ""}${extraCss}</style>`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -156,7 +158,7 @@ function neutralizeLinks(doc: Document) {
|
||||
});
|
||||
}
|
||||
|
||||
function buildDocument(body: string, csp: string, dark: boolean): string {
|
||||
function buildDocument(body: string, csp: string, dark: boolean, extraCss = ""): string {
|
||||
// Our shell goes FIRST in the parsed document's real head, so the
|
||||
// message's own stylesheet comes after it and wins on everything but the
|
||||
// containment rules, and nothing in the markup (a commented-out <head>,
|
||||
@@ -166,12 +168,12 @@ function buildDocument(body: string, csp: string, dark: boolean): string {
|
||||
whole ? body : `<!doctype html><html><head></head><body>${body}</body></html>`,
|
||||
"text/html",
|
||||
);
|
||||
doc.head.insertAdjacentHTML("afterbegin", shell(csp, dark));
|
||||
doc.head.insertAdjacentHTML("afterbegin", shell(csp, dark, extraCss));
|
||||
neutralizeLinks(doc);
|
||||
return `${doc.doctype ? "<!doctype html>" : ""}${doc.documentElement.outerHTML}`;
|
||||
}
|
||||
|
||||
export default function EmailBody({ html, plain, blockRemote = false }: EmailBodyProps) {
|
||||
export default function EmailBody({ html, plain, blockRemote = false, extraCss = "" }: EmailBodyProps) {
|
||||
const frameRef = React.useRef<HTMLIFrameElement>(null);
|
||||
const viewportRef = React.useRef<HTMLDivElement>(null);
|
||||
const [showQuoted, setShowQuoted] = React.useState(false);
|
||||
@@ -199,8 +201,8 @@ export default function EmailBody({ html, plain, blockRemote = false }: EmailBod
|
||||
const designed = React.useMemo(() => isDesignedEmail(body), [body]);
|
||||
const darkDocument = darkTheme && !designed;
|
||||
const srcDoc = React.useMemo(
|
||||
() => (body ? buildDocument(showQuoted ? quotes.expanded : quotes.collapsed, csp, darkDocument) : ""),
|
||||
[body, quotes, showQuoted, csp, darkDocument],
|
||||
() => (body ? buildDocument(showQuoted ? quotes.expanded : quotes.collapsed, csp, darkDocument, extraCss) : ""),
|
||||
[body, quotes, showQuoted, csp, darkDocument, extraCss],
|
||||
);
|
||||
|
||||
// Measure at the available width first; scale only layouts that cannot reflow.
|
||||
|
||||
@@ -34,6 +34,12 @@ export interface TemplatePreview {
|
||||
// what CSS they ignore, and whether the message is long enough to be
|
||||
// clipped. Sized on the body as it ships, after CSS inlining.
|
||||
html_findings?: TemplateHtmlFinding[];
|
||||
// The copy's AI blocks; written is true when this contact's copy is.
|
||||
ai_blocks?: { id: string; name: string; written: boolean }[];
|
||||
// The contact is a lead of the campaign, so its AI copy can be written ahead.
|
||||
lead?: boolean;
|
||||
// The lead has their own copy of this step, which they get instead.
|
||||
personalized?: boolean;
|
||||
}
|
||||
|
||||
export interface TemplatePreviewInput {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import type {
|
||||
AIWritePass,
|
||||
CampaignReviewSummary,
|
||||
LeadEmails,
|
||||
ReviewChange,
|
||||
ReviewLeadsFilter,
|
||||
ReviewLeadsPage,
|
||||
} from "@/lib/api/models/app/campaigns/Review";
|
||||
import Request from "../../Request";
|
||||
|
||||
export async function getCampaignReview(campaignId: string): Promise<CampaignReviewSummary> {
|
||||
return await Request<CampaignReviewSummary>({ method: "GET", url: `/campaigns/${campaignId}/review`, authorization: true });
|
||||
}
|
||||
|
||||
export async function setCampaignReview(campaignId: string, enabled: boolean): Promise<ReviewChange> {
|
||||
return await Request<ReviewChange>({ method: "PUT", url: `/campaigns/${campaignId}/review`, data: { enabled }, authorization: true });
|
||||
}
|
||||
|
||||
export async function getCampaignReviewLeads(
|
||||
campaignId: string,
|
||||
filter: ReviewLeadsFilter,
|
||||
cursor: string | null,
|
||||
limit = 50,
|
||||
): Promise<ReviewLeadsPage> {
|
||||
const params = new URLSearchParams({ status: filter.status, limit: String(limit) });
|
||||
if (filter.missing) params.set("missing", filter.missing);
|
||||
if (filter.q?.trim()) params.set("q", filter.q.trim());
|
||||
if (cursor) params.set("cursor", cursor);
|
||||
return await Request<ReviewLeadsPage>({
|
||||
method: "GET",
|
||||
url: `/campaigns/${campaignId}/review/leads?${params.toString()}`,
|
||||
authorization: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Either contact_ids or all.
|
||||
export async function approveCampaignLeads(campaignId: string, body: { contact_ids?: string[]; all?: boolean }): Promise<ReviewChange> {
|
||||
return await Request<ReviewChange>({ method: "POST", url: `/campaigns/${campaignId}/review/approve`, data: body, authorization: true });
|
||||
}
|
||||
|
||||
export async function reopenCampaignLeads(campaignId: string, contactIds: string[]): Promise<ReviewChange> {
|
||||
return await Request<ReviewChange>({
|
||||
method: "POST",
|
||||
url: `/campaigns/${campaignId}/review/reopen`,
|
||||
data: { contact_ids: contactIds },
|
||||
authorization: true,
|
||||
});
|
||||
}
|
||||
|
||||
// One pass of writing AI copy ahead; repeat with the returned next as after while remaining > 0.
|
||||
export async function writeCampaignReviewAI(
|
||||
campaignId: string,
|
||||
body: { step_id?: string; contact_ids?: string[]; waiting_only?: boolean; after?: string },
|
||||
): Promise<AIWritePass> {
|
||||
return await Request<AIWritePass>({ method: "POST", url: `/campaigns/${campaignId}/review/write`, data: body, authorization: true });
|
||||
}
|
||||
|
||||
export async function getLeadEmails(campaignId: string, contactId: string): Promise<LeadEmails> {
|
||||
return await Request<LeadEmails>({ method: "GET", url: `/campaigns/${campaignId}/leads/${contactId}/emails`, authorization: true });
|
||||
}
|
||||
|
||||
export async function putLeadEmail(
|
||||
campaignId: string,
|
||||
contactId: string,
|
||||
stepId: string,
|
||||
body: { subject: string; body_html: string; body_plain: string },
|
||||
): Promise<unknown> {
|
||||
return await Request<unknown>({
|
||||
method: "PUT",
|
||||
url: `/campaigns/${campaignId}/leads/${contactId}/emails/${stepId}`,
|
||||
data: body,
|
||||
authorization: true,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteLeadEmail(campaignId: string, contactId: string, stepId: string): Promise<void> {
|
||||
await Request<unknown>({ method: "DELETE", url: `/campaigns/${campaignId}/leads/${contactId}/emails/${stepId}`, authorization: true });
|
||||
}
|
||||
|
||||
// rewrite replaces copy already written, and is charged again.
|
||||
export async function writeLeadEmailAI(campaignId: string, contactId: string, stepId: string, rewrite = false): Promise<LeadEmails> {
|
||||
return await Request<LeadEmails>({
|
||||
method: "POST",
|
||||
url: `/campaigns/${campaignId}/leads/${contactId}/emails/${stepId}/write`,
|
||||
data: rewrite ? { rewrite: true } : undefined,
|
||||
authorization: true,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import { useMemo, useSyncExternalStore } from "react";
|
||||
import {
|
||||
infiniteQueryOptions,
|
||||
queryOptions,
|
||||
useInfiniteQuery,
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
type InfiniteData,
|
||||
type QueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
import {
|
||||
approveCampaignLeads,
|
||||
deleteLeadEmail,
|
||||
getCampaignReview,
|
||||
getCampaignReviewLeads,
|
||||
getLeadEmails,
|
||||
putLeadEmail,
|
||||
reopenCampaignLeads,
|
||||
setCampaignReview,
|
||||
writeCampaignReviewAI,
|
||||
writeLeadEmailAI,
|
||||
} from "@/lib/api/client/app/campaigns/review";
|
||||
import type {
|
||||
CampaignReviewSummary,
|
||||
LeadEmails,
|
||||
ReviewLead,
|
||||
ReviewLeadsFilter,
|
||||
ReviewLeadsPage,
|
||||
ReviewStatus,
|
||||
} from "@/lib/api/models/app/campaigns/Review";
|
||||
|
||||
// Every key starts with ["campaigns", id], so the audit spine's campaign and
|
||||
// campaign_lead entries refresh the Review tab for every teammate.
|
||||
export const reviewKey = (campaignId: string) => ["campaigns", campaignId, "review"] as const;
|
||||
|
||||
// The list the tab opens on: waiting leads in review mode, else leads not yet emailed, else everyone.
|
||||
export function openingReviewStatus(s: CampaignReviewSummary): "all" | ReviewStatus {
|
||||
if (s.review_leads && s.counts.waiting > 0) return "waiting";
|
||||
return s.counts.ready > 0 ? "ready" : "all";
|
||||
}
|
||||
|
||||
export const campaignReviewQuery = (campaignId: string) =>
|
||||
queryOptions({
|
||||
queryKey: [...reviewKey(campaignId), "summary"],
|
||||
queryFn: () => getCampaignReview(campaignId),
|
||||
staleTime: 30_000,
|
||||
// Background writing has no event of its own, so its progress is read while it runs.
|
||||
refetchInterval: (q) => (q.state.data?.ai.auto && q.state.data.ai.pending > 0 ? 10_000 : false),
|
||||
});
|
||||
|
||||
export const reviewLeadsQuery = (campaignId: string, filter: ReviewLeadsFilter) =>
|
||||
infiniteQueryOptions<ReviewLeadsPage, Error, InfiniteData<ReviewLeadsPage, string | null>, readonly unknown[], string | null>({
|
||||
queryKey: [...reviewKey(campaignId), "leads", filter.status, filter.missing ?? "", filter.q ?? ""],
|
||||
queryFn: ({ pageParam }) => getCampaignReviewLeads(campaignId, filter, pageParam),
|
||||
initialPageParam: null,
|
||||
getNextPageParam: (last) => (last.pagination.has_more ? last.pagination.next_cursor : undefined),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
|
||||
export const leadEmailsQuery = (campaignId: string, contactId: string) =>
|
||||
queryOptions({
|
||||
queryKey: [...reviewKey(campaignId), "emails", contactId],
|
||||
queryFn: () => getLeadEmails(campaignId, contactId),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
|
||||
export function useCampaignReview(campaignId: string) {
|
||||
return useQuery({ ...campaignReviewQuery(campaignId), enabled: !!campaignId });
|
||||
}
|
||||
|
||||
export function useReviewLeads(campaignId: string, filter: ReviewLeadsFilter) {
|
||||
const query = useInfiniteQuery({ ...reviewLeadsQuery(campaignId, filter), enabled: !!campaignId });
|
||||
const leads = useMemo(() => query.data?.pages.flatMap((p) => p.data) ?? [], [query.data]);
|
||||
return { ...query, leads };
|
||||
}
|
||||
|
||||
export function useLeadEmails(campaignId: string, contactId: string | null) {
|
||||
return useQuery({ ...leadEmailsQuery(campaignId, contactId ?? ""), enabled: !!campaignId && !!contactId });
|
||||
}
|
||||
|
||||
function refreshReview(qc: QueryClient, campaignId: string) {
|
||||
void qc.invalidateQueries({ queryKey: reviewKey(campaignId) });
|
||||
void qc.invalidateQueries({ queryKey: ["campaigns", campaignId], exact: true });
|
||||
// Holds show on the Leads list and the contact drawer.
|
||||
void qc.invalidateQueries({ queryKey: ["contacts"] });
|
||||
}
|
||||
|
||||
// Approving is predictable, so the rows leave "waiting" at once and come back on failure.
|
||||
function patchStatus(qc: QueryClient, campaignId: string, ids: Set<string> | "all", from: ReviewStatus, to: ReviewStatus) {
|
||||
const prefix = [...reviewKey(campaignId), "leads"];
|
||||
const snapshot = qc.getQueriesData<InfiniteData<ReviewLeadsPage, string | null>>({ queryKey: prefix });
|
||||
for (const [key, data] of snapshot) {
|
||||
if (!data) continue;
|
||||
// A list filtered to one state loses the rows that leave it, so they animate out at once.
|
||||
const filter = key[4];
|
||||
const moves = (l: ReviewLead) => l.status === from && (ids === "all" || ids.has(l.contact_id));
|
||||
qc.setQueryData<InfiniteData<ReviewLeadsPage, string | null>>(key, {
|
||||
...data,
|
||||
pages: data.pages.map((p) => ({
|
||||
...p,
|
||||
data:
|
||||
filter === from
|
||||
? p.data.filter((l) => !moves(l))
|
||||
: p.data.map((l) => (moves(l) ? { ...l, status: to, hold: to === "waiting" ? l.hold : null } : l)),
|
||||
})),
|
||||
});
|
||||
}
|
||||
return () => snapshot.forEach(([key, value]) => qc.setQueryData(key, value));
|
||||
}
|
||||
|
||||
export function useApproveLeads(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (body: { contact_ids?: string[]; all?: boolean }) => approveCampaignLeads(campaignId, body),
|
||||
onMutate: async (body) => {
|
||||
await qc.cancelQueries({ queryKey: [...reviewKey(campaignId), "leads"] });
|
||||
return { restore: patchStatus(qc, campaignId, body.all ? "all" : new Set(body.contact_ids), "waiting", "ready") };
|
||||
},
|
||||
onError: (_e, _v, ctx) => ctx?.restore(),
|
||||
onSettled: () => refreshReview(qc, campaignId),
|
||||
});
|
||||
}
|
||||
|
||||
export function useReopenLeads(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (contactIds: string[]) => reopenCampaignLeads(campaignId, contactIds),
|
||||
onMutate: async (ids) => {
|
||||
await qc.cancelQueries({ queryKey: [...reviewKey(campaignId), "leads"] });
|
||||
return { restore: patchStatus(qc, campaignId, new Set(ids), "ready", "waiting") };
|
||||
},
|
||||
onError: (_e, _v, ctx) => ctx?.restore(),
|
||||
onSettled: () => refreshReview(qc, campaignId),
|
||||
});
|
||||
}
|
||||
|
||||
// Turning review off approves every waiting lead, which the server decides; it waits for the answer.
|
||||
export function useSetReview(campaignId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (enabled: boolean) => setCampaignReview(campaignId, enabled),
|
||||
onSettled: () => refreshReview(qc, campaignId),
|
||||
});
|
||||
}
|
||||
|
||||
export function usePersonalizeLeadEmail(campaignId: string, contactId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ stepId, ...body }: { stepId: string; subject: string; body_html: string; body_plain: string }) =>
|
||||
putLeadEmail(campaignId, contactId, stepId, body),
|
||||
onSettled: () => refreshReview(qc, campaignId),
|
||||
});
|
||||
}
|
||||
|
||||
export function useResetLeadEmail(campaignId: string, contactId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (stepId: string) => deleteLeadEmail(campaignId, contactId, stepId),
|
||||
onSettled: () => refreshReview(qc, campaignId),
|
||||
});
|
||||
}
|
||||
|
||||
export function useWriteReviewAIPass(campaignId: string) {
|
||||
return useMutation({
|
||||
mutationFn: (body: { step_id?: string; contact_ids?: string[]; waiting_only?: boolean; after?: string }) =>
|
||||
writeCampaignReviewAI(campaignId, body),
|
||||
});
|
||||
}
|
||||
|
||||
export { refreshReview };
|
||||
|
||||
const aiWrites = new Map<string, Promise<LeadEmails>>();
|
||||
const aiWriteListeners = new Set<() => void>();
|
||||
let aiWritesVersion = 0;
|
||||
function aiWritesChanged() {
|
||||
aiWritesVersion++;
|
||||
aiWriteListeners.forEach((l) => l());
|
||||
}
|
||||
|
||||
// Writes one lead's AI copy for one step and keeps their emails in the cache.
|
||||
// A write already running for the same lead and step is joined, not repeated,
|
||||
// so opening a lead the background is writing waits for that one. Copy already
|
||||
// written costs nothing: the server answers from what it has.
|
||||
export function writeLeadAIOnce(qc: QueryClient, campaignId: string, contactId: string, stepId: string, rewrite = false): Promise<LeadEmails> {
|
||||
const key = `${campaignId}:${contactId}:${stepId}`;
|
||||
const running = aiWrites.get(key);
|
||||
if (running && !rewrite) return running;
|
||||
const p = writeLeadEmailAI(campaignId, contactId, stepId, rewrite)
|
||||
.then((data) => {
|
||||
qc.setQueryData(leadEmailsQuery(campaignId, contactId).queryKey, data);
|
||||
void qc.invalidateQueries({ queryKey: [...reviewKey(campaignId), "summary"] });
|
||||
void qc.invalidateQueries({ queryKey: ["subscription", "credits"] });
|
||||
return data;
|
||||
})
|
||||
.finally(() => {
|
||||
if (aiWrites.get(key) === p) {
|
||||
aiWrites.delete(key);
|
||||
aiWritesChanged();
|
||||
}
|
||||
});
|
||||
aiWrites.set(key, p);
|
||||
aiWritesChanged();
|
||||
return p;
|
||||
}
|
||||
|
||||
export function aiWriteRunning(campaignId: string, contactId: string, stepId: string): boolean {
|
||||
return aiWrites.has(`${campaignId}:${contactId}:${stepId}`);
|
||||
}
|
||||
|
||||
// The leads of a campaign whose AI copy is being written right now, for any step.
|
||||
export function useLeadsBeingWritten(campaignId: string): Set<string> {
|
||||
const version = useSyncExternalStore(
|
||||
(l) => {
|
||||
aiWriteListeners.add(l);
|
||||
return () => aiWriteListeners.delete(l);
|
||||
},
|
||||
() => aiWritesVersion,
|
||||
);
|
||||
return useMemo(() => {
|
||||
void version;
|
||||
const ids = new Set<string>();
|
||||
for (const key of aiWrites.keys()) {
|
||||
const [c, contact] = key.split(":");
|
||||
if (c === campaignId) ids.add(contact);
|
||||
}
|
||||
return ids;
|
||||
}, [campaignId, version]);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ export type AuditAction =
|
||||
| "stop"
|
||||
| "pause"
|
||||
| "resume"
|
||||
| "approve"
|
||||
| "send"
|
||||
| "duplicate"
|
||||
| "disconnect"
|
||||
@@ -34,8 +35,8 @@ export type AuditAction =
|
||||
export type AuditEntityType =
|
||||
| "campaign"
|
||||
// One contact inside one campaign: the entity id is the contact and the
|
||||
// metadata carries the campaign. Written when a lead's flow is held or
|
||||
// resumed.
|
||||
// metadata carries the campaign. Written when a lead's flow is held,
|
||||
// resumed, approved or reopened, or one of its emails is personalized.
|
||||
| "campaign_lead"
|
||||
| "contact"
|
||||
| "email_account"
|
||||
|
||||
@@ -76,6 +76,9 @@ export default interface Campaign {
|
||||
ramp_level_date?: Date | null;
|
||||
// Mailboxes leaving warmup earn volume from replies. Absent from an older backend, which means on.
|
||||
warmup_graduation?: boolean;
|
||||
// Each new lead waits for a member to approve its first email. Changed through
|
||||
// the Review tab (PUT /campaigns/:id/review). Absent from an older backend, which means off.
|
||||
review_leads?: boolean;
|
||||
|
||||
// Match the sending mailbox provider to the recipient's provider.
|
||||
esp_match_mode: 'off' | 'prefer' | 'strict';
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { LeadHold } from "@/lib/api/models/app/contacts/Contact";
|
||||
|
||||
// A lead's review state: waiting for approval, ready to start, paused for
|
||||
// another reason, or already emailed.
|
||||
export type ReviewStatus = "waiting" | "ready" | "held" | "started";
|
||||
|
||||
// The fields the readiness check counts blanks of.
|
||||
export type MissingField = "FirstName" | "LastName" | "Company" | "Phone";
|
||||
|
||||
export const MISSING_FIELD_LABEL: Record<string, string> = {
|
||||
FirstName: "first name",
|
||||
LastName: "last name",
|
||||
Company: "company",
|
||||
Phone: "phone",
|
||||
};
|
||||
|
||||
export interface ReviewCounts {
|
||||
total: number;
|
||||
waiting: number;
|
||||
ready: number;
|
||||
held: number;
|
||||
started: number;
|
||||
personalized: number;
|
||||
}
|
||||
|
||||
export interface CampaignReviewSummary {
|
||||
campaign_id: string;
|
||||
review_leads: boolean;
|
||||
counts: ReviewCounts;
|
||||
missing: { field: MissingField; leads: number }[];
|
||||
undeliverable: number;
|
||||
unsubscribed: number;
|
||||
ai: {
|
||||
step_id?: string;
|
||||
blocks: number;
|
||||
written: number;
|
||||
pending: number;
|
||||
estimated_cost_usd: number;
|
||||
// The campaign is running, so pending leads are being written on the server.
|
||||
auto?: boolean;
|
||||
};
|
||||
template_errors?: { step_id: string; position: number; message: string }[];
|
||||
}
|
||||
|
||||
export interface ReviewLead {
|
||||
contact_id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
company: string;
|
||||
status: ReviewStatus;
|
||||
hold?: LeadHold | null;
|
||||
personalized: number;
|
||||
missing?: MissingField[];
|
||||
added_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ReviewLeadsPage {
|
||||
data: ReviewLead[];
|
||||
pagination: { next_cursor: string | null; has_more: boolean };
|
||||
}
|
||||
|
||||
export interface ReviewLeadsFilter {
|
||||
status: "all" | ReviewStatus;
|
||||
missing?: MissingField;
|
||||
q?: string;
|
||||
}
|
||||
|
||||
export interface LeadEmailStep {
|
||||
step_id: string;
|
||||
position: number;
|
||||
name: string;
|
||||
subject: string;
|
||||
body_html: string;
|
||||
body_plain: string;
|
||||
// The template this lead's copy renders from: their own copy, their A/B arm, or the step's.
|
||||
source: { subject: string; body_html: string; body_plain: string };
|
||||
threaded: boolean;
|
||||
personalized: boolean;
|
||||
edited_at?: string | null;
|
||||
step_changed: boolean;
|
||||
variant_id?: string | null;
|
||||
ai_blocks?: { id: string; name: string; written: boolean }[];
|
||||
missing?: MissingField[];
|
||||
errors?: string[];
|
||||
sent: boolean;
|
||||
sent_at?: string | null;
|
||||
}
|
||||
|
||||
export interface LeadEmails {
|
||||
campaign_id: string;
|
||||
lead: ReviewLead;
|
||||
from?: { name: string; email: string } | null;
|
||||
steps: LeadEmailStep[];
|
||||
}
|
||||
|
||||
export interface ReviewChange {
|
||||
campaign_id: string;
|
||||
review_leads: boolean;
|
||||
held: number;
|
||||
released: number;
|
||||
}
|
||||
|
||||
export interface AIWritePass {
|
||||
written: number;
|
||||
failed: number;
|
||||
remaining: number;
|
||||
stopped?: "insufficient_credits" | "usage_cap_exceeded" | string;
|
||||
// Sent back as after on the next pass.
|
||||
next?: string;
|
||||
}
|
||||
|
||||
export function leadName(l: Pick<ReviewLead, "first_name" | "last_name" | "email">): string {
|
||||
return `${l.first_name ?? ""} ${l.last_name ?? ""}`.trim() || l.email;
|
||||
}
|
||||
@@ -24,13 +24,14 @@ export type LeadStatus =
|
||||
// when an auto-reply parked it, "manual" when a member did, "crm" when the
|
||||
// connected CRM says the contact moved on (a HubSpot deal or lifecycle stage, a
|
||||
// Salesforce rule), and "cc" while the contact is copied on another lead's
|
||||
// emails (reason is that lead's address);
|
||||
// emails (reason is that lead's address), and "review" while a review campaign
|
||||
// waits for someone to approve the lead's first email;
|
||||
// `until` absent means the hold has no end and only a resume lifts it.
|
||||
export interface LeadHold {
|
||||
since: Date;
|
||||
until?: Date | null;
|
||||
reason?: string;
|
||||
source: "manual" | "out_of_office" | "inbox_tagging" | "cc" | "crm" | string;
|
||||
source: "manual" | "out_of_office" | "inbox_tagging" | "cc" | "crm" | "review" | string;
|
||||
}
|
||||
|
||||
// Why a copied contact is or is not on the next email to the lead.
|
||||
@@ -58,6 +59,7 @@ export function leadCCName(cc: Pick<LeadCC, "first_name" | "last_name" | "email"
|
||||
// the flow is parked and when it lifts. One function so the Leads row and the
|
||||
// contact drawer cannot word the same hold two different ways.
|
||||
export function holdSummary(hold: LeadHold): string {
|
||||
if (hold.source === "review") return "Waiting for review · their first email goes out once someone approves it";
|
||||
if (hold.source === "cc") {
|
||||
return hold.reason
|
||||
? `Copied on the emails to ${hold.reason} · none of their own are sent`
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { webcrypto } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { installRandomUUID } from "./randomUUID";
|
||||
|
||||
describe("installRandomUUID", () => {
|
||||
it("gives an insecure-context crypto a v4 randomUUID", () => {
|
||||
const c = { getRandomValues: webcrypto.getRandomValues.bind(webcrypto) } as unknown as Crypto;
|
||||
installRandomUUID(c);
|
||||
const a = c.randomUUID();
|
||||
expect(a).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
|
||||
expect(c.randomUUID()).not.toBe(a);
|
||||
});
|
||||
|
||||
it("leaves a native randomUUID alone", () => {
|
||||
const native = () => "native" as `${string}-${string}-${string}-${string}-${string}`;
|
||||
const c = { randomUUID: native, getRandomValues: webcrypto.getRandomValues.bind(webcrypto) } as unknown as Crypto;
|
||||
installRandomUUID(c);
|
||||
expect(c.randomUUID).toBe(native);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
// crypto.randomUUID exists only in secure contexts; a plain-http self-host has getRandomValues alone.
|
||||
export function installRandomUUID(c: Crypto | undefined = globalThis.crypto): void {
|
||||
if (!c || typeof c.randomUUID === "function" || typeof c.getRandomValues !== "function") return;
|
||||
c.randomUUID = function randomUUID() {
|
||||
const b = c.getRandomValues(new Uint8Array(16));
|
||||
b[6] = (b[6] & 0x0f) | 0x40;
|
||||
b[8] = (b[8] & 0x3f) | 0x80;
|
||||
const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
||||
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}` as `${string}-${string}-${string}-${string}-${string}`;
|
||||
};
|
||||
}
|
||||
@@ -11,11 +11,13 @@ import { Toaster } from '@/components/ui/toaster';
|
||||
import { initErrorReporting, reportsErrors } from "@/lib/observability";
|
||||
import { initProductAnalytics } from "@/lib/productAnalytics";
|
||||
import { installDomMutationGuard } from "@/lib/domGuard";
|
||||
import { installRandomUUID } from "@/lib/randomUUID";
|
||||
import { queryClient } from "@/lib/queryClient";
|
||||
import { dashboardPages, router } from "./router";
|
||||
|
||||
// Before the first render, so a translated page never commits unguarded.
|
||||
installDomMutationGuard();
|
||||
installRandomUUID();
|
||||
|
||||
// Before the first render, so a boot failure is reported too.
|
||||
initErrorReporting();
|
||||
|
||||
+11
-1
@@ -355,6 +355,16 @@ const campaignLeads = dash(campaignRoute, "leads", dashboardPages.campaignLeads,
|
||||
const campaignPreferences = dash(campaignRoute, "preferences", dashboardPages.campaignPreferences, "Campaign settings", loaders.campaignPreferencesLoader);
|
||||
const campaignSchedule = dash(campaignRoute, "schedule", dashboardPages.campaignSchedule, "Campaign schedule", loaders.campaignScheduleLoader);
|
||||
const campaignSteps = dash(campaignRoute, "steps", dashboardPages.campaignSteps, "Campaign steps", loaders.campaignStepsLoader);
|
||||
// Reviewing leads lives on each email step's Review tab; old links open the first email's.
|
||||
const campaignReview = createRoute({
|
||||
getParentRoute: () => campaignRoute,
|
||||
path: "review",
|
||||
beforeLoad: ({ params, location }) => {
|
||||
const search = new URLSearchParams(location.searchStr);
|
||||
search.set("review", "1");
|
||||
throw redirect({ href: `/app/campaigns/${encodeURIComponent((params as { id: string }).id)}/steps?${search.toString()}`, replace: true });
|
||||
},
|
||||
});
|
||||
|
||||
const analyticsRoute = dash(appRoute, "analytics", dashboardPages.analytics, "Analytics", loaders.analyticsLoader);
|
||||
const reportsRoute = createRoute({ getParentRoute: () => appRoute, path: "reports" });
|
||||
@@ -507,7 +517,7 @@ const routeTree = rootRoute.addChildren([
|
||||
formsRoute.addChildren([formsIndex, formRoute]),
|
||||
campaignsRoute.addChildren([
|
||||
campaignsIndex,
|
||||
campaignRoute.addChildren([campaignIndex, campaignLeads, campaignPreferences, campaignSchedule, campaignSteps]),
|
||||
campaignRoute.addChildren([campaignIndex, campaignLeads, campaignReview, campaignPreferences, campaignSchedule, campaignSteps]),
|
||||
]),
|
||||
analyticsRoute,
|
||||
reportsRoute.addChildren([reportsIndex, reportRoute]),
|
||||
|
||||
Reference in New Issue
Block a user