itrm-tools 1.3.2 → 1.3.5-beta.1

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 (175) hide show
  1. package/.github/workflows/node.js.yml +30 -0
  2. package/README.md +2 -2
  3. package/dist/api/APIRequest.js +22 -29
  4. package/dist/api/APIRequest.js.map +1 -1
  5. package/dist/api/APIRouter.js +3 -1
  6. package/dist/api/APIRouter.js.map +1 -1
  7. package/dist/api/APIService.js +11 -17
  8. package/dist/api/APIService.js.map +1 -1
  9. package/dist/api/HttpsAPIService.js +5 -13
  10. package/dist/api/HttpsAPIService.js.map +1 -1
  11. package/dist/api/alegra/AlegraConnectionManager.js +23 -50
  12. package/dist/api/alegra/AlegraConnectionManager.js.map +1 -1
  13. package/dist/api/channel/ServerSentEventsManager.js +2 -1
  14. package/dist/api/channel/ServerSentEventsManager.js.map +1 -1
  15. package/dist/api/check/APIChecker.js +11 -25
  16. package/dist/api/check/APIChecker.js.map +1 -1
  17. package/dist/api/check/CheckableAPIRequest.js +17 -29
  18. package/dist/api/check/CheckableAPIRequest.js.map +1 -1
  19. package/dist/api/check/CheckableAPIRouter.js +17 -29
  20. package/dist/api/check/CheckableAPIRouter.js.map +1 -1
  21. package/dist/api/check/request/CheckableFileUploadingPostRequest.js +2 -0
  22. package/dist/api/check/request/CheckableFileUploadingPostRequest.js.map +1 -1
  23. package/dist/api/check/route/CorsCheckApiRouter.js +2 -13
  24. package/dist/api/check/route/CorsCheckApiRouter.js.map +1 -1
  25. package/dist/api/check/route/SimpleCheckableAPIRouter.js +2 -13
  26. package/dist/api/check/route/SimpleCheckableAPIRouter.js.map +1 -1
  27. package/dist/api/external/ExternalApiSigner.js +2 -0
  28. package/dist/api/external/ExternalApiSigner.js.map +1 -1
  29. package/dist/api/external/cetus/CetusStrategyApiManager.js +8 -20
  30. package/dist/api/external/cetus/CetusStrategyApiManager.js.map +1 -1
  31. package/dist/api/request/RequestAxiosCall.js +20 -37
  32. package/dist/api/request/RequestAxiosCall.js.map +1 -1
  33. package/dist/api/request/crud/CrudServiceManager.js +6 -17
  34. package/dist/api/request/crud/CrudServiceManager.js.map +1 -1
  35. package/dist/api/request/docs/DocumentationRequest.js +4 -7
  36. package/dist/api/request/docs/DocumentationRequest.js.map +1 -1
  37. package/dist/api/route/SimpleAPIRouter.js +2 -13
  38. package/dist/api/route/SimpleAPIRouter.js.map +1 -1
  39. package/dist/database/mongoose/MongooseModelManager.d.ts +8 -40
  40. package/dist/database/mongoose/MongooseModelManager.js +5 -14
  41. package/dist/database/mongoose/MongooseModelManager.js.map +1 -1
  42. package/dist/database/redis/RedisConnection.js +1 -0
  43. package/dist/database/redis/RedisConnection.js.map +1 -1
  44. package/dist/database/redis/RedisModelManager.js +1 -0
  45. package/dist/database/redis/RedisModelManager.js.map +1 -1
  46. package/dist/database/sequelize/SequelizeConnection.js +1 -0
  47. package/dist/database/sequelize/SequelizeConnection.js.map +1 -1
  48. package/dist/database/sequelize/SequelizeModelManager.js +6 -15
  49. package/dist/database/sequelize/SequelizeModelManager.js.map +1 -1
  50. package/dist/index.d.ts +0 -13
  51. package/dist/index.js +1 -28
  52. package/dist/index.js.map +1 -1
  53. package/dist/log/Logger.js +2 -0
  54. package/dist/log/Logger.js.map +1 -1
  55. package/dist/log/LoggerManager.js +11 -21
  56. package/dist/log/LoggerManager.js.map +1 -1
  57. package/dist/log/LoggerWebSocket.js +4 -2
  58. package/dist/log/LoggerWebSocket.js.map +1 -1
  59. package/dist/web3/coingecko/CoingeckoPriceFinder.js +24 -36
  60. package/dist/web3/coingecko/CoingeckoPriceFinder.js.map +1 -1
  61. package/jest.config.js +7 -0
  62. package/package.json +68 -74
  63. package/sequelize.sqlite +0 -0
  64. package/src/algorithm/encryption/EncryptionAlgorithm.ts +4 -0
  65. package/src/api/APIRequest.ts +176 -0
  66. package/src/api/APIRequestBuilder.ts +28 -0
  67. package/src/api/APIRouter.ts +26 -0
  68. package/src/api/APIService.ts +117 -0
  69. package/src/api/ExpressConfiguration.ts +5 -0
  70. package/src/api/HttpsAPIService.ts +35 -0
  71. package/src/api/alegra/AlegraConnectionManager.ts +54 -0
  72. package/src/api/alegra/AlegraTypes.ts +150 -0
  73. package/src/api/builder/StandardGetRequestBuilder.ts +34 -0
  74. package/src/api/channel/ServerSentEventsManager.ts +28 -0
  75. package/src/api/check/APIChecker.ts +50 -0
  76. package/src/api/check/CheckableAPIRequest.ts +33 -0
  77. package/src/api/check/CheckableAPIRouter.ts +39 -0
  78. package/src/api/check/request/CheckableDeleteRequest.ts +17 -0
  79. package/src/api/check/request/CheckableFileUploadingPostRequest.ts +26 -0
  80. package/src/api/check/request/CheckableGetRequest.ts +17 -0
  81. package/src/api/check/request/CheckablePostRequest.ts +17 -0
  82. package/src/api/check/request/CheckablePutRequest.ts +17 -0
  83. package/src/api/check/route/CorsCheckApiRouter.ts +22 -0
  84. package/src/api/check/route/SimpleCheckableAPIRouter.ts +14 -0
  85. package/src/api/express/ExpressFileUploadingConfiguration.ts +22 -0
  86. package/src/api/express/ExpressLogableConfig.ts +11 -0
  87. package/src/api/express/ExpressStandardConfiguration.ts +25 -0
  88. package/src/api/external/ExternalApiSigner.ts +29 -0
  89. package/src/api/external/cetus/CetusStrategyApiManager.ts +48 -0
  90. package/src/api/request/DeleteRequest.ts +16 -0
  91. package/src/api/request/GetRequest.ts +16 -0
  92. package/src/api/request/PostRequest.ts +16 -0
  93. package/src/api/request/PutRequest.ts +16 -0
  94. package/src/api/request/RequestAxiosCall.ts +38 -0
  95. package/src/api/request/crud/CrudManager.ts +11 -0
  96. package/src/api/request/crud/CrudServiceManager.ts +117 -0
  97. package/src/api/request/docs/DocumentationModels.ts +121 -0
  98. package/src/api/request/docs/DocumentationRequest.ts +132 -0
  99. package/src/api/route/SimpleAPIRouter.ts +12 -0
  100. package/src/database/mongoose/MongooseModelManager.ts +65 -0
  101. package/src/database/redis/RedisConnection.ts +18 -0
  102. package/src/database/redis/RedisModelManager.ts +23 -0
  103. package/src/database/sequelize/SequelizeConnection.ts +45 -0
  104. package/src/database/sequelize/SequelizeModelManager.ts +71 -0
  105. package/src/index.ts +51 -0
  106. package/src/log/Logger.ts +27 -0
  107. package/src/log/LoggerManager.ts +50 -0
  108. package/src/log/LoggerWebSocket.ts +13 -0
  109. package/src/math/Utils.ts +4 -0
  110. package/src/types/payments.ts +811 -0
  111. package/src/web3/Coin.ts +18 -0
  112. package/src/web3/coingecko/CoingeckoPriceFinder.ts +75 -0
  113. package/test/api/APIRouter.test.ts +78 -0
  114. package/test/api/APIService.test.ts +50 -0
  115. package/test/api/APITestDefinitions.ts +7 -0
  116. package/test/api/CORS.test.ts +56 -0
  117. package/test/api/alegra/AlegraConnectionManager.test.ts +32 -0
  118. package/test/api/check/CheckDefinitions.ts +47 -0
  119. package/test/api/check/CheckableAPIRouter.test.ts +67 -0
  120. package/test/api/check/CheckableDeleteRequest.test.ts +92 -0
  121. package/test/api/check/CheckableGetRequest.test.ts +99 -0
  122. package/test/api/check/CheckablePostRequest.test.ts +108 -0
  123. package/test/api/check/CheckablePutRequest.test.ts +99 -0
  124. package/test/api/docs/DocumentationRequest.test.ts +192 -0
  125. package/test/api/request/DeleteRequest.test.ts +117 -0
  126. package/test/api/request/GetRequest.test.ts +140 -0
  127. package/test/api/request/PostRequest.test.ts +237 -0
  128. package/test/api/request/PutRequest.test.ts +166 -0
  129. package/test/database/mongoose/MongooseModelManager.test.ts +139 -0
  130. package/test/database/redis/RedisConnection.test.ts +7 -0
  131. package/test/database/sequelize/SequealizeDefinitions.ts +6 -0
  132. package/test/database/sequelize/SequelizeConnection.test.ts +30 -0
  133. package/test/database/sequelize/SequelizeModelManager.test.ts +206 -0
  134. package/test/log/Logger.test.ts +44 -0
  135. package/test/web3/coingecko/CoingeckoPriceFinder.test.ts +72 -0
  136. package/tsconfig.json +23 -0
  137. package/dist/api/check/RoleServicePermissionsChecker.d.ts +0 -13
  138. package/dist/api/check/RoleServicePermissionsChecker.js +0 -92
  139. package/dist/api/check/RoleServicePermissionsChecker.js.map +0 -1
  140. package/dist/api/check/ServiceSessionChecker.d.ts +0 -28
  141. package/dist/api/check/ServiceSessionChecker.js +0 -119
  142. package/dist/api/check/ServiceSessionChecker.js.map +0 -1
  143. package/dist/api/request/crud/common/ActivityHistoryManager.d.ts +0 -40
  144. package/dist/api/request/crud/common/ActivityHistoryManager.js +0 -86
  145. package/dist/api/request/crud/common/ActivityHistoryManager.js.map +0 -1
  146. package/dist/api/request/crud/common/ApplicationManager.d.ts +0 -39
  147. package/dist/api/request/crud/common/ApplicationManager.js +0 -72
  148. package/dist/api/request/crud/common/ApplicationManager.js.map +0 -1
  149. package/dist/api/request/crud/common/AvailablePlatformManager.d.ts +0 -39
  150. package/dist/api/request/crud/common/AvailablePlatformManager.js +0 -86
  151. package/dist/api/request/crud/common/AvailablePlatformManager.js.map +0 -1
  152. package/dist/api/request/crud/common/ComponentManager.d.ts +0 -56
  153. package/dist/api/request/crud/common/ComponentManager.js +0 -78
  154. package/dist/api/request/crud/common/ComponentManager.js.map +0 -1
  155. package/dist/api/request/crud/common/KeyManager.d.ts +0 -39
  156. package/dist/api/request/crud/common/KeyManager.js +0 -88
  157. package/dist/api/request/crud/common/KeyManager.js.map +0 -1
  158. package/dist/api/request/crud/common/PlatformManager.d.ts +0 -44
  159. package/dist/api/request/crud/common/PlatformManager.js +0 -75
  160. package/dist/api/request/crud/common/PlatformManager.js.map +0 -1
  161. package/dist/api/request/crud/common/RoleManager.d.ts +0 -56
  162. package/dist/api/request/crud/common/RoleManager.js +0 -75
  163. package/dist/api/request/crud/common/RoleManager.js.map +0 -1
  164. package/dist/api/request/crud/common/StatusManager.d.ts +0 -34
  165. package/dist/api/request/crud/common/StatusManager.js +0 -74
  166. package/dist/api/request/crud/common/StatusManager.js.map +0 -1
  167. package/dist/api/request/crud/common/TypeManager.d.ts +0 -33
  168. package/dist/api/request/crud/common/TypeManager.js +0 -76
  169. package/dist/api/request/crud/common/TypeManager.js.map +0 -1
  170. package/dist/api/request/crud/common/UserCredentialsManager.d.ts +0 -39
  171. package/dist/api/request/crud/common/UserCredentialsManager.js +0 -84
  172. package/dist/api/request/crud/common/UserCredentialsManager.js.map +0 -1
  173. package/dist/api/request/crud/common/UserManager.d.ts +0 -35
  174. package/dist/api/request/crud/common/UserManager.js +0 -80
  175. package/dist/api/request/crud/common/UserManager.js.map +0 -1
@@ -0,0 +1,176 @@
1
+ import { Express, Request, Response, Router } from 'express';
2
+ import { ITRMAPIServiceGlobal } from './APIService';
3
+ import { ServerSentEventsManager } from './channel/ServerSentEventsManager';
4
+ import { DocDetails } from './APIRequestBuilder';
5
+
6
+ export enum RequestMethod {
7
+ GET = "GET",
8
+ POST = "POST",
9
+ PUT = "PUT",
10
+ DELETE = "DELETE"
11
+ }
12
+
13
+ export enum RequestContext {
14
+ BODY = 'body',
15
+ HEADERS = 'headers',
16
+ PARAMS = 'params',
17
+ QUERY = 'query'
18
+ }
19
+
20
+ export enum RequestParameterType {
21
+ STRING = 'string',
22
+ NUMBER = 'number',
23
+ BOOLEAN = 'boolean',
24
+ OBJECT = 'object'
25
+ }
26
+
27
+ export declare interface IProperties {
28
+ name: string,
29
+ type: RequestParameterType,
30
+ }
31
+
32
+ export declare interface IMissing {
33
+ missing: string[],
34
+ wrongType: string[]
35
+ }
36
+
37
+ export declare interface GroupedParameters {
38
+ context: RequestContext,
39
+ properties: IProperties[]
40
+ }
41
+
42
+ export declare interface APIRequestConfig {
43
+ path: string,
44
+ params: GroupedParameters[],
45
+ details?: DocDetails
46
+ }
47
+
48
+ export abstract class APIRequest {
49
+ public method: RequestMethod;
50
+ public path: string;
51
+ public details?: DocDetails;
52
+ protected params: GroupedParameters[];
53
+ protected bodyParams: GroupedParameters[];
54
+
55
+ constructor(method: RequestMethod, config: APIRequestConfig) {
56
+ this.method = method;
57
+ this.path = config.path;
58
+ this.params = config.params;
59
+ this.details = config.details;
60
+ this.bodyParams = config.params.filter(param => { return param.context === RequestContext.BODY; });
61
+ }
62
+
63
+ public abstract addToApp(app: Express): void;
64
+ public abstract addToRouter(router: Router): void;
65
+ public abstract apply(req: Request, res: Response): Promise<any>;
66
+
67
+ public getRequestDetails() {
68
+ return {
69
+ path: this.path,
70
+ method: this.method,
71
+ params: this.params,
72
+ details: this.details,
73
+ bodyParams: this.bodyParams
74
+ }
75
+ }
76
+
77
+ public async process(req: Request, res: Response): Promise<any> {
78
+ try {
79
+ let request: APIRequest = ITRMAPIServiceGlobal.requests[APIRequest.buildKey(req)];
80
+ let check: any = request.checkParameters(req);
81
+ for (let key of Object.keys(check))
82
+ if (check[key].status !== 'OK')
83
+ return await res.status(400).json(check[key]);
84
+ return await request.apply(req, res);
85
+ } catch (error: any) {
86
+ console.log(">>> error:", error);
87
+ return await res.status(error?.response?.status ?? 500).json({
88
+ type: 'InternalRequestError',
89
+ error: 'An error has ocurred when procesing the request',
90
+ payload: error?.response?.data ?? error
91
+ });
92
+ }
93
+ }
94
+
95
+ public static buildKey(req: Request) {
96
+ if (req.route.path.includes(req.baseUrl))
97
+ return req.method + "_" + req.route.path;
98
+ return req.method + "_" + req.baseUrl + req.route.path;
99
+ }
100
+
101
+ private checkParameters(req: Request): any {
102
+ let result: any = this.checkItem(req, this.params);
103
+ if (this.hasValidValuesProperty(req.body))
104
+ result = this.checkValuesPropertyParameters(req);
105
+ return result;
106
+ }
107
+
108
+ private checkValuesPropertyParameters(req: Request): any {
109
+ let result: any = {};
110
+ for (let i = 0; i < req.body.values.length; i++) {
111
+ result = this.checkItem({ body: req.body.values[i] }, this.bodyParams);
112
+ if (result[RequestContext.BODY].status === 'Error') {
113
+ result[RequestContext.BODY].message += ', item ' + (i + 1);
114
+ return result;
115
+ }
116
+ }
117
+ return result;
118
+ }
119
+
120
+ private hasValidValuesProperty(context: any) {
121
+ return context && context.values && Array.isArray(context.values);
122
+ }
123
+
124
+ private checkItem(item: any, params: GroupedParameters[]) {
125
+ let result: any = {};
126
+ for (let group of params) {
127
+ if (item[group.context])
128
+ result[group.context] = this.buildResponseMessage(result[group.context], group, this.findMissingParameters(item[group.context], group.properties));
129
+ else
130
+ return { status: 'Error', message: group.context + " was not found, check your express configuration" };
131
+ }
132
+ return result;
133
+ }
134
+
135
+ private buildResponseMessage(response: any, group: GroupedParameters, failures: IMissing): any {
136
+ if (failures.missing.length > 0 || failures.wrongType.length > 0)
137
+ return (response && response.blocked) ? response : { status: 'Error', message: this.buildMissingParametersMessage(group.context, failures.missing, failures.wrongType), blocked: group.properties.length > failures.missing.length };
138
+ return { status: 'OK', blocked: true };
139
+ }
140
+
141
+ private buildMissingParametersMessage(context: RequestContext, missing: string[], wrongType: string[]) {
142
+ let message = "Parameters";
143
+ if (missing.length > 0) {
144
+ message += this.buildMessage(missing)
145
+ message += " were not found in " + context;
146
+ }
147
+ if (wrongType.length > 0) {
148
+ message += missing.length > 0 ? " and" : "";
149
+ message += this.buildMessage(wrongType)
150
+ message += " have invalid type ";
151
+ }
152
+ return message;
153
+ }
154
+
155
+ private buildMessage(array: string[]) {
156
+ let message = "";
157
+ for (let i = 0; i < array.length; i++)
158
+ message += (i > 0 ? ", " : " ") + "'" + array[i] + "'";
159
+ return message;
160
+ }
161
+
162
+ private findMissingParameters(context: any, properties: IProperties[]) {
163
+ let missing: string[] = [];
164
+ let wrongType: string[] = [];
165
+ for (let property of properties)
166
+ if (context[property.name] === undefined || context[property.name] === null)
167
+ missing.push(property.name);
168
+ else if (typeof context[property.name] !== property.type)
169
+ wrongType.push(property.name);
170
+ return { missing, wrongType };
171
+ }
172
+
173
+ protected openSentServerEvents(res: Response) {
174
+ return new ServerSentEventsManager(res);
175
+ }
176
+ }
@@ -0,0 +1,28 @@
1
+ import { GroupedParameters } from "./APIRequest"
2
+
3
+ export declare interface ISamples {
4
+ status: number,
5
+ input: any,
6
+ output: any
7
+ }
8
+
9
+ export declare interface DocDetails {
10
+ description: string,
11
+ samples: ISamples[]
12
+ }
13
+
14
+ export abstract class APIRequestBuilder {
15
+
16
+ constructor() { }
17
+
18
+ public abstract buildParams(): GroupedParameters[];
19
+ public abstract buildDocDetails(): DocDetails;
20
+
21
+ public buildApiRequestConfig(path: string) {
22
+ return {
23
+ path: path,
24
+ params: this.buildParams(),
25
+ details: this.buildDocDetails()
26
+ }
27
+ }
28
+ }
@@ -0,0 +1,26 @@
1
+ import { NextFunction, Router, RouterOptions,Request, Response } from 'express';
2
+ import { APIRequest } from './APIRequest';
3
+ import { ITRMAPIServiceGlobal } from './APIService';
4
+
5
+ export abstract class APIRouter {
6
+ public path: string;
7
+ public router: Router;
8
+ public linkedRequest: string[] = [];
9
+
10
+ constructor(path: string, options?: RouterOptions) {
11
+ this.path = path;
12
+ this.router = Router(options);
13
+ }
14
+
15
+ public init() {
16
+ this.router.use(this.runMiddleware);
17
+ }
18
+
19
+ public addRequest(request: APIRequest) {
20
+ ITRMAPIServiceGlobal.requests[request.method + "_" + this.path + request.path] = request;
21
+ request.addToRouter(this.router);
22
+ this.linkedRequest.push(request.method + "_" + this.path + request.path);
23
+ }
24
+
25
+ protected abstract runMiddleware(req: Request, res: Response, next: NextFunction): Promise<void | Response | any>;
26
+ }
@@ -0,0 +1,117 @@
1
+ import express, { Express, Request, Response } from 'express';
2
+ import { APIRequest } from './APIRequest';
3
+ import { APIRouter } from './APIRouter';
4
+ import { ExpressConfiguration } from './ExpressConfiguration';
5
+ import { DocumentationRequest } from './request/docs/DocumentationRequest';
6
+
7
+ export namespace ITRMAPIServiceGlobal {
8
+ export var memory: any = {};
9
+ export var service: APIService | undefined = undefined;
10
+ export var requests: any = {};
11
+ export var routers: any = {};
12
+ export var whitelist: string[] = [];
13
+ export var tools: any = {};
14
+ }
15
+
16
+ export declare interface APIServiceConfig {
17
+ name: string,
18
+ port: string | number,
19
+ express: ExpressConfiguration
20
+ }
21
+
22
+ export declare interface APIServiceResponse {
23
+ status: string,
24
+ message: string,
25
+ error?: any
26
+ }
27
+
28
+ export class APIService {
29
+ protected server: any = undefined;
30
+ protected app: Express = express();
31
+ protected name: string;
32
+ protected port: number | string;
33
+ protected config: ExpressConfiguration;
34
+
35
+ constructor(config: APIServiceConfig) {
36
+ this.name = config.name;
37
+ this.port = config.port;
38
+ this.config = config.express;
39
+ }
40
+
41
+ public init() {
42
+ ITRMAPIServiceGlobal.service = this;
43
+ this.config.apply(this.app);
44
+ this.app.get('/', (req: Request, res: Response | any) => {
45
+ return res.send('Server working!');
46
+ });
47
+ }
48
+
49
+ public addRouter(router: APIRouter) {
50
+ ITRMAPIServiceGlobal.routers[router.path] = router;
51
+ this.app.use(router.path, router.router);
52
+ }
53
+
54
+ public addRequest(request: APIRequest) {
55
+ ITRMAPIServiceGlobal.requests[request.method + "_" + request.path] = request;
56
+ request.addToApp(this.app);
57
+ }
58
+
59
+ public getServerInformation() {
60
+ return {
61
+ name: this.name,
62
+ port: this.port,
63
+ routers: ITRMAPIServiceGlobal.routers,
64
+ requests: ITRMAPIServiceGlobal.requests
65
+ }
66
+ }
67
+
68
+ public enableDocumentation() {
69
+ const swaggerUi = require('swagger-ui-express');
70
+ const documentationRequest = new DocumentationRequest();
71
+ this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(documentationRequest.init()));
72
+ }
73
+
74
+ public run(init: Function): Promise<APIServiceResponse> {
75
+ return new Promise<APIServiceResponse>((resolve, reject) => {
76
+ this.server = this.app.listen(this.port, async () => {
77
+ console.log(`⚡️[server]: Server is running at http://localhost:${this.port}`);
78
+ try {
79
+ await init();
80
+ resolve({ status: 'Ok', message: 'Server has been Initialized' });
81
+ } catch (err: any) {
82
+ reject({
83
+ status: 'Error',
84
+ message: 'An error has ocurred in the initialization function',
85
+ error: err
86
+ });
87
+ }
88
+ });
89
+ });
90
+ }
91
+
92
+ public close(finish: Function): Promise<APIServiceResponse> {
93
+ return new Promise<APIServiceResponse>((resolve, reject) => {
94
+ this.server.close(async (err: any) => {
95
+ if (err)
96
+ reject({
97
+ status: 'Error',
98
+ message: 'An error has ocurred when closing Server',
99
+ error: err
100
+ });
101
+ try {
102
+ await finish();
103
+ resolve({
104
+ status: 'Ok',
105
+ message: 'Server has been closed'
106
+ });
107
+ } catch (err: any) {
108
+ reject({
109
+ status: 'Error',
110
+ message: 'An error has ocurred in the closing function',
111
+ error: err
112
+ });
113
+ }
114
+ });
115
+ });
116
+ }
117
+ }
@@ -0,0 +1,5 @@
1
+ import { Express } from 'express';
2
+
3
+ export interface ExpressConfiguration {
4
+ apply(app: Express): void;
5
+ }
@@ -0,0 +1,35 @@
1
+ import https, { ServerOptions } from 'https';
2
+ import { APIService, APIServiceConfig, APIServiceResponse } from "./APIService";
3
+
4
+ export class HttpsAPIService extends APIService {
5
+ private httpsServer: any = undefined;
6
+ private options: ServerOptions;
7
+
8
+ constructor(config: APIServiceConfig, options: ServerOptions) {
9
+ super(config);
10
+ this.options = options;
11
+ }
12
+
13
+ public init() {
14
+ super.init();
15
+ this.httpsServer = https.createServer(this.options, this.app);
16
+ }
17
+
18
+ public run(init: Function): Promise<APIServiceResponse> {
19
+ return new Promise<APIServiceResponse>((resolve, reject) => {
20
+ this.server = this.httpsServer.listen(this.port, async () => {
21
+ console.log(`⚡️[server]: Server is running at https://localhost:${this.port}`);
22
+ try {
23
+ await init();
24
+ resolve({ status: 'Ok', message: 'Server has been Initialized' });
25
+ } catch (err: any) {
26
+ reject({
27
+ status: 'Error',
28
+ message: 'An error has ocurred in the initialization function',
29
+ error: err
30
+ });
31
+ }
32
+ });
33
+ });
34
+ }
35
+ }
@@ -0,0 +1,54 @@
1
+ import { AxiosRequestConfig } from "axios";
2
+ import { RequestAxiosCall } from "../request/RequestAxiosCall";
3
+ import { IAlegraContact, IAlegraJournal, IAlegraPayment, IAlegraResult } from "./AlegraTypes";
4
+
5
+ export class AlegraConnectionManager {
6
+ private alegraUrl: string;
7
+ private headers: AxiosRequestConfig;
8
+
9
+ constructor(alegraUrl: string, token: string) {
10
+ this.alegraUrl = alegraUrl;
11
+ this.headers = { headers: { Authorization: `Basic ${token}` } };
12
+ }
13
+
14
+ public async createContact(contact: IAlegraContact) {
15
+ return (await RequestAxiosCall.post(`${this.alegraUrl}/v1/contacts`, contact, this.headers)) as IAlegraContact;
16
+ }
17
+
18
+ public async findContact(document: string): Promise<IAlegraContact | undefined> {
19
+ let response: any = await RequestAxiosCall.get(`${this.alegraUrl}/v1/contacts?order_direction=ASC&identification=${document}`, this.headers);
20
+ return response.length > 0 ? response[0] : undefined;
21
+ }
22
+
23
+ public async createJournal(body: IAlegraJournal) {
24
+ return (await RequestAxiosCall.post(`${this.alegraUrl}/v1/journals`, body, this.headers)) as IAlegraJournal;
25
+ }
26
+
27
+ public async findJournal(journalId: string | number) {
28
+ return (await RequestAxiosCall.get(`${this.alegraUrl}/v1/journals/${journalId}`, this.headers) as IAlegraJournal);
29
+ }
30
+
31
+ public async updateJournal(journalId: string | number, body: IAlegraJournal) {
32
+ return await RequestAxiosCall.put(`${this.alegraUrl}/v1/journals/${journalId}`, body, this.headers);
33
+ }
34
+
35
+ public async deleteJournal(journalId: string | number) {
36
+ return (await RequestAxiosCall.delete(`${this.alegraUrl}/v1/journals/${journalId}`, this.headers)) as IAlegraResult;
37
+ }
38
+
39
+ public async createPayment(body: IAlegraPayment) {
40
+ return (await RequestAxiosCall.post(`${this.alegraUrl}/v1/payments`, body, this.headers)) as IAlegraPayment;
41
+ }
42
+
43
+ public async findPayment(paymentId: string | number) {
44
+ return (await RequestAxiosCall.get(`${this.alegraUrl}/v1/payments/${paymentId}`, this.headers) as IAlegraPayment);
45
+ }
46
+
47
+ public async updatePayment(paymentId: string | number, body: IAlegraPayment) {
48
+ return await RequestAxiosCall.put(`${this.alegraUrl}/v1/payments/${paymentId}`, body, this.headers);
49
+ }
50
+
51
+ public async deletePayment(paymentId: string | number) {
52
+ return (await RequestAxiosCall.delete(`${this.alegraUrl}/v1/payments/${paymentId}`, this.headers)) as IAlegraResult;
53
+ }
54
+ }
@@ -0,0 +1,150 @@
1
+ export interface IAlegraContact {
2
+ id?: string | number;
3
+ name?: string;
4
+ identification?: string;
5
+ email?: string;
6
+ phonePrimary?: string;
7
+ phoneSecondary?: string;
8
+ fax?: string;
9
+ mobile?: string;
10
+ observations?: string;
11
+ status?: 'active' | 'inactive';
12
+ kindOfPerson?: 'PERSON_ENTITY' | 'LEGAL_ENTITY ' | 'OTHER_ENTITY ';
13
+ regime?: 'COMMON_REGIME' | 'SIMPLIFIED_REGIME' | 'NATIONAL_CONSUMPTION_TAX' | 'NOT_REPONSIBLE_FOR_CONSUMPTION' | 'INC_IVA_RESPONSIBLE' | 'SPECIAL_REGIME';
14
+ nameObject?: {
15
+ firstName: string;
16
+ secondName: string;
17
+ lastName: string;
18
+ secondLastName?: string;
19
+ };
20
+ identificationObject?: {
21
+ type: 'CC' | 'TI' | 'NIT' | 'DIE' | 'PP' | 'CE' | 'TE' | 'RC' | 'FOREIGN_NIT' | 'NUIP';
22
+ number: string;
23
+ dv?: string;
24
+ };
25
+ fiscalResidence?: 'RESIDENT' | 'NON_RESIDENT';
26
+ enableHealthSector?: boolean;
27
+ healthPatients?: any;
28
+ address?: {
29
+ address: string;
30
+ city: string;
31
+ department?: string;
32
+ country?: 'Colombia';
33
+ zipCode?: string;
34
+ };
35
+ type?: string[];
36
+ seller?: any;
37
+ term?: {
38
+ id: number;
39
+ name: string;
40
+ days: string;
41
+ };
42
+ priceList?: {
43
+ id: number;
44
+ name: string;
45
+ };
46
+ internalContacts?: string[];
47
+ settings?: { sendElectronicDocuments: boolean; };
48
+ statementAttached?: boolean;
49
+ accounting?: {
50
+ accountReceivable: {
51
+ id: string;
52
+ idParent: string;
53
+ name: string;
54
+ text: string;
55
+ code: string;
56
+ description: string;
57
+ type: string;
58
+ readOnly: boolean;
59
+ nature: string;
60
+ blocked: string;
61
+ status: string;
62
+ categoryRule: any;
63
+ use: string;
64
+ showThirdPartyBalance: boolean
65
+ };
66
+ debtToPay: {
67
+ id: string;
68
+ idParent: string;
69
+ name: string;
70
+ text: string;
71
+ code: string;
72
+ description: string;
73
+ type: string;
74
+ readOnly: boolean;
75
+ nature: string;
76
+ blocked: string;
77
+ status: string;
78
+ categoryRule?: any;
79
+ use: string;
80
+ showThirdPartyBalance: boolean
81
+ }
82
+ }
83
+ }
84
+
85
+ export interface IAlegraPayment {
86
+ id?: string | number;
87
+ date: string;
88
+ bankAccount: {
89
+ id: string | number;
90
+ };
91
+ client: IAlegraContact,
92
+ paymentMethod: 'transfer' | 'cash' | 'deposit' | 'check' | 'credit-card' | 'debit-card';
93
+ observations: string;
94
+ anotation: string;
95
+ type: 'in' | 'out';
96
+ categories: IAlegraCategory[];
97
+ costCenter?: any;
98
+ numberTemplate?: {
99
+ id: string;
100
+ prefix: any,
101
+ number: string;
102
+ fullNumber: string;
103
+ formattedNumber:string;
104
+ }
105
+ }
106
+
107
+ export interface IAlegraCategory {
108
+ id: string | number;
109
+ name?: string;
110
+ price: number;
111
+ quantity: number;
112
+ observations: string;
113
+ total?: number;
114
+ behavior?: string;
115
+ tax?: any[]
116
+ }
117
+
118
+ export interface IAlegraJournal {
119
+ id?: string | number;
120
+ date: string;
121
+ observations: string;
122
+ entries: IAlegraEntry[];
123
+ client?: IAlegraContact;
124
+ reference?: string;
125
+ status?: string;
126
+ total?: number;
127
+ }
128
+
129
+ export interface IAlegraEntry {
130
+ id: string | number;
131
+ client: IAlegraContact;
132
+ description: string;
133
+ debit: number;
134
+ credit: number;
135
+ name?: string;
136
+ type?: string;
137
+ line?: string;
138
+ lineParent?: any;
139
+ costCenter?: any;
140
+ associatedDocument?: {
141
+ idResource: any;
142
+ resourceType: any;
143
+ resource: any;
144
+ }
145
+ }
146
+
147
+ export interface IAlegraResult {
148
+ code: number;
149
+ message: string;
150
+ }
@@ -0,0 +1,34 @@
1
+ import { GroupedParameters, RequestContext, RequestParameterType } from "../APIRequest";
2
+ import { APIRequestBuilder } from "../APIRequestBuilder";
3
+
4
+ export abstract class StandardGetRequestBuilder extends APIRequestBuilder {
5
+ protected buildDefaultParams(): GroupedParameters[] {
6
+ return [
7
+ {
8
+ context: RequestContext.QUERY,
9
+ properties: [{ name: "id", type: RequestParameterType.STRING }],
10
+ },
11
+ {
12
+ context: RequestContext.QUERY,
13
+ properties: [{ name: "limit", type: RequestParameterType.STRING }],
14
+ },
15
+ {
16
+ context: RequestContext.QUERY,
17
+ properties: [{ name: "count", type: RequestParameterType.STRING }],
18
+ },
19
+ {
20
+ context: RequestContext.QUERY,
21
+ properties: [
22
+ { name: "limit", type: RequestParameterType.STRING },
23
+ { name: "offset", type: RequestParameterType.STRING },
24
+ ],
25
+ },
26
+ ];
27
+ }
28
+
29
+ public abstract buildSpecificParams(): GroupedParameters[];
30
+
31
+ public buildParams(): GroupedParameters[] {
32
+ return this.buildDefaultParams().concat(this.buildSpecificParams());
33
+ }
34
+ }
@@ -0,0 +1,28 @@
1
+ import { Response } from 'express';
2
+
3
+ export class ServerSentEventsManager {
4
+ private res: Response;
5
+
6
+ constructor(res: Response, config?: any) {
7
+ config = config ?? {
8
+ 'Cache-control': 'no-cahe',
9
+ 'Content-Type': 'text/event-stream',
10
+ 'Connection': 'keep-alive'
11
+ };
12
+ res.set(config);
13
+ res.flushHeaders();
14
+ this.res = res;
15
+ }
16
+
17
+ public write(status: number, payload: string) {
18
+ this.res.status(status).write(payload);
19
+ }
20
+
21
+ public writeObject(status: number, payload: any) {
22
+ this.res.status(status).write(JSON.stringify(payload));
23
+ }
24
+
25
+ public end(status: number, payload: string) {
26
+ this.res.status(200).end(payload);
27
+ }
28
+ }