-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathInvoice.php
More file actions
1386 lines (1254 loc) · 39.3 KB
/
Copy pathInvoice.php
File metadata and controls
1386 lines (1254 loc) · 39.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* OpenAEAT Billing Library - Invoice Class
*
* This class handles VeriFactu invoice creation, validation, and submission
* for the Spanish Tax Agency (AEAT) electronic invoicing system.
*
* Supports all invoice types defined in RD 1619/2012:
* - Standard invoices (F1)
* - Simplified invoices (F2)
* - Substitution invoices (F3)
* - Credit notes / Rectifying invoices (R1-R5)
*
* @package OpenAEAT\Billing
* @author German Luis Aracil Boned <garacilb@gmail.com>
* @copyright 2025 German Luis Aracil Boned
* @license GPL-3.0-or-later
*/
declare(strict_types=1);
namespace OpenAEAT\Billing;
/**
* VeriFactu Invoice Document Builder
*/
class Invoice
{
/**
* VAT qualification codes (AEAT L9)
*/
public const QUAL_TAXABLE = 'S1';
public const QUAL_TAXABLE_REVERSE = 'S2';
public const QUAL_NOT_SUBJECT = 'N1';
public const QUAL_NOT_SUBJECT_LOCATION = 'N2';
/**
* Exemption reason codes (AEAT L10)
*/
public const EXEMPT_ARTICLE_20 = 'E1';
public const EXEMPT_ARTICLE_21 = 'E2';
public const EXEMPT_ARTICLE_22 = 'E3';
public const EXEMPT_ARTICLE_23_24 = 'E4';
public const EXEMPT_ARTICLE_25 = 'E5';
public const EXEMPT_OTHER = 'E6';
/**
* Document type codes (RD 1619/2012)
*/
public const TYPE_STANDARD = 'F1';
public const TYPE_SIMPLIFIED = 'F2';
public const TYPE_SUBSTITUTION = 'F3';
public const TYPE_CREDIT_NOTE_LEGAL = 'R1';
public const TYPE_CREDIT_NOTE_80_3 = 'R2';
public const TYPE_CREDIT_NOTE_80_4 = 'R3';
public const TYPE_CREDIT_NOTE_OTHER = 'R4';
public const TYPE_CREDIT_NOTE_SIMPLIFIED = 'R5';
/**
* Tax system codes (AEAT L1)
*/
public const TAX_VAT = '01';
public const TAX_IPSI = '02';
public const TAX_IGIC = '03';
public const TAX_OTHER = '05';
/**
* Foreign identification type codes
*/
public const ID_TYPE_EU_VAT = '02';
public const ID_TYPE_PASSPORT = '03';
public const ID_TYPE_OFFICIAL_DOC = '04';
public const ID_TYPE_RESIDENCE_CERT = '05';
public const ID_TYPE_OTHER_DOC = '06';
public const ID_TYPE_NOT_REGISTERED = '07';
/**
* Rectification method codes
*/
public const RECT_SUBSTITUTION = 'S';
public const RECT_DIFFERENCES = 'I';
/**
* VAT regime codes
*/
public const REGIME_GENERAL = '01';
public const REGIME_EXPORT = '02';
public const REGIME_USED_GOODS = '03';
public const REGIME_INVESTMENT_GOLD = '04';
public const REGIME_TRAVEL_AGENCIES = '05';
public const REGIME_VAT_GROUP = '06';
public const REGIME_CASH_ACCOUNTING = '07';
public const REGIME_IGIC_IPSI = '08';
public const REGIME_TRAVEL_INTERMEDIARIES = '09';
public const REGIME_THIRD_PARTY_COLLECTIONS = '10';
public const REGIME_BUSINESS_RENTAL = '11';
public const REGIME_CONSTRUCTION_CERT = '14';
public const REGIME_SUCCESSIVE_TRACT = '15';
public const REGIME_OSS_IOSS = '17';
public const REGIME_EQUIVALENCE_SURCHARGE = '18';
public const REGIME_AGRICULTURE = '19';
public const REGIME_SIMPLIFIED = '20';
/**
* Protocol version
*/
private const SCHEMA_VERSION = '1.0';
/**
* Hash algorithm identifier
*/
private const HASH_TYPE_SHA256 = '01';
/**
* Issuer identification
*/
private array $issuerData = [
'taxId' => '',
'legalName' => '',
];
/**
* Document identification
*/
private array $documentId = [
'serial' => '',
'issueDate' => '',
];
/**
* Document payload
*/
private array $payload = [];
/**
* Recipient collection
*/
private array $recipientList = [];
/**
* Tax breakdown entries
*/
private array $taxEntries = [];
/**
* Aggregated tax groups
*/
private array $taxGroups = [];
/**
* Submission header data
*/
private array $headerData = [];
/**
* Document status flags
*/
private array $statusFlags = [
'isAmendment' => false,
'isPriorRejection' => false,
];
/**
* Constructs a new invoice document.
*
* @param string $serial Document serial number
* @param string $issueDate Issue date (DD-MM-YYYY)
* @param string $issuerTaxId Issuer tax identification
* @param string $issuerName Issuer legal name
*/
public function __construct(
string $serial = '',
string $issueDate = '',
string $issuerTaxId = '',
string $issuerName = ''
) {
$this->issuerData['taxId'] = $issuerTaxId;
$this->issuerData['legalName'] = $issuerName;
$this->documentId['serial'] = $serial;
$this->documentId['issueDate'] = $issueDate;
$this->initializePayload($serial, $issueDate, $issuerTaxId, $issuerName);
}
/**
* Initializes the document payload structure.
*/
private function initializePayload(string $serial, string $date, string $taxId, string $name): void
{
$this->payload = [
'IDVersion' => self::SCHEMA_VERSION,
'IDFactura' => [
'NumSerieFactura' => $serial,
'FechaExpedicionFactura' => $date,
],
'TipoFactura' => self::TYPE_STANDARD,
'FechaHoraHusoGenRegistro' => $this->generateTimestamp(),
'TipoHuella' => self::HASH_TYPE_SHA256,
];
if (!empty($taxId)) {
$this->payload['IDFactura']['IDEmisorFactura'] = $taxId;
$this->payload['NombreRazonEmisor'] = $name;
}
}
/**
* Generates current timestamp in ISO 8601 format.
*
* @return string Formatted timestamp
*/
private function generateTimestamp(): string
{
return date('Y-m-d\TH:i:sP');
}
/**
* Creates an amendment document.
*
* @param string $serial Document serial
* @param string $date Issue date
* @param string $taxId Issuer tax ID
* @param string $name Issuer name
* @param bool $priorRejection Whether correcting a rejection
* @return self
*/
public static function createSubsanacion(
string $serial,
string $date,
string $taxId,
string $name,
bool $priorRejection = false
): self {
$instance = new self($serial, $date, $taxId, $name);
$instance->setAsCorrection(true);
if ($priorRejection) {
$instance->setAsPreviousRejection(true);
}
return $instance;
}
/**
* Creates a credit note document.
*
* @param string $serial Document serial
* @param string $date Issue date
* @param string $taxId Issuer tax ID
* @param string $name Issuer name
* @param string $creditType Credit note type code
* @return self
*/
public static function createRectificativa(
string $serial,
string $date,
string $taxId,
string $name,
string $creditType = self::TYPE_CREDIT_NOTE_LEGAL
): self {
$instance = new self($serial, $date, $taxId, $name);
$instance->setType($creditType);
return $instance;
}
/**
* Creates a simplified invoice document.
*
* @param string $serial Document serial
* @param string $date Issue date
* @param string $taxId Issuer tax ID
* @param string $name Issuer name
* @return self
*/
public static function createSimplificada(
string $serial,
string $date,
string $taxId,
string $name
): self {
$instance = new self($serial, $date, $taxId, $name);
$instance->setType(self::TYPE_SIMPLIFIED);
return $instance;
}
/**
* Returns available document types with descriptions.
*
* @return array Type code => description mapping
*/
public static function getTiposFactura(): array
{
return [
self::TYPE_STANDARD => 'Invoice (art. 6, 7.2 and 7.3 of RD 1619/2012)',
self::TYPE_SIMPLIFIED => 'Simplified Invoice',
self::TYPE_SUBSTITUTION => 'Invoice issued as substitution of simplified invoices',
self::TYPE_CREDIT_NOTE_LEGAL => 'Credit Note (Legal error)',
self::TYPE_CREDIT_NOTE_80_3 => 'Credit Note (Art. 80.3)',
self::TYPE_CREDIT_NOTE_80_4 => 'Credit Note (Art. 80.4)',
self::TYPE_CREDIT_NOTE_OTHER => 'Credit Note (Other causes)',
self::TYPE_CREDIT_NOTE_SIMPLIFIED => 'Credit Note for simplified invoices',
];
}
/**
* Returns current timestamp (compatibility method).
*
* @return string ISO 8601 timestamp
*/
public function getCurrentDateTimeISO8601(): string
{
return $this->generateTimestamp();
}
/**
* Sets issuer information.
*
* @param string $taxId Tax identification number
* @param string $name Legal name
* @return self
*/
public function setIssuer(string $taxId, string $name): self
{
$this->issuerData['taxId'] = $taxId;
$this->issuerData['legalName'] = $name;
$this->payload['IDFactura']['IDEmisorFactura'] = $taxId;
$this->payload['NombreRazonEmisor'] = $name;
return $this;
}
/**
* Sets document type.
*
* @param string $type Type code constant
* @return self
*/
public function setType(string $type): self
{
$this->payload['TipoFactura'] = $type;
return $this;
}
/**
* Sets operation description.
*
* @param string $text Description text
* @return self
*/
public function setDescription(string $text): self
{
$this->payload['DescripcionOperacion'] = $text;
return $this;
}
/**
* Sets external reference identifier.
*
* @param string $ref Reference string
* @return self
*/
public function setExternalReference(string $ref): self
{
$this->payload['RefExterna'] = $ref;
return $this;
}
/**
* Sets rectification method type.
*
* @param string $method RECT_SUBSTITUTION or RECT_DIFFERENCES
* @return self
*/
public function setRectificationType(string $method): self
{
$this->payload['TipoRectificativa'] = $method;
return $this;
}
/**
* Sets incidence flag for voluntary submissions.
*
* @param string $flag 'S' or 'N'
* @return self
*/
public function setIncidence(string $flag): self
{
if (!in_array($flag, ['S', 'N'], true)) {
throw new \InvalidArgumentException('Incidence must be "S" or "N"');
}
$this->headerData['RemisionVoluntaria']['Incidencia'] = $flag;
return $this;
}
/**
* Returns current incidence flag.
*
* @return string Flag value
*/
public function getIncidence(): string
{
return $this->headerData['RemisionVoluntaria']['Incidencia'] ?? 'N';
}
/**
* Adds a Spanish recipient.
*
* @param string $taxId Recipient NIF
* @param string $name Recipient name
* @return self
*/
public function addRecipient(string $taxId, string $name): self
{
$this->recipientList[] = [
'NombreRazon' => $name,
'NIF' => $taxId,
];
$this->syncRecipients();
return $this;
}
/**
* Adds a foreign recipient.
*
* @param string $name Recipient name
* @param string $idType Identification type code
* @param string $idNumber Identification number
* @param string|null $countryCode ISO country code
* @return self
*/
public function addForeignRecipient(
string $name,
string $idType,
string $idNumber,
?string $countryCode = null
): self {
if (empty($countryCode) || strtoupper($countryCode) === 'ES') {
return $this->addRecipient($idNumber, $name);
}
$this->recipientList[] = [
'NombreRazon' => $name,
'IDOtro' => [
'CodigoPais' => strtoupper($countryCode),
'IDType' => $idType,
'ID' => $idNumber,
],
];
$this->syncRecipients();
return $this;
}
/**
* Synchronizes recipient list with payload.
*/
private function syncRecipients(): void
{
$this->payload['Destinatarios'] = ['IDDestinatario' => $this->recipientList];
}
/**
* Returns current recipients.
*
* @return array Recipient data
*/
public function getRecipients(): array
{
return $this->payload['Destinatarios'] ?? [];
}
/**
* Sets multiple recipients at once.
*
* @param array $recipients Recipient data array
* @return self
*/
public function setRecipients(array $recipients): self
{
$this->recipientList = [];
foreach ($recipients as $recipient) {
if (isset($recipient['NIF'], $recipient['NombreRazon'])) {
$this->recipientList[] = [
'NombreRazon' => $recipient['NombreRazon'],
'NIF' => $recipient['NIF'],
];
}
}
$this->syncRecipients();
return $this;
}
/**
* Adds a tax breakdown entry.
*
* @param string|null $qualification VAT qualification code
* @param float $baseAmount Tax base or non-subject amount
* @param string|null $exemptionCause Exemption reason code
* @param string $taxSystem Tax system code
* @param string|null $regime VAT regime code
* @param float|null $rate Tax rate percentage
* @param float|null $taxAmount Calculated tax
* @param float|null $costBase Cost base amount
* @param float|null $surchargeRate Equivalence surcharge rate
* @param float|null $surchargeAmount Equivalence surcharge amount
* @return self
*/
public function addDesglose(
?string $qualification,
float $baseAmount,
?string $exemptionCause = null,
string $taxSystem = self::TAX_VAT,
?string $regime = null,
?float $rate = null,
?float $taxAmount = null,
?float $costBase = null,
?float $surchargeRate = null,
?float $surchargeAmount = null
): self {
if ($baseAmount == 0 && ($rate == 0 || $rate === null)) {
return $this;
}
$groupKey = $this->buildGroupKey($rate, $surchargeRate, $regime);
if (!isset($this->taxGroups[$groupKey])) {
$this->taxGroups[$groupKey] = $this->createTaxGroup(
$qualification,
$taxSystem,
$regime,
$exemptionCause,
$rate,
$taxAmount,
$costBase,
$surchargeRate,
$surchargeAmount
);
}
$this->aggregateTaxGroup($groupKey, $baseAmount, $costBase, $taxAmount, $surchargeAmount);
$this->rebuildTaxEntries();
$this->payload['Desglose'] = ['DetalleDesglose' => $this->taxEntries];
return $this;
}
/**
* Builds aggregation key for tax groups.
*/
private function buildGroupKey(?float $rate, ?float $surcharge, ?string $regime): string
{
$rateRounded = $rate !== null ? round($rate, 1) : 0;
$surchargeRounded = $surcharge !== null ? round($surcharge, 1) : 0;
return sprintf('%s_%s_%s', $rateRounded, $surchargeRounded, $regime ?? 'NONE');
}
/**
* Creates a new tax group structure.
*/
private function createTaxGroup(
?string $qual,
string $tax,
?string $regime,
?string $exempt,
?float $rate,
?float $amount,
?float $cost,
?float $surRate,
?float $surAmount
): array {
$group = [
'CalificacionOperacion' => $qual,
'BaseImponibleOimporteNoSujeto' => 0,
'Impuesto' => $tax,
];
if (!empty($regime)) {
$group['ClaveRegimen'] = $regime;
}
if (!empty($exempt)) {
$group['OperacionExenta'] = $exempt;
} else {
if ($rate !== null) {
$group['TipoImpositivo'] = round($rate, 2);
}
if ($amount !== null) {
$group['CuotaRepercutida'] = 0;
}
if ($surRate !== null) {
$group['TipoRecargoEquivalencia'] = round($surRate, 2);
}
if ($surAmount !== null) {
$group['CuotaRecargoEquivalencia'] = 0;
}
}
if ($cost !== null) {
$group['BaseImponibleACoste'] = 0;
}
return $group;
}
/**
* Aggregates amounts into a tax group.
*/
private function aggregateTaxGroup(
string $key,
float $base,
?float $cost,
?float $tax,
?float $surcharge
): void {
$this->taxGroups[$key]['BaseImponibleOimporteNoSujeto'] += $base;
if ($cost !== null && isset($this->taxGroups[$key]['BaseImponibleACoste'])) {
$this->taxGroups[$key]['BaseImponibleACoste'] += $cost;
}
if ($tax !== null && isset($this->taxGroups[$key]['CuotaRepercutida'])) {
$this->taxGroups[$key]['CuotaRepercutida'] += $tax;
$this->taxGroups[$key]['CuotaRepercutida'] = round(
$this->taxGroups[$key]['CuotaRepercutida'],
2
);
}
if ($surcharge !== null && isset($this->taxGroups[$key]['CuotaRecargoEquivalencia'])) {
$this->taxGroups[$key]['CuotaRecargoEquivalencia'] += $surcharge;
$this->taxGroups[$key]['CuotaRecargoEquivalencia'] = round(
$this->taxGroups[$key]['CuotaRecargoEquivalencia'],
2
);
}
}
/**
* Rebuilds tax entries from aggregated groups.
*/
private function rebuildTaxEntries(): void
{
$this->taxEntries = [];
foreach ($this->taxGroups as $group) {
$entry = $group;
$entry['BaseImponibleOimporteNoSujeto'] = round($group['BaseImponibleOimporteNoSujeto'], 2);
if (isset($group['CuotaRepercutida'])) {
$entry['CuotaRepercutida'] = round($group['CuotaRepercutida'], 2);
}
if (isset($group['BaseImponibleACoste'])) {
$entry['BaseImponibleACoste'] = round($group['BaseImponibleACoste'], 2);
}
if (isset($group['CuotaRecargoEquivalencia'])) {
$entry['CuotaRecargoEquivalencia'] = round($group['CuotaRecargoEquivalencia'], 2);
}
$this->taxEntries[] = $entry;
}
$this->computeTotals();
}
/**
* Adds a simplified tax line.
*
* @param string $qualification VAT qualification
* @param float $base Tax base
* @param float $rate Tax rate
* @param float|null $tax Tax amount
* @param string $regime VAT regime
* @param string|null $exemptionCause Exemption cause
* @param float|null $surchargeRate Surcharge rate
* @param float|null $surchargeAmount Surcharge amount
* @return self
*/
public function addTaxLine(
string $qualification,
float $base,
float $rate = 0.0,
?float $tax = null,
string $regime = '01',
?string $exemptionCause = null,
?float $surchargeRate = null,
?float $surchargeAmount = null
): self {
return $this->addDesglose(
$qualification,
$base,
$exemptionCause,
self::TAX_VAT,
$regime,
$rate,
$tax,
null,
$surchargeRate,
$surchargeAmount
);
}
/**
* Marks document as first in chain.
*
* @return self
*/
public function setAsFirstInChain(): self
{
$this->payload['Encadenamiento'] = ['PrimerRegistro' => 'S'];
return $this;
}
/**
* Sets chain link to previous document.
*
* @param string $prevTaxId Previous issuer tax ID
* @param string $prevSerial Previous serial number
* @param string $prevDate Previous issue date
* @param string $prevHash Previous document hash
* @return self
*/
public function setChainLink(
string $prevTaxId,
string $prevSerial,
string $prevDate,
string $prevHash
): self {
if (empty($prevHash)) {
throw new \InvalidArgumentException('The previous fingerprint cannot be empty.');
}
$this->payload['Encadenamiento']['RegistroAnterior'] = [
'IDEmisorFactura' => $prevTaxId,
'NumSerieFactura' => $prevSerial,
'FechaExpedicionFactura' => $prevDate,
'Huella' => $prevHash,
];
return $this;
}
/**
* Marks document as an amendment.
*
* @param bool $isAmendment Amendment flag
* @return self
*/
public function setAsCorrection(bool $isAmendment = true): self
{
$this->statusFlags['isAmendment'] = $isAmendment;
if ($isAmendment) {
$this->payload['Subsanacion'] = 'S';
} else {
unset($this->payload['Subsanacion']);
}
return $this;
}
/**
* Marks document as correction of prior rejection.
*
* @param bool $isPrior Prior rejection flag
* @return self
*/
public function setAsPreviousRejection(bool $isPrior = true): self
{
$this->statusFlags['isPriorRejection'] = $isPrior;
if ($isPrior) {
$this->payload['RechazoPrevio'] = 'X';
$this->setAsCorrection(true);
} else {
unset($this->payload['RechazoPrevio']);
}
return $this;
}
/**
* Sets billing system information.
*
* @param array $config System configuration
* @return self
*/
public function setSystemInfo(array $config): self
{
$this->payload['SistemaInformatico'] = $config;
return $this;
}
/**
* Sets billing system identity with standard fields.
*
* @param string $devTaxId Developer tax ID
* @param string $softName Software name
* @param string $softVersion Software version
* @param string $softId Software identifier
* @return self
*/
public function setSystemIdentity(
string $devTaxId,
string $softName,
string $softVersion,
string $softId
): self {
$this->payload['SistemaInformatico'] = [
'NombreRazon' => $softName,
'NIF' => strtoupper(trim($devTaxId)),
'NombreSistemaInformatico' => $softName,
'IdSistemaInformatico' => $softId,
'Version' => $softVersion,
'NumeroInstalacion' => '1',
'TipoUsoPosibleSoloVerifactu' => 'S',
'TipoUsoPosibleMultiOT' => 'N',
'IndicadorMultiplesOT' => 'N',
];
return $this;
}
/**
* Sets tax breakdown directly.
*
* @param array $breakdown Breakdown entries
* @return self
*/
public function setDesglose(array $breakdown): self
{
$this->taxEntries = $breakdown;
$this->payload['Desglose'] = ['DetalleDesglose' => $this->taxEntries];
$this->computeTotals();
return $this;
}
/**
* Sets additional information fields.
*
* @param array $fields Field => value pairs
* @return self
*/
public function setInformacionAdicional(array $fields): self
{
foreach ($fields as $field => $value) {
$this->payload[$field] = $value;
}
return $this;
}
/**
* Sets generation timestamp.
*
* @param string $timestamp ISO 8601 timestamp
* @return self
*/
public function setGenerationTimestamp(string $timestamp): self
{
$this->payload['FechaHoraHusoGenRegistro'] = $timestamp;
return $this;
}
/**
* Sets fingerprint type code.
*
* @param string $type Type code
* @return self
*/
public function setFingerprintType(string $type): self
{
$this->payload['TipoHuella'] = $type;
return $this;
}
/**
* Sets timestamp for hash generation.
*
* @param string $timestamp Timestamp or empty for current
* @return self
*/
public function setTimestampForHash(string $timestamp = ''): self
{
$this->payload['FechaHoraHusoGenRegistro'] = empty($timestamp)
? $this->generateTimestamp()
: $timestamp;
return $this;
}
/**
* Sets document identification.
*
* @param string $serial Serial number
* @param string $date Issue date
* @return self
*/
public function setInvoiceId(string $serial, string $date): self
{
$this->payload['IDFactura']['NumSerieFactura'] = trim($serial);
$this->payload['IDFactura']['FechaExpedicionFactura'] = $date;
$this->documentId['serial'] = trim($serial);
$this->documentId['issueDate'] = $date;
return $this;
}
/**
* Adds a rectified invoice reference.
*
* @param string $taxId Original issuer tax ID
* @param string $serial Original serial number
* @param string $date Original issue date
* @param float $baseRect Rectified base amount
* @param float $taxRect Rectified tax amount
* @param float|null $surchargeRect Rectified surcharge amount
* @return self
*/
public function addRectifiedInvoice(
string $taxId,
string $serial,
string $date,
float $baseRect,
float $taxRect,
?float $surchargeRect = null
): self {
if (!isset($this->payload['FacturasRectificadas'])) {
$this->payload['FacturasRectificadas'] = [];
}
$this->payload['FacturasRectificadas'][] = [
'IDEmisorFactura' => $taxId,
'NumSerieFactura' => $serial,
'FechaExpedicionFactura' => $date,
];
if (!isset($this->payload['ImporteRectificacion'])) {
$this->payload['ImporteRectificacion'] = [
'BaseRectificada' => 0.00,
'CuotaRectificada' => 0.00,
'CuotaRecargoRectificado' => 0.00,
];
}
$this->payload['ImporteRectificacion']['BaseRectificada'] += $baseRect;
$this->payload['ImporteRectificacion']['CuotaRectificada'] += $taxRect;
if ($surchargeRect !== null && $surchargeRect > 0) {
$this->payload['ImporteRectificacion']['CuotaRecargoRectificado'] += $surchargeRect;
}
$this->formatRectificationAmounts();
return $this;
}
/**
* Formats rectification amounts.
*/
private function formatRectificationAmounts(): void
{
$rect = &$this->payload['ImporteRectificacion'];
$rect['BaseRectificada'] = number_format((float) $rect['BaseRectificada'], 2, '.', '');
$rect['CuotaRectificada'] = number_format((float) $rect['CuotaRectificada'], 2, '.', '');
$rect['CuotaRecargoRectificado'] = number_format((float) $rect['CuotaRecargoRectificado'], 2, '.', '');
}
/**
* Computes and updates document totals.
*/
private function computeTotals(): void
{
$totalBase = 0;
$totalTax = 0;
$totalSurcharge = 0;
foreach ($this->taxEntries as $entry) {
$totalBase += (float) ($entry['BaseImponibleOimporteNoSujeto'] ?? 0);
$totalTax += (float) ($entry['CuotaRepercutida'] ?? 0);
$totalSurcharge += (float) ($entry['CuotaRecargoEquivalencia'] ?? 0);
}
$combinedTax = $totalTax + $totalSurcharge;
$grandTotal = $totalBase + $combinedTax;
$this->payload['CuotaTotal'] = number_format($combinedTax, 2, '.', '');
$this->payload['ImporteTotal'] = number_format($grandTotal, 2, '.', '');
}
/**
* Calculates and returns document totals.
*
* @return array Totals breakdown
*/
public function calculateTotals(): array
{
$this->computeTotals();
$totalBase = 0.0;
$totalTax = 0.0;
$totalSurcharge = 0.0;
foreach ($this->taxEntries as $entry) {
$totalBase += (float) ($entry['BaseImponibleOimporteNoSujeto'] ?? 0);
$totalTax += (float) ($entry['CuotaRepercutida'] ?? 0);
$totalSurcharge += (float) ($entry['CuotaRecargoEquivalencia'] ?? 0);
}
return [
'base' => $totalBase,
'tax' => $totalTax,
'surcharge' => $totalSurcharge,
'total' => $totalBase + $totalTax + $totalSurcharge,
];
}