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