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;
 
  45 use SL::HTML::Restrict;
 
  49 use SL::Util qw(trim);
 
  54   $main::lxdebug->enter_sub();
 
  58   my $myconfig = \%main::myconfig;
 
  59   my $form     = $main::form;
 
  62   my $dbh = $form->get_standard_dbh($myconfig);
 
  64   my (@where, @values, $where);
 
  66   my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
 
  69     qq|SELECT dord.id, dord.donumber, dord.ordnumber, dord.cusordnumber,
 
  70          dord.transdate, dord.reqdate,
 
  71          ct.${vc}number, ct.name, ct.business_id,
 
  72          dord.${vc}_id, dord.globalproject_id,
 
  73          dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
 
  74          dord.transaction_description, dord.itime::DATE AS insertdate,
 
  75          pr.projectnumber AS globalprojectnumber,
 
  76          dep.description AS department,
 
  79        FROM delivery_orders dord
 
  80        LEFT JOIN $vc ct ON (dord.${vc}_id = ct.id)
 
  81        LEFT JOIN contacts cp ON (dord.cp_id = cp.cp_id)
 
  82        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
  83        LEFT JOIN employee sm ON (dord.salesman_id = sm.id)
 
  84        LEFT JOIN project pr ON (dord.globalproject_id = pr.id)
 
  85        LEFT JOIN department dep ON (dord.department_id = dep.id)
 
  88   push @where, ($form->{type} eq 'sales_delivery_order' ? '' : 'NOT ') . qq|COALESCE(dord.is_sales, FALSE)|;
 
  90   if ($form->{department_id}) {
 
  91     push @where,  qq|dord.department_id = ?|;
 
  92     push @values, conv_i($form->{department_id});
 
  95   if ($form->{project_id}) {
 
  97       qq|(dord.globalproject_id = ?) OR EXISTS
 
  98           (SELECT * FROM delivery_order_items doi
 
  99            WHERE (doi.project_id = ?) AND (doi.delivery_order_id = dord.id))|;
 
 100     push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
 
 103   if ($form->{"business_id"}) {
 
 104     push @where,  qq|ct.business_id = ?|;
 
 105     push @values, conv_i($form->{"business_id"});
 
 108   if ($form->{"${vc}_id"}) {
 
 109     push @where,  qq|dord.${vc}_id = ?|;
 
 110     push @values, $form->{"${vc}_id"};
 
 112   } elsif ($form->{$vc}) {
 
 113     push @where,  qq|ct.name ILIKE ?|;
 
 114     push @values, like($form->{$vc});
 
 117   if ($form->{"cp_name"}) {
 
 118     push @where, "(cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
 
 119     push @values, (like($form->{"cp_name"}))x2;
 
 122   foreach my $item (qw(employee_id salesman_id)) {
 
 123     next unless ($form->{$item});
 
 124     push @where, "dord.$item = ?";
 
 125     push @values, conv_i($form->{$item});
 
 127   if (!$main::auth->assert('sales_all_edit', 1)) {
 
 128     push @where, qq|dord.employee_id = (select id from employee where login= ?)|;
 
 129     push @values, $::myconfig{login};
 
 132   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
 
 133     next unless ($form->{$item});
 
 134     push @where,  qq|dord.$item ILIKE ?|;
 
 135     push @values, like($form->{$item});
 
 138   if (($form->{open} || $form->{closed}) &&
 
 139       ($form->{open} ne $form->{closed})) {
 
 140     push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
 
 143   if (($form->{notdelivered} || $form->{delivered}) &&
 
 144       ($form->{notdelivered} ne $form->{delivered})) {
 
 145     push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
 
 148   if ($form->{serialnumber}) {
 
 149     push @where, 'dord.id IN (SELECT doi.delivery_order_id FROM delivery_order_items doi WHERE doi.serialnumber LIKE ?)';
 
 150     push @values, like($form->{serialnumber});
 
 153   if($form->{transdatefrom}) {
 
 154     push @where,  qq|dord.transdate >= ?|;
 
 155     push @values, conv_date($form->{transdatefrom});
 
 158   if($form->{transdateto}) {
 
 159     push @where,  qq|dord.transdate <= ?|;
 
 160     push @values, conv_date($form->{transdateto});
 
 163   if($form->{reqdatefrom}) {
 
 164     push @where,  qq|dord.reqdate >= ?|;
 
 165     push @values, conv_date($form->{reqdatefrom});
 
 168   if($form->{reqdateto}) {
 
 169     push @where,  qq|dord.reqdate <= ?|;
 
 170     push @values, conv_date($form->{reqdateto});
 
 173   if($form->{insertdatefrom}) {
 
 174     push @where, qq|dord.itime::DATE >= ?|;
 
 175     push@values, conv_date($form->{insertdatefrom});
 
 178   if($form->{insertdateto}) {
 
 179     push @where, qq|dord.itime::DATE <= ?|;
 
 180     push @values, conv_date($form->{insertdateto});
 
 183   if ($form->{parts_partnumber}) {
 
 186         SELECT delivery_order_items.delivery_order_id
 
 187         FROM delivery_order_items
 
 188         LEFT JOIN parts ON (delivery_order_items.parts_id = parts.id)
 
 189         WHERE (delivery_order_items.delivery_order_id = dord.id)
 
 190           AND (parts.partnumber ILIKE ?)
 
 194     push @values, like($form->{parts_partnumber});
 
 197   if ($form->{parts_description}) {
 
 200         SELECT delivery_order_items.delivery_order_id
 
 201         FROM delivery_order_items
 
 202         WHERE (delivery_order_items.delivery_order_id = dord.id)
 
 203           AND (delivery_order_items.description ILIKE ?)
 
 207     push @values, like($form->{parts_description});
 
 211     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
 
 214   my %allowed_sort_columns = (
 
 215     "transdate"               => "dord.transdate",
 
 216     "reqdate"                 => "dord.reqdate",
 
 218     "donumber"                => "dord.donumber",
 
 219     "ordnumber"               => "dord.ordnumber",
 
 221     "employee"                => "e.name",
 
 222     "salesman"                => "sm.name",
 
 223     "shipvia"                 => "dord.shipvia",
 
 224     "transaction_description" => "dord.transaction_description",
 
 225     "department"              => "lower(dep.description)",
 
 226     "insertdate"              => "dord.itime",
 
 229   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 230   my $sortorder = "dord.id";
 
 231   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
 
 232     $sortorder = $allowed_sort_columns{$form->{sort}};
 
 235   $query .= qq| ORDER by | . $sortorder . " $sortdir";
 
 237   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
 
 239   if (scalar @{ $form->{DO} }) {
 
 243          WHERE NOT COALESCE(quotation, FALSE)
 
 245            AND (COALESCE(${vc}_id, 0) != 0)|;
 
 247     my $sth = prepare_query($form, $dbh, $query);
 
 249     foreach my $dord (@{ $form->{DO} }) {
 
 250       next unless ($dord->{ordnumber});
 
 251       do_statement($form, $sth, $query, $dord->{ordnumber});
 
 252       ($dord->{oe_id}) = $sth->fetchrow_array();
 
 258   $main::lxdebug->leave_sub();
 
 262   $main::lxdebug->enter_sub();
 
 266   my $myconfig = \%main::myconfig;
 
 267   my $form     = $main::form;
 
 269   # connect to database, turn off autocommit
 
 270   my $dbh = $form->get_standard_dbh($myconfig);
 
 271   my $restricter = SL::HTML::Restrict->create;
 
 273   my ($query, @values, $sth, $null);
 
 275   my $all_units = AM->retrieve_units($myconfig, $form);
 
 276   $form->{all_units} = $all_units;
 
 278   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 281   my $trans_number     = SL::TransNumber->new(type => $form->{type}, dbh => $dbh, number => $form->{donumber}, id => $form->{id});
 
 282   $form->{donumber}  ||= $trans_number->create_unique;
 
 283   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
 
 284   $form->get_employee($dbh) unless ($form->{employee_id});
 
 286   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
 
 288   my (@processed_doi, @processed_dois);
 
 292     # only delete shipto complete
 
 293     $query = qq|DELETE FROM custom_variables
 
 294                 WHERE (config_id IN (SELECT id        FROM custom_variable_configs WHERE (module = 'ShipTo')))
 
 295                   AND (trans_id  IN (SELECT shipto_id FROM shipto                  WHERE (module = 'DO') AND (trans_id = ?)))|;
 
 296     do_query($form, $dbh, $query, $form->{id});
 
 298     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
 
 299     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 303     $query = qq|SELECT nextval('id')|;
 
 304     ($form->{id}) = selectrow_query($form, $dbh, $query);
 
 306     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id, currency_id, taxzone_id) VALUES (?, '', ?, (SELECT currency_id FROM defaults LIMIT 1), ?)|;
 
 307     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}), $form->{taxzone_id});
 
 313   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 314   my %price_factors = map { $_->{id} => $_->{factor} *1 } @{ $form->{ALL_PRICE_FACTORS} };
 
 317   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
 
 318   my @part_ids    = keys %part_id_map;
 
 322     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
 
 323     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
 
 326     UPDATE delivery_order_items SET
 
 327        delivery_order_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
 
 328        sellprice = ?, discount = ?, unit = ?, reqdate = ?, project_id = ?, serialnumber = ?,
 
 329        lastcost = ? , price_factor_id = ?, price_factor = (SELECT factor FROM price_factors where id = ?),
 
 330        marge_price_factor = ?, pricegroup_id = ?, active_price_source = ?, active_discount_source = ?
 
 333   my $h_item = prepare_query($form, $dbh, $q_item);
 
 335   my $q_item_stock = <<SQL;
 
 336     UPDATE delivery_order_items_stock SET
 
 337       delivery_order_item_id = ?, qty = ?,  unit = ?,  warehouse_id = ?,
 
 338       bin_id = ?, chargenumber = ?, bestbefore = ?
 
 341   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
 
 343   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 345   for my $i (1 .. $form->{rowcount}) {
 
 346     next if (!$form->{"id_$i"});
 
 348     CVar->get_non_editable_ic_cvars(form               => $form,
 
 351                                     sub_module         => 'delivery_order_items',
 
 352                                     may_converted_from => ['orderitems', 'delivery_order_items']);
 
 356     if (!$form->{"delivery_order_items_id_$i"}) {
 
 357       # there is no persistent id, therefore create one with all necessary constraints
 
 358       my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
 
 359       my $h_item_id = prepare_query($form, $dbh, $q_item_id);
 
 360       do_statement($form, $h_item_id, $q_item_id);
 
 361       $form->{"delivery_order_items_id_$i"}  = $h_item_id->fetchrow_array();
 
 362       $query = qq|INSERT INTO delivery_order_items (id, delivery_order_id, position, parts_id) VALUES (?, ?, ?, ?)|;
 
 363       do_query($form, $dbh, $query, conv_i($form->{"delivery_order_items_id_$i"}),
 
 364                 conv_i($form->{"id"}), conv_i($position), conv_i($form->{"id_$i"}));
 
 365       $h_item_id->finish();
 
 368     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 370     my $item_unit = $part_unit_map{$form->{"id_$i"}};
 
 373     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
 
 374       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
 
 376     my $baseqty = $form->{"qty_$i"} * $basefactor;
 
 378     # set values to 0 if nothing entered
 
 379     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"});
 
 380     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 381     $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
 
 383     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
 
 384     my $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 386     $items_reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
 
 389     # Get pricegroup_id and save it. Unfortunately the interface
 
 390     # also uses ID "0" for signalling that none is selected, but "0"
 
 391     # must not be stored in the database. Therefore we cannot simply
 
 393     my $pricegroup_id = $form->{"pricegroup_id_$i"} * 1;
 
 394     $pricegroup_id    = undef if !$pricegroup_id;
 
 396     # save detail record in delivery_order_items table
 
 397     @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
 
 398                $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}),
 
 399                $form->{"qty_$i"}, $baseqty,
 
 400                $form->{"sellprice_$i"}, $form->{"discount_$i"} / 100,
 
 401                $form->{"unit_$i"}, conv_date($items_reqdate), conv_i($form->{"project_id_$i"}),
 
 402                $form->{"serialnumber_$i"},
 
 403                $form->{"lastcost_$i"},
 
 404                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
 
 405                conv_i($form->{"marge_price_factor_$i"}),
 
 407                $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
 
 408                conv_i($form->{"delivery_order_items_id_$i"}));
 
 409     do_statement($form, $h_item, $q_item, @values);
 
 410     push @processed_doi, $form->{"delivery_order_items_id_$i"}; # transaction safe?
 
 412     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 414     foreach my $sinfo (@{ $stock_info }) {
 
 415       # if we have stock_info, we have to check for persistents entries
 
 416       if (!$sinfo->{"delivery_order_items_stock_id"}) {
 
 417         my $q_item_stock_id = qq|SELECT nextval('id')|;
 
 418         my $h_item_stock_id = prepare_query($form, $dbh, $q_item_stock_id);
 
 419         do_statement($form, $h_item_stock_id, $q_item_stock_id);
 
 420         $sinfo->{"delivery_order_items_stock_id"} = $h_item_stock_id->fetchrow_array();
 
 421         $query = qq|INSERT INTO delivery_order_items_stock (id, delivery_order_item_id, qty, unit, warehouse_id, bin_id)
 
 422                     VALUES (?, ?, ?, ?, ?, ?)|;
 
 423         do_query($form, $dbh, $query, conv_i($sinfo->{"delivery_order_items_stock_id"}),
 
 424                   conv_i($form->{"delivery_order_items_id_$i"}), $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 425                   conv_i($sinfo->{bin_id}));
 
 426         $h_item_stock_id->finish();
 
 427         # write back the id to the form (important if only transfer was clicked (id fk for invoice)
 
 428         $form->{"stock_${in_out}_$i"} = YAML::Dump($stock_info);
 
 430       @values = ($form->{"delivery_order_items_id_$i"}, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 431                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}),
 
 432                  conv_i($sinfo->{"delivery_order_items_stock_id"}));
 
 433       do_statement($form, $h_item_stock, $q_item_stock, @values);
 
 434       push @processed_dois, $sinfo->{"delivery_order_items_stock_id"};
 
 437     CVar->save_custom_variables(module       => 'IC',
 
 438                                 sub_module   => 'delivery_order_items',
 
 439                                 trans_id     => $form->{"delivery_order_items_id_$i"},
 
 440                                 configs      => $ic_cvar_configs,
 
 442                                 name_prefix  => 'ic_',
 
 443                                 name_postfix => "_$i",
 
 446     # link order items with doi, for future extension look at foreach IS.pm
 
 447     if (!$form->{saveasnew} && $form->{"converted_from_orderitems_id_$i"}) {
 
 448       RecordLinks->create_links('dbh'        => $dbh,
 
 450                                 'from_table' => 'orderitems',
 
 451                                 'from_ids'   => $form->{"converted_from_orderitems_id_$i"},
 
 452                                 'to_table'   => 'delivery_order_items',
 
 453                                 'to_id'      =>  $form->{"delivery_order_items_id_$i"},
 
 456     delete $form->{"converted_from_orderitems_id_$i"};
 
 459   # 1. search for orphaned dois; processed_dois may be empty (no transfer) TODO: be supersafe and alter same statement for doi and oi
 
 460   $query  = sprintf 'SELECT id FROM delivery_order_items_stock WHERE delivery_order_item_id in
 
 461                       (select id from delivery_order_items where delivery_order_id = ?)';
 
 462   $query .= sprintf ' AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_dois if (scalar @processed_dois);
 
 463   @values = (conv_i($form->{id}), map { conv_i($_) } @processed_dois);
 
 464   my @orphaned_dois_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
 
 465   if (scalar @orphaned_dois_ids) {
 
 466     # clean up delivery_order_items_stock
 
 467     $query  = sprintf 'DELETE FROM delivery_order_items_stock WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_dois_ids;
 
 468     do_query($form, $dbh, $query, @orphaned_dois_ids);
 
 470   # 2. search for orphaned doi
 
 471   $query  = sprintf 'SELECT id FROM delivery_order_items WHERE delivery_order_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_doi;
 
 472   @values = (conv_i($form->{id}), map { conv_i($_) } @processed_doi);
 
 473   my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
 
 474   if (scalar @orphaned_ids) {
 
 475     # clean up delivery_order_items
 
 476     $query  = sprintf 'DELETE FROM delivery_order_items WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
 
 477     do_query($form, $dbh, $query, @orphaned_ids);
 
 480   $h_item_stock->finish();
 
 483   # reqdate is last items reqdate (?: old behaviour) if not already set
 
 484   $form->{reqdate} ||= $items_reqdate;
 
 487     qq|UPDATE delivery_orders SET
 
 488          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
 
 489          customer_id = ?, reqdate = ?,
 
 490          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
 
 491          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
 
 492          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
 
 493          is_sales = ?, taxzone_id = ?, taxincluded = ?, payment_id = ?, currency_id = (SELECT id FROM currencies WHERE name = ?),
 
 497   @values = ($form->{donumber}, $form->{ordnumber},
 
 498              $form->{cusordnumber}, conv_date($form->{transdate}),
 
 499              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
 
 500              conv_date($form->{reqdate}), $form->{shippingpoint}, $form->{shipvia},
 
 501              $restricter->process($form->{notes}), $form->{intnotes},
 
 502              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
 
 503              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
 
 504              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
 
 505              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
 
 506              $form->{transaction_description},
 
 507              $form->{type} =~ /^sales/ ? 't' : 'f',
 
 508              conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{payment_id}), $form->{currency},
 
 509              conv_i($form->{delivery_term_id}),
 
 510              conv_i($form->{id}));
 
 511   do_query($form, $dbh, $query, @values);
 
 513   $form->new_lastmtime('delivery_orders');
 
 515   $form->{name} = $form->{ $form->{vc} };
 
 516   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
 
 519   if (!$form->{shipto_id}) {
 
 520     $form->add_shipto($dbh, $form->{id}, "DO");
 
 523   # save printed, emailed, queued
 
 524   $form->save_status($dbh);
 
 526   # Link this delivery order to the quotations it was created from.
 
 527   RecordLinks->create_links('dbh'        => $dbh,
 
 529                             'from_table' => 'oe',
 
 530                             'from_ids'   => $form->{convert_from_oe_ids},
 
 531                             'to_table'   => 'delivery_orders',
 
 532                             'to_id'      => $form->{id},
 
 534   delete $form->{convert_from_oe_ids};
 
 536   $self->mark_orders_if_delivered('do_id' => $form->{id},
 
 537                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
 
 540   my $rc = $dbh->commit();
 
 542   $form->{saved_donumber} = $form->{donumber};
 
 543   $form->{saved_ordnumber} = $form->{ordnumber};
 
 544   $form->{saved_cusordnumber} = $form->{cusordnumber};
 
 546   Common::webdav_folder($form);
 
 548   $main::lxdebug->leave_sub();
 
 553 sub mark_orders_if_delivered {
 
 554   $main::lxdebug->enter_sub();
 
 559   Common::check_params(\%params, qw(do_id type));
 
 561   my $myconfig = \%main::myconfig;
 
 562   my $form     = $main::form;
 
 564   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 566   my %ship = $self->get_shipped_qty('dbh' => $dbh, 'do_id' => $form->{id}, 'delivered' => 1);
 
 568   foreach my $oe_id (keys %ship) {
 
 569       do_query($form, $dbh,"UPDATE oe SET delivered = ".($ship{$oe_id}->{delivered}?"TRUE":"FALSE")." WHERE id = ?", $oe_id);
 
 571   $dbh->commit() if (!$params{dbh});
 
 573   $main::lxdebug->leave_sub();
 
 577   $main::lxdebug->enter_sub();
 
 582   Common::check_params(\%params, qw(ids));
 
 584   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
 
 585     $main::lxdebug->leave_sub();
 
 589   my $myconfig = \%main::myconfig;
 
 590   my $form     = $main::form;
 
 592   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 594   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
 
 596   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
 
 598   $dbh->commit() unless ($params{dbh});
 
 599   $form->new_lastmtime('delivery_orders');
 
 601   $main::lxdebug->leave_sub();
 
 605   $main::lxdebug->enter_sub();
 
 609   my $myconfig = \%main::myconfig;
 
 610   my $form     = $main::form;
 
 611   my $spool    = $::lx_office_conf{paths}->{spool};
 
 613   my $rc = SL::DB::Order->new->db->with_transaction(sub {
 
 614     my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $form->{id} ]) };
 
 616     SL::DB::DeliveryOrder->new(id => $form->{id})->delete;
 
 618     my $spool = $::lx_office_conf{paths}->{spool};
 
 619     unlink map { "$spool/$_" } @spoolfiles if $spool;
 
 624   $main::lxdebug->leave_sub();
 
 630   $main::lxdebug->enter_sub();
 
 635   my $myconfig = \%main::myconfig;
 
 636   my $form     = $main::form;
 
 638   # connect to database
 
 639   my $dbh = $form->get_standard_dbh($myconfig);
 
 641   my ($query, $query_add, @values, $sth, $ref);
 
 643   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 646   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
 
 648   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
 
 650   if ($mode eq 'default') {
 
 651     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate|);
 
 652     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 654     # if reqdate is not set from oe-workflow, set it to transdate (which is current date)
 
 655     $form->{reqdate} ||= $form->{transdate};
 
 658     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
 
 660     $main::lxdebug->leave_sub();
 
 665   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
 
 666   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
 
 668   # retrieve order for single id
 
 669   # NOTE: this query is intended to fetch all information only ONCE.
 
 670   # so if any of these infos is important (or even different) for any item,
 
 671   # it will be killed out and then has to be fetched from the item scope query further down
 
 673     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
 
 674          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
 
 675          e.name AS employee, dord.employee_id, dord.salesman_id,
 
 676          dord.${vc}_id, cv.name AS ${vc},
 
 677          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
 
 678          d.description AS department, dord.language_id,
 
 680          dord.itime, dord.mtime,
 
 681          dord.globalproject_id, dord.delivered, dord.transaction_description,
 
 682          dord.taxzone_id, dord.taxincluded, dord.payment_id, (SELECT cu.name FROM currencies cu WHERE cu.id=dord.currency_id) AS currency,
 
 683          dord.delivery_term_id, dord.itime::DATE AS insertdate
 
 684        FROM delivery_orders dord
 
 685        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
 
 686        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
 687        LEFT JOIN department d ON (dord.department_id = d.id)
 
 688        WHERE dord.id IN ($do_ids_placeholders)|;
 
 689   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
 
 691   delete $form->{"${vc}_id"};
 
 693   $form->{ordnumber_array} = ' ';
 
 694   $form->{cusordnumber_array} = ' ';
 
 695   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 696     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
 
 698       $main::lxdebug->leave_sub();
 
 703     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
 
 704     $form->{donumber_array} .= $form->{donumber} . ' ';
 
 705     $pos = index($form->{ordnumber_array},' ' . $form->{ordnumber} . ' ');
 
 707       $form->{ordnumber_array} .= $form->{ordnumber} . ' ';
 
 709     $pos = index($form->{cusordnumber_array},' ' . $form->{cusordnumber} . ' ');
 
 711       $form->{cusordnumber_array} .= $form->{cusordnumber} . ' ';
 
 715   $form->{mtime}   ||= $form->{itime};
 
 716   $form->{lastmtime} = $form->{mtime};
 
 717   $form->{donumber_array} =~ s/\s*$//g;
 
 718   $form->{ordnumber_array} =~ s/ //;
 
 719   $form->{ordnumber_array} =~ s/\s*$//g;
 
 720   $form->{cusordnumber_array} =~ s/ //;
 
 721   $form->{cusordnumber_array} =~ s/\s*$//g;
 
 723   $form->{saved_donumber} = $form->{donumber};
 
 724   $form->{saved_ordnumber} = $form->{ordnumber};
 
 725   $form->{saved_cusordnumber} = $form->{cusordnumber};
 
 727   # if not given, fill transdate with current_date
 
 728   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
 
 730   if ($mode eq 'single') {
 
 731     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
 
 732     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
 
 734     $ref   = $sth->fetchrow_hashref("NAME_lc");
 
 736     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 739     if ($form->{shipto_id}) {
 
 740       my $cvars = CVar->get_custom_variables(
 
 743         trans_id => $form->{shipto_id},
 
 745       $form->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
 
 748     # get printed, emailed and queued
 
 749     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
 
 750     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 752     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 753       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
 754       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
 755       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
 
 758     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
 764   # retrieve individual items
 
 765   # this query looks up all information about the items
 
 766   # stuff different from the whole will not be overwritten, but saved with a suffix.
 
 768     qq|SELECT doi.id AS delivery_order_items_id,
 
 769          p.partnumber, p.assembly, p.listprice, doi.description, doi.qty,
 
 770          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.notes AS partnotes,
 
 771          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
 
 772          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
 
 773          doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
 
 774          doi.active_price_source, doi.active_discount_source,
 
 775          pr.projectnumber, dord.transdate AS dord_transdate, dord.donumber,
 
 777        FROM delivery_order_items doi
 
 778        JOIN parts p ON (doi.parts_id = p.id)
 
 779        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
 
 780        LEFT JOIN project pr ON (doi.project_id = pr.id)
 
 781        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 782        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
 
 783        ORDER BY doi.delivery_order_id, doi.position|;
 
 785   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
 787   # Retrieve custom variables.
 
 788   foreach my $doi (@{ $form->{form_details} }) {
 
 789     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 791                                            sub_module => 'delivery_order_items',
 
 792                                            trans_id   => $doi->{delivery_order_items_id},
 
 794     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
 
 797   if ($mode eq 'single') {
 
 798     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 801       qq|SELECT id as delivery_order_items_stock_id, qty, unit, bin_id,
 
 802                 warehouse_id, chargenumber, bestbefore
 
 803          FROM delivery_order_items_stock
 
 804          WHERE delivery_order_item_id = ?|;
 
 805     my $sth = prepare_query($form, $dbh, $query);
 
 807     foreach my $doi (@{ $form->{form_details} }) {
 
 808       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
 
 810       while (my $ref = $sth->fetchrow_hashref()) {
 
 811         push @{ $requests }, $ref;
 
 814       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
 
 820   Common::webdav_folder($form);
 
 822   $main::lxdebug->leave_sub();
 
 828   $main::lxdebug->enter_sub();
 
 830   my ($self, $myconfig, $form) = @_;
 
 832   # connect to database
 
 833   my $dbh = $form->get_standard_dbh($myconfig);
 
 842   my $subtotal_header = 0;
 
 848   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
 
 850   # sort items by partsgroup
 
 851   for $i (1 .. $form->{rowcount}) {
 
 853     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
 854       $partsgroup = $form->{"partsgroup_$i"};
 
 856     push @partsgroup, [$i, $partsgroup];
 
 857     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
 
 863     $projects = SL::DB::Manager::Project->get_all(query => [ id => \@project_ids ]);
 
 864     %projects_by_id = map { $_->id => $_ } @$projects;
 
 867   if ($projects_by_id{$form->{"globalproject_id"}}) {
 
 868     $form->{globalprojectnumber} = $projects_by_id{$form->{"globalproject_id"}}->projectnumber;
 
 869     $form->{globalprojectdescription} = $projects_by_id{$form->{"globalproject_id"}}->description;
 
 871     for (@{ $projects_by_id{$form->{"globalproject_id"}}->cvars_by_config }) {
 
 872       $form->{"project_cvar_" . $_->config->name} = $_->value_as_text;
 
 876   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
 
 878                     JOIN parts p ON (a.parts_id = p.id)
 
 879                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 882   my $h_pg     = prepare_query($form, $dbh, $q_pg);
 
 884   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
 
 885                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
 
 886   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
 
 888   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 892   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 893   my $project_cvar_configs = CVar->get_configs(module => 'Projects');
 
 895   # get some values of parts from db on store them in extra array,
 
 896   # so that they can be sorted in later
 
 897   my %prepared_template_arrays = IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
 
 898   my @prepared_arrays          = keys %prepared_template_arrays;
 
 900   $form->{TEMPLATE_ARRAYS} = { };
 
 903     qw(runningnumber number description longdescription qty qty_nofmt unit
 
 904        partnotes serialnumber reqdate projectnumber projectdescription
 
 905        weight weight_nofmt lineweight lineweight_nofmt
 
 906        si_runningnumber si_number si_description
 
 907        si_warehouse si_bin si_chargenumber si_bestbefore
 
 908        si_qty si_qty_nofmt si_unit);
 
 910   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays, @prepared_arrays);
 
 912   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 913   push @arrays, map { "project_cvar_$_->{name}" } @{ $project_cvar_configs };
 
 915   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 916   my %price_factors = map { $_->{id} => $_->{factor} *1 } @{ $form->{ALL_PRICE_FACTORS} };
 
 920   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
 923     next if (!$form->{"id_$i"});
 
 925     if ($item->[1] ne $sameitem) {
 
 926       push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'partsgroup');
 
 927       push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, qq|$item->[1]|);
 
 928       $sameitem = $item->[1];
 
 930       map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
 
 931       map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
 
 935     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 937     # add number, description and qty to $form->{number}, ....
 
 938     if ($form->{"subtotal_$i"} && !$subtotal_header) {
 
 939       $subtotal_header = $i;
 
 940       $position = int($position);
 
 943     } elsif ($subtotal_header) {
 
 945       $position = int($position);
 
 946       $position = $position.".".$subposition;
 
 948       $position = int($position);
 
 954     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
 
 955     my $project = $projects_by_id{$form->{"project_id_$i"}} || SL::DB::Project->new;
 
 957     push(@{ $form->{TEMPLATE_ARRAYS}{$_} },              $prepared_template_arrays{$_}[$i - 1]) for @prepared_arrays;
 
 959     push @{ $form->{TEMPLATE_ARRAYS}{entry_type} },      'normal';
 
 960     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
 
 961     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
 
 962     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
 
 963     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
 
 964     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
 
 965     push @{ $form->{TEMPLATE_ARRAYS}{qty_nofmt} },       $form->{"qty_$i"};
 
 966     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
 
 967     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
 
 968     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
 
 969     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
 
 970     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $project->projectnumber;
 
 971     push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} }, $project->description;
 
 973     if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
 
 974       $subtotal_header     = 0;
 
 977     my $lineweight = $form->{"qty_$i"} * $form->{"weight_$i"};
 
 978     $totalweight += $lineweight;
 
 979     push @{ $form->{TEMPLATE_ARRAYS}->{weight} },            $form->format_amount($myconfig, $form->{"weight_$i"}, 3);
 
 980     push @{ $form->{TEMPLATE_ARRAYS}->{weight_nofmt} },      $form->{"weight_$i"};
 
 981     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight} },        $form->format_amount($myconfig, $lineweight, 3);
 
 982     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight_nofmt} },  $lineweight;
 
 984     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 986     foreach my $si (@{ $stock_info }) {
 
 989       do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
 
 990       my $bin_wh = $h_bin_wh->fetchrow_hashref();
 
 992       push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$si_position-1] }, $num_si;
 
 993       push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$si_position-1] },        $form->{"partnumber_$i"};
 
 994       push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$si_position-1] },   $form->{"description_$i"};
 
 995       push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$si_position-1] },     $bin_wh->{warehouse};
 
 996       push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$si_position-1] },           $bin_wh->{bin};
 
 997       push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$si_position-1] },  $si->{chargenumber};
 
 998       push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$si_position-1] },    $si->{bestbefore};
 
 999       push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$si_position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
 
1000       push @{ $form->{TEMPLATE_ARRAYS}{si_qty_nofmt}[$si_position-1] },     $si->{qty} * 1;
 
1001       push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$si_position-1] },          $si->{unit};
 
1004     if ($form->{"assembly_$i"}) {
 
1007       # get parts and push them onto the stack
 
1009       if ($form->{groupitems}) {
 
1011           qq|ORDER BY pg.partsgroup, a.oid|;
 
1013         $sortorder = qq|ORDER BY a.oid|;
 
1016       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
 
1018       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
 
1019         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
1020           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
 
1021           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
 
1022           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
1023           push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'assembly-item-partsgroup');
 
1024           push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
 
1028         push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  },  'assembly-item');
 
1029         push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
 
1030         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
 
1031         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
 
1036     CVar->get_non_editable_ic_cvars(form               => $form,
 
1039                                     sub_module         => 'delivery_order_items',
 
1040                                     may_converted_from => ['orderitems', 'delivery_order_items']);
 
1042     push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
 
1043       CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
 
1044         for @{ $ic_cvar_configs };
 
1046     push @{ $form->{TEMPLATE_ARRAYS}->{"project_cvar_" . $_->config->name} }, $_->value_as_text for @{ $project->cvars_by_config };
 
1049   $form->{totalweight}       = $form->format_amount($myconfig, $totalweight, 3);
 
1050   $form->{totalweight_nofmt} = $totalweight;
 
1051   my $defaults = AM->get_defaults();
 
1052   $form->{weightunit}        = $defaults->{weightunit};
 
1055   $h_bin_wh->finish();
 
1057   $form->{delivery_term} = SL::DB::Manager::DeliveryTerm->find_by(id => $form->{delivery_term_id} || undef);
 
1058   if ($form->{delivery_term} && $form->{language_id}) {
 
1059     $form->{delivery_term}->description_long(        $form->{delivery_term}->translated_attribute('description_long',         $form->{language_id}));
 
1060     $form->{delivery_term}->description_long_invoice($form->{delivery_term}->translated_attribute('description_long_invoice', $form->{language_id}));
 
1063   $form->{department}    = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
 
1065   $form->{username} = $myconfig->{name};
 
1067   $main::lxdebug->leave_sub();
 
1070 sub project_description {
 
1071   $main::lxdebug->enter_sub();
 
1073   my ($self, $dbh, $id) = @_;
 
1075   my $form     =  $main::form;
 
1077   my $query = qq|SELECT description FROM project WHERE id = ?|;
 
1078   my ($value) = selectrow_query($form, $dbh, $query, $id);
 
1080   $main::lxdebug->leave_sub();
 
1085 sub unpack_stock_information {
 
1086   $main::lxdebug->enter_sub();
 
1091   Common::check_params_x(\%params, qw(packed));
 
1095   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
 
1097   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
 
1099   foreach my $entry (@{ $unpacked }) {
 
1100     next if ('HASH' eq ref $entry);
 
1105   $main::lxdebug->leave_sub();
 
1110 sub get_item_availability {
 
1111   $::lxdebug->enter_sub;
 
1116   Common::check_params(\%params, qw(parts_id));
 
1118   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
 
1121     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
 
1122          w.description AS warehousedescription,
 
1123          b.description AS bindescription
 
1125        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
 
1126        LEFT JOIN bin b       ON (i.bin_id       = b.id)
 
1127        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
 
1128        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
 
1130        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
 
1132   my $contents = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, @parts_ids);
 
1134   $::lxdebug->leave_sub;
 
1136   return @{ $contents };
 
1140 sub check_stock_availability {
 
1141   $main::lxdebug->enter_sub();
 
1146   Common::check_params(\%params, qw(requests parts_id));
 
1148   my $myconfig    = \%main::myconfig;
 
1149   my $form        =  $main::form;
 
1151   my $dbh         = $form->get_standard_dbh($myconfig);
 
1153   my $units       = AM->retrieve_units($myconfig, $form);
 
1155   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
 
1156   my $unit_factor = $units->{$partunit}->{factor} || 1;
 
1158   my @contents    = $self->get_item_availability(%params);
 
1162   foreach my $sinfo (@{ $params{requests} }) {
 
1165     foreach my $row (@contents) {
 
1166       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
 
1167                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
 
1168                ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
 
1169                ($row->{bestbefore}   ne $sinfo->{bestbefore}));
 
1173       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
 
1175       if ($base_qty > $row->{qty}) {
 
1176         $sinfo->{error} = 1;
 
1177         push @errors, $sinfo;
 
1183     push @errors, $sinfo if (!$found);
 
1186   $main::lxdebug->leave_sub();
 
1191 sub transfer_in_out {
 
1192   $main::lxdebug->enter_sub();
 
1197   Common::check_params(\%params, qw(direction requests));
 
1199   if (!@{ $params{requests} }) {
 
1200     $main::lxdebug->leave_sub();
 
1204   my $myconfig = \%main::myconfig;
 
1205   my $form     = $main::form;
 
1207   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
 
1211   foreach my $request (@{ $params{requests} }) {
 
1213       'parts_id'                      => $request->{parts_id},
 
1214       "${prefix}_warehouse_id"        => $request->{warehouse_id},
 
1215       "${prefix}_bin_id"              => $request->{bin_id},
 
1216       'chargenumber'                  => $request->{chargenumber},
 
1217       'bestbefore'                    => $request->{bestbefore},
 
1218       'qty'                           => $request->{qty},
 
1219       'unit'                          => $request->{unit},
 
1220       'oe_id'                         => $form->{id},
 
1221       'shippingdate'                  => 'current_date',
 
1222       'transfer_type'                 => $params{direction} eq 'in' ? 'stock' : 'shipped',
 
1223       'project_id'                    => $request->{project_id},
 
1224       'delivery_order_items_stock_id' => $request->{delivery_order_items_stock_id},
 
1225       'comment'                       => $request->{comment},
 
1229   WH->transfer(@transfers);
 
1231   $main::lxdebug->leave_sub();
 
1235 sub get_shipped_qty {
 
1236   $main::lxdebug->enter_sub();
 
1239   # $params{oe_id} : Alle Lieferscheine zu diesem Auftrag durchsuchen und pro Auftragsposition die Mengen zurückgeben
 
1240   #                  Wird zur Darstellung der gelieferten Mengen im Auftrag benötigt
 
1241   # $params{do_id} : Alle Aufträge zu diesem Lieferschein durchsuchen und pro Lieferscheinposition die Mengen zurückgeben
 
1242   #                  Wird für LaTeX benötigt um im Lieferschein pro Position die Mengen auszugeben
 
1243   # $params{delivered}: Alle Aufträge zum Lieferschein $params{do_id} prüfen ob sie vollständiger ausgeliefert sind
 
1244   #                  Wird für das Setzen des 'delivered' Flag in der Datenbank beim "save" des Lieferscheins benötigt
 
1249   # Eigentlich unkritisch: wenn keine der Parameter gesetzt ist kommt ein leerer Hash zurück
 
1250   croak ("Need at least one parameter oe_id or do_id") unless $params{oe_id} || $params{do_id};
 
1252   my $myconfig = \%main::myconfig;
 
1253   my $form     = $main::form;
 
1254   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1259   if ($params{oe_id} ) {
 
1260     push @oe_ids,  $params{oe_id};
 
1261   } elsif ($params{do_id}) {
 
1262     my @links  = RecordLinks->get_links(  'dbh'        => $dbh,
 
1263                                           'from_table' => 'oe',
 
1264                                           'to_table'   => 'delivery_orders',
 
1265                                           'to_id'      => $params{do_id});
 
1267     @oe_ids  = map { $_->{from_id} } @links;
 
1270   if (scalar (@oe_ids) > 0 ) {
 
1271     my $all_units = AM->retrieve_all_units();
 
1272     my $placeholders = join(', ', ('?') x scalar @oe_ids);
 
1273     my $query = qq|SELECT oi.id, oi.position, oi.parts_id, oi.qty, oi.unit, oi.trans_id,
 
1274                         p.unit AS partunit FROM orderitems oi
 
1275                         LEFT JOIN parts p ON (oi.parts_id = p.id)
 
1276                         WHERE trans_id IN (${placeholders})
 
1277                         ORDER BY position ASC|;
 
1279     my $orderitems = selectall_hashref_query($form, $dbh, $query, @oe_ids);
 
1280     foreach my $oe_entry (@{ $orderitems }) {
 
1281       $oe_entry->{qty} *= AM->convert_unit($oe_entry->{unit}, $oe_entry->{partunit}, $all_units);
 
1282       $oe_entry->{qty_notdelivered} = $oe_entry->{qty};
 
1284       # Bei oe Modus auf jeden Fall einen Record anlegen
 
1285       if ( $params{oe_id} ) {
 
1286         $ship{$oe_entry->{position}} = {
 
1287              'qty_ordered'      => $oe_entry->{qty} ,
 
1288              'qty_notdelivered' => $oe_entry->{qty}
 
1293     my @dolinks  = RecordLinks->get_links('dbh'       => $dbh,
 
1294                                        'from_table' => 'oe',
 
1295                                        'to_table'   => 'delivery_orders',
 
1296                                        'from_id'    => @oe_ids);
 
1298     my @do_ids = map { $_->{to_id} }  @dolinks ;
 
1299     if (scalar (@do_ids) == 0) {
 
1300       $main::lxdebug->leave_sub();
 
1304     my %oeitems_by_id       = map { $_->{id} => $_ } @{ $orderitems };
 
1307     $placeholders = join(', ', ('?') x scalar @do_ids);
 
1308     $query  = qq|SELECT doi.parts_id, doi.id, doi.qty, doi.unit, doi.position,
 
1309                doi.delivery_order_id, COALESCE(rlitem.from_id,0) as from_id,
 
1311                FROM delivery_order_items doi
 
1312                LEFT JOIN parts p ON (doi.parts_id = p.id)
 
1313                LEFT JOIN record_links rlitem
 
1314                ON (rlitem.to_id = doi.id AND rlitem.to_table='delivery_order_items')
 
1315                WHERE doi.delivery_order_id IN (${placeholders})|;
 
1317     my $deliveryorderitems = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
1319     # erst mal qty der links bearbeiten
 
1320     foreach my $do_entry (@{ $deliveryorderitems }) {
 
1321       $do_entry->{qty} *= AM->convert_unit($do_entry->{unit}, $do_entry->{partunit}, $all_units);
 
1322       if ($do_entry->{from_id} > 0 ) {
 
1323         # record link zwischen items vorhanden, kann auch von anderem Auftrag sein
 
1324         my $oe_entry = $oeitems_by_id{$do_entry->{from_id}};
 
1326           $oe_entry->{qty_notdelivered} -= $do_entry->{qty};
 
1327           # derzeit nur ein link pro do_item
 
1328           $do_entry->{oe_entry} = $oe_entry;
 
1331         $main::lxdebug->message(LXDebug->DEBUG2(),"no entry for=".$do_entry->{id}." part=".$do_entry->{parts_id});
 
1334     # nun den rest ohne links bearbeiten
 
1335     foreach my $do_entry (@{ $deliveryorderitems }) {
 
1336       next if $do_entry->{from_id} > 0;
 
1337       next if $do_entry->{qty} == 0;
 
1339       foreach my $oe_entry (@{ $orderitems }) {
 
1340         next if $oe_entry->{qty_notdelivered} == 0;
 
1341         if ( $do_entry->{parts_id} == $oe_entry->{parts_id} ) {
 
1342           # zu viele geliefert auf andere position ?
 
1343           if ( $oe_entry->{qty_notdelivered} < 0 ) {
 
1344             $do_entry->{qty} += - $oe_entry->{qty_notdelivered};
 
1345             $oe_entry->{qty_notdelivered} = 0;
 
1347             if ( $do_entry->{qty} < $oe_entry->{qty_notdelivered} ) {
 
1348               $oe_entry->{qty_notdelivered} -= $do_entry->{qty};
 
1349               $do_entry->{qty} = 0;
 
1351               $do_entry->{qty} -= $oe_entry->{qty_notdelivered};
 
1352               $oe_entry->{qty_notdelivered} = 0;
 
1354             # derzeit nur ein link pro do_item
 
1355             $do_entry->{oe_entry} = $oe_entry if !$do_entry->{oe_entry};
 
1358         last if $do_entry->{qty} <= 0;
 
1361     if ( $params{oe_id} ) {
 
1362       $ship{$_->{position}}->{qty_notdelivered} = $_->{qty_notdelivered} for @{ $orderitems };
 
1364     elsif ($params{do_id} && $params{delivered}) {
 
1365       foreach my $oe_entry (@{ $orderitems }) {
 
1366         if ( !$ship{$oe_entry->{trans_id}} ) {
 
1367             $ship{$oe_entry->{trans_id}} = { 'delivered' => 1 };
 
1369         $ship{$oe_entry->{trans_id}}->{delivered} = 0 if $oe_entry->{qty_notdelivered} > 0;
 
1372     elsif ($params{do_id}) {
 
1373       foreach my $do_entry (@{ $deliveryorderitems }) {
 
1374         next if $params{do_id} != $do_entry->{delivery_order_id};
 
1375         my $position = $do_entry->{position};
 
1376         if ( $position > 0 && $do_entry->{oe_entry}) {
 
1377           if ( !$ship{$position} ) {
 
1378             $ship{$position} = {
 
1379               'qty_ordered'      => $do_entry->{oe_entry}->{qty} ,
 
1380               'qty_notdelivered' => $do_entry->{oe_entry}->{qty_notdelivered}
 
1383             $ship{$position}->{qty_ordered}      += $do_entry->{oe_entry}->{qty};
 
1384             $ship{$position}->{qty_notdelivered} += $do_entry->{oe_entry}->{qty_notdelivered};
 
1390   $main::lxdebug->leave_sub();
 
1394 sub is_marked_as_delivered {
 
1395   $main::lxdebug->enter_sub();
 
1400   Common::check_params(\%params, qw(id));
 
1402   my $myconfig    = \%main::myconfig;
 
1403   my $form        = $main::form;
 
1405   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1407   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
 
1409   $main::lxdebug->leave_sub();
 
1411   return $delivered ? 1 : 0;