1 #====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (C) 1999-2003
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  17 # This program is free software; you can redistribute it and/or modify
 
  18 # it under the terms of the GNU General Public License as published by
 
  19 # the Free Software Foundation; either version 2 of the License, or
 
  20 # (at your option) any later version.
 
  22 # This program is distributed in the hope that it will be useful,
 
  23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  25 # GNU General Public License for more details.
 
  26 # You should have received a copy of the GNU General Public License
 
  27 # along with this program; if not, write to the Free Software
 
  28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  29 #======================================================================
 
  31 # Delivery Order entry module
 
  32 #======================================================================
 
  36 use List::Util qw(max);
 
  42 use SL::DB::DeliveryOrder;
 
  45 use SL::HTML::Restrict;
 
  53   $main::lxdebug->enter_sub();
 
  57   my $myconfig = \%main::myconfig;
 
  58   my $form     = $main::form;
 
  61   my $dbh = $form->get_standard_dbh($myconfig);
 
  63   my (@where, @values, $where);
 
  65   my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
 
  68     qq|SELECT dord.id, dord.donumber, dord.ordnumber, dord.cusordnumber,
 
  69          dord.transdate, dord.reqdate,
 
  70          ct.${vc}number, ct.name, dord.${vc}_id, dord.globalproject_id,
 
  71          dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
 
  72          dord.transaction_description,
 
  73          pr.projectnumber AS globalprojectnumber,
 
  74          dep.description AS department,
 
  77        FROM delivery_orders dord
 
  78        LEFT JOIN $vc ct ON (dord.${vc}_id = ct.id)
 
  79        LEFT JOIN contacts cp ON (dord.cp_id = cp.cp_id)
 
  80        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
  81        LEFT JOIN employee sm ON (dord.salesman_id = sm.id)
 
  82        LEFT JOIN project pr ON (dord.globalproject_id = pr.id)
 
  83        LEFT JOIN department dep ON (dord.department_id = dep.id)
 
  86   push @where, ($form->{type} eq 'sales_delivery_order' ? '' : 'NOT ') . qq|COALESCE(dord.is_sales, FALSE)|;
 
  88   if ($form->{department_id}) {
 
  89     push @where,  qq|dord.department_id = ?|;
 
  90     push @values, conv_i($form->{department_id});
 
  93   if ($form->{project_id}) {
 
  95       qq|(dord.globalproject_id = ?) OR EXISTS
 
  96           (SELECT * FROM delivery_order_items doi
 
  97            WHERE (doi.project_id = ?) AND (doi.delivery_order_id = dord.id))|;
 
  98     push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
 
 101   if ($form->{"${vc}_id"}) {
 
 102     push @where,  qq|dord.${vc}_id = ?|;
 
 103     push @values, $form->{"${vc}_id"};
 
 105   } elsif ($form->{$vc}) {
 
 106     push @where,  qq|ct.name ILIKE ?|;
 
 107     push @values, '%' . $form->{$vc} . '%';
 
 110   if ($form->{"cp_name"}) {
 
 111     push @where, "(cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
 
 112     push @values, ('%' . $form->{"cp_name"} . '%')x2;
 
 115   foreach my $item (qw(employee_id salesman_id)) {
 
 116     next unless ($form->{$item});
 
 117     push @where, "dord.$item = ?";
 
 118     push @values, conv_i($form->{$item});
 
 120   if (!$main::auth->assert('sales_all_edit', 1)) {
 
 121     push @where, qq|dord.employee_id = (select id from employee where login= ?)|;
 
 122     push @values, $form->{login};
 
 125   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
 
 126     next unless ($form->{$item});
 
 127     push @where,  qq|dord.$item ILIKE ?|;
 
 128     push @values, '%' . $form->{$item} . '%';
 
 131   if (($form->{open} || $form->{closed}) &&
 
 132       ($form->{open} ne $form->{closed})) {
 
 133     push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
 
 136   if (($form->{notdelivered} || $form->{delivered}) &&
 
 137       ($form->{notdelivered} ne $form->{delivered})) {
 
 138     push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
 
 141   if ($form->{serialnumber}) {
 
 142     push @where, 'dord.id IN (SELECT doi.delivery_order_id FROM delivery_order_items doi WHERE doi.serialnumber LIKE ?)';
 
 143     push @values, '%' . $form->{serialnumber} . '%';
 
 146   if($form->{transdatefrom}) {
 
 147     push @where,  qq|dord.transdate >= ?|;
 
 148     push @values, conv_date($form->{transdatefrom});
 
 151   if($form->{transdateto}) {
 
 152     push @where,  qq|dord.transdate <= ?|;
 
 153     push @values, conv_date($form->{transdateto});
 
 156   if($form->{reqdatefrom}) {
 
 157     push @where,  qq|dord.reqdate >= ?|;
 
 158     push @values, conv_date($form->{reqdatefrom});
 
 161   if($form->{reqdateto}) {
 
 162     push @where,  qq|dord.reqdate <= ?|;
 
 163     push @values, conv_date($form->{reqdateto});
 
 167     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
 
 170   my %allowed_sort_columns = (
 
 171     "transdate"               => "dord.transdate",
 
 172     "reqdate"                 => "dord.reqdate",
 
 174     "donumber"                => "dord.donumber",
 
 175     "ordnumber"               => "dord.ordnumber",
 
 177     "employee"                => "e.name",
 
 178     "salesman"                => "sm.name",
 
 179     "shipvia"                 => "dord.shipvia",
 
 180     "transaction_description" => "dord.transaction_description",
 
 181     "department"              => "lower(dep.description)",
 
 184   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 185   my $sortorder = "dord.id";
 
 186   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
 
 187     $sortorder = $allowed_sort_columns{$form->{sort}};
 
 190   $query .= qq| ORDER by | . $sortorder . " $sortdir";
 
 192   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
 
 194   if (scalar @{ $form->{DO} }) {
 
 198          WHERE NOT COALESCE(quotation, FALSE)
 
 200            AND (COALESCE(${vc}_id, 0) != 0)|;
 
 202     my $sth = prepare_query($form, $dbh, $query);
 
 204     foreach my $dord (@{ $form->{DO} }) {
 
 205       next unless ($dord->{ordnumber});
 
 206       do_statement($form, $sth, $query, $dord->{ordnumber});
 
 207       ($dord->{oe_id}) = $sth->fetchrow_array();
 
 213   $main::lxdebug->leave_sub();
 
 217   $main::lxdebug->enter_sub();
 
 221   my $myconfig = \%main::myconfig;
 
 222   my $form     = $main::form;
 
 224   # connect to database, turn off autocommit
 
 225   my $dbh = $form->get_standard_dbh($myconfig);
 
 226   my $restricter = SL::HTML::Restrict->create;
 
 228   my ($query, @values, $sth, $null);
 
 230   my $all_units = AM->retrieve_units($myconfig, $form);
 
 231   $form->{all_units} = $all_units;
 
 233   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 236   my $trans_number     = SL::TransNumber->new(type => $form->{type}, dbh => $dbh, number => $form->{donumber}, id => $form->{id});
 
 237   $form->{donumber}  ||= $trans_number->create_unique;
 
 238   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
 
 239   $form->get_employee($dbh) unless ($form->{employee_id});
 
 241   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
 
 243   my (@processed_doi, @processed_dois);
 
 247     # only delete shipto complete
 
 248     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
 
 249     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 253     $query = qq|SELECT nextval('id')|;
 
 254     ($form->{id}) = selectrow_query($form, $dbh, $query);
 
 256     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id, currency_id, taxzone_id) VALUES (?, '', ?, (SELECT currency_id FROM defaults LIMIT 1), ?)|;
 
 257     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}), $form->{taxzone_id});
 
 263   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 264   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 267   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
 
 268   my @part_ids    = keys %part_id_map;
 
 272     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
 
 273     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
 
 276     UPDATE delivery_order_items SET
 
 277        delivery_order_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
 
 278        sellprice = ?, discount = ?, unit = ?, reqdate = ?, project_id = ?, serialnumber = ?,
 
 279        ordnumber = ?, transdate = ?, cusordnumber = ?,
 
 280        lastcost = ? , price_factor_id = ?, price_factor = (SELECT factor FROM price_factors where id = ?),
 
 281        marge_price_factor = ?, pricegroup_id = ?, active_price_source = ?, active_discount_source = ?
 
 284   my $h_item = prepare_query($form, $dbh, $q_item);
 
 286   my $q_item_stock = <<SQL;
 
 287     UPDATE delivery_order_items_stock SET
 
 288       delivery_order_item_id = ?, qty = ?,  unit = ?,  warehouse_id = ?,
 
 289       bin_id = ?, chargenumber = ?, bestbefore = ?
 
 292   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
 
 294   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 296   for my $i (1 .. $form->{rowcount}) {
 
 297     next if (!$form->{"id_$i"});
 
 302     if (!$form->{"delivery_order_items_id_$i"}) {
 
 303       # there is no persistent id, therefore create one with all necessary constraints
 
 304       my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
 
 305       my $h_item_id = prepare_query($form, $dbh, $q_item_id);
 
 306       do_statement($form, $h_item_id, $q_item_id);
 
 307       $form->{"delivery_order_items_id_$i"}  = $h_item_id->fetchrow_array();
 
 308       $query = qq|INSERT INTO delivery_order_items (id, delivery_order_id, position, parts_id) VALUES (?, ?, ?, ?)|;
 
 309       do_query($form, $dbh, $query, conv_i($form->{"delivery_order_items_id_$i"}),
 
 310                 conv_i($form->{"id"}), conv_i($position), conv_i($form->{"id_$i"}));
 
 311       $h_item_id->finish();
 
 313       # get values for CVars from master data for new items
 
 314       $cvars = CVar->get_custom_variables(dbh      => $dbh,
 
 316                                           trans_id => $form->{"id_$i"},
 
 319       # get values for CVars from custom_variables for existing items
 
 320       $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 322                                           sub_module => 'delivery_order_items',
 
 323                                           trans_id   => $form->{"delivery_order_items_id_$i"},
 
 326     # map only non-editable CVars to form (editable ones are already there)
 
 327     map { $form->{"ic_cvar_$_->{name}_$i"} = $_->{value} unless $_->{flag_editable} } @{ $cvars };
 
 329     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 331     my $item_unit = $part_unit_map{$form->{"id_$i"}};
 
 334     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
 
 335       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
 
 337     my $baseqty = $form->{"qty_$i"} * $basefactor;
 
 339     # set values to 0 if nothing entered
 
 340     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"});
 
 341     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 342     $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
 
 344     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
 
 345     my $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 347     $items_reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
 
 350     # Get pricegroup_id and save it. Unfortunately the interface
 
 351     # also uses ID "0" for signalling that none is selected, but "0"
 
 352     # must not be stored in the database. Therefore we cannot simply
 
 354     my $pricegroup_id = $form->{"pricegroup_id_$i"} * 1;
 
 355     $pricegroup_id    = undef if !$pricegroup_id;
 
 357     # save detail record in delivery_order_items table
 
 358     @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
 
 359                $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}),
 
 360                $form->{"qty_$i"}, $baseqty,
 
 361                $form->{"sellprice_$i"}, $form->{"discount_$i"} / 100,
 
 362                $form->{"unit_$i"}, conv_date($items_reqdate), conv_i($form->{"project_id_$i"}),
 
 363                $form->{"serialnumber_$i"},
 
 364                $form->{"ordnumber_$i"}, conv_date($form->{"transdate_$i"}),
 
 365                $form->{"cusordnumber_$i"},
 
 366                $form->{"lastcost_$i"},
 
 367                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
 
 368                conv_i($form->{"marge_price_factor_$i"}),
 
 370                $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
 
 371                conv_i($form->{"delivery_order_items_id_$i"}));
 
 372     do_statement($form, $h_item, $q_item, @values);
 
 373     push @processed_doi, $form->{"delivery_order_items_id_$i"}; # transaction safe?
 
 375     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 377     foreach my $sinfo (@{ $stock_info }) {
 
 378       # if we have stock_info, we have to check for persistents entries
 
 379       if (!$sinfo->{"delivery_order_items_stock_id"}) {
 
 380         my $q_item_stock_id = qq|SELECT nextval('id')|;
 
 381         my $h_item_stock_id = prepare_query($form, $dbh, $q_item_stock_id);
 
 382         do_statement($form, $h_item_stock_id, $q_item_stock_id);
 
 383         $sinfo->{"delivery_order_items_stock_id"} = $h_item_stock_id->fetchrow_array();
 
 384         $query = qq|INSERT INTO delivery_order_items_stock (id, delivery_order_item_id, qty, unit, warehouse_id, bin_id)
 
 385                     VALUES (?, ?, ?, ?, ?, ?)|;
 
 386         do_query($form, $dbh, $query, conv_i($sinfo->{"delivery_order_items_stock_id"}),
 
 387                   conv_i($form->{"delivery_order_items_id_$i"}), $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 388                   conv_i($sinfo->{bin_id}));
 
 389        $h_item_stock_id->finish();
 
 391       @values = ($form->{"delivery_order_items_id_$i"}, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 392                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}),
 
 393                  conv_i($sinfo->{"delivery_order_items_stock_id"}));
 
 394       do_statement($form, $h_item_stock, $q_item_stock, @values);
 
 395       push @processed_dois, $sinfo->{"delivery_order_items_stock_id"};
 
 398     CVar->save_custom_variables(module       => 'IC',
 
 399                                 sub_module   => 'delivery_order_items',
 
 400                                 trans_id     => $form->{"delivery_order_items_id_$i"},
 
 401                                 configs      => $ic_cvar_configs,
 
 403                                 name_prefix  => 'ic_',
 
 404                                 name_postfix => "_$i",
 
 406     # link order items with doi
 
 407     if ($form->{"converted_from_orderitems_id_$i"}) {
 
 408       RecordLinks->create_links('dbh'        => $dbh,
 
 410                                 'from_table' => 'orderitems',
 
 411                                 'from_ids'   => $form->{"converted_from_orderitems_id_$i"},
 
 412                                 'to_table'   => 'delivery_order_items',
 
 413                                 'to_id'      =>  $form->{"delivery_order_items_id_$i"},
 
 415       delete $form->{"converted_from_orderitems_id_$i"};
 
 419   # 1. search for orphaned dois; processed_dois may be empty (no transfer) TODO: be supersafe and alter same statement for doi and oi
 
 420   $query  = sprintf 'SELECT id FROM delivery_order_items_stock WHERE delivery_order_item_id in
 
 421                       (select id from delivery_order_items where delivery_order_id = ?)';
 
 422   $query .= sprintf ' AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_dois if (scalar @processed_dois);
 
 423   @values = (conv_i($form->{id}), map { conv_i($_) } @processed_dois);
 
 424   my @orphaned_dois_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
 
 425   if (scalar @orphaned_dois_ids) {
 
 426     # clean up delivery_order_items_stock
 
 427     $query  = sprintf 'DELETE FROM delivery_order_items_stock WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_dois_ids;
 
 428     do_query($form, $dbh, $query, @orphaned_dois_ids);
 
 430   # 2. search for orphaned doi
 
 431   $query  = sprintf 'SELECT id FROM delivery_order_items WHERE delivery_order_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_doi;
 
 432   @values = (conv_i($form->{id}), map { conv_i($_) } @processed_doi);
 
 433   my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
 
 434   if (scalar @orphaned_ids) {
 
 435     # clean up delivery_order_items
 
 436     $query  = sprintf 'DELETE FROM delivery_order_items WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
 
 437     do_query($form, $dbh, $query, @orphaned_ids);
 
 440   $h_item_stock->finish();
 
 443   # reqdate is last items reqdate (?: old behaviour) if not already set
 
 444   $form->{reqdate} ||= $items_reqdate;
 
 447     qq|UPDATE delivery_orders SET
 
 448          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
 
 449          customer_id = ?, reqdate = ?,
 
 450          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
 
 451          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
 
 452          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
 
 453          is_sales = ?, taxzone_id = ?, taxincluded = ?, terms = ?, currency_id = (SELECT id FROM currencies WHERE name = ?),
 
 457   @values = ($form->{donumber}, $form->{ordnumber},
 
 458              $form->{cusordnumber}, conv_date($form->{transdate}),
 
 459              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
 
 460              conv_date($form->{reqdate}), $form->{shippingpoint}, $form->{shipvia},
 
 461              $form->{notes}, $form->{intnotes},
 
 462              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
 
 463              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
 
 464              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
 
 465              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
 
 466              $form->{transaction_description},
 
 467              $form->{type} =~ /^sales/ ? 't' : 'f',
 
 468              conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{terms}), $form->{currency},
 
 469              conv_i($form->{delivery_term_id}),
 
 470              conv_i($form->{id}));
 
 471   do_query($form, $dbh, $query, @values);
 
 473   $form->{name} = $form->{ $form->{vc} };
 
 474   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
 
 477   if (!$form->{shipto_id}) {
 
 478     $form->add_shipto($dbh, $form->{id}, "DO");
 
 481   # save printed, emailed, queued
 
 482   $form->save_status($dbh);
 
 484   # Link this delivery order to the quotations it was created from.
 
 485   RecordLinks->create_links('dbh'        => $dbh,
 
 487                             'from_table' => 'oe',
 
 488                             'from_ids'   => $form->{convert_from_oe_ids},
 
 489                             'to_table'   => 'delivery_orders',
 
 490                             'to_id'      => $form->{id},
 
 492   delete $form->{convert_from_oe_ids};
 
 494   $self->mark_orders_if_delivered('do_id' => $form->{id},
 
 495                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
 
 498   my $rc = $dbh->commit();
 
 500   $form->{saved_donumber} = $form->{donumber};
 
 501   $form->{saved_ordnumber} = $form->{ordnumber};
 
 502   $form->{saved_cusordnumber} = $form->{cusordnumber};
 
 504   Common::webdav_folder($form);
 
 506   $main::lxdebug->leave_sub();
 
 511 sub mark_orders_if_delivered {
 
 512   $main::lxdebug->enter_sub();
 
 517   Common::check_params(\%params, qw(do_id type));
 
 519   my $myconfig = \%main::myconfig;
 
 520   my $form     = $main::form;
 
 522   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 524   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
 525                                         'from_table' => 'oe',
 
 526                                         'to_table'   => 'delivery_orders',
 
 527                                         'to_id'      => $params{do_id});
 
 529   my $oe_id  = @links ? $links[0]->{from_id} : undef;
 
 531   return $main::lxdebug->leave_sub() if (!$oe_id);
 
 533   my $all_units = AM->retrieve_all_units();
 
 535   my $query     = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
 
 537                      LEFT JOIN parts p ON (oi.parts_id = p.id)
 
 538                      WHERE (oi.trans_id = ?)|;
 
 539   my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
 
 541   my %shipped   = $self->get_shipped_qty('type'  => $params{type},
 
 545   while (my $ref = $sth->fetchrow_hashref()) {
 
 546     $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
 
 548     if ($ordered{$ref->{parts_id}}) {
 
 549       $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
 
 551       $ordered{$ref->{parts_id}}             = $ref;
 
 557   map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
 
 560   foreach my $part (values %ordered) {
 
 561     if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
 
 568     $query = qq|UPDATE oe
 
 571     do_query($form, $dbh, $query, $oe_id);
 
 572     $dbh->commit() if (!$params{dbh});
 
 575   $main::lxdebug->leave_sub();
 
 579   $main::lxdebug->enter_sub();
 
 584   Common::check_params(\%params, qw(ids));
 
 586   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
 
 587     $main::lxdebug->leave_sub();
 
 591   my $myconfig = \%main::myconfig;
 
 592   my $form     = $main::form;
 
 594   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 596   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
 
 598   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
 
 600   $dbh->commit() unless ($params{dbh});
 
 602   $main::lxdebug->leave_sub();
 
 606   $main::lxdebug->enter_sub();
 
 610   my $myconfig = \%main::myconfig;
 
 611   my $form     = $main::form;
 
 612   my $spool    = $::lx_office_conf{paths}->{spool};
 
 614   my $rc = SL::DB::Order->new->db->with_transaction(sub {
 
 615     my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $form->{id} ]) };
 
 617     SL::DB::DeliveryOrder->new(id => $form->{id})->delete;
 
 619     my $spool = $::lx_office_conf{paths}->{spool};
 
 620     unlink map { "$spool/$_" } @spoolfiles if $spool;
 
 625   $main::lxdebug->leave_sub();
 
 631   $main::lxdebug->enter_sub();
 
 636   my $myconfig = \%main::myconfig;
 
 637   my $form     = $main::form;
 
 639   # connect to database
 
 640   my $dbh = $form->get_standard_dbh($myconfig);
 
 642   my ($query, $query_add, @values, $sth, $ref);
 
 644   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 647   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
 
 649   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
 
 651   if ($mode eq 'default') {
 
 652     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate|);
 
 653     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 655     # if reqdate is not set from oe-workflow, set it to transdate (which is current date)
 
 656     $form->{reqdate} ||= $form->{transdate};
 
 659     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
 
 661     $main::lxdebug->leave_sub();
 
 666   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
 
 667   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
 
 669   # retrieve order for single id
 
 670   # NOTE: this query is intended to fetch all information only ONCE.
 
 671   # so if any of these infos is important (or even different) for any item,
 
 672   # it will be killed out and then has to be fetched from the item scope query further down
 
 674     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
 
 675          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
 
 676          e.name AS employee, dord.employee_id, dord.salesman_id,
 
 677          dord.${vc}_id, cv.name AS ${vc},
 
 678          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
 
 679          d.description AS department, dord.language_id,
 
 681          dord.globalproject_id, dord.delivered, dord.transaction_description,
 
 682          dord.taxzone_id, dord.taxincluded, dord.terms, (SELECT cu.name FROM currencies cu WHERE cu.id=dord.currency_id) AS currency,
 
 683          dord.delivery_term_id
 
 684        FROM delivery_orders dord
 
 685        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
 
 686        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
 687        LEFT JOIN department d ON (dord.department_id = d.id)
 
 688        WHERE dord.id IN ($do_ids_placeholders)|;
 
 689   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
 
 691   delete $form->{"${vc}_id"};
 
 693   $form->{ordnumber_array} = ' ';
 
 694   $form->{cusordnumber_array} = ' ';
 
 695   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 696     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
 
 698       $main::lxdebug->leave_sub();
 
 703     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
 
 704     $form->{donumber_array} .= $form->{donumber} . ' ';
 
 705     $pos = index($form->{ordnumber_array},' ' . $form->{ordnumber} . ' ');
 
 707       $form->{ordnumber_array} .= $form->{ordnumber} . ' ';
 
 709     $pos = index($form->{cusordnumber_array},' ' . $form->{cusordnumber} . ' ');
 
 711       $form->{cusordnumber_array} .= $form->{cusordnumber} . ' ';
 
 716   $form->{donumber_array} =~ s/\s*$//g;
 
 717   $form->{ordnumber_array} =~ s/ //;
 
 718   $form->{ordnumber_array} =~ s/\s*$//g;
 
 719   $form->{cusordnumber_array} =~ s/ //;
 
 720   $form->{cusordnumber_array} =~ s/\s*$//g;
 
 722   $form->{saved_donumber} = $form->{donumber};
 
 723   $form->{saved_ordnumber} = $form->{ordnumber};
 
 724   $form->{saved_cusordnumber} = $form->{cusordnumber};
 
 726   # if not given, fill transdate with current_date
 
 727   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
 
 729   if ($mode eq 'single') {
 
 730     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
 
 731     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
 
 733     $ref   = $sth->fetchrow_hashref("NAME_lc");
 
 735     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 738     # get printed, emailed and queued
 
 739     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
 
 740     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 742     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 743       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
 744       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
 745       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
 
 748     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
 754   # retrieve individual items
 
 755   # this query looks up all information about the items
 
 756   # stuff different from the whole will not be overwritten, but saved with a suffix.
 
 758     qq|SELECT doi.id AS delivery_order_items_id,
 
 759          p.partnumber, p.assembly, p.listprice, doi.description, doi.qty,
 
 760          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.notes AS partnotes,
 
 761          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
 
 762          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
 
 763          doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
 
 764          doi.active_price_source, doi.active_discount_source,
 
 765          pr.projectnumber, dord.transdate AS dord_transdate, dord.donumber,
 
 767        FROM delivery_order_items doi
 
 768        JOIN parts p ON (doi.parts_id = p.id)
 
 769        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
 
 770        LEFT JOIN project pr ON (doi.project_id = pr.id)
 
 771        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 772        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
 
 773        ORDER BY doi.delivery_order_id, doi.position|;
 
 775   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
 777   # Retrieve custom variables.
 
 778   foreach my $doi (@{ $form->{form_details} }) {
 
 779     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 781                                            sub_module => 'delivery_order_items',
 
 782                                            trans_id   => $doi->{delivery_order_items_id},
 
 784     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
 
 787   if ($mode eq 'single') {
 
 788     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 791       qq|SELECT id as delivery_order_items_stock_id, qty, unit, bin_id,
 
 792                 warehouse_id, chargenumber, bestbefore
 
 793          FROM delivery_order_items_stock
 
 794          WHERE delivery_order_item_id = ?|;
 
 795     my $sth = prepare_query($form, $dbh, $query);
 
 797     foreach my $doi (@{ $form->{form_details} }) {
 
 798       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
 
 800       while (my $ref = $sth->fetchrow_hashref()) {
 
 801         push @{ $requests }, $ref;
 
 804       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
 
 810   Common::webdav_folder($form);
 
 812   $main::lxdebug->leave_sub();
 
 818   $main::lxdebug->enter_sub();
 
 820   my ($self, $myconfig, $form) = @_;
 
 822   # connect to database
 
 823   my $dbh = $form->get_standard_dbh($myconfig);
 
 832   my $subtotal_header = 0;
 
 838   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
 
 840   # sort items by partsgroup
 
 841   for $i (1 .. $form->{rowcount}) {
 
 843     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
 844       $partsgroup = $form->{"partsgroup_$i"};
 
 846     push @partsgroup, [$i, $partsgroup];
 
 847     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
 
 853     $projects = SL::DB::Manager::Project->get_all(query => [ id => \@project_ids ]);
 
 854     %projects_by_id = map { $_->id => $_ } @$projects;
 
 857   if ($projects_by_id{$form->{"globalproject_id"}}) {
 
 858     $form->{globalprojectnumber} = $projects_by_id{$form->{"globalproject_id"}}->projectnumber;
 
 859     $form->{globalprojectdescription} = $projects_by_id{$form->{"globalproject_id"}}->description;
 
 861     for (@{ $projects_by_id{$form->{"globalproject_id"}}->cvars_by_config }) {
 
 862       $form->{"project_cvar_" . $_->config->name} = $_->value_as_text;
 
 866   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
 
 868                     JOIN parts p ON (a.parts_id = p.id)
 
 869                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 872   my $h_pg     = prepare_query($form, $dbh, $q_pg);
 
 874   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
 
 875                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
 
 876   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
 
 878   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 882   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 883   my $project_cvar_configs = CVar->get_configs(module => 'Projects');
 
 885   $form->{TEMPLATE_ARRAYS} = { };
 
 886   IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
 
 889     qw(runningnumber number description longdescription qty unit
 
 890        partnotes serialnumber reqdate projectnumber projectdescription
 
 892        si_runningnumber si_number si_description
 
 893        si_warehouse si_bin si_chargenumber si_bestbefore
 
 894        si_qty si_qty_nofmt si_unit);
 
 896   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays);
 
 898   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 899   push @arrays, map { "project_cvar_$_->{name}" } @{ $project_cvar_configs };
 
 901   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 902   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 906   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
 909     next if (!$form->{"id_$i"});
 
 911     if ($item->[1] ne $sameitem) {
 
 912       push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, qq|$item->[1]|);
 
 913       $sameitem = $item->[1];
 
 915       map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} @arrays));
 
 916       map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
 
 920     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 922     # add number, description and qty to $form->{number}, ....
 
 923     if ($form->{"subtotal_$i"} && !$subtotal_header) {
 
 924       $subtotal_header = $i;
 
 925       $position = int($position);
 
 928     } elsif ($subtotal_header) {
 
 930       $position = int($position);
 
 931       $position = $position.".".$subposition;
 
 933       $position = int($position);
 
 939     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
 
 940     my $project = $projects_by_id{$form->{"project_id_$i"}} || SL::DB::Project->new;
 
 942     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
 
 943     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
 
 944     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
 
 945     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
 
 946     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
 
 947     push @{ $form->{TEMPLATE_ARRAYS}{qty_nofmt} },       $form->{"qty_$i"};
 
 948     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
 
 949     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
 
 950     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
 
 951     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
 
 952     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $project->projectnumber;
 
 953     push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} }, $project->description;
 
 955     if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
 
 956       $subtotal_header     = 0;
 
 959     my $lineweight = $form->{"qty_$i"} * $form->{"weight_$i"};
 
 960     $totalweight += $lineweight;
 
 961     push @{ $form->{TEMPLATE_ARRAYS}->{weight} },            $form->format_amount($myconfig, $form->{"weight_$i"}, 3);
 
 962     push @{ $form->{TEMPLATE_ARRAYS}->{weight_nofmt} },      $form->{"weight_$i"};
 
 963     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight} },        $form->format_amount($myconfig, $lineweight, 3);
 
 964     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight_nofmt} },  $lineweight;
 
 966     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 968     foreach my $si (@{ $stock_info }) {
 
 971       do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
 
 972       my $bin_wh = $h_bin_wh->fetchrow_hashref();
 
 974       push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$si_position-1] }, $num_si;
 
 975       push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$si_position-1] },        $form->{"partnumber_$i"};
 
 976       push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$si_position-1] },   $form->{"description_$i"};
 
 977       push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$si_position-1] },     $bin_wh->{warehouse};
 
 978       push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$si_position-1] },           $bin_wh->{bin};
 
 979       push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$si_position-1] },  $si->{chargenumber};
 
 980       push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$si_position-1] },    $si->{bestbefore};
 
 981       push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$si_position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
 
 982       push @{ $form->{TEMPLATE_ARRAYS}{si_qty_nofmt}[$si_position-1] },     $si->{qty} * 1;
 
 983       push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$si_position-1] },          $si->{unit};
 
 986     if ($form->{"assembly_$i"}) {
 
 989       # get parts and push them onto the stack
 
 991       if ($form->{groupitems}) {
 
 993           qq|ORDER BY pg.partsgroup, a.oid|;
 
 995         $sortorder = qq|ORDER BY a.oid|;
 
 998       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
 
1000       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
 
1001         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
1002           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} @arrays));
 
1003           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
 
1004           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
1005           push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
 
1009         push(@{ $form->{TEMPLATE_ARRAYS}->{"description"} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
 
1010         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} @arrays));
 
1011         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
 
1017     if (! $form->{"delivery_order_items_id_$i"}) {
 
1018       # get values for CVars from master data for new items
 
1019       $cvars = CVar->get_custom_variables(dbh      => $dbh,
 
1021                                           trans_id => $form->{"id_$i"},
 
1024       # get values for CVars from custom_variables for existing items
 
1025       $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
1027                                           sub_module => 'delivery_order_items',
 
1028                                           trans_id   => $form->{"delivery_order_items_id_$i"},
 
1031     # map only non-editable CVars to form (editable ones are already there)
 
1032     map { $form->{"ic_cvar_$_->{name}_$i"} = $_->{value} unless $_->{flag_editable} } @{ $cvars };
 
1034     push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
 
1035       CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
 
1036         for @{ $ic_cvar_configs };
 
1038     push @{ $form->{TEMPLATE_ARRAYS}->{"project_cvar_" . $_->config->name} }, $_->value_as_text for @{ $project->cvars_by_config };
 
1041   $form->{totalweight}       = $form->format_amount($myconfig, $totalweight, 3);
 
1042   $form->{totalweight_nofmt} = $totalweight;
 
1043   my $defaults = AM->get_defaults();
 
1044   $form->{weightunit}        = $defaults->{weightunit};
 
1047   $h_bin_wh->finish();
 
1049   $form->{delivery_term} = SL::DB::Manager::DeliveryTerm->find_by(id => $form->{delivery_term_id} || undef);
 
1050   $form->{delivery_term}->description_long($form->{delivery_term}->translated_attribute('description_long', $form->{language_id})) if $form->{delivery_term} && $form->{language_id};
 
1052   $form->{username} = $myconfig->{name};
 
1054   $main::lxdebug->leave_sub();
 
1057 sub project_description {
 
1058   $main::lxdebug->enter_sub();
 
1060   my ($self, $dbh, $id) = @_;
 
1062   my $form     =  $main::form;
 
1064   my $query = qq|SELECT description FROM project WHERE id = ?|;
 
1065   my ($value) = selectrow_query($form, $dbh, $query, $id);
 
1067   $main::lxdebug->leave_sub();
 
1072 sub unpack_stock_information {
 
1073   $main::lxdebug->enter_sub();
 
1078   Common::check_params_x(\%params, qw(packed));
 
1082   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
 
1084   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
 
1086   foreach my $entry (@{ $unpacked }) {
 
1087     next if ('HASH' eq ref $entry);
 
1092   $main::lxdebug->leave_sub();
 
1097 sub get_item_availability {
 
1098   $::lxdebug->enter_sub;
 
1103   Common::check_params(\%params, qw(parts_id));
 
1105   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
 
1108     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
 
1109          w.description AS warehousedescription,
 
1110          b.description AS bindescription
 
1112        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
 
1113        LEFT JOIN bin b       ON (i.bin_id       = b.id)
 
1114        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
 
1115        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
 
1117        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
 
1119   my $contents = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, @parts_ids);
 
1121   $::lxdebug->leave_sub;
 
1123   return @{ $contents };
 
1127 sub check_stock_availability {
 
1128   $main::lxdebug->enter_sub();
 
1133   Common::check_params(\%params, qw(requests parts_id));
 
1135   my $myconfig    = \%main::myconfig;
 
1136   my $form        =  $main::form;
 
1138   my $dbh         = $form->get_standard_dbh($myconfig);
 
1140   my $units       = AM->retrieve_units($myconfig, $form);
 
1142   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
 
1143   my $unit_factor = $units->{$partunit}->{factor} || 1;
 
1145   my @contents    = $self->get_item_availability(%params);
 
1149   foreach my $sinfo (@{ $params{requests} }) {
 
1152     foreach my $row (@contents) {
 
1153       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
 
1154                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
 
1155                ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
 
1156                ($row->{bestbefore}   ne $sinfo->{bestbefore}));
 
1160       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
 
1162       if ($base_qty > $row->{qty}) {
 
1163         $sinfo->{error} = 1;
 
1164         push @errors, $sinfo;
 
1170     push @errors, $sinfo if (!$found);
 
1173   $main::lxdebug->leave_sub();
 
1178 sub transfer_in_out {
 
1179   $main::lxdebug->enter_sub();
 
1184   Common::check_params(\%params, qw(direction requests));
 
1186   if (!@{ $params{requests} }) {
 
1187     $main::lxdebug->leave_sub();
 
1191   my $myconfig = \%main::myconfig;
 
1192   my $form     = $main::form;
 
1194   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
 
1198   foreach my $request (@{ $params{requests} }) {
 
1200       'parts_id'               => $request->{parts_id},
 
1201       "${prefix}_warehouse_id" => $request->{warehouse_id},
 
1202       "${prefix}_bin_id"       => $request->{bin_id},
 
1203       'chargenumber'           => $request->{chargenumber},
 
1204       'bestbefore'             => $request->{bestbefore},
 
1205       'qty'                    => $request->{qty},
 
1206       'unit'                   => $request->{unit},
 
1207       'oe_id'                  => $form->{id},
 
1208       'shippingdate'           => 'current_date',
 
1209       'transfer_type'          => $params{direction} eq 'in' ? 'stock' : 'shipped',
 
1210       'project_id'             => $request->{project_id},
 
1214   WH->transfer(@transfers);
 
1216   $main::lxdebug->leave_sub();
 
1219 sub get_shipped_qty {
 
1220   $main::lxdebug->enter_sub();
 
1225   Common::check_params(\%params, qw(type oe_id));
 
1227   my $myconfig = \%main::myconfig;
 
1228   my $form     = $main::form;
 
1230   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1232   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
1233                                         'from_table' => 'oe',
 
1234                                         'from_id'    => $params{oe_id},
 
1235                                         'to_table'   => 'delivery_orders');
 
1236   my @values   = map { $_->{to_id} } @links;
 
1238   if (!scalar @values) {
 
1239     $main::lxdebug->leave_sub();
 
1244     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
 
1245        FROM delivery_order_items doi
 
1246        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
 
1247        LEFT JOIN parts p ON (doi.parts_id = p.id)
 
1248        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
 
1251   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
 
1252   my $all_units = AM->retrieve_all_units();
 
1254   foreach my $entry (@{ $entries }) {
 
1255     $entry->{qty} *= AM->convert_unit($entry->{unit}, $entry->{partunit}, $all_units);
 
1257     if (!$ship{$entry->{parts_id}}) {
 
1258       $ship{$entry->{parts_id}} = $entry;
 
1260       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
 
1264   $main::lxdebug->leave_sub();
 
1269 sub is_marked_as_delivered {
 
1270   $main::lxdebug->enter_sub();
 
1275   Common::check_params(\%params, qw(id));
 
1277   my $myconfig    = \%main::myconfig;
 
1278   my $form        = $main::form;
 
1280   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1282   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
 
1284   $main::lxdebug->leave_sub();
 
1286   return $delivered ? 1 : 0;