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