Lieferscheinbericht: Suchmöglichkeit nach Seriennummer
[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::RecordLinks;
46 use SL::IC;
47
48 use strict;
49
50 sub transactions {
51   $main::lxdebug->enter_sub();
52
53   my ($self)   = @_;
54
55   my $myconfig = \%main::myconfig;
56   my $form     = $main::form;
57
58   # connect to database
59   my $dbh = $form->get_standard_dbh($myconfig);
60
61   my (@where, @values, $where);
62
63   my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
64
65   my $query =
66     qq|SELECT dord.id, dord.donumber, dord.ordnumber,
67          dord.transdate, dord.reqdate,
68          ct.${vc}number, ct.name, dord.${vc}_id, dord.globalproject_id,
69          dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
70          dord.transaction_description,
71          pr.projectnumber AS globalprojectnumber,
72          dep.description AS department,
73          e.name AS employee,
74          sm.name AS salesman
75        FROM delivery_orders dord
76        LEFT JOIN $vc ct ON (dord.${vc}_id = ct.id)
77        LEFT JOIN employee e ON (dord.employee_id = e.id)
78        LEFT JOIN employee sm ON (dord.salesman_id = sm.id)
79        LEFT JOIN project pr ON (dord.globalproject_id = pr.id)
80        LEFT JOIN department dep ON (dord.department_id = dep.id)
81 |;
82
83   push @where, ($form->{type} eq 'sales_delivery_order' ? '' : 'NOT ') . qq|COALESCE(dord.is_sales, FALSE)|;
84
85   if ($form->{department_id}) {
86     push @where,  qq|dord.department_id = ?|;
87     push @values, conv_i($form->{department_id});
88   }
89
90   if ($form->{project_id}) {
91     push @where,
92       qq|(dord.globalproject_id = ?) OR EXISTS
93           (SELECT * FROM delivery_order_items doi
94            WHERE (doi.project_id = ?) AND (doi.delivery_order_id = dord.id))|;
95     push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
96   }
97
98   if ($form->{"${vc}_id"}) {
99     push @where,  qq|dord.${vc}_id = ?|;
100     push @values, $form->{"${vc}_id"};
101
102   } elsif ($form->{$vc}) {
103     push @where,  qq|ct.name ILIKE ?|;
104     push @values, '%' . $form->{$vc} . '%';
105   }
106
107   foreach my $item (qw(employee_id salesman_id)) {
108     next unless ($form->{$item});
109     push @where, "dord.$item = ?";
110     push @values, conv_i($form->{$item});
111   }
112   if (!$main::auth->assert('sales_all_edit', 1)) {
113     push @where, qq|dord.employee_id = (select id from employee where login= ?)|;
114     push @values, $form->{login};
115   }
116
117   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
118     next unless ($form->{$item});
119     push @where,  qq|dord.$item ILIKE ?|;
120     push @values, '%' . $form->{$item} . '%';
121   }
122
123   if (($form->{open} || $form->{closed}) &&
124       ($form->{open} ne $form->{closed})) {
125     push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
126   }
127
128   if (($form->{notdelivered} || $form->{delivered}) &&
129       ($form->{notdelivered} ne $form->{delivered})) {
130     push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
131   }
132
133   if ($form->{serialnumber}) {
134     push @where, 'dord.id IN (SELECT doi.delivery_order_id FROM delivery_order_items doi WHERE doi.serialnumber LIKE ?)';
135     push @values, '%' . $form->{serialnumber} . '%';
136   }
137
138   if($form->{transdatefrom}) {
139     push @where,  qq|dord.transdate >= ?|;
140     push @values, conv_date($form->{transdatefrom});
141   }
142
143   if($form->{transdateto}) {
144     push @where,  qq|dord.transdate <= ?|;
145     push @values, conv_date($form->{transdateto});
146   }
147
148   if (@where) {
149     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
150   }
151
152   my %allowed_sort_columns = (
153     "transdate"               => "dord.transdate",
154     "reqdate"                 => "dord.reqdate",
155     "id"                      => "dord.id",
156     "donumber"                => "dord.donumber",
157     "ordnumber"               => "dord.ordnumber",
158     "name"                    => "ct.name",
159     "employee"                => "e.name",
160     "salesman"                => "sm.name",
161     "shipvia"                 => "dord.shipvia",
162     "transaction_description" => "dord.transaction_description",
163     "department"              => "lower(dep.description)",
164   );
165
166   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
167   my $sortorder = "dord.id";
168   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
169     $sortorder = $allowed_sort_columns{$form->{sort}};
170   }
171
172   $query .= qq| ORDER by | . $sortorder . " $sortdir";
173
174   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
175
176   if (scalar @{ $form->{DO} }) {
177     $query =
178       qq|SELECT id
179          FROM oe
180          WHERE NOT COALESCE(quotation, FALSE)
181            AND (ordnumber = ?)
182            AND (COALESCE(${vc}_id, 0) != 0)|;
183
184     my $sth = prepare_query($form, $dbh, $query);
185
186     foreach my $dord (@{ $form->{DO} }) {
187       next unless ($dord->{ordnumber});
188       do_statement($form, $sth, $query, $dord->{ordnumber});
189       ($dord->{oe_id}) = $sth->fetchrow_array();
190     }
191
192     $sth->finish();
193   }
194
195   $main::lxdebug->leave_sub();
196 }
197
198 sub save {
199   $main::lxdebug->enter_sub();
200
201   my ($self)   = @_;
202
203   my $myconfig = \%main::myconfig;
204   my $form     = $main::form;
205
206   # connect to database, turn off autocommit
207   my $dbh = $form->get_standard_dbh($myconfig);
208
209   my ($query, @values, $sth, $null);
210
211   my $all_units = AM->retrieve_units($myconfig, $form);
212   $form->{all_units} = $all_units;
213
214   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
215                                           dbh    => $dbh);
216
217   $form->{donumber}    = $form->update_defaults($myconfig, $form->{type} eq 'sales_delivery_order' ? 'sdonumber' : 'pdonumber', $dbh) unless $form->{donumber};
218   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
219   $form->get_employee($dbh) unless ($form->{employee_id});
220
221   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
222
223   if ($form->{id}) {
224
225     $query = qq|DELETE FROM delivery_order_items_stock WHERE delivery_order_item_id IN (SELECT id FROM delivery_order_items WHERE delivery_order_id = ?)|;
226     do_query($form, $dbh, $query, conv_i($form->{id}));
227
228     $query = qq|DELETE FROM delivery_order_items WHERE delivery_order_id = ?|;
229     do_query($form, $dbh, $query, conv_i($form->{id}));
230
231     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
232     do_query($form, $dbh, $query, conv_i($form->{id}));
233
234   } else {
235
236     $query = qq|SELECT nextval('id')|;
237     ($form->{id}) = selectrow_query($form, $dbh, $query);
238
239     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id, currency_id) VALUES (?, '', ?, (SELECT currency_id FROM defaults LIMIT 1))|;
240     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}));
241   }
242
243   my $project_id;
244   my $items_reqdate;
245
246   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
247   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
248   my $price_factor;
249
250   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
251   my @part_ids    = keys %part_id_map;
252   my %part_unit_map;
253
254   if (@part_ids) {
255     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
256     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
257   }
258
259   my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
260   my $h_item_id = prepare_query($form, $dbh, $q_item_id);
261
262   my $q_item =
263     qq|INSERT INTO delivery_order_items (
264          id, delivery_order_id, parts_id, description, longdescription, qty, base_qty,
265          sellprice, discount, unit, reqdate, project_id, serialnumber,
266          ordnumber, transdate, cusordnumber,
267          lastcost, price_factor_id, price_factor, marge_price_factor, pricegroup_id)
268        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
269          (SELECT factor FROM price_factors WHERE id = ?), ?, ?)|;
270   my $h_item = prepare_query($form, $dbh, $q_item);
271
272   my $q_item_stock =
273     qq|INSERT INTO delivery_order_items_stock (delivery_order_item_id, qty, unit, warehouse_id, bin_id, chargenumber, bestbefore)
274        VALUES (?, ?, ?, ?, ?, ?, ?)|;
275   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
276
277   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
278
279   for my $i (1 .. $form->{rowcount}) {
280     next if (!$form->{"id_$i"});
281
282     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
283
284     my $item_unit = $part_unit_map{$form->{"id_$i"}};
285
286     my $basefactor = 1;
287     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
288       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
289     }
290     my $baseqty = $form->{"qty_$i"} * $basefactor;
291
292     # set values to 0 if nothing entered
293     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"});
294     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
295     $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
296
297     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
298     my $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
299
300     $items_reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
301
302     do_statement($form, $h_item_id, $q_item_id);
303     my ($item_id) = $h_item_id->fetchrow_array();
304
305     # Get pricegroup_id and save it. Unfortunately the interface
306     # also uses ID "0" for signalling that none is selected, but "0"
307     # must not be stored in the database. Therefore we cannot simply
308     # use conv_i().
309     my $pricegroup_id = $form->{"pricegroup_id_$i"} * 1;
310     $pricegroup_id    = undef if !$pricegroup_id;
311
312     # save detail record in delivery_order_items table
313     @values = (conv_i($item_id), conv_i($form->{id}), conv_i($form->{"id_$i"}),
314                $form->{"description_$i"}, $form->{"longdescription_$i"},
315                $form->{"qty_$i"}, $baseqty,
316                $form->{"sellprice_$i"}, $form->{"discount_$i"} / 100,
317                $form->{"unit_$i"}, conv_date($items_reqdate), conv_i($form->{"project_id_$i"}),
318                $form->{"serialnumber_$i"},
319                $form->{"ordnumber_$i"}, conv_date($form->{"transdate_$i"}),
320                $form->{"cusordnumber_$i"},
321                $form->{"lastcost_$i"},
322                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
323                conv_i($form->{"marge_price_factor_$i"}),
324                $pricegroup_id);
325     do_statement($form, $h_item, $q_item, @values);
326
327     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
328
329     foreach my $sinfo (@{ $stock_info }) {
330       @values = ($item_id, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
331                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}));
332       do_statement($form, $h_item_stock, $q_item_stock, @values);
333     }
334
335     CVar->save_custom_variables(module       => 'IC',
336                                 sub_module   => 'delivery_order_items',
337                                 trans_id     => $item_id,
338                                 configs      => $ic_cvar_configs,
339                                 variables    => $form,
340                                 name_prefix  => 'ic_',
341                                 name_postfix => "_$i",
342                                 dbh          => $dbh);
343   }
344
345   $h_item_id->finish();
346   $h_item->finish();
347   $h_item_stock->finish();
348
349
350   # reqdate is last items reqdate (?: old behaviour) if not already set
351   $form->{reqdate} ||= $items_reqdate;
352   # save DO record
353   $query =
354     qq|UPDATE delivery_orders SET
355          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
356          customer_id = ?, reqdate = ?,
357          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
358          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
359          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
360          is_sales = ?, taxzone_id = ?, taxincluded = ?, terms = ?, currency_id = (SELECT id FROM currencies WHERE name = ?)
361        WHERE id = ?|;
362
363   @values = ($form->{donumber}, $form->{ordnumber},
364              $form->{cusordnumber}, conv_date($form->{transdate}),
365              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
366              conv_date($form->{reqdate}), $form->{shippingpoint}, $form->{shipvia},
367              $form->{notes}, $form->{intnotes},
368              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
369              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
370              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
371              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
372              $form->{transaction_description},
373              $form->{type} =~ /^sales/ ? 't' : 'f',
374              conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{terms}), $form->{currency},
375              conv_i($form->{id}));
376   do_query($form, $dbh, $query, @values);
377
378   # add shipto
379   $form->{name} = $form->{ $form->{vc} };
380   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
381
382   if (!$form->{shipto_id}) {
383     $form->add_shipto($dbh, $form->{id}, "DO");
384   }
385
386   # save printed, emailed, queued
387   $form->save_status($dbh);
388
389   # Link this delivery order to the quotations it was created from.
390   RecordLinks->create_links('dbh'        => $dbh,
391                             'mode'       => 'ids',
392                             'from_table' => 'oe',
393                             'from_ids'   => $form->{convert_from_oe_ids},
394                             'to_table'   => 'delivery_orders',
395                             'to_id'      => $form->{id},
396     );
397   delete $form->{convert_from_oe_ids};
398
399   $self->mark_orders_if_delivered('do_id' => $form->{id},
400                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
401                                   'dbh'   => $dbh,);
402
403   my $rc = $dbh->commit();
404
405   $form->{saved_donumber} = $form->{donumber};
406
407   Common::webdav_folder($form);
408
409   $main::lxdebug->leave_sub();
410
411   return $rc;
412 }
413
414 sub mark_orders_if_delivered {
415   $main::lxdebug->enter_sub();
416
417   my $self   = shift;
418   my %params = @_;
419
420   Common::check_params(\%params, qw(do_id type));
421
422   my $myconfig = \%main::myconfig;
423   my $form     = $main::form;
424
425   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
426
427   my @links    = RecordLinks->get_links('dbh'        => $dbh,
428                                         'from_table' => 'oe',
429                                         'to_table'   => 'delivery_orders',
430                                         'to_id'      => $params{do_id});
431
432   my $oe_id  = @links ? $links[0]->{from_id} : undef;
433
434   return $main::lxdebug->leave_sub() if (!$oe_id);
435
436   my $all_units = AM->retrieve_all_units();
437
438   my $query     = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
439                      FROM orderitems oi
440                      LEFT JOIN parts p ON (oi.parts_id = p.id)
441                      WHERE (oi.trans_id = ?)|;
442   my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
443
444   my %shipped   = $self->get_shipped_qty('type'  => $params{type},
445                                          'oe_id' => $oe_id,);
446   my %ordered   = ();
447
448   while (my $ref = $sth->fetchrow_hashref()) {
449     $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
450
451     if ($ordered{$ref->{parts_id}}) {
452       $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
453     } else {
454       $ordered{$ref->{parts_id}}             = $ref;
455     }
456   }
457
458   $sth->finish();
459
460   map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
461
462   my $delivered = 1;
463   foreach my $part (values %ordered) {
464     if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
465       $delivered = 0;
466       last;
467     }
468   }
469
470   if ($delivered) {
471     $query = qq|UPDATE oe
472                 SET delivered = TRUE
473                 WHERE id = ?|;
474     do_query($form, $dbh, $query, $oe_id);
475     $dbh->commit() if (!$params{dbh});
476   }
477
478   $main::lxdebug->leave_sub();
479 }
480
481 sub close_orders {
482   $main::lxdebug->enter_sub();
483
484   my $self     = shift;
485   my %params   = @_;
486
487   Common::check_params(\%params, qw(ids));
488
489   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
490     $main::lxdebug->leave_sub();
491     return;
492   }
493
494   my $myconfig = \%main::myconfig;
495   my $form     = $main::form;
496
497   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
498
499   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
500
501   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
502
503   $dbh->commit() unless ($params{dbh});
504
505   $main::lxdebug->leave_sub();
506 }
507
508 sub delete {
509   $main::lxdebug->enter_sub();
510
511   my ($self)   = @_;
512
513   my $myconfig = \%main::myconfig;
514   my $form     = $main::form;
515   my $spool    = $::lx_office_conf{paths}->{spool};
516
517   my $rc = SL::DB::Order->new->db->with_transaction(sub {
518     my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $form->{id} ]) };
519
520     SL::DB::DeliveryOrder->new(id => $form->{id})->delete;
521
522     my $spool = $::lx_office_conf{paths}->{spool};
523     unlink map { "$spool/$_" } @spoolfiles if $spool;
524
525     1;
526   });
527
528   $main::lxdebug->leave_sub();
529
530   return $rc;
531 }
532
533 sub retrieve {
534   $main::lxdebug->enter_sub();
535
536   my $self     = shift;
537   my %params   = @_;
538
539   my $myconfig = \%main::myconfig;
540   my $form     = $main::form;
541
542   # connect to database
543   my $dbh = $form->get_standard_dbh($myconfig);
544
545   my ($query, $query_add, @values, $sth, $ref);
546
547   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
548                                           dbh    => $dbh);
549
550   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
551
552   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
553
554   if ($mode eq 'default') {
555     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate|);
556     map { $form->{$_} = $ref->{$_} } keys %$ref;
557
558     # if reqdate is not set from oe-workflow, set it to transdate (which is current date)
559     $form->{reqdate} ||= $form->{transdate};
560
561     # get last name used
562     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
563
564     $main::lxdebug->leave_sub();
565
566     return 1;
567   }
568
569   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
570   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
571
572   # retrieve order for single id
573   # NOTE: this query is intended to fetch all information only ONCE.
574   # so if any of these infos is important (or even different) for any item,
575   # it will be killed out and then has to be fetched from the item scope query further down
576   $query =
577     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
578          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
579          e.name AS employee, dord.employee_id, dord.salesman_id,
580          dord.${vc}_id, cv.name AS ${vc},
581          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
582          d.description AS department, dord.language_id,
583          dord.shipto_id,
584          dord.globalproject_id, dord.delivered, dord.transaction_description,
585          dord.taxzone_id, dord.taxincluded, dord.terms, (SELECT cu.name FROM currencies cu WHERE cu.id=dord.currency_id) AS currency
586        FROM delivery_orders dord
587        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
588        LEFT JOIN employee e ON (dord.employee_id = e.id)
589        LEFT JOIN department d ON (dord.department_id = d.id)
590        WHERE dord.id IN ($do_ids_placeholders)|;
591   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
592
593   delete $form->{"${vc}_id"};
594   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
595     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
596       $sth->finish();
597       $main::lxdebug->leave_sub();
598
599       return 0;
600     }
601
602     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
603     $form->{donumber_array} .= $form->{donumber} . ' ';
604   }
605   $sth->finish();
606
607   $form->{donumber_array} =~ s/\s*$//g;
608
609   $form->{saved_donumber} = $form->{donumber};
610
611   # if not given, fill transdate with current_date
612   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
613
614   if ($mode eq 'single') {
615     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
616     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
617
618     $ref   = $sth->fetchrow_hashref("NAME_lc");
619     delete $ref->{id};
620     map { $form->{$_} = $ref->{$_} } keys %$ref;
621     $sth->finish();
622
623     # get printed, emailed and queued
624     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
625     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
626
627     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
628       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
629       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
630       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
631     }
632     $sth->finish();
633     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
634
635   } else {
636     delete $form->{id};
637   }
638
639   # retrieve individual items
640   # this query looks up all information about the items
641   # stuff different from the whole will not be overwritten, but saved with a suffix.
642   $query =
643     qq|SELECT doi.id AS delivery_order_items_id,
644          p.partnumber, p.assembly, p.listprice, doi.description, doi.qty,
645          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.notes AS partnotes,
646          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
647          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
648          doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
649          pr.projectnumber, dord.transdate AS dord_transdate,
650          pg.partsgroup
651        FROM delivery_order_items doi
652        JOIN parts p ON (doi.parts_id = p.id)
653        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
654        LEFT JOIN project pr ON (doi.project_id = pr.id)
655        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
656        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
657        ORDER BY doi.oid|;
658
659   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
660
661   # Retrieve custom variables.
662   foreach my $doi (@{ $form->{form_details} }) {
663     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
664                                            module     => 'IC',
665                                            sub_module => 'delivery_order_items',
666                                            trans_id   => $doi->{delivery_order_items_id},
667                                           );
668     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
669   }
670
671   if ($mode eq 'single') {
672     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
673
674     $query =
675       qq|SELECT qty, unit, bin_id, warehouse_id, chargenumber, bestbefore
676          FROM delivery_order_items_stock
677          WHERE delivery_order_item_id = ?|;
678     my $sth = prepare_query($form, $dbh, $query);
679
680     foreach my $doi (@{ $form->{form_details} }) {
681       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
682       my $requests = [];
683       while (my $ref = $sth->fetchrow_hashref()) {
684         push @{ $requests }, $ref;
685       }
686
687       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
688     }
689
690     $sth->finish();
691   }
692
693   Common::webdav_folder($form);
694
695   $main::lxdebug->leave_sub();
696
697   return 1;
698 }
699
700 sub order_details {
701   $main::lxdebug->enter_sub();
702
703   my ($self, $myconfig, $form) = @_;
704
705   # connect to database
706   my $dbh = $form->get_standard_dbh($myconfig);
707   my $query;
708   my @values = ();
709   my $sth;
710   my $item;
711   my $i;
712   my @partsgroup = ();
713   my $partsgroup;
714   my $position = 0;
715
716   my (@project_ids, %projectnumbers, %projectdescriptions);
717
718   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
719
720   # sort items by partsgroup
721   for $i (1 .. $form->{rowcount}) {
722     $partsgroup = "";
723     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
724       $partsgroup = $form->{"partsgroup_$i"};
725     }
726     push @partsgroup, [$i, $partsgroup];
727     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
728   }
729
730   if (@project_ids) {
731     $query = "SELECT id, projectnumber, description FROM project WHERE id IN (" .
732       join(", ", map("?", @project_ids)) . ")";
733     $sth = prepare_execute_query($form, $dbh, $query, @project_ids);
734     while (my $ref = $sth->fetchrow_hashref()) {
735       $projectnumbers{$ref->{id}} = $ref->{projectnumber};
736       $projectdescriptions{$ref->{id}} = $ref->{description};
737     }
738     $sth->finish();
739   }
740
741   $form->{"globalprojectnumber"} =
742     $projectnumbers{$form->{"globalproject_id"}};
743   $form->{"globalprojectdescription"} =
744       $projectdescriptions{$form->{"globalproject_id"}};
745
746   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
747                     FROM assembly a
748                     JOIN parts p ON (a.parts_id = p.id)
749                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
750                     WHERE a.bom = '1'
751                       AND a.id = ?|;
752   my $h_pg     = prepare_query($form, $dbh, $q_pg);
753
754   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
755                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
756   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
757
758   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
759
760   my $num_si   = 0;
761
762   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
763
764   $form->{TEMPLATE_ARRAYS} = { };
765   IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
766
767   my @arrays =
768     qw(runningnumber number description longdescription qty unit
769        partnotes serialnumber reqdate projectnumber projectdescription
770        si_runningnumber si_number si_description
771        si_warehouse si_bin si_chargenumber si_bestbefore si_qty si_unit weight lineweight);
772
773   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays);
774
775   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
776
777   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
778   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
779
780   my $totalweight = 0;
781   my $sameitem = "";
782   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
783     $i = $item->[0];
784
785     next if (!$form->{"id_$i"});
786
787     $position++;
788
789     if ($item->[1] ne $sameitem) {
790       push(@{ $form->{description} }, qq|$item->[1]|);
791       $sameitem = $item->[1];
792
793       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
794     }
795
796     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
797
798     # add number, description and qty to $form->{number}, ....
799
800     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
801
802     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
803     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
804     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
805     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
806     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
807     push @{ $form->{TEMPLATE_ARRAYS}{qty_nofmt} },       $form->{"qty_$i"};
808     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
809     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
810     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
811     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
812     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $projectnumbers{$form->{"project_id_$i"}};
813     push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} },
814       $projectdescriptions{$form->{"project_id_$i"}};
815
816     my $lineweight = $form->{"qty_$i"} * $form->{"weight_$i"};
817     $totalweight += $lineweight;
818     push @{ $form->{TEMPLATE_ARRAYS}->{weight} },            $form->format_amount($myconfig, $form->{"weight_$i"}, 3);
819     push @{ $form->{TEMPLATE_ARRAYS}->{weight_nofmt} },      $form->{"weight_$i"};
820     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight} },        $form->format_amount($myconfig, $lineweight, 3);
821     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight_nofmt} },  $lineweight;
822
823     if ($form->{"assembly_$i"}) {
824       $sameitem = "";
825
826       # get parts and push them onto the stack
827       my $sortorder = "";
828       if ($form->{groupitems}) {
829         $sortorder =
830           qq|ORDER BY pg.partsgroup, a.oid|;
831       } else {
832         $sortorder = qq|ORDER BY a.oid|;
833       }
834
835       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
836
837       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
838         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
839           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" } @arrays));
840           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
841           push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
842         }
843         push(@{ $form->{TEMPLATE_ARRAYS}->{"description"} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
844
845         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" } @arrays));
846       }
847     }
848
849     if ($form->{"inventory_accno_$i"} && !$form->{"assembly_$i"}) {
850       my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
851
852       foreach my $si (@{ $stock_info }) {
853         $num_si++;
854
855         do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
856         my $bin_wh = $h_bin_wh->fetchrow_hashref();
857
858         push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$position-1] }, $num_si;
859         push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$position-1] },        $form->{"partnumber_$i"};
860         push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$position-1] },   $form->{"description_$i"};
861         push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$position-1] },     $bin_wh->{warehouse};
862         push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$position-1] },           $bin_wh->{bin};
863         push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$position-1] },  $si->{chargenumber};
864         push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$position-1] },    $si->{bestbefore};
865         push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
866         push @{ $form->{TEMPLATE_ARRAYS}{si_qty_nofmt}[$position-1] },     $si->{qty} * 1;
867         push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$position-1] },          $si->{unit};
868       }
869     }
870
871     push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
872       CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
873         for @{ $ic_cvar_configs };
874   }
875
876   $form->{totalweight}       = $form->format_amount($myconfig, $totalweight, 3);
877   $form->{totalweight_nofmt} = $totalweight;
878   my $defaults = AM->get_defaults();
879   $form->{weightunit}        = $defaults->{weightunit};
880
881   $h_pg->finish();
882   $h_bin_wh->finish();
883
884   $form->{username} = $myconfig->{name};
885
886   $main::lxdebug->leave_sub();
887 }
888
889 sub project_description {
890   $main::lxdebug->enter_sub();
891
892   my ($self, $dbh, $id) = @_;
893
894   my $form     =  $main::form;
895
896   my $query = qq|SELECT description FROM project WHERE id = ?|;
897   my ($value) = selectrow_query($form, $dbh, $query, $id);
898
899   $main::lxdebug->leave_sub();
900
901   return $value;
902 }
903
904 sub unpack_stock_information {
905   $main::lxdebug->enter_sub();
906
907   my $self   = shift;
908   my %params = @_;
909
910   Common::check_params_x(\%params, qw(packed));
911
912   my $unpacked;
913
914   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
915
916   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
917
918   foreach my $entry (@{ $unpacked }) {
919     next if ('HASH' eq ref $entry);
920     $unpacked = [];
921     last;
922   }
923
924   $main::lxdebug->leave_sub();
925
926   return $unpacked;
927 }
928
929 sub get_item_availability {
930   $::lxdebug->enter_sub;
931
932   my $self     = shift;
933   my %params   = @_;
934
935   Common::check_params(\%params, qw(parts_id));
936
937   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
938
939   my $query     =
940     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
941          w.description AS warehousedescription,
942          b.description AS bindescription
943        FROM inventory i
944        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
945        LEFT JOIN bin b       ON (i.bin_id       = b.id)
946        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
947        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
948        HAVING SUM(qty) > 0
949        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
950 |;
951   my $contents = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, @parts_ids);
952
953   $::lxdebug->leave_sub;
954
955   return @{ $contents };
956 }
957
958
959 sub check_stock_availability {
960   $main::lxdebug->enter_sub();
961
962   my $self     = shift;
963   my %params   = @_;
964
965   Common::check_params(\%params, qw(requests parts_id));
966
967   my $myconfig    = \%main::myconfig;
968   my $form        =  $main::form;
969
970   my $dbh         = $form->get_standard_dbh($myconfig);
971
972   my $units       = AM->retrieve_units($myconfig, $form);
973
974   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
975   my $unit_factor = $units->{$partunit}->{factor} || 1;
976
977   my @contents    = $self->get_item_availability(%params);
978
979   my @errors;
980
981   foreach my $sinfo (@{ $params{requests} }) {
982     my $found = 0;
983
984     foreach my $row (@contents) {
985       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
986                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
987                ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
988                ($row->{bestbefore}   ne $sinfo->{bestbefore}));
989
990       $found       = 1;
991
992       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
993
994       if ($base_qty > $row->{qty}) {
995         $sinfo->{error} = 1;
996         push @errors, $sinfo;
997
998         last;
999       }
1000     }
1001
1002     push @errors, $sinfo if (!$found);
1003   }
1004
1005   $main::lxdebug->leave_sub();
1006
1007   return @errors;
1008 }
1009
1010 sub transfer_in_out {
1011   $main::lxdebug->enter_sub();
1012
1013   my $self     = shift;
1014   my %params   = @_;
1015
1016   Common::check_params(\%params, qw(direction requests));
1017
1018   if (!@{ $params{requests} }) {
1019     $main::lxdebug->leave_sub();
1020     return;
1021   }
1022
1023   my $myconfig = \%main::myconfig;
1024   my $form     = $main::form;
1025
1026   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
1027
1028   my @transfers;
1029
1030   foreach my $request (@{ $params{requests} }) {
1031     push @transfers, {
1032       'parts_id'               => $request->{parts_id},
1033       "${prefix}_warehouse_id" => $request->{warehouse_id},
1034       "${prefix}_bin_id"       => $request->{bin_id},
1035       'chargenumber'           => $request->{chargenumber},
1036       'bestbefore'             => $request->{bestbefore},
1037       'qty'                    => $request->{qty},
1038       'unit'                   => $request->{unit},
1039       'oe_id'                  => $form->{id},
1040       'shippingdate'           => 'current_date',
1041       'transfer_type'          => $params{direction} eq 'in' ? 'stock' : 'shipped',
1042       'project_id'             => $request->{project_id},
1043     };
1044   }
1045
1046   WH->transfer(@transfers);
1047
1048   $main::lxdebug->leave_sub();
1049 }
1050
1051 sub get_shipped_qty {
1052   $main::lxdebug->enter_sub();
1053
1054   my $self     = shift;
1055   my %params   = @_;
1056
1057   Common::check_params(\%params, qw(type oe_id));
1058
1059   my $myconfig = \%main::myconfig;
1060   my $form     = $main::form;
1061
1062   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1063
1064   my @links    = RecordLinks->get_links('dbh'        => $dbh,
1065                                         'from_table' => 'oe',
1066                                         'from_id'    => $params{oe_id},
1067                                         'to_table'   => 'delivery_orders');
1068   my @values   = map { $_->{to_id} } @links;
1069
1070   if (!scalar @values) {
1071     $main::lxdebug->leave_sub();
1072     return ();
1073   }
1074
1075   my $query =
1076     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
1077        FROM delivery_order_items doi
1078        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
1079        LEFT JOIN parts p ON (doi.parts_id = p.id)
1080        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
1081
1082   my %ship      = ();
1083   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
1084   my $all_units = AM->retrieve_all_units();
1085
1086   foreach my $entry (@{ $entries }) {
1087     $entry->{qty} *= AM->convert_unit($entry->{unit}, $entry->{partunit}, $all_units);
1088
1089     if (!$ship{$entry->{parts_id}}) {
1090       $ship{$entry->{parts_id}} = $entry;
1091     } else {
1092       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
1093     }
1094   }
1095
1096   $main::lxdebug->leave_sub();
1097
1098   return %ship;
1099 }
1100
1101 sub is_marked_as_delivered {
1102   $main::lxdebug->enter_sub();
1103
1104   my $self     = shift;
1105   my %params   = @_;
1106
1107   Common::check_params(\%params, qw(id));
1108
1109   my $myconfig    = \%main::myconfig;
1110   my $form        = $main::form;
1111
1112   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
1113
1114   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
1115
1116   $main::lxdebug->leave_sub();
1117
1118   return $delivered ? 1 : 0;
1119 }
1120
1121
1122 1;