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