ac018e2580f4a9fe45430bcf291e600a93009310
[kivitendo-erp.git] / bin / mozilla / sepa.pl
1 use strict;
2
3 use List::MoreUtils qw(any none uniq);
4 use List::Util qw(sum first);
5 use POSIX qw(strftime);
6
7 use Data::Dumper;
8 use SL::DB::BankAccount;
9 use SL::Chart;
10 use SL::CT;
11 use SL::Form;
12 use SL::GenericTranslations;
13 use SL::ReportGenerator;
14 use SL::SEPA;
15 use SL::SEPA::XML;
16
17 require "bin/mozilla/common.pl";
18 require "bin/mozilla/reportgenerator.pl";
19
20 sub bank_transfer_add {
21   $main::lxdebug->enter_sub();
22
23   my $form          = $main::form;
24   my $locale        = $main::locale;
25   my $vc            = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
26
27   $form->{title}    = $vc eq 'customer' ? $::locale->text('Prepare bank collection via SEPA XML') : $locale->text('Prepare bank transfer via SEPA XML');
28
29   my $bank_accounts = SL::DB::Manager::BankAccount->get_all_sorted( query => [ obsolete => 0 ] );
30
31   if (!scalar @{ $bank_accounts }) {
32     $form->error($locale->text('You have not added bank accounts yet.'));
33   }
34
35   my $invoices = SL::SEPA->retrieve_open_invoices(vc => $vc);
36
37   if (!scalar @{ $invoices }) {
38     $form->show_generic_information($locale->text('Either there are no open invoices, or you have already initiated bank transfers ' .
39                                                   'with the open amounts for those that are still open.'));
40     $main::lxdebug->leave_sub();
41     return;
42   }
43
44   # Only include those per default that require manual action from our
45   # side. For sales invoices these are the ones for which direct debit
46   # has been selected. For purchase invoices it's the other way
47   # around: if direct debit is active then the vendor will collect
48   # from us automatically and we don't have to send money manually.
49   $_->{checked} = ($vc eq 'customer' ? $_->{direct_debit} : !$_->{direct_debit}) for @{ $invoices };
50
51   my $translation_list = GenericTranslations->list(translation_type => 'sepa_remittance_info_pfx');
52   my %translations     = map { ( ($_->{language_id} || 'default') => $_->{translation} ) } @{ $translation_list };
53
54   foreach my $invoice (@{ $invoices }) {
55     my $prefix                    = $translations{ $invoice->{language_id} } || $translations{default} || $::locale->text('Invoice');
56     $prefix                      .= ' ' unless $prefix =~ m/ $/;
57     $invoice->{reference_prefix}  = $prefix;
58   }
59
60   $form->header();
61   print $form->parse_html_template('sepa/bank_transfer_add',
62                                    { 'INVOICES'           => $invoices,
63                                      'BANK_ACCOUNTS'      => $bank_accounts,
64                                      'vc'                 => $vc,
65                                    });
66
67   $main::lxdebug->leave_sub();
68 }
69
70 sub bank_transfer_create {
71   $main::lxdebug->enter_sub();
72
73   my $form          = $main::form;
74   my $locale        = $main::locale;
75   my $myconfig      = \%main::myconfig;
76   my $vc            = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
77
78   $form->{title}    = $vc eq 'customer' ? $::locale->text('Create bank collection via SEPA XML') : $locale->text('Create bank transfer via SEPA XML');
79
80   my $bank_accounts = SL::DB::Manager::BankAccount->get_all_sorted( query => [ obsolete => 0 ] );
81   if (!scalar @{ $bank_accounts }) {
82     $form->error($locale->text('You have not added bank accounts yet.'));
83   }
84
85   my $bank_account = SL::DB::Manager::BankAccount->find_by( id => $form->{bank_account} );
86
87   unless ( $bank_account ) {
88     $form->error($locale->text('The selected bank account does not exist anymore.'));
89   }
90
91   my $arap_id        = $vc eq 'customer' ? 'ar_id' : 'ap_id';
92   my $invoices       = SL::SEPA->retrieve_open_invoices(vc => $vc);
93
94   # load all open invoices (again), but grep out the ones that were selected with checkboxes beforehand ($_->selected). At this stage we again have all the invoice information, including dropdown with payment_type options
95   # all the information from retrieve_open_invoices is then ADDED to what was passed via @{ $form->{bank_transfers} }
96   # parse amount from the entry in the form, but take skonto_amount from PT again
97   # the map inserts the values of invoice_map directly into the array of hashes
98   my %invoices_map   = map { $_->{id} => $_ } @{ $invoices };
99   my @bank_transfers =
100     map  +{ %{ $invoices_map{ $_->{$arap_id} } }, %{ $_ } },
101     grep  { $_->{selected} && (0 < $_->{amount}) && $invoices_map{ $_->{$arap_id} } }
102     map   { $_->{amount} = $form->parse_amount($myconfig, $_->{amount}); $_ }
103           @{ $form->{bank_transfers} || [] };
104
105   # override default payment_type selection and set it to the one chosen by the user
106   # in the previous step, so that we don't need the logic in the template
107   foreach my $bt (@bank_transfers) {
108     foreach my $type ( @{$bt->{payment_select_options}} ) {
109       if ( $type->{payment_type} eq $bt->{payment_type} ) {
110         $type->{selected} = 1;
111       } else {
112         $type->{selected} = 0;
113       };
114     };
115   };
116
117   if (!scalar @bank_transfers) {
118     $form->error($locale->text('You have selected none of the invoices.'));
119   }
120
121   my $total_trans = sum map { $_->{open_amount} } @bank_transfers;
122
123   my ($vc_bank_info);
124   my $error_message;
125
126   my @bank_columns    = qw(iban bic);
127   push @bank_columns, qw(mandator_id mandate_date_of_signature) if $vc eq 'customer';
128
129   if ($form->{confirmation}) {
130     $vc_bank_info = { map { $_->{id} => $_ } @{ $form->{vc_bank_info} || [] } };
131
132     foreach my $info (values %{ $vc_bank_info }) {
133       if (any { !$info->{$_} } @bank_columns) {
134         $error_message = $locale->text('The bank information must not be empty.');
135         last;
136       }
137     }
138   }
139
140   if ($error_message || !$form->{confirmation}) {
141     my @vc_ids                 = uniq map { $_->{vc_id} } @bank_transfers;
142     $vc_bank_info            ||= CT->get_bank_info('vc' => $vc,
143                                                    'id' => \@vc_ids);
144     my @vc_bank_info           = sort { lc $a->{name} cmp lc $b->{name} } values %{ $vc_bank_info };
145
146     $form->header();
147     print $form->parse_html_template('sepa/bank_transfer_create',
148                                      { 'BANK_TRANSFERS'     => \@bank_transfers,
149                                        'BANK_ACCOUNTS'      => $bank_accounts,
150                                        'VC_BANK_INFO'       => \@vc_bank_info,
151                                        'bank_account'       => $bank_account,
152                                        'error_message'      => $error_message,
153                                        'vc'                 => $vc,
154                                        'total_trans'        => $total_trans,
155                                      });
156
157   } else {
158     foreach my $bank_transfer (@bank_transfers) {
159       foreach (@bank_columns) {
160         $bank_transfer->{"vc_${_}"}  = $vc_bank_info->{ $bank_transfer->{vc_id} }->{$_};
161         $bank_transfer->{"our_${_}"} = $bank_account->{$_};
162       }
163
164       $bank_transfer->{chart_id} = $bank_account->{chart_id};
165     }
166
167     my $id = SL::SEPA->create_export('employee'       => $::myconfig{login},
168                                      'bank_transfers' => \@bank_transfers,
169                                      'vc'             => $vc);
170
171     $form->header();
172     print $form->parse_html_template('sepa/bank_transfer_created', { 'id' => $id, 'vc' => $vc });
173   }
174
175   $main::lxdebug->leave_sub();
176 }
177
178 sub bank_transfer_search {
179   $main::lxdebug->enter_sub();
180
181   my $form   = $main::form;
182   my $locale = $main::locale;
183   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
184
185   $form->{title}    = $vc eq 'customer' ? $::locale->text('List of bank collections') : $locale->text('List of bank transfers');
186
187   $form->header();
188   print $form->parse_html_template('sepa/bank_transfer_search', { vc => $vc });
189
190   $main::lxdebug->leave_sub();
191 }
192
193
194 sub bank_transfer_list {
195   $main::lxdebug->enter_sub();
196
197   my $form   = $main::form;
198   my $locale = $main::locale;
199   my $cgi    = $::request->{cgi};
200   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
201
202   $form->{title}     = $vc eq 'customer' ? $::locale->text('List of bank collections') : $locale->text('List of bank transfers');
203
204   $form->{sort}    ||= 'id';
205   $form->{sortdir}   = '1' if (!defined $form->{sortdir});
206
207   $form->{callback}  = build_std_url('action=bank_transfer_list', 'sort', 'sortdir', 'vc');
208
209   my %filter         = map  +( $_ => $form->{"f_${_}"} ),
210                        grep  { $form->{"f_${_}"} }
211                              (qw(vc invnumber),
212                               map { ("${_}_date_from", "${_}_date_to") }
213                                   qw(export requested_execution execution));
214   $filter{executed}  = $form->{l_executed} ? 1 : 0 if ($form->{l_executed} != $form->{l_not_executed});
215   $filter{closed}    = $form->{l_closed}   ? 1 : 0 if ($form->{l_open}     != $form->{l_closed});
216
217   my $exports        = SL::SEPA->list_exports('filter'    => \%filter,
218                                               'sortorder' => $form->{sort},
219                                               'sortdir'   => $form->{sortdir},
220                                               'vc'        => $vc);
221
222   my $open_available = any { !$_->{closed} } @{ $exports };
223
224   my $report         = SL::ReportGenerator->new(\%main::myconfig, $form);
225
226   my @hidden_vars    = ('vc', grep { m/^[fl]_/ && $form->{$_} } keys %{ $form });
227
228   my $href           = build_std_url('action=bank_transfer_list', @hidden_vars);
229
230   my %column_defs = (
231     'selected'    => { 'text' => $cgi->checkbox(-name => 'select_all', -id => 'select_all', -label => ''), },
232     'id'          => { 'text' => $locale->text('Number'), },
233     'export_date' => { 'text' => $locale->text('Export date'), },
234     'employee'    => { 'text' => $locale->text('Employee'), },
235     'executed'    => { 'text' => $locale->text('Executed'), },
236     'closed'      => { 'text' => $locale->text('Closed'), },
237     num_invoices  => { 'text' => $locale->text('Number of invoices'), },
238     sum_amounts   => { 'text' => $locale->text('Sum of all amounts'), },
239   );
240
241   my @columns = qw(selected id export_date employee executed closed invoices netamount);
242   my %column_alignment = map { ($_ => 'right') } qw(num_invoices sum_amounts);
243
244   foreach my $name (qw(id export_date employee executed closed)) {
245     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
246     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
247   }
248
249   $column_defs{selected}->{visible} = $open_available                                ? 'HTML' : 0;
250   $column_defs{executed}->{visible} = $form->{l_executed} && $form->{l_not_executed} ? 1 : 0;
251   $column_defs{closed}->{visible}   = $form->{l_closed}   && $form->{l_open}         ? 1 : 0;
252   $column_defs{$_}->{align}         = $column_alignment{$_} for keys %column_alignment;
253
254   my @options = ();
255   push @options, ($vc eq 'customer' ? $::locale->text('Customer') : $locale->text('Vendor')) . ' : ' . $form->{f_vc} if ($form->{f_vc});
256   push @options, $locale->text('Invoice number')                . ' : ' . $form->{f_invnumber}                     if ($form->{f_invnumber});
257   push @options, $locale->text('Export date from')              . ' : ' . $form->{f_export_date_from}              if ($form->{f_export_date_from});
258   push @options, $locale->text('Export date to')                . ' : ' . $form->{f_export_date_to}                if ($form->{f_export_date_to});
259   push @options, $locale->text('Requested execution date from') . ' : ' . $form->{f_requested_execution_date_from} if ($form->{f_requested_execution_date_from});
260   push @options, $locale->text('Requested execution date to')   . ' : ' . $form->{f_requested_execution_date_to}   if ($form->{f_requested_execution_date_to});
261   push @options, $locale->text('Execution date from')           . ' : ' . $form->{f_execution_date_from}           if ($form->{f_execution_date_from});
262   push @options, $locale->text('Execution date to')             . ' : ' . $form->{f_execution_date_to}             if ($form->{f_execution_date_to});
263   push @options, $form->{l_executed} ? $locale->text('executed') : $locale->text('not yet executed')               if ($form->{l_executed} != $form->{l_not_executed});
264   push @options, $form->{l_closed}   ? $locale->text('closed')   : $locale->text('open')                           if ($form->{l_open}     != $form->{l_closed});
265
266   $report->set_options('top_info_text'         => join("\n", @options),
267                        'raw_top_info_text'     => $form->parse_html_template('sepa/bank_transfer_list_top'),
268                        'raw_bottom_info_text'  => $form->parse_html_template('sepa/bank_transfer_list_bottom', { 'show_buttons' => $open_available, vc => $vc }),
269                        'std_column_visibility' => 1,
270                        'output_format'         => 'HTML',
271                        'title'                 => $form->{title},
272                        'attachment_basename'   => $locale->text('banktransfers') . strftime('_%Y%m%d', localtime time),
273     );
274   $report->set_options_from_form();
275   $locale->set_numberformat_wo_thousands_separator(\%::myconfig) if lc($report->{options}->{output_format}) eq 'csv';
276
277   $report->set_columns(%column_defs);
278   $report->set_column_order(@columns);
279   $report->set_export_options('bank_transfer_list', @hidden_vars);
280   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
281
282   my $edit_url = build_std_url('action=bank_transfer_edit', 'callback');
283
284   foreach my $export (@{ $exports }) {
285     my $row = { map { $_ => { 'data' => $export->{$_}, 'align' => $column_alignment{$_} } } keys %{ $export } };
286
287     map { $row->{$_}->{data} = $export->{$_} ? $locale->text('yes') : $locale->text('no') } qw(executed closed);
288
289     $row->{id}->{link} = $edit_url . '&id=' . E($export->{id}) . '&vc=' . E($vc);
290
291     $row->{$_}->{data} = $::form->format_amount(\%::myconfig, $row->{$_}->{data}, 2) for qw(sum_amounts);
292
293     if (!$export->{closed}) {
294       $row->{selected}->{raw_data} =
295           $cgi->hidden(-name => "exports[+].id", -value => $export->{id})
296         . $cgi->checkbox(-name => "exports[].selected", -value => 1, -label => '');
297     }
298
299     $report->add_data($row);
300   }
301
302   $report->generate_with_headers();
303
304   $main::lxdebug->leave_sub();
305 }
306
307 sub bank_transfer_edit {
308   $main::lxdebug->enter_sub();
309
310   my $form   = $main::form;
311   my $locale = $main::locale;
312   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
313
314   my @ids    = ();
315   if (!$form->{mode} || ($form->{mode} eq 'single')) {
316     push @ids, $form->{id};
317   } else {
318     @ids = map $_->{id}, grep { $_->{selected} } @{ $form->{exports} || [] };
319
320     if (!@ids) {
321       $form->show_generic_error($locale->text('You have not selected any export.'), 'back_button' => 1);
322     }
323   }
324
325   my $export;
326
327   foreach my $id (@ids) {
328     my $curr_export = SL::SEPA->retrieve_export('id' => $id, 'details' => 1, 'vc' => $vc);
329
330     foreach my $item (@{ $curr_export->{items} }) {
331       map { $item->{"export_${_}"} = $curr_export->{$_} } grep { !ref $curr_export->{$_} } keys %{ $curr_export };
332     }
333
334     if (!$export) {
335       $export = $curr_export;
336     } else {
337       push @{ $export->{items} }, @{ $curr_export->{items} };
338     }
339   }
340
341   if ($form->{mode} && ($form->{mode} eq 'multi')) {
342     $export->{items} = [ grep { !$_->{export_closed} && !$_->{executed} } @{ $export->{items} } ];
343
344     if (!@{ $export->{items} }) {
345       $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'), 'back_button' => 1);
346     }
347
348   } elsif (!$export) {
349     $form->error($locale->text('That export does not exist.'));
350   }
351
352   $form->{title}    = $locale->text('View SEPA export');
353   $form->header();
354   print $form->parse_html_template('sepa/bank_transfer_edit',
355                                    { 'ids'                       => \@ids,
356                                      'export'                    => $export,
357                                      'current_date'              => $form->current_date(\%main::myconfig),
358                                      'show_post_payments_button' => any { !$_->{export_closed} && !$_->{executed} } @{ $export->{items} },
359                                    });
360
361   $main::lxdebug->leave_sub();
362 }
363
364 sub bank_transfer_post_payments {
365   $main::lxdebug->enter_sub();
366
367   my $form   = $main::form;
368   my $locale = $main::locale;
369   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
370
371   my @items  = grep { $_->{selected} } @{ $form->{items} || [] };
372
373   if (!@items) {
374     $form->show_generic_error($locale->text('You have not selected any item.'), 'back_button' => 1);
375   }
376   my @export_ids    = uniq map { $_->{sepa_export_id} } @items;
377   my %exports       = map { $_ => SL::SEPA->retrieve_export('id' => $_, 'details' => 1, vc => $vc) } @export_ids;
378   my @items_to_post = ();
379
380   foreach my $item (@items) {
381     my $export = $exports{ $item->{sepa_export_id} };
382     next if (!$export || $export->{closed} || $export->{executed});
383
384     push @items_to_post, $item if (none { ($_->{id} == $item->{id}) && $_->{executed} } @{ $export->{items} });
385   }
386
387   if (!@items_to_post) {
388     $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'), 'back_button' => 1);
389   }
390
391   if (any { !$_->{execution_date} } @items_to_post) {
392     $form->show_generic_error($locale->text('You have to specify an execution date for each antry.'), 'back_button' => 1);
393   }
394
395   SL::SEPA->post_payment('items' => \@items_to_post, vc => $vc);
396
397   $form->show_generic_information($locale->text('The payments have been posted.'));
398
399   $main::lxdebug->leave_sub();
400 }
401
402 sub bank_transfer_payment_list_as_pdf {
403   $main::lxdebug->enter_sub();
404
405   my $form       = $main::form;
406   my %myconfig   = %main::myconfig;
407   my $locale     = $main::locale;
408   my $vc         = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
409
410   my @ids        = @{ $form->{items} || [] };
411   my @export_ids = uniq map { $_->{export_id} } @ids;
412
413   $form->show_generic_error($locale->text('Multi mode not supported.'), 'back_button' => 1) if 1 != scalar @export_ids;
414
415   my $export = SL::SEPA->retrieve_export('id' => $export_ids[0], 'details' => 1, vc => $vc);
416   my @items  = ();
417
418   foreach my $id (@ids) {
419     my $item = first { $_->{id} == $id->{id} } @{ $export->{items} };
420     push @items, $item if $item;
421   }
422
423   $form->show_generic_error($locale->text('No transfers were executed in this export.'), 'back_button' => 1) if 1 > scalar @items;
424
425   my $report         =  SL::ReportGenerator->new(\%main::myconfig, $form);
426
427   my %column_defs    =  (
428     'invnumber'      => { 'text' => $locale->text('Invoice'),                                                                  },
429     'vc_name'        => { 'text' => $vc eq 'customer' ? $locale->text('Customer')         : $locale->text('Vendor'),           },
430     'our_iban'       => { 'text' => $vc eq 'customer' ? $locale->text('Destination IBAN') : $locale->text('Source IBAN'),      },
431     'our_bic'        => { 'text' => $vc eq 'customer' ? $locale->text('Destination BIC')  : $locale->text('Source BIC'),       },
432     'vc_iban'        => { 'text' => $vc eq 'customer' ? $locale->text('Source IBAN')      : $locale->text('Destination IBAN'), },
433     'vc_bic'         => { 'text' => $vc eq 'customer' ? $locale->text('Source BIC')       : $locale->text('Destination BIC'),  },
434     'amount'         => { 'text' => $locale->text('Amount'),                                                                   },
435     'reference'      => { 'text' => $locale->text('Reference'),                                                                },
436     'execution_date' => { 'text' => $locale->text('Execution date'),                                                           },
437   );
438
439   map { $column_defs{$_}->{align} = 'right' } qw(amount execution_date);
440
441   my @columns        =  qw(invnumber vc_name our_iban our_bic vc_iban vc_bic amount reference execution_date);
442
443   $report->set_options('std_column_visibility' => 1,
444                        'output_format'         => 'PDF',
445                        'title'                 =>  $vc eq 'customer' ? $locale->text('Bank collection payment list for export #1', $export->{id}) : $locale->text('Bank transfer payment list for export #1', $export->{id}),
446                        'attachment_basename'   => ($vc eq 'customer' ? $locale->text('bank_collection_payment_list_#1', $export->{id}) : $locale->text('bank_transfer_payment_list_#1', $export->{id})) . strftime('_%Y%m%d', localtime time),
447     );
448
449   $report->set_columns(%column_defs);
450   $report->set_column_order(@columns);
451
452   foreach my $item (@items) {
453     my $row                = { map { $_ => { 'data' => $item->{$_} } } @columns };
454     $row->{amount}->{data} = $form->format_amount(\%myconfig, $item->{amount}, 2);
455
456     $report->add_data($row);
457   }
458
459   $report->generate_with_headers();
460
461   $main::lxdebug->leave_sub();
462 }
463
464 # TODO
465 sub bank_transfer_download_sepa_xml {
466   $main::lxdebug->enter_sub();
467
468   my $form     =  $main::form;
469   my $myconfig = \%main::myconfig;
470   my $locale   =  $main::locale;
471   my $cgi      =  $::request->{cgi};
472   my $vc       = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
473   my $defaults = SL::DB::Default->get;
474
475   if (!$defaults->company) {
476     $form->show_generic_error($locale->text('You have to enter a company name in the client configuration.'), 'back_button' => 1);
477   }
478
479   if (($vc eq 'customer') && !$defaults->sepa_creditor_id) {
480     $form->show_generic_error($locale->text('You have to enter the SEPA creditor ID in the client configuration.'), 'back_button' => 1);
481   }
482
483   my @ids;
484   if ($form->{mode} && ($form->{mode} eq 'multi')) {
485      @ids = map $_->{id}, grep { $_->{selected} } @{ $form->{exports} || [] };
486
487   } else {
488     @ids = ($form->{id});
489   }
490
491   if (!@ids) {
492     $form->show_generic_error($locale->text('You have not selected any export.'), 'back_button' => 1);
493   }
494
495   my @items = ();
496
497   foreach my $id (@ids) {
498     my $export = SL::SEPA->retrieve_export('id' => $id, 'details' => 1, vc => $vc);
499     push @items, grep { !$_->{executed} } @{ $export->{items} } if ($export && !$export->{closed});
500   }
501
502   if (!@items) {
503     $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'), 'back_button' => 1);
504   }
505
506   my $message_id = strftime('MSG%Y%m%d%H%M%S', localtime) . sprintf('%06d', $$);
507
508   my $sepa_xml   = SL::SEPA::XML->new('company'     => $defaults->company,
509                                       'creditor_id' => $defaults->sepa_creditor_id,
510                                       'src_charset' => 'UTF-8',
511                                       'message_id'  => $message_id,
512                                       'grouped'     => 1,
513                                       'collection'  => $vc eq 'customer',
514     );
515
516   foreach my $item (@items) {
517     my $requested_execution_date;
518     my $mandator_id;
519     if ($item->{requested_execution_date}) {
520       my ($yy, $mm, $dd)        = $locale->parse_date($myconfig, $item->{requested_execution_date});
521       $requested_execution_date = sprintf '%04d-%02d-%02d', $yy, $mm, $dd;
522     }
523
524     if ($vc eq 'customer') {
525       my ($yy, $mm, $dd)      = $locale->parse_date($myconfig, $item->{reference_date});
526       $item->{reference_date} = sprintf '%04d-%02d-%02d', $yy, $mm, $dd;
527       $mandator_id = $item->{mandator_id};
528       if ($item->{mandate_date_of_signature}) {
529         ($yy, $mm, $dd)                    = $locale->parse_date($myconfig, $item->{mandate_date_of_signature});
530         $item->{mandate_date_of_signature} = sprintf '%04d-%02d-%02d', $yy, $mm, $dd;
531       }
532     }
533
534     $sepa_xml->add_transaction({ 'src_iban'       => $item->{our_iban},
535                                  'src_bic'        => $item->{our_bic},
536                                  'dst_iban'       => $item->{vc_iban},
537                                  'dst_bic'        => $item->{vc_bic},
538                                  'company'        => $item->{vc_name},
539                                  'company_number' => $item->{vc_number},
540                                  'amount'         => $item->{amount},
541                                  'reference'      => $item->{reference},
542                                  'mandator_id'    => $mandator_id,
543                                  'reference_date' => $item->{reference_date},
544                                  'execution_date' => $requested_execution_date,
545                                  'end_to_end_id'  => $item->{end_to_end_id},
546                                  'date_of_signature' => $item->{mandate_date_of_signature}, });
547   }
548
549   my $xml = $sepa_xml->to_xml();
550
551   print $cgi->header('-type'                => 'application/octet-stream',
552                      '-content-disposition' => 'attachment; filename="SEPA_' . $message_id . ($vc eq 'customer' ? '.cdd' : '.cct') . '"',
553                      '-content-length'      => length $xml);
554   print $xml;
555
556   $main::lxdebug->leave_sub();
557 }
558
559 sub bank_transfer_mark_as_closed_step1 {
560   $main::lxdebug->enter_sub();
561
562   my $form       = $main::form;
563   my $locale     = $main::locale;
564   my $vc         = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
565
566   my @export_ids = map { $_->{id} } grep { $_->{selected} } @{ $form->{exports} || [] };
567
568   if (!@export_ids) {
569     $form->show_generic_error($locale->text('You have not selected any export.'), 'back_button' => 1);
570   }
571
572   my @open_export_ids = ();
573   foreach my $id (@export_ids) {
574     my $export = SL::SEPA->retrieve_export('id' => $id, vc => $vc);
575     push @open_export_ids, $id if (!$export->{closed});
576   }
577
578   if (!@open_export_ids) {
579     $form->show_generic_error($locale->text('All of the exports you have selected were already closed.'), 'back_button' => 1);
580   }
581
582   $form->{title} = $locale->text('Close SEPA exports');
583   $form->header();
584   print $form->parse_html_template('sepa/bank_transfer_mark_as_closed_step1', { 'OPEN_EXPORT_IDS' => \@open_export_ids, vc => $vc });
585
586   $main::lxdebug->leave_sub();
587 }
588
589 sub bank_transfer_mark_as_closed_step2 {
590   $main::lxdebug->enter_sub();
591
592   my $form       = $main::form;
593   my $locale     = $main::locale;
594
595   map { SL::SEPA->close_export('id' => $_); } @{ $form->{open_export_ids} || [] };
596
597   $form->{title} = $locale->text('Close SEPA exports');
598   $form->header();
599   $form->show_generic_information($locale->text('The selected exports have been closed.'));
600
601   $main::lxdebug->leave_sub();
602 }
603
604 sub dispatcher {
605   my $form = $main::form;
606
607   foreach my $action (qw(bank_transfer_create bank_transfer_edit bank_transfer_list
608                          bank_transfer_post_payments bank_transfer_download_sepa_xml
609                          bank_transfer_mark_as_closed_step1 bank_transfer_mark_as_closed_step2
610                          bank_transfer_payment_list_as_pdf)) {
611     if ($form->{"action_${action}"}) {
612       call_sub($action);
613       return;
614     }
615   }
616
617   $form->error($main::locale->text('No action defined.'));
618 }
619
620 1;