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