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