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