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