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