Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 930
0.00% covered (danger)
0.00%
0 / 39
CRAP
n/a
0 / 0
preparaRemarksBCM
0.00% covered (danger)
0.00%
0 / 54
0.00% covered (danger)
0.00%
0 / 1
756
arreglaRemarksBCM
0.00% covered (danger)
0.00%
0 / 174
0.00% covered (danger)
0.00%
0 / 1
6480
isContainer
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
buscaContenedorPorImporte
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
gastoBuscar
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
encuentraTipoRemarksBCM
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
56
marcaRemarksDuplicados
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
encuentraContenedor
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
110
CalculaBancoCuentaSaldodeunArraydeMovimientos
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
CalculaBancoCuentaSaldodesdeunMovimiento
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
110
HazLinkBancarioManualIncompleto
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
30
esBancoChina
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
generaaCuentasdeBancoMov
0.00% covered (danger)
0.00%
0 / 75
0.00% covered (danger)
0.00%
0 / 1
1980
generayGuardaaCuentasdeBancoMov
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
72
generaListadoLinksBCM
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
380
generayGuardaListadoLinksBCM
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
72
bancoCuentaMovs
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
obtenSQLBancoCuentaMovs
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
banco_cuenta_saldos_refresh
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
preparaTablaSaldosBanco
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
30
obtenNombreBancoCuenta
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
genera_banco_cuenta_saldos
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
encuentraSubcategoria
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
quieroBuscarGasto
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
552
generaLinkAAcuentaT
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
42
leeIngresosEmpesas
0.00% covered (danger)
0.00%
0 / 71
0.00% covered (danger)
0.00%
0 / 1
930
table_header_vb
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
182
showCuenta
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
156
table_row_vb
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
72
table_footer_vb
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
leeFiduciariosEmpesas
0.00% covered (danger)
0.00%
0 / 68
0.00% covered (danger)
0.00%
0 / 1
870
fid_table_header_vb
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
156
fid_showCuenta
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
156
fid_table_row
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
72
fid_table_footer
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
buscaEnTablaSobreCampoElValor
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
quitaIndiceRepetidoDeRepetidos
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
90
buscaRepetidoSAT
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
isSAT
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3function preparaRemarksBCM($bcm_id="", $remarks_ori="", $txt_color="", $blink="", &$remarks_ok=array(), $buscaRep=true, $doSQL=true, $debug=false, $monto = 0.00, $fuerza_titulo = "")
4{
5    $remarks = "";
6
7//    if(empty($remarks_ori))
8//        return $remarks;
9
10    $infoDebug = "";
11
12    if($debug)
13        $infoDebug .= "<hr/><ul><li>remarks_ori: ".nl2br($remarks_ori);
14
15//    $remarks_ori = strip_tags($remarks_ori);
16
17    if($debug)
18        $infoDebug .= "\r\n<li>remarks_ori strip_tagged: ".nl2br($remarks_ori);
19
20    $arrReservadas = array("COMISION BANCARIA");
21
22    foreach ($arrReservadas as $res) {
23        if (strpos($remarks_ori, $res) !== FALSE) {
24
25            return $remarks = $remarks_ori;
26
27        }
28    }
29
30    $arrRemarks = preg_split('/\r\n|\r|\n/', $remarks_ori);
31
32
33
34    if(!sizeof($arrRemarks))
35        return $remarks;
36
37    if($debug)
38        $infoDebug .= "\r\n<li><pre>arrRemarks:".print_r($arrRemarks, true)."</pre>";
39
40    $titulo=""; $benefic=""; $descripcion="";
41
42    //Recorremos el arreglo para encontrar titulo, beneficiario y descripción (de aquí sacamos el contenedor y lo demás para buscar los repetidos
43    $k = 0;
44
45    if($debug)
46        $infoDebug .= "\r\n<ol>";
47
48    foreach($arrRemarks as $line)
49    {
50        $done = false;
51        $line = vx_trim($line);
52        //no debería de incrementar $k si la línea está vacía.
53        //OJO VCA 20-02-2020
54        if(strlen($line) == 0) {
55            $descripcion .= PHP_EOL;
56            continue;
57        }
58
59        if($debug)
60            $infoDebug .= "\r\n<li> $line";
61
62        $carac = preg_match("/([;:,])/i", $line) === 1;
63
64        if(!$carac && !strlen($titulo) && $k==0) {
65            $titulo .= $line;
66            $done = true;
67            $k++;
68            continue; // que ya no revise las siguientes condiciones.
69        }
70        $k++;
71        /** Si tiene una coma, punto, punto y coma o dos puntos, es el beneficiario */
72        if($carac) {
73            if(!strlen($benefic))
74            {
75                $benefic .= $line.PHP_EOL;
76                $done = true;
77                continue;
78            }
79        }
80
81        $descripcion .= $done ? "" : $line.PHP_EOL;
82
83    }
84
85    $titulo = $fuerza_titulo !== false ? $fuerza_titulo : $titulo;
86    $descripcion = $fuerza_titulo !== false ? $remarks_ori : $descripcion;
87    $benefic = $fuerza_titulo !== false ? "" : $benefic;
88
89    if($debug)
90        $infoDebug .= "\r\n</ol>";
91
92    if($debug)
93        $infoDebug .= "PREVIO: \r\n<li>titulo: $titulo"."<li>benefic: $benefic"."<li>descripcion: $descripcion<br><br></ul>";
94
95    $remarks_ok = arreglaRemarksBCM($titulo, $benefic, $descripcion, $bcm_id, $buscaRep, $doSQL, $debug, $txt_color, $blink, $infoDebug, $fuerza_titulo);
96
97    if ($debug)
98        $infoDebug .= "\r\n<pre>preparaRemarksBCM remarks_ok: " .($fuerza_titulo === false ? " ms" : "me"). print_r($remarks_ok, true) . "</pre>";
99
100    if($debug)
101    {
102        //06-Abril-2020
103        global $gWebDir;
104        $myFile = "C:\\wamp\\www\\$gWebDir\\backoffice\\txt\\$bcm_id.txt";
105        $fh = fopen($myFile, 'a+') or die("can't open file");
106        $bleh = $infoDebug;
107        fwrite($fh, $bleh);
108        fclose($fh);
109    }
110    if($debug)
111        $infoDebug .= "POST: \r\n<li>titulo: $remarks_ok[titulo]"."<li>benefic: [benefic]"."<li>descripcion: $remarks_ok[descripcion]<br><br></ul>";
112    return $remarks_ok["titulo"] . $remarks_ok["benefic"] . $remarks_ok["descripcion"];
113}
114
115function arreglaRemarksBCM($titulo="", $benefic="", $descripcion="", $bcm_id="", $buscaRep=true, $doSQL=true, $debug=false, $txt_color="", $blink="", &$infoDebug = "", $fuerza_titulo = "")
116{
117    $remarks_ok = array(
118        'ori_remarks' => $titulo . $benefic . $descripcion,
119        'ori_titulo' => $titulo,
120        'categoria' => $titulo,
121        'sub_categoria' => encuentraSubcategoria($descripcion),
122        'contenedor' => '',
123        'ori_benefic' => $benefic,
124        'ori_descripcion' => $descripcion,
125        'titulo' => $titulo,
126        'benefic' => $benefic,
127        'descripcion' => $descripcion,
128        'link_vale' => "",
129        'cont' => array(),
130        'current_duplicates' => array(),
131        'sql' => array());
132
133    $sqlUpdt = array();
134
135    $remarks = $remarks_ok['ori_remarks']; //strip_tags($remarks_ok['ori_remarks']); //Decidir con qué remarks vamos a trabajar.
136    $cont = array();
137    $naviera = false;
138
139    $hayCont = encuentraContenedor($remarks_ok['ori_remarks'], $remarks_ok['cont'], $naviera);
140    $remarks_ok['contenedor'] = $hayCont == true && array_key_exists(0, $remarks_ok['cont']) ? $remarks_ok['cont'][0] : '';
141
142    //Encontramos Naviera y ponemos link_vale en NAVIERA.
143    if ($naviera !== false && $fuerza_titulo === false) {
144        $remarks_ok['link_vale'] = 'NAVIERA';
145    }
146
147    $tipoNR = array();
148    if($fuerza_titulo === false) {
149        $tieneTipoNR = encuentraTipoRemarksBCM($remarks, $tipoNR); //Según el diccionario de datos para gastos del banco.
150
151        if ($debug)
152            $infoDebug .= "\r\n<pre>TipoNR: " . print_r($tipoNR, true) . "</pre>";
153
154        if ($tieneTipoNR !== false) {
155            if ($tipoNR['titulo'] != $remarks_ok['ori_titulo']) {
156                $remarks_ok['descripcion'] = (empty($remarks_ok['titulo']) ? "" : $remarks_ok['titulo']) . PHP_EOL . $remarks_ok['descripcion'];
157                $remarks_ok['titulo'] = $tipoNR['titulo'];
158            }
159        }
160    }
161    //Subtitulo en titulo
162    $subentitulo = "";
163    if (array_key_exists('st', $tipoNR) && strlen($tipoNR['st']) && $tipoNR['resalta_subtitulo'] == 'Si')
164        $subentitulo = ' <strong class="txt16px txt_centered txt_color_blue">' . $tipoNR['st'] . '</strong>';
165
166    $remarks_ok['titulo'] = empty($remarks_ok['titulo']) ? "" : '<strong class="txt18pxfr txt_bold_red txt_centered ' . ($fuerza_titulo !== false ? 'fuerza_titulo' : '') . ' ' . $txt_color . ' ' . $blink . '" style="min-width: 335px;">' . $remarks_ok['titulo'] . '</strong>' . $subentitulo . PHP_EOL;
167
168    //NO hay que buscar los repetidos. Pero ya arregló los remarks según su tipo.
169    if ($debug)
170        $infoDebug .= "\r\n<pre>arreglaRemarksBCM remarks_ok: " . print_r($remarks_ok, true) . "</pre>";
171
172    if (!$buscaRep) {
173        return $remarks_ok;
174    }
175
176    /*
177     * Pasos previos para liberar repetidos no relacionados
178     * */
179    $sql_current_bcm = "SELECT * FROM banco_cuenta_mov WHERE banco_cuenta_mov_id = '$bcm_id'";
180    $current_bcm = ia_singleton($sql_current_bcm);
181
182    if (!quieroBuscarGasto($remarks_ok['categoria'], $remarks_ok['sub_categoria'], $remarks_ok['contenedor'], $current_bcm['withdrawal'] ?? 0.00)) {
183        $remarks_ok['sql'] = $sqlUpdt;
184        return $remarks_ok;
185    }
186
187
188
189    $repetidos = trim($current_bcm['mov_repetido_id'] ?? '');
190    $explode_repetidos = explode(",", $repetidos);
191
192    $remarks_ok['current_duplicates'] = $repetidos !== "" ? $explode_repetidos : $remarks_ok['current_duplicates'];
193
194    if (count($remarks_ok['current_duplicates']) > 0) {
195        foreach ($remarks_ok['current_duplicates'] as $bcmid_repetido) {
196            if ($bcm_id !== $bcmid_repetido)
197            {
198                $repetido = ia_singleton("SELECT * FROM banco_cuenta_mov WHERE banco_cuenta_mov_id = '$bcmid_repetido'");
199
200                if(!is_array($repetido) || empty($repetido))
201                    continue;
202//                $repetido['remarks'] = str_replace("txt_bold_red txt_underline", "", $repetido['remarks']);
203                $new_remarks = $repetido['remarks'];
204
205                $repetidos = explode(",", trim($repetido['mov_repetido_id']));
206                // Comprueba que el BCM se encuentre en los repetidos del repetido
207                if (in_array($bcm_id, $repetidos)){
208                    // Se obtiene la posicion para eliminarlo de repetidos del repetido
209                    $position = array_search($bcm_id, $repetidos);
210                    unset($repetidos[$position]);
211                    // Se crean nuevos repetidos del repetido
212                    $nuevos_repetidos = implode(",", $repetidos);
213                    // Se valida que repetidos sea mayor a 1 para que pueda ser repetido y no se repita con el mismo
214                    if (count($repetidos) < 2) {
215//                        if ($nuevos_repetidos == $bcmid_repetido){
216                        $new_remarks = str_replace("txt_bold_red txt_underline", "", $repetido['remarks']);
217                        $sqlUpdt[] = "UPDATE banco_cuenta_mov SET repetido = 'No', mov_repetido_id = '', remarks = ". strit(ltrim(trim($new_remarks))) ." WHERE banco_cuenta_mov_id = '$bcmid_repetido'";
218//                        }
219                    } else {
220                        $sqlUpdt[] = "UPDATE banco_cuenta_mov SET mov_repetido_id = '$nuevos_repetidos' WHERE banco_cuenta_mov_id = '$bcmid_repetido'";
221                    }
222                }
223//                print_r($repetido['mov_repetido_id']);
224//                exit;
225//                $new_remarks = $repetido['remarks'];
226//                $sqlUpdt[] = "UPDATE banco_cuenta_mov SET repetido = 'No', mov_repetido_id = '', remarks = ". strit(ltrim(trim($new_remarks))) ." WHERE banco_cuenta_mov_id = '$bcmid_repetido'";
227            } else {
228                $sqlUpdt[] = "UPDATE banco_cuenta_mov SET repetido = 'No', mov_repetido_id = '', remarks = ". strit(ltrim(trim($remarks_ok['titulo']))) ." WHERE banco_cuenta_mov_id = '$bcmid_repetido'";
229            }
230        }
231    }
232    /*
233     * Fin de pasos previos para liberar repetidos no relacionados
234     * */
235
236    $exceptions = ['CONTENEDOR'];
237    $buscaContenedoresRepetidosPorImporte = true; // Para activar el proceso de busqueda de contenedores repetidos por importe, cambiar a true.
238    $container_duplicates = null;
239    if (in_array(trim($remarks), $exceptions)) {
240        // Busca repetidos por importe de tipo contendor. Si no hay repetido por importe e valor es null
241        if ($buscaContenedoresRepetidosPorImporte === true) {
242            $container_duplicates = null;
243            if (isContainer($remarks)) {
244                $container_duplicates = buscaContenedorPorImporte($bcm_id, $current_bcm['withdrawal']);
245                if ($container_duplicates != null){
246                    $duplicates = explode(",", $container_duplicates);
247                    $repIDs = $container_duplicates . ",$bcm_id";
248                    foreach ($duplicates as $bcm_id_repetido) {
249                        $sqlUpdt[] = "UPDATE banco_cuenta_mov SET repetido='Si', mov_repetido_id=" . strit($repIDs) . " WHERE banco_cuenta_mov_id=" . strit($bcm_id_repetido);
250                    }
251                    $sqlUpdt[] = "UPDATE banco_cuenta_mov SET repetido='Si', mov_repetido_id=" . strit($repIDs) . ", remarks=".strit(ltrim(trim($remarks_ok['titulo']))). " WHERE banco_cuenta_mov_id=" . strit($bcm_id);
252                }
253                $remarks_ok['sql'] = $sqlUpdt;
254                return $remarks_ok;
255            }
256        }
257    }
258
259    $buscar = array('VALOR_FACTURA' => array('enc'=>false,'val'=>""),
260        'FACTURA' => array('enc'=>false,'val'=>""),
261        'PEDIMENTO' => array('enc'=>false,'val'=>""),
262        'CONTENEDOR' => array('enc'=>false,'val'=>array(),'dep'=>array('MONTO' => array('enc'=>false,'val'=>"")),),);
263
264
265    /** @var  $re */ //Quité MONTO del $re. Tengo que agregarlo como dependiente de Contenedor
266    $re = '/^\s*(VALOR FAC|VAL FAC|FACT|PEDIMENTO|CONTENE).*?\s(.*?(\s))/mi';
267
268    preg_match_all($re, $remarks, $matches, PREG_SET_ORDER, 0);
269
270    $hayBuscar = false;
271    if(is_array($matches) && !empty($matches))
272        foreach($matches as $match)
273        {
274            $llave = $match[1];
275            $valor = $match[2];
276            if(stripos($llave,"VAL") !== false)
277            {
278                $buscar['VALOR_FACTURA']['val'] = echonf(limpiaCantidad($valor), true, 2, "");
279                $hayBuscar = true;
280            }
281            elseif(stripos($llave,"FAC") !== false)
282            {
283                $buscar['FACTURA']['val']= trim(ltrim($valor));
284                $hayBuscar = true;
285            }
286            elseif(stripos($llave,"PEDIMENTO") !== false)
287            {
288                $buscar['PEDIMENTO']['val'] = trim(ltrim($valor));
289                $hayBuscar = true;
290            }
291            elseif(stripos($llave,"CONTENE") !== false)
292            {
293                $buscar['CONTENEDOR']['val'][] = trim(ltrim($valor));
294                $hayBuscar = true;
295            }
296            elseif(stripos($llave,"MONTO") !== false)
297            {
298                $buscar['MONTO']['val'] = echonf(limpiaCantidad($valor), true, 2, "");
299                $hayBuscar = true;
300            }
301        }
302    //Agrega los contenedores que encontró la función encuentraContenedor
303    if($hayCont) {
304        
305        $hayBuscar = true;
306        foreach ($remarks_ok['cont'] as $c)
307            $buscar['CONTENEDOR']['val'][] = trim(ltrim($c));
308
309//        echo "<pre>".print_r($remarks_ok,true)."</pre>";
310//        exit;
311        //Es naviera
312        if ($naviera !== false) {
313            $stepvar = null;
314        } else {
315            // echo "BUSCAR: " . gastoBuscar($remarks_ok['benefic'], $remarks_ok['descripcion']); 
316            // dd_($remarks_ok);
317            if (gastoBuscar($remarks_ok['benefic'], $remarks_ok['descripcion'])){
318                // echo "hee!";
319                $container_duplicates = buscaContenedorPorImporte($bcm_id, $current_bcm['withdrawal'], $remarks_ok['contenedor']);
320                // dd_($container_duplicates);
321                if ($container_duplicates != null){
322                    $duplicates = explode(",", $container_duplicates);
323                    $repIDs = $container_duplicates . ",$bcm_id";
324                    foreach ($duplicates as $bcm_id_repetido) {
325                        $sqlUpdt[] = "UPDATE banco_cuenta_mov SET repetido='Si', mov_repetido_id=" . strit($repIDs) . " WHERE banco_cuenta_mov_id=" . strit($bcm_id_repetido);
326                    }
327                    $sqlUpdt[] = "UPDATE banco_cuenta_mov SET repetido='Si', mov_repetido_id=" . strit($repIDs) . ", remarks=".strit(ltrim(trim($remarks_ok['titulo']))). " WHERE banco_cuenta_mov_id=" . strit($bcm_id);
328                }
329            }
330        }
331    }
332    //NO hay repetidos. Pero ya arregló los remarks según su tipo.
333    if(!$hayBuscar) {
334        $remarks_ok['sql'] = $sqlUpdt;
335        return $remarks_ok;
336    }
337
338    //$sqlUpdt = array();
339
340    if($debug)
341        $infoDebug .= "\r\n<pre>buscar: ".print_r($buscar, true)."</pre>";
342
343    $sqlBuscar = "SELECT banco_cuenta_mov_id, remarks FROM banco_cuenta_mov WHERE banco_cuenta_mov_id <> " . strit($bcm_id);
344    $remarksLike = " AND es='retiro' AND ( ";
345
346    $valRepetido = array();
347
348    foreach($buscar as $k=>$v) {
349        if (empty($v['val'])) continue;
350
351        if(!is_array($v['val']))
352            $valRepetido[] = $v['val'];
353        else
354            foreach($v['val'] as $c)
355                $valRepetido[] = trim(ltrim($c));
356
357        switch ($k) {
358            case "VALOR_FACTURA" :
359                $valRepetido[] = echonf($v['val'], true);
360                break;
361
362            case "FACTURA" :
363            case "PEDIMENTO" :
364            case "CONTENEDOR" :
365            case "MONTO" :
366                break;
367
368            default:
369                break;
370        }
371
372        $valRepetido = array_unique($valRepetido, SORT_STRING);
373
374        $remarksLike .= " (";
375
376        foreach ($valRepetido as $vr)
377            $remarksLike .= " IFNULL(remarks,'') LIKE " . strit("%$vr%") . " OR ";
378
379        $remarksLike = substr($remarksLike, 0, -4) . " ) OR ";
380    }
381
382//    if (count($buscar['CONTENEDOR']['val']) == 0 and $isContainer) {
383////        $remarksLike = $remarksLike . "remarks LIKE '%CONTENE%') AND remarks NOT LIKE ('%FIDUCI%') AND banco_mov_tipo_id NOT IN (6,11,21)";
384//        $response['Status'] = 'Error';
385//        $response["Error"] = 'Debe ingresar número de contenedor!';
386//        die(json_encode($response));
387//        exit;
388//    }
389    $remarksLike = substr($remarksLike, 0, -4) . ") AND remarks NOT LIKE ('%FIDUCI%') AND banco_mov_tipo_id NOT IN (6,11,21)";
390
391    if($debug)
392        $infoDebug .= "\r\n<li>sqlBuscar: $sqlBuscar $remarksLike";
393
394    // dd_($sqlBuscar . $remarksLike);
395
396    $arrDup = ia_sqlArray($sqlBuscar . $remarksLike, "banco_cuenta_mov_id");
397
398    // echo "<pre>".print_r($arrDup, true)."</pre>";
399    // exit;
400
401    //if(empty($arrDup) || !is_array($arrDup))
402    //return $remarks_ok;
403
404    if($debug)
405        $infoDebug .= "\r\n<pre>arrDup:".print_r($arrDup, true)."</pre>";
406
407    $valFound = array();
408
409    if(!empty($tipoNR['st']))
410        $valRepetido[]=$tipoNR['st'];
411
412    if($debug)
413        $infoDebug .= "\r\n<pre>valRepetido:".print_r($valRepetido, true)."</pre>";
414
415    $repIDs = "";
416
417
418    //Aquí va el coloreo del subtitulo. Es para los gastos de contenedor.
419    //if(!empty($tipoNR['st']))
420
421    if (is_array($arrDup)) {
422        foreach($arrDup as $dup)
423        {
424            $rem_old = $dup['remarks']; //quité strip tags
425            $rem_new =  $remarks_ok['descripcion'];
426            $tipoOR = array();
427            $tieneTipoOR = encuentraTipoRemarksBCM($rem_old,$tipoOR); //Según el diccionario de datos para gastos del banco.
428
429            if($debug)
430                $infoDebug .= "\r\n<li>Old: $tieneTipoOR, New: $tieneTipoNR, Oldst: $tipoOR[st], Newst: $tipoNR[st]";
431
432            //La validación es que sean del mismo tipo y del mismo subtitulo
433            if($tieneTipoNR !== false && ($tieneTipoOR != $tieneTipoNR || $tipoOR['st'] != $tipoNR['st'])) //si el nuevo no tiene, entonces ya no compara, asume que se repiten.
434            {
435                //echo "<li>No son del mismo tipo. Old: $tieneTipoOR, New: $tieneTipoNR, Oldst: $tipoOR[st], Newst: $tipoNR[st]";
436                continue;
437            } //No son del mismo tipo.
438
439            $rem_old = marcaRemarksDuplicados($rem_old, $valRepetido, $valFound);
440
441            //Vamos a depurar
442            $valFinal = array();
443
444            foreach($valRepetido as $vr)
445                foreach($valFound as $vf)
446                    if(!array_key_exists($vr, $valFinal) && stripos($vr, $vf) !== false || stripos($vf, $vr) !== false)
447                        $valFinal[$vr] = $vr;
448
449            if($debug)
450                $infoDebug .= PHP_EOL . "<pre>valFinal:".print_r($valFinal, true)."</pre>";
451
452            $rem_new = marcaRemarksDuplicados($rem_new, $valFinal);
453
454            $remarks_ok['descripcion'] = $rem_new;
455
456            //Aqui agregamos los update.
457
458            $sqlUpdt[] = "UPDATE banco_cuenta_mov SET repetido='Si', mov_repetido_id='*#*#*#*#', remarks=".strit(ltrim(trim($rem_old))). " WHERE banco_cuenta_mov_id IN(" . strit($dup['banco_cuenta_mov_id']) . ", " . strit($bcm_id) . ")";
459
460            $repIDs .= $dup['banco_cuenta_mov_id'] .",";
461        }
462    }
463
464    //  echo "<pre>".print_r($dup, true)."</pre>";
465    //         exit;
466
467    if(strlen($repIDs)) {
468        $repIDs .= $bcm_id;
469//        // Si hay contenedores duplicados por importe, se concatenan para hacer referencia a ellos.
470        $repIDs = $container_duplicates . ($container_duplicates != null ? ",": "") .$repIDs;
471        $sqlUpdt[] = "UPDATE banco_cuenta_mov SET repetido='Si', mov_repetido_id=" . strit($repIDs) . " WHERE banco_cuenta_mov_id=" . strit($bcm_id);
472
473        foreach($sqlUpdt as $k=>&$v)
474            $v = str_replace("*#*#*#*#", $repIDs, $v);
475    }
476    else{ //Aquí un update para quitar todos los lugares donde aparece como repetido.
477        $sqlUpdt[] = "UPDATE banco_cuenta_mov SET mov_repetido_id=REGEXP_REPLACE(mov_repetido_id, '($bcm_id,)|$bcm_id','') WHERE mov_repetido_id LIKE '%$bcm_id%'";
478        $sqlUpdt[] = "UPDATE banco_cuenta_mov SET repetido='No', mov_repetido_id='' WHERE banco_cuenta_mov_id=" . strit($bcm_id);
479    }
480
481
482    if($debug)
483        $infoDebug .= PHP_EOL .  "<pre>valFound:".print_r($valFound, true)."</pre>";
484
485    $remarks_ok['sql'] = $sqlUpdt;
486
487    if($debug)
488        $infoDebug .= PHP_EOL .  "<pre>".print_r($sqlUpdt, true)."</pre>";
489
490    if($doSQL)
491        ia_transaction($sqlUpdt);
492
493    return $remarks_ok;
494}
495
496/**
497 * Determina si el BCM es contenedor
498 * @param string $remarks cadena donde bucar
499 * @return bool Es contenedor
500 * */
501function isContainer($remarks)
502{
503    $str_pos = strpos($remarks, 'CONTENE');
504    if ($str_pos === false) {
505        return false;
506    }
507    return true;
508}
509
510/**
511 * Busca los contenedores repetidos por importe
512 * @param string $bcm_id El banco_cuenta_mov_id del que se desea saber si hay repetidos
513 * @param string $importe El importe (withdrawal) que se desa buscar como repetido
514 * @return string|null Concatenación de los contenedores duplicados por importe
515 * */
516function buscaContenedorPorImporte($bcm_id, $importe = '0', $contenedor = '')
517{
518    $sql = "SELECT 
519                *
520            FROM banco_cuenta_mov
521            WHERE banco_cuenta_mov_id <> '$bcm_id
522              AND remarks LIKE '%CONTENE%' 
523              AND remarks NOT LIKE '%FIDUCI%'
524              AND withdrawal = '$importe'
525              AND es = 'Retiro'";
526
527    // dd_($sql);
528
529    $containers = ia_sqlArray($sql, 'banco_cuenta_mov_id');
530    if (count($containers) > 0) {
531        return implode(",", array_keys($containers));
532    }
533    return null;
534}
535
536function gastoBuscar($benefic, $desc)
537{
538    $exceptions = ['LIMPIEZA', 'SERVICIO'];
539    foreach ($exceptions as $exception) {
540        $str_pos = strpos($benefic, $exception);
541        $str_pos_2 = strpos($desc, $exception);
542        if ($str_pos === false and $str_pos_2 === false) {
543            continue;
544        } else {
545            return false;
546        }
547    }
548    return true;
549
550    /* $re = '/^\s*(LIMPIEZA DE 1 CONTENEDOR|LIMPIEZA DE UN CONTENEDOR|LIMPIEZA DE CONTENEDOR|LIMPIEZA DE).*?\s(.*?(\s))/mi';
551     $array = null;
552     preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
553     echo "gastoEsLimpieaza";
554     print_r($matches);
555     exit;*/
556}
557
558function encuentraTipoRemarksBCM($remarks = "", &$tipo = array())
559{
560    $ddbg = preparaDiccionarioDatosBancoGastos();
561
562    $remarks = quitaacentos($remarks);
563    $encontrado = false;
564    $subtitulo = false;
565    $tipo['st'] = "";
566    foreach($ddbg['si_buscar'] as $k=>$r) {
567        foreach($r['palabra_clave'] as $pc) {
568            $encontrado = stripos($remarks, $pc);
569            if ($encontrado !== false) {
570                $tipo = $ddbg['si_buscar'][$k];
571                $tipo['st'] = "";
572                $encontrado = $k;
573                //Para los gastos de contenedor se necesita una subcategoria, la llamé subtítulo.
574                if(!empty($r['subtitulo']))
575                    foreach($r['subtitulo'] as $st) {
576                        $subtitulo = stripos($remarks, $st);
577                        if($subtitulo !== false)
578                            $tipo['st'] = $st;
579                    }
580                break 2;
581            }
582        }
583    }
584
585    return $encontrado;
586}
587
588function marcaRemarksDuplicados($remarks = "", $valRep = array(), &$valFound = array())
589{
590    $valStr = join("|", $valRep);
591    $re = '/^.*\b(' . $valStr . ')\b.*$/mi';
592    //$re = '/.*(' . $valStr . ').*$/mi';
593
594    //echo "<li>re: $re";
595
596    $result = preg_replace_callback($re, function($m) use (&$valFound){
597        //echo "<pre>m:".print_r($m, true)."</pre>";
598        $str = ltrim(trim(strip_tags($m[0])));
599        $valFound[] = $str;
600        return "<strong class=\"txt_bold_red txt_underline\">".$str."</strong>";
601    }, $remarks);
602
603    return $result;
604}
605
606function encuentraContenedor($str, &$cont, &$naviera)
607{
608    $encontrado = false;
609    if(empty($str))
610        return $encontrado;
611
612    $palCont = stripos($str, "CONTENEDOR");
613
614    $naviera = stripos($str, "NAVIER");
615
616    $naviera = $naviera !== false ?  $naviera : stripos($str, "GARANT");
617
618    if($palCont !== false)
619    {
620        $encontrado = true;
621    }
622
623    /**
624    REGEX para encontrar algún numero de contenedor: /(([A-Za-z]){4}([0-9]){7})/m
625    ( //Dentro de paréntesis para que sea un solo grupo de 11 caracteres
626    ([A-Za-z]){4} //Un grupo de 4 caracteres del alfabeto y que sean contiguos
627    ([0-9]){7} //Un grupo de 3 caracteres numéricos y que sean contiguos
628    ) //Dentro de paréntesis para que sea un solo grupo de 11 caracteres
629    /m //Para que la búsqueda sea multilínea
630
631     **/
632    //$pattern = '/[[:<:]]([^a-zA-Z]*[A-Za-z]){4}([0-9]){7}/m';
633    $pattern = '/(([A-Za-z]){4}([0-9]){7})/m';
634    $matches = array();
635
636    preg_match_all($pattern, $str, $matches, 0, $palCont);
637
638
639    if( !empty($matches) &&
640        is_array($matches) &&
641        array_key_exists(0, $matches) &&
642        !empty($matches[0]) &&
643        is_array($matches[0]))
644    {
645
646        foreach($matches[0] as $k=>$v)
647        {
648            $cont[] = $v;
649            $encontrado = true;
650        }
651
652    }
653
654    return $encontrado;
655}
656
657/**
658 * CalculaBancoCuentaSaldodeunArraydeMovimientos()
659 *
660 * @param   array &$arrMovs = Array de Movimientos Bancarios, se pasa por referencia.
661 * @param   int $indexBalance = Indice que ocupará el Saldo.
662 * @param   int $bcid = ID de la cuenta bancaria.
663 * @param   bool $Original = true = Original, false = Verificacion.
664 */
665function CalculaBancoCuentaSaldodeunArraydeMovimientos(&$arrMovs, $indexBalance, $bcid, $Original)
666{
667    $indexBalance="balance";
668    $bcmid='banco_cuenta_mov_id';
669    $deposit='deposit';
670    $cash='cash';
671    $withdrawal='withdrawal';
672    if(empty($arrMovs))
673        return;
674
675    $arrLength = sizeof($arrMovs);
676    $arrLength--;
677
678    $arrMovs[$arrLength][$indexBalance] = CalculaBancoCuentaSaldodesdeunMovimiento($bcid,$arrMovs[$arrLength][$bcmid],$Original);
679    $arrLength--;
680
681    while ($arrLength>=0)
682    {
683        $arrMovs[$arrLength][$indexBalance] = number_format($arrMovs[$arrLength+1][$indexBalance] + ($arrMovs[$arrLength][$cash] + $arrMovs[$arrLength][$deposit] - $arrMovs[$arrLength][$withdrawal]), 2, ".", "");
684        $arrLength--;
685    }
686}
687
688function CalculaBancoCuentaSaldodesdeunMovimiento($banco_cuenta_id, $banco_cuenta_mov_id, $Original=true)
689{
690    $balance = 0.00;
691    if($banco_cuenta_id == '' || $banco_cuenta_mov_id == '')
692        return $balance;
693
694    if(empty($banco_cuenta_mov_id))
695        return 0;
696    else
697    {
698        if($Original) {
699            $idField = 'banco_cuenta_mov_id'; $tbl = 'banco_cuenta_mov';
700            $fecha = ia_singleread( "SELECT fecha FROM `$tbl` WHERE `banco_cuenta_mov_id` = ".strit($banco_cuenta_mov_id),false);
701            //$sql =  "SELECT fecha FROM `$tbl` WHERE `banco_cuenta_mov_id` = ".strit($banco_cuenta_mov_id);
702            //echo "$sql<br />";
703        } else {
704            $idField = 'mov_verificado_id'; $tbl = 'mov_verificado';
705            $fecha = ia_singleread( "SELECT fecha FROM `$tbl` WHERE `mov_verificado_id` = ".strit($banco_cuenta_mov_id),false);
706        }
707    }
708    if( !empty($fecha) )
709    {
710        $foundit=false;
711        $balance = 0.00;
712        $sql = "SELECT $idField, fecha, banco_cuenta_id, deposit, withdrawal FROM $tbl WHERE banco_cuenta_id = '$banco_cuenta_id' AND fecha <= '$fecha' ORDER BY fecha DESC, $idField DESC";
713        //echo "$sql";
714        $arr = ia_sqlArrayIndx($sql);
715        if( !empty($arr) ) foreach($arr as $k=>$v) {
716            if($v[$idField] == $banco_cuenta_mov_id)
717                $foundit = true;
718            if($foundit)
719                $balance+= $v['deposit'] - $v['withdrawal'];
720        }
721    }
722    //echo "$balance<br />";
723    return $balance;
724}
725
726function HazLinkBancarioManualIncompleto($bcm_id, $Quantity, $lm_tienda_id, $lm_docto, $banco_id, $usuario)
727{
728    $bcml_id = ia_guid();
729
730    $acta_id = ia_guid();
731
732    $arr_tlm = TablaparaLinkManual($lm_docto);
733    //print_r($arr_tlm);
734
735    $acta_tbl = $arr_tlm["acta_tabla"];
736    //$acta_tbl = $lm_docto . '_pago';
737    $acta_id_nombre = $acta_tbl . '_id';
738
739    $acta_fecha = date('Y-m-d H:i:s');
740    $acta_quantity = $Quantity;
741    $acta_moneda_id = 1;
742    $acta_tipo_cambio = 1;
743    $acta_metodo_pago_id = 1;
744    $acta_banco_id = $banco_id;
745    $acta_referencia = $arr_tlm["acta_comentarios"];
746    $acta_comentario = $arr_tlm["acta_comentarios"];
747    $acta_referencia .= 'Link manual desde Edo Cta. ';
748    $acta_comentario .= 'Link manual desde Edo Cta. ';
749    $acta_alta_db = $acta_fecha;
750    $acta_alta_por = $usuario;
751
752
753    $oknumop = 3; //Hay 3 queries. Insertar a cuenta, el banco_cuenta_mov_link, y actualizar el banco_cuenta_mov.
754    $ok = 0;
755
756    $acta_sql = "INSERT INTO $acta_tbl ($acta_id_nombre, fecha, quantity, moneda_id, tipo_cambio, metodo_pago_id, banco_id, banco_cuenta_mov_link_id, referencia, comentario, alta_db, alta_por) VALUES ('$acta_id', '$acta_fecha', '$acta_quantity', '$acta_moneda_id', '$acta_tipo_cambio', '$acta_metodo_pago_id', '$acta_banco_id', '$bcml_id', '$acta_referencia', '$acta_comentario', '$acta_alta_db', '$acta_alta_por')";
757    if(!ia_query($acta_sql,true,false))//Inserto el a cuenta.
758        $ok++;
759    //echo $acta_sql . '<br>';
760
761    $bcml_sql = "INSERT INTO banco_cuenta_mov_link (banco_cuenta_mov_link_id, banco_cuenta_mov_id, link_to, link, tienda_id, link_por, link_el) VALUES ('$bcml_id', '$bcm_id', '$acta_tbl', '$acta_id', '$lm_tienda_id', '$acta_alta_por', '$acta_alta_db')";
762    if(!ia_query($bcml_sql,true,false))//Inserto el a cuenta.
763        $ok++;
764    //echo $bcml_sql . '<br>';
765
766    $bcm_sql = "UPDATE banco_cuenta_mov SET usado = usado + $Quantity, link_vale = 'ND', puede_editar = 'No', ultimo_cambio = '$acta_alta_db', ultimo_cambio_por = '$acta_alta_por' WHERE banco_cuenta_mov_id = '$bcm_id'";
767    if(!ia_query($bcm_sql,true,false)) //Actualizo al banco_cuenta_mov, le resto el Quantity del Usado.
768        $ok++;
769    //echo $bcm_sql . '<br>';
770
771    if($ok == $oknumop)
772        return $acta_tbl;
773    else
774        return false;
775}
776
777function esBancoChina($banco_cuenta_id='')
778{
779    if(empty($banco_cuenta_id))
780        return false;
781
782    $es=ia_singleread("SELECT banco_china FROM banco_cuenta WHERE banco_cuenta_id =".strit($banco_cuenta_id));
783
784    if($es == 'Si')
785        return true;
786    else
787        return false;
788}
789
790function generaaCuentasdeBancoMov($bcmid, $tr='str', $li='NO', $debug=false, $dep_banco_tans_id="")
791{
792    //global $gIAsql;
793    //$gIAsql['trace']=true;
794    $infoDebug='';
795
796    if(empty($bcmid))
797        return;
798
799    $banco_cuenta_mov_id = $bcmid;
800
801    if($tr=='str')
802        $acta_resumen = '';
803    else
804        $acta_resumen = array();
805
806    $nl=$li=='SI'?'<li>':"\r\n<br>";
807    $il=$li=='SI'?0:1;
808
809    $Original = true;
810
811    if($banco_cuenta_mov_id == '' || strlen($banco_cuenta_mov_id) < 32)
812        return $acta_resumen;
813
814    $BancoCuentaMov = new BancoCuentaMov;
815    $BancoCuentaMov->Original = $Original;
816    if(!$BancoCuentaMov->leeBancoCuentaMov($banco_cuenta_mov_id))
817        return $acta_resumen;
818
819    //Leemos los a cuentas de este movimiento bancario.
820    if($BancoCuentaMov->link_vale == 'LT' && $BancoCuentaMov->withdrawal > 0)
821        $bcml_arr = ia_sqlArrayIndx("SELECT * FROM banco_cuenta_mov_link WHERE link_to='banco_cuenta_mov' AND link = ". strit($BancoCuentaMov->banco_cuenta_mov_id));
822    else
823        $bcml_arr = ia_sqlArrayIndx("SELECT * FROM banco_cuenta_mov_link WHERE banco_cuenta_mov_id = ". strit($BancoCuentaMov->banco_cuenta_mov_id));
824
825    if ($debug)
826        $infoDebug .= "\r\n<pre>generaaCuentasdeBancoMov bcml_arr: " . print_r($bcml_arr, true) . "</pre>";
827
828
829    if($debug)
830    {
831        //28-ene-2021
832        global $gWebDir;
833        $myFile = "C:\\wamp\\www\\$gWebDir\\backoffice\\txt\\generaaCuentasdeBancoMov_$bcmid.txt";
834        $fh = fopen($myFile, 'w') or die("can't open file");
835        $bleh = $infoDebug;
836        fwrite($fh, $bleh);
837        fclose($fh);
838    }
839
840    if(is_array($bcml_arr) && !empty($bcml_arr))
841        foreach($bcml_arr as $k=>$bcmlrow)
842        {
843            //Leemos la información de cada a cuenta y le metemos al arreglo $acta_arr. Es estándar para todos los tipos de documentos padre (cheque, nota, pagaré).
844            $acta_arr = leeaCuenta($bcmlrow['link_to'], $bcmlrow['link'], $bcmlrow['banco_cuenta_mov_link_id'], $bcmlrow['tienda_id']);
845
846            if($acta_arr===false) continue;
847            //print_r($acta_arr);
848            $cactar = $k>=$il?$nl:'';
849
850            $ar_pre = '';
851            $ar_post = '';
852
853            if(!empty($acta_arr['acta_moneda']) && $acta_arr['acta_moneda'] == 'USD')
854            {
855                $ar_pre = "<span class='actaUSD'>";
856                $ar_post = "</span>";
857            }
858
859            $cactar .= $ar_pre;
860
861            $class_moneda = $acta_arr['acta_moneda'] == "USD" ? "txt_shadow_verde" : "txt_shadow_azul_marino";
862
863            $cactar .= $acta_arr['acta_numero'] != '' ? $acta_arr['acta_numero'].', ': '';
864            $cactar .= $acta_arr['acta_quantity'] != '' ? 'MONTO APLICADO: <strong class="'. $class_moneda .'">$'.number_format(floatval($acta_arr['acta_quantity']), 2, '.', ',').'</strong> ' : '';
865
866
867
868            $txt_moneda = "<strong class='$class_moneda'>$acta_arr[acta_moneda]</strong> ";
869
870            $cactar .= $txt_moneda;
871
872            $cactar .= $acta_arr['acta_desc'] != '' ? $acta_arr['acta_desc'].' ' : ' ';
873            $cactar .= $ar_post;
874
875            $cactar .= !empty($acta_arr['actapadre_tiendaclv']) ? '('.$acta_arr['actapadre_tiendaclv'].')' : '';
876            $cactar .= !empty($acta_arr['actapadre_number']) ? ' #'.$acta_arr['actapadre_number'].' ' : ' ';
877            $cactar .= !empty($acta_arr['actapadre_quantity']) ? ' DE <strong>$'.number_format(floatval($acta_arr['actapadre_quantity']), 2, '.', ',').'</strong> ' : '';
878            $cactar .= !empty($acta_arr['actapadre_moneda']) ? $acta_arr['actapadre_moneda'] : '';
879
880            //$acta_resumen .= '.';
881
882            if($bcmlrow['link_to'] == 'banco_cuenta_mov') {
883                //Los remarks de las transferencias entre cuentas propias, los tomo del registro mismo de banco_cuenta_trans directamente. Ya están preparados =)
884                if(!empty($dep_banco_tans_id))
885                $cactar = ia_singleread("SELECT remarks FROM banco_cuenta_trans WHERE banco_cuenta_mov_link_id = " . strit($bcmlrow['banco_cuenta_mov_link_id']));
886            }
887            else{
888                if ($bcmlrow['link_to'] == 'cuentat_mov') {
889                    $cbenDB = ia_singleton("SELECT * FROM cuentat_a_banco WHERE banco_cuenta_mov_link_id=" . strit($bcmlrow['banco_cuenta_mov_link_id']));
890
891                    $acta_arr['remarks'] .= !empty($cbenDB['remarks']) ? nl2br($cbenDB['remarks']) : '';
892                    $acta_arr['actapadre_nombre'] .= !empty($cbenDB['tipo_cash_nota']) ? "<br>$cbenDB[tipo_cash_nota]" : '';
893                    $acta_arr['actapadre_nombre'] .= !empty($cbenDB['cash_nota_num']) ? "$cbenDB[cash_nota_num]" : '';
894                    $acta_arr['actapadre_nombre'] .= !empty($cbenDB['cliente']) ? "<br>CLIENTE: $cbenDB[cliente]" : '';
895                    $acta_arr['actapadre_nombre'] .= !empty($cbenDB['factura']) ? "<br>$cbenDB[factura]" : '';
896                    $acta_arr['actapadre_nombre'] .= !empty($cbenDB['factura_numero']) ? "$cbenDB[factura_numero]" : '';
897                } else {
898                    if (array_key_exists('acta_comentario', $acta_arr) && $bcmlrow['link_to'] != 'banco_cuenta_mov')
899                        $acta_arr['remarks'] .= !empty($acta_arr['acta_comentario']) ? nl2br($acta_arr['acta_comentario']) : '';
900                    else
901                        $acta_arr['remarks'] = '';
902                }
903
904                $cactar .= $acta_arr['actapadre_nombre'] != '' ? '<br>' . $acta_arr['actapadre_nombre'] : '';
905                $cactar .= $acta_arr['actapadre_nombre_cheque'] != '' ? '<br>' . 'Cheque a nombre de: ' . BoldaString($acta_arr['actapadre_nombre_cheque']) : '';
906                $cactar .= $acta_arr['acta_ctaTmov'] != '' ? '<br>' . $acta_arr['acta_ctaTmov'] : '';
907
908                $cactar = strtoupper($cactar);
909                $cactar = str_replace('ACUTE', 'acute', $cactar);
910                $cactar = str_replace('ACTAUSD', 'actausd', $cactar);
911                $cactar = str_replace('TXT_SHADOW_VERDE', 'txt_shadow_verde', $cactar);
912                $cactar = str_replace('TXT_SHADOW_AZUL_MARINO', 'txt_shadow_azul_marino', $cactar);
913
914                $cactar .= "<br />" . html_entity_decode($acta_arr['remarks']);
915
916
917            }
918            if($tr=='str')
919                $acta_resumen .= $cactar;
920            else
921                $acta_resumen[] = $cactar;
922
923        }
924
925    /**
926    echo "<pre>gIAsql".print_r($gIAsql, true)."</pre>";
927    echo "<pre>bcml_arr".print_r($bcml_arr, true)."</pre>";
928    echo "<pre>acta_arr".print_r($acta_arr, true)."</pre>";
929    echo "<pre>acta_resumen".print_r($acta_resumen, true)."</pre>";
930     **/
931
932    return $acta_resumen;
933}
934
935function generayGuardaaCuentasdeBancoMov($bcm_id='', $debug=false, $guarda=true, $bcml=false, $mantieneRemarks = false)
936{
937    if(empty($bcm_id))
938        return;
939
940    if($bcml) {
941        // echo $sql;
942        $sql = "SELECT banco_cuenta_mov_id FROM banco_cuenta_mov_link WHERE banco_cuenta_mov_link_id = '$bcm_id'";
943        $bcm_id = ia_singleread($sql);
944    }
945
946    $oldRemarks = ia_singleread("SELECT remarks FROM banco_cuenta_mov WHERE banco_cuenta_mov_id = '$bcm_id'");
947
948    $actas = generaaCuentasdeBancoMov($bcm_id);
949
950
951    //Aqui hacemos el cambio. Los remarks anteriores los pasamos a remarks_log.
952
953    $oldRemarks = empty($oldRemarks) ? "" : date('d-m-Y H:i:s')."$oldRemarks<hr/>";
954
955    $newRemarks = $actas . ($mantieneRemarks ? $oldRemarks : "");
956
957    $oldRemarks = $newRemarks;// strtoupper($newRemarks);
958    // $newRemarks = strtoupper($newRemarks);
959
960    $oldRemarks = str_replace('ACUTE', 'acute', $oldRemarks);
961    $newRemarks = str_replace('ACUTE', 'acute', $newRemarks);
962
963    $links=generaListadoLinksBCM($bcm_id);
964
965    $links=" ,detalle_links = ".strit($links);
966
967    /**
968     * JJDPL 22-03-2021
969     * Se agrega función para generar link a cuentaT
970     */
971    $link_cuentaT = generaLinkAAcuentaT($bcm_id);
972
973    $sql="UPDATE /** generayGuardaaCuentasdeBancoMov **/ banco_cuenta_mov SET
974            remarks = ".strit($newRemarks).",
975            remarks_log = CONCAT(remarks_log,".strit($oldRemarks)."),
976            link_cuenta_t = ".strit($link_cuentaT)."
977            $links
978            WHERE banco_cuenta_mov_id=".strit($bcm_id);
979
980    if($debug)
981        echo "$newRemarks<br/><br/>$sql<br/><br/>";
982
983
984    if($guarda)
985    {
986        if(ia_query($sql))
987            ia_errores_a_dime($sql);
988    }
989    else
990    {
991        $arr = array();
992        $arr['sql']=$sql;
993        $arr['newRemarks']=$actas;
994        $arr['oldRemarks']=$oldRemarks;
995        $arr['link_cuentaT']=$link_cuentaT;
996        return $arr;
997    }
998
999    return true;
1000}
1001
1002function generaListadoLinksBCM($bcmID, $tr='str')
1003{
1004    if(empty($bcmID))
1005        return;
1006
1007    if($tr=='str')
1008        $txtLinks = '';
1009    else
1010        $txtLinks = array();
1011
1012    $bcmenDB = ia_singleton("SELECT * FROM banco_cuenta_mov WHERE banco_cuenta_mov_id = '$bcmID'");
1013    $fDeposit=$bcmenDB['deposit'];
1014
1015    if($bcmenDB['link_vale'] == 'LT' && $bcmenDB['withdrawal'] > 0)
1016        $bcmlenDB = ia_sqlArrayIndx("SELECT * FROM banco_cuenta_mov_link WHERE link_to='banco_cuenta_mov' AND link = ". strit($bcmID));
1017    else
1018        $bcmlenDB = ia_sqlArrayIndx("SELECT * FROM banco_cuenta_mov_link WHERE banco_cuenta_mov_id = ". strit($bcmID));
1019
1020    if(is_array($bcmlenDB) && !empty($bcmlenDB))
1021        foreach($bcmlenDB as $k=>$bcml)
1022        {
1023            $acta_arr = leeaCuenta($bcml['link_to'], $bcml['link'], $bcml['banco_cuenta_mov_link_id'], $bcml['tienda_id']);
1024            if($acta_arr===false) continue;
1025            $txtLink = $acta_arr['acta_app_origen'].
1026                ($acta_arr['acta_app_origen']=="Link de CuentaT" ? " ".propdeCtaT($acta_arr['acta_cuentat_id'],'usuario',true).", ":", ");
1027            $txtLink .= "por: $bcml[link_por]";
1028            $txtLink .= "el ".get_date_spanish(strtotime($bcml['link_el']), false, 'small_date','month_mini').", ";
1029            $fDeposit-=$acta_arr['acta_quantity_total'];
1030            $txtLink .= "$".echonf($acta_arr['acta_quantity_total'],true);
1031            $txtLink .= ($acta_arr['acta_quantity_total'] != $acta_arr['acta_quantity'] ? " ($".echonf($acta_arr['acta_quantity'],true)."), ":", ");
1032            $txtLink .= "RESTA $".echonf($fDeposit,true);
1033            $txtLink = strtoupper($txtLink);
1034            $href='';
1035            switch($bcml['link_to'])
1036            {
1037                case 'cheque_pago': case 'pagare_pago': case 'vale': case 'vale_pago': //VALE_PAGO_MULTIPLE
1038                $href="../backoffice/a_cuentas.php?doc_pago_id=$acta_arr[acta_id]";
1039                break;
1040
1041                case 'cuentat_mov':
1042                    $href="../backoffice/cuentat_a_banco_list.php?cuentat_a_banco_id=$acta_arr[acta_id]";
1043                    break;
1044
1045                case 'fiduciario_reembolso':
1046                    $href="../backoffice/fiduciario_reembolso.php?fiduciario_reembolso_id=$acta_arr[acta_id]";
1047                    break;
1048
1049                case 'banco_cuenta_mov':
1050                    $href="../cobranza/edocta.php?banco_cuenta_id=$acta_arr[acta_banco_cuenta_id]&banco_cuenta_mov_id=$acta_arr[acta_id]";
1051                    break;
1052            }
1053
1054            $txtLink = "<li><a href=\"$href\" target=\"_blank\">$txtLink</a>";
1055
1056            if($tr=='str')
1057                $txtLinks.=$txtLink;
1058            else
1059                $txtLinks[]=$txtLink;
1060        }
1061    return $txtLinks;
1062}
1063
1064function generayGuardaListadoLinksBCM($bcmID, $debug=false, $guarda=true)
1065{
1066    if(empty($bcmID))
1067        return;
1068
1069    $sql='';
1070    $links = generaListadoLinksBCM($bcmID);
1071    if(!empty($links))
1072        $sql="UPDATE /** generayGuardaListadoLinksBCM **/ banco_cuenta_mov SET
1073        detalle_links = ".strit($links)."
1074        WHERE banco_cuenta_mov_id=".strit($bcmID);
1075
1076    if($debug && !empty($links))
1077        echo "$links<br/><br/>";
1078
1079
1080    if($guarda && !empty($sql))
1081    {
1082        if(ia_query($sql))
1083            ia_errores_a_dime($sql);
1084    }
1085    else
1086    {
1087        $arr = array();
1088        $arr['sql']=$sql;
1089        $arr['links']=$actas;
1090        return $arr;
1091    }
1092
1093    return true;
1094}
1095
1096function bancoCuentaMovs($andWhere='',$orderby='')
1097{
1098    global $gIAsql;
1099    $gIAsql['trace'] = true;
1100
1101
1102    $sql = obtenSQLBancoCuentaMovs();
1103
1104    //echo "<pre>sql".print_r($sql, true)."</pre>";
1105
1106    if(!empty($andWhere))
1107    {
1108        if(strpos($andWhere, " AND (") == 0)
1109            $andWhere = substr($andWhere,5);
1110
1111        $andWhere = " WHERE $andWhere ";
1112    }
1113    $sql .= $andWhere . " GROUP BY banco_cuenta_mov_id ".$orderby;
1114
1115    //echo "<pre>sql".print_r($sql, true)."</pre>";die();
1116
1117    $arrBCMovs = ia_sqlArrayIndx($sql,MYSQL_NUM);
1118    //$arrBCMovs = ia_sqlArray($sql,'0',MYSQL_NUM);
1119    //echo "<pre>".print_r($arrBCMovs, true)."</pre>";die();
1120
1121    return $arrBCMovs;
1122}
1123
1124function obtenSQLBancoCuentaMovs()
1125{
1126    $sql = "SELECT
1127b.banco_cuenta_mov_id AS banco_cuenta_mov_id,
1128'0.00' as balance,
1129b.banco_id AS banco_id,
1130b.banco_cuenta_id AS banco_cuenta_id,
1131b.fecha AS fecha,
1132b.es AS es,
1133b.withdrawal AS withdrawal,
1134b.deposit AS deposit,
1135b.cash AS cash,
1136b.link_vale AS link_vale,
1137b.banco_mov_tipo_id AS banco_mov_tipo_id,
1138b.usado AS usado,
1139b.puede_editar AS puede_editar,
1140b.verificado AS verificado,
1141b.verificado_el AS verificado_el,
1142b.verificado_por AS verificado_por,
1143b.mov_verificado_id AS mov_verificado_id,
1144b.remarks AS remarks,
1145b.numero AS numero,
1146'' as actions,
1147b.cliente AS cliente,
1148l.link_por AS link_por,
1149b.tipo_cash_nota AS tipo_cash_nota,
1150b.cash_nota_num AS cash_nota_num,
1151b.alta_db AS alta_db,
1152b.alta_por AS alta_por,
1153b.ultimo_cambio AS ultimo_cambio,
1154b.ultimo_cambio_por AS ultimo_cambio_por,
1155b.idex100 AS idex100,
1156b.idetotal AS idetotal,
1157IF(deposit-withdrawal-(deposit*idex100/100)>0,deposit-withdrawal-(deposit*idex100/100),0) as netdeposit,
1158b.factura AS factura,
1159b.factura_numero AS factura_numero,
1160b.cobra_iva AS cobra_iva,
1161b.iva_incluido AS iva_incluido,
1162b.ivacobradox100 AS ivacobradox100,
1163b.ivacobradototal AS ivacobradototal,
1164b.cash_num_cobro_iva AS cash_num_cobro_iva,
1165b.tienda_id AS tienda_id,
1166b.empresa_id AS empresa_id,
1167l.banco_cuenta_mov_link_id AS banco_cuenta_mov_link_id,
1168l.link_to AS link_to,
1169l.link_el AS link_el,
1170l.link AS link,
1171b.poliza_contabilidad AS poliza_contabilidad,
1172l.tienda_id AS link_tienda_id,
1173b.categoria_gasto_id,
1174b.remarks_log AS remarks_log,
1175b.withdrawal_autorizado AS withdrawal_autorizado,
1176b.withdrawal_autorizado_el AS withdrawal_autorizado_el,
1177b.withdrawal_autorizado_por AS withdrawal_autorizado_por
1178FROM banco_cuenta_mov b
1179LEFT OUTER JOIN banco_cuenta_mov_link l
1180ON b.banco_cuenta_mov_id = l.banco_cuenta_mov_id";
1181
1182    return $sql;
1183}
1184
1185function banco_cuenta_saldos_refresh() {
1186    return false;
1187    return ia_query("
1188        INSERT INTO banco_cuenta_saldos(`banco_cuenta_id`,`saldo_actual`,`sbc`,`deposit_cash`,`deposit_total`,`withdrawal_total`,`Ultimo_Movimiento`,`Ultimo_cash`,`Ultimo_deposit`,`Ultimo_withdrawal`,`ultima_conciliacion`,`orden`,`nombre`)
1189        (
1190            SELECT
1191                bcm.banco_cuenta_id,
1192                SUM(bcm.cash + bcm.deposit - bcm.withdrawal) as saldo_actual,
1193                SUM(IF(bcm.link_vale='SBC',bcm.cash + bcm.deposit,0)) as sbc,
1194                SUM(bcm.cash+bcm.deposit) as deposit_cash,
1195                SUM(bcm.cash + bcm.deposit) as deposit_total,
1196                SUM(bcm.withdrawal) as withdrawal_total,
1197                MAX(fecha) as Ultimo_Movimiento,
1198                MAX(IF(bcm.cash+bcm.deposit>0,fecha,NULL)) as Ultimo_cash,
1199                MAX(IF(bcm.cash+bcm.deposit>0,fecha,NULL)) as Ultimo_deposit,
1200                MAX(IF(bcm.withdrawal>0,fecha,NULL)) as Ultimo_withdrawal,
1201                bc.ultima_conciliacion,
1202                bc.orden,
1203                bc.nombre
1204            FROM banco_cuenta_mov bcm JOIN banco_cuenta bc ON bcm.banco_cuenta_id = bc.banco_cuenta_id WHERE bc.vale = 'Active'
1205            GROUP BY bcm.banco_cuenta_id
1206        )
1207        ON DUPLICATE KEY UPDATE
1208            `saldo_actual`=VALUES(`saldo_actual`),
1209            `sbc`=VALUES(`sbc`),
1210            `deposit_cash`=VALUES(`deposit_cash`),
1211            `deposit_total`=VALUES(`deposit_total`),
1212            `withdrawal_total`=VALUES(`withdrawal_total`),
1213            `Ultimo_Movimiento`=VALUES(`Ultimo_Movimiento`),
1214            `Ultimo_cash`=VALUES(`Ultimo_cash`),
1215            `Ultimo_deposit`=VALUES(`Ultimo_deposit`),
1216            `Ultimo_withdrawal`=VALUES(`Ultimo_withdrawal`),
1217            `ultima_conciliacion`=VALUES(`ultima_conciliacion`),
1218            `orden`=VALUES(`orden`),
1219            `nombre`=VALUES(`nombre`)
1220        ");
1221}
1222
1223function preparaTablaSaldosBanco()
1224{
1225    $sql = "SELECT banco_cuenta_id, orden, nombre, Ultimo_Movimiento, ultima_conciliacion, solicitud_de_importacion, solicitud_por, solicitud_el FROM banco_cuenta_saldos";
1226    $ctas = ia_sqlArray($sql, "banco_cuenta_id");
1227
1228    uasort($ctas, function($a,$b) {
1229        if($a['orden'] === $b['orden'])
1230            return  strnatcasecmp($a['nombre'], $b['nombre']);
1231        return $a['orden'] > $b['orden'];
1232    });
1233
1234    $html = "";
1235
1236    $html .= "<div align='center' style='width:90%;margin-top:32px;'>
1237        <table id='saldosBancos' class='tabla tablesorter' align='center' style='width:1400px;'>
1238        <thead>
1239        <tr>
1240            <th class='cen lbl'>CUENTA</th>
1241            <th class='cen'>ÚLTIMO MOVIMIENTO</th>
1242            <th class='cen'>ACTUALIZADO HACE</th>
1243            <th class='cen'>SOLIC. DE ACTUALIZACIÓN</th>
1244            <th class='cen'>SOLIC. POR</th>
1245            <th class='cen'>SOLIC. HACE</th>
1246        </tr></thead><tbody>";
1247
1248    foreach($ctas as $k => $c)
1249    {
1250        if(empty($c['ultima_conciliacion'])) {
1251            $fuch = $ultima_conc = $txt_difHoras = '';
1252        } else {
1253            $fuch = $c['ultima_conciliacion'];
1254            $fuch = strtotime($fuch);
1255            $txt_difHoras = txtHaceCuantoTiempo($fuch, $nowTime, $monedaClass);
1256            $ultima_conc = get_date_spanish($fuch, false,'small_date','month_mini') . " - " . date('H:i:s',$fuch);
1257        }
1258        $atitle = "title='".htmlentities($cuentaBancaria['banco'].' #cta: '.$cuentaBancaria['numero'],ENT_QUOTES)."'";
1259        echo "\r\n<tr class='$cuentaBancaria[vale]'>".
1260            "<td style='width:3%' class='der nocopy noprint white' style='color:white !important'>".trim($cuentaBancaria['orden']).
1261            "<td style='width:20%'>".
1262            "<a  class='asin $monedaClass'  $atitle href='../cobranza/edocta.php?ACC=CB&ECO=SI&banco_cuenta_id=$t[banco_cuenta_id]' target='_blank'><strong>".
1263            ia_htmlentities($cuentaBancaria['nombre'])."</strong></a>".
1264
1265            "<td style='width:11%' class='der $monedaClass bold'>".echonf($t['saldo_actual'],true).
1266            "<td style='width:11%' class='der bold'>".echonf($t['saldo_actual']-$sbcActual,true).
1267            "<td style='width:11%' class='der bold rojo'>$txtsbcActual".
1268            "<td  class='cen'>".(empty($t['Ultimo_Movimiento']) ? '' :  get_date_spanish(strtotime($t['Ultimo_Movimiento']),false,'small_date','month_mini') ).
1269            "<td style='width:22%' class='der bold'>$txt_difHoras".
1270            "<td style='width:22%' class='cen bold'>$ultima_conc".
1271
1272            "</tr>";
1273
1274        return array($t['saldo_actual'], $sbcActual);
1275    }
1276
1277}
1278
1279function obtenNombreBancoCuenta($bcid)
1280{
1281    return ia_singleread("SELECT nombre  FROM banco_cuenta WHERE banco_cuenta_id = '$bcid'");
1282}
1283
1284function genera_banco_cuenta_saldos()
1285{
1286    $arr_cuentas = ia_sqlArrayIndx("select * from banco_cuenta where vale = 'Active'");
1287
1288    $sql = array();
1289
1290
1291    foreach ($arr_cuentas as $k => $v) {
1292        $bc_id = $v['banco_cuenta_id'];
1293        $sql[] = "UPDATE banco_cuenta SET ultima_conciliacion=NOW() WHERE banco_cuenta_id=" . strit($bc_id);
1294        $sql[] = "CALL actualiza_banco_cuenta_saldos($bc_id)";
1295
1296    }
1297//echo "<pre>".print_r($sql, true)."</pre>";
1298    ia_transaction($sql);
1299
1300}
1301
1302function encuentraSubcategoria($string = '')
1303{
1304    $subcategoria = null;
1305    if (!empty($string)) {
1306        $re_almacenaje = '/^\s*(ALMACENAJE |ALMACENAJE DE|ALMACENAJE|ALMACENAJE DE CONTENE).*?\s(.*?(\s))/mi';
1307        preg_match_all($re_almacenaje, $string, $matches_almacenaje, PREG_SET_ORDER);
1308
1309        if (!empty($matches_almacenaje)) $subcategoria = 'ALMACENAJE';
1310
1311        $re_limpieza = '/^\s*(LIMPIEZA |LIMPIEZA DE|LIMPIEZA|LIMPIEZA DE CONTENE).*?\s(.*?(\s))/mi';
1312        preg_match_all($re_limpieza, $string, $matches_limpieza, PREG_SET_ORDER);
1313
1314        if (!empty($matches_limpieza)) $subcategoria = 'LIMPIEZA';
1315
1316        /* if($carac) {
1317            if(!strlen($subcategoria))
1318            {
1319                $subcategoria .= $line.PHP_EOL;
1320                $done = true;
1321                continue;
1322            }
1323        } */
1324    }
1325
1326    return $subcategoria;
1327}
1328
1329
1330function quieroBuscarGasto($categoria = null, $subcategoria = null, $value = null, $importe = null, $level = 'all')
1331{
1332    $catgeorias = ['GASTOS DE CONTENEDOR']; // Level = 1
1333    $sub_categorias = ['ALMACENAJE']; // Level = 2
1334    $values = ['EITU9144722']; // Level = 3
1335    $importes = [''];
1336
1337    $search = true;
1338
1339    switch ($level) {
1340        case 'all':
1341                if(in_array($categoria, $catgeorias) and in_array($subcategoria, $sub_categorias) and in_array($value, $values) and in_array($importe, $importes) ) {
1342                    $search = false;
1343                }
1344            break;
1345        case '1': case 1:
1346                if(in_array($categoria, $catgeorias)) {
1347                    $search = false;
1348                }
1349            break;
1350        case '2': case 2:
1351                if(in_array($categoria, $catgeorias) and in_array($subcategoria, $sub_categorias)) {
1352                    $search = false;
1353                }
1354            break;
1355        case '3': case 3:
1356                if(in_array($categoria, $catgeorias) and in_array($subcategoria, $sub_categorias) and in_array($value, $values)) {
1357                    $search = false;
1358                }
1359            break;
1360        
1361        default:
1362                if(in_array($categoria, $catgeorias) and in_array($subcategoria, $sub_categorias) and in_array($value, $values) and in_array($importe, $importes) ) {
1363                    $search = false;
1364                }
1365            break;
1366    }
1367
1368
1369
1370    return $search;
1371}
1372
1373function generaLinkAAcuentaT($bcm_id)
1374{
1375    if (empty($bcm_id)) return '';
1376
1377    // Recuperamos de banco_cuenta_mov_link
1378    $sql = "SELECT * FROM banco_cuenta_mov_link WHERE banco_cuenta_mov_id = '$bcm_id'";
1379    $bcml = ia_singleton($sql);
1380
1381    if (empty($bcml)) return '';
1382
1383    // Recuperamos cuenta_t_mov_id del a cuenta origen (link_to)
1384    $field_id = "cuenta_t_mov_id";
1385    $field_cuentaT_id = "cuentaT_id";
1386    $link_to = $bcml['link_to'];
1387    $link_to_id = $bcml['link_to'] . "_id";
1388    switch ($link_to) {
1389        case 'cuentat_mov':
1390            $field_id = "cuentaT_mov_id";
1391            break;
1392        default:
1393                $field_id = "cuenta_t_mov_id";
1394            break;
1395    }
1396    $sql = "SELECT $field_id$field_cuentaT_id FROM $link_to WHERE $link_to_id = '$bcml[link]'";
1397    $acuenta = ia_singleton($sql);
1398    
1399    if (empty($acuenta)) return '';
1400
1401    $cuenta_t_mov_id = $acuenta[$field_id];
1402    $cuentaT_id = $acuenta['cuentaT_id'];
1403
1404    $sql = "SELECT usuario FROM cuentat WHERE cuentaT_id = $cuentaT_id";
1405    $cuentaT_usuario = ia_singleread($sql);
1406
1407   /*  $sql = "SELECT * FROM banco_cuenta_mov WHERE banco_cuenta_mov_id = '$bcm_id'";
1408    $bcm_current = ia_singleton($sql); */
1409
1410    $link_a_cuenat_t = '<a
1411                            href = "../backoffice/cuentat_mov.php?cuentat='.$cuentaT_id.'&selected_row_id='.$cuenta_t_mov_id.'"
1412                            rel = "opener refferer"
1413                            target = "_blank"
1414                            title="Ir al movimiento de CuentaT">'
1415                            .$cuentaT_usuario.
1416                        '</a>';
1417    return $link_a_cuenat_t;
1418}
1419
1420function leeIngresosEmpesas()
1421{
1422    global $configReporte;
1423    global $deposit_custom_where;
1424
1425    $html = "";
1426
1427    // Salen o no las cuentas sin movimientos, etc...
1428    $configReporte = array(
1429        'HideActiveSinMovimiento' => false, // true no sale en el listado principal las cuentas sin movimientos, false si salen
1430        'HideSaldoCero' => true, // ocultar cuenta si tiene saldo 0 y sbc 0.
1431    );
1432    $usuarioTipoRony = usuarioTipoRony();
1433    //VCA 26-02-2021 No queremos la cuenta de Rony aquí
1434    $bcarrayPESOS = cuenta_banco_mov_options('r', '', false, '1', null, false, false, false, true);
1435
1436    $sinRony = " bc.banco_cuenta_id NOT IN (SELECT banco_cuenta_id FROM banco_cuenta WHERE tipo_inversion_empresa_privada = 'privada') "; //" bc.banco_cuenta_id NOT IN ('39') "; // EL id de la cuenta de banco de Rony
1437
1438    $puedeVer = array();
1439    foreach ($bcarrayPESOS as $b) // banco cuenta con permiso nada no vienen en $bcarrayPESOS
1440        $puedeVer[$b['banco_cuenta_id']] = $b['banco_cuenta_id'];
1441    $cuentas = ia_sqlArray("SELECT
1442    bc.banco_cuenta_id,
1443    bc.nombre,
1444    bc.orden,
1445    bc.vale,
1446    bc.moneda_id,
1447    bc.banco_china,
1448    bc.numero,
1449    bc.ultima_conciliacion,
1450    bc.banco_id,
1451    b.banco,
1452    e.empresa
1453    FROM banco_cuenta bc
1454    LEFT OUTER JOIN banco b ON bc.banco_id=b.banco_id LEFT OUTER JOIN empresa e ON e.empresa_id = bc.empresa_id
1455    WHERE $sinRony
1456    ORDER BY bc.nombre", "banco_cuenta_id");
1457
1458    $sbc = ia_sqlArray("SELECT banco_cuenta_id, sbc as deposit_this_month, deposit_today, deposit_this_year, deposit_last_year, deposit_custom FROM banco_cuenta_saldos WHERE sbc > 0 AND $sinRony", "banco_cuenta_id");
1459
1460    $sbc = $sbc == false ? array() : $sbc;
1461
1462    /** OJO VCA saldo_actual cambiar por suma de depositos entre fechas y sin los que no deban de ir **/
1463    $cym = ia_sqlArray("SELECT bcs.banco_cuenta_id, bcs.orden, bcs.nombre, bcs.deposit_this_month, bcs.deposit_today, bcs.deposit_this_year, bcs.deposit_last_year, bcs.deposit_custom, bcs.Ultimo_Movimiento, bcs.Ultima_conciliacion, e.empresa
1464     FROM banco_cuenta_saldos bcs 
1465         JOIN banco_cuenta bc ON bc.banco_cuenta_id=bcs.banco_cuenta_id 
1466         JOIN empresa e ON e.empresa_id=bc.empresa_id
1467         WHERE $sinRony",
1468        "banco_cuenta_id");
1469
1470    uasort($cym, function ($a, $b) {
1471        if ($a['empresa'] === $b['empresa'])
1472            return strnatcasecmp($a['orden'], $b['orden']);
1473        return strnatcasecmp($a['empresa'], $b['empresa']);
1474    });
1475
1476    $sumGroupInitialValues = ['Total' => 0.00, 'Disponible' => 0.00, 'SBC' => 0.00, 'Ultimo_movimiento' => '', 'ultima_conciliacion' => '', 'deposit_today' => 0.00, 'deposit_custom' => 0.00];
1477    $sumGroup = []; // CAMBIO
1478    $sumaCuentas = 0.00;
1479    $sumaSBC = 0.00;
1480    $sumaDisp = 0.00;
1481    $sumaToday = 0.00;
1482    $sumaCustom = 0.00;
1483    $nowTime = strtotime('now');
1484    if (!empty($cym) && is_array($cym)) {
1485        foreach ($cym as $banco_cuenta_id => $t) {
1486            if ((isset($puedeVer[$banco_cuenta_id]) || $usuarioTipoRony) && $cuentas[$banco_cuenta_id]['moneda_id'] == 1 && $cuentas[$banco_cuenta_id]['vale'] == 'Active'
1487                && $cuentas[$banco_cuenta_id]['moneda_id'] == 1
1488            ) {
1489                $groupBy = $cuentas[$banco_cuenta_id]['empresa'];
1490                if (!isset($sumGroup[$groupBy]))
1491                    $sumGroup[$groupBy] = $sumGroupInitialValues;
1492
1493                $sumGroup[$groupBy]['deposit_today'] += $t['deposit_today'];
1494                $sumGroup[$groupBy]['Total'] += $t['deposit_this_month'];
1495                $sumGroup[$groupBy]['SBC'] += $t['deposit_last_year'];
1496                $sumGroup[$groupBy]['Disponible'] += $t['deposit_this_year'];
1497                $sumGroup[$groupBy]['deposit_custom'] += $t['deposit_custom'];
1498
1499                if ($t['Ultimo_Movimiento'] > $sumGroup[$groupBy]['Ultimo_movimiento'])
1500                    $sumGroup[$groupBy]['Ultimo_movimiento'] = $t['Ultimo_Movimiento'];
1501                if ($cuentas[$banco_cuenta_id]['ultima_conciliacion'] > $sumGroup[$groupBy]['ultima_conciliacion'])
1502                    $sumGroup[$groupBy]['ultima_conciliacion'] = $cuentas[$banco_cuenta_id]['ultima_conciliacion'];
1503            }
1504        }
1505
1506        $html .= table_header_vb('bancos_saldo', '', '');
1507        foreach ($cym as $banco_cuenta_id => $t)
1508            if ((isset($puedeVer[$banco_cuenta_id]) || $usuarioTipoRony) && $cuentas[$banco_cuenta_id]['moneda_id'] == 1 && $cuentas[$banco_cuenta_id]['vale'] == 'Active') {
1509                $saldos = @table_row_vb($banco_cuenta_id, $t, $sbc, 'txt_color_PESOS', $cuentas[$banco_cuenta_id], $nowTime, $sumGroup);
1510                $sumaCuentas += $saldos[0]; // $t['saldo_actual'];
1511                $sumaSBC += $saldos[2]; //
1512                $sumaDisp += $saldos[1]; //
1513                $sumaToday += $saldos[3]; //
1514                $html .= $saldos[4];
1515                $sumaCustom += $saldos[5]; //
1516            }
1517        $html .= table_footer_vb('txt_color_PESOS', '', $sumaCuentas, $sumaDisp, $sumaSBC, $sumaToday, $sumaCustom);
1518
1519        // reporta cuentas en usd
1520        $hayusd = null;
1521        $sumaCuentas = 0;
1522        $sumaSBC = 0;
1523        $sumaDisp = 0;
1524        $sumaToday = 0;
1525        $bcarrayUSD = cuenta_banco_mov_options('r', '', false, '2', null, false, false, false, true);
1526        $puedeVer = array();
1527        foreach ($bcarrayUSD as $b) // banco cuenta con permiso nada no vienen en $bcarrayUSD
1528            $puedeVer[$b['banco_cuenta_id']] = $b['banco_cuenta_id'];
1529
1530        foreach ($cym as $banco_cuenta_id => $t) {
1531            if (isset($puedeVer[$banco_cuenta_id]) && $cuentas[$banco_cuenta_id]['moneda_id'] != 1) {
1532                if ($hayusd === null) {
1533                    $hayusd = true;
1534                    $html .= table_header_vb('bancos_saldo_usd', 'Cuentas en USD', 'txt_color_USD');
1535
1536                    foreach ($cym as $banco_cuenta_id => $t)
1537                        //solo mostrar cuentas con permisos, en dolares y activas
1538                        if ((isset($puedeVer[$banco_cuenta_id]) || $usuarioTipoRony) && $cuentas[$banco_cuenta_id]['moneda_id'] != 1 && $cuentas[$banco_cuenta_id]['vale'] == 'Active') {
1539                            $saldos = @table_row_vb($banco_cuenta_id, $t, $sbc, 'txt_color_USD', $cuentas[$banco_cuenta_id], $nowTime);
1540                            $sumaCuentas += $saldos[0]; // $t['saldo_actual'];
1541                            $sumaSBC += $saldos[2]; //
1542                            $sumaDisp += $saldos[1]; //
1543                            $sumaToday += $saldos[3]; //
1544                            $html .= $saldos[4];
1545                            $sumaCustom += $saldos[5]; //
1546                        }
1547
1548                } // cuenta en USD o no pesos
1549            }
1550        }
1551        $html .= table_footer_vb('txt_color_USD', 'txt_color_USD', $sumaCuentas, $sumaDisp, $sumaSBC, $sumaToday, $sumaCustom);
1552    } // end if if(!empty($cym) && is_array($cym))
1553    return $html;
1554}
1555
1556function table_header_vb($table_id, $caption, $usdClass)
1557{
1558    global $deposit_custom_where;
1559
1560    $html = "";
1561    $expandCollapse =
1562        "
1563          <button type='button' class='copyit ui-corner-all' style='vertical-align: bottom;cursor:pointer;' title='Mostrar detalles de todas las cuentas' onclick='expandAll(this)'>
1564          <span class='ui-icon ui-icon-plus'></span>
1565          </button>
1566
1567          <button type='button' class='copyit ui-corner-all' style='vertical-align: bottom;cursor:pointer;' title='Ocultar detalles de todas las cuentas' onclick='collapseAll(this)'>
1568          <span class='ui-icon ui-icon-minus'></span>
1569          </button>
1570        ";
1571    if (usuarioTipoRony())
1572        $copy = "
1573            <div style='text-align:left' class='toolbar_exporter' id='toolbar_$table_id'>
1574              <button type='button' class='copyit ui-corner-all' style='vertical-align: bottom;cursor:pointer;' title='Copiar' data-clipboard-target='#$table_id'>
1575              <span class='ui-icon ui-icon-copy'></span>
1576              </button> $expandCollapse
1577
1578            </div>";
1579    else
1580        $copy = "<div style='text-align:left'>$expandCollapse</div>";
1581    $headerStyle = " style='font-weight:bold;font-size: 17px;color:#0000FF' ";
1582    $headerBlack = " style='font-weight:bold;font-size: 17px;color:black' ";
1583
1584    $headerStyle150 = " style='font-weight:bold;font-size: 17px;color:#0000FF; width:150px; '";
1585    $headerStyle200 = " style='font-weight:bold;font-size: 17px;color:#0000FF; width:200px; '";
1586    $headerStyle250 = " style='font-weight:bold;font-size: 17px;color:#0000FF; width:250px; '";
1587    $headerStyle450 = " style='font-weight:bold;font-size: 17px;color:#0000FF; width:400px; '";
1588    $headerBlack150 = " style='font-weight:bold;font-size: 17px;color:black; width:150px; '";
1589    $headerBlack110 = " style='font-weight:bold;font-size: 17px;color:black; width:110px; '";
1590    $headerBlack250 = " style='font-weight:bold;font-size: 17px;color:black; width:250px; '";
1591
1592    $now = strtotime("now");
1593    $txt_this_year = date('Y');
1594    $txt_today = "HOY " . get_date_spanish($now, false, 'small_date', 'month_mini');
1595    $txt_this_month = strtoupper(get_date_spanish($now, true, 'month', 'month_mini')) . " " . $txt_this_year;
1596    $txt_last_year = date('Y', strtotime("last year"));
1597
1598    $json_custom_nombre = ia_singleread("SELECT deposit_custom_where FROM banco_cuenta_saldos WHERE banco_cuenta_id > 0 LIMIT 1");
1599    //error_log($txt_custom_nombre);
1600    $obj_custom_nombre = empty($json_custom_nombre) ? new stdClass(): json_decode($json_custom_nombre);
1601
1602    $obj_custom_nombre->txt_mes = $obj_custom_nombre->txt_mes ?? '';
1603    $obj_custom_nombre->fecha_ini = $obj_custom_nombre->fecha_ini ?? '';
1604    $obj_custom_nombre->fecha_fin = $obj_custom_nombre->fecha_fin ?? '';
1605    $obj_custom_nombre->mes = !empty($obj_custom_nombre->fecha_ini) ? date("n",strtotime($obj_custom_nombre->fecha_ini)) : '';
1606
1607    $txt_custom_nombre = property_exists($obj_custom_nombre,"txt_mes") ? strtoupper($obj_custom_nombre->txt_mes) : "";
1608
1609    if(empty($txt_custom_nombre) &&
1610        (   property_exists($obj_custom_nombre,"fecha_ini") && !empty($obj_custom_nombre->fecha_ini) ||
1611            property_exists($obj_custom_nombre,"fecha_fin") && !empty($obj_custom_nombre->fecha_fin)))
1612    {
1613        if(property_exists($obj_custom_nombre,"fecha_ini"))
1614            $txt_custom_nombre .= "DEL " . strtoupper(get_date_spanish(strtotime($obj_custom_nombre->fecha_ini), false, 'small_date'));
1615
1616        if(property_exists($obj_custom_nombre,"fecha_fin"))
1617            $txt_custom_nombre .= (!empty($txt_custom_nombre) ? "<br />" : "") . " AL " . strtoupper(get_date_spanish(strtotime($obj_custom_nombre->fecha_fin), false, 'small_date'));
1618
1619    }
1620
1621
1622    $txt_custom = "$txt_custom_nombre<div id='deposit_custom_dates' data-fecha_ini='$obj_custom_nombre->fecha_ini' data-fecha_fin='$obj_custom_nombre->fecha_fin' data-txt_mes='$obj_custom_nombre->txt_mes' data-mes='$obj_custom_nombre->mes'></div>";
1623
1624    $html .= "<div id='div_$table_id' align='center' style='width:95%;margin-left:auto;margin-right:auto;margin-top:32px;'>$copy
1625            <table id='$table_id' class='tabla tablausd tablesorter' align='center' >" .
1626        "<caption>$caption</caption><thead>" .
1627        "<tr class='tablesorter-headerRow'>" .
1628
1629        "<th class='cen lbl $usdClass$headerStyle450>EMPRESA</th>" .
1630
1631        "<th class='cen lbl $usdClass$headerStyle250>CUENTA</th>" .
1632
1633        "<th class='cen lbl $usdClass$headerStyle150>$txt_today</th>" .
1634        "<th class='cen lbl $usdClass$headerStyle150>$txt_this_month</th>" .
1635        "<th class='cen $usdClass$headerBlack150>$txt_this_year</th>" .
1636        "<th class='group-false cen rojo' style='width:150px; font-weight:bold;font-size:17px;color:red !important'>$txt_last_year</th>" .
1637        "<th class='cen $usdClass$headerBlack150>$txt_custom</th>" .
1638
1639        "</tr></thead><tbody>";
1640
1641    return $html;
1642}
1643
1644function showCuenta($banco_cuenta_id, $t, $sbc)
1645{
1646    global $configReporte;
1647    $sbcActual = array_key_exists($banco_cuenta_id, $sbc) ? $sbc[$banco_cuenta_id]['deposit_this_month'] : 0.00;
1648    if ($configReporte['HideActiveSinMovimiento'] && (
1649        (empty($sbcActual) && empty($t['Ultimo_Movimiento']) && empty($t['deposit_this_month']) && empty($sbc[$banco_cuenta_id]) && empty($sbc[$banco_cuenta_id]['deposit_this_month']))
1650        )) {
1651        return false;
1652    }
1653    if ($configReporte['HideSaldoCero'] && (empty($t['deposit_this_month']) && empty($sbc[$banco_cuenta_id]) && empty($sbc[$banco_cuenta_id]['deposit_this_month']))) {
1654        return false;
1655    }
1656
1657    return true;
1658}
1659
1660function table_row_vb($banco_cuenta_id, $t, $sbc, $monedaClass, $cuentaBancaria, $nowTime, $sumGroup = [])
1661{
1662    global $configReporte;
1663    $html = "";
1664    static $prevGroupedBy = "\t";
1665
1666    if (!showCuenta($banco_cuenta_id, $t, $sbc)) {
1667        return array(0, 0);
1668    }
1669    $sbcActual = array_key_exists($banco_cuenta_id, $sbc) ? $sbc[$banco_cuenta_id]['deposit_this_month'] : 0.00;
1670    $txtsbcActual = $sbcActual > 0 ? echonf($sbcActual, true) : '';
1671    /*
1672            if($configReporte['HideActiveSinMovimiento'] && (
1673                (empty($sbcActual) && empty($t['Ultimo_Movimiento']) && empty($t['saldo_actual']) && empty($sbc[$banco_cuenta_id]) && empty($sbc[$banco_cuenta_id]['saldo_actual'])  )
1674            )) {
1675                return array(0, 0);
1676            }
1677            if($configReporte['HideSaldoCero'] && (empty($t['saldo_actual']) && empty($sbc[$banco_cuenta_id]) && empty($sbc[$banco_cuenta_id]['saldo_actual'])  ) ) {
1678                return array(0, 0);
1679            }
1680    */
1681
1682    $font = " tableSorterCo";
1683
1684    if ($prevGroupedBy != $cuentaBancaria['empresa']) {
1685        $prevGroupedBy = $cuentaBancaria['empresa'];
1686        $grp = $sumGroup[$prevGroupedBy];
1687
1688        if (empty($grp['ultima_conciliacion'])) {
1689            $fuchG = $ultima_concG = $txt_difHorasG = '';
1690        } else {
1691            $fuchG = strtotime($grp['ultima_conciliacion']);
1692            $txt_difHorasG = txtHaceCuantoTiempo($fuchG, $nowTime, $monedaClass);
1693            $ultima_concG = get_date_spanish($fuchG, false, 'small_date', 'month_mini') . " - " . date('H:i:s', $fuchG);
1694        }
1695
1696        $html .= "\r\n\r\n\r\n<tr class='tablesorter-hasChildRow Group1'><td colspan=2>
1697                <a href='#' class='toggle asin txt_color_PESOS'>&#x25b6; " . $cuentaBancaria['empresa'] . "</a></td>";
1698        $html .= "<td class='der groupTotal txt_color_PESOS bold saldo_actual nwp'>" . echonf($grp['deposit_today'], true) . "</td>";
1699        $html .= "<td class='der groupTotal txt_color_PESOS bold saldo_actual nwp'>" . echonf($grp['Total'], true) . "</td>";
1700        $html .= "<td class='der groupTotal bold nwp'>" . echonf($grp['Disponible'], true) . "</td>";
1701        $html .= "<td class='der bold rojo groupTotal'>" . ($grp['SBC'] == 0 ? '' : echonf($grp['SBC'], true)) . "</td>";
1702        $html .= "<td class='der groupTotal bold nwp'>" . echonf($grp['deposit_custom'], true) . "</td>";
1703
1704        $html .= "</tr>\r\n\r\n";
1705
1706    }
1707
1708    if (empty($cuentaBancaria['ultima_conciliacion'])) {
1709        $fuch = $ultima_conc = $txt_difHoras = '';
1710    } else {
1711        $fuch = $cuentaBancaria['ultima_conciliacion'];
1712        $fuch = strtotime($fuch);
1713        $txt_difHoras = txtHaceCuantoTiempo($fuch, $nowTime, $monedaClass);
1714        $ultima_conc = get_date_spanish($fuch, false, 'small_date', 'month_mini') . " - " . date('H:i:s', $fuch);
1715    }
1716    $collapsed = 'display:none;';
1717    $atitle = "title='" . htmlentities($cuentaBancaria['banco'] . ' #cta: ' . $cuentaBancaria['numero'], ENT_QUOTES) . "'";
1718    $html .= "\r\n<tr class='tablesorter-childRow $cuentaBancaria[vale]' >" .
1719
1720        "<td style='$collapsed ' class='$monedaClass $font nwp'>&nbsp;" .
1721        "<td style='$collapsed ' class='$font nwp'>" .
1722        "<a  class='asin $monedaClass'  $atitle href='../cobranza/edocta.php?ACC=CB&ECO=SI&banco_cuenta_id=$t[banco_cuenta_id]' target='_blank'><strong>" .
1723        ia_htmlentities($cuentaBancaria['nombre']) . "</strong>" .
1724        "</a>" .
1725        "<td style='$collapsed' class='der $monedaClass bold saldo_actual $font nwp'>" . echonf($t['deposit_today'], true) .
1726        "<td style='$collapsed' class='der $monedaClass bold saldo_actual $font nwp'>" . echonf($t['deposit_this_month'], true) .
1727        "<td style='$collapsed' class='der bold $font'>" . echonf($t['deposit_this_year'], true) .
1728        "<td style='$collapsed' class='der bold rojo $font $font'>" . echonf($t['deposit_last_year'], true) .
1729        "<td style='$collapsed' class='der bold $font'>" . echonf($t['deposit_custom'], true) .
1730
1731
1732        "</tr>";
1733
1734    return array($t['deposit_this_month'], $t['deposit_this_year'], $t['deposit_last_year'], $t['deposit_today'], $html, $t['deposit_custom']);
1735}
1736
1737function table_footer_vb($class1, $class2, $sumaCuentas, $sumaDisp, $sumaSBC, $sumaToday, $sumaCustom)
1738{
1739    $html = "</tbody><tfoot><tr>" .
1740        "<td colspan=2 class='der bold $class2' style='font-size:17px;font-weight:700'>SUMAS:" .
1741        "<td class='der bold $class1' style='font-size:17px;font-weight:700'>" . echonf($sumaToday, true) .
1742        "<td class='der bold $class1' style='font-size:17px;font-weight:700'>" . echonf($sumaCuentas, true) .
1743        "<td class='der bold' style='font-size:17px;font-weight:700'>" . echonf($sumaDisp, true) .
1744        "<td class='der rojo bold' style='font-size:17px;font-weight:700'>" . echonf($sumaSBC, true) .
1745        "<td class='der bold' style='font-size:17px;font-weight:700'>" . echonf($sumaCustom, true) .
1746        "</tr>" .
1747        "</tfoot></table></div>";
1748
1749    return $html;
1750}
1751
1752
1753function leeFiduciariosEmpesas()
1754{
1755    global $configReporte;
1756    global $fiduciario_custom_where;
1757
1758    $html = "";
1759
1760    // Salen o no las cuentas sin movimientos, etc...
1761    $configReporte = array(
1762        'HideActiveSinMovimiento' => false, // true no sale en el listado principal las cuentas sin movimientos, false si salen
1763        'HideSaldoCero' => true, // ocultar cuenta si tiene saldo 0 y sbc 0.
1764    );
1765    $usuarioTipoRony = usuarioTipoRony();
1766
1767    $bcarrayPESOS = cuenta_banco_mov_options('r', '', false, '1', null, false, false, false, true);
1768
1769
1770    $puedeVer = array();
1771    foreach ($bcarrayPESOS as $b) // banco cuenta con permiso nada no vienen en $bcarrayPESOS
1772        $puedeVer[$b['banco_cuenta_id']] = $b['banco_cuenta_id'];
1773    $cuentas = ia_sqlArray("SELECT
1774    bc.banco_cuenta_id,
1775    bc.nombre,
1776    bc.orden,
1777    bc.vale,
1778    bc.moneda_id,
1779    bc.banco_china,
1780    bc.numero,
1781    bc.ultima_conciliacion,
1782    bc.banco_id,
1783    b.banco,
1784    e.empresa
1785    FROM banco_cuenta bc
1786    LEFT OUTER JOIN banco b ON bc.banco_id=b.banco_id LEFT OUTER JOIN empresa e ON e.empresa_id = bc.empresa_id
1787    ORDER BY bc.nombre", "banco_cuenta_id");
1788
1789    //$sbc = ia_sqlArray("SELECT banco_cuenta_id, sbc as deposit_this_month, fiduciario_all, deposit_this_year, deposit_last_year, deposit_custom FROM banco_cuenta_saldos WHERE sbc > 0", "banco_cuenta_id");
1790
1791
1792    $sbc = ia_sqlArray("SELECT banco_cuenta_id, sbc as     fiduciario_all, fiduciario_this_month, fiduciario_this_year, fiduciario_last_year, fiduciario_custom FROM banco_cuenta_saldos WHERE sbc > 0", "banco_cuenta_id");
1793
1794    /** OJO VCA saldo_actual cambiar por suma de depositos entre fechas y sin los que no deban de ir **/
1795    $cym = ia_sqlArray("SELECT bcs.banco_cuenta_id, bcs.orden, bcs.nombre, bcs.fiduciario_all, bcs.fiduciario_this_month, bcs.fiduciario_this_year, bcs.fiduciario_last_year, bcs.fiduciario_custom, fiduciario_all, bcs.Ultimo_Movimiento, bcs.Ultima_conciliacion, e.empresa FROM banco_cuenta_saldos bcs JOIN banco_cuenta bc ON  bc.banco_cuenta_id=bcs.banco_cuenta_id JOIN empresa e ON e.empresa_id=bc.empresa_id",
1796        "banco_cuenta_id");
1797
1798    uasort($cym, function ($a, $b) {
1799        if ($a['empresa'] === $b['empresa'])
1800            return strnatcasecmp($a['orden'], $b['orden']);
1801        return strnatcasecmp($a['empresa'], $b['empresa']);
1802    });
1803
1804    $sumGroupInitialValues = ['Total' => 0.00, 'Disponible' => 0.00, 'SBC' => 0.00, 'Ultimo_movimiento' => '', 'ultima_conciliacion' => '', 'fiduciario_all' => 0.00, 'fiduciario_this_month' => 0.00, 'fiduciario_this_year' => 0.00, 'fiduciario_last_year' => 0.00, 'fiduciario_custom' => 0.00];
1805    $sumGroup = []; // CAMBIO
1806    $sumaCuentas = 0.00;
1807    $sumaSBC = 0.00;
1808    $sumaDisp = 0.00;
1809    $sumaToday = 0.00;
1810    $sumaCustom = 0.00;
1811    $nowTime = strtotime('now');
1812    if (!empty($cym) && is_array($cym)) {
1813        foreach ($cym as $banco_cuenta_id => $t) {
1814            if ((isset($puedeVer[$banco_cuenta_id]) || $usuarioTipoRony) && $cuentas[$banco_cuenta_id]['moneda_id'] == 1 && $cuentas[$banco_cuenta_id]['vale'] == 'Active'
1815                && $cuentas[$banco_cuenta_id]['moneda_id'] == 1
1816            ) {
1817                $groupBy = $cuentas[$banco_cuenta_id]['empresa'];
1818                if (!isset($sumGroup[$groupBy]))
1819                    $sumGroup[$groupBy] = $sumGroupInitialValues;
1820
1821                $sumGroup[$groupBy]['fiduciario_all'] += $t['fiduciario_all'];
1822                $sumGroup[$groupBy]['Total'] += $t['fiduciario_this_month'];
1823                $sumGroup[$groupBy]['SBC'] += $t['fiduciario_last_year'];
1824                $sumGroup[$groupBy]['Disponible'] += $t['fiduciario_this_year'];
1825                $sumGroup[$groupBy]['fiduciario_custom'] += $t['fiduciario_custom'];
1826
1827                if ($t['Ultimo_Movimiento'] > $sumGroup[$groupBy]['Ultimo_movimiento'])
1828                    $sumGroup[$groupBy]['Ultimo_movimiento'] = $t['Ultimo_Movimiento'];
1829                if ($cuentas[$banco_cuenta_id]['ultima_conciliacion'] > $sumGroup[$groupBy]['ultima_conciliacion'])
1830                    $sumGroup[$groupBy]['ultima_conciliacion'] = $cuentas[$banco_cuenta_id]['ultima_conciliacion'];
1831            }
1832        }
1833
1834        $html .= fid_table_header_vb('bancos_saldo', '', '');
1835        foreach ($cym as $banco_cuenta_id => $t)
1836            if ((isset($puedeVer[$banco_cuenta_id]) || $usuarioTipoRony) && $cuentas[$banco_cuenta_id]['moneda_id'] == 1 && $cuentas[$banco_cuenta_id]['vale'] == 'Active') {
1837                $saldos = fid_table_row($banco_cuenta_id, $t, $sbc, 'txt_color_PESOS', $cuentas[$banco_cuenta_id], $nowTime, $sumGroup);
1838                $sumaCuentas += $saldos[0]; // $t['saldo_actual'];
1839                $sumaSBC += $saldos[2]; //
1840                $sumaDisp += $saldos[1]; //
1841                $sumaToday += $saldos[3]; //
1842                $html .= $saldos[4];
1843                $sumaCustom += $saldos[5]; //
1844            }
1845        $html .= fid_table_footer('txt_color_PESOS', '', $sumaCuentas, $sumaDisp, $sumaSBC, $sumaToday, $sumaCustom);
1846
1847        // reporta cuentas en usd
1848        $hayusd = null;
1849        $sumaCuentas = 0;
1850        $sumaSBC = 0;
1851        $sumaDisp = 0;
1852        $sumaToday = 0;
1853        $bcarrayUSD = array(); //cuenta_banco_mov_options('r', '', false, '2', null, false, false, false, true);
1854        $puedeVer = array();
1855        foreach ($bcarrayUSD as $b) // banco cuenta con permiso nada no vienen en $bcarrayUSD
1856            $puedeVer[$b['banco_cuenta_id']] = $b['banco_cuenta_id'];
1857
1858        foreach ($cym as $banco_cuenta_id => $t) {
1859            if (isset($puedeVer[$banco_cuenta_id]) && $cuentas[$banco_cuenta_id]['moneda_id'] != 1) {
1860                if ($hayusd === null) {
1861                    $hayusd = true;
1862                    $html .= fid_table_header_vb('bancos_saldo_usd', 'Cuentas en USD', 'txt_color_USD');
1863                }
1864                foreach ($cym as $banco_cuenta_id => $t)
1865                    //solo mostrar cuentas con permisos, en dolares y activas
1866                    if ((isset($puedeVer[$banco_cuenta_id]) || $usuarioTipoRony) && $cuentas[$banco_cuenta_id]['moneda_id'] != 1 && $cuentas[$banco_cuenta_id]['vale'] == 'Active') {
1867                        $saldos = fid_table_row($banco_cuenta_id, $t, $sbc, 'txt_color_USD', $cuentas[$banco_cuenta_id], $nowTime);
1868                        $sumaCuentas += $saldos[0]; // $t['saldo_actual'];
1869                        $sumaSBC += $saldos[2]; //
1870                        $sumaDisp += $saldos[1]; //
1871                        $sumaToday += $saldos[3]; //
1872                        $html .= $saldos[4];
1873                        $sumaCustom += $saldos[5]; //
1874                    }
1875                $html .= fid_table_footer('txt_color_USD', 'txt_color_USD', $sumaCuentas, $sumaDisp, $sumaSBC, $sumaToday, $sumaCustom);
1876            } // cuenta en USD o no pesos
1877        }
1878    } // end if if(!empty($cym) && is_array($cym))
1879
1880    ia_errores_a_dime();
1881    return $html;
1882}
1883
1884function fid_table_header_vb($table_id, $caption, $usdClass)
1885{
1886    global $fiduciario_custom_where;
1887
1888    $html = "";
1889    $expandCollapse =
1890        "
1891          <button type='button' class='copyit ui-corner-all' style='vertical-align: bottom;cursor:pointer;' title='Mostrar detalles de todas las cuentas' onclick='expandAll(this)'>
1892          <span class='ui-icon ui-icon-plus'></span>
1893          </button>
1894
1895          <button type='button' class='copyit ui-corner-all' style='vertical-align: bottom;cursor:pointer;' title='Ocultar detalles de todas las cuentas' onclick='collapseAll(this)'>
1896          <span class='ui-icon ui-icon-minus'></span>
1897          </button>
1898        ";
1899    if (usuarioTipoRony())
1900        $copy = "
1901            <div style='text-align:left' class='toolbar_exporter' id='toolbar_$table_id'>
1902              <button type='button' class='copyit ui-corner-all' style='vertical-align: bottom;cursor:pointer;' title='Copiar' data-clipboard-target='#$table_id'>
1903              <span class='ui-icon ui-icon-copy'></span>
1904              </button> $expandCollapse
1905
1906            </div>";
1907    else
1908        $copy = "<div style='text-align:left'>$expandCollapse</div>";
1909    $headerStyle = " style='font-weight:bold;font-size: 17px;color:#0000FF' ";
1910    $headerBlack = " style='font-weight:bold;font-size: 17px;color:black' ";
1911
1912    $headerStyle150 = " style='font-weight:bold;font-size: 17px;color:#0000FF; width:150px; '";
1913    $headerStyle200 = " style='font-weight:bold;font-size: 17px;color:#0000FF; width:200px; '";
1914    $headerStyle250 = " style='font-weight:bold;font-size: 17px;color:#0000FF; width:250px; '";
1915    $headerStyle450 = " style='font-weight:bold;font-size: 17px;color:#0000FF; width:400px; '";
1916    $headerBlack150 = " style='font-weight:bold;font-size: 17px;color:black; width:150px; '";
1917    $headerBlack110 = " style='font-weight:bold;font-size: 17px;color:black; width:110px; '";
1918    $headerBlack250 = " style='font-weight:bold;font-size: 17px;color:black; width:250px; '";
1919
1920    $now = strtotime("now");
1921    $txt_this_year = date('Y');
1922    $txt_today = "ACTIVOS";
1923    $txt_this_month = strtoupper(get_date_spanish($now, true, 'month', 'month_mini')) . " " . $txt_this_year;
1924    $txt_last_year = date('Y', strtotime("last year"));
1925
1926    $json_custom_nombre = ia_singleread("SELECT fiduciario_custom_where FROM banco_cuenta_saldos WHERE banco_cuenta_id > 0 LIMIT 1");
1927    //error_log($txt_custom_nombre);
1928    $obj_custom_nombre = empty($json_custom_nombre) ? new stdClass(): json_decode($json_custom_nombre);
1929
1930    $txt_custom_nombre = property_exists($obj_custom_nombre,"txt_mes") ? strtoupper($obj_custom_nombre->txt_mes) : "";
1931
1932    if(empty($txt_custom_nombre) &&
1933        (   property_exists($obj_custom_nombre,"fecha_ini") && !empty($obj_custom_nombre->fecha_ini) ||
1934            property_exists($obj_custom_nombre,"fecha_fin") && !empty($obj_custom_nombre->fecha_fin)))
1935    {
1936        if(property_exists($obj_custom_nombre,"fecha_ini"))
1937            $txt_custom_nombre .= "DEL " . strtoupper(get_date_spanish(strtotime($obj_custom_nombre->fecha_ini), false, 'small_date'));
1938
1939        if(property_exists($obj_custom_nombre,"fecha_fin"))
1940            $txt_custom_nombre .= (!empty($txt_custom_nombre) ? "<br />" : "") . " AL " . strtoupper(get_date_spanish(strtotime($obj_custom_nombre->fecha_fin), false, 'small_date'));
1941
1942    }
1943
1944
1945    $txt_custom = "$txt_custom_nombre<div id='deposit_custom_dates'></div>";
1946
1947    $html .= "<div id='div_$table_id' align='center' style='width:95%;margin-left:auto;margin-right:auto;margin-top:32px;'>$copy
1948            <table id='$table_id' class='tabla tablausd tablesorter' align='center' >" .
1949        "<caption>$caption</caption><thead>" .
1950        "<tr class='tablesorter-headerRow'>" .
1951
1952        "<th class='cen lbl $usdClass$headerStyle450>EMPRESA</th>" .
1953
1954        "<th class='cen lbl $usdClass$headerStyle250>CUENTA</th>" .
1955
1956        "<th class='cen lbl $usdClass$headerStyle150>$txt_today</th>" .
1957        "<th class='cen lbl $usdClass$headerStyle150>$txt_this_month</th>" .
1958        "<th class='cen $usdClass$headerBlack150>$txt_this_year</th>" .
1959        "<th class='group-false cen rojo' style='width:150px; font-weight:bold;font-size:17px;color:red !important'>$txt_last_year</th>" .
1960        "<th class='cen $usdClass$headerBlack150>$txt_custom</th>" .
1961
1962        "</tr></thead><tbody>";
1963
1964    return $html;
1965}
1966
1967function fid_showCuenta($banco_cuenta_id, $t, $sbc)
1968{
1969    global $configReporte;
1970    $sbcActual = array_key_exists($banco_cuenta_id, $sbc) ? $sbc[$banco_cuenta_id]['fiduciario_this_month'] : 0.00;
1971    if ($configReporte['HideActiveSinMovimiento'] && (
1972        (empty($sbcActual) && empty($t['Ultimo_Movimiento']) && empty($t['fiduciario_this_month']) && empty($sbc[$banco_cuenta_id]) && empty($sbc[$banco_cuenta_id]['fiduciario_this_month']))
1973        )) {
1974        return false;
1975    }
1976    if ($configReporte['HideSaldoCero'] && (empty($t['fiduciario_this_month']) && empty($sbc[$banco_cuenta_id]) && empty($sbc[$banco_cuenta_id]['fiduciario_this_month']))) {
1977        return false;
1978    }
1979
1980    return true;
1981}
1982
1983function fid_table_row($banco_cuenta_id, $t, $sbc, $monedaClass, $cuentaBancaria, $nowTime, $sumGroup = [])
1984{
1985    global $configReporte;
1986    $html = "";
1987    static $prevGroupedBy = "\t";
1988
1989    if (!fid_showCuenta($banco_cuenta_id, $t, $sbc)) {
1990        return array(0, 0);
1991    }
1992    $sbcActual = array_key_exists($banco_cuenta_id, $sbc) ? $sbc[$banco_cuenta_id]['fiduciario_this_month'] : 0.00;
1993    $txtsbcActual = $sbcActual > 0 ? echonf($sbcActual, true) : '';
1994    /*
1995            if($configReporte['HideActiveSinMovimiento'] && (
1996                (empty($sbcActual) && empty($t['Ultimo_Movimiento']) && empty($t['saldo_actual']) && empty($sbc[$banco_cuenta_id]) && empty($sbc[$banco_cuenta_id]['saldo_actual'])  )
1997            )) {
1998                return array(0, 0);
1999            }
2000            if($configReporte['HideSaldoCero'] && (empty($t['saldo_actual']) && empty($sbc[$banco_cuenta_id]) && empty($sbc[$banco_cuenta_id]['saldo_actual'])  ) ) {
2001                return array(0, 0);
2002            }
2003    */
2004
2005    $font = " tableSorterCo";
2006
2007    if ($prevGroupedBy != $cuentaBancaria['empresa']) {
2008        $prevGroupedBy = $cuentaBancaria['empresa'];
2009        $grp = $sumGroup[$prevGroupedBy];
2010
2011        if (empty($grp['ultima_conciliacion'])) {
2012            $fuchG = $ultima_concG = $txt_difHorasG = '';
2013        } else {
2014            $fuchG = strtotime($grp['ultima_conciliacion']);
2015            $txt_difHorasG = txtHaceCuantoTiempo($fuchG, $nowTime, $monedaClass);
2016            $ultima_concG = get_date_spanish($fuchG, false, 'small_date', 'month_mini') . " - " . date('H:i:s', $fuchG);
2017        }
2018
2019        $html .= "\r\n\r\n\r\n<tr class='tablesorter-hasChildRow Group1'><td colspan=2>
2020                <a href='#' class='toggle asin txt_color_PESOS'>&#x25b6; " . $cuentaBancaria['empresa'] . "</a></td>";
2021        $html .= "<td class='der groupTotal txt_color_PESOS bold saldo_actual nwp'>" . echonf($grp['fiduciario_all'], true) . "</td>";
2022        $html .= "<td class='der groupTotal txt_color_PESOS bold saldo_actual nwp'>" . echonf($grp['Total'], true) . "</td>";
2023        $html .= "<td class='der groupTotal bold nwp'>" . echonf($grp['Disponible'], true) . "</td>";
2024        $html .= "<td class='der bold rojo groupTotal'>" . ($grp['SBC'] == 0 ? '' : echonf($grp['SBC'], true)) . "</td>";
2025        $html .= "<td class='der groupTotal bold nwp'>" . echonf($grp['fiduciario_custom'], true) . "</td>";
2026
2027        $html .= "</tr>\r\n\r\n";
2028
2029    }
2030
2031    if (empty($cuentaBancaria['ultima_conciliacion'])) {
2032        $fuch = $ultima_conc = $txt_difHoras = '';
2033    } else {
2034        $fuch = $cuentaBancaria['ultima_conciliacion'];
2035        $fuch = strtotime($fuch);
2036        $txt_difHoras = txtHaceCuantoTiempo($fuch, $nowTime, $monedaClass);
2037        $ultima_conc = get_date_spanish($fuch, false, 'small_date', 'month_mini') . " - " . date('H:i:s', $fuch);
2038    }
2039    $collapsed = 'display:none;';
2040    $atitle = "title='" . htmlentities($cuentaBancaria['banco'] . ' #cta: ' . $cuentaBancaria['numero'], ENT_QUOTES) . "'";
2041    $html .= "\r\n<tr class='tablesorter-childRow $cuentaBancaria[vale]' >" .
2042
2043        "<td style='$collapsed ' class='$monedaClass $font nwp'>&nbsp;" .
2044        "<td style='$collapsed ' class='$font nwp'>" .
2045        "<a  class='asin $monedaClass'  $atitle href='../cobranza/edocta.php?ACC=CB&ECO=SI&banco_cuenta_id=$t[banco_cuenta_id]' target='_blank'><strong>" .
2046        ia_htmlentities($cuentaBancaria['nombre']) . "</strong>" .
2047        "</a>" .
2048        "<td style='$collapsed' class='der $monedaClass bold saldo_actual $font nwp'>" . echonf($t['fiduciario_all'], true) .
2049        "<td style='$collapsed' class='der $monedaClass bold saldo_actual $font nwp'>" . echonf($t['fiduciario_this_month'], true) .
2050        "<td style='$collapsed' class='der bold $font'>" . echonf($t['fiduciario_this_year'], true) .
2051        "<td style='$collapsed' class='der bold rojo $font $font'>" . echonf($t['fiduciario_last_year'], true) .
2052        "<td style='$collapsed' class='der bold $font'>" . echonf($t['fiduciario_custom'], true) .
2053
2054
2055        "</tr>";
2056
2057    return array($t['fiduciario_this_month'], $t['fiduciario_this_year'], $t['fiduciario_last_year'], $t['fiduciario_all'], $html, $t['fiduciario_custom']);
2058}
2059
2060function fid_table_footer($class1, $class2, $sumaCuentas, $sumaDisp, $sumaSBC, $sumaToday, $sumaCustom)
2061{
2062    $html = "";
2063    $html .= "</tbody><tfoot><tr>" .
2064        "<td colspan=2 class='der bold $class2' style='font-size:17px;font-weight:700'>SUMAS:" .
2065        "<td class='der bold $class1' style='font-size:17px;font-weight:700'>" . echonf($sumaToday, true) .
2066        "<td class='der bold $class1' style='font-size:17px;font-weight:700'>" . echonf($sumaCuentas, true) .
2067        "<td class='der bold' style='font-size:17px;font-weight:700'>" . echonf($sumaDisp, true) .
2068        "<td class='der rojo bold' style='font-size:17px;font-weight:700'>" . echonf($sumaSBC, true) .
2069        "<td class='der bold' style='font-size:17px;font-weight:700'>" . echonf($sumaCustom, true) .
2070
2071        "</tr>" .
2072        "</tfoot></table></div>";
2073
2074    return $html;
2075}
2076
2077//Funciones de José
2078function buscaEnTablaSobreCampoElValor($in_table, $on_field, $this_value, $is_pk = false)
2079{
2080    $sql = "SELECT * FROM $in_table WHERE $on_field = '$this_value'";
2081
2082    if ($is_pk) {
2083        $result = ia_singleton($sql);
2084    } else {
2085        $result = ia_sqlArray($sql, $on_field);
2086    }
2087    return $result;
2088}
2089
2090function quitaIndiceRepetidoDeRepetidos ($bcmenDB, $bcm_id, &$sqlSet)
2091{
2092    // Se obtienen los repetidos actuales (antes de realizar cualquier otra acción)
2093    $repetidos_string = trim($bcmenDB['mov_repetido_id']);
2094    if ($repetidos_string !== ""){
2095        $current_duplicates = explode(",", $repetidos_string);
2096        if (count($current_duplicates) > 0) {
2097            foreach ($current_duplicates as $bcmid_repetido){
2098                if ($bcm_id !== $bcmid_repetido){
2099                    // Se busca el BCM con el que esta repetido
2100                    $bcmRepedido = buscaEnTablaSobreCampoElValor('banco_cuenta_mov', 'banco_cuenta_mov_id', $bcmid_repetido, true);
2101                    if (!isset($bcmRepedido['mov_repetido_id'])) {
2102                        return;
2103                    }
2104                    // Se obtienen los repetidos del BCM repetido
2105                    $repetidos = explode(",", trim($bcmRepedido['mov_repetido_id']));
2106                    // Comprueba que el BCM se encuentre en los repetidos del repetido
2107                    if (in_array($bcm_id, $repetidos)){
2108                        // Se obtiene la posicion para eliminarlo de repetidos del repetido
2109                        $position = array_search($bcm_id, $repetidos);
2110                        unset($repetidos[$position]);
2111                        // Se crean nuevos repetidos del repetido
2112                        $nuevos_repetidos = implode(",", $repetidos);
2113                        // Se valida que repetidos sea mayor a 1 para que pueda ser repetido y no se repita con el mismo
2114                        if (count($repetidos) < 2) {
2115                            if ($nuevos_repetidos == $bcmid_repetido){
2116                                $remarks = str_replace("txt_bold_red txt_underline", "", $bcmRepedido['remarks']);
2117                                $sqlSet[] = "UPDATE banco_cuenta_mov SET repetido = 'No', mov_repetido_id = '', remarks = ". strit(ltrim(trim($remarks))) ." WHERE banco_cuenta_mov_id = '$bcmid_repetido'";
2118                            }
2119                        } else {
2120                            $sqlSet[] = "UPDATE banco_cuenta_mov SET mov_repetido_id = '$nuevos_repetidos' WHERE banco_cuenta_mov_id = '$bcmid_repetido'";
2121                        }
2122                    }
2123                }
2124            }
2125        }
2126        // Se quita el subrayado de remarks
2127        $bcmenDB['remarks'] = str_replace("txt_bold_red txt_underline", "", $bcmenDB['remarks']);
2128        $new_remarks = $bcmenDB['remarks'];
2129        $sqlSet[] = "UPDATE banco_cuenta_mov SET repetido = 'No', mov_repetido_id = '', remarks = ". strit(ltrim(trim($new_remarks))) ." WHERE banco_cuenta_mov_id = '$bcm_id'";
2130    }
2131}
2132
2133/** Busca los BCM repetidos de la misma empresa el mismo mes
2134 * @param $bcm_id string El banco_cuenta_mov_id del que se desea saber si hay repetidos
2135 * @param $remarks array El array donde se retornaran los query´s de los repetidos
2136 * @return void
2137 */
2138function buscaRepetidoSAT($bcm_id, &$remarks)
2139{
2140    $sql = "SELECT
2141                    bcm.banco_cuenta_mov_id,
2142                    bcm.banco_cuenta_id,
2143                    DATE(bcm.fecha) fecha,
2144                    bc.empresa_id
2145                FROM banco_cuenta_mov bcm
2146                JOIN banco_cuenta bc ON bc.banco_cuenta_id = bcm.banco_cuenta_id
2147                WHERE banco_cuenta_mov_id = '$bcm_id'";
2148    $bcm_current = ia_singleton($sql);
2149
2150    $date = $bcm_current['fecha'];
2151    $empresa_id = $bcm_current['empresa_id'];
2152
2153    $sqlSearchDuplicates = "SELECT
2154                                    bcm.banco_cuenta_mov_id,
2155                                    bcm.banco_cuenta_id,
2156                                    DATE(bcm.fecha) fecha,
2157                                    bc.empresa_id
2158                                FROM banco_cuenta_mov bcm
2159                                JOIN banco_cuenta bc ON bc.banco_cuenta_id = bcm.banco_cuenta_id
2160                                WHERE bcm.banco_cuenta_mov_id <> '$bcm_id'
2161                                  AND bcm.remarks LIKE '%TRIBUTARIA%'
2162                                  AND es = 'Retiro'
2163                                  AND MONTH(DATE(bcm.fecha)) = MONTH('$date')
2164                                  AND YEAR(DATE(bcm.fecha)) = YEAR('$date')
2165                                  AND bc.empresa_id = $empresa_id";
2166
2167    $duplicates = ia_sqlArray($sqlSearchDuplicates, 'banco_cuenta_mov_id');
2168    if (count($duplicates) > 0) {
2169        $mov_repetido_id = "$bcm_id," . implode(",", array_keys($duplicates));
2170        foreach ($duplicates as $key => $duplicate) {
2171            $remarks['sql'][] = "UPDATE banco_cuenta_mov SET repetido = 'Si', mov_repetido_id = '$mov_repetido_id' WHERE banco_cuenta_mov_id = '$key'";
2172        }
2173        $remarks['sql'][] = "UPDATE banco_cuenta_mov SET repetido = 'Si', mov_repetido_id = '$mov_repetido_id', remarks = ". strit(ltrim(trim($remarks['benefic']))) ." WHERE banco_cuenta_mov_id = '$bcm_id'";
2174    }
2175}
2176
2177/** Determina si el BCM es de tipo SAT
2178 * @param string $ori_benefic el String donde buscar conincidencia
2179 * @return bool is SAT
2180 */
2181function isSAT($ori_benefic)
2182{
2183    $re = '/^\s*(SERVICIO DE ADMINISTRACIÓN TRIBUTARIA|SERVICIO DE ADMINISTRACIÓN).*?\s(.*?(\s))/';
2184
2185    preg_match_all($re, $ori_benefic, $matches, PREG_SET_ORDER, 0);
2186
2187    if (count($matches) == 0) return false;
2188
2189    return true;
2190}