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