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