Einkaufs-/Verkaufssuchen: bei Textfeldern führende/anhängende Whitespaces entfernen
[kivitendo-erp.git] / SL / DO.pm
1 #====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1999-2003
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
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.
21 #
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 #======================================================================
30 #
31 # Delivery Order entry module
32 #======================================================================
33
34 package DO;
35
36 use List::Util qw(max);
37 use YAML;
38
39 use SL::AM;
40 use SL::Common;
41 use SL::CVar;
42 use SL::DB::DeliveryOrder;
43 use SL::DB::Status;
44 use SL::DBUtils;
45 use SL::HTML::Restrict;
46 use SL::RecordLinks;
47 use SL::IC;
48 use SL::TransNumber;
49 use SL::Util qw(trim);
50
51 use strict;
52
53 sub transactions {
54   $main::lxdebug->enter_sub();
55
56   my ($self)   = @_;
57
58   my $myconfig = \%main::myconfig;
59   my $form     = $main::form;
60
61   # connect to database
62   my $dbh = $form->get_standard_dbh($myconfig);
63
64   my (@where, @values, $where);
65
66   my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
67
68   my $query =
69     qq|SELECT dord.id, dord.donumber, dord.ordnumber, dord.cusordnumber,
70          dord.transdate, dord.reqdate,
71          ct.${vc}number, ct.name, ct.business_id,
72          dord.${vc}_id, dord.globalproject_id,
73          dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
74          dord.transaction_description, dord.itime::DATE AS insertdate,
75          pr.projectnumber AS globalprojectnumber,
76          dep.description AS department,
77          e.name AS employee,
78          sm.name AS salesman
79        FROM delivery_orders dord
80        LEFT JOIN $vc ct ON (dord.${vc}_id = ct.id)
81        LEFT JOIN contacts cp ON (dord.cp_id = cp.cp_id)
82        LEFT JOIN employee e ON (dord.employee_id = e.id)
83        LEFT JOIN employee sm ON (dord.salesman_id = sm.id)
84        LEFT JOIN project pr ON (dord.globalproject_id = pr.id)
85        LEFT JOIN department dep ON (dord.department_id = dep.id)
86 |;
87
88   push @where, ($form->{type} eq 'sales_delivery_order' ? '' : 'NOT ') . qq|COALESCE(dord.is_sales, FALSE)|;
89
90   if ($form->{department_id}) {
91     push @where,  qq|dord.department_id = ?|;
92     push @values, conv_i($form->{department_id});
93   }
94
95   if ($form->{project_id}) {
96     push @where,
97       qq|(dord.globalproject_id = ?) OR EXISTS
98           (SELECT * FROM delivery_order_items doi
99            WHERE (doi.project_id = ?) AND (doi.delivery_order_id = dord.id))|;
100     push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
101   }
102
103   if ($form->{"business_id"}) {
104     push @where,  qq|ct.business_id = ?|;
105     push @values, conv_i($form->{"business_id"});
106   }
107
108   if ($form->{"${vc}_id"}) {
109     push @where,  qq|dord.${vc}_id = ?|;
110     push @values, $form->{"${vc}_id"};
111
112   } elsif ($form->{$vc}) {
113     push @where,  qq|ct.name ILIKE ?|;
114     push @values, '%' . trim($form->{$vc}) . '%';
115   }
116
117   if ($form->{"cp_name"}) {
118     push @where, "(cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
119     push @values, ('%' . trim($form->{"cp_name"}) . '%')x2;
120   }
121
122   foreach my $item (qw(employee_id salesman_id)) {
123     next unless ($form->{$item});
124     push @where, "dord.$item = ?";
125     push @values, conv_i($form->{$item});
126   }
127   if (!$main::auth->assert('sales_all_edit', 1)) {
128     push @where, qq|dord.employee_id = (select id from employee where login= ?)|;
129     push @values, $::myconfig{login};
130   }
131
132   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
133     next unless ($form->{$item});
134     push @where,  qq|dord.$item ILIKE ?|;
135     push @values, '%' . trim($form->{$item}) . '%';
136   }
137
138   if (($form->{open} || $form->{closed}) &&
139       ($form->{open} ne $form->{closed})) {
140     push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
141   }
142
143   if (($form->{notdelivered} || $form->{delivered}) &&
144       ($form->{notdelivered} ne $form->{delivered})) {
145     push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
146   }
147
148   if ($form->{serialnumber}) {
149     push @where, 'dord.id IN (SELECT doi.delivery_order_id FROM delivery_order_items doi WHERE doi.serialnumber LIKE ?)';
150     push @values, '%' . trim($form->{serialnumber}) . '%';
151   }
152
153   if($form->{transdatefrom}) {
154     push @where,  qq|dord.transdate >= ?|;
155     push @values, conv_date($form->{transdatefrom});
156   }
157
158   if($form->{transdateto}) {
159     push @where,  qq|dord.transdate <= ?|;
160     push @values, conv_date($form->{transdateto});
161   }
162
163   if($form->{reqdatefrom}) {
164     push @where,  qq|dord.reqdate >= ?|;
165     push @values, conv_date($form->{reqdatefrom});
166   }
167
168   if($form->{reqdateto}) {
169     push @where,  qq|dord.reqdate <= ?|;
170     push @values, conv_date($form->{reqdateto});
171   }
172
173   if($form->{insertdatefrom}) {
174     push @where, qq|dord.itime::DATE >= ?|;
175     push@values, conv_date($form->{insertdatefrom});
176   }
177
178   if($form->{insertdateto}) {
179     push @where, qq|dord.itime::DATE <= ?|;
180     push @values, conv_date($form->{insertdateto});
181   }
182
183   if (@where) {
184     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
185   }
186
187   my %allowed_sort_columns = (
188     "transdate"               => "dord.transdate",
189     "reqdate"                 => "dord.reqdate",
190     "id"                      => "dord.id",
191     "donumber"                => "dord.donumber",
192     "ordnumber"               => "dord.ordnumber",
193     "name"                    => "ct.name",
194     "employee"                => "e.name",
195     "salesman"                => "sm.name",
196     "shipvia"                 => "dord.shipvia",
197     "transaction_description" => "dord.transaction_description",
198     "department"              => "lower(dep.description)",
199     "insertdate"              => "dord.itime",
200   );
201
202   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
203   my $sortorder = "dord.id";
204   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
205     $sortorder = $allowed_sort_columns{$form->{sort}};
206   }
207
208   $query .= qq| ORDER by | . $sortorder . " $sortdir";
209
210   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
211
212   if (scalar @{ $form->{DO} }) {
213     $query =
214       qq|SELECT id
215          FROM oe
216          WHERE NOT COALESCE(quotation, FALSE)
217            AND (ordnumber = ?)
218            AND (COALESCE(${vc}_id, 0) != 0)|;
219
220     my $sth = prepare_query($form, $dbh, $query);
221
222     foreach my $dord (@{ $form->{DO} }) {
223       next unless ($dord->{ordnumber});
224       do_statement($form, $sth, $query, $dord->{ordnumber});
225       ($dord->{oe_id}) = $sth->fetchrow_array();
226     }
227
228     $sth->finish();
229   }
230
231   $main::lxdebug->leave_sub();
232 }
233
234 sub save {
235   $main::lxdebug->enter_sub();
236
237   my ($self)   = @_;
238
239   my $myconfig = \%main::myconfig;
240   my $form     = $main::form;
241
242   # connect to database, turn off autocommit
243   my $dbh = $form->get_standard_dbh($myconfig);
244   my $restricter = SL::HTML::Restrict->create;
245
246   my ($query, @values, $sth, $null);
247
248   my $all_units = AM->retrieve_units($myconfig, $form);
249   $form->{all_units} = $all_units;
250
251   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
252                                           dbh    => $dbh);
253
254   my $trans_number     = SL::TransNumber->new(type => $form->{type}, dbh => $dbh, number => $form->{donumber}, id => $form->{id});
255   $form->{donumber}  ||= $trans_number->create_unique;
256   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
257   $form->get_employee($dbh) unless ($form->{employee_id});
258
259   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
260
261   my (@processed_doi, @processed_dois);
262
263   if ($form->{id}) {
264
265     # only delete shipto complete
266     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
267     do_query($form, $dbh, $query, conv_i($form->{id}));
268
269   } else {
270
271     $query = qq|SELECT nextval('id')|;
272     ($form->{id}) = selectrow_query($form, $dbh, $query);
273
274     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id, currency_id, taxzone_id) VALUES (?, '', ?, (SELECT currency_id FROM defaults LIMIT 1), ?)|;
275     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}), $form->{taxzone_id});
276   }
277
278   my $project_id;
279   my $items_reqdate;
280
281   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
282   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
283   my $price_factor;
284
285   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
286   my @part_ids    = keys %part_id_map;
287   my %part_unit_map;
288
289   if (@part_ids) {
290     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
291     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
292   }
293   my $q_item = <<SQL;
294     UPDATE delivery_order_items SET
295        delivery_order_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
296        sellprice = ?, discount = ?, unit = ?, reqdate = ?, project_id = ?, serialnumber = ?,
297        lastcost = ? , price_factor_id = ?, price_factor = (SELECT factor FROM price_factors where id = ?),
298        marge_price_factor = ?, pricegroup_id = ?, active_price_source = ?, active_discount_source = ?
299     WHERE id = ?
300 SQL
301   my $h_item = prepare_query($form, $dbh, $q_item);
302
303   my $q_item_stock = <<SQL;
304     UPDATE delivery_order_items_stock SET
305       delivery_order_item_id = ?, qty = ?,  unit = ?,  warehouse_id = ?,
306       bin_id = ?, chargenumber = ?, bestbefore = ?
307     WHERE id = ?
308 SQL
309   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
310
311   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
312
313   for my $i (1 .. $form->{rowcount}) {
314     next if (!$form->{"id_$i"});
315
316     CVar->get_non_editable_ic_cvars(form               => $form,
317                                     dbh                => $dbh,
318                                     row                => $i,
319                                     sub_module         => 'delivery_order_items',
320                                     may_converted_from => ['orderitems', 'delivery_order_items']);
321
322     my $position = $i;
323
324     if (!$form->{"delivery_order_items_id_$i"}) {
325       # there is no persistent id, therefore create one with all necessary constraints
326       my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
327       my $h_item_id = prepare_query($form, $dbh, $q_item_id);
328       do_statement($form, $h_item_id, $q_item_id);
329       $form->{"delivery_order_items_id_$i"}  = $h_item_id->fetchrow_array();
330       $query = qq|INSERT INTO delivery_order_items (id, delivery_order_id, position, parts_id) VALUES (?, ?, ?, ?)|;
331       do_query($form, $dbh, $query, conv_i($form->{"delivery_order_items_id_$i"}),
332                 conv_i($form->{"id"}), conv_i($position), conv_i($form->{"id_$i"}));
333       $h_item_id->finish();
334     }
335
336     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
337
338     my $item_unit = $part_unit_map{$form->{"id_$i"}};
339
340     my $basefactor = 1;
341     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
342       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
343     }
344     my $baseqty = $form->{"qty_$i"} * $basefactor;
345
346     # set values to 0 if nothing entered
347     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"});
348     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
349     $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
350
351     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
352     my $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
353
354     $items_reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
355
356
357     # Get pricegroup_id and save it. Unfortunately the interface
358     # also uses ID "0" for signalling that none is selected, but "0"
359     # must not be stored in the database. Therefore we cannot simply
360     # use conv_i().
361     my $pricegroup_id = $form->{"pricegroup_id_$i"} * 1;
362     $pricegroup_id    = undef if !$pricegroup_id;
363
364     # save detail record in delivery_order_items table
365     @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
366                $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}),
367                $form->{"qty_$i"}, $baseqty,
368                $form->{"sellprice_$i"}, $form->{"discount_$i"} / 100,
369                $form->{"unit_$i"}, conv_date($items_reqdate), conv_i($form->{"project_id_$i"}),
370                $form->{"serialnumber_$i"},
371                $form->{"lastcost_$i"},
372                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
373                conv_i($form->{"marge_price_factor_$i"}),
374                $pricegroup_id,
375                $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
376                conv_i($form->{"delivery_order_items_id_$i"}));
377     do_statement($form, $h_item, $q_item, @values);
378     push @processed_doi, $form->{"delivery_order_items_id_$i"}; # transaction safe?
379
380     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
381
382     foreach my $sinfo (@{ $stock_info }) {
383       # if we have stock_info, we have to check for persistents entries
384       if (!$sinfo->{"delivery_order_items_stock_id"}) {
385         my $q_item_stock_id = qq|SELECT nextval('id')|;
386         my $h_item_stock_id = prepare_query($form, $dbh, $q_item_stock_id);
387         do_statement($form, $h_item_stock_id, $q_item_stock_id);
388         $sinfo->{"delivery_order_items_stock_id"} = $h_item_stock_id->fetchrow_array();
389         $query = qq|INSERT INTO delivery_order_items_stock (id, delivery_order_item_id, qty, unit, warehouse_id, bin_id)
390                     VALUES (?, ?, ?, ?, ?, ?)|;
391         do_query($form, $dbh, $query, conv_i($sinfo->{"delivery_order_items_stock_id"}),
392                   conv_i($form->{"delivery_order_items_id_$i"}), $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
393                   conv_i($sinfo->{bin_id}));
394         $h_item_stock_id->finish();
395         # write back the id to the form (important if only transfer was clicked (id fk for invoice)
396         $form->{"stock_${in_out}_$i"} = YAML::Dump($stock_info);
397       }
398       @values = ($form->{"delivery_order_items_id_$i"}, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
399                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}),
400                  conv_i($sinfo->{"delivery_order_items_stock_id"}));
401       do_statement($form, $h_item_stock, $q_item_stock, @values);
402       push @processed_dois, $sinfo->{"delivery_order_items_stock_id"};
403     }
404
405     CVar->save_custom_variables(module       => 'IC',
406                                 sub_module   => 'delivery_order_items',
407                                 trans_id     => $form->{"delivery_order_items_id_$i"},
408                                 configs      => $ic_cvar_configs,
409                                 variables    => $form,
410                                 name_prefix  => 'ic_',
411                                 name_postfix => "_$i",
412                                 dbh          => $dbh);
413
414     # link order items with doi, for future extension look at foreach IS.pm
415     if (!$form->{saveasnew} && $form->{"converted_from_orderitems_id_$i"}) {
416       RecordLinks->create_links('dbh'        => $dbh,
417                                 'mode'       => 'ids',
418                                 'from_table' => 'orderitems',
419                                 'from_ids'   => $form->{"converted_from_orderitems_id_$i"},
420                                 'to_table'   => 'delivery_order_items',
421                                 'to_id'      =>  $form->{"delivery_order_items_id_$i"},
422       );
423     }
424     delete $form->{"converted_from_orderitems_id_$i"};
425   }
426
427   # 1. search for orphaned dois; processed_dois may be empty (no transfer) TODO: be supersafe and alter same statement for doi and oi
428   $query  = sprintf 'SELECT id FROM delivery_order_items_stock WHERE delivery_order_item_id in
429                       (select id from delivery_order_items where delivery_order_id = ?)';
430   $query .= sprintf ' AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_dois if (scalar @processed_dois);
431   @values = (conv_i($form->{id}), map { conv_i($_) } @processed_dois);
432   my @orphaned_dois_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
433   if (scalar @orphaned_dois_ids) {
434     # clean up delivery_order_items_stock
435     $query  = sprintf 'DELETE FROM delivery_order_items_stock WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_dois_ids;
436     do_query($form, $dbh, $query, @orphaned_dois_ids);
437   }
438   # 2. search for orphaned doi
439   $query  = sprintf 'SELECT id FROM delivery_order_items WHERE delivery_order_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_doi;
440   @values = (conv_i($form->{id}), map { conv_i($_) } @processed_doi);
441   my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
442   if (scalar @orphaned_ids) {
443     # clean up delivery_order_items
444     $query  = sprintf 'DELETE FROM delivery_order_items WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
445     do_query($form, $dbh, $query, @orphaned_ids);
446   }
447   $h_item->finish();
448   $h_item_stock->finish();
449
450
451   # reqdate is last items reqdate (?: old behaviour) if not already set
452   $form->{reqdate} ||= $items_reqdate;
453   # save DO record
454   $query =
455     qq|UPDATE delivery_orders SET
456          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
457          customer_id = ?, reqdate = ?,
458          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
459          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
460          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
461          is_sales = ?, taxzone_id = ?, taxincluded = ?, payment_id = ?, currency_id = (SELECT id FROM currencies WHERE name = ?),
462          delivery_term_id = ?
463        WHERE id = ?|;
464
465   @values = ($form->{donumber}, $form->{ordnumber},
466              $form->{cusordnumber}, conv_date($form->{transdate}),
467              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
468              conv_date($form->{reqdate}), $form->{shippingpoint}, $form->{shipvia},
469              $restricter->process($form->{notes}), $form->{intnotes},
470              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
471              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
472              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
473              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
474              $form->{transaction_description},
475              $form->{type} =~ /^sales/ ? 't' : 'f',
476              conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{payment_id}), $form->{currency},
477              conv_i($form->{delivery_term_id}),
478              conv_i($form->{id}));
479   do_query($form, $dbh, $query, @values);
480
481   $form->new_lastmtime('delivery_orders');
482
483   $form->{name} = $form->{ $form->{vc} };
484   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
485
486   # add shipto
487   if (!$form->{shipto_id}) {
488     $form->add_shipto($dbh, $form->{id}, "DO");
489   }
490
491   # save printed, emailed, queued
492   $form->save_status($dbh);
493
494   # Link this delivery order to the quotations it was created from.
495   RecordLinks->create_links('dbh'        => $dbh,
496                             'mode'       => 'ids',
497                             'from_table' => 'oe',
498                             'from_ids'   => $form->{convert_from_oe_ids},
499                             'to_table'   => 'delivery_orders',
500                             'to_id'      => $form->{id},
501     );
502   delete $form->{convert_from_oe_ids};
503
504   $self->mark_orders_if_delivered('do_id' => $form->{id},
505                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
506                                   'dbh'   => $dbh,);
507
508   my $rc = $dbh->commit();
509
510   $form->{saved_donumber} = $form->{donumber};
511   $form->{saved_ordnumber} = $form->{ordnumber};
512   $form->{saved_cusordnumber} = $form->{cusordnumber};
513
514   Common::webdav_folder($form);
515
516   $main::lxdebug->leave_sub();
517
518   return $rc;
519 }
520
521 sub mark_orders_if_delivered {
522   $main::lxdebug->enter_sub();
523
524   my $self   = shift;
525   my %params = @_;
526
527   Common::check_params(\%params, qw(do_id type));
528
529   my $myconfig = \%main::myconfig;
530   my $form     = $main::form;
531
532   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
533
534   my @links    = RecordLinks->get_links('dbh'        => $dbh,
535                                         'from_table' => 'oe',
536                                         'to_table'   => 'delivery_orders',
537                                         'to_id'      => $params{do_id});
538
539   my $oe_id  = @links ? $links[0]->{from_id} : undef;
540
541   return $main::lxdebug->leave_sub() if (!$oe_id);
542
543   my $all_units = AM->retrieve_all_units();
544
545   my $query     = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
546                      FROM orderitems oi
547                      LEFT JOIN parts p ON (oi.parts_id = p.id)
548                      WHERE (oi.trans_id = ?)|;
549   my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
550
551   my %shipped   = $self->get_shipped_qty('type'  => $params{type},
552                                          'oe_id' => $oe_id,);
553   my %ordered   = ();
554
555   while (my $ref = $sth->fetchrow_hashref()) {
556     $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
557
558     if ($ordered{$ref->{parts_id}}) {
559       $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
560     } else {
561       $ordered{$ref->{parts_id}}             = $ref;
562     }
563   }
564
565   $sth->finish();
566
567   map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
568
569   my $delivered = 1;
570   foreach my $part (values %ordered) {
571     if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
572       $delivered = 0;
573       last;
574     }
575   }
576
577   if ($delivered) {
578     $query = qq|UPDATE oe
579                 SET delivered = TRUE
580                 WHERE id = ?|;
581     do_query($form, $dbh, $query, $oe_id);
582     $dbh->commit() if (!$params{dbh});
583   }
584
585   $main::lxdebug->leave_sub();
586 }
587
588 sub close_orders {
589   $main::lxdebug->enter_sub();
590
591   my $self     = shift;
592   my %params   = @_;
593
594   Common::check_params(\%params, qw(ids));
595
596   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
597     $main::lxdebug->leave_sub();
598     return;
599   }
600
601   my $myconfig = \%main::myconfig;
602   my $form     = $main::form;
603
604   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
605
606   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
607
608   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
609
610   $dbh->commit() unless ($params{dbh});
611   $form->new_lastmtime('delivery_orders');
612
613   $main::lxdebug->leave_sub();
614 }
615
616 sub delete {
617   $main::lxdebug->enter_sub();
618
619   my ($self)   = @_;
620
621   my $myconfig = \%main::myconfig;
622   my $form     = $main::form;
623   my $spool    = $::lx_office_conf{paths}->{spool};
624
625   my $rc = SL::DB::Order->new->db->with_transaction(sub {
626     my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $form->{id} ]) };
627
628     SL::DB::DeliveryOrder->new(id => $form->{id})->delete;
629
630     my $spool = $::lx_office_conf{paths}->{spool};
631     unlink map { "$spool/$_" } @spoolfiles if $spool;
632
633     1;
634   });
635
636   $main::lxdebug->leave_sub();
637
638   return $rc;
639 }
640
641 sub retrieve {
642   $main::lxdebug->enter_sub();
643
644   my $self     = shift;
645   my %params   = @_;
646
647   my $myconfig = \%main::myconfig;
648   my $form     = $main::form;
649
650   # connect to database
651   my $dbh = $form->get_standard_dbh($myconfig);
652
653   my ($query, $query_add, @values, $sth, $ref);
654
655   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
656                                           dbh    => $dbh);
657
658   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
659
660   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
661
662   if ($mode eq 'default') {
663     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate|);
664     map { $form->{$_} = $ref->{$_} } keys %$ref;
665
666     # if reqdate is not set from oe-workflow, set it to transdate (which is current date)
667     $form->{reqdate} ||= $form->{transdate};
668
669     # get last name used
670     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
671
672     $main::lxdebug->leave_sub();
673
674     return 1;
675   }
676
677   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
678   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
679
680   # retrieve order for single id
681   # NOTE: this query is intended to fetch all information only ONCE.
682   # so if any of these infos is important (or even different) for any item,
683   # it will be killed out and then has to be fetched from the item scope query further down
684   $query =
685     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
686          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
687          e.name AS employee, dord.employee_id, dord.salesman_id,
688          dord.${vc}_id, cv.name AS ${vc},
689          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
690          d.description AS department, dord.language_id,
691          dord.shipto_id,
692          dord.itime, dord.mtime,
693          dord.globalproject_id, dord.delivered, dord.transaction_description,
694          dord.taxzone_id, dord.taxincluded, dord.payment_id, (SELECT cu.name FROM currencies cu WHERE cu.id=dord.currency_id) AS currency,
695          dord.delivery_term_id, dord.itime::DATE AS insertdate
696        FROM delivery_orders dord
697        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
698        LEFT JOIN employee e ON (dord.employee_id = e.id)
699        LEFT JOIN department d ON (dord.department_id = d.id)
700        WHERE dord.id IN ($do_ids_placeholders)|;
701   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
702
703   delete $form->{"${vc}_id"};
704   my $pos = 0;
705   $form->{ordnumber_array} = ' ';
706   $form->{cusordnumber_array} = ' ';
707   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
708     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
709       $sth->finish();
710       $main::lxdebug->leave_sub();
711
712       return 0;
713     }
714
715     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
716     $form->{donumber_array} .= $form->{donumber} . ' ';
717     $pos = index($form->{ordnumber_array},' ' . $form->{ordnumber} . ' ');
718     if ($pos == -1) {
719       $form->{ordnumber_array} .= $form->{ordnumber} . ' ';
720     }
721     $pos = index($form->{cusordnumber_array},' ' . $form->{cusordnumber} . ' ');
722     if ($pos == -1) {
723       $form->{cusordnumber_array} .= $form->{cusordnumber} . ' ';
724     }
725   }
726   $sth->finish();
727   $form->{mtime}   ||= $form->{itime};
728   $form->{lastmtime} = $form->{mtime};
729   $form->{donumber_array} =~ s/\s*$//g;
730   $form->{ordnumber_array} =~ s/ //;
731   $form->{ordnumber_array} =~ s/\s*$//g;
732   $form->{cusordnumber_array} =~ s/ //;
733   $form->{cusordnumber_array} =~ s/\s*$//g;
734
735   $form->{saved_donumber} = $form->{donumber};
736   $form->{saved_ordnumber} = $form->{ordnumber};
737   $form->{saved_cusordnumber} = $form->{cusordnumber};
738
739   # if not given, fill transdate with current_date
740   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
741
742   if ($mode eq 'single') {
743     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
744     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
745
746     $ref   = $sth->fetchrow_hashref("NAME_lc");
747     delete $ref->{id};
748     map { $form->{$_} = $ref->{$_} } keys %$ref;
749     $sth->finish();
750
751     # get printed, emailed and queued
752     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
753     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
754
755     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
756       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
757       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
758       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
759     }
760     $sth->finish();
761     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
762
763   } else {
764     delete $form->{id};
765   }
766
767   # retrieve individual items
768   # this query looks up all information about the items
769   # stuff different from the whole will not be overwritten, but saved with a suffix.
770   $query =
771     qq|SELECT doi.id AS delivery_order_items_id,
772          p.partnumber, p.assembly, p.listprice, doi.description, doi.qty,
773          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.notes AS partnotes,
774          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
775          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
776          doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
777          doi.active_price_source, doi.active_discount_source,
778          pr.projectnumber, dord.transdate AS dord_transdate, dord.donumber,
779          pg.partsgroup
780        FROM delivery_order_items doi
781        JOIN parts p ON (doi.parts_id = p.id)
782        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
783        LEFT JOIN project pr ON (doi.project_id = pr.id)
784        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
785        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
786        ORDER BY doi.delivery_order_id, doi.position|;
787
788   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
789
790   # Retrieve custom variables.
791   foreach my $doi (@{ $form->{form_details} }) {
792     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
793                                            module     => 'IC',
794                                            sub_module => 'delivery_order_items',
795                                            trans_id   => $doi->{delivery_order_items_id},
796                                           );
797     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
798   }
799
800   if ($mode eq 'single') {
801     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
802
803     $query =
804       qq|SELECT id as delivery_order_items_stock_id, qty, unit, bin_id,
805                 warehouse_id, chargenumber, bestbefore
806          FROM delivery_order_items_stock
807          WHERE delivery_order_item_id = ?|;
808     my $sth = prepare_query($form, $dbh, $query);
809
810     foreach my $doi (@{ $form->{form_details} }) {
811       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
812       my $requests = [];
813       while (my $ref = $sth->fetchrow_hashref()) {
814         push @{ $requests }, $ref;
815       }
816
817       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
818     }
819
820     $sth->finish();
821   }
822
823   Common::webdav_folder($form);
824
825   $main::lxdebug->leave_sub();
826
827   return 1;
828 }
829
830 sub order_details {
831   $main::lxdebug->enter_sub();
832
833   my ($self, $myconfig, $form) = @_;
834
835   # connect to database
836   my $dbh = $form->get_standard_dbh($myconfig);
837   my $query;
838   my @values = ();
839   my $sth;
840   my $item;
841   my $i;
842   my @partsgroup = ();
843   my $partsgroup;
844   my $position = 0;
845   my $subtotal_header = 0;
846   my $subposition = 0;
847   my $si_position = 0;
848
849   my (@project_ids);
850
851   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
852
853   # sort items by partsgroup
854   for $i (1 .. $form->{rowcount}) {
855     $partsgroup = "";
856     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
857       $partsgroup = $form->{"partsgroup_$i"};
858     }
859     push @partsgroup, [$i, $partsgroup];
860     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
861   }
862
863   my $projects = [];
864   my %projects_by_id;
865   if (@project_ids) {
866     $projects = SL::DB::Manager::Project->get_all(query => [ id => \@project_ids ]);
867     %projects_by_id = map { $_->id => $_ } @$projects;
868   }
869
870   if ($projects_by_id{$form->{"globalproject_id"}}) {
871     $form->{globalprojectnumber} = $projects_by_id{$form->{"globalproject_id"}}->projectnumber;
872     $form->{globalprojectdescription} = $projects_by_id{$form->{"globalproject_id"}}->description;
873
874     for (@{ $projects_by_id{$form->{"globalproject_id"}}->cvars_by_config }) {
875       $form->{"project_cvar_" . $_->config->name} = $_->value_as_text;
876     }
877   }
878
879   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
880                     FROM assembly a
881                     JOIN parts p ON (a.parts_id = p.id)
882                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
883                     WHERE a.bom = '1'
884                       AND a.id = ?|;
885   my $h_pg     = prepare_query($form, $dbh, $q_pg);
886
887   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
888                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
889   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
890
891   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
892
893   my $num_si   = 0;
894
895   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
896   my $project_cvar_configs = CVar->get_configs(module => 'Projects');
897
898   # get some values of parts from db on store them in extra array,
899   # so that they can be sorted in later
900   my %prepared_template_arrays = IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
901   my @prepared_arrays          = keys %prepared_template_arrays;
902
903   $form->{TEMPLATE_ARRAYS} = { };
904
905   my @arrays =
906     qw(runningnumber number description longdescription qty qty_nofmt unit
907        partnotes serialnumber reqdate projectnumber projectdescription
908        weight weight_nofmt lineweight lineweight_nofmt
909        si_runningnumber si_number si_description
910        si_warehouse si_bin si_chargenumber si_bestbefore
911        si_qty si_qty_nofmt si_unit);
912
913   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays, @prepared_arrays);
914
915   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
916   push @arrays, map { "project_cvar_$_->{name}" } @{ $project_cvar_configs };
917
918   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
919   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
920
921   my $totalweight = 0;
922   my $sameitem = "";
923   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
924     $i = $item->[0];
925
926     next if (!$form->{"id_$i"});
927
928     if ($item->[1] ne $sameitem) {
929       push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'partsgroup');
930       push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, qq|$item->[1]|);
931       $sameitem = $item->[1];
932
933       map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
934       map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
935       $si_position++;
936     }
937
938     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
939
940     # add number, description and qty to $form->{number}, ....
941     if ($form->{"subtotal_$i"} && !$subtotal_header) {
942       $subtotal_header = $i;
943       $position = int($position);
944       $subposition = 0;
945       $position++;
946     } elsif ($subtotal_header) {
947       $subposition += 1;
948       $position = int($position);
949       $position = $position.".".$subposition;
950     } else {
951       $position = int($position);
952       $position++;
953     }
954
955     $si_position++;
956
957     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
958     my $project = $projects_by_id{$form->{"project_id_$i"}} || SL::DB::Project->new;
959
960     push(@{ $form->{TEMPLATE_ARRAYS}{$_} },              $prepared_template_arrays{$_}[$i - 1]) for @prepared_arrays;
961
962     push @{ $form->{TEMPLATE_ARRAYS}{entry_type} },      'normal';
963     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
964     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
965     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
966     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
967     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
968     push @{ $form->{TEMPLATE_ARRAYS}{qty_nofmt} },       $form->{"qty_$i"};
969     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
970     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
971     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
972     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
973     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $project->projectnumber;
974     push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} }, $project->description;
975
976     if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
977       $subtotal_header     = 0;
978     }
979
980     my $lineweight = $form->{"qty_$i"} * $form->{"weight_$i"};
981     $totalweight += $lineweight;
982     push @{ $form->{TEMPLATE_ARRAYS}->{weight} },            $form->format_amount($myconfig, $form->{"weight_$i"}, 3);
983     push @{ $form->{TEMPLATE_ARRAYS}->{weight_nofmt} },      $form->{"weight_$i"};
984     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight} },        $form->format_amount($myconfig, $lineweight, 3);
985     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight_nofmt} },  $lineweight;
986
987     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
988
989     foreach my $si (@{ $stock_info }) {
990       $num_si++;
991
992       do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
993       my $bin_wh = $h_bin_wh->fetchrow_hashref();
994
995       push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$si_position-1] }, $num_si;
996       push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$si_position-1] },        $form->{"partnumber_$i"};
997       push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$si_position-1] },   $form->{"description_$i"};
998       push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$si_position-1] },     $bin_wh->{warehouse};
999       push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$si_position-1] },           $bin_wh->{bin};
1000       push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$si_position-1] },  $si->{chargenumber};
1001       push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$si_position-1] },    $si->{bestbefore};
1002       push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$si_position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
1003       push @{ $form->{TEMPLATE_ARRAYS}{si_qty_nofmt}[$si_position-1] },     $si->{qty} * 1;
1004       push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$si_position-1] },          $si->{unit};
1005     }
1006
1007     if ($form->{"assembly_$i"}) {
1008       $sameitem = "";
1009
1010       # get parts and push them onto the stack
1011       my $sortorder = "";
1012       if ($form->{groupitems}) {
1013         $sortorder =
1014           qq|ORDER BY pg.partsgroup, a.oid|;
1015       } else {
1016         $sortorder = qq|ORDER BY a.oid|;
1017       }
1018
1019       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
1020
1021       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
1022         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
1023           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
1024           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
1025           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
1026           push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'assembly-item-partsgroup');
1027           push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
1028           $si_position++;
1029         }
1030
1031         push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  },  'assembly-item');
1032         push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
1033         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} (@arrays, @prepared_arrays)));
1034         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
1035         $si_position++;
1036       }
1037     }
1038
1039     CVar->get_non_editable_ic_cvars(form               => $form,
1040                                     dbh                => $dbh,
1041                                     row                => $i,
1042                                     sub_module         => 'delivery_order_items',
1043                                     may_converted_from => ['orderitems', 'delivery_order_items']);
1044
1045     push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
1046       CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
1047         for @{ $ic_cvar_configs };
1048
1049     push @{ $form->{TEMPLATE_ARRAYS}->{"project_cvar_" . $_->config->name} }, $_->value_as_text for @{ $project->cvars_by_config };
1050   }
1051
1052   $form->{totalweight}       = $form->format_amount($myconfig, $totalweight, 3);
1053   $form->{totalweight_nofmt} = $totalweight;
1054   my $defaults = AM->get_defaults();
1055   $form->{weightunit}        = $defaults->{weightunit};
1056
1057   $h_pg->finish();
1058   $h_bin_wh->finish();
1059
1060   $form->{delivery_term} = SL::DB::Manager::DeliveryTerm->find_by(id => $form->{delivery_term_id} || undef);
1061   $form->{delivery_term}->description_long($form->{delivery_term}->translated_attribute('description_long', $form->{language_id})) if $form->{delivery_term} && $form->{language_id};
1062   $form->{department}    = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
1063
1064   $form->{username} = $myconfig->{name};
1065
1066   $main::lxdebug->leave_sub();
1067 }
1068
1069 sub project_description {
1070   $main::lxdebug->enter_sub();
1071
1072   my ($self, $dbh, $id) = @_;
1073
1074   my $form     =  $main::form;
1075
1076   my $query = qq|SELECT description FROM project WHERE id = ?|;
1077   my ($value) = selectrow_query($form, $dbh, $query, $id);
1078
1079   $main::lxdebug->leave_sub();
1080
1081   return $value;
1082 }
1083
1084 sub unpack_stock_information {
1085   $main::lxdebug->enter_sub();
1086
1087   my $self   = shift;
1088   my %params = @_;
1089
1090   Common::check_params_x(\%params, qw(packed));
1091
1092   my $unpacked;
1093
1094   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
1095
1096   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
1097
1098   foreach my $entry (@{ $unpacked }) {
1099     next if ('HASH' eq ref $entry);
1100     $unpacked = [];
1101     last;
1102   }
1103
1104   $main::lxdebug->leave_sub();
1105
1106   return $unpacked;
1107 }
1108
1109 sub get_item_availability {
1110   $::lxdebug->enter_sub;
1111
1112   my $self     = shift;
1113   my %params   = @_;
1114
1115   Common::check_params(\%params, qw(parts_id));
1116
1117   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
1118
1119   my $query     =
1120     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
1121          w.description AS warehousedescription,
1122          b.description AS bindescription
1123        FROM inventory i
1124        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
1125        LEFT JOIN bin b       ON (i.bin_id       = b.id)
1126        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
1127        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
1128        HAVING SUM(qty) > 0
1129        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
1130 |;
1131   my $contents = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, @parts_ids);
1132
1133   $::lxdebug->leave_sub;
1134
1135   return @{ $contents };
1136 }
1137
1138
1139 sub check_stock_availability {
1140   $main::lxdebug->enter_sub();
1141
1142   my $self     = shift;
1143   my %params   = @_;
1144
1145   Common::check_params(\%params, qw(requests parts_id));
1146
1147   my $myconfig    = \%main::myconfig;
1148   my $form        =  $main::form;
1149
1150   my $dbh         = $form->get_standard_dbh($myconfig);
1151
1152   my $units       = AM->retrieve_units($myconfig, $form);
1153
1154   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
1155   my $unit_factor = $units->{$partunit}->{factor} || 1;
1156
1157   my @contents    = $self->get_item_availability(%params);
1158
1159   my @errors;
1160
1161   foreach my $sinfo (@{ $params{requests} }) {
1162     my $found = 0;
1163
1164     foreach my $row (@contents) {
1165       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
1166                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
1167                ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
1168                ($row->{bestbefore}   ne $sinfo->{bestbefore}));
1169
1170       $found       = 1;
1171
1172       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
1173
1174       if ($base_qty > $row->{qty}) {
1175         $sinfo->{error} = 1;
1176         push @errors, $sinfo;
1177
1178         last;
1179       }
1180     }
1181
1182     push @errors, $sinfo if (!$found);
1183   }
1184
1185   $main::lxdebug->leave_sub();
1186
1187   return @errors;
1188 }
1189
1190 sub transfer_in_out {
1191   $main::lxdebug->enter_sub();
1192
1193   my $self     = shift;
1194   my %params   = @_;
1195
1196   Common::check_params(\%params, qw(direction requests));
1197
1198   if (!@{ $params{requests} }) {
1199     $main::lxdebug->leave_sub();
1200     return;
1201   }
1202
1203   my $myconfig = \%main::myconfig;
1204   my $form     = $main::form;
1205
1206   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
1207
1208   my @transfers;
1209
1210   foreach my $request (@{ $params{requests} }) {
1211     push @transfers, {
1212       'parts_id'                      => $request->{parts_id},
1213       "${prefix}_warehouse_id"        => $request->{warehouse_id},
1214       "${prefix}_bin_id"              => $request->{bin_id},
1215       'chargenumber'                  => $request->{chargenumber},
1216       'bestbefore'                    => $request->{bestbefore},
1217       'qty'                           => $request->{qty},
1218       'unit'                          => $request->{unit},
1219       'oe_id'                         => $form->{id},
1220       'shippingdate'                  => 'current_date',
1221       'transfer_type'                 => $params{direction} eq 'in' ? 'stock' : 'shipped',
1222       'project_id'                    => $request->{project_id},
1223       'delivery_order_items_stock_id' => $request->{delivery_order_items_stock_id},
1224       'comment'                       => $request->{comment},
1225     };
1226   }
1227
1228   WH->transfer(@transfers);
1229
1230   $main::lxdebug->leave_sub();
1231 }
1232
1233 sub get_shipped_qty {
1234   $main::lxdebug->enter_sub();
1235
1236   my $self     = shift;
1237   my %params   = @_;
1238
1239   Common::check_params(\%params, qw(type oe_id));
1240
1241   my $myconfig = \%main::myconfig;
1242   my $form     = $main::form;
1243
1244   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1245
1246   my @links    = RecordLinks->get_links('dbh'        => $dbh,
1247                                         'from_table' => 'oe',
1248                                         'from_id'    => $params{oe_id},
1249                                         'to_table'   => 'delivery_orders');
1250   my @values   = map { $_->{to_id} } @links;
1251
1252   if (!scalar @values) {
1253     $main::lxdebug->leave_sub();
1254     return ();
1255   }
1256
1257   my $query =
1258     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
1259        FROM delivery_order_items doi
1260        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
1261        LEFT JOIN parts p ON (doi.parts_id = p.id)
1262        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
1263
1264   my %ship      = ();
1265   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
1266   my $all_units = AM->retrieve_all_units();
1267
1268   foreach my $entry (@{ $entries }) {
1269     $entry->{qty} *= AM->convert_unit($entry->{unit}, $entry->{partunit}, $all_units);
1270
1271     if (!$ship{$entry->{parts_id}}) {
1272       $ship{$entry->{parts_id}} = $entry;
1273     } else {
1274       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
1275     }
1276   }
1277
1278   $main::lxdebug->leave_sub();
1279
1280   return %ship;
1281 }
1282
1283 sub is_marked_as_delivered {
1284   $main::lxdebug->enter_sub();
1285
1286   my $self     = shift;
1287   my %params   = @_;
1288
1289   Common::check_params(\%params, qw(id));
1290
1291   my $myconfig    = \%main::myconfig;
1292   my $form        = $main::form;
1293
1294   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
1295
1296   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
1297
1298   $main::lxdebug->leave_sub();
1299
1300   return $delivered ? 1 : 0;
1301 }
1302
1303 1;