Merge branch 'master' of github.com:kivitendo/kivitendo-erp
[kivitendo-erp.git] / SL / BackgroundJob / CreatePeriodicInvoices.pm
index 4777025..9f116be 100644 (file)
@@ -58,7 +58,7 @@ sub run {
     }
   }
 
-  map { _print_invoice(@{ $_ }) } @invoices_to_print;
+  _print_invoice(@{ $_ }) for @invoices_to_print;
 
   _send_email(\@new_invoices, [ map { $_->[0] } @invoices_to_print ]) if @new_invoices;
 
@@ -66,7 +66,7 @@ sub run {
 }
 
 sub _log_msg {
-  my $message  = join('', @_);
+  my $message  = join('', 'SL::BackgroundJob::CreatePeriodicInvoices: ', @_);
   $message    .= "\n" unless $message =~ m/\n$/;
   $::lxdebug->message(LXDebug::DEBUG1(), $message);
 }
@@ -74,7 +74,7 @@ sub _log_msg {
 sub _generate_time_period_variables {
   my $config            = shift;
   my $period_start_date = shift;
-  my $period_end_date   = $period_start_date->clone->truncate(to => 'month')->add(months => $config->get_period_length)->subtract(days => 1);
+  my $period_end_date   = $period_start_date->clone->truncate(to => 'month')->add(months => $config->get_billing_period_length)->subtract(days => 1);
 
   my @month_names       = ('',
                            $::locale->text('January'), $::locale->text('February'), $::locale->text('March'),     $::locale->text('April'),   $::locale->text('May'),      $::locale->text('June'),
@@ -105,32 +105,80 @@ sub _generate_time_period_variables {
 }
 
 sub _replace_vars {
-  my $object = shift;
-  my $vars   = shift;
-  my $sub    = shift;
-  my $str    = $object->$sub;
+  my (%params) = @_;
+  my $sub      = $params{attribute};
+  my $str      = $params{object}->$sub // '';
+  my $sub_fmt  = lc($params{attribute_format} // 'text');
 
-  $str =~ s{ <\% ([a-z0-9_]+) ( \s+ format \s*=\s* (.*?) \s* )? \%>}{
+  my ($start_tag, $end_tag) = $sub_fmt eq 'html' ? ('&lt;%', '%&gt;') : ('<%', '%>');
+
+  $str =~ s{ ${start_tag} ([a-z0-9_]+) ( \s+ format \s*=\s* (.*?) \s* )? ${end_tag} }{
     my ($key, $format) = ($1, $3);
-    if (!$vars->{$key}) {
-      '';
+    $key               = $::locale->unquote_special_chars('html', $key) if $sub_fmt eq 'html';
+    my $new_value;
+
+    if (!$params{vars}->{$key}) {
+      $new_value = '';
 
     } elsif ($format) {
-      DateTime::Format::Strptime->new(
+      $format    = $::locale->unquote_special_chars('html', $format) if $sub_fmt eq 'html';
+
+      $new_value = DateTime::Format::Strptime->new(
         pattern     => $format,
         locale      => 'de_DE',
         time_zone   => 'local',
-      )->format_datetime($vars->{$key}->[0]);
+      )->format_datetime($params{vars}->{$key}->[0]);
 
     } else {
-      $vars->{$1}->[1]->($vars->{$1}->[0]);
+      $new_value = $params{vars}->{$1}->[1]->($params{vars}->{$1}->[0]);
     }
+
+    $new_value = $::locale->quote_special_chars('html', $new_value) if $sub_fmt eq 'html';
+
+    $new_value;
+
   }eigx;
 
-  $object->$sub($str);
+  $params{object}->$sub($str);
+}
+
+sub _adjust_sellprices_for_period_lengths {
+  my (%params) = @_;
+
+  my $billing_len     = $params{config}->get_billing_period_length;
+  my $order_value_len = $params{config}->get_order_value_period_length;
+
+  return if $billing_len == $order_value_len;
+
+  my $is_last_invoice_in_cycle = $params{config}->is_last_bill_date_in_order_value_cycle(date => $params{period_start_date});
+
+  _log_msg("_adjust_sellprices_for_period_lengths: period_start_date $params{period_start_date} is_last_invoice_in_cycle $is_last_invoice_in_cycle billing_len $billing_len order_value_len $order_value_len");
+
+  if ($order_value_len < $billing_len) {
+    my $num_orders_per_invoice = $billing_len / $order_value_len;
+
+    $_->sellprice($_->sellprice * $num_orders_per_invoice) for @{ $params{invoice}->items };
+
+    return;
+  }
+
+  my $num_invoices_in_cycle = $order_value_len / $billing_len;
+
+  foreach my $item (@{ $params{invoice}->items }) {
+    my $sellprice_one_invoice = $::form->round_amount($item->sellprice * $billing_len / $order_value_len, 2);
+
+    if ($is_last_invoice_in_cycle) {
+      $item->sellprice($item->sellprice - ($num_invoices_in_cycle - 1) * $sellprice_one_invoice);
+
+    } else {
+      $item->sellprice($sellprice_one_invoice);
+    }
+  }
 }
 
 sub _create_periodic_invoice {
+  $main::lxdebug->enter_sub();
+
   my $self              = shift;
   my $config            = shift;
   my $period_start_date = shift;
@@ -154,12 +202,14 @@ sub _create_periodic_invoice {
                                 employee     => $order->employee, # new_from sets employee to import user
                                );
 
-    map { _replace_vars($invoice, $time_period_vars, $_) } qw(notes intnotes transaction_description);
+    _replace_vars(object => $invoice, vars => $time_period_vars, attribute => $_, attribute_format => ($_ eq 'notes' ? 'html' : 'text')) for qw(notes intnotes transaction_description);
 
     foreach my $item (@{ $invoice->items }) {
-      map { _replace_vars($item, $time_period_vars, $_) } qw(description longdescription);
+      _replace_vars(object => $item, vars => $time_period_vars, attribute => $_, attribute_format => ($_ eq 'longdescription' ? 'html' : 'text')) for qw(description longdescription);
     }
 
+    _adjust_sellprices_for_period_lengths(invoice => $invoice, config => $config, period_start_date => $period_start_date);
+
     $invoice->post(ar_id => $config->ar_chart_id) || die;
 
     # like $form->add_shipto, but we don't need to check for a manual exception,
@@ -176,17 +226,34 @@ sub _create_periodic_invoice {
 
     $order->link_to_record($invoice);
 
+    foreach my $item (@{ $invoice->items }) {
+      foreach (qw(orderitems)) {    # expand if needed (delivery_order_items)
+          if ($item->{"converted_from_${_}_id"}) {
+            die unless $item->{id};
+            RecordLinks->create_links('mode'       => 'ids',
+                                      'from_table' => $_,
+                                      'from_ids'   => $item->{"converted_from_${_}_id"},
+                                      'to_table'   => 'invoice',
+                                      'to_id'      => $item->{id},
+            ) || die;
+            delete $item->{"converted_from_${_}_id"};
+         }
+      }
+    }
+
     SL::DB::PeriodicInvoice->new(config_id         => $config->id,
                                  ar_id             => $invoice->id,
                                  period_start_date => $period_start_date)
       ->save;
 
+    _log_msg("_create_invoice created for period start date $period_start_date id " . $invoice->id . " number " . $invoice->invnumber . " netamount " . $invoice->netamount . " amount " . $invoice->amount);
+
     # die $invoice->transaction_description;
   })) {
     $::lxdebug->message(LXDebug->WARN(), "_create_invoice failed: " . join("\n", (split(/\n/, $self->{db_obj}->db->error))[0..2]));
     return undef;
   }
-
+  $main::lxdebug->leave_sub();
   return $invoice;
 }
 
@@ -249,6 +316,14 @@ sub _print_invoice {
   $form->{OUT}          = $config->printer->printer_command;
   $form->{OUT_MODE}     = '|-';
 
+  $form->{TEMPLATE_DRIVER_OPTIONS} = {
+    variable_content_types => {
+      longdescription => 'html',
+      partnotes       => 'html',
+      notes           => 'html',
+    },
+  };
+
   $form->prepare_for_printing;
 
   $form->throw_on_error(sub {