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