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