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);
 
  46   $main::lxdebug->enter_sub();
 
  50   my $myconfig = \%main::myconfig;
 
  51   my $form     = $main::form;
 
  54   my $dbh = $form->get_standard_dbh($myconfig);
 
  56   my (@where, @values, $where);
 
  58   my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
 
  61     qq|SELECT dord.id, dord.donumber, dord.ordnumber, dord.transdate,
 
  62          ct.name, dord.${vc}_id, dord.globalproject_id,
 
  63          dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
 
  64          dord.transaction_description,
 
  65          pr.projectnumber AS globalprojectnumber,
 
  68        FROM delivery_orders dord
 
  69        LEFT JOIN $vc ct ON (dord.${vc}_id = ct.id)
 
  70        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
  71        LEFT JOIN employee sm ON (dord.salesman_id = sm.id)
 
  72        LEFT JOIN project pr ON (dord.globalproject_id = pr.id)|;
 
  74   push @where, ($form->{type} eq 'sales_delivery_order' ? '' : 'NOT ') . qq|COALESCE(dord.is_sales, FALSE)|;
 
  76   my $department_id = (split /--/, $form->{department})[1];
 
  78     push @where,  qq|dord.department_id = ?|;
 
  79     push @values, conv_i($department_id);
 
  82   if ($form->{project_id}) {
 
  84       qq|(dord.globalproject_id = ?) OR EXISTS
 
  85           (SELECT * FROM delivery_order_items doi
 
  86            WHERE (doi.project_id = ?) AND (oi.delivery_order_id = dord.id))|;
 
  87     push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
 
  90   if ($form->{"${vc}_id"}) {
 
  91     push @where,  qq|dord.${vc}_id = ?|;
 
  92     push @values, $form->{"${vc}_id"};
 
  94   } elsif ($form->{$vc}) {
 
  95     push @where,  qq|ct.name ILIKE ?|;
 
  96     push @values, '%' . $form->{$vc} . '%';
 
  99   foreach my $item (qw(employee_id salesman_id)) {
 
 100     next unless ($form->{$item});
 
 101     push @where, "dord.$item = ?";
 
 102     push @values, conv_i($form->{$item});
 
 105   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
 
 106     next unless ($form->{$item});
 
 107     push @where,  qq|dord.$item ILIKE ?|;
 
 108     push @values, '%' . $form->{$item} . '%';
 
 111   if (!($form->{open} && $form->{closed})) {
 
 112     push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
 
 115   if (($form->{notdelivered} || $form->{delivered}) &&
 
 116       ($form->{notdelivered} ne $form->{delivered})) {
 
 117     push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
 
 120   if($form->{transdatefrom}) {
 
 121     push @where,  qq|dord.transdate >= ?|;
 
 122     push @values, conv_date($form->{transdatefrom});
 
 125   if($form->{transdateto}) {
 
 126     push @where,  qq|dord.transdate <= ?|;
 
 127     push @values, conv_date($form->{transdateto});
 
 131     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
 
 134   my %allowed_sort_columns = (
 
 135     "transdate"               => "dord.transdate",
 
 137     "donumber"                => "dord.donumber",
 
 138     "ordnumber"               => "dord.ordnumber",
 
 140     "employee"                => "e.name",
 
 141     "salesman"                => "sm.name",
 
 142     "shipvia"                 => "dord.shipvia",
 
 143     "transaction_description" => "dord.transaction_description"
 
 146   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 147   my $sortorder = "dord.id";
 
 148   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
 
 149     $sortorder = $allowed_sort_columns{$form->{sort}};
 
 152   $query .= qq| ORDER by | . $sortorder . " $sortdir";
 
 154   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
 
 156   if (scalar @{ $form->{DO} }) {
 
 160          WHERE NOT COALESCE(quotation, FALSE)
 
 162            AND (COALESCE(${vc}_id, 0) != 0)|;
 
 164     my $sth = prepare_query($form, $dbh, $query);
 
 166     foreach my $dord (@{ $form->{DO} }) {
 
 167       next unless ($dord->{ordnumber});
 
 168       do_statement($form, $sth, $query, $dord->{ordnumber});
 
 169       ($dord->{oe_id}) = $sth->fetchrow_array();
 
 175   $main::lxdebug->leave_sub();
 
 179   $main::lxdebug->enter_sub();
 
 183   my $myconfig = \%main::myconfig;
 
 184   my $form     = $main::form;
 
 186   # connect to database, turn off autocommit
 
 187   my $dbh = $form->get_standard_dbh($myconfig);
 
 189   my ($query, @values, $sth, $null);
 
 191   my $all_units = AM->retrieve_units($myconfig, $form);
 
 192   $form->{all_units} = $all_units;
 
 194   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 197   $form->{donumber}    = $form->update_defaults($myconfig, $form->{type} eq 'sales_delivery_order' ? 'sdonumber' : 'pdonumber', $dbh) unless $form->{donumber};
 
 198   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
 
 199   $form->get_employee($dbh) unless ($form->{employee_id});
 
 201   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
 
 205     $query = qq|DELETE FROM delivery_order_items_stock WHERE delivery_order_item_id IN (SELECT id FROM delivery_order_items WHERE delivery_order_id = ?)|;
 
 206     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 208     $query = qq|DELETE FROM delivery_order_items WHERE delivery_order_id = ?|;
 
 209     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 211     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
 
 212     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 216     $query = qq|SELECT nextval('id')|;
 
 217     ($form->{id}) = selectrow_query($form, $dbh, $query);
 
 219     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id) VALUES (?, '', ?)|;
 
 220     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}));
 
 226   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 227   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 230   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
 
 231   my @part_ids    = keys %part_id_map;
 
 235     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
 
 236     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
 
 239   my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
 
 240   my $h_item_id = prepare_query($form, $dbh, $q_item_id);
 
 243     qq|INSERT INTO delivery_order_items (
 
 244          id, delivery_order_id, parts_id, description, longdescription, qty, base_qty,
 
 245          sellprice, discount, unit, reqdate, project_id, serialnumber,
 
 246          ordnumber, transdate, cusordnumber,
 
 247          lastcost, price_factor_id, price_factor, marge_price_factor)
 
 248        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 
 249          (SELECT factor FROM price_factors WHERE id = ?), ?)|;
 
 250   my $h_item = prepare_query($form, $dbh, $q_item);
 
 253     qq|INSERT INTO delivery_order_items_stock (delivery_order_item_id, qty, unit, warehouse_id, bin_id, chargenumber)
 
 254        VALUES (?, ?, ?, ?, ?, ?)|;
 
 255   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
 
 257   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 259   for my $i (1 .. $form->{rowcount}) {
 
 260     next if (!$form->{"id_$i"});
 
 262     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 264     my $item_unit = $part_unit_map{$form->{"id_$i"}};
 
 267     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
 
 268       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
 
 270     my $baseqty = $form->{"qty_$i"} * $basefactor;
 
 272     $form->{"lastcost_$i"} *= 1;
 
 274     # set values to 0 if nothing entered
 
 275     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
 
 276     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 278     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
 
 279     $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 281     $reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
 
 283     do_statement($form, $h_item_id, $q_item_id);
 
 284     my ($item_id) = $h_item_id->fetchrow_array();
 
 286     # save detail record in delivery_order_items table
 
 287     @values = (conv_i($item_id), conv_i($form->{id}), conv_i($form->{"id_$i"}),
 
 288                $form->{"description_$i"}, $form->{"longdescription_$i"},
 
 289                $form->{"qty_$i"}, $baseqty,
 
 290                $form->{"sellprice_$i"}, $form->{"discount_$i"},
 
 291                $form->{"unit_$i"}, conv_date($reqdate), conv_i($form->{"project_id_$i"}),
 
 292                $form->{"serialnumber_$i"},
 
 293                $form->{"ordnumber_$i"}, conv_date($form->{"transdate_$i"}),
 
 294                $form->{"cusordnumber_$i"},
 
 295                $form->{"lastcost_$i"},
 
 296                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
 
 297                conv_i($form->{"marge_price_factor_$i"}));
 
 298     do_statement($form, $h_item, $q_item, @values);
 
 300     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 302     foreach my $sinfo (@{ $stock_info }) {
 
 303       @values = ($item_id, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 304                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber});
 
 305       do_statement($form, $h_item_stock, $q_item_stock, @values);
 
 308     CVar->save_custom_variables(module       => 'IC',
 
 309                                 sub_module   => 'delivery_order_items',
 
 310                                 trans_id     => $item_id,
 
 311                                 configs      => $ic_cvar_configs,
 
 313                                 name_prefix  => 'ic_',
 
 314                                 name_postfix => "_$i",
 
 318   $h_item_id->finish();
 
 320   $h_item_stock->finish();
 
 322   ($null, $form->{department_id}) = split(/--/, $form->{department});
 
 326     qq|UPDATE delivery_orders SET
 
 327          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
 
 328          customer_id = ?, reqdate = ?,
 
 329          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
 
 330          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
 
 331          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
 
 332          is_sales = ?, taxzone_id = ?, taxincluded = ?, terms = ?, curr = ?
 
 335   @values = ($form->{donumber}, $form->{ordnumber},
 
 336              $form->{cusordnumber}, conv_date($form->{transdate}),
 
 337              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
 
 338              conv_date($reqdate), $form->{shippingpoint}, $form->{shipvia},
 
 339              $form->{notes}, $form->{intnotes},
 
 340              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
 
 341              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
 
 342              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
 
 343              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
 
 344              $form->{transaction_description},
 
 345              $form->{type} =~ /^sales/ ? 't' : 'f',
 
 346              conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{terms}), $form->{curr},
 
 347              conv_i($form->{id}));
 
 348   do_query($form, $dbh, $query, @values);
 
 351   $form->{name} = $form->{ $form->{vc} };
 
 352   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
 
 354   if (!$form->{shipto_id}) {
 
 355     $form->add_shipto($dbh, $form->{id}, "DO");
 
 358   # save printed, emailed, queued
 
 359   $form->save_status($dbh);
 
 361   # Link this delivery order to the quotations it was created from.
 
 362   RecordLinks->create_links('dbh'        => $dbh,
 
 364                             'from_table' => 'oe',
 
 365                             'from_ids'   => $form->{convert_from_oe_ids},
 
 366                             'to_table'   => 'delivery_orders',
 
 367                             'to_id'      => $form->{id},
 
 369   delete $form->{convert_from_oe_ids};
 
 371   $self->mark_orders_if_delivered('do_id' => $form->{id},
 
 372                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
 
 375   my $rc = $dbh->commit();
 
 377   $form->{saved_donumber} = $form->{donumber};
 
 379   Common::webdav_folder($form) if ($main::webdav);
 
 381   $main::lxdebug->leave_sub();
 
 386 sub mark_orders_if_delivered {
 
 387   $main::lxdebug->enter_sub();
 
 392   Common::check_params(\%params, qw(do_id type));
 
 394   my $myconfig = \%main::myconfig;
 
 395   my $form     = $main::form;
 
 397   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 399   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
 400                                         'from_table' => 'oe',
 
 401                                         'to_table'   => 'delivery_orders',
 
 402                                         'to_id'      => $params{do_id});
 
 404   my ($oe_id)  = $links[0]->{from_id} if (scalar @links);
 
 406   return $main::lxdebug->leave_sub() if (!$oe_id);
 
 408   my $all_units = AM->retrieve_all_units();
 
 410   my $query     = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
 
 412                      LEFT JOIN parts p ON (oi.parts_id = p.id)
 
 413                      WHERE (oi.trans_id = ?)|;
 
 414   my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
 
 416   my %shipped   = $self->get_shipped_qty('type'  => $params{type},
 
 420   while (my $ref = $sth->fetchrow_hashref()) {
 
 421     $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
 
 423     if ($ordered{$ref->{parts_id}}) {
 
 424       $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
 
 426       $ordered{$ref->{parts_id}}             = $ref;
 
 432   map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
 
 435   foreach my $part (values %ordered) {
 
 436     if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
 
 443     $query = qq|UPDATE oe
 
 446     do_query($form, $dbh, $query, $oe_id);
 
 447     $dbh->commit() if (!$params{dbh});
 
 450   $main::lxdebug->leave_sub();
 
 454   $main::lxdebug->enter_sub();
 
 459   Common::check_params(\%params, qw(ids));
 
 461   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
 
 462     $main::lxdebug->leave_sub();
 
 466   my $myconfig = \%main::myconfig;
 
 467   my $form     = $main::form;
 
 469   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 471   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
 
 473   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
 
 475   $dbh->commit() unless ($params{dbh});
 
 477   $main::lxdebug->leave_sub();
 
 481   $main::lxdebug->enter_sub();
 
 485   my $myconfig = \%main::myconfig;
 
 486   my $form     = $main::form;
 
 487   my $spool    = $main::spool;
 
 489   # connect to database
 
 490   my $dbh = $form->get_standard_dbh($myconfig);
 
 493   my $query = qq|SELECT s.spoolfile FROM status s WHERE s.trans_id = ?|;
 
 494   my $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 499   while (($spoolfile) = $sth->fetchrow_array) {
 
 500     push @spoolfiles, $spoolfile;
 
 505   @values = (conv_i($form->{id}));
 
 507   # delete status entries
 
 508   $query = qq|DELETE FROM status
 
 510   do_query($form, $dbh, $query, @values);
 
 512   # delete individual entries
 
 513   $query = qq|DELETE FROM delivery_order_items_stock
 
 514               WHERE delivery_order_item_id IN (
 
 515                 SELECT id FROM delivery_order_items
 
 516                 WHERE delivery_order_id = ?
 
 518   do_query($form, $dbh, $query, @values);
 
 520   # delete individual entries
 
 521   $query = qq|DELETE FROM delivery_order_items
 
 522               WHERE delivery_order_id = ?|;
 
 523   do_query($form, $dbh, $query, @values);
 
 526   $query = qq|DELETE FROM delivery_orders
 
 528   do_query($form, $dbh, $query, @values);
 
 530   $query = qq|DELETE FROM shipto
 
 531               WHERE trans_id = ? AND module = 'DO'|;
 
 532   do_query($form, $dbh, $query, @values);
 
 534   my $rc = $dbh->commit();
 
 537     foreach $spoolfile (@spoolfiles) {
 
 538       unlink "$spool/$spoolfile" if $spoolfile;
 
 542   $main::lxdebug->leave_sub();
 
 548   $main::lxdebug->enter_sub();
 
 553   my $myconfig = \%main::myconfig;
 
 554   my $form     = $main::form;
 
 556   # connect to database
 
 557   my $dbh = $form->get_standard_dbh($myconfig);
 
 559   my ($query, $query_add, @values, $sth, $ref);
 
 561   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 564   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
 
 566   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
 
 568   if ($mode eq 'default') {
 
 569     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate, current_date AS reqdate|);
 
 570     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 573     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
 
 575     $main::lxdebug->leave_sub();
 
 580   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
 
 581   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
 
 583   # retrieve order for single id
 
 584   # NOTE: this query is intended to fetch all information only ONCE.
 
 585   # so if any of these infos is important (or even different) for any item,
 
 586   # it will be killed out and then has to be fetched from the item scope query further down
 
 588     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
 
 589          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
 
 590          e.name AS employee, dord.employee_id, dord.salesman_id,
 
 591          dord.${vc}_id, cv.name AS ${vc},
 
 592          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
 
 593          d.description AS department, dord.language_id,
 
 595          dord.globalproject_id, dord.delivered, dord.transaction_description,
 
 596          dord.taxzone_id, dord.taxincluded, dord.terms, dord.curr
 
 597        FROM delivery_orders dord
 
 598        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
 
 599        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
 600        LEFT JOIN department d ON (dord.department_id = d.id)
 
 601        WHERE dord.id IN ($do_ids_placeholders)|;
 
 602   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
 
 604   delete $form->{"${vc}_id"};
 
 605   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
 606     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
 
 608       $main::lxdebug->leave_sub();
 
 613     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
 
 614     $form->{donumber_array} .= $form->{donumber} . ' ';
 
 618   $form->{saved_donumber} = $form->{donumber};
 
 620   # if not given, fill transdate with current_date
 
 621   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
 
 623   if ($mode eq 'single') {
 
 624     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
 
 625     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
 
 627     $ref   = $sth->fetchrow_hashref(NAME_lc);
 
 629     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 632     # get printed, emailed and queued
 
 633     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
 
 634     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 636     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
 637       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
 638       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
 639       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
 
 642     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
 648   my %oid = ('Pg'     => 'oid',
 
 649              'Oracle' => 'rowid');
 
 651   # retrieve individual items
 
 652   # this query looks up all information about the items
 
 653   # stuff different from the whole will not be overwritten, but saved with a suffix.
 
 655     qq|SELECT doi.id AS delivery_order_items_id,
 
 656          p.partnumber, p.assembly, doi.description, doi.qty,
 
 657          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.bin, p.notes AS partnotes,
 
 658          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
 
 659          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
 
 660          doi.price_factor_id, doi.price_factor, doi.marge_price_factor,
 
 663        FROM delivery_order_items doi
 
 664        JOIN parts p ON (doi.parts_id = p.id)
 
 665        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
 
 666        LEFT JOIN project pr ON (doi.project_id = pr.id)
 
 667        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 668        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
 
 669        ORDER BY doi.$oid{$myconfig->{dbdriver}}|;
 
 671   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
 673   # Retrieve custom variables.
 
 674   foreach my $doi (@{ $form->{form_details} }) {
 
 675     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 677                                            sub_module => 'delivery_order_items',
 
 678                                            trans_id   => $doi->{delivery_order_items_id},
 
 680     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
 
 683   if ($mode eq 'single') {
 
 684     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 687       qq|SELECT qty, unit, bin_id, warehouse_id, chargenumber
 
 688          FROM delivery_order_items_stock
 
 689          WHERE delivery_order_item_id = ?|;
 
 690     my $sth = prepare_query($form, $dbh, $query);
 
 692     foreach my $doi (@{ $form->{form_details} }) {
 
 693       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
 
 695       while (my $ref = $sth->fetchrow_hashref()) {
 
 696         push @{ $requests }, $ref;
 
 699       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
 
 705   Common::webdav_folder($form) if ($main::webdav);
 
 707   $main::lxdebug->leave_sub();
 
 713   $main::lxdebug->enter_sub();
 
 717   my $myconfig = \%main::myconfig;
 
 718   my $form     = $main::form;
 
 720   # connect to database
 
 721   my $dbh = $form->get_standard_dbh($myconfig);
 
 731   my %oid = ('Pg'     => 'oid',
 
 732              'Oracle' => 'rowid');
 
 734   my (@project_ids, %projectnumbers);
 
 736   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
 
 738   # sort items by partsgroup
 
 739   for $i (1 .. $form->{rowcount}) {
 
 741     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
 742       $partsgroup = $form->{"partsgroup_$i"};
 
 744     push @partsgroup, [$i, $partsgroup];
 
 745     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
 
 749     $query = "SELECT id, projectnumber FROM project WHERE id IN (" .
 
 750       join(", ", map("?", @project_ids)) . ")";
 
 751     $sth = prepare_execute_query($form, $dbh, $query, @project_ids);
 
 752     while (my $ref = $sth->fetchrow_hashref()) {
 
 753       $projectnumbers{$ref->{id}} = $ref->{projectnumber};
 
 758   $form->{"globalprojectnumber"} =
 
 759     $projectnumbers{$form->{"globalproject_id"}};
 
 761   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
 
 763                     JOIN parts p ON (a.parts_id = p.id)
 
 764                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 766                       AND a.id = ? $sortorder|;
 
 767   my $h_pg     = prepare_query($form, $dbh, $q_pg);
 
 769   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
 
 770                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
 
 771   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
 
 773   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 777   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 780     qw(runningnumber number description longdescription qty unit
 
 781        partnotes serialnumber reqdate projectnumber
 
 782        si_runningnumber si_number si_description
 
 783        si_warehouse si_bin si_chargenumber si_qty si_unit);
 
 785   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 788   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
 791     next if (!$form->{"id_$i"});
 
 795     if ($item->[1] ne $sameitem) {
 
 796       push(@{ $form->{description} }, qq|$item->[1]|);
 
 797       $sameitem = $item->[1];
 
 799       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 802     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 804     # add number, description and qty to $form->{number}, ....
 
 806     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
 
 808     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
 
 809     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
 
 810     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
 
 811     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
 
 812     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
 
 813     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
 
 814     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
 
 815     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
 
 816     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
 
 817     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $projectnumbers{$form->{"project_id_$i"}};
 
 819     if ($form->{"assembly_$i"}) {
 
 822       # get parts and push them onto the stack
 
 824       if ($form->{groupitems}) {
 
 826           qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
 
 828         $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
 
 831       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
 
 833       while (my $ref = $h_pg->fetchrow_hashref(NAME_lc)) {
 
 834         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
 835           map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 836           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
 837           push(@{ $form->{description} }, $sameitem);
 
 840         push(@{ $form->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq|, $ref->{partnumber}, $ref->{description}|);
 
 842         map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 846     if ($form->{"inventory_accno_$i"} && !$form->{"assembly_$i"}) {
 
 847       my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 849       foreach my $si (@{ $stock_info }) {
 
 852         do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
 
 853         my $bin_wh = $h_bin_wh->fetchrow_hashref();
 
 855         push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$position-1] }, $num_si;
 
 856         push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$position-1] },        $form->{"partnumber_$i"};
 
 857         push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$position-1] },   $form->{"description_$i"};
 
 858         push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$position-1] },     $bin_wh->{warehouse};
 
 859         push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$position-1] },           $bin_wh->{bin};
 
 860         push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$position-1] },  $si->{chargenumber};
 
 861         push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
 
 862         push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$position-1] },          $si->{unit};
 
 866     map { push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} }, $form->{"ic_cvar_$_->{name}_$i"} } @{ $ic_cvar_configs };
 
 872   $form->{username} = $myconfig->{name};
 
 874   $main::lxdebug->leave_sub();
 
 877 sub project_description {
 
 878   $main::lxdebug->enter_sub();
 
 880   my ($self, $dbh, $id) = @_;
 
 882   my $query = qq|SELECT description FROM project WHERE id = ?|;
 
 883   my ($value) = selectrow_query($form, $dbh, $query, $id);
 
 885   $main::lxdebug->leave_sub();
 
 890 sub unpack_stock_information {
 
 891   $main::lxdebug->enter_sub();
 
 896   Common::check_params_x(\%params, qw(packed));
 
 900   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
 
 902   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
 
 904   foreach my $entry (@{ $unpacked }) {
 
 905     next if ('HASH' eq ref $entry);
 
 910   $main::lxdebug->leave_sub();
 
 915 sub get_item_availability {
 
 916   $main::lxdebug->enter_sub();
 
 921   Common::check_params(\%params, qw(parts_id));
 
 923   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
 
 924   my $form      = $main::form;
 
 927     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, SUM(qty) AS qty, i.parts_id,
 
 928          w.description AS warehousedescription,
 
 929          b.description AS bindescription
 
 931        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
 
 932        LEFT JOIN bin b       ON (i.bin_id       = b.id)
 
 933        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
 
 934        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.parts_id, w.description, b.description
 
 936        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber)
 
 938   my $contents = selectall_hashref_query($form, $form->get_standard_dbh($myconfig), $query, @parts_ids);
 
 940   $main::lxdebug->leave_sub();
 
 942   return @{ $contents };
 
 946 sub check_stock_availability {
 
 947   $main::lxdebug->enter_sub();
 
 952   Common::check_params(\%params, qw(requests parts_id));
 
 954   my $myconfig    = \%main::myconfig;
 
 955   my $form        =  $main::form;
 
 957   my $dbh         = $form->get_standard_dbh($myconfig);
 
 959   my $units       = AM->retrieve_units($myconfig, $form);
 
 961   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
 
 962   my $unit_factor = $units->{$partunit}->{factor} || 1;
 
 964   my @contents    = $self->get_item_availability(%params);
 
 968   foreach my $sinfo (@{ $params{requests} }) {
 
 971     foreach my $row (@contents) {
 
 972       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
 
 973                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
 
 974                ($row->{chargenumber} ne $sinfo->{chargenumber}));
 
 978       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
 
 980       if ($base_qty > $row->{qty}) {
 
 982         push @errors, $sinfo;
 
 988     push @errors, $sinfo if (!$found);
 
 991   $main::lxdebug->leave_sub();
 
 996 sub transfer_in_out {
 
 997   $main::lxdebug->enter_sub();
 
1002   Common::check_params(\%params, qw(direction requests));
 
1004   if (!@{ $params{requests} }) {
 
1005     $main::lxdebug->leave_sub();
 
1009   my $myconfig = \%main::myconfig;
 
1010   my $form     = $main::form;
 
1012   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
 
1016   foreach my $request (@{ $params{requests} }) {
 
1018       'parts_id'               => $request->{parts_id},
 
1019       "${prefix}_warehouse_id" => $request->{warehouse_id},
 
1020       "${prefix}_bin_id"       => $request->{bin_id},
 
1021       'chargenumber'           => $request->{chargenumber},
 
1022       'qty'                    => $request->{qty},
 
1023       'unit'                   => $request->{unit},
 
1024       'oe_id'                  => $form->{id},
 
1025       'shippingdate'           => 'current_date',
 
1026       'transfer_type'          => $params{direction} eq 'in' ? 'stock' : 'shipped',
 
1030   WH->transfer(@transfers);
 
1032   $main::lxdebug->leave_sub();
 
1035 sub get_shipped_qty {
 
1036   $main::lxdebug->enter_sub();
 
1041   Common::check_params(\%params, qw(type oe_id));
 
1043   my $myconfig = \%main::myconfig;
 
1044   my $form     = $main::form;
 
1046   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1048   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
1049                                         'from_table' => 'oe',
 
1050                                         'from_id'    => $params{oe_id},
 
1051                                         'to_table'   => 'delivery_orders');
 
1052   my @values   = map { $_->{to_id} } @links;
 
1054   if (!scalar @values) {
 
1055     $main::lxdebug->leave_sub();
 
1060     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
 
1061        FROM delivery_order_items doi
 
1062        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
 
1063        LEFT JOIN parts p ON (doi.parts_id = p.id)
 
1064        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
 
1067   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
 
1068   my $all_units = AM->retrieve_all_units();
 
1070   foreach my $entry (@{ $entries }) {
 
1071     $entry->{qty} *= $all_units->{$entry->{unit}}->{factor} / $all_units->{$entry->{partunit}}->{factor};
 
1073     if (!$ship{$entry->{parts_id}}) {
 
1074       $ship{$entry->{parts_id}} = $entry;
 
1076       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
 
1080   $main::lxdebug->leave_sub();
 
1085 sub is_marked_as_delivered {
 
1086   $main::lxdebug->enter_sub();
 
1091   Common::check_params(\%params, qw(id));
 
1093   my $myconfig    = \%main::myconfig;
 
1094   my $form        = $main::form;
 
1096   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1098   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
 
1100   $main::lxdebug->leave_sub();
 
1102   return $delivered ? 1 : 0;