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