@sdflc/backend-helpers 1.0.148 → 1.0.150
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/build/esm/gateways/GoogleSheetsGw.d.ts +85 -0
- package/build/esm/gateways/GoogleSheetsGw.js +302 -0
- package/build/esm/gateways/ZohoCrmGw.d.ts +99 -0
- package/build/esm/gateways/ZohoCrmGw.js +390 -0
- package/build/esm/gateways/index.d.ts +2 -0
- package/build/esm/gateways/index.js +2 -0
- package/build/gateways/GoogleSheetsGw.d.ts +85 -0
- package/build/gateways/GoogleSheetsGw.js +309 -0
- package/build/gateways/ZohoCrmGw.d.ts +99 -0
- package/build/gateways/ZohoCrmGw.js +395 -0
- package/build/gateways/index.d.ts +2 -0
- package/build/gateways/index.js +2 -0
- package/package.json +1 -1
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { OpResult } from '@sdflc/api-helpers';
|
|
2
|
+
import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
|
|
3
|
+
import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
|
|
4
|
+
export interface GoogleSheetsSettings {
|
|
5
|
+
/** The service account's email (`…@<project>.iam.gserviceaccount.com`) — what the host shares the sheet with. */
|
|
6
|
+
clientEmail: string;
|
|
7
|
+
/** The service account's private key (PEM, as in its JSON key; `\n` escapes are read as line breaks). */
|
|
8
|
+
privateKey: string;
|
|
9
|
+
}
|
|
10
|
+
/** A tab as `getSpreadsheet` names it. */
|
|
11
|
+
export interface GoogleSheetTab {
|
|
12
|
+
sheetId: number;
|
|
13
|
+
title: string;
|
|
14
|
+
index: number;
|
|
15
|
+
rowCount: number;
|
|
16
|
+
columnCount: number;
|
|
17
|
+
frozenRowCount: number;
|
|
18
|
+
}
|
|
19
|
+
/** A spreadsheet as `getSpreadsheet` answers it. */
|
|
20
|
+
export interface GoogleSpreadsheet {
|
|
21
|
+
spreadsheetId: string;
|
|
22
|
+
title: string;
|
|
23
|
+
tabs: GoogleSheetTab[];
|
|
24
|
+
}
|
|
25
|
+
/** One range to write: an A1 range (`googleSheetRange`) and its rows. */
|
|
26
|
+
export interface GoogleSheetValues {
|
|
27
|
+
range: string;
|
|
28
|
+
values: unknown[][];
|
|
29
|
+
}
|
|
30
|
+
export declare const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
31
|
+
export declare const GOOGLE_SHEETS_API_URL = "https://sheets.googleapis.com/v4/spreadsheets";
|
|
32
|
+
/** The only scope the writer needs — the spreadsheets shared with the account, nothing else of the host's Drive. */
|
|
33
|
+
export declare const GOOGLE_SHEETS_SCOPE = "https://www.googleapis.com/auth/spreadsheets";
|
|
34
|
+
/**
|
|
35
|
+
* The spreadsheet id in what a host pasted — the address of the sheet (`…/spreadsheets/d/<id>/edit#gid=0`) or the id
|
|
36
|
+
* itself — or '' when it is neither. Pure.
|
|
37
|
+
*/
|
|
38
|
+
export declare const googleSpreadsheetIdOf: (raw: unknown) => string;
|
|
39
|
+
/** A tab's name inside an A1 range: always quoted, a quote doubled (`It's` → `'It''s'`). Pure. */
|
|
40
|
+
export declare const googleSheetRange: (title: string, a1?: string) => string;
|
|
41
|
+
/** A column's letters from its 1-based number (1 → A, 27 → AA). Pure. */
|
|
42
|
+
export declare const googleSheetColumn: (n: number) => string;
|
|
43
|
+
/** Forget every cached access token (a test; a key revoked). */
|
|
44
|
+
export declare const forgetGoogleSheetsTokens: () => void;
|
|
45
|
+
declare class GoogleSheetsGw extends BaseExternalApiGateway<GoogleSheetsSettings> {
|
|
46
|
+
constructor(props?: BaseExternalApiGatewayPropsInterface<GoogleSheetsSettings>);
|
|
47
|
+
protected validateSettings(settings: Partial<GoogleSheetsSettings>): string[];
|
|
48
|
+
protected secretValues(): string[];
|
|
49
|
+
/** Google's error shapes: the API's `{ error: { code, message, status } }`, the token endpoint's `{ error, error_description }`. */
|
|
50
|
+
protected errorMessageOf(reply: ExternalApiReply): string;
|
|
51
|
+
private pemOf;
|
|
52
|
+
private cacheKey;
|
|
53
|
+
/** The signed assertion a token is asked for with, or null when the key cannot sign. */
|
|
54
|
+
private assertion;
|
|
55
|
+
/**
|
|
56
|
+
* A live access token for the account — the cached one, else a new one from Google (`fresh`: never the cached one).
|
|
57
|
+
* OK with `{ accessToken, expiresAt }`. Never throws.
|
|
58
|
+
*/
|
|
59
|
+
accessToken(fresh?: boolean): Promise<OpResult>;
|
|
60
|
+
/** One API call with the account's token; a 401 forgets it and tries once more with a new one. */
|
|
61
|
+
private call;
|
|
62
|
+
private badId;
|
|
63
|
+
/**
|
|
64
|
+
* The spreadsheet's title and tabs (each with its size and frozen rows) — readable only when it is shared with the
|
|
65
|
+
* account (403 FORBIDDEN otherwise; 404 NOT_FOUND when there is no such spreadsheet). OK with a `GoogleSpreadsheet`.
|
|
66
|
+
*/
|
|
67
|
+
getSpreadsheet(spreadsheetId: string): Promise<OpResult>;
|
|
68
|
+
/**
|
|
69
|
+
* The values of several ranges in ONE read, in the order asked, row by row, unformatted (a number stays a number);
|
|
70
|
+
* trailing empty cells and rows are left out, as Google does. OK with `{ valueRanges: [{ range, values }] }`.
|
|
71
|
+
*/
|
|
72
|
+
batchGetValues(spreadsheetId: string, ranges: string[]): Promise<OpResult>;
|
|
73
|
+
/**
|
|
74
|
+
* Structural changes in ONE request, all or none (add a tab, grow one, freeze its header, format cells) — Google's
|
|
75
|
+
* `spreadsheets.batchUpdate` requests as given. OK with `{ replies }`.
|
|
76
|
+
*/
|
|
77
|
+
batchUpdate(spreadsheetId: string, requests: Record<string, unknown>[]): Promise<OpResult>;
|
|
78
|
+
/**
|
|
79
|
+
* Many ranges written in ONE request, all or none — RAW unless told otherwise (nothing typed becomes a formula, a
|
|
80
|
+
* date or a number it was not). A range past the tab's size is refused by Google: grow the tab first (`batchUpdate`
|
|
81
|
+
* with `appendDimension`). OK with `{ updatedCells, updatedRanges }`.
|
|
82
|
+
*/
|
|
83
|
+
batchUpdateValues(spreadsheetId: string, data: GoogleSheetValues[], valueInputOption?: 'RAW' | 'USER_ENTERED'): Promise<OpResult>;
|
|
84
|
+
}
|
|
85
|
+
export { GoogleSheetsGw };
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
// ./src/gateways/GoogleSheetsGw.ts
|
|
2
|
+
//
|
|
3
|
+
// Google Sheets (https://developers.google.com/workspace/sheets/api/reference/rest) as a SERVICE ACCOUNT — the calls that
|
|
4
|
+
// keep a spreadsheet the host shared with us up to date: what tabs it has, the cells a write needs to see (a header row,
|
|
5
|
+
// an id column), tabs added or grown, and many ranges written in one request.
|
|
6
|
+
//
|
|
7
|
+
// const sheets = new GoogleSheetsGw().configure({ clientEmail, privateKey }); // from the service account's JSON key
|
|
8
|
+
// const book = await sheets.getSpreadsheet(googleSpreadsheetIdOf(pastedUrl));
|
|
9
|
+
// await sheets.batchUpdate(id, [{ addSheet: { properties: { title: 'Guests' } } }]);
|
|
10
|
+
// await sheets.batchUpdateValues(id, [{ range: googleSheetRange('Guests', 'A1'), values: [['ID', 'Name']] }]);
|
|
11
|
+
//
|
|
12
|
+
// The host shares their spreadsheet with the service account's email (as Editor); nothing else is needed on their side —
|
|
13
|
+
// no OAuth, no consent screen. The gateway signs a JWT with the account's private key and trades it for an access token
|
|
14
|
+
// (an hour), kept per account in this process and renewed a minute before it ends.
|
|
15
|
+
//
|
|
16
|
+
// ⚠ The private key, the signed assertion and every access token are scrubbed out of every error and reply.
|
|
17
|
+
// ⚠ Values are written RAW by default: a guest named `=IMPORTXML(…)` stays text, never a formula in the host's sheet.
|
|
18
|
+
// ⚠ QUOTA: Google counts a service account as ONE user — 60 reads and 60 writes a minute for every spreadsheet it writes,
|
|
19
|
+
// whoever owns them (a batch is one request). Pacing is the caller's; a 429 is TOO_MANY_REQUESTS.
|
|
20
|
+
// ⚠ A call refused with 401 forgets the cached token and is tried once more with a new one (a key rotated meanwhile).
|
|
21
|
+
import { Buffer } from 'buffer';
|
|
22
|
+
import { createHash, createSign } from 'crypto';
|
|
23
|
+
import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
|
|
24
|
+
import { BaseExternalApiGateway } from './BaseExternalApiGateway';
|
|
25
|
+
export const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token';
|
|
26
|
+
export const GOOGLE_SHEETS_API_URL = 'https://sheets.googleapis.com/v4/spreadsheets';
|
|
27
|
+
/** The only scope the writer needs — the spreadsheets shared with the account, nothing else of the host's Drive. */
|
|
28
|
+
export const GOOGLE_SHEETS_SCOPE = 'https://www.googleapis.com/auth/spreadsheets';
|
|
29
|
+
/** How long before its end a cached token is replaced. */
|
|
30
|
+
const TOKEN_MARGIN_MS = 60_000;
|
|
31
|
+
const text = (value) => String(value ?? '').trim();
|
|
32
|
+
const base64Url = (value) => Buffer.from(value).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
|
33
|
+
/** A spreadsheet id: Google's are 44 characters of letters, digits, `-` and `_` (accepted from 20 to 128). */
|
|
34
|
+
const SPREADSHEET_ID = /^[A-Za-z0-9_-]{20,128}$/;
|
|
35
|
+
/**
|
|
36
|
+
* The spreadsheet id in what a host pasted — the address of the sheet (`…/spreadsheets/d/<id>/edit#gid=0`) or the id
|
|
37
|
+
* itself — or '' when it is neither. Pure.
|
|
38
|
+
*/
|
|
39
|
+
export const googleSpreadsheetIdOf = (raw) => {
|
|
40
|
+
const value = text(raw);
|
|
41
|
+
const inUrl = /\/spreadsheets\/d\/([A-Za-z0-9_-]+)/.exec(value);
|
|
42
|
+
const id = inUrl ? inUrl[1] : value;
|
|
43
|
+
return SPREADSHEET_ID.test(id) ? id : '';
|
|
44
|
+
};
|
|
45
|
+
/** A tab's name inside an A1 range: always quoted, a quote doubled (`It's` → `'It''s'`). Pure. */
|
|
46
|
+
export const googleSheetRange = (title, a1 = '') => {
|
|
47
|
+
const quoted = `'${String(title ?? '').replace(/'/g, "''")}'`;
|
|
48
|
+
return a1 ? `${quoted}!${a1}` : quoted;
|
|
49
|
+
};
|
|
50
|
+
/** A column's letters from its 1-based number (1 → A, 27 → AA). Pure. */
|
|
51
|
+
export const googleSheetColumn = (n) => {
|
|
52
|
+
let left = Math.max(1, Math.floor(Number(n) || 1));
|
|
53
|
+
let out = '';
|
|
54
|
+
while (left > 0) {
|
|
55
|
+
const rem = (left - 1) % 26;
|
|
56
|
+
out = String.fromCharCode(65 + rem) + out;
|
|
57
|
+
left = Math.floor((left - 1) / 26);
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
};
|
|
61
|
+
/** Access tokens by service account (a fingerprint of its email and key) — every gateway in the process shares them. */
|
|
62
|
+
const tokens = new Map();
|
|
63
|
+
/** Forget every cached access token (a test; a key revoked). */
|
|
64
|
+
export const forgetGoogleSheetsTokens = () => {
|
|
65
|
+
tokens.clear();
|
|
66
|
+
};
|
|
67
|
+
class GoogleSheetsGw extends BaseExternalApiGateway {
|
|
68
|
+
constructor(props) {
|
|
69
|
+
super({ baseUrl: GOOGLE_SHEETS_API_URL, ...(props ?? {}) });
|
|
70
|
+
}
|
|
71
|
+
validateSettings(settings) {
|
|
72
|
+
const problems = [];
|
|
73
|
+
if (!/^[^@\s]+@[^@\s]+\.iam\.gserviceaccount\.com$/i.test(text(settings.clientEmail))) {
|
|
74
|
+
problems.push('the client email is missing or not a service account (…@….iam.gserviceaccount.com)');
|
|
75
|
+
}
|
|
76
|
+
if (!/-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(this.pemOf(settings.privateKey))) {
|
|
77
|
+
problems.push('the private key is missing or not a PEM key');
|
|
78
|
+
}
|
|
79
|
+
return problems;
|
|
80
|
+
}
|
|
81
|
+
secretValues() {
|
|
82
|
+
const pem = this.pemOf(this.settings.privateKey);
|
|
83
|
+
// The key's body lines too: a reply never carries the PEM whole, but an echo of a line must not leave either.
|
|
84
|
+
const lines = pem.split('\n').filter((line) => line.length >= 16 && !line.startsWith('-----'));
|
|
85
|
+
return pem ? [pem, text(this.settings.privateKey), ...lines] : [];
|
|
86
|
+
}
|
|
87
|
+
/** Google's error shapes: the API's `{ error: { code, message, status } }`, the token endpoint's `{ error, error_description }`. */
|
|
88
|
+
errorMessageOf(reply) {
|
|
89
|
+
const body = reply.body;
|
|
90
|
+
if (body && typeof body === 'object') {
|
|
91
|
+
if (body.error && typeof body.error === 'object') {
|
|
92
|
+
return ([body.error.status, body.error.message].filter(Boolean).join(': ').slice(0, 500) || `HTTP ${reply.status}`);
|
|
93
|
+
}
|
|
94
|
+
if (typeof body.error === 'string') {
|
|
95
|
+
return [body.error, body.error_description].filter(Boolean).join(': ').slice(0, 500);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return super.errorMessageOf(reply);
|
|
99
|
+
}
|
|
100
|
+
pemOf(raw) {
|
|
101
|
+
return text(raw).replace(/\\n/g, '\n');
|
|
102
|
+
}
|
|
103
|
+
cacheKey() {
|
|
104
|
+
return createHash('sha256')
|
|
105
|
+
.update(`${text(this.settings.clientEmail).toLowerCase()}\n${this.pemOf(this.settings.privateKey)}`)
|
|
106
|
+
.digest('hex');
|
|
107
|
+
}
|
|
108
|
+
/** The signed assertion a token is asked for with, or null when the key cannot sign. */
|
|
109
|
+
assertion(nowMs) {
|
|
110
|
+
const iat = Math.floor(nowMs / 1000);
|
|
111
|
+
const head = base64Url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));
|
|
112
|
+
const claims = base64Url(JSON.stringify({
|
|
113
|
+
iss: text(this.settings.clientEmail),
|
|
114
|
+
scope: GOOGLE_SHEETS_SCOPE,
|
|
115
|
+
aud: GOOGLE_TOKEN_URL,
|
|
116
|
+
iat,
|
|
117
|
+
exp: iat + 3600,
|
|
118
|
+
}));
|
|
119
|
+
try {
|
|
120
|
+
const signature = createSign('RSA-SHA256').update(`${head}.${claims}`).sign(this.pemOf(this.settings.privateKey));
|
|
121
|
+
return `${head}.${claims}.${base64Url(signature)}`;
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* A live access token for the account — the cached one, else a new one from Google (`fresh`: never the cached one).
|
|
129
|
+
* OK with `{ accessToken, expiresAt }`. Never throws.
|
|
130
|
+
*/
|
|
131
|
+
async accessToken(fresh = false) {
|
|
132
|
+
if (!this.isConfigured()) {
|
|
133
|
+
return this.notConfigured();
|
|
134
|
+
}
|
|
135
|
+
const key = this.cacheKey();
|
|
136
|
+
const now = Date.now();
|
|
137
|
+
const cached = tokens.get(key);
|
|
138
|
+
if (!fresh && cached && cached.until - TOKEN_MARGIN_MS > now) {
|
|
139
|
+
return OpResult.ok([{ accessToken: cached.token, expiresAt: new Date(cached.until).toISOString() }]);
|
|
140
|
+
}
|
|
141
|
+
const jwt = this.assertion(now);
|
|
142
|
+
if (!jwt) {
|
|
143
|
+
return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The private key could not sign (is it the whole key from the JSON file?)');
|
|
144
|
+
}
|
|
145
|
+
const result = await this.requestWithRetries({
|
|
146
|
+
url: GOOGLE_TOKEN_URL,
|
|
147
|
+
method: 'POST',
|
|
148
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
149
|
+
body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion: jwt }),
|
|
150
|
+
secrets: [jwt],
|
|
151
|
+
});
|
|
152
|
+
if (result.didFail()) {
|
|
153
|
+
tokens.delete(key);
|
|
154
|
+
return result;
|
|
155
|
+
}
|
|
156
|
+
// ⓘ The reply is scrubbed of the request's secrets only — the token itself is new, so it arrives whole.
|
|
157
|
+
const body = result.getDataFirst()?.body ?? {};
|
|
158
|
+
const accessToken = text(body.access_token);
|
|
159
|
+
if (!accessToken) {
|
|
160
|
+
return OpResult.fail(OP_RESULT_CODES.FAILED, null, 'Google answered without an access token');
|
|
161
|
+
}
|
|
162
|
+
const until = now + (Number(body.expires_in) > 0 ? Number(body.expires_in) : 3600) * 1000;
|
|
163
|
+
tokens.set(key, { token: accessToken, until });
|
|
164
|
+
return OpResult.ok([{ accessToken, expiresAt: new Date(until).toISOString() }]);
|
|
165
|
+
}
|
|
166
|
+
/** One API call with the account's token; a 401 forgets it and tries once more with a new one. */
|
|
167
|
+
async call(method, path, json) {
|
|
168
|
+
let result = OpResult.fail(OP_RESULT_CODES.FAILED, null, 'Not called');
|
|
169
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
170
|
+
const token = await this.accessToken(attempt > 0);
|
|
171
|
+
if (token.didFail()) {
|
|
172
|
+
return token;
|
|
173
|
+
}
|
|
174
|
+
const accessToken = String(token.getDataFirst().accessToken);
|
|
175
|
+
result = await this.requestWithRetries({
|
|
176
|
+
url: `${this.baseUrl}${path}`,
|
|
177
|
+
method,
|
|
178
|
+
headers: { Authorization: `Bearer ${accessToken}`, Accept: 'application/json' },
|
|
179
|
+
...(json === undefined ? {} : { json }),
|
|
180
|
+
secrets: [accessToken],
|
|
181
|
+
});
|
|
182
|
+
if (result.getCode() !== OP_RESULT_CODES.UNAUTHORIZED) {
|
|
183
|
+
return result;
|
|
184
|
+
}
|
|
185
|
+
tokens.delete(this.cacheKey());
|
|
186
|
+
}
|
|
187
|
+
return result;
|
|
188
|
+
}
|
|
189
|
+
badId(spreadsheetId) {
|
|
190
|
+
return SPREADSHEET_ID.test(text(spreadsheetId))
|
|
191
|
+
? null
|
|
192
|
+
: OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The spreadsheet id is not one');
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* The spreadsheet's title and tabs (each with its size and frozen rows) — readable only when it is shared with the
|
|
196
|
+
* account (403 FORBIDDEN otherwise; 404 NOT_FOUND when there is no such spreadsheet). OK with a `GoogleSpreadsheet`.
|
|
197
|
+
*/
|
|
198
|
+
async getSpreadsheet(spreadsheetId) {
|
|
199
|
+
if (!this.isConfigured()) {
|
|
200
|
+
return this.notConfigured();
|
|
201
|
+
}
|
|
202
|
+
const bad = this.badId(spreadsheetId);
|
|
203
|
+
if (bad) {
|
|
204
|
+
return bad;
|
|
205
|
+
}
|
|
206
|
+
const fields = 'spreadsheetId,properties.title,sheets.properties(sheetId,title,index,gridProperties(rowCount,columnCount,frozenRowCount))';
|
|
207
|
+
const result = await this.call('GET', `/${text(spreadsheetId)}?fields=${encodeURIComponent(fields)}`);
|
|
208
|
+
if (result.didFail()) {
|
|
209
|
+
return result;
|
|
210
|
+
}
|
|
211
|
+
const body = result.getDataFirst()?.body ?? {};
|
|
212
|
+
const book = {
|
|
213
|
+
spreadsheetId: text(body.spreadsheetId) || text(spreadsheetId),
|
|
214
|
+
title: text(body.properties?.title),
|
|
215
|
+
tabs: (Array.isArray(body.sheets) ? body.sheets : []).map((s) => ({
|
|
216
|
+
sheetId: Number(s?.properties?.sheetId) || 0,
|
|
217
|
+
title: String(s?.properties?.title ?? ''),
|
|
218
|
+
index: Number(s?.properties?.index) || 0,
|
|
219
|
+
rowCount: Number(s?.properties?.gridProperties?.rowCount) || 0,
|
|
220
|
+
columnCount: Number(s?.properties?.gridProperties?.columnCount) || 0,
|
|
221
|
+
frozenRowCount: Number(s?.properties?.gridProperties?.frozenRowCount) || 0,
|
|
222
|
+
})),
|
|
223
|
+
};
|
|
224
|
+
return OpResult.ok([book]);
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* The values of several ranges in ONE read, in the order asked, row by row, unformatted (a number stays a number);
|
|
228
|
+
* trailing empty cells and rows are left out, as Google does. OK with `{ valueRanges: [{ range, values }] }`.
|
|
229
|
+
*/
|
|
230
|
+
async batchGetValues(spreadsheetId, ranges) {
|
|
231
|
+
if (!this.isConfigured()) {
|
|
232
|
+
return this.notConfigured();
|
|
233
|
+
}
|
|
234
|
+
const bad = this.badId(spreadsheetId);
|
|
235
|
+
const wanted = (ranges ?? []).map((r) => String(r ?? '')).filter(Boolean);
|
|
236
|
+
if (bad || wanted.length === 0) {
|
|
237
|
+
return bad ?? OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'At least one range is needed');
|
|
238
|
+
}
|
|
239
|
+
const params = new URLSearchParams();
|
|
240
|
+
for (const range of wanted) {
|
|
241
|
+
params.append('ranges', range);
|
|
242
|
+
}
|
|
243
|
+
params.set('majorDimension', 'ROWS');
|
|
244
|
+
params.set('valueRenderOption', 'UNFORMATTED_VALUE');
|
|
245
|
+
const result = await this.call('GET', `/${text(spreadsheetId)}/values:batchGet?${params.toString()}`);
|
|
246
|
+
if (result.didFail()) {
|
|
247
|
+
return result;
|
|
248
|
+
}
|
|
249
|
+
const got = result.getDataFirst()?.body?.valueRanges;
|
|
250
|
+
const valueRanges = wanted.map((range, i) => ({
|
|
251
|
+
range,
|
|
252
|
+
values: Array.isArray(got?.[i]?.values) ? got[i].values : [],
|
|
253
|
+
}));
|
|
254
|
+
return OpResult.ok([{ valueRanges }]);
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Structural changes in ONE request, all or none (add a tab, grow one, freeze its header, format cells) — Google's
|
|
258
|
+
* `spreadsheets.batchUpdate` requests as given. OK with `{ replies }`.
|
|
259
|
+
*/
|
|
260
|
+
async batchUpdate(spreadsheetId, requests) {
|
|
261
|
+
if (!this.isConfigured()) {
|
|
262
|
+
return this.notConfigured();
|
|
263
|
+
}
|
|
264
|
+
const bad = this.badId(spreadsheetId);
|
|
265
|
+
const list = (requests ?? []).filter((r) => r && typeof r === 'object');
|
|
266
|
+
if (bad || list.length === 0) {
|
|
267
|
+
return bad ?? OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'At least one request is needed');
|
|
268
|
+
}
|
|
269
|
+
const result = await this.call('POST', `/${text(spreadsheetId)}:batchUpdate`, { requests: list });
|
|
270
|
+
return result.didFail() ? result : OpResult.ok([{ replies: result.getDataFirst()?.body?.replies ?? [] }]);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Many ranges written in ONE request, all or none — RAW unless told otherwise (nothing typed becomes a formula, a
|
|
274
|
+
* date or a number it was not). A range past the tab's size is refused by Google: grow the tab first (`batchUpdate`
|
|
275
|
+
* with `appendDimension`). OK with `{ updatedCells, updatedRanges }`.
|
|
276
|
+
*/
|
|
277
|
+
async batchUpdateValues(spreadsheetId, data, valueInputOption = 'RAW') {
|
|
278
|
+
if (!this.isConfigured()) {
|
|
279
|
+
return this.notConfigured();
|
|
280
|
+
}
|
|
281
|
+
const bad = this.badId(spreadsheetId);
|
|
282
|
+
const list = (data ?? []).filter((d) => text(d?.range) && Array.isArray(d?.values));
|
|
283
|
+
if (bad || list.length === 0) {
|
|
284
|
+
return bad ?? OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'At least one range with values is needed');
|
|
285
|
+
}
|
|
286
|
+
const result = await this.call('POST', `/${text(spreadsheetId)}/values:batchUpdate`, {
|
|
287
|
+
valueInputOption: valueInputOption === 'USER_ENTERED' ? 'USER_ENTERED' : 'RAW',
|
|
288
|
+
data: list.map((d) => ({ range: d.range, majorDimension: 'ROWS', values: d.values })),
|
|
289
|
+
});
|
|
290
|
+
if (result.didFail()) {
|
|
291
|
+
return result;
|
|
292
|
+
}
|
|
293
|
+
const body = result.getDataFirst()?.body ?? {};
|
|
294
|
+
return OpResult.ok([
|
|
295
|
+
{
|
|
296
|
+
updatedCells: Number(body.totalUpdatedCells) || 0,
|
|
297
|
+
updatedRanges: (body.responses ?? []).length || list.length,
|
|
298
|
+
},
|
|
299
|
+
]);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
export { GoogleSheetsGw };
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { OpResult } from '@sdflc/api-helpers';
|
|
2
|
+
import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
|
|
3
|
+
import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
|
|
4
|
+
export interface ZohoCrmSettings {
|
|
5
|
+
clientId: string;
|
|
6
|
+
/** ⓘ With "Multi DC" on, choose the SAME secret for every data centre in the API Console. */
|
|
7
|
+
clientSecret: string;
|
|
8
|
+
}
|
|
9
|
+
/** One connected org, for one call: the API domain its tokens came with and a live access token. */
|
|
10
|
+
export interface ZohoCrmConnection {
|
|
11
|
+
apiDomain: string;
|
|
12
|
+
accessToken: string;
|
|
13
|
+
}
|
|
14
|
+
/** What a code exchange or a refresh answers (the time is ISO, computed from Zoho's seconds). */
|
|
15
|
+
export interface ZohoCrmTokens {
|
|
16
|
+
accessToken: string;
|
|
17
|
+
/** The exchange's; a refresh answers the one it was given (Zoho keeps it). */
|
|
18
|
+
refreshToken: string;
|
|
19
|
+
/** Where this org's API is ("https://www.zohoapis.eu"). */
|
|
20
|
+
apiDomain: string;
|
|
21
|
+
/** When the access token stops working (an hour). */
|
|
22
|
+
expiresAt: string;
|
|
23
|
+
}
|
|
24
|
+
/** The modules a person can be added to. */
|
|
25
|
+
export declare const ZOHO_CRM_MODULES: readonly ["Contacts", "Leads"];
|
|
26
|
+
export type ZohoCrmModule = (typeof ZOHO_CRM_MODULES)[number];
|
|
27
|
+
export declare const ZOHO_AUTHORIZE_URL = "https://accounts.zoho.com/oauth/v2/auth";
|
|
28
|
+
export declare const ZOHO_CRM_API_VERSION = "v8";
|
|
29
|
+
/**
|
|
30
|
+
* What a connection asks for: Contacts and Leads (find, create, update, tag), notes, and the org's name. Nothing that
|
|
31
|
+
* deletes, nothing of the org's settings but reading its tags.
|
|
32
|
+
*/
|
|
33
|
+
export declare const ZOHO_CRM_SCOPES: string[];
|
|
34
|
+
/** Zoho's limit on a tag's name. */
|
|
35
|
+
export declare const ZOHO_TAG_MAX = 50;
|
|
36
|
+
/** The accounts server the way back named, when it is one of Zoho's — else null. Pure. */
|
|
37
|
+
export declare const zohoAccountsServerOf: (raw: unknown) => string | null;
|
|
38
|
+
/** The API domain a token reply named, when it is one of Zoho's — else null. Pure. */
|
|
39
|
+
export declare const zohoApiDomainOf: (raw: unknown) => string | null;
|
|
40
|
+
/** The token endpoint's refusals that mean the grant or the refresh token is no use (expired, used, revoked). */
|
|
41
|
+
export declare const ZOHO_TOKEN_ENDED_ERRORS: string[];
|
|
42
|
+
declare class ZohoCrmGw extends BaseExternalApiGateway<ZohoCrmSettings> {
|
|
43
|
+
constructor(props?: BaseExternalApiGatewayPropsInterface<ZohoCrmSettings>);
|
|
44
|
+
protected validateSettings(settings: Partial<ZohoCrmSettings>): string[];
|
|
45
|
+
protected secretValues(): string[];
|
|
46
|
+
/**
|
|
47
|
+
* Zoho's error shapes: the token endpoint's `{ error, error_description? }`, the API's `{ code, message, details }` —
|
|
48
|
+
* whole, or per record inside `data[]` (an upsert's MANDATORY_NOT_FOUND names the field in `details.api_name`).
|
|
49
|
+
*/
|
|
50
|
+
protected errorMessageOf(reply: ExternalApiReply): string;
|
|
51
|
+
private badConnection;
|
|
52
|
+
private orgCall;
|
|
53
|
+
/**
|
|
54
|
+
* A token call at the org's accounts server. ⚠ Zoho says no with HTTP 200 and `{ error }`: that is turned into a
|
|
55
|
+
* failure here — UNAUTHORIZED for a grant or refresh token that is no use (ZOHO_TOKEN_ENDED_ERRORS), TOO_MANY_REQUESTS
|
|
56
|
+
* for its throttle ("Access Denied" — at most 10 access tokens per refresh token in 10 minutes), else VALIDATION_FAILED
|
|
57
|
+
* (our client id, secret or redirect address). The reply rides on the failure with `error` set.
|
|
58
|
+
*/
|
|
59
|
+
private tokenCall;
|
|
60
|
+
/**
|
|
61
|
+
* Where to send the host to connect their org (Zoho's consent screen, which moves them to their own data centre). An
|
|
62
|
+
* offline grant (a refresh token), the consent asked every time (a reconnect gets a refresh token too). Pure; '' when
|
|
63
|
+
* the gateway is not configured.
|
|
64
|
+
*/
|
|
65
|
+
authorizeUrl(args: {
|
|
66
|
+
state: string;
|
|
67
|
+
redirectUri: string;
|
|
68
|
+
scopes?: string[];
|
|
69
|
+
}): string;
|
|
70
|
+
/** The code Zoho sent back, exchanged at the host's accounts server. OK with a `ZohoCrmTokens`. Never throws. */
|
|
71
|
+
exchangeCode(code: string, redirectUri: string, accountsServer: string): Promise<OpResult>;
|
|
72
|
+
/** A new access token for the org's refresh token (which stays as it is). OK with a `ZohoCrmTokens`. Never throws. */
|
|
73
|
+
refreshTokens(refreshToken: string, accountsServer: string): Promise<OpResult>;
|
|
74
|
+
/** Disconnects: the refresh token and the access tokens made with it stop working. OK with `{ revoked: true }`. */
|
|
75
|
+
revoke(refreshToken: string, accountsServer: string): Promise<OpResult>;
|
|
76
|
+
/** The org a connection reaches. OK with `{ id, name, domainName, type }` (type: production, sandbox, developer…). */
|
|
77
|
+
getOrg(org: ZohoCrmConnection): Promise<OpResult>;
|
|
78
|
+
/**
|
|
79
|
+
* The record with this email in `module`, created or updated (Zoho's upsert, the email the only duplicate check; the
|
|
80
|
+
* org's workflow rules run, as for a record typed in). Only the fields given with a value are sent — an empty one never
|
|
81
|
+
* blanks what Zoho holds. OK with `{ recordId, created }`; a refused record (a mandatory field missing — its name in
|
|
82
|
+
* the message) fails VALIDATION_FAILED with the reply. Never throws.
|
|
83
|
+
*/
|
|
84
|
+
upsertRecord(org: ZohoCrmConnection, module: ZohoCrmModule, fields: Record<string, string | null | undefined>): Promise<OpResult>;
|
|
85
|
+
/** Tags on a record (added to what it has; a tag the org does not have yet is made by Zoho). OK with `{ tags }`. */
|
|
86
|
+
addTags(org: ZohoCrmConnection, module: ZohoCrmModule, recordId: string, tags: string[]): Promise<OpResult>;
|
|
87
|
+
/** A note on a record (plain text; the title optional). OK with `{ noteId }`. Never throws. */
|
|
88
|
+
addNote(org: ZohoCrmConnection, module: ZohoCrmModule, recordId: string, content: string, title?: string): Promise<OpResult>;
|
|
89
|
+
/** Can the connection read `module`? (One record asked for, nothing written.) OK with `{ ok: true }`. Never throws. */
|
|
90
|
+
verify(org: ZohoCrmConnection, module: ZohoCrmModule): Promise<OpResult>;
|
|
91
|
+
private badModule;
|
|
92
|
+
private badRecord;
|
|
93
|
+
/**
|
|
94
|
+
* The one record a write answered: its id and action — or the failure. ⓘ Zoho answers a write 200 / 201 / 202, or 207
|
|
95
|
+
* (multi-status) with the record's own refusal inside `data[0]`: a 2xx is not yet a success.
|
|
96
|
+
*/
|
|
97
|
+
private recordOf;
|
|
98
|
+
}
|
|
99
|
+
export { ZohoCrmGw };
|