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