1 #====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (C) 1999-2003
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  17 # This program is free software; you can redistribute it and/or modify
 
  18 # it under the terms of the GNU General Public License as published by
 
  19 # the Free Software Foundation; either version 2 of the License, or
 
  20 # (at your option) any later version.
 
  22 # This program is distributed in the hope that it will be useful,
 
  23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  25 # GNU General Public License for more details.
 
  26 # You should have received a copy of the GNU General Public License
 
  27 # along with this program; if not, write to the Free Software
 
  28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  29 #======================================================================
 
  31 # Delivery Order entry module
 
  32 #======================================================================
 
  36 use List::Util qw(max);
 
  49   $main::lxdebug->enter_sub();
 
  53   my $myconfig = \%main::myconfig;
 
  54   my $form     = $main::form;
 
  57   my $dbh = $form->get_standard_dbh($myconfig);
 
  59   my (@where, @values, $where);
 
  61   my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
 
  64     qq|SELECT dord.id, dord.donumber, dord.ordnumber, dord.transdate,
 
  65          ct.name, dord.${vc}_id, dord.globalproject_id,
 
  66          dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
 
  67          dord.transaction_description,
 
  68          pr.projectnumber AS globalprojectnumber,
 
  71        FROM delivery_orders dord
 
  72        LEFT JOIN $vc ct ON (dord.${vc}_id = ct.id)
 
  73        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
  74        LEFT JOIN employee sm ON (dord.salesman_id = sm.id)
 
  75        LEFT JOIN project pr ON (dord.globalproject_id = pr.id)|;
 
  77   push @where, ($form->{type} eq 'sales_delivery_order' ? '' : 'NOT ') . qq|COALESCE(dord.is_sales, FALSE)|;
 
  79   my $department_id = (split /--/, $form->{department})[1];
 
  81     push @where,  qq|dord.department_id = ?|;
 
  82     push @values, conv_i($department_id);
 
  85   if ($form->{project_id}) {
 
  87       qq|(dord.globalproject_id = ?) OR EXISTS
 
  88           (SELECT * FROM delivery_order_items doi
 
  89            WHERE (doi.project_id = ?) AND (doi.delivery_order_id = dord.id))|;
 
  90     push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
 
  93   if ($form->{"${vc}_id"}) {
 
  94     push @where,  qq|dord.${vc}_id = ?|;
 
  95     push @values, $form->{"${vc}_id"};
 
  97   } elsif ($form->{$vc}) {
 
  98     push @where,  qq|ct.name ILIKE ?|;
 
  99     push @values, '%' . $form->{$vc} . '%';
 
 102   foreach my $item (qw(employee_id salesman_id)) {
 
 103     next unless ($form->{$item});
 
 104     push @where, "dord.$item = ?";
 
 105     push @values, conv_i($form->{$item});
 
 107   if (!$main::auth->assert('sales_all_edit', 1)) {
 
 108     push @where, qq|dord.employee_id = (select id from employee where login= ?)|;
 
 109     push @values, $form->{login};
 
 112   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
 
 113     next unless ($form->{$item});
 
 114     push @where,  qq|dord.$item ILIKE ?|;
 
 115     push @values, '%' . $form->{$item} . '%';
 
 118   if (($form->{open} || $form->{closed}) &&
 
 119       ($form->{open} ne $form->{closed})) {
 
 120     push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
 
 123   if (($form->{notdelivered} || $form->{delivered}) &&
 
 124       ($form->{notdelivered} ne $form->{delivered})) {
 
 125     push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
 
 128   if($form->{transdatefrom}) {
 
 129     push @where,  qq|dord.transdate >= ?|;
 
 130     push @values, conv_date($form->{transdatefrom});
 
 133   if($form->{transdateto}) {
 
 134     push @where,  qq|dord.transdate <= ?|;
 
 135     push @values, conv_date($form->{transdateto});
 
 139     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
 
 142   my %allowed_sort_columns = (
 
 143     "transdate"               => "dord.transdate",
 
 145     "donumber"                => "dord.donumber",
 
 146     "ordnumber"               => "dord.ordnumber",
 
 148     "employee"                => "e.name",
 
 149     "salesman"                => "sm.name",
 
 150     "shipvia"                 => "dord.shipvia",
 
 151     "transaction_description" => "dord.transaction_description"
 
 154   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 155   my $sortorder = "dord.id";
 
 156   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
 
 157     $sortorder = $allowed_sort_columns{$form->{sort}};
 
 160   $query .= qq| ORDER by | . $sortorder . " $sortdir";
 
 162   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
 
 164   if (scalar @{ $form->{DO} }) {
 
 168          WHERE NOT COALESCE(quotation, FALSE)
 
 170            AND (COALESCE(${vc}_id, 0) != 0)|;
 
 172     my $sth = prepare_query($form, $dbh, $query);
 
 174     foreach my $dord (@{ $form->{DO} }) {
 
 175       next unless ($dord->{ordnumber});
 
 176       do_statement($form, $sth, $query, $dord->{ordnumber});
 
 177       ($dord->{oe_id}) = $sth->fetchrow_array();
 
 183   $main::lxdebug->leave_sub();
 
 187   $main::lxdebug->enter_sub();
 
 191   my $myconfig = \%main::myconfig;
 
 192   my $form     = $main::form;
 
 194   # connect to database, turn off autocommit
 
 195   my $dbh = $form->get_standard_dbh($myconfig);
 
 197   my ($query, @values, $sth, $null);
 
 199   my $all_units = AM->retrieve_units($myconfig, $form);
 
 200   $form->{all_units} = $all_units;
 
 202   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 205   $form->{donumber}    = $form->update_defaults($myconfig, $form->{type} eq 'sales_delivery_order' ? 'sdonumber' : 'pdonumber', $dbh) unless $form->{donumber};
 
 206   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
 
 207   $form->get_employee($dbh) unless ($form->{employee_id});
 
 209   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
 
 213     $query = qq|DELETE FROM delivery_order_items_stock WHERE delivery_order_item_id IN (SELECT id FROM delivery_order_items WHERE delivery_order_id = ?)|;
 
 214     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 216     $query = qq|DELETE FROM delivery_order_items WHERE delivery_order_id = ?|;
 
 217     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 219     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
 
 220     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 224     $query = qq|SELECT nextval('id')|;
 
 225     ($form->{id}) = selectrow_query($form, $dbh, $query);
 
 227     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id) VALUES (?, '', ?)|;
 
 228     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}));
 
 234   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 235   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 238   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
 
 239   my @part_ids    = keys %part_id_map;
 
 243     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
 
 244     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
 
 247   my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
 
 248   my $h_item_id = prepare_query($form, $dbh, $q_item_id);
 
 251     qq|INSERT INTO delivery_order_items (
 
 252          id, delivery_order_id, parts_id, description, longdescription, qty, base_qty,
 
 253          sellprice, discount, unit, reqdate, project_id, serialnumber,
 
 254          ordnumber, transdate, cusordnumber,
 
 255          lastcost, price_factor_id, price_factor, marge_price_factor)
 
 256        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 
 257          (SELECT factor FROM price_factors WHERE id = ?), ?)|;
 
 258   my $h_item = prepare_query($form, $dbh, $q_item);
 
 261     qq|INSERT INTO delivery_order_items_stock (delivery_order_item_id, qty, unit, warehouse_id, bin_id, chargenumber)
 
 262        VALUES (?, ?, ?, ?, ?, ?)|;
 
 263   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
 
 265   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 267   for my $i (1 .. $form->{rowcount}) {
 
 268     next if (!$form->{"id_$i"});
 
 270     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 272     my $item_unit = $part_unit_map{$form->{"id_$i"}};
 
 275     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
 
 276       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
 
 278     my $baseqty = $form->{"qty_$i"} * $basefactor;
 
 280     $form->{"lastcost_$i"} *= 1;
 
 282     # set values to 0 if nothing entered
 
 283     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
 
 284     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 286     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
 
 287     my $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 289     $reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
 
 291     do_statement($form, $h_item_id, $q_item_id);
 
 292     my ($item_id) = $h_item_id->fetchrow_array();
 
 294     # save detail record in delivery_order_items table
 
 295     @values = (conv_i($item_id), conv_i($form->{id}), conv_i($form->{"id_$i"}),
 
 296                $form->{"description_$i"}, $form->{"longdescription_$i"},
 
 297                $form->{"qty_$i"}, $baseqty,
 
 298                $form->{"sellprice_$i"}, $form->{"discount_$i"},
 
 299                $form->{"unit_$i"}, conv_date($reqdate), conv_i($form->{"project_id_$i"}),
 
 300                $form->{"serialnumber_$i"},
 
 301                $form->{"ordnumber_$i"}, conv_date($form->{"transdate_$i"}),
 
 302                $form->{"cusordnumber_$i"},
 
 303                $form->{"lastcost_$i"},
 
 304                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
 
 305                conv_i($form->{"marge_price_factor_$i"}));
 
 306     do_statement($form, $h_item, $q_item, @values);
 
 308     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 310     foreach my $sinfo (@{ $stock_info }) {
 
 311       @values = ($item_id, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 312                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber});
 
 313       do_statement($form, $h_item_stock, $q_item_stock, @values);
 
 316     CVar->save_custom_variables(module       => 'IC',
 
 317                                 sub_module   => 'delivery_order_items',
 
 318                                 trans_id     => $item_id,
 
 319                                 configs      => $ic_cvar_configs,
 
 321                                 name_prefix  => 'ic_',
 
 322                                 name_postfix => "_$i",
 
 326   $h_item_id->finish();
 
 328   $h_item_stock->finish();
 
 330   ($null, $form->{department_id}) = split(/--/, $form->{department});
 
 334     qq|UPDATE delivery_orders SET
 
 335          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
 
 336          customer_id = ?, reqdate = ?,
 
 337          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
 
 338          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
 
 339          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
 
 340          is_sales = ?, taxzone_id = ?, taxincluded = ?, terms = ?, curr = ?
 
 343   @values = ($form->{donumber}, $form->{ordnumber},
 
 344              $form->{cusordnumber}, conv_date($form->{transdate}),
 
 345              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
 
 346              conv_date($reqdate), $form->{shippingpoint}, $form->{shipvia},
 
 347              $form->{notes}, $form->{intnotes},
 
 348              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
 
 349              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
 
 350              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
 
 351              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
 
 352              $form->{transaction_description},
 
 353              $form->{type} =~ /^sales/ ? 't' : 'f',
 
 354              conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{terms}), $form->{curr},
 
 355              conv_i($form->{id}));
 
 356   do_query($form, $dbh, $query, @values);
 
 359   $form->{name} = $form->{ $form->{vc} };
 
 360   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
 
 362   if (!$form->{shipto_id}) {
 
 363     $form->add_shipto($dbh, $form->{id}, "DO");
 
 366   # save printed, emailed, queued
 
 367   $form->save_status($dbh);
 
 369   # Link this delivery order to the quotations it was created from.
 
 370   RecordLinks->create_links('dbh'        => $dbh,
 
 372                             'from_table' => 'oe',
 
 373                             'from_ids'   => $form->{convert_from_oe_ids},
 
 374                             'to_table'   => 'delivery_orders',
 
 375                             'to_id'      => $form->{id},
 
 377   delete $form->{convert_from_oe_ids};
 
 379   $self->mark_orders_if_delivered('do_id' => $form->{id},
 
 380                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
 
 383   my $rc = $dbh->commit();
 
 385   $form->{saved_donumber} = $form->{donumber};
 
 387   Common::webdav_folder($form) if ($main::webdav);
 
 389   $main::lxdebug->leave_sub();
 
 394 sub mark_orders_if_delivered {
 
 395   $main::lxdebug->enter_sub();
 
 400   Common::check_params(\%params, qw(do_id type));
 
 402   my $myconfig = \%main::myconfig;
 
 403   my $form     = $main::form;
 
 405   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 407   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
 408                                         'from_table' => 'oe',
 
 409                                         'to_table'   => 'delivery_orders',
 
 410                                         'to_id'      => $params{do_id});
 
 412   my ($oe_id)  = $links[0]->{from_id} if (scalar @links);
 
 414   return $main::lxdebug->leave_sub() if (!$oe_id);
 
 416   my $all_units = AM->retrieve_all_units();
 
 418   my $query     = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
 
 420                      LEFT JOIN parts p ON (oi.parts_id = p.id)
 
 421                      WHERE (oi.trans_id = ?)|;
 
 422   my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
 
 424   my %shipped   = $self->get_shipped_qty('type'  => $params{type},
 
 428   while (my $ref = $sth->fetchrow_hashref()) {
 
 429     $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
 
 431     if ($ordered{$ref->{parts_id}}) {
 
 432       $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
 
 434       $ordered{$ref->{parts_id}}             = $ref;
 
 440   map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
 
 443   foreach my $part (values %ordered) {
 
 444     if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
 
 451     $query = qq|UPDATE oe
 
 454     do_query($form, $dbh, $query, $oe_id);
 
 455     $dbh->commit() if (!$params{dbh});
 
 458   $main::lxdebug->leave_sub();
 
 462   $main::lxdebug->enter_sub();
 
 467   Common::check_params(\%params, qw(ids));
 
 469   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
 
 470     $main::lxdebug->leave_sub();
 
 474   my $myconfig = \%main::myconfig;
 
 475   my $form     = $main::form;
 
 477   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 479   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
 
 481   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
 
 483   $dbh->commit() unless ($params{dbh});
 
 485   $main::lxdebug->leave_sub();
 
 489   $main::lxdebug->enter_sub();
 
 493   my $myconfig = \%main::myconfig;
 
 494   my $form     = $main::form;
 
 495   my $spool    = $main::spool;
 
 497   # connect to database
 
 498   my $dbh = $form->get_standard_dbh($myconfig);
 
 501   my $query = qq|SELECT s.spoolfile FROM status s WHERE s.trans_id = ?|;
 
 502   my $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 508   while (($spoolfile) = $sth->fetchrow_array) {
 
 509     push @spoolfiles, $spoolfile;
 
 514   @values = (conv_i($form->{id}));
 
 516   # delete status entries
 
 517   $query = qq|DELETE FROM status
 
 519   do_query($form, $dbh, $query, @values);
 
 521   # delete individual entries
 
 522   $query = qq|DELETE FROM delivery_order_items_stock
 
 523               WHERE delivery_order_item_id IN (
 
 524                 SELECT id FROM delivery_order_items
 
 525                 WHERE delivery_order_id = ?
 
 527   do_query($form, $dbh, $query, @values);
 
 529   # delete individual entries
 
 530   $query = qq|DELETE FROM delivery_order_items
 
 531               WHERE delivery_order_id = ?|;
 
 532   do_query($form, $dbh, $query, @values);
 
 535   $query = qq|DELETE FROM delivery_orders
 
 537   do_query($form, $dbh, $query, @values);
 
 539   $query = qq|DELETE FROM shipto
 
 540               WHERE trans_id = ? AND module = 'DO'|;
 
 541   do_query($form, $dbh, $query, @values);
 
 543   my $rc = $dbh->commit();
 
 546     foreach $spoolfile (@spoolfiles) {
 
 547       unlink "$spool/$spoolfile" if $spoolfile;
 
 551   $main::lxdebug->leave_sub();
 
 557   $main::lxdebug->enter_sub();
 
 562   my $myconfig = \%main::myconfig;
 
 563   my $form     = $main::form;
 
 565   # connect to database
 
 566   my $dbh = $form->get_standard_dbh($myconfig);
 
 568   my ($query, $query_add, @values, $sth, $ref);
 
 570   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 573   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
 
 575   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
 
 577   if ($mode eq 'default') {
 
 578     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate, current_date AS reqdate|);
 
 579     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 582     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
 
 584     $main::lxdebug->leave_sub();
 
 589   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
 
 590   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
 
 592   # retrieve order for single id
 
 593   # NOTE: this query is intended to fetch all information only ONCE.
 
 594   # so if any of these infos is important (or even different) for any item,
 
 595   # it will be killed out and then has to be fetched from the item scope query further down
 
 597     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
 
 598          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
 
 599          e.name AS employee, dord.employee_id, dord.salesman_id,
 
 600          dord.${vc}_id, cv.name AS ${vc},
 
 601          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
 
 602          d.description AS department, dord.language_id,
 
 604          dord.globalproject_id, dord.delivered, dord.transaction_description,
 
 605          dord.taxzone_id, dord.taxincluded, dord.terms, dord.curr
 
 606        FROM delivery_orders dord
 
 607        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
 
 608        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
 609        LEFT JOIN department d ON (dord.department_id = d.id)
 
 610        WHERE dord.id IN ($do_ids_placeholders)|;
 
 611   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
 
 613   delete $form->{"${vc}_id"};
 
 614   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 615     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
 
 617       $main::lxdebug->leave_sub();
 
 622     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
 
 623     $form->{donumber_array} .= $form->{donumber} . ' ';
 
 627   $form->{saved_donumber} = $form->{donumber};
 
 629   # if not given, fill transdate with current_date
 
 630   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
 
 632   if ($mode eq 'single') {
 
 633     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
 
 634     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
 
 636     $ref   = $sth->fetchrow_hashref("NAME_lc");
 
 638     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 641     # get printed, emailed and queued
 
 642     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
 
 643     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 645     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 646       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
 647       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
 648       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
 
 651     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
 657   my %oid = ('Pg'     => 'oid',
 
 658              'Oracle' => 'rowid');
 
 660   # retrieve individual items
 
 661   # this query looks up all information about the items
 
 662   # stuff different from the whole will not be overwritten, but saved with a suffix.
 
 664     qq|SELECT doi.id AS delivery_order_items_id,
 
 665          p.partnumber, p.assembly, doi.description, doi.qty,
 
 666          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.bin, p.notes AS partnotes,
 
 667          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
 
 668          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
 
 669          doi.price_factor_id, doi.price_factor, doi.marge_price_factor,
 
 670          pr.projectnumber, dord.transdate AS dord_transdate,
 
 672        FROM delivery_order_items doi
 
 673        JOIN parts p ON (doi.parts_id = p.id)
 
 674        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
 
 675        LEFT JOIN project pr ON (doi.project_id = pr.id)
 
 676        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 677        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
 
 678        ORDER BY doi.$oid{$myconfig->{dbdriver}}|;
 
 680   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
 682   # Retrieve custom variables.
 
 683   foreach my $doi (@{ $form->{form_details} }) {
 
 684     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 686                                            sub_module => 'delivery_order_items',
 
 687                                            trans_id   => $doi->{delivery_order_items_id},
 
 689     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
 
 692   if ($mode eq 'single') {
 
 693     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 696       qq|SELECT qty, unit, bin_id, warehouse_id, chargenumber
 
 697          FROM delivery_order_items_stock
 
 698          WHERE delivery_order_item_id = ?|;
 
 699     my $sth = prepare_query($form, $dbh, $query);
 
 701     foreach my $doi (@{ $form->{form_details} }) {
 
 702       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
 
 704       while (my $ref = $sth->fetchrow_hashref()) {
 
 705         push @{ $requests }, $ref;
 
 708       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
 
 714   Common::webdav_folder($form) if ($main::webdav);
 
 716   $main::lxdebug->leave_sub();
 
 722   $main::lxdebug->enter_sub();
 
 726   my $myconfig = \%main::myconfig;
 
 727   my $form     = $main::form;
 
 729   # connect to database
 
 730   my $dbh = $form->get_standard_dbh($myconfig);
 
 740   my %oid = ('Pg'     => 'oid',
 
 741              'Oracle' => 'rowid');
 
 743   my (@project_ids, %projectnumbers);
 
 745   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
 
 747   # sort items by partsgroup
 
 748   for $i (1 .. $form->{rowcount}) {
 
 750     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
 751       $partsgroup = $form->{"partsgroup_$i"};
 
 753     push @partsgroup, [$i, $partsgroup];
 
 754     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
 
 758     $query = "SELECT id, projectnumber FROM project WHERE id IN (" .
 
 759       join(", ", map("?", @project_ids)) . ")";
 
 760     $sth = prepare_execute_query($form, $dbh, $query, @project_ids);
 
 761     while (my $ref = $sth->fetchrow_hashref()) {
 
 762       $projectnumbers{$ref->{id}} = $ref->{projectnumber};
 
 767   $form->{"globalprojectnumber"} =
 
 768     $projectnumbers{$form->{"globalproject_id"}};
 
 770   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
 
 772                     JOIN parts p ON (a.parts_id = p.id)
 
 773                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 776   my $h_pg     = prepare_query($form, $dbh, $q_pg);
 
 778   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
 
 779                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
 
 780   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
 
 782   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 786   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 788   $form->{TEMPLATE_ARRAYS} = { };
 
 789   IC->prepare_parts_for_printing();
 
 792     qw(runningnumber number description longdescription qty unit
 
 793        partnotes serialnumber reqdate projectnumber
 
 794        si_runningnumber si_number si_description
 
 795        si_warehouse si_bin si_chargenumber si_qty si_unit);
 
 797   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays);
 
 799   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 801   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 802   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 805   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
 808     next if (!$form->{"id_$i"});
 
 812     if ($item->[1] ne $sameitem) {
 
 813       push(@{ $form->{description} }, qq|$item->[1]|);
 
 814       $sameitem = $item->[1];
 
 816       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 819     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 821     # add number, description and qty to $form->{number}, ....
 
 823     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
 
 825     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
 
 826     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
 
 827     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
 
 828     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
 
 829     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
 
 830     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
 
 831     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
 
 832     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
 
 833     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
 
 834     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $projectnumbers{$form->{"project_id_$i"}};
 
 836     if ($form->{"assembly_$i"}) {
 
 839       # get parts and push them onto the stack
 
 841       if ($form->{groupitems}) {
 
 843           qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
 
 845         $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
 
 848       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
 
 850       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
 
 851         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
 852           map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 853           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
 854           push(@{ $form->{description} }, $sameitem);
 
 857         push(@{ $form->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq|, $ref->{partnumber}, $ref->{description}|);
 
 859         map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 863     if ($form->{"inventory_accno_$i"} && !$form->{"assembly_$i"}) {
 
 864       my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 866       foreach my $si (@{ $stock_info }) {
 
 869         do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
 
 870         my $bin_wh = $h_bin_wh->fetchrow_hashref();
 
 872         push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$position-1] }, $num_si;
 
 873         push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$position-1] },        $form->{"partnumber_$i"};
 
 874         push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$position-1] },   $form->{"description_$i"};
 
 875         push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$position-1] },     $bin_wh->{warehouse};
 
 876         push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$position-1] },           $bin_wh->{bin};
 
 877         push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$position-1] },  $si->{chargenumber};
 
 878         push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
 
 879         push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$position-1] },          $si->{unit};
 
 883     map { push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} }, $form->{"ic_cvar_$_->{name}_$i"} } @{ $ic_cvar_configs };
 
 889   $form->{username} = $myconfig->{name};
 
 891   $main::lxdebug->leave_sub();
 
 894 sub project_description {
 
 895   $main::lxdebug->enter_sub();
 
 897   my ($self, $dbh, $id) = @_;
 
 899   my $form     =  $main::form;
 
 901   my $query = qq|SELECT description FROM project WHERE id = ?|;
 
 902   my ($value) = selectrow_query($form, $dbh, $query, $id);
 
 904   $main::lxdebug->leave_sub();
 
 909 sub unpack_stock_information {
 
 910   $main::lxdebug->enter_sub();
 
 915   Common::check_params_x(\%params, qw(packed));
 
 919   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
 
 921   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
 
 923   foreach my $entry (@{ $unpacked }) {
 
 924     next if ('HASH' eq ref $entry);
 
 929   $main::lxdebug->leave_sub();
 
 934 sub get_item_availability {
 
 935   $main::lxdebug->enter_sub();
 
 940   Common::check_params(\%params, qw(parts_id));
 
 942   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
 
 943   my $form      = $main::form;
 
 944   my $myconfig  = \%main::myconfig;
 
 947     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, SUM(qty) AS qty, i.parts_id,
 
 948          w.description AS warehousedescription,
 
 949          b.description AS bindescription
 
 951        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
 
 952        LEFT JOIN bin b       ON (i.bin_id       = b.id)
 
 953        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
 
 954        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.parts_id, w.description, b.description
 
 956        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber)
 
 958   my $contents = selectall_hashref_query($form, $form->get_standard_dbh($myconfig), $query, @parts_ids);
 
 960   $main::lxdebug->leave_sub();
 
 962   return @{ $contents };
 
 966 sub check_stock_availability {
 
 967   $main::lxdebug->enter_sub();
 
 972   Common::check_params(\%params, qw(requests parts_id));
 
 974   my $myconfig    = \%main::myconfig;
 
 975   my $form        =  $main::form;
 
 977   my $dbh         = $form->get_standard_dbh($myconfig);
 
 979   my $units       = AM->retrieve_units($myconfig, $form);
 
 981   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
 
 982   my $unit_factor = $units->{$partunit}->{factor} || 1;
 
 984   my @contents    = $self->get_item_availability(%params);
 
 988   foreach my $sinfo (@{ $params{requests} }) {
 
 991     foreach my $row (@contents) {
 
 992       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
 
 993                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
 
 994                ($row->{chargenumber} ne $sinfo->{chargenumber}));
 
 998       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
 
1000       if ($base_qty > $row->{qty}) {
 
1001         $sinfo->{error} = 1;
 
1002         push @errors, $sinfo;
 
1008     push @errors, $sinfo if (!$found);
 
1011   $main::lxdebug->leave_sub();
 
1016 sub transfer_in_out {
 
1017   $main::lxdebug->enter_sub();
 
1022   Common::check_params(\%params, qw(direction requests));
 
1024   if (!@{ $params{requests} }) {
 
1025     $main::lxdebug->leave_sub();
 
1029   my $myconfig = \%main::myconfig;
 
1030   my $form     = $main::form;
 
1032   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
 
1036   foreach my $request (@{ $params{requests} }) {
 
1038       'parts_id'               => $request->{parts_id},
 
1039       "${prefix}_warehouse_id" => $request->{warehouse_id},
 
1040       "${prefix}_bin_id"       => $request->{bin_id},
 
1041       'chargenumber'           => $request->{chargenumber},
 
1042       'qty'                    => $request->{qty},
 
1043       'unit'                   => $request->{unit},
 
1044       'oe_id'                  => $form->{id},
 
1045       'shippingdate'           => 'current_date',
 
1046       'transfer_type'          => $params{direction} eq 'in' ? 'stock' : 'shipped',
 
1050   WH->transfer(@transfers);
 
1052   $main::lxdebug->leave_sub();
 
1055 sub get_shipped_qty {
 
1056   $main::lxdebug->enter_sub();
 
1061   Common::check_params(\%params, qw(type oe_id));
 
1063   my $myconfig = \%main::myconfig;
 
1064   my $form     = $main::form;
 
1066   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1068   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
1069                                         'from_table' => 'oe',
 
1070                                         'from_id'    => $params{oe_id},
 
1071                                         'to_table'   => 'delivery_orders');
 
1072   my @values   = map { $_->{to_id} } @links;
 
1074   if (!scalar @values) {
 
1075     $main::lxdebug->leave_sub();
 
1080     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
 
1081        FROM delivery_order_items doi
 
1082        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
 
1083        LEFT JOIN parts p ON (doi.parts_id = p.id)
 
1084        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
 
1087   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
 
1088   my $all_units = AM->retrieve_all_units();
 
1090   foreach my $entry (@{ $entries }) {
 
1091     $entry->{qty} *= $all_units->{$entry->{unit}}->{factor} / $all_units->{$entry->{partunit}}->{factor};
 
1093     if (!$ship{$entry->{parts_id}}) {
 
1094       $ship{$entry->{parts_id}} = $entry;
 
1096       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
 
1100   $main::lxdebug->leave_sub();
 
1105 sub is_marked_as_delivered {
 
1106   $main::lxdebug->enter_sub();
 
1111   Common::check_params(\%params, qw(id));
 
1113   my $myconfig    = \%main::myconfig;
 
1114   my $form        = $main::form;
 
1116   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1118   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
 
1120   $main::lxdebug->leave_sub();
 
1122   return $delivered ? 1 : 0;