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