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