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);
 
  45   $main::lxdebug->enter_sub();
 
  49   my $myconfig = \%main::myconfig;
 
  50   my $form     = $main::form;
 
  53   my $dbh = $form->get_standard_dbh($myconfig);
 
  55   my (@where, @values, $where);
 
  57   my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
 
  60     qq|SELECT dord.id, dord.donumber, dord.ordnumber, dord.transdate,
 
  61          ct.name, dord.${vc}_id, dord.globalproject_id,
 
  62          dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
 
  63          dord.transaction_description,
 
  64          pr.projectnumber AS globalprojectnumber,
 
  67        FROM delivery_orders dord
 
  68        LEFT JOIN $vc ct ON (dord.${vc}_id = ct.id)
 
  69        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
  70        LEFT JOIN employee sm ON (dord.salesman_id = sm.id)
 
  71        LEFT JOIN project pr ON (dord.globalproject_id = pr.id)|;
 
  73   push @where, ($form->{type} eq 'sales_delivery_order' ? '' : 'NOT ') . qq|COALESCE(dord.is_sales, FALSE)|;
 
  75   my $department_id = (split /--/, $form->{department})[1];
 
  77     push @where,  qq|dord.department_id = ?|;
 
  78     push @values, conv_i($department_id);
 
  81   if ($form->{project_id}) {
 
  83       qq|(dord.globalproject_id = ?) OR EXISTS
 
  84           (SELECT * FROM delivery_order_items doi
 
  85            WHERE (doi.project_id = ?) AND (oi.delivery_order_id = dord.id))|;
 
  86     push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
 
  89   if ($form->{"${vc}_id"}) {
 
  90     push @where,  qq|dord.${vc}_id = ?|;
 
  91     push @values, $form->{"${vc}_id"};
 
  93   } elsif ($form->{$vc}) {
 
  94     push @where,  qq|ct.name ILIKE ?|;
 
  95     push @values, '%' . $form->{$vc} . '%';
 
  98   foreach my $item (qw(employee_id salesman_id)) {
 
  99     next unless ($form->{$item});
 
 100     push @where, "dord.$item = ?";
 
 101     push @values, conv_i($form->{$item});
 
 104   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
 
 105     next unless ($form->{$item});
 
 106     push @where,  qq|dord.$item ILIKE ?|;
 
 107     push @values, '%' . $form->{$item} . '%';
 
 110   if (!($form->{open} && $form->{closed})) {
 
 111     push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
 
 114   if (($form->{notdelivered} || $form->{delivered}) &&
 
 115       ($form->{notdelivered} ne $form->{delivered})) {
 
 116     push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
 
 119   if($form->{transdatefrom}) {
 
 120     push @where,  qq|dord.transdate >= ?|;
 
 121     push @values, conv_date($form->{transdatefrom});
 
 124   if($form->{transdateto}) {
 
 125     push @where,  qq|dord.transdate <= ?|;
 
 126     push @values, conv_date($form->{transdateto});
 
 130     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
 
 133   my %allowed_sort_columns = (
 
 134     "transdate"               => "dord.transdate",
 
 136     "donumber"                => "dord.donumber",
 
 137     "ordnumber"               => "dord.ordnumber",
 
 139     "employee"                => "e.name",
 
 140     "salesman"                => "sm.name",
 
 141     "shipvia"                 => "dord.shipvia",
 
 142     "transaction_description" => "dord.transaction_description"
 
 145   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 146   my $sortorder = "dord.id";
 
 147   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
 
 148     $sortorder = $allowed_sort_columns{$form->{sort}};
 
 151   $query .= qq| ORDER by | . $sortorder . " $sortdir";
 
 153   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
 
 155   if (scalar @{ $form->{DO} }) {
 
 159          WHERE NOT COALESCE(quotation, FALSE)
 
 161            AND (COALESCE(${vc}_id, 0) != 0)|;
 
 163     my $sth = prepare_query($form, $dbh, $query);
 
 165     foreach my $dord (@{ $form->{DO} }) {
 
 166       next unless ($dord->{ordnumber});
 
 167       do_statement($form, $sth, $query, $dord->{ordnumber});
 
 168       ($dord->{oe_id}) = $sth->fetchrow_array();
 
 174   $main::lxdebug->leave_sub();
 
 178   $main::lxdebug->enter_sub();
 
 182   my $myconfig = \%main::myconfig;
 
 183   my $form     = $main::form;
 
 185   # connect to database, turn off autocommit
 
 186   my $dbh = $form->get_standard_dbh($myconfig);
 
 188   my ($query, @values, $sth, $null);
 
 190   my $all_units = AM->retrieve_units($myconfig, $form);
 
 191   $form->{all_units} = $all_units;
 
 193   $form->{donumber}    = $form->update_defaults($myconfig, $form->{type} eq 'sales_delivery_order' ? 'sdonumber' : 'pdonumber', $dbh) unless $form->{donumber};
 
 194   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
 
 195   $form->get_employee($dbh) unless ($form->{employee_id});
 
 197   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
 
 201     $query = qq|DELETE FROM delivery_order_items_stock WHERE delivery_order_item_id IN (SELECT id FROM delivery_order_items WHERE delivery_order_id = ?)|;
 
 202     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 204     $query = qq|DELETE FROM delivery_order_items WHERE delivery_order_id = ?|;
 
 205     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 207     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
 
 208     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 212     $query = qq|SELECT nextval('id')|;
 
 213     ($form->{id}) = selectrow_query($form, $dbh, $query);
 
 215     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id) VALUES (?, '', ?)|;
 
 216     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}));
 
 222   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 223   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 226   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
 
 227   my @part_ids    = keys %part_id_map;
 
 231     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
 
 232     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
 
 235   my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
 
 236   my $h_item_id = prepare_query($form, $dbh, $q_item_id);
 
 239     qq|INSERT INTO delivery_order_items (
 
 240          id, delivery_order_id, parts_id, description, longdescription, qty, base_qty,
 
 241          sellprice, discount, unit, reqdate, project_id, serialnumber,
 
 242          ordnumber, transdate, cusordnumber,
 
 243          lastcost, price_factor_id, price_factor, marge_price_factor)
 
 244        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 
 245          (SELECT factor FROM price_factors WHERE id = ?), ?)|;
 
 246   my $h_item = prepare_query($form, $dbh, $q_item);
 
 249     qq|INSERT INTO delivery_order_items_stock (delivery_order_item_id, qty, unit, warehouse_id, bin_id, chargenumber)
 
 250        VALUES (?, ?, ?, ?, ?, ?)|;
 
 251   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
 
 253   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 255   for my $i (1 .. $form->{rowcount}) {
 
 256     next if (!$form->{"id_$i"});
 
 258     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 260     my $item_unit = $part_unit_map{$form->{"id_$i"}};
 
 263     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
 
 264       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
 
 266     my $baseqty = $form->{"qty_$i"} * $basefactor;
 
 268     $form->{"lastcost_$i"} *= 1;
 
 270     # set values to 0 if nothing entered
 
 271     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
 
 272     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 274     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
 
 275     $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 277     $reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
 
 279     do_statement($form, $h_item_id, $q_item_id);
 
 280     my ($item_id) = $h_item_id->fetchrow_array();
 
 282     # save detail record in delivery_order_items table
 
 283     @values = (conv_i($item_id), conv_i($form->{id}), conv_i($form->{"id_$i"}),
 
 284                $form->{"description_$i"}, $form->{"longdescription_$i"},
 
 285                $form->{"qty_$i"}, $baseqty,
 
 286                $form->{"sellprice_$i"}, $form->{"discount_$i"},
 
 287                $form->{"unit_$i"}, conv_date($reqdate), conv_i($form->{"project_id_$i"}),
 
 288                $form->{"serialnumber_$i"},
 
 289                $form->{"ordnumber_$i"}, conv_date($form->{"transdate_$i"}),
 
 290                $form->{"cusordnumber_$i"},
 
 291                $form->{"lastcost_$i"},
 
 292                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
 
 293                conv_i($form->{"marge_price_factor_$i"}));
 
 294     do_statement($form, $h_item, $q_item, @values);
 
 296     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 298     foreach my $sinfo (@{ $stock_info }) {
 
 299       @values = ($item_id, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 300                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber});
 
 301       do_statement($form, $h_item_stock, $q_item_stock, @values);
 
 305   $h_item_id->finish();
 
 307   $h_item_stock->finish();
 
 309   ($null, $form->{department_id}) = split(/--/, $form->{department});
 
 313     qq|UPDATE delivery_orders SET
 
 314          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
 
 315          customer_id = ?, reqdate = ?,
 
 316          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
 
 317          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
 
 318          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
 
 322   @values = ($form->{donumber}, $form->{ordnumber},
 
 323              $form->{cusordnumber}, conv_date($form->{transdate}),
 
 324              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
 
 325              conv_date($reqdate), $form->{shippingpoint}, $form->{shipvia},
 
 326              $form->{notes}, $form->{intnotes},
 
 327              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
 
 328              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
 
 329              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
 
 330              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
 
 331              $form->{transaction_description},
 
 332              $form->{type} =~ /^sales/ ? 't' : 'f',
 
 333              conv_i($form->{id}));
 
 334   do_query($form, $dbh, $query, @values);
 
 337   $form->{name} = $form->{ $form->{vc} };
 
 338   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
 
 340   if (!$form->{shipto_id}) {
 
 341     $form->add_shipto($dbh, $form->{id}, "DO");
 
 344   # save printed, emailed, queued
 
 345   $form->save_status($dbh);
 
 347   # Link this delivery order to the quotations it was created from.
 
 348   RecordLinks->create_links('dbh'        => $dbh,
 
 350                             'from_table' => 'oe',
 
 351                             'from_ids'   => $form->{convert_from_oe_ids},
 
 352                             'to_table'   => 'delivery_orders',
 
 353                             'to_id'      => $form->{id},
 
 355   delete $form->{convert_from_oe_ids};
 
 357   $self->mark_orders_if_delivered('do_id' => $form->{id},
 
 358                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
 
 361   my $rc = $dbh->commit();
 
 363   $form->{saved_donumber} = $form->{donumber};
 
 365   Common::webdav_folder($form) if ($main::webdav);
 
 367   $main::lxdebug->leave_sub();
 
 372 sub mark_orders_if_delivered {
 
 373   $main::lxdebug->enter_sub();
 
 378   Common::check_params(\%params, qw(do_id type));
 
 380   my $myconfig = \%main::myconfig;
 
 381   my $form     = $main::form;
 
 383   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 385   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
 386                                         'from_table' => 'oe',
 
 387                                         'to_table'   => 'delivery_orders',
 
 388                                         'to_id'      => $params{do_id});
 
 390   my ($oe_id)  = $links[0]->{from_id} if (scalar @links);
 
 392   $main::lxdebug->message(0, "oe_id $oe_id");
 
 394   return $main::lxdebug->leave_sub() if (!$oe_id);
 
 396   my $all_units = AM->retrieve_all_units();
 
 398   $query        = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
 
 400                      LEFT JOIN parts p ON (oi.parts_id = p.id)
 
 401                      WHERE (oi.trans_id = ?)|;
 
 402   my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
 
 404   my %shipped   = $self->get_shipped_qty('type'  => $params{type},
 
 408   do_statement($form, $sth, $query, $oe_id);
 
 410   while (my $ref = $sth->fetchrow_hashref()) {
 
 411     $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
 
 413     if ($ordered{$ref->{parts_id}}) {
 
 414       $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
 
 416       $ordered{$ref->{parts_id}}             = $ref;
 
 422   map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
 
 425   foreach my $part (values %ordered) {
 
 426     if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
 
 433     $query = qq|UPDATE oe
 
 436     do_query($form, $dbh, $query, $oe_id);
 
 437     $dbh->commit() if (!$params{dbh});
 
 440   $main::lxdebug->leave_sub();
 
 444   $main::lxdebug->enter_sub();
 
 449   Common::check_params(\%params, qw(ids));
 
 451   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
 
 452     $main::lxdebug->leave_sub();
 
 456   my $myconfig = \%main::myconfig;
 
 457   my $form     = $main::form;
 
 459   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 461   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
 
 463   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
 
 465   $dbh->commit() unless ($params{dbh});
 
 467   $main::lxdebug->leave_sub();
 
 471   $main::lxdebug->enter_sub();
 
 475   my $myconfig = \%main::myconfig;
 
 476   my $form     = $main::form;
 
 477   my $spool    = $main::spool;
 
 479   # connect to database
 
 480   my $dbh = $form->get_standard_dbh($myconfig);
 
 483   my $query = qq|SELECT s.spoolfile FROM status s WHERE s.trans_id = ?|;
 
 484   my $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 489   while (($spoolfile) = $sth->fetchrow_array) {
 
 490     push @spoolfiles, $spoolfile;
 
 495   @values = (conv_i($form->{id}));
 
 497   # delete status entries
 
 498   $query = qq|DELETE FROM status
 
 500   do_query($form, $dbh, $query, @values);
 
 502   # delete individual entries
 
 503   $query = qq|DELETE FROM delivery_order_items_stock
 
 504               WHERE delivery_order_item_id IN (
 
 505                 SELECT id FROM delivery_order_items
 
 506                 WHERE delivery_order_id = ?
 
 508   do_query($form, $dbh, $query, @values);
 
 510   # delete individual entries
 
 511   $query = qq|DELETE FROM delivery_order_items
 
 512               WHERE delivery_order_id = ?|;
 
 513   do_query($form, $dbh, $query, @values);
 
 516   $query = qq|DELETE FROM delivery_orders
 
 518   do_query($form, $dbh, $query, @values);
 
 520   $query = qq|DELETE FROM shipto
 
 521               WHERE trans_id = ? AND module = 'DO'|;
 
 522   do_query($form, $dbh, $query, @values);
 
 524   my $rc = $dbh->commit();
 
 527     foreach $spoolfile (@spoolfiles) {
 
 528       unlink "$spool/$spoolfile" if $spoolfile;
 
 532   $main::lxdebug->leave_sub();
 
 538   $main::lxdebug->enter_sub();
 
 543   my $myconfig = \%main::myconfig;
 
 544   my $form     = $main::form;
 
 546   # connect to database
 
 547   my $dbh = $form->get_standard_dbh($myconfig);
 
 549   my ($query, $query_add, @values, $sth, $ref);
 
 551   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
 
 553   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
 
 555   if ($mode eq 'default') {
 
 556     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate, current_date AS reqdate|);
 
 557     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 560     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
 
 562     $main::lxdebug->leave_sub();
 
 567   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
 
 568   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
 
 570   # retrieve order for single id
 
 571   # NOTE: this query is intended to fetch all information only ONCE.
 
 572   # so if any of these infos is important (or even different) for any item,
 
 573   # it will be killed out and then has to be fetched from the item scope query further down
 
 575     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
 
 576          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
 
 577          e.name AS employee, dord.employee_id, dord.salesman_id,
 
 578          dord.${vc}_id, cv.name AS ${vc},
 
 579          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
 
 580          d.description AS department, dord.language_id,
 
 582          dord.globalproject_id, dord.delivered, dord.transaction_description
 
 583        FROM delivery_orders dord
 
 584        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
 
 585        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
 586        LEFT JOIN department d ON (dord.department_id = d.id)
 
 587        WHERE dord.id IN ($do_ids_placeholders)|;
 
 588   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
 
 590   delete $form->{"${vc}_id"};
 
 591   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
 592     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
 
 594       $main::lxdebug->leave_sub();
 
 599     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
 
 603   $form->{saved_donumber} = $form->{donumber};
 
 605   # if not given, fill transdate with current_date
 
 606   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
 
 608   if ($mode eq 'single') {
 
 609     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
 
 610     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
 
 612     $ref   = $sth->fetchrow_hashref(NAME_lc);
 
 614     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 617     # get printed, emailed and queued
 
 618     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
 
 619     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 621     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
 622       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
 623       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
 624       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
 
 627     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
 633   my %oid = ('Pg'     => 'oid',
 
 634              'Oracle' => 'rowid');
 
 636   # retrieve individual items
 
 637   # this query looks up all information about the items
 
 638   # stuff different from the whole will not be overwritten, but saved with a suffix.
 
 640     qq|SELECT doi.id AS delivery_order_items_id,
 
 641          p.partnumber, p.assembly, doi.description, doi.qty,
 
 642          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.bin, p.notes AS partnotes,
 
 643          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
 
 644          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
 
 645          doi.price_factor_id, doi.price_factor, doi.marge_price_factor,
 
 648        FROM delivery_order_items doi
 
 649        JOIN parts p ON (doi.parts_id = p.id)
 
 650        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
 
 651        LEFT JOIN project pr ON (doi.project_id = pr.id)
 
 652        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 653        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
 
 654        ORDER BY doi.$oid{$myconfig->{dbdriver}}|;
 
 656   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
 658   if ($mode eq 'single') {
 
 659     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 662       qq|SELECT qty, unit, bin_id, warehouse_id, chargenumber
 
 663          FROM delivery_order_items_stock
 
 664          WHERE delivery_order_item_id = ?|;
 
 665     my $sth = prepare_query($form, $dbh, $query);
 
 667     foreach my $doi (@{ $form->{form_details} }) {
 
 668       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
 
 670       while (my $ref = $sth->fetchrow_hashref()) {
 
 671         push @{ $requests }, $ref;
 
 674       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
 
 680   Common::webdav_folder($form) if ($main::webdav);
 
 682   $main::lxdebug->leave_sub();
 
 688   $main::lxdebug->enter_sub();
 
 692   my $myconfig = \%main::myconfig;
 
 693   my $form     = $main::form;
 
 695   # connect to database
 
 696   my $dbh = $form->get_standard_dbh($myconfig);
 
 706   my %oid = ('Pg'     => 'oid',
 
 707              'Oracle' => 'rowid');
 
 709   my (@project_ids, %projectnumbers);
 
 711   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
 
 713   # sort items by partsgroup
 
 714   for $i (1 .. $form->{rowcount}) {
 
 716     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
 717       $partsgroup = $form->{"partsgroup_$i"};
 
 719     push @partsgroup, [$i, $partsgroup];
 
 720     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
 
 724     $query = "SELECT id, projectnumber FROM project WHERE id IN (" .
 
 725       join(", ", map("?", @project_ids)) . ")";
 
 726     $sth = prepare_execute_query($form, $dbh, $query, @project_ids);
 
 727     while (my $ref = $sth->fetchrow_hashref()) {
 
 728       $projectnumbers{$ref->{id}} = $ref->{projectnumber};
 
 733   $form->{"globalprojectnumber"} =
 
 734     $projectnumbers{$form->{"globalproject_id"}};
 
 736   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
 
 738                     JOIN parts p ON (a.parts_id = p.id)
 
 739                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 741                       AND a.id = ? $sortorder|;
 
 742   my $h_pg     = prepare_query($form, $dbh, $q_pg);
 
 744   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
 
 745                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
 
 746   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
 
 748   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 753     qw(runningnumber number description longdescription qty unit
 
 754        partnotes serialnumber reqdate projectnumber
 
 755        si_runningnumber si_number si_description
 
 756        si_warehouse si_bin si_chargenumber si_qty si_unit);
 
 759   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
 762     next if (!$form->{"id_$i"});
 
 766     if ($item->[1] ne $sameitem) {
 
 767       push(@{ $form->{description} }, qq|$item->[1]|);
 
 768       $sameitem = $item->[1];
 
 770       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 773     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 775     # add number, description and qty to $form->{number}, ....
 
 777     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
 
 779     push @{ $form->{runningnumber} },   $position;
 
 780     push @{ $form->{number} },          $form->{"partnumber_$i"};
 
 781     push @{ $form->{description} },     $form->{"description_$i"};
 
 782     push @{ $form->{longdescription} }, $form->{"longdescription_$i"};
 
 783     push @{ $form->{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
 
 784     push @{ $form->{unit} },            $form->{"unit_$i"};
 
 785     push @{ $form->{partnotes} },       $form->{"partnotes_$i"};
 
 786     push @{ $form->{serialnumber} },    $form->{"serialnumber_$i"};
 
 787     push @{ $form->{reqdate} },         $form->{"reqdate_$i"};
 
 788     push @{ $form->{projectnumber} },   $projectnumbers{$form->{"project_id_$i"}};
 
 790     if ($form->{"assembly_$i"}) {
 
 793       # get parts and push them onto the stack
 
 795       if ($form->{groupitems}) {
 
 797           qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
 
 799         $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
 
 802       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
 
 804       while (my $ref = $h_pg->fetchrow_hashref(NAME_lc)) {
 
 805         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
 806           map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 807           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
 808           push(@{ $form->{description} }, $sameitem);
 
 811         push(@{ $form->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq|, $ref->{partnumber}, $ref->{description}|);
 
 813         map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 817     if ($form->{"inventory_accno_$i"} && !$form->{"assembly_$i"}) {
 
 818       my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 820       foreach my $si (@{ $stock_info }) {
 
 823         do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
 
 824         my $bin_wh = $h_bin_wh->fetchrow_hashref();
 
 826         push @{ $form->{si_runningnumber} }, $num_si;
 
 827         push @{ $form->{si_number} },        $form->{"partnumber_$i"};
 
 828         push @{ $form->{si_description} },   $form->{"description_$i"};
 
 829         push @{ $form->{si_warehouse} },     $bin_wh->{warehouse};
 
 830         push @{ $form->{si_bin} },           $bin_wh->{bin};
 
 831         push @{ $form->{si_chargenumber} },  $si->{chargenumber};
 
 832         push @{ $form->{si_qty} },           $form->format_amount($myconfig, $si->{qty} * 1);
 
 833         push @{ $form->{si_unit} },          $si->{unit};
 
 841   $form->{username} = $myconfig->{name};
 
 843   $main::lxdebug->leave_sub();
 
 846 sub project_description {
 
 847   $main::lxdebug->enter_sub();
 
 849   my ($self, $dbh, $id) = @_;
 
 851   my $query = qq|SELECT description FROM project WHERE id = ?|;
 
 852   my ($value) = selectrow_query($form, $dbh, $query, $id);
 
 854   $main::lxdebug->leave_sub();
 
 859 sub unpack_stock_information {
 
 860   $main::lxdebug->enter_sub();
 
 865   Common::check_params_x(\%params, qw(packed));
 
 869   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
 
 871   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
 
 873   foreach my $entry (@{ $unpacked }) {
 
 874     next if ('HASH' eq ref $entry);
 
 879   $main::lxdebug->leave_sub();
 
 884 sub get_item_availability {
 
 885   $main::lxdebug->enter_sub();
 
 890   Common::check_params(\%params, qw(parts_id));
 
 892   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
 
 893   my $form      = $main::form;
 
 896     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, SUM(qty) AS qty, i.parts_id,
 
 897          w.description AS warehousedescription,
 
 898          b.description AS bindescription
 
 900        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
 
 901        LEFT JOIN bin b       ON (i.bin_id       = b.id)
 
 902        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
 
 904        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.parts_id, w.description, b.description
 
 905        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber)|;
 
 907   my $contents = selectall_hashref_query($form, $form->get_standard_dbh($myconfig), $query, @parts_ids);
 
 909   $main::lxdebug->leave_sub();
 
 911   return @{ $contents };
 
 915 sub check_stock_availability {
 
 916   $main::lxdebug->enter_sub();
 
 921   Common::check_params(\%params, qw(requests parts_id));
 
 923   my $myconfig    = \%main::myconfig;
 
 924   my $form        =  $main::form;
 
 926   my $dbh         = $form->get_standard_dbh($myconfig);
 
 928   my $units       = AM->retrieve_units($myconfig, $form);
 
 930   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
 
 931   my $unit_factor = $units->{$partunit}->{factor} || 1;
 
 933   my @contents    = $self->get_item_availability(%params);
 
 937   foreach my $sinfo (@{ $params{requests} }) {
 
 940     foreach my $row (@contents) {
 
 941       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
 
 942                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
 
 943                ($row->{chargenumber} ne $sinfo->{chargenumber}));
 
 947       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
 
 949       if ($base_qty > $row->{qty}) {
 
 951         push @errors, $sinfo;
 
 957     push @errors, $sinfo if (!$found);
 
 960   $main::lxdebug->leave_sub();
 
 965 sub transfer_in_out {
 
 966   $main::lxdebug->enter_sub();
 
 971   Common::check_params(\%params, qw(direction requests));
 
 973   if (!@{ $params{requests} }) {
 
 974     $main::lxdebug->leave_sub();
 
 978   my $myconfig = \%main::myconfig;
 
 979   my $form     = $main::form;
 
 981   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
 
 985   foreach my $request (@{ $params{requests} }) {
 
 987       'parts_id'               => $request->{parts_id},
 
 988       "${prefix}_warehouse_id" => $request->{warehouse_id},
 
 989       "${prefix}_bin_id"       => $request->{bin_id},
 
 990       'chargenumber'           => $request->{chargenumber},
 
 991       'qty'                    => $request->{qty},
 
 992       'unit'                   => $request->{unit},
 
 993       'oe_id'                  => $form->{id},
 
 994       'shippingdate'           => 'current_date',
 
 995       'transfer_type'          => $params{direction} eq 'in' ? 'stock' : 'shipped',
 
 999   WH->transfer(@transfers);
 
1001   $main::lxdebug->leave_sub();
 
1004 sub get_shipped_qty {
 
1005   $main::lxdebug->enter_sub();
 
1010   Common::check_params(\%params, qw(type oe_id));
 
1012   my $myconfig = \%main::myconfig;
 
1013   my $form     = $main::form;
 
1015   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1017   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
1018                                         'from_table' => 'oe',
 
1019                                         'from_id'    => $params{oe_id},
 
1020                                         'to_table'   => 'delivery_orders');
 
1021   my @values   = map { $_->{to_id} } @links;
 
1023   if (!scalar @values) {
 
1024     $main::lxdebug->leave_sub();
 
1029     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
 
1030        FROM delivery_order_items doi
 
1031        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
 
1032        LEFT JOIN parts p ON (doi.parts_id = p.id)
 
1033        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
 
1036   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
 
1037   my $all_units = AM->retrieve_all_units();
 
1039   foreach my $entry (@{ $entries }) {
 
1040     $entry->{qty} *= $all_units->{$entry->{unit}}->{factor} / $all_units->{$entry->{partunit}}->{factor};
 
1042     if (!$ship{$entry->{parts_id}}) {
 
1043       $ship{$entry->{parts_id}} = $entry;
 
1045       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
 
1049   $main::lxdebug->leave_sub();
 
1054 sub is_marked_as_delivered {
 
1055   $main::lxdebug->enter_sub();
 
1060   Common::check_params(\%params, qw(id));
 
1062   my $myconfig    = \%main::myconfig;
 
1063   my $form        = $main::form;
 
1065   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1067   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
 
1069   $main::lxdebug->leave_sub();
 
1071   return $delivered ? 1 : 0;