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