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