diff --git a/README.md b/README.md index 95896b7..53a2868 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,8 @@ prints JSON (indented; compact with `--json`) and says what happened in a stable | `reply contact linkedin-connect --linkedin-account-id N [--message -]` | a LinkedIn invitation, with or without a note → `sent` / `already_connected` | | `reply contact linkedin-message …` · `linkedin-inmail …` · `linkedin-voice …` | a LinkedIn message, an InMail, or an AI voice message spoken from a script → `sent` | | any direct send `… [--send-after ] [--schedule-id N] [--idempotency-key K]` | the send held until a moment, timed by a schedule, under a key of yours → `sent`, with its `reference` and `state` | +| any direct send `… [--use-contact-time-zone \| --no-use-contact-time-zone]` | with `--schedule-id`, the schedule read in the contact's time zone or its own | +| a LinkedIn send `… [--retry-window-minutes N]` | how long Reply keeps trying once the send is due | | `reply direct-send get ` | a send as Reply holds it: whether it has gone out, when, and why it failed | | `reply direct-send cancel ` | stop a send that has not gone out yet → `state` `cancelled` | | `reply inbox list (--contact-id \| --sequence-id) [--source] [--channel] [--category-id] [--since]` | one page of threads | @@ -319,18 +321,46 @@ Reply cannot fill is `contact.missing_variables`, with the names under the error # {"error":{"code":"contact.missing_variables",…,"details":{"missing_variables":["FirstName","Company"]}}} ``` -Every direct send also takes `--send-after `, `--schedule-id ` and `--idempotency-key -`. Reply holds the send until the moment, given with its offset (`2026-11-03T14:00:00Z`, -`2026-11-03T16:00:00+02:00`) and sent to Reply in UTC; a moment without an offset is refused -(`usage.date`). `--schedule-id` names the sending schedule Reply times the send by (see `reply -schedule list`). The answer then adds Reply's `reference`, `send_after` and `state`, each only when -Reply gives it. `status: "sent"` means Reply took the send, and `state`, when present, says whether -it has gone out: `queued` or `sending` is not yet, then `sent`, `failed` or `cancelled`. `reply -direct-send get ` reads the send later, and `reply direct-send cancel ` stops -one that has not gone out. The reference is Reply's, `email-` or `linkedin-`, the form -Reply's route takes: a reference of any other form is refused before any call (`usage.reference`, -exit 2), and nothing else is read from it. An answer without `state` comes from a Reply that does -not know these flags yet: it sent at once, as without them. +Every direct send also takes `--send-after `, `--schedule-id ` and +`--idempotency-key `. Reply holds the send until the moment, given with its offset +(`2026-11-03T14:00:00Z`, `2026-11-03T16:00:00+02:00`) and sent to Reply in UTC; a moment without an +offset is refused (`usage.date`). `--schedule-id` names the sending schedule Reply times the send by +(see `reply schedule list`). The answer then adds Reply's `reference`, `send_after` and `state`, +each only when Reply gives it. `status: "sent"` means Reply took the send, and `state`, when +present, says whether it has gone out: `queued`, `waitingForSchedule` or `sending` is not yet, then +`sent`, `failed` or `cancelled`. `reply direct-send get ` reads the send later, and +`reply direct-send cancel ` stops one that has not gone out. The reference is Reply's, +`email-`, `linkedin-` or `linkedin-scheduled-` (a LinkedIn send held for later keeps that +one for its whole life), the form Reply's route takes: a reference of any other form is refused +before any call (`usage.reference`, exit 2), and nothing else is read from it. An answer without +`state` comes from a Reply that does not know these flags yet: it sent at once, as without them. + +A send timed by `--schedule-id` may answer `state` `waitingForSchedule`: Reply holds it for the +schedule's next opening, so `send_after` is left out, and `estimated_send_at` is when Reply expects +to send it, an ISO-8601 UTC moment; Reply sends it within about 10 minutes of that moment. Reply +sets `estimated_send_at` in `waitingForSchedule` only and gives it null in every other state; it is +null in `waitingForSchedule` too when the schedule does not open within 30 days of the moment the +send waits from: its `--send-after`, or when Reply took it. It is added only when Reply gives it. + +Every direct send also takes `--use-contact-time-zone` / `--no-use-contact-time-zone`, and the four +LinkedIn sends take `--retry-window-minutes ` as well; `contact send-email` does not take the +retry window. `--use-contact-time-zone` reads the schedule's windows in the contact's time zone and +`--no-use-contact-time-zone` in the schedule's own; with neither, the schedule's own setting holds. +`--retry-window-minutes` is how long Reply keeps trying to send once the send is due, 1 to 4320 +minutes (Reply's default is 90); a number outside that is refused before any call (`usage.range`). +Reply takes the time zone only with `--schedule-id` and the retry window only for a send made +later, and answers them otherwise with `reply.invalid_request`. + +Reply refuses a send it cannot time when it takes it, and nothing is sent. A `--schedule-id` +naming no schedule this account can read is `schedule.not_found`, a schedule with no active day +that has a time range, so it never opens, is `schedule.no_slot`, and a contact without the time +zone `--use-contact-time-zone` reads the schedule in is `contact.time_zone_missing`. The codes are +the same on an email and on a LinkedIn send; `reply_code` keeps the one Reply gave. + +```sh +echo '{"body":"Following up on my note."}' | reply contact linkedin-message --contact-id 456 --linkedin-account-id 34 --message - --schedule-id 41 --use-contact-time-zone --retry-window-minutes 120 +# {"status":"sent",…,"activity_id":null,"sent_at":null,"reference":"linkedin-scheduled-77","state":"waitingForSchedule","estimated_send_at":"2026-11-04T09:00:00Z"} +``` `--idempotency-key` goes to Reply as the `Idempotency-Key` header, never in the body. A Reply that knows the header answers a repeat with the same key with the send the key first made; while that @@ -352,13 +382,25 @@ reply direct-send get linkedin-1042 reply direct-send cancel linkedin-1042 ``` -Both answer the send under the CLI's names, each null when Reply gives none: `reference`, -`channel`, `contact_id`, `state`, `send_after`, `sent_at`, `message_id`, `failure_reason` and -`cancelled_at`. `failure_code`, `missing_variables`, `rendered_subject` and `rendered_body` are -added only when Reply gives them. `failure_reason` is a sentence for a person and never parsed; -`failure_code` is Reply's code for the failure, the one to branch on. `direct-send cancel` of a send already cancelled answers it -again. A send already gone out or failed is `direct_send.already_sent` or -`direct_send.already_failed`, and a reference Reply has no send for is `direct_send.not_found`. +Both answer the send under the CLI's names, each null when Reply gives none: `reference`, `channel`, +`contact_id`, `state`, `send_after`, `sent_at`, `message_id`, `failure_reason` and `cancelled_at`. +`failure_code`, `missing_variables`, `rendered_subject` and `rendered_body` are added only when +Reply gives them, and so is `estimated_send_at`, read the same way as on the send but as of the +read: set in `waitingForSchedule` only and null in every other state, and null there too when the +schedule does not open within 30 days counted from `--send-after`, or from now once that has passed. +`failure_reason` is a sentence for a person and never parsed; `failure_code` is Reply's code for the +failure, the one to branch on. A failed send may carry no `failure_code`: it is then null, and +`failure_reason` is all Reply says of it. `direct-send cancel` of a send already cancelled answers +it again. A send already gone out, failed or going out is `direct_send.already_sent`, +`direct_send.already_failed` or `direct_send.already_sending`; the last is a LinkedIn send made for +later that Reply is handing to the account's queue or that waits or runs there, even while +`direct-send get` still reads it `queued`. A reference Reply has no send for, a send of another team +included, is `direct_send.not_found`, and an email send made by a teammate this user may not act for +is `direct_send.not_owned`, to a read and a cancel alike. A `503` that Reply answers with +`directSend.cancelNotConfirmed` is `direct_send.cancel_not_confirmed` (exit 1): Reply could not +confirm the cancel, and says the send is still queued or waiting for its schedule, so run the cancel +again, as Reply asks; `retry_after` carries Reply's `Retry-After` when it sends one. Any other `5xx` +to a cancel stays `outcome.unknown` (exit 3). `reply inbox changes` reads the inbox feed forward. Each page holds the threads whose latest message, inbound or outbound, changed, oldest first and as Reply gives them, with `has_more` and a `cursor`. diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index c6e3845..6852ce3 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -33,7 +33,8 @@ describe('operations/commands', ()=>{ it('direct-send get and cancel each take one reference and no flag, and list the refusals Reply gives each', ()=>{ const expected: [string, string[], boolean][] = [ ['get', ['direct_send.not_found', 'direct_send.not_owned'], false], - ['cancel', ['direct_send.not_found', 'direct_send.not_owned', 'direct_send.already_sent', 'direct_send.already_failed'], true], + ['cancel', ['direct_send.not_found', 'direct_send.not_owned', 'direct_send.already_sent', 'direct_send.already_failed', + 'direct_send.already_sending', 'direct_send.cancel_not_confirmed'], true], ]; for (const [name, codes, write] of expected) { @@ -45,18 +46,34 @@ describe('operations/commands', ()=>{ expect(text, name).toContain(codes.map(code=>` ${code}\n`).join('')); expect(text.includes('outcome.unknown'), name).toBe(write); expect(flat, name).toContain('The reference is Reply\'s, from the answer of a send made with --send-after'); - expect(flat, name).toContain('state is Reply\'s own word: queued or sending is not yet sent, then sent, failed or cancelled'); + expect(flat, name).toContain('state is Reply\'s own word: queued, waitingForSchedule or sending is not yet sent, then sent, failed or cancelled'); + expect(flat, name).toContain('A failed send may carry no failure_code: it is then null'); expect(flat, name).toContain('A Reply without this route answers reply.refused with status 404 and no reply_code'); - expect(flat, name).toContain('email- or linkedin-, the form Reply\'s route takes'); + expect(flat, name).toContain('email-, linkedin- or linkedin-scheduled-, the form Reply\'s route takes'); expect(flat, name).toContain('any other form is refused before any call (usage.reference, exit 2), and nothing else is read from it'); expect(flat, name).toContain('a reference of any other form never leaves the CLI, so that 404 means this Reply has no such route'); + expect(flat, name).toContain('direct_send.not_found is a reference that Reply has no send for, a send of another team ' + + 'included. direct_send.not_owned is an email send made by a teammate this user may not act for'); expect(flat, name).not.toContain('step up'); - expect(c.registeredArguments[0].description, name).toContain('email- or linkedin-'); + expect(c.registeredArguments[0].description, name).toContain('email-, linkedin- or linkedin-scheduled-'); expect(flat, name).toContain('failure_code, missing_variables, rendered_subject and rendered_body are added only when Reply gives them'); expect(flat, name).toContain('failure_reason is a sentence for a person, never parsed; failure_code is Reply\'s code for the failure'); + expect(flat, name).toContain('estimated_send_at is added only when Reply gives it, and is when Reply expects a send waiting ' + + 'for its schedule\'s next opening to go out'); + expect(flat, name).toContain('Reply sets estimated_send_at in waitingForSchedule only and gives it null in every other state; ' + + 'it is null in waitingForSchedule too when the schedule does not open within 30 days of the moment the send waits ' + + 'from: its --send-after, or now once that has passed'); + expect(flat, name).not.toContain('that null says nothing'); } - expect(help_of(sub(direct_send_command, 'cancel')).replace(/\s+/g, ' ')) - .toContain('Cancelling a send already cancelled answers it again, so running it again is safe'); + const cancel = help_of(sub(direct_send_command, 'cancel')).replace(/\s+/g, ' '); + expect(cancel).toContain('Cancelling a send already cancelled answers it again, so running it again is safe'); + expect(cancel).toContain('direct_send.already_sent, direct_send.already_failed and direct_send.already_sending mean the send ' + + 'was past cancelling; nothing changed'); + expect(cancel).toContain('direct_send.already_sending is a LinkedIn send made for later that Reply is handing to the ' + + 'account\'s queue or that waits or runs there, even while direct-send get still reads it queued'); + expect(cancel).toContain('direct_send.cancel_not_confirmed is a 503 from Reply that could not confirm the cancel: the send ' + + 'is still queued or waiting for its schedule, so run the cancel again, as Reply asks; retry_after carries Reply\'s Retry-After when it sends one. Any other 5xx ' + + 'is outcome.unknown (exit 3)'); }); it('schedule list takes no flag and no id, and says how a time zone, a weekday, a time and a state are written', ()=>{ @@ -244,11 +261,12 @@ describe('operations/commands', ()=>{ // says sent_at is. const IMPORT = ['contact.not_unique', 'contact.invalid_email', 'contact.invalid_linkedin_url', 'account.contact_limit_reached']; const LINKEDIN = ['contact.not_found', ...IMPORT, 'contact.already_held', 'contact.no_linkedin_profile', 'linkedin.account_not_found', - 'linkedin.feature_disabled', 'linkedin.account_inactive', 'linkedin.invalid_cookie']; + 'linkedin.feature_disabled', 'linkedin.account_inactive', 'linkedin.invalid_cookie', 'schedule.not_found', 'schedule.no_slot', + 'contact.time_zone_missing']; const SENT_AT_AS_GIVEN = 'sentAtUtc as Reply gives them, each null when it gives none; the CLI adds no time of its own'; const DIRECT_SENDS: [string, string, string[], string][] = [ ['send-email', '--email-account-id', ['contact.not_found', ...IMPORT, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted', - 'contact.missing_variables', 'contact.rendering_failed'], + 'contact.missing_variables', 'contact.rendering_failed', 'schedule.not_found', 'schedule.no_slot', 'contact.time_zone_missing'], 'sent_at is always null; the CLI adds none of its own'], ['linkedin-connect', '--linkedin-account-id', [...LINKEDIN, 'linkedin.not_connected', 'linkedin.limit_reached', 'linkedin.message_too_long', 'linkedin.missing_variables'], SENT_AT_AS_GIVEN], @@ -274,7 +292,8 @@ describe('operations/commands', ()=>{ { const c = sub(contact_command, name); expect(flags(c), name).toEqual([...CONTACT_FLAGS, account_flag, '--message', - ...(name === 'send-email' ? ['--track-links', '--track-opens'] : []), '--send-after', '--schedule-id', '--idempotency-key']); + ...(name === 'send-email' ? ['--track-links', '--track-opens'] : []), '--send-after', '--schedule-id', '--idempotency-key', + '--use-contact-time-zone', '--no-use-contact-time-zone', ...(name === 'send-email' ? [] : ['--retry-window-minutes'])]); const text = help_of(c); const flat = text.replace(/\s+/g, ' '); expect(text, text).toContain('--message -'); @@ -292,8 +311,29 @@ describe('operations/commands', ()=>{ expect(flat, text).toContain('read from stdin only'); // A send for later: what status and state each say, and what an older Reply does with the flags. expect(flat, text).toContain('status "sent" means Reply took the send; state, when Reply gives it, says whether it has gone ' - + 'out: queued or sending is not yet, then sent, failed or cancelled'); + + 'out: queued, waitingForSchedule or sending is not yet, then sent, failed or cancelled'); expect(flat, text).toContain('direct-send get reads it later, and direct-send cancel stops one not yet sent'); + // Every send takes a schedule and its time zone; only the LinkedIn sends take a retry window and map the refusals. + const linkedin = name !== 'send-email'; + expect(flat, text).toContain('A send timed by --schedule-id may answer state waitingForSchedule'); + expect(flat, text).toContain('send_after is then left out, and estimated_send_at is when Reply expects to send it.'); + expect(flat, text).toContain('Reply sets estimated_send_at in waitingForSchedule only and gives it null in every other state; ' + + 'it is null in waitingForSchedule too when the schedule does not open within 30 days of the moment the send waits ' + + 'from: its --send-after, or when Reply took it'); + expect(flat, text).not.toContain('that null says nothing'); + expect(flat, text).toContain('--use-contact-time-zone sends useContactTimeZone true: the schedule\'s windows are read in the ' + + 'contact\'s time zone; --no-use-contact-time-zone sends false, the schedule\'s own zone; with neither, the schedule\'s ' + + 'own setting holds. Reply takes it only with --schedule-id, and answers it otherwise with errors[] (reply.invalid_request)'); + expect(flat.includes('--retry-window-minutes is how long Reply keeps trying to send it once it is due, 1 to 4320 ' + + 'minutes (Reply\'s default is 90); one outside that is refused before any call (usage.range)'), text).toBe(linkedin); + expect(flat.includes('Reply takes it only with --schedule-id or --send-after'), text).toBe(linkedin); + // A Reply without the scheduler ignores both on a LinkedIn send and sends at once; no refusal stands for it. + expect(flat, text).not.toContain('before its scheduler'); + // A send Reply cannot time is refused under the same three codes on every route. + expect(flat, text).toContain('schedule.not_found is a --schedule-id naming no schedule this account can read, schedule.no_slot a ' + + 'schedule with no active day that has a time range, so it never opens, and contact.time_zone_missing a contact without the time zone ' + + '--use-contact-time-zone reads it in; none sends anything'); + expect(flat, text).not.toContain('as reply_code'); expect(flat, text).toContain('An answer without state comes from a Reply that does not know --send-after and --schedule-id'); expect(flat, text).toContain('--idempotency-key goes as the Idempotency-Key header'); expect(flat, text).toContain('A Reply that knows the header answers a repeat with the same key with the send the key first made; while that one is still ' diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index 08b62c1..bd69535 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -74,6 +74,13 @@ describe('contact send-email', ()=>{ [json({title: 'Validation failed', errors: [{pointer: '/subject', detail: '\'subject\' must not be empty.'}]}, 400), 'reply.invalid_request', undefined], [json({code: 'contact.somethingElse'}, 400), 'reply.refused', 'contact.somethingElse'], + // An email Reply cannot time maps to the codes a LinkedIn send's refusals of the same meaning map to, each + // read only under the status Reply publishes it with. + [json({code: 'contact.scheduleNotFound'}, 404), 'schedule.not_found', 'contact.scheduleNotFound'], + [json({code: 'contact.scheduleHasNoSlot'}, 409), 'schedule.no_slot', 'contact.scheduleHasNoSlot'], + [json({code: 'contact.contactTimeZoneMissing'}, 409), 'contact.time_zone_missing', 'contact.contactTimeZoneMissing'], + [json({code: 'contact.scheduleNotFound'}, 400), 'reply.refused', 'contact.scheduleNotFound'], + [json({code: 'contact.contactTimeZoneMissing'}, 404), 'reply.refused', 'contact.contactTimeZoneMissing'], ]; for (const [res, code, reply_code] of cases) { @@ -156,6 +163,11 @@ describe('the LinkedIn sends', ()=>{ [['linkedin-inmail', {subject: SUBJECT, body: TEXT}], 400, 'directLinkedIn.noInMailCredits', 'linkedin.no_inmail_credits'], [['linkedin-voice', {script: SCRIPT}], 400, 'directLinkedIn.voiceProfileMissing', 'linkedin.voice_profile_missing'], [['linkedin-voice', {script: SCRIPT}], 400, 'directLinkedIn.voiceTooLong', 'linkedin.voice_too_long'], + [message, 404, 'directLinkedIn.scheduleNotFound', 'schedule.not_found'], + [['linkedin-connect', {note: NOTE}], 409, 'directLinkedIn.scheduleHasNoSlot', 'schedule.no_slot'], + [['linkedin-voice', {script: SCRIPT}], 409, 'directLinkedIn.contactTimeZoneMissing', 'contact.time_zone_missing'], + [message, 400, 'directLinkedIn.scheduleNotFound', 'reply.refused'], + [message, 404, 'directLinkedIn.contactTimeZoneMissing', 'reply.refused'], // Reply's code is read only under the status it publishes it with. [message, 400, 'directLinkedIn.notConnected', 'reply.refused'], [message, 403, 'directLinkedIn.somethingElse', 'access.denied'], @@ -171,6 +183,10 @@ describe('the LinkedIn sends', ()=>{ expect(shown(e), shown(e)).not.toContain('Marta'); expect(mock_fetch, `${name} ${reply_code}`).toHaveBeenCalledTimes(1); } + mock_fetch.mockReset(); + answer(json({status: 409, code: 'directLinkedIn.scheduleHasNoSlot'}, 409)); + expect((await failure('linkedin-message', {body: TEXT}, LINKEDIN_OPTS) as {title?: string}).title) + .toBe('The sending schedule has no active day with a time range, so it never opens; nothing was sent.'); }); it('reads contact-not-found, the limits and already-connected only under the status Reply publishes each with', async()=>{ @@ -674,6 +690,25 @@ describe('a send for later', ()=>{ }); }); + it('adds estimated_send_at to a send waiting for its schedule\'s opening, a null kept as null, only when Reply gives it', async()=>{ + const waiting = {reference: 'linkedin-scheduled-77', state: 'waitingForSchedule', sendAfter: null, linkedInActivityId: null, sentAtUtc: null}; + const cases: [unknown, Record][] = [ + ['2026-11-04T09:00:00Z', {estimated_send_at: '2026-11-04T09:00:00Z'}], + [null, {estimated_send_at: null}], + [undefined, {}], + [7, {}], + ]; + for (const [estimatedSendAt, added] of cases) + { + mock_fetch.mockReset(); + answer(json({...waiting, estimatedSendAt})); + expect(await run('linkedin-message', {body: TEXT}, {...LINKEDIN_OPTS, scheduleId: '41'}), JSON.stringify(estimatedSendAt)).toStrictEqual({ + status: 'sent', contact_id: 456, contact_created: false, activity_id: null, sent_at: null, + reference: 'linkedin-scheduled-77', state: 'waitingForSchedule', ...added, + }); + } + }); + it('adds the rendered subject and body of an email sent inside the request, each only when Reply gives it', async()=>{ answer(accepted('send-email', {renderedSubject: 'Quick question, Marta', renderedBody: '

Hi Marta

', state: 'sent'})); expect(await run('send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS)).toStrictEqual({ @@ -713,6 +748,67 @@ describe('a send for later', ()=>{ expect(mock_fetch).not.toHaveBeenCalled(); }); + it('a LinkedIn send carries useContactTimeZone, true or false, and retryWindowMinutes only when given, as Reply takes them', async()=>{ + const cases: [Partial, Record][] = [ + [{useContactTimeZone: true}, {useContactTimeZone: true}], + [{useContactTimeZone: false}, {useContactTimeZone: false}], + [{retryWindowMinutes: '1'}, {retryWindowMinutes: 1}], + [{retryWindowMinutes: ' 4320 '}, {retryWindowMinutes: 4320}], + [{useContactTimeZone: true, retryWindowMinutes: '90'}, {useContactTimeZone: true, retryWindowMinutes: 90}], + [{}, {}], + ]; + for (const [name, message, opts] of SENDS.filter(([n])=>n !== 'send-email')) + { + for (const [extra, carried] of cases) + { + mock_fetch.mockReset(); + answer(accepted(name, {})); + await run(name, message, {...opts, ...LATER, ...extra}); + const body = sent()[0].body as Record; + const label = `${name} ${JSON.stringify(extra)}`; + expect(body.scheduleId, label).toBe(41); + expect(Object.fromEntries(Object.entries(body).filter(([k])=>k === 'useContactTimeZone' || k === 'retryWindowMinutes')), label) + .toStrictEqual(carried); + } + } + }); + + it('refuses a retry window outside 1 to 4320 minutes before any call, and leaves the rules between the fields to Reply', async()=>{ + for (const [name, message, opts] of SENDS.filter(([n])=>n !== 'send-email')) + { + for (const raw of ['0', '4321', '-5', '1.5', 'ninety', '', '90m']) + { + const e = await failure(name, message, {...opts, retryWindowMinutes: raw}); + expect(e, `${name} ${JSON.stringify(raw)}`).toMatchObject({code: 'usage.range', exit_code: 2}); + } + } + expect(mock_fetch).not.toHaveBeenCalled(); + // Without --schedule-id or --send-after either goes to Reply as given, for Reply to refuse with errors[]. + answer(json({errors: [{pointer: '/useContactTimeZone', detail: 'Only with scheduleId.'}]}, 400)); + const e = await failure('linkedin-message', {body: TEXT}, {...LINKEDIN_OPTS, useContactTimeZone: true, retryWindowMinutes: '30'}); + expect(sent()[0].body).toMatchObject({useContactTimeZone: true, retryWindowMinutes: 30}); + expect(e).toMatchObject({code: 'reply.invalid_request', exit_code: 1, details: {fields: ['useContactTimeZone']}}); + }); + + it('a direct email carries useContactTimeZone, true or false, only when given, and never a retry window', async()=>{ + const cases: [Partial, Record][] = [ + [{useContactTimeZone: true}, {useContactTimeZone: true}], + [{useContactTimeZone: false, retryWindowMinutes: '30'}, {useContactTimeZone: false}], + [{retryWindowMinutes: '30'}, {}], + [{}, {}], + ]; + for (const [extra, carried] of cases) + { + mock_fetch.mockReset(); + answer(accepted('send-email', {})); + await run('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...LATER, ...extra}); + const body = sent()[0].body as Record; + expect(body.scheduleId, JSON.stringify(extra)).toBe(41); + expect(Object.fromEntries(Object.entries(body).filter(([k])=>k === 'useContactTimeZone' || k === 'retryWindowMinutes')), + JSON.stringify(extra)).toStrictEqual(carried); + } + }); + it('a key does not make a lost answer safe to repeat: a Reply that ignores the header would send it twice', async()=>{ mock_fetch.mockRejectedValueOnce(lost_connection()); const e = await failure('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...LATER}); diff --git a/src/__tests__/operations/direct-sends.test.ts b/src/__tests__/operations/direct-sends.test.ts index 0abbd10..53176cc 100644 --- a/src/__tests__/operations/direct-sends.test.ts +++ b/src/__tests__/operations/direct-sends.test.ts @@ -1,5 +1,5 @@ import {describe, it, expect, beforeEach} from 'vitest'; -import {mock_fetch, json, ctx, sent, answer, capture} from './helpers'; +import {mock_fetch, json, ctx, sent, answer, capture, instant_timers, real_timers} from './helpers'; import {handle_direct_send_get, handle_direct_send_cancel} from '../../operations/direct-sends'; beforeEach(()=>{ mock_fetch.mockReset(); }); @@ -68,6 +68,56 @@ describe('direct-send get', ()=>{ } }); + it('adds estimated_send_at, Reply\'s estimatedSendAt, as text or null and only when Reply gives it, to get and cancel', async()=>{ + const WAITING = {...QUEUED, reference: 'linkedin-scheduled-77', channel: 'linkedin', state: 'waitingForSchedule', sendAfter: null}; + const cases: [unknown, Record][] = [ + ['2026-11-04T09:00:00Z', {estimated_send_at: '2026-11-04T09:00:00Z'}], + [null, {estimated_send_at: null}], + ]; + for (const fn of [get, cancel]) + { + for (const [estimatedSendAt, added] of cases) + { + mock_fetch.mockReset(); + answer(json({...WAITING, estimatedSendAt})); + expect(await fn('linkedin-scheduled-77'), JSON.stringify(estimatedSendAt)).toStrictEqual({ + reference: 'linkedin-scheduled-77', channel: 'linkedin', contact_id: 456, state: 'waitingForSchedule', send_after: null, + ...added, sent_at: null, message_id: null, failure_reason: null, cancelled_at: null, + }); + } + for (const odd of [undefined, 7, ['2026-11-04T09:00:00Z']]) + { + mock_fetch.mockReset(); + answer(json({...WAITING, estimatedSendAt: odd})); + expect(await fn('linkedin-scheduled-77'), JSON.stringify(odd)).not.toHaveProperty('estimated_send_at'); + } + } + }); + + it('reads a LinkedIn send through the states Reply\'s scheduler gives it, and a failure with or without its code', async()=>{ + const LINKEDIN = {...QUEUED, reference: 'linkedin-scheduled-77', channel: 'linkedin'}; + const cases: [Record, Record][] = [ + [{state: 'waitingForSchedule', sendAfter: null, estimatedSendAt: null}, {state: 'waitingForSchedule', send_after: null}], + [{state: 'sending'}, {state: 'sending'}], + [{state: 'failed', failureReason: 'The send failed.', failureCode: null}, {state: 'failed', failure_code: null}], + [{state: 'failed', failureCode: 'directSend.dispatchWindowMissed'}, {state: 'failed', failure_code: 'directSend.dispatchWindowMissed'}], + [{state: 'failed', failureCode: 'directSend.dispatchInterrupted'}, {state: 'failed', failure_code: 'directSend.dispatchInterrupted'}], + [{state: 'failed', failureCode: 'directLinkedIn.notConnected'}, {state: 'failed', failure_code: 'directLinkedIn.notConnected'}], + [{state: 'failed', failureCode: 'directLinkedIn.contactNotFound'}, {state: 'failed', failure_code: 'directLinkedIn.contactNotFound'}], + [{state: 'failed', failureCode: 'directLinkedIn.scheduleNotFound'}, {state: 'failed', failure_code: 'directLinkedIn.scheduleNotFound'}], + [{state: 'failed', failureCode: 'directLinkedIn.contactTimeZoneMissing'}, + {state: 'failed', failure_code: 'directLinkedIn.contactTimeZoneMissing'}], + [{state: 'failed', failureCode: 'directLinkedIn.aCodeNotYetKnown'}, {state: 'failed', failure_code: 'directLinkedIn.aCodeNotYetKnown'}], + [{state: 'cancelled', cancelledAt: '2026-11-02T09:15:00Z'}, {state: 'cancelled', cancelled_at: '2026-11-02T09:15:00Z'}], + ]; + for (const [given, read] of cases) + { + mock_fetch.mockReset(); + answer(json({...LINKEDIN, ...given})); + expect(await get('linkedin-scheduled-77'), JSON.stringify(given)).toMatchObject({reference: 'linkedin-scheduled-77', ...read}); + } + }); + it('gives missing_variables only as a list of names, and the others only as text: anything else is left out', async()=>{ for (const missing of [[], ['FirstName']]) { @@ -106,7 +156,35 @@ describe('direct-send get', ()=>{ { const e = await failure(()=>fn(reference, ctx(), {})); expect(e, `${fn.name} ${JSON.stringify(reference)}`).toMatchObject({code: 'usage.reference', exit_code: 2}); - expect((e as Error).message, JSON.stringify(reference)).toContain('email- or linkedin-'); + expect((e as Error).message, JSON.stringify(reference)).toContain('email-, linkedin- or linkedin-scheduled-'); + } + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('sends a deferred LinkedIn send\'s reference, linkedin-scheduled-, as given to get and cancel', async()=>{ + for (const reference of ['linkedin-scheduled-1', 'linkedin-scheduled-1042', 'linkedin-scheduled-9999999999']) + { + for (const [fn, suffix] of [[get, ''], [cancel, '/cancel']] as const) + { + mock_fetch.mockReset(); + answer(json({...QUEUED, channel: 'linkedin', reference})); + expect((await fn(reference)).reference, reference).toBe(reference); + expect(sent()[0].url, reference).toBe(`https://api/v3/direct-sends/${reference}${suffix}`); + } + } + }); + + it('refuses a malformed scheduled reference before any call, by the same one-spelling rule', async()=>{ + const malformed = ['linkedin-scheduled-0', 'linkedin-scheduled-01', 'linkedin-scheduled-12345678901', 'linkedin-scheduled-', + 'linkedin-scheduled', 'linkedin-scheduled--1', 'linkedin-scheduled-1a', 'LINKEDIN-SCHEDULED-1', 'email-scheduled-1', + 'scheduled-1', 'linkedin-scheduled-scheduled-1', ' linkedin-scheduled-1', 'linkedin-scheduled-1/cancel']; + for (const reference of malformed) + { + for (const fn of [handle_direct_send_get, handle_direct_send_cancel]) + { + expect(await failure(()=>fn(reference, ctx(), {})), `${fn.name} ${JSON.stringify(reference)}`) + .toMatchObject({code: 'usage.reference', exit_code: 2}); } } expect(mock_fetch).not.toHaveBeenCalled(); @@ -178,13 +256,15 @@ describe('direct-send cancel', ()=>{ expect(mock_fetch).toHaveBeenCalledTimes(2); }); - it('maps Reply\'s four refusals of a cancel, each definite', async()=>{ + it('maps Reply\'s five refusals of a cancel, each definite', async()=>{ const cases: [Response, string][] = [ [json({code: 'directSend.notFound'}, 404), 'direct_send.not_found'], [json({code: 'directSend.notOwned'}, 403), 'direct_send.not_owned'], [json({code: 'directSend.alreadySent'}, 409), 'direct_send.already_sent'], [json({code: 'directSend.alreadyFailed'}, 409), 'direct_send.already_failed'], + [json({code: 'directSend.alreadySending'}, 409), 'direct_send.already_sending'], [json({code: 'directSend.alreadySent'}, 400), 'reply.refused'], + [json({code: 'directSend.alreadySending'}, 400), 'reply.refused'], ]; for (const [res, code] of cases) { @@ -210,6 +290,8 @@ describe('direct-send cancel', ()=>{ const answers: [string, ()=>void][] = [ ['lost answer', ()=>{ mock_fetch.mockRejectedValueOnce(lost_connection()); }], ['503', ()=>answer(json({title: 'Service Unavailable'}, 503))], + ['503 with another code', ()=>answer(json({code: 'directSend.somethingElse'}, 503))], + ['500 with the unconfirmed cancel\'s code', ()=>answer(json({code: 'directSend.cancelNotConfirmed'}, 500))], ['unreadable 200', ()=>answer(json('ok', 200))], ]; for (const [label, give] of answers) @@ -223,6 +305,38 @@ describe('direct-send cancel', ()=>{ } }); + it('a 503 directSend.cancelNotConfirmed is direct_send.cancel_not_confirmed (exit 1), made once, says the send is still ' + + 'waiting and to cancel again, and passes on Reply\'s wait', async()=>{ + const cases: [Record, number | undefined][] = [[{}, undefined], [{'Retry-After': '5'}, 5]]; + for (const [headers, retry_after] of cases) + { + mock_fetch.mockReset(); + answer(json({code: 'directSend.cancelNotConfirmed', detail: 'The cancel could not be confirmed.'}, 503, headers)); + const e = await failure(()=>handle_direct_send_cancel('linkedin-scheduled-77', ctx(), {})); + expect(e, JSON.stringify(headers)).toMatchObject({ + code: 'direct_send.cancel_not_confirmed', exit_code: 1, status: 503, reply_code: 'directSend.cancelNotConfirmed', + detail: 'The cancel could not be confirmed.', + }); + expect((e as {retry_after?: number}).retry_after, JSON.stringify(headers)).toBe(retry_after); + expect((e as {title?: string}).title).toBe('Reply could not confirm the cancel; the send is still waiting to go out.'); + expect((e as {hint?: string}).hint).toBe('Reply says the send is still queued or waiting for its schedule: run the ' + + 'cancel again, as Reply asks; running it again is safe.'); + expect(mock_fetch).toHaveBeenCalledTimes(1); + } + }); + + it('reads an unconfirmed cancel only on a cancel: a read answering its code maps as any other 5xx', async()=>{ + instant_timers(); + try { + mock_fetch.mockImplementation(()=>Promise.resolve(json({code: 'directSend.cancelNotConfirmed'}, 503))); + expect(await failure(()=>handle_direct_send_get('linkedin-scheduled-77', ctx(), {}))) + .toMatchObject({code: 'reply.unavailable', exit_code: 1}); + } finally { + real_timers(); + mock_fetch.mockReset(); + } + }); + it('refuses a blank reference before any call', async()=>{ expect(await failure(()=>handle_direct_send_cancel(' ', ctx(), {}))).toMatchObject({code: 'usage.reference', exit_code: 2}); expect(mock_fetch).not.toHaveBeenCalled(); diff --git a/src/operations/commands.ts b/src/operations/commands.ts index d67ed67..b28d421 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -298,22 +298,22 @@ const later_options = (c: Command): Command=>c .option('--idempotency-key ', 'Your own key for this send, sent as the Idempotency-Key header'); const LATER = 'With --send-after Reply holds the send until that moment, given with its offset and sent to Reply in UTC; a moment\n' - + 'without an offset is refused (usage.date). --schedule-id names the sending schedule Reply times the send by. The answer\n' - + 'then adds Reply\'s reference, send_after and state, each only when Reply gives it: status "sent" means Reply took the\n' - + 'send; state, when Reply gives it, says whether it has gone out: queued or sending is not yet, then sent, failed or\n' - + 'cancelled. direct-send get reads it later, and direct-send cancel stops one not yet sent. An\n' - + 'answer without state comes from a Reply that does not know --send-after and --schedule-id: it sent at once, as\n' - + 'without them. --idempotency-key goes as the Idempotency-Key header, never in the body. A Reply that knows the header\n' - + 'answers a repeat with the same key with the send the key first made; while that one is still being made the answer\n' - + 'is idempotency_key.in_use, and the same key on a different send is idempotency_key.reused. Neither sends anything.\n' - + 'A repeat of a send given a person\'s fields answers contact.already_held first, since the first one created the\n' - + 'contact: that is safe too, as nothing is sent twice. idempotency_key.reused names the send the key was first taken\n' - + 'for in details: reference, state and send_after, each only when Reply gives it. Any other refusal of a send Reply\n' - + 'already holds names that send the same way, beside the refusal\'s own details; its code is the refusal\'s own.\n' - + 'A 400 to the send with neither a code nor errors[] is Reply failing while it made the send: like a 5xx or a lost\n' - + 'answer, it is outcome.unknown (exit 3). So is a 400 directLinkedIn.unknown to a LinkedIn send, Reply\'s answer when\n' - + 'it failed while making the send or could not map the provider\'s answer; Reply\'s code is kept in reply_code. A 400\n' - + 'with errors[] is reply.invalid_request, and nothing was sent.\n'; + + 'without an offset is refused (usage.date). --schedule-id names the sending schedule Reply times the send by. The\n' + + 'answer then adds Reply\'s reference, send_after and state, each only when Reply gives it: status "sent" means Reply\n' + + 'took the send; state, when Reply gives it, says whether it has gone out: queued, waitingForSchedule or sending is not\n' + + 'yet, then sent, failed or cancelled. direct-send get reads it later, and direct-send cancel \n' + + 'stops one not yet sent. An answer without state comes from a Reply that does not know --send-after and --schedule-id:\n' + + 'it sent at once, as without them. --idempotency-key goes as the Idempotency-Key header, never in the body. A Reply\n' + + 'that knows the header answers a repeat with the same key with the send the key first made; while that one is still\n' + + 'being made the answer is idempotency_key.in_use, and the same key on a different send is idempotency_key.reused.\n' + + 'Neither sends anything. A repeat of a send given a person\'s fields answers contact.already_held first, since the first\n' + + 'one created the contact: that is safe too, as nothing is sent twice. idempotency_key.reused names the send the key was\n' + + 'first taken for in details: reference, state and send_after, each only when Reply gives it. Any other refusal of a\n' + + 'send Reply already holds names that send the same way, beside the refusal\'s own details; its code is the refusal\'s\n' + + 'own. A 400 to the send with neither a code nor errors[] is Reply failing while it made the send: like a 5xx or a lost\n' + + 'answer, it is outcome.unknown (exit 3). So is a 400 directLinkedIn.unknown to a LinkedIn send, Reply\'s answer when it\n' + + 'failed while making the send or could not map the provider\'s answer; Reply\'s code is kept in reply_code. A 400 with\n' + + 'errors[] is reply.invalid_request, and nothing was sent.\n'; // The refusals of a send's key, the same on every direct send, after each send's own. const KEY_CODES = ['idempotency_key.in_use', 'idempotency_key.reused']; @@ -324,17 +324,48 @@ const piped_send = (command: string, contact: string, message: string, flags: st const ANN_EMAIL = '{"email":"ann@example.com","first_name":"Ann"}'; const ANN_PROFILE = '{"linkedin_url":"https://www.linkedin.com/in/ann-example","first_name":"Ann"}'; -later_options(add_contact_options(contact_command.command('send-email'), true) +// The time zone a send timed by a schedule is read in, which every send takes. Without either flag nothing is sent, so +// the schedule's own setting holds. +const time_zone_options = (c: Command): Command=>c + .option('--use-contact-time-zone', 'Read the schedule\'s windows in the contact\'s time zone (with --schedule-id)') + .option('--no-use-contact-time-zone', 'Read the schedule\'s windows in the schedule\'s own time zone (with --schedule-id)'); + +// The flags Reply's LinkedIn sends take for a send made later: the time zone, and the retry window only they take. +const scheduler_options = (c: Command): Command=>time_zone_options(c) + .option('--retry-window-minutes ', 'How long Reply keeps trying once the send is due, 1 to 4320 (Reply\'s default: 90)'); + +// What a send timed by a schedule answers while it waits for the schedule's next opening, the time zone it is read in, and +// the refusals of one Reply cannot time. +const SCHEDULED = 'A send timed by --schedule-id may answer state waitingForSchedule, held for the schedule\'s next opening: send_after is\n' + + 'then left out, and estimated_send_at is when Reply expects to send it. Reply sets estimated_send_at in\n' + + 'waitingForSchedule only and gives it null in every other state; it is null in waitingForSchedule too when the schedule\n' + + 'does not open within 30 days of the moment the send waits from: its --send-after, or when Reply took it. It is added\n' + + 'only when Reply gives it. --use-contact-time-zone sends useContactTimeZone true: the schedule\'s windows are read in\n' + + 'the contact\'s time zone; --no-use-contact-time-zone sends false, the schedule\'s own zone; with neither, the schedule\'s\n' + + 'own setting holds. Reply takes it only with --schedule-id, and answers it otherwise with errors[]\n' + + '(reply.invalid_request). schedule.not_found is a --schedule-id naming no schedule this account can read,\n' + + 'schedule.no_slot a schedule with no active day that has a time range, so it never opens, and contact.time_zone_missing\n' + + 'a contact without the time zone --use-contact-time-zone reads it in; none sends anything.\n'; + +// The codes of a send Reply cannot time, the same on every route. +const SCHEDULE_CODES = ['schedule.not_found', 'schedule.no_slot', 'contact.time_zone_missing']; + +// The retry window only a LinkedIn send takes. +const LINKEDIN_SCHEDULED = '--retry-window-minutes is how long Reply keeps trying to send it once it is due, 1 to 4320\n' + + 'minutes (Reply\'s default is 90); one outside that is refused before any call (usage.range). Reply takes it only with\n' + + '--schedule-id or --send-after, and answers it otherwise with errors[] (reply.invalid_request).\n'; + +time_zone_options(later_options(add_contact_options(contact_command.command('send-email'), true) .option('--email-account-id ', 'The mailbox to send from (see `account list`)') .option('--message ', 'Only -: the email {subject, body} as JSON on stdin') .option('--track-links', 'Track the links in the email (off unless given)') - .option('--track-opens', 'Track the opens of the email (off unless given)')) + .option('--track-opens', 'Track the opens of the email (off unless given)'))) .description('Send one email to a contact now, outside any sequence, from the mailbox you name') .addHelpText('after', help( [`echo '{"subject":"Quick question","body":"

Hi Ann, does Tuesday work?

"}' | ${P} contact send-email --contact-id 456 --email-account-id 12 --message -`, piped_send('send-email', ANN_EMAIL, '{"subject":"Quick question","body":"

Hi Ann

"}', '--email-account-id 12')], ['contact.not_found', ...IMPORT_CODES, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted', - 'contact.missing_variables', 'contact.rendering_failed', ...KEY_CODES], true, + 'contact.missing_variables', 'contact.rendering_failed', ...SCHEDULE_CODES, ...KEY_CODES], true, 'Result: {"status":"sent","contact_id","contact_created","message_id","sent_at","reply_status"}: sent means Reply\n' + 'accepted the email, and reply_status is Reply\'s own word for it (new or sent). message_id is Reply\'s messageId,\n' + 'null when it gives none. Reply\'s answer carries no time, so sent_at is always null; the CLI adds none of its own.\n' @@ -345,7 +376,7 @@ later_options(add_contact_options(contact_command.command('send-email'), true) + 'them; a send held for later has neither. contact.missing_variables names the variables Reply could not fill in\n' + 'details.missing_variables when Reply lists them, and contact.rendering_failed is a template Reply could not\n' + 'render, its message in detail. Neither sends anything.\n' - + LATER + SENT_TO('email', 'email'), + + LATER + SCHEDULED + SENT_TO('email', 'email'), SEND_TWICE('email'))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); @@ -355,7 +386,7 @@ later_options(add_contact_options(contact_command.command('send-email'), true) // The four LinkedIn sends share their flags, their first codes and the shape of their result. const LINKEDIN_SEND_CODES = [ 'contact.not_found', ...IMPORT_CODES, 'contact.already_held', 'contact.no_linkedin_profile', 'linkedin.account_not_found', - 'linkedin.feature_disabled', 'linkedin.account_inactive', 'linkedin.invalid_cookie', + 'linkedin.feature_disabled', 'linkedin.account_inactive', 'linkedin.invalid_cookie', ...SCHEDULE_CODES, ]; const LINKEDIN_SENT = '"contact_id","contact_created","activity_id","sent_at"}:\n' + 'activity_id and sent_at are Reply\'s linkedInActivityId and sentAtUtc as Reply gives them, each null when it gives\n' @@ -368,11 +399,11 @@ const linkedin_send = ( name: Exclude, description: string, message: string, examples: string[], codes: string[], extra: string, what: string, ): void=>{ - later_options(add_contact_options(contact_command.command(name), true) + scheduler_options(later_options(add_contact_options(contact_command.command(name), true) .option('--linkedin-account-id ', 'The LinkedIn account to send from (see `account list`)') - .option('--message ', `Only -: the ${message} as JSON on stdin`)) + .option('--message ', `Only -: the ${message} as JSON on stdin`))) .description(description) - .addHelpText('after', help(examples, [...LINKEDIN_SEND_CODES, ...codes, ...KEY_CODES], true, extra + LATER + SENT_TO('linkedin', what), + .addHelpText('after', help(examples, [...LINKEDIN_SEND_CODES, ...codes, ...KEY_CODES], true, extra + LATER + SCHEDULED + LINKEDIN_SCHEDULED + SENT_TO('linkedin', what), SEND_TWICE(what))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); @@ -581,18 +612,24 @@ const direct_send_command = new Command('direct-send').description('Read or canc const DIRECT_SEND = 'Result: {"reference","channel","contact_id","state","send_after","sent_at","message_id","failure_reason",\n' + '"cancelled_at"}, Reply\'s fields under these names, each null when Reply gives none. The reference is Reply\'s, from the\n' - + 'answer of a send made with --send-after: email- or linkedin-, the form Reply\'s route takes. A reference of\n' - + 'any other form is refused before any call (usage.reference, exit 2), and nothing else is read from it. state is\n' - + 'Reply\'s own word: queued or sending is not yet sent, then sent, failed or cancelled. failure_code,\n' - + 'missing_variables, rendered_subject and rendered_body are added only when Reply gives them: failure_reason is a\n' - + 'sentence for a person, never parsed; failure_code is Reply\'s code for the failure, the one to branch on.\n' + + 'answer of a send made with --send-after: email-, linkedin- or linkedin-scheduled-, the form Reply\'s route\n' + + 'takes. A reference of any other form is refused before any call (usage.reference, exit 2), and nothing else is read\n' + + 'from it. state is Reply\'s own word: queued, waitingForSchedule or sending is not yet sent, then sent, failed or\n' + + 'cancelled. failure_code, missing_variables, rendered_subject and rendered_body are added only when Reply gives them:\n' + + 'failure_reason is a sentence for a person, never parsed; failure_code is Reply\'s code for the failure, the one to\n' + + 'branch on. A failed send may carry no failure_code: it is then null, and failure_reason is all Reply says of it.\n' + 'missing_variables lists the template variables Reply could not fill, and rendered_subject and rendered_body are the\n' - + 'text as Reply filled it in. A Reply without this route answers reply.refused with status 404 and no reply_code; a\n' - + 'reference of any other form never leaves the CLI, so that 404 means this Reply has no such route.\n' - + 'direct_send.not_found is a reference that Reply has no send for.\n'; + + 'text as Reply filled it in. estimated_send_at is added only when Reply gives it, and is when Reply expects a send\n' + + 'waiting for its schedule\'s next opening to go out. Reply sets estimated_send_at in waitingForSchedule only and gives\n' + + 'it null in every other state; it is null in waitingForSchedule too when the schedule does not open within 30 days of\n' + + 'the moment the send waits from: its --send-after, or now once that has passed. A Reply without this route answers\n' + + 'reply.refused with status 404 and no reply_code; a reference of any other form never leaves the CLI, so that 404 means\n' + + 'this Reply has no such route.\n' + + 'direct_send.not_found is a reference that Reply has no send for, a send of another team included.\n' + + 'direct_send.not_owned is an email send made by a teammate this user may not act for.\n'; direct_send_command.command('get') - .argument('', 'The send\'s reference, email- or linkedin-, as a send made with --send-after answered it') + .argument('', 'The send\'s reference, email-, linkedin- or linkedin-scheduled-, as a send made with --send-after answered it') .description('One direct send as Reply holds it: whether it has gone out, when, and why it failed') .addHelpText('after', help([ex('direct-send get email-1001')], ['direct_send.not_found', 'direct_send.not_owned'], false, DIRECT_SEND)) .action(run(async(cmd)=>{ @@ -601,13 +638,18 @@ direct_send_command.command('get') })); direct_send_command.command('cancel') - .argument('', 'The send\'s reference, email- or linkedin-, as a send made with --send-after answered it') + .argument('', 'The send\'s reference, email-, linkedin- or linkedin-scheduled-, as a send made with --send-after answered it') .description('Stop a direct send that has not gone out yet') .addHelpText('after', help([ex('direct-send cancel email-1001')], - ['direct_send.not_found', 'direct_send.not_owned', 'direct_send.already_sent', 'direct_send.already_failed'], true, - DIRECT_SEND + 'The answer is the send as Reply now holds it, state cancelled. Cancelling a send already cancelled answers\n' - + 'it again, so running it again is safe. direct_send.already_sent and direct_send.already_failed mean the send\n' - + 'was past cancelling; nothing changed.\n')) + ['direct_send.not_found', 'direct_send.not_owned', 'direct_send.already_sent', 'direct_send.already_failed', + 'direct_send.already_sending', 'direct_send.cancel_not_confirmed'], true, + DIRECT_SEND + 'The answer is the send as Reply now holds it, state cancelled. Cancelling a send already cancelled answers it again,\n' + + 'so running it again is safe. direct_send.already_sent, direct_send.already_failed and direct_send.already_sending mean\n' + + 'the send was past cancelling; nothing changed. direct_send.already_sending is a LinkedIn send made for later that\n' + + 'Reply is handing to the account\'s queue or that waits or runs there, even while direct-send get still reads it queued.\n' + + 'direct_send.cancel_not_confirmed is a 503 from Reply that could not confirm the cancel: the send is still queued or\n' + + 'waiting for its schedule, so run the cancel again, as Reply asks; retry_after carries Reply\'s Retry-After when it\n' + + 'sends one. Any other 5xx is outcome.unknown (exit 3).\n')) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); await handle_direct_send_cancel(cmd.args[0], ctx, g); diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index 7d2b846..bc201f2 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -2,7 +2,7 @@ import {PROGRAM_NAME} from '../config'; import {Operation_error, Unknown_outcome_error, UsageError, type Ids} from '../utils/errors'; import {parse_retry_after} from '../utils/client'; import {call_reply, expect_object, refusal, is_object, reply_code_of, detail_of, open_session, type Answer} from './call'; -import {parse_id, parse_moment, parse_idempotency_key, LARGEST_SAFE_ID, type Op_globals} from './options'; +import {parse_id, parse_int_in, parse_moment, parse_idempotency_key, LARGEST_SAFE_ID, type Op_globals} from './options'; import {read_contact_input, type Contact_flags, type Contact_ref} from './contact-input'; import {contact_not_found, find_contact_by_address, import_contact, type Channel, type Ensured} from './contacts'; import {read_stdin_object, stdin_inputs} from './stdin-input'; @@ -13,6 +13,7 @@ type Direct_send_name = 'send-email' | 'linkedin-connect' | 'linkedin-message' | type Direct_send_opts = Contact_flags & { emailAccountId?: string; linkedinAccountId?: string; message?: string; sendAfter?: string; scheduleId?: string; idempotencyKey?: string; trackLinks?: boolean; trackOpens?: boolean; + useContactTimeZone?: boolean; retryWindowMinutes?: string; }; type Text = Record; @@ -93,8 +94,9 @@ const read_text = (name: Direct_send_name, send: Direct_send, source: string | u // A refusal Reply publishes, under the status it comes with; details reads what the problem body // carries beside its code, for the error output's details. +// waits passes on the Retry-After Reply sends with a refusal worth repeating. type Refusal = { - status: number; code: string; title: string; hint?: string; + status: number; code: string; title: string; hint?: string; waits?: boolean; details?: (body: Record) => Record | undefined; }; @@ -124,6 +126,17 @@ const TEMPLATE_REFUSALS: Record> = { linkedin: {}, }; +// The refusals of a send Reply cannot time, whichever route it went to. +const SCHEDULE_NOT_FOUND: Refusal = { + status: 404, code: 'schedule.not_found', title: 'Reply has no sending schedule by that id that this account can use, so nothing was sent.', +}; +const SCHEDULE_NO_SLOT: Refusal = { + status: 409, code: 'schedule.no_slot', title: 'The sending schedule has no active day with a time range, so it never opens; nothing was sent.', +}; +const TIME_ZONE_MISSING: Refusal = { + status: 409, code: 'contact.time_zone_missing', title: 'Reply holds no time zone for the contact to read the schedule in, so nothing was sent.', +}; + // Reply's refusals of a direct send, by status and code. Each one is definite: nothing was sent. const REFUSALS: Record = { 'contact.emailAccountNotFound': { @@ -174,6 +187,14 @@ const REFUSALS: Record = { 'directLinkedIn.voiceTooLong': { status: 400, code: 'linkedin.voice_too_long', title: 'The voice message would be longer than Reply allows, so nothing was sent.', }, + // A send timed by a schedule: refused when it is taken, before anything is held. The email route and + // the LinkedIn routes each name it in their own family, and both map to the code of its meaning. + 'directLinkedIn.scheduleNotFound': SCHEDULE_NOT_FOUND, + 'directLinkedIn.scheduleHasNoSlot': SCHEDULE_NO_SLOT, + 'directLinkedIn.contactTimeZoneMissing': TIME_ZONE_MISSING, + 'contact.scheduleNotFound': SCHEDULE_NOT_FOUND, + 'contact.scheduleHasNoSlot': SCHEDULE_NO_SLOT, + 'contact.contactTimeZoneMissing': TIME_ZONE_MISSING, }; const LIMITS: Record = {'directLinkedIn.dailyLimitReached': 'daily', 'directLinkedIn.weeklyLimitReached': 'weekly'}; @@ -210,6 +231,19 @@ const DIRECT_SEND_REFUSALS: Record = { 'directSend.alreadyFailed': { status: 409, code: 'direct_send.already_failed', title: 'The direct send has already failed, so it was not cancelled.', }, + 'directSend.alreadySending': { + status: 409, code: 'direct_send.already_sending', title: 'The direct send is already going out, so it was not cancelled.', + }, +}; +// A cancel Reply could not confirm: Reply says the send is still queued or waiting for its schedule and asks for the +// cancel again, so it is a refusal of its own rather than an outcome left unknown. Only a cancel answers it; a read +// answering this code maps as any other 5xx. +const CANCEL_REFUSALS: Record = { + 'directSend.cancelNotConfirmed': { + status: 503, code: 'direct_send.cancel_not_confirmed', title: 'Reply could not confirm the cancel; the send is still waiting to go out.', + hint: 'Reply says the send is still queued or waiting for its schedule: run the cancel again, as Reply asks; running it again is safe.', + waits: true, + }, }; // The refusal a table holds for this answer, under the status Reply publishes it with, or undefined. @@ -219,6 +253,7 @@ const known_refusal = (a: Answer, table: Record): Operation_err return known !== undefined && known.status === a.status ? new Operation_error(known.code, known.title, { status: a.status, reply_code, detail: detail_of(a), hint: known.hint, details: known.details?.(a.data as Record), + retry_after: known.waits === true ? parse_retry_after(a.headers['retry-after']) ?? undefined : undefined, }) : undefined; }; @@ -280,7 +315,12 @@ const positive_integer = (v: unknown): number | null=> const HELD_KEYS: [string, string][] = [['reference', 'reference'], ['sendAfter', 'send_after'], ['state', 'state']]; const LATER_KEYS: [string, string][] = [...HELD_KEYS, ['renderedSubject', 'rendered_subject'], ['renderedBody', 'rendered_body']]; -const later_of = (sent: Record): Record=>picked(LATER_KEYS, sent); +// When Reply expects a send waiting for its schedule's next opening to go out, as text, or null when no opening falls +// within 30 days of the moment the send waits from; left out when Reply gives neither, as a Reply before its scheduler does. +const estimated_of = (from: Record): Record=> + typeof from.estimatedSendAt === 'string' || from.estimatedSendAt === null ? {estimated_send_at: from.estimatedSendAt} : {}; + +const later_of = (sent: Record): Record=>({...picked(LATER_KEYS, sent), ...estimated_of(sent)}); // What the CLI answers for a send Reply took: the contact it went to, as the add commands name it, so // a caller can keep its id. Neither adds a time of its own: Reply's answer to a direct email carries @@ -354,6 +394,16 @@ const handle_direct_send = async( { later.scheduleId = parse_id(opts.scheduleId, '--schedule-id'); } + // Every send route takes the time zone, and only Reply's LinkedIn routes take the retry window. Which other flag each + // needs is Reply's rule, refused there with errors[]. + if (opts.useContactTimeZone !== undefined) + { + later.useContactTimeZone = opts.useContactTimeZone; + } + if (by === 'linkedin' && opts.retryWindowMinutes !== undefined) + { + later.retryWindowMinutes = parse_int_in(opts.retryWindowMinutes, '--retry-window-minutes', 1, 4320, 0); + } // Reply tracks neither unless asked, so each is sent only to turn it on. if (opts.trackLinks === true) { @@ -429,5 +479,5 @@ const handle_direct_send = async( } }; -export {handle_direct_send, known_refusal, strings_of, DIRECT_SEND_REFUSALS}; +export {handle_direct_send, known_refusal, strings_of, estimated_of, DIRECT_SEND_REFUSALS, CANCEL_REFUSALS}; export type {Direct_send_name, Direct_send_opts}; diff --git a/src/operations/direct-sends.ts b/src/operations/direct-sends.ts index 188b0cd..1ddf0c9 100644 --- a/src/operations/direct-sends.ts +++ b/src/operations/direct-sends.ts @@ -1,14 +1,15 @@ import {Unknown_outcome_error, UsageError} from '../utils/errors'; import {call_reply, expect_object, refusal, unreadable, open_session, type Answer} from './call'; -import {known_refusal, strings_of, DIRECT_SEND_REFUSALS} from './direct-send'; +import {known_refusal, strings_of, estimated_of, DIRECT_SEND_REFUSALS, CANCEL_REFUSALS} from './direct-send'; import {print_result} from './result'; import type {Op_globals} from './options'; import type {Cli_context} from '../context'; // Reply's route takes exactly this form and answers anything else with a bare 404, as it does when it // has no such route at all. Checking the form here keeps that 404 meaning only the latter; nothing else -// is read from the reference, and the form leaves nothing to encode. -const REFERENCE = /^(email|linkedin)-[1-9]\d{0,9}$/; +// is read from the reference, and the form leaves nothing to encode. A LinkedIn send held for later keeps +// linkedin-scheduled- for its whole life; one sent at once is linkedin-. +const REFERENCE = /^(email|linkedin|linkedin-scheduled)-[1-9]\d{0,9}$/; const path_of = (reference: string): string=>{ if (reference.trim() === '') @@ -17,7 +18,7 @@ const path_of = (reference: string): string=>{ } if (!REFERENCE.test(reference)) { - throw new UsageError('That is not a reference Reply gives: email- or linkedin-, n from 1.', + throw new UsageError('That is not a reference Reply gives: email-, linkedin- or linkedin-scheduled-, n from 1.', {code: 'usage.reference', hint: 'A send made with --send-after answers its reference.'}); } return `/v3/direct-sends/${reference}`; @@ -50,7 +51,7 @@ const direct_send_of = (a: Answer, kind: 'read' | 'write'): Recordbody[name] ?? null; return { reference: body.reference, channel: field('channel'), contact_id: field('contactId'), state: body.state, - send_after: field('sendAfter'), sent_at: field('sentAt'), message_id: field('messageId'), + send_after: field('sendAfter'), ...estimated_of(body), sent_at: field('sentAt'), message_id: field('messageId'), failure_reason: field('failureReason'), ...rendering_of(body), cancelled_at: field('cancelledAt'), }; }; @@ -73,7 +74,7 @@ const handle_direct_send_cancel = async(reference: string, ctx: Cli_context, g: const a = await call_reply(s, 'POST', path, 'write'); if (a.status !== 200) { - throw known_refusal(a, DIRECT_SEND_REFUSALS) ?? refusal(a, 'write'); + throw known_refusal(a, DIRECT_SEND_REFUSALS) ?? known_refusal(a, CANCEL_REFUSALS) ?? refusal(a, 'write'); } print_result(direct_send_of(a, 'write'), g); } catch (e) {