2cf7996fb14260f7f709e3f8d10c99f1f3a1aad6
[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 use Carp;
48
49 use strict;
50
51 sub get_part {
52   $main::lxdebug->enter_sub();
53
54   my ($self, $myconfig, $form) = @_;
55
56   # connect to db
57   my $dbh = $form->get_standard_dbh;
58
59   my $sth;
60
61   my $query =
62     qq|SELECT p.*,
63          c1.accno AS inventory_accno,
64          c2.accno AS income_accno,
65          c3.accno AS expense_accno,
66          pg.partsgroup
67        FROM parts p
68        LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
69        LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
70        LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
71        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
72        WHERE p.id = ? |;
73   my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
74
75   # copy to $form variables
76   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
77
78   $form->{mtime} = $form->{itime} if !$form->{mtime};
79   $form->{lastmtime} = $form->{mtime};
80   $form->{onhand} *= 1;
81
82   # part or service item
83   if ($form->{part_type} eq '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   my ($self, $myconfig, $form) = @_;
228   $main::lxdebug->enter_sub();
229
230   my $rc = SL::DB->client->with_transaction(\&_save, $self, $myconfig, $form);
231
232   $main::lxdebug->leave_sub();
233   return $rc;
234 }
235
236 sub _save {
237   my ($self, $myconfig, $form) = @_;
238   my @values;
239
240   my $dbh = SL::DB->client->dbh;
241   my $restricter = SL::HTML::Restrict->create;
242
243   # save the part
244   # make up a unique handle and store in partnumber field
245   # then retrieve the record based on the unique handle to get the id
246   # replace the partnumber field with the actual variable
247   # add records for makemodel
248
249   # if there is a $form->{id} then replace the old entry
250   # delete all makemodel entries and add the new ones
251
252   # undo amount formatting
253   map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
254     qw(rop weight listprice sellprice gv lastcost);
255
256   my $makemodel = ($form->{make_1} || $form->{model_1} || ($form->{makemodel_rows} > 1)) ? 1 : 0;
257
258
259   my ($query, $sth);
260
261   my $priceupdate = ', priceupdate = current_date';
262
263   if ($form->{id}) {
264     my $trans_number = SL::TransNumber->new(type => $form->{part_type}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
265     if (!$trans_number->is_unique) {
266       $::lxdebug->leave_sub;
267       return 3;
268     }
269
270     # get old price
271     $query = qq|SELECT sellprice FROM parts WHERE id = ?|;
272     my ($sellprice) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
273
274     # delete makemodel records
275     do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
276
277     if ($form->{part_type} eq 'assembly') {
278       # delete assembly records
279       do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
280     }
281
282     # delete translations
283     do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
284
285     # Check whether or not the prices have changed. If they haven't
286     # then 'priceupdate' should not be updated.
287     my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
288     $priceupdate        = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
289
290   } else {
291     my $trans_number = SL::TransNumber->new(type => $form->{part_type}, dbh => $dbh, number => $form->{partnumber}, save => 1);
292
293     if ($form->{partnumber} && !$trans_number->is_unique) {
294       $::lxdebug->leave_sub;
295       return 3;
296     }
297
298     $form->{partnumber} ||= $trans_number->create_unique;
299
300     ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
301     do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit, part_type) VALUES (?, ?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit}, $form->{part_type});
302
303     $form->{orphaned} = 1;
304   }
305   my $partsgroup_id = undef;
306
307   if ($form->{partsgroup}) {
308     (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
309   }
310
311   my ($subq_inventory, $subq_expense, $subq_income);
312   if ($form->{part_type} eq "part") {
313     $subq_inventory =
314       qq|(SELECT bg.inventory_accno_id
315           FROM buchungsgruppen bg
316           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
317   } else {
318     $subq_inventory = "NULL";
319   }
320
321   if ($form->{part_type} ne "assembly") {
322     $subq_expense =
323       qq|(SELECT tc.expense_accno_id
324           FROM taxzone_charts tc
325           WHERE tc.buchungsgruppen_id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq| and tc.taxzone_id = 0)|;
326   } else {
327     $subq_expense = "NULL";
328   }
329
330   normalize_text_blocks();
331
332   $query =
333     qq|UPDATE parts SET
334          partnumber = ?,
335          description = ?,
336          makemodel = ?,
337          listprice = ?,
338          sellprice = ?,
339          lastcost = ?,
340          weight = ?,
341          unit = ?,
342          notes = ?,
343          formel = ?,
344          rop = ?,
345          warehouse_id = ?,
346          bin_id = ?,
347          buchungsgruppen_id = ?,
348          payment_id = ?,
349          inventory_accno_id = $subq_inventory,
350          income_accno_id = (SELECT tc.income_accno_id FROM taxzone_charts tc WHERE tc.taxzone_id = 0 and tc.buchungsgruppen_id = ?),
351          expense_accno_id = $subq_expense,
352          obsolete = ?,
353          image = ?,
354          drawing = ?,
355          shop = ?,
356          ve = ?,
357          gv = ?,
358          ean = ?,
359          has_sernumber = ?,
360          not_discountable = ?,
361          microfiche = ?,
362          part_type = ?,
363          partsgroup_id = ?,
364          price_factor_id = ?
365          $priceupdate
366        WHERE id = ?|;
367   @values = ($form->{partnumber},
368              $form->{description},
369              $makemodel ? 't' : 'f',
370              $form->{listprice},
371              $form->{sellprice},
372              $form->{lastcost},
373              $form->{weight},
374              $form->{unit},
375              $restricter->process($form->{notes}),
376              $form->{formel},
377              $form->{rop},
378              conv_i($form->{warehouse_id}),
379              conv_i($form->{bin_id}),
380              conv_i($form->{buchungsgruppen_id}),
381              conv_i($form->{payment_id}),
382              conv_i($form->{buchungsgruppen_id}),
383              $form->{obsolete} ? 't' : 'f',
384              $form->{image},
385              $form->{drawing},
386              $form->{shop} ? 't' : 'f',
387              conv_i($form->{ve}),
388              conv_i($form->{gv}),
389              $form->{ean},
390              $form->{has_sernumber} ? 't' : 'f',
391              $form->{not_discountable} ? 't' : 'f',
392              $form->{microfiche},
393              $form->{part_type},
394              conv_i($partsgroup_id),
395              conv_i($form->{price_factor_id}),
396              conv_i($form->{id})
397   );
398   do_query($form, $dbh, $query, @values);
399
400   $form->new_lastmtime('parts');
401
402   # delete translation records
403   do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
404
405   my @translations = grep { $_->{language_id} && $_->{translation} } @{ $form->{translations} || [] };
406   if (@translations) {
407     $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
408                 VALUES ( ?, ?, ?, ? )|;
409     $sth   = $dbh->prepare($query);
410
411     foreach my $translation (@translations) {
412       do_statement($form, $sth, $query, conv_i($form->{id}), conv_i($translation->{language_id}), $translation->{translation}, $restricter->process($translation->{longdescription}));
413     }
414
415     $sth->finish();
416   }
417
418   # delete price records
419   do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
420
421   $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
422   $sth   = prepare_query($form, $dbh, $query);
423
424   for my $i (1 .. $form->{price_rows}) {
425     my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
426     next unless $price;
427
428     @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
429     do_statement($form, $sth, $query, @values);
430   }
431
432   $sth->finish;
433
434   # insert makemodel records
435     my $lastupdate = '';
436     my $value = 0;
437     for my $i (1 .. $form->{makemodel_rows}) {
438       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
439         #hli
440         $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
441         if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
442         {
443             if ($form->{"lastupdate_$i"} eq "") {
444                 $lastupdate = 'now()';
445             } else {
446                 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
447             }
448         } else {
449             $lastupdate = 'now()';
450         }
451         $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
452                  qq|VALUES (?, ?, ?, ?, ?, ?)|;
453         @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
454
455         do_query($form, $dbh, $query, @values);
456       }
457     }
458
459   # add assembly records
460   if ($form->{part_type} eq 'assembly') {
461     # check additional assembly row
462     my $i = $form->{assembly_rows};
463     # if last row is not empty add them
464     if ($form->{"partnumber_$i"} ne "") {
465       $query = qq|SELECT id FROM parts WHERE partnumber = ?|;
466       my ($partid) = selectrow_query($form, $dbh, $query,$form->{"partnumber_$i"} );
467       if ( $partid ) {
468         $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
469         $form->{"id_$i"} = $partid;
470         $form->{"bom_$i"} = 0;
471         $form->{assembly_rows}++;
472       }
473       else {
474         $::form->error($::locale->text("uncorrect partnumber ").$form->{"partnumber_$i"});
475       }
476     }
477
478     for my $i (1 .. $form->{assembly_rows}) {
479       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
480
481       if ($form->{"qty_$i"} != 0) {
482         $form->{"bom_$i"} *= 1;
483         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
484                  qq|VALUES (?, ?, ?, ?)|;
485         @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
486         do_query($form, $dbh, $query, @values);
487       }
488     }
489     my @a = localtime;
490     $a[5] += 1900;
491     $a[4]++;
492     my $shippingdate = "$a[5]-$a[4]-$a[3]";
493
494     $form->get_employee($dbh);
495
496   }
497
498   #set expense_accno=inventory_accno if they are different => bilanz
499   my $vendor_accno =
500     ($form->{expense_accno} != $form->{inventory_accno})
501     ? $form->{inventory_accno}
502     : $form->{expense_accno};
503
504   # get tax rates and description
505   my $accno_id =
506     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
507   $query =
508     qq|SELECT c.accno, c.description, t.rate, t.taxnumber
509        FROM chart c, tax t
510        WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
511        ORDER BY c.accno|;
512   my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
513
514   $form->{taxaccount} = "";
515   while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
516     $form->{taxaccount} .= "$ptr->{accno} ";
517     if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
518       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
519       $form->{"$ptr->{accno}_description"} = $ptr->{description};
520       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
521       $form->{taxaccount2} .= " $ptr->{accno} ";
522     }
523   }
524
525   CVar->save_custom_variables(dbh           => $dbh,
526                               module        => 'IC',
527                               trans_id      => $form->{id},
528                               variables     => $form,
529                               save_validity => 1);
530
531   # Delete saved custom variable values for configs that have been
532   # marked invalid for this part.
533   $query = <<SQL;
534     DELETE FROM custom_variables
535     WHERE (config_id IN (
536         SELECT val.config_id
537         FROM custom_variables_validity val
538         LEFT JOIN custom_variable_configs val_cfg ON (val.config_id = val_cfg.id)
539         WHERE (val_cfg.module = 'IC')
540           AND (val.trans_id   = ?)))
541       AND (trans_id = ?)
542 SQL
543   do_query($form, $dbh, $query, ($form->{id}) x 2);
544
545   return 1;
546 }
547
548 sub retrieve_assemblies {
549   $main::lxdebug->enter_sub();
550
551   my ($self, $myconfig, $form) = @_;
552
553   # connect to database
554   my $dbh = $form->get_standard_dbh;
555
556   my $where = qq|NOT p.obsolete|;
557   my @values;
558
559   if ($form->{partnumber}) {
560     $where .= qq| AND (p.partnumber ILIKE ?)|;
561     push(@values, like($form->{partnumber}));
562   }
563
564   if ($form->{description}) {
565     $where .= qq| AND (p.description ILIKE ?)|;
566     push(@values, like($form->{description}));
567   }
568
569   # retrieve assembly items
570   my $query =
571     qq|SELECT p.id, p.partnumber, p.description,
572               p.onhand, p.rop,
573          (SELECT sum(p2.inventory_accno_id)
574           FROM parts p2, assembly a
575           WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
576        FROM parts p
577        WHERE NOT p.obsolete AND p.part_type = 'assembly' $where|;
578
579   $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
580
581   $main::lxdebug->leave_sub();
582 }
583
584 sub delete {
585   my ($self, $myconfig, $form) = @_;
586   $main::lxdebug->enter_sub();
587
588   my $rc = SL::DB->client->with_transaction(\&_delete, $self, $myconfig, $form);
589
590   $main::lxdebug->leave_sub();
591   return $rc;
592 }
593
594 sub _delete {
595   my ($self, $myconfig, $form) = @_;
596   my @values = (conv_i($form->{id}));
597
598   my %columns = ( "assembly" => "id", "parts" => "id" );
599
600   for my $table (qw(prices makemodel inventory assembly translation parts)) {
601     my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
602     do_query($form, SL::DB->client->dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
603   }
604
605   return 1;
606 }
607
608 sub assembly_item {
609   $main::lxdebug->enter_sub();
610
611   my ($self, $myconfig, $form) = @_;
612
613   my $i = $form->{assembly_rows};
614   my $var;
615   my $where = qq|1 = 1|;
616   my @values;
617
618   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
619
620   while (my ($column, $table) = each(%columns)) {
621     next unless ($form->{"${column}_$i"});
622     $where .= qq| AND ${table}.${column} ILIKE ?|;
623     push(@values, like($form->{"${column}_$i"}));
624   }
625
626   if ($form->{id}) {
627     $where .= qq| AND NOT (p.id = ?)|;
628     push(@values, conv_i($form->{id}));
629   }
630
631   # Search for part ID overrides all other criteria.
632   if ($form->{"id_${i}"}) {
633     $where  = qq|p.id = ?|;
634     @values = ($form->{"id_${i}"});
635   }
636
637   if ($form->{partnumber}) {
638     $where .= qq| ORDER BY p.partnumber|;
639   } else {
640     $where .= qq| ORDER BY p.description|;
641   }
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, SL::DB->client->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.part_type = 'part'"     if /part/;
895     push @where_tokens, "p.part_type = 'service'"  if /service/;
896     push @where_tokens, "p.part_type = 'assembly'" if /assembly/;
897   }
898
899   for ($form->{itemstatus}) {
900     push @where_tokens, 'p.id NOT IN
901         (SELECT DISTINCT parts_id FROM invoice UNION
902          SELECT DISTINCT parts_id FROM assembly UNION
903          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
904     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
905     push @where_tokens, 'NOT p.obsolete'               if /active/;
906     push @where_tokens, '    p.obsolete',              if /obsolete/;
907     push @where_tokens, 'p.onhand > 0',                if /onhand/;
908     push @where_tokens, 'p.onhand < p.rop',            if /short/;
909   }
910
911   my $q_assembly_lastcost =
912     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
913         FROM assembly a_lc
914         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
915         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
916         WHERE (a_lc.id = p.id)) AS lastcost|;
917   $table_prefix{$q_assembly_lastcost} = ' ';
918
919   # special case makemodel search
920   # all_parts is based upon the assumption that every parameter is named like the column it represents
921   # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
922   # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
923   if ($form->{make}) {
924     push @where_tokens, 'mv.name ILIKE ?';
925     push @bind_vars, like($form->{make});
926   }
927   if ($form->{model}) {
928     push @where_tokens, 'mm.model ILIKE ?';
929     push @bind_vars, like($form->{model});
930   }
931
932   # special case: sorting by partnumber
933   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
934   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
935   # ToDO: implement proper functional sorting
936   # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
937   # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
938   #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
939   #  if $form->{sort} eq 'partnumber';
940
941   #my $order_clause = " ORDER BY $form->{sort} $sort_order";
942
943   my $limit_clause;
944   $limit_clause = " LIMIT 100"                   if $form->{top100};
945   $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
946
947   #=== joins and complicated filters ========#
948
949   my $bsooqr        = any { $form->{$_} } @oe_flags;
950   my @bsooqr_tokens = ();
951
952   push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi'  if $bsooqr;
953   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
954   push @select_tokens, $q_assembly_lastcost                                   if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
955   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
956   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
957   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
958   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
959   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
960   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
961   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
962
963   $joins_needed{partsgroup}  = 1;
964   $joins_needed{pfac}        = 1;
965   $joins_needed{project}     = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
966   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
967   $joins_needed{mv}          = 1 if $joins_needed{makemodel};
968   $joins_needed{cv}          = 1 if $bsooqr;
969   $joins_needed{apoe}        = 1 if $joins_needed{project} || $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
970   $joins_needed{invoice_oi}  = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
971
972   # special case for description search.
973   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
974   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
975   # find the old entries in of @where_tokens and @bind_vars, and adjust them
976   if ($joins_needed{invoice_oi}) {
977     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
978       next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
979       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
980       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
981       last;
982     }
983   }
984
985   # now the master trick: soldtotal.
986   if ($form->{l_soldtotal}) {
987     push @where_tokens, 'NOT ioi.qty = 0';
988     push @group_tokens, @select_tokens;
989      map { s/.*\sAS\s+//si } @group_tokens;
990     push @select_tokens, 'SUM(ioi.qty)';
991   }
992
993   #============= build query ================#
994
995   my $token_builder = $make_token_builder->(\%joins_needed);
996
997   my @sort_cols    = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
998      $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
999   my $sort_order   = ($form->{revers} ? ' DESC' : ' ASC');
1000   my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
1001
1002   my $select_clause = join ', ',    map { $token_builder->($_, 1) } @select_tokens;
1003   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
1004   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
1005   my $group_clause  = @group_tokens ? ' GROUP BY ' . join ', ',    map { $token_builder->($_) } @group_tokens : '';
1006
1007   my %oe_flag_to_cvar = (
1008     bought   => 'invoice',
1009     sold     => 'invoice',
1010     onorder  => 'orderitems',
1011     ordered  => 'orderitems',
1012     rfq      => 'orderitems',
1013     quoted   => 'orderitems',
1014   );
1015
1016   my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1017     module         => 'IC',
1018     trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1019     filter         => $form,
1020     sub_module     => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1021   );
1022
1023   if ($cvar_where) {
1024     $where_clause .= qq| AND ($cvar_where)|;
1025     push @bind_vars, @cvar_values;
1026   }
1027
1028   my $query = <<"  SQL";
1029     SELECT DISTINCT $select_clause
1030     FROM parts p
1031     $join_clause
1032     WHERE $where_clause
1033     $group_clause
1034     $order_clause
1035     $limit_clause
1036   SQL
1037
1038   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1039
1040   map { $_->{onhand} *= 1 } @{ $form->{parts} };
1041
1042   # fix qty sign in ap. those are saved negative
1043   if ($bsooqr && $form->{bought}) {
1044     for my $row (@{ $form->{parts} }) {
1045       $row->{qty} *= -1 if $row->{module} eq 'ir';
1046     }
1047   }
1048
1049   # post processing for assembly parts lists (bom)
1050   # for each part get the assembly parts and add them into the partlist.
1051   my @assemblies;
1052   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1053     $query =
1054       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1055            p.unit, p.notes, p.itime::DATE as insertdate,
1056            p.sellprice, p.listprice, p.lastcost,
1057            p.rop, p.weight, p.priceupdate,
1058            p.image, p.drawing, p.microfiche,
1059            pfac.factor
1060          FROM parts p
1061          INNER JOIN assembly a ON (p.id = a.parts_id)
1062          $joins{pfac}
1063          WHERE a.id = ?|;
1064     my $sth = prepare_query($form, $dbh, $query);
1065
1066     foreach my $item (@{ $form->{parts} }) {
1067       push(@assemblies, $item);
1068       do_statement($form, $sth, $query, conv_i($item->{id}));
1069
1070       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1071         $ref->{assemblyitem} = 1;
1072         map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1073         push(@assemblies, $ref);
1074       }
1075       $sth->finish;
1076     }
1077
1078     # copy assemblies to $form->{parts}
1079     $form->{parts} = \@assemblies;
1080   }
1081
1082   if ($form->{l_pricegroups} ) {
1083     my $query = <<SQL;
1084        SELECT parts_id, price, pricegroup_id
1085        FROM prices
1086        WHERE parts_id = ?
1087 SQL
1088
1089     my $sth = prepare_query($form, $dbh, $query);
1090
1091     foreach my $part (@{ $form->{parts} }) {
1092       do_statement($form, $sth, $query, conv_i($part->{id}));
1093
1094       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1095         $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1096       }
1097       $sth->finish;
1098     }
1099   };
1100
1101
1102   $main::lxdebug->leave_sub();
1103
1104   return @{ $form->{parts} };
1105 }
1106
1107 sub _create_filter_for_priceupdate {
1108   $main::lxdebug->enter_sub();
1109
1110   my $self     = shift;
1111   my $myconfig = \%main::myconfig;
1112   my $form     = $main::form;
1113
1114   my @where_values;
1115   my $where = '1 = 1';
1116
1117   foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1118     my $column = $item;
1119     $column =~ s/.*\.//;
1120     next unless ($form->{$column});
1121
1122     $where .= qq| AND $item ILIKE ?|;
1123     push(@where_values, like($form->{$column}));
1124   }
1125
1126   foreach my $item (qw(description serialnumber)) {
1127     next unless ($form->{$item});
1128
1129     $where .= qq| AND (${item} ILIKE ?)|;
1130     push(@where_values, like($form->{$item}));
1131   }
1132
1133
1134   # items which were never bought, sold or on an order
1135   if ($form->{itemstatus} eq 'orphaned') {
1136     $where .=
1137       qq| AND (p.onhand = 0)
1138           AND p.id NOT IN
1139             (
1140               SELECT DISTINCT parts_id FROM invoice
1141               UNION
1142               SELECT DISTINCT parts_id FROM assembly
1143               UNION
1144               SELECT DISTINCT parts_id FROM orderitems
1145             )|;
1146
1147   } elsif ($form->{itemstatus} eq 'active') {
1148     $where .= qq| AND p.obsolete = '0'|;
1149
1150   } elsif ($form->{itemstatus} eq 'obsolete') {
1151     $where .= qq| AND p.obsolete = '1'|;
1152
1153   } elsif ($form->{itemstatus} eq 'onhand') {
1154     $where .= qq| AND p.onhand > 0|;
1155
1156   } elsif ($form->{itemstatus} eq 'short') {
1157     $where .= qq| AND p.onhand < p.rop|;
1158
1159   }
1160
1161   foreach my $column (qw(make model)) {
1162     next unless ($form->{$column});
1163     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1164     push(@where_values, like($form->{$column}));
1165   }
1166
1167   $main::lxdebug->leave_sub();
1168
1169   return ($where, @where_values);
1170 }
1171
1172 sub get_num_matches_for_priceupdate {
1173   $main::lxdebug->enter_sub();
1174
1175   my $self     = shift;
1176
1177   my $myconfig = \%main::myconfig;
1178   my $form     = $main::form;
1179
1180   my $dbh      = $form->get_standard_dbh($myconfig);
1181
1182   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1183
1184   my $num_updated = 0;
1185   my $query;
1186
1187   for my $column (qw(sellprice listprice)) {
1188     next if ($form->{$column} eq "");
1189
1190     $query =
1191       qq|SELECT COUNT(*)
1192          FROM parts
1193          WHERE id IN
1194            (SELECT p.id
1195             FROM parts p
1196             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1197             WHERE $where)|;
1198     my ($result)  = selectfirst_array_query($form, $dbh, $query, @where_values);
1199     $num_updated += $result if (0 <= $result);
1200   }
1201
1202   $query =
1203     qq|SELECT COUNT(*)
1204        FROM prices
1205        WHERE parts_id IN
1206          (SELECT p.id
1207           FROM parts p
1208           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1209           WHERE $where) AND (pricegroup_id = ?)|;
1210   my $sth = prepare_query($form, $dbh, $query);
1211
1212   for my $i (1 .. $form->{price_rows}) {
1213     next if ($form->{"price_$i"} eq "");
1214
1215     my ($result)  = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1216     $num_updated += $result if (0 <= $result);
1217   }
1218   $sth->finish();
1219
1220   $main::lxdebug->leave_sub();
1221
1222   return $num_updated;
1223 }
1224
1225 sub update_prices {
1226   my ($self, $myconfig, $form) = @_;
1227   $main::lxdebug->enter_sub();
1228
1229   my $num_updated = SL::DB->client->with_transaction(\&_update_prices, $self, $myconfig, $form);
1230
1231   $main::lxdebug->leave_sub();
1232   return $num_updated;
1233 }
1234
1235 sub _update_prices {
1236   my ($self, $myconfig, $form) = @_;
1237
1238   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1239   my $num_updated = 0;
1240
1241   # connect to database
1242   my $dbh = SL::DB->client->dbh;
1243
1244   for my $column (qw(sellprice listprice)) {
1245     next if ($form->{$column} eq "");
1246
1247     my $value = $form->parse_amount($myconfig, $form->{$column});
1248     my $operator = '+';
1249
1250     if ($form->{"${column}_type"} eq "percent") {
1251       $value = ($value / 100) + 1;
1252       $operator = '*';
1253     }
1254
1255     my $query =
1256       qq|UPDATE parts SET $column = $column $operator ?
1257          WHERE id IN
1258            (SELECT p.id
1259             FROM parts p
1260             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1261             WHERE $where)|;
1262     my $result    = do_query($form, $dbh, $query, $value, @where_values);
1263     $num_updated += $result if (0 <= $result);
1264   }
1265
1266   my $q_add =
1267     qq|UPDATE prices SET price = price + ?
1268        WHERE parts_id IN
1269          (SELECT p.id
1270           FROM parts p
1271           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1272           WHERE $where) AND (pricegroup_id = ?)|;
1273   my $sth_add = prepare_query($form, $dbh, $q_add);
1274
1275   my $q_multiply =
1276     qq|UPDATE prices SET price = price * ?
1277        WHERE parts_id IN
1278          (SELECT p.id
1279           FROM parts p
1280           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1281           WHERE $where) AND (pricegroup_id = ?)|;
1282   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1283
1284   for my $i (1 .. $form->{price_rows}) {
1285     next if ($form->{"price_$i"} eq "");
1286
1287     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1288     my $result;
1289
1290     if ($form->{"pricegroup_type_$i"} eq "percent") {
1291       $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1292     } else {
1293       $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1294     }
1295
1296     $num_updated += $result if (0 <= $result);
1297   }
1298
1299   $sth_add->finish();
1300   $sth_multiply->finish();
1301
1302   return $num_updated;
1303 }
1304
1305 sub create_links {
1306   $main::lxdebug->enter_sub();
1307
1308   my ($self, $module, $myconfig, $form) = @_;
1309
1310   # connect to database
1311   my $dbh = $form->get_standard_dbh;
1312
1313   my @values = like($module);
1314   my $query;
1315
1316   if ($form->{id}) {
1317     $query =
1318       qq|SELECT c.accno, c.description, c.link, c.id,
1319            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1320          FROM chart c, parts p
1321          WHERE (c.link LIKE ?) AND (p.id = ?)
1322          ORDER BY c.accno|;
1323     push(@values, conv_i($form->{id}));
1324
1325   } else {
1326     $query =
1327       qq|SELECT c.accno, c.description, c.link, c.id,
1328            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1329          FROM chart c, defaults d
1330          WHERE c.link LIKE ?
1331          ORDER BY c.accno|;
1332   }
1333
1334   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1335   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1336     foreach my $key (split(/:/, $ref->{link})) {
1337       if ($key =~ /\Q$module\E/) {
1338         if (   ($ref->{id} eq $ref->{inventory_accno_id})
1339             || ($ref->{id} eq $ref->{income_accno_id})
1340             || ($ref->{id} eq $ref->{expense_accno_id})) {
1341           push @{ $form->{"${module}_links"}{$key} },
1342             { accno       => $ref->{accno},
1343               description => $ref->{description},
1344               selected    => "selected" };
1345           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1346             } else {
1347           push @{ $form->{"${module}_links"}{$key} },
1348             { accno       => $ref->{accno},
1349               description => $ref->{description},
1350               selected    => "" };
1351         }
1352       }
1353     }
1354   }
1355   $sth->finish;
1356
1357   # get buchungsgruppen
1358   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1359
1360   # get payment terms
1361   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1362
1363   if (!$form->{id}) {
1364     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1365   }
1366
1367   $main::lxdebug->leave_sub();
1368 }
1369
1370 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1371 sub get_parts {
1372   $main::lxdebug->enter_sub();
1373
1374   my ($self, $myconfig, $form, $sortorder) = @_;
1375   my $dbh   = $form->get_standard_dbh;
1376   my $order = qq| p.partnumber|;
1377   my $where = qq|1 = 1|;
1378   my @values;
1379
1380   if ($sortorder eq "all") {
1381     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1382     push(@values, like($form->{partnumber}), like($form->{description}));
1383
1384   } elsif ($sortorder eq "partnumber") {
1385     $where .= qq| AND (partnumber ILIKE ?)|;
1386     push(@values, like($form->{partnumber}));
1387
1388   } elsif ($sortorder eq "description") {
1389     $where .= qq| AND (description ILIKE ?)|;
1390     push(@values, like($form->{description}));
1391     $order = "description";
1392
1393   }
1394
1395   my $query =
1396     qq|SELECT id, partnumber, description, unit, sellprice
1397        FROM parts
1398        WHERE $where ORDER BY $order|;
1399
1400   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1401
1402   my $j = 0;
1403   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1404     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1405       next;
1406     }
1407
1408     $j++;
1409     $form->{"id_$j"}          = $ref->{id};
1410     $form->{"partnumber_$j"}  = $ref->{partnumber};
1411     $form->{"description_$j"} = $ref->{description};
1412     $form->{"unit_$j"}        = $ref->{unit};
1413     $form->{"sellprice_$j"}   = $ref->{sellprice};
1414     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
1415   }    #while
1416   $form->{rows} = $j;
1417   $sth->finish;
1418
1419   $main::lxdebug->leave_sub();
1420
1421   return $self;
1422 }    #end get_parts()
1423
1424 # gets sum of sold part with part_id
1425 sub get_soldtotal {
1426   $main::lxdebug->enter_sub();
1427
1428   my ($dbh, $id) = @_;
1429
1430   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1431   my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1432   $sum ||= 0;
1433
1434   $main::lxdebug->leave_sub();
1435
1436   return $sum;
1437 }    #end get_soldtotal
1438
1439 sub retrieve_languages {
1440   $main::lxdebug->enter_sub();
1441
1442   my ($self, $myconfig, $form) = @_;
1443
1444   # connect to database
1445   my $dbh = $form->get_standard_dbh;
1446
1447   my @values;
1448   my $where;
1449   my $query;
1450
1451   if ($form->{language_values} ne "") {
1452     $query =
1453       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1454          FROM language l
1455          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1456          ORDER BY lower(l.description)|;
1457     @values = (conv_i($form->{id}));
1458
1459   } else {
1460     $query = qq|SELECT id, description
1461                 FROM language
1462                 ORDER BY lower(description)|;
1463   }
1464
1465   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1466
1467   $main::lxdebug->leave_sub();
1468
1469   return $languages;
1470 }
1471
1472 sub follow_account_chain {
1473   $main::lxdebug->enter_sub(2);
1474
1475   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1476
1477   my @visited_accno_ids = ($accno_id);
1478
1479   my ($query, $sth);
1480
1481   $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1482     map { $_->{id} => $_ }
1483       selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1484     SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1485     FROM chart c
1486     LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1487     WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1488 SQL
1489
1490   while (1) {
1491     my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1492     last unless ($ref && $ref->{"is_valid"} &&
1493                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1494     $accno_id = $ref->{"new_chart_id"};
1495     $accno = $ref->{"accno"};
1496     push(@visited_accno_ids, $accno_id);
1497   }
1498
1499   $main::lxdebug->leave_sub(2);
1500
1501   return ($accno_id, $accno);
1502 }
1503
1504 sub retrieve_accounts {
1505   $main::lxdebug->enter_sub;
1506
1507   my $self     = shift;
1508   my $myconfig = shift;
1509   my $form     = shift;
1510   my $dbh      = $form->get_standard_dbh;
1511   my %args     = @_;     # index => part_id
1512
1513   $form->{taxzone_id} *= 1;
1514
1515   return unless grep $_, values %args; # shortfuse if no part_id supplied
1516
1517   # transdate madness.
1518   my $transdate = "";
1519   if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
1520     # use deliverydate for sales and purchase invoice, if it exists
1521     # also use deliverydate for credit notes
1522     if (!$form->{deliverydate}) {
1523       $transdate = $form->{invdate};
1524     } else {
1525       $transdate = $form->{deliverydate};
1526     }
1527   } elsif ($form->{script} eq 'ir.pl') {
1528     # when a purchase invoice is opened from the report of purchase invoices
1529     # $form->{type} isn't set, but $form->{script} is, not sure why this is or
1530     # whether this distinction matters in some other scenario. Otherwise one
1531     # could probably take out this elsif and add a
1532     # " or $form->{script} eq 'ir.pl' "
1533     # to the above if-statement
1534     if (!$form->{deliverydate}) {
1535       $transdate = $form->{invdate};
1536     } else {
1537       $transdate = $form->{deliverydate};
1538     }
1539   } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1540     # if credit_note has a deliverydate, use this instead of invdate
1541     # useful for credit_notes of invoices from an old period with different tax
1542     # if there is no deliverydate then invdate is used, old default (see next elsif)
1543     # Falls hier der Stichtag für Steuern anders bestimmt wird,
1544     # entsprechend auch bei Taxkeys.pm anpassen
1545     $transdate = $form->{deliverydate};
1546   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1547     $transdate = $form->{invdate};
1548   } else {
1549     $transdate = $form->{transdate};
1550   }
1551
1552   if ($transdate eq "") {
1553     $transdate = DateTime->today_local->to_lxoffice;
1554   } else {
1555     $transdate = $dbh->quote($transdate);
1556   }
1557   #/transdate
1558   my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1559
1560   my @part_ids = grep { $_ } values %args;
1561   my $in       = join ',', ('?') x @part_ids;
1562
1563   my %accno_by_part = map { $_->{id} => $_ }
1564     selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1565     SELECT
1566       p.id, p.part_type,
1567       bg.inventory_accno_id,
1568       tc.income_accno_id AS income_accno_id,
1569       tc.expense_accno_id AS expense_accno_id,
1570       c1.accno AS inventory_accno,
1571       c2.accno AS income_accno,
1572       c3.accno AS expense_accno
1573     FROM parts p
1574     LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1575     LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
1576     LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1577     LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
1578     LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
1579     WHERE
1580     tc.taxzone_id = '$form->{taxzone_id}'
1581     and
1582     p.id IN ($in)
1583 SQL
1584
1585   my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1586     SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1587     FROM tax t
1588     LEFT JOIN chart c ON c.id = t.chart_id
1589     WHERE t.id IN
1590       (SELECT tk.tax_id
1591        FROM taxkeys tk
1592        WHERE tk.chart_id = ? AND startdate <= ?
1593        ORDER BY startdate DESC LIMIT 1)
1594 SQL
1595
1596   while (my ($index => $part_id) = each %args) {
1597     my $ref = $accno_by_part{$part_id} or next;
1598
1599     $ref->{"inventory_accno_id"} = undef unless $ref->{"part_type"} eq 'part';
1600
1601     my %accounts;
1602     for my $type (qw(inventory income expense)) {
1603       next unless $ref->{"${type}_accno_id"};
1604       ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1605         $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1606     }
1607
1608     $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1609
1610     $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1611     $ref = $sth_tax->fetchrow_hashref or next;
1612
1613     $form->{"taxaccounts_$index"} = $ref->{"accno"};
1614     $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1615
1616     $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1617   }
1618
1619   $sth_tax->finish;
1620
1621   $::lxdebug->leave_sub;
1622 }
1623
1624 sub get_basic_part_info {
1625   $main::lxdebug->enter_sub();
1626
1627   my $self     = shift;
1628   my %params   = @_;
1629
1630   Common::check_params(\%params, qw(id));
1631
1632   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1633
1634   if (!scalar @ids) {
1635     $main::lxdebug->leave_sub();
1636     return ();
1637   }
1638
1639   my $myconfig = \%main::myconfig;
1640   my $form     = $main::form;
1641
1642   my $dbh      = $form->get_standard_dbh($myconfig);
1643
1644   my $query    = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1645
1646   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1647
1648   if ('' eq ref $params{id}) {
1649     $info = $info->[0] || { };
1650
1651     $main::lxdebug->leave_sub();
1652     return $info;
1653   }
1654
1655   my %info_map = map { $_->{id} => $_ } @{ $info };
1656
1657   $main::lxdebug->leave_sub();
1658
1659   return %info_map;
1660 }
1661
1662 sub prepare_parts_for_printing {
1663   $main::lxdebug->enter_sub();
1664
1665   my $self     = shift;
1666   my %params   = @_;
1667
1668   my $myconfig = $params{myconfig} || \%main::myconfig;
1669   my $form     = $params{form}     || $main::form;
1670
1671   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1672
1673   my $prefix   = $params{prefix} || 'id_';
1674   my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1675
1676   my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1677
1678   if (!@part_ids) {
1679     $main::lxdebug->leave_sub();
1680     return;
1681   }
1682
1683   my $placeholders = join ', ', ('?') x scalar(@part_ids);
1684   my $query        = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1685                         FROM makemodel mm
1686                         LEFT JOIN vendor v ON (mm.make = v.id)
1687                         WHERE mm.parts_id IN ($placeholders)|;
1688
1689   my %makemodel    = ();
1690
1691   my $sth          = prepare_execute_query($form, $dbh, $query, @part_ids);
1692
1693   while (my $ref = $sth->fetchrow_hashref()) {
1694     $makemodel{$ref->{parts_id}} ||= [];
1695     push @{ $makemodel{$ref->{parts_id}} }, $ref;
1696   }
1697
1698   $sth->finish();
1699
1700   my @columns = qw(ean image microfiche drawing);
1701
1702   $query      = qq|SELECT id, | . join(', ', @columns) . qq|
1703                    FROM parts
1704                    WHERE id IN ($placeholders)|;
1705
1706   my %data    = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1707
1708   my %template_arrays;
1709   map { $template_arrays{$_} = [] } (qw(make model), @columns);
1710
1711   foreach my $i (1 .. $rowcount) {
1712     my $id = $form->{"${prefix}${i}"};
1713
1714     next if (!$id);
1715
1716     foreach (@columns) {
1717       push @{ $template_arrays{$_} }, $data{$id}->{$_};
1718     }
1719
1720     push @{ $template_arrays{make} },  [];
1721     push @{ $template_arrays{model} }, [];
1722
1723     next if (!$makemodel{$id});
1724
1725     foreach my $ref (@{ $makemodel{$id} }) {
1726       map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model);
1727     }
1728   }
1729
1730   my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
1731   my %parts_by_id = map { $_->id => $_ } @$parts;
1732
1733   for my $i (1..$rowcount) {
1734     my $id = $form->{"${prefix}${i}"};
1735     next unless $id;
1736
1737     push @{ $template_arrays{part_type} },  $parts_by_id{$id}->type;
1738   }
1739
1740   return %template_arrays;
1741   $main::lxdebug->leave_sub();
1742 }
1743
1744 sub normalize_text_blocks {
1745   $main::lxdebug->enter_sub();
1746
1747   my $self     = shift;
1748   my %params   = @_;
1749
1750   my $form     = $params{form}     || $main::form;
1751
1752   # check if feature is enabled (select normalize_part_descriptions from defaults)
1753   return unless ($::instance_conf->get_normalize_part_descriptions);
1754
1755   foreach (qw(description notes)) {
1756     $form->{$_} =~ s/\s+$//s;
1757     $form->{$_} =~ s/^\s+//s;
1758     $form->{$_} =~ s/ {2,}/ /g;
1759   }
1760    $main::lxdebug->leave_sub();
1761 }
1762
1763
1764 1;