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