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