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