Passed
Pull Request — master (#11)
by Carlos C
01:51
created

QuickFinkok::obtainCancelRequestReceipt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpCfdi\Finkok;
6
7
use DateTimeImmutable;
8
use PhpCfdi\Credentials\Credential;
9
use PhpCfdi\Finkok\Definitions\CancelAnswer;
10
use PhpCfdi\Finkok\Definitions\ReceiptType;
11
use PhpCfdi\Finkok\Definitions\RfcRole;
12
use PhpCfdi\Finkok\Services\Cancel;
13
use PhpCfdi\Finkok\Services\Manifest;
14
use PhpCfdi\Finkok\Services\Registration;
15
use PhpCfdi\Finkok\Services\Stamping;
16
use PhpCfdi\Finkok\Services\Utilities;
17
18
class QuickFinkok
19
{
20
    /** @var FinkokSettings */
21
    private $settings;
22
23 22
    public function __construct(FinkokSettings $factory)
24
    {
25 22
        $this->settings = $factory;
26 22
    }
27
28
    /**
29
     * Obtiene la configuración de conexión con la que será consumida la API de Finkok
30
     *
31
     * @return FinkokSettings
32
     */
33 22
    public function settings(): FinkokSettings
34
    {
35 22
        return $this->settings;
36
    }
37
38
    /**
39
     * Este método se encarga de realizar el timbrado de XML
40
     *
41
     * @param string $preCfdi
42
     * @return Stamping\StampingResult
43
     * @see https://wiki.finkok.com/doku.php?id=stamp
44
     */
45 1
    public function stamp(string $preCfdi): Stamping\StampingResult
46
    {
47 1
        $command = new Stamping\StampingCommand($preCfdi);
48 1
        $service = new Stamping\StampService($this->settings());
49 1
        return $service->stamp($command);
50
    }
51
52
    /**
53
     * Este método se encarga de realizar el timbrado de XML, una vez que se timbra el XML se guarda en una cola de
54
     * espera para ser enviado en el mejor momento a los servicios del SAT, por lo que el servicio de timbrado es
55
     * mucho mas rápido, y es de uso recomendado en timbrado de alto numero de timbres por segundo.
56
     *
57
     * Nota: El CFDI generado puede no estar disponible en los servidores del SAT hasta varios minutos después
58
     *
59
     * @param string $preCfdi
60
     * @return Stamping\StampingResult
61
     * @see https://wiki.finkok.com/doku.php?id=metodo_quick_stamp
62
     */
63 1
    public function quickStamp(string $preCfdi): Stamping\StampingResult
64
    {
65 1
        $command = new Stamping\StampingCommand($preCfdi);
66 1
        $service = new Stamping\QuickStampService($this->settings());
67 1
        return $service->quickstamp($command);
68
    }
69
70
    /**
71
     * Este método regresa la información de un XML ya timbrado previamente y que por algún motivo no se pudo recuperar
72
     * en la primera petición que se realizó, con este método se puede recuperar el UUID y el XML timbrado
73
     *
74
     * @param string $preCfdi
75
     * @return Stamping\StampingResult
76
     * @see https://wiki.finkok.com/doku.php?id=stamped
77
     */
78 1
    public function stamped(string $preCfdi): Stamping\StampingResult
79
    {
80 1
        $command = new Stamping\StampingCommand($preCfdi);
81 1
        $service = new Stamping\StampedService($this->settings());
82 1
        return $service->stamped($command);
83
    }
84
85
    /**
86
     * Obtiene el XML de un UUID timbrado en Finkok, solo es posible recuperar los timbrados en los últimos 3 meses
87
     *
88
     * @param string $uuid
89
     * @param string $rfc
90
     * @return Utilities\DownloadXmlResult
91
     * @see https://wiki.finkok.com/doku.php?id=get_xml
92
     */
93 1
    public function cfdiDownload(string $uuid, string $rfc): Utilities\DownloadXmlResult
94
    {
95 1
        $command = new Utilities\DownloadXmlCommand($uuid, $rfc, 'I');
96 1
        $service = new Utilities\DownloadXmlService($this->settings());
97 1
        return $service->downloadXml($command);
98
    }
99
100
    /**
101
     * Este método se usa para consultar el estatus de una factura que se quedo pendiente de enviar al SAT debido a una
102
     * falla en el sistema del SAT o bien que se envió a través del método Quick_Stamp
103
     *
104
     * @param string $uuid
105
     * @return Stamping\QueryPendingResult
106
     * @see https://wiki.finkok.com/doku.php?id=query_pending
107
     */
108 1
    public function stampQueryPending(string $uuid): Stamping\QueryPendingResult
109
    {
110 1
        $command = new Stamping\QueryPendingCommand($uuid);
111 1
        $service = new Stamping\QueryPendingService($this->settings());
112 1
        return $service->queryPending($command);
113
    }
114
115
    /**
116
     * Este método es el encargado de cancelar uno o varios CFDIs emitidos por medio de los web services de Finkok
117
     * Durante el proceso no se envía ningún CSD a Finkok y la solicitud firmada es creada usando los datos del CSD
118
     *
119
     * @param Credential $credential
120
     * @param string $uuid
121
     * @return Cancel\CancelSignatureResult
122
     * @see https://wiki.finkok.com/doku.php?id=cancelsigned_method
123
     * @see https://wiki.finkok.com/doku.php?id=cancel_method
124
     */
125 1
    public function cancel(Credential $credential, string $uuid): Cancel\CancelSignatureResult
126
    {
127 1
        $signer = new Helpers\CancelSigner([$uuid]);
128 1
        $signedRequest = $signer->sign($credential);
129 1
        $command = new Cancel\CancelSignatureCommand($signedRequest);
130 1
        $service = new Cancel\CancelSignatureService($this->settings());
131 1
        return $service->cancelSignature($command);
132
    }
133
134
    /**
135
     * Consulta el estatus del CFDI emitido con Finkok y la forma posible de cancelación a partir de todos sus datos.
136
     * También se puede consultar en modo producción utilizando la librería `phpcfdi/sat-estado-cfdi`
137
     *
138
     * @param string $rfcIssuer
139
     * @param string $rfcRecipient
140
     * @param string $uuid
141
     * @param string $total
142
     * @return Cancel\GetSatStatusResult
143
     * @see https://wiki.finkok.com/doku.php?id=get_sat_status
144
     * @see https://github.com/phpcfdi/sat-estado-cfdi
145
     */
146 1
    public function satStatus(
147
        string $rfcIssuer,
148
        string $rfcRecipient,
149
        string $uuid,
150
        string $total
151
    ): Cancel\GetSatStatusResult {
152 1
        $command = new Cancel\GetSatStatusCommand($rfcIssuer, $rfcRecipient, $uuid, $total);
153 1
        $service = new Cancel\GetSatStatusService($this->settings());
154 1
        return $service->query($command);
155
    }
156
157
    /**
158
     * Consulta el estatus del CFDI emitido por Finkok y la forma posible de cancelación a partir del XML de un CFDI
159
     *
160
     * @param string $xmlCfdi
161
     * @return Cancel\GetSatStatusResult
162
     * @see https://wiki.finkok.com/doku.php?id=get_sat_status
163
     */
164 1
    public function satStatusXml(string $xmlCfdi): Cancel\GetSatStatusResult
165
    {
166 1
        $extractor = Helpers\GetSatStatusExtractor::fromXmlString($xmlCfdi);
167 1
        $command = $extractor->buildCommand();
168 1
        $service = new Cancel\GetSatStatusService($this->settings());
169 1
        return $service->query($command);
170
    }
171
172
    /**
173
     * Obtiene una lista de los UUIDs relacionados de un UUID
174
     *
175
     * @param Credential $credential
176
     * @param string $uuid
177
     * @param RfcRole|null $role si es NULL entonces se usa el rol de emisor
178
     * @return Cancel\GetRelatedSignatureResult
179
     * @see https://wiki.finkok.com/doku.php?id=get_related_signature
180
     * @see https://wiki.finkok.com/doku.php?id=get_related
181
     */
182 1
    public function obtainRelated(
183
        Credential $credential,
184
        string $uuid,
185
        RfcRole $role = null
186
    ): Cancel\GetRelatedSignatureResult {
187 1
        $signer = new Helpers\GetRelatedSigner($uuid, $role);
188 1
        $signedRequest = $signer->sign($credential);
189 1
        $command = new Cancel\GetRelatedSignatureCommand($signedRequest);
190 1
        $service = new Cancel\GetRelatedSignatureService($this->settings());
191 1
        return $service->getRelatedSignature($command);
192
    }
193
194
    /**
195
     * Consulta las solicitudes de cancelación tiene pendientes un receptor
196
     * Durante el proceso no se envía ningún CSD a Finkok y la solicitud firmada es creada usando los datos del CSD
197
     *
198
     * @param string $rfc
199
     * @return Cancel\GetPendingResult
200
     * @see https://wiki.finkok.com/doku.php?id=get_pending
201
     */
202 1
    public function obtainPendingToCancel(string $rfc): Cancel\GetPendingResult
203
    {
204 1
        $command = new Cancel\GetPendingCommand($rfc);
205 1
        $service = new Cancel\GetPendingService($this->settings());
206 1
        return $service->obtainPending($command);
207
    }
208
209
    /**
210
     * Permite al receptor de una factura Aceptar o Rechazar una determinada cancelación que tenga pendiente
211
     * Durante el proceso no se envía ningún CSD a Finkok y la solicitud firmada es creada usando los datos del CSD
212
     *
213
     * @param Credential $credential
214
     * @param string $uuid
215
     * @param CancelAnswer $answer
216
     * @return Cancel\AcceptRejectSignatureResult
217
     * @see https://wiki.finkok.com/doku.php?id=accept_reject_signature
218
     * @see https://wiki.finkok.com/doku.php?id=accept_reject
219
     */
220 1
    public function answerAcceptRejectCancellation(
221
        Credential $credential,
222
        string $uuid,
223
        CancelAnswer $answer
224
    ): Cancel\AcceptRejectSignatureResult {
225 1
        $signer = new Helpers\AcceptRejectSigner($uuid, $answer);
226 1
        $signedRequest = $signer->sign($credential);
227 1
        $command = new Cancel\AcceptRejectSignatureCommand($signedRequest);
228 1
        $service = new Cancel\AcceptRejectSignatureService($this->settings());
229 1
        return $service->acceptRejectSignature($command);
230
    }
231
232
    /**
233
     * Obtiene el acuse de recepción de la solicitud de cancelación
234
     *
235
     * @param string $rfcIssuer
236
     * @param string $uuid
237
     * @return Cancel\GetReceiptResult
238
     * @see https://wiki.finkok.com/doku.php?id=get_receipt
239
     */
240 1
    public function obtainCancelRequestReceipt(string $rfcIssuer, string $uuid): Cancel\GetReceiptResult
241
    {
242 1
        $command = new Cancel\GetReceiptCommand($rfcIssuer, $uuid, ReceiptType::cancellation());
243 1
        $service = new Cancel\GetReceiptService($this->settings());
244 1
        return $service->download($command);
245
    }
246
247
    /**
248
     * Obtener la fecha exacta de los servidores de timbrado para realizar el XML del CFDI
249
     *
250
     * @param string $postalCode Si está vacío se utiliza el horario de America/Mexico_City
251
     * @return Utilities\DatetimeResult
252
     * @see https://wiki.finkok.com/doku.php?id=datetime
253
     */
254 1
    public function serversDateTime(string $postalCode = ''): Utilities\DatetimeResult
255
    {
256 1
        $command = new Utilities\DatetimeCommand($postalCode);
257 1
        $service = new Utilities\DatetimeService($this->settings());
258 1
        return $service->datetime($command);
259
    }
260
261
    /**
262
     * Reporte de los UUID timbrados con fecha, de un RFC entre un periodo de tiempo determinado
263
     *
264
     * @param string $rfc
265
     * @param DateTimeImmutable $since
266
     * @param DateTimeImmutable $until
267
     * @return Utilities\ReportUuidResult
268
     * @see https://wiki.finkok.com/doku.php?id=report_uuid
269
     */
270 1
    public function reportUuids(
271
        string $rfc,
272
        DateTimeImmutable $since,
273
        DateTimeImmutable $until
274
    ): Utilities\ReportUuidResult {
275 1
        $command = new Utilities\ReportUuidCommand($rfc, 'I', $since, $until);
276 1
        $service = new Utilities\ReportUuidService($this->settings());
277 1
        return $service->reportUuid($command);
278
    }
279
280
    /**
281
     * Reporte de los créditos añadidos de un RFC
282
     *
283
     * @param string $rfc
284
     * @return Utilities\ReportCreditResult
285
     * @see https://wiki.finkok.com/doku.php?id=report_uuid
286
     */
287 1
    public function reportCredits(string $rfc): Utilities\ReportCreditResult
288
    {
289 1
        $command = new Utilities\ReportCreditCommand($rfc);
290 1
        $service = new Utilities\ReportCreditService($this->settings());
291 1
        return $service->reportCredit($command);
292
    }
293
294
    /**
295
     * Reporte de los créditos añadidos de un RFC
296
     *
297
     * @param string $rfc
298
     * @param int $startYear
299
     * @param int $startMonth
300
     * @param int $endYear
301
     * @param int $endMonth
302
     * @return Utilities\ReportTotalResult
303
     * @see https://wiki.finkok.com/doku.php?id=report_uuid
304
     */
305 1
    public function reportTotals(
306
        string $rfc,
307
        int $startYear,
308
        int $startMonth,
309
        int $endYear = 0,
310
        int $endMonth = 0
311
    ): Utilities\ReportTotalResult {
312 1
        $command = new Utilities\ReportTotalCommand($rfc, 'I', $startYear, $startMonth, $endYear, $endMonth);
313 1
        $service = new Utilities\ReportTotalService($this->settings());
314 1
        return $service->reportTotal($command);
315
    }
316
317
    /**
318
     * Agrega un cliente que va a timbrar bajo la cuenta de un socio de negocios de Finkok
319
     *
320
     * @param string $rfc
321
     * @param Registration\CustomerType|null $type Si es NULL entonces se utiliza OnDemand
322
     * @return Registration\AddResult
323
     * @see https://wiki.finkok.com/doku.php?id=add
324
     */
325 1
    public function customersAdd(string $rfc, ?Registration\CustomerType $type = null): Registration\AddResult
326
    {
327 1
        $command = new Registration\AddCommand($rfc, $type);
328 1
        $service = new Registration\AddService($this->settings());
329 1
        return $service->add($command);
330
    }
331
332
    /**
333
     * Edita el estatus de un cliente (suspender o activar)
334
     *
335
     * @param string $rfc
336
     * @param Registration\CustomerStatus $status
337
     * @return Registration\EditResult
338
     * @see https://wiki.finkok.com/doku.php?id=edit
339
     */
340 1
    public function customersEdit(string $rfc, Registration\CustomerStatus $status): Registration\EditResult
341
    {
342 1
        $command = new Registration\EditCommand($rfc, $status);
343 1
        $service = new Registration\EditService($this->settings());
344 1
        return $service->edit($command);
345
    }
346
347
    /**
348
     * Obtiene un listado de clientes registrados, o solo uno si se especifica el RFC
349
     *
350
     * @param string $filterByRfc
351
     * @return Registration\ObtainResult
352
     * @see https://wiki.finkok.com/doku.php?id=get
353
     */
354 1
    public function customersObtain(string $filterByRfc = ''): Registration\ObtainResult
355
    {
356 1
        $command = new Registration\ObtainCommand($filterByRfc);
357 1
        $service = new Registration\ObtainService($this->settings());
358 1
        return $service->obtain($command);
359
    }
360
361
    /**
362
     * Asignar créditos un cliente que va a timbrar
363
     * Si el crédito es un valor positivo y el cliente está como OnDemand se cambiará a PrePaid con los créditos
364
     * Si el crédito es un valor positivo y el cliente está como PrePaid sumarán los créditos a los actuales
365
     * Si el crédito es -1 el cliente se pondrá como OnDemand
366
     *
367
     * @param string $rfc
368
     * @param int $credits
369
     * @return Registration\AssignResult
370
     * @see https://wiki.finkok.com/doku.php?id=assign
371
     */
372 1
    public function customersAssign(string $rfc, int $credits): Registration\AssignResult
373
    {
374 1
        $command = new Registration\AssignCommand($rfc, $credits);
375 1
        $service = new Registration\AssignService($this->settings());
376 1
        return $service->assign($command);
377
    }
378
379
    /**
380
     * Obtiene los textos del manifiesto de FINKOK (Aviso de Privacidad y Contrato de Servicio)
381
     *
382
     * @param string $rfc
383
     * @param string $name
384
     * @param string $address
385
     * @param string $email
386
     * @return Manifest\GetContractsResult
387
     * @see https://wiki.finkok.com/doku.php?id=get_contracts
388
     */
389 1
    public function customerGetContracts(
390
        string $rfc,
391
        string $name,
392
        string $address,
393
        string $email
394
    ): Manifest\GetContractsResult {
395 1
        $command = new Manifest\GetContractsCommand($rfc, $name, $address, $email);
396 1
        $service = new Manifest\GetContractsService($this->settings());
397 1
        return $service->obtainContracts($command);
398
    }
399
400
    /**
401
     * Envía el aviso de privacidad y contratos firmados
402
     *
403
     * @param string $snid
404
     * @param string $signedPrivacy
405
     * @param string $signedContract
406
     * @return Manifest\SignContractsResult
407
     * @see https://wiki.finkok.com/doku.php?id=firmar
408
     */
409 1
    public function customerSendContracts(
410
        string $snid,
411
        string $signedPrivacy,
412
        string $signedContract
413
    ): Manifest\SignContractsResult {
414 1
        $command = new Manifest\SignContractsCommand($snid, $signedPrivacy, $signedContract);
415 1
        $service = new Manifest\SignContractsService($this->settings());
416 1
        return $service->sendSignedContracts($command);
417
    }
418
419
    /**
420
     * Obtiene los documentos legales (aviso de privacidad y contrato), los firma con la FIEL y envía
421
     *
422
     * @param Credential $fiel
423
     * @param string $snid
424
     * @param string $address
425
     * @param string $email
426
     * @param DateTimeImmutable|null $signedOn Si es NULL se utiliza la fecha y hora del sistema
427
     * @return Manifest\SignContractsResult
428
     */
429 2
    public function customerSignAndSendContracts(
430
        Credential $fiel,
431
        string $snid,
432
        string $address,
433
        string $email,
434
        ?DateTimeImmutable $signedOn = null
435
    ): Manifest\SignContractsResult {
436 2
        $rfc = $fiel->rfc();
437 2
        $name = $fiel->legalName();
438 2
        $signedOn = $signedOn ?? new DateTimeImmutable();
439 2
        $documents = $this->customerGetContracts($rfc, $name, $address, $email);
440 2
        if (! $documents->success()) {
441 1
            return Manifest\SignContractsResult::createFromData(
442 1
                false,
443 1
                sprintf('Unable to get contracts: %s', $documents->error() ?: '(no error)')
444
            );
445
        }
446 1
        $privacy = (new Helpers\DocumentSigner($rfc, $signedOn, $documents->privacy()))->signUsingCredential($fiel);
447 1
        $contract = (new Helpers\DocumentSigner($rfc, $signedOn, $documents->contract()))->signUsingCredential($fiel);
448 1
        return $this->customerSendContracts($snid, $privacy, $contract);
449
    }
450
}
451