diff --git a/README.md b/README.md index d97f196..0f5bac3 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,7 @@ prints JSON (indented; compact with `--json`) and says what happened in a stable | `reply inbox categorize (--category-id N \| --clear)` | → `categorized` / `cleared` | | `reply inbox mark-read ` · `reply inbox mark-unread ` | → `read` / `unread` | | `reply account list [--channel email\|linkedin]` | the email and LinkedIn accounts a send can go from, whose each is, and the state of each | +| `reply schedule list` | the sending schedules the account can use, each with its time zone and its windows by weekday | `` is exactly one of `--contact |@file|-`, `--email
` (with `--first-name`, `--last-name`, `--company`, `--title`), or `--contact-id `. The JSON takes the same fields @@ -303,6 +304,24 @@ lengths Reply publishes (a LinkedIn message's 8000 characters, an InMail's 200 a 1000) are refused before anything is sent. Reply reads `{{…}}` in a LinkedIn text as its template variables, and refuses one it cannot fill with `linkedin.missing_variables`. +`reply schedule list` gives every sending schedule the account can use, in one answer and in the +order Reply gives them: its `time_zone_id` as Reply holds it, a Windows time zone identifier such as +`Eastern Standard Time`, whether it reads its windows in each recipient's own time zone, whether it +skips holidays, whether it is your default, and its windows, one entry for each day Reply holds, in +Reply's order, each day's `week_day` in lower case and each time of day as `HH:MM`. +`follow_up_timings` are the windows of the later steps, used when `use_follow_up_schedule` is true, +and `reply_status` is Reply's own word for how the schedule is used: `unknown`, +`inCampaignTemplate`, `inCurrentUserSequence`, `inTeamMemberSequence`, `isDefaultForCurrentUser` or +`isDefaultForTeamMember`, only the first of them that holds: + +```sh +reply schedule list --json +# {"items":[{"id":41,"name":"Business hours","time_zone_id":"Eastern Standard Time","use_recipient_time_zone":false, +# "exclude_holidays":true,"is_default":true,"main_timings":[{"week_day":"monday","active":true, +# "ranges":[{"from":"09:00","to":"17:00"}]}, …],"use_follow_up_schedule":false,"follow_up_timings":[], +# "reply_status":"isDefaultForCurrentUser"}]} +``` + `inbox reply`, `sequence create` and the five direct sends are the work commands that are not safe to re-run. On exit 3 (outcome unknown) a reply or a send may already have gone, and running it again may send it twice, unless the hint says nothing was sent: a send whose contact's import lost its answer diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 79610be..bc3afec 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -1,6 +1,6 @@ import {describe, it, expect} from 'vitest'; import type {Command} from 'commander'; -import {sequence_command, contact_list_command, contact_command, inbox_command, account_command} from '../../operations/commands'; +import {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command} from '../../operations/commands'; const sub = (parent: Command, name: string): Command=>{ const found = parent.commands.find(c=>c.name() === name); @@ -25,6 +25,27 @@ describe('operations/commands', ()=>{ 'send-email', 'linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']); expect(inbox_command.commands.map(c=>c.name())).toEqual(['list', 'get', 'reply', 'categories', 'categorize', 'mark-read', 'mark-unread']); expect(account_command.commands.map(c=>c.name())).toEqual(['list']); + expect(schedule_command.commands.map(c=>c.name())).toEqual(['list']); + }); + + it('schedule list takes no flag and no id, and says how a time zone, a weekday, a time and a state are written', ()=>{ + const c = sub(schedule_command, 'list'); + expect(flags(c)).toEqual([]); + expect(c.registeredArguments).toEqual([]); + const text = help_of(c); + const flat = text.replace(/\s+/g, ' '); + expect(flat, text).toContain('time_zone_id is a Windows time zone identifier'); + expect(flat, text).toContain('the weekday in lower case and each time of day as HH:MM'); + expect(flat, text).toContain('follow_up_timings are the windows of the later steps'); + expect(flat, text).toContain('all in one answer'); + expect(flat, text).toContain('one entry for each day Reply holds, in Reply\'s order'); + expect(flat, text).toContain('whether the schedule is your default'); + expect(flat, text).toContain('unknown, inCampaignTemplate, inCurrentUserSequence, inTeamMemberSequence, ' + + 'isDefaultForCurrentUser or isDefaultForTeamMember, only the first of them that holds'); + expect(flat, text).toContain('A key without Reply\'s sequences read scope is access.feature_unavailable'); + expect(flat, text).not.toContain('plan or role'); + expect(text, text).toContain(' access.feature_unavailable\n'); + expect(text, text).not.toContain('outcome.unknown'); }); it('account list takes only --channel, and says what each status means and that every page is read', ()=>{ diff --git a/src/__tests__/operations/program.test.ts b/src/__tests__/operations/program.test.ts index a5c9833..feb4fda 100644 --- a/src/__tests__/operations/program.test.ts +++ b/src/__tests__/operations/program.test.ts @@ -172,6 +172,22 @@ describe('the program', ()=>{ expect(mock_fetch).not.toHaveBeenCalled(); }); + it('schedule list is a work command of its own: a flag or an id exits 2 before any request, a refusal exits 1', async()=>{ + for (const extra of [['--name', 'Business hours'], ['41']]) + { + const {code} = await run_program(['--json', '-q', '-k', 'key-1', 'schedule', 'list', ...extra]); + expect(code, extra.join(' ')).toBe(2); + } + expect(mock_fetch).not.toHaveBeenCalled(); + // What Reply answers a key without the sequences read scope: a problem with no code. + answer(json({error: 'insufficient_scope', message: 'This endpoint requires scope \'…\'.', required_scope: '…'}, 403, + {'Content-Type': 'application/problem+json'})); + const {code, err} = await run_program(['--json', '-q', '-k', 'key-1', 'schedule', 'list']); + expect(code).toBe(1); + expect(JSON.parse(err)).toMatchObject({error: {code: 'access.feature_unavailable', status: 403}}); + expect((mock_fetch.mock.calls[0] as [string, RequestInit])[0]).toBe('https://api.reply.io/v3/schedules'); + }); + it('a usage error exits 2 before any request', async()=>{ const {code, err} = await run_program(['--json', '-k', 'key-1', 'sequence', 'stats', '123', '--from', '2026-10-02', '--to', '2026-10-01']); expect(code).toBe(2); diff --git a/src/__tests__/operations/schedules.test.ts b/src/__tests__/operations/schedules.test.ts new file mode 100644 index 0000000..9837b23 --- /dev/null +++ b/src/__tests__/operations/schedules.test.ts @@ -0,0 +1,120 @@ +import {describe, it, expect, beforeEach} from 'vitest'; +import {mock_fetch, json, ctx, sent, answer, capture} from './helpers'; +import {handle_schedule_list} from '../../operations/schedules'; + +const day = (weekDay: unknown, isActive: unknown, ...ranges: [number, number, number, number][])=>({ + weekDay, isActive, + timeRanges: ranges.map(([fh, fm, th, tm])=>({fromTime: {hour: fh, minute: fm}, toTime: {hour: th, minute: tm}})), +}); +const schedule = (over: Record = {})=>({ + id: 41, name: 'Business hours', timezoneId: 'Eastern Standard Time', excludeHolidays: false, useProspectTimezone: false, + useFollowUpSchedule: false, mainTimings: [day('Monday', true, [9, 0, 17, 0])], followUpTimings: [], isDefault: true, + status: 'isDefaultForCurrentUser', ...over, +}); + +// What Reply answers a key without the sequences read scope, the only thing that refuses the read: a problem with no code. +const scope_refusal = ()=>json({ + error: 'insufficient_scope', message: 'This endpoint requires scope \'…\'.', required_scope: '…', +}, 403, {'Content-Type': 'application/problem+json'}); + +const list = async()=> + JSON.parse((await capture(()=>handle_schedule_list(ctx(), {json: true}))).out) as {items: Record[]}; +const failure = ()=>handle_schedule_list(ctx(), {}).catch((x: unknown)=>x); + +beforeEach(()=>{ mock_fetch.mockReset(); }); + +describe('schedule list', ()=>{ + it('lists every schedule in one read, in Reply\'s order, each with its time zone and its windows by weekday', async()=>{ + answer(json([ + schedule({ + id: 57, name: 'Madrid mornings', timezoneId: 'Romance Standard Time', useProspectTimezone: true, isDefault: false, + mainTimings: [day('Friday', true, [8, 30, 12, 0], [13, 0, 14, 5])], useFollowUpSchedule: true, + followUpTimings: [day('Saturday', false)], status: 'inCurrentUserSequence', + }), + schedule({excludeHolidays: true}), + ])); + expect(await list()).toStrictEqual({items: [ + {id: 57, name: 'Madrid mornings', time_zone_id: 'Romance Standard Time', use_recipient_time_zone: true, exclude_holidays: false, + is_default: false, + main_timings: [{week_day: 'friday', active: true, ranges: [{from: '08:30', to: '12:00'}, {from: '13:00', to: '14:05'}]}], + use_follow_up_schedule: true, follow_up_timings: [{week_day: 'saturday', active: false, ranges: []}], + reply_status: 'inCurrentUserSequence'}, + {id: 41, name: 'Business hours', time_zone_id: 'Eastern Standard Time', use_recipient_time_zone: false, exclude_holidays: true, + is_default: true, main_timings: [{week_day: 'monday', active: true, ranges: [{from: '09:00', to: '17:00'}]}], + use_follow_up_schedule: false, follow_up_timings: [], reply_status: 'isDefaultForCurrentUser'}, + ]}); + expect(sent()).toEqual([{method: 'GET', url: 'https://api/v3/schedules', body: undefined}]); + }); + + it('an account with no schedules is an empty list', async()=>{ + answer(json([])); + expect(await list()).toStrictEqual({items: []}); + }); + + it('a name or time zone Reply leaves out or gives blank, or a state word it leaves out or gives empty, is null, and a flag it does not give as true is false', async()=>{ + answer(json([ + schedule({name: ' ', timezoneId: '', status: '', isDefault: undefined, excludeHolidays: 'true', useProspectTimezone: 1}), + schedule({id: 42, name: undefined, timezoneId: null, status: undefined, useFollowUpSchedule: null}), + schedule({id: 43, name: 'Weekends', timezoneId: 'UTC', status: ' ', isDefault: false}), + ])); + expect((await list()).items.map(i=>[i.name, i.time_zone_id, i.reply_status, i.is_default, i.exclude_holidays, + i.use_recipient_time_zone, i.use_follow_up_schedule])).toEqual([ + [null, null, null, false, false, false, false], + [null, null, null, true, false, false, false], + ['Weekends', 'UTC', ' ', false, false, false, false], + ]); + }); + + it('a name or time zone is kept exactly as Reply gives it when it is not blank', async()=>{ + answer(json([schedule({name: ' Late shift ', timezoneId: 'UTC'})])); + expect((await list()).items.map(i=>[i.name, i.time_zone_id])).toEqual([[' Late shift ', 'UTC']]); + }); + + it('follow-up windows Reply does not give as a list are null, a day or range it gives unreadably is kept without a guess, and an entry that is not a day at all is left out', async()=>{ + answer(json([schedule({ + followUpTimings: null, + mainTimings: [ + day('SUNDAY', 'yes'), + day('Tuesday', true, [18, 0, 24, 0], [23, 0, 24, 30], [-1, 0, 9, 60]), + {weekDay: 7, isActive: true, timeRanges: 'all day'}, + {isActive: true, timeRanges: [{fromTime: '09:00', toTime: {hour: 25, minute: 0}}, {fromTime: {hour: 9.5, minute: 0}, toTime: null}]}, + 'not a day', + ], + })])); + const [item] = (await list()).items; + expect(item.follow_up_timings).toBeNull(); + expect(item.main_timings).toStrictEqual([ + {week_day: 'sunday', active: false, ranges: []}, + {week_day: 'tuesday', active: true, ranges: [{from: '18:00', to: '24:00'}, {from: '23:00', to: null}, {from: null, to: null}]}, + {week_day: null, active: true, ranges: []}, + {week_day: null, active: true, ranges: [{from: null, to: null}, {from: null, to: null}]}, + ]); + }); + + it('a schedule without a usable id is reply.unavailable, never a guess', async()=>{ + for (const entry of [schedule({id: '41'}), schedule({id: undefined}), schedule({id: 0}), schedule({id: 1.5}), 'not a schedule']) + { + mock_fetch.mockReset(); + answer(json([entry])); + await expect(failure(), JSON.stringify(entry)).resolves.toMatchObject({code: 'reply.unavailable', exit_code: 1}); + } + }); + + it('a refused or unreadable read is the house refusal', async()=>{ + const cases: [Response, string][] = [ + [scope_refusal(), 'access.feature_unavailable'], + [json({title: 'Unauthorized'}, 401), 'access.denied'], + [json('', 503), 'reply.unavailable'], + [json({items: []}), 'reply.unavailable'], + ]; + for (const [response, code] of cases) + { + mock_fetch.mockReset(); + answer(response); + await expect(failure(), code).resolves.toMatchObject({code, exit_code: 1}); + } + mock_fetch.mockReset(); + answer(scope_refusal()); + await expect(failure()).resolves.toMatchObject({status: 403, reply_code: undefined}); + }); +}); diff --git a/src/index.ts b/src/index.ts index 30a861d..a874344 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,7 @@ import {team_command} from './commands/team'; import {api_command} from './commands/api'; import {skills_command} from './commands/skills'; import {install_command} from './commands/install'; -import {sequence_command, contact_list_command, contact_command, inbox_command, account_command} from './operations/commands'; +import {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command} from './operations/commands'; import {update_notice} from './selfupdate/notice'; import {CliError, format_hint} from './utils/errors'; import {info, set_quiet} from './utils/output'; @@ -46,7 +46,7 @@ const build_program = (): Command=>{ const WORK = 'Work with your Reply account:'; const SETUP = 'Setup:'; - for (const c of [sequence_command, contact_list_command, contact_command, inbox_command, account_command, api_command]) + for (const c of [sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command, api_command]) { program.addCommand(c.helpGroup(WORK)); } @@ -91,6 +91,7 @@ Work commands (JSON out; exit 0 done, 1 failed, 2 usage, 3 outcome unknown): ${PROGRAM_NAME} contact opt-out --contact-id 456 ${PROGRAM_NAME} inbox list --contact-id 456 ${PROGRAM_NAME} account list --channel linkedin + ${PROGRAM_NAME} schedule list Each command's --help lists its flags, its result and its error codes. Raw API (agent/CI escape hatch) — docs: https://docs.reply.io/api-reference/introduction diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 665d30e..9f6db12 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -16,6 +16,7 @@ import {handle_contact_opt_out} from './contact'; import {handle_contact_find, handle_contact_get, handle_contact_update, handle_contact_delete} from './contact-record'; import {handle_direct_send, type Direct_send_name} from './direct-send'; import {handle_account_list} from './accounts'; +import {handle_schedule_list} from './schedules'; const P = PROGRAM_NAME; const COMMON_ERRORS = [ @@ -497,4 +498,25 @@ account_command.command('list') await handle_account_list(cmd.opts(), ctx, g); })); -export {sequence_command, contact_list_command, contact_command, inbox_command, account_command}; +const schedule_command = new Command('schedule').description('List the sending schedules a sequence can send within'); + +schedule_command.command('list') + .description('Every sending schedule the account can use, with its time zone and its sending windows by weekday') + .addHelpText('after', help([ex('schedule list')], [], false, + 'Result: {"items":[{"id","name","time_zone_id","use_recipient_time_zone","exclude_holidays","is_default","main_timings",\n' + + '"use_follow_up_schedule","follow_up_timings","reply_status"}]}, in the order Reply gives them, all in one answer.\n' + + 'time_zone_id is a Windows time zone identifier (e.g. "Eastern Standard Time"), as Reply holds it. main_timings has\n' + + 'one entry for each day Reply holds, in Reply\'s order: {"week_day","active","ranges":[{"from","to"}]}, the weekday\n' + + 'in lower case and each time of day as HH:MM; a range may end at 24:00, the end of the day. follow_up_timings are\n' + + 'the windows of the later steps, which Reply uses when use_follow_up_schedule is true. is_default says whether the\n' + + 'schedule is your default. reply_status is Reply\'s own word for how the schedule is used: unknown,\n' + + 'inCampaignTemplate, inCurrentUserSequence, inTeamMemberSequence, isDefaultForCurrentUser or isDefaultForTeamMember,\n' + + 'only the first of them that holds. A name, time zone, weekday, time or reply_status Reply gives none of is null;\n' + + 'follow_up_timings is null when Reply gives no list. A key without Reply\'s sequences read scope is\n' + + 'access.feature_unavailable.\n')) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_schedule_list(ctx, g); + })); + +export {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command}; diff --git a/src/operations/schedules.ts b/src/operations/schedules.ts new file mode 100644 index 0000000..68b6a72 --- /dev/null +++ b/src/operations/schedules.ts @@ -0,0 +1,77 @@ +import {Operation_error} from '../utils/errors'; +import {call_reply, refusal, unreadable, is_object, open_session} from './call'; +import {print_result} from './result'; +import type {Op_globals} from './options'; +import type {Cli_context} from '../context'; + +type Range = {from: string | null; to: string | null}; +type Day = {week_day: string | null; active: boolean; ranges: Range[]}; +type Schedule = { + id: number; name: string | null; time_zone_id: string | null; use_recipient_time_zone: boolean; exclude_holidays: boolean; + is_default: boolean; main_timings: Day[]; use_follow_up_schedule: boolean; follow_up_timings: Day[] | null; + reply_status: string | null; +}; + +const text_or_null = (v: unknown): string | null=>(typeof v === 'string' && v.trim() !== '' ? v : null); + +const two = (n: number): string=>String(n).padStart(2, '0'); + +// A time of day as HH:MM, from Reply's {hour, minute}. A range may end at 24:00, the end of the +// day; anything else that is not a time of day is null rather than a guess. +const clock = (v: unknown): string | null=>{ + if (!is_object(v) || !Number.isInteger(v.hour) || !Number.isInteger(v.minute)) + { + return null; + } + const hour = v.hour as number; + const minute = v.minute as number; + const valid = minute >= 0 && minute < 60 && hour >= 0 && (hour < 24 || (hour === 24 && minute === 0)); + return valid ? `${two(hour)}:${two(minute)}` : null; +}; + +// Reply's timings, one entry a weekday, in Reply's order. Reply names the day as .NET does +// (`Monday`); the CLI writes it in lower case. +const timings_of = (v: unknown): Day[]=> + (Array.isArray(v) ? v : []).filter(is_object).map(day=>({ + week_day: typeof day.weekDay === 'string' && day.weekDay !== '' ? day.weekDay.toLowerCase() : null, + active: day.isActive === true, + ranges: (Array.isArray(day.timeRanges) ? day.timeRanges : []).filter(is_object).map(r=>({from: clock(r.fromTime), to: clock(r.toTime)})), + })); + +const schedule_of = (entry: unknown): Schedule=>{ + if (!is_object(entry) || typeof entry.id !== 'number' || !Number.isSafeInteger(entry.id) || entry.id <= 0) + { + throw new Operation_error('reply.unavailable', 'Reply listed a schedule without a usable id.', {status: 200}); + } + return { + id: entry.id, + name: text_or_null(entry.name), + // A Windows time zone identifier (`Eastern Standard Time`), as Reply holds it. + time_zone_id: text_or_null(entry.timezoneId), + use_recipient_time_zone: entry.useProspectTimezone === true, + exclude_holidays: entry.excludeHolidays === true, + is_default: entry.isDefault === true, + main_timings: timings_of(entry.mainTimings), + use_follow_up_schedule: entry.useFollowUpSchedule === true, + follow_up_timings: Array.isArray(entry.followUpTimings) ? timings_of(entry.followUpTimings) : null, + // Reply's own word for how the schedule is used (`inCurrentUserSequence`, ...). + reply_status: typeof entry.status === 'string' && entry.status !== '' ? entry.status : null, + }; +}; + +// Reply gives every schedule in one answer, with no paging. +const handle_schedule_list = async(ctx: Cli_context, g: Op_globals): Promise=>{ + const s = await open_session(ctx, g); + const a = await call_reply(s, 'GET', '/v3/schedules', 'read'); + if (a.status !== 200) + { + throw refusal(a, 'read'); + } + if (!Array.isArray(a.data)) + { + throw unreadable(a, 'read'); + } + print_result({items: a.data.map(schedule_of)}, g); +}; + +export {handle_schedule_list};