-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path24_Repository.gs
More file actions
664 lines (567 loc) · 18.9 KB
/
Copy path24_Repository.gs
File metadata and controls
664 lines (567 loc) · 18.9 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
/**
* @file Repository.gs
* @description Repository Pattern - Abstração de acesso a dados
* @version 1.0.0
* @author Sistema TE-DF-PP
*
8000
div>
* IMPORTANTE: Este arquivo implementa o Repository Pattern para padronizar
* operações CRUD e abstrair o acesso direto às planilhas.
* Baseado nas melhores práticas identificadas no TE.txt
*/
// ============================================================================
// BASE REPOSITORY - Classe Abstrata
// ============================================================================
/**
* @class BaseRepository
* @description Classe base para todos os repositories
* Implementa operações CRUD genéricas
*/
const BaseRepository = (function() {
/**
* Construtor do BaseRepository
* @param {string} sheetName - Nome da planilha
*/
function BaseRepository(sheetName) {
if (!sheetName) {
throw new Error('[BaseRepository] Nome da planilha é obrigatório');
}
this.sheetName = sheetName;
this.dataService = new DataService(sheetName);
this.cache = CacheService.getScriptCache();
this.cachePrefix = 'repo_' + sheetName + '_';
this.cacheDuration = getConfig('env.CACHE_DURATION') || 300;
}
// ==========================================================================
// OPERAÇÕES CRUD BÁSICAS
// ==========================================================================
/**
* Cria um novo registro
* @param {Object} data - Dados do registro
* @return {Object} { success: boolean, data?: Object, error?: string }
*/
BaseRepository.prototype.create = function(data) {
try {
// Validação básica
if (!data || typeof data !== 'object') {
return { success: false, error: 'Dados inválidos' };
}
// Adiciona metadados de auditoria
data.createdAt = new Date().toISOString();
data.updatedAt = new Date().toISOString();
// Cria registro via DataService
var result = this.dataService.create(data);
// Limpa cache se sucesso
if (result.success) {
this._clearCache();
}
return result;
} catch (error) {
Logger.log('[BaseRepository.create] Erro: ' + error.message);
return { success: false, error: error.message };
}
};
/**
* Busca um registro por ID
* @param {string|number} id - ID do registro
* @return {Object} { success: boolean, data?: Object, error?: string }
*/
BaseRepository.prototype.findById = function(id) {
try {
if (!id) {
return { success: false, error: 'ID não fornecido' };
}
// Tenta buscar no cache
var cacheKey = this.cachePrefix + 'id_' + id;
const cached = this.cache.get(cacheKey);
if (cached) {
return { success: true, data: safeJSONParse(cached, []), fromCache: true };
}
// Busca no DataService
var result = this.dataService.read(id);
// Armazena no cache se sucesso
if (result.success && result.data) {
this.cache.put(cacheKey, JSON.stringify(result.data), this.cacheDuration);
}
return result;
} catch (error) {
Logger.log('[BaseRepository.findById] Erro: ' + error.message);
return { success: false, error: error.message };
}
};
/**
* Busca todos os registros
* @param {Object} filters - Filtros opcionais
* @return {Object} { success: boolean, data?: Array, error?: string }
*/
BaseRepository.prototype.findAll = function(filters) {
try {
filters = filters || {};
// Tenta buscar no cache (apenas se sem filtros)
if (Object.keys(filters).length === 0) {
var cacheKey = this.cachePrefix + 'all';
const cached = this.cache.get(cacheKey);
if (cached) {
return { success: true, data: safeJSONParse(cached, null), fromCache: true };
}
}
// Busca no DataService
var result = this.dataService.read(null, filters);
// Armazena no cache se sucesso e sem filtros
if (result.success && result.data && Object.keys(filters).length === 0) {
var cacheKey = this.cachePrefix + 'all';
this.cache.put(cacheKey, JSON.stringify(result.data), this.cacheDuration);
}
return result;
} catch (error) {
Logger.log('[BaseRepository.findAll] Erro: ' + error.message);
return { success: false, error: error.message };
}
};
/**
* Busca registros com filtros específicos
* @param {Object} filters - Filtros
* @return {Object} { success: boolean, data?: Array, error?: string }
*/
BaseRepository.prototype.findWhere = function(filters) {
return this.findAll(filters);
};
/**
* Busca um único registro com filtros
* @param {Object} filters - Filtros
* @return {Object} { success: boolean, data?: Object, error?: string }
*/
BaseRepository.prototype.findOne = function(filters) {
try {
var result = this.findWhere(filters);
if (result.success && result.data && result.data.length > 0) {
return { success: true, data: result.data[0] };
}
return { success: false, error: 'Registro não encontrado' };
} catch (error) {
Logger.log('[BaseRepository.findOne] Erro: ' + error.message);
return { success: false, error: error.message };
}
};
/**
* Atualiza um registro
* @param {string|number} id - ID do registro
* @param {Object} data - Dados para atualizar
* @return {Object} { success: boolean, data?: Object, error?: string }
*/
BaseRepository.prototype.update = function(id, data) {
try {
if (!id) {
return { success: false, error: 'ID não fornecido' };
}
if (!data || typeof data !== 'object') {
return { success: false, error: 'Dados inválidos' };
}
// Adiciona metadado de atualização
data.updatedAt = new Date().toISOString();
// Atualiza via DataService
var result = this.dataService.update(id, data);
// Limpa cache se sucesso
if (result.success) {
this._clearCache();
}
return result;
} catch (error) {
Logger.log('[BaseRepository.update] Erro: ' + error.message);
return { success: false, error: error.message };
}
};
/**
* Deleta um registro
* @param {string|number} id - ID do registro
* @return {Object} { success: boolean, error?: string }
*/
BaseRepository.prototype.delete = function(id) {
try {
if (!id) {
return { success: false, error: 'ID não fornecido' };
}
// Deleta via DataService
var result = this.dataService.delete(id);
// Limpa cache se sucesso
if (result.success) {
this._clearCache();
}
return result;
} catch (error) {
Logger.log('[BaseRepository.delete] Erro: ' + error.message);
return { success: false, error: error.message };
}
};
// ==========================================================================
// OPERAÇÕES AVANÇADAS
// ==========================================================================
/**
* Busca com paginação
* @param {number} page - Número da página (1-based)
* @param {number} pageSize - Tamanho da página
* @param {Object} filters - Filtros opcionais
* @return {Object} { success: boolean, data?: Array, pagination?: Object, error?: string }
*/
BaseRepository.prototype.findPaginated = function(page, pageSize, filters) {
try {
page = page || 1;
pageSize = pageSize || getConfig('limits.DEFAULT_PAGE_SIZE') || 20;
filters = filters || {};
// Busca todos os registros
var result = this.findAll(filters);
if (!result.success) {
return result;
}
const allData = result.data || [];
const totalRecords = allData.length;
const totalPages = Math.ceil(totalRecords / pageSize);
// Calcula índices
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
// Extrai página
const pageData = allData.slice(startIndex, endIndex);
return {
success: true,
data: pageData,
pagination: {
page: page,
pageSize: pageSize,
totalRecords: totalRecords,
totalPages: totalPages,
hasNext: page < totalPages,
hasPrev: page > 1
}
};
} catch (error) {
Logger.log('[BaseRepository.findPaginated] Erro: ' + error.message);
return { success: false, error: error.message };
}
};
/**
* Conta registros
* @param {Object} filters - Filtros opcionais
* @return {Object} { success: boolean, count?: number, error?: string }
*/
BaseRepository.prototype.count = function(filters) {
try {
var result = this.findAll(filters);
if (!result.success) {
return result;
}
return {
success: true,
count: result.data ? result.data.length : 0
};
} catch (error) {
Logger.log('[BaseRepository.count] Erro: ' + error.message);
return { success: false, error: error.message };
}
};
/**
* Verifica se existe um registro
* @param {string|number} id - ID do registro
* @return {Object} { success: boolean, exists?: boolean, error?: string }
*/
BaseRepository.prototype.exists = function(id) {
try {
var result = this.findById(id);
return {
success: true,
exists: result.success && result.data !== null
};
} catch (error) {
Logger.log('[BaseRepository.exists] Erro: ' + error.message);
return { success: false, error: error.message };
}
};
/**
* Operações em lote
* @param {Array} operations - Array de operações { type: 'create'|'update'|'delete', data: {...} }
* @return {Object} { success: boolean, results?: Array, error?: string }
*/
BaseRepository.prototype.batch = function(operations) {
try {
if (!Array.isArray(operations)) {
return { success: false, error: 'Operações devem ser um array' };
}
var results = [];
var hasError = false;
for (var i = 0; i < operations.length; i++) {
var op = operations[i];
var result;
switch (op.type) {
case 'create':
result = this.create(op.data);
break;
case 'update':
result = this.update(op.id, op.data);
break;
case 'delete':
result = this.delete(op.id);
break;
default:
result = { success: false, error: 'Tipo de operação inválido: ' + op.type };
}
results.push(result);
if (!result.success) {
hasError = true;
}
}
// Limpa cache após operações em lote
this._clearCache();
return {
success: !hasError,
results: results,
total: operations.length,
succeeded: results.filter(function(r) { return r.success; }).length,
failed: results.filter(function(r) { return !r.success; }).length
};
} catch (error) {
Logger.log('[BaseRepository.batch] Erro: ' + error.message);
return { success: false, error: error.message };
}
};
// ==========================================================================
// MÉTODOS DE CACHE
// ==========================================================================
/**
* Limpa o cache do repository
* @private
*/
BaseRepository.prototype._clearCache = function() {
try {
// Remove cache de 'all'
this.cache.remove(this.cachePrefix + 'all');
// Nota: Não é possível remover todos os caches com prefixo no Apps Script
// Cada ID específico permanecerá em cache até expirar
Logger.log('[BaseRepository] Cache limpo para: ' + this.sheetName);
} catch (error) {
Logger.log('[BaseRepository._clearCache] Erro: ' + error.message);
}
};
/**
* Limpa cache de um ID específico
* @param {string|number} id - ID do registro
*/
BaseRepository.prototype.clearCacheById = function(id) {
try {
var cacheKey = this.cachePrefix + 'id_' + id;
this.cache.remove(cacheKey);
} catch (error) {
Logger.log('[BaseRepository.clearCacheById] Erro: ' + error.message);
}
};
// ==========================================================================
// MÉTODOS DE ESTATÍSTICAS
// ==========================================================================
/**
* Obtém estatísticas do repository
* @return {Object} { success: boolean, stats?: Object, error?: string }
*/
BaseRepository.prototype.getStats = function() {
try {
return this.dataService.getStats();
} catch (error) {
Logger.log('[BaseRepository.getStats] Erro: ' + error.message);
return { success: false, error: error.message };
}
};
return BaseRepository;
})();
// ============================================================================
// EXPORT BASEREPO SITORY FOR GLOBAL ACCESS
// ============================================================================
/**
* Alias global para BaseRepository
* Resolve o erro "Repository is not defined"
*/
var Repository = BaseRepository;
// ============================================================================
// REPOSITORIES ESPECÍFICOS
// ============================================================================
/**
* @class AlunoRepository
* @extends BaseRepository
* @description Repository específico para Alunos
*/
var AlunoRepository = (function() {
function AlunoRepository() {
var sheetName = (typeof SHEET_NAMES !== 'undefined' && SHEET_NAMES.ALUNOS) || 'Alunos';
BaseRepository.call(this, sheetName);
}
// Herda do BaseRepository
AlunoRepository.prototype = Object.create(BaseRepository.prototype);
AlunoRepository.prototype.constructor = AlunoRepository;
/**
* Busca alunos por rota
* @param {string} rotaId - ID da rota
* @return {Object}
*/
AlunoRepository.prototype.findByRota = function(rotaId) {
return this.findWhere({ rotaId: rotaId });
};
/**
* Busca alunos por escola
* @param {string} escolaNome - Nome da escola
* @return {Object}
*/
AlunoRepository.prototype.findByEscola = function(escolaNome) {
return this.findWhere({ escola: escolaNome });
};
/**
* Busca alunos com necessidades especiais
* @return {Object}
*/
AlunoRepository.prototype.findComNecessidadesEspeciais = function() {
return this.findWhere({ necessidadesEspeciais: 'Sim' });
};
return AlunoRepository;
})();
/**
* @class RotaRepository
* @extends BaseRepository
* @description Repository específico para Rotas
*/
var RotaRepository = (function() {
function RotaRepository() {
var sheetName = (typeof SHEET_NAMES !== 'undefined' && SHEET_NAMES.ROTAS) || 'Rotas';
BaseRepository.call(this, sheetName);
}
RotaRepository.prototype = Object.create(BaseRepository.prototype);
RotaRepository.prototype.constructor = RotaRepository;
/**
* Busca rotas por veículo
* @param {string} veiculoId - ID do veículo
* @return {Object}
*/
RotaRepository.prototype.findByVeiculo = function(veiculoId) {
return this.findWhere({ veiculoId: veiculoId });
};
/**
* Busca rotas ativas
* @return {Object}
*/
RotaRepository.prototype.findAtivas = function() {
return this.findWhere({ status: 'Ativa' });
};
return RotaRepository;
})();
/**
* @class VeiculoRepository
* @extends BaseRepository
* @description Repository específico para Veículos
*/
var VeiculoRepository = (function() {
function VeiculoRepository() {
var sheetName = (typeof SHEET_NAMES !== 'undefined' && SHEET_NAMES.VEICULOS) || 'Veiculos';
BaseRepository.call(this, sheetName);
}
VeiculoRepository.prototype = Object.create(BaseRepository.prototype);
VeiculoRepository.prototype.constructor = VeiculoRepository;
/**
* Busca veículos disponíveis
* @return {Object}
*/
VeiculoRepository.prototype.findDisponiveis = function() {
return this.findWhere({ status: 'Disponível' });
};
/**
* Busca veículo por placa
* @param {string} placa - Placa do veículo
* @return {Object}
*/
VeiculoRepository.prototype.findByPlaca = function(placa) {
return this.findOne({ placa: placa });
};
return VeiculoRepository;
})();
/**
* @class UsuarioRepository
* @extends BaseRepository
* @description Repository específico para Usuários
*/
var UsuarioRepository = (function() {
function UsuarioRepository() {
var sheetName = (typeof SHEET_NAMES !== 'undefined' && SHEET_NAMES.USUARIOS) || 'Usuarios';
BaseRepository.call(this, sheetName);
}
UsuarioRepository.prototype = Object.create(BaseRepository.prototype);
UsuarioRepository.prototype.constructor = UsuarioRepository;
/**
* Busca usuário por email
* @param {string} email - Email do usuário
* @return {Object}
*/
UsuarioRepository.prototype.findByEmail = function(email) {
return this.findOne({ email: email });
};
/**
* Busca usuários por função
* @param {string} funcao - Função do usuário
* @return {Object}
*/
UsuarioRepository.prototype.findByFuncao = function(funcao) {
return this.findWhere({ funcao: funcao });
};
/**
* Busca usuários ativos
* @return {Object}
*/
UsuarioRepository.prototype.findAtivos = function() {
return this.findWhere({ status: 'Ativo' });
};
return UsuarioRepository;
})();
// ============================================================================
// FACTORY DE REPOSITORIES
// ============================================================================
/**
* @class RepositoryFactory
* @description Factory para criar repositories
*/
var RepositoryFactory = (function() {
var instances = {};
return {
/**
* Obtém repository para uma entidade
* @param {string} entityName - Nome da entidade
* @return {BaseRepository}
*/
getRepository: function(entityName) {
// Singleton pattern
if (instances[entityName]) {
return instances[entityName];
}
var repository;
switch (entityName.toLowerCase()) {
case 'aluno':
case 'alunos':
repository = new AlunoRepository();
break;
case 'rota':
case 'rotas':
repository = new RotaRepository();
break;
case 'veiculo':
case 'veiculos':
repository = new VeiculoRepository();
break;
case 'usuario':
case 'usuarios':
repository = new UsuarioRepository();
break;
default:
// Repository genérico
repository = new BaseRepository(entityName);
}
instances[entityName] = repository;
return repository;
},
/**
* Limpa instâncias em cache
*/
clearInstances: function() {
instances = {};
}
};
})();
You can’t perform that action at this time.