@authenty/authapi-types 1.0.10 → 1.0.12

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