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