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