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