-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclsAplicacion.cls
More file actions
479 lines (393 loc) · 18.5 KB
/
Copy pathclsAplicacion.cls
File metadata and controls
479 lines (393 loc) · 18.5 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
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "clsAplicacion"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
' gestion de la aplicacion 'gestor de oportunidades ABC'
'@Folder "3-Aplicac (Coord)"
Option Explicit
Private Const MODULE_NAME As String = "clsAplicacion"
Private m_bChartActive As Boolean
' lo siguiente es para controlar **SUCESOS EN LA COLECCION clsOpportunitiesMgr QUE HACEN
' QUE TENGA QUE INTERVENIR clsAplicacion (para coordinar con clsFileManager, o con el Ribbon, ...)
'@MemberAttribute VB_VarHelpID, -1
Private WithEvents mOpportunities As clsOpportunitiesMgr
Attribute mOpportunities.VB_VarHelpID = -1
Private WithEvents mChartManager As clsChartEventsManager
Attribute mChartManager.VB_VarHelpID = -1
Private WithEvents mFSMonitoringCoord As clsFSMonitoringCoord
Attribute mFSMonitoringCoord.VB_VarHelpID = -1
Private WithEvents mRibbonState As clsRibbonState
Attribute mRibbonState.VB_VarHelpID = -1
Private WithEvents evRibbon As clsRibbonEvents
Attribute evRibbon.VB_VarHelpID = -1
Private mConfiguration As clsConfiguration
Private mFileMgr As clsFileManager
Private WithEvents ctx As clsExecutionContext
Attribute ctx.VB_VarHelpID = -1
Public Property Get bChartActive() As Boolean
bChartActive = m_bChartActive
End Property
Public Property Get Configuration() As clsConfiguration
Set Configuration = mConfiguration
End Property
Public Property Get executionContext() As clsExecutionContext
Set executionContext = ctx
End Property
Public Property Get FileMgr() As clsFileManager
Set FileMgr = mFileMgr
End Property
Public Property Get OpportunitiesMgr() As clsOpportunitiesMgr
Set OpportunitiesMgr = mOpportunities
End Property
Public Property Get ChartManager() As clsChartEventsManager
Set ChartManager = mChartManager
End Property
Public Property Get Ribbon() As clsRibbonEvents
Set Ribbon = evRibbon
End Property
Public Property Get RibbonState() As clsRibbonState
Set RibbonState = mRibbonState
End Property
Public Property Let RibbonHandler(xlRibbon As IRibbonUI)
If evRibbon Is Nothing Then Set evRibbon = New clsRibbonEvents
Call evRibbon.Init(xlRibbon)
LogInfo MODULE_NAME, "[RibbonHandler] - conectada instancia WithEvents de ribbon para gestion de eventos"
End Property
' -------------------------------------------------------------
' Class_Initialize: SOLO inicialización mínima (ligera y segura)
' NO debe hacer trabajo pesado ni depender de App
' -------------------------------------------------------------
Private Sub Class_Initialize()
On Error GoTo ErrHandler
LogInfo MODULE_NAME, "[Class_Initialize] - Iniciando aplicacion"
Set evRibbon = New clsRibbonEvents
Set mRibbonState = New clsRibbonState
mRibbonState.Modo = Ribbon_OpportunityOnly
' 1. Configuración (sin dependencias)
Set mConfiguration = New clsConfiguration
' 2. Contexto de ejecución (suscripción a eventos de Application) (antes del FileManager y demás)
Set ctx = New clsExecutionContext
ctx.Initialize
LogInfo MODULE_NAME, "[Class_Initialize] - ctx suscrito a eventos de Application"
' 3. FileManager (recibe el contexto compartido)
Set mFileMgr = New clsFileManager
mFileMgr.Initialize ctx
InitFileManager
' 4. OpportunitiesMgr
Set mOpportunities = New clsOpportunitiesMgr
' Inicialización explícita
mOpportunities.SetBaseFolder mConfiguration.RutaOportunidades
' 5. ChartManager (gestion de eventos del usuario sobre charts de excel (seleccion; etc)
Set mChartManager = New clsChartEventsManager
' 6. Watcher - recibe el diccionario de carpetas como parametro
Set mFSMonitoringCoord = New clsFSMonitoringCoord
mFSMonitoringCoord.IniciarMonitoreo mConfiguration.oDicFoldersToWatch
LogInfo MODULE_NAME, "[Class_Initialize] - inicialización completada"
' como consecuencia de introducir el watcher, habrá que gestionar la actualizacion del ribbon, con los cambios que se graben en el
' registro; de ello se encarga la aplicacion (la configuracion NO sabe si hay un control dinámico de las carpetas, o si su contenido
' es estático)
' LA PREGUNTA: DEL RIBBON SOLO SABE LA APLICACION, o trmaiben sabe el watcher? (encomiendo al modulo del watcher, o a la app, la actualiz del ribbon?)
Exit Sub
ErrHandler:
Err.Raise Err.Number, "clsAplicacion.Class_Initialize", _
"Error inicializando aplicación: " & Err.Description
End Sub
' -------------------------------------------------------------
' Class_Terminate: limpieza
' -------------------------------------------------------------
Private Sub Class_Terminate()
Terminate
End Sub
' Método Terminate para ser llamado desde ThisWorkbook.Workbook_BeforeClose/Uninstall
Public Sub Terminate()
LogInfo MODULE_NAME, "[Terminate] - Iniciando limpieza de la aplicacion"
On Error Resume Next ' Asegurar que la limpieza continúa aunque haya errores
' 1. Liberar FolderWatcher primero (tiene recursos COM externos)
Set mFSMonitoringCoord = Nothing
' 2. Liberar Ribbon events
If Not evRibbon Is Nothing Then
evRibbon.StopEvents
Set evRibbon = Nothing
End If
' 3. Liberar managers
Set mConfiguration = Nothing
Set mOpportunities = Nothing
Set mFileMgr = Nothing
Set mChartManager = Nothing
Set mRibbonState = Nothing
' 4. Liberar contexto de ejecución (desuscribe de Application)
Set ctx = Nothing
LogInfo MODULE_NAME, "[Terminate] - Limpieza completada"
End Sub
' -------------------------------------------------------------
' InitFileManager: GESTIONA LA COLECCIÓN DE WORKBOOKS
' (Es responsabilidad de clsAplicacion, NO de clsFileManager)
' -------------------------------------------------------------
Public Sub InitFileManager()
LogInfo MODULE_NAME, "[InitFileManager]"
On Error GoTo ErrHandler
Dim oWorkBook As Workbook
Dim TrackedCount As Long
' Trackear todos los workbooks abiertos
For Each oWorkBook In Application.Workbooks
mFileMgr.GetOrTrackWorkbook oWorkBook
TrackedCount = TrackedCount + 1
Next oWorkBook
' Establecer el archivo activo
Dim wb As Workbook
Set wb = ctx.Workbook
If Not wb Is Nothing Then
Set mFileMgr.ActiveWb = mFileMgr.GetOrTrackWorkbook(wb)
End If
LogInfo MODULE_NAME, "[InitFileManager] Workbooks tracked: " & TrackedCount
Exit Sub
ErrHandler:
LogError MODULE_NAME, "[InitFileManager] Error inicializando tracking de workbooks", , Err.Description
Err.Raise Err.Number, "clsAplicacion.InitFileManager", _
"Error inicializando tracking de workbooks: " & Err.Description
End Sub
' ==========================================
' gestion del ribbon
' ==========================================
'@Description: Conmuta cíclicamente el modo del Ribbon (admin ? opp ? user ? admin)
'@Scope: público
'@Category: UI / Ribbon
Public Sub ToggleRibbonMode()
mRibbonState.ToggleModo
Call ActivarTabSiProcede
End Sub
Private Sub ActivarTabSiProcede()
On Error Resume Next
If evRibbon Is Nothing Then Exit Sub
If EsFicheroOportunidad() Then
evRibbon.ActivarTab "tabOfertasEspecial"
End If
End Sub
Private Sub mRibbonState_StateChanged()
evRibbon.InvalidarRibbon
End Sub
' ==================================================================
' GESTION DE EVENTOS
' ==================================================================
' -------------------------------------------------------------
' Eventos de clsExecutionContext (propagados desde Application)
' -------------------------------------------------------------
'@Description: Se dispara cuando se activa un workbook (desde ctx)
'@Category: Gráficos
'@Scope: Grafico seleccionado
'@ArgumentDescriptions: wb As Workbook
Private Sub ctx_WorkbookActivated(ByVal wb As Workbook)
LogDebug MODULE_NAME, "[ctx_WorkbookActivated] " & wb.Name
mChartManager.RefreshCurrentSheet
End Sub
'@Description: Se dispara al activar una hoja; inicia vigilancia de graficos
'@Category: Gráficos
'@Scope: Grafico seleccionado
'@ArgumentDescriptions: sh As Object
Private Sub ctx_SheetActivated(ByVal sh As Object)
On Error GoTo ErrHandler
LogDebug MODULE_NAME, "[ctx_SheetActivated] " & TypeName(sh) & " '" & sh.Name & "'"
mChartManager.WatchSheet sh
evRibbon.InvalidarControl "btnGenerarGraficos"
evRibbon.InvalidarControl "btnCGASING"
Exit Sub
ErrHandler:
LogError MODULE_NAME, "[ctx_SheetActivated] Error", , Err.Description
End Sub
'@Description: Se dispara al desactivar una hoja; detiene vigilancia de graficos
'@Category: Gráficos
'@Scope: Grafico seleccionado
'@ArgumentDescriptions: sh As Object
Private Sub ctx_SheetDeactivated(ByVal sh As Object)
On Error GoTo ErrHandler
LogDebug MODULE_NAME, "[ctx_SheetDeactivated] '" & sh.Name & "'"
mChartManager.StopWatching
evRibbon.InvalidarControl "btnGenerarGraficos"
evRibbon.InvalidarControl "btnCGASING"
Exit Sub
ErrHandler:
LogError MODULE_NAME, "[ctx_SheetDeactivated] Error", , Err.Description
End Sub
' -------------------------------------------------------------
' Evento: cambios detectados en oportunidades (desde OpportunitiesMgr)
' -------------------------------------------------------------
Private Sub mOpportunities_OpportunityCollectionUpdate(ByVal cambios As String)
LogInfo MODULE_NAME, "[callback: clsOpportunitiesMgr OpportunityCollectionUpdate] - cambios detectados: " & cambios
' Actualizar ribbon - usar Invalidate en lugar de InvalidarControl
If Not evRibbon Is Nothing Then
'evRibbon.InvalidarRibbon
evRibbon.InvalidarControl "ddlOportunidades"
LogDebug MODULE_NAME, "[mOpportunities_OpportunityCollectionUpdate] - Ribbon invalidado"
End If
End Sub
'TODO: Extraer la lógica de clsExcelFile A una función (En principio se mantendrá en Celesa aplicación pero es posible que se lleve a otra clase)
Private Sub mOpportunities_currOpportunityChanged(ByVal Index As Long, ByVal Path As String)
LogInfo MODULE_NAME, "[callback: clsOpportunitiesMgr currOpportunityChanged] - Oportunidad seleccionada: " & Path
Dim f As clsExcelFile
Set f = mFileMgr.ActiveWb
If Not f Is Nothing Then
If f.DebeMoverseAOp(Path, mConfiguration.RutaOportunidades) Then
f.MoverAOp Path, mConfiguration.RutaOportunidades
End If
End If
' (Aquí no tiene sentido invalidar el ribbon, esto no tiene nada que ver con ribbon, SOLO LÓGICA DE NEGOCIO)
End Sub
' -------------------------------------------------------------
' Eventos de mFSMonitoringCoord (cambios en sistema de archivos)
' clsAplicacion recibe estos eventos y delega a OpportunitiesMgr
' -------------------------------------------------------------
Private Sub mFSMonitoringCoord_OpportunityCreated(ByVal parentFolder As String, ByVal subfolderName As String)
LogDebug MODULE_NAME, "[mFSMonitoringCoord_OpportunityCreated] " & subfolderName
mOpportunities.ProcesarCambiosEnOportunidades subfolderName
End Sub
Private Sub mFSMonitoringCoord_OpportunityDeleted(ByVal parentFolder As String, ByVal subfolderName As String)
LogDebug MODULE_NAME, "[mFSMonitoringCoord_OpportunityDeleted] " & subfolderName
mOpportunities.ProcesarCambiosEnOportunidades subfolderName
End Sub
Private Sub mFSMonitoringCoord_OpportunityRenamed(ByVal parentFolder As String, ByVal oldName As String, ByVal newName As String)
LogDebug MODULE_NAME, "[mFSMonitoringCoord_OpportunityRenamed] " & oldName & " -> " & newName
mOpportunities.ProcesarCambiosEnOportunidades oldName
mOpportunities.ProcesarCambiosEnOportunidades newName
End Sub
Private Sub mFSMonitoringCoord_OpportunityItemDeleted(ByVal folder As String, ByVal fileName As String)
LogDebug MODULE_NAME, "[mFSMonitoringCoord_OpportunityItemDeleted] " & fileName
mOpportunities.ProcesarCambiosEnItemsOportunidad fileName
End Sub
Private Sub mFSMonitoringCoord_OpportunityItemRenamed(ByVal folder As String, ByVal oldName As String, ByVal newName As String)
LogDebug MODULE_NAME, "[mFSMonitoringCoord_OpportunityItemRenamed] " & oldName & " -> " & newName
mOpportunities.ProcesarCambiosEnItemsOportunidad newName
End Sub
Private Sub mFSMonitoringCoord_TemplateCreated(ByVal folder As String, ByVal fileName As String)
LogDebug MODULE_NAME, "[mFSMonitoringCoord_TemplateCreated] " & fileName
' TODO: Implementar logica de actualizacion de plantillas si es necesario
End Sub
Private Sub mFSMonitoringCoord_TemplateChanged(ByVal folder As String, ByVal fileName As String)
LogDebug MODULE_NAME, "[mFSMonitoringCoord_TemplateChanged] " & fileName
' TODO: Notificar cambio en plantilla si es necesario
End Sub
Private Sub mFSMonitoringCoord_GasFileCreated(ByVal folder As String, ByVal fileName As String)
LogDebug MODULE_NAME, "[mFSMonitoringCoord_GasFileCreated] " & fileName
' TODO: Implementar logica de sincronizacion Gas si es necesario
End Sub
Private Sub mFSMonitoringCoord_GasFileChanged(ByVal folder As String, ByVal fileName As String)
LogDebug MODULE_NAME, "[mFSMonitoringCoord_GasFileChanged] " & fileName
' TODO: Actualizar referencias Gas si es necesario
End Sub
Private Sub mFSMonitoringCoord_MonitoringError(ByVal folder As String, ByVal errorMessage As String)
LogError MODULE_NAME, "[mFSMonitoringCoord_MonitoringError] " & folder & ": " & errorMessage
' Mostrar al usuario solo errores criticos
If InStr(1, errorMessage, "Limite", vbTextCompare) > 0 Or _
InStr(1, errorMessage, "no encontrada", vbTextCompare) > 0 Then
MsgBox "Error en monitoreo de carpeta:" & vbCrLf & _
folder & vbCrLf & vbCrLf & _
errorMessage, vbExclamation, "FolderWatcher"
End If
End Sub
Private Sub mFSMonitoringCoord_MonitoringReconnected(ByVal folder As String, ByVal attempts As Long)
LogInfo MODULE_NAME, "[mFSMonitoringCoord_MonitoringReconnected] " & folder & " tras " & attempts & " intentos"
End Sub
Private Sub mFSMonitoringCoord_MonitoringFailed(ByVal folder As String, ByVal reason As String)
LogError MODULE_NAME, "[mFSMonitoringCoord_MonitoringFailed] " & folder & ": " & reason
MsgBox "El monitoreo de la carpeta ha fallado permanentemente:" & vbCrLf & _
folder & vbCrLf & vbCrLf & _
"Razon: " & reason & vbCrLf & vbCrLf & _
"Es posible que la carpeta no este accesible o haya problemas de red.", _
vbExclamation, "FolderWatcher - Reconexion Fallida"
End Sub
' -------------------------------------------------------------
' Eventos de cambio de seleccion de charts (desde ChartManager)
' -------------------------------------------------------------
Private Sub mChartManager_ChartActivated(cht As Chart)
LogDebug MODULE_NAME, "[callback: clsChartEventsManager ChartActivated] - Gráfico activado: " & cht.Name
m_bChartActive = True
' Aquí decides:
' - ¿Invalidar ribbon?
' - ¿Cargar datos del gráfico?
' - ¿Actualizar estado de la oportunidad?
evRibbon.InvalidarControl "btnInvertirSeries"
End Sub
Private Sub mChartManager_ChartDeactivated(cht As Chart)
LogDebug MODULE_NAME, "[callback: clsChartEventsManager ChartActivated] - Gráfico DESactivado: " & cht.Name
m_bChartActive = False
evRibbon.InvalidarControl "btnInvertirSeries"
End Sub
' -------------------------------------------------------------
' Eventos de comandos activados desde el Ribbon
' -------------------------------------------------------------
Private Sub evRibbon_GenerarGraficosDesdeCurvasRto()
LogDebug MODULE_NAME, "[callback: clsRibbonEvents GenerarGraficosDesdeCurvasRto]"
On Error GoTo ErrorHandler
Application.ScreenUpdating = False
Call EjecutarGraficoEnLibroActivo
mChartManager.RefreshCurrentSheet
ErrorHandler:
Application.ScreenUpdating = True
End Sub
Private Sub evRibbon_InvertirEjes()
LogDebug MODULE_NAME, "[callback: clsRibbonEvents InvertirEjes]"
On Error GoTo ErrorHandler
Application.ScreenUpdating = False
Call InvertirEjesDelGraficoActivo
ErrorHandler:
Application.ScreenUpdating = True
End Sub
Private Sub evRibbon_FormatearCGASING()
LogDebug MODULE_NAME, "[callback: clsRibbonEvents FormatearCGASING]"
On Error GoTo ErrorHandler
'Application.ScreenUpdating = False
Call FixCGASING
ErrorHandler:
Application.ScreenUpdating = True
End Sub
'@Description: Muestra el formulario de configuracion de la aplicacion
'@Scope: Private (evento de ribbon)
'@ArgumentDescriptions: (sin argumentos)
'@Returns: (ninguno)
'@Dependencies: frmConfiguracion
'@Note: Usa instanciacion explicita para evitar problemas de memoria con la instancia predeterminada
Private Sub evRibbon_Configurador()
Dim frm As frmConfiguracion
Set frm = New frmConfiguracion
frm.Show vbModal
Unload frm
Set frm = Nothing
End Sub
Private Sub evRibbon_NuevaOportunidad()
OpportunitiesMgr.CreaOportunidad
'evRibbon.InvalidarControl "ddlOportunidades"
End Sub
Private Sub evRibbon_ReplaceWithNamesInValidations()
On Error GoTo ErrorHandler
'Application.ScreenUpdating = False
Call modAPPBudgetQuotesUtilids.AplicarNombresAValidacionesCeldasActWBConReporte
ErrorHandler:
'Application.ScreenUpdating = True
End Sub
'@Description: Devuelve True si, en el estado actual de la aplicación,
' tiene sentido habilitar la acción "Invertir Ejes".
'@Scope: público (consulta de estado desde el Ribbon/modRibbonCallbacks)
'@ArgumentDescriptions: (sin argumentos)
'@Returns: Boolean | True si es posible invertir ejes ahora mismo.
'@Category: UI / Estado consolidado
Public Property Get bCanInvertAxes() As Boolean
On Error GoTo ErrHandler
bCanInvertAxes = m_bChartActive
If bCanInvertAxes Then bCanInvertAxes = mFileMgr.AnalizarArchivoActivo.TipoDetectado = CGASING_CurvasRendimiento
If Not bCanInvertAxes Then Exit Property
Dim oExcelFile As clsExcelFile
Set oExcelFile = mFileMgr.ActiveWb
If Not oExcelFile Is Nothing Then
bCanInvertAxes = oExcelFile.EsValidoInvertirEjes
Else
bCanInvertAxes = False
End If
Exit Property
ErrHandler:
LogError MODULE_NAME, "[bCanInvertAxes] Error", , Err.Description
bCanInvertAxes = False
End Property