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