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