5314d4b8e694ca4333e53a27c5b31e9f537745d0
[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, p.weight, p.onhand, p.unit, pg.partsgroup,
702               p.price_factor_id, pfac.factor AS price_factor
703        FROM parts p
704        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
705        LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
706        WHERE $where|;
707   $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
708
709   $dbh->disconnect;
710
711   $main::lxdebug->leave_sub();
712 }
713
714 #
715 # Report for Wares.
716 # Warning, deep magic ahead.
717 # This function gets all parts from the database according to the filters specified
718 #
719 # specials:
720 #   sort revers  - sorting field + direction
721 #   top100
722 #
723 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
724 #   partnumber ean description partsgroup microfiche drawing
725 #
726 # column flags:
727 #   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
728 #
729 # exclusives:
730 #   itemstatus  = active | onhand | short | obsolete | orphaned
731 #   searchitems = part | assembly | service
732 #
733 # joining filters:
734 #   make model                               - makemodel
735 #   serialnumber transdatefrom transdateto   - invoice/orderitems
736 #
737 # binary flags:
738 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
739 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
740 #   l_soldtotal                              - aggreg join to display total of sold quantity
741 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
742 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
743 #   l_serialnumber                           - belonges to serialnumber filter
744 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
745 #   l_soldtotal                              - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
746 #
747 # not working:
748 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
749 #   masking of onhand in bsooqr mode         - ToDO: fixme
750 #
751 # disabled sanity checks and changes:
752 #  - searchitems = assembly will no longer disable bought
753 #  - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
754 #  - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
755 #  - itemstatus = obsolete will no longer disable onhand, short
756 #  - allow sorting by ean
757 #  - serialnumber filter also works if l_serialnumber isn't ticked
758 #  - onhand doesn't get masked by it's oi or invoice counterparts atm. ToDO: fix this
759 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
760 #
761 sub all_parts {
762   $main::lxdebug->enter_sub();
763
764   my ($self, $myconfig, $form) = @_;
765   my $dbh = $form->get_standard_dbh($myconfig);
766
767   $form->{parts}     = +{ };
768   $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
769
770   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
771   my @makemodel_filters    = qw(make model);
772   my @invoice_oi_filters   = qw(serialnumber soldtotal);
773   my @apoe_filters         = qw(transdate);
774   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
775   my @simple_l_switches    = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
776   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
777   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module);
778   my @deliverydate_flags   = qw(deliverydate);
779 #  my @other_flags          = qw(onhand); # ToDO: implement these
780 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
781
782   my %joins = (
783     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
784     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
785     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
786     invoice_oi =>
787       q|LEFT JOIN (
788          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem, 'invoice'    AS ioi FROM invoice UNION
789          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, 'orderitems' AS ioi FROM orderitems
790        ) AS ioi ON ioi.parts_id = p.id|,
791     apoe       =>
792       q|LEFT JOIN (
793          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
794          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
795          SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber,          quotation,         customer_id,         vendor_id, NULL AS deliverydate, 'orderitems' AS ioi FROM oe
796        ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
797     cv         =>
798       q|LEFT JOIN (
799            SELECT id, name, 'customer' AS cv FROM customer UNION
800            SELECT id, name, 'vendor'   AS cv FROM vendor
801          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
802   );
803   my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
804   my %joins_needed;
805
806   if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
807     @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
808   }
809
810   #===== switches and simple filters ========#
811
812   my @select_tokens = qw(id factor);
813   my @where_tokens  = qw(1=1);
814   my @group_tokens  = ();
815
816   # special case transdate
817   if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
818     $form->{"l_transdate"} = 1;
819     push @select_tokens, 'transdate';
820     for (qw(transdatefrom transdateto)) {
821       next unless $form->{$_};
822       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
823       push @bind_vars,    $form->{$_};
824     }
825   }
826
827   my %simple_filter_table_prefix = (
828      description  => 'p.',
829   );
830
831   foreach (@simple_filters, @makemodel_filters, @invoice_oi_filters) {
832     next unless $form->{$_};
833     $form->{"l_$_"} = '1'; # show the column
834     push @where_tokens, "$simple_filter_table_prefix{$_}$_ ILIKE ?";
835     push @bind_vars,    "%$form->{$_}%";
836   }
837
838   foreach (@simple_l_switches) {
839     next unless $form->{"l_$_"};
840     push @select_tokens, $_;
841   }
842
843   for ($form->{searchitems}) {
844     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
845     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
846     push @where_tokens, 'NOT p.assembly'               if /service/;
847     push @where_tokens, '    p.assembly'               if /assembly/;
848   }
849
850   for ($form->{itemstatus}) {
851     push @where_tokens, 'p.id NOT IN
852         (SELECT DISTINCT parts_id FROM invoice UNION
853          SELECT DISTINCT parts_id FROM assembly UNION
854          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
855     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
856     push @where_tokens, 'NOT p.obsolete'               if /active/;
857     push @where_tokens, '    p.obsolete',              if /obsolete/;
858     push @where_tokens, 'p.onhand > 0',                if /onhand/;
859     push @where_tokens, 'p.onhand < p.rop',            if /short/;
860   }
861
862   my $q_assembly_lastcost =
863     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
864         FROM assembly a_lc
865         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
866         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
867         WHERE (a_lc.id = p.id)) AS lastcost|;
868
869   my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
870   $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols;
871
872   my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
873
874   # special case: sorting by partnumber
875   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
876   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
877   # ToDO: implement proper functional sorting
878   $form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
879     if $form->{sort} eq 'partnumber';
880
881   my $order_clause = " ORDER BY $form->{sort} $sort_order";
882
883   my $limit_clause = " LIMIT 100" if $form->{top100};
884
885   #=== joins and complicated filters ========#
886
887   my $bsooqr = $form->{bought}  || $form->{sold}
888             || $form->{ordered} || $form->{onorder}
889             || $form->{quoted}  || $form->{rfq};
890
891   my @bsooqr;
892   push @select_tokens, @qsooqr_flags                                          if $bsooqr;
893   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
894   push @select_tokens, $q_assembly_lastcost                                   if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
895   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
896   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
897   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
898   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
899   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
900   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
901   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
902
903   $joins_needed{partsgroup}  = 1;
904   $joins_needed{pfac}        = 1;
905   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
906   $joins_needed{cv}          = 1 if $bsooqr;
907   $joins_needed{apoe}        = 1 if $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
908   $joins_needed{invoice_oi}  = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
909
910   # special case for description search.
911   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
912   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
913   # find the old entries in of @where_tokens and @bind_vars, and adjust them
914   if ($joins_needed{invoice_oi}) {
915     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
916       next unless $where_tokens[$wi] =~ /^description ILIKE/;
917       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
918       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
919       last;
920     }
921   }
922
923   # now the master trick: soldtotal.
924   if ($form->{l_soldtotal}) {
925     push @where_tokens, 'ioi.qty >= 0';
926     push @group_tokens, @select_tokens;
927      map { s/.*\sAS\s+//si } @group_tokens;
928     push @select_tokens, 'SUM(ioi.qty)';
929   }
930
931   #============= build query ================#
932
933   %table_prefix = (
934      %table_prefix,
935      deliverydate => 'apoe.', serialnumber => 'ioi.',
936      transdate    => 'apoe.', trans_id     => 'ioi.',
937      module       => 'apoe.', name         => 'cv.',
938      ordnumber    => 'apoe.', make         => 'mm.',
939      quonumber    => 'apoe.', model        => 'mm.',
940      invnumber    => 'apoe.', partsgroup   => 'pg.',
941      lastcost     => ' ',
942      factor       => 'pfac.',
943      'SUM(ioi.qty)' => ' ',
944   );
945
946   $table_prefix{$q_assembly_lastcost} = ' ';
947
948   my %renamed_columns = (
949     'factor'       => 'price_factor',
950     'SUM(ioi.qty)' => 'soldtotal',
951   );
952
953   map { $table_prefix{$_} = 'ioi.' } qw(description serialnumber qty unit) if $joins_needed{invoice_oi};
954   map { $renamed_columns{$_} = ' AS ' . $renamed_columns{$_} } keys %renamed_columns;
955
956   my $select_clause = join ', ',    map { ($table_prefix{$_} || "p.") . $_ . $renamed_columns{$_} } @select_tokens;
957   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
958   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
959   my $group_clause  = ' GROUP BY ' . join ', ',    map { ($table_prefix{$_} || "p.") . $_ } @group_tokens if scalar @group_tokens;
960
961   my $query = qq|SELECT DISTINCT $select_clause FROM parts p $join_clause WHERE $where_clause $group_clause $order_clause $limit_clause|;
962
963   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
964
965   map { $_->{onhand} *= 1 } @{ $form->{parts} };
966
967   my @assemblies;
968   # include individual items for assemblies
969   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
970     $query =
971       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
972            p.unit, p.bin,
973            p.sellprice, p.listprice, p.lastcost,
974            p.rop, p.weight, p.priceupdate,
975            p.image, p.drawing, p.microfiche
976          FROM parts p, assembly a
977          WHERE (p.id = a.parts_id) AND (a.id = ?)|;
978     $sth = prepare_query($form, $dbh, $query);
979
980     foreach $item (@{ $form->{parts} }) {
981       push(@assemblies, $item);
982       do_statement($form, $sth, $query, conv_i($item->{id}));
983
984       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
985         $ref->{assemblyitem} = 1;
986         push(@assemblies, $ref);
987       }
988       $sth->finish;
989     }
990
991     # copy assemblies to $form->{parts}
992     $form->{parts} = \@assemblies;
993   }
994
995   $main::lxdebug->leave_sub();
996 }
997
998 sub update_prices {
999   $main::lxdebug->enter_sub();
1000
1001   my ($self, $myconfig, $form) = @_;
1002   my @where_values;
1003   my $where = '1 = 1';
1004   my $var;
1005
1006   my $group;
1007   my $limit;
1008
1009   if ($item ne 'make') {
1010     foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1011       my $column = $item;
1012       $column =~ s/.*\.//;
1013       next unless ($form->{$column});
1014       $where .= qq| AND $item ILIKE ?|;
1015       push(@where_values, '%' . $form->{$column} . '%');
1016     }
1017   }
1018
1019   # special case for description
1020   if ($form->{description}
1021       && !(   $form->{bought}  || $form->{sold} || $form->{onorder}
1022            || $form->{ordered} || $form->{rfq} || $form->{quoted})) {
1023     $where .= qq| AND (p.description ILIKE ?)|;
1024     push(@where_values, '%' . $form->{description} . '%');
1025   }
1026
1027   # special case for serialnumber
1028   if ($form->{l_serialnumber} && $form->{serialnumber}) {
1029     $where .= qq| AND serialnumber ILIKE ?|;
1030     push(@where_values, '%' . $form->{serialnumber} . '%');
1031   }
1032
1033
1034   # items which were never bought, sold or on an order
1035   if ($form->{itemstatus} eq 'orphaned') {
1036     $form->{onhand}  = $form->{short}   = 0;
1037     $form->{bought}  = $form->{sold}    = 0;
1038     $form->{onorder} = $form->{ordered} = 0;
1039     $form->{rfq}     = $form->{quoted}  = 0;
1040
1041     $form->{transdatefrom} = $form->{transdateto} = "";
1042
1043     $where .=
1044       qq| AND (p.onhand = 0)
1045           AND p.id NOT IN
1046             (
1047               SELECT DISTINCT parts_id FROM invoice
1048               UNION
1049               SELECT DISTINCT parts_id FROM assembly
1050               UNION
1051               SELECT DISTINCT parts_id FROM orderitems
1052             )|;
1053   }
1054
1055   if ($form->{itemstatus} eq 'active') {
1056     $where .= qq| AND p.obsolete = '0'|;
1057   }
1058
1059   if ($form->{itemstatus} eq 'obsolete') {
1060     $where .= qq| AND p.obsolete = '1'|;
1061     $form->{onhand} = $form->{short} = 0;
1062   }
1063
1064   if ($form->{itemstatus} eq 'onhand') {
1065     $where .= qq| AND p.onhand > 0|;
1066   }
1067
1068   if ($form->{itemstatus} eq 'short') {
1069     $where .= qq| AND p.onhand < p.rop|;
1070   }
1071
1072   foreach my $column (qw(make model)) {
1073     next unless ($form->{$colum});
1074     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1075     push(@where_values, '%' . $form->{$column} . '%');
1076   }
1077
1078   # connect to database
1079   my $dbh = $form->dbconnect_noauto($myconfig);
1080
1081   for my $column (qw(sellprice listprice)) {
1082     next if ($form->{$column} eq "");
1083
1084     my $value = $form->parse_amount($myconfig, $form->{$column});
1085     my $operator = '+';
1086
1087     if ($form->{"${column}_type"} eq "percent") {
1088       $value = ($value / 100) + 1;
1089       $operator = '*';
1090     }
1091
1092     $query =
1093       qq|UPDATE parts SET $column = $column $operator ?
1094          WHERE id IN
1095            (SELECT p.id
1096             FROM parts p
1097             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1098             WHERE $where)|;
1099     do_query($from, $dbh, $query, $value, @where_values);
1100   }
1101
1102   my $q_add =
1103     qq|UPDATE prices SET price = price + ?
1104        WHERE parts_id IN
1105          (SELECT p.id
1106           FROM parts p
1107           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1108           WHERE $where) AND (pricegroup_id = ?)|;
1109   my $sth_add = prepare_query($form, $dbh, $q_add);
1110
1111   my $q_multiply =
1112     qq|UPDATE prices SET price = price * ?
1113        WHERE parts_id IN
1114          (SELECT p.id
1115           FROM parts p
1116           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1117           WHERE $where) AND (pricegroup_id = ?)|;
1118   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1119
1120   for my $i (1 .. $form->{price_rows}) {
1121     next if ($form->{"price_$i"} eq "");
1122
1123     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1124
1125     if ($form->{"pricegroup_type_$i"} eq "percent") {
1126       do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1127     } else {
1128       do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1129     }
1130   }
1131
1132   $sth_add->finish();
1133   $sth_multiply->finish();
1134
1135   my $rc= $dbh->commit;
1136   $dbh->disconnect;
1137
1138   $main::lxdebug->leave_sub();
1139
1140   return $rc;
1141 }
1142
1143 sub create_links {
1144   $main::lxdebug->enter_sub();
1145
1146   my ($self, $module, $myconfig, $form) = @_;
1147
1148   # connect to database
1149   my $dbh = $form->dbconnect($myconfig);
1150
1151   my @values = ('%' . $module . '%');
1152
1153   if ($form->{id}) {
1154     $query =
1155       qq|SELECT c.accno, c.description, c.link, c.id,
1156            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1157          FROM chart c, parts p
1158          WHERE (c.link LIKE ?) AND (p.id = ?)
1159          ORDER BY c.accno|;
1160     push(@values, conv_i($form->{id}));
1161
1162   } else {
1163     $query =
1164       qq|SELECT c.accno, c.description, c.link, c.id,
1165            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1166          FROM chart c, defaults d
1167          WHERE c.link LIKE ?
1168          ORDER BY c.accno|;
1169   }
1170
1171   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1172   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1173     foreach my $key (split(/:/, $ref->{link})) {
1174       if ($key =~ /\Q$module\E/) {
1175         if (   ($ref->{id} eq $ref->{inventory_accno_id})
1176             || ($ref->{id} eq $ref->{income_accno_id})
1177             || ($ref->{id} eq $ref->{expense_accno_id})) {
1178           push @{ $form->{"${module}_links"}{$key} },
1179             { accno       => $ref->{accno},
1180               description => $ref->{description},
1181               selected    => "selected" };
1182           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1183             } else {
1184           push @{ $form->{"${module}_links"}{$key} },
1185             { accno       => $ref->{accno},
1186               description => $ref->{description},
1187               selected    => "" };
1188         }
1189       }
1190     }
1191   }
1192   $sth->finish;
1193
1194   # get buchungsgruppen
1195   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1196
1197   # get payment terms
1198   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1199
1200   if (!$form->{id}) {
1201     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1202   }
1203
1204   $dbh->disconnect;
1205   $main::lxdebug->leave_sub();
1206 }
1207
1208 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1209 sub get_parts {
1210   $main::lxdebug->enter_sub();
1211
1212   my ($self, $myconfig, $form, $sortorder) = @_;
1213   my $dbh   = $form->dbconnect($myconfig);
1214   my $order = qq| p.partnumber|;
1215   my $where = qq|1 = 1|;
1216   my @values;
1217
1218   if ($sortorder eq "all") {
1219     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1220     push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1221
1222   } elsif ($sortorder eq "partnumber") {
1223     $where .= qq| AND (partnumber ILIKE ?)|;
1224     push(@values, '%' . $form->{partnumber} . '%');
1225
1226   } elsif ($sortorder eq "description") {
1227     $where .= qq| AND (description ILIKE ?)|;
1228     push(@values, '%' . $form->{description} . '%');
1229     $order = "description";
1230
1231   }
1232
1233   my $query =
1234     qq|SELECT id, partnumber, description, unit, sellprice
1235        FROM parts
1236        WHERE $where ORDER BY $order|;
1237
1238   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1239
1240   my $j = 0;
1241   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1242     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1243       next;
1244     }
1245
1246     $j++;
1247     $form->{"id_$j"}          = $ref->{id};
1248     $form->{"partnumber_$j"}  = $ref->{partnumber};
1249     $form->{"description_$j"} = $ref->{description};
1250     $form->{"unit_$j"}        = $ref->{unit};
1251     $form->{"sellprice_$j"}   = $ref->{sellprice};
1252     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
1253   }    #while
1254   $form->{rows} = $j;
1255   $sth->finish;
1256   $dbh->disconnect;
1257
1258   $main::lxdebug->leave_sub();
1259
1260   return $self;
1261 }    #end get_parts()
1262
1263 # gets sum of sold part with part_id
1264 sub get_soldtotal {
1265   $main::lxdebug->enter_sub();
1266
1267   my ($dbh, $id) = @_;
1268
1269   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1270   my ($sum) = selectrow_query($form, $dbh, $query, conv_i($id));
1271   $sum ||= 0;
1272
1273   $main::lxdebug->leave_sub();
1274
1275   return $sum;
1276 }    #end get_soldtotal
1277
1278 sub retrieve_languages {
1279   $main::lxdebug->enter_sub();
1280
1281   my ($self, $myconfig, $form) = @_;
1282
1283   # connect to database
1284   my $dbh = $form->dbconnect($myconfig);
1285
1286   my @values;
1287   my $where;
1288
1289   if ($form->{language_values} ne "") {
1290     $query =
1291       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1292          FROM language l
1293          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1294          ORDER BY lower(l.description)|;
1295     @values = (conv_i($form->{id}));
1296
1297   } else {
1298     $query = qq|SELECT id, description
1299                 FROM language
1300                 ORDER BY lower(description)|;
1301   }
1302
1303   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1304
1305   $dbh->disconnect;
1306
1307   $main::lxdebug->leave_sub();
1308
1309   return $languages;
1310 }
1311
1312 sub follow_account_chain {
1313   $main::lxdebug->enter_sub(2);
1314
1315   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1316
1317   my @visited_accno_ids = ($accno_id);
1318
1319   my ($query, $sth);
1320
1321   $query =
1322     qq|SELECT c.new_chart_id, date($transdate) >= c.valid_from AS is_valid, | .
1323     qq|  cnew.accno | .
1324     qq|FROM chart c | .
1325     qq|LEFT JOIN chart cnew ON c.new_chart_id = cnew.id | .
1326     qq|WHERE (c.id = ?) AND NOT c.new_chart_id ISNULL AND (c.new_chart_id > 0)|;
1327   $sth = prepare_query($form, $dbh, $query);
1328
1329   while (1) {
1330     do_statement($form, $sth, $query, $accno_id);
1331     $ref = $sth->fetchrow_hashref();
1332     last unless ($ref && $ref->{"is_valid"} &&
1333                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1334     $accno_id = $ref->{"new_chart_id"};
1335     $accno = $ref->{"accno"};
1336     push(@visited_accno_ids, $accno_id);
1337   }
1338
1339   $main::lxdebug->leave_sub(2);
1340
1341   return ($accno_id, $accno);
1342 }
1343
1344 sub retrieve_accounts {
1345   $main::lxdebug->enter_sub(2);
1346
1347   my ($self, $myconfig, $form, $parts_id, $index) = @_;
1348
1349   my ($query, $sth, $dbh);
1350
1351   $form->{"taxzone_id"} *= 1;
1352
1353   $dbh = $form->get_standard_dbh($myconfig);
1354
1355   my $transdate = "";
1356   if ($form->{type} eq "invoice") {
1357     if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1358       $transdate = $form->{invdate};
1359     } else {
1360       $transdate = $form->{deliverydate};
1361     }
1362   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1363     $transdate = $form->{invdate};
1364   } else {
1365     $transdate = $form->{transdate};
1366   }
1367
1368   if ($transdate eq "") {
1369     $transdate = "current_date";
1370   } else {
1371     $transdate = $dbh->quote($transdate);
1372   }
1373
1374   $query =
1375     qq|SELECT | .
1376     qq|  p.inventory_accno_id AS is_part, | .
1377     qq|  bg.inventory_accno_id, | .
1378     qq|  bg.income_accno_id_$form->{taxzone_id} AS income_accno_id, | .
1379     qq|  bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id, | .
1380     qq|  c1.accno AS inventory_accno, | .
1381     qq|  c2.accno AS income_accno, | .
1382     qq|  c3.accno AS expense_accno | .
1383     qq|FROM parts p | .
1384     qq|LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id | .
1385     qq|LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id | .
1386     qq|LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id | .
1387     qq|LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id | .
1388     qq|WHERE p.id = ?|;
1389   my $ref = selectfirst_hashref_query($form, $dbh, $query, $parts_id);
1390
1391   return $main::lxdebug->leave_sub(2) if (!$ref);
1392
1393   $ref->{"inventory_accno_id"} = undef unless ($ref->{"is_part"});
1394
1395   my %accounts;
1396   foreach my $type (qw(inventory income expense)) {
1397     next unless ($ref->{"${type}_accno_id"});
1398     ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1399       $self->follow_account_chain($form, $dbh, $transdate,
1400                                   $ref->{"${type}_accno_id"},
1401                                   $ref->{"${type}_accno"});
1402   }
1403
1404   map({ $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} }
1405       qw(inventory income expense));
1406
1407   my $inc_exp = $form->{"vc"} eq "customer" ? "income" : "expense";
1408   my $accno_id = $accounts{"${inc_exp}_accno_id"};
1409
1410   $query =
1411     qq|SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber | .
1412     qq|FROM tax t | .
1413     qq|LEFT JOIN chart c ON c.id = t.chart_id | .
1414     qq|WHERE t.id IN | .
1415     qq|  (SELECT tk.tax_id | .
1416     qq|   FROM taxkeys tk | .
1417     qq|   WHERE tk.chart_id = ? AND startdate <= | . quote_db_date($transdate) .
1418     qq|   ORDER BY startdate DESC LIMIT 1) |;
1419   $ref = selectfirst_hashref_query($form, $dbh, $query, $accno_id);
1420
1421   unless ($ref) {
1422     $main::lxdebug->leave_sub(2);
1423     return;
1424   }
1425
1426   $form->{"taxaccounts_$index"} = $ref->{"accno"};
1427   if ($form->{"taxaccounts"} !~ /$ref->{accno}/) {
1428     $form->{"taxaccounts"} .= "$ref->{accno} ";
1429   }
1430   map({ $form->{"$ref->{accno}_${_}"} = $ref->{$_}; }
1431       qw(rate description taxnumber));
1432
1433 #   $main::lxdebug->message(0, "formvars: rate " . $form->{"$ref->{accno}_rate"} .
1434 #                           " description " . $form->{"$ref->{accno}_description"} .
1435 #                           " taxnumber " . $form->{"$ref->{accno}_taxnumber"} .
1436 #                           " || taxaccounts_$index " . $form->{"taxaccounts_$index"} .
1437 #                           " || taxaccounts " . $form->{"taxaccounts"});
1438
1439   $main::lxdebug->leave_sub(2);
1440 }
1441
1442 sub get_basic_part_info {
1443   $main::lxdebug->enter_sub();
1444
1445   my $self     = shift;
1446   my %params   = @_;
1447
1448   Common::check_params(\%params, qw(id));
1449
1450   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1451
1452   if (!scalar @ids) {
1453     $main::lxdebug->leave_sub();
1454     return ();
1455   }
1456
1457   my $myconfig = \%main::myconfig;
1458   my $form     = $main::form;
1459
1460   my $dbh      = $form->get_standard_dbh($myconfig);
1461
1462   my $query    = qq|SELECT id, partnumber, description, unit FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1463
1464   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1465
1466   if ('' eq ref $params{id}) {
1467     $info = $info->[0] || { };
1468
1469     $main::lxdebug->leave_sub();
1470     return $info;
1471   }
1472
1473   my %info_map = map { $_->{id} => $_ } @{ $info };
1474
1475   $main::lxdebug->leave_sub();
1476
1477   return %info_map;
1478 }
1479
1480 sub prepare_parts_for_printing {
1481   $main::lxdebug->enter_sub();
1482
1483   my $self     = shift;
1484   my %params   = @_;
1485
1486   my $myconfig = \%main::myconfig;
1487   my $form     = $main::form;
1488
1489   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1490
1491   my $prefix   = $params{prefix} || 'id_';
1492   my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1493
1494   my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1495
1496   if (!@part_ids) {
1497     $main::lxdebug->leave_sub();
1498     return;
1499   }
1500
1501   my $placeholders = join ', ', ('?') x scalar(@part_ids);
1502   my $query        = qq|SELECT mm.parts_id, mm.model, v.name AS make
1503                         FROM makemodel mm
1504                         LEFT JOIN vendor v ON (mm.make = cast (v.id as text))
1505                         WHERE mm.parts_id IN ($placeholders)|;
1506
1507   my %makemodel    = ();
1508
1509   my $sth          = prepare_execute_query($form, $dbh, $query, @part_ids);
1510
1511   while (my $ref = $sth->fetchrow_hashref()) {
1512     $makemodel{$ref->{parts_id}} ||= [];
1513     push @{ $makemodel{$ref->{parts_id}} }, $ref;
1514   }
1515
1516   $sth->finish();
1517
1518   my @columns = qw(ean);
1519
1520   $query      = qq|SELECT id, | . join(', ', @columns) . qq|
1521                    FROM parts
1522                    WHERE id IN ($placeholders)|;
1523
1524   my %data    = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1525
1526   map { $form->{$_} = [] } (qw(make model), @columns);
1527
1528   foreach my $i (1 .. $rowcount) {
1529     my $id = $form->{"${prefix}${i}"};
1530
1531     next if (!$id);
1532
1533     foreach (@columns) {
1534       push @{ $form->{$_} }, $data{$id}->{$_};
1535     }
1536
1537     push @{ $form->{make} },  [];
1538     push @{ $form->{model} }, [];
1539
1540     next if (!$makemodel{$id});
1541
1542     foreach my $ref (@{ $makemodel{$id} }) {
1543       map { push @{ $form->{$_}->[-1] }, $ref->{$_} } qw(make model);
1544     }
1545   }
1546
1547   $main::lxdebug->leave_sub();
1548 }
1549
1550
1551 1;