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