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