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