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