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