aaae3491fff2a6f96e32ba74b15dbea842403f27
[kivitendo-erp.git] / SL / IC.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 # Inventory Control backend
32 #
33 #======================================================================
34
35 package IC;
36
37 use Data::Dumper;
38 use List::MoreUtils qw(all);
39 use YAML;
40
41 use SL::CVar;
42 use SL::DBUtils;
43
44 sub get_part {
45   $main::lxdebug->enter_sub();
46
47   my ($self, $myconfig, $form) = @_;
48
49   # connect to db
50   my $dbh = $form->dbconnect($myconfig);
51
52   my $sth;
53
54   my $query =
55     qq|SELECT p.*,
56          c1.accno AS inventory_accno,
57          c2.accno AS income_accno,
58          c3.accno AS expense_accno,
59          pg.partsgroup
60        FROM parts p
61        LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
62        LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
63        LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
64        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
65        WHERE p.id = ? |;
66   my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
67
68   # copy to $form variables
69   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
70
71   $form->{onhand} *= 1;
72
73   # 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 #   masking of onhand in bsooqr mode         - ToDO: fixme
748 #   warehouse onhand
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 #  - onhand doesn't get masked by it's oi or invoice counterparts atm. ToDO: fix this
758 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
759 #
760 sub all_parts {
761   $main::lxdebug->enter_sub();
762
763   my ($self, $myconfig, $form) = @_;
764   my $dbh = $form->get_standard_dbh($myconfig);
765
766   $form->{parts}     = +{ };
767   $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
768
769   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
770   my @makemodel_filters    = qw(make model);
771   my @invoice_oi_filters   = qw(serialnumber soldtotal);
772   my @apoe_filters         = qw(transdate);
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 %joins = (
782     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
783     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
784     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
785     invoice_oi =>
786       q|LEFT JOIN (
787          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem, 'invoice'    AS ioi FROM invoice UNION
788          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, 'orderitems' AS ioi FROM orderitems
789        ) AS ioi ON ioi.parts_id = p.id|,
790     apoe       =>
791       q|LEFT JOIN (
792          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
793          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
794          SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber,          quotation,         customer_id,         vendor_id, NULL AS deliverydate, 'orderitems' AS ioi FROM oe
795        ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
796     cv         =>
797       q|LEFT JOIN (
798            SELECT id, name, 'customer' AS cv FROM customer UNION
799            SELECT id, name, 'vendor'   AS cv FROM vendor
800          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
801   );
802   my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
803
804   my %table_prefix = (
805      deliverydate => 'apoe.', serialnumber => 'ioi.',
806      transdate    => 'apoe.', trans_id     => 'ioi.',
807      module       => 'apoe.', name         => 'cv.',
808      ordnumber    => 'apoe.', make         => 'mm.',
809      quonumber    => 'apoe.', model        => 'mm.',
810      invnumber    => 'apoe.', partsgroup   => 'pg.',
811      lastcost     => ' ',
812      factor       => 'pfac.',
813      'SUM(ioi.qty)' => ' ',
814   );
815
816   my %renamed_columns = (
817     'factor'       => 'price_factor',
818     'SUM(ioi.qty)' => 'soldtotal',
819   );
820
821   my %joins_needed;
822
823   if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
824     @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
825   }
826
827   #===== switches and simple filters ========#
828
829   my @select_tokens = qw(id factor);
830   my @where_tokens  = qw(1=1);
831   my @group_tokens  = ();
832   my @bind_vars     = ();
833
834   # special case transdate
835   if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
836     $form->{"l_transdate"} = 1;
837     push @select_tokens, 'transdate';
838     for (qw(transdatefrom transdateto)) {
839       next unless $form->{$_};
840       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
841       push @bind_vars,    $form->{$_};
842     }
843   }
844
845   my %simple_filter_table_prefix = (
846      description  => 'p.',
847   );
848
849   foreach (@simple_filters, @makemodel_filters, @invoice_oi_filters) {
850     next unless $form->{$_};
851     $form->{"l_$_"} = '1'; # show the column
852     push @where_tokens, "$simple_filter_table_prefix{$_}$_ ILIKE ?";
853     push @bind_vars,    "%$form->{$_}%";
854   }
855
856   foreach (@simple_l_switches) {
857     next unless $form->{"l_$_"};
858     push @select_tokens, $_;
859   }
860
861   for ($form->{searchitems}) {
862     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
863     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
864     push @where_tokens, 'NOT p.assembly'               if /service/;
865     push @where_tokens, '    p.assembly'               if /assembly/;
866   }
867
868   for ($form->{itemstatus}) {
869     push @where_tokens, 'p.id NOT IN
870         (SELECT DISTINCT parts_id FROM invoice UNION
871          SELECT DISTINCT parts_id FROM assembly UNION
872          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
873     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
874     push @where_tokens, 'NOT p.obsolete'               if /active/;
875     push @where_tokens, '    p.obsolete',              if /obsolete/;
876     push @where_tokens, 'p.onhand > 0',                if /onhand/;
877     push @where_tokens, 'p.onhand < p.rop',            if /short/;
878   }
879
880   my $q_assembly_lastcost =
881     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
882         FROM assembly a_lc
883         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
884         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
885         WHERE (a_lc.id = p.id)) AS lastcost|;
886
887   my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
888   $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols;
889
890   my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
891
892   my $order_clause = " ORDER BY $form->{sort} " . ($form->{revers} ? 'DESC' : 'ASC');
893
894   # special case: sorting by partnumber
895   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
896   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
897   # ToDO: implement proper functional sorting
898   # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
899   # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
900   #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
901   #  if $form->{sort} eq 'partnumber';
902
903   #my $order_clause = " ORDER BY $form->{sort} $sort_order";
904
905   my $limit_clause = " LIMIT 100" if $form->{top100};
906
907   #=== joins and complicated filters ========#
908
909   my $bsooqr = $form->{bought}  || $form->{sold}
910             || $form->{ordered} || $form->{onorder}
911             || $form->{quoted}  || $form->{rfq};
912
913   my @bsooqr;
914   my @bsooqr_tokens = ();
915   push @select_tokens, @qsooqr_flags                                          if $bsooqr;
916   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
917   push @select_tokens, $q_assembly_lastcost                                   if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
918   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
919   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
920   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
921   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
922   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
923   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
924   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
925
926   $renamed_columns{onhand} = 'onhand_before_bsooqr';
927   $renamed_columns{qty}    = 'onhand';
928
929   $joins_needed{partsgroup}  = 1;
930   $joins_needed{pfac}        = 1;
931   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
932   $joins_needed{cv}          = 1 if $bsooqr;
933   $joins_needed{apoe}        = 1 if $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
934   $joins_needed{invoice_oi}  = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
935
936   # special case for description search.
937   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
938   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
939   # find the old entries in of @where_tokens and @bind_vars, and adjust them
940   if ($joins_needed{invoice_oi}) {
941     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
942       next unless $where_tokens[$wi] =~ /^description ILIKE/;
943       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
944       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
945       last;
946     }
947   }
948
949   # now the master trick: soldtotal.
950   if ($form->{l_soldtotal}) {
951     push @where_tokens, 'ioi.qty >= 0';
952     push @group_tokens, @select_tokens;
953      map { s/.*\sAS\s+//si } @group_tokens;
954     push @select_tokens, 'SUM(ioi.qty)';
955   }
956
957   #============= build query ================#
958
959   $table_prefix{$q_assembly_lastcost} = ' ';
960
961   map { $table_prefix{$_} = 'ioi.' } qw(description serialnumber qty unit) if $joins_needed{invoice_oi};
962   map { $renamed_columns{$_} = ' AS ' . $renamed_columns{$_} } keys %renamed_columns;
963
964   my $select_clause = join ', ',    map { ($table_prefix{$_} || "p.") . $_ . $renamed_columns{$_} } @select_tokens;
965   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
966   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
967   my $group_clause  = ' GROUP BY ' . join ', ',    map { ($table_prefix{$_} || "p.") . $_ } @group_tokens if scalar @group_tokens;
968
969   my ($cvar_where, @cvar_values) = CVar->build_filter_query('module'         => 'IC',
970                                                             'trans_id_field' => 'p.id',
971                                                             'filter'         => $form);
972
973   if ($cvar_where) {
974     $where_clause .= qq| AND ($cvar_where)|;
975     push @bind_vars, @cvar_values;
976   }
977
978   my $query = qq|SELECT DISTINCT $select_clause FROM parts p $join_clause WHERE $where_clause $group_clause $order_clause $limit_clause|;
979
980   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
981
982   map { $_->{onhand} *= 1 } @{ $form->{parts} };
983
984   # post processing for assembly parts lists (bom)
985   # for each part get the assembly parts and add them into the partlist.
986   my @assemblies;
987   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
988     $query =
989       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
990            p.unit, p.bin,
991            p.sellprice, p.listprice, p.lastcost,
992            p.rop, p.weight, p.priceupdate,
993            p.image, p.drawing, p.microfiche,
994            pfac.factor
995          FROM parts p
996          INNER JOIN assembly a ON (p.id = a.parts_id)
997          $joins{pfac}
998          WHERE a.id = ?|;
999     my $sth = prepare_query($form, $dbh, $query);
1000
1001     foreach my $item (@{ $form->{parts} }) {
1002       push(@assemblies, $item);
1003       do_statement($form, $sth, $query, conv_i($item->{id}));
1004
1005       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1006         $ref->{assemblyitem} = 1;
1007         map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1008         push(@assemblies, $ref);
1009       }
1010       $sth->finish;
1011     }
1012
1013     # copy assemblies to $form->{parts}
1014     $form->{parts} = \@assemblies;
1015   }
1016
1017   $main::lxdebug->leave_sub();
1018 }
1019
1020 sub _create_filter_for_priceupdate {
1021   $main::lxdebug->enter_sub();
1022
1023   my $self     = shift;
1024   my $myconfig = \%main::myconfig;
1025   my $form     = $main::form;
1026
1027   my @where_values;
1028   my $where = '1 = 1';
1029
1030   foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1031     my $column = $item;
1032     $column =~ s/.*\.//;
1033     next unless ($form->{$column});
1034
1035     $where .= qq| AND $item ILIKE ?|;
1036     push(@where_values, '%' . $form->{$column} . '%');
1037   }
1038
1039   foreach my $item (qw(description serialnumber)) {
1040     next unless ($form->{$item});
1041
1042     $where .= qq| AND (${item} ILIKE ?)|;
1043     push(@where_values, '%' . $form->{$item} . '%');
1044   }
1045
1046
1047   # items which were never bought, sold or on an order
1048   if ($form->{itemstatus} eq 'orphaned') {
1049     $where .=
1050       qq| AND (p.onhand = 0)
1051           AND p.id NOT IN
1052             (
1053               SELECT DISTINCT parts_id FROM invoice
1054               UNION
1055               SELECT DISTINCT parts_id FROM assembly
1056               UNION
1057               SELECT DISTINCT parts_id FROM orderitems
1058             )|;
1059
1060   } elsif ($form->{itemstatus} eq 'active') {
1061     $where .= qq| AND p.obsolete = '0'|;
1062
1063   } elsif ($form->{itemstatus} eq 'obsolete') {
1064     $where .= qq| AND p.obsolete = '1'|;
1065
1066   } elsif ($form->{itemstatus} eq 'onhand') {
1067     $where .= qq| AND p.onhand > 0|;
1068
1069   } elsif ($form->{itemstatus} eq 'short') {
1070     $where .= qq| AND p.onhand < p.rop|;
1071
1072   }
1073
1074   foreach my $column (qw(make model)) {
1075     next unless ($form->{$column});
1076     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1077     push(@where_values, '%' . $form->{$column} . '%');
1078   }
1079
1080   $main::lxdebug->leave_sub();
1081
1082   return ($where, @where_values);
1083 }
1084
1085 sub get_num_matches_for_priceupdate {
1086   $main::lxdebug->enter_sub();
1087
1088   my $self     = shift;
1089
1090   my $myconfig = \%main::myconfig;
1091   my $form     = $main::form;
1092
1093   my $dbh      = $form->get_standard_dbh($myconfig);
1094
1095   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1096
1097   my $num_updated = 0;
1098   my $query;
1099
1100   for my $column (qw(sellprice listprice)) {
1101     next if ($form->{$column} eq "");
1102
1103     $query =
1104       qq|SELECT COUNT(*)
1105          FROM parts
1106          WHERE id IN
1107            (SELECT p.id
1108             FROM parts p
1109             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1110             WHERE $where)|;
1111     my ($result)  = selectfirst_array_query($form, $dbh, $query, @where_values);
1112     $num_updated += $result if (0 <= $result);
1113   }
1114
1115   $query =
1116     qq|SELECT COUNT(*)
1117        FROM prices
1118        WHERE parts_id IN
1119          (SELECT p.id
1120           FROM parts p
1121           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1122           WHERE $where) AND (pricegroup_id = ?)|;
1123   my $sth = prepare_query($form, $dbh, $query);
1124
1125   for my $i (1 .. $form->{price_rows}) {
1126     next if ($form->{"price_$i"} eq "");
1127
1128     my ($result)  = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1129     $num_updated += $result if (0 <= $result);
1130   }
1131   $sth->finish();
1132
1133   $main::lxdebug->leave_sub();
1134
1135   return $num_updated;
1136 }
1137
1138 sub update_prices {
1139   $main::lxdebug->enter_sub();
1140
1141   my ($self, $myconfig, $form) = @_;
1142
1143   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1144   my $num_updated = 0;
1145
1146   # connect to database
1147   my $dbh = $form->dbconnect_noauto($myconfig);
1148
1149   for my $column (qw(sellprice listprice)) {
1150     next if ($form->{$column} eq "");
1151
1152     my $value = $form->parse_amount($myconfig, $form->{$column});
1153     my $operator = '+';
1154
1155     if ($form->{"${column}_type"} eq "percent") {
1156       $value = ($value / 100) + 1;
1157       $operator = '*';
1158     }
1159
1160     my $query =
1161       qq|UPDATE parts SET $column = $column $operator ?
1162          WHERE id IN
1163            (SELECT p.id
1164             FROM parts p
1165             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1166             WHERE $where)|;
1167     my $result    = do_query($form, $dbh, $query, $value, @where_values);
1168     $num_updated += $result if (0 <= $result);
1169   }
1170
1171   my $q_add =
1172     qq|UPDATE prices SET price = price + ?
1173        WHERE parts_id IN
1174          (SELECT p.id
1175           FROM parts p
1176           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1177           WHERE $where) AND (pricegroup_id = ?)|;
1178   my $sth_add = prepare_query($form, $dbh, $q_add);
1179
1180   my $q_multiply =
1181     qq|UPDATE prices SET price = price * ?
1182        WHERE parts_id IN
1183          (SELECT p.id
1184           FROM parts p
1185           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1186           WHERE $where) AND (pricegroup_id = ?)|;
1187   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1188
1189   for my $i (1 .. $form->{price_rows}) {
1190     next if ($form->{"price_$i"} eq "");
1191
1192     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1193     my $result;
1194
1195     if ($form->{"pricegroup_type_$i"} eq "percent") {
1196       $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1197     } else {
1198       $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1199     }
1200
1201     $num_updated += $result if (0 <= $result);
1202   }
1203
1204   $sth_add->finish();
1205   $sth_multiply->finish();
1206
1207   my $rc= $dbh->commit;
1208   $dbh->disconnect;
1209
1210   $main::lxdebug->leave_sub();
1211
1212   return $num_updated;
1213 }
1214
1215 sub create_links {
1216   $main::lxdebug->enter_sub();
1217
1218   my ($self, $module, $myconfig, $form) = @_;
1219
1220   # connect to database
1221   my $dbh = $form->dbconnect($myconfig);
1222
1223   my @values = ('%' . $module . '%');
1224   my $query;
1225
1226   if ($form->{id}) {
1227     $query =
1228       qq|SELECT c.accno, c.description, c.link, c.id,
1229            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1230          FROM chart c, parts p
1231          WHERE (c.link LIKE ?) AND (p.id = ?)
1232          ORDER BY c.accno|;
1233     push(@values, conv_i($form->{id}));
1234
1235   } else {
1236     $query =
1237       qq|SELECT c.accno, c.description, c.link, c.id,
1238            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1239          FROM chart c, defaults d
1240          WHERE c.link LIKE ?
1241          ORDER BY c.accno|;
1242   }
1243
1244   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1245   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1246     foreach my $key (split(/:/, $ref->{link})) {
1247       if ($key =~ /\Q$module\E/) {
1248         if (   ($ref->{id} eq $ref->{inventory_accno_id})
1249             || ($ref->{id} eq $ref->{income_accno_id})
1250             || ($ref->{id} eq $ref->{expense_accno_id})) {
1251           push @{ $form->{"${module}_links"}{$key} },
1252             { accno       => $ref->{accno},
1253               description => $ref->{description},
1254               selected    => "selected" };
1255           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1256             } else {
1257           push @{ $form->{"${module}_links"}{$key} },
1258             { accno       => $ref->{accno},
1259               description => $ref->{description},
1260               selected    => "" };
1261         }
1262       }
1263     }
1264   }
1265   $sth->finish;
1266
1267   # get buchungsgruppen
1268   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1269
1270   # get payment terms
1271   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1272
1273   if (!$form->{id}) {
1274     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1275   }
1276
1277   $dbh->disconnect;
1278   $main::lxdebug->leave_sub();
1279 }
1280
1281 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1282 sub get_parts {
1283   $main::lxdebug->enter_sub();
1284
1285   my ($self, $myconfig, $form, $sortorder) = @_;
1286   my $dbh   = $form->dbconnect($myconfig);
1287   my $order = qq| p.partnumber|;
1288   my $where = qq|1 = 1|;
1289   my @values;
1290
1291   if ($sortorder eq "all") {
1292     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1293     push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1294
1295   } elsif ($sortorder eq "partnumber") {
1296     $where .= qq| AND (partnumber ILIKE ?)|;
1297     push(@values, '%' . $form->{partnumber} . '%');
1298
1299   } elsif ($sortorder eq "description") {
1300     $where .= qq| AND (description ILIKE ?)|;
1301     push(@values, '%' . $form->{description} . '%');
1302     $order = "description";
1303
1304   }
1305
1306   my $query =
1307     qq|SELECT id, partnumber, description, unit, sellprice
1308        FROM parts
1309        WHERE $where ORDER BY $order|;
1310
1311   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1312
1313   my $j = 0;
1314   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1315     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1316       next;
1317     }
1318
1319     $j++;
1320     $form->{"id_$j"}          = $ref->{id};
1321     $form->{"partnumber_$j"}  = $ref->{partnumber};
1322     $form->{"description_$j"} = $ref->{description};
1323     $form->{"unit_$j"}        = $ref->{unit};
1324     $form->{"sellprice_$j"}   = $ref->{sellprice};
1325     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
1326   }    #while
1327   $form->{rows} = $j;
1328   $sth->finish;
1329   $dbh->disconnect;
1330
1331   $main::lxdebug->leave_sub();
1332
1333   return $self;
1334 }    #end get_parts()
1335
1336 # gets sum of sold part with part_id
1337 sub get_soldtotal {
1338   $main::lxdebug->enter_sub();
1339
1340   my ($dbh, $id) = @_;
1341
1342   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1343   my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1344   $sum ||= 0;
1345
1346   $main::lxdebug->leave_sub();
1347
1348   return $sum;
1349 }    #end get_soldtotal
1350
1351 sub retrieve_languages {
1352   $main::lxdebug->enter_sub();
1353
1354   my ($self, $myconfig, $form) = @_;
1355
1356   # connect to database
1357   my $dbh = $form->dbconnect($myconfig);
1358
1359   my @values;
1360   my $where;
1361   my $query;
1362
1363   if ($form->{language_values} ne "") {
1364     $query =
1365       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1366          FROM language l
1367          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1368          ORDER BY lower(l.description)|;
1369     @values = (conv_i($form->{id}));
1370
1371   } else {
1372     $query = qq|SELECT id, description
1373                 FROM language
1374                 ORDER BY lower(description)|;
1375   }
1376
1377   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1378
1379   $dbh->disconnect;
1380
1381   $main::lxdebug->leave_sub();
1382
1383   return $languages;
1384 }
1385
1386 sub follow_account_chain {
1387   $main::lxdebug->enter_sub(2);
1388
1389   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1390
1391   my @visited_accno_ids = ($accno_id);
1392
1393   my ($query, $sth);
1394
1395   $query =
1396     qq|SELECT c.new_chart_id, date($transdate) >= c.valid_from AS is_valid, | .
1397     qq|  cnew.accno | .
1398     qq|FROM chart c | .
1399     qq|LEFT JOIN chart cnew ON c.new_chart_id = cnew.id | .
1400     qq|WHERE (c.id = ?) AND NOT c.new_chart_id ISNULL AND (c.new_chart_id > 0)|;
1401   $sth = prepare_query($form, $dbh, $query);
1402
1403   while (1) {
1404     do_statement($form, $sth, $query, $accno_id);
1405     my $ref = $sth->fetchrow_hashref();
1406     last unless ($ref && $ref->{"is_valid"} &&
1407                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1408     $accno_id = $ref->{"new_chart_id"};
1409     $accno = $ref->{"accno"};
1410     push(@visited_accno_ids, $accno_id);
1411   }
1412
1413   $main::lxdebug->leave_sub(2);
1414
1415   return ($accno_id, $accno);
1416 }
1417
1418 sub retrieve_accounts {
1419   $main::lxdebug->enter_sub(2);
1420
1421   my ($self, $myconfig, $form, $parts_id, $index) = @_;
1422
1423   my ($query, $sth, $dbh);
1424
1425   $form->{"taxzone_id"} *= 1;
1426
1427   $dbh = $form->get_standard_dbh($myconfig);
1428
1429   my $transdate = "";
1430   if ($form->{type} eq "invoice") {
1431     if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1432       $transdate = $form->{invdate};
1433     } else {
1434       $transdate = $form->{deliverydate};
1435     }
1436   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1437     $transdate = $form->{invdate};
1438   } else {
1439     $transdate = $form->{transdate};
1440   }
1441
1442   if ($transdate eq "") {
1443     $transdate = "current_date";
1444   } else {
1445     $transdate = $dbh->quote($transdate);
1446   }
1447
1448   $query =
1449     qq|SELECT | .
1450     qq|  p.inventory_accno_id AS is_part, | .
1451     qq|  bg.inventory_accno_id, | .
1452     qq|  bg.income_accno_id_$form->{taxzone_id} AS income_accno_id, | .
1453     qq|  bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id, | .
1454     qq|  c1.accno AS inventory_accno, | .
1455     qq|  c2.accno AS income_accno, | .
1456     qq|  c3.accno AS expense_accno | .
1457     qq|FROM parts p | .
1458     qq|LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id | .
1459     qq|LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id | .
1460     qq|LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id | .
1461     qq|LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id | .
1462     qq|WHERE p.id = ?|;
1463   my $ref = selectfirst_hashref_query($form, $dbh, $query, $parts_id);
1464
1465   return $main::lxdebug->leave_sub(2) if (!$ref);
1466
1467   $ref->{"inventory_accno_id"} = undef unless ($ref->{"is_part"});
1468
1469   my %accounts;
1470   foreach my $type (qw(inventory income expense)) {
1471     next unless ($ref->{"${type}_accno_id"});
1472     ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1473       $self->follow_account_chain($form, $dbh, $transdate,
1474                                   $ref->{"${type}_accno_id"},
1475                                   $ref->{"${type}_accno"});
1476   }
1477
1478   map({ $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} }
1479       qw(inventory income expense));
1480
1481   my $inc_exp = $form->{"vc"} eq "customer" ? "income" : "expense";
1482   my $accno_id = $accounts{"${inc_exp}_accno_id"};
1483
1484   $query =
1485     qq|SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber | .
1486     qq|FROM tax t | .
1487     qq|LEFT JOIN chart c ON c.id = t.chart_id | .
1488     qq|WHERE t.id IN | .
1489     qq|  (SELECT tk.tax_id | .
1490     qq|   FROM taxkeys tk | .
1491     qq|   WHERE tk.chart_id = ? AND startdate <= | . quote_db_date($transdate) .
1492     qq|   ORDER BY startdate DESC LIMIT 1) |;
1493   $ref = selectfirst_hashref_query($form, $dbh, $query, $accno_id);
1494
1495   unless ($ref) {
1496     $main::lxdebug->leave_sub(2);
1497     return;
1498   }
1499
1500   $form->{"taxaccounts_$index"} = $ref->{"accno"};
1501   if ($form->{"taxaccounts"} !~ /$ref->{accno}/) {
1502     $form->{"taxaccounts"} .= "$ref->{accno} ";
1503   }
1504   map({ $form->{"$ref->{accno}_${_}"} = $ref->{$_}; }
1505       qw(rate description taxnumber));
1506
1507 #   $main::lxdebug->message(0, "formvars: rate " . $form->{"$ref->{accno}_rate"} .
1508 #                           " description " . $form->{"$ref->{accno}_description"} .
1509 #                           " taxnumber " . $form->{"$ref->{accno}_taxnumber"} .
1510 #                           " || taxaccounts_$index " . $form->{"taxaccounts_$index"} .
1511 #                           " || taxaccounts " . $form->{"taxaccounts"});
1512
1513   $main::lxdebug->leave_sub(2);
1514 }
1515
1516 sub get_basic_part_info {
1517   $main::lxdebug->enter_sub();
1518
1519   my $self     = shift;
1520   my %params   = @_;
1521
1522   Common::check_params(\%params, qw(id));
1523
1524   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1525
1526   if (!scalar @ids) {
1527     $main::lxdebug->leave_sub();
1528     return ();
1529   }
1530
1531   my $myconfig = \%main::myconfig;
1532   my $form     = $main::form;
1533
1534   my $dbh      = $form->get_standard_dbh($myconfig);
1535
1536   my $query    = qq|SELECT id, partnumber, description, unit FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1537
1538   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1539
1540   if ('' eq ref $params{id}) {
1541     $info = $info->[0] || { };
1542
1543     $main::lxdebug->leave_sub();
1544     return $info;
1545   }
1546
1547   my %info_map = map { $_->{id} => $_ } @{ $info };
1548
1549   $main::lxdebug->leave_sub();
1550
1551   return %info_map;
1552 }
1553
1554 sub prepare_parts_for_printing {
1555   $main::lxdebug->enter_sub();
1556
1557   my $self     = shift;
1558   my %params   = @_;
1559
1560   my $myconfig = \%main::myconfig;
1561   my $form     = $main::form;
1562
1563   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1564
1565   my $prefix   = $params{prefix} || 'id_';
1566   my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1567
1568   my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1569
1570   if (!@part_ids) {
1571     $main::lxdebug->leave_sub();
1572     return;
1573   }
1574
1575   my $placeholders = join ', ', ('?') x scalar(@part_ids);
1576   my $query        = qq|SELECT mm.parts_id, mm.model, v.name AS make
1577                         FROM makemodel mm
1578                         LEFT JOIN vendor v ON (mm.make = cast (v.id as text))
1579                         WHERE mm.parts_id IN ($placeholders)|;
1580
1581   my %makemodel    = ();
1582
1583   my $sth          = prepare_execute_query($form, $dbh, $query, @part_ids);
1584
1585   while (my $ref = $sth->fetchrow_hashref()) {
1586     $makemodel{$ref->{parts_id}} ||= [];
1587     push @{ $makemodel{$ref->{parts_id}} }, $ref;
1588   }
1589
1590   $sth->finish();
1591
1592   my @columns = qw(ean image microfiche drawing weight);
1593
1594   $query      = qq|SELECT id, | . join(', ', @columns) . qq|
1595                    FROM parts
1596                    WHERE id IN ($placeholders)|;
1597
1598   my %data    = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1599
1600   map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1601
1602   foreach my $i (1 .. $rowcount) {
1603     my $id = $form->{"${prefix}${i}"};
1604
1605     next if (!$id);
1606
1607     foreach (@columns) {
1608       push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1609     }
1610
1611     push @{ $form->{TEMPLATE_ARRAYS}{make} },  [];
1612     push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1613
1614     next if (!$makemodel{$id});
1615
1616     foreach my $ref (@{ $makemodel{$id} }) {
1617       map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1618     }
1619   }
1620
1621   $main::lxdebug->leave_sub();
1622 }
1623
1624
1625 1;