Completed
Push — master ( 37efbc...b75b92 )
by Esteban De La Fuente
01:39
created

Cesion::getCesionario()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/**
4
 * LibreDTE
5
 * Copyright (C) SASCO SpA (https://sasco.cl)
6
 *
7
 * Este programa es software libre: usted puede redistribuirlo y/o
8
 * modificarlo bajo los términos de la Licencia Pública General Affero de GNU
9
 * publicada por la Fundación para el Software Libre, ya sea la versión
10
 * 3 de la Licencia, o (a su elección) cualquier versión posterior de la
11
 * misma.
12
 *
13
 * Este programa se distribuye con la esperanza de que sea útil, pero
14
 * SIN GARANTÍA ALGUNA; ni siquiera la garantía implícita
15
 * MERCANTIL o de APTITUD PARA UN PROPÓSITO DETERMINADO.
16
 * Consulte los detalles de la Licencia Pública General Affero de GNU para
17
 * obtener una información más detallada.
18
 *
19
 * Debería haber recibido una copia de la Licencia Pública General Affero de GNU
20
 * junto a este programa.
21
 * En caso contrario, consulte <http://www.gnu.org/licenses/agpl.html>.
22
 */
23
24
namespace sasco\LibreDTE\Sii\Factoring;
25
26
/**
27
 * Clase que representa la cesion electrónica
28
 * @author Adonias Vasquez (adonias.vasquez[at]epys.cl)
29
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
30
 * @version 2016-12-30
31
 */
32
class Cesion
33
{
34
35
    private $Encabezado; ///< Encabezado del DTE que se está cediendo
36
    private $datos; ///< Datos del XML de cesión
37
    private $declaracion = 'Yo, {usuario_nombre}, RUN {usuario_run}, representando a {emisor_razon_social}, RUT {emisor_rut}, declaro que he puesto a disposición del cesionario {cesionario_razon_social}, RUT {cesionario_rut}, el documento donde constan los recibos de la recepción de mercaderías entregadas o servicios prestados, entregados por parte del deudor de la factura {receptor_razon_social}, RUT {receptor_rut}, de acuerdo a lo establecido en la Ley N° 19.983'; ///< Declaración estándar en caso que no sea indicada al momento de crear al cedente
38
    private $secuencia = 1;
39
40
    /**
41
     * Constructor de la clase Cesion
42
     * @param DTECedido Objeto DteCedido
43
     * @param Seq secuencia de la cesión
44
     * @author Adonias Vasquez (adonias.vasquez[at]epys.cl)
45
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
46
     * @version 2020-07-28
47
     */
48
    public function __construct(DteCedido $DTECedido = null, $Seq = 1)
49
    {
50
        if (!empty($DTECedido)) {
51
            $this->secuencia = $Seq;
52
            $this->Encabezado = $DTECedido->getDTE()->getDatos()['Encabezado'];
53
            $this->datos = [
54
                'Cesion' => [
55
                    '@attributes' => [
56
                        'xmlns' => 'http://www.sii.cl/SiiDte',
57
                        'version' => '1.0'
58
                    ],
59
                    'DocumentoCesion' => [
60
                        '@attributes' => [
61
                            'ID' => $this->getID(),
62
                        ],
63
                        'SeqCesion' => $Seq,
64
                        'IdDTE' => [
65
                            'TipoDTE' => $this->Encabezado['IdDoc']['TipoDTE'],
66
                            'RUTEmisor' => $this->Encabezado['Emisor']['RUTEmisor'],
67
                            'RUTReceptor' => $this->Encabezado['Receptor']['RUTRecep'],
68
                            'Folio' => $this->Encabezado['IdDoc']['Folio'],
69
                            'FchEmis' => $this->Encabezado['IdDoc']['FchEmis'],
70
                            'MntTotal' => $this->Encabezado['Totales']['MntTotal'],
71
                        ],
72
                        'Cedente' => false,
73
                        'Cesionario' => false,
74
                        'MontoCesion' => $this->Encabezado['Totales']['MntTotal'],
75
                        'UltimoVencimiento' =>
76
                            isset($this->Encabezado['IdDoc']['MntPagos']['FchPago'])
77
                            ? $this->Encabezado['IdDoc']['MntPagos']['FchPago']
78
                            : $this->Encabezado['IdDoc']['FchEmis'],
79
                        'OtrasCondiciones' => false,
80
                        'eMailDeudor' => false,
81
                        'TmstCesion' => date('Y-m-d\TH:i:s')
82
                    ]
83
                ]
84
            ];
85
        }
86
    }
87
88
    /**
89
     * Método entrega el ID de la cesión en base a la secuencia
90
     * @param declaracion String con la declaración y las variables para poder reemplazar los datos si es necesario
91
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
92
     * @version 2020-07-28
93
     */
94
    protected function getID()
95
    {
96
        return 'LibreDTE_Cesion_'.$this->secuencia;
97
    }
98
99
    /**
100
     * Método que permite cambiar la declaración por defecto
101
     * Están disponibles las siguientes variables dentro del string de la declaración:
102
     *   - {usuario_nombre}
103
     *   - {usuario_run}
104
     *   - {emisor_razon_social}
105
     *   - {emisor_rut}
106
     *   - {cesionario_razon_social}
107
     *   - {cesionario_rut}
108
     *   - {receptor_razon_social}
109
     *   - {receptor_rut}
110
     * @param declaracion String con la declaración y las variables para poder reemplazar los datos si es necesario
111
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
112
     * @version 2016-12-10
113
     */
114
    public function setDeclaracion($declaracion)
115
    {
116
        $this->declaracion = $declaracion;
117
    }
118
119
    /**
120
     * Método que agrega los datos del cedente
121
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
122
     * @version 2017-07-24
123
     */
124
    public function setCedente(array $cedente = [])
125
    {
126
        $this->datos['Cesion']['DocumentoCesion']['Cedente'] = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
127
            'RUT' => $this->Encabezado['Emisor']['RUTEmisor'],
128
            'RazonSocial' => $this->Encabezado['Emisor']['RznSoc'],
129
            'Direccion' => $this->Encabezado['Emisor']['DirOrigen'].', '.$this->Encabezado['Emisor']['CmnaOrigen'],
130
            'eMail' => !empty($this->Encabezado['Emisor']['CorreoEmisor']) ? $this->Encabezado['Emisor']['CorreoEmisor'] : false,
131
            'RUTAutorizado' => [
132
                'RUT' => false,
133
                'Nombre' => false,
134
            ],
135
            'DeclaracionJurada' => false,
136
        ], $cedente);
137
        if (!$this->datos['Cesion']['DocumentoCesion']['Cedente']['DeclaracionJurada']) {
138
            $this->datos['Cesion']['DocumentoCesion']['Cedente']['DeclaracionJurada'] = mb_substr(str_replace(
139
                [
140
                    '{usuario_nombre}',
141
                    '{usuario_run}',
142
                    '{emisor_razon_social}',
143
                    '{emisor_rut}',
144
                    '{cesionario_razon_social}',
145
                    '{cesionario_rut}',
146
                    '{receptor_razon_social}',
147
                    '{receptor_rut}',
148
                ],
149
                [
150
                    $this->datos['Cesion']['DocumentoCesion']['Cedente']['RUTAutorizado']['Nombre'],
151
                    $this->datos['Cesion']['DocumentoCesion']['Cedente']['RUTAutorizado']['RUT'],
152
                    $this->datos['Cesion']['DocumentoCesion']['Cedente']['RazonSocial'],
153
                    $this->datos['Cesion']['DocumentoCesion']['Cedente']['RUT'],
154
                    $this->datos['Cesion']['DocumentoCesion']['Cesionario']['RazonSocial'],
155
                    $this->datos['Cesion']['DocumentoCesion']['Cesionario']['RUT'],
156
                    $this->Encabezado['Receptor']['RznSocRecep'],
157
                    $this->Encabezado['Receptor']['RUTRecep'],
158
                ],
159
                $this->declaracion
160
            ), 0, 512);
161
        }
162
    }
163
164
    /**
165
     * Método que agrega los datos del cesionario
166
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
167
     * @version 2016-12-10
168
     */
169
    public function setCesionario(array $cesionario)
170
    {
171
        $this->datos['Cesion']['DocumentoCesion']['Cesionario'] = $cesionario;
172
    }
173
174
    /**
175
     * Método que asigna otros datos de la cesión. Su uso es opcional, ya que de no ser llamado
176
     * se usará el monto total del documento y su fecha de emisión o pago si existe
177
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
178
     * @version 2016-12-10
179
     */
180
    public function setDatos(array $datos)
181
    {
182 View Code Duplication
        if (!empty($datos['MontoCesion'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
183
            $this->datos['Cesion']['DocumentoCesion']['MontoCesion'] = $datos['MontoCesion'];
184
        }
185 View Code Duplication
        if (!empty($datos['UltimoVencimiento'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
186
            $this->datos['Cesion']['DocumentoCesion']['UltimoVencimiento'] = $datos['UltimoVencimiento'];
187
        }
188 View Code Duplication
        if (!empty($datos['OtrasCondiciones'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
189
            $this->datos['Cesion']['DocumentoCesion']['OtrasCondiciones'] = $datos['OtrasCondiciones'];
190
        }
191 View Code Duplication
        if (!empty($datos['eMailDeudor'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
192
            $this->datos['Cesion']['DocumentoCesion']['eMailDeudor'] = $datos['eMailDeudor'];
193
        }
194
    }
195
196
    /**
197
     * Método que realiza la firma de cesión
198
     * @param Firma objeto que representa la Firma Electrónca
199
     * @return =true si el DTE pudo ser fimado o =false si no se pudo firmar
0 ignored issues
show
Documentation introduced by
The doc-type =true could not be parsed: Unknown type name "=true" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
200
     * @author Adonias Vasquez (adonias.vasquez[at]epys.cl)
201
     * @version 2020-07-28
202
     */
203
    public function firmar(\sasco\LibreDTE\FirmaElectronica $Firma)
204
    {
205
        $xml_unsigned = (new \sasco\LibreDTE\XML())->generate($this->datos)->saveXML();
206
        $xml = $Firma->signXML($xml_unsigned, '#'.$this->getID(), 'DocumentoCesion');
0 ignored issues
show
Documentation introduced by
$xml_unsigned is of type string, but the function expects a object<sasco\LibreDTE\Datos>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
207 View Code Duplication
        if (!$xml) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
208
            \sasco\LibreDTE\Log::write(
209
                \sasco\LibreDTE\Estado::DTE_ERROR_FIRMA,
210
                \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA, '#'.$this->getID())
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::..., '#' . $this->getID()) is of type integer|string, but the function expects a object<sasco\LibreDTE\Mensaje>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
211
            );
212
            return false;
213
        }
214
        $this->xml = new \sasco\LibreDTE\XML();
0 ignored issues
show
Bug introduced by
The property xml does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
215
        if (!$this->xml->loadXML($xml) or !$this->schemaValidate())
0 ignored issues
show
Bug introduced by
It seems like $xml defined by $Firma->signXML($xml_uns...D(), 'DocumentoCesion') on line 206 can also be of type boolean; however, sasco\LibreDTE\XML::loadXML() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
216
            return false;
217
        return true;
218
    }
219
220
    /**
221
     * Método que entrega el string con el XML de la cesion
222
     * @author Adonias Vasquez (adonias.vasquez[at]epys.cl)
223
     * @version 2016-08-10
224
     */
225
    public function saveXML()
226
    {
227
        return $this->xml->saveXML();
228
    }
229
230
    /**
231
     * Método que valida el schema de la Cesion
232
     * @return =true si el schema del documento del DTE es válido, =null si no se pudo determinar
0 ignored issues
show
Documentation introduced by
The doc-type =true could not be parsed: Unknown type name "=true" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
233
     * @author Adonias Vasquez (adonias.vasquez[at]epys.cl)
234
     * @version 2016-08-10
235
     */
236
    public function schemaValidate()
237
    {
238
        return true;
239
    }
240
241
    /**
242
     * Método que entrega los datos del cedente
243
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
244
     * @version 2016-12-10
245
     */
246
    public function getCedente()
247
    {
248
        return $this->datos['Cesion']['DocumentoCesion']['Cedente'];
249
    }
250
251
    /**
252
     * Método que entrega los datos del cesionario
253
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
254
     * @version 2016-12-10
255
     */
256
    public function getCesionario()
257
    {
258
        return $this->datos['Cesion']['DocumentoCesion']['Cesionario'];
259
    }
260
261
    /**
262
     * Método que carga un XML y asigna el objeto XML correspondiente
263
     * @return Objeto XML
264
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
265
     * @version 2020-07-27
266
     */
267
    public function loadXML($xml_data)
268
    {
269
        $this->xml = new \sasco\LibreDTE\XML();
270
        if (!$this->xml->loadXML($xml_data)) {
271
            return false;
272
        }
273
        return $this->xml;
274
    }
275
276
}
277