Merge branch 'b-3.6.1' of ../kivitendo-erp_20220811
[kivitendo-erp.git] / bin / mozilla / sepa.pl
index 2e45511..ca4ad0a 100755 (executable)
@@ -4,13 +4,13 @@ use List::MoreUtils qw(any none uniq);
 use List::Util qw(sum first);
 use POSIX qw(strftime);
 
-use Data::Dumper;
 use SL::DB::BankAccount;
 use SL::DB::SepaExport;
 use SL::Chart;
 use SL::CT;
 use SL::Form;
 use SL::GenericTranslations;
+use SL::Locale::String qw(t8);
 use SL::ReportGenerator;
 use SL::SEPA;
 use SL::SEPA::XML;
@@ -24,6 +24,7 @@ sub bank_transfer_add {
   my $form          = $main::form;
   my $locale        = $main::locale;
   my $vc            = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
+  my $vc_no         = $form->{vc} eq 'customer' ? $::locale->text('VN') : $::locale->text('CN');
 
   $form->{title}    = $vc eq 'customer' ? $::locale->text('Prepare bank collection via SEPA XML') : $locale->text('Prepare bank transfer via SEPA XML');
 
@@ -56,8 +57,17 @@ sub bank_transfer_add {
     my $prefix                    = $translations{ $invoice->{language_id} } || $translations{default} || $::locale->text('Invoice');
     $prefix                      .= ' ' unless $prefix =~ m/ $/;
     $invoice->{reference_prefix}  = $prefix;
+
+    # add c_vendor_id or v_vendor_id as a prefix if a entry exists
+    next unless $invoice->{vc_vc_id};
+
+    my $prefix_vc_number             = $translations{ $invoice->{language_id} } || $translations{default} || $vc_no;
+    $prefix_vc_number               .= ' ' unless $prefix_vc_number =~ m/ $/;
+    $invoice->{reference_prefix_vc}  = ' '  . $prefix_vc_number unless $prefix_vc_number =~ m/^ /;
   }
 
+  setup_sepa_add_transfer_action_bar();
+
   $form->header();
   print $form->parse_html_template('sepa/bank_transfer_add',
                                    { 'INVOICES'           => $invoices,
@@ -92,20 +102,36 @@ sub bank_transfer_create {
   my $arap_id        = $vc eq 'customer' ? 'ar_id' : 'ap_id';
   my $invoices       = SL::SEPA->retrieve_open_invoices(vc => $vc);
 
-  # 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
-  # all the information from retrieve_open_invoices is then ADDED to what was passed via @{ $form->{bank_transfers} }
-  # parse amount from the entry in the form, but take skonto_amount from PT again
-  # the map inserts the values of invoice_map directly into the array of hashes
+  # 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.
+  # All the information from retrieve_open_invoices is then ADDED to what was passed via @{ $form->{bank_transfers} }.
+  # Parse amount from the entry in the form, but take skonto_amount from PT again.
+  # The map inserts the values of invoice_map directly into the array of hashes.
+  my %selected_ids   = map { ($_ => 1) } @{ $form->{ids} || [] };
   my %invoices_map   = map { $_->{id} => $_ } @{ $invoices };
   my @bank_transfers =
     map  +{ %{ $invoices_map{ $_->{$arap_id} } }, %{ $_ } },
-    grep  { $_->{selected} && (0 < $_->{amount}) && $invoices_map{ $_->{$arap_id} } }
+    grep  { ($_->{selected} || $selected_ids{$_->{$arap_id}}) && (0 < $_->{amount}) && $invoices_map{ $_->{$arap_id} } }
     map   { $_->{amount} = $form->parse_amount($myconfig, $_->{amount}); $_ }
           @{ $form->{bank_transfers} || [] };
 
   # override default payment_type selection and set it to the one chosen by the user
   # in the previous step, so that we don't need the logic in the template
+  my $subtract_days   = $::instance_conf->get_sepa_set_skonto_date_buffer_in_days;
+  my $set_skonto_date = $::instance_conf->get_sepa_set_skonto_date_as_default_exec_date;
+  my $set_duedate     = $::instance_conf->get_sepa_set_duedate_as_default_exec_date;
   foreach my $bt (@bank_transfers) {
+    # add a good recommended exec date
+    # set to skonto date if exists or to duedate
+    # in both cases subtract the same buffer (if configured, default 0)
+    $bt->{recommended_execution_date} =
+      $set_skonto_date && $bt->{payment_type} eq 'with_skonto_pt' ?
+                   DateTime->from_kivitendo($bt->{skonto_date})->subtract(days => $subtract_days)->to_kivitendo
+   :  $set_duedate && $bt->{duedate}                              ?
+                   DateTime->from_kivitendo($bt->{duedate}    )->subtract(days => $subtract_days)->to_kivitendo
+   :  undef;
+
+
     foreach my $type ( @{$bt->{payment_select_options}} ) {
       if ( $type->{payment_type} eq $bt->{payment_type} ) {
         $type->{selected} = 1;
@@ -144,6 +170,8 @@ sub bank_transfer_create {
                                                    'id' => \@vc_ids);
     my @vc_bank_info           = sort { lc $a->{name} cmp lc $b->{name} } values %{ $vc_bank_info };
 
+    setup_sepa_create_transfer_action_bar(is_vendor => $vc eq 'vendor');
+
     $form->header();
     print $form->parse_html_template('sepa/bank_transfer_create',
                                      { 'BANK_TRANSFERS'     => \@bank_transfers,
@@ -185,6 +213,8 @@ sub bank_transfer_search {
 
   $form->{title}    = $vc eq 'customer' ? $::locale->text('List of bank collections') : $locale->text('List of bank transfers');
 
+  setup_sepa_search_transfer_action_bar();
+
   $form->header();
   print $form->parse_html_template('sepa/bank_transfer_search', { vc => $vc });
 
@@ -294,14 +324,14 @@ sub bank_transfer_list {
     $row->{$_}->{data} = $::form->format_amount(\%::myconfig, $row->{$_}->{data}, 2) for qw(sum_amounts);
 
     if (!$export->{closed}) {
-      $row->{selected}->{raw_data} =
-          $cgi->hidden(-name => "exports[+].id", -value => $export->{id})
-        . $cgi->checkbox(-name => "exports[].selected", -value => 1, -label => '');
+      $row->{selected}->{raw_data} = $cgi->checkbox(-name => "ids[]", -value => $export->{id}, -label => '');
     }
 
     $report->add_data($row);
   }
 
+  setup_sepa_list_transfers_action_bar(show_buttons => $open_available, is_vendor => $vc eq 'vendor');
+
   $report->generate_with_headers();
 
   $main::lxdebug->leave_sub();
@@ -318,10 +348,10 @@ sub bank_transfer_edit {
   if (!$form->{mode} || ($form->{mode} eq 'single')) {
     push @ids, $form->{id};
   } else {
-    @ids = map $_->{id}, grep { $_->{selected} } @{ $form->{exports} || [] };
+    @ids = @{ $form->{ids} || [] };
 
     if (!@ids) {
-      $form->show_generic_error($locale->text('You have not selected any export.'), 'back_button' => 1);
+      $form->show_generic_error($locale->text('You have not selected any export.'));
     }
   }
 
@@ -345,20 +375,28 @@ sub bank_transfer_edit {
     $export->{items} = [ grep { !$_->{export_closed} && !$_->{executed} } @{ $export->{items} } ];
 
     if (!@{ $export->{items} }) {
-      $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'), 'back_button' => 1);
+      $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'));
     }
 
   } elsif (!$export) {
     $form->error($locale->text('That export does not exist.'));
   }
 
+  my $show_post_payments_button = any { !$_->{export_closed} && !$_->{executed} } @{ $export->{items} };
+  my $has_executed              = any { $_->{executed}                          } @{ $export->{items} };
+
+  setup_sepa_edit_transfer_action_bar(
+    show_post_payments_button => $show_post_payments_button,
+    has_executed              => $has_executed,
+  );
+
   $form->{title}    = $locale->text('View SEPA export');
   $form->header();
   print $form->parse_html_template('sepa/bank_transfer_edit',
-                                   { 'ids'                       => \@ids,
-                                     'export'                    => $export,
-                                     'current_date'              => $form->current_date(\%main::myconfig),
-                                     'show_post_payments_button' => any { !$_->{export_closed} && !$_->{executed} } @{ $export->{items} },
+                                   { ids                       => \@ids,
+                                     export                    => $export,
+                                     current_date              => $form->current_date(\%main::myconfig),
+                                     show_post_payments_button => $show_post_payments_button,
                                    });
 
   $main::lxdebug->leave_sub();
@@ -371,10 +409,11 @@ sub bank_transfer_post_payments {
   my $locale = $main::locale;
   my $vc     = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
 
-  my @items  = grep { $_->{selected} } @{ $form->{items} || [] };
+  my %selected = map { ($_ => 1) } @{ $form->{ids} || [] };
+  my @items    = grep { $selected{$_->{id}} } @{ $form->{items} || [] };
 
   if (!@items) {
-    $form->show_generic_error($locale->text('You have not selected any item.'), 'back_button' => 1);
+    $form->show_generic_error($locale->text('You have not selected any item.'));
   }
   my @export_ids    = uniq map { $_->{sepa_export_id} } @items;
   my %exports       = map { $_ => SL::SEPA->retrieve_export('id' => $_, 'details' => 1, vc => $vc) } @export_ids;
@@ -388,11 +427,11 @@ sub bank_transfer_post_payments {
   }
 
   if (!@items_to_post) {
-    $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'), 'back_button' => 1);
+    $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'));
   }
 
   if (any { !$_->{execution_date} } @items_to_post) {
-    $form->show_generic_error($locale->text('You have to specify an execution date for each antry.'), 'back_button' => 1);
+    $form->show_generic_error($locale->text('You have to specify an execution date for each antry.'));
   }
 
   SL::SEPA->post_payment('items' => \@items_to_post, vc => $vc);
@@ -410,20 +449,20 @@ sub bank_transfer_payment_list_as_pdf {
   my $locale     = $main::locale;
   my $vc         = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
 
-  my @ids        = @{ $form->{items} || [] };
-  my @export_ids = uniq map { $_->{export_id} } @ids;
+  my @ids        = @{ $form->{ids} || [] };
+  my @export_ids = uniq map { $_->{sepa_export_id} } @{ $form->{items} || [] };
 
-  $form->show_generic_error($locale->text('Multi mode not supported.'), 'back_button' => 1) if 1 != scalar @export_ids;
+  $form->show_generic_error($locale->text('Multi mode not supported.')) if 1 != scalar @export_ids;
 
   my $export = SL::SEPA->retrieve_export('id' => $export_ids[0], 'details' => 1, vc => $vc);
   my @items  = ();
 
   foreach my $id (@ids) {
-    my $item = first { $_->{id} == $id->{id} } @{ $export->{items} };
+    my $item = first { $_->{id} == $id } @{ $export->{items} };
     push @items, $item if $item;
   }
 
-  $form->show_generic_error($locale->text('No transfers were executed in this export.'), 'back_button' => 1) if 1 > scalar @items;
+  $form->show_generic_error($locale->text('No transfers were executed in this export.')) if 1 > scalar @items;
 
   my $report         =  SL::ReportGenerator->new(\%main::myconfig, $form);
 
@@ -476,23 +515,23 @@ sub bank_transfer_download_sepa_xml {
   my $defaults = SL::DB::Default->get;
 
   if (!$defaults->company) {
-    $form->show_generic_error($locale->text('You have to enter a company name in the client configuration.'), 'back_button' => 1);
+    $form->show_generic_error($locale->text('You have to enter a company name in the client configuration.'));
   }
 
   if (($vc eq 'customer') && !$defaults->sepa_creditor_id) {
-    $form->show_generic_error($locale->text('You have to enter the SEPA creditor ID in the client configuration.'), 'back_button' => 1);
+    $form->show_generic_error($locale->text('You have to enter the SEPA creditor ID in the client configuration.'));
   }
 
   my @ids;
   if ($form->{mode} && ($form->{mode} eq 'multi')) {
-     @ids = map $_->{id}, grep { $_->{selected} } @{ $form->{exports} || [] };
+     @ids = @{ $form->{ids} || [] };
 
   } else {
     @ids = ($form->{id});
   }
 
   if (!@ids) {
-    $form->show_generic_error($locale->text('You have not selected any export.'), 'back_button' => 1);
+    $form->show_generic_error($locale->text('You have not selected any export.'));
   }
 
   my @items = ();
@@ -503,7 +542,7 @@ sub bank_transfer_download_sepa_xml {
   }
 
   if (!@items) {
-    $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'), 'back_button' => 1);
+    $form->show_generic_error($locale->text('All the selected exports have already been closed, or all of their items have already been executed.'));
   }
 
   my $message_id = strftime('MSG%Y%m%d%H%M%S', localtime) . sprintf('%06d', $$);
@@ -568,47 +607,32 @@ sub bank_transfer_download_sepa_xml {
   $main::lxdebug->leave_sub();
 }
 
-sub bank_transfer_mark_as_closed_step1 {
+sub bank_transfer_mark_as_closed {
   $main::lxdebug->enter_sub();
 
   my $form       = $main::form;
   my $locale     = $main::locale;
-  my $vc         = $form->{vc} eq 'customer' ? 'customer' : 'vendor';
-
-  my @export_ids = map { $_->{id} } grep { $_->{selected} } @{ $form->{exports} || [] };
-
-  if (!@export_ids) {
-    $form->show_generic_error($locale->text('You have not selected any export.'), 'back_button' => 1);
-  }
-
-  my @open_export_ids = ();
-  foreach my $id (@export_ids) {
-    my $export = SL::SEPA->retrieve_export('id' => $id, vc => $vc);
-    push @open_export_ids, $id if (!$export->{closed});
-  }
 
-  if (!@open_export_ids) {
-    $form->show_generic_error($locale->text('All of the exports you have selected were already closed.'), 'back_button' => 1);
-  }
+  map { SL::SEPA->close_export('id' => $_); } @{ $form->{ids} || [] };
 
   $form->{title} = $locale->text('Close SEPA exports');
   $form->header();
-  print $form->parse_html_template('sepa/bank_transfer_mark_as_closed_step1', { 'OPEN_EXPORT_IDS' => \@open_export_ids, vc => $vc });
+  $form->show_generic_information($locale->text('The selected exports have been closed.'));
 
   $main::lxdebug->leave_sub();
 }
 
-sub bank_transfer_mark_as_closed_step2 {
+sub bank_transfer_undo_sepa_xml {
   $main::lxdebug->enter_sub();
 
   my $form       = $main::form;
   my $locale     = $main::locale;
 
-  map { SL::SEPA->close_export('id' => $_); } @{ $form->{open_export_ids} || [] };
+  map { SL::SEPA->undo_export('id' => $_); } @{ $form->{ids} || [] };
 
-  $form->{title} = $locale->text('Close SEPA exports');
+  $form->{title} = $locale->text('Undo SEPA exports');
   $form->header();
-  $form->show_generic_information($locale->text('The selected exports have been closed.'));
+  $form->show_generic_information($locale->text('The selected exports have been undone.'));
 
   $main::lxdebug->leave_sub();
 }
@@ -619,7 +643,7 @@ sub dispatcher {
   foreach my $action (qw(bank_transfer_create bank_transfer_edit bank_transfer_list
                          bank_transfer_post_payments bank_transfer_download_sepa_xml
                          bank_transfer_mark_as_closed_step1 bank_transfer_mark_as_closed_step2
-                         bank_transfer_payment_list_as_pdf)) {
+                         bank_transfer_payment_list_as_pdf bank_transfer_undo_sepa_xml)) {
     if ($form->{"action_${action}"}) {
       call_sub($action);
       return;
@@ -629,4 +653,114 @@ sub dispatcher {
   $form->error($main::locale->text('No action defined.'));
 }
 
+sub setup_sepa_add_transfer_action_bar {
+  my (%params) = @_;
+
+  for my $bar ($::request->layout->get('actionbar')) {
+    $bar->add(
+      action => [
+        t8('Step 2'),
+        submit    => [ '#form', { action => "bank_transfer_create" } ],
+        accesskey => 'enter',
+        checks    => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
+      ],
+    );
+  }
+}
+
+sub setup_sepa_create_transfer_action_bar {
+  my (%params) = @_;
+
+  for my $bar ($::request->layout->get('actionbar')) {
+    $bar->add(
+      action => [
+        t8('Create'),
+        submit    => [ '#form', { action => "bank_transfer_create" } ],
+        accesskey => 'enter',
+        tooltip   => $params{is_vendor} ? t8('Create bank transfer') : t8('Create bank collection'),
+      ],
+      action => [
+        t8('Back'),
+        call => [ 'kivi.history_back' ],
+      ],
+    );
+  }
+}
+
+sub setup_sepa_search_transfer_action_bar {
+  my (%params) = @_;
+
+  for my $bar ($::request->layout->get('actionbar')) {
+    $bar->add(
+      action => [
+        t8('Search'),
+        submit    => [ '#form', { action => 'bank_transfer_list' } ],
+        accesskey => 'enter',
+      ],
+    );
+  }
+}
+
+sub setup_sepa_list_transfers_action_bar {
+  my (%params) = @_;
+
+  return unless $params{show_buttons};
+
+  for my $bar ($::request->layout->get('actionbar')) {
+    $bar->add(
+      combobox => [
+        action => [ t8('Actions') ],
+        action => [
+          t8('SEPA XML download'),
+          submit => [ '#form', { action => 'bank_transfer_download_sepa_xml' } ],
+          checks => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
+        ],
+        action => [
+          t8('Post payments'),
+          submit => [ '#form', { action => 'bank_transfer_edit' } ],
+          checks => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
+        ],
+        action => [
+          t8('Mark as closed'),
+          submit => [ '#form', { action => 'bank_transfer_mark_as_closed' } ],
+          checks => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
+          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.')
+                                          : 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.') ],
+        ],
+        action => [
+          t8('Undo SEPA exports'),
+          submit => [ '#form', { action => 'bank_transfer_undo_sepa_xml' } ],
+          checks => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
+          confirm => [ t8('Do you really want to undo the selected SEPA exports? You have to reassign the export again.') ],
+        ],
+      ], # end of combobox "Actions"
+    );
+  }
+}
+
+sub setup_sepa_edit_transfer_action_bar {
+  my (%params) = @_;
+
+  for my $bar ($::request->layout->get('actionbar')) {
+    $bar->add(
+      action => [
+        t8('Post'),
+        submit    => [ '#form', { action => 'bank_transfer_post_payments' } ],
+        accesskey => 'enter',
+        tooltip   => t8('Post payments for selected invoices'),
+        checks    => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
+        disabled  => $params{show_post_payments_button} ? undef : t8('All payments have already been posted.'),
+      ],
+      action => [
+        t8('Payment list'),
+        submit    => [ '#form', { action => 'bank_transfer_payment_list_as_pdf' } ],
+        accesskey => 'enter',
+        tooltip   => t8('Download list of payments as PDF'),
+        checks    => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
+        disabled  => $params{show_post_payments_button} ? t8('All payments must be posted before the payment list can be downloaded.') : undef,
+      ],
+    );
+  }
+}
+
 1;