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});
 
 184     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
 
 187   my %allowed_sort_columns = (
 
 188     "transdate"               => "dord.transdate",
 
 189     "reqdate"                 => "dord.reqdate",
 
 191     "donumber"                => "dord.donumber",
 
 192     "ordnumber"               => "dord.ordnumber",
 
 194     "employee"                => "e.name",
 
 195     "salesman"                => "sm.name",
 
 196     "shipvia"                 => "dord.shipvia",
 
 197     "transaction_description" => "dord.transaction_description",
 
 198     "department"              => "lower(dep.description)",
 
 199     "insertdate"              => "dord.itime",
 
 202   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 203   my $sortorder = "dord.id";
 
 204   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
 
 205     $sortorder = $allowed_sort_columns{$form->{sort}};
 
 208   $query .= qq| ORDER by | . $sortorder . " $sortdir";
 
 210   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
 
 212   if (scalar @{ $form->{DO} }) {
 
 216          WHERE NOT COALESCE(quotation, FALSE)
 
 218            AND (COALESCE(${vc}_id, 0) != 0)|;
 
 220     my $sth = prepare_query($form, $dbh, $query);
 
 222     foreach my $dord (@{ $form->{DO} }) {
 
 223       next unless ($dord->{ordnumber});
 
 224       do_statement($form, $sth, $query, $dord->{ordnumber});
 
 225       ($dord->{oe_id}) = $sth->fetchrow_array();
 
 231   $main::lxdebug->leave_sub();
 
 235   $main::lxdebug->enter_sub();
 
 239   my $myconfig = \%main::myconfig;
 
 240   my $form     = $main::form;
 
 242   # connect to database, turn off autocommit
 
 243   my $dbh = $form->get_standard_dbh($myconfig);
 
 244   my $restricter = SL::HTML::Restrict->create;
 
 246   my ($query, @values, $sth, $null);
 
 248   my $all_units = AM->retrieve_units($myconfig, $form);
 
 249   $form->{all_units} = $all_units;
 
 251   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 254   my $trans_number     = SL::TransNumber->new(type => $form->{type}, dbh => $dbh, number => $form->{donumber}, id => $form->{id});
 
 255   $form->{donumber}  ||= $trans_number->create_unique;
 
 256   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
 
 257   $form->get_employee($dbh) unless ($form->{employee_id});
 
 259   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
 
 261   my (@processed_doi, @processed_dois);
 
 265     # only delete shipto complete
 
 266     $query = qq|DELETE FROM custom_variables
 
 267                 WHERE (config_id IN (SELECT id        FROM custom_variable_configs WHERE (module = 'ShipTo')))
 
 268                   AND (trans_id  IN (SELECT shipto_id FROM shipto                  WHERE (module = 'DO') AND (trans_id = ?)))|;
 
 269     do_query($form, $dbh, $query, $form->{id});
 
 271     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
 
 272     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 276     $query = qq|SELECT nextval('id')|;
 
 277     ($form->{id}) = selectrow_query($form, $dbh, $query);
 
 279     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id, currency_id, taxzone_id) VALUES (?, '', ?, (SELECT currency_id FROM defaults LIMIT 1), ?)|;
 
 280     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}), $form->{taxzone_id});
 
 286   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 287   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 290   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
 
 291   my @part_ids    = keys %part_id_map;
 
 295     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
 
 296     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
 
 299     UPDATE delivery_order_items SET
 
 300        delivery_order_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
 
 301        sellprice = ?, discount = ?, unit = ?, reqdate = ?, project_id = ?, serialnumber = ?,
 
 302        lastcost = ? , price_factor_id = ?, price_factor = (SELECT factor FROM price_factors where id = ?),
 
 303        marge_price_factor = ?, pricegroup_id = ?, active_price_source = ?, active_discount_source = ?
 
 306   my $h_item = prepare_query($form, $dbh, $q_item);
 
 308   my $q_item_stock = <<SQL;
 
 309     UPDATE delivery_order_items_stock SET
 
 310       delivery_order_item_id = ?, qty = ?,  unit = ?,  warehouse_id = ?,
 
 311       bin_id = ?, chargenumber = ?, bestbefore = ?
 
 314   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
 
 316   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 318   for my $i (1 .. $form->{rowcount}) {
 
 319     next if (!$form->{"id_$i"});
 
 321     CVar->get_non_editable_ic_cvars(form               => $form,
 
 324                                     sub_module         => 'delivery_order_items',
 
 325                                     may_converted_from => ['orderitems', 'delivery_order_items']);
 
 329     if (!$form->{"delivery_order_items_id_$i"}) {
 
 330       # there is no persistent id, therefore create one with all necessary constraints
 
 331       my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
 
 332       my $h_item_id = prepare_query($form, $dbh, $q_item_id);
 
 333       do_statement($form, $h_item_id, $q_item_id);
 
 334       $form->{"delivery_order_items_id_$i"}  = $h_item_id->fetchrow_array();
 
 335       $query = qq|INSERT INTO delivery_order_items (id, delivery_order_id, position, parts_id) VALUES (?, ?, ?, ?)|;
 
 336       do_query($form, $dbh, $query, conv_i($form->{"delivery_order_items_id_$i"}),
 
 337                 conv_i($form->{"id"}), conv_i($position), conv_i($form->{"id_$i"}));
 
 338       $h_item_id->finish();
 
 341     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 343     my $item_unit = $part_unit_map{$form->{"id_$i"}};
 
 346     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
 
 347       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
 
 349     my $baseqty = $form->{"qty_$i"} * $basefactor;
 
 351     # set values to 0 if nothing entered
 
 352     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"});
 
 353     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 354     $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
 
 356     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
 
 357     my $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 359     $items_reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
 
 362     # Get pricegroup_id and save it. Unfortunately the interface
 
 363     # also uses ID "0" for signalling that none is selected, but "0"
 
 364     # must not be stored in the database. Therefore we cannot simply
 
 366     my $pricegroup_id = $form->{"pricegroup_id_$i"} * 1;
 
 367     $pricegroup_id    = undef if !$pricegroup_id;
 
 369     # save detail record in delivery_order_items table
 
 370     @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
 
 371                $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}),
 
 372                $form->{"qty_$i"}, $baseqty,
 
 373                $form->{"sellprice_$i"}, $form->{"discount_$i"} / 100,
 
 374                $form->{"unit_$i"}, conv_date($items_reqdate), conv_i($form->{"project_id_$i"}),
 
 375                $form->{"serialnumber_$i"},
 
 376                $form->{"lastcost_$i"},
 
 377                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
 
 378                conv_i($form->{"marge_price_factor_$i"}),
 
 380                $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
 
 381                conv_i($form->{"delivery_order_items_id_$i"}));
 
 382     do_statement($form, $h_item, $q_item, @values);
 
 383     push @processed_doi, $form->{"delivery_order_items_id_$i"}; # transaction safe?
 
 385     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 387     foreach my $sinfo (@{ $stock_info }) {
 
 388       # if we have stock_info, we have to check for persistents entries
 
 389       if (!$sinfo->{"delivery_order_items_stock_id"}) {
 
 390         my $q_item_stock_id = qq|SELECT nextval('id')|;
 
 391         my $h_item_stock_id = prepare_query($form, $dbh, $q_item_stock_id);
 
 392         do_statement($form, $h_item_stock_id, $q_item_stock_id);
 
 393         $sinfo->{"delivery_order_items_stock_id"} = $h_item_stock_id->fetchrow_array();
 
 394         $query = qq|INSERT INTO delivery_order_items_stock (id, delivery_order_item_id, qty, unit, warehouse_id, bin_id)
 
 395                     VALUES (?, ?, ?, ?, ?, ?)|;
 
 396         do_query($form, $dbh, $query, conv_i($sinfo->{"delivery_order_items_stock_id"}),
 
 397                   conv_i($form->{"delivery_order_items_id_$i"}), $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 398                   conv_i($sinfo->{bin_id}));
 
 399         $h_item_stock_id->finish();
 
 400         # write back the id to the form (important if only transfer was clicked (id fk for invoice)
 
 401         $form->{"stock_${in_out}_$i"} = YAML::Dump($stock_info);
 
 403       @values = ($form->{"delivery_order_items_id_$i"}, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
 
 404                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}),
 
 405                  conv_i($sinfo->{"delivery_order_items_stock_id"}));
 
 406       do_statement($form, $h_item_stock, $q_item_stock, @values);
 
 407       push @processed_dois, $sinfo->{"delivery_order_items_stock_id"};
 
 410     CVar->save_custom_variables(module       => 'IC',
 
 411                                 sub_module   => 'delivery_order_items',
 
 412                                 trans_id     => $form->{"delivery_order_items_id_$i"},
 
 413                                 configs      => $ic_cvar_configs,
 
 415                                 name_prefix  => 'ic_',
 
 416                                 name_postfix => "_$i",
 
 419     # link order items with doi, for future extension look at foreach IS.pm
 
 420     if (!$form->{saveasnew} && $form->{"converted_from_orderitems_id_$i"}) {
 
 421       RecordLinks->create_links('dbh'        => $dbh,
 
 423                                 'from_table' => 'orderitems',
 
 424                                 'from_ids'   => $form->{"converted_from_orderitems_id_$i"},
 
 425                                 'to_table'   => 'delivery_order_items',
 
 426                                 'to_id'      =>  $form->{"delivery_order_items_id_$i"},
 
 429     delete $form->{"converted_from_orderitems_id_$i"};
 
 432   # 1. search for orphaned dois; processed_dois may be empty (no transfer) TODO: be supersafe and alter same statement for doi and oi
 
 433   $query  = sprintf 'SELECT id FROM delivery_order_items_stock WHERE delivery_order_item_id in
 
 434                       (select id from delivery_order_items where delivery_order_id = ?)';
 
 435   $query .= sprintf ' AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_dois if (scalar @processed_dois);
 
 436   @values = (conv_i($form->{id}), map { conv_i($_) } @processed_dois);
 
 437   my @orphaned_dois_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
 
 438   if (scalar @orphaned_dois_ids) {
 
 439     # clean up delivery_order_items_stock
 
 440     $query  = sprintf 'DELETE FROM delivery_order_items_stock WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_dois_ids;
 
 441     do_query($form, $dbh, $query, @orphaned_dois_ids);
 
 443   # 2. search for orphaned doi
 
 444   $query  = sprintf 'SELECT id FROM delivery_order_items WHERE delivery_order_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_doi;
 
 445   @values = (conv_i($form->{id}), map { conv_i($_) } @processed_doi);
 
 446   my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
 
 447   if (scalar @orphaned_ids) {
 
 448     # clean up delivery_order_items
 
 449     $query  = sprintf 'DELETE FROM delivery_order_items WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
 
 450     do_query($form, $dbh, $query, @orphaned_ids);
 
 453   $h_item_stock->finish();
 
 456   # reqdate is last items reqdate (?: old behaviour) if not already set
 
 457   $form->{reqdate} ||= $items_reqdate;
 
 460     qq|UPDATE delivery_orders SET
 
 461          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
 
 462          customer_id = ?, reqdate = ?,
 
 463          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
 
 464          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
 
 465          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
 
 466          is_sales = ?, taxzone_id = ?, taxincluded = ?, payment_id = ?, currency_id = (SELECT id FROM currencies WHERE name = ?),
 
 470   @values = ($form->{donumber}, $form->{ordnumber},
 
 471              $form->{cusordnumber}, conv_date($form->{transdate}),
 
 472              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
 
 473              conv_date($form->{reqdate}), $form->{shippingpoint}, $form->{shipvia},
 
 474              $restricter->process($form->{notes}), $form->{intnotes},
 
 475              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
 
 476              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
 
 477              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
 
 478              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
 
 479              $form->{transaction_description},
 
 480              $form->{type} =~ /^sales/ ? 't' : 'f',
 
 481              conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{payment_id}), $form->{currency},
 
 482              conv_i($form->{delivery_term_id}),
 
 483              conv_i($form->{id}));
 
 484   do_query($form, $dbh, $query, @values);
 
 486   $form->new_lastmtime('delivery_orders');
 
 488   $form->{name} = $form->{ $form->{vc} };
 
 489   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
 
 492   if (!$form->{shipto_id}) {
 
 493     $form->add_shipto($dbh, $form->{id}, "DO");
 
 496   # save printed, emailed, queued
 
 497   $form->save_status($dbh);
 
 499   # Link this delivery order to the quotations it was created from.
 
 500   RecordLinks->create_links('dbh'        => $dbh,
 
 502                             'from_table' => 'oe',
 
 503                             'from_ids'   => $form->{convert_from_oe_ids},
 
 504                             'to_table'   => 'delivery_orders',
 
 505                             'to_id'      => $form->{id},
 
 507   delete $form->{convert_from_oe_ids};
 
 509   $self->mark_orders_if_delivered('do_id' => $form->{id},
 
 510                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
 
 513   my $rc = $dbh->commit();
 
 515   $form->{saved_donumber} = $form->{donumber};
 
 516   $form->{saved_ordnumber} = $form->{ordnumber};
 
 517   $form->{saved_cusordnumber} = $form->{cusordnumber};
 
 519   Common::webdav_folder($form);
 
 521   $main::lxdebug->leave_sub();
 
 526 sub mark_orders_if_delivered {
 
 527   $main::lxdebug->enter_sub();
 
 532   Common::check_params(\%params, qw(do_id type));
 
 534   my $myconfig = \%main::myconfig;
 
 535   my $form     = $main::form;
 
 537   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 539   my %ship = $self->get_shipped_qty('dbh' => $dbh, 'do_id' => $form->{id}, 'delivered' => 1);
 
 541   foreach my $oe_id (keys %ship) {
 
 542       do_query($form, $dbh,"UPDATE oe SET delivered = ".($ship{$oe_id}->{delivered}?"TRUE":"FALSE")." WHERE id = ?", $oe_id);
 
 544   $dbh->commit() if (!$params{dbh});
 
 546   $main::lxdebug->leave_sub();
 
 550   $main::lxdebug->enter_sub();
 
 555   Common::check_params(\%params, qw(ids));
 
 557   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
 
 558     $main::lxdebug->leave_sub();
 
 562   my $myconfig = \%main::myconfig;
 
 563   my $form     = $main::form;
 
 565   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 567   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
 
 569   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
 
 571   $dbh->commit() unless ($params{dbh});
 
 572   $form->new_lastmtime('delivery_orders');
 
 574   $main::lxdebug->leave_sub();
 
 578   $main::lxdebug->enter_sub();
 
 582   my $myconfig = \%main::myconfig;
 
 583   my $form     = $main::form;
 
 584   my $spool    = $::lx_office_conf{paths}->{spool};
 
 586   my $rc = SL::DB::Order->new->db->with_transaction(sub {
 
 587     my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $form->{id} ]) };
 
 589     SL::DB::DeliveryOrder->new(id => $form->{id})->delete;
 
 591     my $spool = $::lx_office_conf{paths}->{spool};
 
 592     unlink map { "$spool/$_" } @spoolfiles if $spool;
 
 597   $main::lxdebug->leave_sub();
 
 603   $main::lxdebug->enter_sub();
 
 608   my $myconfig = \%main::myconfig;
 
 609   my $form     = $main::form;
 
 611   # connect to database
 
 612   my $dbh = $form->get_standard_dbh($myconfig);
 
 614   my ($query, $query_add, @values, $sth, $ref);
 
 616   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 619   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
 
 621   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
 
 623   if ($mode eq 'default') {
 
 624     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate|);
 
 625     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 627     # if reqdate is not set from oe-workflow, set it to transdate (which is current date)
 
 628     $form->{reqdate} ||= $form->{transdate};
 
 631     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
 
 633     $main::lxdebug->leave_sub();
 
 638   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
 
 639   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
 
 641   # retrieve order for single id
 
 642   # NOTE: this query is intended to fetch all information only ONCE.
 
 643   # so if any of these infos is important (or even different) for any item,
 
 644   # it will be killed out and then has to be fetched from the item scope query further down
 
 646     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
 
 647          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
 
 648          e.name AS employee, dord.employee_id, dord.salesman_id,
 
 649          dord.${vc}_id, cv.name AS ${vc},
 
 650          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
 
 651          d.description AS department, dord.language_id,
 
 653          dord.itime, dord.mtime,
 
 654          dord.globalproject_id, dord.delivered, dord.transaction_description,
 
 655          dord.taxzone_id, dord.taxincluded, dord.payment_id, (SELECT cu.name FROM currencies cu WHERE cu.id=dord.currency_id) AS currency,
 
 656          dord.delivery_term_id, dord.itime::DATE AS insertdate
 
 657        FROM delivery_orders dord
 
 658        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
 
 659        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
 660        LEFT JOIN department d ON (dord.department_id = d.id)
 
 661        WHERE dord.id IN ($do_ids_placeholders)|;
 
 662   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
 
 664   delete $form->{"${vc}_id"};
 
 666   $form->{ordnumber_array} = ' ';
 
 667   $form->{cusordnumber_array} = ' ';
 
 668   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 669     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
 
 671       $main::lxdebug->leave_sub();
 
 676     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
 
 677     $form->{donumber_array} .= $form->{donumber} . ' ';
 
 678     $pos = index($form->{ordnumber_array},' ' . $form->{ordnumber} . ' ');
 
 680       $form->{ordnumber_array} .= $form->{ordnumber} . ' ';
 
 682     $pos = index($form->{cusordnumber_array},' ' . $form->{cusordnumber} . ' ');
 
 684       $form->{cusordnumber_array} .= $form->{cusordnumber} . ' ';
 
 688   $form->{mtime}   ||= $form->{itime};
 
 689   $form->{lastmtime} = $form->{mtime};
 
 690   $form->{donumber_array} =~ s/\s*$//g;
 
 691   $form->{ordnumber_array} =~ s/ //;
 
 692   $form->{ordnumber_array} =~ s/\s*$//g;
 
 693   $form->{cusordnumber_array} =~ s/ //;
 
 694   $form->{cusordnumber_array} =~ s/\s*$//g;
 
 696   $form->{saved_donumber} = $form->{donumber};
 
 697   $form->{saved_ordnumber} = $form->{ordnumber};
 
 698   $form->{saved_cusordnumber} = $form->{cusordnumber};
 
 700   # if not given, fill transdate with current_date
 
 701   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
 
 703   if ($mode eq 'single') {
 
 704     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
 
 705     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
 
 707     $ref   = $sth->fetchrow_hashref("NAME_lc");
 
 709     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 712     if ($form->{shipto_id}) {
 
 713       my $cvars = CVar->get_custom_variables(
 
 716         trans_id => $form->{shipto_id},
 
 718       $form->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
 
 721     # get printed, emailed and queued
 
 722     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
 
 723     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 725     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 726       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
 727       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
 728       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
 
 731     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
 737   # retrieve individual items
 
 738   # this query looks up all information about the items
 
 739   # stuff different from the whole will not be overwritten, but saved with a suffix.
 
 741     qq|SELECT doi.id AS delivery_order_items_id,
 
 742          p.partnumber, p.assembly, p.listprice, doi.description, doi.qty,
 
 743          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.notes AS partnotes,
 
 744          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
 
 745          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
 
 746          doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
 
 747          doi.active_price_source, doi.active_discount_source,
 
 748          pr.projectnumber, dord.transdate AS dord_transdate, dord.donumber,
 
 750        FROM delivery_order_items doi
 
 751        JOIN parts p ON (doi.parts_id = p.id)
 
 752        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
 
 753        LEFT JOIN project pr ON (doi.project_id = pr.id)
 
 754        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 755        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
 
 756        ORDER BY doi.delivery_order_id, doi.position|;
 
 758   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
 760   # Retrieve custom variables.
 
 761   foreach my $doi (@{ $form->{form_details} }) {
 
 762     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 764                                            sub_module => 'delivery_order_items',
 
 765                                            trans_id   => $doi->{delivery_order_items_id},
 
 767     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
 
 770   if ($mode eq 'single') {
 
 771     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 774       qq|SELECT id as delivery_order_items_stock_id, qty, unit, bin_id,
 
 775                 warehouse_id, chargenumber, bestbefore
 
 776          FROM delivery_order_items_stock
 
 777          WHERE delivery_order_item_id = ?|;
 
 778     my $sth = prepare_query($form, $dbh, $query);
 
 780     foreach my $doi (@{ $form->{form_details} }) {
 
 781       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
 
 783       while (my $ref = $sth->fetchrow_hashref()) {
 
 784         push @{ $requests }, $ref;
 
 787       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
 
 793   Common::webdav_folder($form);
 
 795   $main::lxdebug->leave_sub();
 
 801   $main::lxdebug->enter_sub();
 
 803   my ($self, $myconfig, $form) = @_;
 
 805   # connect to database
 
 806   my $dbh = $form->get_standard_dbh($myconfig);
 
 815   my $subtotal_header = 0;
 
 821   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
 
 823   # sort items by partsgroup
 
 824   for $i (1 .. $form->{rowcount}) {
 
 826     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
 827       $partsgroup = $form->{"partsgroup_$i"};
 
 829     push @partsgroup, [$i, $partsgroup];
 
 830     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
 
 836     $projects = SL::DB::Manager::Project->get_all(query => [ id => \@project_ids ]);
 
 837     %projects_by_id = map { $_->id => $_ } @$projects;
 
 840   if ($projects_by_id{$form->{"globalproject_id"}}) {
 
 841     $form->{globalprojectnumber} = $projects_by_id{$form->{"globalproject_id"}}->projectnumber;
 
 842     $form->{globalprojectdescription} = $projects_by_id{$form->{"globalproject_id"}}->description;
 
 844     for (@{ $projects_by_id{$form->{"globalproject_id"}}->cvars_by_config }) {
 
 845       $form->{"project_cvar_" . $_->config->name} = $_->value_as_text;
 
 849   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
 
 851                     JOIN parts p ON (a.parts_id = p.id)
 
 852                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 855   my $h_pg     = prepare_query($form, $dbh, $q_pg);
 
 857   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
 
 858                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
 
 859   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
 
 861   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 865   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 866   my $project_cvar_configs = CVar->get_configs(module => 'Projects');
 
 868   # get some values of parts from db on store them in extra array,
 
 869   # so that they can be sorted in later
 
 870   my %prepared_template_arrays = IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
 
 871   my @prepared_arrays          = keys %prepared_template_arrays;
 
 873   $form->{TEMPLATE_ARRAYS} = { };
 
 876     qw(runningnumber number description longdescription qty qty_nofmt unit
 
 877        partnotes serialnumber reqdate projectnumber projectdescription
 
 878        weight weight_nofmt lineweight lineweight_nofmt
 
 879        si_runningnumber si_number si_description
 
 880        si_warehouse si_bin si_chargenumber si_bestbefore
 
 881        si_qty si_qty_nofmt si_unit);
 
 883   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays, @prepared_arrays);
 
 885   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 886   push @arrays, map { "project_cvar_$_->{name}" } @{ $project_cvar_configs };
 
 888   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 889   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 893   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
 896     next if (!$form->{"id_$i"});
 
 898     if ($item->[1] ne $sameitem) {
 
 899       push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'partsgroup');
 
 900       push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, qq|$item->[1]|);
 
 901       $sameitem = $item->[1];
 
 903       map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
 
 904       map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
 
 908     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 910     # add number, description and qty to $form->{number}, ....
 
 911     if ($form->{"subtotal_$i"} && !$subtotal_header) {
 
 912       $subtotal_header = $i;
 
 913       $position = int($position);
 
 916     } elsif ($subtotal_header) {
 
 918       $position = int($position);
 
 919       $position = $position.".".$subposition;
 
 921       $position = int($position);
 
 927     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
 
 928     my $project = $projects_by_id{$form->{"project_id_$i"}} || SL::DB::Project->new;
 
 930     push(@{ $form->{TEMPLATE_ARRAYS}{$_} },              $prepared_template_arrays{$_}[$i - 1]) for @prepared_arrays;
 
 932     push @{ $form->{TEMPLATE_ARRAYS}{entry_type} },      'normal';
 
 933     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
 
 934     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
 
 935     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
 
 936     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
 
 937     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
 
 938     push @{ $form->{TEMPLATE_ARRAYS}{qty_nofmt} },       $form->{"qty_$i"};
 
 939     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
 
 940     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
 
 941     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
 
 942     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
 
 943     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $project->projectnumber;
 
 944     push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} }, $project->description;
 
 946     if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
 
 947       $subtotal_header     = 0;
 
 950     my $lineweight = $form->{"qty_$i"} * $form->{"weight_$i"};
 
 951     $totalweight += $lineweight;
 
 952     push @{ $form->{TEMPLATE_ARRAYS}->{weight} },            $form->format_amount($myconfig, $form->{"weight_$i"}, 3);
 
 953     push @{ $form->{TEMPLATE_ARRAYS}->{weight_nofmt} },      $form->{"weight_$i"};
 
 954     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight} },        $form->format_amount($myconfig, $lineweight, 3);
 
 955     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight_nofmt} },  $lineweight;
 
 957     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
 959     foreach my $si (@{ $stock_info }) {
 
 962       do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
 
 963       my $bin_wh = $h_bin_wh->fetchrow_hashref();
 
 965       push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$si_position-1] }, $num_si;
 
 966       push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$si_position-1] },        $form->{"partnumber_$i"};
 
 967       push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$si_position-1] },   $form->{"description_$i"};
 
 968       push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$si_position-1] },     $bin_wh->{warehouse};
 
 969       push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$si_position-1] },           $bin_wh->{bin};
 
 970       push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$si_position-1] },  $si->{chargenumber};
 
 971       push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$si_position-1] },    $si->{bestbefore};
 
 972       push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$si_position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
 
 973       push @{ $form->{TEMPLATE_ARRAYS}{si_qty_nofmt}[$si_position-1] },     $si->{qty} * 1;
 
 974       push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$si_position-1] },          $si->{unit};
 
 977     if ($form->{"assembly_$i"}) {
 
 980       # get parts and push them onto the stack
 
 982       if ($form->{groupitems}) {
 
 984           qq|ORDER BY pg.partsgroup, a.oid|;
 
 986         $sortorder = qq|ORDER BY a.oid|;
 
 989       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
 
 991       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
 
 992         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
 993           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
 
 994           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
 
 995           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
 996           push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'assembly-item-partsgroup');
 
 997           push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
 
1001         push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  },  'assembly-item');
 
1002         push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
 
1003         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
 
1004         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
 
1009     CVar->get_non_editable_ic_cvars(form               => $form,
 
1012                                     sub_module         => 'delivery_order_items',
 
1013                                     may_converted_from => ['orderitems', 'delivery_order_items']);
 
1015     push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
 
1016       CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
 
1017         for @{ $ic_cvar_configs };
 
1019     push @{ $form->{TEMPLATE_ARRAYS}->{"project_cvar_" . $_->config->name} }, $_->value_as_text for @{ $project->cvars_by_config };
 
1022   $form->{totalweight}       = $form->format_amount($myconfig, $totalweight, 3);
 
1023   $form->{totalweight_nofmt} = $totalweight;
 
1024   my $defaults = AM->get_defaults();
 
1025   $form->{weightunit}        = $defaults->{weightunit};
 
1028   $h_bin_wh->finish();
 
1030   $form->{delivery_term} = SL::DB::Manager::DeliveryTerm->find_by(id => $form->{delivery_term_id} || undef);
 
1031   $form->{delivery_term}->description_long($form->{delivery_term}->translated_attribute('description_long', $form->{language_id})) if $form->{delivery_term} && $form->{language_id};
 
1032   $form->{department}    = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
 
1034   $form->{username} = $myconfig->{name};
 
1036   $main::lxdebug->leave_sub();
 
1039 sub project_description {
 
1040   $main::lxdebug->enter_sub();
 
1042   my ($self, $dbh, $id) = @_;
 
1044   my $form     =  $main::form;
 
1046   my $query = qq|SELECT description FROM project WHERE id = ?|;
 
1047   my ($value) = selectrow_query($form, $dbh, $query, $id);
 
1049   $main::lxdebug->leave_sub();
 
1054 sub unpack_stock_information {
 
1055   $main::lxdebug->enter_sub();
 
1060   Common::check_params_x(\%params, qw(packed));
 
1064   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
 
1066   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
 
1068   foreach my $entry (@{ $unpacked }) {
 
1069     next if ('HASH' eq ref $entry);
 
1074   $main::lxdebug->leave_sub();
 
1079 sub get_item_availability {
 
1080   $::lxdebug->enter_sub;
 
1085   Common::check_params(\%params, qw(parts_id));
 
1087   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
 
1090     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
 
1091          w.description AS warehousedescription,
 
1092          b.description AS bindescription
 
1094        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
 
1095        LEFT JOIN bin b       ON (i.bin_id       = b.id)
 
1096        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
 
1097        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
 
1099        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
 
1101   my $contents = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, @parts_ids);
 
1103   $::lxdebug->leave_sub;
 
1105   return @{ $contents };
 
1109 sub check_stock_availability {
 
1110   $main::lxdebug->enter_sub();
 
1115   Common::check_params(\%params, qw(requests parts_id));
 
1117   my $myconfig    = \%main::myconfig;
 
1118   my $form        =  $main::form;
 
1120   my $dbh         = $form->get_standard_dbh($myconfig);
 
1122   my $units       = AM->retrieve_units($myconfig, $form);
 
1124   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
 
1125   my $unit_factor = $units->{$partunit}->{factor} || 1;
 
1127   my @contents    = $self->get_item_availability(%params);
 
1131   foreach my $sinfo (@{ $params{requests} }) {
 
1134     foreach my $row (@contents) {
 
1135       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
 
1136                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
 
1137                ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
 
1138                ($row->{bestbefore}   ne $sinfo->{bestbefore}));
 
1142       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
 
1144       if ($base_qty > $row->{qty}) {
 
1145         $sinfo->{error} = 1;
 
1146         push @errors, $sinfo;
 
1152     push @errors, $sinfo if (!$found);
 
1155   $main::lxdebug->leave_sub();
 
1160 sub transfer_in_out {
 
1161   $main::lxdebug->enter_sub();
 
1166   Common::check_params(\%params, qw(direction requests));
 
1168   if (!@{ $params{requests} }) {
 
1169     $main::lxdebug->leave_sub();
 
1173   my $myconfig = \%main::myconfig;
 
1174   my $form     = $main::form;
 
1176   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
 
1180   foreach my $request (@{ $params{requests} }) {
 
1182       'parts_id'                      => $request->{parts_id},
 
1183       "${prefix}_warehouse_id"        => $request->{warehouse_id},
 
1184       "${prefix}_bin_id"              => $request->{bin_id},
 
1185       'chargenumber'                  => $request->{chargenumber},
 
1186       'bestbefore'                    => $request->{bestbefore},
 
1187       'qty'                           => $request->{qty},
 
1188       'unit'                          => $request->{unit},
 
1189       'oe_id'                         => $form->{id},
 
1190       'shippingdate'                  => 'current_date',
 
1191       'transfer_type'                 => $params{direction} eq 'in' ? 'stock' : 'shipped',
 
1192       'project_id'                    => $request->{project_id},
 
1193       'delivery_order_items_stock_id' => $request->{delivery_order_items_stock_id},
 
1194       'comment'                       => $request->{comment},
 
1198   WH->transfer(@transfers);
 
1200   $main::lxdebug->leave_sub();
 
1204 sub get_shipped_qty {
 
1205   $main::lxdebug->enter_sub();
 
1208   # $params{oe_id} : Alle Lieferscheine zu diesem Auftrag durchsuchen und pro Auftragsposition die Mengen zurückgeben
 
1209   #                  Wird zur Darstellung der gelieferten Mengen im Auftrag benötigt
 
1210   # $params{do_id} : Alle Aufträge zu diesem Lieferschein durchsuchen und pro Lieferscheinposition die Mengen zurückgeben
 
1211   #                  Wird für LaTeX benötigt um im Lieferschein pro Position die Mengen auszugeben
 
1212   # $params{delivered}: Alle Aufträge zum Lieferschein $params{do_id} prüfen ob sie vollständiger ausgeliefert sind
 
1213   #                  Wird für das Setzen des 'delivered' Flag in der Datenbank beim "save" des Lieferscheins benötigt
 
1218   # Eigentlich unkritisch: wenn keine der Parameter gesetzt ist kommt ein leerer Hash zurück
 
1219   croak ("Need at least one parameter oe_id or do_id") unless $params{oe_id} || $params{do_id};
 
1221   my $myconfig = \%main::myconfig;
 
1222   my $form     = $main::form;
 
1223   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1228   if ($params{oe_id} ) {
 
1229     push @oe_ids,  $params{oe_id};
 
1230   } elsif ($params{do_id}) {
 
1231     my @links  = RecordLinks->get_links(  'dbh'        => $dbh,
 
1232                                           'from_table' => 'oe',
 
1233                                           'to_table'   => 'delivery_orders',
 
1234                                           'to_id'      => $params{do_id});
 
1236     @oe_ids  = map { $_->{from_id} } @links;
 
1239   if (scalar (@oe_ids) > 0 ) {
 
1240     my $all_units = AM->retrieve_all_units();
 
1241     my $placeholders = join(', ', ('?') x scalar @oe_ids);
 
1242     my $query = qq|SELECT oi.id, oi.position, oi.parts_id, oi.qty, oi.unit, oi.trans_id,
 
1243                         p.unit AS partunit FROM orderitems oi
 
1244                         LEFT JOIN parts p ON (oi.parts_id = p.id)
 
1245                         WHERE trans_id IN (${placeholders})
 
1246                         ORDER BY position ASC|;
 
1248     my $orderitems = selectall_hashref_query($form, $dbh, $query, @oe_ids);
 
1249     foreach my $oe_entry (@{ $orderitems }) {
 
1250       $oe_entry->{qty} *= AM->convert_unit($oe_entry->{unit}, $oe_entry->{partunit}, $all_units);
 
1251       $oe_entry->{qty_notdelivered} = $oe_entry->{qty};
 
1253       # Bei oe Modus auf jeden Fall einen Record anlegen
 
1254       if ( $params{oe_id} ) {
 
1255         $ship{$oe_entry->{position}} = {
 
1256              'qty_ordered'      => $oe_entry->{qty} ,
 
1257              'qty_notdelivered' => $oe_entry->{qty}
 
1262     my @dolinks  = RecordLinks->get_links('dbh'       => $dbh,
 
1263                                        'from_table' => 'oe',
 
1264                                        'to_table'   => 'delivery_orders',
 
1265                                        'from_id'    => @oe_ids);
 
1267     my @do_ids = map { $_->{to_id} }  @dolinks ;
 
1268     if (scalar (@do_ids) == 0) {
 
1269       $main::lxdebug->leave_sub();
 
1273     my %oeitems_by_id       = map { $_->{id} => $_ } @{ $orderitems };
 
1276     $placeholders = join(', ', ('?') x scalar @do_ids);
 
1277     $query  = qq|SELECT doi.parts_id, doi.id, doi.qty, doi.unit, doi.position,
 
1278                doi.delivery_order_id, COALESCE(rlitem.from_id,0) as from_id,
 
1280                FROM delivery_order_items doi
 
1281                LEFT JOIN parts p ON (doi.parts_id = p.id)
 
1282                LEFT JOIN record_links rlitem
 
1283                ON (rlitem.to_id = doi.id AND rlitem.to_table='delivery_order_items')
 
1284                WHERE doi.delivery_order_id IN (${placeholders})|;
 
1286     my $deliveryorderitems = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
1288     # erst mal qty der links bearbeiten
 
1289     foreach my $do_entry (@{ $deliveryorderitems }) {
 
1290       $do_entry->{qty} *= AM->convert_unit($do_entry->{unit}, $do_entry->{partunit}, $all_units);
 
1291       if ($do_entry->{from_id} > 0 ) {
 
1292         # record link zwischen items vorhanden, kann auch von anderem Auftrag sein
 
1293         my $oe_entry = $oeitems_by_id{$do_entry->{from_id}};
 
1295           $oe_entry->{qty_notdelivered} -= $do_entry->{qty};
 
1296           # derzeit nur ein link pro do_item
 
1297           $do_entry->{oe_entry} = $oe_entry;
 
1300         $main::lxdebug->message(LXDebug->DEBUG2(),"no entry for=".$do_entry->{id}." part=".$do_entry->{parts_id});
 
1303     # nun den rest ohne links bearbeiten
 
1304     foreach my $do_entry (@{ $deliveryorderitems }) {
 
1305       next if $do_entry->{from_id} > 0;
 
1306       next if $do_entry->{qty} == 0;
 
1308       foreach my $oe_entry (@{ $orderitems }) {
 
1309         next if $oe_entry->{qty_notdelivered} == 0;
 
1310         if ( $do_entry->{parts_id} == $oe_entry->{parts_id} ) {
 
1311           # zu viele geliefert auf andere position ?
 
1312           if ( $oe_entry->{qty_notdelivered} < 0 ) {
 
1313             $do_entry->{qty} += - $oe_entry->{qty_notdelivered};
 
1314             $oe_entry->{qty_notdelivered} = 0;
 
1316             if ( $do_entry->{qty} < $oe_entry->{qty_notdelivered} ) {
 
1317               $oe_entry->{qty_notdelivered} -= $do_entry->{qty};
 
1318               $do_entry->{qty} = 0;
 
1320               $do_entry->{qty} -= $oe_entry->{qty_notdelivered};
 
1321               $oe_entry->{qty_notdelivered} = 0;
 
1323             # derzeit nur ein link pro do_item
 
1324             $do_entry->{oe_entry} = $oe_entry if !$do_entry->{oe_entry};
 
1327         last if $do_entry->{qty} <= 0;
 
1330     if ( $params{oe_id} ) {
 
1331       $ship{$_->{position}}->{qty_notdelivered} = $_->{qty_notdelivered} for @{ $orderitems };
 
1333     elsif ($params{do_id} && $params{delivered}) {
 
1334       foreach my $oe_entry (@{ $orderitems }) {
 
1335         if ( !$ship{$oe_entry->{trans_id}} ) {
 
1336             $ship{$oe_entry->{trans_id}} = { 'delivered' => 1 };
 
1338         $ship{$oe_entry->{trans_id}}->{delivered} = 0 if $oe_entry->{qty_notdelivered} > 0;
 
1341     elsif ($params{do_id}) {
 
1342       foreach my $do_entry (@{ $deliveryorderitems }) {
 
1343         next if $params{do_id} != $do_entry->{delivery_order_id};
 
1344         my $position = $do_entry->{position};
 
1345         if ( $position > 0 && $do_entry->{oe_entry}) {
 
1346           if ( !$ship{$position} ) {
 
1347             $ship{$position} = {
 
1348               'qty_ordered'      => $do_entry->{oe_entry}->{qty} ,
 
1349               'qty_notdelivered' => $do_entry->{oe_entry}->{qty_notdelivered}
 
1352             $ship{$position}->{qty_ordered}      += $do_entry->{oe_entry}->{qty};
 
1353             $ship{$position}->{qty_notdelivered} += $do_entry->{oe_entry}->{qty_notdelivered};
 
1359   $main::lxdebug->leave_sub();
 
1363 sub is_marked_as_delivered {
 
1364   $main::lxdebug->enter_sub();
 
1369   Common::check_params(\%params, qw(id));
 
1371   my $myconfig    = \%main::myconfig;
 
1372   my $form        = $main::form;
 
1374   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1376   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
 
1378   $main::lxdebug->leave_sub();
 
1380   return $delivered ? 1 : 0;