epic-s6ts
[kivitendo-erp.git] / SL / DO.pm
index a37e516..ebc6051 100644 (file)
--- a/SL/DO.pm
+++ b/SL/DO.pm
@@ -25,7 +25,8 @@
 # GNU General Public License for more details.
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, write to the Free Software
-# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+# MA 02110-1335, USA.
 #======================================================================
 #
 # Delivery Order entry module
 
 package DO;
 
+use Carp;
 use List::Util qw(max);
-use YAML;
+use Text::ParseWords;
 
 use SL::AM;
 use SL::Common;
 use SL::CVar;
 use SL::DB::DeliveryOrder;
+use SL::DB::DeliveryOrder::TypeData qw(:types is_valid_type);
 use SL::DB::Status;
 use SL::DBUtils;
+use SL::Helper::ShippedQty;
 use SL::HTML::Restrict;
 use SL::RecordLinks;
 use SL::IC;
 use SL::TransNumber;
+use SL::DB;
+use SL::Util qw(trim);
+use SL::YAML;
 
 use strict;
 
@@ -67,11 +74,13 @@ sub transactions {
   my $query =
     qq|SELECT dord.id, dord.donumber, dord.ordnumber, dord.cusordnumber,
          dord.transdate, dord.reqdate,
-         ct.${vc}number, ct.name, dord.${vc}_id, dord.globalproject_id,
+         ct.${vc}number, ct.name, ct.business_id,
+         dord.${vc}_id, dord.globalproject_id,
          dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
-         dord.transaction_description,
+         dord.transaction_description, dord.itime::DATE AS insertdate,
          pr.projectnumber AS globalprojectnumber,
          dep.description AS department,
+         dord.order_type,
          e.name AS employee,
          sm.name AS salesman
        FROM delivery_orders dord
@@ -83,7 +92,10 @@ sub transactions {
        LEFT JOIN department dep ON (dord.department_id = dep.id)
 |;
 
-  push @where, ($form->{type} eq 'sales_delivery_order' ? '' : 'NOT ') . qq|COALESCE(dord.is_sales, FALSE)|;
+  if ($form->{type} && is_valid_type($form->{type})) {
+    push @where, 'dord.order_type = ?';
+    push @values, $form->{type};
+  }
 
   if ($form->{department_id}) {
     push @where,  qq|dord.department_id = ?|;
@@ -98,18 +110,23 @@ sub transactions {
     push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
   }
 
+  if ($form->{"business_id"}) {
+    push @where,  qq|ct.business_id = ?|;
+    push @values, conv_i($form->{"business_id"});
+  }
+
   if ($form->{"${vc}_id"}) {
     push @where,  qq|dord.${vc}_id = ?|;
     push @values, $form->{"${vc}_id"};
 
   } elsif ($form->{$vc}) {
     push @where,  qq|ct.name ILIKE ?|;
-    push @values, '%' . $form->{$vc} . '%';
+    push @values, like($form->{$vc});
   }
 
   if ($form->{"cp_name"}) {
     push @where, "(cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
-    push @values, ('%' . $form->{"cp_name"} . '%')x2;
+    push @values, (like($form->{"cp_name"}))x2;
   }
 
   foreach my $item (qw(employee_id salesman_id)) {
@@ -117,15 +134,16 @@ sub transactions {
     push @where, "dord.$item = ?";
     push @values, conv_i($form->{$item});
   }
-  if (!$main::auth->assert('sales_all_edit', 1)) {
+  if ( !(    ($vc eq 'customer' && ($main::auth->assert('sales_all_edit',    1) || $main::auth->assert('sales_delivery_order_view',    1)))
+          || ($vc eq 'vendor'   && ($main::auth->assert('purchase_all_edit', 1) || $main::auth->assert('purchase_delivery_order_view', 1))) ) ) {
     push @where, qq|dord.employee_id = (select id from employee where login= ?)|;
-    push @values, $form->{login};
+    push @values, $::myconfig{login};
   }
 
   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
     next unless ($form->{$item});
     push @where,  qq|dord.$item ILIKE ?|;
-    push @values, '%' . $form->{$item} . '%';
+    push @values, like($form->{$item});
   }
 
   if (($form->{open} || $form->{closed}) &&
@@ -140,7 +158,7 @@ sub transactions {
 
   if ($form->{serialnumber}) {
     push @where, 'dord.id IN (SELECT doi.delivery_order_id FROM delivery_order_items doi WHERE doi.serialnumber LIKE ?)';
-    push @values, '%' . $form->{serialnumber} . '%';
+    push @values, like($form->{serialnumber});
   }
 
   if($form->{transdatefrom}) {
@@ -163,6 +181,54 @@ sub transactions {
     push @values, conv_date($form->{reqdateto});
   }
 
+  if($form->{insertdatefrom}) {
+    push @where, qq|dord.itime::DATE >= ?|;
+    push@values, conv_date($form->{insertdatefrom});
+  }
+
+  if($form->{insertdateto}) {
+    push @where, qq|dord.itime::DATE <= ?|;
+    push @values, conv_date($form->{insertdateto});
+  }
+
+  if ($form->{parts_partnumber}) {
+    push @where, <<SQL;
+      EXISTS (
+        SELECT delivery_order_items.delivery_order_id
+        FROM delivery_order_items
+        LEFT JOIN parts ON (delivery_order_items.parts_id = parts.id)
+        WHERE (delivery_order_items.delivery_order_id = dord.id)
+          AND (parts.partnumber ILIKE ?)
+        LIMIT 1
+      )
+SQL
+    push @values, like($form->{parts_partnumber});
+  }
+
+  if ($form->{parts_description}) {
+    push @where, <<SQL;
+      EXISTS (
+        SELECT delivery_order_items.delivery_order_id
+        FROM delivery_order_items
+        WHERE (delivery_order_items.delivery_order_id = dord.id)
+          AND (delivery_order_items.description ILIKE ?)
+        LIMIT 1
+      )
+SQL
+    push @values, like($form->{parts_description});
+  }
+
+  if ($form->{all}) {
+    my @tokens = parse_line('\s+', 0, $form->{all});
+    # ordnumber quonumber customer.name vendor.name transaction_description
+    push @where, <<SQL for @tokens;
+      (   (dord.donumber                ILIKE ?)
+       OR (ct.name                      ILIKE ?)
+       OR (dord.transaction_description ILIKE ?))
+SQL
+    push @values, (like($_))x3 for @tokens;
+  }
+
   if (@where) {
     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
   }
@@ -179,6 +245,7 @@ sub transactions {
     "shipvia"                 => "dord.shipvia",
     "transaction_description" => "dord.transaction_description",
     "department"              => "lower(dep.description)",
+    "insertdate"              => "dord.itime",
   );
 
   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
@@ -214,6 +281,16 @@ sub transactions {
 }
 
 sub save {
+  my ($self) = @_;
+  $main::lxdebug->enter_sub();
+
+  my $rc = SL::DB->client->with_transaction(\&_save, $self);
+
+  $main::lxdebug->leave_sub();
+  return $rc;
+}
+
+sub _save {
   $main::lxdebug->enter_sub();
 
   my ($self)   = @_;
@@ -221,8 +298,7 @@ sub save {
   my $myconfig = \%main::myconfig;
   my $form     = $main::form;
 
-  # connect to database, turn off autocommit
-  my $dbh = $form->get_standard_dbh($myconfig);
+  my $dbh = SL::DB->client->dbh;
   my $restricter = SL::HTML::Restrict->create;
 
   my ($query, @values, $sth, $null);
@@ -240,13 +316,15 @@ sub save {
 
   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
 
-  if ($form->{id}) {
+  my (@processed_doi, @processed_dois);
 
-    $query = qq|DELETE FROM delivery_order_items_stock WHERE delivery_order_item_id IN (SELECT id FROM delivery_order_items WHERE delivery_order_id = ?)|;
-    do_query($form, $dbh, $query, conv_i($form->{id}));
+  if ($form->{id}) {
 
-    $query = qq|DELETE FROM delivery_order_items WHERE delivery_order_id = ?|;
-    do_query($form, $dbh, $query, conv_i($form->{id}));
+    # only delete shipto complete
+    $query = qq|DELETE FROM custom_variables
+                WHERE (config_id IN (SELECT id        FROM custom_variable_configs WHERE (module = 'ShipTo')))
+                  AND (trans_id  IN (SELECT shipto_id FROM shipto                  WHERE (module = 'DO') AND (trans_id = ?)))|;
+    do_query($form, $dbh, $query, $form->{id});
 
     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
     do_query($form, $dbh, $query, conv_i($form->{id}));
@@ -256,15 +334,15 @@ sub save {
     $query = qq|SELECT nextval('id')|;
     ($form->{id}) = selectrow_query($form, $dbh, $query);
 
-    $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id, currency_id, taxzone_id) VALUES (?, '', ?, (SELECT currency_id FROM defaults LIMIT 1), ?)|;
-    do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}), $form->{taxzone_id});
+    $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id, currency_id, taxzone_id, order_type) VALUES (?, '', ?, (SELECT currency_id FROM defaults LIMIT 1), ?, ?)|;
+    do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}), $form->{taxzone_id}, SALES_DELIVERY_ORDER_TYPE);
   }
 
   my $project_id;
   my $items_reqdate;
 
   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
-  my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
+  my %price_factors = map { $_->{id} => $_->{factor} *1 } @{ $form->{ALL_PRICE_FACTORS} };
   my $price_factor;
 
   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
@@ -275,24 +353,22 @@ sub save {
     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
   }
-
-  my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
-  my $h_item_id = prepare_query($form, $dbh, $q_item_id);
-
-  my $q_item =
-    qq|INSERT INTO delivery_order_items (
-         id, delivery_order_id, parts_id, description, longdescription, qty, base_qty,
-         sellprice, discount, unit, reqdate, project_id, serialnumber,
-         ordnumber, transdate, cusordnumber,
-         lastcost, price_factor_id, price_factor, marge_price_factor, pricegroup_id,
-         active_price_source)
-       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
-         (SELECT factor FROM price_factors WHERE id = ?), ?, ?, ?)|;
+  my $q_item = <<SQL;
+    UPDATE delivery_order_items SET
+       delivery_order_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
+       sellprice = ?, discount = ?, unit = ?, reqdate = ?, project_id = ?, serialnumber = ?,
+       lastcost = ? , price_factor_id = ?, price_factor = (SELECT factor FROM price_factors where id = ?),
+       marge_price_factor = ?, pricegroup_id = ?, active_price_source = ?, active_discount_source = ?
+    WHERE id = ?
+SQL
   my $h_item = prepare_query($form, $dbh, $q_item);
 
-  my $q_item_stock =
-    qq|INSERT INTO delivery_order_items_stock (delivery_order_item_id, qty, unit, warehouse_id, bin_id, chargenumber, bestbefore)
-       VALUES (?, ?, ?, ?, ?, ?, ?)|;
+  my $q_item_stock = <<SQL;
+    UPDATE delivery_order_items_stock SET
+      delivery_order_item_id = ?, qty = ?,  unit = ?,  warehouse_id = ?,
+      bin_id = ?, chargenumber = ?, bestbefore = ?
+    WHERE id = ?
+SQL
   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
 
   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
@@ -300,6 +376,26 @@ sub save {
   for my $i (1 .. $form->{rowcount}) {
     next if (!$form->{"id_$i"});
 
+    CVar->get_non_editable_ic_cvars(form               => $form,
+                                    dbh                => $dbh,
+                                    row                => $i,
+                                    sub_module         => 'delivery_order_items',
+                                    may_converted_from => ['orderitems', 'delivery_order_items']);
+
+    my $position = $i;
+
+    if (!$form->{"delivery_order_items_id_$i"}) {
+      # there is no persistent id, therefore create one with all necessary constraints
+      my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
+      my $h_item_id = prepare_query($form, $dbh, $q_item_id);
+      do_statement($form, $h_item_id, $q_item_id);
+      $form->{"delivery_order_items_id_$i"}  = $h_item_id->fetchrow_array();
+      $query = qq|INSERT INTO delivery_order_items (id, delivery_order_id, position, parts_id) VALUES (?, ?, ?, ?)|;
+      do_query($form, $dbh, $query, conv_i($form->{"delivery_order_items_id_$i"}),
+                conv_i($form->{"id"}), conv_i($position), conv_i($form->{"id_$i"}));
+      $h_item_id->finish();
+    }
+
     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
     my $item_unit = $part_unit_map{$form->{"id_$i"}};
@@ -320,8 +416,6 @@ sub save {
 
     $items_reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
 
-    do_statement($form, $h_item_id, $q_item_id);
-    my ($item_id) = $h_item_id->fetchrow_array();
 
     # Get pricegroup_id and save it. Unfortunately the interface
     # also uses ID "0" for signalling that none is selected, but "0"
@@ -331,40 +425,88 @@ sub save {
     $pricegroup_id    = undef if !$pricegroup_id;
 
     # save detail record in delivery_order_items table
-    @values = (conv_i($item_id), conv_i($form->{id}), conv_i($form->{"id_$i"}),
+    @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
                $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}),
                $form->{"qty_$i"}, $baseqty,
                $form->{"sellprice_$i"}, $form->{"discount_$i"} / 100,
                $form->{"unit_$i"}, conv_date($items_reqdate), conv_i($form->{"project_id_$i"}),
                $form->{"serialnumber_$i"},
-               $form->{"ordnumber_$i"}, conv_date($form->{"transdate_$i"}),
-               $form->{"cusordnumber_$i"},
                $form->{"lastcost_$i"},
                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
                conv_i($form->{"marge_price_factor_$i"}),
                $pricegroup_id,
-               $form->{"active_price_source_$i"});
+               $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
+               conv_i($form->{"delivery_order_items_id_$i"}));
     do_statement($form, $h_item, $q_item, @values);
+    push @processed_doi, $form->{"delivery_order_items_id_$i"}; # transaction safe?
 
     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
     foreach my $sinfo (@{ $stock_info }) {
-      @values = ($item_id, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
-                 conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}));
+      # if we have stock_info, we have to check for persistents entries
+      if (!$sinfo->{"delivery_order_items_stock_id"}) {
+        my $q_item_stock_id = qq|SELECT nextval('id')|;
+        my $h_item_stock_id = prepare_query($form, $dbh, $q_item_stock_id);
+        do_statement($form, $h_item_stock_id, $q_item_stock_id);
+        $sinfo->{"delivery_order_items_stock_id"} = $h_item_stock_id->fetchrow_array();
+        $query = qq|INSERT INTO delivery_order_items_stock (id, delivery_order_item_id, qty, unit, warehouse_id, bin_id)
+                    VALUES (?, ?, ?, ?, ?, ?)|;
+        do_query($form, $dbh, $query, conv_i($sinfo->{"delivery_order_items_stock_id"}),
+                  conv_i($form->{"delivery_order_items_id_$i"}), $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
+                  conv_i($sinfo->{bin_id}));
+        $h_item_stock_id->finish();
+        # write back the id to the form (important if only transfer was clicked (id fk for invoice)
+        $form->{"stock_${in_out}_$i"} = SL::YAML::Dump($stock_info);
+      }
+      @values = ($form->{"delivery_order_items_id_$i"}, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
+                 conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}),
+                 conv_i($sinfo->{"delivery_order_items_stock_id"}));
       do_statement($form, $h_item_stock, $q_item_stock, @values);
+      push @processed_dois, $sinfo->{"delivery_order_items_stock_id"};
     }
 
     CVar->save_custom_variables(module       => 'IC',
                                 sub_module   => 'delivery_order_items',
-                                trans_id     => $item_id,
+                                trans_id     => $form->{"delivery_order_items_id_$i"},
                                 configs      => $ic_cvar_configs,
                                 variables    => $form,
                                 name_prefix  => 'ic_',
                                 name_postfix => "_$i",
                                 dbh          => $dbh);
+
+    # link order items with doi, for future extension look at foreach IS.pm
+    if (!$form->{saveasnew} && $form->{"converted_from_orderitems_id_$i"}) {
+      RecordLinks->create_links('dbh'        => $dbh,
+                                'mode'       => 'ids',
+                                'from_table' => 'orderitems',
+                                'from_ids'   => $form->{"converted_from_orderitems_id_$i"},
+                                'to_table'   => 'delivery_order_items',
+                                'to_id'      =>  $form->{"delivery_order_items_id_$i"},
+      );
+    }
+    delete $form->{"converted_from_orderitems_id_$i"};
   }
 
-  $h_item_id->finish();
+  # 1. search for orphaned dois; processed_dois may be empty (no transfer) TODO: be supersafe and alter same statement for doi and oi
+  $query  = sprintf 'SELECT id FROM delivery_order_items_stock WHERE delivery_order_item_id in
+                      (select id from delivery_order_items where delivery_order_id = ?)';
+  $query .= sprintf ' AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_dois if (scalar @processed_dois);
+  @values = (conv_i($form->{id}), map { conv_i($_) } @processed_dois);
+  my @orphaned_dois_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
+  if (scalar @orphaned_dois_ids) {
+    # clean up delivery_order_items_stock
+    $query  = sprintf 'DELETE FROM delivery_order_items_stock WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_dois_ids;
+    do_query($form, $dbh, $query, @orphaned_dois_ids);
+  }
+  # 2. search for orphaned doi
+  $query  = sprintf 'SELECT id FROM delivery_order_items WHERE delivery_order_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_doi;
+  @values = (conv_i($form->{id}), map { conv_i($_) } @processed_doi);
+  my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
+  if (scalar @orphaned_ids) {
+    # clean up delivery_order_items
+    $query  = sprintf 'DELETE FROM delivery_order_items WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
+    do_query($form, $dbh, $query, @orphaned_ids);
+  }
   $h_item->finish();
   $h_item_stock->finish();
 
@@ -375,30 +517,32 @@ sub save {
   $query =
     qq|UPDATE delivery_orders SET
          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
-         customer_id = ?, reqdate = ?,
+         customer_id = ?, reqdate = ?, tax_point = ?,
          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
-         delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
+         delivered = ?, department_id = ?, language_id = ?, shipto_id = ?, billing_address_id = ?,
          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
-         is_sales = ?, taxzone_id = ?, taxincluded = ?, terms = ?, currency_id = (SELECT id FROM currencies WHERE name = ?),
+         order_type = ?, taxzone_id = ?, taxincluded = ?, payment_id = ?, currency_id = (SELECT id FROM currencies WHERE name = ?),
          delivery_term_id = ?
        WHERE id = ?|;
 
   @values = ($form->{donumber}, $form->{ordnumber},
              $form->{cusordnumber}, conv_date($form->{transdate}),
              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
-             conv_date($form->{reqdate}), $form->{shippingpoint}, $form->{shipvia},
-             $form->{notes}, $form->{intnotes},
+             conv_date($form->{reqdate}), conv_date($form->{tax_point}), $form->{shippingpoint}, $form->{shipvia},
+             $restricter->process($form->{notes}), $form->{intnotes},
              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
-             conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
+             conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}), conv_i($form->{billing_address_id}),
              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
              $form->{transaction_description},
-             $form->{type} =~ /^sales/ ? 't' : 'f',
-             conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{terms}), $form->{currency},
+             $form->{type} =~ /^sales/ ? SALES_DELIVERY_ORDER_TYPE : PURCHASE_DELIVERY_ORDER_TYPE,
+             conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{payment_id}), $form->{currency},
              conv_i($form->{delivery_term_id}),
              conv_i($form->{id}));
   do_query($form, $dbh, $query, @values);
 
+  $form->new_lastmtime('delivery_orders');
+
   $form->{name} = $form->{ $form->{vc} };
   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
 
@@ -419,12 +563,10 @@ sub save {
                             'to_id'      => $form->{id},
     );
   delete $form->{convert_from_oe_ids};
-
-  $self->mark_orders_if_delivered('do_id' => $form->{id},
-                                  'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
-                                  'dbh'   => $dbh,);
-
-  my $rc = $dbh->commit();
+  unless ($::instance_conf->get_shipped_qty_require_stock_out) {
+    $self->mark_orders_if_delivered('do_id' => $form->{id},
+                                    'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase');
+  }
 
   $form->{saved_donumber} = $form->{donumber};
   $form->{saved_ordnumber} = $form->{ordnumber};
@@ -434,74 +576,28 @@ sub save {
 
   $main::lxdebug->leave_sub();
 
-  return $rc;
+  return 1;
 }
 
 sub mark_orders_if_delivered {
-  $main::lxdebug->enter_sub();
-
-  my $self   = shift;
-  my %params = @_;
+  my ($self, %params) = @_;
 
   Common::check_params(\%params, qw(do_id type));
 
-  my $myconfig = \%main::myconfig;
-  my $form     = $main::form;
-
-  my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
-
-  my @links    = RecordLinks->get_links('dbh'        => $dbh,
-                                        'from_table' => 'oe',
-                                        'to_table'   => 'delivery_orders',
-                                        'to_id'      => $params{do_id});
-
-  my $oe_id  = @links ? $links[0]->{from_id} : undef;
-
-  return $main::lxdebug->leave_sub() if (!$oe_id);
+  my $do     = SL::DB::Manager::DeliveryOrder->find_by(id => $params{do_id});
+  my $orders = $do->linked_records(from => 'Order');
 
-  my $all_units = AM->retrieve_all_units();
+  SL::Helper::ShippedQty->new->calculate($orders)->write_to_objects;
 
-  my $query     = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
-                     FROM orderitems oi
-                     LEFT JOIN parts p ON (oi.parts_id = p.id)
-                     WHERE (oi.trans_id = ?)|;
-  my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
+  SL::DB->client->with_transaction(sub {
+    for my $oe (@$orders) {
+      next if $params{type} eq 'sales'    && !$oe->customer_id;
+      next if $params{type} eq 'purchase' && !$oe->vendor_id;
 
-  my %shipped   = $self->get_shipped_qty('type'  => $params{type},
-                                         'oe_id' => $oe_id,);
-  my %ordered   = ();
-
-  while (my $ref = $sth->fetchrow_hashref()) {
-    $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
-
-    if ($ordered{$ref->{parts_id}}) {
-      $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
-    } else {
-      $ordered{$ref->{parts_id}}             = $ref;
-    }
-  }
-
-  $sth->finish();
-
-  map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
-
-  my $delivered = 1;
-  foreach my $part (values %ordered) {
-    if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
-      $delivered = 0;
-      last;
+      $oe->update_attributes(delivered => $oe->{delivered});
     }
-  }
-
-  if ($delivered) {
-    $query = qq|UPDATE oe
-                SET delivered = TRUE
-                WHERE id = ?|;
-    do_query($form, $dbh, $query, $oe_id);
-    $dbh->commit() if (!$params{dbh});
-  }
-
-  $main::lxdebug->leave_sub();
+    1;
+  }) or do { die SL::DB->client->error };
 }
 
 sub close_orders {
@@ -520,13 +616,16 @@ sub close_orders {
   my $myconfig = \%main::myconfig;
   my $form     = $main::form;
 
-  my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
+  SL::DB->client->with_transaction(sub {
+    my $dbh      = $params{dbh} || SL::DB->client->dbh;
 
-  my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
+    my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
 
-  do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
+    do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
+    1;
+  }) or die { SL::DB->client->error };
 
-  $dbh->commit() unless ($params{dbh});
+  $form->new_lastmtime('delivery_orders');
 
   $main::lxdebug->leave_sub();
 }
@@ -556,6 +655,38 @@ sub delete {
   return $rc;
 }
 
+sub delete_transfers {
+  $main::lxdebug->enter_sub();
+
+  my ($self)   = @_;
+
+  my $myconfig = \%main::myconfig;
+  my $form     = $main::form;
+
+  my $rc = SL::DB::Order->new->db->with_transaction(sub {
+
+    my $do = SL::DB::DeliveryOrder->new(id => $form->{id})->load;
+    die "No valid delivery order found" unless ref $do eq 'SL::DB::DeliveryOrder';
+
+    my $dt = DateTime->today->subtract(days => $::instance_conf->get_undo_transfer_interval);
+    croak "Wrong call. Please check undoing interval" unless $do->itime > $dt;
+
+    foreach my $doi (@{ $do->orderitems }) {
+      foreach my $dois (@{ $doi->delivery_order_stock_entries}) {
+        $dois->inventory->delete;
+        $dois->delete;
+      }
+    }
+    $do->update_attributes(delivered => 0);
+
+    1;
+  });
+
+  $main::lxdebug->leave_sub();
+
+  return $rc;
+}
+
 sub retrieve {
   $main::lxdebug->enter_sub();
 
@@ -600,16 +731,17 @@ sub retrieve {
   # so if any of these infos is important (or even different) for any item,
   # it will be killed out and then has to be fetched from the item scope query further down
   $query =
-    qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
+    qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate, dord.tax_point,
          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
          e.name AS employee, dord.employee_id, dord.salesman_id,
          dord.${vc}_id, cv.name AS ${vc},
          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
          d.description AS department, dord.language_id,
-         dord.shipto_id,
+         dord.shipto_id, dord.billing_address_id,
+         dord.itime, dord.mtime,
          dord.globalproject_id, dord.delivered, dord.transaction_description,
-         dord.taxzone_id, dord.taxincluded, dord.terms, (SELECT cu.name FROM currencies cu WHERE cu.id=dord.currency_id) AS currency,
-         dord.delivery_term_id
+         dord.taxzone_id, dord.taxincluded, dord.payment_id, (SELECT cu.name FROM currencies cu WHERE cu.id=dord.currency_id) AS currency,
+         dord.delivery_term_id, dord.itime::DATE AS insertdate
        FROM delivery_orders dord
        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
        LEFT JOIN employee e ON (dord.employee_id = e.id)
@@ -641,7 +773,8 @@ sub retrieve {
     }
   }
   $sth->finish();
-
+  $form->{mtime}   ||= $form->{itime};
+  $form->{lastmtime} = $form->{mtime};
   $form->{donumber_array} =~ s/\s*$//g;
   $form->{ordnumber_array} =~ s/ //;
   $form->{ordnumber_array} =~ s/\s*$//g;
@@ -660,10 +793,18 @@ sub retrieve {
     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
 
     $ref   = $sth->fetchrow_hashref("NAME_lc");
-    delete $ref->{id};
-    map { $form->{$_} = $ref->{$_} } keys %$ref;
+    $form->{$_} = $ref->{$_} for grep { m{^shipto(?!_id$)} } keys %$ref;
     $sth->finish();
 
+    if ($ref->{shipto_id}) {
+      my $cvars = CVar->get_custom_variables(
+        dbh      => $dbh,
+        module   => 'ShipTo',
+        trans_id => $ref->{shipto_id},
+      );
+      $form->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
+    }
+
     # get printed, emailed and queued
     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
@@ -685,12 +826,12 @@ sub retrieve {
   # stuff different from the whole will not be overwritten, but saved with a suffix.
   $query =
     qq|SELECT doi.id AS delivery_order_items_id,
-         p.partnumber, p.assembly, p.listprice, doi.description, doi.qty,
+         p.partnumber, p.part_type, p.listprice, doi.description, doi.qty,
          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.notes AS partnotes,
          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
          doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
-         doi.active_price_source,
+         doi.active_price_source, doi.active_discount_source,
          pr.projectnumber, dord.transdate AS dord_transdate, dord.donumber,
          pg.partsgroup
        FROM delivery_order_items doi
@@ -699,7 +840,7 @@ sub retrieve {
        LEFT JOIN project pr ON (doi.project_id = pr.id)
        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
-       ORDER BY doi.oid|;
+       ORDER BY doi.delivery_order_id, doi.position|;
 
   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
@@ -717,7 +858,8 @@ sub retrieve {
     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
     $query =
-      qq|SELECT qty, unit, bin_id, warehouse_id, chargenumber, bestbefore
+      qq|SELECT id as delivery_order_items_stock_id, qty, unit, bin_id,
+                warehouse_id, chargenumber, bestbefore
          FROM delivery_order_items_stock
          WHERE delivery_order_item_id = ?|;
     my $sth = prepare_query($form, $dbh, $query);
@@ -729,7 +871,7 @@ sub retrieve {
         push @{ $requests }, $ref;
       }
 
-      $doi->{"stock_${in_out}"} = YAML::Dump($requests);
+      $doi->{"stock_${in_out}"} = SL::YAML::Dump($requests);
     }
 
     $sth->finish();
@@ -810,24 +952,28 @@ sub order_details {
   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
   my $project_cvar_configs = CVar->get_configs(module => 'Projects');
 
+  # get some values of parts from db on store them in extra array,
+  # so that they can be sorted in later
+  my %prepared_template_arrays = IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
+  my @prepared_arrays          = keys %prepared_template_arrays;
+
   $form->{TEMPLATE_ARRAYS} = { };
-  IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
 
   my @arrays =
-    qw(runningnumber number description longdescription qty unit
+    qw(runningnumber number description longdescription qty qty_nofmt unit
        partnotes serialnumber reqdate projectnumber projectdescription
-       weight lineweight
+       weight weight_nofmt lineweight lineweight_nofmt
        si_runningnumber si_number si_description
        si_warehouse si_bin si_chargenumber si_bestbefore
        si_qty si_qty_nofmt si_unit);
 
-  map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays);
+  map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays, @prepared_arrays);
 
   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
   push @arrays, map { "project_cvar_$_->{name}" } @{ $project_cvar_configs };
 
   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
-  my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
+  my %price_factors = map { $_->{id} => $_->{factor} *1 } @{ $form->{ALL_PRICE_FACTORS} };
 
   my $totalweight = 0;
   my $sameitem = "";
@@ -837,10 +983,13 @@ sub order_details {
     next if (!$form->{"id_$i"});
 
     if ($item->[1] ne $sameitem) {
-      push(@{ $form->{description} }, qq|$item->[1]|);
+      push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'partsgroup');
+      push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, qq|$item->[1]|);
       $sameitem = $item->[1];
 
-      map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
+      map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
+      map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
+      $si_position++;
     }
 
     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
@@ -865,6 +1014,9 @@ sub order_details {
     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
     my $project = $projects_by_id{$form->{"project_id_$i"}} || SL::DB::Project->new;
 
+    push(@{ $form->{TEMPLATE_ARRAYS}{$_} },              $prepared_template_arrays{$_}[$i - 1]) for @prepared_arrays;
+
+    push @{ $form->{TEMPLATE_ARRAYS}{entry_type} },      'normal';
     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
@@ -909,36 +1061,44 @@ sub order_details {
       push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$si_position-1] },          $si->{unit};
     }
 
-    if ($form->{"assembly_$i"}) {
+    if ($form->{"part_type_$i"} eq 'assembly') {
       $sameitem = "";
 
       # get parts and push them onto the stack
       my $sortorder = "";
       if ($form->{groupitems}) {
         $sortorder =
-          qq|ORDER BY pg.partsgroup, a.oid|;
+          qq|ORDER BY pg.partsgroup, a.position|;
       } else {
-        $sortorder = qq|ORDER BY a.oid|;
+        $sortorder = qq|ORDER BY a.position|;
       }
 
       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
 
       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
-          map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} @arrays));
+          map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
+          push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'assembly-item-partsgroup');
           push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
           $si_position++;
         }
 
-        push(@{ $form->{TEMPLATE_ARRAYS}->{"description"} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
-        map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} @arrays));
+        push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  },  'assembly-item');
+        push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
+        map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
         $si_position++;
       }
     }
 
+    CVar->get_non_editable_ic_cvars(form               => $form,
+                                    dbh                => $dbh,
+                                    row                => $i,
+                                    sub_module         => 'delivery_order_items',
+                                    may_converted_from => ['orderitems', 'delivery_order_items']);
+
     push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
       CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
         for @{ $ic_cvar_configs };
@@ -954,6 +1114,7 @@ sub order_details {
   $h_pg->finish();
   $h_bin_wh->finish();
 
+  $form->{department}    = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
   $form->{delivery_term} = SL::DB::Manager::DeliveryTerm->find_by(id => $form->{delivery_term_id} || undef);
   $form->{delivery_term}->description_long($form->{delivery_term}->translated_attribute('description_long', $form->{language_id})) if $form->{delivery_term} && $form->{language_id};
 
@@ -962,21 +1123,6 @@ sub order_details {
   $main::lxdebug->leave_sub();
 }
 
-sub project_description {
-  $main::lxdebug->enter_sub();
-
-  my ($self, $dbh, $id) = @_;
-
-  my $form     =  $main::form;
-
-  my $query = qq|SELECT description FROM project WHERE id = ?|;
-  my ($value) = selectrow_query($form, $dbh, $query, $id);
-
-  $main::lxdebug->leave_sub();
-
-  return $value;
-}
-
 sub unpack_stock_information {
   $main::lxdebug->enter_sub();
 
@@ -987,7 +1133,7 @@ sub unpack_stock_information {
 
   my $unpacked;
 
-  eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
+  eval { $unpacked = $params{packed} ? SL::YAML::Load($params{packed}) : []; };
 
   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
 
@@ -1105,73 +1251,30 @@ sub transfer_in_out {
 
   foreach my $request (@{ $params{requests} }) {
     push @transfers, {
-      'parts_id'               => $request->{parts_id},
-      "${prefix}_warehouse_id" => $request->{warehouse_id},
-      "${prefix}_bin_id"       => $request->{bin_id},
-      'chargenumber'           => $request->{chargenumber},
-      'bestbefore'             => $request->{bestbefore},
-      'qty'                    => $request->{qty},
-      'unit'                   => $request->{unit},
-      'oe_id'                  => $form->{id},
-      'shippingdate'           => 'current_date',
-      'transfer_type'          => $params{direction} eq 'in' ? 'stock' : 'shipped',
-      'project_id'             => $request->{project_id},
+      'parts_id'                      => $request->{parts_id},
+      "${prefix}_warehouse_id"        => $request->{warehouse_id},
+      "${prefix}_bin_id"              => $request->{bin_id},
+      'chargenumber'                  => $request->{chargenumber},
+      'bestbefore'                    => $request->{bestbefore},
+      'qty'                           => $request->{qty},
+      'unit'                          => $request->{unit},
+      'oe_id'                         => $form->{id},
+      'shippingdate'                  => 'current_date',
+      'transfer_type'                 => $params{direction} eq 'in' ? 'stock' : 'shipped',
+      'project_id'                    => $request->{project_id},
+      'delivery_order_items_stock_id' => $request->{delivery_order_items_stock_id},
+      'comment'                       => $request->{comment},
     };
   }
 
   WH->transfer(@transfers);
 
-  $main::lxdebug->leave_sub();
-}
-
-sub get_shipped_qty {
-  $main::lxdebug->enter_sub();
-
-  my $self     = shift;
-  my %params   = @_;
-
-  Common::check_params(\%params, qw(type oe_id));
-
-  my $myconfig = \%main::myconfig;
-  my $form     = $main::form;
-
-  my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
-
-  my @links    = RecordLinks->get_links('dbh'        => $dbh,
-                                        'from_table' => 'oe',
-                                        'from_id'    => $params{oe_id},
-                                        'to_table'   => 'delivery_orders');
-  my @values   = map { $_->{to_id} } @links;
-
-  if (!scalar @values) {
-    $main::lxdebug->leave_sub();
-    return ();
-  }
-
-  my $query =
-    qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
-       FROM delivery_order_items doi
-       LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
-       LEFT JOIN parts p ON (doi.parts_id = p.id)
-       WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
-
-  my %ship      = ();
-  my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
-  my $all_units = AM->retrieve_all_units();
-
-  foreach my $entry (@{ $entries }) {
-    $entry->{qty} *= AM->convert_unit($entry->{unit}, $entry->{partunit}, $all_units);
-
-    if (!$ship{$entry->{parts_id}}) {
-      $ship{$entry->{parts_id}} = $entry;
-    } else {
-      $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
-    }
+  if ($::instance_conf->get_shipped_qty_require_stock_out) {
+    $self->mark_orders_if_delivered('do_id' => $form->{id},
+                                    'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase');
   }
 
   $main::lxdebug->leave_sub();
-
-  return %ship;
 }
 
 sub is_marked_as_delivered {
@@ -1194,5 +1297,4 @@ sub is_marked_as_delivered {
   return $delivered ? 1 : 0;
 }
 
-
 1;