@sdflc/backend-helpers 1.0.142 → 1.0.144
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -0
- package/build/BaseGateway.d.ts +7 -0
- package/build/BaseGateway.js +52 -1
- package/build/esm/BaseGateway.d.ts +7 -0
- package/build/esm/BaseGateway.js +52 -1
- package/build/esm/gateways/HubSpotGw.d.ts +46 -0
- package/build/esm/gateways/HubSpotGw.js +181 -0
- package/build/esm/gateways/MailchimpGw.d.ts +57 -0
- package/build/esm/gateways/MailchimpGw.js +187 -0
- package/build/esm/gateways/index.d.ts +2 -0
- package/build/esm/gateways/index.js +2 -0
- package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +11 -0
- package/build/gateways/HubSpotGw.d.ts +46 -0
- package/build/gateways/HubSpotGw.js +184 -0
- package/build/gateways/MailchimpGw.d.ts +57 -0
- package/build/gateways/MailchimpGw.js +192 -0
- package/build/gateways/index.d.ts +2 -0
- package/build/gateways/index.js +2 -0
- package/build/interfaces/BaseGatewayPropsInterface.d.ts +11 -0
- package/package.json +2 -2
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// ./src/gateways/MailchimpGw.ts
|
|
2
|
+
//
|
|
3
|
+
// Mailchimp's Marketing API (https://mailchimp.com/developer/marketing/api/) — the calls that put a person into a host's
|
|
4
|
+
// audience: a member added or updated by email, tags on it, a note on it, and the audiences to choose from.
|
|
5
|
+
//
|
|
6
|
+
// const mailchimp = new MailchimpGw().configure({ apiKey });
|
|
7
|
+
// await mailchimp.upsertMember(audienceId, { email, mergeFields: { FNAME: 'Ann' }, statusIfNew: 'transactional' });
|
|
8
|
+
// await mailchimp.addTags(audienceId, email, ['Volunteers']);
|
|
9
|
+
// await mailchimp.addNote(audienceId, email, 'Signed up to volunteer at …');
|
|
10
|
+
//
|
|
11
|
+
// The API key ends with its data centre (`…-us21`), which names the server: https://us21.api.mailchimp.com/3.0.
|
|
12
|
+
//
|
|
13
|
+
// ⚠ The key IS the credential — it (and the Basic header made of it) is scrubbed out of every error.
|
|
14
|
+
// ⚠ An existing member's subscription is never changed: only `status_if_new` is sent, which Mailchimp applies to a NEW
|
|
15
|
+
// member. Someone who unsubscribed stays unsubscribed.
|
|
16
|
+
// ⚠ At most 10 connections at once per Mailchimp user — callers send one member at a time.
|
|
17
|
+
import { createHash } from 'crypto';
|
|
18
|
+
import { Buffer } from 'buffer';
|
|
19
|
+
import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
|
|
20
|
+
import { BaseExternalApiGateway } from './BaseExternalApiGateway';
|
|
21
|
+
export const MAILCHIMP_STATUSES_IF_NEW = ['transactional', 'pending', 'subscribed'];
|
|
22
|
+
/** Mailchimp's own limit on a note. */
|
|
23
|
+
export const MAILCHIMP_NOTE_MAX = 1000;
|
|
24
|
+
/** A tag's name, at most (Mailchimp's limit). */
|
|
25
|
+
export const MAILCHIMP_TAG_MAX = 100;
|
|
26
|
+
const text = (value) => String(value ?? '').trim();
|
|
27
|
+
/** The data centre at the end of an API key (`us21`), or null. Pure. */
|
|
28
|
+
export const mailchimpDataCenterOf = (apiKey) => {
|
|
29
|
+
const match = /^[0-9a-f]{32}-([a-z]{2,4}\d{1,3})$/i.exec(text(apiKey));
|
|
30
|
+
return match ? match[1].toLowerCase() : null;
|
|
31
|
+
};
|
|
32
|
+
/** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
|
|
33
|
+
export const mailchimpSubscriberHash = (email) => createHash('md5').update(text(email).toLowerCase()).digest('hex');
|
|
34
|
+
class MailchimpGw extends BaseExternalApiGateway {
|
|
35
|
+
constructor(props) {
|
|
36
|
+
super(props);
|
|
37
|
+
}
|
|
38
|
+
validateSettings(settings) {
|
|
39
|
+
return mailchimpDataCenterOf(settings.apiKey) ? [] : ['the API key is missing or not a Mailchimp one (…-us21)'];
|
|
40
|
+
}
|
|
41
|
+
secretValues() {
|
|
42
|
+
const key = text(this.settings.apiKey);
|
|
43
|
+
return [key, Buffer.from(`anystring:${key}`).toString('base64')];
|
|
44
|
+
}
|
|
45
|
+
/** Mailchimp's error shape (problem+json): `{ title, status, detail, errors: [{ field, message }] }`. */
|
|
46
|
+
errorMessageOf(reply) {
|
|
47
|
+
const body = reply.body;
|
|
48
|
+
if (body && typeof body === 'object') {
|
|
49
|
+
const fields = Array.isArray(body.errors)
|
|
50
|
+
? body.errors.map((e) => [e?.field, e?.message].filter(Boolean).join(' ')).join('; ')
|
|
51
|
+
: '';
|
|
52
|
+
return [body.title, body.detail, fields].filter(Boolean).join(': ').slice(0, 500) || `HTTP ${reply.status}`;
|
|
53
|
+
}
|
|
54
|
+
return super.errorMessageOf(reply);
|
|
55
|
+
}
|
|
56
|
+
call(method, path, json) {
|
|
57
|
+
const key = text(this.settings.apiKey);
|
|
58
|
+
return this.requestWithRetries({
|
|
59
|
+
url: `https://${mailchimpDataCenterOf(key)}.api.mailchimp.com/3.0${path}`,
|
|
60
|
+
method,
|
|
61
|
+
headers: {
|
|
62
|
+
Authorization: `Basic ${Buffer.from(`anystring:${key}`).toString('base64')}`,
|
|
63
|
+
Accept: 'application/json',
|
|
64
|
+
},
|
|
65
|
+
...(json === undefined ? {} : { json }),
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
/** An audience id may only be letters and digits — it goes into the path. */
|
|
69
|
+
badAudience(audienceId) {
|
|
70
|
+
return /^[A-Za-z0-9]{1,32}$/.test(text(audienceId))
|
|
71
|
+
? null
|
|
72
|
+
: OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The audience id is not one');
|
|
73
|
+
}
|
|
74
|
+
memberPath(audienceId, email) {
|
|
75
|
+
return `/lists/${text(audienceId)}/members/${mailchimpSubscriberHash(email)}`;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The member with this email, added or updated (one PUT). A NEW member gets `statusIfNew`; an existing one keeps its
|
|
79
|
+
* subscription. Required merge fields the host added are not demanded (`skip_merge_validation`). OK with
|
|
80
|
+
* `{ memberId, status }`. Never throws.
|
|
81
|
+
*/
|
|
82
|
+
async upsertMember(audienceId, member) {
|
|
83
|
+
if (!this.isConfigured()) {
|
|
84
|
+
return this.notConfigured();
|
|
85
|
+
}
|
|
86
|
+
const email = text(member?.email).toLowerCase();
|
|
87
|
+
const bad = this.badAudience(audienceId);
|
|
88
|
+
if (bad) {
|
|
89
|
+
return bad;
|
|
90
|
+
}
|
|
91
|
+
if (!email.includes('@')) {
|
|
92
|
+
return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The member has no email');
|
|
93
|
+
}
|
|
94
|
+
const statusIfNew = MAILCHIMP_STATUSES_IF_NEW.includes(member.statusIfNew)
|
|
95
|
+
? member.statusIfNew
|
|
96
|
+
: 'transactional';
|
|
97
|
+
const mergeFields = {};
|
|
98
|
+
for (const [tag, value] of Object.entries(member.mergeFields ?? {})) {
|
|
99
|
+
if (/^[A-Z0-9_]{1,10}$/.test(tag) && text(value)) {
|
|
100
|
+
mergeFields[tag] = text(value);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const result = await this.call('PUT', `${this.memberPath(audienceId, email)}?skip_merge_validation=true`, {
|
|
104
|
+
email_address: email,
|
|
105
|
+
status_if_new: statusIfNew,
|
|
106
|
+
...(Object.keys(mergeFields).length ? { merge_fields: mergeFields } : {}),
|
|
107
|
+
});
|
|
108
|
+
if (result.didFail()) {
|
|
109
|
+
return result;
|
|
110
|
+
}
|
|
111
|
+
const body = result.getDataFirst()?.body ?? {};
|
|
112
|
+
return OpResult.ok([
|
|
113
|
+
{ memberId: body.id ? String(body.id) : mailchimpSubscriberHash(email), status: body.status ?? null },
|
|
114
|
+
]);
|
|
115
|
+
}
|
|
116
|
+
/** Tags ADDED to a member (made in the audience when new; the member's other tags kept). OK with `{ tags }`. */
|
|
117
|
+
async addTags(audienceId, email, tags) {
|
|
118
|
+
if (!this.isConfigured()) {
|
|
119
|
+
return this.notConfigured();
|
|
120
|
+
}
|
|
121
|
+
const bad = this.badAudience(audienceId);
|
|
122
|
+
const names = Array.from(new Set((tags ?? []).map((t) => text(t).slice(0, MAILCHIMP_TAG_MAX)).filter(Boolean)));
|
|
123
|
+
if (bad) {
|
|
124
|
+
return bad;
|
|
125
|
+
}
|
|
126
|
+
if (!text(email).includes('@') || names.length === 0) {
|
|
127
|
+
return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A member and at least one tag are needed');
|
|
128
|
+
}
|
|
129
|
+
const result = await this.call('POST', `${this.memberPath(audienceId, email)}/tags`, {
|
|
130
|
+
tags: names.map((name) => ({ name, status: 'active' })),
|
|
131
|
+
});
|
|
132
|
+
return result.didFail() ? result : OpResult.ok([{ tags: names }]);
|
|
133
|
+
}
|
|
134
|
+
/** A note on a member (cut to Mailchimp's 1,000 characters). OK with `{ noteId }`. Never throws. */
|
|
135
|
+
async addNote(audienceId, email, note) {
|
|
136
|
+
if (!this.isConfigured()) {
|
|
137
|
+
return this.notConfigured();
|
|
138
|
+
}
|
|
139
|
+
const bad = this.badAudience(audienceId);
|
|
140
|
+
if (bad) {
|
|
141
|
+
return bad;
|
|
142
|
+
}
|
|
143
|
+
if (!text(email).includes('@') || !text(note)) {
|
|
144
|
+
return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A member and the note are needed');
|
|
145
|
+
}
|
|
146
|
+
const result = await this.call('POST', `${this.memberPath(audienceId, email)}/notes`, {
|
|
147
|
+
note: String(note).slice(0, MAILCHIMP_NOTE_MAX),
|
|
148
|
+
});
|
|
149
|
+
return result.didFail() ? result : OpResult.ok([{ noteId: result.getDataFirst()?.body?.id ?? null }]);
|
|
150
|
+
}
|
|
151
|
+
/** The account's audiences (at most 1,000), by name. Never throws. */
|
|
152
|
+
async listAudiences() {
|
|
153
|
+
if (!this.isConfigured()) {
|
|
154
|
+
return this.notConfigured();
|
|
155
|
+
}
|
|
156
|
+
const result = await this.call('GET', '/lists?count=1000&fields=lists.id,lists.name,lists.stats.member_count');
|
|
157
|
+
if (result.didFail()) {
|
|
158
|
+
return result;
|
|
159
|
+
}
|
|
160
|
+
const audiences = (result.getDataFirst()?.body?.lists ?? [])
|
|
161
|
+
.map((l) => ({
|
|
162
|
+
id: String(l?.id ?? ''),
|
|
163
|
+
name: text(l?.name) || String(l?.id ?? ''),
|
|
164
|
+
memberCount: l?.stats?.member_count ?? null,
|
|
165
|
+
}))
|
|
166
|
+
.filter((l) => !!l.id)
|
|
167
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
168
|
+
return OpResult.ok(audiences);
|
|
169
|
+
}
|
|
170
|
+
/** One audience — OK with `{ id, name }`; NOT_FOUND when the account has none by that id. Never throws. */
|
|
171
|
+
async getAudience(audienceId) {
|
|
172
|
+
if (!this.isConfigured()) {
|
|
173
|
+
return this.notConfigured();
|
|
174
|
+
}
|
|
175
|
+
const bad = this.badAudience(audienceId);
|
|
176
|
+
if (bad) {
|
|
177
|
+
return bad;
|
|
178
|
+
}
|
|
179
|
+
const result = await this.call('GET', `/lists/${text(audienceId)}?fields=id,name`);
|
|
180
|
+
if (result.didFail()) {
|
|
181
|
+
return result;
|
|
182
|
+
}
|
|
183
|
+
const body = result.getDataFirst()?.body ?? {};
|
|
184
|
+
return OpResult.ok([{ id: String(body.id ?? audienceId), name: text(body.name) || String(audienceId) }]);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
export { MailchimpGw };
|
|
@@ -74,6 +74,17 @@ export interface BaseGatewayPropsInterface extends CacheInterface {
|
|
|
74
74
|
*/
|
|
75
75
|
localizationForField?: string;
|
|
76
76
|
defaultSorting?: SortItemInterface[];
|
|
77
|
+
/**
|
|
78
|
+
* The column `list()` adds as the LAST sort term whenever it applies a limit, so rows that tie on the caller's sort
|
|
79
|
+
* come back in the same order on every page. Defaults to the id field, qualified with the table's own name
|
|
80
|
+
* (`getListTieBreaker()`). `false` turns it off — for a list query it would break (one that groups, selects
|
|
81
|
+
* DISTINCT, or reads the table under an alias). A string names a different unique column.
|
|
82
|
+
*
|
|
83
|
+
* ⚠ Without it, Postgres does not promise the same order of tied rows from one LIMIT/OFFSET to the next: page 2 can
|
|
84
|
+
* repeat a row from page 1 and skip another for good — rows created together (one bulk insert = one created_at) or a
|
|
85
|
+
* shared `order_no` / name tie all the time. (SQL Server also refuses OFFSET/FETCH — page 2 — with no ORDER BY.)
|
|
86
|
+
*/
|
|
87
|
+
listTieBreaker?: string | false;
|
|
77
88
|
/**
|
|
78
89
|
* Field to apply keyword (ILIKE) search against when filterParams.keyword is set.
|
|
79
90
|
*/
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { OpResult } from '@sdflc/api-helpers';
|
|
2
|
+
import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
|
|
3
|
+
import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
|
|
4
|
+
export interface HubSpotSettings {
|
|
5
|
+
/** A service key or a private app token (`pat-na1-…`). */
|
|
6
|
+
accessToken: string;
|
|
7
|
+
}
|
|
8
|
+
export interface HubSpotContact {
|
|
9
|
+
/** The contact is found — or made — by this. */
|
|
10
|
+
email: string;
|
|
11
|
+
firstName?: string | null;
|
|
12
|
+
lastName?: string | null;
|
|
13
|
+
phone?: string | null;
|
|
14
|
+
company?: string | null;
|
|
15
|
+
}
|
|
16
|
+
/** A static list as `listStaticLists` returns it. */
|
|
17
|
+
export interface HubSpotList {
|
|
18
|
+
id: string;
|
|
19
|
+
name: string;
|
|
20
|
+
processingType: string;
|
|
21
|
+
}
|
|
22
|
+
export declare const HUBSPOT_API_URL = "https://api.hubapi.com";
|
|
23
|
+
declare class HubSpotGw extends BaseExternalApiGateway<HubSpotSettings> {
|
|
24
|
+
constructor(props?: BaseExternalApiGatewayPropsInterface<HubSpotSettings>);
|
|
25
|
+
protected validateSettings(settings: Partial<HubSpotSettings>): string[];
|
|
26
|
+
protected secretValues(): string[];
|
|
27
|
+
/** HubSpot's error shape: `{ status: 'error', message, category, correlationId }`. */
|
|
28
|
+
protected errorMessageOf(reply: ExternalApiReply): string;
|
|
29
|
+
private call;
|
|
30
|
+
/**
|
|
31
|
+
* The contact with this email, created or updated (one call — HubSpot's upsert by email). Only the values given are
|
|
32
|
+
* written; an empty one never blanks what HubSpot holds. OK with `{ contactId, created }`. Never throws.
|
|
33
|
+
*/
|
|
34
|
+
upsertContact(contact: HubSpotContact): Promise<OpResult>;
|
|
35
|
+
/** Puts contacts into a static list (already members are skipped by HubSpot). OK with `{ listId, added }`. Never throws. */
|
|
36
|
+
addToList(listId: string, contactIds: string[]): Promise<OpResult>;
|
|
37
|
+
/** A note on a contact, dated `at` (HubSpot shows `body` as rich text — pass HTML, escaped). OK with `{ noteId }`. */
|
|
38
|
+
addNote(contactId: string, body: string, at?: Date): Promise<OpResult>;
|
|
39
|
+
/** The account's static CONTACT lists (the ones that take members), at most 500, by name. Never throws. */
|
|
40
|
+
listStaticLists(query?: string): Promise<OpResult>;
|
|
41
|
+
/** One list by id — OK with `{ id, name, processingType, isStatic }`; NOT_FOUND when HubSpot has none. Never throws. */
|
|
42
|
+
getList(listId: string): Promise<OpResult>;
|
|
43
|
+
/** Can the token read contacts? (One contact asked for, nothing written.) OK with `{ ok: true }`. Never throws. */
|
|
44
|
+
verify(): Promise<OpResult>;
|
|
45
|
+
}
|
|
46
|
+
export { HubSpotGw };
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.HubSpotGw = exports.HUBSPOT_API_URL = void 0;
|
|
4
|
+
// ./src/gateways/HubSpotGw.ts
|
|
5
|
+
//
|
|
6
|
+
// HubSpot's CRM (https://developers.hubspot.com/docs/api-reference) — the calls that put a person into a host's HubSpot:
|
|
7
|
+
// a contact created or updated by email, a note on it, and membership of a static list.
|
|
8
|
+
//
|
|
9
|
+
// const hubspot = new HubSpotGw().configure({ accessToken });
|
|
10
|
+
// const contact = await hubspot.upsertContact({ email, firstName, lastName });
|
|
11
|
+
// await hubspot.addToList(listId, [contact.getDataFirst().contactId]);
|
|
12
|
+
// await hubspot.addNote(contact.getDataFirst().contactId, '<p>Registered for …</p>');
|
|
13
|
+
//
|
|
14
|
+
// The token is a SERVICE KEY (HubSpot › Development › Keys › Service keys) or a legacy private app's token — both are
|
|
15
|
+
// sent as `Authorization: Bearer pat-…`. The scopes it needs: crm.objects.contacts.read / .write (contacts and their
|
|
16
|
+
// notes), crm.lists.read / .write (static lists).
|
|
17
|
+
//
|
|
18
|
+
// ⚠ The token IS the credential — it is scrubbed out of every error.
|
|
19
|
+
// ⚠ Only a static list (processingType MANUAL or SNAPSHOT) takes members; HubSpot refuses a dynamic one.
|
|
20
|
+
const api_helpers_1 = require("@sdflc/api-helpers");
|
|
21
|
+
const BaseExternalApiGateway_1 = require("./BaseExternalApiGateway");
|
|
22
|
+
exports.HUBSPOT_API_URL = 'https://api.hubapi.com';
|
|
23
|
+
/** The association type of a note to a contact (HUBSPOT_DEFINED). */
|
|
24
|
+
const NOTE_TO_CONTACT = 202;
|
|
25
|
+
/** The contacts object type (lists name it so). */
|
|
26
|
+
const CONTACTS_OBJECT_TYPE = '0-1';
|
|
27
|
+
/** The list types that take members by id. */
|
|
28
|
+
const STATIC_PROCESSING_TYPES = ['MANUAL', 'SNAPSHOT'];
|
|
29
|
+
const text = (value) => String(value ?? '').trim();
|
|
30
|
+
class HubSpotGw extends BaseExternalApiGateway_1.BaseExternalApiGateway {
|
|
31
|
+
constructor(props) {
|
|
32
|
+
super({ baseUrl: exports.HUBSPOT_API_URL, ...(props ?? {}) });
|
|
33
|
+
}
|
|
34
|
+
validateSettings(settings) {
|
|
35
|
+
return /^[A-Za-z0-9._-]{20,256}$/.test(text(settings.accessToken))
|
|
36
|
+
? []
|
|
37
|
+
: ['the access token is missing or not a HubSpot one (pat-…)'];
|
|
38
|
+
}
|
|
39
|
+
secretValues() {
|
|
40
|
+
return [text(this.settings.accessToken)];
|
|
41
|
+
}
|
|
42
|
+
/** HubSpot's error shape: `{ status: 'error', message, category, correlationId }`. */
|
|
43
|
+
errorMessageOf(reply) {
|
|
44
|
+
const body = reply.body;
|
|
45
|
+
if (body && typeof body === 'object') {
|
|
46
|
+
return [body.category, body.message].filter(Boolean).join(': ').slice(0, 500) || `HTTP ${reply.status}`;
|
|
47
|
+
}
|
|
48
|
+
return super.errorMessageOf(reply);
|
|
49
|
+
}
|
|
50
|
+
call(method, path, json) {
|
|
51
|
+
return this.requestWithRetries({
|
|
52
|
+
url: `${this.baseUrl}${path}`,
|
|
53
|
+
method,
|
|
54
|
+
headers: { Authorization: `Bearer ${text(this.settings.accessToken)}`, Accept: 'application/json' },
|
|
55
|
+
...(json === undefined ? {} : { json }),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The contact with this email, created or updated (one call — HubSpot's upsert by email). Only the values given are
|
|
60
|
+
* written; an empty one never blanks what HubSpot holds. OK with `{ contactId, created }`. Never throws.
|
|
61
|
+
*/
|
|
62
|
+
async upsertContact(contact) {
|
|
63
|
+
if (!this.isConfigured()) {
|
|
64
|
+
return this.notConfigured();
|
|
65
|
+
}
|
|
66
|
+
const email = text(contact?.email).toLowerCase();
|
|
67
|
+
if (!email.includes('@')) {
|
|
68
|
+
return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The contact has no email');
|
|
69
|
+
}
|
|
70
|
+
const properties = { email };
|
|
71
|
+
const given = [
|
|
72
|
+
['firstname', contact.firstName],
|
|
73
|
+
['lastname', contact.lastName],
|
|
74
|
+
['phone', contact.phone],
|
|
75
|
+
['company', contact.company],
|
|
76
|
+
];
|
|
77
|
+
for (const [name, value] of given) {
|
|
78
|
+
if (text(value)) {
|
|
79
|
+
properties[name] = text(value);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const result = await this.call('POST', '/crm/v3/objects/contacts/batch/upsert', {
|
|
83
|
+
inputs: [{ idProperty: 'email', id: email, properties }],
|
|
84
|
+
});
|
|
85
|
+
if (result.didFail()) {
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
88
|
+
const row = result.getDataFirst()?.body?.results?.[0] ?? null;
|
|
89
|
+
if (!row?.id) {
|
|
90
|
+
return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FAILED, [result.getDataFirst()], 'HubSpot answered without the contact');
|
|
91
|
+
}
|
|
92
|
+
return api_helpers_1.OpResult.ok([{ contactId: String(row.id), created: row.new === true }]);
|
|
93
|
+
}
|
|
94
|
+
/** Puts contacts into a static list (already members are skipped by HubSpot). OK with `{ listId, added }`. Never throws. */
|
|
95
|
+
async addToList(listId, contactIds) {
|
|
96
|
+
if (!this.isConfigured()) {
|
|
97
|
+
return this.notConfigured();
|
|
98
|
+
}
|
|
99
|
+
const id = text(listId);
|
|
100
|
+
const ids = (contactIds ?? []).map(text).filter(Boolean);
|
|
101
|
+
if (!/^\d{1,20}$/.test(id) || ids.length === 0) {
|
|
102
|
+
return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A list id (a number) and at least one contact are needed');
|
|
103
|
+
}
|
|
104
|
+
const result = await this.call('PUT', `/crm/v3/lists/${id}/memberships/add`, ids);
|
|
105
|
+
return result.didFail()
|
|
106
|
+
? result
|
|
107
|
+
: api_helpers_1.OpResult.ok([{ listId: id, added: result.getDataFirst()?.body?.recordIdsAdded ?? ids }]);
|
|
108
|
+
}
|
|
109
|
+
/** A note on a contact, dated `at` (HubSpot shows `body` as rich text — pass HTML, escaped). OK with `{ noteId }`. */
|
|
110
|
+
async addNote(contactId, body, at = new Date()) {
|
|
111
|
+
if (!this.isConfigured()) {
|
|
112
|
+
return this.notConfigured();
|
|
113
|
+
}
|
|
114
|
+
if (!text(contactId) || !text(body)) {
|
|
115
|
+
return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A contact and the note are needed');
|
|
116
|
+
}
|
|
117
|
+
const result = await this.call('POST', '/crm/v3/objects/notes', {
|
|
118
|
+
properties: { hs_timestamp: at.toISOString(), hs_note_body: String(body) },
|
|
119
|
+
associations: [
|
|
120
|
+
{
|
|
121
|
+
to: { id: text(contactId) },
|
|
122
|
+
types: [{ associationCategory: 'HUBSPOT_DEFINED', associationTypeId: NOTE_TO_CONTACT }],
|
|
123
|
+
},
|
|
124
|
+
],
|
|
125
|
+
});
|
|
126
|
+
return result.didFail() ? result : api_helpers_1.OpResult.ok([{ noteId: String(result.getDataFirst()?.body?.id ?? '') || null }]);
|
|
127
|
+
}
|
|
128
|
+
/** The account's static CONTACT lists (the ones that take members), at most 500, by name. Never throws. */
|
|
129
|
+
async listStaticLists(query = '') {
|
|
130
|
+
if (!this.isConfigured()) {
|
|
131
|
+
return this.notConfigured();
|
|
132
|
+
}
|
|
133
|
+
// ⓘ The schema names listIds and additionalProperties as required: empty — no filter by id, no extra properties.
|
|
134
|
+
const result = await this.call('POST', '/crm/v3/lists/search', {
|
|
135
|
+
query: text(query),
|
|
136
|
+
processingTypes: STATIC_PROCESSING_TYPES,
|
|
137
|
+
listIds: [],
|
|
138
|
+
additionalProperties: [],
|
|
139
|
+
count: 500,
|
|
140
|
+
offset: 0,
|
|
141
|
+
});
|
|
142
|
+
if (result.didFail()) {
|
|
143
|
+
return result;
|
|
144
|
+
}
|
|
145
|
+
const lists = (result.getDataFirst()?.body?.lists ?? [])
|
|
146
|
+
.filter((l) => String(l?.objectTypeId ?? CONTACTS_OBJECT_TYPE) === CONTACTS_OBJECT_TYPE &&
|
|
147
|
+
STATIC_PROCESSING_TYPES.includes(String(l?.processingType)))
|
|
148
|
+
.map((l) => ({
|
|
149
|
+
id: String(l.listId),
|
|
150
|
+
name: text(l.name) || String(l.listId),
|
|
151
|
+
processingType: String(l.processingType),
|
|
152
|
+
}))
|
|
153
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
154
|
+
return api_helpers_1.OpResult.ok(lists);
|
|
155
|
+
}
|
|
156
|
+
/** One list by id — OK with `{ id, name, processingType, isStatic }`; NOT_FOUND when HubSpot has none. Never throws. */
|
|
157
|
+
async getList(listId) {
|
|
158
|
+
if (!this.isConfigured()) {
|
|
159
|
+
return this.notConfigured();
|
|
160
|
+
}
|
|
161
|
+
const id = text(listId);
|
|
162
|
+
if (!/^\d{1,20}$/.test(id)) {
|
|
163
|
+
return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A list id is a number');
|
|
164
|
+
}
|
|
165
|
+
const result = await this.call('GET', `/crm/v3/lists/${id}`);
|
|
166
|
+
if (result.didFail()) {
|
|
167
|
+
return result;
|
|
168
|
+
}
|
|
169
|
+
const list = result.getDataFirst()?.body?.list ?? result.getDataFirst()?.body ?? {};
|
|
170
|
+
const processingType = String(list.processingType ?? '');
|
|
171
|
+
return api_helpers_1.OpResult.ok([
|
|
172
|
+
{ id, name: text(list.name) || id, processingType, isStatic: STATIC_PROCESSING_TYPES.includes(processingType) },
|
|
173
|
+
]);
|
|
174
|
+
}
|
|
175
|
+
/** Can the token read contacts? (One contact asked for, nothing written.) OK with `{ ok: true }`. Never throws. */
|
|
176
|
+
async verify() {
|
|
177
|
+
if (!this.isConfigured()) {
|
|
178
|
+
return this.notConfigured();
|
|
179
|
+
}
|
|
180
|
+
const result = await this.call('GET', '/crm/v3/objects/contacts?limit=1&archived=false');
|
|
181
|
+
return result.didFail() ? result : api_helpers_1.OpResult.ok([{ ok: true }]);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
exports.HubSpotGw = HubSpotGw;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { OpResult } from '@sdflc/api-helpers';
|
|
2
|
+
import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
|
|
3
|
+
import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
|
|
4
|
+
export interface MailchimpSettings {
|
|
5
|
+
/** `<32 hex>-<data centre>`, e.g. `…-us21`. */
|
|
6
|
+
apiKey: string;
|
|
7
|
+
}
|
|
8
|
+
/** A new member's subscription. `subscribed` only with the person's consent to marketing email. */
|
|
9
|
+
export type MailchimpStatusIfNew = 'transactional' | 'pending' | 'subscribed';
|
|
10
|
+
export declare const MAILCHIMP_STATUSES_IF_NEW: MailchimpStatusIfNew[];
|
|
11
|
+
export interface MailchimpMember {
|
|
12
|
+
email: string;
|
|
13
|
+
/** By merge tag — FNAME, LNAME (every audience has them unless the host removed them). Empty values are not sent. */
|
|
14
|
+
mergeFields?: Record<string, string | null | undefined>;
|
|
15
|
+
/** Default `transactional`: on the audience, not subscribed to marketing. */
|
|
16
|
+
statusIfNew?: MailchimpStatusIfNew;
|
|
17
|
+
}
|
|
18
|
+
/** An audience as `listAudiences` returns it. */
|
|
19
|
+
export interface MailchimpAudience {
|
|
20
|
+
id: string;
|
|
21
|
+
name: string;
|
|
22
|
+
memberCount: number | null;
|
|
23
|
+
}
|
|
24
|
+
/** Mailchimp's own limit on a note. */
|
|
25
|
+
export declare const MAILCHIMP_NOTE_MAX = 1000;
|
|
26
|
+
/** A tag's name, at most (Mailchimp's limit). */
|
|
27
|
+
export declare const MAILCHIMP_TAG_MAX = 100;
|
|
28
|
+
/** The data centre at the end of an API key (`us21`), or null. Pure. */
|
|
29
|
+
export declare const mailchimpDataCenterOf: (apiKey: unknown) => string | null;
|
|
30
|
+
/** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
|
|
31
|
+
export declare const mailchimpSubscriberHash: (email: string) => string;
|
|
32
|
+
declare class MailchimpGw extends BaseExternalApiGateway<MailchimpSettings> {
|
|
33
|
+
constructor(props?: BaseExternalApiGatewayPropsInterface<MailchimpSettings>);
|
|
34
|
+
protected validateSettings(settings: Partial<MailchimpSettings>): string[];
|
|
35
|
+
protected secretValues(): string[];
|
|
36
|
+
/** Mailchimp's error shape (problem+json): `{ title, status, detail, errors: [{ field, message }] }`. */
|
|
37
|
+
protected errorMessageOf(reply: ExternalApiReply): string;
|
|
38
|
+
private call;
|
|
39
|
+
/** An audience id may only be letters and digits — it goes into the path. */
|
|
40
|
+
private badAudience;
|
|
41
|
+
private memberPath;
|
|
42
|
+
/**
|
|
43
|
+
* The member with this email, added or updated (one PUT). A NEW member gets `statusIfNew`; an existing one keeps its
|
|
44
|
+
* subscription. Required merge fields the host added are not demanded (`skip_merge_validation`). OK with
|
|
45
|
+
* `{ memberId, status }`. Never throws.
|
|
46
|
+
*/
|
|
47
|
+
upsertMember(audienceId: string, member: MailchimpMember): Promise<OpResult>;
|
|
48
|
+
/** Tags ADDED to a member (made in the audience when new; the member's other tags kept). OK with `{ tags }`. */
|
|
49
|
+
addTags(audienceId: string, email: string, tags: string[]): Promise<OpResult>;
|
|
50
|
+
/** A note on a member (cut to Mailchimp's 1,000 characters). OK with `{ noteId }`. Never throws. */
|
|
51
|
+
addNote(audienceId: string, email: string, note: string): Promise<OpResult>;
|
|
52
|
+
/** The account's audiences (at most 1,000), by name. Never throws. */
|
|
53
|
+
listAudiences(): Promise<OpResult>;
|
|
54
|
+
/** One audience — OK with `{ id, name }`; NOT_FOUND when the account has none by that id. Never throws. */
|
|
55
|
+
getAudience(audienceId: string): Promise<OpResult>;
|
|
56
|
+
}
|
|
57
|
+
export { MailchimpGw };
|