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