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