diff --git a/README.md b/README.md index 81c32de..d97f196 100644 --- a/README.md +++ b/README.md @@ -195,11 +195,11 @@ prints JSON (indented; compact with `--json`) and says what happened in a stable | `reply contact-list add-contact [--refuse-opted-out]` | → `added` | | `reply contact find --contact -` | the id of the contact under an email or a LinkedIn URL, or null; never creates one | | `reply contact get ` | the contact as Reply holds it | -| `reply contact update --fields -` | change some fields and custom fields; null clears one → `updated` | +| `reply contact update ( \| ) --fields -` | change some fields and custom fields; null clears one → `updated` | | `reply contact delete ` | → `deleted` | | `reply contact opt-out ` | → `opted_out` | -| `reply contact send-email --contact-id N --email-account-id N --message -` | one email now, outside any sequence → `sent` | -| `reply contact linkedin-connect --contact-id N --linkedin-account-id N [--message -]` | a LinkedIn invitation, with or without a note → `sent` / `already_connected` | +| `reply contact send-email --email-account-id N --message -` | one email now, outside any sequence → `sent` | +| `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` | | `reply inbox list (--contact-id \| --sequence-id) [--source] [--channel] [--category-id] [--since]` | one page of threads | | `reply inbox get ` | a thread with its subject, and one page of its messages | @@ -221,9 +221,27 @@ echo '{"linkedin_url":"https://www.linkedin.com/in/ann-example","first_name":"An The two `add-contact` commands always import a contact given by email, and Reply refuses an import without a first name, even for a contact it already holds; a contact given only by LinkedIn URL is -looked up first and imported only when Reply holds nobody under it. `contact opt-out` imports only -someone Reply doesn't hold yet; `sequence remove-contact` never imports. A contact is looked up, and -an import matched, by its email; one with only a LinkedIn URL, by that. The lookup is Reply's exact +looked up first and imported only when Reply holds nobody under it. `contact opt-out`, `contact +update` and the direct sends look first and import only someone Reply doesn't hold yet, so only then +is a first name needed, and a direct send sends only to a contact it created (below); `sequence +remove-contact` never imports. Each of these except `sequence remove-contact` answers the +`contact_id` it acted on and `contact_created`, so a caller can keep the id. A send looks the person +up by every address it was given, the one it reaches them at first (the email for `contact send-email`, +the LinkedIn URL for the LinkedIn sends), then the other when there is one. Otherwise a contact is +looked up by its email, and one with only a LinkedIn URL by that; an import is matched by the email +when there is one. + +A direct send given a person's fields sends only to a contact it creates. When a lookup by any address +it was given finds a contact, or its import matches one Reply already holds (by the email, say, or a teammate's), nothing +is sent: the answer is `contact.already_held` (exit 1) with that contact's id in `ids.contact_id`. +Read that contact first with `reply contact get`, its opt-out included, and send to it with +`--contact-id` if it is the one to reach. Reply does not refuse a direct send to a contact it holds +as opted out, so a send never reaches a contact Reply already held without that read. A LinkedIn +send needs a `linkedin_url` in `--contact` (or `--contact-id`): `--email` alone is refused. On a send, +`contact_created` is kept for consistency with the add commands: given a person's fields it is always `true`, +and with `--contact-id` it is always `false`; in both cases a successful answer says the send was made. + +The lookup is Reply's exact one: an email matches ignoring case, and a LinkedIn URL is matched by its lowercased slug — on linkedin.com the path's case does not count, nor the scheme's or host's, a default port, one trailing slash or a fragment, while `www` and the query do. Reply is asked for a LinkedIn URL in that form @@ -242,7 +260,18 @@ echo '{"name":"Q4 outreach"}' | reply sequence list --name - ``` `contact update` refuses a custom field the account has none of, `contact.field_not_found`, before -it changes anything. +it changes or imports anything. Given the contact by its flags rather than its id, it changes only +what `--fields` names: the contact's own fields find the contact, or import it, and never change one +Reply already holds. + +When `--contact -` and the command's own input (`--message -` or `--fields -`) both read stdin, it +holds one object with each under its flag's name, so neither the person nor the text ever sits in +the argument list: + +```sh +echo '{"contact":{"email":"ann@example.com","first_name":"Ann"},"fields":{"title":"CTO"}}' | reply contact update --contact - --fields - +echo '{"contact":{"linkedin_url":"https://www.linkedin.com/in/ann-example","first_name":"Ann"},"message":{"body":"Thanks for connecting, Ann."}}' | reply contact linkedin-message --contact - --linkedin-account-id 34 --message - +``` `inbox reply` takes its message, `{body, reply_to_message_id}`, from stdin only, and refuses it on the argument list. The reply goes to the thread's contact from the account that owns the thread; @@ -276,7 +305,10 @@ variables, and refuses one it cannot fill with `linkedin.missing_variables`. `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; for `inbox reply`, read the thread with `reply inbox get` before trying again. For +send it twice, unless the hint says nothing was sent: a send whose contact's import lost its answer +was never made, and its hint says so; run again, it answers `contact.already_held` if that import did +create the contact. +For `inbox reply`, read the thread with `reply inbox get` before trying again. For `sequence create`, Reply allows two sequences of one name, so after exit 3 look the name up with `sequence list --name -` first. Every other work command can simply be run again; a `contact delete` repeated after its first one took effect answers `contact.not_found`. diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 97bb68f..79610be 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -42,17 +42,21 @@ describe('operations/commands', ()=>{ expect(text, text).not.toContain('outcome.unknown'); }); + // The sends and contact update find or import the person as the add commands do. + const SENDS_AND_UPDATE = ['update', 'send-email', 'linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']; + const CONTACT_FLAGS = ['--contact-id', '--email', '--first-name', '--last-name', '--company', '--title', '--contact']; + it('the commands about a person take the contact flags', ()=>{ for (const c of [sub(sequence_command, 'add-contact'), sub(sequence_command, 'remove-contact'), - sub(contact_list_command, 'add-contact'), sub(contact_command, 'opt-out')]) + sub(contact_list_command, 'add-contact'), sub(contact_command, 'opt-out'), ...SENDS_AND_UPDATE.map(n=>sub(contact_command, n))]) { - expect(flags(c)).toEqual(expect.arrayContaining(['--contact-id', '--email', '--contact'])); + expect(flags(c), c.name()).toEqual(expect.arrayContaining(CONTACT_FLAGS)); } }); it('the commands about a person say their JSON takes linkedin_url, and a lookup is never left incomplete', ()=>{ for (const c of [sub(sequence_command, 'add-contact'), sub(sequence_command, 'remove-contact'), - sub(contact_list_command, 'add-contact'), sub(contact_command, 'opt-out')]) + sub(contact_list_command, 'add-contact'), sub(contact_command, 'opt-out'), ...SENDS_AND_UPDATE.map(n=>sub(contact_command, n))]) { const text = help_of(c); expect(text, text).toContain('linkedin_url'); @@ -61,11 +65,42 @@ describe('operations/commands', ()=>{ // Each of them looks a contact up by address, and two contacts under one address is refused. expect(text, text).toContain(' contact.not_unique\n'); } - for (const c of [sub(sequence_command, 'add-contact'), sub(contact_list_command, 'add-contact'), sub(contact_command, 'opt-out')]) + for (const c of [sub(sequence_command, 'add-contact'), sub(contact_list_command, 'add-contact'), sub(contact_command, 'opt-out'), + ...SENDS_AND_UPDATE.map(n=>sub(contact_command, n))]) { const text = help_of(c); - expect(text, text).toContain('contact.invalid_linkedin_url'); + for (const code of ['contact.invalid_email', 'contact.invalid_linkedin_url', 'account.contact_limit_reached']) + { + expect(text, `${c.name()} ${code}`).toContain(` ${code}\n`); + } + } + }); + + it('the sends and contact update say a contact is imported only when Reply holds nobody, and how stdin holds both inputs', ()=>{ + for (const name of SENDS_AND_UPDATE) + { + const text = help_of(sub(contact_command, name)); + const flat = text.replace(/\s+/g, ' '); + const input = name === 'update' ? 'fields' : 'message'; + expect(flat, text).toContain('imported only when Reply holds nobody under'); + expect(flat, text).toContain(name === 'update' ? 'contact_created says whether this command created' + : 'contact_created is kept for consistency with the add commands: given a person\'s fields it is always true, and with --contact-id it is always false; in both cases a successful answer says the send was made'); + expect(flat, text).toContain(`With --contact - and --${input} - both, stdin holds one object: {"contact": {…}, "${input}": {…}}`); + expect(text, text).toContain(`--contact - `); + } + const email = help_of(sub(contact_command, 'send-email')).replace(/\s+/g, ' '); + expect(email, email).toContain('looked up by its email'); + for (const name of ['linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']) + { + const text = help_of(sub(contact_command, name)).replace(/\s+/g, ' '); + expect(text, text).toContain('looked up by its LinkedIn URL'); } + const update = help_of(sub(contact_command, 'update')).replace(/\s+/g, ' '); + expect(update, update).toContain('looked up as the add commands look one up'); + // An update acts on a contact it finds, so only an import needs a first name. + expect(update, update).toContain('only then does Reply need a first name'); + expect(update, update).toContain('only what --fields names is changed'); + expect(update, update).toContain('contact update 456 is contact update --contact-id 456'); }); it('carries each command\'s own flags', ()=>{ @@ -98,7 +133,7 @@ describe('operations/commands', ()=>{ it('contact update takes its values only through --fields -, and contact delete says what a re-run answers', ()=>{ const update = sub(contact_command, 'update'); - expect(flags(update)).toEqual(['--fields']); + expect(flags(update)).toEqual([...CONTACT_FLAGS, '--fields']); const text = help_of(update); expect(text, text).toContain('--fields -'); expect(text, text).toContain('contact.field_not_found'); @@ -117,13 +152,30 @@ describe('operations/commands', ()=>{ expect(text.replace(/\s+/g, ' '), text).toContain('matched by its lowercased slug'); }); + it('the commands that look a contact up first say the name flags are used only if it is imported; the add commands do not', ()=>{ + const described = (c: Command, flag: string)=>c.options.find(o=>o.long === flag)?.description as string; + const lookups = ['update', 'opt-out', 'send-email', 'linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']; + for (const name of lookups) + { + for (const flag of ['--last-name', '--company', '--title']) + { + expect(described(sub(contact_command, name), flag), `${name} ${flag}`).toContain('used only if the contact is imported'); + } + } + for (const flag of ['--last-name', '--company', '--title']) + { + expect(described(sub(sequence_command, 'add-contact'), flag), flag).not.toContain('used only if'); + } + }); + // Each direct send: the flag naming the account it goes from, the codes its endpoint publishes, and what its help // says sent_at is. - const LINKEDIN = ['contact.not_found', 'contact.no_linkedin_profile', 'linkedin.account_not_found', 'linkedin.feature_disabled', - 'linkedin.account_inactive', 'linkedin.invalid_cookie']; + 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']; 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', 'email_account.not_found', 'contact.blacklisted'], + ['send-email', '--email-account-id', ['contact.not_found', ...IMPORT, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted'], '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], @@ -143,16 +195,25 @@ describe('operations/commands', ()=>{ expect(text, text).not.toContain('connected or not'); }); - it('each direct send takes ids by flag and its text only through --message -, and says a repeat may send it twice', ()=>{ + it('each direct send takes the contact flags, the account by flag and its text only through --message -, and says a ' + + 'repeat may send it twice', ()=>{ for (const [name, account_flag, codes, sent_at] of DIRECT_SENDS) { const c = sub(contact_command, name); - expect(flags(c), name).toEqual(['--contact-id', account_flag, '--message']); + expect(flags(c), name).toEqual([...CONTACT_FLAGS, account_flag, '--message']); const text = help_of(c); const flat = text.replace(/\s+/g, ' '); expect(text, text).toContain('--message -'); - expect(flat, text).toContain('may send it twice'); + expect(flat, text).toContain('may send it twice, unless the hint says nothing was sent'); expect(text, text).not.toContain('re-running is safe'); + // A send given a person's fields sends only to a contact it creates, and names one Reply already holds. + expect(flat, text).toContain('A send given a person\'s fields sends only to a contact it creates'); + expect(flat, text).toContain('a lookup finds a contact, or the import matches one Reply already holds, nothing is sent'); + expect(flat, text).toContain(`then by its ${name === 'send-email' ? 'LinkedIn URL' : 'email'} when it was given one`); + expect(flat, text).toContain('imported only when Reply holds nobody under any address given'); + expect(flat, text).toContain('the answer is contact.already_held (exit 1) with that contact\'s id in ids.contact_id'); + expect(flat, text).toContain('send to it with --contact-id'); + expect(flat.includes('--email alone is refused (usage.contact)'), text).toBe(name !== 'send-email'); expect(flat, text).toContain(sent_at); expect(flat, text).toContain('read from stdin only'); // Exactly the codes its endpoint publishes, then the shared ones, as the help lists them. diff --git a/src/__tests__/operations/contact-record.test.ts b/src/__tests__/operations/contact-record.test.ts index 6ef510b..c6298bd 100644 --- a/src/__tests__/operations/contact-record.test.ts +++ b/src/__tests__/operations/contact-record.test.ts @@ -129,7 +129,7 @@ describe('contact update', ()=>{ answer(json([{id: 1, title: 'leadSource', fieldType: 'text'}, {id: 2, title: 'budget', fieldType: 'text'}]), json({id: 456})); const {out} = await update('-', {first_name: ' Marta ', title: null, linkedin_url: URL_, custom_fields: [{name: 'leadSource', value: 'Event'}, {name: 'Budget', value: null}]}); - expect(JSON.parse(out)).toEqual({status: 'updated', contact_id: 456}); + expect(JSON.parse(out)).toEqual({status: 'updated', contact_id: 456, contact_created: false}); expect(sent()).toEqual([ {method: 'GET', url: FIELDS_URL, body: undefined}, {method: 'PATCH', url: 'https://api/v3/contacts/456', body: {firstName: 'Marta', title: null, linkedInUrl: URL_, @@ -146,7 +146,7 @@ describe('contact update', ()=>{ it('without custom fields there is no read before the PATCH', async()=>{ answer(json({id: 456})); const {out} = await update('-', {company: 'Acme', last_name: null}); - expect(JSON.parse(out)).toEqual({status: 'updated', contact_id: 456}); + expect(JSON.parse(out)).toEqual({status: 'updated', contact_id: 456, contact_created: false}); expect(sent()).toEqual([{method: 'PATCH', url: 'https://api/v3/contacts/456', body: {company: 'Acme', lastName: null}}]); }); @@ -223,6 +223,129 @@ describe('contact update', ()=>{ }); }); +describe('contact update of a person given by their fields', ()=>{ + const OTHER_PROFILE = 'https://www.linkedin.com/in/marta-other'; + const EMAIL_LOOKUP = 'GET https://api/v3/contacts?email=marta%40example.com&top=100&skip=0'; + const PROFILE_LOOKUP = `GET https://api/v3/contacts?linkedIn=${encodeURIComponent(URL_)}&top=100&skip=0`; + const IMPORT = 'POST https://api/v3/contacts/import'; + const nobody = ()=>json({items: [], hasMore: false}); + const held = (entry: Record)=>json({items: [entry], hasMore: false}); + const lines = ()=>sent().map(r=>`${r.method} ${r.url}`); + type Update_opts = Parameters[1]; + + // The person and the fields both come on stdin, so the argument list carries neither: it is checked on every run. + const PERSONAL = /marta|example\.com|cto|acme|secret/i; + const update_by_fields = (input: unknown, opts: Update_opts = {contact: '-', fields: '-'}, id?: string)=>{ + expect(JSON.stringify([id, opts]), JSON.stringify(opts)).not.toMatch(PERSONAL); + return capture(()=>handle_contact_update(id, opts, ctx(), {json: true}, stdin(input))); + }; + const fail_by_fields = (input: unknown, opts?: Update_opts, id?: string)=>update_by_fields(input, opts, id).catch((x: unknown)=>x); + + it('a person Reply holds is found as the add commands find one and changed only by --fields: never their email or ' + + 'LinkedIn URL from the fields that found them', async()=>{ + answer(held({id: 456, email: 'marta@example.com'}), json({id: 456})); + const contact = {email: EMAIL, linkedin_url: OTHER_PROFILE, first_name: 'Marta', last_name: 'Example', company: 'Old Co', title: 'Old'}; + const {out} = await update_by_fields({contact, fields: {title: 'CTO'}}); + expect(JSON.parse(out)).toStrictEqual({status: 'updated', contact_id: 456, contact_created: false}); + expect(lines()).toEqual([EMAIL_LOOKUP, 'PATCH https://api/v3/contacts/456']); + expect(sent()[1].body).toStrictEqual({title: 'CTO'}); + }); + + it('a person given only by LinkedIn URL is found by it, and only a linkedin_url in --fields changes it', async()=>{ + answer(held({id: 456, linkedInUrl: URL_}), json({id: 456})); + await update_by_fields({contact: {linkedin_url: URL_}, fields: {company: 'Acme'}}); + expect(lines()).toEqual([PROFILE_LOOKUP, 'PATCH https://api/v3/contacts/456']); + expect(sent()[1].body).toStrictEqual({company: 'Acme'}); + mock_fetch.mockReset(); + answer(held({id: 456, linkedInUrl: URL_}), json({id: 456})); + await update_by_fields({contact: {linkedin_url: URL_}, fields: {linkedin_url: OTHER_PROFILE}}); + expect(sent()[1].body).toStrictEqual({linkedInUrl: OTHER_PROFILE}); + }); + + it('a person Reply holds nobody under is imported with their names as an add imports them, then changed', async()=>{ + answer(nobody(), json({items: [{id: 457, status: 'created'}]}), json({id: 457})); + const {out} = await update_by_fields({contact: {email: EMAIL, first_name: 'Marta'}, fields: {title: 'CTO'}}); + expect(JSON.parse(out)).toStrictEqual({status: 'updated', contact_id: 457, contact_created: true}); + expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT, 'PATCH https://api/v3/contacts/457']); + expect(sent()[1].body).toStrictEqual({items: [{email: EMAIL, firstName: 'Marta'}]}); + expect(sent()[2].body).toStrictEqual({title: 'CTO'}); + mock_fetch.mockReset(); + answer(nobody(), json({items: [{id: 458, status: 'created'}]}), json({id: 458})); + await update_by_fields({contact: {linkedin_url: URL_, first_name: 'Marta'}, fields: {title: 'CTO'}}); + expect(lines()).toEqual([PROFILE_LOOKUP, IMPORT, 'PATCH https://api/v3/contacts/458']); + expect(sent()[1].body).toStrictEqual({items: [{linkedInUrl: URL_, firstName: 'Marta'}], options: {keys: {linkedInUrl: true}}}); + }); + + it('custom fields are read before the person is found or imported, so a name the account lacks imports nobody', async()=>{ + answer(json([{id: 1, title: 'leadSource', fieldType: 'text'}])); + const e = await fail_by_fields({contact: {email: EMAIL, first_name: 'Marta'}, fields: {custom_fields: [{name: 'Tier', value: SECRET}]}}); + expect(e).toMatchObject({code: 'contact.field_not_found', exit_code: 1}); + expect(lines()).toEqual([`GET ${FIELDS_URL}`]); + }); + + it('refuses as the add commands do, and changes nothing: two contacts held, the plan\'s limit, an item the import failed', async()=>{ + const two = json({items: [{id: 1, email: EMAIL}, {id: 2, email: EMAIL}], hasMore: false}); + const cases: [Response[], string][] = [ + [[two], 'contact.not_unique'], + [[nobody(), json({code: 'contact.limitExceeded', detail: 'Contact limit reached.'}, 400)], 'account.contact_limit_reached'], + [[nobody(), json({items: [{id: null, status: 'failed', error: 'Invalid data'}]})], 'reply.refused'], + ]; + for (const [answers, code] of cases) + { + mock_fetch.mockReset(); + answer(...answers); + const e = await fail_by_fields({contact: {email: EMAIL}, fields: {title: 'CTO'}}); + expect(e, code).toMatchObject({code, exit_code: 1}); + expect(shown(e), shown(e)).not.toMatch(PERSONAL); + expect(lines().filter(l=>l.startsWith('PATCH')), code).toEqual([]); + } + }); + + it('a lost answer to the import is outcome.unknown (exit 3), and nothing is changed; a lost PATCH names the contact', async()=>{ + const lost = Object.assign(new TypeError('fetch failed'), {cause: Object.assign(new Error('ECONNRESET'), {code: 'ECONNRESET'})}); + mock_fetch.mockResolvedValueOnce(nobody()).mockRejectedValueOnce(lost); + const before = await fail_by_fields({contact: {email: EMAIL, first_name: 'Marta'}, fields: {title: 'CTO'}}); + expect(before).toMatchObject({code: 'outcome.unknown', exit_code: 3}); + expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT]); + mock_fetch.mockReset(); + answer(nobody(), json({items: [{id: 457, status: 'created'}]}), json('', 503)); + const after = await fail_by_fields({contact: {email: EMAIL, first_name: 'Marta'}, fields: {title: 'CTO'}}); + expect(after).toMatchObject({code: 'outcome.unknown', exit_code: 3, ids: {contact_id: 457}}); + }); + + it('the contact is given one way only: the id argument with a contact flag, or none at all, is refused before any call', async()=>{ + const cases: [Update_opts, string | undefined][] = [ + [{contactId: '457', fields: '-'}, '456'], [{contact: '-', fields: '-'}, '456'], [{fields: '-'}, undefined], + ]; + for (const [opts, id] of cases) + { + const e = await fail_by_fields({contact: {email: EMAIL}, fields: {title: 'CTO'}}, opts, id); + expect(e, JSON.stringify([id, opts])).toMatchObject({code: 'usage.contact', exit_code: 2}); + } + expect(mock_fetch).not.toHaveBeenCalled(); + answer(json({id: 457})); + const {out} = await update_by_fields({title: 'CTO'}, {contactId: '457', fields: '-'}); + expect(JSON.parse(out)).toStrictEqual({status: 'updated', contact_id: 457, contact_created: false}); + expect(lines()).toEqual(['PATCH https://api/v3/contacts/457']); + }); + + it('with --contact - and --fields - both, stdin must be one object holding each; nothing is repeated or called otherwise', async()=>{ + const cases: [unknown, string][] = [ + ['not json, Marta', 'usage.stdin'], [{contact: {email: EMAIL}}, 'usage.stdin'], [{fields: {title: 'CTO'}}, 'usage.stdin'], + [{contact: {email: EMAIL}, fields: {title: 'CTO'}, message: {body: SECRET}}, 'usage.stdin'], + [{contact: {email: EMAIL}, fields: {email: 'marta@example.org'}}, 'usage.fields'], + [{contact: {first_name: 'Marta'}, fields: {title: 'CTO'}}, 'usage.contact'], + ]; + for (const [input, code] of cases) + { + const e = await fail_by_fields(input); + expect(e, JSON.stringify(input)).toMatchObject({code, exit_code: 2}); + expect(shown(e), shown(e)).not.toMatch(PERSONAL); + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); +}); + describe('contact delete', ()=>{ it('deletes the contact with one DELETE', async()=>{ answer(json(undefined, 204)); diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index 9a31b33..9f6272a 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -1,3 +1,6 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; import {describe, it, expect, beforeEach} from 'vitest'; import {mock_fetch, json, ctx, sent, answer, capture} from './helpers'; import {handle_direct_send, type Direct_send_name, type Direct_send_opts} from '../../operations/direct-send'; @@ -34,7 +37,7 @@ describe('contact send-email', ()=>{ it('sends one email from the mailbox named, with the subject and body from stdin, and adds no time of its own', async()=>{ answer(json({status: 'sent', messageId: ''})); expect(await run('send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS)).toStrictEqual({ - status: 'sent', contact_id: 456, message_id: '', sent_at: null, reply_status: 'sent', + status: 'sent', contact_id: 456, contact_created: false, message_id: '', sent_at: null, reply_status: 'sent', }); expect(sent()).toEqual([{ method: 'POST', url: 'https://api/v3/contacts/456/send-direct-email', body: {emailAccountId: 12, subject: SUBJECT, body: BODY}, @@ -44,12 +47,12 @@ describe('contact send-email', ()=>{ it('keeps Reply\'s own word as reply_status, gives a null messageId as null, and never takes a time from the answer', async()=>{ answer(json({status: 'new', messageId: null, sentAtUtc: '2026-10-19T10:00:00Z', date: '2026-10-19T10:00:00Z'})); expect(await run('send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS)).toStrictEqual({ - status: 'sent', contact_id: 456, message_id: null, sent_at: null, reply_status: 'new', + status: 'sent', contact_id: 456, contact_created: false, message_id: null, sent_at: null, reply_status: 'new', }); mock_fetch.mockReset(); answer(json({})); expect(await run('send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS)).toStrictEqual({ - status: 'sent', contact_id: 456, message_id: null, sent_at: null, reply_status: null, + status: 'sent', contact_id: 456, contact_created: false, message_id: null, sent_at: null, reply_status: null, }); }); @@ -99,7 +102,7 @@ describe('the LinkedIn sends', ()=>{ mock_fetch.mockReset(); answer(activity(action)); expect(await run(name, message, LINKEDIN_OPTS), name).toStrictEqual({ - status: 'sent', contact_id: 456, activity_id: 1042, sent_at: '2026-10-19T10:30:00Z', + status: 'sent', contact_id: 456, contact_created: false, activity_id: 1042, sent_at: '2026-10-19T10:30:00Z', }); const requests = sent(); expect(requests.map(r=>[r.method, r.url]), name).toEqual([['POST', `https://api/v3/contacts/456/${path}`]]); @@ -113,7 +116,7 @@ describe('the LinkedIn sends', ()=>{ mock_fetch.mockReset(); answer(json({actionType: 'message', linkedInActivityId: '1042'})); expect(await run('linkedin-message', {body: TEXT}, LINKEDIN_OPTS)).toStrictEqual({ - status: 'sent', contact_id: 456, activity_id: null, sent_at: null, + status: 'sent', contact_id: 456, contact_created: false, activity_id: null, sent_at: null, }); }); @@ -127,7 +130,7 @@ describe('the LinkedIn sends', ()=>{ it('an invitation to someone already connected is already_connected, exit 0, sent once; on a message it is a refusal', async()=>{ answer(json({title: 'Conflict', status: 409, code: 'directLinkedIn.alreadyConnected'}, 409)); expect(await run('linkedin-connect', {note: NOTE}, LINKEDIN_OPTS)).toStrictEqual({ - status: 'already_connected', contact_id: 456, activity_id: null, sent_at: null, + status: 'already_connected', contact_id: 456, contact_created: false, activity_id: null, sent_at: null, }); expect(mock_fetch).toHaveBeenCalledTimes(1); mock_fetch.mockReset(); @@ -328,16 +331,292 @@ describe('every direct send', ()=>{ expect(mock_fetch).not.toHaveBeenCalled(); }); - it('refuses a missing or malformed contact or account id before any call', async()=>{ + it('refuses a missing contact, or a malformed contact or account id, before any call', async()=>{ for (const [name, message, opts] of SENDS) { const account_flag = Object.keys(opts).find(k=>k.endsWith('AccountId')) as keyof Direct_send_opts; - for (const bad of [{contactId: undefined}, {contactId: 'abc'}, {contactId: '0'}, {[account_flag]: undefined}, {[account_flag]: '-3'}]) + const cases: [Direct_send_opts, string][] = [ + [{contactId: undefined}, 'usage.contact'], [{contactId: 'abc'}, 'usage.id'], [{contactId: '0'}, 'usage.id'], + [{[account_flag]: undefined}, 'usage.id'], [{[account_flag]: '-3'}, 'usage.id'], + ]; + for (const [bad, code] of cases) { const e = await failure(name, message, {...opts, ...bad}); - expect(e, `${name} ${JSON.stringify(bad)}`).toMatchObject({code: 'usage.id', exit_code: 2}); + expect(e, `${name} ${JSON.stringify(bad)}`).toMatchObject({code, exit_code: 2}); + } + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); +}); + +describe('a direct send to a person given by their fields', ()=>{ + const MARTA = {email: 'marta@example.com', first_name: 'Marta', last_name: 'Example'}; + const PROFILE = 'https://www.linkedin.com/in/marta-example'; + const EMAIL_LOOKUP = 'GET https://api/v3/contacts?email=marta%40example.com&top=100&skip=0'; + const PROFILE_LOOKUP = `GET https://api/v3/contacts?linkedIn=${encodeURIComponent(PROFILE)}&top=100&skip=0`; + const IMPORT = 'POST https://api/v3/contacts/import'; + const nobody = ()=>json({items: [], hasMore: false}); + const held = (entry: Record)=>json({items: [entry], hasMore: false}); + const imported = (id: number, status = 'created')=>json({items: [{id, status}]}); + const by_fields = (opts: Direct_send_opts): Direct_send_opts=>({...opts, contactId: undefined, contact: '-'}); + const lines = ()=>sent().map(r=>`${r.method} ${r.url}`); + + // The person and the text both come on stdin, so the argument list carries neither: it is checked on every run. + const PERSONAL = /marta|example\.com|tuesday|meetup/i; + const send_by_fields = (name: Direct_send_name, input: unknown, opts: Direct_send_opts)=>{ + expect(JSON.stringify(opts), JSON.stringify(opts)).not.toMatch(PERSONAL); + return send(name, input, opts); + }; + const run_by_fields = async(name: Direct_send_name, input: unknown, opts: Direct_send_opts)=> + JSON.parse((await capture(()=>send_by_fields(name, input, opts))).out); + const fail_by_fields = (name: Direct_send_name, input: unknown, opts: Direct_send_opts)=> + send_by_fields(name, input, opts).catch((x: unknown)=>x); + + const LINKEDIN_SENDS: [Direct_send_name, unknown, string, string][] = [ + ['linkedin-connect', {note: NOTE}, 'send-direct-linkedin-connect', 'connect'], + ['linkedin-message', {body: TEXT}, 'send-direct-linkedin-message', 'message'], + ['linkedin-inmail', {subject: SUBJECT, body: TEXT}, 'send-direct-linkedin-inmail', 'inMail'], + ['linkedin-voice', {script: SCRIPT}, 'send-direct-linkedin-ai-voice', 'aiVoice'], + ]; + + it('send-email: Reply holds nobody under the email, so it is looked up, imported with the person\'s names, then sent, ' + + 'and the answer names the contact it went to', async()=>{ + answer(nobody(), imported(457), json({status: 'sent', messageId: ''})); + const message = {subject: SUBJECT, body: BODY}; + expect(await run_by_fields('send-email', {contact: MARTA, message}, by_fields(EMAIL_OPTS))).toStrictEqual({ + status: 'sent', contact_id: 457, contact_created: true, message_id: '', sent_at: null, reply_status: 'sent', + }); + expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-email']); + expect(sent()[1].body).toStrictEqual({items: [{email: 'marta@example.com', firstName: 'Marta', lastName: 'Example'}]}); + expect(sent()[2].body).toStrictEqual({emailAccountId: 12, subject: SUBJECT, body: BODY}); + }); + + it('each LinkedIn send: Reply holds nobody under the profile, so it is looked up by it, the person imported keyed by it ' + + 'with no email, then sent', async()=>{ + for (const [name, message, path, action] of LINKEDIN_SENDS) + { + mock_fetch.mockReset(); + answer(nobody(), imported(458), activity(action)); + const person = {linkedin_url: PROFILE, first_name: 'Marta'}; + expect(await run_by_fields(name, {contact: person, message}, by_fields(LINKEDIN_OPTS)), name).toStrictEqual({ + status: 'sent', contact_id: 458, contact_created: true, activity_id: 1042, sent_at: '2026-10-19T10:30:00Z', + }); + expect(lines(), name).toEqual([PROFILE_LOOKUP, IMPORT, `POST https://api/v3/contacts/458/${path}`]); + expect(sent()[1].body, name).toStrictEqual({items: [{linkedInUrl: PROFILE, firstName: 'Marta'}], options: {keys: {linkedInUrl: true}}}); + } + }); + + it('a send looks the person up by every address it was given, the one it reaches them at first, and the import matches by ' + + 'the email as an add\'s does', async()=>{ + const both = {...MARTA, linkedin_url: PROFILE}; + answer(nobody(), nobody(), imported(457), activity('message')); + expect(await run_by_fields('linkedin-message', {contact: both, message: {body: TEXT}}, by_fields(LINKEDIN_OPTS))) + .toMatchObject({contact_id: 457, contact_created: true}); + expect(lines()).toEqual([PROFILE_LOOKUP, EMAIL_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-linkedin-message']); + expect(sent()[2].body).toStrictEqual({items: [{email: 'marta@example.com', linkedInUrl: PROFILE, firstName: 'Marta', lastName: 'Example'}]}); + mock_fetch.mockReset(); + answer(nobody(), nobody(), imported(457), json({status: 'sent'})); + await run_by_fields('send-email', {contact: both, message: {subject: SUBJECT, body: BODY}}, by_fields(EMAIL_OPTS)); + expect(lines()).toEqual([EMAIL_LOOKUP, PROFILE_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-email']); + }); + + // Reply does not refuse a direct send to a contact it holds as opted out, so a send given a person's fields acts only + // on a contact it created: one Reply already holds, found by the lookup or matched by the import, is refused before + // anything is sent and named, for the caller to read before sending to it by its id. + describe('a send given a person\'s fields acts only on a contact it created', ()=>{ + type Case = {name: Direct_send_name; message: unknown; opts: Direct_send_opts; lookup: string; other: string; path: string; holder: object; other_holder: object; done: () => Response}; + const FIVE: Case[] = [ + {name: 'send-email', message: {subject: SUBJECT, body: BODY}, opts: EMAIL_OPTS, lookup: EMAIL_LOOKUP, other: PROFILE_LOOKUP, + path: 'send-direct-email', holder: {email: 'Marta@Example.com'}, other_holder: {linkedInUrl: `${PROFILE}/`}, done: ()=>json({status: 'sent'})}, + ...LINKEDIN_SENDS.map(([name, message, path, action]): Case=>({name, message, opts: LINKEDIN_OPTS, lookup: PROFILE_LOOKUP, other: EMAIL_LOOKUP, + path, holder: {linkedInUrl: `${PROFILE}/`}, other_holder: {email: 'Marta@Example.com'}, done: ()=>activity(action)})), + ]; + const PERSON = {...MARTA, linkedin_url: PROFILE}; + const refused = (e: unknown, label: string)=>{ + expect(e, label).toMatchObject({code: 'contact.already_held', exit_code: 1, ids: {contact_id: 456}}); + const hint = (e as {hint?: string}).hint ?? ''; + expect(hint, `${label}: ${hint}`).toContain('contact get 456'); + expect(hint, `${label}: ${hint}`).toContain('--contact-id 456'); + expect(shown(e), shown(e)).toContain('nothing was sent'); + expect(shown(e), shown(e)).not.toMatch(PERSONAL); + expect(lines().filter(l=>l.includes('send-direct')), label).toEqual([]); + }; + + it('refuses a person the lookup finds: nothing is imported or sent, and the contact is named', async()=>{ + for (const c of FIVE) + { + mock_fetch.mockReset(); + answer(held({id: 456, ...c.holder}), c.done()); + refused(await fail_by_fields(c.name, {contact: PERSON, message: c.message}, by_fields(c.opts)), c.name); + expect(lines(), c.name).toEqual([c.lookup]); + } + }); + + it('refuses a person the import matches to a contact Reply already holds, a teammate\'s too: nothing is sent, and the ' + + 'contact is named', async()=>{ + for (const c of FIVE) + { + for (const status of ['updated', 'skipped']) + { + mock_fetch.mockReset(); + answer(nobody(), nobody(), imported(456, status), c.done()); + refused(await fail_by_fields(c.name, {contact: PERSON, message: c.message}, by_fields(c.opts)), `${c.name} ${status}`); + expect(lines(), `${c.name} ${status}`).toEqual([c.lookup, c.other, IMPORT]); + } + } + }); + + it('sends to a person the import creates', async()=>{ + for (const c of FIVE) + { + mock_fetch.mockReset(); + answer(nobody(), nobody(), imported(457), c.done()); + expect(await run_by_fields(c.name, {contact: PERSON, message: c.message}, by_fields(c.opts)), c.name) + .toMatchObject({status: 'sent', contact_id: 457, contact_created: true}); + expect(lines(), c.name).toEqual([c.lookup, c.other, IMPORT, `POST https://api/v3/contacts/457/${c.path}`]); + } + }); + + it('refuses a person held only under the other address it was given: the lookup by the address it reaches them at ' + + 'finds nobody, the one by the other finds the contact, and nothing is imported or sent', async()=>{ + for (const c of FIVE) + { + mock_fetch.mockReset(); + answer(nobody(), held({id: 456, ...c.other_holder}), c.done()); + refused(await fail_by_fields(c.name, {contact: PERSON, message: c.message}, by_fields(c.opts)), c.name); + expect(lines(), c.name).toEqual([c.lookup, c.other]); + } + }); + + it('names the first contact found when two are held, one under each address: the address it reaches them at is asked ' + + 'first, and the second is never asked', async()=>{ + for (const c of FIVE) + { + mock_fetch.mockReset(); + answer(held({id: 456, ...c.holder}), held({id: 789, ...c.other_holder}), c.done()); + refused(await fail_by_fields(c.name, {contact: PERSON, message: c.message}, by_fields(c.opts)), c.name); + expect(lines(), c.name).toEqual([c.lookup]); } + }); + }); + + it('a person without the address the send reaches them at is refused before any call, the address not repeated', async()=>{ + const cases: [Direct_send_name, unknown, Direct_send_opts][] = [ + ['send-email', {contact: {linkedin_url: PROFILE, first_name: 'Marta'}, message: {subject: SUBJECT, body: BODY}}, by_fields(EMAIL_OPTS)], + ...LINKEDIN_SENDS.map(([name, message]): [Direct_send_name, unknown, Direct_send_opts]=> + [name, {contact: MARTA, message}, by_fields(LINKEDIN_OPTS)]), + ]; + for (const [name, input, opts] of cases) + { + const e = await fail_by_fields(name, input, opts); + expect(e, name).toMatchObject({code: 'usage.contact', exit_code: 2}); + expect(shown(e), shown(e)).not.toMatch(PERSONAL); } expect(mock_fetch).not.toHaveBeenCalled(); }); + + it('refuses as the add commands do: two contacts held, an address or a profile Reply will not import, the plan\'s limit, ' + + 'an item the import failed; and nothing is sent', async()=>{ + const two = json({items: [{id: 1, email: 'marta@example.com'}, {id: 2, email: 'marta@example.com'}], hasMore: false}); + const cases: [Response[], string, number][] = [ + [[two], 'contact.not_unique', 1], + [[nobody(), nobody(), json({status: 400, errors: [{pointer: '/items/0/email', detail: '\'marta@example\' is not valid'}]}, 400)], + 'contact.invalid_email', 1], + [[nobody(), nobody(), json({status: 400, errors: [{pointer: '/items/0/linkedInUrl', detail: 'not valid'}]}, 400)], + 'contact.invalid_linkedin_url', 1], + [[nobody(), nobody(), json({code: 'contact.limitExceeded', detail: 'Contact limit reached.'}, 400)], 'account.contact_limit_reached', 1], + [[nobody(), nobody(), json({items: [{id: null, status: 'failed', error: 'Invalid data'}]})], 'reply.refused', 1], + ]; + for (const [answers, code, exit_code] of cases) + { + mock_fetch.mockReset(); + answer(...answers); + const e = await fail_by_fields('send-email', {contact: {...MARTA, linkedin_url: PROFILE}, message: {subject: SUBJECT, body: BODY}}, + by_fields(EMAIL_OPTS)); + expect(e, code).toMatchObject({code, exit_code, ids: {email_account_id: 12}}); + expect((e as {ids?: Record}).ids, code).not.toHaveProperty('contact_id'); + expect(shown(e), shown(e)).not.toMatch(PERSONAL); + expect(lines().filter(l=>l.includes('send-direct')), code).toEqual([]); + } + }); + + it('a lost answer to the import is outcome.unknown (exit 3) that says nothing was sent; one to the send says it may go ' + + 'twice, and names the contact', async()=>{ + mock_fetch.mockResolvedValueOnce(nobody()).mockRejectedValueOnce(lost_connection()); + const input = {contact: MARTA, message: {subject: SUBJECT, body: BODY}}; + const before = await fail_by_fields('send-email', input, by_fields(EMAIL_OPTS)) as {hint?: string; ids?: object}; + expect(before).toMatchObject({code: 'outcome.unknown', exit_code: 3}); + expect(before.hint, before.hint).toContain('Nothing was sent'); + expect(before.hint, before.hint).toContain('contact.already_held'); + expect(before.hint, before.hint).not.toContain('may send it twice'); + expect(before.ids, JSON.stringify(before.ids)).not.toHaveProperty('contact_id'); + expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT]); + mock_fetch.mockReset(); + mock_fetch.mockResolvedValueOnce(nobody()).mockResolvedValueOnce(imported(457)).mockRejectedValueOnce(lost_connection()); + const after = await fail_by_fields('send-email', input, by_fields(EMAIL_OPTS)) as {hint?: string}; + expect(after).toMatchObject({code: 'outcome.unknown', exit_code: 3, ids: {contact_id: 457, email_account_id: 12}}); + expect(after.hint, after.hint).toContain('may send it twice'); + expect(shown(after), shown(after)).not.toMatch(PERSONAL); + }); + + it('a refusal of the send after an import carries the contact it created, and an invitation to someone already connected ' + + 'names them too', async()=>{ + answer(nobody(), imported(457), json({code: 'contact.contactInBlackList'}, 400)); + const e = await fail_by_fields('send-email', {contact: MARTA, message: {subject: SUBJECT, body: BODY}}, by_fields(EMAIL_OPTS)); + expect(e).toMatchObject({code: 'contact.blacklisted', exit_code: 1, ids: {contact_id: 457, email_account_id: 12}}); + mock_fetch.mockReset(); + answer(nobody(), imported(458), json({code: 'directLinkedIn.alreadyConnected'}, 409)); + expect(await run_by_fields('linkedin-connect', {contact: {linkedin_url: PROFILE, first_name: 'Marta'}, message: {note: NOTE}}, + by_fields(LINKEDIN_OPTS))).toStrictEqual({ + status: 'already_connected', contact_id: 458, contact_created: true, activity_id: null, sent_at: null, + }); + }); + + it('an invitation without a note reads the person alone from stdin', async()=>{ + answer(nobody(), imported(458), activity('connect')); + const opts = {...by_fields(LINKEDIN_OPTS), message: undefined}; + await run_by_fields('linkedin-connect', {linkedin_url: PROFILE, first_name: 'Marta'}, opts); + expect(sent()[2].body).toStrictEqual({linkedInAccountId: 34}); + }); + + it('with --contact - and --message - both, stdin is one object holding each, read once', async()=>{ + answer(nobody(), imported(457), json({status: 'sent'})); + let reads = 0; + const input = JSON.stringify({contact: MARTA, message: {subject: SUBJECT, body: BODY}}); + await capture(()=>handle_direct_send('send-email', by_fields(EMAIL_OPTS), ctx(), {json: true}, ()=>{ reads++; return input; })); + expect(reads).toBe(1); + expect(sent()[2].body).toMatchObject({subject: SUBJECT, body: BODY}); + }); + + it('refuses stdin that is not that object, without repeating any of it and before any call', async()=>{ + const message = {subject: SUBJECT, body: BODY}; + const cases: [unknown, string][] = [ + ['not json, Marta', 'usage.stdin'], [[MARTA, message], 'usage.stdin'], [{contact: MARTA}, 'usage.stdin'], + [{message}, 'usage.stdin'], [{contact: MARTA, message, cc: 'marta@example.com'}, 'usage.stdin'], + [{...MARTA, ...message}, 'usage.stdin'], + [{contact: 'marta@example.com', message}, 'usage.contact'], [{contact: {...MARTA, phone: '1'}, message}, 'usage.contact'], + [{contact: MARTA, message: {subject: SUBJECT}}, 'usage.message'], [{contact: MARTA, message: 'Hi Marta'}, 'usage.message'], + ]; + for (const [input, code] of cases) + { + const e = await fail_by_fields('send-email', input, by_fields(EMAIL_OPTS)); + expect(e, JSON.stringify(input)).toMatchObject({code, exit_code: 2}); + expect(shown(e), shown(e)).not.toMatch(PERSONAL); + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('a person from a file leaves stdin to the text alone', async()=>{ + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'reply-send-')); + const file = path.join(dir, 'person.json'); + fs.writeFileSync(file, JSON.stringify(MARTA)); + try { + answer(nobody(), imported(457), json({status: 'sent'})); + await run_by_fields('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, contactId: undefined, contact: `@${file}`}); + expect(lines()).toEqual([EMAIL_LOOKUP, IMPORT, 'POST https://api/v3/contacts/457/send-direct-email']); + expect(sent()[2].body).toMatchObject({subject: SUBJECT, body: BODY}); + } finally { + fs.rmSync(dir, {recursive: true, force: true}); + } + }); }); diff --git a/src/__tests__/operations/program.test.ts b/src/__tests__/operations/program.test.ts index 2bd0626..a5c9833 100644 --- a/src/__tests__/operations/program.test.ts +++ b/src/__tests__/operations/program.test.ts @@ -109,6 +109,62 @@ describe('the program', ()=>{ } }); + // Stdin as the program reads it: descriptor 0 answers the text piped in, every other read goes to the disk. + const pipe_stdin = (text: string): void=>{ + const real = fs.readFileSync; + vi.spyOn(fs, 'readFileSync').mockImplementation(((file: fs.PathOrFileDescriptor, ...rest: unknown[])=> + (file === 0 ? text : (real as (...a: unknown[]) => unknown)(file, ...rest))) as typeof fs.readFileSync); + }; + const requests = ()=>(mock_fetch.mock.calls as [string, RequestInit][]).map(([url, init])=> + ({method: String(init.method), url, body: typeof init.body === 'string' ? JSON.parse(init.body) : undefined})); + const PERSONAL = /marta|example\.com|tuesday|cto/i; + + it('a send to a person Reply does not hold takes the person and the text from stdin: the argument list carries ' + + 'neither, and Reply gets both', async()=>{ + pipe_stdin(JSON.stringify({contact: {email: 'marta@example.com', first_name: 'Marta'}, + message: {subject: 'Hi Marta', body: 'Tuesday works'}})); + answer(json({items: [], hasMore: false}), json({items: [{id: 457, status: 'created'}]}), + json({code: 'contact.contactInBlackList'}, 400)); + const args = ['--json', '-k', 'key-1', 'contact', 'send-email', '--contact', '-', '--email-account-id', '12', '--message', '-']; + const {code, err} = await run_program(args); + expect(args.join(' '), args.join(' ')).not.toMatch(PERSONAL); + expect(code).toBe(1); + expect(JSON.parse(err)).toMatchObject({error: {code: 'contact.blacklisted', ids: {contact_id: 457, email_account_id: 12}}}); + expect(err, err).not.toMatch(PERSONAL); + expect(requests()).toEqual([ + {method: 'GET', url: 'https://api.reply.io/v3/contacts?email=marta%40example.com&top=100&skip=0', body: undefined}, + {method: 'POST', url: 'https://api.reply.io/v3/contacts/import', body: {items: [{email: 'marta@example.com', firstName: 'Marta'}]}}, + {method: 'POST', url: 'https://api.reply.io/v3/contacts/457/send-direct-email', + body: {emailAccountId: 12, subject: 'Hi Marta', body: 'Tuesday works'}}, + ]); + }); + + it('a send to a person Reply already holds exits 1, sends nothing, and names the contact', async()=>{ + pipe_stdin(JSON.stringify({contact: {email: 'marta@example.com', first_name: 'Marta'}, + message: {subject: 'Hi Marta', body: 'Tuesday works'}})); + // Were the send made, this refusal would answer it: a send Reply took ends without the exit this run waits for. + answer(json({items: [{id: 456, email: 'marta@example.com'}], hasMore: false}), json({code: 'contact.contactInBlackList'}, 400)); + const {code, err} = await run_program(['--json', '-k', 'key-1', 'contact', 'send-email', '--contact', '-', '--email-account-id', '12', + '--message', '-']); + expect(code).toBe(1); + expect(JSON.parse(err)).toMatchObject({error: {code: 'contact.already_held', ids: {contact_id: 456, email_account_id: 12}}}); + expect(err, err).not.toMatch(PERSONAL); + expect(requests().map(r=>r.method)).toEqual(['GET']); + }); + + it('contact update of a person Reply holds takes the person and the fields from stdin, and changes only the fields', async()=>{ + pipe_stdin(JSON.stringify({contact: {email: 'marta@example.com', linkedin_url: 'https://www.linkedin.com/in/marta-other'}, + fields: {title: 'CTO'}})); + answer(json({items: [{id: 456, email: 'marta@example.com'}], hasMore: false}), json('', 503)); + const args = ['--json', '-k', 'key-1', 'contact', 'update', '--contact', '-', '--fields', '-']; + const {code, err} = await run_program(args); + expect(args.join(' '), args.join(' ')).not.toMatch(PERSONAL); + expect(code).toBe(3); + expect(JSON.parse(err)).toMatchObject({error: {code: 'outcome.unknown', ids: {contact_id: 456}}}); + expect(requests().map(r=>[r.method, r.body])).toEqual([['GET', undefined], ['PATCH', {title: 'CTO'}]]); + expect(requests()[1].url).toBe('https://api.reply.io/v3/contacts/456'); + }); + it('account list is a work command of its own: a channel it does not know exits 2 before any request', async()=>{ const {code, err} = await run_program(['--json', '-k', 'key-1', 'account', 'list', '--channel', 'sms']); expect(code).toBe(2); diff --git a/src/operations/commands.ts b/src/operations/commands.ts index ab38a78..665d30e 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -2,7 +2,7 @@ import {Command} from 'commander'; import {PROGRAM_NAME} from '../config'; import {build_context} from '../context'; import {read_op_globals} from './options'; -import {add_contact_options, CONTACT_HELP} from './contact-input'; +import {add_contact_options, CONTACT_FORMS, CONTACT_HELP} from './contact-input'; import {handle_sequence_get, handle_sequence_contacts, handle_sequence_stats} from './sequence-read'; import {handle_sequence_list, handle_sequence_create} from './sequence-by-name'; import {handle_sequence_add_contact, handle_sequence_remove_contact} from './sequence-membership'; @@ -42,6 +42,13 @@ const piped = (command: string, contact = '{"email":"ann@example.com","first_nam const ALWAYS_IMPORTED = 'A contact given by email is always imported, so Reply needs a first name, even for one it already holds.\n' + 'One given only by LinkedIn URL is looked up first and imported only when Reply holds nobody under it.\n'; +// The codes a command that finds or imports a contact shares with the add commands. +const IMPORT_CODES = ['contact.not_unique', 'contact.invalid_email', 'contact.invalid_linkedin_url', 'account.contact_limit_reached']; + +// Both inputs on stdin, the person and the one the command acts with. +const STDIN_PAIR = (input: string): string=> + `With --contact - and --${input} - both, stdin holds one object: {"contact": {…}, "${input}": {…}}.\n`; + const run = (fn: (cmd: Command) => Promise)=>async function(this: Command): Promise { await fn(this); @@ -212,19 +219,27 @@ contact_command.command('get') await handle_contact_get(cmd.args[0], ctx, g); })); -contact_command.command('update') - .argument('', 'Contact id') +add_contact_options(contact_command.command('update') + .argument('[contact-id]', 'Contact id (or give the contact by the flags below)'), true) .option('--fields ', 'Only -: the fields to change as JSON on stdin') .description('Change some of a contact\'s fields and custom fields; the rest stay as they are') .addHelpText('after', help( [`echo '{"title":"CTO","company":"Acme"}' | ${P} contact update 456 --fields -`, - `echo '{"last_name":null,"custom_fields":[{"name":"leadSource","value":"Event"}]}' | ${P} contact update 456 --fields -`], - ['contact.not_found', 'contact.field_not_found'], true, - 'Result: {"status":"updated","contact_id"}\n' + `echo '{"last_name":null,"custom_fields":[{"name":"leadSource","value":"Event"}]}' | ${P} contact update 456 --fields -`, + `echo '{"contact":{"email":"ann@example.com","first_name":"Ann"},"fields":{"title":"CTO"}}' | ${P} contact update --contact - --fields -`], + ['contact.not_found', ...IMPORT_CODES, 'contact.field_not_found'], true, + 'Result: {"status":"updated","contact_id","contact_created"}\n' + 'Fields: {first_name, last_name, company, title, linkedin_url, custom_fields: [{name, value}]}; a field left out stays as\n' + 'it is, and null clears one. They are read from stdin only, so no value ever sits in the argument list. The CLI stores\n' + 'a LinkedIn URL by its lowercased slug, the form contacts are looked up by. A custom field is named as the account\n' - + 'names it (ignoring case); a name the account has none of is contact.field_not_found, and then nothing is changed.\n')) + + 'names it (ignoring case); a name the account has none of is contact.field_not_found, and then nothing is changed.\n' + + CONTACT_FORMS + + 'contact update 456 is contact update --contact-id 456. A contact given by its fields is looked up as the add commands\n' + + 'look one up, by its email, or one with only a LinkedIn URL by that, and imported only when Reply holds nobody under\n' + + 'it, as they import one; only then does Reply need a first name. A LinkedIn URL is matched by its lowercased slug,\n' + + 'and the CLI stores it by that slug when it imports the contact. Those fields only find or import the contact: on\n' + + 'one Reply holds, only what --fields names is changed. contact_created says whether this command created it.\n' + + STDIN_PAIR('fields'))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); await handle_contact_update(cmd.args[0], cmd.opts(), ctx, g); @@ -241,7 +256,7 @@ contact_command.command('delete') await handle_contact_delete(cmd.args[0], ctx, g); })); -add_contact_options(contact_command.command('opt-out')) +add_contact_options(contact_command.command('opt-out'), true) .description('Mark the contact as opted out at Reply, creating them only if Reply has nobody under the address') .addHelpText('after', help([piped('contact opt-out'), ex('contact opt-out --contact-id 456')], ['contact.not_found', 'contact.not_unique', 'contact.invalid_email', 'contact.invalid_linkedin_url', 'account.contact_limit_reached'], true, @@ -253,21 +268,47 @@ add_contact_options(contact_command.command('opt-out')) await handle_contact_opt_out(cmd.opts(), ctx, g); })); -const SEND_TWICE = (what: string): string=>`the ${what} may have been sent; running the command again may send it twice`; - -contact_command.command('send-email') - .option('--contact-id ', 'The contact by its Reply id') +const SEND_TWICE = (what: string): string=> + `the ${what} may have been sent; running the command again may send it twice, unless the hint says nothing was sent`; + +const LINKEDIN_URL_NEEDED = 'A LinkedIn send needs the contact\'s linkedin_url in --contact (or --contact-id); --email alone is refused ' + + '(usage.contact).\n'; + +// How a send names its contact: looked up by every address it was given, else imported as an add imports one; and +// it sends only to a contact it created, naming one Reply already holds instead. +const SENT_TO = (by: 'email' | 'linkedin', what: string): string=>CONTACT_FORMS + + 'A send given a person\'s fields sends only to a contact it creates. The contact is looked up by\n' + + `${by === 'email' ? 'its email' : 'its LinkedIn URL'}, where the ${what} goes, then by its ${by === 'email' ? 'LinkedIn URL' : 'email'} when it was given one, and imported only when\n` + + 'Reply holds nobody under any address given, as the add commands import one (matched by its email when it has\n' + + 'one), so Reply needs a first name. When a lookup finds a contact,\n' + + 'or the import matches one Reply already holds, nothing is sent: the answer is contact.already_held (exit 1)\n' + + 'with that contact\'s id in ids.contact_id. Read that contact first (contact get shows it, its opt-out included),\n' + + 'and send to it with --contact-id if it is the one to reach. A LinkedIn URL is matched by its lowercased slug, and\n' + + `the CLI stores it by that slug when it imports the contact. contact_id is the contact the ${what} went to, and\n` + + 'contact_created is kept for consistency with the add commands: given a person\'s fields it is always true, and with\n' + + '--contact-id it is always false; in both cases a successful answer says the send was made.\n' + + (by === 'email' ? '' : LINKEDIN_URL_NEEDED) + STDIN_PAIR('message'); + +// One send's example with the person and the text both on stdin. +const piped_send = (command: string, contact: string, message: string, flags: string): string=> + `echo '{"contact":${contact},"message":${message}}' | ${P} contact ${command} --contact - ${flags} --message -`; +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"}'; + +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') .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 -`], - ['contact.not_found', 'email_account.not_found', 'contact.blacklisted'], true, - 'Result: {"status":"sent","contact_id","message_id","sent_at","reply_status"}: sent means Reply accepted the email, and\n' - + 'reply_status is Reply\'s own word for it (new or sent). message_id is Reply\'s messageId, null when it gives none.\n' - + 'Reply\'s answer carries no time, so sent_at is always null; the CLI adds none of its own.\n' + [`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'], 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' + 'The email is read from stdin only, so its text never sits in the argument list. The body is HTML. Reply sends a\n' - + 'direct email at once, outside the mailbox\'s daily limit and sending delay.\n', + + 'direct email at once, outside the mailbox\'s daily limit and sending delay.\n' + + SENT_TO('email', 'email'), SEND_TWICE('email'))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); @@ -276,10 +317,10 @@ contact_command.command('send-email') // The four LinkedIn sends share their flags, their first codes and the shape of their result. const LINKEDIN_SEND_CODES = [ - 'contact.not_found', 'contact.no_linkedin_profile', 'linkedin.account_not_found', 'linkedin.feature_disabled', - 'linkedin.account_inactive', 'linkedin.invalid_cookie', + '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', ]; -const LINKEDIN_SENT = '"contact_id","activity_id","sent_at"}:\n' +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' + 'none; the CLI adds no time of its own.\n'; const VARIABLES = (where: string): string=> @@ -290,12 +331,11 @@ const linkedin_send = ( name: Exclude, description: string, message: string, examples: string[], codes: string[], extra: string, what: string, ): void=>{ - contact_command.command(name) - .option('--contact-id ', 'The contact by its Reply id') + 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`) .description(description) - .addHelpText('after', help(examples, [...LINKEDIN_SEND_CODES, ...codes], true, extra, SEND_TWICE(what))) + .addHelpText('after', help(examples, [...LINKEDIN_SEND_CODES, ...codes], true, extra + SENT_TO('linkedin', what), SEND_TWICE(what))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); await handle_direct_send(name, cmd.opts(), ctx, g); @@ -304,17 +344,21 @@ const linkedin_send = ( linkedin_send('linkedin-connect', 'Invite a contact to connect on LinkedIn, with or without a note', 'note {note}', [`echo '{"note":"Hi Ann, we met at the meetup."}' | ${P} contact linkedin-connect ${LINKEDIN_EXAMPLE} --message -`, - ex(`contact linkedin-connect ${LINKEDIN_EXAMPLE}`)], + ex(`contact linkedin-connect ${LINKEDIN_EXAMPLE}`), + piped_send('linkedin-connect', ANN_PROFILE, '{"note":"Hi Ann, we met at the meetup."}', '--linkedin-account-id 34'), + `echo '${ANN_PROFILE}' | ${P} contact linkedin-connect --contact - --linkedin-account-id 34`], ['linkedin.not_connected', 'linkedin.limit_reached', 'linkedin.message_too_long', 'linkedin.missing_variables'], 'Result: {"status":"sent"|"already_connected",' + LINKEDIN_SENT + 'already_connected means the contact is already a connection: nothing is sent, and activity_id and sent_at are null.\n' + 'The note is read from stdin only, so its text never sits in the argument list; without --message the invitation\n' - + 'carries no note. Reply publishes no limit for a note, and one it finds too long is linkedin.message_too_long.\n' + + 'carries no note, and stdin holds the contact alone. Reply publishes no limit for a note, and one it finds too long\n' + + 'is linkedin.message_too_long.\n' + VARIABLES('note'), 'invitation'); linkedin_send('linkedin-message', 'Send a LinkedIn message to a contact the account is connected with', 'message {body}', - [`echo '{"body":"Thanks for connecting, Ann."}' | ${P} contact linkedin-message ${LINKEDIN_EXAMPLE} --message -`], + [`echo '{"body":"Thanks for connecting, Ann."}' | ${P} contact linkedin-message ${LINKEDIN_EXAMPLE} --message -`, + piped_send('linkedin-message', ANN_PROFILE, '{"body":"Thanks for connecting, Ann."}', '--linkedin-account-id 34')], ['linkedin.not_connected', 'linkedin.limit_reached', 'linkedin.message_too_long', 'linkedin.missing_variables'], 'Result: {"status":"sent",' + LINKEDIN_SENT + 'The message is read from stdin only, so its text never sits in the argument list. Reply takes a body of at most\n' @@ -323,7 +367,8 @@ linkedin_send('linkedin-message', 'Send a LinkedIn message to a contact the acco linkedin_send('linkedin-inmail', 'Send a LinkedIn InMail, which reaches a contact the account is not connected with (needs Sales Navigator and InMail credits)', 'InMail {subject, body}', - [`echo '{"subject":"Quick question","body":"Hi Ann, does Tuesday work?"}' | ${P} contact linkedin-inmail ${LINKEDIN_EXAMPLE} --message -`], + [`echo '{"subject":"Quick question","body":"Hi Ann, does Tuesday work?"}' | ${P} contact linkedin-inmail ${LINKEDIN_EXAMPLE} --message -`, + piped_send('linkedin-inmail', ANN_PROFILE, '{"subject":"Quick question","body":"Hi Ann, does Tuesday work?"}', '--linkedin-account-id 34')], ['linkedin.limit_reached', 'linkedin.message_too_long', 'linkedin.missing_variables', 'linkedin.sales_navigator_required', 'linkedin.sales_navigator_disconnected', 'linkedin.no_inmail_credits'], 'Result: {"status":"sent",' + LINKEDIN_SENT @@ -332,7 +377,8 @@ linkedin_send('linkedin-inmail', 'Send a LinkedIn InMail, which reaches a contac 'InMail'); linkedin_send('linkedin-voice', 'Send a LinkedIn voice message that Reply speaks from a script in the account\'s voice', 'script {script}', - [`echo '{"script":"Hi Ann, a quick hello about Tuesday."}' | ${P} contact linkedin-voice ${LINKEDIN_EXAMPLE} --message -`], + [`echo '{"script":"Hi Ann, a quick hello about Tuesday."}' | ${P} contact linkedin-voice ${LINKEDIN_EXAMPLE} --message -`, + piped_send('linkedin-voice', ANN_PROFILE, '{"script":"Hi Ann, a quick hello about Tuesday."}', '--linkedin-account-id 34')], ['linkedin.not_connected', 'linkedin.limit_reached', 'linkedin.missing_variables', 'linkedin.voice_profile_missing', 'linkedin.voice_too_long'], 'Result: {"status":"sent",' + LINKEDIN_SENT diff --git a/src/operations/contact-input.ts b/src/operations/contact-input.ts index c56ec44..a231b9f 100644 --- a/src/operations/contact-input.ts +++ b/src/operations/contact-input.ts @@ -20,23 +20,27 @@ const PERSON_FIELDS = ['email', 'linkedin_url', 'first_name', 'last_name', 'comp const CODE = 'usage.contact'; const ONE_WAY_HINT = 'Use exactly one of --contact-id, --email (with its name flags), or --contact (which also takes linkedin_url).'; -const add_contact_options = (cmd: Command): Command=>cmd +// `found_first`: the command looks the contact up before it imports one, so the names only matter for a contact +// Reply doesn't hold yet and are otherwise unused. +const add_contact_options = (cmd: Command, found_first = false): Command=>cmd .option('--contact-id ', 'The contact by its Reply id') .option('--email
', 'The contact by email; with --first-name, --last-name, --company, --title') - .option('--first-name ', 'First name (with --email; Reply refuses to import a contact without one)') - .option('--last-name ', 'Last name (with --email)') - .option('--company ', 'Company (with --email)') - .option('--title ', 'Job title (with --email)') + .option('--first-name <name>', `First name (with --email; Reply refuses to import a contact without one)`) + .option('--last-name <name>', `Last name (with --email${found_first ? '; used only if the contact is imported' : ''})`) + .option('--company <name>', `Company (with --email${found_first ? '; used only if the contact is imported' : ''})`) + .option('--title <title>', `Job title (with --email${found_first ? '; used only if the contact is imported' : ''})`) .option('--contact <json>', 'The contact as JSON {email, linkedin_url, first_name, last_name, company, title}: inline, @file, or - for stdin'); -const CONTACT_HELP = ` +const CONTACT_FORMS = ` A contact is given exactly one way: --contact <json>|@file|- {email, linkedin_url, first_name, last_name, company, title}, with an email, a LinkedIn URL or both; '-' reads stdin, which keeps personal data out of the argument list --email <address> [--first-name <name>] [--last-name <name>] [--company <name>] [--title <title>] --contact-id <id> a contact Reply already holds -Reply is asked about a contact by its email; one with only a LinkedIn URL, by that. A LinkedIn URL is +`; + +const CONTACT_HELP = `${CONTACT_FORMS}Reply is asked about a contact by its email; one with only a LinkedIn URL, by that. A LinkedIn URL is matched by its lowercased slug, and the CLI stores it by that slug when it imports the contact. `; @@ -150,5 +154,5 @@ const read_contact_input = (f: Contact_flags, read_stdin?: () => string): Contac })}; }; -export {read_contact_input, add_contact_options, person_of, CONTACT_HELP, linkedin_key, is_email}; +export {read_contact_input, add_contact_options, person_of, CONTACT_FORMS, CONTACT_HELP, linkedin_key, is_email}; export type {Person, Contact_ref, Contact_flags}; diff --git a/src/operations/contact-record.ts b/src/operations/contact-record.ts index f2bc612..dd4ad77 100644 --- a/src/operations/contact-record.ts +++ b/src/operations/contact-record.ts @@ -1,10 +1,10 @@ import {PROGRAM_NAME} from '../config'; -import {Operation_error, Unknown_outcome_error, UsageError} from '../utils/errors'; +import {Operation_error, Unknown_outcome_error, UsageError, type Ids} from '../utils/errors'; import {call_reply, expect_object, is_object, refusal, unreadable, open_session, type Op_session} from './call'; import {parse_id, type Op_globals} from './options'; -import {person_of, linkedin_key} from './contact-input'; -import {find_contact_by_address, contact_not_found} from './contacts'; -import {read_stdin_object} from './stdin-input'; +import {person_of, linkedin_key, read_contact_input, type Contact_flags, type Contact_ref} from './contact-input'; +import {find_contact_by_address, find_or_import, contact_not_found} from './contacts'; +import {read_stdin_object, stdin_inputs} from './stdin-input'; import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; @@ -161,27 +161,55 @@ const resolve_custom_fields = async(s: Op_session, custom: Custom_value[]): Prom return custom.map(c=>({name: title_of(c.name) as string, value: c.value})); }; +type Update_opts = Contact_flags & {fields?: string}; + +// The contact id as the argument, as it always was, or the contact flags; never both. +const contact_to_update = (id_arg: string | undefined, opts: Update_opts, read_stdin: () => string): Contact_ref=>{ + if (id_arg === undefined) + { + return read_contact_input(opts, read_stdin); + } + if ([opts.contactId, opts.email, opts.firstName, opts.lastName, opts.company, opts.title, opts.contact].some(v=>v !== undefined)) + { + throw new UsageError('The contact was given more than one way.', { + code: 'usage.contact', hint: 'Give the contact id as the argument, or the contact by its flags, not both.', + }); + } + return {kind: 'id', id: parse_id(id_arg, 'Contact id')}; +}; + const handle_contact_update = async( - id_arg: string, opts: {fields?: string}, ctx: Cli_context, g: Op_globals, read_stdin?: () => string, + id_arg: string | undefined, opts: Update_opts, ctx: Cli_context, g: Op_globals, read_stdin?: () => string, ): Promise<void>=>{ - const id = parse_id(id_arg, 'Contact id'); - const {patch, custom} = read_contact_update(opts.fields, read_stdin); + const stdin = stdin_inputs({contact: opts.contact, fields: opts.fields}, { + code: 'usage.stdin', hint: `Pipe both in one object: echo '{"contact":{…},"fields":{…}}' | ${PROGRAM_NAME} contact update --contact - --fields -`, + }, read_stdin); + const contact = contact_to_update(id_arg, opts, stdin.contact); + const {patch, custom} = read_contact_update(opts.fields, stdin.fields); const s = await open_session(ctx, g); + const ids: Ids = contact.kind === 'id' ? {contact_id: contact.id} : {}; try { - // Absent fields stay as they are; a null clears one. Custom fields go by name. - const body = custom === undefined ? patch : {...patch, customFields: await resolve_custom_fields(s, custom)}; - const a = await call_reply(s, 'PATCH', `/v3/contacts/${id}`, 'write', body); + // Custom fields go by name, read before the contact is found or imported, so a name the account + // lacks changes nothing at all. + const custom_fields = custom === undefined ? undefined : await resolve_custom_fields(s, custom); + // The contact's fields only find the contact, or import it as an add would; the change is the + // --fields alone, so a contact Reply holds keeps the address it was found by. + const ensured = await find_or_import(s, contact); + ids.contact_id = ensured.id; + // Absent fields stay as they are; a null clears one. + const body = custom_fields === undefined ? patch : {...patch, customFields: custom_fields}; + const a = await call_reply(s, 'PATCH', `/v3/contacts/${ensured.id}`, 'write', body); if (a.status === 404) { - throw contact_not_found(id, a); + throw contact_not_found(ensured.id, a); } if (a.status !== 200 && a.status !== 204) { throw refusal(a, 'write'); } - print_result({status: 'updated', contact_id: id}, g); + print_result({status: 'updated', contact_id: ensured.id, contact_created: ensured.created}, g); } catch (e) { - throw with_ids(e, {contact_id: id}); + throw with_ids(e, ids); } }; @@ -210,3 +238,4 @@ const handle_contact_delete = async(id_arg: string, ctx: Cli_context, g: Op_glob }; export {handle_contact_find, handle_contact_get, handle_contact_update, handle_contact_delete}; +export type {Update_opts}; diff --git a/src/operations/contact.ts b/src/operations/contact.ts index 41a52c5..0698b2b 100644 --- a/src/operations/contact.ts +++ b/src/operations/contact.ts @@ -2,7 +2,7 @@ import {Operation_error, type Ids} from '../utils/errors'; import {call_reply, expect_object, item_failure, refusal, open_session, type Op_session} from './call'; import type {Op_globals} from './options'; import {read_contact_input, type Contact_flags} from './contact-input'; -import {find_contact_by_address, import_contact} from './contacts'; +import {find_or_import} from './contacts'; import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; @@ -36,22 +36,10 @@ const handle_contact_opt_out = async(opts: Opt_out_opts, ctx: Cli_context, g: Op try { // The person Reply already holds, so the opt-out lands on them. A contact is created only // when Reply holds nobody under the address, by an import that asks nothing again. - let contact_id: number; - let created = false; - if (contact.kind === 'id') - { - contact_id = contact.id; - } - else - { - const found = await find_contact_by_address(s, contact.person); - const ensured = found === null ? await import_contact(s, contact.person) : {id: found, created: false}; - contact_id = ensured.id; - created = ensured.created; - } - ids.contact_id = contact_id; - await set_opted_out(s, contact_id); - print_result({status: 'opted_out', contact_id, contact_created: created}, g); + const ensured = await find_or_import(s, contact); + ids.contact_id = ensured.id; + await set_opted_out(s, ensured.id); + print_result({status: 'opted_out', contact_id: ensured.id, contact_created: ensured.created}, g); } catch (e) { throw with_ids(e, ids); } diff --git a/src/operations/contacts.ts b/src/operations/contacts.ts index a5a50c7..181d4cd 100644 --- a/src/operations/contacts.ts +++ b/src/operations/contacts.ts @@ -99,17 +99,18 @@ const import_contact = async(s: Op_session, person: Person): Promise<Ensured>=>{ }; type Lookup = {param: 'email' | 'linkedIn'; values: string[]; holds: (entry: Record<string, unknown>) => boolean}; +type Channel = 'email' | 'linkedin'; -// What a person is looked up by: the email when there is one, else the LinkedIn URL. An entry -// counts only when it carries the same address: an email equal ignoring case, a LinkedIn URL equal -// under linkedin_key. +// What a person is looked up by: the channel named, which the person carries, or else the email when +// there is one, else the LinkedIn URL. An entry counts only when it carries the same address: an email +// equal ignoring case, a LinkedIn URL equal under linkedin_key. // INTERIM (API gap): the document does not say whether the exact lookup by LinkedIn URL ignores case. // Needed: a lookup that matches a LinkedIn URL by its slug whatever its case, or a word that it does. // Workaround: ask with the URL in the form it is written in (its lowercased slug) first, then as // given, and count the matches of both together, so one slug held under two spellings is refused // rather than half seen. -const lookup_of = (p: Person): Lookup=>{ - if (p.email !== undefined) +const lookup_of = (p: Person, by?: Channel): Lookup=>{ + if (p.email !== undefined && by !== 'linkedin') { const wanted = p.email.toLowerCase(); return {param: 'email', values: [p.email], holds: entry=>typeof entry.email === 'string' && entry.email.toLowerCase() === wanted}; @@ -162,8 +163,8 @@ const read_lookup = async(s: Op_session, lookup: Lookup, value: string, found_be throw new Operation_error('reply.unavailable', 'Reply answered the exact lookup with more pages than one address can fill.', {status: 200}); }; -const find_contact_by_address = async(s: Op_session, person: Person): Promise<number | null>=>{ - const lookup = lookup_of(person); +const find_contact_by_address = async(s: Op_session, person: Person, by?: Channel): Promise<number | null>=>{ + const lookup = lookup_of(person, by); let found: number | null = null; for (const value of lookup.values) { @@ -195,6 +196,18 @@ const ensure_contact = async(s: Op_session, ref: Contact_ref): Promise<Ensured>= return import_contact(s, ref.person); }; +// The contact a command acts on: the id given; else the one Reply holds under the address a lookup uses; +// else the person imported as an add imports them. Looking first means that a person Reply already holds needs +// no first name. +const find_or_import = async(s: Op_session, ref: Contact_ref): Promise<Ensured>=>{ + if (ref.kind === 'id') + { + return {id: ref.id, created: false}; + } + const found = await find_contact_by_address(s, ref.person); + return found === null ? import_contact(s, ref.person) : {id: found, created: false}; +}; + const find_contact = async(s: Op_session, ref: Contact_ref): Promise<number | null>=> ref.kind === 'id' ? ref.id : find_contact_by_address(s, ref.person); @@ -219,5 +232,5 @@ const read_opted_out = async(s: Op_session, contact_id: number): Promise<boolean return body.isOptedOut; }; -export {ensure_contact, import_contact, find_contact, find_contact_by_address, read_opted_out, contact_not_found}; -export type {Ensured}; +export {ensure_contact, find_or_import, import_contact, find_contact, find_contact_by_address, read_opted_out, contact_not_found}; +export type {Ensured, Channel}; diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index 996356c..19fe209 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -3,13 +3,14 @@ import {Operation_error, Unknown_outcome_error, UsageError, type Ids} from '../u import {parse_retry_after} from '../utils/client'; import {call_reply, expect_object, refusal, reply_code_of, detail_of, open_session, type Answer} from './call'; import {parse_id, LARGEST_SAFE_ID, type Op_globals} from './options'; -import {contact_not_found} from './contacts'; -import {read_stdin_object} from './stdin-input'; +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'; import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; type Direct_send_name = 'send-email' | 'linkedin-connect' | 'linkedin-message' | 'linkedin-inmail' | 'linkedin-voice'; -type Direct_send_opts = {contactId?: string; emailAccountId?: string; linkedinAccountId?: string; message?: string}; +type Direct_send_opts = Contact_flags & {emailAccountId?: string; linkedinAccountId?: string; message?: string}; type Text = Record<string, string>; type Direct_send = { @@ -165,53 +166,124 @@ const send_refusal = (a: Answer, contact_id: number): Operation_error=>{ const positive_integer = (v: unknown): number | null=> typeof v === 'number' && Number.isSafeInteger(v) && v > 0 ? v : null; -// What the CLI answers for a send Reply took. Neither adds a time of its own: Reply's answer to a -// direct email carries none, and a LinkedIn send's sentAtUtc is given as Reply gives it. -const result_of = (name: Direct_send_name, contact_id: number, sent: Record<string, unknown>): Record<string, unknown>=> +// 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 +// none, and a LinkedIn send's sentAtUtc is given as Reply gives it. +const result_of = (name: Direct_send_name, contact: Ensured, sent: Record<string, unknown>): Record<string, unknown>=> name === 'send-email' ? { - status: 'sent', contact_id, + status: 'sent', contact_id: contact.id, contact_created: contact.created, message_id: typeof sent.messageId === 'string' ? sent.messageId : null, sent_at: null, reply_status: typeof sent.status === 'string' ? sent.status : null, } : { - status: 'sent', contact_id, + status: 'sent', contact_id: contact.id, contact_created: contact.created, activity_id: positive_integer(sent.linkedInActivityId), sent_at: typeof sent.sentAtUtc === 'string' ? sent.sentAtUtc : null, }; +// A person given by their fields is looked up by the address the send reaches them at, so one who +// lacks it is refused before anything is asked. The address is never repeated. +const require_address = (name: Direct_send_name, contact: Contact_ref, by: Channel): void=>{ + if (contact.kind === 'person' && (by === 'email' ? contact.person.email : contact.person.linkedin_url) === undefined) + { + throw new UsageError(by === 'email' + ? `contact ${name} needs the contact's email: the email goes to it.` + : `contact ${name} needs the contact's linkedin_url: the send goes to that profile.`, { + code: 'usage.contact', hint: 'Give it in --contact, or name a contact Reply holds with --contact-id.', + }); + } +}; + +// INTERIM (API gap): Reply does not refuse a direct send to a contact it holds as opted out, so the only guard on that +// opt-out is a caller that reads the contact before it sends. +// Needed: a direct send that refuses a contact Reply holds as opted out. +// Workaround: a send given a person's fields acts only on a contact it created. One Reply already holds, found by the +// lookup or matched by the import, is refused before anything is sent, and named, for the caller to read and then send +// to by its id. +const already_held = (contact_id: number): Operation_error=> + new Operation_error('contact.already_held', + `Reply already holds contact ${contact_id} under what was given, so nothing was sent: a send given a person's fields goes only to a contact it creates.`, { + status: 200, + hint: `Read it first with ${PROGRAM_NAME} contact get ${contact_id}; if it is the one to reach, send to it with --contact-id ${contact_id}.`, + }); + const handle_direct_send = async( name: Direct_send_name, opts: Direct_send_opts, ctx: Cli_context, g: Op_globals, read_stdin?: () => string, ): Promise<void>=>{ const send = DIRECT_SENDS[name]; - const contact_id = required_id(opts.contactId, '--contact-id'); + const stdin = stdin_inputs({contact: opts.contact, message: opts.message}, { + code: 'usage.stdin', hint: `Pipe both in one object: echo '{"contact":{…},"message":{…}}' | ${PROGRAM_NAME} contact ${name} --contact - … --message -`, + }, read_stdin); + const contact = read_contact_input(opts, stdin.contact); // A send always names the account it goes from: Reply would send an email from the default mailbox. const by_email = name === 'send-email'; + const by: Channel = by_email ? 'email' : 'linkedin'; + require_address(name, contact, by); const account_id = by_email ? required_id(opts.emailAccountId, '--email-account-id', LARGEST_SAFE_ID) : required_id(opts.linkedinAccountId, '--linkedin-account-id'); - const ids: Ids = by_email ? {contact_id, email_account_id: account_id} : {contact_id, linkedin_account_id: account_id}; - const text = read_text(name, send, opts.message, read_stdin); + const ids: Ids = by_email ? {email_account_id: account_id} : {linkedin_account_id: account_id}; + const text = read_text(name, send, opts.message, stdin.message); const s = await open_session(ctx, g); + let sending = false; try { - const a = await call_reply(s, 'POST', `/v3/contacts/${contact_id}/${send.path}`, 'write', send.body(account_id, text)); + // The contact first, found or imported as an add would; a person given by their fields is sent to only when + // this import created them. + let ensured: Ensured; + if (contact.kind === 'person') + { + // A person is looked up by every address given, the one the send reaches them at first: a hit under any of + // them is a contact Reply holds, and the first one found is the one named. + const other: Channel = by === 'email' ? 'linkedin' : 'email'; + for (const channel of [by, other]) + { + if ((channel === 'email' ? contact.person.email : contact.person.linkedin_url) === undefined) + { + continue; + } + const held = await find_contact_by_address(s, contact.person, channel); + if (held !== null) + { + ids.contact_id = held; + throw already_held(held); + } + } + ensured = await import_contact(s, contact.person); + ids.contact_id = ensured.id; + if (!ensured.created) + { + throw already_held(ensured.id); + } + } + else + { + ensured = {id: contact.id, created: false}; + ids.contact_id = ensured.id; + } + sending = true; + const a = await call_reply(s, 'POST', `/v3/contacts/${ensured.id}/${send.path}`, 'write', send.body(account_id, text)); if (name === 'linkedin-connect' && a.status === 409 && reply_code_of(a) === 'directLinkedIn.alreadyConnected') { // Nothing was sent, and nothing needs to be: the contact is already a connection. - print_result({status: 'already_connected', contact_id, activity_id: null, sent_at: null}, g); + print_result({status: 'already_connected', contact_id: ensured.id, contact_created: ensured.created, activity_id: null, sent_at: null}, g); return; } if (a.status !== 200) { - throw send_refusal(a, contact_id); + throw send_refusal(a, ensured.id); } - print_result(result_of(name, contact_id, expect_object(a, 'write')), g); + print_result(result_of(name, ensured, expect_object(a, 'write')), g); } catch (e) { - // Unlike most work commands, a send is not safe to repeat: the same text would go twice. + // Unlike most work commands, a send is not safe to repeat: the same text would go twice. Before + // the send was made, only the contact's import can have been lost, and that is safe to repeat. if (e instanceof Unknown_outcome_error) { - e.hint = `The ${send.what} may have been sent; running the command again may send it twice.`; + e.hint = sending + ? `The ${send.what} may have been sent; running the command again may send it twice.` + : `Nothing was sent: the outcome of the contact's import is unknown, so the ${send.what} was never made. ` + + 'Running the command again is safe: if the import did create the contact, it answers contact.already_held with its id.'; } throw with_ids(e, ids); } diff --git a/src/operations/stdin-input.ts b/src/operations/stdin-input.ts index ae89635..55a6fba 100644 --- a/src/operations/stdin-input.ts +++ b/src/operations/stdin-input.ts @@ -39,5 +39,46 @@ const read_stdin_object = (source: string | undefined, o: Stdin_object_opts, rea return value; }; -export {read_stdin_object}; +// The person and their text, each read from stdin by its own flag. When both flags take '-', stdin +// holds one object with each input under its flag's name, {"contact": {…}, "message": {…}}; it is +// read once, and each flag is handed its member as the text it would have read alone. When at most +// one does, that one reads stdin as ever. No message here repeats any of it: an unknown member is +// named, never its value. +const stdin_inputs = <K extends string>( + sources: Record<K, string | undefined>, o: {code: string; hint: string}, read_stdin?: () => string, +): Record<K, () => string>=>{ + const read = read_stdin ?? read_all_stdin; + const names = Object.keys(sources) as K[]; + const piped = names.filter(n=>sources[n] === '-'); + if (piped.length < 2) + { + return Object.fromEntries(names.map(n=>[n, read])) as Record<K, () => string>; + } + const flags = piped.map(n=>`--${n} -`).join(' and '); + const shape = `{${piped.map(n=>`"${n}": {…}`).join(', ')}}`; + let value: unknown; + try { + value = JSON.parse(read()); + } catch { + throw new UsageError(`With ${flags} both, stdin must be JSON: ${shape}.`, {code: o.code, hint: o.hint}); + } + if (!is_object(value)) + { + throw new UsageError(`With ${flags} both, stdin must be one JSON object: ${shape}.`, {code: o.code, hint: o.hint}); + } + const input = value; + const unknown_field = Object.keys(input).find(k=>!(piped as string[]).includes(k)); + if (unknown_field !== undefined) + { + throw new UsageError(`Stdin has an unknown field '${unknown_field}'.`, {code: o.code, hint: `Fields: ${piped.join(', ')}.`}); + } + const missing = piped.find(n=>input[n] === undefined); + if (missing !== undefined) + { + throw new UsageError(`Stdin has no ${missing}: with ${flags} both, it holds ${shape}.`, {code: o.code, hint: o.hint}); + } + return Object.fromEntries(names.map(n=>[n, sources[n] === '-' ? ()=>JSON.stringify(input[n]) : read])) as Record<K, () => string>; +}; + +export {read_stdin_object, stdin_inputs}; export type {Stdin_object_opts};