atlas-crm-api-client 0.0.0-development

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Ryan Sonshine
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # atlas-crm-api-client
2
+
3
+ [![npm package][npm-img]][npm-url] [![Build Status][build-img]][build-url]
4
+ [![Downloads][downloads-img]][downloads-url] [![Issues][issues-img]][issues-url]
5
+ [![Code Coverage][codecov-img]][codecov-url]
6
+ [![Commitizen Friendly][commitizen-img]][commitizen-url]
7
+ [![Semantic Release][semantic-release-img]][semantic-release-url]
8
+
9
+ > AtlasCRM API Client
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm install atlas-crm-api-client
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```ts
20
+ import { AtlasCrmClient } from "atlas-crm-api-client";
21
+
22
+ const client = new AtlasCrmClient({
23
+ clientId: "YOUR_CLIENT_ID",
24
+ clientSecret: "YOUR_CLIENT_SECRET",
25
+ workspace: "CRM", // Defaults to CRM
26
+ });
27
+
28
+ // Grouped by entity type as per Swagger
29
+ const companies = await client.companies.list({ size: 50 });
30
+ const contact = await client.contacts.get("uuid");
31
+
32
+ // Easy creation with typed fields
33
+ const newCompany = await client.companies.create({
34
+ "company-name": "Acme Corp",
35
+ "company-website": "https://acme.com",
36
+ });
37
+
38
+ // Link Jira issues
39
+ await client.issues.link(newCompany.id, ["PROJ-1", "PROJ-2"]);
40
+ ```
41
+
42
+ ## API
43
+
44
+ ### myPackage(input, options?)
45
+
46
+ #### input
47
+
48
+ Type: `string`
49
+
50
+ Lorem ipsum.
51
+
52
+ #### options
53
+
54
+ Type: `object`
55
+
56
+ ##### postfix
57
+
58
+ Type: `string` Default: `rainbows`
59
+
60
+ Lorem ipsum.
61
+
62
+ [build-img]: https://github.com/ryansonshine/typescript-npm-package-template/actions/workflows/release.yml/badge.svg
63
+ [build-url]: https://github.com/ryansonshine/typescript-npm-package-template/actions/workflows/release.yml
64
+ [downloads-img]: https://img.shields.io/npm/dt/typescript-npm-package-template
65
+ [downloads-url]: https://www.npmtrends.com/typescript-npm-package-template
66
+ [npm-img]: https://img.shields.io/npm/v/typescript-npm-package-template
67
+ [npm-url]: https://www.npmjs.com/package/typescript-npm-package-template
68
+ [issues-img]: https://img.shields.io/github/issues/ryansonshine/typescript-npm-package-template
69
+ [issues-url]: https://github.com/ryansonshine/typescript-npm-package-template/issues
70
+ [codecov-img]: https://codecov.io/gh/ryansonshine/typescript-npm-package-template/branch/main/graph/badge.svg
71
+ [codecov-url]: https://codecov.io/gh/ryansonshine/typescript-npm-package-template
72
+ [semantic-release-img]: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg
73
+ [semantic-release-url]: https://github.com/semantic-release/semantic-release
74
+ [commitizen-img]: https://img.shields.io/badge/commitizen-friendly-brightgreen.svg
75
+ [commitizen-url]: http://commitizen.github.io/cz-cli/
76
+
77
+ ---
78
+
79
+ ## Features
80
+
81
+ - [Semantic Release](https://github.com/semantic-release/semantic-release)
82
+ - [Issue Templates](https://github.com/ryansonshine/typescript-npm-package-template/tree/main/.github/ISSUE_TEMPLATE)
83
+ - [GitHub Actions](https://github.com/ryansonshine/typescript-npm-package-template/tree/main/.github/workflows)
84
+ - [Codecov](https://about.codecov.io/)
85
+ - [VSCode Launch Configurations](https://github.com/ryansonshine/typescript-npm-package-template/blob/main/.vscode/launch.json)
86
+ - [TypeScript](https://www.typescriptlang.org/)
87
+ - [Husky](https://github.com/typicode/husky)
88
+ - [Lint Staged](https://github.com/okonet/lint-staged)
89
+ - [Commitizen](https://github.com/search?q=commitizen)
90
+ - [Jest](https://jestjs.io/)
91
+ - [ESLint](https://eslint.org/)
92
+ - [Prettier](https://prettier.io/)
@@ -0,0 +1,67 @@
1
+ import type { Entity, PaginatedResponse, AtlasCrmConfig, QueryParams, TemplateResponse, LinkResponse, CommentResponse } from './types';
2
+ export declare class AtlasCrmError extends Error {
3
+ message: string;
4
+ status?: number | undefined;
5
+ data?: any;
6
+ constructor(message: string, status?: number | undefined, data?: any);
7
+ }
8
+ /**
9
+ * Robust Atlas CRM API Client
10
+ * Strictly follows Swagger: https://atlascrm.avisi-apps.com/api/1.0/swagger.json
11
+ */
12
+ export declare class AtlasCrmClient {
13
+ private baseUrl;
14
+ private clientId;
15
+ private clientSecret;
16
+ private workspace;
17
+ private accessToken;
18
+ private tokenExpiry;
19
+ constructor(config: AtlasCrmConfig);
20
+ /**
21
+ * Internal Request Handler
22
+ */
23
+ private request;
24
+ /**
25
+ * OAuth2 Client Credentials Handshake
26
+ */
27
+ authenticate(): Promise<string>;
28
+ private getValidToken;
29
+ /**
30
+ * Generic Entity Operations Factory
31
+ */
32
+ private createEntityNamespace;
33
+ readonly companies: {
34
+ list: (params?: QueryParams) => Promise<PaginatedResponse<Entity>>;
35
+ get: (id: string) => Promise<Entity>;
36
+ create: (fields: Record<string, any>) => Promise<Entity>;
37
+ update: (id: string, fields: Record<string, any>) => Promise<Entity>;
38
+ delete: (id: string) => Promise<Entity>;
39
+ getTemplate: () => Promise<TemplateResponse>;
40
+ };
41
+ readonly contacts: {
42
+ list: (params?: QueryParams) => Promise<PaginatedResponse<Entity>>;
43
+ get: (id: string) => Promise<Entity>;
44
+ create: (fields: Record<string, any>) => Promise<Entity>;
45
+ update: (id: string, fields: Record<string, any>) => Promise<Entity>;
46
+ delete: (id: string) => Promise<Entity>;
47
+ getTemplate: () => Promise<TemplateResponse>;
48
+ };
49
+ readonly sales: {
50
+ list: (params?: QueryParams) => Promise<PaginatedResponse<Entity>>;
51
+ get: (id: string) => Promise<Entity>;
52
+ create: (fields: Record<string, any>) => Promise<Entity>;
53
+ update: (id: string, fields: Record<string, any>) => Promise<Entity>;
54
+ delete: (id: string) => Promise<Entity>;
55
+ getTemplate: () => Promise<TemplateResponse>;
56
+ };
57
+ /**
58
+ * Advanced endpoints (Issue links, Comments)
59
+ */
60
+ readonly issues: {
61
+ link: (entityId: string, issueIds: string[]) => Promise<LinkResponse>;
62
+ unlink: (entityId: string, issueIds: string[]) => Promise<LinkResponse>;
63
+ };
64
+ readonly comments: {
65
+ create: (entityId: string, comment: string, accountId: string) => Promise<CommentResponse>;
66
+ };
67
+ }
package/lib/client.js ADDED
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.AtlasCrmClient = exports.AtlasCrmError = void 0;
13
+ class AtlasCrmError extends Error {
14
+ constructor(message, status,
15
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
16
+ data) {
17
+ super(message);
18
+ this.message = message;
19
+ this.status = status;
20
+ this.data = data;
21
+ this.name = 'AtlasCrmError';
22
+ }
23
+ }
24
+ exports.AtlasCrmError = AtlasCrmError;
25
+ /**
26
+ * Robust Atlas CRM API Client
27
+ * Strictly follows Swagger: https://atlascrm.avisi-apps.com/api/1.0/swagger.json
28
+ */
29
+ class AtlasCrmClient {
30
+ constructor(config) {
31
+ this.accessToken = null;
32
+ this.tokenExpiry = null;
33
+ this.companies = this.createEntityNamespace('entity.type/company');
34
+ this.contacts = this.createEntityNamespace('entity.type/contact');
35
+ this.sales = this.createEntityNamespace('entity.type/sale');
36
+ /**
37
+ * Advanced endpoints (Issue links, Comments)
38
+ */
39
+ this.issues = {
40
+ link: (entityId, issueIds) => this.request('POST', `/api/1.0/workspace/${this.workspace}/entities/${entityId}/issues`, {
41
+ body: { 'issue-ids': issueIds },
42
+ }),
43
+ unlink: (entityId, issueIds) => this.request('DELETE', `/api/1.0/workspace/${this.workspace}/entities/${entityId}/issues`, {
44
+ body: { 'issue-ids': issueIds },
45
+ }),
46
+ };
47
+ this.comments = {
48
+ create: (entityId, comment, accountId) => this.request('POST', `/api/1.0/workspace/${this.workspace}/entities/${entityId}/comments`, {
49
+ body: {
50
+ format: 'plain-text',
51
+ comment,
52
+ 'account-id': accountId,
53
+ },
54
+ }),
55
+ };
56
+ this.baseUrl = (config.baseUrl || 'https://atlascrm.avisi-apps.com').replace(/\/$/, '');
57
+ this.clientId = config.clientId;
58
+ this.clientSecret = config.clientSecret;
59
+ this.workspace = config.workspace || 'CRM';
60
+ }
61
+ /**
62
+ * Internal Request Handler
63
+ */
64
+ request(method, path, options = {}, retryCount = 0) {
65
+ return __awaiter(this, void 0, void 0, function* () {
66
+ const token = yield this.getValidToken();
67
+ let url = `${this.baseUrl}${path}`;
68
+ if (options.params) {
69
+ const search = new URLSearchParams();
70
+ Object.entries(options.params).forEach(([k, v]) => {
71
+ if (v !== undefined)
72
+ search.append(k, String(v));
73
+ });
74
+ url += (url.includes('?') ? '&' : '?') + search.toString();
75
+ }
76
+ const response = yield fetch(url, {
77
+ method,
78
+ headers: {
79
+ Authorization: `Bearer ${token}`,
80
+ Accept: 'application/json',
81
+ 'Content-Type': 'application/json',
82
+ },
83
+ body: options.body ? JSON.stringify(options.body) : undefined,
84
+ });
85
+ // Handle token expiration
86
+ if (response.status === 401 && retryCount < 1) {
87
+ this.accessToken = null;
88
+ return this.request(method, path, options, retryCount + 1);
89
+ }
90
+ if (!response.ok) {
91
+ const errorData = yield response
92
+ .json()
93
+ .catch(() => ({}));
94
+ throw new AtlasCrmError(errorData.message || `Request failed with status ${response.status}`, response.status, errorData);
95
+ }
96
+ return response.json();
97
+ });
98
+ }
99
+ /**
100
+ * OAuth2 Client Credentials Handshake
101
+ */
102
+ authenticate() {
103
+ return __awaiter(this, void 0, void 0, function* () {
104
+ const credentials = btoa(`${this.clientId}:${this.clientSecret}`);
105
+ const response = yield fetch(`${this.baseUrl}/api/1.0/oauth/token`, {
106
+ method: 'POST',
107
+ headers: {
108
+ Authorization: `Basic ${credentials}`,
109
+ 'Content-Type': 'application/x-www-form-urlencoded',
110
+ },
111
+ body: new URLSearchParams({
112
+ grant_type: 'client_credentials',
113
+ }).toString(),
114
+ });
115
+ if (!response.ok) {
116
+ throw new AtlasCrmError('Authentication failed', response.status);
117
+ }
118
+ const data = yield response.json();
119
+ this.accessToken = data.access_token;
120
+ this.tokenExpiry = Date.now() + data.expires_in * 1000 - 30000;
121
+ return data.access_token;
122
+ });
123
+ }
124
+ getValidToken() {
125
+ return __awaiter(this, void 0, void 0, function* () {
126
+ if (this.accessToken && this.tokenExpiry && Date.now() < this.tokenExpiry) {
127
+ return this.accessToken;
128
+ }
129
+ return this.authenticate();
130
+ });
131
+ }
132
+ /**
133
+ * Generic Entity Operations Factory
134
+ */
135
+ createEntityNamespace(type) {
136
+ const basePath = `/api/1.0/workspace/${this.workspace}/entities`;
137
+ return {
138
+ list: (params = {}) => this.request('GET', basePath, {
139
+ params: Object.assign(Object.assign({}, params), { type }),
140
+ }),
141
+ get: (id) => this.request('GET', `${basePath}/${id}`),
142
+ create: (fields) => this.request('POST', basePath, {
143
+ body: { type, fields },
144
+ }),
145
+ update: (id, fields) => this.request('PUT', `${basePath}/${id}`, {
146
+ body: { fields },
147
+ }),
148
+ delete: (id) => this.request('DELETE', `${basePath}/${id}`),
149
+ getTemplate: () => this.request('GET', `/api/1.0/workspace/${this.workspace}/template/${type}`),
150
+ };
151
+ }
152
+ }
153
+ exports.AtlasCrmClient = AtlasCrmClient;
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './types';
2
+ export * from './client';
package/lib/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./types"), exports);
18
+ __exportStar(require("./client"), exports);
package/lib/types.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ export declare type EntityType = 'entity.type/company' | 'entity.type/contact' | 'entity.type/sale';
2
+ export interface EntityLinks {
3
+ self: {
4
+ href: string;
5
+ };
6
+ next?: {
7
+ href: string;
8
+ };
9
+ app?: {
10
+ href: string;
11
+ };
12
+ }
13
+ export interface Entity {
14
+ id: string;
15
+ type: EntityType;
16
+ fields: Record<string, any>;
17
+ _links: EntityLinks;
18
+ }
19
+ export interface Company {
20
+ name: string;
21
+ industry?: string;
22
+ description?: string;
23
+ }
24
+ export interface Contact {
25
+ firstName: string;
26
+ lastName: string;
27
+ position?: string;
28
+ }
29
+ export interface PaginatedResponse<T> {
30
+ items: T[];
31
+ total: number;
32
+ _links: EntityLinks;
33
+ }
34
+ export interface AtlasCrmConfig {
35
+ baseUrl?: string;
36
+ clientId: string;
37
+ clientSecret: string;
38
+ workspace?: string;
39
+ }
40
+ export interface QueryParams {
41
+ size?: number;
42
+ 'sort-type'?: 'asc' | 'desc';
43
+ 'sort-by'?: string;
44
+ cursor?: string;
45
+ [key: string]: any;
46
+ }
47
+ export interface TemplateField {
48
+ id: string;
49
+ label: string;
50
+ type: string;
51
+ required: boolean;
52
+ 'default-value'?: string;
53
+ 'allowed-values'?: Record<string, any>;
54
+ config?: {
55
+ currency?: string;
56
+ max?: number;
57
+ min?: number;
58
+ };
59
+ }
60
+ export interface TemplateSection {
61
+ name: string;
62
+ fields: TemplateField[];
63
+ }
64
+ export interface TemplateResponse {
65
+ sections: TemplateSection[];
66
+ }
67
+ export declare type LinkResponse = {
68
+ issue_ids: string[];
69
+ } | {
70
+ message: string;
71
+ 'invalid-issue-ids': string[];
72
+ } | {
73
+ message: string;
74
+ };
75
+ export declare type CommentResponse = Record<'id' | 'comment' | 'account-id', string> | Record<string, never>;
package/lib/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,115 @@
1
+ {
2
+ "name": "atlas-crm-api-client",
3
+ "version": "0.0.0-development",
4
+ "description": "A template for creating npm packages using TypeScript and VSCode",
5
+ "main": "./lib/index.js",
6
+ "files": [
7
+ "lib/**/*"
8
+ ],
9
+ "scripts": {
10
+ "build": "tsc --project tsconfig.build.json",
11
+ "clean": "rm -rf ./lib/",
12
+ "cm": "cz",
13
+ "lint": "eslint ./src/ --fix",
14
+ "prepare": "husky install",
15
+ "semantic-release": "semantic-release",
16
+ "test:watch": "jest --watch",
17
+ "test": "jest --coverage",
18
+ "typecheck": "tsc --noEmit"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/oskarherz/atlas-crm-api-client.git"
23
+ },
24
+ "license": "MIT",
25
+ "author": {
26
+ "name": "Oskar Herz",
27
+ "email": "oskarherz@users.noreply.github.com",
28
+ "url": "https://github.com/oskarherz"
29
+ },
30
+ "engines": {
31
+ "node": ">=12.0"
32
+ },
33
+ "keywords": [
34
+ "typescript",
35
+ "vscode",
36
+ "jest",
37
+ "husky",
38
+ "commitizen",
39
+ "semantic-release"
40
+ ],
41
+ "devDependencies": {
42
+ "@ryansonshine/commitizen": "^4.2.8",
43
+ "@ryansonshine/cz-conventional-changelog": "^3.3.4",
44
+ "@types/jest": "^27.5.2",
45
+ "@types/node": "^12.20.11",
46
+ "@typescript-eslint/eslint-plugin": "^4.22.0",
47
+ "@typescript-eslint/parser": "^4.22.0",
48
+ "conventional-changelog-conventionalcommits": "^5.0.0",
49
+ "eslint": "^7.25.0",
50
+ "eslint-config-prettier": "^8.3.0",
51
+ "eslint-plugin-node": "^11.1.0",
52
+ "eslint-plugin-prettier": "^3.4.0",
53
+ "husky": "^6.0.0",
54
+ "jest": "^27.2.0",
55
+ "lint-staged": "^13.2.1",
56
+ "prettier": "^2.2.1",
57
+ "semantic-release": "^21.0.1",
58
+ "ts-jest": "^27.0.5",
59
+ "ts-node": "^10.2.1",
60
+ "typescript": "^4.2.4"
61
+ },
62
+ "config": {
63
+ "commitizen": {
64
+ "path": "./node_modules/@ryansonshine/cz-conventional-changelog"
65
+ }
66
+ },
67
+ "lint-staged": {
68
+ "*.ts": "eslint --cache --cache-location .eslintcache --fix"
69
+ },
70
+ "release": {
71
+ "branches": [
72
+ "main"
73
+ ],
74
+ "plugins": [
75
+ [
76
+ "@semantic-release/commit-analyzer",
77
+ {
78
+ "preset": "conventionalcommits",
79
+ "releaseRules": [
80
+ {
81
+ "type": "build",
82
+ "scope": "deps",
83
+ "release": "patch"
84
+ }
85
+ ]
86
+ }
87
+ ],
88
+ [
89
+ "@semantic-release/release-notes-generator",
90
+ {
91
+ "preset": "conventionalcommits",
92
+ "presetConfig": {
93
+ "types": [
94
+ {
95
+ "type": "feat",
96
+ "section": "Features"
97
+ },
98
+ {
99
+ "type": "fix",
100
+ "section": "Bug Fixes"
101
+ },
102
+ {
103
+ "type": "build",
104
+ "section": "Dependencies and Other Build Updates",
105
+ "hidden": false
106
+ }
107
+ ]
108
+ }
109
+ }
110
+ ],
111
+ "@semantic-release/npm",
112
+ "@semantic-release/github"
113
+ ]
114
+ }
115
+ }