f981cd3849a95c387fd2eeb76686573ea8378574
[kivitendo-erp.git] / SL / IC.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) 2001
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 # Inventory Control backend
32 #
33 #======================================================================
34
35 package IC;
36
37 use Data::Dumper;
38 use YAML;
39
40 use SL::DBUtils;
41
42 sub get_part {
43   $main::lxdebug->enter_sub();
44
45   my ($self, $myconfig, $form) = @_;
46
47   # connect to db
48   my $dbh = $form->dbconnect($myconfig);
49
50   my $sth;
51
52   my $query =
53     qq|SELECT p.*,
54          c1.accno AS inventory_accno,
55          c2.accno AS income_accno,
56          c3.accno AS expense_accno,
57          pg.partsgroup
58        FROM parts p
59        LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
60        LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
61        LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
62        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
63        WHERE p.id = ? |;
64   my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
65
66   # copy to $form variables
67   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
68
69   $form->{onhand} *= 1;
70
71   my %oid = ('Pg'     => 'a.oid',
72              'Oracle' => 'a.rowid');
73
74   # part or service item
75   $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
76   if ($form->{assembly}) {
77     $form->{item} = 'assembly';
78
79     # retrieve assembly items
80     $query =
81       qq|SELECT p.id, p.partnumber, p.description,
82            p.sellprice, p.weight, a.qty, a.bom, p.unit,
83            pg.partsgroup
84          FROM parts p
85          JOIN assembly a ON (a.parts_id = p.id)
86          LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
87          WHERE (a.id = ?)
88          ORDER BY $oid{$myconfig->{dbdriver}}|;
89     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
90
91     $form->{assembly_rows} = 0;
92     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
93       $form->{assembly_rows}++;
94       foreach my $key (keys %{$ref}) {
95         $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
96       }
97     }
98     $sth->finish;
99
100   }
101
102   # setup accno hash for <option checked> {amount} is used in create_links
103   $form->{amount}{IC}         = $form->{inventory_accno};
104   $form->{amount}{IC_income}  = $form->{income_accno};
105   $form->{amount}{IC_sale}    = $form->{income_accno};
106   $form->{amount}{IC_expense} = $form->{expense_accno};
107   $form->{amount}{IC_cogs}    = $form->{expense_accno};
108
109   my @pricegroups          = ();
110   my @pricegroups_not_used = ();
111
112   # get prices
113   $query =
114     qq|SELECT p.parts_id, p.pricegroup_id, p.price,
115          (SELECT pg.pricegroup
116           FROM pricegroup pg
117           WHERE pg.id = p.pricegroup_id) AS pricegroup
118        FROM prices p
119        WHERE (parts_id = ?)
120        ORDER BY pricegroup|;
121   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
122
123   #for pricegroups
124   my $i = 1;
125   while (($form->{"klass_$i"}, $form->{"pricegroup_id_$i"},
126           $form->{"price_$i"}, $form->{"pricegroup_$i"})
127          = $sth->fetchrow_array()) {
128     $form->{"price_$i"} = $form->round_amount($form->{"price_$i"}, 5);
129     $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
130     push @pricegroups, $form->{"pricegroup_id_$i"};
131     $i++;
132   }
133
134   $sth->finish;
135
136   # get pricegroups
137   $query = qq|SELECT id, pricegroup FROM pricegroup|;
138   $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
139
140   #find not used pricegroups
141   while ($tmp = pop(@{ $form->{PRICEGROUPS} })) {
142     my $in_use = 0;
143     foreach my $item (@pricegroups) {
144       if ($item eq $tmp->{id}) {
145         $in_use = 1;
146         last;
147       }
148     }
149     push(@pricegroups_not_used, $tmp) unless ($in_use);
150   }
151
152   # if not used pricegroups are avaible
153   if (@pricegroups_not_used) {
154
155     foreach $name (@pricegroups_not_used) {
156       $form->{"klass_$i"} = "$name->{id}";
157       $form->{"price_$i"} = $form->round_amount($form->{sellprice}, 5);
158       $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
159       $form->{"pricegroup_id_$i"} = "$name->{id}";
160       $form->{"pricegroup_$i"}    = "$name->{pricegroup}";
161       $i++;
162     }
163   }
164
165   #correct rows
166   $form->{price_rows} = $i - 1;
167
168   unless ($form->{item} eq 'service') {
169
170     # get makes
171     if ($form->{makemodel}) {
172       $query = qq|SELECT m.make, m.model FROM makemodel m | .
173                qq|WHERE m.parts_id = ?|;
174       @values = ($form->{id});
175       $sth = $dbh->prepare($query);
176       $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
177
178       my $i = 1;
179       while (($form->{"make_$i"}, $form->{"model_$i"}) = $sth->fetchrow_array)
180       {
181         $i++;
182       }
183       $sth->finish;
184       $form->{makemodel_rows} = $i - 1;
185
186     }
187   }
188
189   # get translations
190   $form->{language_values} = "";
191   $query = qq|SELECT language_id, translation FROM translation WHERE parts_id = ?|;
192   my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
193   while ($tr = $trq->fetchrow_hashref(NAME_lc)) {
194     $form->{language_values} .= "---+++---".$tr->{language_id}."--++--".$tr->{translation};
195   }
196   $trq->finish;
197
198   # now get accno for taxes
199   $query =
200     qq|SELECT c.accno
201        FROM chart c, partstax pt
202        WHERE (pt.chart_id = c.id) AND (pt.parts_id = ?)|;
203   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
204   while (($key) = $sth->fetchrow_array) {
205     $form->{amount}{$key} = $key;
206   }
207
208   $sth->finish;
209
210   # is it an orphan
211   my @referencing_tables = qw(invoice orderitems invoice inventory rmaitems);
212   my %column_map         = ( );
213   my $parts_id           = conv_i($form->{id});
214
215   $form->{orphaned}      = 1;
216
217   foreach my $table (@referencing_tables) {
218     my $column  = $column_map{$table} || 'parts_id';
219     $query      = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
220     my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
221
222     if ($found) {
223       $form->{orphaned} = 0;
224       last;
225     }
226   }
227
228   $form->{"unit_changeable"} = $form->{orphaned};
229
230   $dbh->disconnect;
231
232   $main::lxdebug->leave_sub();
233 }
234
235 sub get_pricegroups {
236   $main::lxdebug->enter_sub();
237
238   my ($self, $myconfig, $form) = @_;
239
240   my $dbh = $form->dbconnect($myconfig);
241
242   # get pricegroups
243   my $query = qq|SELECT id, pricegroup FROM pricegroup|;
244   my $pricegroups = selectall_hashref_query($form, $dbh, $query);
245
246   my $i = 1;
247   foreach $pg (@{ $pricegroups }) {
248     $form->{"klass_$i"} = "$pg->{id}";
249     $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
250     $form->{"pricegroup_id_$i"} = "$pg->{id}";
251     $form->{"pricegroup_$i"}    = "$pg->{pricegroup}";
252     $i++;
253   }
254
255   #correct rows
256   $form->{price_rows} = $i - 1;
257
258   $dbh->disconnect;
259
260   $main::lxdebug->leave_sub();
261
262   return $pricegroups;
263 }
264
265 sub retrieve_buchungsgruppen {
266   $main::lxdebug->enter_sub();
267
268   my ($self, $myconfig, $form) = @_;
269
270   my ($query, $sth);
271
272   my $dbh = $form->dbconnect($myconfig);
273
274   # get buchungsgruppen
275   $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
276   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
277
278   $main::lxdebug->leave_sub();
279 }
280
281 sub save {
282   $main::lxdebug->enter_sub();
283
284   my ($self, $myconfig, $form) = @_;
285   my @values;
286   # connect to database, turn off AutoCommit
287   my $dbh = $form->dbconnect_noauto($myconfig);
288
289   # save the part
290   # make up a unique handle and store in partnumber field
291   # then retrieve the record based on the unique handle to get the id
292   # replace the partnumber field with the actual variable
293   # add records for makemodel
294
295   # if there is a $form->{id} then replace the old entry
296   # delete all makemodel entries and add the new ones
297
298   # undo amount formatting
299   map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
300     qw(rop weight listprice sellprice gv lastcost stock);
301
302   my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
303
304   $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
305
306   my ($query, $sth);
307
308   if ($form->{id}) {
309
310     # get old price
311     $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
312     my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
313
314     # if item is part of an assembly adjust all assemblies
315     $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
316     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
317     while (my ($id, $qty) = $sth->fetchrow_array) {
318       &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
319     }
320     $sth->finish;
321
322     if ($form->{item} ne 'service') {
323       # delete makemodel records
324       do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
325     }
326
327     if ($form->{item} eq 'assembly') {
328       # delete assembly records
329       do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
330     }
331
332     # delete tax records
333     do_query($form, $dbh, qq|DELETE FROM partstax WHERE parts_id = ?|, conv_i($form->{id}));
334
335     # delete translations
336     do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
337
338   } else {
339     my ($count) = selectrow_query($form, $dbh, qq|SELECT COUNT(*) FROM parts WHERE partnumber = ?|, $form->{partnumber});
340     if ($count) {
341       $main::lxdebug->leave_sub();
342       return 3;
343     }
344
345     ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
346     do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber) VALUES (?, '')|, $form->{id});
347
348     $form->{orphaned} = 1;
349     if ($form->{partnumber} eq "" && $form->{"item"} eq "service") {
350       $form->{partnumber} = $form->update_defaults($myconfig, "servicenumber");
351     }
352     if ($form->{partnumber} eq "" && $form->{"item"} ne "service") {
353       $form->{partnumber} = $form->update_defaults($myconfig, "articlenumber");
354     }
355
356   }
357   my $partsgroup_id = 0;
358
359   if ($form->{partsgroup}) {
360     ($partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
361   }
362
363   my ($subq_inventory, $subq_expense, $subq_income);
364   if ($form->{"item"} eq "part") {
365     $subq_inventory =
366       qq|(SELECT bg.inventory_accno_id
367           FROM buchungsgruppen bg
368           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
369   } else {
370     $subq_inventory = "NULL";
371   }
372
373   if ($form->{"item"} ne "assembly") {
374     $subq_expense =
375       qq|(SELECT bg.expense_accno_id_0
376           FROM buchungsgruppen bg
377           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
378   } else {
379     $subq_expense = "NULL";
380   }
381
382   $query =
383     qq|UPDATE parts SET
384          partnumber = ?,
385          description = ?,
386          makemodel = ?,
387          alternate = 'f',
388          assembly = ?,
389          listprice = ?,
390          sellprice = ?,
391          lastcost = ?,
392          weight = ?,
393          priceupdate = ?,
394          unit = ?,
395          notes = ?,
396          formel = ?,
397          rop = ?,
398          bin = ?,
399          buchungsgruppen_id = ?,
400          payment_id = ?,
401          inventory_accno_id = $subq_inventory,
402          income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
403          expense_accno_id = $subq_expense,
404          obsolete = ?,
405          image = ?,
406          drawing = ?,
407          shop = ?,
408          ve = ?,
409          gv = ?,
410          ean = ?,
411          not_discountable = ?,
412          microfiche = ?,
413          partsgroup_id = ?,
414          price_factor_id = ?
415        WHERE id = ?|;
416   @values = ($form->{partnumber},
417              $form->{description},
418              $makemodel ? 't' : 'f',
419              $form->{assembly} ? 't' : 'f',
420              $form->{listprice},
421              $form->{sellprice},
422              $form->{lastcost},
423              $form->{weight},
424              conv_date($form->{priceupdate}),
425              $form->{unit},
426              $form->{notes},
427              $form->{formel},
428              $form->{rop},
429              $form->{bin},
430              conv_i($form->{buchungsgruppen_id}),
431              conv_i($form->{payment_id}),
432              conv_i($form->{buchungsgruppen_id}),
433              $form->{obsolete} ? 't' : 'f',
434              $form->{image},
435              $form->{drawing},
436              $form->{shop} ? 't' : 'f',
437              conv_i($form->{ve}),
438              conv_i($form->{gv}),
439              $form->{ean},
440              $form->{not_discountable} ? 't' : 'f',
441              $form->{microfiche},
442              conv_i($partsgroup_id),
443              conv_i($form->{price_factor_id}),
444              conv_i($form->{id})
445   );
446   do_query($form, $dbh, $query, @values);
447
448   # delete translation records
449   do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
450
451   if ($form->{language_values} ne "") {
452     foreach $item (split(/---\+\+\+---/, $form->{language_values})) {
453       my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
454       if ($translation ne "") {
455         $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
456                     VALUES ( ?, ?, ?, ? )|;
457         @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
458         do_query($form, $dbh, $query, @values);
459       }
460     }
461   }
462
463   # delete price records
464   do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
465
466   # insert price records only if different to sellprice
467   for my $i (1 .. $form->{price_rows}) {
468     if ($form->{"price_$i"} eq "0") {
469       $form->{"price_$i"} = $form->{sellprice};
470     }
471     if (
472         (   $form->{"price_$i"}
473          || $form->{"klass_$i"}
474          || $form->{"pricegroup_id_$i"})
475         and $form->{"price_$i"} != $form->{sellprice}
476       ) {
477       #$klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
478       $price = $form->parse_amount($myconfig, $form->{"price_$i"});
479       $pricegroup_id =
480         $form->parse_amount($myconfig, $form->{"pricegroup_id_$i"});
481       $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) | .
482                qq|VALUES(?, ?, ?)|;
483       @values = (conv_i($form->{id}), conv_i($pricegroup_id), $price);
484       do_query($form, $dbh, $query, @values);
485     }
486   }
487
488   # insert makemodel records
489   unless ($form->{item} eq 'service') {
490     for my $i (1 .. $form->{makemodel_rows}) {
491       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
492         map { $form->{"${_}_$i"} =~ s/\'/\'\'/g } qw(make model);
493
494         $query = qq|INSERT INTO makemodel (parts_id, make, model) | .
495                              qq|VALUES (?, ?, ?)|;
496                     @values = (conv_i($form->{id}), $form->{"make_$i"}, $form->{"model_$i"});
497         do_query($form, $dbh, $query, @values);
498       }
499     }
500   }
501
502   # insert taxes
503   foreach $item (split(/ /, $form->{taxaccounts})) {
504     if ($form->{"IC_tax_$item"}) {
505       $query =
506         qq|INSERT INTO partstax (parts_id, chart_id)
507            VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
508                         @values = (conv_i($form->{id}), $item);
509       do_query($form, $dbh, $query, @values);
510     }
511   }
512
513   # add assembly records
514   if ($form->{item} eq 'assembly') {
515
516     for my $i (1 .. $form->{assembly_rows}) {
517       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
518
519       if ($form->{"qty_$i"} != 0) {
520         $form->{"bom_$i"} *= 1;
521         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
522                              qq|VALUES (?, ?, ?, ?)|;
523                     @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
524         do_query($form, $dbh, $query, @values);
525       }
526     }
527
528     @a = localtime;
529     $a[5] += 1900;
530     $a[4]++;
531     my $shippingdate = "$a[5]-$a[4]-$a[3]";
532
533     $form->get_employee($dbh);
534
535   }
536
537   #set expense_accno=inventory_accno if they are different => bilanz
538   $vendor_accno =
539     ($form->{expense_accno} != $form->{inventory_accno})
540     ? $form->{inventory_accno}
541     : $form->{expense_accno};
542
543   # get tax rates and description
544   $accno_id =
545     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
546   $query =
547     qq|SELECT c.accno, c.description, t.rate, t.taxnumber
548        FROM chart c, tax t
549        WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
550        ORDER BY c.accno|;
551   $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
552
553   $form->{taxaccount} = "";
554   while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
555     $form->{taxaccount} .= "$ptr->{accno} ";
556     if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
557       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
558       $form->{"$ptr->{accno}_description"} = $ptr->{description};
559       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
560       $form->{taxaccount2} .= " $ptr->{accno} ";
561     }
562   }
563
564   # commit
565   my $rc = $dbh->commit;
566   $dbh->disconnect;
567
568   $main::lxdebug->leave_sub();
569
570   return $rc;
571 }
572
573 sub update_assembly {
574   $main::lxdebug->enter_sub();
575
576   my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
577
578   my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
579   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
580
581   while (my ($pid, $aqty) = $sth->fetchrow_array) {
582     &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
583   }
584   $sth->finish;
585
586   $query =
587     qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
588        WHERE id = ?|;
589   @values = ($qty * ($form->{sellprice} - $sellprice),
590              $qty * ($form->{weight} - $weight), conv_i($id));
591   do_query($form, $dbh, $query, @values);
592
593   $main::lxdebug->leave_sub();
594 }
595
596 sub retrieve_assemblies {
597   $main::lxdebug->enter_sub();
598
599   my ($self, $myconfig, $form) = @_;
600
601   # connect to database
602   my $dbh = $form->dbconnect($myconfig);
603
604   my $where = qq|NOT p.obsolete|;
605   my @values;
606
607   if ($form->{partnumber}) {
608     $where .= qq| AND (p.partnumber ILIKE ?)|;
609     push(@values, '%' . $form->{partnumber} . '%');
610   }
611
612   if ($form->{description}) {
613     $where .= qq| AND (p.description ILIKE ?)|;
614     push(@values, '%' . $form->{description} . '%');
615   }
616
617   # retrieve assembly items
618   my $query =
619     qq|SELECT p.id, p.partnumber, p.description,
620          p.bin, p.onhand, p.rop,
621          (SELECT sum(p2.inventory_accno_id)
622           FROM parts p2, assembly a
623           WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
624        FROM parts p
625        WHERE NOT p.obsolete AND p.assembly $where|;
626
627   $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
628
629   $dbh->disconnect;
630
631   $main::lxdebug->leave_sub();
632 }
633
634 sub delete {
635   $main::lxdebug->enter_sub();
636
637   my ($self, $myconfig, $form) = @_;
638   my @values = (conv_i($form->{id}));
639   # connect to database, turn off AutoCommit
640   my $dbh = $form->dbconnect_noauto($myconfig);
641
642   my %columns = ( "assembly" => "id", "parts" => "id" );
643
644   for my $table (qw(prices partstax makemodel inventory assembly license translation parts)) {
645     my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
646     do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
647   }
648
649   # commit
650   my $rc = $dbh->commit;
651   $dbh->disconnect;
652
653   $main::lxdebug->leave_sub();
654
655   return $rc;
656 }
657
658 sub assembly_item {
659   $main::lxdebug->enter_sub();
660
661   my ($self, $myconfig, $form) = @_;
662
663   my $i = $form->{assembly_rows};
664   my $var;
665   my $where = qq|1 = 1|;
666   my @values;
667
668   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
669
670   while (my ($column, $table) = each(%columns)) {
671     next unless ($form->{"${column}_$i"});
672     $where .= qq| AND ${table}.${column} ILIKE ?|;
673     push(@values, '%' . $form->{"${column}_$i"} . '%');
674   }
675
676   if ($form->{id}) {
677     $where .= qq| AND NOT (p.id = ?)|;
678     push(@values, conv_i($form->{id}));
679   }
680
681   if ($partnumber) {
682     $where .= qq| ORDER BY p.partnumber|;
683   } else {
684     $where .= qq| ORDER BY p.description|;
685   }
686
687   # connect to database
688   my $dbh = $form->dbconnect($myconfig);
689
690   my $query =
691     qq|SELECT p.id, p.partnumber, p.description, p.sellprice, p.weight, p.onhand, p.unit, pg.partsgroup
692        FROM parts p
693        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
694        WHERE $where|;
695   $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
696
697   $dbh->disconnect;
698
699   $main::lxdebug->leave_sub();
700 }
701
702 #
703 # Report for Wares.
704 # Warning, deep magic ahead.
705 # This function gets all parts from the database according to the filters specified
706 #
707 # specials:
708 #   sort revers  - sorting field + direction
709 #   top100
710 #
711 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
712 #   partnumber ean description partsgroup microfiche drawing
713 #
714 # column flags:
715 #   l_partnumber l_description l_listprice l_sellprice l_lastcost l_priceupdate l_weight l_unit l_bin l_rop l_image l_drawing l_microfiche l_partsgroup
716 #
717 # exclusives:
718 #   itemstatus  = active | onhand | short | obsolete | orphaned
719 #   searchitems = part | assembly | service
720 #
721 # joining filters:
722 #   make model                               - makemodel
723 #   serialnumber transdatefrom transdateto   - invoice/orderitems
724 #
725 # binary flags:
726 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
727 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
728 #   l_soldtotal                              - aggreg join to display total of sold quantity
729 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
730 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
731 #   l_serialnumber                           - belonges to serialnumber filter
732 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
733 #   l_soldtotal                              - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
734 #
735 # not working:
736 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
737 #   masking of onhand in bsooqr mode         - ToDO: fixme
738 #
739 # disabled sanity checks and changes:
740 #  - searchitems = assembly will no longer disable bought
741 #  - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
742 #  - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
743 #  - itemstatus = obsolete will no longer disable onhand, short
744 #  - allow sorting by ean
745 #  - serialnumber filter also works if l_serialnumber isn't ticked
746 #  - onhand doesn't get masked by it's oi or invoice counterparts atm. ToDO: fix this
747 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
748 #
749 sub all_parts {
750   $main::lxdebug->enter_sub();
751
752   my ($self, $myconfig, $form) = @_;
753   my $dbh = $form->get_standard_dbh($myconfig);
754
755   $form->{parts}     = +{ };
756   $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
757
758   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
759   my @makemodel_filters    = qw(make model);
760   my @invoice_oi_filters   = qw(serialnumber soldtotal);
761   my @apoe_filters         = qw(transdate);
762   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
763   my @simple_l_switches    = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
764   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
765   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module);
766   my @deliverydate_flags   = qw(deliverydate);
767 #  my @other_flags          = qw(onhand); # ToDO: implement these
768 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
769
770   my %joins = (
771     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
772     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
773     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
774     invoice_oi =>
775       q|LEFT JOIN (
776          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem, 'invoice'    AS ioi FROM invoice UNION
777          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, 'orderitems' AS ioi FROM orderitems
778        ) AS ioi ON ioi.parts_id = p.id|,
779     apoe       =>
780       q|LEFT JOIN (
781          SELECT id, transdate, 'ir' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation, NULL AS customer_id,         vendor_id, NULL AS deliverydate FROM ap UNION
782          SELECT id, transdate, 'is' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation,         customer_id, NULL AS vendor_id,         deliverydate FROM ar UNION
783          SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber,          quotation,         customer_id,         vendor_id, NULL AS deliverydate FROM oe
784        ) AS apoe ON ioi.trans_id = apoe.id|,
785     cv         =>
786       q|LEFT JOIN (
787            SELECT id, name, 'customer' AS cv FROM customer UNION
788            SELECT id, name, 'vendor'   AS cv FROM vendor
789          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
790   );
791   my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
792   my %joins_needed;
793
794   #===== switches and simple filters ========#
795
796   my @select_tokens = qw(id factor);
797   my @where_tokens  = qw(1=1);
798   my @group_tokens  = ();
799
800   # special case transdate
801   if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
802     $form->{"l_transdate"} = 1;
803     push @select_tokens, 'transdate';
804     for (qw(transdatefrom transdateto)) {
805       next unless $form->{$_};
806       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
807       push @bind_vars,    $form->{$_};
808     }
809   }
810
811   my %simple_filter_table_prefix = (
812      description  => 'p.',
813   );
814
815   foreach (@simple_filters, @makemodel_filters, @invoice_oi_filters) {
816     next unless $form->{$_};
817     $form->{"l_$_"} = '1'; # show the column
818     push @where_tokens, "$simple_filter_table_prefix{$_}$_ ILIKE ?";
819     push @bind_vars,    "%$form->{$_}%";
820   }
821
822   foreach (@simple_l_switches) {
823     next unless $form->{"l_$_"};
824     push @select_tokens, $_;
825   }
826
827   for ($form->{searchitems}) {
828     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
829     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
830     push @where_tokens, 'NOT p.assembly'               if /service/;
831     push @where_tokens, '    p.assembly'               if /assembly/;
832   }
833
834   for ($form->{itemstatus}) {
835     push @where_tokens, 'p.id NOT IN
836         (SELECT DISTINCT parts_id FROM invoice UNION
837          SELECT DISTINCT parts_id FROM assembly UNION
838          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
839     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
840     push @where_tokens, 'NOT p.obsolete'               if /active/;
841     push @where_tokens, '    p.obsolete',              if /obsolete/;
842     push @where_tokens, 'p.onhand > 0',                if /onhand/;
843     push @where_tokens, 'p.onhand < p.rop',            if /short/;
844   }
845
846
847   my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
848   $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols;
849
850   my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
851
852   # special case: sorting by partnumber
853   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
854   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
855   # ToDO: implement proper functional sorting
856   $form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
857     if $form->{sort} eq 'partnumber';
858
859   my $order_clause = " ORDER BY $form->{sort} $sort_order";
860
861   my $limit_clause = " LIMIT 100" if $form->{top100};
862
863   #=== joins and complicated filters ========#
864
865   my $bsooqr = $form->{bought}  || $form->{sold}
866             || $form->{ordered} || $form->{onorder}
867             || $form->{quoted}  || $form->{rfq};
868
869   my @bsooqr;
870   push @select_tokens, @qsooqr_flags                                          if $bsooqr;
871   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
872   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
873   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
874   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
875   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
876   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
877   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
878   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
879
880   $joins_needed{partsgroup}  = 1;
881   $joins_needed{pfac}        = 1;
882   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
883   $joins_needed{cv}          = 1 if $bsooqr;
884   $joins_needed{apoe}        = 1 if $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
885   $joins_needed{invoice_oi}  = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
886
887   # special case for description search.
888   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
889   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
890   # find the old entries in of @where_tokens and @bind_vars, and adjust them
891   if ($joins_needed{invoice_oi}) {
892     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
893       next unless $where_tokens[$wi] =~ /^description ILIKE/;
894       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
895       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
896       last;
897     }
898   }
899
900   # now the master trick: soldtotal.
901   if ($form->{l_soldtotal}) {
902     push @where_tokens, 'ioi.qty >= 0';
903     push @group_tokens, @select_tokens;
904     push @select_tokens, 'SUM(ioi.qty)';
905   }
906
907   #============= build query ================#
908
909   %table_prefix = (
910      %table_prefix,
911      deliverydate => 'apoe.', serialnumber => 'ioi.',
912      transdate    => 'apoe.', trans_id     => 'ioi.',
913      module       => 'apoe.', name         => 'cv.',
914      ordnumber    => 'apoe.', make         => 'mm.',
915      quonumber    => 'apoe.', model        => 'mm.',
916      invnumber    => 'apoe.', partsgroup   => 'pg.',
917      factor       => 'pfac.',
918      'SUM(ioi.qty)' => ' ',
919   );
920
921   my %renamed_columns = (
922     'factor'       => 'price_factor',
923     'SUM(ioi.qty)' => 'soldtotal',
924   );
925
926   map { $table_prefix{$_} = 'ioi.' } qw(description serialnumber qty unit) if $joins_needed{invoice_oi};
927   map { $renamed_columns{$_} = ' AS ' . $renamed_columns{$_} } keys %renamed_columns;
928
929   my $select_clause = join ', ',    map { ($table_prefix{$_} || "p.") . $_ . $renamed_columns{$_} } @select_tokens;
930   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
931   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
932   my $group_clause  = ' GROUP BY ' . join ', ',    map { ($table_prefix{$_} || "p.") . $_ } @group_tokens if scalar @group_tokens;
933
934   my $query = qq|SELECT DISTINCT $select_clause FROM parts p $join_clause WHERE $where_clause $group_clause $order_clause $limit_clause|;
935
936   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
937
938   map { $_->{onhand} *= 1 } @{ $form->{parts} };
939
940 ##  my $where = qq|1 = 1|;
941 ##  my (@values, $var, $flds, $group, $limit);
942 ##
943 ##  foreach my $item (qw(partnumber drawing microfiche ean pg.partsgroup)) {
944 ##    my $column = $item;
945 ##    $column =~ s/.*\.//; # get rid of table prefixes
946 ##    if ($form->{$column}) {
947 ##      $where .= qq| AND ($item ILIKE ?)|;
948 ##      push(@values, "%$form->{$column}%");
949 ##    }
950 ##  }
951 ##
952 ##  # special case for description
953 ##  if ($form->{description}
954 ##      && !(   $form->{bought}  || $form->{sold} || $form->{onorder}
955 ##           || $form->{ordered} || $form->{rfq} || $form->{quoted})) {
956 ##    $where .= qq| AND (p.description ILIKE ?)|;
957 ##    push(@values, "%$form->{description}%");
958 ##  }
959 ##
960 ##  # special case for serialnumber
961 ##  if ($form->{l_serialnumber} && $form->{serialnumber}) {
962 ##    $where .= qq| AND (serialnumber ILIKE ?)|;
963 ##    push(@values, "%$form->{serialnumber}%");
964 ##  }
965 ##
966 ##  if ($form->{searchitems} eq 'part') {
967 ##    $where .= qq| AND (p.inventory_accno_id > 0) |;
968 ##  }
969 ##
970 ##  if ($form->{searchitems} eq 'assembly') {
971 ##    $form->{bought} = "";
972 ##    $where .= qq| AND p.assembly|;
973 ##  }
974 ##
975 ##  if ($form->{searchitems} eq 'service') {
976 ##    $where .= qq| AND (p.inventory_accno_id IS NULL) AND NOT (p.assembly = '1')|;
977 ##    # irrelevant for services
978 ##    map { $form->{$_} = '' } qw(make model);
979 ##  }
980 ##
981 ##  # items which were never bought, sold or on an order
982 ##  if ($form->{itemstatus} eq 'orphaned') {
983 ##    map { $form->{$_} = 0  } qw(onhand short bought sold onorder ordered rfq quoted);
984 ##    map { $form->{$_} = '' } qw(transdatefrom transdateto);
985 ##
986 ##    $where .=
987 ##      qq| AND (p.onhand = 0)
988 ##          AND p.id NOT IN
989 ##            (
990 ##              SELECT DISTINCT parts_id FROM invoice
991 ##              UNION
992 ##              SELECT DISTINCT parts_id FROM assembly
993 ##              UNION
994 ##              SELECT DISTINCT parts_id FROM orderitems
995 ##            )|;
996 ##  }
997 ##
998 ##  my %status2condition = (
999 ##    active   => " AND (p.obsolete = '0')",
1000 ##    obsolete => " AND (p.obsolete = '1')",
1001 ##    onhand   => " AND (p.onhand > 0)",
1002 ##    short    => " AND (p.onhand < p.rop)",
1003 ##  );
1004 ##  $where .= $status2condition{$form->{itemstatus}};
1005 ##
1006 ##  $form->{onhand} = $form->{short} = 0 if ($form->{itemstatus} eq 'obsolete');
1007 ##
1008 ##  my @subcolumns;
1009 ##  foreach my $column (qw(make model)) {
1010 ##    push @subcolumns, $column if $form->{$column};
1011 ##  }
1012 ##  if (@subcolumns) {
1013 ##    $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE | . (join " AND ", map { "($_ ILIKE ?)"; } @subcolumns) . ")";
1014 ##    push @values, map { '%' . $form->{$_} . '%' } @subcolumns;
1015 ##  }
1016 ##
1017 ##  if ($form->{l_soldtotal}) {
1018 ##    $where .= qq| AND (p.id = i.parts_id) AND (i.qty >= 0)|;
1019 ##    $group = qq| GROUP BY p.id, p.partnumber, p.description, p.onhand, p.unit, p.bin, p.sellprice, p.listprice, p.lastcost, p.priceupdate, pg.partsgroup|;
1020 ##  }
1021 ##
1022 ##  $limit = qq| LIMIT 100| if ($form->{top100});
1023 ##
1024 ##  # connect to database
1025 ##  my $dbh = $form->dbconnect($myconfig);
1026 ##
1027 ##  my @sort_cols = qw(id partnumber description partsgroup bin priceupdate onhand
1028 ##                     invnumber ordnumber quonumber name drawing microfiche
1029 ##                     serialnumber soldtotal deliverydate);
1030 ##
1031 ##  my $sortorder = "partnumber";
1032 ##  $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } @sort_cols));
1033 ##  $sortorder .= " DESC" if ($form->{revers});
1034 ##
1035 ##  my $query = "";
1036 ##
1037 ##  if ($form->{l_soldtotal}) {
1038 ##    $form->{soldtotal} = 'soldtotal';
1039 ##    $query =
1040 ##      qq|SELECT p.id, p.partnumber, p.description, p.onhand, p.unit,
1041 ##           p.bin, p.sellprice, p.listprice, p.lastcost,
1042 ##           p.priceupdate, pg.partsgroup,sum(i.qty) AS soldtotal
1043 ##         FROM parts p
1044 ##         LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id), invoice i
1045 ##         WHERE $where
1046 ##         $group
1047 ##         ORDER BY $sortorder $limit|;
1048 ##  } else {
1049 ##    $query =
1050 ##      qq|SELECT p.id, p.partnumber, p.description, p.onhand, p.unit,
1051 ##           p.bin, p.sellprice, p.listprice, p.lastcost, p.rop, p.weight,
1052 ##           p.priceupdate, p.image, p.drawing, p.microfiche,
1053 ##           pg.partsgroup
1054 ##         FROM parts p
1055 ##         LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1056 ##         WHERE $where
1057 ##         $group
1058 ##         ORDER BY $sortorder $limit|;
1059 ##  }
1060 ##
1061 ##  my @all_values = @values;
1062 ##
1063 ##  # rebuild query for bought and sold items
1064 ##  if (   $form->{bought}
1065 ##      || $form->{sold}
1066 ##      || $form->{onorder}
1067 ##      || $form->{ordered}
1068 ##      || $form->{rfq}
1069 ##      || $form->{quoted}) {
1070 ##    my $union = "";
1071 ##    $query = "";
1072 ##    @all_values = ();
1073 ##
1074 ##    if ($form->{bought} || $form->{sold}) {
1075 ##
1076 ##      my @invvalues = @values;
1077 ##      my $invwhere = "$where";
1078 #      $invwhere .= qq| AND i.assemblyitem = '0'|;
1079 ##
1080 ##      if ($form->{transdatefrom}) {
1081 ##        $invwhere .= qq| AND a.transdate >= ?|;
1082 ##        push(@invvalues, $form->{transdatefrom});
1083 ##      }
1084 ##
1085 ##      if ($form->{transdateto}) {
1086 ##        $invwhere .= qq| AND a.transdate <= ?|;
1087 ##        push(@invvalues, $form->{transdateto});
1088 ##      }
1089 ##
1090 ##      if ($form->{description}) {
1091 ##        $invwhere .= qq| AND i.description ILIKE ?|;
1092 ##        push(@invvalues, '%' . $form->{description} . '%');
1093 ##      }
1094 ##
1095 ##      $flds =
1096 ##        qq|p.id, p.partnumber, i.description, i.serialnumber,
1097 #           i.qty AS onhand, i.unit, p.bin, i.sellprice,
1098 ##           p.listprice, p.lastcost, p.rop, p.weight,
1099 ##           p.priceupdate, p.image, p.drawing, p.microfiche,
1100 ##           pg.partsgroup,
1101 ##           a.invnumber, a.ordnumber, a.quonumber, i.trans_id,
1102 ##           ct.name, i.deliverydate|;
1103 ##
1104 ##      if ($form->{bought}) {
1105 ##        $query =
1106 ##          qq|SELECT $flds, 'ir' AS module, '' AS type, 1 AS exchangerate
1107 ##             FROM invoice i
1108 ##             JOIN parts p ON (p.id = i.parts_id)
1109 ##             JOIN ap a ON (a.id = i.trans_id)
1110 ##             JOIN vendor ct ON (a.vendor_id = ct.id)
1111 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1112 ##             WHERE $invwhere|;
1113 ##
1114 ##        $union = qq| UNION |;
1115 ##
1116 ##        push(@all_values, @invvalues);
1117 ##      }
1118 ##
1119 ##      if ($form->{sold}) {
1120 ##        $query .=
1121 ##          qq|$union
1122 ##
1123 ##             SELECT $flds, 'is' AS module, '' AS type, 1 As exchangerate
1124 ##             FROM invoice i
1125 ##             JOIN parts p ON (p.id = i.parts_id)
1126 ##             JOIN ar a ON (a.id = i.trans_id)
1127 ##             JOIN customer ct ON (a.customer_id = ct.id)
1128 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1129 ##             WHERE $invwhere|;
1130 ##        $union = qq| UNION |;
1131 ##
1132 ##        push(@all_values, @invvalues);
1133 ##      }
1134 ##    }
1135 ##
1136 ##    if ($form->{onorder} || $form->{ordered}) {
1137 ##      my @ordvalues = @values;
1138 ##      my $ordwhere = $where . qq| AND o.quotation = '0'|;
1139 ##
1140 ##      if ($form->{transdatefrom}) {
1141 ##        $ordwhere .= qq| AND o.transdate >= ?|;
1142 ##        push(@ordvalues, $form->{transdatefrom});
1143 ##      }
1144 ##
1145 ##      if ($form->{transdateto}) {
1146 ##        $ordwhere .= qq| AND o.transdate <= ?|;
1147 ##        push(@ordvalues, $form->{transdateto});
1148 ##      }
1149 ##
1150 ##      if ($form->{description}) {
1151 ##        $ordwhere .= qq| AND oi.description ILIKE ?|;
1152 ##        push(@ordvalues, '%' . $form->{description} . '%');
1153 ##      }
1154 ##
1155 ##      if ($form->{ordered}) {
1156 ##        $query .=
1157 ##          qq|$union
1158 ##
1159 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
1160 ##               oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
1161 ##               p.listprice, p.lastcost, p.rop, p.weight,
1162 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
1163 ##               pg.partsgroup,
1164 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1165 ##               ct.name, NULL AS deliverydate,
1166 ##               'oe' AS module, 'sales_order' AS type,
1167 ##               (SELECT buy FROM exchangerate ex
1168 ##                WHERE ex.curr = o.curr AND ex.transdate = o.transdate) AS exchangerate
1169 ##             FROM orderitems oi
1170 ##             JOIN parts p ON (oi.parts_id = p.id)
1171 ##             JOIN oe o ON (oi.trans_id = o.id)
1172 ##             JOIN customer ct ON (o.customer_id = ct.id)
1173 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1174 ##             WHERE $ordwhere AND (o.customer_id > 0)|;
1175 ##        $union = qq| UNION |;
1176 ##
1177 ##        push(@all_values, @ordvalues);
1178 ##      }
1179 ##
1180 ##      if ($form->{onorder}) {
1181 ##        $query .=
1182 ##          qq|$union
1183 ##
1184 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
1185 ##               oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
1186 ##               p.listprice, p.lastcost, p.rop, p.weight,
1187 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
1188 ##               pg.partsgroup,
1189 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1190 ##               ct.name, NULL AS deliverydate,
1191 ##               'oe' AS module, 'purchase_order' AS type,
1192 ##               (SELECT sell FROM exchangerate ex
1193 ##               WHERE ex.curr = o.curr AND (ex.transdate = o.transdate)) AS exchangerate
1194 ##             FROM orderitems oi
1195 ##             JOIN parts p ON (oi.parts_id = p.id)
1196 ##             JOIN oe o ON (oi.trans_id = o.id)
1197 ##             JOIN vendor ct ON (o.vendor_id = ct.id)
1198 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1199 ##             WHERE $ordwhere AND (o.vendor_id > 0)|;
1200 ##        $union = qq| UNION |;
1201 ##
1202 ##        push(@all_values, @ordvalues);
1203 ##      }
1204 ##
1205 ##    }
1206 ##
1207 ##    if ($form->{rfq} || $form->{quoted}) {
1208 ##      my $quowhere = $where . qq| AND o.quotation = '1'|;
1209 ##      my @quovalues = @values;
1210 ##
1211 ##      if ($form->{transdatefrom}) {
1212 ##        $quowhere .= qq| AND o.transdate >= ?|;
1213 ##        push(@quovalues, $form->{transdatefrom});
1214 ##      }
1215 ##
1216 ##      if ($form->{transdateto}) {
1217 ##        $quowhere .= qq| AND o.transdate <= ?|;
1218 ##        push(@quovalues, $form->{transdateto});
1219 ##      }
1220 ##
1221 ##      if ($form->{description}) {
1222 ##        $quowhere .= qq| AND oi.description ILIKE ?|;
1223 ##        push(@quovalues, '%' . $form->{description} . '%');
1224 ##      }
1225 ##
1226 ##      if ($form->{quoted}) {
1227 ##        $query .=
1228 ##          qq|$union
1229 ##
1230 ##             SELECT
1231 ##               p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
1232 ##               oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
1233 ##               p.listprice, p.lastcost, p.rop, p.weight,
1234 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
1235 ##               pg.partsgroup,
1236 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1237 ##               ct.name, NULL AS deliverydate, 'oe' AS module, 'sales_quotation' AS type,
1238 ##               (SELECT buy FROM exchangerate ex
1239 ##                WHERE (ex.curr = o.curr) AND (ex.transdate = o.transdate)) AS exchangerate
1240 ##             FROM orderitems oi
1241 ##             JOIN parts p ON (oi.parts_id = p.id)
1242 ##             JOIN oe o ON (oi.trans_id = o.id)
1243 ##             JOIN customer ct ON (o.customer_id = ct.id)
1244 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1245 ##             WHERE $quowhere
1246 ##             AND o.customer_id > 0|;
1247 ##        $union = qq| UNION |;
1248 ##
1249 ##        push(@all_values, @quovalues);
1250 ##      }
1251 ##
1252 ##      if ($form->{rfq}) {
1253 ##        $query .=
1254 ##          qq|$union
1255 ##
1256 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
1257 ##               oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
1258 ##               p.listprice, p.lastcost, p.rop, p.weight,
1259 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
1260 ##               pg.partsgroup,
1261 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1262 ##               ct.name, NULL AS deliverydate,
1263 ##               'oe' AS module, 'request_quotation' AS type,
1264 ##               (SELECT sell FROM exchangerate ex
1265 ##               WHERE (ex.curr = o.curr) AND (ex.transdate = o.transdate)) AS exchangerate
1266 ##             FROM orderitems oi
1267 ##             JOIN parts p ON (oi.parts_id = p.id)
1268 ##             JOIN oe o ON (oi.trans_id = o.id)
1269 ##             JOIN vendor ct ON (o.vendor_id = ct.id)
1270 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1271 ##             WHERE $quowhere
1272 ##             AND o.vendor_id > 0|;
1273 ##
1274 ##        push(@all_values, @quovalues);
1275 ##      }
1276 ##
1277 ##    }
1278 ##    $query .= qq| ORDER BY  | . $sortorder;
1279 ##
1280 ##  }
1281 ##
1282 ##  $form->{parts} = selectall_hashref_query($form, $dbh, $query, @all_values);
1283 #
1284   my @assemblies;
1285   # include individual items for assemblies
1286   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1287     $query =
1288       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1289            p.unit, p.bin,
1290            p.sellprice, p.listprice, p.lastcost,
1291            p.rop, p.weight, p.priceupdate,
1292            p.image, p.drawing, p.microfiche
1293          FROM parts p, assembly a
1294          WHERE (p.id = a.parts_id) AND (a.id = ?)|;
1295     $sth = prepare_query($form, $dbh, $query);
1296
1297     foreach $item (@{ $form->{parts} }) {
1298       push(@assemblies, $item);
1299       do_statement($form, $sth, $query, conv_i($item->{id}));
1300
1301       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1302         $ref->{assemblyitem} = 1;
1303         push(@assemblies, $ref);
1304       }
1305       $sth->finish;
1306     }
1307
1308     # copy assemblies to $form->{parts}
1309     $form->{parts} = \@assemblies;
1310   }
1311
1312   $dbh->disconnect;
1313   $main::lxdebug->leave_sub();
1314 }
1315
1316 sub update_prices {
1317   $main::lxdebug->enter_sub();
1318
1319   my ($self, $myconfig, $form) = @_;
1320   my @where_values;
1321   my $where = '1 = 1';
1322   my $var;
1323
1324   my $group;
1325   my $limit;
1326
1327   if ($item ne 'make') {
1328     foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1329       my $column = $item;
1330       $column =~ s/.*\.//;
1331       next unless ($form->{$column});
1332       $where .= qq| AND $item ILIKE ?|;
1333       push(@where_values, '%' . $form->{$column} . '%');
1334     }
1335   }
1336
1337   # special case for description
1338   if ($form->{description}
1339       && !(   $form->{bought}  || $form->{sold} || $form->{onorder}
1340            || $form->{ordered} || $form->{rfq} || $form->{quoted})) {
1341     $where .= qq| AND (p.description ILIKE ?)|;
1342     push(@where_values, '%' . $form->{description} . '%');
1343   }
1344
1345   # special case for serialnumber
1346   if ($form->{l_serialnumber} && $form->{serialnumber}) {
1347     $where .= qq| AND serialnumber ILIKE ?|;
1348     push(@where_values, '%' . $form->{serialnumber} . '%');
1349   }
1350
1351
1352   # items which were never bought, sold or on an order
1353   if ($form->{itemstatus} eq 'orphaned') {
1354     $form->{onhand}  = $form->{short}   = 0;
1355     $form->{bought}  = $form->{sold}    = 0;
1356     $form->{onorder} = $form->{ordered} = 0;
1357     $form->{rfq}     = $form->{quoted}  = 0;
1358
1359     $form->{transdatefrom} = $form->{transdateto} = "";
1360
1361     $where .=
1362       qq| AND (p.onhand = 0)
1363           AND p.id NOT IN
1364             (
1365               SELECT DISTINCT parts_id FROM invoice
1366               UNION
1367               SELECT DISTINCT parts_id FROM assembly
1368               UNION
1369               SELECT DISTINCT parts_id FROM orderitems
1370             )|;
1371   }
1372
1373   if ($form->{itemstatus} eq 'active') {
1374     $where .= qq| AND p.obsolete = '0'|;
1375   }
1376
1377   if ($form->{itemstatus} eq 'obsolete') {
1378     $where .= qq| AND p.obsolete = '1'|;
1379     $form->{onhand} = $form->{short} = 0;
1380   }
1381
1382   if ($form->{itemstatus} eq 'onhand') {
1383     $where .= qq| AND p.onhand > 0|;
1384   }
1385
1386   if ($form->{itemstatus} eq 'short') {
1387     $where .= qq| AND p.onhand < p.rop|;
1388   }
1389
1390   foreach my $column (qw(make model)) {
1391     next unless ($form->{$colum});
1392     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1393     push(@where_values, '%' . $form->{$column} . '%');
1394   }
1395
1396   # connect to database
1397   my $dbh = $form->dbconnect_noauto($myconfig);
1398
1399   for my $column (qw(sellprice listprice)) {
1400     next if ($form->{$column} eq "");
1401
1402     my $value = $form->parse_amount($myconfig, $form->{$column});
1403     my $operator = '+';
1404
1405     if ($form->{"${column}_type"} eq "percent") {
1406       $value = ($value / 100) + 1;
1407       $operator = '*';
1408     }
1409
1410     $query =
1411       qq|UPDATE parts SET $column = $column $operator ?
1412          WHERE id IN
1413            (SELECT p.id
1414             FROM parts p
1415             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1416             WHERE $where)|;
1417     do_query($from, $dbh, $query, $value, @where_values);
1418   }
1419
1420   my $q_add =
1421     qq|UPDATE prices SET price = price + ?
1422        WHERE parts_id IN
1423          (SELECT p.id
1424           FROM parts p
1425           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1426           WHERE $where) AND (pricegroup_id = ?)|;
1427   my $sth_add = prepare_query($form, $dbh, $q_add);
1428
1429   my $q_multiply =
1430     qq|UPDATE prices SET price = price * ?
1431        WHERE parts_id IN
1432          (SELECT p.id
1433           FROM parts p
1434           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1435           WHERE $where) AND (pricegroup_id = ?)|;
1436   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1437
1438   for my $i (1 .. $form->{price_rows}) {
1439     next if ($form->{"price_$i"} eq "");
1440
1441     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1442
1443     if ($form->{"pricegroup_type_$i"} eq "percent") {
1444       do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1445     } else {
1446       do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1447     }
1448   }
1449
1450   $sth_add->finish();
1451   $sth_multiply->finish();
1452
1453   my $rc= $dbh->commit;
1454   $dbh->disconnect;
1455
1456   $main::lxdebug->leave_sub();
1457
1458   return $rc;
1459 }
1460
1461 sub create_links {
1462   $main::lxdebug->enter_sub();
1463
1464   my ($self, $module, $myconfig, $form) = @_;
1465
1466   # connect to database
1467   my $dbh = $form->dbconnect($myconfig);
1468
1469   my @values = ('%' . $module . '%');
1470
1471   if ($form->{id}) {
1472     $query =
1473       qq|SELECT c.accno, c.description, c.link, c.id,
1474            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1475          FROM chart c, parts p
1476          WHERE (c.link LIKE ?) AND (p.id = ?)
1477          ORDER BY c.accno|;
1478     push(@values, conv_i($form->{id}));
1479
1480   } else {
1481     $query =
1482       qq|SELECT c.accno, c.description, c.link, c.id,
1483            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1484          FROM chart c, defaults d
1485          WHERE c.link LIKE ?
1486          ORDER BY c.accno|;
1487   }
1488
1489   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1490   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1491     foreach my $key (split(/:/, $ref->{link})) {
1492       if ($key =~ /\Q$module\E/) {
1493         if (   ($ref->{id} eq $ref->{inventory_accno_id})
1494             || ($ref->{id} eq $ref->{income_accno_id})
1495             || ($ref->{id} eq $ref->{expense_accno_id})) {
1496           push @{ $form->{"${module}_links"}{$key} },
1497             { accno       => $ref->{accno},
1498               description => $ref->{description},
1499               selected    => "selected" };
1500           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1501             } else {
1502           push @{ $form->{"${module}_links"}{$key} },
1503             { accno       => $ref->{accno},
1504               description => $ref->{description},
1505               selected    => "" };
1506         }
1507       }
1508     }
1509   }
1510   $sth->finish;
1511
1512   # get buchungsgruppen
1513   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1514
1515   # get payment terms
1516   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1517
1518   if (!$form->{id}) {
1519     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1520   }
1521
1522   $dbh->disconnect;
1523   $main::lxdebug->leave_sub();
1524 }
1525
1526 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1527 sub get_parts {
1528   $main::lxdebug->enter_sub();
1529
1530   my ($self, $myconfig, $form, $sortorder) = @_;
1531   my $dbh   = $form->dbconnect($myconfig);
1532   my $order = qq| p.partnumber|;
1533   my $where = qq|1 = 1|;
1534   my @values;
1535
1536   if ($sortorder eq "all") {
1537     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1538     push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1539
1540   } elsif ($sortorder eq "partnumber") {
1541     $where .= qq| AND (partnumber ILIKE ?)|;
1542     push(@values, '%' . $form->{partnumber} . '%');
1543
1544   } elsif ($sortorder eq "description") {
1545     $where .= qq| AND (description ILIKE ?)|;
1546     push(@values, '%' . $form->{description} . '%');
1547     $order = "description";
1548
1549   }
1550
1551   my $query =
1552     qq|SELECT id, partnumber, description, unit, sellprice
1553        FROM parts
1554        WHERE $where ORDER BY $order|;
1555
1556   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1557
1558   my $j = 0;
1559   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1560     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1561       next;
1562     }
1563
1564     $j++;
1565     $form->{"id_$j"}          = $ref->{id};
1566     $form->{"partnumber_$j"}  = $ref->{partnumber};
1567     $form->{"description_$j"} = $ref->{description};
1568     $form->{"unit_$j"}        = $ref->{unit};
1569     $form->{"sellprice_$j"}   = $ref->{sellprice};
1570     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
1571   }    #while
1572   $form->{rows} = $j;
1573   $sth->finish;
1574   $dbh->disconnect;
1575
1576   $main::lxdebug->leave_sub();
1577
1578   return $self;
1579 }    #end get_parts()
1580
1581 # gets sum of sold part with part_id
1582 sub get_soldtotal {
1583   $main::lxdebug->enter_sub();
1584
1585   my ($dbh, $id) = @_;
1586
1587   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1588   my ($sum) = selectrow_query($form, $dbh, $query, conv_i($id));
1589   $sum ||= 0;
1590
1591   $main::lxdebug->leave_sub();
1592
1593   return $sum;
1594 }    #end get_soldtotal
1595
1596 sub retrieve_languages {
1597   $main::lxdebug->enter_sub();
1598
1599   my ($self, $myconfig, $form) = @_;
1600
1601   # connect to database
1602   my $dbh = $form->dbconnect($myconfig);
1603
1604   my @values;
1605   my $where;
1606
1607   if ($form->{language_values} ne "") {
1608     $query =
1609       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1610          FROM language l
1611          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1612          ORDER BY lower(l.description)|;
1613     @values = (conv_i($form->{id}));
1614
1615   } else {
1616     $query = qq|SELECT id, description
1617                 FROM language
1618                 ORDER BY lower(description)|;
1619   }
1620
1621   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1622
1623   $dbh->disconnect;
1624
1625   $main::lxdebug->leave_sub();
1626
1627   return $languages;
1628 }
1629
1630 sub follow_account_chain {
1631   $main::lxdebug->enter_sub(2);
1632
1633   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1634
1635   my @visited_accno_ids = ($accno_id);
1636
1637   my ($query, $sth);
1638
1639   $query =
1640     qq|SELECT c.new_chart_id, date($transdate) >= c.valid_from AS is_valid, | .
1641     qq|  cnew.accno | .
1642     qq|FROM chart c | .
1643     qq|LEFT JOIN chart cnew ON c.new_chart_id = cnew.id | .
1644     qq|WHERE (c.id = ?) AND NOT c.new_chart_id ISNULL AND (c.new_chart_id > 0)|;
1645   $sth = prepare_query($form, $dbh, $query);
1646
1647   while (1) {
1648     do_statement($form, $sth, $query, $accno_id);
1649     $ref = $sth->fetchrow_hashref();
1650     last unless ($ref && $ref->{"is_valid"} &&
1651                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1652     $accno_id = $ref->{"new_chart_id"};
1653     $accno = $ref->{"accno"};
1654     push(@visited_accno_ids, $accno_id);
1655   }
1656
1657   $main::lxdebug->leave_sub(2);
1658
1659   return ($accno_id, $accno);
1660 }
1661
1662 sub retrieve_accounts {
1663   $main::lxdebug->enter_sub(2);
1664
1665   my ($self, $myconfig, $form, $parts_id, $index) = @_;
1666
1667   my ($query, $sth, $dbh);
1668
1669   $form->{"taxzone_id"} *= 1;
1670
1671   $dbh = $form->get_standard_dbh($myconfig);
1672
1673   my $transdate = "";
1674   if ($form->{type} eq "invoice") {
1675     if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1676       $transdate = $form->{invdate};
1677     } else {
1678       $transdate = $form->{deliverydate};
1679     }
1680   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1681     $transdate = $form->{invdate};
1682   } else {
1683     $transdate = $form->{transdate};
1684   }
1685
1686   if ($transdate eq "") {
1687     $transdate = "current_date";
1688   } else {
1689     $transdate = $dbh->quote($transdate);
1690   }
1691
1692   $query =
1693     qq|SELECT | .
1694     qq|  p.inventory_accno_id AS is_part, | .
1695     qq|  bg.inventory_accno_id, | .
1696     qq|  bg.income_accno_id_$form->{taxzone_id} AS income_accno_id, | .
1697     qq|  bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id, | .
1698     qq|  c1.accno AS inventory_accno, | .
1699     qq|  c2.accno AS income_accno, | .
1700     qq|  c3.accno AS expense_accno | .
1701     qq|FROM parts p | .
1702     qq|LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id | .
1703     qq|LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id | .
1704     qq|LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id | .
1705     qq|LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id | .
1706     qq|WHERE p.id = ?|;
1707   my $ref = selectfirst_hashref_query($form, $dbh, $query, $parts_id);
1708
1709   return $main::lxdebug->leave_sub(2) if (!$ref);
1710
1711   $ref->{"inventory_accno_id"} = undef unless ($ref->{"is_part"});
1712
1713   my %accounts;
1714   foreach my $type (qw(inventory income expense)) {
1715     next unless ($ref->{"${type}_accno_id"});
1716     ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1717       $self->follow_account_chain($form, $dbh, $transdate,
1718                                   $ref->{"${type}_accno_id"},
1719                                   $ref->{"${type}_accno"});
1720   }
1721
1722   map({ $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} }
1723       qw(inventory income expense));
1724
1725   my $inc_exp = $form->{"vc"} eq "customer" ? "income" : "expense";
1726   my $accno_id = $accounts{"${inc_exp}_accno_id"};
1727
1728   $query =
1729     qq|SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber | .
1730     qq|FROM tax t | .
1731     qq|LEFT JOIN chart c ON c.id = t.chart_id | .
1732     qq|WHERE t.id IN | .
1733     qq|  (SELECT tk.tax_id | .
1734     qq|   FROM taxkeys tk | .
1735     qq|   WHERE tk.chart_id = ? AND startdate <= | . quote_db_date($transdate) .
1736     qq|   ORDER BY startdate DESC LIMIT 1) |;
1737   $ref = selectfirst_hashref_query($form, $dbh, $query, $accno_id);
1738
1739   unless ($ref) {
1740     $main::lxdebug->leave_sub(2);
1741     return;
1742   }
1743
1744   $form->{"taxaccounts_$index"} = $ref->{"accno"};
1745   if ($form->{"taxaccounts"} !~ /$ref->{accno}/) {
1746     $form->{"taxaccounts"} .= "$ref->{accno} ";
1747   }
1748   map({ $form->{"$ref->{accno}_${_}"} = $ref->{$_}; }
1749       qw(rate description taxnumber));
1750
1751 #   $main::lxdebug->message(0, "formvars: rate " . $form->{"$ref->{accno}_rate"} .
1752 #                           " description " . $form->{"$ref->{accno}_description"} .
1753 #                           " taxnumber " . $form->{"$ref->{accno}_taxnumber"} .
1754 #                           " || taxaccounts_$index " . $form->{"taxaccounts_$index"} .
1755 #                           " || taxaccounts " . $form->{"taxaccounts"});
1756
1757   $main::lxdebug->leave_sub(2);
1758 }
1759
1760 sub get_basic_part_info {
1761   $main::lxdebug->enter_sub();
1762
1763   my $self     = shift;
1764   my %params   = @_;
1765
1766   Common::check_params(\%params, qw(id));
1767
1768   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1769
1770   if (!scalar @ids) {
1771     $main::lxdebug->leave_sub();
1772     return ();
1773   }
1774
1775   my $myconfig = \%main::myconfig;
1776   my $form     = $main::form;
1777
1778   my $dbh      = $form->get_standard_dbh($myconfig);
1779
1780   my $query    = qq|SELECT id, partnumber, description, unit FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1781
1782   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1783
1784   if ($params{vendor_id}) {
1785     $query     = qq|SELECT * FROM parts_vendor WHERE (parts_id = ?) AND (vendor_id = ?)|;
1786     my $sth    = prepare_query($form, $dbh, $query);
1787
1788     foreach my $part (@{ $info }) {
1789       do_statement($form, $sth, $query, $part->{id}, conv_i($params{vendor_id}));
1790       $part->{vendor_info} = $sth->fetchrow_hashref();
1791     }
1792
1793     $sth->finish();
1794   }
1795
1796   if ('' eq ref $params{id}) {
1797     $info = $info->[0] || { };
1798
1799     $main::lxdebug->leave_sub();
1800     return $info;
1801   }
1802
1803   my %info_map = map { $_->{id} => $_ } @{ $info };
1804
1805   $main::lxdebug->leave_sub();
1806
1807   return %info_map;
1808 }
1809
1810
1811 1;