Nutzung der Tabelle currencies
[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 = (SELECT id FROM currencies WHERE 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, (SELECT cu.curr FROM currencies cu WHERE cu.id=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   $form->{donumber_array} =~ s/\s*$//g;
642
643   $form->{saved_donumber} = $form->{donumber};
644
645   # if not given, fill transdate with current_date
646   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
647
648   if ($mode eq 'single') {
649     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
650     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
651
652     $ref   = $sth->fetchrow_hashref("NAME_lc");
653     delete $ref->{id};
654     map { $form->{$_} = $ref->{$_} } keys %$ref;
655     $sth->finish();
656
657     # get printed, emailed and queued
658     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
659     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
660
661     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
662       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
663       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
664       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
665     }
666     $sth->finish();
667     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
668
669   } else {
670     delete $form->{id};
671   }
672
673   my %oid = ('Pg'     => 'oid',
674              'Oracle' => 'rowid');
675
676   # retrieve individual items
677   # this query looks up all information about the items
678   # stuff different from the whole will not be overwritten, but saved with a suffix.
679   $query =
680     qq|SELECT doi.id AS delivery_order_items_id,
681          p.partnumber, p.assembly, p.listprice, doi.description, doi.qty,
682          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.bin, p.notes AS partnotes,
683          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
684          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
685          doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
686          pr.projectnumber, dord.transdate AS dord_transdate,
687          pg.partsgroup
688        FROM delivery_order_items doi
689        JOIN parts p ON (doi.parts_id = p.id)
690        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
691        LEFT JOIN project pr ON (doi.project_id = pr.id)
692        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
693        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
694        ORDER BY doi.$oid{$myconfig->{dbdriver}}|;
695
696   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
697
698   # Retrieve custom variables.
699   foreach my $doi (@{ $form->{form_details} }) {
700     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
701                                            module     => 'IC',
702                                            sub_module => 'delivery_order_items',
703                                            trans_id   => $doi->{delivery_order_items_id},
704                                           );
705     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
706   }
707
708   if ($mode eq 'single') {
709     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
710
711     $query =
712       qq|SELECT qty, unit, bin_id, warehouse_id, chargenumber, bestbefore
713          FROM delivery_order_items_stock
714          WHERE delivery_order_item_id = ?|;
715     my $sth = prepare_query($form, $dbh, $query);
716
717     foreach my $doi (@{ $form->{form_details} }) {
718       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
719       my $requests = [];
720       while (my $ref = $sth->fetchrow_hashref()) {
721         push @{ $requests }, $ref;
722       }
723
724       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
725     }
726
727     $sth->finish();
728   }
729
730   Common::webdav_folder($form);
731
732   $main::lxdebug->leave_sub();
733
734   return 1;
735 }
736
737 sub order_details {
738   $main::lxdebug->enter_sub();
739
740   my ($self)   = @_;
741
742   my $myconfig = \%main::myconfig;
743   my $form     = $main::form;
744
745   # connect to database
746   my $dbh = $form->get_standard_dbh($myconfig);
747   my $query;
748   my @values = ();
749   my $sth;
750   my $item;
751   my $i;
752   my @partsgroup = ();
753   my $partsgroup;
754   my $position = 0;
755
756   my %oid = ('Pg'     => 'oid',
757              'Oracle' => 'rowid');
758
759   my (@project_ids, %projectnumbers, %projectdescriptions);
760
761   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
762
763   # sort items by partsgroup
764   for $i (1 .. $form->{rowcount}) {
765     $partsgroup = "";
766     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
767       $partsgroup = $form->{"partsgroup_$i"};
768     }
769     push @partsgroup, [$i, $partsgroup];
770     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
771   }
772
773   if (@project_ids) {
774     $query = "SELECT id, projectnumber, description FROM project WHERE id IN (" .
775       join(", ", map("?", @project_ids)) . ")";
776     $sth = prepare_execute_query($form, $dbh, $query, @project_ids);
777     while (my $ref = $sth->fetchrow_hashref()) {
778       $projectnumbers{$ref->{id}} = $ref->{projectnumber};
779       $projectdescriptions{$ref->{id}} = $ref->{description};
780     }
781     $sth->finish();
782   }
783
784   $form->{"globalprojectnumber"} =
785     $projectnumbers{$form->{"globalproject_id"}};
786   $form->{"globalprojectdescription"} =
787       $projectdescriptions{$form->{"globalproject_id"}};
788
789   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
790                     FROM assembly a
791                     JOIN parts p ON (a.parts_id = p.id)
792                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
793                     WHERE a.bom = '1'
794                       AND a.id = ?|;
795   my $h_pg     = prepare_query($form, $dbh, $q_pg);
796
797   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
798                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
799   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
800
801   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
802
803   my $num_si   = 0;
804
805   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
806
807   $form->{TEMPLATE_ARRAYS} = { };
808   IC->prepare_parts_for_printing();
809
810   my @arrays =
811     qw(runningnumber number description longdescription qty unit
812        partnotes serialnumber reqdate projectnumber projectdescription
813        si_runningnumber si_number si_description
814        si_warehouse si_bin si_chargenumber si_bestbefore si_qty si_unit);
815
816   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays);
817
818   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
819
820   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
821   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
822
823   my $sameitem = "";
824   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
825     $i = $item->[0];
826
827     next if (!$form->{"id_$i"});
828
829     $position++;
830
831     if ($item->[1] ne $sameitem) {
832       push(@{ $form->{description} }, qq|$item->[1]|);
833       $sameitem = $item->[1];
834
835       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
836     }
837
838     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
839
840     # add number, description and qty to $form->{number}, ....
841
842     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
843
844     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
845     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
846     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
847     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
848     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
849     push @{ $form->{TEMPLATE_ARRAYS}{qty_nofmt} },       $form->{"qty_$i"};
850     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
851     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
852     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
853     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
854     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $projectnumbers{$form->{"project_id_$i"}};
855     push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} },
856       $projectdescriptions{$form->{"project_id_$i"}};
857
858     if ($form->{"assembly_$i"}) {
859       $sameitem = "";
860
861       # get parts and push them onto the stack
862       my $sortorder = "";
863       if ($form->{groupitems}) {
864         $sortorder =
865           qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
866       } else {
867         $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
868       }
869
870       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
871
872       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
873         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
874           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" } @arrays));
875           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
876           push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
877         }
878         push(@{ $form->{TEMPLATE_ARRAYS}->{"description"} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
879
880         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" } @arrays));
881       }
882     }
883
884     if ($form->{"inventory_accno_$i"} && !$form->{"assembly_$i"}) {
885       my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
886
887       foreach my $si (@{ $stock_info }) {
888         $num_si++;
889
890         do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
891         my $bin_wh = $h_bin_wh->fetchrow_hashref();
892
893         push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$position-1] }, $num_si;
894         push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$position-1] },        $form->{"partnumber_$i"};
895         push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$position-1] },   $form->{"description_$i"};
896         push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$position-1] },     $bin_wh->{warehouse};
897         push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$position-1] },           $bin_wh->{bin};
898         push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$position-1] },  $si->{chargenumber};
899         push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$position-1] },    $si->{bestbefore};
900         push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
901         push @{ $form->{TEMPLATE_ARRAYS}{si_qty_nofmt}[$position-1] },     $si->{qty} * 1;
902         push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$position-1] },          $si->{unit};
903       }
904     }
905
906     push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
907       CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
908         for @{ $ic_cvar_configs };
909   }
910
911   $h_pg->finish();
912   $h_bin_wh->finish();
913
914   $form->{username} = $myconfig->{name};
915
916   $main::lxdebug->leave_sub();
917 }
918
919 sub project_description {
920   $main::lxdebug->enter_sub();
921
922   my ($self, $dbh, $id) = @_;
923
924   my $form     =  $main::form;
925
926   my $query = qq|SELECT description FROM project WHERE id = ?|;
927   my ($value) = selectrow_query($form, $dbh, $query, $id);
928
929   $main::lxdebug->leave_sub();
930
931   return $value;
932 }
933
934 sub unpack_stock_information {
935   $main::lxdebug->enter_sub();
936
937   my $self   = shift;
938   my %params = @_;
939
940   Common::check_params_x(\%params, qw(packed));
941
942   my $unpacked;
943
944   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
945
946   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
947
948   foreach my $entry (@{ $unpacked }) {
949     next if ('HASH' eq ref $entry);
950     $unpacked = [];
951     last;
952   }
953
954   $main::lxdebug->leave_sub();
955
956   return $unpacked;
957 }
958
959 sub get_item_availability {
960   $::lxdebug->enter_sub;
961
962   my $self     = shift;
963   my %params   = @_;
964
965   Common::check_params(\%params, qw(parts_id));
966
967   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
968
969   my $query     =
970     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
971          w.description AS warehousedescription,
972          b.description AS bindescription
973        FROM inventory i
974        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
975        LEFT JOIN bin b       ON (i.bin_id       = b.id)
976        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
977        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
978        HAVING SUM(qty) > 0
979        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
980 |;
981   my $contents = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, @parts_ids);
982
983   $::lxdebug->leave_sub;
984
985   return @{ $contents };
986 }
987
988
989 sub check_stock_availability {
990   $main::lxdebug->enter_sub();
991
992   my $self     = shift;
993   my %params   = @_;
994
995   Common::check_params(\%params, qw(requests parts_id));
996
997   my $myconfig    = \%main::myconfig;
998   my $form        =  $main::form;
999
1000   my $dbh         = $form->get_standard_dbh($myconfig);
1001
1002   my $units       = AM->retrieve_units($myconfig, $form);
1003
1004   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
1005   my $unit_factor = $units->{$partunit}->{factor} || 1;
1006
1007   my @contents    = $self->get_item_availability(%params);
1008
1009   my @errors;
1010
1011   foreach my $sinfo (@{ $params{requests} }) {
1012     my $found = 0;
1013
1014     foreach my $row (@contents) {
1015       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
1016                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
1017                ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
1018                ($row->{bestbefore}   ne $sinfo->{bestbefore}));
1019
1020       $found       = 1;
1021
1022       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
1023
1024       if ($base_qty > $row->{qty}) {
1025         $sinfo->{error} = 1;
1026         push @errors, $sinfo;
1027
1028         last;
1029       }
1030     }
1031
1032     push @errors, $sinfo if (!$found);
1033   }
1034
1035   $main::lxdebug->leave_sub();
1036
1037   return @errors;
1038 }
1039
1040 sub transfer_in_out {
1041   $main::lxdebug->enter_sub();
1042
1043   my $self     = shift;
1044   my %params   = @_;
1045
1046   Common::check_params(\%params, qw(direction requests));
1047
1048   if (!@{ $params{requests} }) {
1049     $main::lxdebug->leave_sub();
1050     return;
1051   }
1052
1053   my $myconfig = \%main::myconfig;
1054   my $form     = $main::form;
1055
1056   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
1057
1058   my @transfers;
1059
1060   foreach my $request (@{ $params{requests} }) {
1061     push @transfers, {
1062       'parts_id'               => $request->{parts_id},
1063       "${prefix}_warehouse_id" => $request->{warehouse_id},
1064       "${prefix}_bin_id"       => $request->{bin_id},
1065       'chargenumber'           => $request->{chargenumber},
1066       'bestbefore'             => $request->{bestbefore},
1067       'qty'                    => $request->{qty},
1068       'unit'                   => $request->{unit},
1069       'oe_id'                  => $form->{id},
1070       'shippingdate'           => 'current_date',
1071       'transfer_type'          => $params{direction} eq 'in' ? 'stock' : 'shipped',
1072       'project_id'             => $request->{project_id},
1073     };
1074   }
1075
1076   WH->transfer(@transfers);
1077
1078   $main::lxdebug->leave_sub();
1079 }
1080
1081 sub get_shipped_qty {
1082   $main::lxdebug->enter_sub();
1083
1084   my $self     = shift;
1085   my %params   = @_;
1086
1087   Common::check_params(\%params, qw(type oe_id));
1088
1089   my $myconfig = \%main::myconfig;
1090   my $form     = $main::form;
1091
1092   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1093
1094   my @links    = RecordLinks->get_links('dbh'        => $dbh,
1095                                         'from_table' => 'oe',
1096                                         'from_id'    => $params{oe_id},
1097                                         'to_table'   => 'delivery_orders');
1098   my @values   = map { $_->{to_id} } @links;
1099
1100   if (!scalar @values) {
1101     $main::lxdebug->leave_sub();
1102     return ();
1103   }
1104
1105   my $query =
1106     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
1107        FROM delivery_order_items doi
1108        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
1109        LEFT JOIN parts p ON (doi.parts_id = p.id)
1110        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
1111
1112   my %ship      = ();
1113   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
1114   my $all_units = AM->retrieve_all_units();
1115
1116   foreach my $entry (@{ $entries }) {
1117     $entry->{qty} *= AM->convert_unit($entry->{unit}, $entry->{partunit}, $all_units);
1118
1119     if (!$ship{$entry->{parts_id}}) {
1120       $ship{$entry->{parts_id}} = $entry;
1121     } else {
1122       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
1123     }
1124   }
1125
1126   $main::lxdebug->leave_sub();
1127
1128   return %ship;
1129 }
1130
1131 sub is_marked_as_delivered {
1132   $main::lxdebug->enter_sub();
1133
1134   my $self     = shift;
1135   my %params   = @_;
1136
1137   Common::check_params(\%params, qw(id));
1138
1139   my $myconfig    = \%main::myconfig;
1140   my $form        = $main::form;
1141
1142   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
1143
1144   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
1145
1146   $main::lxdebug->leave_sub();
1147
1148   return $delivered ? 1 : 0;
1149 }
1150
1151
1152 1;