@authenty/authapi-types 1.0.9 → 1.0.11

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/src/index.ts CHANGED
@@ -1,7 +1,921 @@
1
- export * from './admin';
2
- export * from './cronjobs';
3
- export * from './general';
4
- export * from './payment-system';
1
+ import packageJson from '../package.json';
2
+ import { safeStringify } from "./tools";
5
3
 
4
+ /**
5
+ * Namespace principal da API de autenticação
6
+ * Acesso aos tipos: AuthApi.objects.User, AuthApi.responses.auth.login.post, etc.
7
+ */
8
+ export namespace AuthApi {
6
9
 
10
+ /**
11
+ * Objetos de domínio da aplicação
12
+ */
13
+ export namespace objects {
14
+ export enum BundleType {
15
+ BUNDLE = 0,
16
+ SYMBOLIC_PRODUCT = 1,
17
+ SYMBOLIC_COURSE = 2,
18
+ SYMBOLIC_CONSULTANCY = 3,
19
+ }
7
20
 
21
+ export type Product = {
22
+ id: number;
23
+ title: string;
24
+ short: string;
25
+ resume: string;
26
+ video: string;
27
+ imgUrls: string | null;
28
+ logo: string;
29
+ themeImage: string;
30
+ themeColor: string;
31
+ themeVideo: string;
32
+ url: string;
33
+ type: number;
34
+ period_test: number;
35
+ created: string;
36
+ deletedAt?: string | null;
37
+ Levels?: ProductLevel[];
38
+ }
39
+
40
+ export type ProductLevel = {
41
+ id: number;
42
+ productID: number;
43
+ level: number;
44
+ short: string;
45
+ Product?: Product;
46
+ store_bundles_levels?: {
47
+ id: number,
48
+ bundleID: number,
49
+ levelID: number,
50
+ quantity: number,
51
+ Bundle?: Bundle
52
+ }[];
53
+ }
54
+
55
+ export type Course = {
56
+ id: number;
57
+ type: number;
58
+ name: string;
59
+ short: string;
60
+ resume: string;
61
+ img_landscape: string;
62
+ img_square: string;
63
+ workload: number;
64
+ langID: number;
65
+ num_classes?: number;
66
+ seats: number;
67
+ url?: string;
68
+ dates: string;
69
+ local: string;
70
+ local_url: string;
71
+ date_mat_s?: string;
72
+ date_mat_e?: string;
73
+ date_ends?: string;
74
+ email_enrollment?: string;
75
+ email_before?: string;
76
+ email_after?: string;
77
+ date_c: string;
78
+ date_r?: string | null;
79
+ }
80
+
81
+ export type Consultancy = {
82
+ id: number;
83
+ teacherID: number;
84
+ type: number;
85
+ name: string;
86
+ short: string;
87
+ resume: string;
88
+ img_landscape: string;
89
+ img_square: string;
90
+ workload: number;
91
+ langID: number;
92
+ url?: string;
93
+ datetime: string;
94
+ date_mat_s?: string;
95
+ date_mat_e?: string;
96
+ date_ends?: string;
97
+ email_enrollment: string;
98
+ email_before: string;
99
+ email_after: string;
100
+ date_c: string;
101
+ date_r?: string | null;
102
+ }
103
+
104
+ export type Bundle = {
105
+ id: number;
106
+ type: BundleType;
107
+ title?: string;
108
+ short?: string;
109
+ resume?: string;
110
+ img: string;
111
+ themeImage: string;
112
+ themeColor: string;
113
+ shareLimit: number;
114
+ created: string;
115
+ active: boolean;
116
+ showInSite: boolean;
117
+ defaultMetaArray: string;
118
+ deletedAt?: string | null;
119
+ Levels?: {
120
+ id: number;
121
+ bundleID: number;
122
+ levelID: number;
123
+ quantity: number;
124
+ Level: ProductLevel;
125
+ }[];
126
+ Courses?: {
127
+ id: number;
128
+ bundleID: number;
129
+ courseID: number;
130
+ quantity: number;
131
+ Course: Course;
132
+ }[];
133
+ Consultancies?: {
134
+ id: number;
135
+ bundleID: number;
136
+ consultancyID: number;
137
+ quantity: number;
138
+ Consultancy: Consultancy;
139
+ }[];
140
+ store_bundles_paymethod: PaymentMethod[];
141
+ }
142
+
143
+ export type PaymentMethod = {
144
+ id: number;
145
+ bundleID: number;
146
+ price: number;
147
+ fromprice: number;
148
+ period_renew: number;
149
+ period_grace: number;
150
+ gatewayHash: string;
151
+ allowBoleto: boolean;
152
+ gatewayID: number;
153
+ Bundle?: Bundle;
154
+ }
155
+
156
+ export type Purchase = {
157
+ paghash: string;
158
+ id: number;
159
+ price: number;
160
+ licenseStatus: PaymentSystem.PG_PurchaseLicenseStatus;
161
+ paymentStatus: PaymentSystem.PG_PurchasePaymentStatus,
162
+ type_step: PaymentSystem.PG_PurchaseType,
163
+ PaymentMethod: PaymentMethod;
164
+ Wallet?: Wallet;
165
+ walletID: number;
166
+ createdAt: string;
167
+ paymentDueAt: string | null;
168
+ owner: string;
169
+ invoiceUrl?: string;
170
+ nfUrl?: string;
171
+ isAdmin?: boolean;
172
+ meta_data?: Record<string, any>;
173
+ PurchaseShares?: PurchaseShare[];
174
+ Levels?: {
175
+ Level: ProductLevel
176
+ quant: number
177
+ }[]
178
+ }
179
+
180
+ export type Wallet = {
181
+ id: number;
182
+ userID: number;
183
+ balance?: number;
184
+ Purchases?: Purchase[];
185
+ }
186
+
187
+ export type PurchaseShare = {
188
+ id: number;
189
+ purchaseID: number;
190
+ userID: number;
191
+ Purchase: Purchase;
192
+ }
193
+
194
+ export type LocalUser = {
195
+ id: number,
196
+ fullname: string,
197
+ email: string,
198
+ lang: number,
199
+ avatar: string,
200
+ end_city?: number,
201
+ end_comp?: string,
202
+ end_country: number,
203
+ end_district?: string,
204
+ end_n?: string,
205
+ end_state?: number,
206
+ end_street?: string,
207
+ end_zip?: string,
208
+
209
+ email_verif: boolean,
210
+ fiscal_verif: boolean,
211
+ terms: boolean,
212
+
213
+ cpf?: string,
214
+ newslatter?: boolean,
215
+ allow_purchase?: boolean,
216
+ allow_license?: boolean,
217
+ date_c?: Date | string,
218
+ date_r?: Date | string | null,
219
+
220
+ Wallets?: Wallet[];
221
+ PurchasesShares?: PurchaseShare[];
222
+
223
+ Sys_admUser_config?: AdminUserConfig,
224
+ Sys_adminUser?: auxiliarTypes.PrivilegeTable
225
+ }
226
+ export type AdminUserConfig = {
227
+ campaigns_blacklist: string,
228
+ deletedAt: Date | null,
229
+ userID: number
230
+ }
231
+
232
+ // Tipos para logs do sistema
233
+ export type LogEntry = {
234
+ appId: string;
235
+ logCode: number;
236
+ content: string;
237
+ timestamp?: string;
238
+ metadata?: {
239
+ requestId: string;
240
+ endpoint: string;
241
+ method: string;
242
+ userId?: number;
243
+ ip?: string;
244
+ browser?: string;
245
+ system?: string;
246
+ referer?: string;
247
+ };
248
+ }
249
+
250
+ export namespace PaymentSystem {
251
+
252
+ export type PG_Customer = {
253
+ id: string,
254
+ email: string,
255
+ name: string
256
+ }
257
+
258
+ export enum PG_PurchaseLicenseStatus {
259
+
260
+ // Pagamentos ou Assinaturas
261
+ UNKNOWN = 0,//Nunca será atualizado automaticamente!!
262
+ OPEN = 3, //ABERTA - Aguardando pagamento
263
+
264
+ // Pagamentos
265
+ EXPIRED = 1, //VENCEU - Era PAGAMENTO, e acabou prazo pra uso acabou
266
+ PAID = 5, //PAGA - Pagamento realizado com sucesso - é pagamento único
267
+
268
+ // Assinaturas
269
+ ACTIVE = 6, //ATIVO - Assinatura ativa e em dia
270
+ RECYCLING = 4, //RETENTANDO - Tentativa de renovação automática falhou, mas ainda está no prazo para pagar manualmente
271
+ CANCELED = 2, //CANCELADA - Foi cancelada pelo usuário ou admin
272
+ }
273
+
274
+ export const PG_PurchaseLicenseStatus_GroupActive = [//quais são os Status que são considerados ATIVOS (aptos a usar a licença)
275
+ PG_PurchaseLicenseStatus.PAID,
276
+ PG_PurchaseLicenseStatus.ACTIVE,
277
+ PG_PurchaseLicenseStatus.RECYCLING,
278
+ ]
279
+
280
+ export enum PG_PurchasePaymentStatus {
281
+ UNKNOWN = 0,//pendent or unknown
282
+ ACTIVE = 1,
283
+ CANCELED = 2,
284
+ REFUNDED = 3,
285
+ REMOVED = 4,// REMOVIDO DO GATEWAY - Não há mais registro do pagamento no gateway
286
+ PENDING = 5, //não paga ainda
287
+ }
288
+
289
+ export enum PG_PurchaseType {
290
+ SESSION = 0, //o registro se trata de uma sessão de compra (ex: intenção de compra preparada para redirecionar o usuário ao gateway. Ainda não é um pagamento nem uma assinatura ativa)
291
+ STANDARD = 1, //Pagamento único
292
+ RECURRENT = 2, //Assinatura recorrente
293
+ }
294
+
295
+ export type PG_Purchase = {
296
+ id: string,
297
+ amount: number,
298
+ recurrent: boolean,
299
+ type: PG_PurchaseType,
300
+ // licenseStatus: PG_PurchaseLicenseStatus,
301
+ paymentStatus: PG_PurchasePaymentStatus,
302
+ url: string | null,
303
+ dueTime: Date | null
304
+ }
305
+
306
+ export enum PG_RecurrenceType {
307
+ NONE = 0,
308
+ DAILY = 1,
309
+ WEEKLY = 2,
310
+ MONTHLY = 3,
311
+ YEARLY = 4
312
+ }
313
+ }
314
+ }
315
+
316
+ export namespace auxiliarTypes {
317
+
318
+ export type availableSoftware = {
319
+ Level: objects.ProductLevel,
320
+ quantity: number,//acessos simultâneos permitidos por esta COMPRA
321
+ purchaseId: number | null, //null when free
322
+ type: 'free' | 'own' | 'shared'
323
+ }
324
+
325
+ export enum Privilege {
326
+ NONE = 0,
327
+ READ = 1,
328
+ WRITE = 2
329
+ }
330
+
331
+ export type PrivilegeTable = {// ESTES PRIVILÉGIOS JÁ SÃO CONVERTIDOS NO `server.ts` para que quando é externo tenha que ter maior nível de acesso...
332
+ users: Privilege;
333
+ products: Privilege;
334
+ courses: Privilege;
335
+ consultancies: Privilege;
336
+ bundles: Privilege;
337
+ logs: Privilege;
338
+ support: Privilege;
339
+ leads: Privilege;
340
+ paymentSystem: Privilege;
341
+ adminMaster: Privilege;
342
+ activityTrakking: Privilege;
343
+ financial: Privilege;
344
+ }
345
+
346
+ export type CronJob = { //Também definido em ~/server/src/cronjobs.ts
347
+ startAt: Date | null //null se não está rodando
348
+ latestRunErrorCount: number //zero se não teve erro
349
+ latestCompletedAt: Date | null
350
+ }
351
+
352
+ export type CronjobsStatuses = {
353
+ purchasesStatusUpdate: CronJob
354
+ }
355
+
356
+ export type LogFilters = {
357
+ page: number;
358
+ itemsPerPage: number;
359
+ search: string;
360
+ logCode?: number;
361
+ appId?: string;
362
+ userId?: number;
363
+ method?: string;
364
+ startDate?: string;
365
+ endDate?: string;
366
+ }
367
+
368
+ export type PaginationInfo = {
369
+ total: number;
370
+ page: number;
371
+ itemsPerPage: number;
372
+ totalPages: number;
373
+ }
374
+ }
375
+
376
+ /**
377
+ * Tipos de resposta padrão da API
378
+ */
379
+ export namespace responses {
380
+
381
+ export type ApiResponse<T = any> = {
382
+ conex: boolean;
383
+ reqStat: number;
384
+ success: boolean;
385
+ data: T;
386
+ msg: string;
387
+ }
388
+
389
+ export namespace auth {
390
+ export namespace login {
391
+ export type POST = ApiResponse<{ user: objects.LocalUser; msg?: string }>;
392
+ }
393
+ export namespace logout {
394
+ export type GET = ApiResponse<{}>;
395
+ }
396
+ export namespace checkSession {
397
+ export type GET = ApiResponse<{ user?: objects.LocalUser; msg?: string }>;
398
+ }
399
+ }
400
+
401
+ export namespace users {
402
+ export type GET = ApiResponse<objects.LocalUser[]>;
403
+ }
404
+
405
+ export namespace user {
406
+ export type GET = ApiResponse<objects.LocalUser & { Wallets?: objects.Wallet[]; PurchasesShares?: objects.PurchaseShare[] }>;
407
+ export type PUT = ApiResponse<objects.LocalUser>;
408
+
409
+ export namespace updateConfig {
410
+ export type PUT = ApiResponse<{ msg?: string }>;
411
+ }
412
+ export namespace updateAdmin {
413
+ export type PUT = ApiResponse<objects.LocalUser>;
414
+ }
415
+ export namespace license {
416
+ export type PUT = ApiResponse<{ availableLicenses: number; heldLicenses: number; usedLicenses: number; msg?: string }>;
417
+ }
418
+ }
419
+
420
+ export namespace purchase {
421
+ export namespace create {
422
+ export type POST = ApiResponse<{ msg?: string; purchase: objects.Purchase; url?: string }>;
423
+ }
424
+ export namespace id {
425
+ export namespace sync {
426
+ export type POST = ApiResponse<objects.Purchase & { msg?: string }>;
427
+ }
428
+ }
429
+ export type PUT = ApiResponse<objects.Purchase | { msg?: string }>;
430
+ export namespace cancel {
431
+ export type PUT = ApiResponse<objects.Purchase>;
432
+ }
433
+ export type DELETE = ApiResponse<{ msg?: string }>;
434
+ export namespace getFromGateway {
435
+ export type GET = ApiResponse<objects.PaymentSystem.PG_Purchase>;
436
+ }
437
+ }
438
+
439
+ export namespace purchases {
440
+ export type post_list = ApiResponse<{
441
+ purchases: objects.Purchase[];
442
+ pagination: {
443
+ page: number;
444
+ pageSize: number;
445
+ count: number;
446
+ };
447
+ }>;
448
+ }
449
+
450
+ export namespace product {
451
+ export type GET = ApiResponse<objects.Product>;
452
+ export type PUT = ApiResponse<objects.Product>;
453
+ }
454
+ export namespace products {
455
+
456
+ export type GET = ApiResponse<objects.Product[]>;
457
+ }
458
+
459
+ export namespace paymentMethod {
460
+ export type POST = ApiResponse<objects.PaymentMethod>;
461
+ export type PUT = ApiResponse<objects.PaymentMethod>;
462
+ export type DELETE = ApiResponse<{ msg?: string }>;
463
+ }
464
+
465
+ export namespace logs {
466
+
467
+ export type POST_SEARCH = ApiResponse<{ data: {
468
+ logs: objects.LogEntry[];
469
+ pagination: auxiliarTypes.PaginationInfo;
470
+ available: boolean;
471
+ } }>;
472
+ export namespace status {
473
+ export type GET = ApiResponse<{
474
+ saveToFile: boolean;
475
+ logPretty: boolean;
476
+ fileExists: boolean;
477
+ filePath: string;
478
+ logLevel: string;
479
+ canListLogs: boolean;
480
+ }>;
481
+ }
482
+ }
483
+
484
+ export namespace cronJobs {
485
+ export namespace status {
486
+ export type GET = ApiResponse<auxiliarTypes.CronjobsStatuses>;
487
+ }
488
+ export namespace run {
489
+ export type POST = ApiResponse<{ msg: string }>;
490
+ }
491
+ }
492
+
493
+ export namespace aux {
494
+ export namespace countries {
495
+ export type GET = ApiResponse<Array<{ id: number; nome: string; nome_pt: string }>>;
496
+ }
497
+ export namespace states {
498
+ export type GET = ApiResponse<Array<{ id: number; nome: string; uf: string; ibge: number; pais?: number; ddd?: string }>>;
499
+ }
500
+ export namespace cities {
501
+ export type GET = ApiResponse<Array<{ id: number; nome: string; uf: number; ibge: number }>>;
502
+ }
503
+ }
504
+
505
+ export namespace report {
506
+ export type POST = ApiResponse<{ msg?: string }>;
507
+ }
508
+ }
509
+
510
+ /**
511
+ * Configuração do Client
512
+ */
513
+ export type ClientConfig = {
514
+ baseURL: string;
515
+ tokenStorage?: {
516
+ getToken: () => string | null;
517
+ setToken: (token: string) => void;
518
+ getPin1: () => string | null;
519
+ setPin1: (pin1: string) => void;
520
+ };
521
+ onTokenUpdate?: (token: string) => void;
522
+ onPin1Update?: (pin1: string) => void;
523
+ retryAttempts?: number;
524
+ retryDelay?: number;
525
+ }
526
+
527
+ /**
528
+ * Client para comunicação com a API de autenticação
529
+ */
530
+ export class Client {
531
+ private baseURL: string;
532
+ private bearer: string = '';
533
+ private pin1: string = '';
534
+ private tokenStorage?: ClientConfig['tokenStorage'];
535
+ private onTokenUpdate?: (token: string) => void;
536
+ private onPin1Update?: (pin1: string) => void;
537
+ private retryAttempts: number = 0;
538
+ private retryDelay: number = 500;
539
+ private isHealth: boolean = true;
540
+
541
+ constructor(config: ClientConfig) {
542
+ this.baseURL = config.baseURL;
543
+ this.tokenStorage = config.tokenStorage;
544
+ this.onTokenUpdate = config.onTokenUpdate;
545
+ this.onPin1Update = config.onPin1Update;
546
+ this.retryAttempts = config.retryAttempts ?? 0;
547
+ this.retryDelay = config.retryDelay ?? 500;
548
+
549
+ // Carrega tokens do storage se disponível
550
+ if (this.tokenStorage) {
551
+ this.bearer = this.tokenStorage.getToken() ?? '';
552
+ this.pin1 = this.tokenStorage.getPin1() ?? '';
553
+ }
554
+ }
555
+
556
+ /**
557
+ * Define o token de autenticação
558
+ */
559
+ public setToken(token: string): void {
560
+ this.bearer = token;
561
+ if (this.tokenStorage) {
562
+ this.tokenStorage.setToken(token);
563
+ }
564
+ if (this.onTokenUpdate) {
565
+ this.onTokenUpdate(token);
566
+ }
567
+ }
568
+
569
+ /**
570
+ * Define o PIN1
571
+ */
572
+ public setPin1(pin1: string): void {
573
+ this.pin1 = pin1;
574
+ if (this.tokenStorage) {
575
+ this.tokenStorage.setPin1(pin1);
576
+ }
577
+ if (this.onPin1Update) {
578
+ this.onPin1Update(pin1);
579
+ }
580
+ }
581
+
582
+ /**
583
+ * Obtém o token atual
584
+ */
585
+ public getToken(): string {
586
+ return this.bearer;
587
+ }
588
+
589
+ /**
590
+ * Obtém o PIN1 atual
591
+ */
592
+ public getPin1(): string {
593
+ return this.pin1;
594
+ }
595
+
596
+ /**
597
+ * Verifica se o servidor está saudável
598
+ */
599
+ public async isHealthy(): Promise<boolean> {
600
+ if (!this.isHealth) {
601
+ try {
602
+ const r = await this.request('GET', '', {});
603
+ if (r.success) {
604
+ this.isHealth = true;
605
+ return true;
606
+ }
607
+ } catch { }
608
+ return false;
609
+ }
610
+ return true;
611
+ }
612
+
613
+ /**
614
+ * Requisição base para a API
615
+ */
616
+ private async request<T = any>(
617
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE',
618
+ endpoint: string,
619
+ params: any = {},
620
+ options?: {
621
+ retryAttempts?: number;
622
+ retryDelay?: number;
623
+ }
624
+ ): Promise<responses.ApiResponse<T>> {
625
+ const result: responses.ApiResponse<T> = {
626
+ conex: true,
627
+ reqStat: 0,
628
+ success: false,
629
+ data: {} as T,
630
+ msg: ''
631
+ };
632
+
633
+ const headers: Record<string, string> = {};
634
+ if (this.bearer) headers['authorization'] = `Bearer ${this.bearer}`;
635
+ if (this.pin1) headers['pin1'] = this.pin1;
636
+
637
+ const maxAttempts = 1 + (options?.retryAttempts ?? this.retryAttempts);
638
+ const retryDelay = options?.retryDelay ?? this.retryDelay;
639
+
640
+ let attempts = 0;
641
+ let response: Response | null = null;
642
+
643
+ while (attempts < maxAttempts) {
644
+ attempts++;
645
+ try {
646
+ const url = `${this.baseURL}/${endpoint}${method === 'GET' || method === 'DELETE' ? this.buildQueryString(params) : ''}`;
647
+ const fetchOptions: RequestInit = {
648
+ method,
649
+ headers: {
650
+ 'Content-Type': 'application/json',
651
+ ...headers
652
+ },
653
+ credentials: 'include'
654
+ };
655
+
656
+ if (method === 'POST' || method === 'PUT') {
657
+ fetchOptions.body = JSON.stringify(params);
658
+ }
659
+
660
+ response = await fetch(url, fetchOptions);
661
+
662
+ // Atualiza tokens se presentes nos headers
663
+ const newToken = response.headers.get('authorization');
664
+ if (newToken) {
665
+ this.setToken(newToken.replace('Bearer ', ''));
666
+ }
667
+
668
+ const newPin1 = response.headers.get('pin1');
669
+ if (newPin1) {
670
+ this.setPin1(newPin1);
671
+ }
672
+
673
+ // Se receber 503, marca como unhealthy e tenta novamente
674
+ if (response.status === 503) {
675
+ this.isHealth = false;
676
+ if (attempts >= maxAttempts) break;
677
+ await new Promise(res => setTimeout(res, retryDelay));
678
+ continue;
679
+ }
680
+
681
+ this.isHealth = true;
682
+ result.reqStat = response.status;
683
+ result.success = response.status >= 200 && response.status < 300;
684
+
685
+ try {
686
+ const jsonData = await response.json();
687
+ result.data = jsonData;
688
+ result.msg = jsonData.msg ?? '';
689
+ } catch {
690
+ result.msg = `stat_${response.status}`;
691
+ }
692
+
693
+ break;
694
+ } catch (e: any) {
695
+ this.isHealth = false;
696
+ if (attempts >= maxAttempts) {
697
+ result.conex = false;
698
+ result.msg = `connectionError_${e.code ?? 'unknown'}`;
699
+ } else {
700
+ await new Promise(res => setTimeout(res, retryDelay));
701
+ }
702
+ }
703
+ }
704
+
705
+ if (!result.conex) {
706
+ result.msg = result.msg || 'generic connection error';
707
+ }
708
+
709
+ return result;
710
+ }
711
+
712
+ /**
713
+ * Constrói query string a partir de um objeto
714
+ */
715
+ private buildQueryString(params: any): string {
716
+ if (!params || Object.keys(params).length === 0) return '';
717
+
718
+ const queryParams = new URLSearchParams();
719
+ Object.keys(params).forEach(key => {
720
+ const value = params[key];
721
+ if (value !== undefined && value !== null) {
722
+ if (Array.isArray(value)) {
723
+ queryParams.append(key, JSON.stringify(value));
724
+ } else if (typeof value === 'object') {
725
+ queryParams.append(key, JSON.stringify(value));
726
+ } else {
727
+ queryParams.append(key, String(value));
728
+ }
729
+ }
730
+ });
731
+
732
+ return `?${queryParams.toString()}`;
733
+ }
734
+
735
+ // ==================== MÉTODOS DE AUTENTICAÇÃO ====================
736
+
737
+ public auth = {
738
+
739
+ /**
740
+ * Faz login na API
741
+ */
742
+ login: async (email: string, password: string): Promise<responses.auth.login.POST> => {
743
+ return this.request<responses.auth.login.POST['data']>('POST', 'auth/login', { email, password });
744
+ },
745
+
746
+ /**
747
+ * Faz logout da API
748
+ */
749
+ logout: async (): Promise<responses.auth.logout.GET> => {
750
+ const result = await this.request<responses.auth.logout.GET['data']>('GET', 'auth/logout', {});
751
+ this.setToken('');
752
+ this.setPin1('');
753
+ return result;
754
+ },
755
+
756
+ /**
757
+ * Verifica a sessão atual
758
+ */
759
+ checkSession: async (): Promise<responses.auth.checkSession.GET> => {
760
+ if (!this.bearer) {
761
+ return {
762
+ conex: true,
763
+ reqStat: 401,
764
+ success: false,
765
+ data: {},
766
+ msg: 'Token not found'
767
+ };
768
+ }
769
+ return this.request<responses.auth.checkSession.GET['data']>('GET', 'auth', {}, { retryAttempts: 2, retryDelay: 1000 });
770
+ }
771
+ }
772
+
773
+ public async checkHealth() {
774
+ if( !this.isHealth ){
775
+ try {
776
+ const r = await this.request('GET', '',{});
777
+ if( r.success ){
778
+ this.isHealth = true;
779
+ return true;
780
+ }
781
+ } catch { }
782
+ return false;
783
+ }
784
+
785
+ return true;
786
+ }
787
+
788
+ public user = {
789
+ list: async () => {
790
+ return await this.request<responses.users.GET>('GET', 'users', {});
791
+ },
792
+ get: async (userId: number, includePurchases: boolean = true) => {
793
+ return await this.request<responses.user.GET>('GET', `user/${userId}?includePurchases=${includePurchases}`, {});
794
+ },
795
+ update: async (userId: number, userData: Partial<objects.LocalUser>) => {
796
+ return await this.request<responses.user.PUT>('PUT', `user/${userId}`, userData);
797
+ },
798
+ updateConfig: async ( obj:{id: number, config_ihm_showRates?: boolean} ) => {
799
+ return await this.request<responses.user.updateConfig.PUT>('PUT', `user/${obj.id}/config`, obj);
800
+ },
801
+ updateAdmin: async (userId: number, isAdmin: boolean) => {
802
+ return await this.request<responses.user.updateAdmin.PUT>('PUT', `user/${userId}/admin`, { isAdmin });
803
+ },
804
+ license: async (userId:number) => {
805
+ return await this.request<responses.user.license.PUT>('GET', `user/${userId}/license`, {});
806
+ }
807
+ }
808
+
809
+ public purchase = {
810
+ new: async (paymentMethodId: number, userId: number) => {
811
+ return await this.request<responses.purchase.create.POST>('POST', `user/${userId}/purchase/new/${paymentMethodId}`, {});
812
+ },
813
+ sync: async (purchaseId: number, userId: number, async: boolean = false) => {
814
+ return await this.request<responses.purchase.id.sync.POST>('POST', `user/${userId}/purchase/${purchaseId}/sync`, { async });
815
+ },
816
+ update: async (userId: number, purchase: objects.Purchase) => {
817
+ return await this.request<responses.purchase.PUT>('PUT', `user/${userId}/purchase/${purchase.id}`, purchase );
818
+ },
819
+ cancel: async (purchaseId: number, userId: number) => {
820
+ return await this.request<responses.purchase.cancel.PUT>('PUT', `user/${userId}/purchase/${purchaseId}/cancel`, {} );
821
+ },
822
+ delete: async (purchaseId: number, userId: number) => {
823
+ return await this.request<responses.purchase.DELETE>('DELETE', `user/${userId}/purchase/${purchaseId}`, { });
824
+ },
825
+ list: async (page:number=1, pageSize?:number, userId?: number) => {
826
+ return await this.request<responses.purchases.post_list>('POST', `admin/purchases/search`, { page, pageSize, userId });
827
+ },
828
+ getFromGateway: async (purchaseId: number, userId: number, async: boolean = false) => {
829
+ return await this.request<responses.purchase.getFromGateway.GET>('GET', `user/${userId}/purchase/${purchaseId}/getFromGateway`, {});
830
+ },
831
+ }
832
+
833
+ public products = {
834
+
835
+ list: async () => {
836
+ return await this.request<responses.products.GET>('GET', 'products', {});
837
+ },
838
+ get: async (productId: number) => {
839
+ return await this.request<responses.product.GET>('GET', `product/${productId}`, { mode: 'admin' });
840
+ },
841
+ update: async (productId: number, productData: any) => {
842
+ return await this.request<responses.product.PUT>('PUT', `product/${productId}`, productData);
843
+ }
844
+ }
845
+
846
+ public paymentMethods = {
847
+
848
+ create: async (id: number, paymentMethodData: objects.PaymentMethod) => {
849
+ return await this.request<responses.paymentMethod.POST>('POST', `bundle/${id}/payment-method`, paymentMethodData);
850
+ },
851
+ update: async (id: number, paymentMethodId: number, paymentMethodData: objects.PaymentMethod) => {
852
+ return await this.request<responses.paymentMethod.PUT>('PUT', `bundle/${id}/payment-method/${paymentMethodId}`, paymentMethodData);
853
+ },
854
+ delete: async (id: number, paymentMethodId: number) => {
855
+ return await this.request<responses.paymentMethod.DELETE>('DELETE', `bundle/${id}/payment-method/${paymentMethodId}`, {});
856
+ }
857
+ }
858
+
859
+ public aux = {
860
+ countries: async () => {
861
+ return await this.request<responses.aux.countries.GET>('GET', 'aux/countries', {});
862
+ },
863
+
864
+ states: async (countryId: number) => {
865
+ return await this.request<responses.aux.states.GET>('GET', `aux/country/${countryId}/states`, {});
866
+ },
867
+
868
+ cities: async (countryId: number, stateId: number) => {
869
+ return await this.request<responses.aux.cities.GET>('GET', `aux/country/${countryId}/state/${stateId}/cities`, {});
870
+ }
871
+ }
872
+
873
+ public admin = {
874
+
875
+ logs: {
876
+ /**
877
+ * @param filters
878
+ * @returns
879
+ */
880
+ list: async (filters: Partial<auxiliarTypes.LogFilters> = {}) => {
881
+ const defaultFilters: auxiliarTypes.LogFilters = {
882
+ page: 1,
883
+ itemsPerPage: 50,
884
+ search: '',
885
+ ...filters
886
+ };
887
+ return await this.request<responses.logs.POST_SEARCH>('POST', 'logs', defaultFilters);
888
+ },
889
+
890
+ status: async () => {
891
+ return await this.request<responses.logs.status.GET>('GET', 'logs/status', {});
892
+ }
893
+ },
894
+
895
+ cronJobs: {
896
+ status: async () => {
897
+ return await this.request<responses.cronJobs.status.GET>('GET', 'admin/cronjobs/status', {});
898
+ },
899
+ run: async (name: string) => {
900
+ return await this.request<responses.cronJobs.run.POST>('POST', `admin/cronjobs/run/${name}`, {});
901
+ }
902
+ }
903
+ }
904
+
905
+ public report = {
906
+ new: async (id: string, data: any) => {
907
+
908
+ return await this.request<responses.report.POST>('POST', 'report', {
909
+ id,
910
+ data: safeStringify(data),
911
+ appVersion: packageJson.version
912
+ });
913
+ }
914
+ }
915
+
916
+ }
917
+
918
+ }
919
+
920
+ // Exporta o namespace como default também
921
+ export default AuthApi;