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