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