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