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