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