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