$form->{item} nach $form->{part_type} umbenannt
[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 use SL::DB;
47
48 use strict;
49
50 sub get_part {
51   $main::lxdebug->enter_sub();
52
53   my ($self, $myconfig, $form) = @_;
54
55   # connect to db
56   my $dbh = $form->get_standard_dbh;
57
58   my $sth;
59
60   my $query =
61     qq|SELECT p.*,
62          c1.accno AS inventory_accno,
63          c2.accno AS income_accno,
64          c3.accno AS expense_accno,
65          pg.partsgroup
66        FROM parts p
67        LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
68        LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
69        LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
70        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
71        WHERE p.id = ? |;
72   my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
73
74   # copy to $form variables
75   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
76
77   $form->{mtime} = $form->{itime} if !$form->{mtime};
78   $form->{lastmtime} = $form->{mtime};
79   $form->{onhand} *= 1;
80
81   # part or service item
82   if ($form->{part_type} eq 'assembly') {
83
84     # retrieve assembly items
85     $query =
86       qq|SELECT p.id, p.partnumber, p.description,
87            p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
88            pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
89          FROM parts p
90          JOIN assembly a ON (a.parts_id = p.id)
91          LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
92          LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
93          WHERE (a.id = ?)
94          ORDER BY a.oid|;
95     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
96
97     $form->{assembly_rows} = 0;
98     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
99       $form->{assembly_rows}++;
100       foreach my $key (keys %{$ref}) {
101         $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
102       }
103     }
104     $sth->finish;
105
106   }
107
108   # setup accno hash for <option checked> {amount} is used in create_links
109   $form->{amount}{IC}         = $form->{inventory_accno};
110   $form->{amount}{IC_income}  = $form->{income_accno};
111   $form->{amount}{IC_sale}    = $form->{income_accno};
112   $form->{amount}{IC_expense} = $form->{expense_accno};
113   $form->{amount}{IC_cogs}    = $form->{expense_accno};
114
115   # get prices
116   $query = <<SQL;
117     SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
118     FROM pricegroup pg
119     LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
120     ORDER BY lower(pg.pricegroup)
121 SQL
122
123   my $row = 1;
124   foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
125     $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
126     $row++;
127   }
128   $form->{price_rows} = $row - 1;
129
130   # get makes
131   if ($form->{makemodel}) {
132   #hli
133     $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
134              qq|WHERE m.parts_id = ? order by m.sortorder asc|;
135     my @values = ($form->{id});
136     $sth = $dbh->prepare($query);
137     $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
138
139     my $i = 1;
140
141     while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
142               $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
143     {
144       $i++;
145     }
146     $sth->finish;
147     $form->{makemodel_rows} = $i - 1;
148
149   }
150
151   # get translations
152   $query = qq|SELECT language_id, translation, longdescription
153               FROM translation
154               WHERE parts_id = ?|;
155   $form->{translations} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
156
157   # is it an orphan
158   my @referencing_tables = qw(invoice orderitems inventory);
159   my %column_map         = ( );
160   my $parts_id           = conv_i($form->{id});
161
162   $form->{orphaned}      = 1;
163
164   foreach my $table (@referencing_tables) {
165     my $column  = $column_map{$table} || 'parts_id';
166     $query      = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
167     my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
168
169     if ($found) {
170       $form->{orphaned} = 0;
171       last;
172     }
173   }
174
175   $form->{"unit_changeable"} = $form->{orphaned};
176
177   Common::webdav_folder($form) if $::lx_office_conf{features}{webdav};
178
179   $main::lxdebug->leave_sub();
180 }
181
182 sub get_pricegroups {
183   $main::lxdebug->enter_sub();
184
185   my ($self, $myconfig, $form) = @_;
186
187   my $dbh = $form->get_standard_dbh;
188
189   # get pricegroups
190   my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
191   my $pricegroups = selectall_hashref_query($form, $dbh, $query);
192
193   my $i = 1;
194   foreach my $pg (@{ $pricegroups }) {
195     $form->{"price_$i"}         = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
196     $form->{"pricegroup_id_$i"} = "$pg->{id}";
197     $form->{"pricegroup_$i"}    = "$pg->{pricegroup}";
198     $i++;
199   }
200
201   #correct rows
202   $form->{price_rows} = $i - 1;
203
204   $main::lxdebug->leave_sub();
205
206   return $pricegroups;
207 }
208
209 sub retrieve_buchungsgruppen {
210   $main::lxdebug->enter_sub();
211
212   my ($self, $myconfig, $form) = @_;
213
214   my ($query, $sth);
215
216   my $dbh = $form->get_standard_dbh;
217
218   # get buchungsgruppen
219   $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
220   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
221
222   $main::lxdebug->leave_sub();
223 }
224
225 sub save {
226   my ($self, $myconfig, $form) = @_;
227   $main::lxdebug->enter_sub();
228
229   my $rc = SL::DB->client->with_transaction(\&_save, $self, $myconfig, $form);
230
231   $main::lxdebug->leave_sub();
232   return $rc;
233 }
234
235 sub _save {
236   my ($self, $myconfig, $form) = @_;
237   my @values;
238
239   my $dbh = SL::DB->client->dbh;
240   my $restricter = SL::HTML::Restrict->create;
241
242   # save the part
243   # make up a unique handle and store in partnumber field
244   # then retrieve the record based on the unique handle to get the id
245   # replace the partnumber field with the actual variable
246   # add records for makemodel
247
248   # if there is a $form->{id} then replace the old entry
249   # delete all makemodel entries and add the new ones
250
251   # undo amount formatting
252   map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
253     qw(rop weight listprice sellprice gv lastcost);
254
255   my $makemodel = ($form->{make_1} || $form->{model_1} || ($form->{makemodel_rows} > 1)) ? 1 : 0;
256
257
258   my ($query, $sth);
259
260   my $priceupdate = ', priceupdate = current_date';
261
262   if ($form->{id}) {
263     my $trans_number = SL::TransNumber->new(type => $form->{part_type}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
264     if (!$trans_number->is_unique) {
265       $::lxdebug->leave_sub;
266       return 3;
267     }
268
269     # get old price
270     $query = qq|SELECT sellprice FROM parts WHERE id = ?|;
271     my ($sellprice) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
272
273     # delete makemodel records
274     do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
275
276     if ($form->{part_type} eq 'assembly') {
277       # delete assembly records
278       do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
279     }
280
281     # delete translations
282     do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
283
284     # Check whether or not the prices have changed. If they haven't
285     # then 'priceupdate' should not be updated.
286     my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
287     $priceupdate        = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
288
289   } else {
290     my $trans_number = SL::TransNumber->new(type => $form->{part_type}, dbh => $dbh, number => $form->{partnumber}, save => 1);
291
292     if ($form->{partnumber} && !$trans_number->is_unique) {
293       $::lxdebug->leave_sub;
294       return 3;
295     }
296
297     $form->{partnumber} ||= $trans_number->create_unique;
298
299     ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
300     do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit, part_type) VALUES (?, ?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit}, $form->{part_type});
301
302     $form->{orphaned} = 1;
303   }
304   my $partsgroup_id = undef;
305
306   if ($form->{partsgroup}) {
307     (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
308   }
309
310   my ($subq_inventory, $subq_expense, $subq_income);
311   if ($form->{part_type} eq "part") {
312     $subq_inventory =
313       qq|(SELECT bg.inventory_accno_id
314           FROM buchungsgruppen bg
315           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
316   } else {
317     $subq_inventory = "NULL";
318   }
319
320   if ($form->{part_type} ne "assembly") {
321     $subq_expense =
322       qq|(SELECT tc.expense_accno_id
323           FROM taxzone_charts tc
324           WHERE tc.buchungsgruppen_id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq| and tc.taxzone_id = 0)|;
325   } else {
326     $subq_expense = "NULL";
327   }
328
329   normalize_text_blocks();
330
331   $query =
332     qq|UPDATE parts SET
333          partnumber = ?,
334          description = ?,
335          makemodel = ?,
336          listprice = ?,
337          sellprice = ?,
338          lastcost = ?,
339          weight = ?,
340          unit = ?,
341          notes = ?,
342          formel = ?,
343          rop = ?,
344          warehouse_id = ?,
345          bin_id = ?,
346          buchungsgruppen_id = ?,
347          payment_id = ?,
348          inventory_accno_id = $subq_inventory,
349          income_accno_id = (SELECT tc.income_accno_id FROM taxzone_charts tc WHERE tc.taxzone_id = 0 and tc.buchungsgruppen_id = ?),
350          expense_accno_id = $subq_expense,
351          obsolete = ?,
352          image = ?,
353          drawing = ?,
354          shop = ?,
355          ve = ?,
356          gv = ?,
357          ean = ?,
358          has_sernumber = ?,
359          not_discountable = ?,
360          microfiche = ?,
361          part_type = ?,
362          partsgroup_id = ?,
363          price_factor_id = ?
364          $priceupdate
365        WHERE id = ?|;
366   @values = ($form->{partnumber},
367              $form->{description},
368              $makemodel ? 't' : 'f',
369              $form->{listprice},
370              $form->{sellprice},
371              $form->{lastcost},
372              $form->{weight},
373              $form->{unit},
374              $restricter->process($form->{notes}),
375              $form->{formel},
376              $form->{rop},
377              conv_i($form->{warehouse_id}),
378              conv_i($form->{bin_id}),
379              conv_i($form->{buchungsgruppen_id}),
380              conv_i($form->{payment_id}),
381              conv_i($form->{buchungsgruppen_id}),
382              $form->{obsolete} ? 't' : 'f',
383              $form->{image},
384              $form->{drawing},
385              $form->{shop} ? 't' : 'f',
386              conv_i($form->{ve}),
387              conv_i($form->{gv}),
388              $form->{ean},
389              $form->{has_sernumber} ? 't' : 'f',
390              $form->{not_discountable} ? 't' : 'f',
391              $form->{microfiche},
392              $form->{part_type},
393              conv_i($partsgroup_id),
394              conv_i($form->{price_factor_id}),
395              conv_i($form->{id})
396   );
397   do_query($form, $dbh, $query, @values);
398
399   $form->new_lastmtime('parts');
400
401   # delete translation records
402   do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
403
404   my @translations = grep { $_->{language_id} && $_->{translation} } @{ $form->{translations} || [] };
405   if (@translations) {
406     $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
407                 VALUES ( ?, ?, ?, ? )|;
408     $sth   = $dbh->prepare($query);
409
410     foreach my $translation (@translations) {
411       do_statement($form, $sth, $query, conv_i($form->{id}), conv_i($translation->{language_id}), $translation->{translation}, $restricter->process($translation->{longdescription}));
412     }
413
414     $sth->finish();
415   }
416
417   # delete price records
418   do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
419
420   $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
421   $sth   = prepare_query($form, $dbh, $query);
422
423   for my $i (1 .. $form->{price_rows}) {
424     my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
425     next unless $price;
426
427     @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
428     do_statement($form, $sth, $query, @values);
429   }
430
431   $sth->finish;
432
433   # insert makemodel records
434     my $lastupdate = '';
435     my $value = 0;
436     for my $i (1 .. $form->{makemodel_rows}) {
437       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
438         #hli
439         $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
440         if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
441         {
442             if ($form->{"lastupdate_$i"} eq "") {
443                 $lastupdate = 'now()';
444             } else {
445                 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
446             }
447         } else {
448             $lastupdate = 'now()';
449         }
450         $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
451                  qq|VALUES (?, ?, ?, ?, ?, ?)|;
452         @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
453
454         do_query($form, $dbh, $query, @values);
455       }
456     }
457
458   # add assembly records
459   if ($form->{part_type} eq 'assembly') {
460     # check additional assembly row
461     my $i = $form->{assembly_rows};
462     # if last row is not empty add them
463     if ($form->{"partnumber_$i"} ne "") {
464       $query = qq|SELECT id FROM parts WHERE partnumber = ?|;
465       my ($partid) = selectrow_query($form, $dbh, $query,$form->{"partnumber_$i"} );
466       if ( $partid ) {
467         $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
468         $form->{"id_$i"} = $partid;
469         $form->{"bom_$i"} = 0;
470         $form->{assembly_rows}++;
471       }
472       else {
473         $::form->error($::locale->text("uncorrect partnumber ").$form->{"partnumber_$i"});
474       }
475     }
476
477     for my $i (1 .. $form->{assembly_rows}) {
478       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
479
480       if ($form->{"qty_$i"} != 0) {
481         $form->{"bom_$i"} *= 1;
482         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
483                  qq|VALUES (?, ?, ?, ?)|;
484         @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
485         do_query($form, $dbh, $query, @values);
486       }
487     }
488     my @a = localtime;
489     $a[5] += 1900;
490     $a[4]++;
491     my $shippingdate = "$a[5]-$a[4]-$a[3]";
492
493     $form->get_employee($dbh);
494
495   }
496
497   #set expense_accno=inventory_accno if they are different => bilanz
498   my $vendor_accno =
499     ($form->{expense_accno} != $form->{inventory_accno})
500     ? $form->{inventory_accno}
501     : $form->{expense_accno};
502
503   # get tax rates and description
504   my $accno_id =
505     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
506   $query =
507     qq|SELECT c.accno, c.description, t.rate, t.taxnumber
508        FROM chart c, tax t
509        WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
510        ORDER BY c.accno|;
511   my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
512
513   $form->{taxaccount} = "";
514   while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
515     $form->{taxaccount} .= "$ptr->{accno} ";
516     if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
517       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
518       $form->{"$ptr->{accno}_description"} = $ptr->{description};
519       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
520       $form->{taxaccount2} .= " $ptr->{accno} ";
521     }
522   }
523
524   CVar->save_custom_variables(dbh           => $dbh,
525                               module        => 'IC',
526                               trans_id      => $form->{id},
527                               variables     => $form,
528                               save_validity => 1);
529
530   # Delete saved custom variable values for configs that have been
531   # marked invalid for this part.
532   $query = <<SQL;
533     DELETE FROM custom_variables
534     WHERE (config_id IN (
535         SELECT val.config_id
536         FROM custom_variables_validity val
537         LEFT JOIN custom_variable_configs val_cfg ON (val.config_id = val_cfg.id)
538         WHERE (val_cfg.module = 'IC')
539           AND (val.trans_id   = ?)))
540       AND (trans_id = ?)
541 SQL
542   do_query($form, $dbh, $query, ($form->{id}) x 2);
543
544   return 1;
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.part_type = '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   my ($self, $myconfig, $form) = @_;
585   $main::lxdebug->enter_sub();
586
587   my $rc = SL::DB->client->with_transaction(\&_delete, $self, $myconfig, $form);
588
589   $main::lxdebug->leave_sub();
590   return $rc;
591 }
592
593 sub _delete {
594   my ($self, $myconfig, $form) = @_;
595   my @values = (conv_i($form->{id}));
596
597   my %columns = ( "assembly" => "id", "parts" => "id" );
598
599   for my $table (qw(prices makemodel inventory assembly translation parts)) {
600     my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
601     do_query($form, SL::DB->client->dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
602   }
603
604   return 1;
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   my $query =
643     qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
644        p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
645        p.price_factor_id, pfac.factor AS price_factor, p.notes as longdescription
646        FROM parts p
647        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
648        LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
649        WHERE $where|;
650   $form->{item_list} = selectall_hashref_query($form, SL::DB->client->dbh, $query, @values);
651
652   $main::lxdebug->leave_sub();
653 }
654
655 #
656 # Report for Wares.
657 # Warning, deep magic ahead.
658 # This function gets all parts from the database according to the filters specified
659 #
660 # specials:
661 #   sort revers  - sorting field + direction
662 #   top100
663 #
664 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
665 #   partnumber ean description partsgroup microfiche drawing
666 #
667 # column flags:
668 #   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
669 #
670 # exclusives:
671 #   itemstatus  = active | onhand | short | obsolete | orphaned
672 #   searchitems = part | assembly | service
673 #
674 # joining filters:
675 #   make model                               - makemodel
676 #   serialnumber transdatefrom transdateto   - invoice/orderitems
677 #
678 # binary flags:
679 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
680 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
681 #   l_soldtotal                              - aggreg join to display total of sold quantity
682 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
683 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
684 #   l_serialnumber                           - belonges to serialnumber filter
685 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
686 #   l_soldtotal                              - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
687 #
688 # not working:
689 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
690 #   warehouse onhand
691 #   search by overrides of description
692 #
693 # disabled sanity checks and changes:
694 #  - searchitems = assembly will no longer disable bought
695 #  - searchitems = service  will no longer disable make and model, although services don't have make/model, it doesn't break the query
696 #  - itemstatus  = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
697 #  - itemstatus  = obsolete will no longer disable onhand, short
698 #  - allow sorting by ean
699 #  - serialnumber filter also works if l_serialnumber isn't ticked
700 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
701 #
702 sub all_parts {
703   $main::lxdebug->enter_sub();
704
705   my ($self, $myconfig, $form) = @_;
706   my $dbh = $form->get_standard_dbh($myconfig);
707
708   $form->{parts}     = +{ };
709   $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
710
711   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
712   my @project_filters      = qw(projectnumber projectdescription);
713   my @makemodel_filters    = qw(make model);
714   my @invoice_oi_filters   = qw(serialnumber soldtotal);
715   my @apoe_filters         = qw(transdate);
716   my @like_filters         = (@simple_filters, @invoice_oi_filters);
717   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
718   my @simple_l_switches    = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image shop insertdate));
719   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
720   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module qty);
721   my @deliverydate_flags   = qw(deliverydate);
722 #  my @other_flags          = qw(onhand); # ToDO: implement these
723 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
724
725   my @select_tokens = qw(id factor);
726   my @where_tokens  = qw(1=1);
727   my @group_tokens  = ();
728   my @bind_vars     = ();
729   my %joins_needed  = ();
730
731   my %joins = (
732     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
733     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
734     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
735     invoice_oi =>
736       q|LEFT JOIN (
737          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem,         deliverydate, 'invoice'    AS ioi, project_id, id FROM invoice UNION
738          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
739        ) AS ioi ON ioi.parts_id = p.id|,
740     apoe       =>
741       q|LEFT JOIN (
742          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
743          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
744          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
745        ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
746     cv         =>
747       q|LEFT JOIN (
748            SELECT id, name, 'customer' AS cv FROM customer UNION
749            SELECT id, name, 'vendor'   AS cv FROM vendor
750          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
751     mv         => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
752     project    => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
753   );
754   my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
755
756   my %table_prefix = (
757      deliverydate => 'apoe.', serialnumber => 'ioi.',
758      transdate    => 'apoe.', trans_id     => 'ioi.',
759      module       => 'apoe.', name         => 'cv.',
760      ordnumber    => 'apoe.', make         => 'mm.',
761      quonumber    => 'apoe.', model        => 'mm.',
762      invnumber    => 'apoe.', partsgroup   => 'pg.',
763      lastcost     => 'p.',  , soldtotal    => ' ',
764      factor       => 'pfac.', projectnumber => 'pj.',
765      'SUM(ioi.qty)' => ' ',   projectdescription => 'pj.',
766      description  => 'p.',
767      qty          => 'ioi.',
768      serialnumber => 'ioi.',
769      quotation    => 'apoe.',
770      cv           => 'cv.',
771      "ioi.id"     => ' ',
772      "ioi.ioi"    => ' ',
773   );
774
775   # if the join condition in these blocks are met, the column
776   # of the scecified table will gently override (coalesce actually) the original value
777   # use it to conditionally coalesce values from subtables
778   my @column_override = (
779     #  column name,   prefix,  joins_needed,  nick name (in case column is named like another)
780     [ 'description',  'ioi.',  'invoice_oi'  ],
781     [ 'deliverydate', 'ioi.',  'invoice_oi'  ],
782     [ 'transdate',    'apoe.', 'apoe'        ],
783     [ 'unit',         'ioi.',  'invoice_oi'  ],
784     [ 'sellprice',    'ioi.',  'invoice_oi'  ],
785   );
786
787   # careful with renames. these are HARD, and any filters done on the original column will break
788   my %renamed_columns = (
789     'factor'       => 'price_factor',
790     'SUM(ioi.qty)' => 'soldtotal',
791     'ioi.id'       => 'ioi_id',
792     'ioi.ioi'      => 'ioi',
793     'projectdescription' => 'projectdescription',
794     'insertdate'   => 'insertdate',
795   );
796
797   my %real_column = (
798     projectdescription => 'description',
799     insertdate         => 'itime::DATE',
800   );
801
802   if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
803     @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
804   }
805
806   my $make_token_builder = sub {
807     my $joins_needed = shift;
808     sub {
809       my ($nick, $alias) = @_;
810       my ($col) = $real_column{$nick} || $nick;
811       my @coalesce_tokens =
812         map  { ($_->[1] || 'p.') . $_->[0] }
813         grep { !$_->[2] || $joins_needed->{$_->[2]} }
814         grep { ($_->[3] || $_->[0]) eq $nick }
815         @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
816
817       my $coalesce = scalar @coalesce_tokens > 1;
818       return ($coalesce
819         ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
820         : shift                              @coalesce_tokens)
821         . ($alias && ($coalesce || $renamed_columns{$nick})
822         ?  " AS " . ($renamed_columns{$nick} || $nick)
823         : '');
824     }
825   };
826
827   #===== switches and simple filters ========#
828
829   # special case transdate
830   if (grep { trim($form->{$_}) } qw(transdatefrom transdateto)) {
831     $form->{"l_transdate"} = 1;
832     push @select_tokens, 'transdate';
833     for (qw(transdatefrom transdateto)) {
834       my $value = trim($form->{$_});
835       next unless $value;
836       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
837       push @bind_vars,    $value;
838     }
839   }
840
841   # special case smart search
842   if ($form->{all}) {
843     $form->{"l_$_"} = 1 for qw(partnumber description unit sellprice lastcost cvar_packaging linetotal);
844     push @where_tokens, "p.partnumber ILIKE ? OR p.description ILIKE ?";
845     push @bind_vars,    (like($form->{all})) x 2;
846   }
847
848   # special case insertdate
849   if (grep { trim($form->{$_}) } qw(insertdatefrom insertdateto)) {
850     $form->{"l_insertdate"} = 1;
851     push @select_tokens, 'insertdate';
852
853     my $token_builder = $make_token_builder->();
854     my $token = $token_builder->('insertdate');
855
856     for (qw(insertdatefrom insertdateto)) {
857       my $value = trim($form->{$_});
858       next unless $value;
859       push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
860       push @bind_vars,    $value;
861     }
862   }
863
864   if ($form->{"partsgroup_id"}) {
865     $form->{"l_partsgroup"} = '1'; # show the column
866     push @where_tokens, "pg.id = ?";
867     push @bind_vars, $form->{"partsgroup_id"};
868   }
869
870   if ($form->{shop} ne '') {
871     $form->{l_shop} = '1'; # show the column
872     if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
873       push @where_tokens, 'NOT p.shop';
874       $form->{shop} = 'f';
875     } else {
876       push @where_tokens, 'p.shop';
877     }
878   }
879
880   foreach (@like_filters) {
881     next unless $form->{$_};
882     $form->{"l_$_"} = '1'; # show the column
883     push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
884     push @bind_vars,    like($form->{$_});
885   }
886
887   foreach (@simple_l_switches) {
888     next unless $form->{"l_$_"};
889     push @select_tokens, $_;
890   }
891
892   for ($form->{searchitems}) {
893     push @where_tokens, "p.part_type = 'part'"     if /part/;
894     push @where_tokens, "p.part_type = 'service'"  if /service/;
895     push @where_tokens, "p.part_type = 'assembly'" if /assembly/;
896   }
897
898   for ($form->{itemstatus}) {
899     push @where_tokens, 'p.id NOT IN
900         (SELECT DISTINCT parts_id FROM invoice UNION
901          SELECT DISTINCT parts_id FROM assembly UNION
902          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
903     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
904     push @where_tokens, 'NOT p.obsolete'               if /active/;
905     push @where_tokens, '    p.obsolete',              if /obsolete/;
906     push @where_tokens, 'p.onhand > 0',                if /onhand/;
907     push @where_tokens, 'p.onhand < p.rop',            if /short/;
908   }
909
910   my $q_assembly_lastcost =
911     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
912         FROM assembly a_lc
913         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
914         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
915         WHERE (a_lc.id = p.id)) AS lastcost|;
916   $table_prefix{$q_assembly_lastcost} = ' ';
917
918   # special case makemodel search
919   # all_parts is based upon the assumption that every parameter is named like the column it represents
920   # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
921   # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
922   if ($form->{make}) {
923     push @where_tokens, 'mv.name ILIKE ?';
924     push @bind_vars, like($form->{make});
925   }
926   if ($form->{model}) {
927     push @where_tokens, 'mm.model ILIKE ?';
928     push @bind_vars, like($form->{model});
929   }
930
931   # special case: sorting by partnumber
932   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
933   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
934   # ToDO: implement proper functional sorting
935   # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
936   # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
937   #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
938   #  if $form->{sort} eq 'partnumber';
939
940   #my $order_clause = " ORDER BY $form->{sort} $sort_order";
941
942   my $limit_clause;
943   $limit_clause = " LIMIT 100"                   if $form->{top100};
944   $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
945
946   #=== joins and complicated filters ========#
947
948   my $bsooqr        = any { $form->{$_} } @oe_flags;
949   my @bsooqr_tokens = ();
950
951   push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi'  if $bsooqr;
952   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
953   push @select_tokens, $q_assembly_lastcost                                   if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
954   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
955   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
956   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
957   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
958   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
959   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
960   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
961
962   $joins_needed{partsgroup}  = 1;
963   $joins_needed{pfac}        = 1;
964   $joins_needed{project}     = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
965   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
966   $joins_needed{mv}          = 1 if $joins_needed{makemodel};
967   $joins_needed{cv}          = 1 if $bsooqr;
968   $joins_needed{apoe}        = 1 if $joins_needed{project} || $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
969   $joins_needed{invoice_oi}  = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
970
971   # special case for description search.
972   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
973   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
974   # find the old entries in of @where_tokens and @bind_vars, and adjust them
975   if ($joins_needed{invoice_oi}) {
976     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
977       next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
978       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
979       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
980       last;
981     }
982   }
983
984   # now the master trick: soldtotal.
985   if ($form->{l_soldtotal}) {
986     push @where_tokens, 'NOT ioi.qty = 0';
987     push @group_tokens, @select_tokens;
988      map { s/.*\sAS\s+//si } @group_tokens;
989     push @select_tokens, 'SUM(ioi.qty)';
990   }
991
992   #============= build query ================#
993
994   my $token_builder = $make_token_builder->(\%joins_needed);
995
996   my @sort_cols    = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
997      $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
998   my $sort_order   = ($form->{revers} ? ' DESC' : ' ASC');
999   my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
1000
1001   my $select_clause = join ', ',    map { $token_builder->($_, 1) } @select_tokens;
1002   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
1003   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
1004   my $group_clause  = @group_tokens ? ' GROUP BY ' . join ', ',    map { $token_builder->($_) } @group_tokens : '';
1005
1006   my %oe_flag_to_cvar = (
1007     bought   => 'invoice',
1008     sold     => 'invoice',
1009     onorder  => 'orderitems',
1010     ordered  => 'orderitems',
1011     rfq      => 'orderitems',
1012     quoted   => 'orderitems',
1013   );
1014
1015   my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1016     module         => 'IC',
1017     trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1018     filter         => $form,
1019     sub_module     => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1020   );
1021
1022   if ($cvar_where) {
1023     $where_clause .= qq| AND ($cvar_where)|;
1024     push @bind_vars, @cvar_values;
1025   }
1026
1027   my $query = <<"  SQL";
1028     SELECT DISTINCT $select_clause
1029     FROM parts p
1030     $join_clause
1031     WHERE $where_clause
1032     $group_clause
1033     $order_clause
1034     $limit_clause
1035   SQL
1036
1037   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1038
1039   map { $_->{onhand} *= 1 } @{ $form->{parts} };
1040
1041   # fix qty sign in ap. those are saved negative
1042   if ($bsooqr && $form->{bought}) {
1043     for my $row (@{ $form->{parts} }) {
1044       $row->{qty} *= -1 if $row->{module} eq 'ir';
1045     }
1046   }
1047
1048   # post processing for assembly parts lists (bom)
1049   # for each part get the assembly parts and add them into the partlist.
1050   my @assemblies;
1051   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1052     $query =
1053       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1054            p.unit, p.notes, p.itime::DATE as insertdate,
1055            p.sellprice, p.listprice, p.lastcost,
1056            p.rop, p.weight, p.priceupdate,
1057            p.image, p.drawing, p.microfiche,
1058            pfac.factor
1059          FROM parts p
1060          INNER JOIN assembly a ON (p.id = a.parts_id)
1061          $joins{pfac}
1062          WHERE a.id = ?|;
1063     my $sth = prepare_query($form, $dbh, $query);
1064
1065     foreach my $item (@{ $form->{parts} }) {
1066       push(@assemblies, $item);
1067       do_statement($form, $sth, $query, conv_i($item->{id}));
1068
1069       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1070         $ref->{assemblyitem} = 1;
1071         map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1072         push(@assemblies, $ref);
1073       }
1074       $sth->finish;
1075     }
1076
1077     # copy assemblies to $form->{parts}
1078     $form->{parts} = \@assemblies;
1079   }
1080
1081   if ($form->{l_pricegroups} ) {
1082     my $query = <<SQL;
1083        SELECT parts_id, price, pricegroup_id
1084        FROM prices
1085        WHERE parts_id = ?
1086 SQL
1087
1088     my $sth = prepare_query($form, $dbh, $query);
1089
1090     foreach my $part (@{ $form->{parts} }) {
1091       do_statement($form, $sth, $query, conv_i($part->{id}));
1092
1093       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1094         $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1095       }
1096       $sth->finish;
1097     }
1098   };
1099
1100
1101   $main::lxdebug->leave_sub();
1102
1103   return @{ $form->{parts} };
1104 }
1105
1106 sub _create_filter_for_priceupdate {
1107   $main::lxdebug->enter_sub();
1108
1109   my $self     = shift;
1110   my $myconfig = \%main::myconfig;
1111   my $form     = $main::form;
1112
1113   my @where_values;
1114   my $where = '1 = 1';
1115
1116   foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1117     my $column = $item;
1118     $column =~ s/.*\.//;
1119     next unless ($form->{$column});
1120
1121     $where .= qq| AND $item ILIKE ?|;
1122     push(@where_values, like($form->{$column}));
1123   }
1124
1125   foreach my $item (qw(description serialnumber)) {
1126     next unless ($form->{$item});
1127
1128     $where .= qq| AND (${item} ILIKE ?)|;
1129     push(@where_values, like($form->{$item}));
1130   }
1131
1132
1133   # items which were never bought, sold or on an order
1134   if ($form->{itemstatus} eq 'orphaned') {
1135     $where .=
1136       qq| AND (p.onhand = 0)
1137           AND p.id NOT IN
1138             (
1139               SELECT DISTINCT parts_id FROM invoice
1140               UNION
1141               SELECT DISTINCT parts_id FROM assembly
1142               UNION
1143               SELECT DISTINCT parts_id FROM orderitems
1144             )|;
1145
1146   } elsif ($form->{itemstatus} eq 'active') {
1147     $where .= qq| AND p.obsolete = '0'|;
1148
1149   } elsif ($form->{itemstatus} eq 'obsolete') {
1150     $where .= qq| AND p.obsolete = '1'|;
1151
1152   } elsif ($form->{itemstatus} eq 'onhand') {
1153     $where .= qq| AND p.onhand > 0|;
1154
1155   } elsif ($form->{itemstatus} eq 'short') {
1156     $where .= qq| AND p.onhand < p.rop|;
1157
1158   }
1159
1160   foreach my $column (qw(make model)) {
1161     next unless ($form->{$column});
1162     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1163     push(@where_values, like($form->{$column}));
1164   }
1165
1166   $main::lxdebug->leave_sub();
1167
1168   return ($where, @where_values);
1169 }
1170
1171 sub get_num_matches_for_priceupdate {
1172   $main::lxdebug->enter_sub();
1173
1174   my $self     = shift;
1175
1176   my $myconfig = \%main::myconfig;
1177   my $form     = $main::form;
1178
1179   my $dbh      = $form->get_standard_dbh($myconfig);
1180
1181   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1182
1183   my $num_updated = 0;
1184   my $query;
1185
1186   for my $column (qw(sellprice listprice)) {
1187     next if ($form->{$column} eq "");
1188
1189     $query =
1190       qq|SELECT COUNT(*)
1191          FROM parts
1192          WHERE id IN
1193            (SELECT p.id
1194             FROM parts p
1195             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1196             WHERE $where)|;
1197     my ($result)  = selectfirst_array_query($form, $dbh, $query, @where_values);
1198     $num_updated += $result if (0 <= $result);
1199   }
1200
1201   $query =
1202     qq|SELECT COUNT(*)
1203        FROM prices
1204        WHERE parts_id IN
1205          (SELECT p.id
1206           FROM parts p
1207           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1208           WHERE $where) AND (pricegroup_id = ?)|;
1209   my $sth = prepare_query($form, $dbh, $query);
1210
1211   for my $i (1 .. $form->{price_rows}) {
1212     next if ($form->{"price_$i"} eq "");
1213
1214     my ($result)  = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1215     $num_updated += $result if (0 <= $result);
1216   }
1217   $sth->finish();
1218
1219   $main::lxdebug->leave_sub();
1220
1221   return $num_updated;
1222 }
1223
1224 sub update_prices {
1225   my ($self, $myconfig, $form) = @_;
1226   $main::lxdebug->enter_sub();
1227
1228   my $num_updated = SL::DB->client->with_transaction(\&_update_prices, $self, $myconfig, $form);
1229
1230   $main::lxdebug->leave_sub();
1231   return $num_updated;
1232 }
1233
1234 sub _update_prices {
1235   my ($self, $myconfig, $form) = @_;
1236
1237   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1238   my $num_updated = 0;
1239
1240   # connect to database
1241   my $dbh = SL::DB->client->dbh;
1242
1243   for my $column (qw(sellprice listprice)) {
1244     next if ($form->{$column} eq "");
1245
1246     my $value = $form->parse_amount($myconfig, $form->{$column});
1247     my $operator = '+';
1248
1249     if ($form->{"${column}_type"} eq "percent") {
1250       $value = ($value / 100) + 1;
1251       $operator = '*';
1252     }
1253
1254     my $query =
1255       qq|UPDATE parts SET $column = $column $operator ?
1256          WHERE id IN
1257            (SELECT p.id
1258             FROM parts p
1259             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1260             WHERE $where)|;
1261     my $result    = do_query($form, $dbh, $query, $value, @where_values);
1262     $num_updated += $result if (0 <= $result);
1263   }
1264
1265   my $q_add =
1266     qq|UPDATE prices SET price = price + ?
1267        WHERE parts_id IN
1268          (SELECT p.id
1269           FROM parts p
1270           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1271           WHERE $where) AND (pricegroup_id = ?)|;
1272   my $sth_add = prepare_query($form, $dbh, $q_add);
1273
1274   my $q_multiply =
1275     qq|UPDATE prices SET price = price * ?
1276        WHERE parts_id IN
1277          (SELECT p.id
1278           FROM parts p
1279           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1280           WHERE $where) AND (pricegroup_id = ?)|;
1281   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1282
1283   for my $i (1 .. $form->{price_rows}) {
1284     next if ($form->{"price_$i"} eq "");
1285
1286     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1287     my $result;
1288
1289     if ($form->{"pricegroup_type_$i"} eq "percent") {
1290       $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1291     } else {
1292       $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1293     }
1294
1295     $num_updated += $result if (0 <= $result);
1296   }
1297
1298   $sth_add->finish();
1299   $sth_multiply->finish();
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;