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