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