inventarios_balances::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
eloc 4
c 1
b 1
f 0
nc 1
nop 1
dl 0
loc 6
rs 10
1
<?php
2
/*
3
 * This file is part of facturacion_base
4
 * Copyright (C) 2013-2017  Carlos Garcia Gomez  [email protected]
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as
8
 * published by the Free Software Foundation, either version 3 of the
9
 * License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU Lesser General Public License for more details.
15
 * 
16
 * You should have received a copy of the GNU Lesser General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
require_once 'plugins/republica_dominicana/extras/fpdf181/fs_pdf.php';
21
22
class inventarios_balances
23
{
24
25
    private $balance;
26
    private $balance_cuenta_a;
27
    private $db;
28
    private $empresa;
29
30
    public function __construct(&$db)
31
    {
32
        $this->balance = new balance();
0 ignored issues
show
Bug introduced by
The type balance was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
33
        $this->balance_cuenta_a = new balance_cuenta_a();
0 ignored issues
show
Bug introduced by
The type balance_cuenta_a was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
34
        $this->db = $db;
35
        $this->empresa = new empresa();
0 ignored issues
show
Bug introduced by
The type empresa was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
36
    }
37
38
    /**
39
     * Función para ejecutar en el cron.php
40
     */
41
    public function cron_job()
42
    {
43
        /**
44
         * Como es un proceso que tarda mucho, solamente comprobamos los dos primeros
45
         * ejercicios de la lista (los más nuevos), más uno aleatorio.
46
         */
47
        $ejercicio = new ejercicio();
0 ignored issues
show
Bug introduced by
The type ejercicio was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
48
        $ejercicios = $ejercicio->all();
49
        $random = mt_rand(0, count($ejercicios) - 1);
50
        foreach ($ejercicios as $num => $eje) {
51
            if ($num < 2 || $num == $random) {
52
                $this->generar_libro($eje);
53
            }
54
        }
55
    }
56
57
    /**
58
     * Genera el libro de inventarios y balances de un ejercicio.
59
     * @param ejercicio $eje
60
     */
61
    private function generar_libro(&$eje)
62
    {
63
        if ($eje) {
0 ignored issues
show
introduced by
$eje is of type ejercicio, thus it always evaluated to true.
Loading history...
64
            if (!file_exists('tmp/' . FS_TMP_NAME . 'inventarios_balances')) {
0 ignored issues
show
Bug introduced by
The constant FS_TMP_NAME was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
65
                mkdir('tmp/' . FS_TMP_NAME . 'inventarios_balances');
66
            }
67
68
            if (!file_exists('tmp/' . FS_TMP_NAME . 'inventarios_balances/' . $eje->codejercicio . '.pdf')) {
69
                echo '.' . $eje->codejercicio . '.';
70
71
                $pdf_doc = new fs_pdf();
72
                $pdf_doc->pdf->addInfo('Title', 'Libro de inventarios y balances de ' . fs_fix_html($this->empresa->nombre));
73
                $pdf_doc->pdf->addInfo('Subject', 'Libro de inventarios y balances de ' . fs_fix_html($this->empresa->nombre));
74
                $pdf_doc->pdf->addInfo('Author', fs_fix_html($this->empresa->nombre));
75
                $pdf_doc->pdf->ezStartPageNumbers(580, 10, 10, 'left', '{PAGENUM} de {TOTALPAGENUM}');
76
77
                $excluir = FALSE;
78
                if (isset($eje->idasientocierre) && isset($eje->idasientopyg)) {
79
                    $excluir = array($eje->idasientocierre, $eje->idasientopyg);
80
                }
81
82
                $this->sumas_y_saldos($pdf_doc, $eje, 'de apertura a cierre', $eje->fechainicio, $eje->fechafin, $excluir, FALSE);
83
                $this->sumas_y_saldos($pdf_doc, $eje, 'de apertura a apertura', $eje->fechainicio, $eje->fechainicio);
84
                $this->sumas_y_saldos($pdf_doc, $eje, 'del 1º trimestre', $eje->fechainicio, '31-3-' . $eje->year());
85
                $this->sumas_y_saldos($pdf_doc, $eje, 'del 2º trimestre', '1-4-' . $eje->year(), '30-6-' . $eje->year());
86
                $this->sumas_y_saldos($pdf_doc, $eje, 'del 3º trimestre', '1-7-' . $eje->year(), '30-9-' . $eje->year());
87
                $this->sumas_y_saldos($pdf_doc, $eje, 'del 4º trimestre', '1-10-' . $eje->year(), $eje->fechafin);
88
                $this->perdidas_y_ganancias($pdf_doc, $eje);
89
                $this->situacion($pdf_doc, $eje);
90
91
                $pdf_doc->save('tmp/' . FS_TMP_NAME . 'inventarios_balances/' . $eje->codejercicio . '.pdf');
92
            }
93
        }
94
    }
95
96
    /**
97
     * Genera el balance de pérdidas y ganancias de un ejercicio.
98
     * @param string $codeje
99
     */
100
    public function generar_pyg($codeje)
101
    {
102
        $ejercicio = new ejercicio();
103
104
        $eje0 = $ejercicio->get($codeje);
105
        if ($eje0) {
106
            $pdf_doc = new fs_pdf();
107
            $pdf_doc->pdf->addInfo('Title', 'Balance de pérdidas y ganancias de ' . fs_fix_html($this->empresa->nombre));
108
            $pdf_doc->pdf->addInfo('Subject', 'Balance de pérdidas y ganancias de ' . fs_fix_html($this->empresa->nombre));
109
            $pdf_doc->pdf->addInfo('Author', fs_fix_html($this->empresa->nombre));
110
            $pdf_doc->pdf->ezStartPageNumbers(580, 10, 10, 'left', '{PAGENUM} de {TOTALPAGENUM}');
111
112
            $this->perdidas_y_ganancias($pdf_doc, $eje0, FALSE);
113
114
            $pdf_doc->show();
115
        }
116
    }
117
118
    /**
119
     * Genera el balance de situación.
120
     * @param string $codeje
121
     */
122
    public function generar_sit($codeje)
123
    {
124
        $ejercicio = new ejercicio();
125
126
        $eje0 = $ejercicio->get($codeje);
127
        if ($eje0) {
128
            $pdf_doc = new fs_pdf();
129
            $pdf_doc->pdf->addInfo('Title', 'Balance de pérdidas y ganancias de ' . fs_fix_html($this->empresa->nombre));
130
            $pdf_doc->pdf->addInfo('Subject', 'Balance de pérdidas y ganancias de ' . fs_fix_html($this->empresa->nombre));
131
            $pdf_doc->pdf->addInfo('Author', fs_fix_html($this->empresa->nombre));
132
            $pdf_doc->pdf->ezStartPageNumbers(580, 10, 10, 'left', '{PAGENUM} de {TOTALPAGENUM}');
133
134
            $this->situacion($pdf_doc, $eje0, FALSE);
135
136
            $pdf_doc->show();
137
        }
138
    }
139
140
    /**
141
     * Función auxiliar para generar el balance de sumas y saldos de un ejercicio y unas fechas concretas.
142
     * Este informe muestra los saldos (distintos de cero) de cada cuenta y subcuenta
143
     * por periodos, pero siempre excluyendo los asientos de cierre y pérdidas y ganancias.
144
     * @param fs_pdf $pdf_doc
145
     * @param ejercicio $eje
146
     * @param string $titulo
147
     * @param string $fechaini
148
     * @param string $fechafin
149
     * @param array|boolean $excluir
150
     * @param boolean $np
151
     */
152
    public function sumas_y_saldos(&$pdf_doc, &$eje, $titulo, $fechaini, $fechafin, $excluir = FALSE, $np = TRUE)
153
    {
154
        $ge0 = new grupo_epigrafes();
0 ignored issues
show
Bug introduced by
The type grupo_epigrafes was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
155
        $epi0 = new epigrafe();
0 ignored issues
show
Bug introduced by
The type epigrafe was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
156
        $cuenta0 = new cuenta();
0 ignored issues
show
Bug introduced by
The type cuenta was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
157
        $subcuenta0 = new subcuenta();
0 ignored issues
show
Bug introduced by
The type subcuenta was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
158
159
        $lineas = array();
160
161
        $sql = "SELECT p.codsubcuenta, SUM(p.debe) as debe, SUM(p.haber) as haber" .
162
            " FROM co_partidas p, co_asientos a WHERE p.idasiento = a.idasiento" .
163
            " AND a.codejercicio = " . $this->empresa->var2str($eje->codejercicio) .
164
            " AND a.fecha >= " . $this->empresa->var2str($fechaini) .
165
            " AND fecha <= " . $this->empresa->var2str($fechafin);
166
167
        if (is_array($excluir)) {
168
            foreach ($excluir as $exc) {
169
                $sql .= " AND p.idasiento != " . $this->empresa->var2str($exc);
170
            }
171
        }
172
173
        $sql .= " GROUP BY p.codsubcuenta ORDER BY codsubcuenta ASC;";
174
175
        $data = $this->db->select($sql);
176
        if ($data) {
177
            $grupos = $ge0->all_from_ejercicio($eje->codejercicio);
178
            $epigrafes = $epi0->all_from_ejercicio($eje->codejercicio);
179
180
            for ($i = 1; $i < 10; $i++) {
181
                $debe = 0;
182
                $haber = 0;
183
                foreach ($data as $d) {
184
                    if (substr($d['codsubcuenta'], 0, 1) == (string) $i) {
185
                        $debe += floatval($d['debe']);
186
                        $haber += floatval($d['haber']);
187
                    }
188
                }
189
190
                /// añadimos el grupo
191
                foreach ($grupos as $ge) {
192
                    if ($ge->codgrupo == $i) {
193
                        $lineas[] = array(
194
                            'cuenta' => $i,
195
                            'descripcion' => $ge->descripcion,
196
                            'debe' => $debe,
197
                            'haber' => $haber
198
                        );
199
                        break;
200
                    }
201
                }
202
203
                for ($j = 0; $j < 10; $j++) {
204
                    $debe = 0;
205
                    $haber = 0;
206
                    foreach ($data as $d) {
207
                        if (substr($d['codsubcuenta'], 0, 2) == (string) $i . $j) {
208
                            $debe += floatval($d['debe']);
209
                            $haber += floatval($d['haber']);
210
                        }
211
                    }
212
213
                    /// añadimos el epígrafe
214
                    foreach ($epigrafes as $ep) {
215
                        if ($ep->codepigrafe == (string) $i . $j) {
216
                            $lineas[] = array(
217
                                'cuenta' => $i . $j,
218
                                'descripcion' => $ep->descripcion,
219
                                'debe' => $debe,
220
                                'haber' => $haber
221
                            );
222
                            break;
223
                        }
224
                    }
225
226
                    for ($k = 0; $k < 10; $k++) {
227
                        $debe = 0;
228
                        $haber = 0;
229
                        foreach ($data as $d) {
230
                            if (substr($d['codsubcuenta'], 0, 3) == (string) $i . $j . $k) {
231
                                $debe += floatval($d['debe']);
232
                                $haber += floatval($d['haber']);
233
                            }
234
                        }
235
236
                        /// añadimos la cuenta
237
                        if ($debe != 0 || $haber != 0) {
238
                            $cuenta = $cuenta0->get_by_codigo($i . $j . $k, $eje->codejercicio);
239
                            if ($cuenta) {
240
                                $lineas[] = array(
241
                                    'cuenta' => $i . $j . $k,
242
                                    'descripcion' => $cuenta->descripcion,
243
                                    'debe' => $debe,
244
                                    'haber' => $haber
245
                                );
246
                            } else {
247
                                $lineas[] = array(
248
                                    'cuenta' => $i . $j . $k,
249
                                    'descripcion' => '-',
250
                                    'debe' => $debe,
251
                                    'haber' => $haber
252
                                );
253
                            }
254
                        }
255
256
                        /// añadimos las subcuentas
257
                        foreach ($data as $d) {
258
                            if (substr($d['codsubcuenta'], 0, 3) == (string) $i . $j . $k) {
259
                                $desc = '';
260
                                $subc = $subcuenta0->get_by_codigo($d['codsubcuenta'], $eje->codejercicio);
261
                                if ($subc) {
262
                                    $desc = $subc->descripcion;
263
                                }
264
265
                                $lineas[] = array(
266
                                    'cuenta' => $d['codsubcuenta'],
267
                                    'descripcion' => $desc,
268
                                    'debe' => floatval($d['debe']),
269
                                    'haber' => floatval($d['haber'])
270
                                );
271
                            }
272
                        }
273
                    }
274
                }
275
            }
276
        }
277
278
        /// a partir de la lista generamos el documento
279
        $linea = 0;
280
        $tdebe = 0;
281
        $thaber = 0;
282
        while ($linea < count($lineas)) {
283
            if ($linea > 0) {
284
                $pdf_doc->pdf->ezNewPage();
285
            }
286
287
            $pdf_doc->pdf->ezText(fs_fix_html($this->empresa->nombre) . " - Balance de sumas y saldos " . $eje->year() . ' ' . $titulo . ".\n\n", 12);
288
289
            /// Creamos la tabla con las lineas
290
            $pdf_doc->new_table();
291
            $pdf_doc->add_table_header(
292
                array(
293
                    'cuenta' => '<b>Cuenta</b>',
294
                    'descripcion' => '<b>Descripción</b>',
295
                    'debe' => '<b>Debe</b>',
296
                    'haber' => '<b>Haber</b>',
297
                    'saldo' => '<b>Saldo</b>'
298
                )
299
            );
300
301
            for ($i = $linea; $i < min(array($linea + 48, count($lineas))); $i++) {
302
                if (strlen($lineas[$i]['cuenta']) == 1) {
303
                    $a = '<b>';
304
                    $b = '</b>';
305
                    $tdebe += $lineas[$i]['debe'];
306
                    $thaber += $lineas[$i]['haber'];
307
                } else if (strlen($lineas[$i]['cuenta']) == 2) {
308
                    $a = $b = '';
309
                } else {
310
                    $a = '<i>';
311
                    $b = '</i>';
312
                }
313
314
                $pdf_doc->add_table_row(
315
                    array(
316
                        'cuenta' => $a . $lineas[$i]['cuenta'] . $b,
317
                        'descripcion' => $a . substr(fs_fix_html($lineas[$i]['descripcion']), 0, 50) . $b,
318
                        'debe' => $a . $this->show_numero($lineas[$i]['debe']) . $b,
319
                        'haber' => $a . $this->show_numero($lineas[$i]['haber']) . $b,
320
                        'saldo' => $a . $this->show_numero(floatval($lineas[$i]['debe']) - floatval($lineas[$i]['haber'])) . $b
321
                    )
322
                );
323
            }
324
            $linea += 48;
325
326
            /// añadimos las sumas de la línea actual
327
            $desc = 'Suma y sigue';
328
            if ($linea >= count($lineas)) {
329
                $desc = 'Totales';
330
            }
331
            $pdf_doc->add_table_row(
332
                array(
333
                    'cuenta' => '',
334
                    'descripcion' => '<b>' . fs_fix_html($desc) . '</b>',
335
                    'debe' => '<b>' . $this->show_numero($tdebe) . '</b>',
336
                    'haber' => '<b>' . $this->show_numero($thaber) . '</b>',
337
                    'saldo' => '<b>' . $this->show_numero($tdebe - $thaber) . '</b>'
338
                )
339
            );
340
            $pdf_doc->save_table(
341
                array(
342
                    'fontSize' => 9,
343
                    'cols' => array(
344
                        'debe' => array('justification' => 'right'),
345
                        'haber' => array('justification' => 'right'),
346
                        'saldo' => array('justification' => 'right')
347
                    ),
348
                    'width' => 540,
349
                    'shaded' => 0
350
                )
351
            );
352
        }
353
    }
354
355
    /**
356
     * Función auxiliar para generar el balance de pérdidas y ganancias.
357
     * Este informe se confecciona a partir de las cuentas que señalan los códigos
358
     * de balance que empiezan por PG.
359
     * @param fs_pdf $pdf_doc
360
     * @param ejercicio $eje
361
     * @param boolean $np
362
     */
363
    private function perdidas_y_ganancias(&$pdf_doc, &$eje, $np = TRUE)
364
    {
365
        if ($np) {
366
            $pdf_doc->pdf->ezNewPage();
367
        }
368
369
        $pdf_doc->pdf->ezText(fs_fix_html($this->empresa->nombre) . " - Cuenta de pérdidas y ganancias abreviada del ejercicio " . $eje->year() . ".\n\n", 13);
370
371
        /// necesitamos el ejercicio anterior
372
        $eje0 = $eje->get_by_fecha('1-1-' . (intval($eje->year()) - 1), FALSE, FALSE);
373
        if ($eje0) {
374
            /// creamos las cabeceras de la tabla
375
            $pdf_doc->new_table();
376
            $pdf_doc->add_table_header(
377
                array(
378
                    'descripcion' => '<b>Descripción</b>',
379
                    'actual' => '<b>' . $eje->year() . '</b>',
380
                    'anterior' => '<b>' . $eje0->year() . '</b>'
381
                )
382
            );
383
384
            $balances = $this->balance->all();
385
            $num = 1;
386
            $continuar = TRUE;
387
            $totales = array(
388
                $eje->year() => array('a' => 0, 'b' => 0, 'c' => 0, 'd' => 0),
389
                $eje0->year() => array('a' => 0, 'b' => 0, 'c' => 0, 'd' => 0)
390
            );
391
            while ($continuar) {
392
                if ($num == 12) {
393
                    $pdf_doc->add_table_row(
394
                        array(
395
                            'descripcion' => "\n<b>A) RESULTADOS DE EXPLOTACIÓN (1+2+3+4+5+6+7+8+9+10+11)</b>",
396
                            'actual' => "\n<b>" . $this->show_numero($totales[$eje->year()]['a']) . '</b>',
397
                            'anterior' => "\n<b>" . $this->show_numero($totales[$eje0->year()]['a']) . '</b>'
398
                        )
399
                    );
400
                } else if ($num == 17) {
401
                    $pdf_doc->add_table_row(
402
                        array(
403
                            'descripcion' => "\n<b>B) RESULTADO FINANCIERO (12+13+14+15+16)</b>",
404
                            'actual' => "\n<b>" . $this->show_numero($totales[$eje->year()]['b']) . '</b>',
405
                            'anterior' => "\n<b>" . $this->show_numero($totales[$eje0->year()]['b']) . '</b>'
406
                        )
407
                    );
408
                    $pdf_doc->add_table_row(
409
                        array(
410
                            'descripcion' => "<b>C) RESULTADO ANTES DE IMPUESTOS (A+B)</b>",
411
                            'actual' => '<b>' . $this->show_numero($totales[$eje->year()]['c']) . '</b>',
412
                            'anterior' => '<b>' . $this->show_numero($totales[$eje0->year()]['c']) . '</b>'
413
                        )
414
                    );
415
                }
416
417
                $encontrado = FALSE;
418
                foreach ($balances as $bal) {
419
                    if ($bal->naturaleza == 'PG' && strstr($bal->codbalance, 'PG')) {
420
                        $saldo1 = $this->get_saldo_balance('PG', $eje);
421
                        $saldo0 = $this->get_saldo_balance('PG', $eje0);
422
423
                        /// añadimos la fila
424
                        $pdf_doc->add_table_row(
425
                            array(
426
                                'descripcion' => $bal->descripcion2,
427
                                'actual' => $this->show_numero($saldo1),
428
                                'anterior' => $this->show_numero($saldo0)
429
                            )
430
                        );
431
432
                        /// sumamos donde corresponda
433
                        if ($num <= 11) {
434
                            $totales[$eje->year()]['a'] += $saldo1;
435
                            $totales[$eje0->year()]['a'] += $saldo0;
436
                        } else if ($num <= 16) {
437
                            $totales[$eje->year()]['b'] += $saldo1;
438
                            $totales[$eje0->year()]['b'] += $saldo0;
439
440
                            $totales[$eje->year()]['c'] = $totales[$eje->year()]['a'] + $totales[$eje->year()]['b'];
441
                            $totales[$eje0->year()]['c'] = $totales[$eje0->year()]['a'] + $totales[$eje0->year()]['b'];
442
                        } else if ($num == 17) {
443
                            $totales[$eje->year()]['d'] = $totales[$eje->year()]['c'] + $saldo1;
444
                            $totales[$eje0->year()]['d'] = $totales[$eje0->year()]['c'] + $saldo0;
445
                        }
446
447
                        $encontrado = TRUE;
448
                        $num++;
449
                        break;
450
                    }
451
                }
452
453
                $continuar = $encontrado;
454
            }
455
456
            $pdf_doc->add_table_row(
457
                array(
458
                    'descripcion' => "\n<b>D) RESULTADO DEL EJERCICIO (C+17)</b>",
459
                    'actual' => "\n<b>" . $this->show_numero($totales[$eje->year()]['d']) . '</b>',
460
                    'anterior' => "\n<b>" . $this->show_numero($totales[$eje0->year()]['d']) . '</b>'
461
                )
462
            );
463
464
            $pdf_doc->save_table(
465
                array(
466
                    'fontSize' => 12,
467
                    'cols' => array(
468
                        'actual' => array('justification' => 'right'),
469
                        'anterior' => array('justification' => 'right')
470
                    ),
471
                    'width' => 540,
472
                    'shaded' => 0
473
                )
474
            );
475
        } else {
476
            /// creamos las cabeceras de la tabla
477
            $pdf_doc->new_table();
478
            $pdf_doc->add_table_header(
479
                array(
480
                    'descripcion' => '<b>Descripción</b>',
481
                    'actual' => '<b>' . $eje->year() . '</b>'
482
                )
483
            );
484
485
            $balances = $this->balance->all();
486
            $num = 1;
487
            $continuar = TRUE;
488
            $totales = array($eje->year() => array('a' => 0, 'b' => 0, 'c' => 0, 'd' => 0));
489
            while ($continuar) {
490
                if ($num == 12) {
491
                    $pdf_doc->add_table_row(
492
                        array(
493
                            'descripcion' => "\n<b>A) RESULTADOS DE EXPLOTACIÓN (1+2+3+4+5+6+7+8)</b>",
494
                            'actual' => "\n<b>" . $this->show_numero($totales[$eje->year()]['a']) . '</b>'
495
                        )
496
                    );
497
                } else if ($num == 17) {
498
                    $pdf_doc->add_table_row(
499
                        array(
500
                            'descripcion' => "\n<b>B) RESULTADO FINANCIERO (P1+P2+P3)</b>",
501
                            'actual' => "\n<b>" . $this->show_numero($totales[$eje->year()]['b']) . '</b>'
502
                        )
503
                    );
504
                    $pdf_doc->add_table_row(
505
                        array(
506
                            'descripcion' => "<b>C) RESULTADO ANTES DE IMPUESTOS (A+B)</b>",
507
                            'actual' => '<b>' . $this->show_numero($totales[$eje->year()]['c']) . '</b>'
508
                        )
509
                    );
510
                }
511
512
                $encontrado = FALSE;
513
                foreach ($balances as $bal) {
514
                    if ($bal->naturaleza == 'PG' && strstr($bal->codbalance, 'PG-A-' . $num . '-')) {
515
                        $saldo1 = $this->get_saldo_balance('PG-A-' . $num . '-', $eje);
516
517
                        /// añadimos la fila
518
                        $pdf_doc->add_table_row(
519
                            array(
520
                                'descripcion' => $bal->descripcion2,
521
                                'actual' => $this->show_numero($saldo1)
522
                            )
523
                        );
524
525
                        /// sumamos donde corresponda
526
                        if ($num <= 11) {
527
                            $totales[$eje->year()]['a'] += $saldo1;
528
                        } else if ($num <= 16) {
529
                            $totales[$eje->year()]['b'] += $saldo1;
530
                            $totales[$eje->year()]['c'] = $totales[$eje->year()]['a'] + $totales[$eje->year()]['b'];
531
                        } else if ($num == 17) {
532
                            $totales[$eje->year()]['d'] = $totales[$eje->year()]['c'] + $saldo1;
533
                        }
534
535
                        $encontrado = TRUE;
536
                        $num++;
537
                        break;
538
                    }
539
                }
540
541
                $continuar = $encontrado;
542
            }
543
544
            $pdf_doc->add_table_row(
545
                array(
546
                    'descripcion' => "\n<b>D) RESULTADO DEL EJERCICIO (C+17)</b>",
547
                    'actual' => "\n<b>" . $this->show_numero($totales[$eje->year()]['d']) . '</b>'
548
                )
549
            );
550
551
            $pdf_doc->save_table(
552
                array(
553
                    'fontSize' => 12,
554
                    'cols' => array(
555
                        'actual' => array('justification' => 'right')
556
                    ),
557
                    'width' => 540,
558
                    'shaded' => 0
559
                )
560
            );
561
        }
562
    }
563
564
    private function get_saldo_balance($codbalance, &$ejercicio)
565
    {
566
        $total = 0;
567
568
        foreach ($this->balance_cuenta_a->search_by_codbalance($codbalance) as $bca) {
569
            $total += $bca->saldo($ejercicio);
570
        }
571
572
        return $total;
573
    }
574
575
    /**
576
     * Función auxiliar para generar el informe de situación.
577
     * Para generar este informe hay que leer los códigos de balance con naturaleza A o P
578
     * en orden. Pero como era demasiado sencillo, los hijos de puta de facturalux decidieron
579
     * añadir números romanos, para que no puedas ordenarlos fácilemnte.
580
     * @param fs_pdf $pdf_doc
581
     * @param ejercicio $eje
582
     * @param boolean $np
583
     */
584
    private function situacion(&$pdf_doc, &$eje, $np = TRUE)
585
    {
586
        /// necesitamos el ejercicio anterior
587
        $eje0 = $eje->get_by_fecha('1-1-' . (intval($eje->year()) - 1), FALSE, FALSE);
588
        if ($eje0) {
589
            $nivel0 = array('A', 'P');
590
            //$nivel1 = array('A', 'B', 'C');
591
            $nivel1 = array('', '1', '2', '3', '4', '5', '6', '7', '8', '9');
592
            $nivel2 = array('', '1', '2', '3', '4', '5', '6', '7', '8', '9');
0 ignored issues
show
Unused Code introduced by
The assignment to $nivel2 is dead and can be removed.
Loading history...
593
            $nivel3 = array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X');
0 ignored issues
show
Unused Code introduced by
The assignment to $nivel3 is dead and can be removed.
Loading history...
594
            $nivel4 = array('', '1', '2', '3', '4', '5', '6', '7', '8', '9');
0 ignored issues
show
Unused Code introduced by
The assignment to $nivel4 is dead and can be removed.
Loading history...
595
            $balances = $this->balance->all();
596
597
            foreach ($nivel0 as $nv0) {
598
                if ($np) {
599
                    $pdf_doc->pdf->ezNewPage();
600
                } else {
601
                    $np = TRUE;
602
                }
603
604
                $pdf_doc->pdf->ezText(fs_fix_html($this->empresa->nombre) . " - Balance de situación del ejercicio " . $eje->year() . ".\n\n", 13);
605
606
                /// creamos las cabeceras de la tabla
607
                $pdf_doc->new_table();
608
                $pdf_doc->add_table_header(
609
                    array(
610
                        'descripcion' => '<b>Descripción</b>',
611
                        'actual' => '<b>' . $eje->year() . '</b>',
612
                        'anterior' => '<b>' . $eje0->year() . '</b>'
613
                    )
614
                );
615
616
                $desc1 = '';
617
                $desc2 = '';
618
                $desc3 = '';
619
                foreach ($nivel1 as $nv1) {
620
                    //foreach ($nivel2 as $nv2) {
621
                        //foreach ($nivel3 as $nv3) {
622
                            //foreach ($nivel4 as $nv4) {
623
                                foreach ($balances as $bal) {
624
                                    if ($bal->naturaleza == $nv0 && $bal->nivel1 == $nv1) {
625
                                        if ($bal->descripcion1 != $desc1 && $bal->descripcion1 != '') {
626
                                            $pdf_doc->add_table_row(
627
                                                array(
628
                                                    'descripcion' => "\n<b>" . fs_fix_html($bal->descripcion1) . '</b>',
629
                                                    'actual' => "\n<b>" . $this->get_saldo_balance2($nv0 . '-' . $nv1, $eje, $nv0) . '</b>',
630
                                                    'anterior' => "\n<b>" . $this->get_saldo_balance2($nv0 . '-' . $nv1, $eje0, $nv0) . '</b>'
631
                                                )
632
                                            );
633
634
                                            $desc1 = $bal->descripcion1;
635
                                        }
636
637
                                        if ($bal->descripcion2 != $desc2 && $bal->descripcion2 != '') {
638
                                            $pdf_doc->add_table_row(
639
                                                array(
640
                                                    'descripcion' => ' <b>' . fs_fix_html($bal->descripcion2) . '</b>',
641
                                                    'actual' => $this->get_saldo_balance2($nv0 . '-' . $nv1, $eje, $nv0),
642
                                                    'anterior' => $this->get_saldo_balance2($nv0 . '-' . $nv1, $eje0, $nv0)
643
                                                )
644
                                            );
645
646
                                            $desc2 = $bal->descripcion2;
647
                                        }
648
649
                                        if ($bal->descripcion3 != $desc3 && $bal->descripcion3 != '') {
650
                                            $pdf_doc->add_table_row(
651
                                                array(
652
                                                    'descripcion' => '  ' . fs_fix_html($bal->descripcion3),
653
                                                    'actual' => $this->get_saldo_balance2($nv0 . '-' . $nv1, $eje, $nv0),
654
                                                    'anterior' => $this->get_saldo_balance2($nv0 . '-' . $nv1, $eje0, $nv0)
655
                                                )
656
                                            );
657
658
                                            $desc3 = $bal->descripcion3;
659
                                        }
660
                                    }
661
                                }
662
                            //}
663
                        //}
664
                    //}
665
                }
666
667
                if ($nv0 == 'A') {
668
                    $pdf_doc->add_table_row(
669
                        array(
670
                            'descripcion' => "\n<b>TOTAL ACTIVO (A+B)</b>",
671
                            'actual' => "\n<b>" . $this->get_saldo_balance2($nv0 . '-', $eje, $nv0) . '</b>',
672
                            'anterior' => "\n<b>" . $this->get_saldo_balance2($nv0 . '-', $eje0, $nv0) . '</b>'
673
                        )
674
                    );
675
                } else if ($nv0 == 'P') {
676
                    $pdf_doc->add_table_row(
677
                        array(
678
                            'descripcion' => "\n<b>TOTAL PATRIMONIO NETO Y PASIVO (A+B+C)</b>",
679
                            'actual' => "\n<b>" . $this->get_saldo_balance2($nv0 . '-', $eje, $nv0) . '</b>',
680
                            'anterior' => "\n<b>" . $this->get_saldo_balance2($nv0 . '-', $eje0, $nv0) . '</b>'
681
                        )
682
                    );
683
                }
684
685
                $pdf_doc->save_table(
686
                    array(
687
                        'fontSize' => 12,
688
                        'cols' => array(
689
                            'actual' => array('justification' => 'right'),
690
                            'anterior' => array('justification' => 'right')
691
                        ),
692
                        'width' => 540,
693
                        'shaded' => 0
694
                    )
695
                );
696
            }
697
        } else {
698
            $nivel0 = array('A', 'P');
699
            //$nivel1 = array('A', 'B', 'C');
700
            $nivel1 = array('', '1', '2', '3', '4', '5', '6', '7', '8', '9');
701
            $nivel2 = array('', '1', '2', '3', '4', '5', '6', '7', '8', '9');
702
            $nivel3 = array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X');
703
            $nivel4 = array('', '1', '2', '3', '4', '5', '6', '7', '8', '9');
704
            $balances = $this->balance->all();
705
706
            foreach ($nivel0 as $nv0) {
707
                if ($np) {
708
                    $pdf_doc->pdf->ezNewPage();
709
                } else {
710
                    $np = TRUE;
711
                }
712
713
                $pdf_doc->pdf->ezText(fs_fix_html($this->empresa->nombre) . " - Balance de situación del ejercicio " . $eje->year() . ".\n\n", 13);
714
715
                /// creamos las cabeceras de la tabla
716
                $pdf_doc->new_table();
717
                $pdf_doc->add_table_header(
718
                    array(
719
                        'descripcion' => '<b>Descripción</b>',
720
                        'actual' => '<b>' . $eje->year() . '</b>'
721
                    )
722
                );
723
724
                $desc1 = '';
725
                $desc2 = '';
726
                $desc3 = '';
727
                foreach ($nivel1 as $nv1) {
728
                    //foreach ($nivel2 as $nv2) {
729
                        //foreach ($nivel3 as $nv3) {
730
                            //foreach ($nivel4 as $nv4) {
731
                                foreach ($balances as $bal) {
732
                                    if ($bal->naturaleza == $nv0 && $bal->nivel1 == $nv1) {
733
                                        if ($bal->descripcion1 != $desc1 && $bal->descripcion1 != '') {
734
                                            $pdf_doc->add_table_row(
735
                                                array(
736
                                                    'descripcion' => "\n<b>" . fs_fix_html($bal->descripcion1) . '</b>',
737
                                                    'actual' => "\n<b>" . $this->get_saldo_balance2($nv0 . '-' . $nv1 . '-', $eje, $nv0) . '</b>'
738
                                                )
739
                                            );
740
741
                                            $desc1 = $bal->descripcion1;
742
                                        }
743
744
                                        if ($bal->descripcion2 != $desc2 && $bal->descripcion2 != '') {
745
                                            $pdf_doc->add_table_row(
746
                                                array(
747
                                                    'descripcion' => ' <b>' . fs_fix_html($bal->descripcion2) . '</b>',
748
                                                    'actual' => $this->get_saldo_balance2($nv0 . '-' . $nv1 . '-', $eje, $nv0)
749
                                                )
750
                                            );
751
752
                                            $desc2 = $bal->descripcion2;
753
                                        }
754
755
                                        if ($bal->descripcion3 != $desc3 && $bal->descripcion3 != '') {
756
                                            $pdf_doc->add_table_row(
757
                                                array(
758
                                                    'descripcion' => '  ' . fs_fix_html($bal->descripcion3),
759
                                                    'actual' => $this->get_saldo_balance2($nv0 . '-' . $nv1 . '-' , $eje, $nv0)
760
                                                )
761
                                            );
762
763
                                            $desc3 = $bal->descripcion3;
764
                                        }
765
                                    }
766
                                }
767
                            //}
768
                        //}
769
                    //}
770
                }
771
772
                if ($nv0 == 'A') {
773
                    $pdf_doc->add_table_row(
774
                        array(
775
                            'descripcion' => "\n<b>TOTAL ACTIVO (A+B)</b>",
776
                            'actual' => "\n<b>" . $this->get_saldo_balance2($nv0, $eje, $nv0) . '</b>'
777
                        )
778
                    );
779
                } else if ($nv0 == 'P') {
780
                    $pdf_doc->add_table_row(
781
                        array(
782
                            'descripcion' => "\n<b>TOTAL PATRIMONIO NETO Y PASIVO (A+B+C)</b>",
783
                            'actual' => "\n<b>" . $this->get_saldo_balance2($nv0, $eje, $nv0) . '</b>'
784
                        )
785
                    );
786
                }
787
788
                $pdf_doc->save_table(
789
                    array(
790
                        'fontSize' => 12,
791
                        'cols' => array(
792
                            'actual' => array('justification' => 'right')
793
                        ),
794
                        'width' => 540,
795
                        'shaded' => 0
796
                    )
797
                );
798
            }
799
        }
800
    }
801
802
    private function get_saldo_balance2($codbalance, $ejercicio, $naturaleza = 'A')
803
    {
804
        $total = 0;
805
        foreach ($this->balance_cuenta_a->search_by_codbalance($codbalance) as $bca) {
806
            $total += $bca->saldo($ejercicio);
807
            
808
            if($bca->codcuenta == '129') {
809
                $cuenta_model = new cuenta();
810
                $cuenta_129 = $cuenta_model->get_by_codigo('129', $ejercicio->codejercicio);
811
                if($cuenta_129) {
812
                    foreach($cuenta_129->get_subcuentas() as $subc) {
813
                        $total += $subc->saldo;
814
                    }
815
                }
816
            }
817
        }
818
819
        if ($naturaleza == 'A') {
820
            return $this->show_numero(0 - $total);
821
        }
822
823
        return $this->show_numero($total);
824
    }
825
826
    private function show_numero($num)
827
    {
828
        return number_format($num, FS_NF0, FS_NF1, FS_NF2);
829
    }
830
}
831