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