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