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, '%' . trim($form->{$vc}) . '%';
 
 117   if ($form->{"cp_name"}) {
 
 118     push @where, "(cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
 
 119     push @values, ('%' . trim($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, '%' . trim($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, '%' . trim($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 @links    = RecordLinks->get_links('dbh'        => $dbh,
 
 540                                         'from_table' => 'oe',
 
 541                                         'to_table'   => 'delivery_orders',
 
 542                                         'to_id'      => $params{do_id});
 
 544   my $oe_id  = @links ? $links[0]->{from_id} : undef;
 
 546   return $main::lxdebug->leave_sub() if (!$oe_id);
 
 548   my $all_units = AM->retrieve_all_units();
 
 550   my $query     = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
 
 552                      LEFT JOIN parts p ON (oi.parts_id = p.id)
 
 553                      WHERE (oi.trans_id = ?)|;
 
 554   my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
 
 556   my %shipped   = $self->get_shipped_qty('type'  => $params{type},
 
 560   while (my $ref = $sth->fetchrow_hashref()) {
 
 561     $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
 
 563     if ($ordered{$ref->{parts_id}}) {
 
 564       $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
 
 566       $ordered{$ref->{parts_id}}             = $ref;
 
 572   map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
 
 575   foreach my $part (values %ordered) {
 
 576     if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
 
 583     $query = qq|UPDATE oe
 
 586     do_query($form, $dbh, $query, $oe_id);
 
 587     $dbh->commit() if (!$params{dbh});
 
 590   $main::lxdebug->leave_sub();
 
 594   $main::lxdebug->enter_sub();
 
 599   Common::check_params(\%params, qw(ids));
 
 601   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
 
 602     $main::lxdebug->leave_sub();
 
 606   my $myconfig = \%main::myconfig;
 
 607   my $form     = $main::form;
 
 609   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
 611   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
 
 613   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
 
 615   $dbh->commit() unless ($params{dbh});
 
 616   $form->new_lastmtime('delivery_orders');
 
 618   $main::lxdebug->leave_sub();
 
 622   $main::lxdebug->enter_sub();
 
 626   my $myconfig = \%main::myconfig;
 
 627   my $form     = $main::form;
 
 628   my $spool    = $::lx_office_conf{paths}->{spool};
 
 630   my $rc = SL::DB::Order->new->db->with_transaction(sub {
 
 631     my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $form->{id} ]) };
 
 633     SL::DB::DeliveryOrder->new(id => $form->{id})->delete;
 
 635     my $spool = $::lx_office_conf{paths}->{spool};
 
 636     unlink map { "$spool/$_" } @spoolfiles if $spool;
 
 641   $main::lxdebug->leave_sub();
 
 647   $main::lxdebug->enter_sub();
 
 652   my $myconfig = \%main::myconfig;
 
 653   my $form     = $main::form;
 
 655   # connect to database
 
 656   my $dbh = $form->get_standard_dbh($myconfig);
 
 658   my ($query, $query_add, @values, $sth, $ref);
 
 660   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
 663   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
 
 665   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
 
 667   if ($mode eq 'default') {
 
 668     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate|);
 
 669     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 671     # if reqdate is not set from oe-workflow, set it to transdate (which is current date)
 
 672     $form->{reqdate} ||= $form->{transdate};
 
 675     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
 
 677     $main::lxdebug->leave_sub();
 
 682   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
 
 683   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
 
 685   # retrieve order for single id
 
 686   # NOTE: this query is intended to fetch all information only ONCE.
 
 687   # so if any of these infos is important (or even different) for any item,
 
 688   # it will be killed out and then has to be fetched from the item scope query further down
 
 690     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
 
 691          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
 
 692          e.name AS employee, dord.employee_id, dord.salesman_id,
 
 693          dord.${vc}_id, cv.name AS ${vc},
 
 694          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
 
 695          d.description AS department, dord.language_id,
 
 697          dord.itime, dord.mtime,
 
 698          dord.globalproject_id, dord.delivered, dord.transaction_description,
 
 699          dord.taxzone_id, dord.taxincluded, dord.payment_id, (SELECT cu.name FROM currencies cu WHERE cu.id=dord.currency_id) AS currency,
 
 700          dord.delivery_term_id, dord.itime::DATE AS insertdate
 
 701        FROM delivery_orders dord
 
 702        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
 
 703        LEFT JOIN employee e ON (dord.employee_id = e.id)
 
 704        LEFT JOIN department d ON (dord.department_id = d.id)
 
 705        WHERE dord.id IN ($do_ids_placeholders)|;
 
 706   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
 
 708   delete $form->{"${vc}_id"};
 
 710   $form->{ordnumber_array} = ' ';
 
 711   $form->{cusordnumber_array} = ' ';
 
 712   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 713     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
 
 715       $main::lxdebug->leave_sub();
 
 720     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
 
 721     $form->{donumber_array} .= $form->{donumber} . ' ';
 
 722     $pos = index($form->{ordnumber_array},' ' . $form->{ordnumber} . ' ');
 
 724       $form->{ordnumber_array} .= $form->{ordnumber} . ' ';
 
 726     $pos = index($form->{cusordnumber_array},' ' . $form->{cusordnumber} . ' ');
 
 728       $form->{cusordnumber_array} .= $form->{cusordnumber} . ' ';
 
 732   $form->{mtime}   ||= $form->{itime};
 
 733   $form->{lastmtime} = $form->{mtime};
 
 734   $form->{donumber_array} =~ s/\s*$//g;
 
 735   $form->{ordnumber_array} =~ s/ //;
 
 736   $form->{ordnumber_array} =~ s/\s*$//g;
 
 737   $form->{cusordnumber_array} =~ s/ //;
 
 738   $form->{cusordnumber_array} =~ s/\s*$//g;
 
 740   $form->{saved_donumber} = $form->{donumber};
 
 741   $form->{saved_ordnumber} = $form->{ordnumber};
 
 742   $form->{saved_cusordnumber} = $form->{cusordnumber};
 
 744   # if not given, fill transdate with current_date
 
 745   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
 
 747   if ($mode eq 'single') {
 
 748     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
 
 749     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
 
 751     $ref   = $sth->fetchrow_hashref("NAME_lc");
 
 753     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 756     if ($form->{shipto_id}) {
 
 757       my $cvars = CVar->get_custom_variables(
 
 760         trans_id => $form->{shipto_id},
 
 762       $form->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
 
 765     # get printed, emailed and queued
 
 766     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
 
 767     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 769     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 770       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
 771       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
 772       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
 
 775     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
 781   # retrieve individual items
 
 782   # this query looks up all information about the items
 
 783   # stuff different from the whole will not be overwritten, but saved with a suffix.
 
 785     qq|SELECT doi.id AS delivery_order_items_id,
 
 786          p.partnumber, p.assembly, p.listprice, doi.description, doi.qty,
 
 787          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.notes AS partnotes,
 
 788          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
 
 789          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
 
 790          doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
 
 791          doi.active_price_source, doi.active_discount_source,
 
 792          pr.projectnumber, dord.transdate AS dord_transdate, dord.donumber,
 
 794        FROM delivery_order_items doi
 
 795        JOIN parts p ON (doi.parts_id = p.id)
 
 796        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
 
 797        LEFT JOIN project pr ON (doi.project_id = pr.id)
 
 798        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 799        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
 
 800        ORDER BY doi.delivery_order_id, doi.position|;
 
 802   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
 
 804   # Retrieve custom variables.
 
 805   foreach my $doi (@{ $form->{form_details} }) {
 
 806     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 808                                            sub_module => 'delivery_order_items',
 
 809                                            trans_id   => $doi->{delivery_order_items_id},
 
 811     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
 
 814   if ($mode eq 'single') {
 
 815     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 818       qq|SELECT id as delivery_order_items_stock_id, qty, unit, bin_id,
 
 819                 warehouse_id, chargenumber, bestbefore
 
 820          FROM delivery_order_items_stock
 
 821          WHERE delivery_order_item_id = ?|;
 
 822     my $sth = prepare_query($form, $dbh, $query);
 
 824     foreach my $doi (@{ $form->{form_details} }) {
 
 825       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
 
 827       while (my $ref = $sth->fetchrow_hashref()) {
 
 828         push @{ $requests }, $ref;
 
 831       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
 
 837   Common::webdav_folder($form);
 
 839   $main::lxdebug->leave_sub();
 
 845   $main::lxdebug->enter_sub();
 
 847   my ($self, $myconfig, $form) = @_;
 
 849   # connect to database
 
 850   my $dbh = $form->get_standard_dbh($myconfig);
 
 859   my $subtotal_header = 0;
 
 865   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
 
 867   # sort items by partsgroup
 
 868   for $i (1 .. $form->{rowcount}) {
 
 870     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
 871       $partsgroup = $form->{"partsgroup_$i"};
 
 873     push @partsgroup, [$i, $partsgroup];
 
 874     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
 
 880     $projects = SL::DB::Manager::Project->get_all(query => [ id => \@project_ids ]);
 
 881     %projects_by_id = map { $_->id => $_ } @$projects;
 
 884   if ($projects_by_id{$form->{"globalproject_id"}}) {
 
 885     $form->{globalprojectnumber} = $projects_by_id{$form->{"globalproject_id"}}->projectnumber;
 
 886     $form->{globalprojectdescription} = $projects_by_id{$form->{"globalproject_id"}}->description;
 
 888     for (@{ $projects_by_id{$form->{"globalproject_id"}}->cvars_by_config }) {
 
 889       $form->{"project_cvar_" . $_->config->name} = $_->value_as_text;
 
 893   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
 
 895                     JOIN parts p ON (a.parts_id = p.id)
 
 896                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 899   my $h_pg     = prepare_query($form, $dbh, $q_pg);
 
 901   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
 
 902                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
 
 903   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
 
 905   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
 
 909   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 910   my $project_cvar_configs = CVar->get_configs(module => 'Projects');
 
 912   # get some values of parts from db on store them in extra array,
 
 913   # so that they can be sorted in later
 
 914   my %prepared_template_arrays = IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
 
 915   my @prepared_arrays          = keys %prepared_template_arrays;
 
 917   $form->{TEMPLATE_ARRAYS} = { };
 
 920     qw(runningnumber number description longdescription qty qty_nofmt unit
 
 921        partnotes serialnumber reqdate projectnumber projectdescription
 
 922        weight weight_nofmt lineweight lineweight_nofmt
 
 923        si_runningnumber si_number si_description
 
 924        si_warehouse si_bin si_chargenumber si_bestbefore
 
 925        si_qty si_qty_nofmt si_unit);
 
 927   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays, @prepared_arrays);
 
 929   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 930   push @arrays, map { "project_cvar_$_->{name}" } @{ $project_cvar_configs };
 
 932   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
 933   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 937   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
 940     next if (!$form->{"id_$i"});
 
 942     if ($item->[1] ne $sameitem) {
 
 943       push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'partsgroup');
 
 944       push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, qq|$item->[1]|);
 
 945       $sameitem = $item->[1];
 
 947       map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
 
 948       map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
 
 952     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 954     # add number, description and qty to $form->{number}, ....
 
 955     if ($form->{"subtotal_$i"} && !$subtotal_header) {
 
 956       $subtotal_header = $i;
 
 957       $position = int($position);
 
 960     } elsif ($subtotal_header) {
 
 962       $position = int($position);
 
 963       $position = $position.".".$subposition;
 
 965       $position = int($position);
 
 971     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
 
 972     my $project = $projects_by_id{$form->{"project_id_$i"}} || SL::DB::Project->new;
 
 974     push(@{ $form->{TEMPLATE_ARRAYS}{$_} },              $prepared_template_arrays{$_}[$i - 1]) for @prepared_arrays;
 
 976     push @{ $form->{TEMPLATE_ARRAYS}{entry_type} },      'normal';
 
 977     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
 
 978     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
 
 979     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
 
 980     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
 
 981     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
 
 982     push @{ $form->{TEMPLATE_ARRAYS}{qty_nofmt} },       $form->{"qty_$i"};
 
 983     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
 
 984     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
 
 985     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
 
 986     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
 
 987     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $project->projectnumber;
 
 988     push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} }, $project->description;
 
 990     if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
 
 991       $subtotal_header     = 0;
 
 994     my $lineweight = $form->{"qty_$i"} * $form->{"weight_$i"};
 
 995     $totalweight += $lineweight;
 
 996     push @{ $form->{TEMPLATE_ARRAYS}->{weight} },            $form->format_amount($myconfig, $form->{"weight_$i"}, 3);
 
 997     push @{ $form->{TEMPLATE_ARRAYS}->{weight_nofmt} },      $form->{"weight_$i"};
 
 998     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight} },        $form->format_amount($myconfig, $lineweight, 3);
 
 999     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight_nofmt} },  $lineweight;
 
1001     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
 
1003     foreach my $si (@{ $stock_info }) {
 
1006       do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
 
1007       my $bin_wh = $h_bin_wh->fetchrow_hashref();
 
1009       push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$si_position-1] }, $num_si;
 
1010       push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$si_position-1] },        $form->{"partnumber_$i"};
 
1011       push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$si_position-1] },   $form->{"description_$i"};
 
1012       push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$si_position-1] },     $bin_wh->{warehouse};
 
1013       push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$si_position-1] },           $bin_wh->{bin};
 
1014       push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$si_position-1] },  $si->{chargenumber};
 
1015       push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$si_position-1] },    $si->{bestbefore};
 
1016       push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$si_position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
 
1017       push @{ $form->{TEMPLATE_ARRAYS}{si_qty_nofmt}[$si_position-1] },     $si->{qty} * 1;
 
1018       push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$si_position-1] },          $si->{unit};
 
1021     if ($form->{"assembly_$i"}) {
 
1024       # get parts and push them onto the stack
 
1026       if ($form->{groupitems}) {
 
1028           qq|ORDER BY pg.partsgroup, a.oid|;
 
1030         $sortorder = qq|ORDER BY a.oid|;
 
1033       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
 
1035       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
 
1036         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
1037           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
 
1038           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
 
1039           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
1040           push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'assembly-item-partsgroup');
 
1041           push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
 
1045         push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  },  'assembly-item');
 
1046         push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
 
1047         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
 
1048         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
 
1053     CVar->get_non_editable_ic_cvars(form               => $form,
 
1056                                     sub_module         => 'delivery_order_items',
 
1057                                     may_converted_from => ['orderitems', 'delivery_order_items']);
 
1059     push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
 
1060       CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
 
1061         for @{ $ic_cvar_configs };
 
1063     push @{ $form->{TEMPLATE_ARRAYS}->{"project_cvar_" . $_->config->name} }, $_->value_as_text for @{ $project->cvars_by_config };
 
1066   $form->{totalweight}       = $form->format_amount($myconfig, $totalweight, 3);
 
1067   $form->{totalweight_nofmt} = $totalweight;
 
1068   my $defaults = AM->get_defaults();
 
1069   $form->{weightunit}        = $defaults->{weightunit};
 
1072   $h_bin_wh->finish();
 
1074   $form->{delivery_term} = SL::DB::Manager::DeliveryTerm->find_by(id => $form->{delivery_term_id} || undef);
 
1075   $form->{delivery_term}->description_long($form->{delivery_term}->translated_attribute('description_long', $form->{language_id})) if $form->{delivery_term} && $form->{language_id};
 
1076   $form->{department}    = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
 
1078   $form->{username} = $myconfig->{name};
 
1080   $main::lxdebug->leave_sub();
 
1083 sub project_description {
 
1084   $main::lxdebug->enter_sub();
 
1086   my ($self, $dbh, $id) = @_;
 
1088   my $form     =  $main::form;
 
1090   my $query = qq|SELECT description FROM project WHERE id = ?|;
 
1091   my ($value) = selectrow_query($form, $dbh, $query, $id);
 
1093   $main::lxdebug->leave_sub();
 
1098 sub unpack_stock_information {
 
1099   $main::lxdebug->enter_sub();
 
1104   Common::check_params_x(\%params, qw(packed));
 
1108   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
 
1110   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
 
1112   foreach my $entry (@{ $unpacked }) {
 
1113     next if ('HASH' eq ref $entry);
 
1118   $main::lxdebug->leave_sub();
 
1123 sub get_item_availability {
 
1124   $::lxdebug->enter_sub;
 
1129   Common::check_params(\%params, qw(parts_id));
 
1131   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
 
1134     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
 
1135          w.description AS warehousedescription,
 
1136          b.description AS bindescription
 
1138        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
 
1139        LEFT JOIN bin b       ON (i.bin_id       = b.id)
 
1140        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
 
1141        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
 
1143        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
 
1145   my $contents = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, @parts_ids);
 
1147   $::lxdebug->leave_sub;
 
1149   return @{ $contents };
 
1153 sub check_stock_availability {
 
1154   $main::lxdebug->enter_sub();
 
1159   Common::check_params(\%params, qw(requests parts_id));
 
1161   my $myconfig    = \%main::myconfig;
 
1162   my $form        =  $main::form;
 
1164   my $dbh         = $form->get_standard_dbh($myconfig);
 
1166   my $units       = AM->retrieve_units($myconfig, $form);
 
1168   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
 
1169   my $unit_factor = $units->{$partunit}->{factor} || 1;
 
1171   my @contents    = $self->get_item_availability(%params);
 
1175   foreach my $sinfo (@{ $params{requests} }) {
 
1178     foreach my $row (@contents) {
 
1179       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
 
1180                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
 
1181                ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
 
1182                ($row->{bestbefore}   ne $sinfo->{bestbefore}));
 
1186       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
 
1188       if ($base_qty > $row->{qty}) {
 
1189         $sinfo->{error} = 1;
 
1190         push @errors, $sinfo;
 
1196     push @errors, $sinfo if (!$found);
 
1199   $main::lxdebug->leave_sub();
 
1204 sub transfer_in_out {
 
1205   $main::lxdebug->enter_sub();
 
1210   Common::check_params(\%params, qw(direction requests));
 
1212   if (!@{ $params{requests} }) {
 
1213     $main::lxdebug->leave_sub();
 
1217   my $myconfig = \%main::myconfig;
 
1218   my $form     = $main::form;
 
1220   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
 
1224   foreach my $request (@{ $params{requests} }) {
 
1226       'parts_id'                      => $request->{parts_id},
 
1227       "${prefix}_warehouse_id"        => $request->{warehouse_id},
 
1228       "${prefix}_bin_id"              => $request->{bin_id},
 
1229       'chargenumber'                  => $request->{chargenumber},
 
1230       'bestbefore'                    => $request->{bestbefore},
 
1231       'qty'                           => $request->{qty},
 
1232       'unit'                          => $request->{unit},
 
1233       'oe_id'                         => $form->{id},
 
1234       'shippingdate'                  => 'current_date',
 
1235       'transfer_type'                 => $params{direction} eq 'in' ? 'stock' : 'shipped',
 
1236       'project_id'                    => $request->{project_id},
 
1237       'delivery_order_items_stock_id' => $request->{delivery_order_items_stock_id},
 
1238       'comment'                       => $request->{comment},
 
1242   WH->transfer(@transfers);
 
1244   $main::lxdebug->leave_sub();
 
1247 sub get_shipped_qty {
 
1248   $main::lxdebug->enter_sub();
 
1253   Common::check_params(\%params, qw(type oe_id));
 
1255   my $myconfig = \%main::myconfig;
 
1256   my $form     = $main::form;
 
1258   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1260   my @links    = RecordLinks->get_links('dbh'        => $dbh,
 
1261                                         'from_table' => 'oe',
 
1262                                         'from_id'    => $params{oe_id},
 
1263                                         'to_table'   => 'delivery_orders');
 
1264   my @values   = map { $_->{to_id} } @links;
 
1266   if (!scalar @values) {
 
1267     $main::lxdebug->leave_sub();
 
1272     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
 
1273        FROM delivery_order_items doi
 
1274        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
 
1275        LEFT JOIN parts p ON (doi.parts_id = p.id)
 
1276        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
 
1279   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
 
1280   my $all_units = AM->retrieve_all_units();
 
1282   foreach my $entry (@{ $entries }) {
 
1283     $entry->{qty} *= AM->convert_unit($entry->{unit}, $entry->{partunit}, $all_units);
 
1285     if (!$ship{$entry->{parts_id}}) {
 
1286       $ship{$entry->{parts_id}} = $entry;
 
1288       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
 
1292   $main::lxdebug->leave_sub();
 
1297 sub is_marked_as_delivered {
 
1298   $main::lxdebug->enter_sub();
 
1303   Common::check_params(\%params, qw(id));
 
1305   my $myconfig    = \%main::myconfig;
 
1306   my $form        = $main::form;
 
1308   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1310   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
 
1312   $main::lxdebug->leave_sub();
 
1314   return $delivered ? 1 : 0;