n8n-nodes-kapacity 0.1.0

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.
Files changed (32) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +101 -0
  3. package/dist/credentials/KapacityApi.credentials.d.ts +10 -0
  4. package/dist/credentials/KapacityApi.credentials.js +56 -0
  5. package/dist/icons/kapacity.dark.svg +1 -0
  6. package/dist/icons/kapacity.svg +1 -0
  7. package/dist/nodes/Kapacity/Kapacity.node.d.ts +23 -0
  8. package/dist/nodes/Kapacity/Kapacity.node.js +92 -0
  9. package/dist/nodes/Kapacity/Kapacity.node.json +18 -0
  10. package/dist/nodes/Kapacity/actions.d.ts +13 -0
  11. package/dist/nodes/Kapacity/actions.js +277 -0
  12. package/dist/nodes/Kapacity/methods.d.ts +17 -0
  13. package/dist/nodes/Kapacity/methods.js +111 -0
  14. package/dist/nodes/Kapacity/resources/contact.d.ts +2 -0
  15. package/dist/nodes/Kapacity/resources/contact.js +111 -0
  16. package/dist/nodes/Kapacity/resources/contract.d.ts +6 -0
  17. package/dist/nodes/Kapacity/resources/contract.js +126 -0
  18. package/dist/nodes/Kapacity/resources/reading.d.ts +11 -0
  19. package/dist/nodes/Kapacity/resources/reading.js +137 -0
  20. package/dist/nodes/Kapacity/resources/row.d.ts +7 -0
  21. package/dist/nodes/Kapacity/resources/row.js +140 -0
  22. package/dist/nodes/Kapacity/shared/columns.d.ts +24 -0
  23. package/dist/nodes/Kapacity/shared/columns.js +158 -0
  24. package/dist/nodes/Kapacity/shared/descriptions.d.ts +16 -0
  25. package/dist/nodes/Kapacity/shared/descriptions.js +154 -0
  26. package/dist/nodes/Kapacity/shared/transport.d.ts +5 -0
  27. package/dist/nodes/Kapacity/shared/transport.js +91 -0
  28. package/dist/nodes/KapacityTrigger/KapacityTrigger.node.d.ts +12 -0
  29. package/dist/nodes/KapacityTrigger/KapacityTrigger.node.js +182 -0
  30. package/dist/nodes/KapacityTrigger/KapacityTrigger.node.json +18 -0
  31. package/dist/package.json +65 -0
  32. package/package.json +65 -0
@@ -0,0 +1,24 @@
1
+ import type { IDataObject, IExecuteFunctions, ILoadOptionsFunctions, ResourceMapperField } from 'n8n-workflow';
2
+ export interface KapacityColumn {
3
+ id: string;
4
+ nom: string;
5
+ type: string;
6
+ lecture_seule: boolean;
7
+ options?: Array<{
8
+ id: string;
9
+ libelle: string;
10
+ }>;
11
+ }
12
+ export interface KapacityMember {
13
+ id: string;
14
+ nom: string;
15
+ email: string | null;
16
+ }
17
+ export declare const CONTACT_BASES: string[];
18
+ export declare function getColumns(this: IExecuteFunctions | ILoadOptionsFunctions, tableId: string): Promise<KapacityColumn[]>;
19
+ export declare function getMembers(this: IExecuteFunctions | ILoadOptionsFunctions): Promise<KapacityMember[]>;
20
+ export declare function isWritable(column: KapacityColumn, tableId: string): boolean;
21
+ export declare function fieldLabel(column: KapacityColumn): string;
22
+ export declare function toMapperFields(columns: KapacityColumn[], tableId: string, members: KapacityMember[], required?: string[]): ResourceMapperField[];
23
+ export declare function toApiValues(values: IDataObject, columns: KapacityColumn[]): IDataObject;
24
+ export declare function toReadable(record: IDataObject, columns: KapacityColumn[], members: KapacityMember[]): IDataObject;
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CONTACT_BASES = void 0;
4
+ exports.getColumns = getColumns;
5
+ exports.getMembers = getMembers;
6
+ exports.isWritable = isWritable;
7
+ exports.fieldLabel = fieldLabel;
8
+ exports.toMapperFields = toMapperFields;
9
+ exports.toApiValues = toApiValues;
10
+ exports.toReadable = toReadable;
11
+ const transport_1 = require("./transport");
12
+ exports.CONTACT_BASES = ['leads', 'leads_setting'];
13
+ const WRITABLE_TYPES = new Set([
14
+ 'texte',
15
+ 'texte_long',
16
+ 'nombre',
17
+ 'monetaire',
18
+ 'pourcentage',
19
+ 'selection',
20
+ 'selection_multiple',
21
+ 'case',
22
+ 'date',
23
+ 'datetime',
24
+ 'email',
25
+ 'telephone',
26
+ 'url',
27
+ 'membre',
28
+ 'note',
29
+ 'tags',
30
+ ]);
31
+ const LIST_TYPES = new Set(['selection_multiple', 'tags']);
32
+ async function getColumns(tableId) {
33
+ var _a;
34
+ const response = await transport_1.kapacityApiRequest.call(this, 'GET', `/tables/${encodeURIComponent(tableId)}`);
35
+ return (_a = response.colonnes) !== null && _a !== void 0 ? _a : [];
36
+ }
37
+ async function getMembers() {
38
+ var _a;
39
+ const response = await transport_1.kapacityApiRequest.call(this, 'GET', '/members');
40
+ return (_a = response.membres) !== null && _a !== void 0 ? _a : [];
41
+ }
42
+ function isWritable(column, tableId) {
43
+ if (!WRITABLE_TYPES.has(column.type))
44
+ return false;
45
+ if (exports.CONTACT_BASES.includes(tableId) && column.id === 'email')
46
+ return true;
47
+ return !column.lecture_seule;
48
+ }
49
+ function fieldTypeOf(column) {
50
+ switch (column.type) {
51
+ case 'nombre':
52
+ case 'monetaire':
53
+ case 'pourcentage':
54
+ return 'number';
55
+ case 'case':
56
+ return 'boolean';
57
+ case 'date':
58
+ case 'datetime':
59
+ return 'dateTime';
60
+ case 'selection':
61
+ case 'membre':
62
+ return 'options';
63
+ default:
64
+ return 'string';
65
+ }
66
+ }
67
+ function fieldLabel(column) {
68
+ if (column.type === 'monetaire')
69
+ return `${column.nom} (€)`;
70
+ if (LIST_TYPES.has(column.type))
71
+ return `${column.nom} (comma-separated)`;
72
+ return column.nom;
73
+ }
74
+ function toMapperFields(columns, tableId, members, required = []) {
75
+ return columns
76
+ .filter((column) => isWritable(column, tableId))
77
+ .map((column) => {
78
+ var _a;
79
+ const field = {
80
+ id: column.id,
81
+ displayName: fieldLabel(column),
82
+ required: required.includes(column.id),
83
+ defaultMatch: false,
84
+ canBeUsedToMatch: false,
85
+ display: true,
86
+ type: fieldTypeOf(column),
87
+ };
88
+ if (column.type === 'selection') {
89
+ field.options = ((_a = column.options) !== null && _a !== void 0 ? _a : []).map((o) => ({ name: o.libelle, value: o.id }));
90
+ }
91
+ if (column.type === 'membre') {
92
+ field.options = members.map((m) => ({ name: m.email ? `${m.nom} (${m.email})` : m.nom, value: m.id }));
93
+ }
94
+ return field;
95
+ });
96
+ }
97
+ function toApiValues(values, columns) {
98
+ const byId = new Map(columns.map((c) => [c.id, c]));
99
+ const out = {};
100
+ for (const [key, raw] of Object.entries(values)) {
101
+ if (raw === undefined || raw === null || raw === '')
102
+ continue;
103
+ const column = byId.get(key);
104
+ if (!column) {
105
+ out[key] = raw;
106
+ continue;
107
+ }
108
+ if (column.type === 'monetaire') {
109
+ const amount = typeof raw === 'number' ? raw : Number(String(raw).replace(',', '.'));
110
+ out[key] = Number.isFinite(amount) ? Math.round(amount * 100) : raw;
111
+ }
112
+ else if (LIST_TYPES.has(column.type)) {
113
+ out[key] = Array.isArray(raw)
114
+ ? raw
115
+ : String(raw)
116
+ .split(',')
117
+ .map((s) => s.trim())
118
+ .filter(Boolean);
119
+ }
120
+ else {
121
+ out[key] = raw;
122
+ }
123
+ }
124
+ return out;
125
+ }
126
+ function toReadable(record, columns, members) {
127
+ var _a, _b;
128
+ const values = (_a = record.champs) !== null && _a !== void 0 ? _a : {};
129
+ const byId = new Map(columns.map((c) => [c.id, c]));
130
+ const memberName = new Map(members.map((m) => [m.id, m.nom]));
131
+ const out = {
132
+ id: record.id,
133
+ created_at: record.cree_le,
134
+ updated_at: record.modifie_le,
135
+ };
136
+ for (const [key, value] of Object.entries(values)) {
137
+ const column = byId.get(key);
138
+ if (!column) {
139
+ out[key] = value;
140
+ continue;
141
+ }
142
+ const label = (id) => { var _a, _b, _c; return (_c = (_b = (_a = column.options) === null || _a === void 0 ? void 0 : _a.find((o) => o.id === id)) === null || _b === void 0 ? void 0 : _b.libelle) !== null && _c !== void 0 ? _c : id; };
143
+ let readable = value;
144
+ if (value !== null && value !== undefined) {
145
+ if (column.type === 'monetaire' && typeof value === 'number')
146
+ readable = value / 100;
147
+ else if (column.type === 'selection')
148
+ readable = label(value);
149
+ else if (column.type === 'selection_multiple' && Array.isArray(value))
150
+ readable = value.map(label);
151
+ else if (column.type === 'membre')
152
+ readable = (_b = memberName.get(String(value))) !== null && _b !== void 0 ? _b : value;
153
+ }
154
+ out[column.nom] = readable;
155
+ }
156
+ return out;
157
+ }
158
+ //# sourceMappingURL=columns.js.map
@@ -0,0 +1,16 @@
1
+ import type { IDisplayOptions, INodeProperties } from 'n8n-workflow';
2
+ export declare const UUID_REGEX = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
3
+ export declare function contactBaseSelect(show: IDisplayOptions['show']): INodeProperties;
4
+ export declare function contactLocator(show: IDisplayOptions['show'], name?: string): INodeProperties;
5
+ export declare function tableLocator(show: IDisplayOptions['show']): INodeProperties;
6
+ export declare function simpleLocator(show: IDisplayOptions['show'], opts: {
7
+ displayName: string;
8
+ name: string;
9
+ method: string;
10
+ placeholder: string;
11
+ description: string;
12
+ }): INodeProperties;
13
+ export declare function paginationFields(show: IDisplayOptions['show']): INodeProperties[];
14
+ export declare const outputFormatOption: INodeProperties;
15
+ export declare const triggerAutomationsOption: INodeProperties;
16
+ export declare const dateFilter: (displayName: string, name: string, description: string) => INodeProperties;
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.dateFilter = exports.triggerAutomationsOption = exports.outputFormatOption = exports.UUID_REGEX = void 0;
4
+ exports.contactBaseSelect = contactBaseSelect;
5
+ exports.contactLocator = contactLocator;
6
+ exports.tableLocator = tableLocator;
7
+ exports.simpleLocator = simpleLocator;
8
+ exports.paginationFields = paginationFields;
9
+ exports.UUID_REGEX = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
10
+ const idMode = (placeholder) => ({
11
+ displayName: 'By ID',
12
+ name: 'id',
13
+ type: 'string',
14
+ placeholder,
15
+ validation: [
16
+ {
17
+ type: 'regex',
18
+ properties: { regex: `^${exports.UUID_REGEX}$`, errorMessage: 'Not a valid Kapacity ID' },
19
+ },
20
+ ],
21
+ });
22
+ function contactBaseSelect(show) {
23
+ return {
24
+ displayName: 'Base',
25
+ name: 'base',
26
+ type: 'options',
27
+ noDataExpression: true,
28
+ options: [
29
+ { name: 'Mon Pipe', value: 'leads', description: 'The closing pipeline' },
30
+ { name: 'Setting', value: 'leads_setting', description: 'The setting pipeline' },
31
+ ],
32
+ default: 'leads',
33
+ description: 'The Kapacity base the contact belongs to',
34
+ displayOptions: { show },
35
+ };
36
+ }
37
+ function contactLocator(show, name = 'contactId') {
38
+ return {
39
+ displayName: 'Contact',
40
+ name,
41
+ type: 'resourceLocator',
42
+ default: { mode: 'list', value: '' },
43
+ required: true,
44
+ description: 'The contact, searched by name, e-mail, company or phone',
45
+ modes: [
46
+ {
47
+ displayName: 'From List',
48
+ name: 'list',
49
+ type: 'list',
50
+ placeholder: 'Select a contact...',
51
+ typeOptions: { searchListMethod: name === 'contactId' ? 'searchContacts' : 'searchAllContacts', searchable: true },
52
+ },
53
+ idMode('e.g. 7fc74cfb-c67a-43d2-868f-f4a8ab028475'),
54
+ ],
55
+ displayOptions: { show },
56
+ };
57
+ }
58
+ function tableLocator(show) {
59
+ return {
60
+ displayName: 'Table',
61
+ name: 'table',
62
+ type: 'resourceLocator',
63
+ default: { mode: 'list', value: '' },
64
+ required: true,
65
+ description: 'A table created in the CRM (Mes Ventes, Ressources, your own tables). Contacts have their own resource.',
66
+ modes: [
67
+ {
68
+ displayName: 'From List',
69
+ name: 'list',
70
+ type: 'list',
71
+ placeholder: 'Select a table...',
72
+ typeOptions: { searchListMethod: 'searchTables', searchable: true },
73
+ },
74
+ idMode('e.g. 6b0c9e2a-1f3d-4c5b-9a8e-7d6c5b4a3f2e'),
75
+ ],
76
+ displayOptions: { show },
77
+ };
78
+ }
79
+ function simpleLocator(show, opts) {
80
+ return {
81
+ displayName: opts.displayName,
82
+ name: opts.name,
83
+ type: 'resourceLocator',
84
+ default: { mode: 'list', value: '' },
85
+ required: true,
86
+ description: opts.description,
87
+ modes: [
88
+ {
89
+ displayName: 'From List',
90
+ name: 'list',
91
+ type: 'list',
92
+ placeholder: opts.placeholder,
93
+ typeOptions: { searchListMethod: opts.method, searchable: true },
94
+ },
95
+ idMode('e.g. 3e5a7c9b-2d4f-4e6a-8b1c-9d0e2f4a6b8c'),
96
+ ],
97
+ displayOptions: { show },
98
+ };
99
+ }
100
+ function paginationFields(show) {
101
+ return [
102
+ {
103
+ displayName: 'Return All',
104
+ name: 'returnAll',
105
+ type: 'boolean',
106
+ default: false,
107
+ description: 'Whether to return all results or only up to a given limit',
108
+ displayOptions: { show },
109
+ },
110
+ {
111
+ displayName: 'Limit',
112
+ name: 'limit',
113
+ type: 'number',
114
+ typeOptions: { minValue: 1 },
115
+ default: 50,
116
+ description: 'Max number of results to return',
117
+ displayOptions: { show: { ...show, returnAll: [false] } },
118
+ },
119
+ ];
120
+ }
121
+ exports.outputFormatOption = {
122
+ displayName: 'Output Format',
123
+ name: 'outputFormat',
124
+ type: 'options',
125
+ options: [
126
+ {
127
+ name: 'Readable',
128
+ value: 'readable',
129
+ description: 'Column names instead of IDs, option labels, member names and amounts in euros',
130
+ },
131
+ {
132
+ name: 'Raw',
133
+ value: 'raw',
134
+ description: 'The API response as is: values keyed by column ID, amounts in cents',
135
+ },
136
+ ],
137
+ default: 'readable',
138
+ };
139
+ exports.triggerAutomationsOption = {
140
+ displayName: 'Trigger Automations',
141
+ name: 'triggerAutomations',
142
+ type: 'boolean',
143
+ default: true,
144
+ description: 'Whether this write starts the Kapacity automations, as a change made on screen would. Turn off when importing data, or when copying data that already comes from Kapacity.',
145
+ };
146
+ const dateFilter = (displayName, name, description) => ({
147
+ displayName,
148
+ name,
149
+ type: 'dateTime',
150
+ default: '',
151
+ description,
152
+ });
153
+ exports.dateFilter = dateFilter;
154
+ //# sourceMappingURL=descriptions.js.map
@@ -0,0 +1,5 @@
1
+ import type { IDataObject, IExecuteFunctions, IHookFunctions, IHttpRequestMethods, ILoadOptionsFunctions } from 'n8n-workflow';
2
+ type Context = IExecuteFunctions | ILoadOptionsFunctions | IHookFunctions;
3
+ export declare function kapacityApiRequest(this: Context, method: IHttpRequestMethods, path: string, qs?: IDataObject, body?: IDataObject | undefined, headers?: IDataObject): Promise<IDataObject>;
4
+ export declare function kapacityApiRequestAll(this: IExecuteFunctions | ILoadOptionsFunctions, path: string, listKey: string, qs?: IDataObject, limit?: number): Promise<IDataObject[]>;
5
+ export {};
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.kapacityApiRequest = kapacityApiRequest;
4
+ exports.kapacityApiRequestAll = kapacityApiRequestAll;
5
+ const n8n_workflow_1 = require("n8n-workflow");
6
+ const MESSAGES = {
7
+ cle_absente: 'The API key is missing',
8
+ cle_invalide: 'The API key is not valid',
9
+ cle_expiree: 'The API key has expired: create a new one in Kapacity, page Integrations, API tab',
10
+ cle_revoquee: 'The API key has been revoked: create a new one in Kapacity, page Integrations, API tab',
11
+ espace_incorrect: 'This API key does not belong to the workspace set in the credentials',
12
+ portee: 'This API key is read-only: create a "Read and write" key to change data',
13
+ proprietaire: 'Only a key created by the workspace owner can do this',
14
+ introuvable: 'The requested item does not exist in this workspace',
15
+ validation: 'Kapacity refused a value',
16
+ quota_mensuel: 'The monthly API quota of this workspace is reached',
17
+ debit: 'Too many requests per second: slow down the workflow',
18
+ debit_heure: 'Too many requests in the last hour',
19
+ disjoncteur: 'Writes to this record are paused: it was changed too often in a few seconds (loop protection)',
20
+ limite_plan: 'A limit of the workspace plan is reached',
21
+ api_fermee: 'The API is not open on this workspace yet',
22
+ };
23
+ async function baseOf(ctx) {
24
+ const credentials = await ctx.getCredentials('kapacityApi');
25
+ const base = String(credentials.baseUrl || 'https://kapacity.app').replace(/\/+$/, '');
26
+ return `${base}/api/v1/w/${String(credentials.workspaceId).trim()}`;
27
+ }
28
+ async function kapacityApiRequest(method, path, qs = {}, body = undefined, headers = {}) {
29
+ var _a;
30
+ const options = {
31
+ method,
32
+ url: `${await baseOf(this)}${path}`,
33
+ qs,
34
+ body,
35
+ headers: { Accept: 'application/json', ...headers },
36
+ json: true,
37
+ };
38
+ if (body === undefined)
39
+ delete options.body;
40
+ try {
41
+ return (await this.helpers.httpRequestWithAuthentication.call(this, 'kapacityApi', options));
42
+ }
43
+ catch (error) {
44
+ const { code, detail } = readRefusal(error);
45
+ const cause = error.cause;
46
+ const source = error instanceof n8n_workflow_1.NodeApiError && cause instanceof Error ? cause : error;
47
+ throw new n8n_workflow_1.NodeApiError(this.getNode(), source, {
48
+ message: (code && MESSAGES[code]) || undefined,
49
+ description: detail ? `Kapacity: ${detail}` : undefined,
50
+ httpCode: (_a = error.httpCode) !== null && _a !== void 0 ? _a : undefined,
51
+ });
52
+ }
53
+ }
54
+ function readRefusal(error) {
55
+ var _a, _b, _c, _d, _e;
56
+ const e = error;
57
+ const candidates = [(_a = e.context) === null || _a === void 0 ? void 0 : _a.data, (_c = (_b = e.cause) === null || _b === void 0 ? void 0 : _b.response) === null || _c === void 0 ? void 0 : _c.data, (_d = e.response) === null || _d === void 0 ? void 0 : _d.body, (_e = e.response) === null || _e === void 0 ? void 0 : _e.data];
58
+ for (const candidate of candidates) {
59
+ const parsed = typeof candidate === 'string' ? safeJson(candidate) : candidate;
60
+ if (parsed && typeof parsed === 'object' && (parsed.code || parsed.error)) {
61
+ return { code: parsed.code, detail: parsed.error };
62
+ }
63
+ }
64
+ return {};
65
+ }
66
+ function safeJson(text) {
67
+ try {
68
+ return JSON.parse(text);
69
+ }
70
+ catch {
71
+ return undefined;
72
+ }
73
+ }
74
+ async function kapacityApiRequestAll(path, listKey, qs = {}, limit = 0) {
75
+ var _a, _b;
76
+ const items = [];
77
+ let cursor;
78
+ do {
79
+ const pageSize = limit ? Math.min(200, limit - items.length) : 200;
80
+ const response = await kapacityApiRequest.call(this, 'GET', path, {
81
+ ...qs,
82
+ limite: pageSize,
83
+ ...(cursor ? { curseur: cursor } : {}),
84
+ });
85
+ const page = (_a = response[listKey]) !== null && _a !== void 0 ? _a : [];
86
+ items.push(...page);
87
+ cursor = (_b = response.curseur_suivant) !== null && _b !== void 0 ? _b : undefined;
88
+ } while (cursor && (!limit || items.length < limit));
89
+ return limit ? items.slice(0, limit) : items;
90
+ }
91
+ //# sourceMappingURL=transport.js.map
@@ -0,0 +1,12 @@
1
+ import type { IHookFunctions, INodeType, INodeTypeDescription, IWebhookFunctions, IWebhookResponseData } from 'n8n-workflow';
2
+ export declare class KapacityTrigger implements INodeType {
3
+ description: INodeTypeDescription;
4
+ webhookMethods: {
5
+ default: {
6
+ checkExists(this: IHookFunctions): Promise<boolean>;
7
+ create(this: IHookFunctions): Promise<boolean>;
8
+ delete(this: IHookFunctions): Promise<boolean>;
9
+ };
10
+ };
11
+ webhook(this: IWebhookFunctions): Promise<IWebhookResponseData>;
12
+ }
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KapacityTrigger = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const n8n_workflow_1 = require("n8n-workflow");
6
+ const transport_1 = require("../Kapacity/shared/transport");
7
+ const EVENTS = [
8
+ { name: 'Contact Created', value: 'contact.cree', description: 'A contact is added to Mon Pipe or Setting' },
9
+ { name: 'Contact Updated', value: 'contact.modifie', description: 'A field of a contact changes' },
10
+ { name: 'Row Created', value: 'ligne.creee', description: 'A row is added to one of your tables' },
11
+ { name: 'Row Updated', value: 'ligne.modifiee', description: 'A row of one of your tables changes' },
12
+ { name: 'Appointment Booked', value: 'rendez_vous.pris', description: 'Someone books an appointment' },
13
+ { name: 'Appointment Rescheduled', value: 'rendez_vous.reprogramme', description: 'An appointment moves to another time' },
14
+ { name: 'Appointment Canceled', value: 'rendez_vous.annule', description: 'An appointment is canceled' },
15
+ { name: 'Form Submitted', value: 'formulaire.soumis', description: 'Someone submits one of your forms' },
16
+ { name: 'Contract Sent', value: 'contrat.envoye', description: 'A contract is sent for signature' },
17
+ { name: 'Contract Signed', value: 'contrat.signe', description: 'A contract comes back signed' },
18
+ { name: 'Payment Received', value: 'paiement.recu', description: 'A payment is received' },
19
+ ];
20
+ const TIMESTAMP_TOLERANCE_SEC = 300;
21
+ const sameEvents = (a, b) => a.length === b.length && a.every((e) => b.includes(e));
22
+ class KapacityTrigger {
23
+ constructor() {
24
+ this.description = {
25
+ displayName: 'Kapacity Trigger',
26
+ name: 'kapacityTrigger',
27
+ icon: { light: 'file:../../icons/kapacity.svg', dark: 'file:../../icons/kapacity.dark.svg' },
28
+ group: ['trigger'],
29
+ version: 1,
30
+ subtitle: '={{$parameter["events"].join(", ")}}',
31
+ description: 'Starts the workflow when something happens in Kapacity',
32
+ defaults: { name: 'Kapacity Trigger' },
33
+ inputs: [],
34
+ outputs: [n8n_workflow_1.NodeConnectionTypes.Main],
35
+ credentials: [{ name: 'kapacityApi', required: true }],
36
+ webhooks: [{ name: 'default', httpMethod: 'POST', responseMode: 'onReceived', path: 'webhook' }],
37
+ properties: [
38
+ {
39
+ displayName: 'Events',
40
+ name: 'events',
41
+ type: 'multiOptions',
42
+ options: EVENTS,
43
+ default: [],
44
+ required: true,
45
+ description: 'The events that start the workflow',
46
+ },
47
+ {
48
+ displayName: 'Options',
49
+ name: 'options',
50
+ type: 'collection',
51
+ placeholder: 'Add Option',
52
+ default: {},
53
+ options: [
54
+ {
55
+ displayName: 'Ignore Changes Made by the API',
56
+ name: 'ignoreApiWrites',
57
+ type: 'boolean',
58
+ default: true,
59
+ description: 'Whether to ignore what is written through the Kapacity API (by this workflow or another one). Keep it on when the workflow writes to Kapacity: otherwise it would start itself again, endlessly.',
60
+ },
61
+ ],
62
+ },
63
+ ],
64
+ };
65
+ this.webhookMethods = {
66
+ default: {
67
+ async checkExists() {
68
+ var _a;
69
+ const data = this.getWorkflowStaticData('node');
70
+ if (!data.webhookId)
71
+ return false;
72
+ const response = await transport_1.kapacityApiRequest.call(this, 'GET', '/webhooks');
73
+ const hooks = (_a = response.webhooks) !== null && _a !== void 0 ? _a : [];
74
+ const hook = hooks.find((h) => h.id === data.webhookId);
75
+ const events = this.getNodeParameter('events');
76
+ if (hook && hook.url === this.getNodeWebhookUrl('default') && sameEvents(hook.evenements, events)) {
77
+ return true;
78
+ }
79
+ if (hook)
80
+ await transport_1.kapacityApiRequest.call(this, 'DELETE', `/webhooks/${data.webhookId}`).catch(() => undefined);
81
+ delete data.webhookId;
82
+ delete data.secret;
83
+ return false;
84
+ },
85
+ async create() {
86
+ var _a, _b;
87
+ const events = this.getNodeParameter('events');
88
+ if (!events.length)
89
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Choose at least one event');
90
+ const options = this.getNodeParameter('options', {});
91
+ const workflowName = (_a = this.getWorkflow().name) !== null && _a !== void 0 ? _a : '';
92
+ const body = {
93
+ nom: `n8n · ${workflowName || 'workflow'}`.slice(0, 80),
94
+ url: this.getNodeWebhookUrl('default'),
95
+ evenements: events,
96
+ ignorer_api: options.ignoreApiWrites !== false,
97
+ description: 'Created by the n8n Kapacity Trigger. Deactivating the workflow deletes it.',
98
+ };
99
+ let response;
100
+ try {
101
+ response = await transport_1.kapacityApiRequest.call(this, 'POST', '/webhooks', {}, body);
102
+ }
103
+ catch (error) {
104
+ const url = String((_b = body.url) !== null && _b !== void 0 ? _b : '');
105
+ if (!url.startsWith('https://') || /localhost|127\.0\.0\.1/.test(url)) {
106
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Kapacity only calls public https addresses, and this n8n webhook address is not one', {
107
+ description: `Address: ${url}. Set the WEBHOOK_URL environment variable of n8n to its public https address (or use a tunnel), then try again.`,
108
+ });
109
+ }
110
+ throw new n8n_workflow_1.NodeApiError(this.getNode(), error);
111
+ }
112
+ const data = this.getWorkflowStaticData('node');
113
+ data.webhookId = String(response.webhook.id);
114
+ data.secret = String(response.secret);
115
+ return true;
116
+ },
117
+ async delete() {
118
+ const data = this.getWorkflowStaticData('node');
119
+ if (data.webhookId) {
120
+ try {
121
+ await transport_1.kapacityApiRequest.call(this, 'DELETE', `/webhooks/${data.webhookId}`);
122
+ }
123
+ catch (error) {
124
+ const status = error.httpCode;
125
+ if (status !== '404')
126
+ return false;
127
+ }
128
+ }
129
+ delete data.webhookId;
130
+ delete data.secret;
131
+ return true;
132
+ },
133
+ },
134
+ };
135
+ }
136
+ async webhook() {
137
+ var _a, _b, _c, _d;
138
+ const data = this.getWorkflowStaticData('node');
139
+ const request = this.getRequestObject();
140
+ const body = this.getBodyData();
141
+ if (data.secret) {
142
+ const headers = this.getHeaderData();
143
+ const id = String((_a = headers['webhook-id']) !== null && _a !== void 0 ? _a : '');
144
+ const timestamp = String((_b = headers['webhook-timestamp']) !== null && _b !== void 0 ? _b : '');
145
+ const signatures = String((_c = headers['webhook-signature']) !== null && _c !== void 0 ? _c : '');
146
+ const rawBody = request.rawBody;
147
+ const payload = rawBody ? rawBody.toString('utf8') : JSON.stringify(body);
148
+ if (!verifySignature(data.secret, id, timestamp, payload, signatures)) {
149
+ const response = this.getResponseObject();
150
+ response.status(401).json({ error: 'Invalid signature' });
151
+ return { noWebhookResponse: true };
152
+ }
153
+ }
154
+ const headers = this.getHeaderData();
155
+ return {
156
+ workflowData: [
157
+ this.helpers.returnJsonArray({
158
+ ...body,
159
+ event_id: (_d = headers['webhook-id']) !== null && _d !== void 0 ? _d : null,
160
+ }),
161
+ ],
162
+ };
163
+ }
164
+ }
165
+ exports.KapacityTrigger = KapacityTrigger;
166
+ function verifySignature(secret, id, timestamp, payload, header) {
167
+ const sentAt = Number(timestamp);
168
+ if (!id || !Number.isFinite(sentAt))
169
+ return false;
170
+ if (Math.abs(Date.now() / 1000 - sentAt) > TIMESTAMP_TOLERANCE_SEC)
171
+ return false;
172
+ const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64url');
173
+ const expected = Buffer.from((0, crypto_1.createHmac)('sha256', key).update(`${id}.${timestamp}.${payload}`).digest('base64'));
174
+ return header.split(' ').some((part) => {
175
+ const [version, signature] = part.split(',');
176
+ if (version !== 'v1' || !signature)
177
+ return false;
178
+ const given = Buffer.from(signature);
179
+ return given.length === expected.length && (0, crypto_1.timingSafeEqual)(given, expected);
180
+ });
181
+ }
182
+ //# sourceMappingURL=KapacityTrigger.node.js.map
@@ -0,0 +1,18 @@
1
+ {
2
+ "node": "n8n-nodes-kapacity.kapacityTrigger",
3
+ "nodeVersion": "1.0",
4
+ "codexVersion": "1.0",
5
+ "categories": ["Sales", "Productivity"],
6
+ "resources": {
7
+ "credentialDocumentation": [
8
+ {
9
+ "url": "https://github.com/kapacity-saas/n8n-nodes-kapacity#credentials"
10
+ }
11
+ ],
12
+ "primaryDocumentation": [
13
+ {
14
+ "url": "https://kapacity.app/docs/api"
15
+ }
16
+ ]
17
+ }
18
+ }