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