Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 234
0.00% covered (danger)
0.00%
0 / 11
CRAP
n/a
0 / 0
bloqueaDocumentos
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
210
bloqueaMovimientosOptimizado
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
930
bloqueaCuentaTMovs
0.00% covered (danger)
0.00%
0 / 87
0.00% covered (danger)
0.00%
0 / 1
342
actualizaGastosImportantes
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
actualizaWithdrawalsImportantes
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
actualizaLinksAlBancoLive
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
actualizaACuentasLive
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
genera_y_guarda_despliega_autorizaciones
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
ejecuta_transaccion_sql_desde_chron
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
guardaConsulta
0.00% covered (danger)
0.00%
0 / 59
0.00% covered (danger)
0.00%
0 / 1
132
marcaCerradoDocumentosExpirados
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
72
1<?php
2//VCA 04-Feb-2021 Estás funciones corren seguido. Son como demonios. Algunos se mandan llamar con su función asincrona
3function bloqueaDocumentos($documento='cheque', $do='SI')
4{
5    return; //Quitar esta función.
6
7    global $gIAParametros;
8
9    $commentSQL = " /** bloqueaDocumentos **/";
10
11    $ahora = new DateTime();
12    $ahora->modify("-".$gIAParametros['tiempo_para_borrar_documento']." minutes");
13
14    $sql=array();
15    //VCA está provocando deadlock por el trigger que actualiza el saldo
16    $sql[] = "SET @TRIGGER_DISABLED = 1;";
17
18    //$documentosPorBloquear = array();
19    //Bloquea Cheques y Pagarés
20
21    //$sql = "SELECT * FROM $documento WHERE puede_borrar='Si' OR puede_origen_cuentat='Si' OR alta_db<=".strit($ahora->format('Y-m-d H:i:s'))." OR set_origen_cuentat<=".strit($ahora->format('Y-m-d H:i:s'));
22    $docs_sql = "SELECT $commentSQL $documento"."_id,puede_borrar,puede_origen_cuentat,alta_db,set_origen_cuentat
23            FROM $documento
24            WHERE (puede_borrar='Si' OR puede_origen_cuentat='Si')
25            AND ( alta_db<=".strit($ahora->format('Y-m-d H:i:s'))."
26            OR set_origen_cuentat<=".strit($ahora->format('Y-m-d H:i:s')) . " )";
27
28    $documentosPorBloquear = ia_sqlArrayIndx($docs_sql);
29
30    //echo "<pre>".print_r($ahora, true)."</pre>";
31    //echo "<pre>".print_r($documentosPorBloquear, true)."</pre>";
32
33    if(is_array($documentosPorBloquear)) foreach($documentosPorBloquear as $vDocumento)
34    {
35        $updateDo = false;
36        if($vDocumento['puede_borrar'] == 'Si' && diferenciadeTiempo($vDocumento['alta_db'],'','minutos') >= $gIAParametros['tiempo_para_borrar_documento'])
37        {
38            //$documentosPorBloquear[$k]['puede_borrar'] = 'No';
39            $vDocumento['puede_borrar'] = 'No';
40            //$documentosPorBloquear[$k]['updateDo'] = true;
41            $updateDo = true;
42        }
43
44        if($vDocumento['puede_origen_cuentat'] == 'Si' && diferenciadeTiempo($vDocumento['set_origen_cuentat'],'','minutos') >= $gIAParametros['tiempo_para_cambiar_cuentat_origen'])
45        {
46            //$documentosPorBloquear[$k]['puede_origen_cuentat'] = 'No';
47            $vDocumento['puede_origen_cuentat'] = 'No';
48            //$documentosPorBloquear[$k]['updateDo'] = true;
49            $updateDo = true;
50        }
51
52        //if(array_key_exists('updateDo',$documentosPorBloquear[$k]))
53        if($updateDo)
54            $sql[]="UPDATE $commentSQL $documento SET puede_borrar=".strit($vDocumento['puede_borrar']).", puede_origen_cuentat=".strit($vDocumento['puede_origen_cuentat'])." WHERE ".$documento."_id=".strit($vDocumento[$documento."_id"]);
55        // ia_query("UPDATE $documento SET puede_borrar=".strit($documentosPorBloquear[$k]['puede_borrar']).", puede_origen_cuentat=".strit($documentosPorBloquear[$k]['puede_origen_cuentat'])." WHERE ".$documento."_id=".strit($documentosPorBloquear[$k][$documento."_id"]));
56        // ** // ia_query("UPDATE $documento SET puede_borrar=".strit($vDocumento['puede_borrar']).", puede_origen_cuentat=".strit($vDocumento['puede_origen_cuentat'])." WHERE ".$documento."_id=".strit($vDocumento[$documento."_id"]));
57
58    }
59
60
61    //Bloquea A cuentas de Cheques y Pagarés
62    $actas_sql = "SELECT $commentSQL $documento"."_pago_id,puede_borrar,alta_db FROM ".$documento."_pago WHERE puede_borrar='Si' AND alta_db<=".strit($ahora->format('Y-m-d H:i:s'));
63    $documentoPagosPorBloquear = ia_sqlArrayIndx($actas_sql);
64
65    //echo "<pre>".print_r($ahora, true)."</pre>";
66    //echo "<pre>".print_r($documentosPorBloquear, true)."</pre>";
67
68    if(is_array($documentoPagosPorBloquear)) foreach($documentoPagosPorBloquear as $vDocumentoPago)
69    {
70
71        if($vDocumentoPago['puede_borrar'] == 'Si' && diferenciadeTiempo($vDocumentoPago['alta_db'],'','minutos') >= $gIAParametros['tiempo_para_borrar_a_cuenta'])
72        {
73            $vDocumentoPago['puede_borrar'] = 'No';
74            $sql[]="UPDATE $commentSQL ".$documento."_pago SET puede_borrar='No'  WHERE ".$documento."_pago_id=".strit($vDocumentoPago[$documento."_pago_id"]);
75            //$vDocumentoPago['updateDo'] = true;
76            // ** // ia_query("UPDATE ".$documento."_pago SET puede_borrar='No'  WHERE ".$documento."_pago_id=".strit($vDocumentoPago[$documento."_pago_id"]));
77        }
78
79    }
80    $sql[] = "SET @TRIGGER_DISABLED = 0;";
81    if($do=='SI')
82    {
83        if(ia_transaction($sql))
84            ia_errores_a_dime();
85        return true;
86    }
87    else
88        return $sql;
89}
90
91function bloqueaMovimientosOptimizado($doc = "", $fuerza = false) {
92    if((array_key_exists('usuario_id',$_SESSION) && strpos($_SERVER['REQUEST_URI'], '/ajax/') === false && strpos($_SERVER['REQUEST_URI'], '/chron/') === false) || (!empty($doc) && $fuerza)) {
93        // $myLock = new ProcessLock();
94        // $myLock->release_all();
95        //$sql += bloqueaDocumentos('cheque', 'NO');
96        //$sql += bloqueaDocumentos('pagare', 'NO');
97        //$sql += marcaCerradoDocumentosExpirados('cheque', 'NO');
98        //$sql += marcaCerradoDocumentosExpirados('pagare', 'NO');
99        //$sql += marcaCerradoDocumentosExpirados('vale', 'NO');
100
101        $sql = [];
102        //VCA está provocando deadlock por el trigger que actualiza el saldo
103        $sql[] = "SET @TRIGGER_DISABLED = 1;";
104        $uri = $_SERVER['REQUEST_URI'];
105        if(stripos($uri, 'cuenta') !== false || ($doc == "cuenta" && $fuerza)) {
106            $sql = array_merge($sql, bloqueaCuentaTMovs('cuentat_a_banco', 'NO') );
107            $sql = array_merge($sql, bloqueaCuentaTMovs('cuentat_gasto', 'NO'));
108            $sql = array_merge($sql, bloqueaCuentaTMovs('cuentat_ingreso', 'NO'));
109            $sql = array_merge($sql, bloqueaCuentaTMovs('cuentat_transfer', 'NO'));
110        }
111        elseif(stripos($uri, '/compra.php') !== false || ($doc == "compra" && $fuerza)) {
112            $sql = array_merge($sql, bloqueaCuentaTMovs('compra', 'NO'));
113            $sql = array_merge($sql, bloqueaCuentaTMovs('compra_pago', 'NO'));
114        }
115        elseif(stripos($uri, '/cheque.php') !== false || ($doc == "cheque" && $fuerza)) {
116            $sql = array_merge($sql, bloqueaCuentaTMovs('cheque', 'NO'));
117            $sql = array_merge($sql, bloqueaCuentaTMovs('cheque_pago', 'NO'));
118            //$sql = array_merge($sql, bloqueaCuentaTMovs('supervisor_cheque', 'NO'));
119        }
120        elseif(stripos($uri, '/cheque_dd.php') !== false || ($doc == "cheque" && $fuerza)) {
121            $sql = array_merge($sql, bloqueaCuentaTMovs('cheque', 'NO'));
122            $sql = array_merge($sql, bloqueaCuentaTMovs('cheque_pago', 'NO'));
123            //$sql = array_merge($sql, bloqueaCuentaTMovs('supervisor_cheque', 'NO'));
124        }
125        elseif(stripos($uri, '/pagare.php') !== false || ($doc == "pagare" && $fuerza)) {
126            $sql = array_merge($sql, bloqueaCuentaTMovs('pagare', 'NO') );
127            $sql = array_merge($sql, bloqueaCuentaTMovs('pagare_pago', 'NO'));
128            //$sql = array_merge($sql, bloqueaCuentaTMovs('supervisor_pagare', 'NO'));
129        }
130        elseif(stripos($uri, '/vale.php') !== false || ($doc == "vale" && $fuerza)) {
131            $sql = array_merge($sql, bloqueaCuentaTMovs('vale', 'NO'));
132            $sql = array_merge($sql, bloqueaCuentaTMovs('vale_pago', 'NO'));
133        }
134        elseif(stripos($uri, 'fiduciario') !== false || ($doc == "fiduciario" && $fuerza)) {
135            $sql = array_merge($sql, bloqueaCuentaTMovs('fiduciario', 'NO'));
136        }
137        elseif(stripos($uri, 'bodega') !== false || ($doc == "bodega" && $fuerza)) {
138            $sql = array_merge($sql, bloqueaCuentaTMovs('bodega', 'NO'));
139            //$sql = array_merge($sql, bloqueaCuentaTMovs('supervisor_cheque', 'NO'));
140        }
141        //$sql = array_merge($sql, bloqueaCuentaTMovs('plantilla_cuentat_gasto', 'NO'));
142        //$sql = array_merge($sql, bloqueaFiduciarioContenedores('NO'));
143        $sql[] = "SET @TRIGGER_DISABLED = 0;";
144        $arrsqlData = array('sql' => $sql);
145        $arrsqlData = json_encode($arrsqlData);
146        async_ejecuta_transaccion_sql($arrsqlData);
147        extraeTCdeXE();
148
149        /*
150        //Para cuando haya updates.
151        $sql[]="UPDATE `banco_mov_tipo` SET `cash` = 'No' WHERE `banco_mov_tipo`.`banco_mov_tipo_id` =3;";
152        $sql[]="UPDATE `banco_mov_tipo` SET `deposit` = 'No' WHERE `banco_mov_tipo`.`banco_mov_tipo_id` =2;";
153        ia_transaction($sql);*/
154    }
155}
156
157function bloqueaCuentaTMovs($tipoMov='cuentat_gasto', $do='SI')
158{
159    global $gIAParametros;
160    $sql=array();
161    //VCA está provocando deadlock por el triggers en update de cheque, pagare y vale
162    $sql[] = "SET @TRIGGER_DISABLED = 1;";
163    $ahora = new DateTime();
164    switch($tipoMov)
165    {
166        case "cuentat_gasto":
167            $ahora->modify("-".$gIAParametros['tiempo_para_borrar_gasto_cuentat']." minutes");
168            $sql[]="UPDATE cuentat_gasto SET puede_borrar='No' WHERE puede_borrar='Si' AND fecha_capturado<".strit($ahora->format('Y-m-d H:i:s'));
169            break;
170
171        case "cuentat_ingreso":
172            $ahora->modify("-".$gIAParametros['tiempo_para_borrar_gasto_cuentat']." minutes");
173            $sql[]="UPDATE cuentat_ingreso SET puede_borrar='No' WHERE puede_borrar='Si' AND alta_db<".strit($ahora->format('Y-m-d H:i:s'));
174            break;
175
176        case "cuentat_a_banco":
177            $ahora->modify("-".$gIAParametros['tiempo_para_borrar_transfer_cuentat_banco']." minutes");
178            $sql[]="UPDATE cuentat_a_banco SET puede_borrar='No' WHERE puede_borrar='Si' AND fecha_capturado<".strit($ahora->format('Y-m-d H:i:s'));
179            break;
180
181        case "compra_pago":
182            $ahora->modify("-".$gIAParametros['tiempo_para_borrar_a_cuenta']." minutes");
183            $sql[]="UPDATE compra_pago SET puede_borrar='No' WHERE puede_borrar='Si' AND fecha_capturado<".strit($ahora->format('Y-m-d H:i:s'));
184            break;
185
186        case "cheque_pago":
187            $ahora->modify("-".$gIAParametros['tiempo_para_borrar_a_cuenta']." minutes");
188            $sql[]="UPDATE cheque_pago SET puede_borrar='No' WHERE puede_borrar='Si' AND fecha_capturado<".strit($ahora->format('Y-m-d H:i:s'));
189            break;
190
191        case "pagare_pago":
192            $ahora->modify("-".$gIAParametros['tiempo_para_borrar_a_cuenta']." minutes");
193            $sql[]="UPDATE pagare_pago SET puede_borrar='No' WHERE puede_borrar='Si' AND fecha_capturado<".strit($ahora->format('Y-m-d H:i:s'));
194            break;
195
196        case "vale_pago": // VALE_PAGO_MULTIPLE
197            $ahora->modify("-".$gIAParametros['tiempo_para_borrar_a_cuenta']." minutes");
198            $sql[]="UPDATE vale_pago SET puede_borrar='No' WHERE puede_borrar='Si' AND fecha_capturado<".strit($ahora->format('Y-m-d H:i:s'));
199            break;
200
201        case "compra":
202            /** Bloquea para borrar **/
203            $ahora->modify("-".$gIAParametros['tiempo_para_borrar_documento']." minutes");
204            $sql[]="UPDATE compra SET puede_borrar='No' WHERE puede_borrar='Si' AND alta_db<".strit($ahora->format('Y-m-d H:i:s'));
205
206            /** Cierra documentos **/
207            $ahora = new DateTime();
208            $ahora->modify("-".$gIAParametros['tiempo_para_cerrar_documento']." minutes");
209            $sql[]="UPDATE compra SET abierto_por = '', abierto_el = NULL WHERE abierto_por <> '' AND abierto_el<".strit($ahora->format('Y-m-d H:i:s'));
210            break;
211
212        case "cheque":
213            /** Bloquea para borrar **/
214            $ahora->modify("-".$gIAParametros['tiempo_para_borrar_documento']." minutes");
215            $sql[]="UPDATE cheque SET puede_borrar='No', bloqueado_el=NOW() WHERE puede_borrar='Si' AND alta_db<".strit($ahora->format('Y-m-d H:i:s'));
216
217            /** Bloquea cuentat origen **/
218            $ahora = new DateTime();
219            $ahora->modify("-".$gIAParametros['tiempo_para_cambiar_cuentat_origen']." minutes");
220            $sql[]="UPDATE cheque SET puede_origen_cuentat='No' WHERE puede_origen_cuentat='Si' AND set_origen_cuentat<".strit($ahora->format('Y-m-d H:i:s'));
221
222            /** Cierra documentos **/
223            $ahora = new DateTime();
224            $ahora->modify("-".$gIAParametros['tiempo_para_cerrar_documento']." minutes");
225            $sql[]="UPDATE cheque SET abierto_por = '', abierto_el = NULL WHERE abierto_por <> '' AND abierto_el<".strit($ahora->format('Y-m-d H:i:s'));
226            break;
227
228        case "pagare":
229            $ahora->modify("-".$gIAParametros['tiempo_para_borrar_documento']." minutes");
230            $sql[]="UPDATE pagare SET puede_borrar='No', bloqueado_el=NOW() WHERE puede_borrar='Si' AND alta_db<".strit($ahora->format('Y-m-d H:i:s'));
231
232            /** Cierra documentos **/
233            $ahora = new DateTime();
234            $ahora->modify("-".$gIAParametros['tiempo_para_cerrar_documento']." minutes");
235            $sql[]="UPDATE pagare SET abierto_por = '', abierto_el = NULL WHERE abierto_por <> '' AND abierto_el<".strit($ahora->format('Y-m-d H:i:s'));
236            break;
237
238        case "vale":
239            $ahora->modify("-".$gIAParametros['tiempo_para_borrar_documento']." minutes");
240            $sql[]="UPDATE vale SET puede_cambiar_tipo_cambio='No', bloqueado_el=NOW() WHERE puede_cambiar_tipo_cambio='Si' AND conversion_ultimo_cambio<".strit($ahora->format('Y-m-d H:i:s'));
241            /** Cierra documentos **/
242            //$ahora = new DateTime();
243            //$ahora->modify("-".$gIAParametros['tiempo_para_cerrar_documento']." minutes");
244            $sql[]="UPDATE vale SET abierto_por = '', abierto_el = NULL WHERE abierto_por <> '' AND abierto_el<".strit($ahora->format('Y-m-d H:i:s'));
245            break;
246
247        case "fiduciario":
248            $ahora->modify("-".$gIAParametros['tiempo_para_bloquear_contenedor_fiduciario']." hours");
249            $fechaCapturados=$ahora->format('Y-m-d H:i:s');
250            $sql[]="UPDATE fiduciario_contenedor SET puede_borrar='No' WHERE
251                (fecha_capturado IS NOT NULL AND puede_borrar='Si' AND fecha_capturado<'$fechaCapturados') OR
252                (fecha_capturado IS NULL AND puede_borrar='Si' AND numero_contenedor<>'' AND monto_garantia > 0 AND alta_db<'$fechaCapturados')";
253            break;
254
255        case "cuentat_transfer":
256            $ahora->modify("-".$gIAParametros['tiempo_para_cancelar_transfer_cuentat']." minutes");
257            $sql[]="UPDATE cuentat_transfer SET puede_borrar='No' WHERE status='Transfer accepted' AND puede_borrar='Si' AND fecha_recibe<".strit($ahora->format('Y-m-d H:i:s'));
258            break;
259
260        case "plantilla_cuentat_gasto":
261            $mesActual = date("Y-m");
262            $primerdiamesActual = date('Y-m-01');
263            $ultimodiamesActual = date('Y-m-t');
264            $lunes = date('Y-m-d', strtotime('monday this week'))." 00:00:00";
265            $domingo = date('Y-m-d', strtotime('sunday this week'))." 23:59:59";
266            $now = $ahora->format('Y-m-d H:i:s');
267            $sql[]="UPDATE plantilla_cuentat_gasto AS pc
268                    SET pc.pausado=IF(pc.fecha_inicio_validez > '$now' OR
269                    pc.fecha_expiracion < '$now' OR
270                    (pc.num_veces_utilizar > 0 AND pc.num_veces_utilizado > pc.num_veces_utilizar) OR
271                    (pc.periodicidad_mensual > 0 AND
272                        (SELECT COUNT(c.cuentat_gasto_id) FROM cuentat_gasto AS c
273                        WHERE c.activo='Si' AND c.fecha between '$primerdiamesActual%' AND '$ultimodiamesActual' AND
274                        c.plantilla_cuentat_gasto_id=pc.plantilla_cuentat_gasto_id) >= pc.periodicidad_mensual) OR
275                    (pc.periodicidad_semanal > 0 AND
276                        (SELECT COUNT(c.cuentat_gasto_id) FROM cuentat_gasto AS c
277                        WHERE c.activo='Si' AND c.fecha BETWEEN '$lunes' AND '$domingo' AND
278                        c.plantilla_cuentat_gasto_id=pc.plantilla_cuentat_gasto_id) >= pc.periodicidad_semanal), 'Si', 'No')
279                    WHERE pc.activa='Si'";
280
281            break;
282
283        case "bodega":
284            /** Bloquea notas con lock = 1 **/
285            //if($gIAParametros['bloquear_notas_automaticamente'] == 'No')
286            //    break;
287            NotaBodega::lockTiempoSuperUser();
288            NotaBodega::lockPorTiempoNotaBodega();
289            NotaBodega::cronLockTrasladoMatch();
290            //$ahora->modify("-".$gIAParametros['tiempo_para_editar_nota_bodega']." minutes");
291            //$sql[]="UPDATE nota_bodega SET `lock`='1', `lock_el`=NOW() WHERE `lock`='0' AND alta_db<".strit($ahora->format('Y-m-d H:i:s'));
292
293            break;
294
295    }
296
297    $sql[] = "SET @TRIGGER_DISABLED = 0;";
298    if($do=='SI')
299    {
300        if(ia_transaction($sql))
301            ia_errores_a_dime();
302        return true;
303    }
304    else
305        return $sql;
306}
307
308function actualizaGastosImportantes()
309{
310    //Para rápido aqui meto los gastos de cuentat pendientes e importantes
311    //Gastos de CuentaT pendientes e importantes
312    $sql15 = "SELECT SUM(CASE WHEN pendiente='Si' THEN 1 ELSE 0 END) AS pendientes, SUM(CASE WHEN importante='Si' THEN 1 ELSE 0 END) AS importantes FROM cuentat_gasto WHERE activo='Si'";
313
314    $CtaTPI = ia_singleton($sql15);
315
316    //Gastos de CuentaT
317    $sql[] = "INSERT INTO campos_exists (campo_id, valor, tabla_exists, tabla_origen) VALUES(1, $CtaTPI[pendientes],    'pendiente',    'cuentat_gasto') ON DUPLICATE KEY UPDATE valor=$CtaTPI[pendientes]";
318    $sql[] = "INSERT INTO campos_exists (campo_id, valor, tabla_exists, tabla_origen) VALUES(1, $CtaTPI[importantes],   'importante',   'cuentat_gasto') ON DUPLICATE KEY UPDATE valor=$CtaTPI[importantes]";
319
320    ia_transaction($sql);
321}
322
323function actualizaWithdrawalsImportantes()
324{
325    //Para rápido aqui meto los Withdrawals pendientes e importantes
326    //Withdrawals pendientes e importantes
327    $sql16 = "SELECT SUM(CASE WHEN pendiente='Si' THEN 1 ELSE 0 END) AS pendientes, SUM(CASE WHEN importante='Si' THEN 1 ELSE 0 END) AS importantes , SUM(CASE WHEN repetido='Si' THEN 1 ELSE 0 END) AS repetidos FROM banco_cuenta_mov WHERE es = 'retiro' AND withdrawal > 0";
328
329    $WithPI = ia_singleton($sql16);
330
331    //Withdrawals
332    $sql[] = "INSERT INTO campos_exists (campo_id, valor, tabla_exists, tabla_origen) VALUES(1, $WithPI[pendientes],    'pendiente',    'withdrawals_de_banco') ON DUPLICATE KEY UPDATE valor=$WithPI[pendientes]";
333    $sql[] = "INSERT INTO campos_exists (campo_id, valor, tabla_exists, tabla_origen) VALUES(1, $WithPI[importantes],   'importante',   'withdrawals_de_banco') ON DUPLICATE KEY UPDATE valor=$WithPI[importantes]";
334    $sql[] = "INSERT INTO campos_exists (campo_id, valor, tabla_exists, tabla_origen) VALUES(1, $WithPI[repetidos],       'repetido',   'withdrawals_de_banco') ON DUPLICATE KEY UPDATE valor=$WithPI[repetidos]";
335
336    ia_transaction($sql);
337}
338
339function actualizaLinksAlBancoLive($force='NO')
340{
341    $sql = "";
342    if($force == 'SI')
343    {
344        $hay = ia_singleread("SELECT COUNT(*) FROM links_al_banco_live");
345        if(!$hay)
346            $sql = "CALL actualiza_links_al_banco_live('')";
347    }
348    else
349        $sql = "CALL actualiza_links_al_banco_live('')";
350    if(!empty($sql))
351        ia_query($sql);
352}
353
354function actualizaACuentasLive($force='NO')
355{
356    $sql = "";
357    if($force == 'SI')
358    {
359        $hay = ia_singleread("SELECT COUNT(*) FROM actualiza_a_cuentas_live");
360        if(!$hay)
361            $sql = "CALL actualiza_a_cuentas_live()";
362    }
363    else
364        $sql = "CALL actualiza_a_cuentas_live()";
365    if(!empty($sql))
366        ia_query($sql);
367}
368
369/**
370 * @param array $sqlData array('id'=>"ID del doc", 'table'=>'doc', 'sql'=>array())
371 */
372function genera_y_guarda_despliega_autorizaciones($sqlData = array('id'=>"", 'table'=>'', 'sql'=>array()))
373{
374
375    $doc_id = $sqlData->doc."_id";
376    $app_doc = "app_".$sqlData->doc;
377    $ins_doc = new $app_doc;
378
379    $ins_doc->id = $sqlData->id;
380    $ins_doc->h = 'r';
381    $ins_doc->enDB=$ins_doc->values=$ins_doc->read_sql($doc_id, $ins_doc->h);
382
383    $html = $ins_doc->despliega_autorizaciones();
384
385    $sqlData->sql = !property_exists($sqlData, 'sql') || !is_array($sqlData->sql) ? array() : $sqlData->sql;
386
387    $sqlData->sql[] = "UPDATE $sqlData->doc SET html_verified=".strit($html) ." WHERE ". $sqlData->doc ."_id=".strit($sqlData->id);
388
389
390 /*   $myFile = "genera_y_guarda_despliega_autorizaciones.txt";
391    $fh = fopen($myFile, 'w') or die("can't open file");
392    $bleh = "\r\n\r\n<pre>params: ".print_r($sqlData, true)."</pre>";
393    $bleh .= "\r\n\r\n<pre>doc: ".print_r($ins_doc, true)."</pre>";
394    fwrite($fh, $bleh);
395    fclose($fh);*/
396
397//    $sql = $sqlData->sql;
398
399    if (ia_transaction($sqlData->sql))
400        ia_errores_a_dime();
401
402}
403
404function ejecuta_transaccion_sql_desde_chron($sqlData)
405{
406    $sql = $sqlData->sql;
407
408    if (ia_transaction($sql))
409        ia_errores_a_dime();
410
411}
412
413function guardaConsulta($sqlData)
414{
415    global $gIAsql;
416    global $vx_debug;
417
418    $gIAsql['usr_err']=true;
419    $gIAsql['trace']=true;
420
421    $tempTable4Sum = $memTable4Sum = $sqlData->tempTable4Sum;
422    $sql = $sqlData->sql;
423    $sumasGridServer = $sqlData->sumasGridServer;
424    $func = $sqlData->func;
425    $sqllimit = $sumasGridServer->sqllimit;
426
427    /**$forceIndex = $sumasGridServer->forceIndex;**/
428
429
430
431    $sqlmt4s = "";
432    $sqlimt4s = "";
433    $sqlat4s = "";
434    $sqldi4s = "";
435    $sqldi4sstr = "";
436    $sqldibcm[] = "";
437    $tablaOriginal = $sumasGridServer->tablaOriginal;
438
439    if($sumasGridServer->demasiadasLineasGrid == "SI")
440    {
441        $tempTable4Sum = "aa_tmp".ia_guid();
442
443        if($sumasGridServer->iactbl == $sumasGridServer->tablaOriginal) {
444            $sql = "SELECT /**guardaConsulta demasiadasLineasGrid **/ * " . strstr($sql, " FROM $tablaOriginal ");
445        }
446
447        $sqltt4s = "CREATE TEMPORARY TABLE $tempTable4Sum $sql";
448        ia_query($sqltt4s);
449
450        //hack, no se me ocurre nada
451        $tablaOriginal = $tablaOriginal == "doctos" ? "doctos_schema" : $tablaOriginal;
452        $sqlmt4s = "CREATE TABLE $memTable4Sum LIKE $tablaOriginal";
453        ia_query($sqlmt4s);
454
455
456        //Por el indice del banco.
457        if($tablaOriginal == 'banco_cuenta_mov')
458        {
459            $sqldibcm[] = "DROP INDEX banco_1 ON $memTable4Sum";
460            //$sqldibcm[] = "DROP INDEX banco_3 ON $memTable4Sum";
461            ia_transaction($sqldibcm);
462        }
463
464        if($tablaOriginal == 'cheque')
465        {
466            $sqldibcm[] = "DROP INDEX default_grid_sort ON $memTable4Sum";
467            //$sqldibcm[] = "DROP INDEX banco_3 ON $memTable4Sum";
468            ia_transaction($sqldibcm);
469        }
470
471        //Sugerencia de Pepe ENGINE=InnoDB. Jala mucho más rápido con memory
472
473        $index = ia_sqlArrayIndx("SELECT INDEX_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = 'vitex' AND TABLE_NAME='$memTable4Sum' AND INDEX_TYPE='FULLTEXT'");
474        foreach($index as $k=>$v)
475        {
476            $sqldi4s = "DROP INDEX $v[INDEX_NAME] ON $memTable4Sum";
477            ia_query($sqldi4s);
478            $sqldi4sstr .= " | $sqldi4s";
479        }
480
481        $sqldi4sstr = substr($sqldi4sstr, 3);
482
483        $sqlat4s = "ALTER TABLE $memTable4Sum ENGINE=MEMORY";
484        ia_query($sqlat4s);
485
486
487
488        $sqlimt4s = "INSERT INTO $memTable4Sum SELECT * FROM $tempTable4Sum";
489        ia_query($sqlimt4s);
490
491        ia_errores_a_dime();
492    }
493    else
494    {
495        if($sumasGridServer->iact == "iacase") {
496            $sql = "SELECT /**guardaConsulta **/ * " . strstr($sql, " FROM $tablaOriginal ");
497        }
498
499        if($sumasGridServer->iaGridInicial == "SI")
500            $sqltt4s = "CREATE TEMPORARY TABLE $tempTable4Sum $sql $sumasGridServer->iaGIsqllimit";
501        else
502            $sqltt4s = "CREATE TEMPORARY TABLE $tempTable4Sum $sql";
503        ia_query($sqltt4s);
504    }
505
506    if($vx_debug)
507    {
508        //13-agosto-2019
509        global $gWebDir;
510        $myFile = "C:\\wamp\\www\\$gWebDir\\backoffice\\txt\\guardaConsulta.txt";
511        $fh = fopen($myFile, 'w') or die("can't open file");
512        $bleh = "\r\n\r\nsql<pre>$sql</pre>";
513        $bleh = "\r\n\r\nsqltt4s:<pre>$sqltt4s</pre>";
514        $bleh .= "\r\n\r\nsqlmt4s<pre>$sqlmt4s</pre>";
515        $bleh .= "\r\n\r\nsqldi4s<pre>$sqldi4sstr</pre>";
516        $bleh .= "\r\n\r\nsqlat4s<pre>$sqlat4s</pre>";
517        $bleh .= "\r\n\r\nsqlimt4s<pre>$sqlimt4s</pre>";
518        $bleh .= "\r\n\r\nsqldibcm:<pre>".print_r($sqldibcm, true)."</pre>";
519        $bleh .= "\r\n\r\nsqlData:<pre>".print_r($sqlData, true)."</pre>";
520        fwrite($fh, $bleh);
521        fclose($fh);
522    }
523    //fileputcontents con lock_ex
524}
525
526function marcaCerradoDocumentosExpirados($doc='', $do='SI')
527{
528    if(empty($doc))
529        $doc = 'cheque';
530
531    $sql=array();
532
533    $docs_sql = "SELECT ".$doc."_id FROM $doc WHERE abierto_por <> ''";
534    $docs_abiertos = ia_sqlArrayIndx($docs_sql);
535
536    //echo "<pre>".print_r($docs_abiertos,true)."</pre>";
537    $sql = array();
538    $sql[] = "SET @TRIGGER_DISABLED = 1;";
539
540    if(!empty($docs_abiertos) && is_array($docs_abiertos)) foreach($docs_abiertos as $k=>$doc_abierto)
541    {
542        $doc_status = estatusDocumento($doc, $doc_abierto[$doc."_id"]);
543        if($doc_status['status'] == 'EXPIRADO')
544            $sql[]=marcaCerradoDocumento($doc, $doc_abierto[$doc."_id"], 'NO');
545    }
546    $sql[] = "SET @TRIGGER_DISABLED = 0;";
547
548    if($do=='SI')
549    {
550        if(ia_transaction($sql))
551            ia_errores_a_dime();
552        return true;
553    }
554    else
555        return $sql;
556}