Completed
Pull Request — master (#9)
by Carlos C
03:14
created

QuickFinkok::answerAcceptRejectCancellation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 10
ccs 6
cts 6
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
     * @return Utilities\DatetimeResult
251
     * @see https://wiki.finkok.com/doku.php?id=datetime
252
     */
253 1
    public function serversDateTime(): Utilities\DatetimeResult
254
    {
255 1
        $service = new Utilities\DatetimeService($this->settings());
256 1
        return $service->datetime();
257
    }
258
259
    /**
260
     * Reporte de los UUID timbrados con fecha, de un RFC entre un periodo de tiempo determinado
261
     *
262
     * @param string $rfc
263
     * @param DateTimeImmutable $since
264
     * @param DateTimeImmutable $until
265
     * @return Utilities\ReportUuidResult
266
     * @see https://wiki.finkok.com/doku.php?id=report_uuid
267
     */
268 1
    public function reportUuids(
269
        string $rfc,
270
        DateTimeImmutable $since,
271
        DateTimeImmutable $until
272
    ): Utilities\ReportUuidResult {
273 1
        $command = new Utilities\ReportUuidCommand($rfc, 'I', $since, $until);
274 1
        $service = new Utilities\ReportUuidService($this->settings());
275 1
        return $service->reportUuid($command);
276
    }
277
278
    /**
279
     * Reporte de los créditos añadidos de un RFC
280
     *
281
     * @param string $rfc
282
     * @return Utilities\ReportCreditResult
283
     * @see https://wiki.finkok.com/doku.php?id=report_uuid
284
     */
285 1
    public function reportCredits(string $rfc): Utilities\ReportCreditResult
286
    {
287 1
        $command = new Utilities\ReportCreditCommand($rfc);
288 1
        $service = new Utilities\ReportCreditService($this->settings());
289 1
        return $service->reportCredit($command);
290
    }
291
292
    /**
293
     * Reporte de los créditos añadidos de un RFC
294
     *
295
     * @param string $rfc
296
     * @param int $startYear
297
     * @param int $startMonth
298
     * @param int $endYear
299
     * @param int $endMonth
300
     * @return Utilities\ReportTotalResult
301
     * @see https://wiki.finkok.com/doku.php?id=report_uuid
302
     */
303 1
    public function reportTotals(
304
        string $rfc,
305
        int $startYear,
306
        int $startMonth,
307
        int $endYear = 0,
308
        int $endMonth = 0
309
    ): Utilities\ReportTotalResult {
310 1
        $command = new Utilities\ReportTotalCommand($rfc, 'I', $startYear, $startMonth, $endYear, $endMonth);
311 1
        $service = new Utilities\ReportTotalService($this->settings());
312 1
        return $service->reportTotal($command);
313
    }
314
315
    /**
316
     * Agrega un cliente que va a timbrar bajo la cuenta de un socio de negocios de Finkok
317
     *
318
     * @param string $rfc
319
     * @param Registration\CustomerType|null $type Si es NULL entonces se utiliza OnDemand
320
     * @return Registration\AddResult
321
     * @see https://wiki.finkok.com/doku.php?id=add
322
     */
323 1
    public function customersAdd(string $rfc, ?Registration\CustomerType $type = null): Registration\AddResult
324
    {
325 1
        $command = new Registration\AddCommand($rfc, $type);
326 1
        $service = new Registration\AddService($this->settings());
327 1
        return $service->add($command);
328
    }
329
330
    /**
331
     * Edita el estatus de un cliente (suspender o activar)
332
     *
333
     * @param string $rfc
334
     * @param Registration\CustomerStatus $status
335
     * @return Registration\EditResult
336
     * @see https://wiki.finkok.com/doku.php?id=edit
337
     */
338 1
    public function customersEdit(string $rfc, Registration\CustomerStatus $status): Registration\EditResult
339
    {
340 1
        $command = new Registration\EditCommand($rfc, $status);
341 1
        $service = new Registration\EditService($this->settings());
342 1
        return $service->edit($command);
343
    }
344
345
    /**
346
     * Obtiene un listado de clientes registrados, o solo uno si se especifica el RFC
347
     *
348
     * @param string $filterByRfc
349
     * @return Registration\ObtainResult
350
     * @see https://wiki.finkok.com/doku.php?id=get
351
     */
352 1
    public function customersObtain(string $filterByRfc = ''): Registration\ObtainResult
353
    {
354 1
        $command = new Registration\ObtainCommand($filterByRfc);
355 1
        $service = new Registration\ObtainService($this->settings());
356 1
        return $service->obtain($command);
357
    }
358
359
    /**
360
     * Asignar créditos un cliente que va a timbrar
361
     * Si el crédito es un valor positivo y el cliente está como OnDemand se cambiará a PrePaid con los créditos
362
     * Si el crédito es un valor positivo y el cliente está como PrePaid sumarán los créditos a los actuales
363
     * Si el crédito es -1 el cliente se pondrá como OnDemand
364
     *
365
     * @param string $rfc
366
     * @param int $credits
367
     * @return Registration\AssignResult
368
     * @see https://wiki.finkok.com/doku.php?id=assign
369
     */
370 1
    public function customersAssign(string $rfc, int $credits): Registration\AssignResult
371
    {
372 1
        $command = new Registration\AssignCommand($rfc, $credits);
373 1
        $service = new Registration\AssignService($this->settings());
374 1
        return $service->assign($command);
375
    }
376
377
    /**
378
     * Obtiene los textos del manifiesto de FINKOK (Aviso de Privacidad y Contrato de Servicio)
379
     *
380
     * @param string $rfc
381
     * @param string $name
382
     * @param string $address
383
     * @param string $email
384
     * @return Manifest\GetContractsResult
385
     * @see https://wiki.finkok.com/doku.php?id=get_contracts
386
     */
387 1
    public function customerGetContracts(
388
        string $rfc,
389
        string $name,
390
        string $address,
391
        string $email
392
    ): Manifest\GetContractsResult {
393 1
        $command = new Manifest\GetContractsCommand($rfc, $name, $address, $email);
394 1
        $service = new Manifest\GetContractsService($this->settings());
395 1
        return $service->obtainContracts($command);
396
    }
397
398
    /**
399
     * Envía el aviso de privacidad y contratos firmados
400
     *
401
     * @param string $snid
402
     * @param string $signedPrivacy
403
     * @param string $signedContract
404
     * @return Manifest\SignContractsResult
405
     * @see https://wiki.finkok.com/doku.php?id=firmar
406
     */
407 1
    public function customerSendContracts(
408
        string $snid,
409
        string $signedPrivacy,
410
        string $signedContract
411
    ): Manifest\SignContractsResult {
412 1
        $command = new Manifest\SignContractsCommand($snid, $signedPrivacy, $signedContract);
413 1
        $service = new Manifest\SignContractsService($this->settings());
414 1
        return $service->sendSignedContracts($command);
415
    }
416
417
    /**
418
     * Obtiene los documentos legales (aviso de privacidad y contrato), los firma con la FIEL y envía
419
     *
420
     * @param Credential $fiel
421
     * @param string $snid
422
     * @param string $address
423
     * @param string $email
424
     * @param DateTimeImmutable|null $signedOn Si es NULL se utiliza la fecha y hora del sistema
425
     * @return Manifest\SignContractsResult
426
     */
427 2
    public function customerSignAndSendContracts(
428
        Credential $fiel,
429
        string $snid,
430
        string $address,
431
        string $email,
432
        ?DateTimeImmutable $signedOn = null
433
    ): Manifest\SignContractsResult {
434 2
        $rfc = $fiel->rfc();
435 2
        $name = $fiel->legalName();
436 2
        $signedOn = $signedOn ?? new DateTimeImmutable();
437 2
        $documents = $this->customerGetContracts($rfc, $name, $address, $email);
438 2
        if (! $documents->success()) {
439 1
            return Manifest\SignContractsResult::createFromData(
440 1
                false,
441 1
                sprintf('Unable to get contracts: %s', $documents->error() ?: '(no error)')
442
            );
443
        }
444 1
        $privacy = (new Helpers\DocumentSigner($rfc, $signedOn, $documents->privacy()))->signUsingCredential($fiel);
445 1
        $contract = (new Helpers\DocumentSigner($rfc, $signedOn, $documents->contract()))->signUsingCredential($fiel);
446 1
        return $this->customerSendContracts($snid, $privacy, $contract);
447
    }
448
}
449