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   if ($form->{department_id}) {
 
  80     push @where,  qq|dord.department_id = ?|;
 
  81     push @values, conv_i($form->{department_id});
 
  84   if ($form->{project_id}) {
 
  86       qq|(dord.globalproject_id = ?) OR EXISTS
 
  87           (SELECT * FROM delivery_order_items doi
 
  88            WHERE (doi.project_id = ?) AND (doi.delivery_order_id = dord.id))|;
 
  89     push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
 
  92   if ($form->{"${vc}_id"}) {
 
  93     push @where,  qq|dord.${vc}_id = ?|;
 
  94     push @values, $form->{"${vc}_id"};
 
  96   } elsif ($form->{$vc}) {
 
  97     push @where,  qq|ct.name ILIKE ?|;
 
  98     push @values, '%' . $form->{$vc} . '%';
 
 101   foreach my $item (qw(employee_id salesman_id)) {
 
 102     next unless ($form->{$item});
 
 103     push @where, "dord.$item = ?";
 
 104     push @values, conv_i($form->{$item});
 
 106   if (!$main::auth->assert('sales_all_edit', 1)) {
 
 107     push @where, qq|dord.employee_id = (select id from employee where login= ?)|;
 
 108     push @values, $form->{login};
 
 111   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
 
 112     next unless ($form->{$item});
 
 113     push @where,  qq|dord.$item ILIKE ?|;
 
 114     push @values, '%' . $form->{$item} . '%';
 
 117   if (($form->{open} || $form->{closed}) &&
 
 118       ($form->{open} ne $form->{closed})) {
 
 119     push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
 
 122   if (($form->{notdelivered} || $form->{delivered}) &&
 
 123       ($form->{notdelivered} ne $form->{delivered})) {
 
 124     push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
 
 127   if($form->{transdatefrom}) {
 
 128     push @where,  qq|dord.transdate >= ?|;
 
 129     push @values, conv_date($form->{transdatefrom});
 
 132   if($form->{transdateto}) {
 
 133     push @where,  qq|dord.transdate <= ?|;
 
 134     push @values, conv_date($form->{transdateto});
 
 138     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
 
 141   my %allowed_sort_columns = (
 
 142     "transdate"               => "dord.transdate",
 
 144     "donumber"                => "dord.donumber",
 
 145     "ordnumber"               => "dord.ordnumber",
 
 147     "employee"                => "e.name",
 
 148     "salesman"                => "sm.name",
 
 149     "shipvia"                 => "dord.shipvia",
 
 150     "transaction_description" => "dord.transaction_description"
 
 153   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 154   my $sortorder = "dord.id";
 
 155   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
 
 156     $sortorder = $allowed_sort_columns{$form->{sort}};
 
 159   $query .= qq| ORDER by | . $sortorder . " $sortdir";
 
 161   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
 
 163   if (scalar @{ $form->{DO} }) {
 
 167          WHERE NOT COALESCE(quotation, FALSE)
 
 169            AND (COALESCE(${vc}_id, 0) != 0)|;
 
 171     my $sth = prepare_query($form, $dbh, $query);
 
 173     foreach my $dord (@{ $form->{DO} }) {
 
 174       next unless ($dord->{ordnumber});
 
 175       do_statement($form, $sth, $query, $dord->{ordnumber});
 
 176       ($dord->{oe_id}) = $sth->fetchrow_array();
 
 182   $main::lxdebug->leave_sub();
 
 186   $main::lxdebug->enter_sub();
 
 190   my $myconfig = \%main::myconfig;
 
 191   my $form     = $main::form;
 
 193   # connect to database, turn off autocommit
 
 194   my $dbh = $form->get_standard_dbh($myconfig);
 
 196   my ($query, @values, $sth, $null);
 
 198   my $all_units = AM->retrieve_units($myconfig, $form);
 
 199   $form->{all_units} = $all_units;
 
 201   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 204   $form->{donumber}    = $form->update_defaults($myconfig, $form->{type} eq 'sales_delivery_order' ? 'sdonumber' : 'pdonumber', $dbh) unless $form->{donumber};
 
 205   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
 
 206   $form->get_employee($dbh) unless ($form->{employee_id});
 
 208   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
 
 212     $query = qq|DELETE FROM delivery_order_items_stock WHERE delivery_order_item_id IN (SELECT id FROM delivery_order_items WHERE delivery_order_id = ?)|;
 
 213     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 215     $query = qq|DELETE FROM delivery_order_items WHERE delivery_order_id = ?|;
 
 216     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 218     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
 
 219     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 223     $query = qq|SELECT nextval('id')|;
 
 224     ($form->{id}) = selectrow_query($form, $dbh, $query);
 
 226     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id) VALUES (?, '', ?)|;
 
 227     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}));
 
 233   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 234   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 237   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
 
 238   my @part_ids    = keys %part_id_map;
 
 242     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
 
 243     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
 
 246   my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
 
 247   my $h_item_id = prepare_query($form, $dbh, $q_item_id);
 
 250     qq|INSERT INTO delivery_order_items (
 
 251          id, delivery_order_id, parts_id, description, longdescription, qty, base_qty,
 
 252          sellprice, discount, unit, reqdate, project_id, serialnumber,
 
 253          ordnumber, transdate, cusordnumber,
 
 254          lastcost, price_factor_id, price_factor, marge_price_factor, pricegroup_id)
 
 255        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 
 256          (SELECT factor FROM price_factors WHERE id = ?), ?, ?)|;
 
 257   my $h_item = prepare_query($form, $dbh, $q_item);
 
 260     qq|INSERT INTO delivery_order_items_stock (delivery_order_item_id, qty, unit, warehouse_id, bin_id, chargenumber, bestbefore)
 
 261        VALUES (?, ?, ?, ?, ?, ?, ?)|;
 
 262   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
 
 264   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 266   for my $i (1 .. $form->{rowcount}) {
 
 267     next if (!$form->{"id_$i"});
 
 269     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 271     my $item_unit = $part_unit_map{$form->{"id_$i"}};
 
 274     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
 
 275       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
 
 277     my $baseqty = $form->{"qty_$i"} * $basefactor;
 
 279     # set values to 0 if nothing entered
 
 280     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"});
 
 281     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 282     $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
 
 284     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
 
 285     my $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 287     $reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
 
 289     do_statement($form, $h_item_id, $q_item_id);
 
 290     my ($item_id) = $h_item_id->fetchrow_array();
 
 292     # save detail record in delivery_order_items table
 
 293     @values = (conv_i($item_id), conv_i($form->{id}), conv_i($form->{"id_$i"}),
 
 294                $form->{"description_$i"}, $form->{"longdescription_$i"},
 
 295                $form->{"qty_$i"}, $baseqty,
 
 296                $form->{"sellprice_$i"}, $form->{"discount_$i"} / 100,
 
 297                $form->{"unit_$i"}, conv_date($reqdate), conv_i($form->{"project_id_$i"}),
 
 298                $form->{"serialnumber_$i"},
 
 299                $form->{"ordnumber_$i"}, conv_date($form->{"transdate_$i"}),
 
 300                $form->{"cusordnumber_$i"},
 
 301                $form->{"lastcost_$i"},
 
 302                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
 
 303                conv_i($form->{"marge_price_factor_$i"}),
 
 304                conv_i($form->{"pricegroup_id_$i"}));
 
 305     do_statement($form, $h_item, $q_item, @values);
 
 307     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 309     foreach my $sinfo (@{ $stock_info }) {
 
 310       @values = ($item_id, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 311                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}));
 
 312       do_statement($form, $h_item_stock, $q_item_stock, @values);
 
 315     CVar->save_custom_variables(module       => 'IC',
 
 316                                 sub_module   => 'delivery_order_items',
 
 317                                 trans_id     => $item_id,
 
 318                                 configs      => $ic_cvar_configs,
 
 320                                 name_prefix  => 'ic_',
 
 321                                 name_postfix => "_$i",
 
 325   $h_item_id->finish();
 
 327   $h_item_stock->finish();
 
 332     qq|UPDATE delivery_orders SET
 
 333          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
 
 334          customer_id = ?, reqdate = ?,
 
 335          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
 
 336          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
 
 337          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
 
 338          is_sales = ?, taxzone_id = ?, taxincluded = ?, terms = ?, curr = ?
 
 341   @values = ($form->{donumber}, $form->{ordnumber},
 
 342              $form->{cusordnumber}, conv_date($form->{transdate}),
 
 343              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
 
 344              conv_date($reqdate), $form->{shippingpoint}, $form->{shipvia},
 
 345              $form->{notes}, $form->{intnotes},
 
 346              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
 
 347              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
 
 348              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
 
 349              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
 
 350              $form->{transaction_description},
 
 351              $form->{type} =~ /^sales/ ? 't' : 'f',
 
 352              conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{terms}), substr($form->{currency}, 0, 3),
 
 353              conv_i($form->{id}));
 
 354   do_query($form, $dbh, $query, @values);
 
 357   $form->{name} = $form->{ $form->{vc} };
 
 358   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
 
 360   if (!$form->{shipto_id}) {
 
 361     $form->add_shipto($dbh, $form->{id}, "DO");
 
 364   # save printed, emailed, queued
 
 365   $form->save_status($dbh);
 
 367   # Link this delivery order to the quotations it was created from.
 
 368   RecordLinks->create_links('dbh'        => $dbh,
 
 370                             'from_table' => 'oe',
 
 371                             'from_ids'   => $form->{convert_from_oe_ids},
 
 372                             'to_table'   => 'delivery_orders',
 
 373                             'to_id'      => $form->{id},
 
 375   delete $form->{convert_from_oe_ids};
 
 377   $self->mark_orders_if_delivered('do_id' => $form->{id},
 
 378                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
 
 381   my $rc = $dbh->commit();
 
 383   $form->{saved_donumber} = $form->{donumber};
 
 385   Common::webdav_folder($form);
 
 387   $main::lxdebug->leave_sub();
 
 392 sub mark_orders_if_delivered {
 
 393   $main::lxdebug->enter_sub();
 
 398   Common::check_params(\%params, qw(do_id type));
 
 400   my $myconfig = \%main::myconfig;
 
 401   my $form     = $main::form;
 
 403   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 405   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
 406                                         'from_table' => 'oe',
 
 407                                         'to_table'   => 'delivery_orders',
 
 408                                         'to_id'      => $params{do_id});
 
 410   my $oe_id  = @links ? $links[0]->{from_id} : undef;
 
 412   return $main::lxdebug->leave_sub() if (!$oe_id);
 
 414   my $all_units = AM->retrieve_all_units();
 
 416   my $query     = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
 
 418                      LEFT JOIN parts p ON (oi.parts_id = p.id)
 
 419                      WHERE (oi.trans_id = ?)|;
 
 420   my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
 
 422   my %shipped   = $self->get_shipped_qty('type'  => $params{type},
 
 426   while (my $ref = $sth->fetchrow_hashref()) {
 
 427     $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
 
 429     if ($ordered{$ref->{parts_id}}) {
 
 430       $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
 
 432       $ordered{$ref->{parts_id}}             = $ref;
 
 438   map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
 
 441   foreach my $part (values %ordered) {
 
 442     if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
 
 449     $query = qq|UPDATE oe
 
 452     do_query($form, $dbh, $query, $oe_id);
 
 453     $dbh->commit() if (!$params{dbh});
 
 456   $main::lxdebug->leave_sub();
 
 460   $main::lxdebug->enter_sub();
 
 465   Common::check_params(\%params, qw(ids));
 
 467   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
 
 468     $main::lxdebug->leave_sub();
 
 472   my $myconfig = \%main::myconfig;
 
 473   my $form     = $main::form;
 
 475   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 477   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
 
 479   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
 
 481   $dbh->commit() unless ($params{dbh});
 
 483   $main::lxdebug->leave_sub();
 
 487   $main::lxdebug->enter_sub();
 
 491   my $myconfig = \%main::myconfig;
 
 492   my $form     = $main::form;
 
 493   my $spool    = $::lx_office_conf{paths}->{spool};
 
 495   # connect to database
 
 496   my $dbh = $form->get_standard_dbh($myconfig);
 
 499   my $query = qq|SELECT s.spoolfile FROM status s WHERE s.trans_id = ?|;
 
 500   my $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 506   while (($spoolfile) = $sth->fetchrow_array) {
 
 507     push @spoolfiles, $spoolfile;
 
 512   @values = (conv_i($form->{id}));
 
 514   # delete status entries
 
 515   $query = qq|DELETE FROM status
 
 517   do_query($form, $dbh, $query, @values);
 
 519   # delete individual entries
 
 520   $query = qq|DELETE FROM delivery_order_items_stock
 
 521               WHERE delivery_order_item_id IN (
 
 522                 SELECT id FROM delivery_order_items
 
 523                 WHERE delivery_order_id = ?
 
 525   do_query($form, $dbh, $query, @values);
 
 527   # delete individual entries
 
 528   $query = qq|DELETE FROM delivery_order_items
 
 529               WHERE delivery_order_id = ?|;
 
 530   do_query($form, $dbh, $query, @values);
 
 533   $query = qq|DELETE FROM delivery_orders
 
 535   do_query($form, $dbh, $query, @values);
 
 537   $query = qq|DELETE FROM shipto
 
 538               WHERE trans_id = ? AND module = 'DO'|;
 
 539   do_query($form, $dbh, $query, @values);
 
 541   my $rc = $dbh->commit();
 
 544     foreach $spoolfile (@spoolfiles) {
 
 545       unlink "$spool/$spoolfile" if $spoolfile;
 
 549   $main::lxdebug->leave_sub();
 
 555   $main::lxdebug->enter_sub();
 
 560   my $myconfig = \%main::myconfig;
 
 561   my $form     = $main::form;
 
 563   # connect to database
 
 564   my $dbh = $form->get_standard_dbh($myconfig);
 
 566   my ($query, $query_add, @values, $sth, $ref);
 
 568   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 571   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
 
 573   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
 
 575   if ($mode eq 'default') {
 
 576     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate, current_date AS reqdate|);
 
 577     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 580     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
 
 582     $main::lxdebug->leave_sub();
 
 587   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
 
 588   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
 
 590   # retrieve order for single id
 
 591   # NOTE: this query is intended to fetch all information only ONCE.
 
 592   # so if any of these infos is important (or even different) for any item,
 
 593   # it will be killed out and then has to be fetched from the item scope query further down
 
 595     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
 
 596          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
 
 597          e.name AS employee, dord.employee_id, dord.salesman_id,
 
 598          dord.${vc}_id, cv.name AS ${vc},
 
 599          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
 
 600          d.description AS department, dord.language_id,
 
 602          dord.globalproject_id, dord.delivered, dord.transaction_description,
 
 603          dord.taxzone_id, dord.taxincluded, dord.terms, dord.curr AS currency
 
 604        FROM delivery_orders dord
 
 605        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
 
 606        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
 607        LEFT JOIN department d ON (dord.department_id = d.id)
 
 608        WHERE dord.id IN ($do_ids_placeholders)|;
 
 609   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
 
 611   delete $form->{"${vc}_id"};
 
 612   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 613     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
 
 615       $main::lxdebug->leave_sub();
 
 620     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
 
 621     $form->{donumber_array} .= $form->{donumber} . ' ';
 
 625   # remove any trailing whitespace
 
 626   $form->{currency} =~ s/\s*$//;
 
 628   $form->{donumber_array} =~ s/\s*$//g;
 
 630   $form->{saved_donumber} = $form->{donumber};
 
 632   # if not given, fill transdate with current_date
 
 633   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
 
 635   if ($mode eq 'single') {
 
 636     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
 
 637     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
 
 639     $ref   = $sth->fetchrow_hashref("NAME_lc");
 
 641     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 644     # get printed, emailed and queued
 
 645     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
 
 646     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 648     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 649       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
 650       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
 651       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
 
 654     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
 660   my %oid = ('Pg'     => 'oid',
 
 661              'Oracle' => 'rowid');
 
 663   # retrieve individual items
 
 664   # this query looks up all information about the items
 
 665   # stuff different from the whole will not be overwritten, but saved with a suffix.
 
 667     qq|SELECT doi.id AS delivery_order_items_id,
 
 668          p.partnumber, p.assembly, p.listprice, doi.description, doi.qty,
 
 669          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.bin, p.notes AS partnotes,
 
 670          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
 
 671          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
 
 672          doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
 
 673          pr.projectnumber, dord.transdate AS dord_transdate,
 
 675        FROM delivery_order_items doi
 
 676        JOIN parts p ON (doi.parts_id = p.id)
 
 677        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
 
 678        LEFT JOIN project pr ON (doi.project_id = pr.id)
 
 679        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 680        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
 
 681        ORDER BY doi.$oid{$myconfig->{dbdriver}}|;
 
 683   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
 685   # Retrieve custom variables.
 
 686   foreach my $doi (@{ $form->{form_details} }) {
 
 687     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 689                                            sub_module => 'delivery_order_items',
 
 690                                            trans_id   => $doi->{delivery_order_items_id},
 
 692     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
 
 695   if ($mode eq 'single') {
 
 696     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 699       qq|SELECT qty, unit, bin_id, warehouse_id, chargenumber, bestbefore
 
 700          FROM delivery_order_items_stock
 
 701          WHERE delivery_order_item_id = ?|;
 
 702     my $sth = prepare_query($form, $dbh, $query);
 
 704     foreach my $doi (@{ $form->{form_details} }) {
 
 705       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
 
 707       while (my $ref = $sth->fetchrow_hashref()) {
 
 708         push @{ $requests }, $ref;
 
 711       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
 
 717   Common::webdav_folder($form);
 
 719   $main::lxdebug->leave_sub();
 
 725   $main::lxdebug->enter_sub();
 
 729   my $myconfig = \%main::myconfig;
 
 730   my $form     = $main::form;
 
 732   # connect to database
 
 733   my $dbh = $form->get_standard_dbh($myconfig);
 
 743   my %oid = ('Pg'     => 'oid',
 
 744              'Oracle' => 'rowid');
 
 746   my (@project_ids, %projectnumbers, %projectdescriptions);
 
 748   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
 
 750   # sort items by partsgroup
 
 751   for $i (1 .. $form->{rowcount}) {
 
 753     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
 754       $partsgroup = $form->{"partsgroup_$i"};
 
 756     push @partsgroup, [$i, $partsgroup];
 
 757     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
 
 761     $query = "SELECT id, projectnumber, description FROM project WHERE id IN (" .
 
 762       join(", ", map("?", @project_ids)) . ")";
 
 763     $sth = prepare_execute_query($form, $dbh, $query, @project_ids);
 
 764     while (my $ref = $sth->fetchrow_hashref()) {
 
 765       $projectnumbers{$ref->{id}} = $ref->{projectnumber};
 
 766       $projectdescriptions{$ref->{id}} = $ref->{description};
 
 771   $form->{"globalprojectnumber"} =
 
 772     $projectnumbers{$form->{"globalproject_id"}};
 
 773   $form->{"globalprojectdescription"} =
 
 774       $projectdescriptions{$form->{"globalproject_id"}};
 
 776   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
 
 778                     JOIN parts p ON (a.parts_id = p.id)
 
 779                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 782   my $h_pg     = prepare_query($form, $dbh, $q_pg);
 
 784   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
 
 785                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
 
 786   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
 
 788   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 792   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 794   $form->{TEMPLATE_ARRAYS} = { };
 
 795   IC->prepare_parts_for_printing();
 
 798     qw(runningnumber number description longdescription qty unit
 
 799        partnotes serialnumber reqdate projectnumber projectdescription
 
 800        si_runningnumber si_number si_description
 
 801        si_warehouse si_bin si_chargenumber si_bestbefore si_qty si_unit);
 
 803   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays);
 
 805   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 807   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 808   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 811   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
 814     next if (!$form->{"id_$i"});
 
 818     if ($item->[1] ne $sameitem) {
 
 819       push(@{ $form->{description} }, qq|$item->[1]|);
 
 820       $sameitem = $item->[1];
 
 822       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 825     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 827     # add number, description and qty to $form->{number}, ....
 
 829     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
 
 831     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
 
 832     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
 
 833     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
 
 834     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
 
 835     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
 
 836     push @{ $form->{TEMPLATE_ARRAYS}{qty_nofmt} },       $form->{"qty_$i"};
 
 837     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
 
 838     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
 
 839     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
 
 840     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
 
 841     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $projectnumbers{$form->{"project_id_$i"}};
 
 842     push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} },
 
 843       $projectdescriptions{$form->{"project_id_$i"}};
 
 845     if ($form->{"assembly_$i"}) {
 
 848       # get parts and push them onto the stack
 
 850       if ($form->{groupitems}) {
 
 852           qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
 
 854         $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
 
 857       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
 
 859       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
 
 860         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
 861           map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 862           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
 863           push(@{ $form->{description} }, $sameitem);
 
 865         push(@{ $form->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq|, $ref->{partnumber}, $ref->{description}|);
 
 867         map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 871     if ($form->{"inventory_accno_$i"} && !$form->{"assembly_$i"}) {
 
 872       my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 874       foreach my $si (@{ $stock_info }) {
 
 877         do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
 
 878         my $bin_wh = $h_bin_wh->fetchrow_hashref();
 
 880         push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$position-1] }, $num_si;
 
 881         push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$position-1] },        $form->{"partnumber_$i"};
 
 882         push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$position-1] },   $form->{"description_$i"};
 
 883         push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$position-1] },     $bin_wh->{warehouse};
 
 884         push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$position-1] },           $bin_wh->{bin};
 
 885         push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$position-1] },  $si->{chargenumber};
 
 886         push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$position-1] },    $si->{bestbefore};
 
 887         push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
 
 888         push @{ $form->{TEMPLATE_ARRAYS}{si_qty_nofmt}[$position-1] },     $si->{qty} * 1;
 
 889         push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$position-1] },          $si->{unit};
 
 893     push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
 
 894       CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
 
 895         for @{ $ic_cvar_configs };
 
 901   $form->{username} = $myconfig->{name};
 
 903   $main::lxdebug->leave_sub();
 
 906 sub project_description {
 
 907   $main::lxdebug->enter_sub();
 
 909   my ($self, $dbh, $id) = @_;
 
 911   my $form     =  $main::form;
 
 913   my $query = qq|SELECT description FROM project WHERE id = ?|;
 
 914   my ($value) = selectrow_query($form, $dbh, $query, $id);
 
 916   $main::lxdebug->leave_sub();
 
 921 sub unpack_stock_information {
 
 922   $main::lxdebug->enter_sub();
 
 927   Common::check_params_x(\%params, qw(packed));
 
 931   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
 
 933   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
 
 935   foreach my $entry (@{ $unpacked }) {
 
 936     next if ('HASH' eq ref $entry);
 
 941   $main::lxdebug->leave_sub();
 
 946 sub get_item_availability {
 
 947   $::lxdebug->enter_sub;
 
 952   Common::check_params(\%params, qw(parts_id));
 
 954   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
 
 957     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
 
 958          w.description AS warehousedescription,
 
 959          b.description AS bindescription
 
 961        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
 
 962        LEFT JOIN bin b       ON (i.bin_id       = b.id)
 
 963        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
 
 964        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
 
 966        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
 
 968   my $contents = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, @parts_ids);
 
 970   $::lxdebug->leave_sub;
 
 972   return @{ $contents };
 
 976 sub check_stock_availability {
 
 977   $main::lxdebug->enter_sub();
 
 982   Common::check_params(\%params, qw(requests parts_id));
 
 984   my $myconfig    = \%main::myconfig;
 
 985   my $form        =  $main::form;
 
 987   my $dbh         = $form->get_standard_dbh($myconfig);
 
 989   my $units       = AM->retrieve_units($myconfig, $form);
 
 991   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
 
 992   my $unit_factor = $units->{$partunit}->{factor} || 1;
 
 994   my @contents    = $self->get_item_availability(%params);
 
 998   foreach my $sinfo (@{ $params{requests} }) {
 
1001     foreach my $row (@contents) {
 
1002       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
 
1003                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
 
1004                ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
 
1005                ($row->{bestbefore}   ne $sinfo->{bestbefore}));
 
1009       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
 
1011       if ($base_qty > $row->{qty}) {
 
1012         $sinfo->{error} = 1;
 
1013         push @errors, $sinfo;
 
1019     push @errors, $sinfo if (!$found);
 
1022   $main::lxdebug->leave_sub();
 
1027 sub transfer_in_out {
 
1028   $main::lxdebug->enter_sub();
 
1033   Common::check_params(\%params, qw(direction requests));
 
1035   if (!@{ $params{requests} }) {
 
1036     $main::lxdebug->leave_sub();
 
1040   my $myconfig = \%main::myconfig;
 
1041   my $form     = $main::form;
 
1043   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
 
1047   foreach my $request (@{ $params{requests} }) {
 
1049       'parts_id'               => $request->{parts_id},
 
1050       "${prefix}_warehouse_id" => $request->{warehouse_id},
 
1051       "${prefix}_bin_id"       => $request->{bin_id},
 
1052       'chargenumber'           => $request->{chargenumber},
 
1053       'bestbefore'             => $request->{bestbefore},
 
1054       'qty'                    => $request->{qty},
 
1055       'unit'                   => $request->{unit},
 
1056       'oe_id'                  => $form->{id},
 
1057       'shippingdate'           => 'current_date',
 
1058       'transfer_type'          => $params{direction} eq 'in' ? 'stock' : 'shipped',
 
1059       'project_id'             => $request->{project_id},
 
1063   WH->transfer(@transfers);
 
1065   $main::lxdebug->leave_sub();
 
1068 sub get_shipped_qty {
 
1069   $main::lxdebug->enter_sub();
 
1074   Common::check_params(\%params, qw(type oe_id));
 
1076   my $myconfig = \%main::myconfig;
 
1077   my $form     = $main::form;
 
1079   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1081   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
1082                                         'from_table' => 'oe',
 
1083                                         'from_id'    => $params{oe_id},
 
1084                                         'to_table'   => 'delivery_orders');
 
1085   my @values   = map { $_->{to_id} } @links;
 
1087   if (!scalar @values) {
 
1088     $main::lxdebug->leave_sub();
 
1093     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
 
1094        FROM delivery_order_items doi
 
1095        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
 
1096        LEFT JOIN parts p ON (doi.parts_id = p.id)
 
1097        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
 
1100   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
 
1101   my $all_units = AM->retrieve_all_units();
 
1103   foreach my $entry (@{ $entries }) {
 
1104     $entry->{qty} *= AM->convert_unit($entry->{unit}, $entry->{partunit}, $all_units);
 
1106     if (!$ship{$entry->{parts_id}}) {
 
1107       $ship{$entry->{parts_id}} = $entry;
 
1109       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
 
1113   $main::lxdebug->leave_sub();
 
1118 sub is_marked_as_delivered {
 
1119   $main::lxdebug->enter_sub();
 
1124   Common::check_params(\%params, qw(id));
 
1126   my $myconfig    = \%main::myconfig;
 
1127   my $form        = $main::form;
 
1129   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1131   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
 
1133   $main::lxdebug->leave_sub();
 
1135   return $delivered ? 1 : 0;