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 #======================================================================
37 use List::Util qw(max);
43 use SL::DB::DeliveryOrder;
46 use SL::HTML::Restrict;
50 use SL::Util qw(trim);
55 $main::lxdebug->enter_sub();
59 my $myconfig = \%main::myconfig;
60 my $form = $main::form;
63 my $dbh = $form->get_standard_dbh($myconfig);
65 my (@where, @values, $where);
67 my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
70 qq|SELECT dord.id, dord.donumber, dord.ordnumber, dord.cusordnumber,
71 dord.transdate, dord.reqdate,
72 ct.${vc}number, ct.name, ct.business_id,
73 dord.${vc}_id, dord.globalproject_id,
74 dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
75 dord.transaction_description, dord.itime::DATE AS insertdate,
76 pr.projectnumber AS globalprojectnumber,
77 dep.description AS department,
80 FROM delivery_orders dord
81 LEFT JOIN $vc ct ON (dord.${vc}_id = ct.id)
82 LEFT JOIN contacts cp ON (dord.cp_id = cp.cp_id)
83 LEFT JOIN employee e ON (dord.employee_id = e.id)
84 LEFT JOIN employee sm ON (dord.salesman_id = sm.id)
85 LEFT JOIN project pr ON (dord.globalproject_id = pr.id)
86 LEFT JOIN department dep ON (dord.department_id = dep.id)
89 push @where, ($form->{type} eq 'sales_delivery_order' ? '' : 'NOT ') . qq|COALESCE(dord.is_sales, FALSE)|;
91 if ($form->{department_id}) {
92 push @where, qq|dord.department_id = ?|;
93 push @values, conv_i($form->{department_id});
96 if ($form->{project_id}) {
98 qq|(dord.globalproject_id = ?) OR EXISTS
99 (SELECT * FROM delivery_order_items doi
100 WHERE (doi.project_id = ?) AND (doi.delivery_order_id = dord.id))|;
101 push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
104 if ($form->{"business_id"}) {
105 push @where, qq|ct.business_id = ?|;
106 push @values, conv_i($form->{"business_id"});
109 if ($form->{"${vc}_id"}) {
110 push @where, qq|dord.${vc}_id = ?|;
111 push @values, $form->{"${vc}_id"};
113 } elsif ($form->{$vc}) {
114 push @where, qq|ct.name ILIKE ?|;
115 push @values, like($form->{$vc});
118 if ($form->{"cp_name"}) {
119 push @where, "(cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
120 push @values, (like($form->{"cp_name"}))x2;
123 foreach my $item (qw(employee_id salesman_id)) {
124 next unless ($form->{$item});
125 push @where, "dord.$item = ?";
126 push @values, conv_i($form->{$item});
128 if (!$main::auth->assert('sales_all_edit', 1)) {
129 push @where, qq|dord.employee_id = (select id from employee where login= ?)|;
130 push @values, $::myconfig{login};
133 foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
134 next unless ($form->{$item});
135 push @where, qq|dord.$item ILIKE ?|;
136 push @values, like($form->{$item});
139 if (($form->{open} || $form->{closed}) &&
140 ($form->{open} ne $form->{closed})) {
141 push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
144 if (($form->{notdelivered} || $form->{delivered}) &&
145 ($form->{notdelivered} ne $form->{delivered})) {
146 push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
149 if ($form->{serialnumber}) {
150 push @where, 'dord.id IN (SELECT doi.delivery_order_id FROM delivery_order_items doi WHERE doi.serialnumber LIKE ?)';
151 push @values, like($form->{serialnumber});
154 if($form->{transdatefrom}) {
155 push @where, qq|dord.transdate >= ?|;
156 push @values, conv_date($form->{transdatefrom});
159 if($form->{transdateto}) {
160 push @where, qq|dord.transdate <= ?|;
161 push @values, conv_date($form->{transdateto});
164 if($form->{reqdatefrom}) {
165 push @where, qq|dord.reqdate >= ?|;
166 push @values, conv_date($form->{reqdatefrom});
169 if($form->{reqdateto}) {
170 push @where, qq|dord.reqdate <= ?|;
171 push @values, conv_date($form->{reqdateto});
174 if($form->{insertdatefrom}) {
175 push @where, qq|dord.itime::DATE >= ?|;
176 push@values, conv_date($form->{insertdatefrom});
179 if($form->{insertdateto}) {
180 push @where, qq|dord.itime::DATE <= ?|;
181 push @values, conv_date($form->{insertdateto});
184 if ($form->{parts_partnumber}) {
187 SELECT delivery_order_items.delivery_order_id
188 FROM delivery_order_items
189 LEFT JOIN parts ON (delivery_order_items.parts_id = parts.id)
190 WHERE (delivery_order_items.delivery_order_id = dord.id)
191 AND (parts.partnumber ILIKE ?)
195 push @values, like($form->{parts_partnumber});
198 if ($form->{parts_description}) {
201 SELECT delivery_order_items.delivery_order_id
202 FROM delivery_order_items
203 WHERE (delivery_order_items.delivery_order_id = dord.id)
204 AND (delivery_order_items.description ILIKE ?)
208 push @values, like($form->{parts_description});
212 $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
215 my %allowed_sort_columns = (
216 "transdate" => "dord.transdate",
217 "reqdate" => "dord.reqdate",
219 "donumber" => "dord.donumber",
220 "ordnumber" => "dord.ordnumber",
222 "employee" => "e.name",
223 "salesman" => "sm.name",
224 "shipvia" => "dord.shipvia",
225 "transaction_description" => "dord.transaction_description",
226 "department" => "lower(dep.description)",
227 "insertdate" => "dord.itime",
230 my $sortdir = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
231 my $sortorder = "dord.id";
232 if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
233 $sortorder = $allowed_sort_columns{$form->{sort}};
236 $query .= qq| ORDER by | . $sortorder . " $sortdir";
238 $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
240 if (scalar @{ $form->{DO} }) {
244 WHERE NOT COALESCE(quotation, FALSE)
246 AND (COALESCE(${vc}_id, 0) != 0)|;
248 my $sth = prepare_query($form, $dbh, $query);
250 foreach my $dord (@{ $form->{DO} }) {
251 next unless ($dord->{ordnumber});
252 do_statement($form, $sth, $query, $dord->{ordnumber});
253 ($dord->{oe_id}) = $sth->fetchrow_array();
259 $main::lxdebug->leave_sub();
263 $main::lxdebug->enter_sub();
267 my $myconfig = \%main::myconfig;
268 my $form = $main::form;
270 # connect to database, turn off autocommit
271 my $dbh = $form->get_standard_dbh($myconfig);
272 my $restricter = SL::HTML::Restrict->create;
274 my ($query, @values, $sth, $null);
276 my $all_units = AM->retrieve_units($myconfig, $form);
277 $form->{all_units} = $all_units;
279 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
282 my $trans_number = SL::TransNumber->new(type => $form->{type}, dbh => $dbh, number => $form->{donumber}, id => $form->{id});
283 $form->{donumber} ||= $trans_number->create_unique;
284 $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
285 $form->get_employee($dbh) unless ($form->{employee_id});
287 my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
289 my (@processed_doi, @processed_dois);
293 # only delete shipto complete
294 $query = qq|DELETE FROM custom_variables
295 WHERE (config_id IN (SELECT id FROM custom_variable_configs WHERE (module = 'ShipTo')))
296 AND (trans_id IN (SELECT shipto_id FROM shipto WHERE (module = 'DO') AND (trans_id = ?)))|;
297 do_query($form, $dbh, $query, $form->{id});
299 $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
300 do_query($form, $dbh, $query, conv_i($form->{id}));
304 $query = qq|SELECT nextval('id')|;
305 ($form->{id}) = selectrow_query($form, $dbh, $query);
307 $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id, currency_id, taxzone_id) VALUES (?, '', ?, (SELECT currency_id FROM defaults LIMIT 1), ?)|;
308 do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}), $form->{taxzone_id});
314 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
315 my %price_factors = map { $_->{id} => $_->{factor} *1 } @{ $form->{ALL_PRICE_FACTORS} };
318 my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
319 my @part_ids = keys %part_id_map;
323 $query = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
324 %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
327 UPDATE delivery_order_items SET
328 delivery_order_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
329 sellprice = ?, discount = ?, unit = ?, reqdate = ?, project_id = ?, serialnumber = ?,
330 lastcost = ? , price_factor_id = ?, price_factor = (SELECT factor FROM price_factors where id = ?),
331 marge_price_factor = ?, pricegroup_id = ?, active_price_source = ?, active_discount_source = ?
334 my $h_item = prepare_query($form, $dbh, $q_item);
336 my $q_item_stock = <<SQL;
337 UPDATE delivery_order_items_stock SET
338 delivery_order_item_id = ?, qty = ?, unit = ?, warehouse_id = ?,
339 bin_id = ?, chargenumber = ?, bestbefore = ?
342 my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
344 my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
346 for my $i (1 .. $form->{rowcount}) {
347 next if (!$form->{"id_$i"});
349 CVar->get_non_editable_ic_cvars(form => $form,
352 sub_module => 'delivery_order_items',
353 may_converted_from => ['orderitems', 'delivery_order_items']);
357 if (!$form->{"delivery_order_items_id_$i"}) {
358 # there is no persistent id, therefore create one with all necessary constraints
359 my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
360 my $h_item_id = prepare_query($form, $dbh, $q_item_id);
361 do_statement($form, $h_item_id, $q_item_id);
362 $form->{"delivery_order_items_id_$i"} = $h_item_id->fetchrow_array();
363 $query = qq|INSERT INTO delivery_order_items (id, delivery_order_id, position, parts_id) VALUES (?, ?, ?, ?)|;
364 do_query($form, $dbh, $query, conv_i($form->{"delivery_order_items_id_$i"}),
365 conv_i($form->{"id"}), conv_i($position), conv_i($form->{"id_$i"}));
366 $h_item_id->finish();
369 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
371 my $item_unit = $part_unit_map{$form->{"id_$i"}};
374 if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
375 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
377 my $baseqty = $form->{"qty_$i"} * $basefactor;
379 # set values to 0 if nothing entered
380 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"});
381 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
382 $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
384 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
385 my $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
387 $items_reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
390 # Get pricegroup_id and save it. Unfortunately the interface
391 # also uses ID "0" for signalling that none is selected, but "0"
392 # must not be stored in the database. Therefore we cannot simply
394 my $pricegroup_id = $form->{"pricegroup_id_$i"} * 1;
395 $pricegroup_id = undef if !$pricegroup_id;
397 # save detail record in delivery_order_items table
398 @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
399 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}),
400 $form->{"qty_$i"}, $baseqty,
401 $form->{"sellprice_$i"}, $form->{"discount_$i"} / 100,
402 $form->{"unit_$i"}, conv_date($items_reqdate), conv_i($form->{"project_id_$i"}),
403 $form->{"serialnumber_$i"},
404 $form->{"lastcost_$i"},
405 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
406 conv_i($form->{"marge_price_factor_$i"}),
408 $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
409 conv_i($form->{"delivery_order_items_id_$i"}));
410 do_statement($form, $h_item, $q_item, @values);
411 push @processed_doi, $form->{"delivery_order_items_id_$i"}; # transaction safe?
413 my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
415 foreach my $sinfo (@{ $stock_info }) {
416 # if we have stock_info, we have to check for persistents entries
417 if (!$sinfo->{"delivery_order_items_stock_id"}) {
418 my $q_item_stock_id = qq|SELECT nextval('id')|;
419 my $h_item_stock_id = prepare_query($form, $dbh, $q_item_stock_id);
420 do_statement($form, $h_item_stock_id, $q_item_stock_id);
421 $sinfo->{"delivery_order_items_stock_id"} = $h_item_stock_id->fetchrow_array();
422 $query = qq|INSERT INTO delivery_order_items_stock (id, delivery_order_item_id, qty, unit, warehouse_id, bin_id)
423 VALUES (?, ?, ?, ?, ?, ?)|;
424 do_query($form, $dbh, $query, conv_i($sinfo->{"delivery_order_items_stock_id"}),
425 conv_i($form->{"delivery_order_items_id_$i"}), $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
426 conv_i($sinfo->{bin_id}));
427 $h_item_stock_id->finish();
428 # write back the id to the form (important if only transfer was clicked (id fk for invoice)
429 $form->{"stock_${in_out}_$i"} = YAML::Dump($stock_info);
431 @values = ($form->{"delivery_order_items_id_$i"}, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
432 conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}),
433 conv_i($sinfo->{"delivery_order_items_stock_id"}));
434 do_statement($form, $h_item_stock, $q_item_stock, @values);
435 push @processed_dois, $sinfo->{"delivery_order_items_stock_id"};
438 CVar->save_custom_variables(module => 'IC',
439 sub_module => 'delivery_order_items',
440 trans_id => $form->{"delivery_order_items_id_$i"},
441 configs => $ic_cvar_configs,
443 name_prefix => 'ic_',
444 name_postfix => "_$i",
447 # link order items with doi, for future extension look at foreach IS.pm
448 if (!$form->{saveasnew} && $form->{"converted_from_orderitems_id_$i"}) {
449 RecordLinks->create_links('dbh' => $dbh,
451 'from_table' => 'orderitems',
452 'from_ids' => $form->{"converted_from_orderitems_id_$i"},
453 'to_table' => 'delivery_order_items',
454 'to_id' => $form->{"delivery_order_items_id_$i"},
457 delete $form->{"converted_from_orderitems_id_$i"};
460 # 1. search for orphaned dois; processed_dois may be empty (no transfer) TODO: be supersafe and alter same statement for doi and oi
461 $query = sprintf 'SELECT id FROM delivery_order_items_stock WHERE delivery_order_item_id in
462 (select id from delivery_order_items where delivery_order_id = ?)';
463 $query .= sprintf ' AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_dois if (scalar @processed_dois);
464 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_dois);
465 my @orphaned_dois_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
466 if (scalar @orphaned_dois_ids) {
467 # clean up delivery_order_items_stock
468 $query = sprintf 'DELETE FROM delivery_order_items_stock WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_dois_ids;
469 do_query($form, $dbh, $query, @orphaned_dois_ids);
471 # 2. search for orphaned doi
472 $query = sprintf 'SELECT id FROM delivery_order_items WHERE delivery_order_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_doi;
473 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_doi);
474 my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
475 if (scalar @orphaned_ids) {
476 # clean up delivery_order_items
477 $query = sprintf 'DELETE FROM delivery_order_items WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
478 do_query($form, $dbh, $query, @orphaned_ids);
481 $h_item_stock->finish();
484 # reqdate is last items reqdate (?: old behaviour) if not already set
485 $form->{reqdate} ||= $items_reqdate;
488 qq|UPDATE delivery_orders SET
489 donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
490 customer_id = ?, reqdate = ?,
491 shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
492 delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
493 globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
494 is_sales = ?, taxzone_id = ?, taxincluded = ?, payment_id = ?, currency_id = (SELECT id FROM currencies WHERE name = ?),
498 @values = ($form->{donumber}, $form->{ordnumber},
499 $form->{cusordnumber}, conv_date($form->{transdate}),
500 conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
501 conv_date($form->{reqdate}), $form->{shippingpoint}, $form->{shipvia},
502 $restricter->process($form->{notes}), $form->{intnotes},
503 $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
504 conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
505 conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
506 conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
507 $form->{transaction_description},
508 $form->{type} =~ /^sales/ ? 't' : 'f',
509 conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{payment_id}), $form->{currency},
510 conv_i($form->{delivery_term_id}),
511 conv_i($form->{id}));
512 do_query($form, $dbh, $query, @values);
514 $form->new_lastmtime('delivery_orders');
516 $form->{name} = $form->{ $form->{vc} };
517 $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
520 if (!$form->{shipto_id}) {
521 $form->add_shipto($dbh, $form->{id}, "DO");
524 # save printed, emailed, queued
525 $form->save_status($dbh);
527 # Link this delivery order to the quotations it was created from.
528 RecordLinks->create_links('dbh' => $dbh,
530 'from_table' => 'oe',
531 'from_ids' => $form->{convert_from_oe_ids},
532 'to_table' => 'delivery_orders',
533 'to_id' => $form->{id},
535 delete $form->{convert_from_oe_ids};
537 $self->mark_orders_if_delivered('do_id' => $form->{id},
538 'type' => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
541 my $rc = $dbh->commit();
543 $form->{saved_donumber} = $form->{donumber};
544 $form->{saved_ordnumber} = $form->{ordnumber};
545 $form->{saved_cusordnumber} = $form->{cusordnumber};
547 Common::webdav_folder($form);
549 $main::lxdebug->leave_sub();
554 sub mark_orders_if_delivered {
555 $main::lxdebug->enter_sub();
560 Common::check_params(\%params, qw(do_id type));
562 my $myconfig = \%main::myconfig;
563 my $form = $main::form;
565 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
567 my %ship = $self->get_shipped_qty('dbh' => $dbh, 'do_id' => $form->{id}, 'delivered' => 1);
569 foreach my $oe_id (keys %ship) {
570 do_query($form, $dbh,"UPDATE oe SET delivered = ".($ship{$oe_id}->{delivered}?"TRUE":"FALSE")." WHERE id = ?", $oe_id);
572 $dbh->commit() if (!$params{dbh});
574 $main::lxdebug->leave_sub();
578 $main::lxdebug->enter_sub();
583 Common::check_params(\%params, qw(ids));
585 if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
586 $main::lxdebug->leave_sub();
590 my $myconfig = \%main::myconfig;
591 my $form = $main::form;
593 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
595 my $query = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
597 do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
599 $dbh->commit() unless ($params{dbh});
600 $form->new_lastmtime('delivery_orders');
602 $main::lxdebug->leave_sub();
606 $main::lxdebug->enter_sub();
610 my $myconfig = \%main::myconfig;
611 my $form = $main::form;
612 my $spool = $::lx_office_conf{paths}->{spool};
614 my $rc = SL::DB::Order->new->db->with_transaction(sub {
615 my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $form->{id} ]) };
617 SL::DB::DeliveryOrder->new(id => $form->{id})->delete;
619 my $spool = $::lx_office_conf{paths}->{spool};
620 unlink map { "$spool/$_" } @spoolfiles if $spool;
625 $main::lxdebug->leave_sub();
631 $main::lxdebug->enter_sub();
636 my $myconfig = \%main::myconfig;
637 my $form = $main::form;
639 # connect to database
640 my $dbh = $form->get_standard_dbh($myconfig);
642 my ($query, $query_add, @values, $sth, $ref);
644 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
647 my $vc = $params{vc} eq 'customer' ? 'customer' : 'vendor';
649 my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
651 if ($mode eq 'default') {
652 $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate|);
653 map { $form->{$_} = $ref->{$_} } keys %$ref;
655 # if reqdate is not set from oe-workflow, set it to transdate (which is current date)
656 $form->{reqdate} ||= $form->{transdate};
659 $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
661 $main::lxdebug->leave_sub();
666 my @do_ids = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
667 my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
669 # retrieve order for single id
670 # NOTE: this query is intended to fetch all information only ONCE.
671 # so if any of these infos is important (or even different) for any item,
672 # it will be killed out and then has to be fetched from the item scope query further down
674 qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
675 dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
676 e.name AS employee, dord.employee_id, dord.salesman_id,
677 dord.${vc}_id, cv.name AS ${vc},
678 dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
679 d.description AS department, dord.language_id,
681 dord.itime, dord.mtime,
682 dord.globalproject_id, dord.delivered, dord.transaction_description,
683 dord.taxzone_id, dord.taxincluded, dord.payment_id, (SELECT cu.name FROM currencies cu WHERE cu.id=dord.currency_id) AS currency,
684 dord.delivery_term_id, dord.itime::DATE AS insertdate
685 FROM delivery_orders dord
686 JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
687 LEFT JOIN employee e ON (dord.employee_id = e.id)
688 LEFT JOIN department d ON (dord.department_id = d.id)
689 WHERE dord.id IN ($do_ids_placeholders)|;
690 $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
692 delete $form->{"${vc}_id"};
694 $form->{ordnumber_array} = ' ';
695 $form->{cusordnumber_array} = ' ';
696 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
697 if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
699 $main::lxdebug->leave_sub();
704 map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
705 $form->{donumber_array} .= $form->{donumber} . ' ';
706 $pos = index($form->{ordnumber_array},' ' . $form->{ordnumber} . ' ');
708 $form->{ordnumber_array} .= $form->{ordnumber} . ' ';
710 $pos = index($form->{cusordnumber_array},' ' . $form->{cusordnumber} . ' ');
712 $form->{cusordnumber_array} .= $form->{cusordnumber} . ' ';
716 $form->{mtime} ||= $form->{itime};
717 $form->{lastmtime} = $form->{mtime};
718 $form->{donumber_array} =~ s/\s*$//g;
719 $form->{ordnumber_array} =~ s/ //;
720 $form->{ordnumber_array} =~ s/\s*$//g;
721 $form->{cusordnumber_array} =~ s/ //;
722 $form->{cusordnumber_array} =~ s/\s*$//g;
724 $form->{saved_donumber} = $form->{donumber};
725 $form->{saved_ordnumber} = $form->{ordnumber};
726 $form->{saved_cusordnumber} = $form->{cusordnumber};
728 # if not given, fill transdate with current_date
729 $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
731 if ($mode eq 'single') {
732 $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
733 $sth = prepare_execute_query($form, $dbh, $query, $form->{id});
735 $ref = $sth->fetchrow_hashref("NAME_lc");
737 map { $form->{$_} = $ref->{$_} } keys %$ref;
740 if ($form->{shipto_id}) {
741 my $cvars = CVar->get_custom_variables(
744 trans_id => $form->{shipto_id},
746 $form->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
749 # get printed, emailed and queued
750 $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
751 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
753 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
754 $form->{printed} .= "$ref->{formname} " if $ref->{printed};
755 $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
756 $form->{queued} .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
759 map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
765 # retrieve individual items
766 # this query looks up all information about the items
767 # stuff different from the whole will not be overwritten, but saved with a suffix.
769 qq|SELECT doi.id AS delivery_order_items_id,
770 p.partnumber, p.assembly, p.listprice, doi.description, doi.qty,
771 doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.notes AS partnotes,
772 doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
773 doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
774 doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
775 doi.active_price_source, doi.active_discount_source,
776 pr.projectnumber, dord.transdate AS dord_transdate, dord.donumber,
778 FROM delivery_order_items doi
779 JOIN parts p ON (doi.parts_id = p.id)
780 JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
781 LEFT JOIN project pr ON (doi.project_id = pr.id)
782 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
783 WHERE doi.delivery_order_id IN ($do_ids_placeholders)
784 ORDER BY doi.delivery_order_id, doi.position|;
786 $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
788 # Retrieve custom variables.
789 foreach my $doi (@{ $form->{form_details} }) {
790 my $cvars = CVar->get_custom_variables(dbh => $dbh,
792 sub_module => 'delivery_order_items',
793 trans_id => $doi->{delivery_order_items_id},
795 map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
798 if ($mode eq 'single') {
799 my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
802 qq|SELECT id as delivery_order_items_stock_id, qty, unit, bin_id,
803 warehouse_id, chargenumber, bestbefore
804 FROM delivery_order_items_stock
805 WHERE delivery_order_item_id = ?|;
806 my $sth = prepare_query($form, $dbh, $query);
808 foreach my $doi (@{ $form->{form_details} }) {
809 do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
811 while (my $ref = $sth->fetchrow_hashref()) {
812 push @{ $requests }, $ref;
815 $doi->{"stock_${in_out}"} = YAML::Dump($requests);
821 Common::webdav_folder($form);
823 $main::lxdebug->leave_sub();
829 $main::lxdebug->enter_sub();
831 my ($self, $myconfig, $form) = @_;
833 # connect to database
834 my $dbh = $form->get_standard_dbh($myconfig);
843 my $subtotal_header = 0;
849 push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
851 # sort items by partsgroup
852 for $i (1 .. $form->{rowcount}) {
854 if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
855 $partsgroup = $form->{"partsgroup_$i"};
857 push @partsgroup, [$i, $partsgroup];
858 push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
864 $projects = SL::DB::Manager::Project->get_all(query => [ id => \@project_ids ]);
865 %projects_by_id = map { $_->id => $_ } @$projects;
868 if ($projects_by_id{$form->{"globalproject_id"}}) {
869 $form->{globalprojectnumber} = $projects_by_id{$form->{"globalproject_id"}}->projectnumber;
870 $form->{globalprojectdescription} = $projects_by_id{$form->{"globalproject_id"}}->description;
872 for (@{ $projects_by_id{$form->{"globalproject_id"}}->cvars_by_config }) {
873 $form->{"project_cvar_" . $_->config->name} = $_->value_as_text;
877 my $q_pg = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
879 JOIN parts p ON (a.parts_id = p.id)
880 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
883 my $h_pg = prepare_query($form, $dbh, $q_pg);
885 my $q_bin_wh = qq|SELECT (SELECT description FROM bin WHERE id = ?) AS bin,
886 (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
887 my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
889 my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
893 my $ic_cvar_configs = CVar->get_configs(module => 'IC');
894 my $project_cvar_configs = CVar->get_configs(module => 'Projects');
896 # get some values of parts from db on store them in extra array,
897 # so that they can be sorted in later
898 my %prepared_template_arrays = IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
899 my @prepared_arrays = keys %prepared_template_arrays;
901 $form->{TEMPLATE_ARRAYS} = { };
904 qw(runningnumber number description longdescription qty qty_nofmt unit
905 partnotes serialnumber reqdate projectnumber projectdescription
906 weight weight_nofmt lineweight lineweight_nofmt
907 si_runningnumber si_number si_description
908 si_warehouse si_bin si_chargenumber si_bestbefore
909 si_qty si_qty_nofmt si_unit);
911 map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays, @prepared_arrays);
913 push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
914 push @arrays, map { "project_cvar_$_->{name}" } @{ $project_cvar_configs };
916 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
917 my %price_factors = map { $_->{id} => $_->{factor} *1 } @{ $form->{ALL_PRICE_FACTORS} };
921 foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
924 next if (!$form->{"id_$i"});
926 if ($item->[1] ne $sameitem) {
927 push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type} }, 'partsgroup');
928 push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, qq|$item->[1]|);
929 $sameitem = $item->[1];
931 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
932 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
936 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
938 # add number, description and qty to $form->{number}, ....
939 if ($form->{"subtotal_$i"} && !$subtotal_header) {
940 $subtotal_header = $i;
941 $position = int($position);
944 } elsif ($subtotal_header) {
946 $position = int($position);
947 $position = $position.".".$subposition;
949 $position = int($position);
955 my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
956 my $project = $projects_by_id{$form->{"project_id_$i"}} || SL::DB::Project->new;
958 push(@{ $form->{TEMPLATE_ARRAYS}{$_} }, $prepared_template_arrays{$_}[$i - 1]) for @prepared_arrays;
960 push @{ $form->{TEMPLATE_ARRAYS}{entry_type} }, 'normal';
961 push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} }, $position;
962 push @{ $form->{TEMPLATE_ARRAYS}{number} }, $form->{"partnumber_$i"};
963 push @{ $form->{TEMPLATE_ARRAYS}{description} }, $form->{"description_$i"};
964 push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
965 push @{ $form->{TEMPLATE_ARRAYS}{qty} }, $form->format_amount($myconfig, $form->{"qty_$i"});
966 push @{ $form->{TEMPLATE_ARRAYS}{qty_nofmt} }, $form->{"qty_$i"};
967 push @{ $form->{TEMPLATE_ARRAYS}{unit} }, $form->{"unit_$i"};
968 push @{ $form->{TEMPLATE_ARRAYS}{partnotes} }, $form->{"partnotes_$i"};
969 push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} }, $form->{"serialnumber_$i"};
970 push @{ $form->{TEMPLATE_ARRAYS}{reqdate} }, $form->{"reqdate_$i"};
971 push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} }, $project->projectnumber;
972 push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} }, $project->description;
974 if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
975 $subtotal_header = 0;
978 my $lineweight = $form->{"qty_$i"} * $form->{"weight_$i"};
979 $totalweight += $lineweight;
980 push @{ $form->{TEMPLATE_ARRAYS}->{weight} }, $form->format_amount($myconfig, $form->{"weight_$i"}, 3);
981 push @{ $form->{TEMPLATE_ARRAYS}->{weight_nofmt} }, $form->{"weight_$i"};
982 push @{ $form->{TEMPLATE_ARRAYS}->{lineweight} }, $form->format_amount($myconfig, $lineweight, 3);
983 push @{ $form->{TEMPLATE_ARRAYS}->{lineweight_nofmt} }, $lineweight;
985 my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
987 foreach my $si (@{ $stock_info }) {
990 do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
991 my $bin_wh = $h_bin_wh->fetchrow_hashref();
993 push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$si_position-1] }, $num_si;
994 push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$si_position-1] }, $form->{"partnumber_$i"};
995 push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$si_position-1] }, $form->{"description_$i"};
996 push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$si_position-1] }, $bin_wh->{warehouse};
997 push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$si_position-1] }, $bin_wh->{bin};
998 push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$si_position-1] }, $si->{chargenumber};
999 push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$si_position-1] }, $si->{bestbefore};
1000 push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$si_position-1] }, $form->format_amount($myconfig, $si->{qty} * 1);
1001 push @{ $form->{TEMPLATE_ARRAYS}{si_qty_nofmt}[$si_position-1] }, $si->{qty} * 1;
1002 push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$si_position-1] }, $si->{unit};
1005 if ($form->{"assembly_$i"}) {
1008 # get parts and push them onto the stack
1010 if ($form->{groupitems}) {
1012 qq|ORDER BY pg.partsgroup, a.oid|;
1014 $sortorder = qq|ORDER BY a.oid|;
1017 do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
1019 while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
1020 if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
1021 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
1022 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
1023 $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
1024 push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type} }, 'assembly-item-partsgroup');
1025 push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
1029 push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type} }, 'assembly-item');
1030 push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
1031 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
1032 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
1037 CVar->get_non_editable_ic_cvars(form => $form,
1040 sub_module => 'delivery_order_items',
1041 may_converted_from => ['orderitems', 'delivery_order_items']);
1043 push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
1044 CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
1045 for @{ $ic_cvar_configs };
1047 push @{ $form->{TEMPLATE_ARRAYS}->{"project_cvar_" . $_->config->name} }, $_->value_as_text for @{ $project->cvars_by_config };
1050 $form->{totalweight} = $form->format_amount($myconfig, $totalweight, 3);
1051 $form->{totalweight_nofmt} = $totalweight;
1052 my $defaults = AM->get_defaults();
1053 $form->{weightunit} = $defaults->{weightunit};
1056 $h_bin_wh->finish();
1058 $form->{department} = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
1059 $form->{delivery_term} = SL::DB::Manager::DeliveryTerm->find_by(id => $form->{delivery_term_id} || undef);
1060 $form->{delivery_term}->description_long($form->{delivery_term}->translated_attribute('description_long', $form->{language_id})) if $form->{delivery_term} && $form->{language_id};
1062 $form->{username} = $myconfig->{name};
1064 $main::lxdebug->leave_sub();
1067 sub project_description {
1068 $main::lxdebug->enter_sub();
1070 my ($self, $dbh, $id) = @_;
1072 my $form = $main::form;
1074 my $query = qq|SELECT description FROM project WHERE id = ?|;
1075 my ($value) = selectrow_query($form, $dbh, $query, $id);
1077 $main::lxdebug->leave_sub();
1082 sub unpack_stock_information {
1083 $main::lxdebug->enter_sub();
1088 Common::check_params_x(\%params, qw(packed));
1092 eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
1094 $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
1096 foreach my $entry (@{ $unpacked }) {
1097 next if ('HASH' eq ref $entry);
1102 $main::lxdebug->leave_sub();
1107 sub get_item_availability {
1108 $::lxdebug->enter_sub;
1113 Common::check_params(\%params, qw(parts_id));
1115 my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
1118 qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
1119 w.description AS warehousedescription,
1120 b.description AS bindescription
1122 LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
1123 LEFT JOIN bin b ON (i.bin_id = b.id)
1124 WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
1125 GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
1127 ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
1129 my $contents = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, @parts_ids);
1131 $::lxdebug->leave_sub;
1133 return @{ $contents };
1137 sub check_stock_availability {
1138 $main::lxdebug->enter_sub();
1143 Common::check_params(\%params, qw(requests parts_id));
1145 my $myconfig = \%main::myconfig;
1146 my $form = $main::form;
1148 my $dbh = $form->get_standard_dbh($myconfig);
1150 my $units = AM->retrieve_units($myconfig, $form);
1152 my ($partunit) = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
1153 my $unit_factor = $units->{$partunit}->{factor} || 1;
1155 my @contents = $self->get_item_availability(%params);
1159 foreach my $sinfo (@{ $params{requests} }) {
1162 foreach my $row (@contents) {
1163 next if (($row->{bin_id} != $sinfo->{bin_id}) ||
1164 ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
1165 ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
1166 ($row->{bestbefore} ne $sinfo->{bestbefore}));
1170 my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
1172 if ($base_qty > $row->{qty}) {
1173 $sinfo->{error} = 1;
1174 push @errors, $sinfo;
1180 push @errors, $sinfo if (!$found);
1183 $main::lxdebug->leave_sub();
1188 sub transfer_in_out {
1189 $main::lxdebug->enter_sub();
1194 Common::check_params(\%params, qw(direction requests));
1196 if (!@{ $params{requests} }) {
1197 $main::lxdebug->leave_sub();
1201 my $myconfig = \%main::myconfig;
1202 my $form = $main::form;
1204 my $prefix = $params{direction} eq 'in' ? 'dst' : 'src';
1208 foreach my $request (@{ $params{requests} }) {
1210 'parts_id' => $request->{parts_id},
1211 "${prefix}_warehouse_id" => $request->{warehouse_id},
1212 "${prefix}_bin_id" => $request->{bin_id},
1213 'chargenumber' => $request->{chargenumber},
1214 'bestbefore' => $request->{bestbefore},
1215 'qty' => $request->{qty},
1216 'unit' => $request->{unit},
1217 'oe_id' => $form->{id},
1218 'shippingdate' => 'current_date',
1219 'transfer_type' => $params{direction} eq 'in' ? 'stock' : 'shipped',
1220 'project_id' => $request->{project_id},
1221 'delivery_order_items_stock_id' => $request->{delivery_order_items_stock_id},
1222 'comment' => $request->{comment},
1226 WH->transfer(@transfers);
1228 $main::lxdebug->leave_sub();
1232 sub get_shipped_qty {
1233 $main::lxdebug->enter_sub();
1236 # $params{oe_id} : Alle Lieferscheine zu diesem Auftrag durchsuchen und pro Auftragsposition die Mengen zurückgeben
1237 # Wird zur Darstellung der gelieferten Mengen im Auftrag benötigt
1238 # $params{do_id} : Alle Aufträge zu diesem Lieferschein durchsuchen und pro Lieferscheinposition die Mengen zurückgeben
1239 # Wird für LaTeX benötigt um im Lieferschein pro Position die Mengen auszugeben
1240 # $params{delivered}: Alle Aufträge zum Lieferschein $params{do_id} prüfen ob sie vollständiger ausgeliefert sind
1241 # Wird für das Setzen des 'delivered' Flag in der Datenbank beim "save" des Lieferscheins benötigt
1246 # Eigentlich unkritisch: wenn keine der Parameter gesetzt ist kommt ein leerer Hash zurück
1247 croak ("Need at least one parameter oe_id or do_id") unless $params{oe_id} || $params{do_id};
1249 my $myconfig = \%main::myconfig;
1250 my $form = $main::form;
1251 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1256 if ($params{oe_id} ) {
1257 push @oe_ids, $params{oe_id};
1258 } elsif ($params{do_id}) {
1259 my @links = RecordLinks->get_links( 'dbh' => $dbh,
1260 'from_table' => 'oe',
1261 'to_table' => 'delivery_orders',
1262 'to_id' => $params{do_id});
1264 @oe_ids = map { $_->{from_id} } @links;
1267 if (scalar (@oe_ids) > 0 ) {
1268 my $all_units = AM->retrieve_all_units();
1269 my $placeholders = join(', ', ('?') x scalar @oe_ids);
1270 my $query = qq|SELECT oi.id, oi.position, oi.parts_id, oi.qty, oi.unit, oi.trans_id,
1271 p.unit AS partunit FROM orderitems oi
1272 LEFT JOIN parts p ON (oi.parts_id = p.id)
1273 WHERE trans_id IN (${placeholders})
1274 ORDER BY position ASC|;
1276 my $orderitems = selectall_hashref_query($form, $dbh, $query, @oe_ids);
1277 foreach my $oe_entry (@{ $orderitems }) {
1278 $oe_entry->{qty} *= AM->convert_unit($oe_entry->{unit}, $oe_entry->{partunit}, $all_units);
1279 $oe_entry->{qty_notdelivered} = $oe_entry->{qty};
1281 # Bei oe Modus auf jeden Fall einen Record anlegen
1282 if ( $params{oe_id} ) {
1283 $ship{$oe_entry->{position}} = {
1284 'qty_ordered' => $oe_entry->{qty} ,
1285 'qty_notdelivered' => $oe_entry->{qty}
1290 my @dolinks = RecordLinks->get_links('dbh' => $dbh,
1291 'from_table' => 'oe',
1292 'to_table' => 'delivery_orders',
1293 'from_id' => @oe_ids);
1295 my @do_ids = map { $_->{to_id} } @dolinks ;
1296 if (scalar (@do_ids) == 0) {
1297 $main::lxdebug->leave_sub();
1301 my %oeitems_by_id = map { $_->{id} => $_ } @{ $orderitems };
1304 $placeholders = join(', ', ('?') x scalar @do_ids);
1305 $query = qq|SELECT doi.parts_id, doi.id, doi.qty, doi.unit, doi.position,
1306 doi.delivery_order_id, COALESCE(rlitem.from_id,0) as from_id,
1308 FROM delivery_order_items doi
1309 LEFT JOIN parts p ON (doi.parts_id = p.id)
1310 LEFT JOIN record_links rlitem
1311 ON (rlitem.to_id = doi.id AND rlitem.to_table='delivery_order_items')
1312 WHERE doi.delivery_order_id IN (${placeholders})|;
1314 my $deliveryorderitems = selectall_hashref_query($form, $dbh, $query, @do_ids);
1316 # erst mal qty der links bearbeiten
1317 foreach my $do_entry (@{ $deliveryorderitems }) {
1318 $do_entry->{qty} *= AM->convert_unit($do_entry->{unit}, $do_entry->{partunit}, $all_units);
1319 if ($do_entry->{from_id} > 0 ) {
1320 # record link zwischen items vorhanden, kann auch von anderem Auftrag sein
1321 my $oe_entry = $oeitems_by_id{$do_entry->{from_id}};
1323 $oe_entry->{qty_notdelivered} -= $do_entry->{qty};
1324 # derzeit nur ein link pro do_item
1325 $do_entry->{oe_entry} = $oe_entry;
1328 $main::lxdebug->message(LXDebug->DEBUG2(),"no entry for=".$do_entry->{id}." part=".$do_entry->{parts_id});
1331 # nun den rest ohne links bearbeiten
1332 foreach my $do_entry (@{ $deliveryorderitems }) {
1333 next if $do_entry->{from_id} > 0;
1334 next if $do_entry->{qty} == 0;
1336 foreach my $oe_entry (@{ $orderitems }) {
1337 next if $oe_entry->{qty_notdelivered} == 0;
1338 if ( $do_entry->{parts_id} == $oe_entry->{parts_id} ) {
1339 # zu viele geliefert auf andere position ?
1340 if ( $oe_entry->{qty_notdelivered} < 0 ) {
1341 $do_entry->{qty} += - $oe_entry->{qty_notdelivered};
1342 $oe_entry->{qty_notdelivered} = 0;
1344 if ( $do_entry->{qty} < $oe_entry->{qty_notdelivered} ) {
1345 $oe_entry->{qty_notdelivered} -= $do_entry->{qty};
1346 $do_entry->{qty} = 0;
1348 $do_entry->{qty} -= $oe_entry->{qty_notdelivered};
1349 $oe_entry->{qty_notdelivered} = 0;
1351 # derzeit nur ein link pro do_item
1352 $do_entry->{oe_entry} = $oe_entry if !$do_entry->{oe_entry};
1355 last if $do_entry->{qty} <= 0;
1358 if ( $params{oe_id} ) {
1359 $ship{$_->{position}}->{qty_notdelivered} = $_->{qty_notdelivered} for @{ $orderitems };
1361 elsif ($params{do_id} && $params{delivered}) {
1362 foreach my $oe_entry (@{ $orderitems }) {
1363 if ( !$ship{$oe_entry->{trans_id}} ) {
1364 $ship{$oe_entry->{trans_id}} = { 'delivered' => 1 };
1366 $ship{$oe_entry->{trans_id}}->{delivered} = 0 if $oe_entry->{qty_notdelivered} > 0;
1369 elsif ($params{do_id}) {
1370 foreach my $do_entry (@{ $deliveryorderitems }) {
1371 next if $params{do_id} != $do_entry->{delivery_order_id};
1372 my $position = $do_entry->{position};
1373 if ( $position > 0 && $do_entry->{oe_entry}) {
1374 if ( !$ship{$position} ) {
1375 $ship{$position} = {
1376 'qty_ordered' => $do_entry->{oe_entry}->{qty} ,
1377 'qty_notdelivered' => $do_entry->{oe_entry}->{qty_notdelivered}
1380 $ship{$position}->{qty_ordered} += $do_entry->{oe_entry}->{qty};
1381 $ship{$position}->{qty_notdelivered} += $do_entry->{oe_entry}->{qty_notdelivered};
1387 $main::lxdebug->leave_sub();
1391 sub is_marked_as_delivered {
1392 $main::lxdebug->enter_sub();
1397 Common::check_params(\%params, qw(id));
1399 my $myconfig = \%main::myconfig;
1400 my $form = $main::form;
1402 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1404 my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
1406 $main::lxdebug->leave_sub();
1408 return $delivered ? 1 : 0;