Completed
Pull Request — master (#13)
by Carlos C
01:54
created

QuickFinkok::customerGetSignedContracts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 3
dl 0
loc 9
ccs 0
cts 5
cp 0
crap 2
rs 10
c 0
b 0
f 0
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 22
    public function __construct(FinkokSettings $factory)
25
    {
26 22
        $this->settings = $factory;
27 22
    }
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 22
    public function settings(): FinkokSettings
35
    {
36 22
        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
     * Obtiene un listado de clientes registrados, o solo uno si se especifica el RFC
350
     *
351
     * @param string $filterByRfc
352
     * @return Registration\ObtainResult
353
     * @see https://wiki.finkok.com/doku.php?id=get
354
     */
355 1
    public function customersObtain(string $filterByRfc = ''): Registration\ObtainResult
356
    {
357 1
        $command = new Registration\ObtainCommand($filterByRfc);
358 1
        $service = new Registration\ObtainService($this->settings());
359 1
        return $service->obtain($command);
360
    }
361
362
    /**
363
     * Asignar créditos un cliente que va a timbrar
364
     * Si el crédito es un valor positivo y el cliente está como OnDemand se cambiará a PrePaid con los créditos
365
     * Si el crédito es un valor positivo y el cliente está como PrePaid sumarán los créditos a los actuales
366
     * Si el crédito es -1 el cliente se pondrá como OnDemand
367
     *
368
     * @param string $rfc
369
     * @param int $credits
370
     * @return Registration\AssignResult
371
     * @see https://wiki.finkok.com/doku.php?id=assign
372
     */
373 1
    public function customersAssign(string $rfc, int $credits): Registration\AssignResult
374
    {
375 1
        $command = new Registration\AssignCommand($rfc, $credits);
376 1
        $service = new Registration\AssignService($this->settings());
377 1
        return $service->assign($command);
378
    }
379
380
    /**
381
     * Obtiene los textos del manifiesto de FINKOK (Aviso de Privacidad y Contrato de Servicio)
382
     *
383
     * @param string $rfc
384
     * @param string $name
385
     * @param string $address
386
     * @param string $email
387
     * @return Manifest\GetContractsResult
388
     * @see https://wiki.finkok.com/doku.php?id=get_contracts
389
     */
390 1
    public function customerGetContracts(
391
        string $rfc,
392
        string $name,
393
        string $address,
394
        string $email
395
    ): Manifest\GetContractsResult {
396 1
        $command = new Manifest\GetContractsCommand($rfc, $name, $address, $email);
397 1
        $service = new Manifest\GetContractsService($this->settings());
398 1
        return $service->obtainContracts($command);
399
    }
400
401
    /**
402
     * Envía el aviso de privacidad y contratos firmados
403
     *
404
     * @param string $snid
405
     * @param string $signedPrivacy
406
     * @param string $signedContract
407
     * @return Manifest\SignContractsResult
408
     * @see https://wiki.finkok.com/doku.php?id=firmar
409
     */
410 1
    public function customerSendContracts(
411
        string $snid,
412
        string $signedPrivacy,
413
        string $signedContract
414
    ): Manifest\SignContractsResult {
415 1
        $command = new Manifest\SignContractsCommand($snid, $signedPrivacy, $signedContract);
416 1
        $service = new Manifest\SignContractsService($this->settings());
417 1
        return $service->sendSignedContracts($command);
418
    }
419
420
    /**
421
     * Obtiene los documentos legales (aviso de privacidad y contrato), los firma con la FIEL y envía
422
     *
423
     * @param Credential $fiel
424
     * @param string $snid
425
     * @param string $address
426
     * @param string $email
427
     * @param DateTimeImmutable|null $signedOn Si es NULL se utiliza la fecha y hora del sistema
428
     * @return Manifest\SignContractsResult
429
     */
430 2
    public function customerSignAndSendContracts(
431
        Credential $fiel,
432
        string $snid,
433
        string $address,
434
        string $email,
435
        ?DateTimeImmutable $signedOn = null
436
    ): Manifest\SignContractsResult {
437 2
        $rfc = $fiel->rfc();
438 2
        $name = $fiel->legalName();
439 2
        $signedOn = $signedOn ?? new DateTimeImmutable();
440 2
        $documents = $this->customerGetContracts($rfc, $name, $address, $email);
441 2
        if (! $documents->success()) {
442 1
            return Manifest\SignContractsResult::createFromData(
443 1
                false,
444 1
                sprintf('Unable to get contracts: %s', $documents->error() ?: '(no error)')
445
            );
446
        }
447 1
        $privacy = (new Helpers\DocumentSigner($rfc, $signedOn, $documents->privacy()))->signUsingCredential($fiel);
448 1
        $contract = (new Helpers\DocumentSigner($rfc, $signedOn, $documents->contract()))->signUsingCredential($fiel);
449 1
        return $this->customerSendContracts($snid, $privacy, $contract);
450
    }
451
452
    /**
453
     * Obtiene los documentos legales (aviso de privacidad y contrato) previamente firmados con el SNID y RFC
454
     *
455
     * @param string $snid
456
     * @param string $rfc
457
     * @param SignedDocumentFormat|null $format
458
     * @return Manifest\GetSignedContractsResult
459
     */
460
    public function customerGetSignedContracts(
461
        string $snid,
462
        string $rfc,
463
        SignedDocumentFormat $format = null
464
    ): Manifest\GetSignedContractsResult {
465
        $format = $format ?? SignedDocumentFormat::xml();
466
        $command = new Manifest\GetSignedContractsCommand($snid, $rfc, $format);
467
        $service = new Manifest\GetSignedContractsService($this->settings());
468
        return $service->getSignedContracts($command);
469
    }
470
}
471