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