Factur-X/ZUGFeRD-Import: Falsche Nutzung von t8() für Fehlermeldung korrigiert
[kivitendo-erp.git] / SL / DB / Helper / ZUGFeRD.pm
1 package SL::DB::Helper::ZUGFeRD;
2
3 use strict;
4 use utf8;
5
6 use parent qw(Exporter);
7 our @EXPORT = qw(create_zugferd_data create_zugferd_xmp_data);
8
9 use SL::DB::BankAccount;
10 use SL::DB::GenericTranslation;
11 use SL::DB::Tax;
12 use SL::DB::TaxKey;
13 use SL::Helper::ISO3166;
14 use SL::Helper::ISO4217;
15 use SL::Helper::UNECERecommendation20;
16 use SL::VATIDNr;
17 use SL::ZUGFeRD qw(:PROFILES);
18
19 use Carp;
20 use Encode qw(encode);
21 use List::MoreUtils qw(any pairwise);
22 use List::Util qw(first sum);
23 use Template;
24 use XML::Writer;
25
26 my @line_names = qw(LineOne LineTwo LineThree);
27
28 my %standards_ids = (
29   PROFILE_FACTURX_EXTENDED() => 'urn:cen.eu:en16931:2017#conformant#urn:factur-x.eu:1p0:extended',
30 sub _is_profile {
31   my ($self, @profiles) = @_;
32   return any { $self->{_zugferd}->{profile} == $_ } @profiles;
33 }
34
35 sub _u8 {
36   my ($value) = @_;
37   return encode('UTF-8', $value // '');
38 }
39
40 sub _r2 {
41   my ($value) = @_;
42   return $::form->round_amount($value, 2);
43 }
44
45 sub _type_name {
46   my ($self) = @_;
47   my $type   = $self->invoice_type;
48
49   no warnings 'once';
50   return $type eq 'ar_transaction' ? $::locale->text('Invoice') : $self->displayable_type;
51 }
52
53 sub _type_code {
54   my ($self) = @_;
55   my $type   = $self->invoice_type;
56
57   # 326 (Partial invoice)
58   # 380 (Commercial invoice)
59   # 384 (Corrected Invoice)
60   # 381 (Credit note)
61   # 389 (Credit note, self billed invoice)
62
63   return $type eq 'credit_note'        ? 381
64        : $type eq 'invoice_storno'     ? 457
65        : $type eq 'credit_note_storno' ? 458
66        :                                 380;
67 }
68
69 sub _unit_code {
70   my ($unit) = @_;
71
72   # Mapping from kivitendo's units to UN/ECE Recommendation 20 & 21.
73   my $code = SL::Helper::UNECERecommendation20::map_name_to_code($unit);
74   return $code if $code;
75
76   $::lxdebug->message(LXDebug::WARN(), "ZUGFeRD unit name mapping: no UN/ECE Recommendation 20/21 unit known for kivitendo unit '$unit'; using 'C62'");
77
78   return 'C62';
79 }
80
81 sub _parse_our_address {
82   my @result;
83   my @street = grep { $_ } ($::instance_conf->get_address_street1, $::instance_conf->get_address_street2);
84
85   push @result, [ 'PostcodeCode', $::instance_conf->get_address_zipcode ] if $::instance_conf->get_address_zipcode;
86   push @result, grep { $_->[1] } pairwise { [ $a, $b] } @line_names, @street;
87   push @result, [ 'CityName', $::instance_conf->get_address_city ] if $::instance_conf->get_address_city;
88   push @result, [ 'CountryID', SL::Helper::ISO3166::map_name_to_alpha_2_code($::instance_conf->get_address_country) // 'DE' ];
89
90   return @result;
91 }
92
93 sub _customer_postal_trade_address {
94   my (%params) = @_;
95
96   #       <ram:PostalTradeAddress>
97   $params{xml}->startTag("ram:PostalTradeAddress");
98
99   my @parts = grep { $_ } map { $params{customer}->$_ } qw(department_1 department_2 street);
100
101   $params{xml}->dataElement("ram:PostcodeCode", _u8($params{customer}->zipcode));
102   $params{xml}->dataElement("ram:" . $_->[0],   _u8($_->[1])) for grep { $_->[1] } pairwise { [ $a, $b] } @line_names, @parts;
103   $params{xml}->dataElement("ram:CityName",     _u8($params{customer}->city));
104   $params{xml}->dataElement("ram:CountryID",    _u8(SL::Helper::ISO3166::map_name_to_alpha_2_code($params{customer}->country) // 'DE'));
105   $params{xml}->endTag;
106   #       </ram:PostalTradeAddress>
107 }
108
109 sub _tax_rate_and_code {
110   my ($taxzone, $tax) = @_;
111
112   my ($tax_rate, $tax_code) = @_;
113
114   if ($taxzone->description =~ m{Au.*erhalb}) {
115     $tax_rate = 0;
116     $tax_code = 'G';
117
118   } elsif ($taxzone->description =~ m{EU mit}) {
119     $tax_rate = 0;
120     $tax_code = 'K';
121
122   } else {
123     $tax_rate = $tax->rate * 100;
124     $tax_code = !$tax_rate ? 'Z' : 'S';
125   }
126
127   return (rate => $tax_rate, code => $tax_code);
128 }
129
130 sub _line_item {
131   my ($self, %params) = @_;
132
133   my $item_ptc = $params{ptc_data}->{items}->[$params{line_number}];
134
135   my $taxkey   = $item_ptc->{taxkey_id} ? SL::DB::TaxKey->load_cached($item_ptc->{taxkey_id}) : undef;
136   my $tax      = $item_ptc->{taxkey_id} ? SL::DB::Tax->load_cached($taxkey->tax_id)           : undef;
137   my %tax_info = _tax_rate_and_code($self->taxzone, $tax);
138
139   # <ram:IncludedSupplyChainTradeLineItem>
140   $params{xml}->startTag("ram:IncludedSupplyChainTradeLineItem");
141
142   #   <ram:AssociatedDocumentLineDocument>
143   $params{xml}->startTag("ram:AssociatedDocumentLineDocument");
144   $params{xml}->dataElement("ram:LineID", $params{line_number} + 1);
145   $params{xml}->endTag;
146
147   $params{xml}->startTag("ram:SpecifiedTradeProduct");
148   $params{xml}->dataElement("ram:SellerAssignedID", _u8($params{item}->part->partnumber));
149   $params{xml}->dataElement("ram:Name",             _u8($params{item}->description));
150   $params{xml}->endTag;
151
152   $params{xml}->startTag("ram:SpecifiedLineTradeAgreement");
153   $params{xml}->startTag("ram:NetPriceProductTradePrice");
154   $params{xml}->dataElement("ram:ChargeAmount", _r2($item_ptc->{sellprice}));
155   $params{xml}->endTag;
156   $params{xml}->endTag;
157   #   </ram:SpecifiedLineTradeAgreement>
158
159   #   <ram:SpecifiedLineTradeDelivery>
160   $params{xml}->startTag("ram:SpecifiedLineTradeDelivery");
161   $params{xml}->dataElement("ram:BilledQuantity", $params{item}->qty, unitCode => _unit_code($params{item}->unit));
162   $params{xml}->endTag;
163   #   </ram:SpecifiedLineTradeDelivery>
164
165   #   <ram:SpecifiedLineTradeSettlement>
166   $params{xml}->startTag("ram:SpecifiedLineTradeSettlement");
167
168   #     <ram:ApplicableTradeTax>
169   $params{xml}->startTag("ram:ApplicableTradeTax");
170   $params{xml}->dataElement("ram:TypeCode",              "VAT");
171   $params{xml}->dataElement("ram:CategoryCode",          $tax_info{code});
172   $params{xml}->dataElement("ram:RateApplicablePercent", _r2($tax_info{rate}));
173   $params{xml}->endTag;
174   #     </ram:ApplicableTradeTax>
175
176   #     <ram:SpecifiedTradeSettlementLineMonetarySummation>
177   $params{xml}->startTag("ram:SpecifiedTradeSettlementLineMonetarySummation");
178   $params{xml}->dataElement("ram:LineTotalAmount", _r2($item_ptc->{linetotal}));
179   $params{xml}->endTag;
180   #     </ram:SpecifiedTradeSettlementLineMonetarySummation>
181
182   $params{xml}->endTag;
183   #   </ram:SpecifiedLineTradeSettlement>
184
185   $params{xml}->endTag;
186   # <ram:IncludedSupplyChainTradeLineItem>
187 }
188
189 sub _specified_trade_settlement_payment_means {
190   my ($self, %params) = @_;
191
192   #     <ram:SpecifiedTradeSettlementPaymentMeans>
193   $params{xml}->startTag('ram:SpecifiedTradeSettlementPaymentMeans');
194   $params{xml}->dataElement('ram:TypeCode', $self->direct_debit ? 59 : 58); # 59 = SEPA direct debit, 58 = SEPA credit transfer
195
196   if ($self->direct_debit) {
197     $params{xml}->startTag('ram:PayerPartyDebtorFinancialAccount');
198     $params{xml}->dataElement('ram:IBANID', $self->customer->iban);
199     $params{xml}->endTag;
200
201   } else {
202     $params{xml}->startTag('ram:PayeePartyCreditorFinancialAccount');
203     $params{xml}->dataElement('ram:IBANID', $params{bank_account}->iban);
204     $params{xml}->endTag;
205   }
206
207   $params{xml}->endTag;
208   #     </ram:SpecifiedTradeSettlementPaymentMeans>
209 }
210
211 sub _taxes {
212   my ($self, %params) = @_;
213
214   my %taxkey_info;
215
216   foreach my $item (@{ $params{ptc_data}->{items} }) {
217     $taxkey_info{$item->{taxkey_id}} //= {
218       linetotal  => 0,
219       tax_amount => 0,
220     };
221     my $info             = $taxkey_info{$item->{taxkey_id}};
222     $info->{taxkey}    //= SL::DB::TaxKey->load_cached($item->{taxkey_id});
223     $info->{tax}       //= SL::DB::Tax->load_cached($info->{taxkey}->tax_id);
224     $info->{linetotal}  += $item->{linetotal};
225   }
226
227   foreach my $taxkey_id (sort keys %taxkey_info) {
228     my $info     = $taxkey_info{$taxkey_id};
229     my %tax_info = _tax_rate_and_code($self->taxzone, $info->{tax});
230
231     #     <ram:ApplicableTradeTax>
232     $params{xml}->startTag("ram:ApplicableTradeTax");
233     $params{xml}->dataElement("ram:CalculatedAmount",      _r2($params{ptc_data}->{taxes_by_tax_id}->{$info->{taxkey}->tax_id}));
234     $params{xml}->dataElement("ram:TypeCode",              "VAT");
235     $params{xml}->dataElement("ram:BasisAmount",           _r2($info->{linetotal}));
236     $params{xml}->dataElement("ram:CategoryCode",          $tax_info{code});
237     $params{xml}->dataElement("ram:RateApplicablePercent", _r2($tax_info{rate}));
238     $params{xml}->endTag;
239     #     </ram:ApplicableTradeTax>
240   }
241 }
242
243 sub _calculate_payment_terms_values {
244   my ($self) = @_;
245
246   my (%vars, %amounts, %formatted_amounts);
247
248   local $::myconfig{numberformat} = $::myconfig{numberformat};
249   local $::myconfig{dateformat}   = $::myconfig{dateformat};
250
251   if ($self->language_id) {
252     my $language = SL::DB::Language->load_cached($self->language_id);
253     $::myconfig{dateformat}   = $language->output_dateformat   if $language->output_dateformat;
254     $::myconfig{numberformat} = $language->output_numberformat if $language->output_numberformat;
255   }
256
257   $vars{currency}              = $self->currency->name if $self->currency;
258   $vars{$_}                    = $self->customer->$_      for qw(account_number bank bank_code bic iban mandate_date_of_signature mandator_id);
259   $vars{$_}                    = $self->payment_terms->$_ for qw(terms_netto terms_skonto percent_skonto);
260   $vars{payment_description}   = $self->payment_terms->description;
261   $vars{netto_date}            = $self->payment_terms->calc_date(reference_date => $self->transdate, due_date => $self->duedate, terms => 'net')->to_kivitendo;
262   $vars{skonto_date}           = $self->payment_terms->calc_date(reference_date => $self->transdate, due_date => $self->duedate, terms => 'discount')->to_kivitendo;
263
264   $amounts{invtotal}           = $self->amount;
265   $amounts{total}              = $self->amount - $self->paid;
266
267   $amounts{skonto_in_percent}  = 100.0 * $vars{percent_skonto};
268   $amounts{skonto_amount}      = $amounts{invtotal} * $vars{percent_skonto};
269   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $vars{percent_skonto});
270   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $vars{percent_skonto});
271
272   foreach (keys %amounts) {
273     $amounts{$_}           = $::form->round_amount($amounts{$_}, 2);
274     $formatted_amounts{$_} = $::form->format_amount(\%::myconfig, $amounts{$_}, 2);
275   }
276
277   return (
278     vars              => \%vars,
279     amounts           => \%amounts,
280     formatted_amounts => \%formatted_amounts,
281   );
282 }
283
284 sub _format_payment_terms_description {
285   my ($self, %params) = @_;
286
287   my $description = ($self->payment_terms->translated_attribute('description_long_invoice', $self->language_id) // '') || $self->payment_terms->description_long_invoice;
288   $description    =~ s{<\%$_\%>}{ $params{vars}->{$_} }ge              for keys %{ $params{vars} };
289   $description    =~ s{<\%$_\%>}{ $params{formatted_amounts}->{$_} }ge for keys %{ $params{formatted_amounts} };
290
291   return $description;
292 }
293
294 sub _payment_terms {
295   my ($self, %params) = @_;
296
297   return unless $self->payment_terms;
298
299   my %payment_terms_vars = _calculate_payment_terms_values($self);
300
301   #     <ram:SpecifiedTradePaymentTerms>
302   $params{xml}->startTag("ram:SpecifiedTradePaymentTerms");
303
304   $params{xml}->dataElement("ram:Description", _u8(_format_payment_terms_description($self, %payment_terms_vars)));
305
306   #       <ram:DueDateDateTime>
307   $params{xml}->startTag("ram:DueDateDateTime");
308   $params{xml}->dataElement("udt:DateTimeString", $self->duedate->strftime('%Y%m%d'), format => "102");
309   $params{xml}->endTag;
310   #       </ram:DueDateDateTime>
311
312   if ($self->payment_terms->percent_skonto && $self->payment_terms->terms_skonto) {
313     my $currency_id = _u8(SL::Helper::ISO4217::map_currency_name_to_code($self->currency->name) // 'EUR');
314
315     #       <ram:ApplicableTradePaymentDiscountTerms>
316     $params{xml}->startTag("ram:ApplicableTradePaymentDiscountTerms");
317     $params{xml}->dataElement("ram:BasisPeriodMeasure", $self->payment_terms->terms_skonto, unitCode => "DAY");
318     $params{xml}->dataElement("ram:BasisAmount",        _r2($payment_terms_vars{amounts}->{invtotal}), currencyID => $currency_id);
319     $params{xml}->dataElement("ram:CalculationPercent", _r2($self->payment_terms->percent_skonto * 100));
320     $params{xml}->endTag;
321     #       </ram:ApplicableTradePaymentDiscountTerms>
322   }
323
324   $params{xml}->endTag;
325   #     </ram:SpecifiedTradePaymentTerms>
326 }
327
328 sub _totals {
329   my ($self, %params) = @_;
330
331   #     <ram:SpecifiedTradeSettlementHeaderMonetarySummation>
332   $params{xml}->startTag("ram:SpecifiedTradeSettlementHeaderMonetarySummation");
333
334   $params{xml}->dataElement("ram:LineTotalAmount",     _r2($self->netamount));
335   $params{xml}->dataElement("ram:TaxBasisTotalAmount", _r2($self->netamount));
336   $params{xml}->dataElement("ram:TaxTotalAmount",      _r2(sum(values %{ $params{ptc_data}->{taxes_by_tax_id} })), currencyID => "EUR");
337   $params{xml}->dataElement("ram:GrandTotalAmount",    _r2($self->amount));
338   $params{xml}->dataElement("ram:TotalPrepaidAmount",  _r2($self->paid));
339   $params{xml}->dataElement("ram:DuePayableAmount",    _r2($self->amount - $self->paid));
340
341   $params{xml}->endTag;
342   #     </ram:SpecifiedTradeSettlementHeaderMonetarySummation>
343 }
344
345 sub _exchanged_document_context {
346   my ($self, %params) = @_;
347
348   #   <rsm:ExchangedDocumentContext>
349   $params{xml}->startTag("rsm:ExchangedDocumentContext");
350
351   if ($self->{_zugferd}->{test_mode}) {
352     $params{xml}->startTag("ram:TestIndicator");
353     $params{xml}->dataElement("udt:Indicator", "true");
354     $params{xml}->endTag;
355   }
356
357   $params{xml}->startTag("ram:GuidelineSpecifiedDocumentContextParameter");
358   $params{xml}->dataElement("ram:ID", $standards_ids{ $self->{_zugferd}->{profile} });
359   $params{xml}->endTag;
360   $params{xml}->endTag;
361   #   </rsm:ExchangedDocumentContext>
362 }
363
364 sub _included_note {
365   my ($self, %params) = @_;
366
367   $params{xml}->startTag("ram:IncludedNote");
368   $params{xml}->dataElement("ram:Content", _u8($params{note}));
369   $params{xml}->endTag;
370 }
371
372 sub _exchanged_document {
373   my ($self, %params) = @_;
374
375   #   <rsm:ExchangedDocument>
376   $params{xml}->startTag("rsm:ExchangedDocument");
377
378   $params{xml}->dataElement("ram:ID",       _u8($self->invnumber));
379   $params{xml}->dataElement("ram:Name",     _u8(_type_name($self)));
380   $params{xml}->dataElement("ram:TypeCode", _u8(_type_code($self)));
381
382   #     <ram:IssueDateTime>
383   $params{xml}->startTag("ram:IssueDateTime");
384   $params{xml}->dataElement("udt:DateTimeString", $self->transdate->strftime('%Y%m%d'), format => "102");
385   $params{xml}->endTag;
386   #     </ram:IssueDateTime>
387
388   if ($self->language && (($self->language->template_code // '') =~ m{^(de|en)}i)) {
389     $params{xml}->dataElement("ram:LanguageID", uc($1));
390   }
391
392   my $std_notes = SL::DB::Manager::GenericTranslation->get_all(
393     where => [
394       translation_type => 'ZUGFeRD/notes',
395       or               => [
396         language_id    => undef,
397         language_id    => $self->language_id,
398       ],
399       '!translation'   => undef,
400       '!translation'   => '',
401     ],
402   );
403
404   my $std_note = first { $_->language_id == $self->language_id } @{ $std_notes };
405   $std_note  //= first { !defined $_->language_id }              @{ $std_notes };
406
407   my $notes = $self->notes_as_stripped_html;
408
409   _included_note($self, %params, note => $self->transaction_description) if $self->transaction_description;
410   _included_note($self, %params, note => $notes)                         if $notes;
411   _included_note($self, %params, note => $std_note->translation)         if $std_note;
412
413   $params{xml}->endTag;
414   #   </rsm:ExchangedDocument>
415 }
416
417 sub _specified_tax_registration {
418   my ($ustid_nr, %params) = @_;
419
420   #         <ram:SpecifiedTaxRegistration>
421   $params{xml}->startTag("ram:SpecifiedTaxRegistration");
422   $params{xml}->dataElement("ram:ID", _u8(SL::VATIDNr->normalize($ustid_nr)), schemeID => "VA");
423   $params{xml}->endTag;
424   #         </ram:SpecifiedTaxRegistration>
425 }
426
427 sub _seller_trade_party {
428   my ($self, %params) = @_;
429
430   my @our_address            = _parse_our_address();
431
432   my $sales_person           = $self->salesman;
433   my $sales_person_auth      = SL::DB::Manager::AuthUser->find_by(login => $sales_person->login);
434   my %sales_person_cfg       = $sales_person_auth ? %{ $sales_person_auth->config_values } : ();
435   $sales_person_cfg{email} ||= $sales_person->deleted_email;
436   $sales_person_cfg{tel}   ||= $sales_person->deleted_tel;
437
438   #       <ram:SellerTradeParty>
439   $params{xml}->startTag("ram:SellerTradeParty");
440   $params{xml}->dataElement("ram:ID",   _u8($self->customer->c_vendor_id)) if ($self->customer->c_vendor_id // '') ne '';
441   $params{xml}->dataElement("ram:Name", _u8($::instance_conf->get_company));
442
443   #         <ram:DefinedTradeContact>
444   $params{xml}->startTag("ram:DefinedTradeContact");
445
446   $params{xml}->dataElement("ram:PersonName", _u8($sales_person->safe_name));
447
448   if ($sales_person_cfg{tel}) {
449     $params{xml}->startTag("ram:TelephoneUniversalCommunication");
450     $params{xml}->dataElement("ram:CompleteNumber", _u8($sales_person_cfg{tel}));
451     $params{xml}->endTag;
452   }
453
454   if ($sales_person_cfg{email}) {
455     $params{xml}->startTag("ram:EmailURIUniversalCommunication");
456     $params{xml}->dataElement("ram:URIID", _u8($sales_person_cfg{email}));
457     $params{xml}->endTag;
458   }
459
460   $params{xml}->endTag;
461   #         </ram:DefinedTradeContact>
462
463   if (@our_address) {
464     #         <ram:PostalTradeAddress>
465     $params{xml}->startTag("ram:PostalTradeAddress");
466     foreach my $element (@our_address) {
467       $params{xml}->dataElement("ram:" . $element->[0], _u8($element->[1]));
468     }
469     $params{xml}->endTag;
470     #         </ram:PostalTradeAddress>
471   }
472
473   _specified_tax_registration($::instance_conf->get_co_ustid, %params);
474
475   $params{xml}->endTag;
476   #     </ram:SellerTradeParty>
477 }
478
479 sub _buyer_trade_party {
480   my ($self, %params) = @_;
481
482   #       <ram:BuyerTradeParty>
483   $params{xml}->startTag("ram:BuyerTradeParty");
484   $params{xml}->dataElement("ram:ID",   _u8($self->customer->customernumber));
485   $params{xml}->dataElement("ram:Name", _u8($self->customer->name));
486
487   _customer_postal_trade_address(%params, customer => $self->customer);
488   _specified_tax_registration($self->customer->ustid, %params) if $self->customer->ustid;
489
490   $params{xml}->endTag;
491   #       </ram:BuyerTradeParty>
492 }
493
494 sub _included_supply_chain_trade_line_item {
495   my ($self, %params) = @_;
496
497   my $line_number = 0;
498   foreach my $item (@{ $self->items }) {
499     _line_item($self, %params, item => $item, line_number => $line_number);
500     $line_number++;
501   }
502 }
503
504 sub _applicable_header_trade_agreement {
505   my ($self, %params) = @_;
506
507   #     <ram:ApplicableHeaderTradeAgreement>
508   $params{xml}->startTag("ram:ApplicableHeaderTradeAgreement");
509
510   _seller_trade_party($self, %params);
511   _buyer_trade_party($self, %params);
512
513   if ($self->cusordnumber) {
514     #     <ram:BuyerOrderReferencedDocument>
515     $params{xml}->startTag("ram:BuyerOrderReferencedDocument");
516     $params{xml}->dataElement("ram:IssuerAssignedID", _u8($self->cusordnumber));
517     $params{xml}->endTag;
518     #     </ram:BuyerOrderReferencedDocument>
519   }
520
521   $params{xml}->endTag;
522   #     </ram:ApplicableHeaderTradeAgreement>
523 }
524
525 sub _applicable_header_trade_delivery {
526   my ($self, %params) = @_;
527
528   #     <ram:ApplicableHeaderTradeDelivery>
529   $params{xml}->startTag("ram:ApplicableHeaderTradeDelivery");
530   #       <ram:ActualDeliverySupplyChainEvent>
531   $params{xml}->startTag("ram:ActualDeliverySupplyChainEvent");
532
533   $params{xml}->startTag("ram:OccurrenceDateTime");
534   $params{xml}->dataElement("udt:DateTimeString", ($self->deliverydate // $self->transdate)->strftime('%Y%m%d'), format => "102");
535   $params{xml}->endTag;
536
537   $params{xml}->endTag;
538   #       </ram:ActualDeliverySupplyChainEvent>
539   $params{xml}->endTag;
540   #     </ram:ApplicableHeaderTradeDelivery>
541 }
542
543 sub _applicable_header_trade_settlement {
544   my ($self, %params) = @_;
545
546   #     <ram:ApplicableHeaderTradeSettlement>
547   $params{xml}->startTag("ram:ApplicableHeaderTradeSettlement");
548   $params{xml}->dataElement("ram:InvoiceCurrencyCode", _u8(SL::Helper::ISO4217::map_currency_name_to_code($self->currency->name) // 'EUR'));
549
550   _specified_trade_settlement_payment_means($self, %params);
551   _taxes($self, %params);
552   _payment_terms($self, %params);
553   _totals($self, %params);
554
555   $params{xml}->endTag;
556   #     </ram:ApplicableHeaderTradeSettlement>
557 }
558
559 sub _supply_chain_trade_transaction {
560   my ($self, %params) = @_;
561
562   #   <rsm:SupplyChainTradeTransaction>
563   $params{xml}->startTag("rsm:SupplyChainTradeTransaction");
564
565   _included_supply_chain_trade_line_item($self, %params);
566   _applicable_header_trade_agreement($self, %params);
567   _applicable_header_trade_delivery($self, %params);
568   _applicable_header_trade_settlement($self, %params);
569
570   $params{xml}->endTag;
571   #   </rsm:SupplyChainTradeTransaction>
572 }
573
574 sub _validate_data {
575   my ($self) = @_;
576
577   my %result;
578   my $prefix = $::locale->text('The ZUGFeRD invoice data cannot be generated because the data validation failed.') . ' ';
579
580   if (!$::instance_conf->get_co_ustid) {
581     SL::X::ZUGFeRDValidation->throw(message => $prefix . $::locale->text('The VAT registration number is missing in the client configuration.'));
582   }
583
584   if (!SL::VATIDNr->validate($::instance_conf->get_co_ustid)) {
585     SL::X::ZUGFeRDValidation->throw(message => $prefix . $::locale->text("The VAT ID number in the client configuration is invalid."));
586   }
587
588   if (!$::instance_conf->get_company || any { my $get = "get_address_$_"; !$::instance_conf->$get } qw(street1 zipcode city)) {
589     SL::X::ZUGFeRDValidation->throw(message => $prefix . $::locale->text('The company\'s address information is incomplete in the client configuration.'));
590   }
591
592   if ($::instance_conf->get_address_country && !SL::Helper::ISO3166::map_name_to_alpha_2_code($::instance_conf->get_address_country)) {
593     SL::X::ZUGFeRDValidation->throw(message => $prefix . $::locale->text('The country from the company\'s address in the client configuration cannot be mapped to an ISO 3166-1 alpha 2 code.'));
594   }
595
596   if ($self->customer->country && !SL::Helper::ISO3166::map_name_to_alpha_2_code($self->customer->country)) {
597     SL::X::ZUGFeRDValidation->throw(message => $prefix . $::locale->text('The country from the customer\'s address cannot be mapped to an ISO 3166-1 alpha 2 code.'));
598   }
599
600   if (!SL::Helper::ISO4217::map_currency_name_to_code($self->currency->name)) {
601     SL::X::ZUGFeRDValidation->throw(message => $prefix . $::locale->text('The currency "#1" cannot be mapped to an ISO 4217 currency code.', $self->currency->name));
602   }
603
604   my $failed_unit = first { !SL::Helper::UNECERecommendation20::map_name_to_code($_) } map { $_->unit } @{ $self->items };
605   if ($failed_unit) {
606     SL::X::ZUGFeRDValidation->throw(message => $prefix . $::locale->text('One of the units used (#1) cannot be mapped to a known unit code from the UN/ECE Recommendation 20 list.', $failed_unit));
607   }
608
609   if ($self->direct_debit) {
610     if (!$self->customer->iban) {
611       SL::X::ZUGFeRDValidation->throw(message => $prefix . $::locale->text('The customer\'s bank account number (IBAN) is missing.'));
612     }
613
614   } else {
615     my $bank_accounts     = SL::DB::Manager::BankAccount->get_all;
616     $result{bank_account} = scalar(@{ $bank_accounts }) == 1 ? $bank_accounts->[0] : first { $_->use_for_zugferd } @{ $bank_accounts };
617
618     if (!$result{bank_account}) {
619       SL::X::ZUGFeRDValidation->throw(message => $prefix . $::locale->text('No bank account flagged for Factur-X/ZUGFeRD usage was found.'));
620     }
621   }
622
623   return %result;
624 }
625
626 sub create_zugferd_data {
627   my ($self)        = @_;
628   $self->{_zugferd} = { SL::ZUGFeRD->convert_customer_setting($self->customer->create_zugferd_invoices_for_this_customer) };
629
630   if (!$standards_ids{ $self->{_zugferd}->{profile} }) {
631     croak "Profile '" . $self->{_zugferd}->{profile} . "' is not supported";
632   }
633
634   my $output        = '';
635
636   my %params        = _validate_data($self);
637   $params{ptc_data} = { $self->calculate_prices_and_taxes };
638   $params{xml}      = XML::Writer->new(
639     OUTPUT          => \$output,
640     DATA_MODE       => 1,
641     DATA_INDENT     => 2,
642     ENCODING        => 'utf-8',
643   );
644
645   $params{xml}->xmlDecl();
646
647   # <rsm:CrossIndustryInvoice>
648   $params{xml}->startTag("rsm:CrossIndustryInvoice",
649                          "xmlns:a"   => "urn:un:unece:uncefact:data:standard:QualifiedDataType:100",
650                          "xmlns:rsm" => "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100",
651                          "xmlns:qdt" => "urn:un:unece:uncefact:data:standard:QualifiedDataType:10",
652                          "xmlns:ram" => "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100",
653                          "xmlns:xs"  => "http://www.w3.org/2001/XMLSchema",
654                          "xmlns:udt" => "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100");
655
656   _exchanged_document_context($self, %params);
657   _exchanged_document($self, %params);
658   _supply_chain_trade_transaction($self, %params);
659
660   $params{xml}->endTag;
661   # </rsm:CrossIndustryInvoice>
662
663   return $output;
664 }
665
666 sub create_zugferd_xmp_data {
667   my ($self) = @_;
668
669   return {
670     conformance_level  => 'EXTENDED',
671     document_file_name => 'factur-x.xml',
672     document_type      => 'INVOICE',
673     version            => '1.0',
674   };
675 }
676
677 1;