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