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