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