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