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);
 
  42 use SL::DB::DeliveryOrder;
 
  52   $main::lxdebug->enter_sub();
 
  56   my $myconfig = \%main::myconfig;
 
  57   my $form     = $main::form;
 
  60   my $dbh = $form->get_standard_dbh($myconfig);
 
  62   my (@where, @values, $where);
 
  64   my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
 
  67     qq|SELECT dord.id, dord.donumber, dord.ordnumber, dord.cusordnumber,
 
  68          dord.transdate, dord.reqdate,
 
  69          ct.${vc}number, ct.name, dord.${vc}_id, dord.globalproject_id,
 
  70          dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
 
  71          dord.transaction_description,
 
  72          pr.projectnumber AS globalprojectnumber,
 
  73          dep.description AS department,
 
  76        FROM delivery_orders dord
 
  77        LEFT JOIN $vc ct ON (dord.${vc}_id = ct.id)
 
  78        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
  79        LEFT JOIN employee sm ON (dord.salesman_id = sm.id)
 
  80        LEFT JOIN project pr ON (dord.globalproject_id = pr.id)
 
  81        LEFT JOIN department dep ON (dord.department_id = dep.id)
 
  84   push @where, ($form->{type} eq 'sales_delivery_order' ? '' : 'NOT ') . qq|COALESCE(dord.is_sales, FALSE)|;
 
  86   if ($form->{department_id}) {
 
  87     push @where,  qq|dord.department_id = ?|;
 
  88     push @values, conv_i($form->{department_id});
 
  91   if ($form->{project_id}) {
 
  93       qq|(dord.globalproject_id = ?) OR EXISTS
 
  94           (SELECT * FROM delivery_order_items doi
 
  95            WHERE (doi.project_id = ?) AND (doi.delivery_order_id = dord.id))|;
 
  96     push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
 
  99   if ($form->{"${vc}_id"}) {
 
 100     push @where,  qq|dord.${vc}_id = ?|;
 
 101     push @values, $form->{"${vc}_id"};
 
 103   } elsif ($form->{$vc}) {
 
 104     push @where,  qq|ct.name ILIKE ?|;
 
 105     push @values, '%' . $form->{$vc} . '%';
 
 108   foreach my $item (qw(employee_id salesman_id)) {
 
 109     next unless ($form->{$item});
 
 110     push @where, "dord.$item = ?";
 
 111     push @values, conv_i($form->{$item});
 
 113   if (!$main::auth->assert('sales_all_edit', 1)) {
 
 114     push @where, qq|dord.employee_id = (select id from employee where login= ?)|;
 
 115     push @values, $form->{login};
 
 118   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
 
 119     next unless ($form->{$item});
 
 120     push @where,  qq|dord.$item ILIKE ?|;
 
 121     push @values, '%' . $form->{$item} . '%';
 
 124   if (($form->{open} || $form->{closed}) &&
 
 125       ($form->{open} ne $form->{closed})) {
 
 126     push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
 
 129   if (($form->{notdelivered} || $form->{delivered}) &&
 
 130       ($form->{notdelivered} ne $form->{delivered})) {
 
 131     push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
 
 134   if ($form->{serialnumber}) {
 
 135     push @where, 'dord.id IN (SELECT doi.delivery_order_id FROM delivery_order_items doi WHERE doi.serialnumber LIKE ?)';
 
 136     push @values, '%' . $form->{serialnumber} . '%';
 
 139   if($form->{transdatefrom}) {
 
 140     push @where,  qq|dord.transdate >= ?|;
 
 141     push @values, conv_date($form->{transdatefrom});
 
 144   if($form->{transdateto}) {
 
 145     push @where,  qq|dord.transdate <= ?|;
 
 146     push @values, conv_date($form->{transdateto});
 
 149   if($form->{reqdatefrom}) {
 
 150     push @where,  qq|dord.reqdate >= ?|;
 
 151     push @values, conv_date($form->{reqdatefrom});
 
 154   if($form->{reqdateto}) {
 
 155     push @where,  qq|dord.reqdate <= ?|;
 
 156     push @values, conv_date($form->{reqdateto});
 
 160     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
 
 163   my %allowed_sort_columns = (
 
 164     "transdate"               => "dord.transdate",
 
 165     "reqdate"                 => "dord.reqdate",
 
 167     "donumber"                => "dord.donumber",
 
 168     "ordnumber"               => "dord.ordnumber",
 
 170     "employee"                => "e.name",
 
 171     "salesman"                => "sm.name",
 
 172     "shipvia"                 => "dord.shipvia",
 
 173     "transaction_description" => "dord.transaction_description",
 
 174     "department"              => "lower(dep.description)",
 
 177   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 178   my $sortorder = "dord.id";
 
 179   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
 
 180     $sortorder = $allowed_sort_columns{$form->{sort}};
 
 183   $query .= qq| ORDER by | . $sortorder . " $sortdir";
 
 185   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
 
 187   if (scalar @{ $form->{DO} }) {
 
 191          WHERE NOT COALESCE(quotation, FALSE)
 
 193            AND (COALESCE(${vc}_id, 0) != 0)|;
 
 195     my $sth = prepare_query($form, $dbh, $query);
 
 197     foreach my $dord (@{ $form->{DO} }) {
 
 198       next unless ($dord->{ordnumber});
 
 199       do_statement($form, $sth, $query, $dord->{ordnumber});
 
 200       ($dord->{oe_id}) = $sth->fetchrow_array();
 
 206   $main::lxdebug->leave_sub();
 
 210   $main::lxdebug->enter_sub();
 
 214   my $myconfig = \%main::myconfig;
 
 215   my $form     = $main::form;
 
 217   # connect to database, turn off autocommit
 
 218   my $dbh = $form->get_standard_dbh($myconfig);
 
 220   my ($query, @values, $sth, $null);
 
 222   my $all_units = AM->retrieve_units($myconfig, $form);
 
 223   $form->{all_units} = $all_units;
 
 225   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 228   my $trans_number     = SL::TransNumber->new(type => $form->{type}, dbh => $dbh, number => $form->{donumber}, id => $form->{id});
 
 229   $form->{donumber}  ||= $trans_number->create_unique;
 
 230   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
 
 231   $form->get_employee($dbh) unless ($form->{employee_id});
 
 233   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
 
 237     $query = qq|DELETE FROM delivery_order_items_stock WHERE delivery_order_item_id IN (SELECT id FROM delivery_order_items WHERE delivery_order_id = ?)|;
 
 238     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 240     $query = qq|DELETE FROM delivery_order_items WHERE delivery_order_id = ?|;
 
 241     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 243     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
 
 244     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 248     $query = qq|SELECT nextval('id')|;
 
 249     ($form->{id}) = selectrow_query($form, $dbh, $query);
 
 251     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id, currency_id) VALUES (?, '', ?, (SELECT currency_id FROM defaults LIMIT 1))|;
 
 252     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}));
 
 258   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 259   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 262   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
 
 263   my @part_ids    = keys %part_id_map;
 
 267     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
 
 268     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
 
 271   my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
 
 272   my $h_item_id = prepare_query($form, $dbh, $q_item_id);
 
 275     qq|INSERT INTO delivery_order_items (
 
 276          id, delivery_order_id, parts_id, description, longdescription, qty, base_qty,
 
 277          sellprice, discount, unit, reqdate, project_id, serialnumber,
 
 278          ordnumber, transdate, cusordnumber,
 
 279          lastcost, price_factor_id, price_factor, marge_price_factor, pricegroup_id)
 
 280        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
 
 281          (SELECT factor FROM price_factors WHERE id = ?), ?, ?)|;
 
 282   my $h_item = prepare_query($form, $dbh, $q_item);
 
 285     qq|INSERT INTO delivery_order_items_stock (delivery_order_item_id, qty, unit, warehouse_id, bin_id, chargenumber, bestbefore)
 
 286        VALUES (?, ?, ?, ?, ?, ?, ?)|;
 
 287   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
 
 289   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 291   for my $i (1 .. $form->{rowcount}) {
 
 292     next if (!$form->{"id_$i"});
 
 294     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 296     my $item_unit = $part_unit_map{$form->{"id_$i"}};
 
 299     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
 
 300       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
 
 302     my $baseqty = $form->{"qty_$i"} * $basefactor;
 
 304     # set values to 0 if nothing entered
 
 305     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"});
 
 306     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 307     $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
 
 309     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
 
 310     my $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 312     $items_reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
 
 314     do_statement($form, $h_item_id, $q_item_id);
 
 315     my ($item_id) = $h_item_id->fetchrow_array();
 
 317     # Get pricegroup_id and save it. Unfortunately the interface
 
 318     # also uses ID "0" for signalling that none is selected, but "0"
 
 319     # must not be stored in the database. Therefore we cannot simply
 
 321     my $pricegroup_id = $form->{"pricegroup_id_$i"} * 1;
 
 322     $pricegroup_id    = undef if !$pricegroup_id;
 
 324     # save detail record in delivery_order_items table
 
 325     @values = (conv_i($item_id), conv_i($form->{id}), conv_i($form->{"id_$i"}),
 
 326                $form->{"description_$i"}, $form->{"longdescription_$i"},
 
 327                $form->{"qty_$i"}, $baseqty,
 
 328                $form->{"sellprice_$i"}, $form->{"discount_$i"} / 100,
 
 329                $form->{"unit_$i"}, conv_date($items_reqdate), conv_i($form->{"project_id_$i"}),
 
 330                $form->{"serialnumber_$i"},
 
 331                $form->{"ordnumber_$i"}, conv_date($form->{"transdate_$i"}),
 
 332                $form->{"cusordnumber_$i"},
 
 333                $form->{"lastcost_$i"},
 
 334                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
 
 335                conv_i($form->{"marge_price_factor_$i"}),
 
 337     do_statement($form, $h_item, $q_item, @values);
 
 339     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 341     foreach my $sinfo (@{ $stock_info }) {
 
 342       @values = ($item_id, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 343                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}));
 
 344       do_statement($form, $h_item_stock, $q_item_stock, @values);
 
 347     CVar->save_custom_variables(module       => 'IC',
 
 348                                 sub_module   => 'delivery_order_items',
 
 349                                 trans_id     => $item_id,
 
 350                                 configs      => $ic_cvar_configs,
 
 352                                 name_prefix  => 'ic_',
 
 353                                 name_postfix => "_$i",
 
 357   $h_item_id->finish();
 
 359   $h_item_stock->finish();
 
 362   # reqdate is last items reqdate (?: old behaviour) if not already set
 
 363   $form->{reqdate} ||= $items_reqdate;
 
 366     qq|UPDATE delivery_orders SET
 
 367          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
 
 368          customer_id = ?, reqdate = ?,
 
 369          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
 
 370          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
 
 371          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
 
 372          is_sales = ?, taxzone_id = ?, taxincluded = ?, terms = ?, currency_id = (SELECT id FROM currencies WHERE name = ?),
 
 376   @values = ($form->{donumber}, $form->{ordnumber},
 
 377              $form->{cusordnumber}, conv_date($form->{transdate}),
 
 378              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
 
 379              conv_date($form->{reqdate}), $form->{shippingpoint}, $form->{shipvia},
 
 380              $form->{notes}, $form->{intnotes},
 
 381              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
 
 382              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
 
 383              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
 
 384              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
 
 385              $form->{transaction_description},
 
 386              $form->{type} =~ /^sales/ ? 't' : 'f',
 
 387              conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{terms}), $form->{currency},
 
 388              conv_i($form->{delivery_term_id}),
 
 389              conv_i($form->{id}));
 
 390   do_query($form, $dbh, $query, @values);
 
 393   $form->{name} = $form->{ $form->{vc} };
 
 394   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
 
 396   if (!$form->{shipto_id}) {
 
 397     $form->add_shipto($dbh, $form->{id}, "DO");
 
 400   # save printed, emailed, queued
 
 401   $form->save_status($dbh);
 
 403   # Link this delivery order to the quotations it was created from.
 
 404   RecordLinks->create_links('dbh'        => $dbh,
 
 406                             'from_table' => 'oe',
 
 407                             'from_ids'   => $form->{convert_from_oe_ids},
 
 408                             'to_table'   => 'delivery_orders',
 
 409                             'to_id'      => $form->{id},
 
 411   delete $form->{convert_from_oe_ids};
 
 413   $self->mark_orders_if_delivered('do_id' => $form->{id},
 
 414                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
 
 417   my $rc = $dbh->commit();
 
 419   $form->{saved_donumber} = $form->{donumber};
 
 420   $form->{saved_ordnumber} = $form->{ordnumber};
 
 421   $form->{saved_cusordnumber} = $form->{cusordnumber};
 
 423   Common::webdav_folder($form);
 
 425   $main::lxdebug->leave_sub();
 
 430 sub mark_orders_if_delivered {
 
 431   $main::lxdebug->enter_sub();
 
 436   Common::check_params(\%params, qw(do_id type));
 
 438   my $myconfig = \%main::myconfig;
 
 439   my $form     = $main::form;
 
 441   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 443   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
 444                                         'from_table' => 'oe',
 
 445                                         'to_table'   => 'delivery_orders',
 
 446                                         'to_id'      => $params{do_id});
 
 448   my $oe_id  = @links ? $links[0]->{from_id} : undef;
 
 450   return $main::lxdebug->leave_sub() if (!$oe_id);
 
 452   my $all_units = AM->retrieve_all_units();
 
 454   my $query     = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
 
 456                      LEFT JOIN parts p ON (oi.parts_id = p.id)
 
 457                      WHERE (oi.trans_id = ?)|;
 
 458   my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
 
 460   my %shipped   = $self->get_shipped_qty('type'  => $params{type},
 
 464   while (my $ref = $sth->fetchrow_hashref()) {
 
 465     $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
 
 467     if ($ordered{$ref->{parts_id}}) {
 
 468       $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
 
 470       $ordered{$ref->{parts_id}}             = $ref;
 
 476   map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
 
 479   foreach my $part (values %ordered) {
 
 480     if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
 
 487     $query = qq|UPDATE oe
 
 490     do_query($form, $dbh, $query, $oe_id);
 
 491     $dbh->commit() if (!$params{dbh});
 
 494   $main::lxdebug->leave_sub();
 
 498   $main::lxdebug->enter_sub();
 
 503   Common::check_params(\%params, qw(ids));
 
 505   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
 
 506     $main::lxdebug->leave_sub();
 
 510   my $myconfig = \%main::myconfig;
 
 511   my $form     = $main::form;
 
 513   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 515   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
 
 517   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
 
 519   $dbh->commit() unless ($params{dbh});
 
 521   $main::lxdebug->leave_sub();
 
 525   $main::lxdebug->enter_sub();
 
 529   my $myconfig = \%main::myconfig;
 
 530   my $form     = $main::form;
 
 531   my $spool    = $::lx_office_conf{paths}->{spool};
 
 533   my $rc = SL::DB::Order->new->db->with_transaction(sub {
 
 534     my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $form->{id} ]) };
 
 536     SL::DB::DeliveryOrder->new(id => $form->{id})->delete;
 
 538     my $spool = $::lx_office_conf{paths}->{spool};
 
 539     unlink map { "$spool/$_" } @spoolfiles if $spool;
 
 544   $main::lxdebug->leave_sub();
 
 550   $main::lxdebug->enter_sub();
 
 555   my $myconfig = \%main::myconfig;
 
 556   my $form     = $main::form;
 
 558   # connect to database
 
 559   my $dbh = $form->get_standard_dbh($myconfig);
 
 561   my ($query, $query_add, @values, $sth, $ref);
 
 563   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 566   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
 
 568   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
 
 570   if ($mode eq 'default') {
 
 571     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate|);
 
 572     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 574     # if reqdate is not set from oe-workflow, set it to transdate (which is current date)
 
 575     $form->{reqdate} ||= $form->{transdate};
 
 578     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
 
 580     $main::lxdebug->leave_sub();
 
 585   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
 
 586   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
 
 588   # retrieve order for single id
 
 589   # NOTE: this query is intended to fetch all information only ONCE.
 
 590   # so if any of these infos is important (or even different) for any item,
 
 591   # it will be killed out and then has to be fetched from the item scope query further down
 
 593     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
 
 594          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
 
 595          e.name AS employee, dord.employee_id, dord.salesman_id,
 
 596          dord.${vc}_id, cv.name AS ${vc},
 
 597          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
 
 598          d.description AS department, dord.language_id,
 
 600          dord.globalproject_id, dord.delivered, dord.transaction_description,
 
 601          dord.taxzone_id, dord.taxincluded, dord.terms, (SELECT cu.name FROM currencies cu WHERE cu.id=dord.currency_id) AS currency,
 
 602          dord.delivery_term_id
 
 603        FROM delivery_orders dord
 
 604        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
 
 605        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
 606        LEFT JOIN department d ON (dord.department_id = d.id)
 
 607        WHERE dord.id IN ($do_ids_placeholders)|;
 
 608   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
 
 610   delete $form->{"${vc}_id"};
 
 612   $form->{ordnumber_array} = ' ';
 
 613   $form->{cusordnumber_array} = ' ';
 
 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} . ' ';
 
 624     $pos = index($form->{ordnumber_array},' ' . $form->{ordnumber} . ' ');
 
 626       $form->{ordnumber_array} .= $form->{ordnumber} . ' ';
 
 628     $pos = index($form->{cusordnumber_array},' ' . $form->{cusordnumber} . ' ');
 
 630       $form->{cusordnumber_array} .= $form->{cusordnumber} . ' ';
 
 635   $form->{donumber_array} =~ s/\s*$//g;
 
 636   $form->{ordnumber_array} =~ s/ //;
 
 637   $form->{ordnumber_array} =~ s/\s*$//g;
 
 638   $form->{cusordnumber_array} =~ s/ //;
 
 639   $form->{cusordnumber_array} =~ s/\s*$//g;
 
 641   $form->{saved_donumber} = $form->{donumber};
 
 642   $form->{saved_ordnumber} = $form->{ordnumber};
 
 643   $form->{saved_cusordnumber} = $form->{cusordnumber};
 
 645   # if not given, fill transdate with current_date
 
 646   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
 
 648   if ($mode eq 'single') {
 
 649     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
 
 650     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
 
 652     $ref   = $sth->fetchrow_hashref("NAME_lc");
 
 654     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 657     # get printed, emailed and queued
 
 658     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
 
 659     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 661     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 662       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
 663       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
 664       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
 
 667     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
 673   # retrieve individual items
 
 674   # this query looks up all information about the items
 
 675   # stuff different from the whole will not be overwritten, but saved with a suffix.
 
 677     qq|SELECT doi.id AS delivery_order_items_id,
 
 678          p.partnumber, p.assembly, p.listprice, doi.description, doi.qty,
 
 679          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.notes AS partnotes,
 
 680          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
 
 681          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
 
 682          doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
 
 683          pr.projectnumber, dord.transdate AS dord_transdate, dord.donumber,
 
 685        FROM delivery_order_items doi
 
 686        JOIN parts p ON (doi.parts_id = p.id)
 
 687        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
 
 688        LEFT JOIN project pr ON (doi.project_id = pr.id)
 
 689        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 690        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
 
 693   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
 695   # Retrieve custom variables.
 
 696   foreach my $doi (@{ $form->{form_details} }) {
 
 697     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 699                                            sub_module => 'delivery_order_items',
 
 700                                            trans_id   => $doi->{delivery_order_items_id},
 
 702     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
 
 705   if ($mode eq 'single') {
 
 706     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 709       qq|SELECT qty, unit, bin_id, warehouse_id, chargenumber, bestbefore
 
 710          FROM delivery_order_items_stock
 
 711          WHERE delivery_order_item_id = ?|;
 
 712     my $sth = prepare_query($form, $dbh, $query);
 
 714     foreach my $doi (@{ $form->{form_details} }) {
 
 715       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
 
 717       while (my $ref = $sth->fetchrow_hashref()) {
 
 718         push @{ $requests }, $ref;
 
 721       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
 
 727   Common::webdav_folder($form);
 
 729   $main::lxdebug->leave_sub();
 
 735   $main::lxdebug->enter_sub();
 
 737   my ($self, $myconfig, $form) = @_;
 
 739   # connect to database
 
 740   my $dbh = $form->get_standard_dbh($myconfig);
 
 749   my $subtotal_header = 0;
 
 754   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
 
 756   # sort items by partsgroup
 
 757   for $i (1 .. $form->{rowcount}) {
 
 759     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
 760       $partsgroup = $form->{"partsgroup_$i"};
 
 762     push @partsgroup, [$i, $partsgroup];
 
 763     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
 
 769     $projects = SL::DB::Manager::Project->get_all(query => [ id => \@project_ids ]);
 
 770     %projects_by_id = map { $_->id => $_ } @$projects;
 
 773   if ($projects_by_id{$form->{"globalproject_id"}}) {
 
 774     $form->{globalprojectnumber} = $projects_by_id{$form->{"globalproject_id"}}->projectnumber;
 
 775     $form->{globalprojectdescription} = $projects_by_id{$form->{"globalproject_id"}}->description;
 
 777     for (@{ $projects_by_id{$form->{"globalproject_id"}}->cvars_by_config }) {
 
 778       $form->{"project_cvar_" . $_->config->name} = $_->value_as_text;
 
 782   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
 
 784                     JOIN parts p ON (a.parts_id = p.id)
 
 785                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 788   my $h_pg     = prepare_query($form, $dbh, $q_pg);
 
 790   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
 
 791                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
 
 792   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
 
 794   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 798   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 799   my $project_cvar_configs = CVar->get_configs(module => 'Projects');
 
 801   $form->{TEMPLATE_ARRAYS} = { };
 
 802   IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
 
 805     qw(runningnumber number description longdescription qty unit
 
 806        partnotes serialnumber reqdate projectnumber projectdescription
 
 807        si_runningnumber si_number si_description
 
 808        si_warehouse si_bin si_chargenumber si_bestbefore si_qty si_unit weight lineweight);
 
 810   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays);
 
 812   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 813   push @arrays, map { "project_cvar_$_->{name}" } @{ $project_cvar_configs };
 
 815   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 816   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 820   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
 823     next if (!$form->{"id_$i"});
 
 825     if ($item->[1] ne $sameitem) {
 
 826       push(@{ $form->{description} }, qq|$item->[1]|);
 
 827       $sameitem = $item->[1];
 
 829       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 832     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 834     # add number, description and qty to $form->{number}, ....
 
 835     if ($form->{"subtotal_$i"} && !$subtotal_header) {
 
 836       $subtotal_header = $i;
 
 837       $position = int($position);
 
 840     } elsif ($subtotal_header) {
 
 842       $position = int($position);
 
 843       $position = $position.".".$subposition;
 
 845       $position = int($position);
 
 849     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
 
 850     my $project = $projects_by_id{$form->{"project_id_$i"}} || SL::DB::Project->new;
 
 852     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
 
 853     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
 
 854     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
 
 855     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
 
 856     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
 
 857     push @{ $form->{TEMPLATE_ARRAYS}{qty_nofmt} },       $form->{"qty_$i"};
 
 858     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
 
 859     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
 
 860     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
 
 861     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
 
 862     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $project->projectnumber;
 
 863     push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} }, $project->description;
 
 865     if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
 
 866       $subtotal_header     = 0;
 
 869     my $lineweight = $form->{"qty_$i"} * $form->{"weight_$i"};
 
 870     $totalweight += $lineweight;
 
 871     push @{ $form->{TEMPLATE_ARRAYS}->{weight} },            $form->format_amount($myconfig, $form->{"weight_$i"}, 3);
 
 872     push @{ $form->{TEMPLATE_ARRAYS}->{weight_nofmt} },      $form->{"weight_$i"};
 
 873     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight} },        $form->format_amount($myconfig, $lineweight, 3);
 
 874     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight_nofmt} },  $lineweight;
 
 876     if ($form->{"assembly_$i"}) {
 
 879       # get parts and push them onto the stack
 
 881       if ($form->{groupitems}) {
 
 883           qq|ORDER BY pg.partsgroup, a.oid|;
 
 885         $sortorder = qq|ORDER BY a.oid|;
 
 888       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
 
 890       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
 
 891         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
 892           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 893           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
 894           push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
 
 896         push(@{ $form->{TEMPLATE_ARRAYS}->{"description"} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
 
 898         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 902     if ($form->{"inventory_accno_$i"} && !$form->{"assembly_$i"}) {
 
 903       my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 905       foreach my $si (@{ $stock_info }) {
 
 908         do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
 
 909         my $bin_wh = $h_bin_wh->fetchrow_hashref();
 
 911         push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$position-1] }, $num_si;
 
 912         push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$position-1] },        $form->{"partnumber_$i"};
 
 913         push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$position-1] },   $form->{"description_$i"};
 
 914         push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$position-1] },     $bin_wh->{warehouse};
 
 915         push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$position-1] },           $bin_wh->{bin};
 
 916         push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$position-1] },  $si->{chargenumber};
 
 917         push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$position-1] },    $si->{bestbefore};
 
 918         push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
 
 919         push @{ $form->{TEMPLATE_ARRAYS}{si_qty_nofmt}[$position-1] },     $si->{qty} * 1;
 
 920         push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$position-1] },          $si->{unit};
 
 924     push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
 
 925       CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
 
 926         for @{ $ic_cvar_configs };
 
 928     push @{ $form->{TEMPLATE_ARRAYS}->{"project_cvar_" . $_->config->name} }, $_->value_as_text for @{ $project->cvars_by_config };
 
 931   $form->{totalweight}       = $form->format_amount($myconfig, $totalweight, 3);
 
 932   $form->{totalweight_nofmt} = $totalweight;
 
 933   my $defaults = AM->get_defaults();
 
 934   $form->{weightunit}        = $defaults->{weightunit};
 
 939   $form->{delivery_term} = SL::DB::Manager::DeliveryTerm->find_by(id => $form->{delivery_term_id} || undef);
 
 940   $form->{delivery_term}->description_long($form->{delivery_term}->translated_attribute('description_long', $form->{language_id})) if $form->{delivery_term} && $form->{language_id};
 
 942   $form->{username} = $myconfig->{name};
 
 944   $main::lxdebug->leave_sub();
 
 947 sub project_description {
 
 948   $main::lxdebug->enter_sub();
 
 950   my ($self, $dbh, $id) = @_;
 
 952   my $form     =  $main::form;
 
 954   my $query = qq|SELECT description FROM project WHERE id = ?|;
 
 955   my ($value) = selectrow_query($form, $dbh, $query, $id);
 
 957   $main::lxdebug->leave_sub();
 
 962 sub unpack_stock_information {
 
 963   $main::lxdebug->enter_sub();
 
 968   Common::check_params_x(\%params, qw(packed));
 
 972   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
 
 974   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
 
 976   foreach my $entry (@{ $unpacked }) {
 
 977     next if ('HASH' eq ref $entry);
 
 982   $main::lxdebug->leave_sub();
 
 987 sub get_item_availability {
 
 988   $::lxdebug->enter_sub;
 
 993   Common::check_params(\%params, qw(parts_id));
 
 995   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
 
 998     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
 
 999          w.description AS warehousedescription,
 
1000          b.description AS bindescription
 
1002        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
 
1003        LEFT JOIN bin b       ON (i.bin_id       = b.id)
 
1004        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
 
1005        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
 
1007        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
 
1009   my $contents = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, @parts_ids);
 
1011   $::lxdebug->leave_sub;
 
1013   return @{ $contents };
 
1017 sub check_stock_availability {
 
1018   $main::lxdebug->enter_sub();
 
1023   Common::check_params(\%params, qw(requests parts_id));
 
1025   my $myconfig    = \%main::myconfig;
 
1026   my $form        =  $main::form;
 
1028   my $dbh         = $form->get_standard_dbh($myconfig);
 
1030   my $units       = AM->retrieve_units($myconfig, $form);
 
1032   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
 
1033   my $unit_factor = $units->{$partunit}->{factor} || 1;
 
1035   my @contents    = $self->get_item_availability(%params);
 
1039   foreach my $sinfo (@{ $params{requests} }) {
 
1042     foreach my $row (@contents) {
 
1043       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
 
1044                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
 
1045                ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
 
1046                ($row->{bestbefore}   ne $sinfo->{bestbefore}));
 
1050       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
 
1052       if ($base_qty > $row->{qty}) {
 
1053         $sinfo->{error} = 1;
 
1054         push @errors, $sinfo;
 
1060     push @errors, $sinfo if (!$found);
 
1063   $main::lxdebug->leave_sub();
 
1068 sub transfer_in_out {
 
1069   $main::lxdebug->enter_sub();
 
1074   Common::check_params(\%params, qw(direction requests));
 
1076   if (!@{ $params{requests} }) {
 
1077     $main::lxdebug->leave_sub();
 
1081   my $myconfig = \%main::myconfig;
 
1082   my $form     = $main::form;
 
1084   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
 
1088   foreach my $request (@{ $params{requests} }) {
 
1090       'parts_id'               => $request->{parts_id},
 
1091       "${prefix}_warehouse_id" => $request->{warehouse_id},
 
1092       "${prefix}_bin_id"       => $request->{bin_id},
 
1093       'chargenumber'           => $request->{chargenumber},
 
1094       'bestbefore'             => $request->{bestbefore},
 
1095       'qty'                    => $request->{qty},
 
1096       'unit'                   => $request->{unit},
 
1097       'oe_id'                  => $form->{id},
 
1098       'shippingdate'           => 'current_date',
 
1099       'transfer_type'          => $params{direction} eq 'in' ? 'stock' : 'shipped',
 
1100       'project_id'             => $request->{project_id},
 
1104   WH->transfer(@transfers);
 
1106   $main::lxdebug->leave_sub();
 
1109 sub get_shipped_qty {
 
1110   $main::lxdebug->enter_sub();
 
1115   Common::check_params(\%params, qw(type oe_id));
 
1117   my $myconfig = \%main::myconfig;
 
1118   my $form     = $main::form;
 
1120   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1122   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
1123                                         'from_table' => 'oe',
 
1124                                         'from_id'    => $params{oe_id},
 
1125                                         'to_table'   => 'delivery_orders');
 
1126   my @values   = map { $_->{to_id} } @links;
 
1128   if (!scalar @values) {
 
1129     $main::lxdebug->leave_sub();
 
1134     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
 
1135        FROM delivery_order_items doi
 
1136        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
 
1137        LEFT JOIN parts p ON (doi.parts_id = p.id)
 
1138        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
 
1141   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
 
1142   my $all_units = AM->retrieve_all_units();
 
1144   foreach my $entry (@{ $entries }) {
 
1145     $entry->{qty} *= AM->convert_unit($entry->{unit}, $entry->{partunit}, $all_units);
 
1147     if (!$ship{$entry->{parts_id}}) {
 
1148       $ship{$entry->{parts_id}} = $entry;
 
1150       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
 
1154   $main::lxdebug->leave_sub();
 
1159 sub is_marked_as_delivered {
 
1160   $main::lxdebug->enter_sub();
 
1165   Common::check_params(\%params, qw(id));
 
1167   my $myconfig    = \%main::myconfig;
 
1168   my $form        = $main::form;
 
1170   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1172   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
 
1174   $main::lxdebug->leave_sub();
 
1176   return $delivered ? 1 : 0;