Passed
Push — master ( 777707...496bfe )
by Carlos C
46s queued 10s
created

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