5548d19dfa3d29eeab75fbe07059af292946db27
[kivitendo-erp.git] / SL / IC.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 # Inventory Control backend
32 #
33 #======================================================================
34
35 package IC;
36
37 use Data::Dumper;
38 use List::MoreUtils qw(all);
39 use YAML;
40
41 use SL::DBUtils;
42
43 sub get_part {
44   $main::lxdebug->enter_sub();
45
46   my ($self, $myconfig, $form) = @_;
47
48   # connect to db
49   my $dbh = $form->dbconnect($myconfig);
50
51   my $sth;
52
53   my $query =
54     qq|SELECT p.*,
55          c1.accno AS inventory_accno,
56          c2.accno AS income_accno,
57          c3.accno AS expense_accno,
58          pg.partsgroup
59        FROM parts p
60        LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
61        LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
62        LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
63        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
64        WHERE p.id = ? |;
65   my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
66
67   # copy to $form variables
68   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
69
70   $form->{onhand} *= 1;
71
72   my %oid = ('Pg'     => 'a.oid',
73              'Oracle' => 'a.rowid');
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 $oid{$myconfig->{dbdriver}}|;
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 ($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 $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       @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 (($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 $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     ($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          not_discountable = ?,
418          microfiche = ?,
419          partsgroup_id = ?,
420          price_factor_id = ?
421          $priceupdate
422        WHERE id = ?|;
423   @values = ($form->{partnumber},
424              $form->{description},
425              $makemodel ? 't' : 'f',
426              $form->{assembly} ? 't' : 'f',
427              $form->{listprice},
428              $form->{sellprice},
429              $form->{lastcost},
430              $form->{weight},
431              $form->{unit},
432              $form->{notes},
433              $form->{formel},
434              $form->{rop},
435              $form->{bin},
436              conv_i($form->{buchungsgruppen_id}),
437              conv_i($form->{payment_id}),
438              conv_i($form->{buchungsgruppen_id}),
439              $form->{obsolete} ? 't' : 'f',
440              $form->{image},
441              $form->{drawing},
442              $form->{shop} ? 't' : 'f',
443              conv_i($form->{ve}),
444              conv_i($form->{gv}),
445              $form->{ean},
446              $form->{not_discountable} ? 't' : 'f',
447              $form->{microfiche},
448              conv_i($partsgroup_id),
449              conv_i($form->{price_factor_id}),
450              conv_i($form->{id})
451   );
452   do_query($form, $dbh, $query, @values);
453
454   # delete translation records
455   do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
456
457   if ($form->{language_values} ne "") {
458     foreach $item (split(/---\+\+\+---/, $form->{language_values})) {
459       my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
460       if ($translation ne "") {
461         $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
462                     VALUES ( ?, ?, ?, ? )|;
463         @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
464         do_query($form, $dbh, $query, @values);
465       }
466     }
467   }
468
469   # delete price records
470   do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
471
472   # insert price records only if different to sellprice
473   for my $i (1 .. $form->{price_rows}) {
474     my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
475     if ($price == 0) {
476       $form->{"price_$i"} = $form->{sellprice};
477     }
478     if (
479         (   $price
480          || $form->{"klass_$i"}
481          || $form->{"pricegroup_id_$i"})
482         and $price != $form->{sellprice}
483       ) {
484       #$klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
485       $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) | .
486                qq|VALUES(?, ?, ?)|;
487       @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
488       do_query($form, $dbh, $query, @values);
489     }
490   }
491
492   # insert makemodel records
493   unless ($form->{item} eq 'service') {
494     for my $i (1 .. $form->{makemodel_rows}) {
495       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
496
497         $query = qq|INSERT INTO makemodel (parts_id, make, model) | .
498                              qq|VALUES (?, ?, ?)|;
499                     @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"});
500
501         do_query($form, $dbh, $query, @values);
502       }
503     }
504   }
505
506   # insert taxes
507   foreach $item (split(/ /, $form->{taxaccounts})) {
508     if ($form->{"IC_tax_$item"}) {
509       $query =
510         qq|INSERT INTO partstax (parts_id, chart_id)
511            VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
512                         @values = (conv_i($form->{id}), $item);
513       do_query($form, $dbh, $query, @values);
514     }
515   }
516
517   # add assembly records
518   if ($form->{item} eq 'assembly') {
519
520     for my $i (1 .. $form->{assembly_rows}) {
521       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
522
523       if ($form->{"qty_$i"} != 0) {
524         $form->{"bom_$i"} *= 1;
525         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
526                              qq|VALUES (?, ?, ?, ?)|;
527                     @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
528         do_query($form, $dbh, $query, @values);
529       }
530     }
531
532     @a = localtime;
533     $a[5] += 1900;
534     $a[4]++;
535     my $shippingdate = "$a[5]-$a[4]-$a[3]";
536
537     $form->get_employee($dbh);
538
539   }
540
541   #set expense_accno=inventory_accno if they are different => bilanz
542   $vendor_accno =
543     ($form->{expense_accno} != $form->{inventory_accno})
544     ? $form->{inventory_accno}
545     : $form->{expense_accno};
546
547   # get tax rates and description
548   $accno_id =
549     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
550   $query =
551     qq|SELECT c.accno, c.description, t.rate, t.taxnumber
552        FROM chart c, tax t
553        WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
554        ORDER BY c.accno|;
555   $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
556
557   $form->{taxaccount} = "";
558   while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
559     $form->{taxaccount} .= "$ptr->{accno} ";
560     if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
561       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
562       $form->{"$ptr->{accno}_description"} = $ptr->{description};
563       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
564       $form->{taxaccount2} .= " $ptr->{accno} ";
565     }
566   }
567
568   # commit
569   my $rc = $dbh->commit;
570   $dbh->disconnect;
571
572   $main::lxdebug->leave_sub();
573
574   return $rc;
575 }
576
577 sub update_assembly {
578   $main::lxdebug->enter_sub();
579
580   my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
581
582   my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
583   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
584
585   while (my ($pid, $aqty) = $sth->fetchrow_array) {
586     &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
587   }
588   $sth->finish;
589
590   $query =
591     qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
592        WHERE id = ?|;
593   @values = ($qty * ($form->{sellprice} - $sellprice),
594              $qty * ($form->{weight} - $weight), conv_i($id));
595   do_query($form, $dbh, $query, @values);
596
597   $main::lxdebug->leave_sub();
598 }
599
600 sub retrieve_assemblies {
601   $main::lxdebug->enter_sub();
602
603   my ($self, $myconfig, $form) = @_;
604
605   # connect to database
606   my $dbh = $form->dbconnect($myconfig);
607
608   my $where = qq|NOT p.obsolete|;
609   my @values;
610
611   if ($form->{partnumber}) {
612     $where .= qq| AND (p.partnumber ILIKE ?)|;
613     push(@values, '%' . $form->{partnumber} . '%');
614   }
615
616   if ($form->{description}) {
617     $where .= qq| AND (p.description ILIKE ?)|;
618     push(@values, '%' . $form->{description} . '%');
619   }
620
621   # retrieve assembly items
622   my $query =
623     qq|SELECT p.id, p.partnumber, p.description,
624          p.bin, p.onhand, p.rop,
625          (SELECT sum(p2.inventory_accno_id)
626           FROM parts p2, assembly a
627           WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
628        FROM parts p
629        WHERE NOT p.obsolete AND p.assembly $where|;
630
631   $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
632
633   $dbh->disconnect;
634
635   $main::lxdebug->leave_sub();
636 }
637
638 sub delete {
639   $main::lxdebug->enter_sub();
640
641   my ($self, $myconfig, $form) = @_;
642   my @values = (conv_i($form->{id}));
643   # connect to database, turn off AutoCommit
644   my $dbh = $form->dbconnect_noauto($myconfig);
645
646   my %columns = ( "assembly" => "id", "parts" => "id" );
647
648   for my $table (qw(prices partstax makemodel inventory assembly license translation parts)) {
649     my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
650     do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
651   }
652
653   # commit
654   my $rc = $dbh->commit;
655   $dbh->disconnect;
656
657   $main::lxdebug->leave_sub();
658
659   return $rc;
660 }
661
662 sub assembly_item {
663   $main::lxdebug->enter_sub();
664
665   my ($self, $myconfig, $form) = @_;
666
667   my $i = $form->{assembly_rows};
668   my $var;
669   my $where = qq|1 = 1|;
670   my @values;
671
672   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
673
674   while (my ($column, $table) = each(%columns)) {
675     next unless ($form->{"${column}_$i"});
676     $where .= qq| AND ${table}.${column} ILIKE ?|;
677     push(@values, '%' . $form->{"${column}_$i"} . '%');
678   }
679
680   if ($form->{id}) {
681     $where .= qq| AND NOT (p.id = ?)|;
682     push(@values, conv_i($form->{id}));
683   }
684
685   if ($partnumber) {
686     $where .= qq| ORDER BY p.partnumber|;
687   } else {
688     $where .= qq| ORDER BY p.description|;
689   }
690
691   # connect to database
692   my $dbh = $form->dbconnect($myconfig);
693
694   my $query =
695     qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
696        p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
697        p.price_factor_id, pfac.factor AS price_factor
698        FROM parts p
699        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
700        LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
701        WHERE $where|;
702   $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
703
704   $dbh->disconnect;
705
706   $main::lxdebug->leave_sub();
707 }
708
709 #
710 # Report for Wares.
711 # Warning, deep magic ahead.
712 # This function gets all parts from the database according to the filters specified
713 #
714 # specials:
715 #   sort revers  - sorting field + direction
716 #   top100
717 #
718 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
719 #   partnumber ean description partsgroup microfiche drawing
720 #
721 # column flags:
722 #   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
723 #
724 # exclusives:
725 #   itemstatus  = active | onhand | short | obsolete | orphaned
726 #   searchitems = part | assembly | service
727 #
728 # joining filters:
729 #   make model                               - makemodel
730 #   serialnumber transdatefrom transdateto   - invoice/orderitems
731 #
732 # binary flags:
733 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
734 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
735 #   l_soldtotal                              - aggreg join to display total of sold quantity
736 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
737 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
738 #   l_serialnumber                           - belonges to serialnumber filter
739 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
740 #   l_soldtotal                              - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
741 #
742 # not working:
743 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
744 #   masking of onhand in bsooqr mode         - ToDO: fixme
745 #
746 # disabled sanity checks and changes:
747 #  - searchitems = assembly will no longer disable bought
748 #  - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
749 #  - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
750 #  - itemstatus = obsolete will no longer disable onhand, short
751 #  - allow sorting by ean
752 #  - serialnumber filter also works if l_serialnumber isn't ticked
753 #  - onhand doesn't get masked by it's oi or invoice counterparts atm. ToDO: fix this
754 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
755 #
756 sub all_parts {
757   $main::lxdebug->enter_sub();
758
759   my ($self, $myconfig, $form) = @_;
760   my $dbh = $form->get_standard_dbh($myconfig);
761
762   $form->{parts}     = +{ };
763   $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
764
765   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
766   my @makemodel_filters    = qw(make model);
767   my @invoice_oi_filters   = qw(serialnumber soldtotal);
768   my @apoe_filters         = qw(transdate);
769   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
770   my @simple_l_switches    = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
771   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
772   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module);
773   my @deliverydate_flags   = qw(deliverydate);
774 #  my @other_flags          = qw(onhand); # ToDO: implement these
775 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
776
777   my %joins = (
778     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
779     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
780     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
781     invoice_oi =>
782       q|LEFT JOIN (
783          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem, 'invoice'    AS ioi FROM invoice UNION
784          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, 'orderitems' AS ioi FROM orderitems
785        ) AS ioi ON ioi.parts_id = p.id|,
786     apoe       =>
787       q|LEFT JOIN (
788          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
789          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
790          SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber,          quotation,         customer_id,         vendor_id, NULL AS deliverydate, 'orderitems' AS ioi FROM oe
791        ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
792     cv         =>
793       q|LEFT JOIN (
794            SELECT id, name, 'customer' AS cv FROM customer UNION
795            SELECT id, name, 'vendor'   AS cv FROM vendor
796          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
797   );
798   my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
799   my %joins_needed;
800
801   if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
802     @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
803   }
804
805   #===== switches and simple filters ========#
806
807   my @select_tokens = qw(id factor);
808   my @where_tokens  = qw(1=1);
809   my @group_tokens  = ();
810
811   # special case transdate
812   if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
813     $form->{"l_transdate"} = 1;
814     push @select_tokens, 'transdate';
815     for (qw(transdatefrom transdateto)) {
816       next unless $form->{$_};
817       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
818       push @bind_vars,    $form->{$_};
819     }
820   }
821
822   my %simple_filter_table_prefix = (
823      description  => 'p.',
824   );
825
826   foreach (@simple_filters, @makemodel_filters, @invoice_oi_filters) {
827     next unless $form->{$_};
828     $form->{"l_$_"} = '1'; # show the column
829     push @where_tokens, "$simple_filter_table_prefix{$_}$_ ILIKE ?";
830     push @bind_vars,    "%$form->{$_}%";
831   }
832
833   foreach (@simple_l_switches) {
834     next unless $form->{"l_$_"};
835     push @select_tokens, $_;
836   }
837
838   for ($form->{searchitems}) {
839     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
840     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
841     push @where_tokens, 'NOT p.assembly'               if /service/;
842     push @where_tokens, '    p.assembly'               if /assembly/;
843   }
844
845   for ($form->{itemstatus}) {
846     push @where_tokens, 'p.id NOT IN
847         (SELECT DISTINCT parts_id FROM invoice UNION
848          SELECT DISTINCT parts_id FROM assembly UNION
849          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
850     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
851     push @where_tokens, 'NOT p.obsolete'               if /active/;
852     push @where_tokens, '    p.obsolete',              if /obsolete/;
853     push @where_tokens, 'p.onhand > 0',                if /onhand/;
854     push @where_tokens, 'p.onhand < p.rop',            if /short/;
855   }
856
857   my $q_assembly_lastcost =
858     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
859         FROM assembly a_lc
860         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
861         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
862         WHERE (a_lc.id = p.id)) AS lastcost|;
863
864   my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
865   $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols;
866
867   my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
868
869   my $order_clause = " ORDER BY $form->{sort} " . ($form->{revers} ? 'DESC' : 'ASC');
870
871   # special case: sorting by partnumber
872   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
873   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
874   # ToDO: implement proper functional sorting
875   # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
876   # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018 
877   #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
878   #  if $form->{sort} eq 'partnumber';
879
880   #my $order_clause = " ORDER BY $form->{sort} $sort_order";
881
882   my $limit_clause = " LIMIT 100" if $form->{top100};
883
884   #=== joins and complicated filters ========#
885
886   my $bsooqr = $form->{bought}  || $form->{sold}
887             || $form->{ordered} || $form->{onorder}
888             || $form->{quoted}  || $form->{rfq};
889
890   my @bsooqr;
891   push @select_tokens, @qsooqr_flags                                          if $bsooqr;
892   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
893   push @select_tokens, $q_assembly_lastcost                                   if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
894   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
895   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
896   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
897   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
898   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
899   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
900   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
901
902   $joins_needed{partsgroup}  = 1;
903   $joins_needed{pfac}        = 1;
904   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
905   $joins_needed{cv}          = 1 if $bsooqr;
906   $joins_needed{apoe}        = 1 if $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
907   $joins_needed{invoice_oi}  = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
908
909   # special case for description search.
910   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
911   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
912   # find the old entries in of @where_tokens and @bind_vars, and adjust them
913   if ($joins_needed{invoice_oi}) {
914     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
915       next unless $where_tokens[$wi] =~ /^description ILIKE/;
916       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
917       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
918       last;
919     }
920   }
921
922   # now the master trick: soldtotal.
923   if ($form->{l_soldtotal}) {
924     push @where_tokens, 'ioi.qty >= 0';
925     push @group_tokens, @select_tokens;
926      map { s/.*\sAS\s+//si } @group_tokens;
927     push @select_tokens, 'SUM(ioi.qty)';
928   }
929
930   #============= build query ================#
931
932   %table_prefix = (
933      %table_prefix,
934      deliverydate => 'apoe.', serialnumber => 'ioi.',
935      transdate    => 'apoe.', trans_id     => 'ioi.',
936      module       => 'apoe.', name         => 'cv.',
937      ordnumber    => 'apoe.', make         => 'mm.',
938      quonumber    => 'apoe.', model        => 'mm.',
939      invnumber    => 'apoe.', partsgroup   => 'pg.',
940      lastcost     => ' ',
941      factor       => 'pfac.',
942      'SUM(ioi.qty)' => ' ',
943   );
944
945   $table_prefix{$q_assembly_lastcost} = ' ';
946
947   my %renamed_columns = (
948     'factor'       => 'price_factor',
949     'SUM(ioi.qty)' => 'soldtotal',
950   );
951
952   map { $table_prefix{$_} = 'ioi.' } qw(description serialnumber qty unit) if $joins_needed{invoice_oi};
953   map { $renamed_columns{$_} = ' AS ' . $renamed_columns{$_} } keys %renamed_columns;
954
955   my $select_clause = join ', ',    map { ($table_prefix{$_} || "p.") . $_ . $renamed_columns{$_} } @select_tokens;
956   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
957   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
958   my $group_clause  = ' GROUP BY ' . join ', ',    map { ($table_prefix{$_} || "p.") . $_ } @group_tokens if scalar @group_tokens;
959
960   my $query = qq|SELECT DISTINCT $select_clause FROM parts p $join_clause WHERE $where_clause $group_clause $order_clause $limit_clause|;
961
962   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
963
964   map { $_->{onhand} *= 1 } @{ $form->{parts} };
965
966   # post processing for assembly parts lists (bom)
967   # for each part get the assembly parts and add them into the partlist.
968   my @assemblies;
969   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
970     $query =
971       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
972            p.unit, p.bin,
973            p.sellprice, p.listprice, p.lastcost,
974            p.rop, p.weight, p.priceupdate,
975            p.image, p.drawing, p.microfiche,
976            pfac.factor
977          FROM parts p
978          INNER JOIN assembly a ON (p.id = a.parts_id)
979          $joins{pfac}
980          WHERE a.id = ?|;
981     $sth = prepare_query($form, $dbh, $query);
982
983     foreach $item (@{ $form->{parts} }) {
984       push(@assemblies, $item);
985       do_statement($form, $sth, $query, conv_i($item->{id}));
986
987       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
988         $ref->{assemblyitem} = 1;
989         map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
990         push(@assemblies, $ref);
991       }
992       $sth->finish;
993     }
994
995     # copy assemblies to $form->{parts}
996     $form->{parts} = \@assemblies;
997   }
998
999   $main::lxdebug->leave_sub();
1000 }
1001
1002 sub _create_filter_for_priceupdate {
1003   $main::lxdebug->enter_sub();
1004
1005   my $self     = shift;
1006   my $myconfig = \%main::myconfig;
1007   my $form     = $main::form;
1008
1009   my @where_values;
1010   my $where = '1 = 1';
1011
1012   foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1013     my $column = $item;
1014     $column =~ s/.*\.//;
1015     next unless ($form->{$column});
1016
1017     $where .= qq| AND $item ILIKE ?|;
1018     push(@where_values, '%' . $form->{$column} . '%');
1019   }
1020
1021   foreach my $item (qw(description serialnumber)) {
1022     next unless ($form->{$item});
1023
1024     $where .= qq| AND (${item} ILIKE ?)|;
1025     push(@where_values, '%' . $form->{$item} . '%');
1026   }
1027
1028
1029   # items which were never bought, sold or on an order
1030   if ($form->{itemstatus} eq 'orphaned') {
1031     $where .=
1032       qq| AND (p.onhand = 0)
1033           AND p.id NOT IN
1034             (
1035               SELECT DISTINCT parts_id FROM invoice
1036               UNION
1037               SELECT DISTINCT parts_id FROM assembly
1038               UNION
1039               SELECT DISTINCT parts_id FROM orderitems
1040             )|;
1041
1042   } elsif ($form->{itemstatus} eq 'active') {
1043     $where .= qq| AND p.obsolete = '0'|;
1044
1045   } elsif ($form->{itemstatus} eq 'obsolete') {
1046     $where .= qq| AND p.obsolete = '1'|;
1047
1048   } elsif ($form->{itemstatus} eq 'onhand') {
1049     $where .= qq| AND p.onhand > 0|;
1050
1051   } elsif ($form->{itemstatus} eq 'short') {
1052     $where .= qq| AND p.onhand < p.rop|;
1053
1054   }
1055
1056   foreach my $column (qw(make model)) {
1057     next unless ($form->{$colum});
1058     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1059     push(@where_values, '%' . $form->{$column} . '%');
1060   }
1061
1062   $main::lxdebug->leave_sub();
1063
1064   return ($where, @where_values);
1065 }
1066
1067 sub get_num_matches_for_priceupdate {
1068   $main::lxdebug->enter_sub();
1069
1070   my $self     = shift;
1071
1072   my $myconfig = \%main::myconfig;
1073   my $form     = $main::form;
1074
1075   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1076
1077   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1078
1079   my $num_updated = 0;
1080   my $query;
1081
1082   for my $column (qw(sellprice listprice)) {
1083     next if ($form->{$column} eq "");
1084
1085     $query =
1086       qq|SELECT COUNT(*)
1087          FROM parts
1088          WHERE id IN
1089            (SELECT p.id
1090             FROM parts p
1091             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1092             WHERE $where)|;
1093     my ($result)  = selectfirst_array_query($from, $dbh, $query, @where_values);
1094     $num_updated += $result if (0 <= $result);
1095   }
1096
1097   $query =
1098     qq|SELECT COUNT(*)
1099        FROM prices
1100        WHERE parts_id IN
1101          (SELECT p.id
1102           FROM parts p
1103           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1104           WHERE $where) AND (pricegroup_id = ?)|;
1105   my $sth = prepare_query($form, $dbh, $query);
1106
1107   for my $i (1 .. $form->{price_rows}) {
1108     next if ($form->{"price_$i"} eq "");
1109
1110     my ($result)  = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1111     $num_updated += $result if (0 <= $result);
1112   }
1113   $sth->finish();
1114
1115   $main::lxdebug->leave_sub();
1116
1117   return $num_updated;
1118 }
1119
1120 sub update_prices {
1121   $main::lxdebug->enter_sub();
1122
1123   my ($self, $myconfig, $form) = @_;
1124
1125   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1126   my $num_updated = 0;
1127
1128   # connect to database
1129   my $dbh = $form->dbconnect_noauto($myconfig);
1130
1131   for my $column (qw(sellprice listprice)) {
1132     next if ($form->{$column} eq "");
1133
1134     my $value = $form->parse_amount($myconfig, $form->{$column});
1135     my $operator = '+';
1136
1137     if ($form->{"${column}_type"} eq "percent") {
1138       $value = ($value / 100) + 1;
1139       $operator = '*';
1140     }
1141
1142     $query =
1143       qq|UPDATE parts SET $column = $column $operator ?
1144          WHERE id IN
1145            (SELECT p.id
1146             FROM parts p
1147             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1148             WHERE $where)|;
1149     my $result    = do_query($from, $dbh, $query, $value, @where_values);
1150     $num_updated += $result if (0 <= $result);
1151   }
1152
1153   my $q_add =
1154     qq|UPDATE prices SET price = price + ?
1155        WHERE parts_id IN
1156          (SELECT p.id
1157           FROM parts p
1158           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1159           WHERE $where) AND (pricegroup_id = ?)|;
1160   my $sth_add = prepare_query($form, $dbh, $q_add);
1161
1162   my $q_multiply =
1163     qq|UPDATE prices SET price = price * ?
1164        WHERE parts_id IN
1165          (SELECT p.id
1166           FROM parts p
1167           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1168           WHERE $where) AND (pricegroup_id = ?)|;
1169   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1170
1171   for my $i (1 .. $form->{price_rows}) {
1172     next if ($form->{"price_$i"} eq "");
1173
1174     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1175     my $result;
1176
1177     if ($form->{"pricegroup_type_$i"} eq "percent") {
1178       $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1179     } else {
1180       $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1181     }
1182
1183     $num_updated += $result if (0 <= $result);
1184   }
1185
1186   $sth_add->finish();
1187   $sth_multiply->finish();
1188
1189   my $rc= $dbh->commit;
1190   $dbh->disconnect;
1191
1192   $main::lxdebug->leave_sub();
1193
1194   return $num_updated;
1195 }
1196
1197 sub create_links {
1198   $main::lxdebug->enter_sub();
1199
1200   my ($self, $module, $myconfig, $form) = @_;
1201
1202   # connect to database
1203   my $dbh = $form->dbconnect($myconfig);
1204
1205   my @values = ('%' . $module . '%');
1206
1207   if ($form->{id}) {
1208     $query =
1209       qq|SELECT c.accno, c.description, c.link, c.id,
1210            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1211          FROM chart c, parts p
1212          WHERE (c.link LIKE ?) AND (p.id = ?)
1213          ORDER BY c.accno|;
1214     push(@values, conv_i($form->{id}));
1215
1216   } else {
1217     $query =
1218       qq|SELECT c.accno, c.description, c.link, c.id,
1219            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1220          FROM chart c, defaults d
1221          WHERE c.link LIKE ?
1222          ORDER BY c.accno|;
1223   }
1224
1225   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1226   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1227     foreach my $key (split(/:/, $ref->{link})) {
1228       if ($key =~ /\Q$module\E/) {
1229         if (   ($ref->{id} eq $ref->{inventory_accno_id})
1230             || ($ref->{id} eq $ref->{income_accno_id})
1231             || ($ref->{id} eq $ref->{expense_accno_id})) {
1232           push @{ $form->{"${module}_links"}{$key} },
1233             { accno       => $ref->{accno},
1234               description => $ref->{description},
1235               selected    => "selected" };
1236           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1237             } else {
1238           push @{ $form->{"${module}_links"}{$key} },
1239             { accno       => $ref->{accno},
1240               description => $ref->{description},
1241               selected    => "" };
1242         }
1243       }
1244     }
1245   }
1246   $sth->finish;
1247
1248   # get buchungsgruppen
1249   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1250
1251   # get payment terms
1252   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1253
1254   if (!$form->{id}) {
1255     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1256   }
1257
1258   $dbh->disconnect;
1259   $main::lxdebug->leave_sub();
1260 }
1261
1262 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1263 sub get_parts {
1264   $main::lxdebug->enter_sub();
1265
1266   my ($self, $myconfig, $form, $sortorder) = @_;
1267   my $dbh   = $form->dbconnect($myconfig);
1268   my $order = qq| p.partnumber|;
1269   my $where = qq|1 = 1|;
1270   my @values;
1271
1272   if ($sortorder eq "all") {
1273     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1274     push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1275
1276   } elsif ($sortorder eq "partnumber") {
1277     $where .= qq| AND (partnumber ILIKE ?)|;
1278     push(@values, '%' . $form->{partnumber} . '%');
1279
1280   } elsif ($sortorder eq "description") {
1281     $where .= qq| AND (description ILIKE ?)|;
1282     push(@values, '%' . $form->{description} . '%');
1283     $order = "description";
1284
1285   }
1286
1287   my $query =
1288     qq|SELECT id, partnumber, description, unit, sellprice
1289        FROM parts
1290        WHERE $where ORDER BY $order|;
1291
1292   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1293
1294   my $j = 0;
1295   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1296     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1297       next;
1298     }
1299
1300     $j++;
1301     $form->{"id_$j"}          = $ref->{id};
1302     $form->{"partnumber_$j"}  = $ref->{partnumber};
1303     $form->{"description_$j"} = $ref->{description};
1304     $form->{"unit_$j"}        = $ref->{unit};
1305     $form->{"sellprice_$j"}   = $ref->{sellprice};
1306     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
1307   }    #while
1308   $form->{rows} = $j;
1309   $sth->finish;
1310   $dbh->disconnect;
1311
1312   $main::lxdebug->leave_sub();
1313
1314   return $self;
1315 }    #end get_parts()
1316
1317 # gets sum of sold part with part_id
1318 sub get_soldtotal {
1319   $main::lxdebug->enter_sub();
1320
1321   my ($dbh, $id) = @_;
1322
1323   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1324   my ($sum) = selectrow_query($form, $dbh, $query, conv_i($id));
1325   $sum ||= 0;
1326
1327   $main::lxdebug->leave_sub();
1328
1329   return $sum;
1330 }    #end get_soldtotal
1331
1332 sub retrieve_languages {
1333   $main::lxdebug->enter_sub();
1334
1335   my ($self, $myconfig, $form) = @_;
1336
1337   # connect to database
1338   my $dbh = $form->dbconnect($myconfig);
1339
1340   my @values;
1341   my $where;
1342
1343   if ($form->{language_values} ne "") {
1344     $query =
1345       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1346          FROM language l
1347          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1348          ORDER BY lower(l.description)|;
1349     @values = (conv_i($form->{id}));
1350
1351   } else {
1352     $query = qq|SELECT id, description
1353                 FROM language
1354                 ORDER BY lower(description)|;
1355   }
1356
1357   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1358
1359   $dbh->disconnect;
1360
1361   $main::lxdebug->leave_sub();
1362
1363   return $languages;
1364 }
1365
1366 sub follow_account_chain {
1367   $main::lxdebug->enter_sub(2);
1368
1369   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1370
1371   my @visited_accno_ids = ($accno_id);
1372
1373   my ($query, $sth);
1374
1375   $query =
1376     qq|SELECT c.new_chart_id, date($transdate) >= c.valid_from AS is_valid, | .
1377     qq|  cnew.accno | .
1378     qq|FROM chart c | .
1379     qq|LEFT JOIN chart cnew ON c.new_chart_id = cnew.id | .
1380     qq|WHERE (c.id = ?) AND NOT c.new_chart_id ISNULL AND (c.new_chart_id > 0)|;
1381   $sth = prepare_query($form, $dbh, $query);
1382
1383   while (1) {
1384     do_statement($form, $sth, $query, $accno_id);
1385     $ref = $sth->fetchrow_hashref();
1386     last unless ($ref && $ref->{"is_valid"} &&
1387                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1388     $accno_id = $ref->{"new_chart_id"};
1389     $accno = $ref->{"accno"};
1390     push(@visited_accno_ids, $accno_id);
1391   }
1392
1393   $main::lxdebug->leave_sub(2);
1394
1395   return ($accno_id, $accno);
1396 }
1397
1398 sub retrieve_accounts {
1399   $main::lxdebug->enter_sub(2);
1400
1401   my ($self, $myconfig, $form, $parts_id, $index) = @_;
1402
1403   my ($query, $sth, $dbh);
1404
1405   $form->{"taxzone_id"} *= 1;
1406
1407   $dbh = $form->get_standard_dbh($myconfig);
1408
1409   my $transdate = "";
1410   if ($form->{type} eq "invoice") {
1411     if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1412       $transdate = $form->{invdate};
1413     } else {
1414       $transdate = $form->{deliverydate};
1415     }
1416   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1417     $transdate = $form->{invdate};
1418   } else {
1419     $transdate = $form->{transdate};
1420   }
1421
1422   if ($transdate eq "") {
1423     $transdate = "current_date";
1424   } else {
1425     $transdate = $dbh->quote($transdate);
1426   }
1427
1428   $query =
1429     qq|SELECT | .
1430     qq|  p.inventory_accno_id AS is_part, | .
1431     qq|  bg.inventory_accno_id, | .
1432     qq|  bg.income_accno_id_$form->{taxzone_id} AS income_accno_id, | .
1433     qq|  bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id, | .
1434     qq|  c1.accno AS inventory_accno, | .
1435     qq|  c2.accno AS income_accno, | .
1436     qq|  c3.accno AS expense_accno | .
1437     qq|FROM parts p | .
1438     qq|LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id | .
1439     qq|LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id | .
1440     qq|LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id | .
1441     qq|LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id | .
1442     qq|WHERE p.id = ?|;
1443   my $ref = selectfirst_hashref_query($form, $dbh, $query, $parts_id);
1444
1445   return $main::lxdebug->leave_sub(2) if (!$ref);
1446
1447   $ref->{"inventory_accno_id"} = undef unless ($ref->{"is_part"});
1448
1449   my %accounts;
1450   foreach my $type (qw(inventory income expense)) {
1451     next unless ($ref->{"${type}_accno_id"});
1452     ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1453       $self->follow_account_chain($form, $dbh, $transdate,
1454                                   $ref->{"${type}_accno_id"},
1455                                   $ref->{"${type}_accno"});
1456   }
1457
1458   map({ $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} }
1459       qw(inventory income expense));
1460
1461   my $inc_exp = $form->{"vc"} eq "customer" ? "income" : "expense";
1462   my $accno_id = $accounts{"${inc_exp}_accno_id"};
1463
1464   $query =
1465     qq|SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber | .
1466     qq|FROM tax t | .
1467     qq|LEFT JOIN chart c ON c.id = t.chart_id | .
1468     qq|WHERE t.id IN | .
1469     qq|  (SELECT tk.tax_id | .
1470     qq|   FROM taxkeys tk | .
1471     qq|   WHERE tk.chart_id = ? AND startdate <= | . quote_db_date($transdate) .
1472     qq|   ORDER BY startdate DESC LIMIT 1) |;
1473   $ref = selectfirst_hashref_query($form, $dbh, $query, $accno_id);
1474
1475   unless ($ref) {
1476     $main::lxdebug->leave_sub(2);
1477     return;
1478   }
1479
1480   $form->{"taxaccounts_$index"} = $ref->{"accno"};
1481   if ($form->{"taxaccounts"} !~ /$ref->{accno}/) {
1482     $form->{"taxaccounts"} .= "$ref->{accno} ";
1483   }
1484   map({ $form->{"$ref->{accno}_${_}"} = $ref->{$_}; }
1485       qw(rate description taxnumber));
1486
1487 #   $main::lxdebug->message(0, "formvars: rate " . $form->{"$ref->{accno}_rate"} .
1488 #                           " description " . $form->{"$ref->{accno}_description"} .
1489 #                           " taxnumber " . $form->{"$ref->{accno}_taxnumber"} .
1490 #                           " || taxaccounts_$index " . $form->{"taxaccounts_$index"} .
1491 #                           " || taxaccounts " . $form->{"taxaccounts"});
1492
1493   $main::lxdebug->leave_sub(2);
1494 }
1495
1496 sub get_basic_part_info {
1497   $main::lxdebug->enter_sub();
1498
1499   my $self     = shift;
1500   my %params   = @_;
1501
1502   Common::check_params(\%params, qw(id));
1503
1504   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1505
1506   if (!scalar @ids) {
1507     $main::lxdebug->leave_sub();
1508     return ();
1509   }
1510
1511   my $myconfig = \%main::myconfig;
1512   my $form     = $main::form;
1513
1514   my $dbh      = $form->get_standard_dbh($myconfig);
1515
1516   my $query    = qq|SELECT id, partnumber, description, unit FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1517
1518   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1519
1520   if ('' eq ref $params{id}) {
1521     $info = $info->[0] || { };
1522
1523     $main::lxdebug->leave_sub();
1524     return $info;
1525   }
1526
1527   my %info_map = map { $_->{id} => $_ } @{ $info };
1528
1529   $main::lxdebug->leave_sub();
1530
1531   return %info_map;
1532 }
1533
1534 sub prepare_parts_for_printing {
1535   $main::lxdebug->enter_sub();
1536
1537   my $self     = shift;
1538   my %params   = @_;
1539
1540   my $myconfig = \%main::myconfig;
1541   my $form     = $main::form;
1542
1543   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1544
1545   my $prefix   = $params{prefix} || 'id_';
1546   my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1547
1548   my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1549
1550   if (!@part_ids) {
1551     $main::lxdebug->leave_sub();
1552     return;
1553   }
1554
1555   my $placeholders = join ', ', ('?') x scalar(@part_ids);
1556   my $query        = qq|SELECT mm.parts_id, mm.model, v.name AS make
1557                         FROM makemodel mm
1558                         LEFT JOIN vendor v ON (mm.make = cast (v.id as text))
1559                         WHERE mm.parts_id IN ($placeholders)|;
1560
1561   my %makemodel    = ();
1562
1563   my $sth          = prepare_execute_query($form, $dbh, $query, @part_ids);
1564
1565   while (my $ref = $sth->fetchrow_hashref()) {
1566     $makemodel{$ref->{parts_id}} ||= [];
1567     push @{ $makemodel{$ref->{parts_id}} }, $ref;
1568   }
1569
1570   $sth->finish();
1571
1572   my @columns = qw(ean image microfiche drawing weight);
1573
1574   $query      = qq|SELECT id, | . join(', ', @columns) . qq|
1575                    FROM parts
1576                    WHERE id IN ($placeholders)|;
1577
1578   my %data    = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1579
1580   map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1581
1582   foreach my $i (1 .. $rowcount) {
1583     my $id = $form->{"${prefix}${i}"};
1584
1585     next if (!$id);
1586
1587     foreach (@columns) {
1588       push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1589     }
1590
1591     push @{ $form->{TEMPLATE_ARRAYS}{make} },  [];
1592     push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1593
1594     next if (!$makemodel{$id});
1595
1596     foreach my $ref (@{ $makemodel{$id} }) {
1597       map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1598     }
1599   }
1600
1601   $main::lxdebug->leave_sub();
1602 }
1603
1604
1605 1;