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