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