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