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