-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path70_System.gs
More file actions
225 lines (200 loc) · 6.52 KB
/
Copy path70_System.gs
File metadata and controls
225 lines (200 loc) · 6.52 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
/**
* @file System.gs
* @description Unified System Initialization and Lifecycle Management
* @version 2.0.0
* @author Sistema TE-DF-PP
*
* This file replaces CONFIGURE_SYSTEM.gs, INICIALIZAR_SISTEMA.gs, and SETUP_SPREADSHEET.gs.
* It provides a single, organic entry point for system initialization.
*/
const System = (function() {
// Private state
var initialized = false;
let degradedMode = false;
let initializationErrors = [];
const config = {
// CORRIGIDO: Usa nomes de SHEET_NAMES
criticalSheets: ['Usuarios', 'Configuracoes', 'Logs', 'JobQueue'],
optionalSheets: ['Sessoes', 'Auditoria', 'Telemetry'],
version: '2.0.0'
};
/**
* Private: Checks if the environment is ready
*/
function _checkEnvironment() {
const props = PropertiesService.getScriptProperties();
var spreadsheetId = props.getProperty('SPREADSHEET_ID');
if (!spreadsheetId) {
// Try to auto-detect from active spreadsheet (if running in container-bound script)
try {
const ss = SpreadsheetApp.getActiveSpreadsheet();
if (ss) {
spreadsheetId = ss.getId();
props.setProperty('SPREADSHEET_ID', spreadsheetId);
Logger.log('[System] Auto-detected and saved SPREADSHEET_ID: ' + spreadsheetId);
return true;
}
} catch (e) {
// Not container bound or no active sheet
}
Logger.log('[System] ⚠️ SPREADSHEET_ID not found. System requires setup.');
return false;
}
return true;
}
/**
* Private: Ensures critical sheets exist
* ATUALIZADO: Modo degradado se sheets opcionais falharem
*/
function _ensureSheets() {
try {
// Use the existing CreateMissingSheets logic if available
if (typeof createMissingProductionSheets === 'function') {
Logger.log('[System] Verifying sheet structure...');
var result = createMissingProductionSheets();
Logger.log('[System] Sheet verification result: ' + JSON.stringify(result));
return true;
} else {
Logger.log('[System] ⚠️ CreateMissingSheets function not found.');
return false;
}
} catch (e) {
Logger.log('[System] ❌ Error ensuring sheets: ' + e.message);
return false;
}
}
return {
/**
* Main entry point to initialize the system.
* Call this at the start of doGet/doPost or any entry point.
* ATUALIZADO: Suporta modo degradado
*/
init: function() {
if (initialized) {
return {
success: true,
degradedMode: degradedMode,
message: 'Sistema já inicializado'
};
}
Logger.log('[System] Initializing v' + config.version + '...');
initializationErrors = [];
degradedMode = false;
// 1. Environment Check
if (!_checkEnvironment()) {
Logger.log('[System] ⚠️ SPREADSHEET_ID não configurado');
initializationErrors.push('SPREADSHEET_ID não configurado');
degradedMode = true;
// Tenta continuar sem SPREADSHEET_ID (modo muito degradado)
Logger.log('[System] Tentando continuar em modo degradado...');
}
// 1.1 Colab Webhook Check (Warning only)
const props = PropertiesService.getScriptProperties();
const colabUrl = props.getProperty('COLAB_WEBHOOK_URL');
if (!colabUrl) {
Logger.log('[System] ⚠️ COLAB_WEBHOOK_URL não configurada. Integração Colab indisponível.');
// Não adiciona a initializationErrors para não alarmar se não for usar Colab
}
// 2. Sheet Structure Check (Lazy/Self-Healing)
// Não lança erro para permitir modo degradado
if (!degradedMode) {
_ensureSheets();
}
// 3. Service Initialization
if (typeof ServiceManager !== 'undefined') {
// Pre-warm critical services
try {
ServiceManager.getLoggerService();
ServiceManager.getPropertiesManager();
Logger.log('[System] Serviços críticos inicializados');
} catch (e) {
Logger.log('[System] ⚠️ Erro ao inicializar serviços: ' + e.message);
initializationErrors.push('Erro ao inicializar serviços: ' + e.message);
degradedMode = true;
}
} else {
Logger.log('[System] ⚠️ ServiceManager não disponível');
degradedMode = true;
}
initialized = true;
if (degradedMode) {
Logger.log('[System] ⚠️ Sistema inicializado em MODO DEGRADADO');
Logger.log('[System] Erros: ' + initializationErrors.join('; '));
} else {
Logger.log('[System] ✅ Initialization complete.');
}
return {
success: true,
degradedMode: degradedMode,
errors: initializationErrors,
message: degradedMode ? 'Sistema em modo degradado' : 'Sistema inicializado com sucesso'
};
},
/**
* Force a system setup/reset.
* Useful for manual execution or admin dashboard.
*/
setup: function() {
Logger.log('[System] Starting manual setup...');
const envOk = _checkEnvironment();
const sheetsOk = _ensureSheets();
return {
success: envOk && sheetsOk,
environment: envOk,
sheets: sheetsOk
};
},
/**
* Get system health status
* ATUALIZADO: Inclui modo degradado
*/
getStatus: function() {
return {
initialized: initialized,
degradedMode: degradedMode,
version: config.version,
errors: initializationErrors,
timestamp: new Date().toISOString(),
criticalSheets: config.criticalSheets,
optionalSheets: config.optionalSheets
};
},
/**
* Verifica se sistema está em modo degradado
* @return {boolean}
*/
isDegraded: function() {
return degradedMode;
},
/**
* Obtém erros de inicialização
* @return {Array<string>}
*/
getInitializationErrors: function() {
return initializationErrors;
},
/**
* Força reinicialização do sistema
*/
reinitialize: function() {
initialized = false;
degradedMode = false;
initializationErrors = [];
return this.init();
}
};
})();
/**
* Global wrapper for backward compatibility or easy access
*/
function initSystem() {
return System.init();
}
/**
* Manual setup function for the IDE
*/
function setupSystem() {
const result = System.setup();
Logger.log('Setup Result: ' + JSON.stringify(result, null, 2));
return result;
}