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);
 
  49   $main::lxdebug->enter_sub();
 
  53   my $myconfig = \%main::myconfig;
 
  54   my $form     = $main::form;
 
  57   my $dbh = $form->get_standard_dbh($myconfig);
 
  59   my (@where, @values, $where);
 
  61   my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
 
  64     qq|SELECT dord.id, dord.donumber, dord.ordnumber, dord.transdate,
 
  65          ct.name, dord.${vc}_id, dord.globalproject_id,
 
  66          dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
 
  67          dord.transaction_description,
 
  68          pr.projectnumber AS globalprojectnumber,
 
  71        FROM delivery_orders dord
 
  72        LEFT JOIN $vc ct ON (dord.${vc}_id = ct.id)
 
  73        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
  74        LEFT JOIN employee sm ON (dord.salesman_id = sm.id)
 
  75        LEFT JOIN project pr ON (dord.globalproject_id = pr.id)|;
 
  77   push @where, ($form->{type} eq 'sales_delivery_order' ? '' : 'NOT ') . qq|COALESCE(dord.is_sales, FALSE)|;
 
  79   my $department_id = (split /--/, $form->{department})[1];
 
  81     push @where,  qq|dord.department_id = ?|;
 
  82     push @values, conv_i($department_id);
 
  85   if ($form->{project_id}) {
 
  87       qq|(dord.globalproject_id = ?) OR EXISTS
 
  88           (SELECT * FROM delivery_order_items doi
 
  89            WHERE (doi.project_id = ?) AND (doi.delivery_order_id = dord.id))|;
 
  90     push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
 
  93   if ($form->{"${vc}_id"}) {
 
  94     push @where,  qq|dord.${vc}_id = ?|;
 
  95     push @values, $form->{"${vc}_id"};
 
  97   } elsif ($form->{$vc}) {
 
  98     push @where,  qq|ct.name ILIKE ?|;
 
  99     push @values, '%' . $form->{$vc} . '%';
 
 102   foreach my $item (qw(employee_id salesman_id)) {
 
 103     next unless ($form->{$item});
 
 104     push @where, "dord.$item = ?";
 
 105     push @values, conv_i($form->{$item});
 
 107   if (!$main::auth->assert('sales_all_edit', 1)) {
 
 108     push @where, qq|dord.employee_id = (select id from employee where login= ?)|;
 
 109     push @values, $form->{login};
 
 112   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
 
 113     next unless ($form->{$item});
 
 114     push @where,  qq|dord.$item ILIKE ?|;
 
 115     push @values, '%' . $form->{$item} . '%';
 
 118   if (($form->{open} || $form->{closed}) &&
 
 119       ($form->{open} ne $form->{closed})) {
 
 120     push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
 
 123   if (($form->{notdelivered} || $form->{delivered}) &&
 
 124       ($form->{notdelivered} ne $form->{delivered})) {
 
 125     push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
 
 128   if($form->{transdatefrom}) {
 
 129     push @where,  qq|dord.transdate >= ?|;
 
 130     push @values, conv_date($form->{transdatefrom});
 
 133   if($form->{transdateto}) {
 
 134     push @where,  qq|dord.transdate <= ?|;
 
 135     push @values, conv_date($form->{transdateto});
 
 139     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
 
 142   my %allowed_sort_columns = (
 
 143     "transdate"               => "dord.transdate",
 
 145     "donumber"                => "dord.donumber",
 
 146     "ordnumber"               => "dord.ordnumber",
 
 148     "employee"                => "e.name",
 
 149     "salesman"                => "sm.name",
 
 150     "shipvia"                 => "dord.shipvia",
 
 151     "transaction_description" => "dord.transaction_description"
 
 154   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 155   my $sortorder = "dord.id";
 
 156   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
 
 157     $sortorder = $allowed_sort_columns{$form->{sort}};
 
 160   $query .= qq| ORDER by | . $sortorder . " $sortdir";
 
 162   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
 
 164   if (scalar @{ $form->{DO} }) {
 
 168          WHERE NOT COALESCE(quotation, FALSE)
 
 170            AND (COALESCE(${vc}_id, 0) != 0)|;
 
 172     my $sth = prepare_query($form, $dbh, $query);
 
 174     foreach my $dord (@{ $form->{DO} }) {
 
 175       next unless ($dord->{ordnumber});
 
 176       do_statement($form, $sth, $query, $dord->{ordnumber});
 
 177       ($dord->{oe_id}) = $sth->fetchrow_array();
 
 183   $main::lxdebug->leave_sub();
 
 187   $main::lxdebug->enter_sub();
 
 191   my $myconfig = \%main::myconfig;
 
 192   my $form     = $main::form;
 
 194   # connect to database, turn off autocommit
 
 195   my $dbh = $form->get_standard_dbh($myconfig);
 
 197   my ($query, @values, $sth, $null);
 
 199   my $all_units = AM->retrieve_units($myconfig, $form);
 
 200   $form->{all_units} = $all_units;
 
 202   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 205   $form->{donumber}    = $form->update_defaults($myconfig, $form->{type} eq 'sales_delivery_order' ? 'sdonumber' : 'pdonumber', $dbh) unless $form->{donumber};
 
 206   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
 
 207   $form->get_employee($dbh) unless ($form->{employee_id});
 
 209   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
 
 213     $query = qq|DELETE FROM delivery_order_items_stock WHERE delivery_order_item_id IN (SELECT id FROM delivery_order_items WHERE delivery_order_id = ?)|;
 
 214     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 216     $query = qq|DELETE FROM delivery_order_items WHERE delivery_order_id = ?|;
 
 217     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 219     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
 
 220     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 224     $query = qq|SELECT nextval('id')|;
 
 225     ($form->{id}) = selectrow_query($form, $dbh, $query);
 
 227     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id) VALUES (?, '', ?)|;
 
 228     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}));
 
 234   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 235   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 238   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
 
 239   my @part_ids    = keys %part_id_map;
 
 243     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
 
 244     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
 
 247   my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
 
 248   my $h_item_id = prepare_query($form, $dbh, $q_item_id);
 
 251     qq|INSERT INTO delivery_order_items (
 
 252          id, delivery_order_id, parts_id, description, longdescription, qty, base_qty,
 
 253          sellprice, discount, unit, reqdate, project_id, serialnumber,
 
 254          ordnumber, transdate, cusordnumber,
 
 255          lastcost, price_factor_id, price_factor, marge_price_factor)
 
 256        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 
 257          (SELECT factor FROM price_factors WHERE id = ?), ?)|;
 
 258   my $h_item = prepare_query($form, $dbh, $q_item);
 
 261     qq|INSERT INTO delivery_order_items_stock (delivery_order_item_id, qty, unit, warehouse_id, bin_id, chargenumber, bestbefore)
 
 262        VALUES (?, ?, ?, ?, ?, ?, ?)|;
 
 263   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
 
 265   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 267   for my $i (1 .. $form->{rowcount}) {
 
 268     next if (!$form->{"id_$i"});
 
 270     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 272     my $item_unit = $part_unit_map{$form->{"id_$i"}};
 
 275     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
 
 276       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
 
 278     my $baseqty = $form->{"qty_$i"} * $basefactor;
 
 280     # set values to 0 if nothing entered
 
 281     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"});
 
 282     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 283     $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
 
 285     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
 
 286     my $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 288     $reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
 
 290     do_statement($form, $h_item_id, $q_item_id);
 
 291     my ($item_id) = $h_item_id->fetchrow_array();
 
 293     # save detail record in delivery_order_items table
 
 294     @values = (conv_i($item_id), conv_i($form->{id}), conv_i($form->{"id_$i"}),
 
 295                $form->{"description_$i"}, $form->{"longdescription_$i"},
 
 296                $form->{"qty_$i"}, $baseqty,
 
 297                $form->{"sellprice_$i"}, $form->{"discount_$i"} / 100,
 
 298                $form->{"unit_$i"}, conv_date($reqdate), conv_i($form->{"project_id_$i"}),
 
 299                $form->{"serialnumber_$i"},
 
 300                $form->{"ordnumber_$i"}, conv_date($form->{"transdate_$i"}),
 
 301                $form->{"cusordnumber_$i"},
 
 302                $form->{"lastcost_$i"},
 
 303                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
 
 304                conv_i($form->{"marge_price_factor_$i"}));
 
 305     do_statement($form, $h_item, $q_item, @values);
 
 307     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 309     foreach my $sinfo (@{ $stock_info }) {
 
 310       @values = ($item_id, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 311                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}));
 
 312       do_statement($form, $h_item_stock, $q_item_stock, @values);
 
 315     CVar->save_custom_variables(module       => 'IC',
 
 316                                 sub_module   => 'delivery_order_items',
 
 317                                 trans_id     => $item_id,
 
 318                                 configs      => $ic_cvar_configs,
 
 320                                 name_prefix  => 'ic_',
 
 321                                 name_postfix => "_$i",
 
 325   $h_item_id->finish();
 
 327   $h_item_stock->finish();
 
 329   ($null, $form->{department_id}) = split(/--/, $form->{department});
 
 333     qq|UPDATE delivery_orders SET
 
 334          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
 
 335          customer_id = ?, reqdate = ?,
 
 336          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
 
 337          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
 
 338          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
 
 339          is_sales = ?, taxzone_id = ?, taxincluded = ?, terms = ?, curr = ?
 
 342   @values = ($form->{donumber}, $form->{ordnumber},
 
 343              $form->{cusordnumber}, conv_date($form->{transdate}),
 
 344              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
 
 345              conv_date($reqdate), $form->{shippingpoint}, $form->{shipvia},
 
 346              $form->{notes}, $form->{intnotes},
 
 347              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
 
 348              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
 
 349              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
 
 350              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
 
 351              $form->{transaction_description},
 
 352              $form->{type} =~ /^sales/ ? 't' : 'f',
 
 353              conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{terms}), $form->{curr},
 
 354              conv_i($form->{id}));
 
 355   do_query($form, $dbh, $query, @values);
 
 358   $form->{name} = $form->{ $form->{vc} };
 
 359   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
 
 361   if (!$form->{shipto_id}) {
 
 362     $form->add_shipto($dbh, $form->{id}, "DO");
 
 365   # save printed, emailed, queued
 
 366   $form->save_status($dbh);
 
 368   # Link this delivery order to the quotations it was created from.
 
 369   RecordLinks->create_links('dbh'        => $dbh,
 
 371                             'from_table' => 'oe',
 
 372                             'from_ids'   => $form->{convert_from_oe_ids},
 
 373                             'to_table'   => 'delivery_orders',
 
 374                             'to_id'      => $form->{id},
 
 376   delete $form->{convert_from_oe_ids};
 
 378   $self->mark_orders_if_delivered('do_id' => $form->{id},
 
 379                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
 
 382   my $rc = $dbh->commit();
 
 384   $form->{saved_donumber} = $form->{donumber};
 
 386   Common::webdav_folder($form) if ($main::webdav);
 
 388   $main::lxdebug->leave_sub();
 
 393 sub mark_orders_if_delivered {
 
 394   $main::lxdebug->enter_sub();
 
 399   Common::check_params(\%params, qw(do_id type));
 
 401   my $myconfig = \%main::myconfig;
 
 402   my $form     = $main::form;
 
 404   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 406   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
 407                                         'from_table' => 'oe',
 
 408                                         'to_table'   => 'delivery_orders',
 
 409                                         'to_id'      => $params{do_id});
 
 411   my ($oe_id)  = $links[0]->{from_id} if (scalar @links);
 
 413   return $main::lxdebug->leave_sub() if (!$oe_id);
 
 415   my $all_units = AM->retrieve_all_units();
 
 417   my $query     = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
 
 419                      LEFT JOIN parts p ON (oi.parts_id = p.id)
 
 420                      WHERE (oi.trans_id = ?)|;
 
 421   my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
 
 423   my %shipped   = $self->get_shipped_qty('type'  => $params{type},
 
 427   while (my $ref = $sth->fetchrow_hashref()) {
 
 428     $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
 
 430     if ($ordered{$ref->{parts_id}}) {
 
 431       $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
 
 433       $ordered{$ref->{parts_id}}             = $ref;
 
 439   map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
 
 442   foreach my $part (values %ordered) {
 
 443     if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
 
 450     $query = qq|UPDATE oe
 
 453     do_query($form, $dbh, $query, $oe_id);
 
 454     $dbh->commit() if (!$params{dbh});
 
 457   $main::lxdebug->leave_sub();
 
 461   $main::lxdebug->enter_sub();
 
 466   Common::check_params(\%params, qw(ids));
 
 468   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
 
 469     $main::lxdebug->leave_sub();
 
 473   my $myconfig = \%main::myconfig;
 
 474   my $form     = $main::form;
 
 476   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 478   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
 
 480   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
 
 482   $dbh->commit() unless ($params{dbh});
 
 484   $main::lxdebug->leave_sub();
 
 488   $main::lxdebug->enter_sub();
 
 492   my $myconfig = \%main::myconfig;
 
 493   my $form     = $main::form;
 
 494   my $spool    = $main::spool;
 
 496   # connect to database
 
 497   my $dbh = $form->get_standard_dbh($myconfig);
 
 500   my $query = qq|SELECT s.spoolfile FROM status s WHERE s.trans_id = ?|;
 
 501   my $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 507   while (($spoolfile) = $sth->fetchrow_array) {
 
 508     push @spoolfiles, $spoolfile;
 
 513   @values = (conv_i($form->{id}));
 
 515   # delete status entries
 
 516   $query = qq|DELETE FROM status
 
 518   do_query($form, $dbh, $query, @values);
 
 520   # delete individual entries
 
 521   $query = qq|DELETE FROM delivery_order_items_stock
 
 522               WHERE delivery_order_item_id IN (
 
 523                 SELECT id FROM delivery_order_items
 
 524                 WHERE delivery_order_id = ?
 
 526   do_query($form, $dbh, $query, @values);
 
 528   # delete individual entries
 
 529   $query = qq|DELETE FROM delivery_order_items
 
 530               WHERE delivery_order_id = ?|;
 
 531   do_query($form, $dbh, $query, @values);
 
 534   $query = qq|DELETE FROM delivery_orders
 
 536   do_query($form, $dbh, $query, @values);
 
 538   $query = qq|DELETE FROM shipto
 
 539               WHERE trans_id = ? AND module = 'DO'|;
 
 540   do_query($form, $dbh, $query, @values);
 
 542   my $rc = $dbh->commit();
 
 545     foreach $spoolfile (@spoolfiles) {
 
 546       unlink "$spool/$spoolfile" if $spoolfile;
 
 550   $main::lxdebug->leave_sub();
 
 556   $main::lxdebug->enter_sub();
 
 561   my $myconfig = \%main::myconfig;
 
 562   my $form     = $main::form;
 
 564   # connect to database
 
 565   my $dbh = $form->get_standard_dbh($myconfig);
 
 567   my ($query, $query_add, @values, $sth, $ref);
 
 569   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 572   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
 
 574   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
 
 576   if ($mode eq 'default') {
 
 577     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate, current_date AS reqdate|);
 
 578     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 581     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
 
 583     $main::lxdebug->leave_sub();
 
 588   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
 
 589   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
 
 591   # retrieve order for single id
 
 592   # NOTE: this query is intended to fetch all information only ONCE.
 
 593   # so if any of these infos is important (or even different) for any item,
 
 594   # it will be killed out and then has to be fetched from the item scope query further down
 
 596     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
 
 597          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
 
 598          e.name AS employee, dord.employee_id, dord.salesman_id,
 
 599          dord.${vc}_id, cv.name AS ${vc},
 
 600          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
 
 601          d.description AS department, dord.language_id,
 
 603          dord.globalproject_id, dord.delivered, dord.transaction_description,
 
 604          dord.taxzone_id, dord.taxincluded, dord.terms, dord.curr
 
 605        FROM delivery_orders dord
 
 606        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
 
 607        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
 608        LEFT JOIN department d ON (dord.department_id = d.id)
 
 609        WHERE dord.id IN ($do_ids_placeholders)|;
 
 610   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
 
 612   delete $form->{"${vc}_id"};
 
 613   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 614     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
 
 616       $main::lxdebug->leave_sub();
 
 621     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
 
 622     $form->{donumber_array} .= $form->{donumber} . ' ';
 
 626   $form->{donumber_array} =~ s/\s*$//g;
 
 628   $form->{saved_donumber} = $form->{donumber};
 
 630   # if not given, fill transdate with current_date
 
 631   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
 
 633   if ($mode eq 'single') {
 
 634     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
 
 635     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
 
 637     $ref   = $sth->fetchrow_hashref("NAME_lc");
 
 639     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 642     # get printed, emailed and queued
 
 643     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
 
 644     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 646     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 647       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
 648       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
 649       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
 
 652     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
 658   my %oid = ('Pg'     => 'oid',
 
 659              'Oracle' => 'rowid');
 
 661   # retrieve individual items
 
 662   # this query looks up all information about the items
 
 663   # stuff different from the whole will not be overwritten, but saved with a suffix.
 
 665     qq|SELECT doi.id AS delivery_order_items_id,
 
 666          p.partnumber, p.assembly, doi.description, doi.qty,
 
 667          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.bin, p.notes AS partnotes,
 
 668          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
 
 669          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
 
 670          doi.price_factor_id, doi.price_factor, doi.marge_price_factor,
 
 671          pr.projectnumber, dord.transdate AS dord_transdate,
 
 673        FROM delivery_order_items doi
 
 674        JOIN parts p ON (doi.parts_id = p.id)
 
 675        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
 
 676        LEFT JOIN project pr ON (doi.project_id = pr.id)
 
 677        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 678        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
 
 679        ORDER BY doi.$oid{$myconfig->{dbdriver}}|;
 
 681   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
 683   # Retrieve custom variables.
 
 684   foreach my $doi (@{ $form->{form_details} }) {
 
 685     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 687                                            sub_module => 'delivery_order_items',
 
 688                                            trans_id   => $doi->{delivery_order_items_id},
 
 690     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
 
 693   if ($mode eq 'single') {
 
 694     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 697       qq|SELECT qty, unit, bin_id, warehouse_id, chargenumber, bestbefore
 
 698          FROM delivery_order_items_stock
 
 699          WHERE delivery_order_item_id = ?|;
 
 700     my $sth = prepare_query($form, $dbh, $query);
 
 702     foreach my $doi (@{ $form->{form_details} }) {
 
 703       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
 
 705       while (my $ref = $sth->fetchrow_hashref()) {
 
 706         push @{ $requests }, $ref;
 
 709       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
 
 715   Common::webdav_folder($form) if ($main::webdav);
 
 717   $main::lxdebug->leave_sub();
 
 723   $main::lxdebug->enter_sub();
 
 727   my $myconfig = \%main::myconfig;
 
 728   my $form     = $main::form;
 
 730   # connect to database
 
 731   my $dbh = $form->get_standard_dbh($myconfig);
 
 741   my %oid = ('Pg'     => 'oid',
 
 742              'Oracle' => 'rowid');
 
 744   my (@project_ids, %projectnumbers, %projectdescriptions);
 
 746   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
 
 748   # sort items by partsgroup
 
 749   for $i (1 .. $form->{rowcount}) {
 
 751     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
 752       $partsgroup = $form->{"partsgroup_$i"};
 
 754     push @partsgroup, [$i, $partsgroup];
 
 755     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
 
 759     $query = "SELECT id, projectnumber, description FROM project WHERE id IN (" .
 
 760       join(", ", map("?", @project_ids)) . ")";
 
 761     $sth = prepare_execute_query($form, $dbh, $query, @project_ids);
 
 762     while (my $ref = $sth->fetchrow_hashref()) {
 
 763       $projectnumbers{$ref->{id}} = $ref->{projectnumber};
 
 764       $projectdescriptions{$ref->{id}} = $ref->{description};
 
 769   $form->{"globalprojectnumber"} =
 
 770     $projectnumbers{$form->{"globalproject_id"}};
 
 771   $form->{"globalprojectdescription"} =
 
 772       $projectdescriptions{$form->{"globalproject_id"}};
 
 774   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
 
 776                     JOIN parts p ON (a.parts_id = p.id)
 
 777                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 780   my $h_pg     = prepare_query($form, $dbh, $q_pg);
 
 782   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
 
 783                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
 
 784   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
 
 786   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 790   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 792   $form->{TEMPLATE_ARRAYS} = { };
 
 793   IC->prepare_parts_for_printing();
 
 796     qw(runningnumber number description longdescription qty unit
 
 797        partnotes serialnumber reqdate projectnumber projectdescription
 
 798        si_runningnumber si_number si_description
 
 799        si_warehouse si_bin si_chargenumber si_bestbefore si_qty si_unit);
 
 801   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays);
 
 803   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 805   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 806   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 809   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
 812     next if (!$form->{"id_$i"});
 
 816     if ($item->[1] ne $sameitem) {
 
 817       push(@{ $form->{description} }, qq|$item->[1]|);
 
 818       $sameitem = $item->[1];
 
 820       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 823     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 825     # add number, description and qty to $form->{number}, ....
 
 827     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
 
 829     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
 
 830     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
 
 831     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
 
 832     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
 
 833     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
 
 834     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
 
 835     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
 
 836     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
 
 837     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
 
 838     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $projectnumbers{$form->{"project_id_$i"}};
 
 839     push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} },
 
 840       $projectdescriptions{$form->{"project_id_$i"}};
 
 842     if ($form->{"assembly_$i"}) {
 
 845       # get parts and push them onto the stack
 
 847       if ($form->{groupitems}) {
 
 849           qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
 
 851         $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
 
 854       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
 
 856       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
 
 857         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
 858           map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 859           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
 860           push(@{ $form->{description} }, $sameitem);
 
 863         push(@{ $form->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq|, $ref->{partnumber}, $ref->{description}|);
 
 865         map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 869     if ($form->{"inventory_accno_$i"} && !$form->{"assembly_$i"}) {
 
 870       my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 872       foreach my $si (@{ $stock_info }) {
 
 875         do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
 
 876         my $bin_wh = $h_bin_wh->fetchrow_hashref();
 
 878         push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$position-1] }, $num_si;
 
 879         push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$position-1] },        $form->{"partnumber_$i"};
 
 880         push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$position-1] },   $form->{"description_$i"};
 
 881         push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$position-1] },     $bin_wh->{warehouse};
 
 882         push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$position-1] },           $bin_wh->{bin};
 
 883         push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$position-1] },  $si->{chargenumber};
 
 884         push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$position-1] },    $si->{bestbefore};
 
 885         push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
 
 886         push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$position-1] },          $si->{unit};
 
 890     map { push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} }, $form->{"ic_cvar_$_->{name}_$i"} } @{ $ic_cvar_configs };
 
 896   $form->{username} = $myconfig->{name};
 
 898   $main::lxdebug->leave_sub();
 
 901 sub project_description {
 
 902   $main::lxdebug->enter_sub();
 
 904   my ($self, $dbh, $id) = @_;
 
 906   my $form     =  $main::form;
 
 908   my $query = qq|SELECT description FROM project WHERE id = ?|;
 
 909   my ($value) = selectrow_query($form, $dbh, $query, $id);
 
 911   $main::lxdebug->leave_sub();
 
 916 sub unpack_stock_information {
 
 917   $main::lxdebug->enter_sub();
 
 922   Common::check_params_x(\%params, qw(packed));
 
 926   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
 
 928   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
 
 930   foreach my $entry (@{ $unpacked }) {
 
 931     next if ('HASH' eq ref $entry);
 
 936   $main::lxdebug->leave_sub();
 
 941 sub get_item_availability {
 
 942   $main::lxdebug->enter_sub();
 
 947   Common::check_params(\%params, qw(parts_id));
 
 949   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
 
 950   my $form      = $main::form;
 
 951   my $myconfig  = \%main::myconfig;
 
 954     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
 
 955          w.description AS warehousedescription,
 
 956          b.description AS bindescription
 
 958        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
 
 959        LEFT JOIN bin b       ON (i.bin_id       = b.id)
 
 960        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
 
 961        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
 
 963        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
 
 965   my $contents = selectall_hashref_query($form, $form->get_standard_dbh($myconfig), $query, @parts_ids);
 
 967   $main::lxdebug->leave_sub();
 
 969   return @{ $contents };
 
 973 sub check_stock_availability {
 
 974   $main::lxdebug->enter_sub();
 
 979   Common::check_params(\%params, qw(requests parts_id));
 
 981   my $myconfig    = \%main::myconfig;
 
 982   my $form        =  $main::form;
 
 984   my $dbh         = $form->get_standard_dbh($myconfig);
 
 986   my $units       = AM->retrieve_units($myconfig, $form);
 
 988   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
 
 989   my $unit_factor = $units->{$partunit}->{factor} || 1;
 
 991   my @contents    = $self->get_item_availability(%params);
 
 995   foreach my $sinfo (@{ $params{requests} }) {
 
 998     foreach my $row (@contents) {
 
 999       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
 
1000                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
 
1001                ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
 
1002                ($row->{bestbefore}   ne $sinfo->{bestbefore}));
 
1006       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
 
1008       if ($base_qty > $row->{qty}) {
 
1009         $sinfo->{error} = 1;
 
1010         push @errors, $sinfo;
 
1016     push @errors, $sinfo if (!$found);
 
1019   $main::lxdebug->leave_sub();
 
1024 sub transfer_in_out {
 
1025   $main::lxdebug->enter_sub();
 
1030   Common::check_params(\%params, qw(direction requests));
 
1032   if (!@{ $params{requests} }) {
 
1033     $main::lxdebug->leave_sub();
 
1037   my $myconfig = \%main::myconfig;
 
1038   my $form     = $main::form;
 
1040   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
 
1044   foreach my $request (@{ $params{requests} }) {
 
1046       'parts_id'               => $request->{parts_id},
 
1047       "${prefix}_warehouse_id" => $request->{warehouse_id},
 
1048       "${prefix}_bin_id"       => $request->{bin_id},
 
1049       'chargenumber'           => $request->{chargenumber},
 
1050       'bestbefore'             => $request->{bestbefore},
 
1051       'qty'                    => $request->{qty},
 
1052       'unit'                   => $request->{unit},
 
1053       'oe_id'                  => $form->{id},
 
1054       'shippingdate'           => 'current_date',
 
1055       'transfer_type'          => $params{direction} eq 'in' ? 'stock' : 'shipped',
 
1059   WH->transfer(@transfers);
 
1061   $main::lxdebug->leave_sub();
 
1064 sub get_shipped_qty {
 
1065   $main::lxdebug->enter_sub();
 
1070   Common::check_params(\%params, qw(type oe_id));
 
1072   my $myconfig = \%main::myconfig;
 
1073   my $form     = $main::form;
 
1075   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1077   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
1078                                         'from_table' => 'oe',
 
1079                                         'from_id'    => $params{oe_id},
 
1080                                         'to_table'   => 'delivery_orders');
 
1081   my @values   = map { $_->{to_id} } @links;
 
1083   if (!scalar @values) {
 
1084     $main::lxdebug->leave_sub();
 
1089     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
 
1090        FROM delivery_order_items doi
 
1091        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
 
1092        LEFT JOIN parts p ON (doi.parts_id = p.id)
 
1093        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
 
1096   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
 
1097   my $all_units = AM->retrieve_all_units();
 
1099   foreach my $entry (@{ $entries }) {
 
1100     $entry->{qty} *= $all_units->{$entry->{unit}}->{factor} / $all_units->{$entry->{partunit}}->{factor};
 
1102     if (!$ship{$entry->{parts_id}}) {
 
1103       $ship{$entry->{parts_id}} = $entry;
 
1105       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
 
1109   $main::lxdebug->leave_sub();
 
1114 sub is_marked_as_delivered {
 
1115   $main::lxdebug->enter_sub();
 
1120   Common::check_params(\%params, qw(id));
 
1122   my $myconfig    = \%main::myconfig;
 
1123   my $form        = $main::form;
 
1125   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1127   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
 
1129   $main::lxdebug->leave_sub();
 
1131   return $delivered ? 1 : 0;