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