<pagebreak> auch in der Langbeschreibung auswerten.
[kivitendo-erp.git] / SL / IS.pm
index 55203db..2363771 100644 (file)
--- a/SL/IS.pm
+++ b/SL/IS.pm
@@ -37,9 +37,13 @@ package IS;
 use List::Util qw(max);
 
 use SL::AM;
+use SL::ARAP;
+use SL::CVar;
 use SL::Common;
 use SL::DBUtils;
+use SL::DO;
 use SL::MoreCommon;
+use SL::IC;
 use Data::Dumper;
 
 sub invoice_details {
@@ -127,6 +131,10 @@ sub invoice_details {
   my $subtotal_header = 0;
   my $subposition = 0;
 
+  $form->{discount} = [];
+
+  IC->prepare_parts_for_printing();
+
   my @arrays =
     qw(runningnumber number description longdescription qty ship unit bin
        deliverydate_oe ordnumber_oe transdate_oe licensenumber validuntil
@@ -207,8 +215,11 @@ sub invoice_details {
       my ($dec)         = ($sellprice =~ /\.(\d+)/);
       my $decimalplaces = max 2, length($dec);
 
-      my $discount             = $form->round_amount($form->{"qty_$i"} * $sellprice * $form->{"discount_$i"} / 100 / $price_factor->{factor}, $decimalplaces);
-      my $linetotal            = $form->round_amount($form->{"qty_$i"} * $sellprice * (100 - $form->{"discount_$i"}) / 100 / $price_factor->{factor}, 2);
+      my $parsed_discount      = $form->parse_amount($myconfig, $form->{"discount_$i"});
+      my $linetotal_exact      =                     $form->{"qty_$i"} * $sellprice * (100 - $parsed_discount) / 100 / $price_factor->{factor};
+      my $linetotal            = $form->round_amount($linetotal_exact, 2);
+      my $discount             = $form->round_amount($form->{"qty_$i"} * $sellprice * $parsed_discount / 100 / $price_factor->{factor} - ($linetotal - $linetotal_exact),
+                                                     $decimalplaces);
       my $nodiscount_linetotal = $form->round_amount($form->{"qty_$i"} * $sellprice / $price_factor->{factor}, 2);
       $form->{"netprice_$i"}   = $form->round_amount($form->{"qty_$i"} ? ($linetotal / $form->{"qty_$i"}) : 0, 2);
 
@@ -216,7 +227,7 @@ sub invoice_details {
 
       $linetotal = ($linetotal != 0) ? $linetotal : '';
 
-      push @{ $form->{discount} },   ($discount  != 0) ? $form->format_amount($myconfig, $discount * -1, $decimalplaces) : '';
+      push @{ $form->{discount} },   ($discount  != 0) ? $form->format_amount($myconfig, $discount * -1, 2) : '';
       push @{ $form->{p_discount} }, $form->{"discount_$i"};
 
       $form->{total}            += $linetotal;
@@ -268,29 +279,25 @@ sub invoice_details {
 
       if ($form->round_amount($taxrate, 7) == 0) {
         if ($form->{taxincluded}) {
-          foreach $item (@taxaccounts) {
-            $taxamount =
-              $form->round_amount($linetotal * $form->{"${item}_rate"} /
-                                    (1 + abs($form->{"${item}_rate"})),
-                                  2);
+          foreach my $accno (@taxaccounts) {
+            $taxamount            = $form->round_amount($linetotal * $form->{"${accno}_rate"} / (1 + abs($form->{"${accno}_rate"})), 2);
 
-            $taxaccounts{$item} += $taxamount;
-            $taxdiff            += $taxamount;
+            $taxaccounts{$accno} += $taxamount;
+            $taxdiff             += $taxamount;
 
-            $taxbase{$item} += $taxbase;
+            $taxbase{$accno}     += $taxbase;
           }
           $taxaccounts{ $taxaccounts[0] } += $taxdiff;
         } else {
-          foreach $item (@taxaccounts) {
-            $taxaccounts{$item} += $linetotal * $form->{"${item}_rate"};
-            $taxbase{$item}     += $taxbase;
+          foreach my $accno (@taxaccounts) {
+            $taxaccounts{$accno} += $linetotal * $form->{"${accno}_rate"};
+            $taxbase{$accno}     += $taxbase;
           }
         }
       } else {
-        foreach $item (@taxaccounts) {
-          $taxaccounts{$item} +=
-            $taxamount * $form->{"${item}_rate"} / $taxrate;
-          $taxbase{$item} += $taxbase;
+        foreach my $accno (@taxaccounts) {
+          $taxaccounts{$accno} += $taxamount * $form->{"${accno}_rate"} / $taxrate;
+          $taxbase{$accno}     += $taxbase;
         }
       }
       $tax_rate = $taxrate * 100;
@@ -463,6 +470,12 @@ sub customer_details {
 
     map { $form->{"dv_$_"} = $ref->{$_} } keys %$ref;
   }
+
+  my $custom_variables = CVar->get_custom_variables('dbh'      => $dbh,
+                                                    'module'   => 'CT',
+                                                    'trans_id' => $form->{customer_id});
+  map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
+
   $dbh->disconnect;
 
   $main::lxdebug->leave_sub();
@@ -517,9 +530,7 @@ sub post_invoice {
   if ($form->{currency} eq $defaultcurrency) {
     $form->{exchangerate} = 1;
   } else {
-    $exchangerate =
-      $form->check_exchangerate($myconfig, $form->{currency},
-                                $form->{transdate}, 'buy');
+    $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy');
   }
 
   $form->{exchangerate} =
@@ -638,32 +649,11 @@ sub post_invoice {
 
       if ($form->{"inventory_accno_$i"} || $form->{"assembly_$i"}) {
 
-        # adjust parts onhand quantity
-
         if ($form->{"assembly_$i"}) {
-
-          # do not update if assembly consists of all services
-          $query =
-            qq|SELECT sum(p.inventory_accno_id)
-               FROM parts p
-               JOIN assembly a ON (a.parts_id = p.id)
-               WHERE a.id = ?|;
-          $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
-
-          if ($sth->fetchrow_array) {
-            $form->update_balance($dbh, "parts", "onhand", qq|id = ?|,
-                                  $baseqty * -1, $form->{"id_$i"})
-              unless $form->{shipped};
-          }
-          $sth->finish;
-
           # record assembly item as allocated
           &process_assembly($dbh, $form, $form->{"id_$i"}, $baseqty);
-        } else {
-          $form->update_balance($dbh, "parts", "onhand", qq|id = ?|,
-                                $baseqty * -1, $form->{"id_$i"})
-            unless $form->{shipped};
 
+        } else {
           $allocated = &cogs($dbh, $form, $form->{"id_$i"}, $baseqty, $basefactor, $i);
         }
       }
@@ -687,7 +677,7 @@ sub post_invoice {
                  $form->{"description_$i"}, $form->{"longdescription_$i"}, $form->{"qty_$i"},
                  $form->{"sellprice_$i"}, $fxsellprice,
                  $form->{"discount_$i"}, $allocated, 'f',
-                 $form->{"unit_$i"}, conv_date($form->{"deliverydate_$i"}), conv_i($form->{"project_id_$i"}),
+                 $form->{"unit_$i"}, conv_date($form->{"reqdate_$i"}), conv_i($form->{"project_id_$i"}),
                  $form->{"serialnumber_$i"}, conv_i($pricegroup_id),
                  $form->{"ordnumber_$i"}, conv_date($form->{"transdate_$i"}),
                  $form->{"cusordnumber_$i"}, $baseqty, $form->{"subtotal_$i"} ? 't' : 'f',
@@ -834,13 +824,8 @@ sub post_invoice {
       if ($form->{currency} eq $defaultcurrency) {
         $form->{"exchangerate_$i"} = 1;
       } else {
-        $exchangerate =
-          $form->check_exchangerate($myconfig, $form->{currency},
-                                    $form->{"datepaid_$i"}, 'buy');
-
-        $form->{"exchangerate_$i"} =
-          $exchangerate ? $exchangerate
-            : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
+        $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
+        $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
       }
 
       # record AR
@@ -990,6 +975,36 @@ sub post_invoice {
 
   Common::webdav_folder($form) if ($main::webdav);
 
+  # Link this record to the records it was created from.
+  RecordLinks->create_links('dbh'        => $dbh,
+                            'mode'       => 'ids',
+                            'from_table' => 'oe',
+                            'from_ids'   => $form->{convert_from_oe_ids},
+                            'to_table'   => 'ar',
+                            'to_id'      => $form->{id},
+    );
+  delete $form->{convert_from_oe_ids};
+
+  my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
+
+  if (scalar @convert_from_do_ids) {
+    DO->close_orders('dbh' => $dbh,
+                     'ids' => \@convert_from_do_ids);
+
+    RecordLinks->create_links('dbh'        => $dbh,
+                              'mode'       => 'ids',
+                              'from_table' => 'delivery_orders',
+                              'from_ids'   => \@convert_from_do_ids,
+                              'to_table'   => 'ar',
+                              'to_id'      => $form->{id},
+      );
+  }
+  delete $form->{convert_from_do_ids};
+
+  ARAP->close_orders_if_billed('dbh'     => $dbh,
+                               'arap_id' => $form->{id},
+                               'table'   => 'ar',);
+
   my $rc = 1;
   if (!$provided_dbh) {
     $dbh->commit();
@@ -1229,18 +1244,7 @@ sub reverse_invoice {
 
   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
-    if ($ref->{inventory_accno_id} || $ref->{assembly}) {
-
-      # if the invoice item is not an assemblyitem adjust parts onhand
-      if (!$ref->{assemblyitem}) {
-
-        # adjust onhand in parts table
-        $form->update_balance($dbh, "parts", "onhand", qq|id = $ref->{parts_id}|, $ref->{qty});
-      }
-
-      # loop if it is an assembly
-      next if ($ref->{assembly});
-
+    if ($ref->{inventory_accno_id}) {
       # de-allocated purchases
       $query =
         qq|SELECT i.id, i.trans_id, i.allocated
@@ -1405,7 +1409,7 @@ sub retrieve_invoice {
            c2.accno AS income_accno,    c2.new_chart_id AS income_new_chart,    date($transdate) - c2.valid_from as income_valid,
            c3.accno AS expense_accno,   c3.new_chart_id AS expense_new_chart,   date($transdate) - c3.valid_from AS expense_valid,
 
-           i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.discount, i.parts_id AS id, i.unit, i.deliverydate,
+           i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.discount, i.parts_id AS id, i.unit, i.deliverydate AS reqdate,
            i.project_id, i.serialnumber, i.id AS invoice_pos, i.pricegroup_id, i.ordnumber, i.transdate, i.cusordnumber, i.subtotal, i.lastcost,
            i.price_factor_id, i.price_factor, i.marge_price_factor,
            p.partnumber, p.assembly, p.bin, p.notes AS partnotes, p.inventory_accno_id AS part_inventory_accno_id, p.formel,
@@ -1513,11 +1517,17 @@ sub get_customer {
   }
 
   my $cid = conv_i($form->{customer_id});
+  my $payment_id;
+
+  if ($form->{payment_id}) {
+    $payment_id = "(pt.id = ?) OR";
+    push @values, conv_i($form->{payment_id});
+  }
 
   # get customer
   $query =
     qq|SELECT
-         c.name AS customer, c.discount, c.creditlimit, c.terms,
+         c.id AS customer_id, c.name AS customer, c.discount, c.creditlimit, c.terms,
          c.email, c.cc, c.bcc, c.language_id, c.payment_id,
          c.street, c.zipcode, c.city, c.country,
          c.notes AS intnotes, c.klass as customer_klass, c.taxzone_id, c.salesman_id,
@@ -1525,7 +1535,7 @@ sub get_customer {
          b.discount AS tradediscount, b.description AS business
        FROM customer c
        LEFT JOIN business b ON (b.id = c.business_id)
-       LEFT JOIN payment_terms pt ON (c.payment_id = pt.id)
+       LEFT JOIN payment_terms pt ON ($payment_id (c.payment_id = pt.id))
        WHERE c.id = ?|;
   push @values, $cid;
   $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
@@ -1812,6 +1822,8 @@ sub retrieve_item {
       }
     }
 
+    $ref->{onhand} *= 1;
+
     push @{ $form->{item_list} }, $ref;
 
     if ($form->{lizenzen}) {
@@ -1852,8 +1864,6 @@ sub get_pricegroups_for_parts {
 
   my $i  = 1;
   my $id = 0;
-  my $dimension_units = AM->retrieve_units($myconfig, $form, "dimension");
-  my $service_units = AM->retrieve_units($myconfig, $form, "service");
   my $all_units = AM->retrieve_units($myconfig, $form);
   while (($form->{"id_$i"}) or ($form->{"new_id_$i"})) {
     $form->{"PRICES"}{$i} = [];
@@ -1886,9 +1896,8 @@ sub get_pricegroups_for_parts {
     # vergleichen und bei Unterschied den Preis entsprechend umrechnen.
     $form->{"selected_unit_$i"} = $form->{"unit_$i"} unless ($form->{"selected_unit_$i"});
 
-    my $check_units = $form->{"inventory_accno_$i"} ? $dimension_units : $service_units;
-    if (!$check_units->{$form->{"selected_unit_$i"}} ||
-        ($check_units->{$form->{"selected_unit_$i"}}->{"base_unit"} ne
+    if (!$all_units->{$form->{"selected_unit_$i"}} ||
+        ($all_units->{$form->{"selected_unit_$i"}}->{"base_unit"} ne
          $all_units->{$form->{"unit_old_$i"}}->{"base_unit"})) {
       # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
       # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber