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});
 
 108   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
 
 109     next unless ($form->{$item});
 
 110     push @where,  qq|dord.$item ILIKE ?|;
 
 111     push @values, '%' . $form->{$item} . '%';
 
 114   if (($form->{open} || $form->{closed}) &&
 
 115       ($form->{open} ne $form->{closed})) {
 
 116     push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
 
 119   if (($form->{notdelivered} || $form->{delivered}) &&
 
 120       ($form->{notdelivered} ne $form->{delivered})) {
 
 121     push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
 
 124   if($form->{transdatefrom}) {
 
 125     push @where,  qq|dord.transdate >= ?|;
 
 126     push @values, conv_date($form->{transdatefrom});
 
 129   if($form->{transdateto}) {
 
 130     push @where,  qq|dord.transdate <= ?|;
 
 131     push @values, conv_date($form->{transdateto});
 
 135     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
 
 138   my %allowed_sort_columns = (
 
 139     "transdate"               => "dord.transdate",
 
 141     "donumber"                => "dord.donumber",
 
 142     "ordnumber"               => "dord.ordnumber",
 
 144     "employee"                => "e.name",
 
 145     "salesman"                => "sm.name",
 
 146     "shipvia"                 => "dord.shipvia",
 
 147     "transaction_description" => "dord.transaction_description"
 
 150   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 151   my $sortorder = "dord.id";
 
 152   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
 
 153     $sortorder = $allowed_sort_columns{$form->{sort}};
 
 156   $query .= qq| ORDER by | . $sortorder . " $sortdir";
 
 158   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
 
 160   if (scalar @{ $form->{DO} }) {
 
 164          WHERE NOT COALESCE(quotation, FALSE)
 
 166            AND (COALESCE(${vc}_id, 0) != 0)|;
 
 168     my $sth = prepare_query($form, $dbh, $query);
 
 170     foreach my $dord (@{ $form->{DO} }) {
 
 171       next unless ($dord->{ordnumber});
 
 172       do_statement($form, $sth, $query, $dord->{ordnumber});
 
 173       ($dord->{oe_id}) = $sth->fetchrow_array();
 
 179   $main::lxdebug->leave_sub();
 
 183   $main::lxdebug->enter_sub();
 
 187   my $myconfig = \%main::myconfig;
 
 188   my $form     = $main::form;
 
 190   # connect to database, turn off autocommit
 
 191   my $dbh = $form->get_standard_dbh($myconfig);
 
 193   my ($query, @values, $sth, $null);
 
 195   my $all_units = AM->retrieve_units($myconfig, $form);
 
 196   $form->{all_units} = $all_units;
 
 198   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 201   $form->{donumber}    = $form->update_defaults($myconfig, $form->{type} eq 'sales_delivery_order' ? 'sdonumber' : 'pdonumber', $dbh) unless $form->{donumber};
 
 202   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
 
 203   $form->get_employee($dbh) unless ($form->{employee_id});
 
 205   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
 
 209     $query = qq|DELETE FROM delivery_order_items_stock WHERE delivery_order_item_id IN (SELECT id FROM delivery_order_items WHERE delivery_order_id = ?)|;
 
 210     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 212     $query = qq|DELETE FROM delivery_order_items WHERE delivery_order_id = ?|;
 
 213     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 215     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
 
 216     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 220     $query = qq|SELECT nextval('id')|;
 
 221     ($form->{id}) = selectrow_query($form, $dbh, $query);
 
 223     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id) VALUES (?, '', ?)|;
 
 224     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}));
 
 230   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 231   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 234   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
 
 235   my @part_ids    = keys %part_id_map;
 
 239     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
 
 240     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
 
 243   my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
 
 244   my $h_item_id = prepare_query($form, $dbh, $q_item_id);
 
 247     qq|INSERT INTO delivery_order_items (
 
 248          id, delivery_order_id, parts_id, description, longdescription, qty, base_qty,
 
 249          sellprice, discount, unit, reqdate, project_id, serialnumber,
 
 250          ordnumber, transdate, cusordnumber,
 
 251          lastcost, price_factor_id, price_factor, marge_price_factor)
 
 252        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 
 253          (SELECT factor FROM price_factors WHERE id = ?), ?)|;
 
 254   my $h_item = prepare_query($form, $dbh, $q_item);
 
 257     qq|INSERT INTO delivery_order_items_stock (delivery_order_item_id, qty, unit, warehouse_id, bin_id, chargenumber)
 
 258        VALUES (?, ?, ?, ?, ?, ?)|;
 
 259   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
 
 261   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 263   for my $i (1 .. $form->{rowcount}) {
 
 264     next if (!$form->{"id_$i"});
 
 266     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 268     my $item_unit = $part_unit_map{$form->{"id_$i"}};
 
 271     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
 
 272       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
 
 274     my $baseqty = $form->{"qty_$i"} * $basefactor;
 
 276     $form->{"lastcost_$i"} *= 1;
 
 278     # set values to 0 if nothing entered
 
 279     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
 
 280     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 282     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
 
 283     my $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 285     $reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
 
 287     do_statement($form, $h_item_id, $q_item_id);
 
 288     my ($item_id) = $h_item_id->fetchrow_array();
 
 290     # save detail record in delivery_order_items table
 
 291     @values = (conv_i($item_id), conv_i($form->{id}), conv_i($form->{"id_$i"}),
 
 292                $form->{"description_$i"}, $form->{"longdescription_$i"},
 
 293                $form->{"qty_$i"}, $baseqty,
 
 294                $form->{"sellprice_$i"}, $form->{"discount_$i"},
 
 295                $form->{"unit_$i"}, conv_date($reqdate), conv_i($form->{"project_id_$i"}),
 
 296                $form->{"serialnumber_$i"},
 
 297                $form->{"ordnumber_$i"}, conv_date($form->{"transdate_$i"}),
 
 298                $form->{"cusordnumber_$i"},
 
 299                $form->{"lastcost_$i"},
 
 300                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
 
 301                conv_i($form->{"marge_price_factor_$i"}));
 
 302     do_statement($form, $h_item, $q_item, @values);
 
 304     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 306     foreach my $sinfo (@{ $stock_info }) {
 
 307       @values = ($item_id, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 308                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber});
 
 309       do_statement($form, $h_item_stock, $q_item_stock, @values);
 
 312     CVar->save_custom_variables(module       => 'IC',
 
 313                                 sub_module   => 'delivery_order_items',
 
 314                                 trans_id     => $item_id,
 
 315                                 configs      => $ic_cvar_configs,
 
 317                                 name_prefix  => 'ic_',
 
 318                                 name_postfix => "_$i",
 
 322   $h_item_id->finish();
 
 324   $h_item_stock->finish();
 
 326   ($null, $form->{department_id}) = split(/--/, $form->{department});
 
 330     qq|UPDATE delivery_orders SET
 
 331          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
 
 332          customer_id = ?, reqdate = ?,
 
 333          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
 
 334          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
 
 335          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
 
 336          is_sales = ?, taxzone_id = ?, taxincluded = ?, terms = ?, curr = ?
 
 339   @values = ($form->{donumber}, $form->{ordnumber},
 
 340              $form->{cusordnumber}, conv_date($form->{transdate}),
 
 341              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
 
 342              conv_date($reqdate), $form->{shippingpoint}, $form->{shipvia},
 
 343              $form->{notes}, $form->{intnotes},
 
 344              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
 
 345              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
 
 346              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
 
 347              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
 
 348              $form->{transaction_description},
 
 349              $form->{type} =~ /^sales/ ? 't' : 'f',
 
 350              conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{terms}), $form->{curr},
 
 351              conv_i($form->{id}));
 
 352   do_query($form, $dbh, $query, @values);
 
 355   $form->{name} = $form->{ $form->{vc} };
 
 356   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
 
 358   if (!$form->{shipto_id}) {
 
 359     $form->add_shipto($dbh, $form->{id}, "DO");
 
 362   # save printed, emailed, queued
 
 363   $form->save_status($dbh);
 
 365   # Link this delivery order to the quotations it was created from.
 
 366   RecordLinks->create_links('dbh'        => $dbh,
 
 368                             'from_table' => 'oe',
 
 369                             'from_ids'   => $form->{convert_from_oe_ids},
 
 370                             'to_table'   => 'delivery_orders',
 
 371                             'to_id'      => $form->{id},
 
 373   delete $form->{convert_from_oe_ids};
 
 375   $self->mark_orders_if_delivered('do_id' => $form->{id},
 
 376                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
 
 379   my $rc = $dbh->commit();
 
 381   $form->{saved_donumber} = $form->{donumber};
 
 383   Common::webdav_folder($form) if ($main::webdav);
 
 385   $main::lxdebug->leave_sub();
 
 390 sub mark_orders_if_delivered {
 
 391   $main::lxdebug->enter_sub();
 
 396   Common::check_params(\%params, qw(do_id type));
 
 398   my $myconfig = \%main::myconfig;
 
 399   my $form     = $main::form;
 
 401   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 403   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
 404                                         'from_table' => 'oe',
 
 405                                         'to_table'   => 'delivery_orders',
 
 406                                         'to_id'      => $params{do_id});
 
 408   my ($oe_id)  = $links[0]->{from_id} if (scalar @links);
 
 410   return $main::lxdebug->leave_sub() if (!$oe_id);
 
 412   my $all_units = AM->retrieve_all_units();
 
 414   my $query     = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
 
 416                      LEFT JOIN parts p ON (oi.parts_id = p.id)
 
 417                      WHERE (oi.trans_id = ?)|;
 
 418   my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
 
 420   my %shipped   = $self->get_shipped_qty('type'  => $params{type},
 
 424   while (my $ref = $sth->fetchrow_hashref()) {
 
 425     $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
 
 427     if ($ordered{$ref->{parts_id}}) {
 
 428       $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
 
 430       $ordered{$ref->{parts_id}}             = $ref;
 
 436   map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
 
 439   foreach my $part (values %ordered) {
 
 440     if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
 
 447     $query = qq|UPDATE oe
 
 450     do_query($form, $dbh, $query, $oe_id);
 
 451     $dbh->commit() if (!$params{dbh});
 
 454   $main::lxdebug->leave_sub();
 
 458   $main::lxdebug->enter_sub();
 
 463   Common::check_params(\%params, qw(ids));
 
 465   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
 
 466     $main::lxdebug->leave_sub();
 
 470   my $myconfig = \%main::myconfig;
 
 471   my $form     = $main::form;
 
 473   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 475   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
 
 477   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
 
 479   $dbh->commit() unless ($params{dbh});
 
 481   $main::lxdebug->leave_sub();
 
 485   $main::lxdebug->enter_sub();
 
 489   my $myconfig = \%main::myconfig;
 
 490   my $form     = $main::form;
 
 491   my $spool    = $main::spool;
 
 493   # connect to database
 
 494   my $dbh = $form->get_standard_dbh($myconfig);
 
 497   my $query = qq|SELECT s.spoolfile FROM status s WHERE s.trans_id = ?|;
 
 498   my $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 504   while (($spoolfile) = $sth->fetchrow_array) {
 
 505     push @spoolfiles, $spoolfile;
 
 510   @values = (conv_i($form->{id}));
 
 512   # delete status entries
 
 513   $query = qq|DELETE FROM status
 
 515   do_query($form, $dbh, $query, @values);
 
 517   # delete individual entries
 
 518   $query = qq|DELETE FROM delivery_order_items_stock
 
 519               WHERE delivery_order_item_id IN (
 
 520                 SELECT id FROM delivery_order_items
 
 521                 WHERE delivery_order_id = ?
 
 523   do_query($form, $dbh, $query, @values);
 
 525   # delete individual entries
 
 526   $query = qq|DELETE FROM delivery_order_items
 
 527               WHERE delivery_order_id = ?|;
 
 528   do_query($form, $dbh, $query, @values);
 
 531   $query = qq|DELETE FROM delivery_orders
 
 533   do_query($form, $dbh, $query, @values);
 
 535   $query = qq|DELETE FROM shipto
 
 536               WHERE trans_id = ? AND module = 'DO'|;
 
 537   do_query($form, $dbh, $query, @values);
 
 539   my $rc = $dbh->commit();
 
 542     foreach $spoolfile (@spoolfiles) {
 
 543       unlink "$spool/$spoolfile" if $spoolfile;
 
 547   $main::lxdebug->leave_sub();
 
 553   $main::lxdebug->enter_sub();
 
 558   my $myconfig = \%main::myconfig;
 
 559   my $form     = $main::form;
 
 561   # connect to database
 
 562   my $dbh = $form->get_standard_dbh($myconfig);
 
 564   my ($query, $query_add, @values, $sth, $ref);
 
 566   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 569   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
 
 571   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
 
 573   if ($mode eq 'default') {
 
 574     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate, current_date AS reqdate|);
 
 575     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 578     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
 
 580     $main::lxdebug->leave_sub();
 
 585   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
 
 586   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
 
 588   # retrieve order for single id
 
 589   # NOTE: this query is intended to fetch all information only ONCE.
 
 590   # so if any of these infos is important (or even different) for any item,
 
 591   # it will be killed out and then has to be fetched from the item scope query further down
 
 593     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
 
 594          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
 
 595          e.name AS employee, dord.employee_id, dord.salesman_id,
 
 596          dord.${vc}_id, cv.name AS ${vc},
 
 597          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
 
 598          d.description AS department, dord.language_id,
 
 600          dord.globalproject_id, dord.delivered, dord.transaction_description,
 
 601          dord.taxzone_id, dord.taxincluded, dord.terms, dord.curr
 
 602        FROM delivery_orders dord
 
 603        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
 
 604        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
 605        LEFT JOIN department d ON (dord.department_id = d.id)
 
 606        WHERE dord.id IN ($do_ids_placeholders)|;
 
 607   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
 
 609   delete $form->{"${vc}_id"};
 
 610   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 611     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
 
 613       $main::lxdebug->leave_sub();
 
 618     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
 
 619     $form->{donumber_array} .= $form->{donumber} . ' ';
 
 623   $form->{saved_donumber} = $form->{donumber};
 
 625   # if not given, fill transdate with current_date
 
 626   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
 
 628   if ($mode eq 'single') {
 
 629     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
 
 630     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
 
 632     $ref   = $sth->fetchrow_hashref("NAME_lc");
 
 634     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 637     # get printed, emailed and queued
 
 638     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
 
 639     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 641     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 642       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
 643       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
 644       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
 
 647     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
 653   my %oid = ('Pg'     => 'oid',
 
 654              'Oracle' => 'rowid');
 
 656   # retrieve individual items
 
 657   # this query looks up all information about the items
 
 658   # stuff different from the whole will not be overwritten, but saved with a suffix.
 
 660     qq|SELECT doi.id AS delivery_order_items_id,
 
 661          p.partnumber, p.assembly, doi.description, doi.qty,
 
 662          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.bin, p.notes AS partnotes,
 
 663          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
 
 664          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
 
 665          doi.price_factor_id, doi.price_factor, doi.marge_price_factor,
 
 666          pr.projectnumber, dord.transdate AS dord_transdate,
 
 668        FROM delivery_order_items doi
 
 669        JOIN parts p ON (doi.parts_id = p.id)
 
 670        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
 
 671        LEFT JOIN project pr ON (doi.project_id = pr.id)
 
 672        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 673        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
 
 674        ORDER BY doi.$oid{$myconfig->{dbdriver}}|;
 
 676   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
 678   # Retrieve custom variables.
 
 679   foreach my $doi (@{ $form->{form_details} }) {
 
 680     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 682                                            sub_module => 'delivery_order_items',
 
 683                                            trans_id   => $doi->{delivery_order_items_id},
 
 685     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
 
 688   if ($mode eq 'single') {
 
 689     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 692       qq|SELECT qty, unit, bin_id, warehouse_id, chargenumber
 
 693          FROM delivery_order_items_stock
 
 694          WHERE delivery_order_item_id = ?|;
 
 695     my $sth = prepare_query($form, $dbh, $query);
 
 697     foreach my $doi (@{ $form->{form_details} }) {
 
 698       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
 
 700       while (my $ref = $sth->fetchrow_hashref()) {
 
 701         push @{ $requests }, $ref;
 
 704       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
 
 710   Common::webdav_folder($form) if ($main::webdav);
 
 712   $main::lxdebug->leave_sub();
 
 718   $main::lxdebug->enter_sub();
 
 722   my $myconfig = \%main::myconfig;
 
 723   my $form     = $main::form;
 
 725   # connect to database
 
 726   my $dbh = $form->get_standard_dbh($myconfig);
 
 736   my %oid = ('Pg'     => 'oid',
 
 737              'Oracle' => 'rowid');
 
 739   my (@project_ids, %projectnumbers);
 
 741   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
 
 743   # sort items by partsgroup
 
 744   for $i (1 .. $form->{rowcount}) {
 
 746     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
 747       $partsgroup = $form->{"partsgroup_$i"};
 
 749     push @partsgroup, [$i, $partsgroup];
 
 750     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
 
 754     $query = "SELECT id, projectnumber FROM project WHERE id IN (" .
 
 755       join(", ", map("?", @project_ids)) . ")";
 
 756     $sth = prepare_execute_query($form, $dbh, $query, @project_ids);
 
 757     while (my $ref = $sth->fetchrow_hashref()) {
 
 758       $projectnumbers{$ref->{id}} = $ref->{projectnumber};
 
 763   $form->{"globalprojectnumber"} =
 
 764     $projectnumbers{$form->{"globalproject_id"}};
 
 766   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
 
 768                     JOIN parts p ON (a.parts_id = p.id)
 
 769                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 772   my $h_pg     = prepare_query($form, $dbh, $q_pg);
 
 774   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
 
 775                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
 
 776   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
 
 778   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 782   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 784   $form->{TEMPLATE_ARRAYS} = { };
 
 785   IC->prepare_parts_for_printing();
 
 788     qw(runningnumber number description longdescription qty unit
 
 789        partnotes serialnumber reqdate projectnumber
 
 790        si_runningnumber si_number si_description
 
 791        si_warehouse si_bin si_chargenumber si_qty si_unit);
 
 793   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays);
 
 795   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 797   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 798   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 801   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
 804     next if (!$form->{"id_$i"});
 
 808     if ($item->[1] ne $sameitem) {
 
 809       push(@{ $form->{description} }, qq|$item->[1]|);
 
 810       $sameitem = $item->[1];
 
 812       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 815     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 817     # add number, description and qty to $form->{number}, ....
 
 819     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
 
 821     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
 
 822     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
 
 823     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
 
 824     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
 
 825     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
 
 826     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
 
 827     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
 
 828     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
 
 829     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
 
 830     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $projectnumbers{$form->{"project_id_$i"}};
 
 832     if ($form->{"assembly_$i"}) {
 
 835       # get parts and push them onto the stack
 
 837       if ($form->{groupitems}) {
 
 839           qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
 
 841         $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
 
 844       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
 
 846       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
 
 847         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
 848           map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 849           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
 850           push(@{ $form->{description} }, $sameitem);
 
 853         push(@{ $form->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq|, $ref->{partnumber}, $ref->{description}|);
 
 855         map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 859     if ($form->{"inventory_accno_$i"} && !$form->{"assembly_$i"}) {
 
 860       my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 862       foreach my $si (@{ $stock_info }) {
 
 865         do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
 
 866         my $bin_wh = $h_bin_wh->fetchrow_hashref();
 
 868         push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$position-1] }, $num_si;
 
 869         push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$position-1] },        $form->{"partnumber_$i"};
 
 870         push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$position-1] },   $form->{"description_$i"};
 
 871         push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$position-1] },     $bin_wh->{warehouse};
 
 872         push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$position-1] },           $bin_wh->{bin};
 
 873         push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$position-1] },  $si->{chargenumber};
 
 874         push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
 
 875         push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$position-1] },          $si->{unit};
 
 879     map { push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} }, $form->{"ic_cvar_$_->{name}_$i"} } @{ $ic_cvar_configs };
 
 885   $form->{username} = $myconfig->{name};
 
 887   $main::lxdebug->leave_sub();
 
 890 sub project_description {
 
 891   $main::lxdebug->enter_sub();
 
 893   my ($self, $dbh, $id) = @_;
 
 895   my $form     =  $main::form;
 
 897   my $query = qq|SELECT description FROM project WHERE id = ?|;
 
 898   my ($value) = selectrow_query($form, $dbh, $query, $id);
 
 900   $main::lxdebug->leave_sub();
 
 905 sub unpack_stock_information {
 
 906   $main::lxdebug->enter_sub();
 
 911   Common::check_params_x(\%params, qw(packed));
 
 915   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
 
 917   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
 
 919   foreach my $entry (@{ $unpacked }) {
 
 920     next if ('HASH' eq ref $entry);
 
 925   $main::lxdebug->leave_sub();
 
 930 sub get_item_availability {
 
 931   $main::lxdebug->enter_sub();
 
 936   Common::check_params(\%params, qw(parts_id));
 
 938   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
 
 939   my $form      = $main::form;
 
 940   my $myconfig  = \%main::myconfig;
 
 943     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, SUM(qty) AS qty, i.parts_id,
 
 944          w.description AS warehousedescription,
 
 945          b.description AS bindescription
 
 947        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
 
 948        LEFT JOIN bin b       ON (i.bin_id       = b.id)
 
 949        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
 
 950        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.parts_id, w.description, b.description
 
 952        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber)
 
 954   my $contents = selectall_hashref_query($form, $form->get_standard_dbh($myconfig), $query, @parts_ids);
 
 956   $main::lxdebug->leave_sub();
 
 958   return @{ $contents };
 
 962 sub check_stock_availability {
 
 963   $main::lxdebug->enter_sub();
 
 968   Common::check_params(\%params, qw(requests parts_id));
 
 970   my $myconfig    = \%main::myconfig;
 
 971   my $form        =  $main::form;
 
 973   my $dbh         = $form->get_standard_dbh($myconfig);
 
 975   my $units       = AM->retrieve_units($myconfig, $form);
 
 977   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
 
 978   my $unit_factor = $units->{$partunit}->{factor} || 1;
 
 980   my @contents    = $self->get_item_availability(%params);
 
 984   foreach my $sinfo (@{ $params{requests} }) {
 
 987     foreach my $row (@contents) {
 
 988       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
 
 989                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
 
 990                ($row->{chargenumber} ne $sinfo->{chargenumber}));
 
 994       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
 
 996       if ($base_qty > $row->{qty}) {
 
 998         push @errors, $sinfo;
 
1004     push @errors, $sinfo if (!$found);
 
1007   $main::lxdebug->leave_sub();
 
1012 sub transfer_in_out {
 
1013   $main::lxdebug->enter_sub();
 
1018   Common::check_params(\%params, qw(direction requests));
 
1020   if (!@{ $params{requests} }) {
 
1021     $main::lxdebug->leave_sub();
 
1025   my $myconfig = \%main::myconfig;
 
1026   my $form     = $main::form;
 
1028   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
 
1032   foreach my $request (@{ $params{requests} }) {
 
1034       'parts_id'               => $request->{parts_id},
 
1035       "${prefix}_warehouse_id" => $request->{warehouse_id},
 
1036       "${prefix}_bin_id"       => $request->{bin_id},
 
1037       'chargenumber'           => $request->{chargenumber},
 
1038       'qty'                    => $request->{qty},
 
1039       'unit'                   => $request->{unit},
 
1040       'oe_id'                  => $form->{id},
 
1041       'shippingdate'           => 'current_date',
 
1042       'transfer_type'          => $params{direction} eq 'in' ? 'stock' : 'shipped',
 
1046   WH->transfer(@transfers);
 
1048   $main::lxdebug->leave_sub();
 
1051 sub get_shipped_qty {
 
1052   $main::lxdebug->enter_sub();
 
1057   Common::check_params(\%params, qw(type oe_id));
 
1059   my $myconfig = \%main::myconfig;
 
1060   my $form     = $main::form;
 
1062   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1064   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
1065                                         'from_table' => 'oe',
 
1066                                         'from_id'    => $params{oe_id},
 
1067                                         'to_table'   => 'delivery_orders');
 
1068   my @values   = map { $_->{to_id} } @links;
 
1070   if (!scalar @values) {
 
1071     $main::lxdebug->leave_sub();
 
1076     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
 
1077        FROM delivery_order_items doi
 
1078        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
 
1079        LEFT JOIN parts p ON (doi.parts_id = p.id)
 
1080        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
 
1083   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
 
1084   my $all_units = AM->retrieve_all_units();
 
1086   foreach my $entry (@{ $entries }) {
 
1087     $entry->{qty} *= $all_units->{$entry->{unit}}->{factor} / $all_units->{$entry->{partunit}}->{factor};
 
1089     if (!$ship{$entry->{parts_id}}) {
 
1090       $ship{$entry->{parts_id}} = $entry;
 
1092       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
 
1096   $main::lxdebug->leave_sub();
 
1101 sub is_marked_as_delivered {
 
1102   $main::lxdebug->enter_sub();
 
1107   Common::check_params(\%params, qw(id));
 
1109   my $myconfig    = \%main::myconfig;
 
1110   my $form        = $main::form;
 
1112   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1114   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
 
1116   $main::lxdebug->leave_sub();
 
1118   return $delivered ? 1 : 0;