Lagerverwaltung implementiert.
[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 #
734 # not working:
735 #   l_soldtotal                              - aggreg join to display total of sold quantity
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
757   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
758   my @makemodel_filters    = qw(make model);
759   my @invoice_oi_filters   = qw(serialnumber soldtotal);
760   my @apoe_filters         = qw(transdate);
761   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
762   my @simple_l_switches    = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
763   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
764   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module);
765   my @deliverydate_flags   = qw(deliverydate);
766 #  my @other_flags          = qw(onhand); # ToDO: implement these
767 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
768
769   my %joins = (
770     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
771     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
772     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
773     invoice_oi =>
774       q|LEFT JOIN (
775          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem, 'invoice'    AS ioi FROM invoice UNION
776          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, 'orderitems' AS ioi FROM orderitems
777        ) AS ioi ON ioi.parts_id = p.id|,
778     apoe       =>
779       q|LEFT JOIN (
780          SELECT id, transdate, 'ir' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation, NULL AS customer_id,         vendor_id, NULL AS deliverydate FROM ap UNION
781          SELECT id, transdate, 'is' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation,         customer_id, NULL AS vendor_id,         deliverydate FROM ar UNION
782          SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber,          quotation,         customer_id,         vendor_id, NULL AS deliverydate FROM oe
783        ) AS apoe ON ioi.trans_id = apoe.id|,
784     cv         =>
785       q|LEFT JOIN (
786            SELECT id, name, 'customer' AS cv FROM customer UNION
787            SELECT id, name, 'vendor'   AS cv FROM vendor
788          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
789   );
790   my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
791   my %joins_needed;
792
793   #===== switches and simple filters ========#
794
795   my @select_tokens = qw(id factor);
796   my @where_tokens  = qw(1=1);
797   my @group_tokens  = ();
798
799   # special case transdate
800   if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
801     $form->{"l_transdate"} = 1;
802     push @select_tokens, 'transdate';
803     for (qw(transdatefrom transdateto)) {
804       next unless $form->{$_};
805       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
806       push @bind_vars,    $form->{$_};
807     }
808   }
809
810   my %simple_filter_table_prefix = (
811      description  => 'p.',
812   );
813
814   foreach (@simple_filters, @makemodel_filters, @invoice_oi_filters) {
815     next unless $form->{$_};
816     $form->{"l_$_"} = '1'; # show the column
817     push @where_tokens, "$simple_filter_table_prefix{$_}$_ ILIKE ?";
818     push @bind_vars,    "%$form->{$_}%";
819   }
820
821   foreach (@simple_l_switches) {
822     next unless $form->{"l_$_"};
823     push @select_tokens, $_;
824   }
825
826   for ($form->{searchitems}) {
827     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
828     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
829     push @where_tokens, 'NOT p.assembly'               if /service/;
830     push @where_tokens, '    p.assembly'               if /assembly/;
831   }
832
833   for ($form->{itemstatus}) {
834     push @where_tokens, 'p.id NOT IN
835         (SELECT DISTINCT parts_id FROM invoice UNION
836          SELECT DISTINCT parts_id FROM assembly UNION
837          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
838     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
839     push @where_tokens, 'NOT p.obsolete'               if /active/;
840     push @where_tokens, '    p.obsolete',              if /obsolete/;
841     push @where_tokens, 'p.onhand > 0',                if /onhand/;
842     push @where_tokens, 'p.onhand < p.rop',            if /short/;
843   }
844
845
846   my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
847   $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols;
848
849   my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
850
851   # special case: sorting by partnumber
852   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
853   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
854   # ToDO: implement proper functional sorting
855   $form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
856     if $form->{sort} eq 'partnumber';
857
858   my $order_clause = " ORDER BY $form->{sort} $sort_order";
859
860   my $limit_clause = " LIMIT 100" if $form->{top100};
861
862   #=== joins and complicated filters ========#
863
864   my $bsooqr = $form->{bought}  || $form->{sold}
865             || $form->{ordered} || $form->{onorder}
866             || $form->{quoted}  || $form->{rfq};
867
868   my @bsooqr;
869   push @select_tokens, @qsooqr_flags                                          if $bsooqr;
870   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
871   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
872   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
873   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
874   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
875   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
876   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
877   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
878
879   $joins_needed{partsgroup}  = 1;
880   $joins_needed{pfac}        = 1;
881   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
882   $joins_needed{cv}          = 1 if $bsooqr;
883   $joins_needed{apoe}        = 1 if $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
884   $joins_needed{invoice_oi}  = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
885
886   # special case for description search.
887   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
888   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
889   # find the old entries in of @where_tokens and @bind_vars, and adjust them
890   if ($joins_needed{invoice_oi}) {
891     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
892       next unless $where_tokens[$wi] =~ /^description ILIKE/;
893       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
894       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
895       last;
896     }
897   }
898
899   # now the master trick: soldtotal.
900   if ($form->{l_soldtotal}) {
901     push @where_tokens, 'ioi.qty >= 0';
902     push @group_tokens, @select_tokens;
903     push @select_tokens, 'SUM(ioi.qty)';
904   }
905
906   #============= build query ================#
907
908   %table_prefix = (
909      %table_prefix,
910      deliverydate => 'apoe.', serialnumber => 'ioi.',
911      transdate    => 'apoe.', trans_id     => 'ioi.',
912      module       => 'apoe.', name         => 'cv.',
913      ordnumber    => 'apoe.', make         => 'mm.',
914      quonumber    => 'apoe.', model        => 'mm.',
915      invnumber    => 'apoe.', partsgroup   => 'pg.',
916      factor       => 'pfac.',
917      'SUM(ioi.qty)' => ' ',
918   );
919
920   my %renamed_columns = (
921     'factor'       => 'price_factor',
922     'SUM(ioi.qty)' => 'soldtotal',
923   );
924
925   map { $table_prefix{$_} = 'ioi.' } qw(description serialnumber qty unit) if $joins_needed{invoice_oi};
926   map { $renamed_columns{$_} = ' AS ' . $renamed_columns{$_} } keys %renamed_columns;
927
928   my $select_clause = join ', ',    map { ($table_prefix{$_} || "p.") . $_ . $renamed_columns{$_} } @select_tokens;
929   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
930   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
931   my $group_clause  = ' GROUP BY ' . join ', ',    map { ($table_prefix{$_} || "p.") . $_ } @group_tokens if scalar @group_tokens;
932
933   my $query = qq|SELECT DISTINCT $select_clause FROM parts p $join_clause WHERE $where_clause $group_clause $order_clause $limit_clause|;
934
935   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
936
937   map { $_->{onhand} *= 1 } @{ $form->{parts} };
938
939 ##  my $where = qq|1 = 1|;
940 ##  my (@values, $var, $flds, $group, $limit);
941 ##
942 ##  foreach my $item (qw(partnumber drawing microfiche ean pg.partsgroup)) {
943 ##    my $column = $item;
944 ##    $column =~ s/.*\.//; # get rid of table prefixes
945 ##    if ($form->{$column}) {
946 ##      $where .= qq| AND ($item ILIKE ?)|;
947 ##      push(@values, "%$form->{$column}%");
948 ##    }
949 ##  }
950 ##
951 ##  # special case for description
952 ##  if ($form->{description}
953 ##      && !(   $form->{bought}  || $form->{sold} || $form->{onorder}
954 ##           || $form->{ordered} || $form->{rfq} || $form->{quoted})) {
955 ##    $where .= qq| AND (p.description ILIKE ?)|;
956 ##    push(@values, "%$form->{description}%");
957 ##  }
958 ##
959 ##  # special case for serialnumber
960 ##  if ($form->{l_serialnumber} && $form->{serialnumber}) {
961 ##    $where .= qq| AND (serialnumber ILIKE ?)|;
962 ##    push(@values, "%$form->{serialnumber}%");
963 ##  }
964 ##
965 ##  if ($form->{searchitems} eq 'part') {
966 ##    $where .= qq| AND (p.inventory_accno_id > 0) |;
967 ##  }
968 ##
969 ##  if ($form->{searchitems} eq 'assembly') {
970 ##    $form->{bought} = "";
971 ##    $where .= qq| AND p.assembly|;
972 ##  }
973 ##
974 ##  if ($form->{searchitems} eq 'service') {
975 ##    $where .= qq| AND (p.inventory_accno_id IS NULL) AND NOT (p.assembly = '1')|;
976 ##    # irrelevant for services
977 ##    map { $form->{$_} = '' } qw(make model);
978 ##  }
979 ##
980 ##  # items which were never bought, sold or on an order
981 ##  if ($form->{itemstatus} eq 'orphaned') {
982 ##    map { $form->{$_} = 0  } qw(onhand short bought sold onorder ordered rfq quoted);
983 ##    map { $form->{$_} = '' } qw(transdatefrom transdateto);
984 ##
985 ##    $where .=
986 ##      qq| AND (p.onhand = 0)
987 ##          AND p.id NOT IN
988 ##            (
989 ##              SELECT DISTINCT parts_id FROM invoice
990 ##              UNION
991 ##              SELECT DISTINCT parts_id FROM assembly
992 ##              UNION
993 ##              SELECT DISTINCT parts_id FROM orderitems
994 ##            )|;
995 ##  }
996 ##
997 ##  my %status2condition = (
998 ##    active   => " AND (p.obsolete = '0')",
999 ##    obsolete => " AND (p.obsolete = '1')",
1000 ##    onhand   => " AND (p.onhand > 0)",
1001 ##    short    => " AND (p.onhand < p.rop)",
1002 ##  );
1003 ##  $where .= $status2condition{$form->{itemstatus}};
1004 ##
1005 ##  $form->{onhand} = $form->{short} = 0 if ($form->{itemstatus} eq 'obsolete');
1006 ##
1007 ##  my @subcolumns;
1008 ##  foreach my $column (qw(make model)) {
1009 ##    push @subcolumns, $column if $form->{$column};
1010 ##  }
1011 ##  if (@subcolumns) {
1012 ##    $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE | . (join " AND ", map { "($_ ILIKE ?)"; } @subcolumns) . ")";
1013 ##    push @values, map { '%' . $form->{$_} . '%' } @subcolumns;
1014 ##  }
1015 ##
1016 ##  if ($form->{l_soldtotal}) {
1017 ##    $where .= qq| AND (p.id = i.parts_id) AND (i.qty >= 0)|;
1018 ##    $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|;
1019 ##  }
1020 ##
1021 ##  $limit = qq| LIMIT 100| if ($form->{top100});
1022 ##
1023 ##  # connect to database
1024 ##  my $dbh = $form->dbconnect($myconfig);
1025 ##
1026 ##  my @sort_cols = qw(id partnumber description partsgroup bin priceupdate onhand
1027 ##                     invnumber ordnumber quonumber name drawing microfiche
1028 ##                     serialnumber soldtotal deliverydate);
1029 ##
1030 ##  my $sortorder = "partnumber";
1031 ##  $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } @sort_cols));
1032 ##  $sortorder .= " DESC" if ($form->{revers});
1033 ##
1034 ##  my $query = "";
1035 ##
1036 ##  if ($form->{l_soldtotal}) {
1037 ##    $form->{soldtotal} = 'soldtotal';
1038 ##    $query =
1039 ##      qq|SELECT p.id, p.partnumber, p.description, p.onhand, p.unit,
1040 ##           p.bin, p.sellprice, p.listprice, p.lastcost,
1041 ##           p.priceupdate, pg.partsgroup,sum(i.qty) AS soldtotal
1042 ##         FROM parts p
1043 ##         LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id), invoice i
1044 ##         WHERE $where
1045 ##         $group
1046 ##         ORDER BY $sortorder $limit|;
1047 ##  } else {
1048 ##    $query =
1049 ##      qq|SELECT p.id, p.partnumber, p.description, p.onhand, p.unit,
1050 ##           p.bin, p.sellprice, p.listprice, p.lastcost, p.rop, p.weight,
1051 ##           p.priceupdate, p.image, p.drawing, p.microfiche,
1052 ##           pg.partsgroup
1053 ##         FROM parts p
1054 ##         LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1055 ##         WHERE $where
1056 ##         $group
1057 ##         ORDER BY $sortorder $limit|;
1058 ##  }
1059 ##
1060 ##  my @all_values = @values;
1061 ##
1062 ##  # rebuild query for bought and sold items
1063 ##  if (   $form->{bought}
1064 ##      || $form->{sold}
1065 ##      || $form->{onorder}
1066 ##      || $form->{ordered}
1067 ##      || $form->{rfq}
1068 ##      || $form->{quoted}) {
1069 ##    my $union = "";
1070 ##    $query = "";
1071 ##    @all_values = ();
1072 ##
1073 ##    if ($form->{bought} || $form->{sold}) {
1074 ##
1075 ##      my @invvalues = @values;
1076 ##      my $invwhere = "$where";
1077 #      $invwhere .= qq| AND i.assemblyitem = '0'|;
1078 ##
1079 ##      if ($form->{transdatefrom}) {
1080 ##        $invwhere .= qq| AND a.transdate >= ?|;
1081 ##        push(@invvalues, $form->{transdatefrom});
1082 ##      }
1083 ##
1084 ##      if ($form->{transdateto}) {
1085 ##        $invwhere .= qq| AND a.transdate <= ?|;
1086 ##        push(@invvalues, $form->{transdateto});
1087 ##      }
1088 ##
1089 ##      if ($form->{description}) {
1090 ##        $invwhere .= qq| AND i.description ILIKE ?|;
1091 ##        push(@invvalues, '%' . $form->{description} . '%');
1092 ##      }
1093 ##
1094 ##      $flds =
1095 ##        qq|p.id, p.partnumber, i.description, i.serialnumber,
1096 #           i.qty AS onhand, i.unit, p.bin, i.sellprice,
1097 ##           p.listprice, p.lastcost, p.rop, p.weight,
1098 ##           p.priceupdate, p.image, p.drawing, p.microfiche,
1099 ##           pg.partsgroup,
1100 ##           a.invnumber, a.ordnumber, a.quonumber, i.trans_id,
1101 ##           ct.name, i.deliverydate|;
1102 ##
1103 ##      if ($form->{bought}) {
1104 ##        $query =
1105 ##          qq|SELECT $flds, 'ir' AS module, '' AS type, 1 AS exchangerate
1106 ##             FROM invoice i
1107 ##             JOIN parts p ON (p.id = i.parts_id)
1108 ##             JOIN ap a ON (a.id = i.trans_id)
1109 ##             JOIN vendor ct ON (a.vendor_id = ct.id)
1110 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1111 ##             WHERE $invwhere|;
1112 ##
1113 ##        $union = qq| UNION |;
1114 ##
1115 ##        push(@all_values, @invvalues);
1116 ##      }
1117 ##
1118 ##      if ($form->{sold}) {
1119 ##        $query .=
1120 ##          qq|$union
1121 ##
1122 ##             SELECT $flds, 'is' AS module, '' AS type, 1 As exchangerate
1123 ##             FROM invoice i
1124 ##             JOIN parts p ON (p.id = i.parts_id)
1125 ##             JOIN ar a ON (a.id = i.trans_id)
1126 ##             JOIN customer ct ON (a.customer_id = ct.id)
1127 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1128 ##             WHERE $invwhere|;
1129 ##        $union = qq| UNION |;
1130 ##
1131 ##        push(@all_values, @invvalues);
1132 ##      }
1133 ##    }
1134 ##
1135 ##    if ($form->{onorder} || $form->{ordered}) {
1136 ##      my @ordvalues = @values;
1137 ##      my $ordwhere = $where . qq| AND o.quotation = '0'|;
1138 ##
1139 ##      if ($form->{transdatefrom}) {
1140 ##        $ordwhere .= qq| AND o.transdate >= ?|;
1141 ##        push(@ordvalues, $form->{transdatefrom});
1142 ##      }
1143 ##
1144 ##      if ($form->{transdateto}) {
1145 ##        $ordwhere .= qq| AND o.transdate <= ?|;
1146 ##        push(@ordvalues, $form->{transdateto});
1147 ##      }
1148 ##
1149 ##      if ($form->{description}) {
1150 ##        $ordwhere .= qq| AND oi.description ILIKE ?|;
1151 ##        push(@ordvalues, '%' . $form->{description} . '%');
1152 ##      }
1153 ##
1154 ##      if ($form->{ordered}) {
1155 ##        $query .=
1156 ##          qq|$union
1157 ##
1158 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
1159 ##               oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
1160 ##               p.listprice, p.lastcost, p.rop, p.weight,
1161 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
1162 ##               pg.partsgroup,
1163 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1164 ##               ct.name, NULL AS deliverydate,
1165 ##               'oe' AS module, 'sales_order' AS type,
1166 ##               (SELECT buy FROM exchangerate ex
1167 ##                WHERE ex.curr = o.curr AND ex.transdate = o.transdate) AS exchangerate
1168 ##             FROM orderitems oi
1169 ##             JOIN parts p ON (oi.parts_id = p.id)
1170 ##             JOIN oe o ON (oi.trans_id = o.id)
1171 ##             JOIN customer ct ON (o.customer_id = ct.id)
1172 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1173 ##             WHERE $ordwhere AND (o.customer_id > 0)|;
1174 ##        $union = qq| UNION |;
1175 ##
1176 ##        push(@all_values, @ordvalues);
1177 ##      }
1178 ##
1179 ##      if ($form->{onorder}) {
1180 ##        $query .=
1181 ##          qq|$union
1182 ##
1183 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
1184 ##               oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
1185 ##               p.listprice, p.lastcost, p.rop, p.weight,
1186 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
1187 ##               pg.partsgroup,
1188 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1189 ##               ct.name, NULL AS deliverydate,
1190 ##               'oe' AS module, 'purchase_order' AS type,
1191 ##               (SELECT sell FROM exchangerate ex
1192 ##               WHERE ex.curr = o.curr AND (ex.transdate = o.transdate)) AS exchangerate
1193 ##             FROM orderitems oi
1194 ##             JOIN parts p ON (oi.parts_id = p.id)
1195 ##             JOIN oe o ON (oi.trans_id = o.id)
1196 ##             JOIN vendor ct ON (o.vendor_id = ct.id)
1197 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1198 ##             WHERE $ordwhere AND (o.vendor_id > 0)|;
1199 ##        $union = qq| UNION |;
1200 ##
1201 ##        push(@all_values, @ordvalues);
1202 ##      }
1203 ##
1204 ##    }
1205 ##
1206 ##    if ($form->{rfq} || $form->{quoted}) {
1207 ##      my $quowhere = $where . qq| AND o.quotation = '1'|;
1208 ##      my @quovalues = @values;
1209 ##
1210 ##      if ($form->{transdatefrom}) {
1211 ##        $quowhere .= qq| AND o.transdate >= ?|;
1212 ##        push(@quovalues, $form->{transdatefrom});
1213 ##      }
1214 ##
1215 ##      if ($form->{transdateto}) {
1216 ##        $quowhere .= qq| AND o.transdate <= ?|;
1217 ##        push(@quovalues, $form->{transdateto});
1218 ##      }
1219 ##
1220 ##      if ($form->{description}) {
1221 ##        $quowhere .= qq| AND oi.description ILIKE ?|;
1222 ##        push(@quovalues, '%' . $form->{description} . '%');
1223 ##      }
1224 ##
1225 ##      if ($form->{quoted}) {
1226 ##        $query .=
1227 ##          qq|$union
1228 ##
1229 ##             SELECT
1230 ##               p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
1231 ##               oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
1232 ##               p.listprice, p.lastcost, p.rop, p.weight,
1233 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
1234 ##               pg.partsgroup,
1235 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1236 ##               ct.name, NULL AS deliverydate, 'oe' AS module, 'sales_quotation' AS type,
1237 ##               (SELECT buy FROM exchangerate ex
1238 ##                WHERE (ex.curr = o.curr) AND (ex.transdate = o.transdate)) AS exchangerate
1239 ##             FROM orderitems oi
1240 ##             JOIN parts p ON (oi.parts_id = p.id)
1241 ##             JOIN oe o ON (oi.trans_id = o.id)
1242 ##             JOIN customer ct ON (o.customer_id = ct.id)
1243 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1244 ##             WHERE $quowhere
1245 ##             AND o.customer_id > 0|;
1246 ##        $union = qq| UNION |;
1247 ##
1248 ##        push(@all_values, @quovalues);
1249 ##      }
1250 ##
1251 ##      if ($form->{rfq}) {
1252 ##        $query .=
1253 ##          qq|$union
1254 ##
1255 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
1256 ##               oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
1257 ##               p.listprice, p.lastcost, p.rop, p.weight,
1258 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
1259 ##               pg.partsgroup,
1260 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1261 ##               ct.name, NULL AS deliverydate,
1262 ##               'oe' AS module, 'request_quotation' AS type,
1263 ##               (SELECT sell FROM exchangerate ex
1264 ##               WHERE (ex.curr = o.curr) AND (ex.transdate = o.transdate)) AS exchangerate
1265 ##             FROM orderitems oi
1266 ##             JOIN parts p ON (oi.parts_id = p.id)
1267 ##             JOIN oe o ON (oi.trans_id = o.id)
1268 ##             JOIN vendor ct ON (o.vendor_id = ct.id)
1269 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1270 ##             WHERE $quowhere
1271 ##             AND o.vendor_id > 0|;
1272 ##
1273 ##        push(@all_values, @quovalues);
1274 ##      }
1275 ##
1276 ##    }
1277 ##    $query .= qq| ORDER BY  | . $sortorder;
1278 ##
1279 ##  }
1280 ##
1281 ##  $form->{parts} = selectall_hashref_query($form, $dbh, $query, @all_values);
1282 #
1283   my @assemblies;
1284   # include individual items for assemblies
1285   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1286     $query =
1287       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1288            p.unit, p.bin,
1289            p.sellprice, p.listprice, p.lastcost,
1290            p.rop, p.weight, p.priceupdate,
1291            p.image, p.drawing, p.microfiche
1292          FROM parts p, assembly a
1293          WHERE (p.id = a.parts_id) AND (a.id = ?)|;
1294     $sth = prepare_query($form, $dbh, $query);
1295
1296     foreach $item (@{ $form->{parts} }) {
1297       push(@assemblies, $item);
1298       do_statement($form, $sth, $query, conv_i($item->{id}));
1299
1300       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1301         $ref->{assemblyitem} = 1;
1302         push(@assemblies, $ref);
1303       }
1304       $sth->finish;
1305     }
1306
1307     # copy assemblies to $form->{parts}
1308     $form->{parts} = \@assemblies;
1309   }
1310
1311   $dbh->disconnect;
1312   $main::lxdebug->leave_sub();
1313 }
1314
1315 sub update_prices {
1316   $main::lxdebug->enter_sub();
1317
1318   my ($self, $myconfig, $form) = @_;
1319   my @where_values;
1320   my $where = '1 = 1';
1321   my $var;
1322
1323   my $group;
1324   my $limit;
1325
1326   if ($item ne 'make') {
1327     foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1328       my $column = $item;
1329       $column =~ s/.*\.//;
1330       next unless ($form->{$column});
1331       $where .= qq| AND $item ILIKE ?|;
1332       push(@where_values, '%' . $form->{$column} . '%');
1333     }
1334   }
1335
1336   # special case for description
1337   if ($form->{description}
1338       && !(   $form->{bought}  || $form->{sold} || $form->{onorder}
1339            || $form->{ordered} || $form->{rfq} || $form->{quoted})) {
1340     $where .= qq| AND (p.description ILIKE ?)|;
1341     push(@where_values, '%' . $form->{description} . '%');
1342   }
1343
1344   # special case for serialnumber
1345   if ($form->{l_serialnumber} && $form->{serialnumber}) {
1346     $where .= qq| AND serialnumber ILIKE ?|;
1347     push(@where_values, '%' . $form->{serialnumber} . '%');
1348   }
1349
1350
1351   # items which were never bought, sold or on an order
1352   if ($form->{itemstatus} eq 'orphaned') {
1353     $form->{onhand}  = $form->{short}   = 0;
1354     $form->{bought}  = $form->{sold}    = 0;
1355     $form->{onorder} = $form->{ordered} = 0;
1356     $form->{rfq}     = $form->{quoted}  = 0;
1357
1358     $form->{transdatefrom} = $form->{transdateto} = "";
1359
1360     $where .=
1361       qq| AND (p.onhand = 0)
1362           AND p.id NOT IN
1363             (
1364               SELECT DISTINCT parts_id FROM invoice
1365               UNION
1366               SELECT DISTINCT parts_id FROM assembly
1367               UNION
1368               SELECT DISTINCT parts_id FROM orderitems
1369             )|;
1370   }
1371
1372   if ($form->{itemstatus} eq 'active') {
1373     $where .= qq| AND p.obsolete = '0'|;
1374   }
1375
1376   if ($form->{itemstatus} eq 'obsolete') {
1377     $where .= qq| AND p.obsolete = '1'|;
1378     $form->{onhand} = $form->{short} = 0;
1379   }
1380
1381   if ($form->{itemstatus} eq 'onhand') {
1382     $where .= qq| AND p.onhand > 0|;
1383   }
1384
1385   if ($form->{itemstatus} eq 'short') {
1386     $where .= qq| AND p.onhand < p.rop|;
1387   }
1388
1389   foreach my $column (qw(make model)) {
1390     next unless ($form->{$colum});
1391     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1392     push(@where_values, '%' . $form->{$column} . '%');
1393   }
1394
1395   # connect to database
1396   my $dbh = $form->dbconnect_noauto($myconfig);
1397
1398   for my $column (qw(sellprice listprice)) {
1399     next if ($form->{$column} eq "");
1400
1401     my $value = $form->parse_amount($myconfig, $form->{$column});
1402     my $operator = '+';
1403
1404     if ($form->{"${column}_type"} eq "percent") {
1405       $value = ($value / 100) + 1;
1406       $operator = '*';
1407     }
1408
1409     $query =
1410       qq|UPDATE parts SET $column = $column $operator ?
1411          WHERE id IN
1412            (SELECT p.id
1413             FROM parts p
1414             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1415             WHERE $where)|;
1416     do_query($from, $dbh, $query, $value, @where_values);
1417   }
1418
1419   my $q_add =
1420     qq|UPDATE prices SET price = price + ?
1421        WHERE parts_id IN
1422          (SELECT p.id
1423           FROM parts p
1424           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1425           WHERE $where) AND (pricegroup_id = ?)|;
1426   my $sth_add = prepare_query($form, $dbh, $q_add);
1427
1428   my $q_multiply =
1429     qq|UPDATE prices SET price = price * ?
1430        WHERE parts_id IN
1431          (SELECT p.id
1432           FROM parts p
1433           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1434           WHERE $where) AND (pricegroup_id = ?)|;
1435   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1436
1437   for my $i (1 .. $form->{price_rows}) {
1438     next if ($form->{"price_$i"} eq "");
1439
1440     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1441
1442     if ($form->{"pricegroup_type_$i"} eq "percent") {
1443       do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1444     } else {
1445       do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1446     }
1447   }
1448
1449   $sth_add->finish();
1450   $sth_multiply->finish();
1451
1452   my $rc= $dbh->commit;
1453   $dbh->disconnect;
1454
1455   $main::lxdebug->leave_sub();
1456
1457   return $rc;
1458 }
1459
1460 sub create_links {
1461   $main::lxdebug->enter_sub();
1462
1463   my ($self, $module, $myconfig, $form) = @_;
1464
1465   # connect to database
1466   my $dbh = $form->dbconnect($myconfig);
1467
1468   my @values = ('%' . $module . '%');
1469
1470   if ($form->{id}) {
1471     $query =
1472       qq|SELECT c.accno, c.description, c.link, c.id,
1473            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1474          FROM chart c, parts p
1475          WHERE (c.link LIKE ?) AND (p.id = ?)
1476          ORDER BY c.accno|;
1477     push(@values, conv_i($form->{id}));
1478
1479   } else {
1480     $query =
1481       qq|SELECT c.accno, c.description, c.link, c.id,
1482            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1483          FROM chart c, defaults d
1484          WHERE c.link LIKE ?
1485          ORDER BY c.accno|;
1486   }
1487
1488   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1489   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1490     foreach my $key (split(/:/, $ref->{link})) {
1491       if ($key =~ /\Q$module\E/) {
1492         if (   ($ref->{id} eq $ref->{inventory_accno_id})
1493             || ($ref->{id} eq $ref->{income_accno_id})
1494             || ($ref->{id} eq $ref->{expense_accno_id})) {
1495           push @{ $form->{"${module}_links"}{$key} },
1496             { accno       => $ref->{accno},
1497               description => $ref->{description},
1498               selected    => "selected" };
1499           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1500             } else {
1501           push @{ $form->{"${module}_links"}{$key} },
1502             { accno       => $ref->{accno},
1503               description => $ref->{description},
1504               selected    => "" };
1505         }
1506       }
1507     }
1508   }
1509   $sth->finish;
1510
1511   # get buchungsgruppen
1512   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1513
1514   # get payment terms
1515   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1516
1517   if (!$form->{id}) {
1518     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1519   }
1520
1521   $dbh->disconnect;
1522   $main::lxdebug->leave_sub();
1523 }
1524
1525 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1526 sub get_parts {
1527   $main::lxdebug->enter_sub();
1528
1529   my ($self, $myconfig, $form, $sortorder) = @_;
1530   my $dbh   = $form->dbconnect($myconfig);
1531   my $order = qq| p.partnumber|;
1532   my $where = qq|1 = 1|;
1533   my @values;
1534
1535   if ($sortorder eq "all") {
1536     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1537     push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1538
1539   } elsif ($sortorder eq "partnumber") {
1540     $where .= qq| AND (partnumber ILIKE ?)|;
1541     push(@values, '%' . $form->{partnumber} . '%');
1542
1543   } elsif ($sortorder eq "description") {
1544     $where .= qq| AND (description ILIKE ?)|;
1545     push(@values, '%' . $form->{description} . '%');
1546     $order = "description";
1547
1548   }
1549
1550   my $query =
1551     qq|SELECT id, partnumber, description, unit, sellprice
1552        FROM parts
1553        WHERE $where ORDER BY $order|;
1554
1555   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1556
1557   my $j = 0;
1558   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1559     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1560       next;
1561     }
1562
1563     $j++;
1564     $form->{"id_$j"}          = $ref->{id};
1565     $form->{"partnumber_$j"}  = $ref->{partnumber};
1566     $form->{"description_$j"} = $ref->{description};
1567     $form->{"unit_$j"}        = $ref->{unit};
1568     $form->{"sellprice_$j"}   = $ref->{sellprice};
1569     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
1570   }    #while
1571   $form->{rows} = $j;
1572   $sth->finish;
1573   $dbh->disconnect;
1574
1575   $main::lxdebug->leave_sub();
1576
1577   return $self;
1578 }    #end get_parts()
1579
1580 # gets sum of sold part with part_id
1581 sub get_soldtotal {
1582   $main::lxdebug->enter_sub();
1583
1584   my ($dbh, $id) = @_;
1585
1586   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1587   my ($sum) = selectrow_query($form, $dbh, $query, conv_i($id));
1588   $sum ||= 0;
1589
1590   $main::lxdebug->leave_sub();
1591
1592   return $sum;
1593 }    #end get_soldtotal
1594
1595 sub retrieve_languages {
1596   $main::lxdebug->enter_sub();
1597
1598   my ($self, $myconfig, $form) = @_;
1599
1600   # connect to database
1601   my $dbh = $form->dbconnect($myconfig);
1602
1603   my @values;
1604   my $where;
1605
1606   if ($form->{language_values} ne "") {
1607     $query =
1608       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1609          FROM language l
1610          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1611          ORDER BY lower(l.description)|;
1612     @values = (conv_i($form->{id}));
1613
1614   } else {
1615     $query = qq|SELECT id, description
1616                 FROM language
1617                 ORDER BY lower(description)|;
1618   }
1619
1620   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1621
1622   $dbh->disconnect;
1623
1624   $main::lxdebug->leave_sub();
1625
1626   return $languages;
1627 }
1628
1629 sub follow_account_chain {
1630   $main::lxdebug->enter_sub(2);
1631
1632   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1633
1634   my @visited_accno_ids = ($accno_id);
1635
1636   my ($query, $sth);
1637
1638   $query =
1639     qq|SELECT c.new_chart_id, date($transdate) >= c.valid_from AS is_valid, | .
1640     qq|  cnew.accno | .
1641     qq|FROM chart c | .
1642     qq|LEFT JOIN chart cnew ON c.new_chart_id = cnew.id | .
1643     qq|WHERE (c.id = ?) AND NOT c.new_chart_id ISNULL AND (c.new_chart_id > 0)|;
1644   $sth = prepare_query($form, $dbh, $query);
1645
1646   while (1) {
1647     do_statement($form, $sth, $query, $accno_id);
1648     $ref = $sth->fetchrow_hashref();
1649     last unless ($ref && $ref->{"is_valid"} &&
1650                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1651     $accno_id = $ref->{"new_chart_id"};
1652     $accno = $ref->{"accno"};
1653     push(@visited_accno_ids, $accno_id);
1654   }
1655
1656   $main::lxdebug->leave_sub(2);
1657
1658   return ($accno_id, $accno);
1659 }
1660
1661 sub retrieve_accounts {
1662   $main::lxdebug->enter_sub(2);
1663
1664   my ($self, $myconfig, $form, $parts_id, $index) = @_;
1665
1666   my ($query, $sth, $dbh);
1667
1668   $form->{"taxzone_id"} *= 1;
1669
1670   $dbh = $form->get_standard_dbh($myconfig);
1671
1672   my $transdate = "";
1673   if ($form->{type} eq "invoice") {
1674     if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1675       $transdate = $form->{invdate};
1676     } else {
1677       $transdate = $form->{deliverydate};
1678     }
1679   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1680     $transdate = $form->{invdate};
1681   } else {
1682     $transdate = $form->{transdate};
1683   }
1684
1685   if ($transdate eq "") {
1686     $transdate = "current_date";
1687   } else {
1688     $transdate = $dbh->quote($transdate);
1689   }
1690
1691   $query =
1692     qq|SELECT | .
1693     qq|  p.inventory_accno_id AS is_part, | .
1694     qq|  bg.inventory_accno_id, | .
1695     qq|  bg.income_accno_id_$form->{taxzone_id} AS income_accno_id, | .
1696     qq|  bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id, | .
1697     qq|  c1.accno AS inventory_accno, | .
1698     qq|  c2.accno AS income_accno, | .
1699     qq|  c3.accno AS expense_accno | .
1700     qq|FROM parts p | .
1701     qq|LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id | .
1702     qq|LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id | .
1703     qq|LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id | .
1704     qq|LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id | .
1705     qq|WHERE p.id = ?|;
1706   my $ref = selectfirst_hashref_query($form, $dbh, $query, $parts_id);
1707
1708   return $main::lxdebug->leave_sub(2) if (!$ref);
1709
1710   $ref->{"inventory_accno_id"} = undef unless ($ref->{"is_part"});
1711
1712   my %accounts;
1713   foreach my $type (qw(inventory income expense)) {
1714     next unless ($ref->{"${type}_accno_id"});
1715     ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1716       $self->follow_account_chain($form, $dbh, $transdate,
1717                                   $ref->{"${type}_accno_id"},
1718                                   $ref->{"${type}_accno"});
1719   }
1720
1721   map({ $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} }
1722       qw(inventory income expense));
1723
1724   my $inc_exp = $form->{"vc"} eq "customer" ? "income" : "expense";
1725   my $accno_id = $accounts{"${inc_exp}_accno_id"};
1726
1727   $query =
1728     qq|SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber | .
1729     qq|FROM tax t | .
1730     qq|LEFT JOIN chart c ON c.id = t.chart_id | .
1731     qq|WHERE t.id IN | .
1732     qq|  (SELECT tk.tax_id | .
1733     qq|   FROM taxkeys tk | .
1734     qq|   WHERE tk.chart_id = ? AND startdate <= | . quote_db_date($transdate) .
1735     qq|   ORDER BY startdate DESC LIMIT 1) |;
1736   $ref = selectfirst_hashref_query($form, $dbh, $query, $accno_id);
1737
1738   unless ($ref) {
1739     $main::lxdebug->leave_sub(2);
1740     return;
1741   }
1742
1743   $form->{"taxaccounts_$index"} = $ref->{"accno"};
1744   if ($form->{"taxaccounts"} !~ /$ref->{accno}/) {
1745     $form->{"taxaccounts"} .= "$ref->{accno} ";
1746   }
1747   map({ $form->{"$ref->{accno}_${_}"} = $ref->{$_}; }
1748       qw(rate description taxnumber));
1749
1750 #   $main::lxdebug->message(0, "formvars: rate " . $form->{"$ref->{accno}_rate"} .
1751 #                           " description " . $form->{"$ref->{accno}_description"} .
1752 #                           " taxnumber " . $form->{"$ref->{accno}_taxnumber"} .
1753 #                           " || taxaccounts_$index " . $form->{"taxaccounts_$index"} .
1754 #                           " || taxaccounts " . $form->{"taxaccounts"});
1755
1756   $main::lxdebug->leave_sub(2);
1757 }
1758
1759 sub get_basic_part_info {
1760   $main::lxdebug->enter_sub();
1761
1762   my $self     = shift;
1763   my %params   = @_;
1764
1765   Common::check_params(\%params, qw(id));
1766
1767   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1768
1769   if (!scalar @ids) {
1770     $main::lxdebug->leave_sub();
1771     return ();
1772   }
1773
1774   my $myconfig = \%main::myconfig;
1775   my $form     = $main::form;
1776
1777   my $dbh      = $form->get_standard_dbh($myconfig);
1778
1779   my $query    = qq|SELECT id, partnumber, description, unit FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1780
1781   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1782
1783   if ($params{vendor_id}) {
1784     $query     = qq|SELECT * FROM parts_vendor WHERE (parts_id = ?) AND (vendor_id = ?)|;
1785     my $sth    = prepare_query($form, $dbh, $query);
1786
1787     foreach my $part (@{ $info }) {
1788       do_statement($form, $sth, $query, $part->{id}, conv_i($params{vendor_id}));
1789       $part->{vendor_info} = $sth->fetchrow_hashref();
1790     }
1791
1792     $sth->finish();
1793   }
1794
1795   if ('' eq ref $params{id}) {
1796     $info = $info->[0] || { };
1797
1798     $main::lxdebug->leave_sub();
1799     return $info;
1800   }
1801
1802   my %info_map = map { $_->{id} => $_ } @{ $info };
1803
1804   $main::lxdebug->leave_sub();
1805
1806   return %info_map;
1807 }
1808
1809
1810 1;