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