ActionBar: Verwendung bei SEPA-Einzügen/-Ü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 SL::DB::BankAccount;
8 use SL::DB::SepaExport;
9 use SL::Chart;
10 use SL::CT;
11 use SL::Form;
12 use SL::GenericTranslations;
13 use SL::Locale::String qw(t8);
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   setup_sepa_add_transfer_action_bar();
70
71   $form->header();
72   print $form->parse_html_template('sepa/bank_transfer_add',
73                                    { 'INVOICES'           => $invoices,
74                                      'BANK_ACCOUNTS'      => $bank_accounts,
75                                      'vc'                 => $vc,
76                                    });
77
78   $main::lxdebug->leave_sub();
79 }
80
81 sub bank_transfer_create {
82   $main::lxdebug->enter_sub();
83
84   my $form          = $main::form;
85   my $locale        = $main::locale;
86   my $myconfig      = \%main::myconfig;
87   my $vc            = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
88
89   $form->{title}    = $vc eq 'customer' ? $::locale->text('Create bank collection via SEPA XML') : $locale->text('Create bank transfer via SEPA XML');
90
91   my $bank_accounts = SL::DB::Manager::BankAccount->get_all_sorted( query => [ obsolete => 0 ] );
92   if (!scalar @{ $bank_accounts }) {
93     $form->error($locale->text('You have not added bank accounts yet.'));
94   }
95
96   my $bank_account = SL::DB::Manager::BankAccount->find_by( id => $form->{bank_account} );
97
98   unless ( $bank_account ) {
99     $form->error($locale->text('The selected bank account does not exist anymore.'));
100   }
101
102   my $arap_id        = $vc eq 'customer' ? 'ar_id' : 'ap_id';
103   my $invoices       = SL::SEPA->retrieve_open_invoices(vc => $vc);
104
105   # 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
106   # all the information from retrieve_open_invoices is then ADDED to what was passed via @{ $form->{bank_transfers} }
107   # parse amount from the entry in the form, but take skonto_amount from PT again
108   # the map inserts the values of invoice_map directly into the array of hashes
109   my %selected_ids   = map { ($_ => 1) } @{ $form->{ids} || [] };
110   my %invoices_map   = map { $_->{id} => $_ } @{ $invoices };
111   my @bank_transfers =
112     map  +{ %{ $invoices_map{ $_->{$arap_id} } }, %{ $_ } },
113     grep  { ($_->{selected} || $selected_ids{$_->{$arap_id}}) && (0 < $_->{amount}) && $invoices_map{ $_->{$arap_id} } }
114     map   { $_->{amount} = $form->parse_amount($myconfig, $_->{amount}); $_ }
115           @{ $form->{bank_transfers} || [] };
116
117   # override default payment_type selection and set it to the one chosen by the user
118   # in the previous step, so that we don't need the logic in the template
119   foreach my $bt (@bank_transfers) {
120     foreach my $type ( @{$bt->{payment_select_options}} ) {
121       if ( $type->{payment_type} eq $bt->{payment_type} ) {
122         $type->{selected} = 1;
123       } else {
124         $type->{selected} = 0;
125       };
126     };
127   };
128
129   if (!scalar @bank_transfers) {
130     $form->error($locale->text('You have selected none of the invoices.'));
131   }
132
133   my $total_trans = sum map { $_->{open_amount} } @bank_transfers;
134
135   my ($vc_bank_info);
136   my $error_message;
137
138   my @bank_columns    = qw(iban bic);
139   push @bank_columns, qw(mandator_id mandate_date_of_signature) if $vc eq 'customer';
140
141   if ($form->{confirmation}) {
142     $vc_bank_info = { map { $_->{id} => $_ } @{ $form->{vc_bank_info} || [] } };
143
144     foreach my $info (values %{ $vc_bank_info }) {
145       if (any { !$info->{$_} } @bank_columns) {
146         $error_message = $locale->text('The bank information must not be empty.');
147         last;
148       }
149     }
150   }
151
152   if ($error_message || !$form->{confirmation}) {
153     my @vc_ids                 = uniq map { $_->{vc_id} } @bank_transfers;
154     $vc_bank_info            ||= CT->get_bank_info('vc' => $vc,
155                                                    'id' => \@vc_ids);
156     my @vc_bank_info           = sort { lc $a->{name} cmp lc $b->{name} } values %{ $vc_bank_info };
157
158     setup_sepa_create_transfer_action_bar(is_vendor => $vc eq 'vendor');
159
160     $form->header();
161     print $form->parse_html_template('sepa/bank_transfer_create',
162                                      { 'BANK_TRANSFERS'     => \@bank_transfers,
163                                        'BANK_ACCOUNTS'      => $bank_accounts,
164                                        'VC_BANK_INFO'       => \@vc_bank_info,
165                                        'bank_account'       => $bank_account,
166                                        'error_message'      => $error_message,
167                                        'vc'                 => $vc,
168                                        'total_trans'        => $total_trans,
169                                      });
170
171   } else {
172     foreach my $bank_transfer (@bank_transfers) {
173       foreach (@bank_columns) {
174         $bank_transfer->{"vc_${_}"}  = $vc_bank_info->{ $bank_transfer->{vc_id} }->{$_};
175         $bank_transfer->{"our_${_}"} = $bank_account->{$_};
176       }
177
178       $bank_transfer->{chart_id} = $bank_account->{chart_id};
179     }
180
181     my $id = SL::SEPA->create_export('employee'       => $::myconfig{login},
182                                      'bank_transfers' => \@bank_transfers,
183                                      'vc'             => $vc);
184
185     $form->header();
186     print $form->parse_html_template('sepa/bank_transfer_created', { 'id' => $id, 'vc' => $vc });
187   }
188
189   $main::lxdebug->leave_sub();
190 }
191
192 sub bank_transfer_search {
193   $main::lxdebug->enter_sub();
194
195   my $form   = $main::form;
196   my $locale = $main::locale;
197   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
198
199   $form->{title}    = $vc eq 'customer' ? $::locale->text('List of bank collections') : $locale->text('List of bank transfers');
200
201   setup_sepa_search_transfer_action_bar();
202
203   $form->header();
204   print $form->parse_html_template('sepa/bank_transfer_search', { vc => $vc });
205
206   $main::lxdebug->leave_sub();
207 }
208
209
210 sub bank_transfer_list {
211   $main::lxdebug->enter_sub();
212
213   my $form   = $main::form;
214   my $locale = $main::locale;
215   my $cgi    = $::request->{cgi};
216   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
217
218   $form->{title}     = $vc eq 'customer' ? $::locale->text('List of bank collections') : $locale->text('List of bank transfers');
219
220   $form->{sort}    ||= 'id';
221   $form->{sortdir}   = '1' if (!defined $form->{sortdir});
222
223   $form->{callback}  = build_std_url('action=bank_transfer_list', 'sort', 'sortdir', 'vc');
224
225   my %filter         = map  +( $_ => $form->{"f_${_}"} ),
226                        grep  { $form->{"f_${_}"} }
227                              (qw(vc invnumber message_id),
228                               map { ("${_}_date_from", "${_}_date_to") }
229                                   qw(export requested_execution execution));
230   $filter{executed}  = $form->{l_executed} ? 1 : 0 if ($form->{l_executed} != $form->{l_not_executed});
231   $filter{closed}    = $form->{l_closed}   ? 1 : 0 if ($form->{l_open}     != $form->{l_closed});
232
233   my $exports        = SL::SEPA->list_exports('filter'    => \%filter,
234                                               'sortorder' => $form->{sort},
235                                               'sortdir'   => $form->{sortdir},
236                                               'vc'        => $vc);
237
238   my $open_available = any { !$_->{closed} } @{ $exports };
239
240   my $report         = SL::ReportGenerator->new(\%main::myconfig, $form);
241
242   my @hidden_vars    = ('vc', grep { m/^[fl]_/ && $form->{$_} } keys %{ $form });
243
244   my $href           = build_std_url('action=bank_transfer_list', @hidden_vars);
245
246   my %column_defs = (
247     'selected'    => { 'text' => $cgi->checkbox(-name => 'select_all', -id => 'select_all', -label => ''), },
248     'id'          => { 'text' => $locale->text('Number'), },
249     'export_date' => { 'text' => $locale->text('Export date'), },
250     'employee'    => { 'text' => $locale->text('Employee'), },
251     'executed'    => { 'text' => $locale->text('Executed'), },
252     'closed'      => { 'text' => $locale->text('Closed'), },
253     num_invoices  => { 'text' => $locale->text('Number of invoices'), },
254     sum_amounts   => { 'text' => $locale->text('Sum of all amounts'), },
255     message_ids   => { 'text' => $locale->text('SEPA message IDs'), },
256   );
257
258   my @columns = qw(selected id export_date employee executed closed num_invoices sum_amounts message_ids);
259   my %column_alignment = map { ($_ => 'right') } qw(num_invoices sum_amounts);
260
261   foreach my $name (qw(id export_date employee executed closed)) {
262     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
263     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
264   }
265
266   $column_defs{selected}->{visible} = $open_available                                ? 'HTML' : 0;
267   $column_defs{executed}->{visible} = $form->{l_executed} && $form->{l_not_executed} ? 1 : 0;
268   $column_defs{closed}->{visible}   = $form->{l_closed}   && $form->{l_open}         ? 1 : 0;
269   $column_defs{$_}->{align}         = $column_alignment{$_} for keys %column_alignment;
270
271   my @options = ();
272   push @options, ($vc eq 'customer' ? $::locale->text('Customer') : $locale->text('Vendor')) . ' : ' . $form->{f_vc} if ($form->{f_vc});
273   push @options, $locale->text('Invoice number')                . ' : ' . $form->{f_invnumber}                     if ($form->{f_invnumber});
274   push @options, $locale->text('SEPA message ID')               . ' : ' . $form->{f_message_id}                    if (length $form->{f_message_id});
275   push @options, $locale->text('Export date from')              . ' : ' . $form->{f_export_date_from}              if ($form->{f_export_date_from});
276   push @options, $locale->text('Export date to')                . ' : ' . $form->{f_export_date_to}                if ($form->{f_export_date_to});
277   push @options, $locale->text('Requested execution date from') . ' : ' . $form->{f_requested_execution_date_from} if ($form->{f_requested_execution_date_from});
278   push @options, $locale->text('Requested execution date to')   . ' : ' . $form->{f_requested_execution_date_to}   if ($form->{f_requested_execution_date_to});
279   push @options, $locale->text('Execution date from')           . ' : ' . $form->{f_execution_date_from}           if ($form->{f_execution_date_from});
280   push @options, $locale->text('Execution date to')             . ' : ' . $form->{f_execution_date_to}             if ($form->{f_execution_date_to});
281   push @options, $form->{l_executed} ? $locale->text('executed') : $locale->text('not yet executed')               if ($form->{l_executed} != $form->{l_not_executed});
282   push @options, $form->{l_closed}   ? $locale->text('closed')   : $locale->text('open')                           if ($form->{l_open}     != $form->{l_closed});
283
284   $report->set_options('top_info_text'         => join("\n", @options),
285                        'raw_top_info_text'     => $form->parse_html_template('sepa/bank_transfer_list_top'),
286                        'raw_bottom_info_text'  => $form->parse_html_template('sepa/bank_transfer_list_bottom', { 'show_buttons' => $open_available, vc => $vc }),
287                        'std_column_visibility' => 1,
288                        'output_format'         => 'HTML',
289                        'title'                 => $form->{title},
290                        'attachment_basename'   => $locale->text('banktransfers') . strftime('_%Y%m%d', localtime time),
291     );
292   $report->set_options_from_form();
293   $locale->set_numberformat_wo_thousands_separator(\%::myconfig) if lc($report->{options}->{output_format}) eq 'csv';
294
295   $report->set_columns(%column_defs);
296   $report->set_column_order(@columns);
297   $report->set_export_options('bank_transfer_list', @hidden_vars);
298   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
299
300   my $edit_url = build_std_url('action=bank_transfer_edit', 'callback');
301
302   foreach my $export (@{ $exports }) {
303     my $row = { map { $_ => { 'data' => $export->{$_}, 'align' => $column_alignment{$_} } } keys %{ $export } };
304
305     map { $row->{$_}->{data} = $export->{$_} ? $locale->text('yes') : $locale->text('no') } qw(executed closed);
306
307     $row->{id}->{link} = $edit_url . '&id=' . E($export->{id}) . '&vc=' . E($vc);
308
309     $row->{$_}->{data} = $::form->format_amount(\%::myconfig, $row->{$_}->{data}, 2) for qw(sum_amounts);
310
311     if (!$export->{closed}) {
312       $row->{selected}->{raw_data} = $cgi->checkbox(-name => "ids[]", -value => $export->{id}, -label => '');
313     }
314
315     $report->add_data($row);
316   }
317
318   setup_sepa_list_transfers_action_bar(show_buttons => $open_available, is_vendor => $vc eq 'vendor');
319
320   $report->generate_with_headers();
321
322   $main::lxdebug->leave_sub();
323 }
324
325 sub bank_transfer_edit {
326   $main::lxdebug->enter_sub();
327
328   my $form   = $main::form;
329   my $locale = $main::locale;
330   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
331
332   my @ids    = ();
333   if (!$form->{mode} || ($form->{mode} eq 'single')) {
334     push @ids, $form->{id};
335   } else {
336     @ids = @{ $form->{ids} || [] };
337
338     if (!@ids) {
339       $form->show_generic_error($locale->text('You have not selected any export.'));
340     }
341   }
342
343   my $export;
344
345   foreach my $id (@ids) {
346     my $curr_export = SL::SEPA->retrieve_export('id' => $id, 'details' => 1, 'vc' => $vc);
347
348     foreach my $item (@{ $curr_export->{items} }) {
349       map { $item->{"export_${_}"} = $curr_export->{$_} } grep { !ref $curr_export->{$_} } keys %{ $curr_export };
350     }
351
352     if (!$export) {
353       $export = $curr_export;
354     } else {
355       push @{ $export->{items} }, @{ $curr_export->{items} };
356     }
357   }
358
359   if ($form->{mode} && ($form->{mode} eq 'multi')) {
360     $export->{items} = [ grep { !$_->{export_closed} && !$_->{executed} } @{ $export->{items} } ];
361
362     if (!@{ $export->{items} }) {
363       $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'));
364     }
365
366   } elsif (!$export) {
367     $form->error($locale->text('That export does not exist.'));
368   }
369
370   my $show_post_payments_button = any { !$_->{export_closed} && !$_->{executed} } @{ $export->{items} };
371   my $has_executed              = any { $_->{executed}                          } @{ $export->{items} };
372
373   setup_sepa_edit_transfer_action_bar(
374     show_post_payments_button => $show_post_payments_button,
375     has_executed              => $has_executed,
376   );
377
378   $form->{title}    = $locale->text('View SEPA export');
379   $form->header();
380   print $form->parse_html_template('sepa/bank_transfer_edit',
381                                    { ids                       => \@ids,
382                                      export                    => $export,
383                                      current_date              => $form->current_date(\%main::myconfig),
384                                      show_post_payments_button => $show_post_payments_button,
385                                    });
386
387   $main::lxdebug->leave_sub();
388 }
389
390 sub bank_transfer_post_payments {
391   $main::lxdebug->enter_sub();
392
393   my $form   = $main::form;
394   my $locale = $main::locale;
395   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
396
397   my %selected = map { ($_ => 1) } @{ $form->{ids} || [] };
398   my @items    = grep { $selected{$_->{id}} } @{ $form->{items} || [] };
399
400   if (!@items) {
401     $form->show_generic_error($locale->text('You have not selected any item.'));
402   }
403   my @export_ids    = uniq map { $_->{sepa_export_id} } @items;
404   my %exports       = map { $_ => SL::SEPA->retrieve_export('id' => $_, 'details' => 1, vc => $vc) } @export_ids;
405   my @items_to_post = ();
406
407   foreach my $item (@items) {
408     my $export = $exports{ $item->{sepa_export_id} };
409     next if (!$export || $export->{closed} || $export->{executed});
410
411     push @items_to_post, $item if (none { ($_->{id} == $item->{id}) && $_->{executed} } @{ $export->{items} });
412   }
413
414   if (!@items_to_post) {
415     $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'));
416   }
417
418   if (any { !$_->{execution_date} } @items_to_post) {
419     $form->show_generic_error($locale->text('You have to specify an execution date for each antry.'));
420   }
421
422   SL::SEPA->post_payment('items' => \@items_to_post, vc => $vc);
423
424   $form->show_generic_information($locale->text('The payments have been posted.'));
425
426   $main::lxdebug->leave_sub();
427 }
428
429 sub bank_transfer_payment_list_as_pdf {
430   $main::lxdebug->enter_sub();
431
432   my $form       = $main::form;
433   my %myconfig   = %main::myconfig;
434   my $locale     = $main::locale;
435   my $vc         = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
436
437   my @ids        = @{ $form->{ids} || [] };
438   my @export_ids = uniq map { $_->{sepa_export_id} } @{ $form->{items} || [] };
439
440   $form->show_generic_error($locale->text('Multi mode not supported.')) if 1 != scalar @export_ids;
441
442   my $export = SL::SEPA->retrieve_export('id' => $export_ids[0], 'details' => 1, vc => $vc);
443   my @items  = ();
444
445   foreach my $id (@ids) {
446     my $item = first { $_->{id} == $id } @{ $export->{items} };
447     push @items, $item if $item;
448   }
449
450   $form->show_generic_error($locale->text('No transfers were executed in this export.')) if 1 > scalar @items;
451
452   my $report         =  SL::ReportGenerator->new(\%main::myconfig, $form);
453
454   my %column_defs    =  (
455     'invnumber'      => { 'text' => $locale->text('Invoice'),                                                                  },
456     'vc_name'        => { 'text' => $vc eq 'customer' ? $locale->text('Customer')         : $locale->text('Vendor'),           },
457     'our_iban'       => { 'text' => $vc eq 'customer' ? $locale->text('Destination IBAN') : $locale->text('Source IBAN'),      },
458     'our_bic'        => { 'text' => $vc eq 'customer' ? $locale->text('Destination BIC')  : $locale->text('Source BIC'),       },
459     'vc_iban'        => { 'text' => $vc eq 'customer' ? $locale->text('Source IBAN')      : $locale->text('Destination IBAN'), },
460     'vc_bic'         => { 'text' => $vc eq 'customer' ? $locale->text('Source BIC')       : $locale->text('Destination BIC'),  },
461     'amount'         => { 'text' => $locale->text('Amount'),                                                                   },
462     'reference'      => { 'text' => $locale->text('Reference'),                                                                },
463     'execution_date' => { 'text' => $locale->text('Execution date'),                                                           },
464   );
465
466   map { $column_defs{$_}->{align} = 'right' } qw(amount execution_date);
467
468   my @columns        =  qw(invnumber vc_name our_iban our_bic vc_iban vc_bic amount reference execution_date);
469
470   $report->set_options('std_column_visibility' => 1,
471                        'output_format'         => 'PDF',
472                        '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}),
473                        '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),
474     );
475
476   $report->set_columns(%column_defs);
477   $report->set_column_order(@columns);
478
479   foreach my $item (@items) {
480     my $row                = { map { $_ => { 'data' => $item->{$_} } } @columns };
481     $row->{amount}->{data} = $form->format_amount(\%myconfig, $item->{amount}, 2);
482
483     $report->add_data($row);
484   }
485
486   $report->generate_with_headers();
487
488   $main::lxdebug->leave_sub();
489 }
490
491 # TODO
492 sub bank_transfer_download_sepa_xml {
493   $main::lxdebug->enter_sub();
494
495   my $form     =  $main::form;
496   my $myconfig = \%main::myconfig;
497   my $locale   =  $main::locale;
498   my $cgi      =  $::request->{cgi};
499   my $vc       = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
500   my $defaults = SL::DB::Default->get;
501
502   if (!$defaults->company) {
503     $form->show_generic_error($locale->text('You have to enter a company name in the client configuration.'));
504   }
505
506   if (($vc eq 'customer') && !$defaults->sepa_creditor_id) {
507     $form->show_generic_error($locale->text('You have to enter the SEPA creditor ID in the client configuration.'));
508   }
509
510   my @ids;
511   if ($form->{mode} && ($form->{mode} eq 'multi')) {
512      @ids = @{ $form->{ids} || [] };
513
514   } else {
515     @ids = ($form->{id});
516   }
517
518   if (!@ids) {
519     $form->show_generic_error($locale->text('You have not selected any export.'));
520   }
521
522   my @items = ();
523
524   foreach my $id (@ids) {
525     my $export = SL::SEPA->retrieve_export('id' => $id, 'details' => 1, vc => $vc);
526     push @items, grep { !$_->{executed} } @{ $export->{items} } if ($export && !$export->{closed});
527   }
528
529   if (!@items) {
530     $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'));
531   }
532
533   my $message_id = strftime('MSG%Y%m%d%H%M%S', localtime) . sprintf('%06d', $$);
534
535   my $sepa_xml   = SL::SEPA::XML->new('company'     => $defaults->company,
536                                       'creditor_id' => $defaults->sepa_creditor_id,
537                                       'src_charset' => 'UTF-8',
538                                       'message_id'  => $message_id,
539                                       'grouped'     => 1,
540                                       'collection'  => $vc eq 'customer',
541     );
542
543   foreach my $item (@items) {
544     my $requested_execution_date;
545     my $mandator_id;
546     if ($item->{requested_execution_date}) {
547       my ($yy, $mm, $dd)        = $locale->parse_date($myconfig, $item->{requested_execution_date});
548       $requested_execution_date = sprintf '%04d-%02d-%02d', $yy, $mm, $dd;
549     }
550
551     if ($vc eq 'customer') {
552       my ($yy, $mm, $dd)      = $locale->parse_date($myconfig, $item->{reference_date});
553       $item->{reference_date} = sprintf '%04d-%02d-%02d', $yy, $mm, $dd;
554       $mandator_id = $item->{mandator_id};
555       if ($item->{mandate_date_of_signature}) {
556         ($yy, $mm, $dd)                    = $locale->parse_date($myconfig, $item->{mandate_date_of_signature});
557         $item->{mandate_date_of_signature} = sprintf '%04d-%02d-%02d', $yy, $mm, $dd;
558       }
559     }
560
561     $sepa_xml->add_transaction({ 'src_iban'       => $item->{our_iban},
562                                  'src_bic'        => $item->{our_bic},
563                                  'dst_iban'       => $item->{vc_iban},
564                                  'dst_bic'        => $item->{vc_bic},
565                                  'company'        => $item->{vc_name},
566                                  'company_number' => $item->{vc_number},
567                                  'amount'         => $item->{amount},
568                                  'reference'      => $item->{reference},
569                                  'mandator_id'    => $mandator_id,
570                                  'reference_date' => $item->{reference_date},
571                                  'execution_date' => $requested_execution_date,
572                                  'end_to_end_id'  => $item->{end_to_end_id},
573                                  'date_of_signature' => $item->{mandate_date_of_signature}, });
574   }
575
576   # Store the message ID used in each of the entries in order to
577   # facilitate finding them by looking at bank statements.
578   foreach my $id (@ids) {
579     SL::DB::SepaExportMessageId->new(
580       sepa_export_id => $id,
581       message_id     => $message_id,
582     )->save;
583   }
584
585   my $xml = $sepa_xml->to_xml();
586
587   print $cgi->header('-type'                => 'application/octet-stream',
588                      '-content-disposition' => 'attachment; filename="SEPA_' . $message_id . ($vc eq 'customer' ? '.cdd' : '.cct') . '"',
589                      '-content-length'      => length $xml);
590   print $xml;
591
592   $main::lxdebug->leave_sub();
593 }
594
595 sub bank_transfer_mark_as_closed {
596   $main::lxdebug->enter_sub();
597
598   my $form       = $main::form;
599   my $locale     = $main::locale;
600
601   map { SL::SEPA->close_export('id' => $_); } @{ $form->{ids} || [] };
602
603   $form->{title} = $locale->text('Close SEPA exports');
604   $form->header();
605   $form->show_generic_information($locale->text('The selected exports have been closed.'));
606
607   $main::lxdebug->leave_sub();
608 }
609
610 sub dispatcher {
611   my $form = $main::form;
612
613   foreach my $action (qw(bank_transfer_create bank_transfer_edit bank_transfer_list
614                          bank_transfer_post_payments bank_transfer_download_sepa_xml
615                          bank_transfer_mark_as_closed_step1 bank_transfer_mark_as_closed_step2
616                          bank_transfer_payment_list_as_pdf)) {
617     if ($form->{"action_${action}"}) {
618       call_sub($action);
619       return;
620     }
621   }
622
623   $form->error($main::locale->text('No action defined.'));
624 }
625
626 sub setup_sepa_add_transfer_action_bar {
627   my (%params) = @_;
628
629   for my $bar ($::request->layout->get('actionbar')) {
630     $bar->add(
631       action => [
632         t8('Step 2'),
633         submit    => [ '#form', { action => "bank_transfer_create" } ],
634         accesskey => 'enter',
635         checks    => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
636       ],
637     );
638   }
639 }
640
641 sub setup_sepa_create_transfer_action_bar {
642   my (%params) = @_;
643
644   for my $bar ($::request->layout->get('actionbar')) {
645     $bar->add(
646       action => [
647         t8('Create'),
648         submit    => [ '#form', { action => "bank_transfer_create" } ],
649         accesskey => 'enter',
650         tooltip   => $params{is_vendor} ? t8('Create bank transfer') : t8('Create bank collection'),
651       ],
652       action => [
653         t8('Back'),
654         call => [ 'kivi.history_back' ],
655       ],
656     );
657   }
658 }
659
660 sub setup_sepa_search_transfer_action_bar {
661   my (%params) = @_;
662
663   for my $bar ($::request->layout->get('actionbar')) {
664     $bar->add(
665       action => [
666         t8('Search'),
667         submit    => [ '#form', { action => 'bank_transfer_list' } ],
668         accesskey => 'enter',
669       ],
670     );
671   }
672 }
673
674 sub setup_sepa_list_transfers_action_bar {
675   my (%params) = @_;
676
677   return unless $params{show_buttons};
678
679   for my $bar ($::request->layout->get('actionbar')) {
680     $bar->add(
681       combobox => [
682         action => [ t8('Actions') ],
683         action => [
684           t8('SEPA XML download'),
685           submit => [ '#form', { action => 'bank_transfer_download_sepa_xml' } ],
686           checks => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
687         ],
688         action => [
689           t8('Post payments'),
690           submit => [ '#form', { action => 'bank_transfer_edit' } ],
691           checks => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
692         ],
693         action => [
694           t8('Mark as closed'),
695           submit => [ '#form', { action => 'bank_transfer_mark_as_closed' } ],
696           checks => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
697           confirm => [ $params{is_vendor} ? t8('Do you really want to close the selected SEPA exports? No payment will be recorded for bank transfers that haven\'t been marked as executed yet.')
698                                           : t8('Do you really want to close the selected SEPA exports? No payment will be recorded for bank collections that haven\'t been marked as executed yet.') ],
699         ],
700       ], # end of combobox "Actions"
701     );
702   }
703 }
704
705 sub setup_sepa_edit_transfer_action_bar {
706   my (%params) = @_;
707
708   for my $bar ($::request->layout->get('actionbar')) {
709     $bar->add(
710       action => [
711         t8('Post'),
712         submit    => [ '#form', { action => 'bank_transfer_post_payments' } ],
713         accesskey => 'enter',
714         tooltip   => t8('Post payments for selected invoices'),
715         checks    => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
716         only_if   => $params{show_post_payments_button},
717       ],
718       action => [
719         t8('Payment list'),
720         submit    => [ '#form', { action => 'bank_transfer_payment_list_as_pdf' } ],
721         accesskey => 'enter',
722         tooltip   => t8('Download list of payments as PDF'),
723         checks    => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
724         not_if    => $params{show_post_payments_button},
725       ],
726     );
727   }
728 }
729
730 1;