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., 51 Franklin Street, Fifth Floor, Boston,
30 #======================================================================
32 # Delivery Order entry module
33 #======================================================================
38 use List::Util qw(max);
44 use SL::DB::DeliveryOrder;
45 use SL::DB::DeliveryOrder::TypeData qw(:types is_valid_type);
47 use SL::DB::ValidityToken;
49 use SL::Helper::ShippedQty;
50 use SL::HTML::Restrict;
55 use SL::Util qw(trim);
61 $main::lxdebug->enter_sub();
65 my $myconfig = \%main::myconfig;
66 my $form = $main::form;
69 my $dbh = $form->get_standard_dbh($myconfig);
73 my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
75 $form->{l_order_confirmation_number} = 'Y' if $form->{order_confirmation_number};
78 qq|SELECT dord.id, dord.donumber, dord.ordnumber, dord.cusordnumber,
79 dord.transdate, dord.reqdate,
80 dord.vendor_confirmation_number,
81 ct.${vc}number, ct.name, ct.business_id,
82 dord.${vc}_id, dord.globalproject_id,
83 dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
84 dord.transaction_description, dord.itime::DATE AS insertdate,
85 pr.projectnumber AS globalprojectnumber,
86 dep.description AS department,
90 FROM delivery_orders dord
91 LEFT JOIN $vc ct ON (dord.${vc}_id = ct.id)
92 LEFT JOIN contacts cp ON (dord.cp_id = cp.cp_id)
93 LEFT JOIN employee e ON (dord.employee_id = e.id)
94 LEFT JOIN employee sm ON (dord.salesman_id = sm.id)
95 LEFT JOIN project pr ON (dord.globalproject_id = pr.id)
96 LEFT JOIN department dep ON (dord.department_id = dep.id)
99 if ($form->{type} && is_valid_type($form->{type})) {
100 push @where, 'dord.record_type = ?';
101 push @values, $form->{type};
104 if ($form->{department_id}) {
105 push @where, qq|dord.department_id = ?|;
106 push @values, conv_i($form->{department_id});
109 if ($form->{project_id}) {
111 qq|(dord.globalproject_id = ?) OR EXISTS
112 (SELECT * FROM delivery_order_items doi
113 WHERE (doi.project_id = ?) AND (doi.delivery_order_id = dord.id))|;
114 push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
117 if ($form->{"business_id"}) {
118 push @where, qq|ct.business_id = ?|;
119 push @values, conv_i($form->{"business_id"});
122 if ($form->{"${vc}_id"}) {
123 push @where, qq|dord.${vc}_id = ?|;
124 push @values, $form->{"${vc}_id"};
126 } elsif ($form->{$vc}) {
127 push @where, qq|ct.name ILIKE ?|;
128 push @values, like($form->{$vc});
131 if ($form->{"cp_name"}) {
132 push @where, "(cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
133 push @values, (like($form->{"cp_name"}))x2;
136 foreach my $item (qw(employee_id salesman_id)) {
137 next unless ($form->{$item});
138 push @where, "dord.$item = ?";
139 push @values, conv_i($form->{$item});
141 if ( !( ($vc eq 'customer' && ($main::auth->assert('sales_all_edit', 1) || $main::auth->assert('sales_delivery_order_view', 1)))
142 || ($vc eq 'vendor' && ($main::auth->assert('purchase_all_edit', 1) || $main::auth->assert('purchase_delivery_order_view', 1))) ) ) {
143 push @where, qq|dord.employee_id = (select id from employee where login= ?)|;
144 push @values, $::myconfig{login};
147 foreach my $item (qw(donumber ordnumber cusordnumber transaction_description vendor_confirmation_number)) {
148 next unless ($form->{$item});
149 push @where, qq|dord.$item ILIKE ?|;
150 push @values, like($form->{$item});
153 if ($form->{order_confirmation_number}) {
154 push @where, qq|(EXISTS (SELECT id FROM oe
155 WHERE ordnumber ILIKE ?
156 AND record_type = 'purchase_order_confirmation'
158 (SELECT from_id FROM record_links
159 WHERE to_id = dord.id
160 AND to_table = 'delivery_orders'
161 AND from_table = 'oe')
163 push @values, like($form->{order_confirmation_number});
166 if (($form->{open} || $form->{closed}) &&
167 ($form->{open} ne $form->{closed})) {
168 push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
171 if (($form->{notdelivered} || $form->{delivered}) &&
172 ($form->{notdelivered} ne $form->{delivered})) {
173 push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
176 if ($form->{serialnumber}) {
177 push @where, 'dord.id IN (SELECT doi.delivery_order_id FROM delivery_order_items doi WHERE doi.serialnumber LIKE ?)';
178 push @values, like($form->{serialnumber});
181 if($form->{transdatefrom}) {
182 push @where, qq|dord.transdate >= ?|;
183 push @values, conv_date($form->{transdatefrom});
186 if($form->{transdateto}) {
187 push @where, qq|dord.transdate <= ?|;
188 push @values, conv_date($form->{transdateto});
191 if($form->{reqdatefrom}) {
192 push @where, qq|dord.reqdate >= ?|;
193 push @values, conv_date($form->{reqdatefrom});
196 if($form->{reqdateto}) {
197 push @where, qq|dord.reqdate <= ?|;
198 push @values, conv_date($form->{reqdateto});
201 if($form->{insertdatefrom}) {
202 push @where, qq|dord.itime::DATE >= ?|;
203 push@values, conv_date($form->{insertdatefrom});
206 if($form->{insertdateto}) {
207 push @where, qq|dord.itime::DATE <= ?|;
208 push @values, conv_date($form->{insertdateto});
211 $form->{fulltext} = trim($form->{fulltext});
212 if ($form->{fulltext}) {
213 my @fulltext_fields = qw(dord.notes
217 dord.transaction_description
222 dord.vendor_confirmation_number
226 $tmp_where .= join ' OR ', map {"$_ ILIKE ?"} @fulltext_fields;
227 push(@values, like($form->{fulltext})) for 1 .. (scalar @fulltext_fields);
231 SELECT files.id FROM files LEFT JOIN file_full_texts ON (file_full_texts.file_id = files.id)
232 WHERE files.object_id = dord.id AND files.object_type = ?
233 AND file_full_texts.full_text ILIKE ?)
235 push(@values, $form->{type});
236 push(@values, like($form->{fulltext}));
237 push @where, $tmp_where;
241 if ($form->{parts_partnumber}) {
244 SELECT delivery_order_items.delivery_order_id
245 FROM delivery_order_items
246 LEFT JOIN parts ON (delivery_order_items.parts_id = parts.id)
247 WHERE (delivery_order_items.delivery_order_id = dord.id)
248 AND (parts.partnumber ILIKE ?)
252 push @values, like($form->{parts_partnumber});
255 if ($form->{parts_description}) {
258 SELECT delivery_order_items.delivery_order_id
259 FROM delivery_order_items
260 WHERE (delivery_order_items.delivery_order_id = dord.id)
261 AND (delivery_order_items.description ILIKE ?)
265 push @values, like($form->{parts_description});
268 if ($form->{chargenumber}) {
271 SELECT delivery_order_items_stock.id
272 FROM delivery_order_items_stock
273 LEFT JOIN delivery_order_items ON (delivery_order_items.id = delivery_order_items_stock.delivery_order_item_id)
274 WHERE delivery_order_items.delivery_order_id = dord.id
275 AND delivery_order_items_stock.chargenumber ILIKE ?
279 push @values, like($form->{chargenumber});
283 unshift @{$form->{ids}}, 0; # no error and no results if no ids are given
284 my $placeholders = join(', ', ('?') x scalar(@{$form->{ids}}));
285 push @where, "dord.id IN ($placeholders)";
286 push @values, @{$form->{ids}};
290 my @tokens = parse_line('\s+', 0, $form->{all});
291 # ordnumber quonumber customer.name vendor.name transaction_description
292 push @where, <<SQL for @tokens;
293 ( (dord.donumber ILIKE ?)
295 OR (dord.transaction_description ILIKE ?))
297 push @values, (like($_))x3 for @tokens;
301 $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
304 my %allowed_sort_columns = (
305 "transdate" => "dord.transdate",
306 "reqdate" => "dord.reqdate",
308 "donumber" => "dord.donumber",
309 "ordnumber" => "dord.ordnumber",
311 "employee" => "e.name",
312 "salesman" => "sm.name",
313 "shipvia" => "dord.shipvia",
314 "transaction_description" => "dord.transaction_description",
315 "department" => "lower(dep.description)",
316 "insertdate" => "dord.itime",
317 "vendor_confirmation_number" => "dord.vendor_confirmation_number",
320 my $sortdir = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
321 my $sortorder = "dord.id";
322 if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
323 $sortorder = $allowed_sort_columns{$form->{sort}};
326 $query .= qq| ORDER by | . $sortorder . " $sortdir";
328 $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
330 my $record_type = $vc eq 'customer' ? 'sales_order' : 'purchase_order';
331 if (scalar @{ $form->{DO} }) {
335 WHERE (record_type = '$record_type'
338 my $sth = prepare_query($form, $dbh, $query);
341 my ($items_query, $items_sth);
342 if ($form->{l_items}) {
345 FROM delivery_order_items
346 WHERE delivery_order_id = ?
349 $items_sth = prepare_query($form, $dbh, $items_query);
352 my ($order_confirmation_query, $order_confirmation_sth);
353 if ($form->{l_order_confirmation_number}) {
354 $order_confirmation_query =
355 qq|SELECT id, ordnumber FROM oe
357 (SELECT from_id FROM record_links
358 WHERE from_table = 'oe'
359 AND to_table = 'delivery_orders'
361 AND record_type = 'purchase_order_confirmation' ORDER BY ordnumber|;
363 $order_confirmation_sth = prepare_query($form, $dbh, $order_confirmation_query);
366 foreach my $dord (@{ $form->{DO} }) {
367 if ($form->{l_items}) {
368 do_statement($form, $items_sth, $items_query, $dord->{id});
369 $dord->{item_ids} = $dbh->selectcol_arrayref($items_sth);
370 $dord->{item_ids} = undef if !@{$dord->{item_ids}};
373 if ($form->{l_order_confirmation_number}) {
374 do_statement($form, $order_confirmation_sth, $order_confirmation_query, $dord->{id});
375 my @r = @{$order_confirmation_sth->fetchall_arrayref()};
376 push @{$dord->{order_confirmation_numbers}}, { id => $_->[0], number => $_->[1] } for @r;
379 next unless ($dord->{ordnumber});
380 do_statement($form, $sth, $query, $dord->{ordnumber});
381 ($dord->{oe_id}) = $sth->fetchrow_array();
385 $items_sth->finish() if $form->{l_items};
386 $order_confirmation_sth->finish() if $form->{l_order_confirmation_number};
389 $main::lxdebug->leave_sub();
394 $main::lxdebug->enter_sub();
396 my $rc = SL::DB->client->with_transaction(\&_save, $self);
398 $main::lxdebug->leave_sub();
403 $main::lxdebug->enter_sub();
407 my $myconfig = \%main::myconfig;
408 my $form = $main::form;
412 $validity_token = SL::DB::Manager::ValidityToken->fetch_valid_token(
413 scope => SL::DB::ValidityToken::SCOPE_DELIVERY_ORDER_SAVE(),
414 token => $form->{form_validity_token},
417 die $::locale->text('The form is not valid anymore.') if !$validity_token;
420 my $dbh = SL::DB->client->dbh;
421 my $restricter = SL::HTML::Restrict->create;
423 my ($query, @values, $sth, $null);
425 my $all_units = AM->retrieve_units($myconfig, $form);
426 $form->{all_units} = $all_units;
428 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
431 my $trans_number = SL::TransNumber->new(type => $form->{type}, dbh => $dbh, number => $form->{donumber}, id => $form->{id});
432 $form->{donumber} ||= $trans_number->create_unique;
433 $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
434 $form->get_employee($dbh) unless ($form->{employee_id});
436 my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
438 my (@processed_doi, @processed_dois);
442 # only delete shipto complete
443 $query = qq|DELETE FROM custom_variables
444 WHERE (config_id IN (SELECT id FROM custom_variable_configs WHERE (module = 'ShipTo')))
445 AND (trans_id IN (SELECT shipto_id FROM shipto WHERE (module = 'DO') AND (trans_id = ?)))|;
446 do_query($form, $dbh, $query, $form->{id});
448 $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
449 do_query($form, $dbh, $query, conv_i($form->{id}));
453 $query = qq|SELECT nextval('id')|;
454 ($form->{id}) = selectrow_query($form, $dbh, $query);
456 $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id, currency_id, taxzone_id, record_type) VALUES (?, '', ?, (SELECT currency_id FROM defaults LIMIT 1), ?, ?)|;
457 do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}), $form->{taxzone_id}, SALES_DELIVERY_ORDER_TYPE);
463 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
464 my %price_factors = map { $_->{id} => $_->{factor} *1 } @{ $form->{ALL_PRICE_FACTORS} };
467 my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
468 my @part_ids = keys %part_id_map;
472 $query = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
473 %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
476 UPDATE delivery_order_items SET
477 delivery_order_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
478 sellprice = ?, discount = ?, unit = ?, reqdate = ?, project_id = ?, serialnumber = ?,
479 lastcost = ? , price_factor_id = ?, price_factor = (SELECT factor FROM price_factors where id = ?),
480 marge_price_factor = ?, pricegroup_id = ?, active_price_source = ?, active_discount_source = ?
483 my $h_item = prepare_query($form, $dbh, $q_item);
485 my $q_item_stock = <<SQL;
486 UPDATE delivery_order_items_stock SET
487 delivery_order_item_id = ?, qty = ?, unit = ?, warehouse_id = ?,
488 bin_id = ?, chargenumber = ?, bestbefore = ?
491 my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
493 my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
495 for my $i (1 .. $form->{rowcount}) {
496 next if (!$form->{"id_$i"});
498 CVar->get_non_editable_ic_cvars(form => $form,
501 sub_module => 'delivery_order_items',
502 may_converted_from => ['orderitems', 'delivery_order_items']);
506 if (!$form->{"delivery_order_items_id_$i"}) {
507 # there is no persistent id, therefore create one with all necessary constraints
508 my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
509 my $h_item_id = prepare_query($form, $dbh, $q_item_id);
510 do_statement($form, $h_item_id, $q_item_id);
511 $form->{"delivery_order_items_id_$i"} = $h_item_id->fetchrow_array();
512 $query = qq|INSERT INTO delivery_order_items (id, delivery_order_id, position, parts_id) VALUES (?, ?, ?, ?)|;
513 do_query($form, $dbh, $query, conv_i($form->{"delivery_order_items_id_$i"}),
514 conv_i($form->{"id"}), conv_i($position), conv_i($form->{"id_$i"}));
515 $h_item_id->finish();
518 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
520 my $item_unit = $part_unit_map{$form->{"id_$i"}};
523 if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
524 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
526 my $baseqty = $form->{"qty_$i"} * $basefactor;
528 # set values to 0 if nothing entered
529 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"});
530 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
531 $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
533 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
534 my $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
536 $items_reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
539 # Get pricegroup_id and save it. Unfortunately the interface
540 # also uses ID "0" for signalling that none is selected, but "0"
541 # must not be stored in the database. Therefore we cannot simply
543 my $pricegroup_id = $form->{"pricegroup_id_$i"} * 1;
544 $pricegroup_id = undef if !$pricegroup_id;
546 # save detail record in delivery_order_items table
547 @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
548 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}),
549 $form->{"qty_$i"}, $baseqty,
550 $form->{"sellprice_$i"}, $form->{"discount_$i"} / 100,
551 $form->{"unit_$i"}, conv_date($items_reqdate), conv_i($form->{"project_id_$i"}),
552 trim($form->{"serialnumber_$i"}),
553 $form->{"lastcost_$i"},
554 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
555 conv_i($form->{"marge_price_factor_$i"}),
557 $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
558 conv_i($form->{"delivery_order_items_id_$i"}));
559 do_statement($form, $h_item, $q_item, @values);
560 push @processed_doi, $form->{"delivery_order_items_id_$i"}; # transaction safe?
562 my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
564 foreach my $sinfo (@{ $stock_info }) {
565 # if we have stock_info, we have to check for persistents entries
566 if (!$sinfo->{"delivery_order_items_stock_id"}) {
567 my $q_item_stock_id = qq|SELECT nextval('id')|;
568 my $h_item_stock_id = prepare_query($form, $dbh, $q_item_stock_id);
569 do_statement($form, $h_item_stock_id, $q_item_stock_id);
570 $sinfo->{"delivery_order_items_stock_id"} = $h_item_stock_id->fetchrow_array();
571 $query = qq|INSERT INTO delivery_order_items_stock (id, delivery_order_item_id, qty, unit, warehouse_id, bin_id)
572 VALUES (?, ?, ?, ?, ?, ?)|;
573 do_query($form, $dbh, $query, conv_i($sinfo->{"delivery_order_items_stock_id"}),
574 conv_i($form->{"delivery_order_items_id_$i"}), $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
575 conv_i($sinfo->{bin_id}));
576 $h_item_stock_id->finish();
577 # write back the id to the form (important if only transfer was clicked (id fk for invoice)
578 $form->{"stock_${in_out}_$i"} = SL::YAML::Dump($stock_info);
580 @values = ($form->{"delivery_order_items_id_$i"}, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
581 conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}),
582 conv_i($sinfo->{"delivery_order_items_stock_id"}));
583 do_statement($form, $h_item_stock, $q_item_stock, @values);
584 push @processed_dois, $sinfo->{"delivery_order_items_stock_id"};
587 CVar->save_custom_variables(module => 'IC',
588 sub_module => 'delivery_order_items',
589 trans_id => $form->{"delivery_order_items_id_$i"},
590 configs => $ic_cvar_configs,
592 name_prefix => 'ic_',
593 name_postfix => "_$i",
596 # link order items with doi, for future extension look at foreach IS.pm
597 if (!$form->{saveasnew} && $form->{"converted_from_orderitems_id_$i"}) {
598 RecordLinks->create_links('dbh' => $dbh,
600 'from_table' => 'orderitems',
601 'from_ids' => $form->{"converted_from_orderitems_id_$i"},
602 'to_table' => 'delivery_order_items',
603 'to_id' => $form->{"delivery_order_items_id_$i"},
606 delete $form->{"converted_from_orderitems_id_$i"};
609 # 1. search for orphaned dois; processed_dois may be empty (no transfer) TODO: be supersafe and alter same statement for doi and oi
610 $query = sprintf 'SELECT id FROM delivery_order_items_stock WHERE delivery_order_item_id in
611 (select id from delivery_order_items where delivery_order_id = ?)';
612 $query .= sprintf ' AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_dois if (scalar @processed_dois);
613 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_dois);
614 my @orphaned_dois_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
615 if (scalar @orphaned_dois_ids) {
616 # clean up delivery_order_items_stock
617 $query = sprintf 'DELETE FROM delivery_order_items_stock WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_dois_ids;
618 do_query($form, $dbh, $query, @orphaned_dois_ids);
620 # 2. search for orphaned doi
621 $query = sprintf 'SELECT id FROM delivery_order_items WHERE delivery_order_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_doi;
622 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_doi);
623 my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
624 if (scalar @orphaned_ids) {
625 # clean up delivery_order_items
626 $query = sprintf 'DELETE FROM delivery_order_items WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
627 do_query($form, $dbh, $query, @orphaned_ids);
630 $h_item_stock->finish();
633 # reqdate is last items reqdate (?: old behaviour) if not already set
634 $form->{reqdate} ||= $items_reqdate;
637 qq|UPDATE delivery_orders SET
638 donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
639 customer_id = ?, reqdate = ?, tax_point = ?,
640 shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
641 delivered = ?, department_id = ?, language_id = ?, shipto_id = ?, billing_address_id = ?,
642 globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
643 record_type = ?, taxzone_id = ?, taxincluded = ?, payment_id = ?, currency_id = (SELECT id FROM currencies WHERE name = ?),
647 @values = ($form->{donumber}, $form->{ordnumber},
648 $form->{cusordnumber}, conv_date($form->{transdate}),
649 conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
650 conv_date($form->{reqdate}), conv_date($form->{tax_point}), $form->{shippingpoint}, $form->{shipvia},
651 $restricter->process($form->{notes}), $form->{intnotes},
652 $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
653 conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}), conv_i($form->{billing_address_id}),
654 conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
655 conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
656 $form->{transaction_description},
657 $form->{type} =~ /^sales/ ? SALES_DELIVERY_ORDER_TYPE : PURCHASE_DELIVERY_ORDER_TYPE,
658 conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{payment_id}), $form->{currency},
659 conv_i($form->{delivery_term_id}),
660 conv_i($form->{id}));
661 do_query($form, $dbh, $query, @values);
663 $form->new_lastmtime('delivery_orders');
665 $form->{name} = $form->{ $form->{vc} };
666 $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
669 if (!$form->{shipto_id}) {
670 $form->add_shipto($dbh, $form->{id}, "DO");
673 # save printed, emailed, queued
674 $form->save_status($dbh);
676 # Link this delivery order to the quotations it was created from.
677 RecordLinks->create_links('dbh' => $dbh,
679 'from_table' => 'oe',
680 'from_ids' => $form->{convert_from_oe_ids},
681 'to_table' => 'delivery_orders',
682 'to_id' => $form->{id},
684 delete $form->{convert_from_oe_ids};
685 unless ($::instance_conf->get_shipped_qty_require_stock_out) {
686 $self->mark_orders_if_delivered('do_id' => $form->{id},
687 'type' => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase');
690 $form->{saved_donumber} = $form->{donumber};
691 $form->{saved_ordnumber} = $form->{ordnumber};
692 $form->{saved_cusordnumber} = $form->{cusordnumber};
694 Common::webdav_folder($form);
696 $validity_token->delete if $validity_token;
697 delete $form->{form_validity_token};
699 $main::lxdebug->leave_sub();
704 sub mark_orders_if_delivered {
705 my ($self, %params) = @_;
707 Common::check_params(\%params, qw(do_id type));
709 my $do = SL::DB::Manager::DeliveryOrder->find_by(id => $params{do_id});
710 my $orders = $do->linked_records(from => 'Order');
712 SL::Helper::ShippedQty->new->calculate($orders)->write_to_objects;
714 SL::DB->client->with_transaction(sub {
715 for my $oe (@$orders) {
716 next if $params{type} eq 'sales' && !$oe->customer_id;
717 next if $params{type} eq 'purchase' && !$oe->vendor_id;
719 $oe->update_attributes(delivered => $oe->{delivered});
722 }) or do { die SL::DB->client->error };
726 $main::lxdebug->enter_sub();
731 Common::check_params(\%params, qw(ids));
733 if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
734 $main::lxdebug->leave_sub();
738 my $myconfig = \%main::myconfig;
739 my $form = $main::form;
741 SL::DB->client->with_transaction(sub {
742 my $dbh = $params{dbh} || SL::DB->client->dbh;
744 my $query = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
746 do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
748 }) or die { SL::DB->client->error };
750 $form->new_lastmtime('delivery_orders');
752 $main::lxdebug->leave_sub();
756 $main::lxdebug->enter_sub();
760 my $myconfig = \%main::myconfig;
761 my $form = $main::form;
762 my $spool = $::lx_office_conf{paths}->{spool};
764 my $rc = SL::DB::Order->new->db->with_transaction(sub {
765 my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $form->{id} ]) };
767 SL::DB::DeliveryOrder->new(id => $form->{id})->delete;
769 my $spool = $::lx_office_conf{paths}->{spool};
770 unlink map { "$spool/$_" } @spoolfiles if $spool;
775 $main::lxdebug->leave_sub();
780 sub delete_transfers {
781 $main::lxdebug->enter_sub();
785 my $myconfig = \%main::myconfig;
786 my $form = $main::form;
788 my $rc = SL::DB::Order->new->db->with_transaction(sub {
790 my $do = SL::DB::DeliveryOrder->new(id => $form->{id})->load;
791 die "No valid delivery order found" unless ref $do eq 'SL::DB::DeliveryOrder';
793 my $dt = DateTime->today->subtract(days => $::instance_conf->get_undo_transfer_interval);
794 croak "Wrong call. Please check undoing interval" unless $do->itime > $dt;
796 foreach my $doi (@{ $do->orderitems }) {
797 foreach my $dois (@{ $doi->delivery_order_stock_entries}) {
798 $dois->inventory->delete;
802 $do->update_attributes(delivered => 0);
807 $main::lxdebug->leave_sub();
813 $main::lxdebug->enter_sub();
818 my $myconfig = \%main::myconfig;
819 my $form = $main::form;
821 # connect to database
822 my $dbh = $form->get_standard_dbh($myconfig);
824 my ($query, $query_add, @values, $sth, $ref);
826 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
829 my $vc = $params{vc} eq 'customer' ? 'customer' : 'vendor';
831 my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
833 if ($mode eq 'default') {
834 $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate|);
835 map { $form->{$_} = $ref->{$_} } keys %$ref;
837 # if reqdate is not set from oe-workflow, set it to transdate (which is current date)
838 $form->{reqdate} ||= $form->{transdate};
841 $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
843 $main::lxdebug->leave_sub();
848 my @do_ids = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
849 my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
851 # retrieve order for single id
852 # NOTE: this query is intended to fetch all information only ONCE.
853 # so if any of these infos is important (or even different) for any item,
854 # it will be killed out and then has to be fetched from the item scope query further down
856 qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate, dord.tax_point,
857 dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
858 e.name AS employee, dord.employee_id, dord.salesman_id,
859 dord.${vc}_id, cv.name AS ${vc},
860 dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
861 d.description AS department, dord.language_id,
862 dord.shipto_id, dord.billing_address_id,
863 dord.itime, dord.mtime,
864 dord.globalproject_id, dord.delivered, dord.transaction_description,
865 dord.taxzone_id, dord.taxincluded, dord.payment_id, (SELECT cu.name FROM currencies cu WHERE cu.id=dord.currency_id) AS currency,
866 dord.delivery_term_id, dord.itime::DATE AS insertdate
867 FROM delivery_orders dord
868 JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
869 LEFT JOIN employee e ON (dord.employee_id = e.id)
870 LEFT JOIN department d ON (dord.department_id = d.id)
871 WHERE dord.id IN ($do_ids_placeholders)|;
872 $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
874 delete $form->{"${vc}_id"};
876 $form->{ordnumber_array} = ' ';
877 $form->{cusordnumber_array} = ' ';
878 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
879 if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
881 $main::lxdebug->leave_sub();
886 map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
887 $form->{donumber_array} .= $form->{donumber} . ' ';
888 $pos = index($form->{ordnumber_array},' ' . $form->{ordnumber} . ' ');
890 $form->{ordnumber_array} .= $form->{ordnumber} . ' ';
892 $pos = index($form->{cusordnumber_array},' ' . $form->{cusordnumber} . ' ');
894 $form->{cusordnumber_array} .= $form->{cusordnumber} . ' ';
898 $form->{mtime} ||= $form->{itime};
899 $form->{lastmtime} = $form->{mtime};
900 $form->{donumber_array} =~ s/\s*$//g;
901 $form->{ordnumber_array} =~ s/ //;
902 $form->{ordnumber_array} =~ s/\s*$//g;
903 $form->{cusordnumber_array} =~ s/ //;
904 $form->{cusordnumber_array} =~ s/\s*$//g;
906 $form->{saved_donumber} = $form->{donumber};
907 $form->{saved_ordnumber} = $form->{ordnumber};
908 $form->{saved_cusordnumber} = $form->{cusordnumber};
910 # if not given, fill transdate with current_date
911 $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
913 if ($mode eq 'single') {
914 $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
915 $sth = prepare_execute_query($form, $dbh, $query, $form->{id});
917 $ref = $sth->fetchrow_hashref("NAME_lc");
918 $form->{$_} = $ref->{$_} for grep { m{^shipto(?!_id$)} } keys %$ref;
921 if ($ref->{shipto_id}) {
922 my $cvars = CVar->get_custom_variables(
925 trans_id => $ref->{shipto_id},
927 $form->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
930 # get printed, emailed and queued
931 $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
932 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
934 while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
935 $form->{printed} .= "$ref->{formname} " if $ref->{printed};
936 $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
937 $form->{queued} .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
940 map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
946 # retrieve individual items
947 # this query looks up all information about the items
948 # stuff different from the whole will not be overwritten, but saved with a suffix.
950 qq|SELECT doi.id AS delivery_order_items_id,
951 p.partnumber, p.part_type, p.listprice, doi.description, doi.qty,
952 doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.notes AS partnotes,
953 doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
954 doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
955 doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
956 doi.active_price_source, doi.active_discount_source,
957 pr.projectnumber, dord.transdate AS dord_transdate, dord.donumber,
959 FROM delivery_order_items doi
960 JOIN parts p ON (doi.parts_id = p.id)
961 JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
962 LEFT JOIN project pr ON (doi.project_id = pr.id)
963 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
964 WHERE doi.delivery_order_id IN ($do_ids_placeholders)
965 ORDER BY doi.delivery_order_id, doi.position|;
967 $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
969 # Retrieve custom variables.
970 foreach my $doi (@{ $form->{form_details} }) {
971 my $cvars = CVar->get_custom_variables(dbh => $dbh,
973 sub_module => 'delivery_order_items',
974 trans_id => $doi->{delivery_order_items_id},
976 map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
978 my $makemodel = SL::DB::Manager::MakeModel->find_by(parts_id => $doi->{id}, make =>$form->{vendor_id});
979 $doi->{vendor_partnumber} = $makemodel->model if $makemodel;
981 if ($mode eq 'single') {
982 my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
985 qq|SELECT id as delivery_order_items_stock_id, qty, unit, bin_id,
986 warehouse_id, chargenumber, bestbefore
987 FROM delivery_order_items_stock
988 WHERE delivery_order_item_id = ?|;
989 my $sth = prepare_query($form, $dbh, $query);
991 foreach my $doi (@{ $form->{form_details} }) {
992 do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
994 while (my $ref = $sth->fetchrow_hashref()) {
995 push @{ $requests }, $ref;
998 $doi->{"stock_${in_out}"} = SL::YAML::Dump($requests);
1004 Common::webdav_folder($form);
1006 $main::lxdebug->leave_sub();
1012 $main::lxdebug->enter_sub();
1014 my ($self, $myconfig, $form) = @_;
1016 # connect to database
1017 my $dbh = $form->get_standard_dbh($myconfig);
1023 my @partsgroup = ();
1026 my $subtotal_header = 0;
1027 my $subposition = 0;
1028 my $si_position = 0;
1032 push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
1034 # sort items by partsgroup
1035 for $i (1 .. $form->{rowcount}) {
1037 if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
1038 $partsgroup = $form->{"partsgroup_$i"};
1040 push @partsgroup, [$i, $partsgroup];
1041 push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
1047 $projects = SL::DB::Manager::Project->get_all(query => [ id => \@project_ids ]);
1048 %projects_by_id = map { $_->id => $_ } @$projects;
1051 if ($projects_by_id{$form->{"globalproject_id"}}) {
1052 $form->{globalprojectnumber} = $projects_by_id{$form->{"globalproject_id"}}->projectnumber;
1053 $form->{globalprojectdescription} = $projects_by_id{$form->{"globalproject_id"}}->description;
1055 for (@{ $projects_by_id{$form->{"globalproject_id"}}->cvars_by_config }) {
1056 $form->{"project_cvar_" . $_->config->name} = $_->value_as_text;
1060 my $q_pg = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
1062 JOIN parts p ON (a.parts_id = p.id)
1063 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1066 my $h_pg = prepare_query($form, $dbh, $q_pg);
1068 my $q_bin_wh = qq|SELECT (SELECT description FROM bin WHERE id = ?) AS bin,
1069 (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
1070 my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
1072 my $in_out = $form->{type} =~ /^sales|^supplier/ ? 'out' : 'in';
1076 my $ic_cvar_configs = CVar->get_configs(module => 'IC');
1077 my $project_cvar_configs = CVar->get_configs(module => 'Projects');
1079 # get some values of parts from db on store them in extra array,
1080 # so that they can be sorted in later
1081 my %prepared_template_arrays = IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
1082 my @prepared_arrays = keys %prepared_template_arrays;
1084 $form->{TEMPLATE_ARRAYS} = { };
1087 qw(runningnumber number description longdescription qty qty_nofmt unit
1088 partnotes serialnumber reqdate projectnumber projectdescription
1089 weight weight_nofmt lineweight lineweight_nofmt
1090 si_runningnumber si_number si_description
1091 si_warehouse si_bin si_chargenumber si_bestbefore
1092 si_qty si_qty_nofmt si_unit);
1094 map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays, @prepared_arrays);
1096 push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
1097 push @arrays, map { "project_cvar_$_->{name}" } @{ $project_cvar_configs };
1099 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
1100 my %price_factors = map { $_->{id} => $_->{factor} *1 } @{ $form->{ALL_PRICE_FACTORS} };
1102 my $totalweight = 0;
1104 foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
1107 next if (!$form->{"id_$i"});
1109 if ($item->[1] ne $sameitem) {
1110 push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type} }, 'partsgroup');
1111 push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, qq|$item->[1]|);
1112 $sameitem = $item->[1];
1114 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
1115 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
1119 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
1121 # add number, description and qty to $form->{number}, ....
1122 if ($form->{"subtotal_$i"} && !$subtotal_header) {
1123 $subtotal_header = $i;
1124 $position = int($position);
1127 } elsif ($subtotal_header) {
1129 $position = int($position);
1130 $position = $position.".".$subposition;
1132 $position = int($position);
1138 my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
1139 my $project = $projects_by_id{$form->{"project_id_$i"}} || SL::DB::Project->new;
1141 push(@{ $form->{TEMPLATE_ARRAYS}{$_} }, $prepared_template_arrays{$_}[$i - 1]) for @prepared_arrays;
1143 push @{ $form->{TEMPLATE_ARRAYS}{entry_type} }, 'normal';
1144 push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} }, $position;
1145 push @{ $form->{TEMPLATE_ARRAYS}{number} }, $form->{"partnumber_$i"};
1146 push @{ $form->{TEMPLATE_ARRAYS}{description} }, $form->{"description_$i"};
1147 push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
1148 push @{ $form->{TEMPLATE_ARRAYS}{qty} }, $form->format_amount($myconfig, $form->{"qty_$i"});
1149 push @{ $form->{TEMPLATE_ARRAYS}{qty_nofmt} }, $form->{"qty_$i"};
1150 push @{ $form->{TEMPLATE_ARRAYS}{unit} }, $form->{"unit_$i"};
1151 push @{ $form->{TEMPLATE_ARRAYS}{partnotes} }, $form->{"partnotes_$i"};
1152 push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} }, $form->{"serialnumber_$i"};
1153 push @{ $form->{TEMPLATE_ARRAYS}{reqdate} }, $form->{"reqdate_$i"};
1154 push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} }, $project->projectnumber;
1155 push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} }, $project->description;
1157 if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
1158 $subtotal_header = 0;
1161 my $lineweight = $form->{"qty_$i"} * $form->{"weight_$i"};
1162 $totalweight += $lineweight;
1163 push @{ $form->{TEMPLATE_ARRAYS}->{weight} }, $form->format_amount($myconfig, $form->{"weight_$i"}, 3);
1164 push @{ $form->{TEMPLATE_ARRAYS}->{weight_nofmt} }, $form->{"weight_$i"};
1165 push @{ $form->{TEMPLATE_ARRAYS}->{lineweight} }, $form->format_amount($myconfig, $lineweight, 3);
1166 push @{ $form->{TEMPLATE_ARRAYS}->{lineweight_nofmt} }, $lineweight;
1168 my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
1170 foreach my $si (@{ $stock_info }) {
1173 do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
1174 my $bin_wh = $h_bin_wh->fetchrow_hashref();
1176 push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$si_position-1] }, $num_si;
1177 push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$si_position-1] }, $form->{"partnumber_$i"};
1178 push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$si_position-1] }, $form->{"description_$i"};
1179 push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$si_position-1] }, $bin_wh->{warehouse};
1180 push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$si_position-1] }, $bin_wh->{bin};
1181 push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$si_position-1] }, $si->{chargenumber};
1182 push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$si_position-1] }, $si->{bestbefore};
1183 push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$si_position-1] }, $form->format_amount($myconfig, $si->{qty} * 1);
1184 push @{ $form->{TEMPLATE_ARRAYS}{si_qty_nofmt}[$si_position-1] }, $si->{qty} * 1;
1185 push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$si_position-1] }, $si->{unit};
1188 if ($form->{"part_type_$i"} eq 'assembly') {
1191 # get parts and push them onto the stack
1193 if ($form->{groupitems}) {
1195 qq|ORDER BY pg.partsgroup, a.position|;
1197 $sortorder = qq|ORDER BY a.position|;
1200 do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
1202 while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
1203 if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
1204 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
1205 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
1206 $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
1207 push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type} }, 'assembly-item-partsgroup');
1208 push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
1212 push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type} }, 'assembly-item');
1213 push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
1214 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
1215 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
1220 CVar->get_non_editable_ic_cvars(form => $form,
1223 sub_module => 'delivery_order_items',
1224 may_converted_from => ['orderitems', 'delivery_order_items']);
1226 push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
1227 CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
1228 for @{ $ic_cvar_configs };
1230 push @{ $form->{TEMPLATE_ARRAYS}->{"project_cvar_" . $_->config->name} }, $_->value_as_text for @{ $project->cvars_by_config };
1233 $form->{totalweight} = $form->format_amount($myconfig, $totalweight, 3);
1234 $form->{totalweight_nofmt} = $totalweight;
1235 my $defaults = AM->get_defaults();
1236 $form->{weightunit} = $defaults->{weightunit};
1239 $h_bin_wh->finish();
1241 $form->{department} = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
1242 $form->{delivery_term} = SL::DB::Manager::DeliveryTerm->find_by(id => $form->{delivery_term_id} || undef);
1243 $form->{delivery_term}->description_long($form->{delivery_term}->translated_attribute('description_long', $form->{language_id})) if $form->{delivery_term} && $form->{language_id};
1245 $form->{username} = $myconfig->{name};
1247 $main::lxdebug->leave_sub();
1250 sub unpack_stock_information {
1251 $main::lxdebug->enter_sub();
1256 Common::check_params_x(\%params, qw(packed));
1260 eval { $unpacked = $params{packed} ? SL::YAML::Load($params{packed}) : []; };
1262 $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
1264 foreach my $entry (@{ $unpacked }) {
1265 next if ('HASH' eq ref $entry);
1270 $main::lxdebug->leave_sub();
1275 sub get_item_availability {
1276 $::lxdebug->enter_sub;
1281 Common::check_params(\%params, qw(parts_id));
1283 my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
1286 qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
1287 w.description AS warehousedescription,
1288 b.description AS bindescription
1290 LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
1291 LEFT JOIN bin b ON (i.bin_id = b.id)
1292 WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
1293 GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
1295 ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
1297 my $contents = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, @parts_ids);
1299 $::lxdebug->leave_sub;
1301 return @{ $contents };
1305 sub check_stock_availability {
1306 $main::lxdebug->enter_sub();
1311 Common::check_params(\%params, qw(requests parts_id));
1313 my $myconfig = \%main::myconfig;
1314 my $form = $main::form;
1316 my $dbh = $form->get_standard_dbh($myconfig);
1318 my $units = AM->retrieve_units($myconfig, $form);
1320 my ($partunit) = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
1321 my $unit_factor = $units->{$partunit}->{factor} || 1;
1323 my @contents = $self->get_item_availability(%params);
1327 foreach my $sinfo (@{ $params{requests} }) {
1330 foreach my $row (@contents) {
1331 next if (($row->{bin_id} != $sinfo->{bin_id}) ||
1332 ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
1333 ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
1334 ($row->{bestbefore} ne $sinfo->{bestbefore}));
1338 my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
1340 if ($base_qty > $row->{qty}) {
1341 $sinfo->{error} = 1;
1342 push @errors, $sinfo;
1348 push @errors, $sinfo if (!$found);
1351 $main::lxdebug->leave_sub();
1356 sub transfer_in_out {
1357 $main::lxdebug->enter_sub();
1362 Common::check_params(\%params, qw(direction requests));
1364 if (!@{ $params{requests} }) {
1365 $main::lxdebug->leave_sub();
1369 my $myconfig = \%main::myconfig;
1370 my $form = $main::form;
1372 my $prefix = $params{direction} eq 'in' ? 'dst' : 'src';
1376 foreach my $request (@{ $params{requests} }) {
1378 'parts_id' => $request->{parts_id},
1379 "${prefix}_warehouse_id" => $request->{warehouse_id},
1380 "${prefix}_bin_id" => $request->{bin_id},
1381 'chargenumber' => $request->{chargenumber},
1382 'bestbefore' => $request->{bestbefore},
1383 'qty' => $request->{qty},
1384 'unit' => $request->{unit},
1385 'oe_id' => $form->{id},
1386 'shippingdate' => 'current_date',
1387 'transfer_type' => $params{direction} eq 'in' ? 'stock' : 'shipped',
1388 'project_id' => $request->{project_id},
1389 'delivery_order_items_stock_id' => $request->{delivery_order_items_stock_id},
1390 'comment' => $request->{comment},
1394 WH->transfer(@transfers);
1396 if ($::instance_conf->get_shipped_qty_require_stock_out) {
1397 $self->mark_orders_if_delivered('do_id' => $form->{id},
1398 'type' => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase');
1401 $main::lxdebug->leave_sub();
1404 sub is_marked_as_delivered {
1405 $main::lxdebug->enter_sub();
1410 Common::check_params(\%params, qw(id));
1412 my $myconfig = \%main::myconfig;
1413 my $form = $main::form;
1415 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1417 my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
1419 $main::lxdebug->leave_sub();
1421 return $delivered ? 1 : 0;