Repository navigation
Expand file tree
/
Copy pathCode.ts
More file actions
2443 lines (2158 loc) · 74 KB
/
Copy pathCode.ts
File metadata and controls
2443 lines (2158 loc) · 74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// =================================================================
// ARQUIVO DE LÓGICA CENTRAL (TYPESCRIPT)
// =================================================================
// --- TIPOS E INTERFACES GLOBAIS ---
// Adicionando referências de tipo para os serviços do Google Apps Script
/// <reference types="google-apps-script" />
// Use the correct GAS event type name (DoGet) or fallback to any if needed
type GASEvent = GoogleAppsScript.Events.DoGet;
type HTMLOutput = GoogleAppsScript.HTML.HtmlOutput;
type Sheet = GoogleAppsScript.Spreadsheet.Sheet;
type Spreadsheet = GoogleAppsScript.Spreadsheet.Spreadsheet;
// --- INTERFACES CUSTOMIZADAS PARA A APLICAÇÃO ---
interface SheetCache {
[key: string]: Spreadsheet;
}
interface ValidationResult {
isValid: boolean;
message: string;
}
interface LongTermRuleResult {
isApplicable: boolean;
isValid: boolean;
message: string;
}
interface HeadersAndData {
data: any[][];
headers: string[];
headerRowIndex: number;
error?: string;
}
interface User {
email: string;
role: string;
permissions: StringMap;
}
interface RequestData {
material: string;
descricao: string;
fornecedor: string;
bandeira: string;
loja: string;
precoDe: number;
precoPor: number;
descPercent: string;
dataInicio: string;
dataFim: string;
recompMargem: string;
valorRebate: string;
obsComercial: string;
nRebaixa: string;
nAcao: string;
mecanica?: string;
}
interface UpdateRequestData {
itemId: string;
newStatus: string;
reason?: string;
}
interface UpdateDetailsPayload {
itemId: string;
details: {
recompMargem: string;
valorRebate: string;
nRebaixa: string;
};
}
interface ProductInfo {
sku: string;
descricao: string;
categoriaN3: string;
categoriaN4: string;
fornecedor: string;
status: string;
imageUrl?: string;
}
interface BusinessRules {
startDays?: number[];
endDays?: number[];
exceptionKeyword?: string;
maxDiscount?: number;
}
interface AuditAction {
action: string;
targetId: string;
sku: string | null;
details: object;
dataInicio?: Date | string | null;
dataFim?: Date | string | null;
}
interface DetailedValidationResult {
isValid: boolean;
errors: string[];
autoFilledData?: {
descricao?: string;
fornecedor?: string;
};
}
interface FileUploadData {
name: string;
mimeType: string;
content: string;
}
interface StoreGroupData {
name: string;
type: "paste" | "upload";
data: string | FileUploadData;
}
interface SkuFamily {
group: string;
skus: string[];
}
interface SkuFamilyPayload {
group: string;
material: string;
}
// =================================================================
// CONTEÚDO DE HELPERS.JS (MIGRADO PARA TYPESCRIPT)
// =================================================================
/**
* Procura a informação de um produto (SKU) na base de dados de produtos.
* Implementa um cache para evitar múltiplas leituras da planilha para o mesmo SKU.
* @param sku O SKU a ser procurado.
* @returns Um objeto com a informação do produto ou null se não for encontrado.
* @private
*/
function getProductInfo_(sku: string): ProductInfo | null {
if (!sku || typeof sku !== "string") return null;
const trimmedSku = sku.trim();
const cache = CacheService.getScriptCache();
const cacheKey = `product_info_${trimmedSku.toLowerCase()}`;
const cachedInfo = cache.get(cacheKey);
if (cachedInfo) {
return JSON.parse(cachedInfo) as ProductInfo;
}
const sheet = getSheet_(PRODUCT_INFO_SHEET_NAME);
if (!sheet) {
throw new Error(
`Planilha de informações de produto '${PRODUCT_INFO_SHEET_NAME}' não foi encontrada.`
);
}
const data = sheet.getDataRange().getValues();
const headers = data.shift()?.map((h) => String(h).trim()) || [];
const columnIndices = {
sku: headers.indexOf("COD_PRODUTO"),
descricao: headers.indexOf("DESC_PRODUTO"),
categoriaN3: headers.indexOf("DESC_CATN3"),
categoriaN4: headers.indexOf("DESC_CATN4"),
fornecedor: headers.indexOf("NOME_FORNECEDOR_REGULAR"),
status: headers.indexOf("DESC_STATUS"),
imageUrl: headers.indexOf("IMAGEM_URL"),
};
if (columnIndices.sku === -1) {
throw new Error(
"Não foi possível encontrar a coluna de SKU na planilha de produtos."
);
}
for (const row of data) {
const sheetSku = String(row[columnIndices.sku]).trim();
if (sheetSku.toLowerCase() === trimmedSku.toLowerCase()) {
const productInfo: ProductInfo = {
sku: row[columnIndices.sku],
descricao: row[columnIndices.descricao],
categoriaN3: row[columnIndices.categoriaN3],
categoriaN4: row[columnIndices.categoriaN4],
fornecedor: row[columnIndices.fornecedor],
status: row[columnIndices.status],
imageUrl:
columnIndices.imageUrl > -1 ? row[columnIndices.imageUrl] : undefined,
};
cache.put(cacheKey, JSON.stringify(productInfo), 21600); // Cache por 6 horas
return productInfo;
}
}
return null; // SKU não encontrado
}
/**
* Valida os dados de uma nova solicitação de promoção com base nas regras de negócio.
* @param requestData Os dados da solicitação a serem validados.
* @returns Um objeto DetailedValidationResult.
* @private
*/
function validateRequestData_(
requestData: RequestData
): DetailedValidationResult {
const result: DetailedValidationResult = {
isValid: true,
errors: [],
autoFilledData: {},
};
// 1. Validação de SKU (pré-requisito)
const productInfo = getProductInfo_(requestData.material);
if (!productInfo) {
result.errors.push(
`SKU '${requestData.material}' não encontrado na base de dados de produtos.`
);
} else {
result.autoFilledData.descricao = productInfo.descricao;
result.autoFilledData.fornecedor = productInfo.fornecedor;
}
// 2. Validação de Regras de Negócio
const dataInicio = parseDate(requestData.dataInicio);
const dataFim = parseDate(requestData.dataFim);
const precoDe = Number(requestData.precoDe);
const precoPor = Number(requestData.precoPor);
// Validação de Datas
if (!dataInicio || !dataFim) {
result.errors.push("As datas de início e fim são obrigatórias.");
} else if (dataFim < dataInicio) {
result.errors.push("A data de fim não pode ser anterior à data de início.");
}
// Validação de Preços
if (isNaN(precoDe) || isNaN(precoPor) || precoDe <= 0 || precoPor <= 0) {
result.errors.push("Os preços 'De' e 'Por' devem ser números positivos.");
} else if (precoPor > precoDe) {
result.errors.push("O preço 'Por' não pode ser maior que o preço 'De'.");
}
// Conclusão da Validação
if (result.errors.length > 0) {
result.isValid = false;
}
return result;
}
/**
* Obtém a planilha correta com base no nome da aba.
* @param sheetName O nome da aba a ser acessada.
* @returns O objeto da Planilha Google correta.
* @private
*/
function getSpreadsheetForSheet_(sheetName: string): Spreadsheet {
let spreadsheetId: string;
switch (sheetName) {
case DB_SHEET_NAME:
case QUEUE_SHEET_NAME:
spreadsheetId = DB_PRINCIPAL_SPREADSHEET_ID;
break;
case AUDIT_LOG_SHEET_NAME:
case "log_sistema": // Adicionado para cobrir todos os casos
case "log_performance":
spreadsheetId = DB_LOGS_SPREADSHEET_ID;
break;
case USER_CONFIG_SHEET_NAME:
case RULES_CONFIG_SHEET_NAME:
spreadsheetId = DB_CONFIG_SPREADSHEET_ID;
break;
case PRODUCT_INFO_SHEET_NAME:
spreadsheetId = PRODUCT_INFO_SPREADSHEET_ID;
break;
case SKU_FAMILIES_ETNIAS_SHEET_NAME:
case SKU_FAMILIES_OBSOLETOS_SHEET_NAME:
spreadsheetId = SKU_FAMILIES_SPREADSHEET_ID;
break;
default:
console.warn(
`Aba "${sheetName}" não mapeada. Usando a planilha principal por defeito.`
);
spreadsheetId = DB_PRINCIPAL_SPREADSHEET_ID;
}
if (!spreadsheetId || spreadsheetId.startsWith("COLOQUE_O_ID")) {
throw new Error(
`ERRO CRÍTICO: ID da planilha para '${sheetName}' não definido em Config.ts.`
);
}
try {
// Não é possível armazenar o objeto Spreadsheet diretamente no CacheService.
// A abordagem de cache em memória por execução (`sCache`) é a correta aqui,
// pois o objeto Spreadsheet não é serializável.
// A otimização já foi feita na camada de dados com o cache granular.
// Vamos manter a lógica original de cache em memória que é válida por execução.
const sCache: SheetCache = this["spreadsheets"] || {};
if (!sCache[spreadsheetId]) {
const perf_startTime = new Date().getTime();
console.log(
`PERF: Abrindo planilha pela primeira vez nesta execução: '${sheetName}' (ID: ${spreadsheetId})`
);
sCache[spreadsheetId] = SpreadsheetApp.openById(spreadsheetId);
const perf_endTime = new Date().getTime();
console.log(
`PERF: SpreadsheetApp.openById concluído em ${
perf_endTime - perf_startTime
}ms`
);
}
this["spreadsheets"] = sCache;
return sCache[spreadsheetId];
} catch (e) {
throw new Error(
`Falha ao acessar planilha com ID '${spreadsheetId}'. Detalhes: ${
(e as Error).message
}`
);
}
}
/**
* Obtém uma aba específica, abstraindo a lógica de qual planilha abrir.
* @param sheetName O nome da aba desejada.
* @returns O objeto da aba ou null se não for encontrada.
*/
function getSheet_(sheetName: string): Sheet | null {
const spreadsheet = getSpreadsheetForSheet_(sheetName);
return spreadsheet.getSheetByName(sheetName);
}
/**
* Converte um valor para um objeto Date, retornando null se inválido.
*/
function parseDate(dateValue: any): Date | null {
if (!dateValue) return null;
if (dateValue instanceof Date && !isNaN(dateValue.getTime()))
return dateValue;
const d = new Date(dateValue);
return !isNaN(d.valueOf()) ? d : null;
}
/**
* Formata um valor de data para uma string no formato dd/MM/yyyy.
* @param dateValue O valor da data a ser formatado.
* @returns A data formatada ou uma string vazia se a data for inválida.
*/
function formatDateForExport_(dateValue: Date | string): string {
if (!dateValue) return "";
const d = new Date(dateValue);
if (d instanceof Date && !isNaN(d.getTime())) {
return Utilities.formatDate(d, FUSO_HORARIO_NEGOCIO, "dd/MM/yyyy");
}
return String(dateValue);
}
/**
* Encontra a linha de cabeçalho e os índices de colunas importantes.
* @param data A matriz de dados da planilha.
* @returns Um objeto com os dados encontrados ou um erro.
*/
/**
* Gera um ID único para uma nova solicitação.
* @returns Uma string de ID única.
* @private
*/
function generateUniqueId_(): string {
const timestamp = new Date().getTime();
const randomPart = Math.random().toString(36).substring(2, 8).toUpperCase();
return `REQ-${timestamp}-${randomPart}`;
}
function findHeadersAndData_(
data: any[][],
keyColumn: string = "ID_ITEM"
): HeadersAndData {
// Limita a busca do cabeçalho às primeiras 5 linhas para performance e robustez.
const headerSearchRange = data.slice(0, 5);
let headerRowIndex = headerSearchRange.findIndex(
(row) => Array.isArray(row) && row.indexOf(keyColumn) > -1
);
if (headerRowIndex === -1) {
// Se não encontrou nas primeiras 5, podemos opcionalmente procurar em todo o conjunto de dados como fallback.
headerRowIndex = data.findIndex(
(row) => Array.isArray(row) && row.indexOf(keyColumn) > -1
);
if (headerRowIndex === -1) {
return {
error: `Linha de cabeçalho com a coluna chave '${keyColumn}' não encontrada.`,
data: [],
headers: [],
headerRowIndex: -1,
};
}
}
const headers = data[headerRowIndex].map((h) => String(h));
const dataRows = data.slice(headerRowIndex + 1);
return { data: dataRows, headers: headers, headerRowIndex: headerRowIndex };
}
// =================================================================
// CONTEÚDO DE OBSERVABILIDADE.JS (MIGRADO PARA TYPESCRIPT)
// =================================================================
const SYSTEM_LOG_SHEET: string = "log_sistema";
const PERF_LOG_SHEET: string = "log_performance";
const LOG_LEVEL: StringMap = {
ERROR: "ERROR",
WARN: "WARN",
INFO: "INFO",
DEBUG: "DEBUG",
};
// Server-side default page size for paginated endpoints
const PAGE_SIZE_SERVER: number = 50;
/**
* Regista uma entrada de log do sistema de forma persistente.
*/
function logSystemEvent(
level: string,
functionName: string,
message: string,
executionTimeMs: number | null = null
): void {
try {
const sheet = getOrCreateSheetByName_(SYSTEM_LOG_SHEET, [
"Timestamp",
"Level",
"FunctionName",
"Message",
"UserEmail",
"ExecutionTimeMs",
]);
const user = Session.getActiveUser()
? Session.getActiveUser().getEmail()
: "SYSTEM";
sheet.appendRow([
new Date(),
level,
functionName,
message,
user,
executionTimeMs,
]);
} catch (e) {
console.error(
`Falha CRÍTICA ao registar log do sistema: ${
(e as Error).message
}. Log original: [${level}] ${functionName} - ${message}`
);
}
}
/**
* Envolve uma função para medir sua performance e registar os resultados.
*/
function measurePerformance<T>(functionName: string, fn: () => T): T {
const startTime = new Date().getTime();
let result: T;
let error: Error | null = null;
try {
result = fn();
return result;
} catch (e) {
error = e as Error;
throw e;
} finally {
const endTime = new Date().getTime();
const executionTimeMs = endTime - startTime;
const user = Session.getActiveUser()
? Session.getActiveUser().getEmail()
: "SYSTEM";
try {
const sheet = getOrCreateSheetByName_(PERF_LOG_SHEET, [
"Timestamp",
"FunctionName",
"UserEmail",
"ExecutionTimeMs",
"HasError",
]);
sheet.appendRow([
new Date(),
functionName,
user,
executionTimeMs,
error !== null,
]);
} catch (e) {
console.error(
`Falha ao registar métrica de performance para ${functionName}: ${
(e as Error).message
}`
);
}
if (error) {
logSystemEvent(
LOG_LEVEL.ERROR,
functionName,
`${error.message} | Stack: ${error.stack}`,
executionTimeMs
);
} else {
console.log(
`Performance: ${functionName} executou em ${executionTimeMs}ms.`
);
}
}
}
/**
* Função auxiliar para obter ou criar uma aba de log.
*/
function getOrCreateSheetByName_(sheetName: string, headers: string[]): Sheet {
let sheet = getSheet_(sheetName);
if (!sheet) {
const spreadsheet = getSpreadsheetForSheet_(sheetName);
sheet = spreadsheet.insertSheet(sheetName);
sheet.appendRow(headers);
sheet.setFrozenRows(1);
}
return sheet;
}
// =================================================================
// CONTEÚDO DE AUDITORIA.JS (MIGRADO PARA TYPESCRIPT)
// =================================================================
/**
* Regista uma ação no registo de auditoria imutável.
*/
function logAction_(
action: string,
targetId: string,
sku: string | null,
details: object,
dataInicio: any = null,
dataFim: any = null
): void {
try {
const auditSheet = getOrCreateSheetByName_(
AUDIT_LOG_SHEET_NAME,
AUDIT_LOG_HEADERS
);
const timestamp = new Date();
const user = Session.getActiveUser().getEmail();
const detailsString = JSON.stringify(details);
auditSheet.appendRow([
timestamp,
user,
action,
targetId,
sku || "N/A",
detailsString,
dataInicio || null,
dataFim || null,
]);
} catch (e) {
console.error(
`Falha CRÍTICA ao registar no registo de auditoria: ${
(e as Error).message
}`
);
}
}
/**
* Regista múltiplas ações no registo de auditoria de uma só vez.
*/
function logBulkActions_(actions: AuditAction[]): void {
if (!actions || actions.length === 0) return;
try {
const auditSheet = getOrCreateSheetByName_(
AUDIT_LOG_SHEET_NAME,
AUDIT_LOG_HEADERS
);
const user = Session.getActiveUser().getEmail();
const timestamp = new Date();
const rowsToAppend = actions.map((entry) => {
const detailsString = JSON.stringify(entry.details);
return [
timestamp,
user,
entry.action,
entry.targetId,
entry.sku || "N/A",
detailsString,
entry.dataInicio || null,
entry.dataFim || null,
];
});
auditSheet
.getRange(
auditSheet.getLastRow() + 1,
1,
rowsToAppend.length,
AUDIT_LOG_HEADERS.length
)
.setValues(rowsToAppend);
} catch (e) {
console.error(
`Falha CRÍTICA ao registar ações em massa no registo de auditoria: ${
(e as Error).message
}`
);
}
}
/**
* Envia notificações para o utilizador através dos canais configurados.
*/
function sendNotification_(
recipientEmail: string,
subject: string,
htmlBody: string
): void {
if (!recipientEmail) return;
const finalRecipient =
NOTIFICATION_SETTINGS.DEV_NOTIFICATION_EMAIL || recipientEmail;
if (NOTIFICATION_SETTINGS.EMAIL_ENABLED) {
try {
MailApp.sendEmail({
to: finalRecipient,
subject: `[${NOTIFICATION_SETTINGS.APP_NAME}] ${subject}`,
htmlBody: `...`, // O corpo do e-mail permanece o mesmo
});
} catch (e) {
console.error(
`Falha ao enviar e-mail para ${finalRecipient}: ${(e as Error).message}`
);
}
}
if (
NOTIFICATION_SETTINGS.CHAT_ENABLED &&
NOTIFICATION_SETTINGS.CHAT_WEBHOOK_URL
) {
// A lógica do chat permanece a mesma
}
}
// =================================================================
// CONTEÚDO DE ADMIN_ACTIONS.JS (MIGRADO PARA TYPESCRIPT)
// =================================================================
function onOpen(): void {
// A lógica permanece a mesma
}
function showUpdateStatusDialog(): void {
// A lógica permanece a mesma
}
function showApproveUrgentDialog(): void {
// A lógica permanece a mesma
}
function approveUrgentItems(idListString: string, justification: string): void {
// Invalidate the cache whenever urgent items are approved.
const cache = CacheService.getScriptCache();
cache.remove("promotion_requests_data");
// A lógica permanece a mesma, mas com tipagem interna mais forte se necessário
}
function updateItemStatus(idListString: string, newStatus: string): void {
// Invalidate the cache whenever an item's status is updated.
const cache = CacheService.getScriptCache();
cache.remove("promotion_requests_data");
// A lógica permanece a mesma
}
function resetWorkerState(): void {
// A lógica permanece a mesma
}
function showReprocessDialog(): void {
// A lógica permanece a mesma
}
function forceReprocessJob(jobId: string): void {
// A lógica permanece a mesma
}
function getCompleteUserPermissions_(): PermMap {
const activeUser = Session.getActiveUser().getEmail();
if (!activeUser) return {};
const cache = CacheService.getScriptCache();
const cacheKey = `user_complete_perms_${activeUser.toLowerCase()}`;
const cachedPerms = cache.get(cacheKey);
if (cachedPerms) {
return JSON.parse(cachedPerms);
}
const sheet = getSheet_(USER_CONFIG_SHEET_NAME);
if (!sheet) {
// Lança um erro aqui porque a ausência desta planilha é uma falha de configuração crítica.
throw new Error(
"A planilha de configuração de usuários não foi encontrada."
);
}
const allSheetData = sheet.getDataRange().getValues();
const {
headers,
data: userData,
error,
} = findHeadersAndData_(allSheetData, "EMAIL");
if (error) {
// Propaga o erro de `findHeadersAndData_`.
throw new Error(`Erro ao ler dados de usuários: ${error}`);
}
// Validação de Schema: Verifica a presença dos cabeçalhos essenciais.
const requiredHeaders = ["EMAIL", "ROLE", "PERMISSIONS"];
for (const header of requiredHeaders) {
if (headers.indexOf(header) === -1) {
throw new Error(
`Cabeçalho '${header}' ausente na planilha de configuração de usuários.`
);
}
}
const emailIndex = headers.indexOf("EMAIL");
const roleIndex = headers.indexOf("ROLE");
const permsIndex = headers.indexOf("PERMISSIONS");
const userRow = userData.find(
(row) => String(row[emailIndex]).toLowerCase() === activeUser.toLowerCase()
);
if (!userRow) {
return {}; // Usuário não encontrado, sem permissões.
}
const userRole = userRow[roleIndex];
let granularPerms: PermMap = {};
// Parse Seguro de JSON para permissões granulares.
const permsString = userRow[permsIndex];
if (
permsString &&
typeof permsString === "string" &&
permsString.trim().startsWith("{")
) {
try {
const parsedPerms = JSON.parse(permsString);
// Garante que as permissões sejam booleanas.
for (const key in parsedPerms) {
granularPerms[key] = String(parsedPerms[key]).toLowerCase() === "true";
}
} catch (e) {
logSystemEvent(
LOG_LEVEL.WARN,
"getCompleteUserPermissions_",
`Falha ao fazer parse do JSON de permissões para o usuário ${activeUser}. Permissões granulares ignoradas. Conteúdo: "${permsString}". Erro: ${
(e as Error).message
}`
);
// Continua com um objeto de permissões granulares vazio em caso de erro.
}
}
// 1. Lógica de ADMIN: Começa com as permissões base para um admin.
const finalPerms: PermMap = {};
if (userRole === USER_ROLES.ADMIN) {
finalPerms.is_admin = true;
AVAILABLE_PERMISSIONS.forEach((perm) => {
finalPerms[perm.id] = true;
});
}
// 2. Mescla as permissões granulares, que podem sobrescrever as de admin se necessário (ex: uma permissão específica negada).
Object.assign(finalPerms, granularPerms);
finalPerms.role = userRole;
// 3. Cache por 1 hora.
cache.put(cacheKey, JSON.stringify(finalPerms), 3600);
return finalPerms;
}
function checkPermission_(permission: string): boolean {
const allPermissions = getCompleteUserPermissions_();
// Um administrador (is_admin) sempre tem a permissão.
// Caso contrário, verifica a permissão específica, que já garantimos ser um booleano.
return (
allPermissions.is_admin === true || allPermissions[permission] === true
);
}
function isUserAuthorized_(): boolean {
const allPermissions = getCompleteUserPermissions_();
return allPermissions.is_admin === true || allPermissions.is_admin === "true";
}
// =================================================================
// CONTEÚDO DAS APIs (MIGRADO PARA TYPESCRIPT)
// =================================================================
function getUserPermissions(): string {
return measurePerformance("getUserPermissions", () => {
const userPerms = getCompleteUserPermissions_();
const availablePerms = AVAILABLE_PERMISSIONS;
return JSON.stringify({
success: true,
data: {
userPermissions: userPerms,
availablePermissions: availablePerms,
},
});
});
}
function getBusinessRules(): string {
return measurePerformance("getBusinessRules", () => {
try {
const sheet = getSheet_(RULES_CONFIG_SHEET_NAME);
if (!sheet)
throw new Error("A planilha de regras de negócio não foi encontrada.");
const data = sheet.getDataRange().getValues();
const rules: BusinessRules = {};
// Converte a lista de chave-valor da planilha num objeto
data.forEach((row) => {
const key = row[0];
let value = row[1];
if (key === "startDays" || key === "endDays") {
value = String(value).split(",").map(Number);
} else if (key === "maxDiscount") {
value = Number(value);
}
(rules as any)[key] = value;
});
return JSON.stringify({ success: true, rules: rules });
} catch (e) {
return JSON.stringify({ success: false, message: e.message });
}
});
}
function getUserDetails(email: string): string {
return measurePerformance("getUserDetails", () => {
try {
if (!checkPermission_("can_manage_users")) {
throw new Error(
"Acesso negado. Você não tem permissão para ver detalhes de usuários."
);
}
const sheet = getSheet_(USER_CONFIG_SHEET_NAME);
if (!sheet)
throw new Error(
"A planilha de configuração de usuários não foi encontrada."
);
const data = sheet.getDataRange().getValues();
const headers = data[0];
const emailColumn = headers.indexOf("EMAIL");
if (emailColumn === -1) {
throw new Error(
"Coluna 'EMAIL' não encontrada na planilha de usuários."
);
}
const userRow = data.find((row) => row[emailColumn] === email);
if (!userRow) {
return JSON.stringify({
success: false,
message: `Usuário com email '${email}' não encontrado.`,
});
}
const user: any = {};
headers.forEach((header, i) => {
const key = header.toLowerCase();
if (
key === "permissions" &&
typeof userRow[i] === "string" &&
userRow[i].startsWith("{")
) {
try {
user[key] = JSON.parse(userRow[i]);
} catch (e) {
user[key] = {}; // Fallback
}
} else {
user[key] = userRow[i];
}
});
return JSON.stringify({ success: true, user: user });
} catch (e) {
return JSON.stringify({ success: false, message: e.message });
}
});
}
function getRequestsImportTemplate(): string {
// Card 2: Unifica o esquema de dados. O template deve refletir os campos essenciais para a criação.
const headers = [
"MATERIAL", // Obrigatório
"DE (R$)", // Obrigatório
"POR (R$)", // Obrigatório
"DATA INÍCIO", // Obrigatório
"DATA FIM", // Obrigatório
"OBSERVAÇÃO COMERCIAL", // Opcional
];
// Adiciona o BOM para garantir a codificação UTF-8 correta no Excel.
const csvContent = "\uFEFF" + headers.join(",");
const fileName = "template_importacao_solicitacoes.csv";
return JSON.stringify({
success: true,
csvData: csvContent,
fileName: fileName,
});
}
function importNewRequests(fileContent: string): string {
return measurePerformance("importNewRequests", () => {
if (!checkPermission_("can_create_requests")) {
return JSON.stringify({
success: false,
message:
"Acesso negado. Você não tem permissão para criar solicitações.",
});
}
const lock = LockService.getScriptLock();
try {
lock.waitLock(30000);
const sheet = getSheet_(DB_SHEET_NAME);
if (!sheet)
throw new Error("A planilha de banco de dados não foi encontrada.");
// Remove o BOM se ele existir para evitar problemas com o parser.
if (fileContent.startsWith("\uFEFF")) {
fileContent = fileContent.substring(1);
}
const csvRows = Utilities.parseCsv(fileContent);
if (csvRows.length < 2)
throw new Error(
"O arquivo CSV está vazio ou contém apenas o cabeçalho."
);
const csvHeader = csvRows.shift().map((h) => h.trim());
// Card 2: Unifica o esquema de dados. Valida contra o novo template.
const requiredHeaders = [
"MATERIAL",
"DE (R$)",
"POR (R$)",
"DATA INÍCIO",
"DATA FIM",
];
if (!requiredHeaders.every((h) => csvHeader.includes(h))) {
throw new Error(
"O cabeçalho do arquivo é inválido. Faça o download do template mais recente."
);
}
const validationResults = { valid: [], invalid: [] };
const rowsToInsert = [];
const actionsToLog: AuditAction[] = [];
const currentUser = Session.getActiveUser().getEmail();
const timestamp = new Date();
// Mapeia os índices de forma segura.