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