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