Passed
Push — master ( d22648...9d79d3 )
by
unknown
09:19
created

TemplateDataHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 121
Duplicated Lines 0 %

Test Coverage

Coverage 72.21%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 5
eloc 75
c 5
b 0
f 0
dl 0
loc 121
ccs 65
cts 90
cp 0.7221
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B createHandlers() 0 104 4
A __construct() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * LibreDTE: Biblioteca PHP (Núcleo).
7
 * Copyright (C) LibreDTE <https://www.libredte.cl>
8
 *
9
 * Este programa es software libre: usted puede redistribuirlo y/o modificarlo
10
 * bajo los términos de la Licencia Pública General Affero de GNU publicada por
11
 * la Fundación para el Software Libre, ya sea la versión 3 de la Licencia, o
12
 * (a su elección) cualquier versión posterior de la misma.
13
 *
14
 * Este programa se distribuye con la esperanza de que sea útil, pero SIN
15
 * GARANTÍA ALGUNA; ni siquiera la garantía implícita MERCANTIL o de APTITUD
16
 * PARA UN PROPÓSITO DETERMINADO. Consulte los detalles de la Licencia Pública
17
 * General Affero de GNU para obtener una información más detallada.
18
 *
19
 * Debería haber recibido una copia de la Licencia Pública General Affero de
20
 * GNU junto a este programa.
21
 *
22
 * En caso contrario, consulte <http://www.gnu.org/licenses/agpl.html>.
23
 */
24
25
namespace libredte\lib\Core\Package\Billing\Component\Document\Service;
26
27
use Derafu\Lib\Core\Enum\Currency;
28
use Derafu\Lib\Core\Helper\Date;
29
use Derafu\Lib\Core\Helper\Rut;
30
use Derafu\Lib\Core\Package\Prime\Component\Entity\Contract\EntityComponentInterface;
31
use Derafu\Lib\Core\Package\Prime\Component\Template\Abstract\AbstractTemplateDataHandler;
32
use Derafu\Lib\Core\Package\Prime\Component\Template\Contract\DataHandlerInterface;
33
use libredte\lib\Core\Package\Billing\Component\Document\Contract\TipoDocumentoInterface;
34
use libredte\lib\Core\Package\Billing\Component\Document\Entity\AduanaMoneda;
35
use libredte\lib\Core\Package\Billing\Component\Document\Entity\AduanaPais;
36
use libredte\lib\Core\Package\Billing\Component\Document\Entity\AduanaTransporte;
37
use libredte\lib\Core\Package\Billing\Component\Document\Entity\Comuna;
38
use libredte\lib\Core\Package\Billing\Component\Document\Entity\FormaPago;
39
use libredte\lib\Core\Package\Billing\Component\Document\Entity\ImpuestoAdicionalRetencion;
40
use libredte\lib\Core\Package\Billing\Component\Document\Entity\MedioPago;
41
use libredte\lib\Core\Package\Billing\Component\Document\Entity\FormaPagoExportacion;
42
use libredte\lib\Core\Package\Billing\Component\Document\Entity\TagXml;
43
use libredte\lib\Core\Package\Billing\Component\Document\Entity\Traslado;
44
use TCPDF2DBarcode;
45
46
/**
47
 * Servicio para traducir los datos de los documentos a su representación para
48
 * ser utilizada en la renderización del documento.
49
 */
50
class TemplateDataHandler extends AbstractTemplateDataHandler implements DataHandlerInterface
51
{
52
    /**
53
     * Constructor del handler.
54
     *
55
     * @param EntityComponentInterface $entityComponent
56
     */
57 103
    public function __construct(
58
        private EntityComponentInterface $entityComponent
59
    ) {
60 103
    }
61
62
    /**
63
     * Mapa de campos a handlers para los documentos tributarios electrónicos.
64
     *
65
     * @return array
66
     */
67 103
    protected function createHandlers(): array
68
    {
69 103
        return [
70
            // Tipos de documento.
71 103
            'TipoDTE' => $this->entityComponent->getRepository(
72 103
                TipoDocumentoInterface::class
73 103
            ),
74 103
            'TpoDocRef' => 'alias:TipoDTE',
75
            // RUT.
76 103
            'RUTEmisor' => fn (string $rut) => Rut::formatFull($rut),
77 103
            'RUTRecep' => 'alias:RUTEmisor',
78 103
            'RUTSolicita' => 'alias:RUTEmisor',
79 103
            'RUTTrans' => 'alias:RUTEmisor',
80 103
            'RUTChofer' => 'alias:RUTEmisor',
81
            // Comuna.
82 103
            'CdgSIISucur' => fn (string $comuna) =>
83 103
                $this->entityComponent->getRepository(
84 103
                    Comuna::class
85 103
                )->find($comuna)->getDireccionRegional()
86 103
            ,
87 103
            'CiudadOrigen' => fn (string $comuna) =>
88
                $this->entityComponent->getRepository(
89
                    Comuna::class
90
                )->find($comuna)->getCiudad()
91 103
            ,
92 103
            'CiudadRecep' => 'alias:CiudadOrigen',
93
            // Fechas largas.
94 103
            'FchEmis' => fn (string $fecha) => Date::formatSpanish($fecha),
95 103
            'FchRef' => 'alias:FchEmis',
96 103
            'FchVenc' => 'alias:FchEmis',
97 103
            'FchCancel' => 'alias:FchEmis',
98
            // Fechas cortas.
99 103
            'PeriodoDesde' => function (string $fecha) {
100 2
                $timestamp = strtotime($fecha);
101 2
                return date('d/m/Y', $timestamp);
102 103
            },
103 103
            'PeriodoHasta' => 'alias:PeriodoDesde',
104 103
            'FchPago' => 'alias:PeriodoDesde',
105
            // Solo año de una fecha.
106 103
            'FchResol' => fn (string $fecha) => explode('-', $fecha, 2)[0],
107
            // Datos de Aduana.
108 103
            'Aduana' => function (string $tagXmlAndValue) {
109
                [$tagXml, $value] = explode(':', $tagXmlAndValue);
110
                $xmlTagEntity = $this->entityComponent->getRepository(
111
                    TagXml::class
112
                )->find($tagXml);
113
                $name = $xmlTagEntity->getGlosa();
114
                $entityClass = $xmlTagEntity->getEntity();
115
                if ($entityClass) {
116
                    $description = $this->entityComponent->getRepository(
117
                        $entityClass
118
                    )->find($value)->getGlosa();
119
                } else {
120
                    $description = $this->handle($tagXml, $value);
121
                }
122
                if ($name && !in_array($description, [false, null, ''], true)) {
123
                    return $name . ': ' . $description;
124
                }
125
                return '';
126 103
            },
127 103
            'TotItems' => 'alias:Number',
128
            // Otros datos que se mapean de un código a su glosa usando un
129
            // repositorio.
130 103
            'TipoImp' => $this->entityComponent->getRepository(
131 103
                ImpuestoAdicionalRetencion::class
132 103
            ),
133 103
            'MedioPago' => $this->entityComponent->getRepository(
134 103
                MedioPago::class
135 103
            ),
136 103
            'FmaPago' => $this->entityComponent->getRepository(
137 103
                FormaPago::class
138 103
            ),
139 103
            'FmaPagExp' => $this->entityComponent->getRepository(
140 103
                FormaPagoExportacion::class
141 103
            ),
142 103
            'Nacionalidad' => $this->entityComponent->getRepository(
143 103
                AduanaPais::class
144 103
            ),
145 103
            'CodPaisRecep' => 'alias:Nacionalidad',
146 103
            'IndTraslado' => $this->entityComponent->getRepository(
147 103
                Traslado::class
148 103
            ),
149 103
            'CodViaTransp' => $this->entityComponent->getRepository(
150 103
                AduanaTransporte::class
151 103
            ),
152
            //  Timbre Electrónico del Documento (TED).
153 103
            'TED' => function (string $timbre) {
154 103
                $pdf417 = new TCPDF2DBarcode($timbre, 'PDF417,,5');
155 103
                $png = $pdf417->getBarcodePngData(1, 1, [0,0,0]);
156 103
                return 'data:image/png;base64,' . base64_encode($png);
157 103
            },
158
            // Montos sin decimales y formato de Chile en separadores.
159 103
            'Number' => function (int|float|string $num) {
160
                $num = round((float) $num);
161
                return number_format($num, 0, ',', '.');
162 103
            },
163
            // Montos según moneda.
164 103
            'MontoMoneda' => function (string $value) {
165
                [$codigo, $num] = explode(':', $value);
166
                $result = $this->entityComponent->getRepository(
167
                    AduanaMoneda::class
168
                )->findBy(['glosa' => $codigo]);
169
                $currency = ($result[0] ?? null)?->getCurrency() ?? Currency::XXX;
170
                return $currency->format((float) $num);
171 103
            },
172 103
        ];
173
    }
174
}
175