3 use List::MoreUtils qw(any none uniq);
 
   4 use List::Util qw(sum first);
 
   5 use POSIX qw(strftime);
 
   7 use SL::DB::BankAccount;
 
   8 use SL::DB::SepaExport;
 
  12 use SL::GenericTranslations;
 
  13 use SL::Locale::String qw(t8);
 
  14 use SL::ReportGenerator;
 
  18 require "bin/mozilla/common.pl";
 
  19 require "bin/mozilla/reportgenerator.pl";
 
  21 sub bank_transfer_add {
 
  22   $main::lxdebug->enter_sub();
 
  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');
 
  29   $form->{title}    = $vc eq 'customer' ? $::locale->text('Prepare bank collection via SEPA XML') : $locale->text('Prepare bank transfer via SEPA XML');
 
  31   my $bank_accounts = SL::DB::Manager::BankAccount->get_all_sorted( query => [ obsolete => 0 ] );
 
  33   if (!scalar @{ $bank_accounts }) {
 
  34     $form->error($locale->text('You have not added bank accounts yet.'));
 
  37   my $invoices = SL::SEPA->retrieve_open_invoices(vc => $vc);
 
  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();
 
  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 };
 
  53   my $translation_list = GenericTranslations->list(translation_type => 'sepa_remittance_info_pfx');
 
  54   my %translations     = map { ( ($_->{language_id} || 'default') => $_->{translation} ) } @{ $translation_list };
 
  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;
 
  61     # add c_vendor_id or v_vendor_id as a prefix if a entry exists
 
  62     next unless $invoice->{vc_vc_id};
 
  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/^ /;
 
  69   setup_sepa_add_transfer_action_bar();
 
  72   print $form->parse_html_template('sepa/bank_transfer_add',
 
  73                                    { 'INVOICES'           => $invoices,
 
  74                                      'BANK_ACCOUNTS'      => $bank_accounts,
 
  78   $main::lxdebug->leave_sub();
 
  81 sub bank_transfer_create {
 
  82   $main::lxdebug->enter_sub();
 
  84   my $form          = $main::form;
 
  85   my $locale        = $main::locale;
 
  86   my $myconfig      = \%main::myconfig;
 
  87   my $vc            = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
 
  89   $form->{title}    = $vc eq 'customer' ? $::locale->text('Create bank collection via SEPA XML') : $locale->text('Create bank transfer via SEPA XML');
 
  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.'));
 
  96   my $bank_account = SL::DB::Manager::BankAccount->find_by( id => $form->{bank_account} );
 
  98   unless ( $bank_account ) {
 
  99     $form->error($locale->text('The selected bank account does not exist anymore.'));
 
 102   my $arap_id        = $vc eq 'customer' ? 'ar_id' : 'ap_id';
 
 103   my $invoices       = SL::SEPA->retrieve_open_invoices(vc => $vc);
 
 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 };
 
 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} || [] };
 
 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
 
 135     foreach my $type ( @{$bt->{payment_select_options}} ) {
 
 136       if ( $type->{payment_type} eq $bt->{payment_type} ) {
 
 137         $type->{selected} = 1;
 
 139         $type->{selected} = 0;
 
 144   if (!scalar @bank_transfers) {
 
 145     $form->error($locale->text('You have selected none of the invoices.'));
 
 148   my $total_trans = sum map { $_->{open_amount} } @bank_transfers;
 
 153   my @bank_columns    = qw(iban bic);
 
 154   push @bank_columns, qw(mandator_id mandate_date_of_signature) if $vc eq 'customer';
 
 156   if ($form->{confirmation}) {
 
 157     $vc_bank_info = { map { $_->{id} => $_ } @{ $form->{vc_bank_info} || [] } };
 
 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.');
 
 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,
 
 171     my @vc_bank_info           = sort { lc $a->{name} cmp lc $b->{name} } values %{ $vc_bank_info };
 
 173     setup_sepa_create_transfer_action_bar(is_vendor => $vc eq 'vendor');
 
 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,
 
 183                                        'total_trans'        => $total_trans,
 
 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->{$_};
 
 193       $bank_transfer->{chart_id} = $bank_account->{chart_id};
 
 196     my $id = SL::SEPA->create_export('employee'       => $::myconfig{login},
 
 197                                      'bank_transfers' => \@bank_transfers,
 
 201     print $form->parse_html_template('sepa/bank_transfer_created', { 'id' => $id, 'vc' => $vc });
 
 204   $main::lxdebug->leave_sub();
 
 207 sub bank_transfer_search {
 
 208   $main::lxdebug->enter_sub();
 
 210   my $form   = $main::form;
 
 211   my $locale = $main::locale;
 
 212   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
 
 214   $form->{title}    = $vc eq 'customer' ? $::locale->text('List of bank collections') : $locale->text('List of bank transfers');
 
 216   setup_sepa_search_transfer_action_bar();
 
 219   print $form->parse_html_template('sepa/bank_transfer_search', { vc => $vc });
 
 221   $main::lxdebug->leave_sub();
 
 225 sub bank_transfer_list {
 
 226   $main::lxdebug->enter_sub();
 
 228   my $form   = $main::form;
 
 229   my $locale = $main::locale;
 
 230   my $cgi    = $::request->{cgi};
 
 231   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
 
 233   $form->{title}     = $vc eq 'customer' ? $::locale->text('List of bank collections') : $locale->text('List of bank transfers');
 
 235   $form->{sort}    ||= 'id';
 
 236   $form->{sortdir}   = '1' if (!defined $form->{sortdir});
 
 238   $form->{callback}  = build_std_url('action=bank_transfer_list', 'sort', 'sortdir', 'vc');
 
 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});
 
 248   my $exports        = SL::SEPA->list_exports('filter'    => \%filter,
 
 249                                               'sortorder' => $form->{sort},
 
 250                                               'sortdir'   => $form->{sortdir},
 
 253   my $open_available = any { !$_->{closed} } @{ $exports };
 
 255   my $report         = SL::ReportGenerator->new(\%main::myconfig, $form);
 
 257   my @hidden_vars    = ('vc', grep { m/^[fl]_/ && $form->{$_} } keys %{ $form });
 
 259   my $href           = build_std_url('action=bank_transfer_list', @hidden_vars);
 
 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'), },
 
 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);
 
 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";
 
 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;
 
 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});
 
 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),
 
 307   $report->set_options_from_form();
 
 308   $locale->set_numberformat_wo_thousands_separator(\%::myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
 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});
 
 315   my $edit_url = build_std_url('action=bank_transfer_edit', 'callback');
 
 317   foreach my $export (@{ $exports }) {
 
 318     my $row = { map { $_ => { 'data' => $export->{$_}, 'align' => $column_alignment{$_} } } keys %{ $export } };
 
 320     map { $row->{$_}->{data} = $export->{$_} ? $locale->text('yes') : $locale->text('no') } qw(executed closed);
 
 322     $row->{id}->{link} = $edit_url . '&id=' . E($export->{id}) . '&vc=' . E($vc);
 
 324     $row->{$_}->{data} = $::form->format_amount(\%::myconfig, $row->{$_}->{data}, 2) for qw(sum_amounts);
 
 326     if (!$export->{closed}) {
 
 327       $row->{selected}->{raw_data} = $cgi->checkbox(-name => "ids[]", -value => $export->{id}, -label => '');
 
 330     $report->add_data($row);
 
 333   setup_sepa_list_transfers_action_bar(show_buttons => $open_available, is_vendor => $vc eq 'vendor');
 
 335   $report->generate_with_headers();
 
 337   $main::lxdebug->leave_sub();
 
 340 sub bank_transfer_edit {
 
 341   $main::lxdebug->enter_sub();
 
 343   my $form   = $main::form;
 
 344   my $locale = $main::locale;
 
 345   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
 
 348   if (!$form->{mode} || ($form->{mode} eq 'single')) {
 
 349     push @ids, $form->{id};
 
 351     @ids = @{ $form->{ids} || [] };
 
 354       $form->show_generic_error($locale->text('You have not selected any export.'));
 
 360   foreach my $id (@ids) {
 
 361     my $curr_export = SL::SEPA->retrieve_export('id' => $id, 'details' => 1, 'vc' => $vc);
 
 363     foreach my $item (@{ $curr_export->{items} }) {
 
 364       map { $item->{"export_${_}"} = $curr_export->{$_} } grep { !ref $curr_export->{$_} } keys %{ $curr_export };
 
 368       $export = $curr_export;
 
 370       push @{ $export->{items} }, @{ $curr_export->{items} };
 
 374   if ($form->{mode} && ($form->{mode} eq 'multi')) {
 
 375     $export->{items} = [ grep { !$_->{export_closed} && !$_->{executed} } @{ $export->{items} } ];
 
 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.'));
 
 382     $form->error($locale->text('That export does not exist.'));
 
 385   my $show_post_payments_button = any { !$_->{export_closed} && !$_->{executed} } @{ $export->{items} };
 
 386   my $has_executed              = any { $_->{executed}                          } @{ $export->{items} };
 
 388   setup_sepa_edit_transfer_action_bar(
 
 389     show_post_payments_button => $show_post_payments_button,
 
 390     has_executed              => $has_executed,
 
 393   $form->{title}    = $locale->text('View SEPA export');
 
 395   print $form->parse_html_template('sepa/bank_transfer_edit',
 
 398                                      current_date              => $form->current_date(\%main::myconfig),
 
 399                                      show_post_payments_button => $show_post_payments_button,
 
 402   $main::lxdebug->leave_sub();
 
 405 sub bank_transfer_post_payments {
 
 406   $main::lxdebug->enter_sub();
 
 408   my $form   = $main::form;
 
 409   my $locale = $main::locale;
 
 410   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
 
 412   my %selected = map { ($_ => 1) } @{ $form->{ids} || [] };
 
 413   my @items    = grep { $selected{$_->{id}} } @{ $form->{items} || [] };
 
 416     $form->show_generic_error($locale->text('You have not selected any item.'));
 
 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 = ();
 
 422   foreach my $item (@items) {
 
 423     my $export = $exports{ $item->{sepa_export_id} };
 
 424     next if (!$export || $export->{closed} || $export->{executed});
 
 426     push @items_to_post, $item if (none { ($_->{id} == $item->{id}) && $_->{executed} } @{ $export->{items} });
 
 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.'));
 
 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.'));
 
 437   SL::SEPA->post_payment('items' => \@items_to_post, vc => $vc);
 
 439   $form->show_generic_information($locale->text('The payments have been posted.'));
 
 441   $main::lxdebug->leave_sub();
 
 444 sub bank_transfer_payment_list_as_pdf {
 
 445   $main::lxdebug->enter_sub();
 
 447   my $form       = $main::form;
 
 448   my %myconfig   = %main::myconfig;
 
 449   my $locale     = $main::locale;
 
 450   my $vc         = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
 
 452   my @ids        = @{ $form->{ids} || [] };
 
 453   my @export_ids = uniq map { $_->{sepa_export_id} } @{ $form->{items} || [] };
 
 455   $form->show_generic_error($locale->text('Multi mode not supported.')) if 1 != scalar @export_ids;
 
 457   my $export = SL::SEPA->retrieve_export('id' => $export_ids[0], 'details' => 1, vc => $vc);
 
 460   foreach my $id (@ids) {
 
 461     my $item = first { $_->{id} == $id } @{ $export->{items} };
 
 462     push @items, $item if $item;
 
 465   $form->show_generic_error($locale->text('No transfers were executed in this export.')) if 1 > scalar @items;
 
 467   my $report         =  SL::ReportGenerator->new(\%main::myconfig, $form);
 
 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'),                                                           },
 
 481   map { $column_defs{$_}->{align} = 'right' } qw(amount execution_date);
 
 483   my @columns        =  qw(invnumber vc_name our_iban our_bic vc_iban vc_bic amount reference execution_date);
 
 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),
 
 491   $report->set_columns(%column_defs);
 
 492   $report->set_column_order(@columns);
 
 494   foreach my $item (@items) {
 
 495     my $row                = { map { $_ => { 'data' => $item->{$_} } } @columns };
 
 496     $row->{amount}->{data} = $form->format_amount(\%myconfig, $item->{amount}, 2);
 
 498     $report->add_data($row);
 
 501   $report->generate_with_headers();
 
 503   $main::lxdebug->leave_sub();
 
 507 sub bank_transfer_download_sepa_xml {
 
 508   $main::lxdebug->enter_sub();
 
 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;
 
 517   if (!$defaults->company) {
 
 518     $form->show_generic_error($locale->text('You have to enter a company name in the client configuration.'));
 
 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.'));
 
 526   if ($form->{mode} && ($form->{mode} eq 'multi')) {
 
 527      @ids = @{ $form->{ids} || [] };
 
 530     @ids = ($form->{id});
 
 534     $form->show_generic_error($locale->text('You have not selected any export.'));
 
 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});
 
 545     $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'));
 
 548   my $message_id = strftime('MSG%Y%m%d%H%M%S', localtime) . sprintf('%06d', $$);
 
 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,
 
 555                                       'collection'  => $vc eq 'customer',
 
 558   foreach my $item (@items) {
 
 559     my $requested_execution_date;
 
 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;
 
 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;
 
 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}, });
 
 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,
 
 600   my $xml = $sepa_xml->to_xml();
 
 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);
 
 607   $main::lxdebug->leave_sub();
 
 610 sub bank_transfer_mark_as_closed {
 
 611   $main::lxdebug->enter_sub();
 
 613   my $form       = $main::form;
 
 614   my $locale     = $main::locale;
 
 616   map { SL::SEPA->close_export('id' => $_); } @{ $form->{ids} || [] };
 
 618   $form->{title} = $locale->text('Close SEPA exports');
 
 620   $form->show_generic_information($locale->text('The selected exports have been closed.'));
 
 622   $main::lxdebug->leave_sub();
 
 625 sub bank_transfer_undo_sepa_xml {
 
 626   $main::lxdebug->enter_sub();
 
 628   my $form       = $main::form;
 
 629   my $locale     = $main::locale;
 
 631   map { SL::SEPA->undo_export('id' => $_); } @{ $form->{ids} || [] };
 
 633   $form->{title} = $locale->text('Undo SEPA exports');
 
 635   $form->show_generic_information($locale->text('The selected exports have been undone.'));
 
 637   $main::lxdebug->leave_sub();
 
 641   my $form = $main::form;
 
 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}"}) {
 
 653   $form->error($main::locale->text('No action defined.'));
 
 656 sub setup_sepa_add_transfer_action_bar {
 
 659   for my $bar ($::request->layout->get('actionbar')) {
 
 663         submit    => [ '#form', { action => "bank_transfer_create" } ],
 
 664         accesskey => 'enter',
 
 665         checks    => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
 
 671 sub setup_sepa_create_transfer_action_bar {
 
 674   for my $bar ($::request->layout->get('actionbar')) {
 
 678         submit    => [ '#form', { action => "bank_transfer_create" } ],
 
 679         accesskey => 'enter',
 
 680         tooltip   => $params{is_vendor} ? t8('Create bank transfer') : t8('Create bank collection'),
 
 684         call => [ 'kivi.history_back' ],
 
 690 sub setup_sepa_search_transfer_action_bar {
 
 693   for my $bar ($::request->layout->get('actionbar')) {
 
 697         submit    => [ '#form', { action => 'bank_transfer_list' } ],
 
 698         accesskey => 'enter',
 
 704 sub setup_sepa_list_transfers_action_bar {
 
 707   return unless $params{show_buttons};
 
 709   for my $bar ($::request->layout->get('actionbar')) {
 
 712         action => [ t8('Actions') ],
 
 714           t8('SEPA XML download'),
 
 715           submit => [ '#form', { action => 'bank_transfer_download_sepa_xml' } ],
 
 716           checks => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
 
 720           submit => [ '#form', { action => 'bank_transfer_edit' } ],
 
 721           checks => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
 
 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.') ],
 
 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.') ],
 
 736       ], # end of combobox "Actions"
 
 741 sub setup_sepa_edit_transfer_action_bar {
 
 744   for my $bar ($::request->layout->get('actionbar')) {
 
 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.'),
 
 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,