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