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