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