Part Controller - ic.pl und IC.pm Funktionen entfernt
[kivitendo-erp.git] / SL / IC.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 # Inventory Control backend
32 #
33 #======================================================================
34
35 package IC;
36
37 use Data::Dumper;
38 use List::MoreUtils qw(all any uniq);
39 use YAML;
40
41 use SL::CVar;
42 use SL::DBUtils;
43 use SL::HTML::Restrict;
44 use SL::TransNumber;
45 use SL::Util qw(trim);
46 use SL::DB;
47 use Carp;
48
49 use strict;
50
51 sub get_pricegroups {
52   $main::lxdebug->enter_sub();
53
54   my ($self, $myconfig, $form) = @_;
55
56   my $dbh = $form->get_standard_dbh;
57
58   # get pricegroups
59   my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
60   my $pricegroups = selectall_hashref_query($form, $dbh, $query);
61
62   my $i = 1;
63   foreach my $pg (@{ $pricegroups }) {
64     $form->{"price_$i"}         = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
65     $form->{"pricegroup_id_$i"} = "$pg->{id}";
66     $form->{"pricegroup_$i"}    = "$pg->{pricegroup}";
67     $i++;
68   }
69
70   #correct rows
71   $form->{price_rows} = $i - 1;
72
73   $main::lxdebug->leave_sub();
74
75   return $pricegroups;
76 }
77
78 sub retrieve_buchungsgruppen {
79   $main::lxdebug->enter_sub();
80
81   my ($self, $myconfig, $form) = @_;
82
83   my ($query, $sth);
84
85   my $dbh = $form->get_standard_dbh;
86
87   # get buchungsgruppen
88   $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
89   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
90
91   $main::lxdebug->leave_sub();
92 }
93
94 sub retrieve_assemblies {
95   $main::lxdebug->enter_sub();
96
97   my ($self, $myconfig, $form) = @_;
98
99   # connect to database
100   my $dbh = $form->get_standard_dbh;
101
102   my $where = qq|NOT p.obsolete|;
103   my @values;
104
105   if ($form->{partnumber}) {
106     $where .= qq| AND (p.partnumber ILIKE ?)|;
107     push(@values, like($form->{partnumber}));
108   }
109
110   if ($form->{description}) {
111     $where .= qq| AND (p.description ILIKE ?)|;
112     push(@values, like($form->{description}));
113   }
114
115   # retrieve assembly items
116   my $query =
117     qq|SELECT p.id, p.partnumber, p.description,
118               p.onhand, p.rop,
119          (SELECT sum(p2.inventory_accno_id)
120           FROM parts p2, assembly a
121           WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
122        FROM parts p
123        WHERE NOT p.obsolete AND p.part_type = 'assembly' $where|;
124
125   $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
126
127   $main::lxdebug->leave_sub();
128 }
129
130 sub assembly_item {
131   $main::lxdebug->enter_sub();
132
133   my ($self, $myconfig, $form) = @_;
134
135   my $i = $form->{assembly_rows};
136   my $var;
137   my $where = qq|1 = 1|;
138   my @values;
139
140   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
141
142   while (my ($column, $table) = each(%columns)) {
143     next unless ($form->{"${column}_$i"});
144     $where .= qq| AND ${table}.${column} ILIKE ?|;
145     push(@values, like($form->{"${column}_$i"}));
146   }
147
148   if ($form->{id}) {
149     $where .= qq| AND NOT (p.id = ?)|;
150     push(@values, conv_i($form->{id}));
151   }
152
153   # Search for part ID overrides all other criteria.
154   if ($form->{"id_${i}"}) {
155     $where  = qq|p.id = ?|;
156     @values = ($form->{"id_${i}"});
157   }
158
159   if ($form->{partnumber}) {
160     $where .= qq| ORDER BY p.partnumber|;
161   } else {
162     $where .= qq| ORDER BY p.description|;
163   }
164
165   my $query =
166     qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
167        p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
168        p.price_factor_id, pfac.factor AS price_factor, p.notes as longdescription
169        FROM parts p
170        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
171        LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
172        WHERE $where|;
173   $form->{item_list} = selectall_hashref_query($form, SL::DB->client->dbh, $query, @values);
174
175   $main::lxdebug->leave_sub();
176 }
177
178 #
179 # Report for Wares.
180 # Warning, deep magic ahead.
181 # This function gets all parts from the database according to the filters specified
182 #
183 # specials:
184 #   sort revers  - sorting field + direction
185 #   top100
186 #
187 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
188 #   partnumber ean description partsgroup microfiche drawing
189 #
190 # column flags:
191 #   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
192 #
193 # exclusives:
194 #   itemstatus  = active | onhand | short | obsolete | orphaned
195 #   searchitems = part | assembly | service
196 #
197 # joining filters:
198 #   make model                               - makemodel
199 #   serialnumber transdatefrom transdateto   - invoice/orderitems
200 #
201 # binary flags:
202 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
203 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
204 #   l_soldtotal                              - aggreg join to display total of sold quantity
205 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
206 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
207 #   l_serialnumber                           - belonges to serialnumber filter
208 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
209 #   l_soldtotal                              - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
210 #
211 # not working:
212 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
213 #   warehouse onhand
214 #   search by overrides of description
215 #
216 # disabled sanity checks and changes:
217 #  - searchitems = assembly will no longer disable bought
218 #  - searchitems = service  will no longer disable make and model, although services don't have make/model, it doesn't break the query
219 #  - itemstatus  = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
220 #  - itemstatus  = obsolete will no longer disable onhand, short
221 #  - allow sorting by ean
222 #  - serialnumber filter also works if l_serialnumber isn't ticked
223 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
224 #
225 sub all_parts {
226   $main::lxdebug->enter_sub();
227
228   my ($self, $myconfig, $form) = @_;
229   my $dbh = $form->get_standard_dbh($myconfig);
230
231   $form->{parts}     = +{ };
232   $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
233
234   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
235   my @project_filters      = qw(projectnumber projectdescription);
236   my @makemodel_filters    = qw(make model);
237   my @invoice_oi_filters   = qw(serialnumber soldtotal);
238   my @apoe_filters         = qw(transdate);
239   my @like_filters         = (@simple_filters, @invoice_oi_filters);
240   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
241   my @simple_l_switches    = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image shop insertdate));
242   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
243   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module qty);
244   my @deliverydate_flags   = qw(deliverydate);
245 #  my @other_flags          = qw(onhand); # ToDO: implement these
246 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
247
248   my @select_tokens = qw(id factor);
249   my @where_tokens  = qw(1=1);
250   my @group_tokens  = ();
251   my @bind_vars     = ();
252   my %joins_needed  = ();
253
254   my %joins = (
255     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
256     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
257     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
258     invoice_oi =>
259       q|LEFT JOIN (
260          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem,         deliverydate, 'invoice'    AS ioi, project_id, id FROM invoice UNION
261          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
262        ) AS ioi ON ioi.parts_id = p.id|,
263     apoe       =>
264       q|LEFT JOIN (
265          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
266          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
267          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
268        ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
269     cv         =>
270       q|LEFT JOIN (
271            SELECT id, name, 'customer' AS cv FROM customer UNION
272            SELECT id, name, 'vendor'   AS cv FROM vendor
273          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
274     mv         => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
275     project    => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
276   );
277   my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
278
279   my %table_prefix = (
280      deliverydate => 'apoe.', serialnumber => 'ioi.',
281      transdate    => 'apoe.', trans_id     => 'ioi.',
282      module       => 'apoe.', name         => 'cv.',
283      ordnumber    => 'apoe.', make         => 'mm.',
284      quonumber    => 'apoe.', model        => 'mm.',
285      invnumber    => 'apoe.', partsgroup   => 'pg.',
286      lastcost     => 'p.',  , soldtotal    => ' ',
287      factor       => 'pfac.', projectnumber => 'pj.',
288      'SUM(ioi.qty)' => ' ',   projectdescription => 'pj.',
289      description  => 'p.',
290      qty          => 'ioi.',
291      serialnumber => 'ioi.',
292      quotation    => 'apoe.',
293      cv           => 'cv.',
294      "ioi.id"     => ' ',
295      "ioi.ioi"    => ' ',
296   );
297
298   # if the join condition in these blocks are met, the column
299   # of the scecified table will gently override (coalesce actually) the original value
300   # use it to conditionally coalesce values from subtables
301   my @column_override = (
302     #  column name,   prefix,  joins_needed,  nick name (in case column is named like another)
303     [ 'description',  'ioi.',  'invoice_oi'  ],
304     [ 'deliverydate', 'ioi.',  'invoice_oi'  ],
305     [ 'transdate',    'apoe.', 'apoe'        ],
306     [ 'unit',         'ioi.',  'invoice_oi'  ],
307     [ 'sellprice',    'ioi.',  'invoice_oi'  ],
308   );
309
310   # careful with renames. these are HARD, and any filters done on the original column will break
311   my %renamed_columns = (
312     'factor'       => 'price_factor',
313     'SUM(ioi.qty)' => 'soldtotal',
314     'ioi.id'       => 'ioi_id',
315     'ioi.ioi'      => 'ioi',
316     'projectdescription' => 'projectdescription',
317     'insertdate'   => 'insertdate',
318   );
319
320   my %real_column = (
321     projectdescription => 'description',
322     insertdate         => 'itime::DATE',
323   );
324
325   if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
326     @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
327   }
328
329   my $make_token_builder = sub {
330     my $joins_needed = shift;
331     sub {
332       my ($nick, $alias) = @_;
333       my ($col) = $real_column{$nick} || $nick;
334       my @coalesce_tokens =
335         map  { ($_->[1] || 'p.') . $_->[0] }
336         grep { !$_->[2] || $joins_needed->{$_->[2]} }
337         grep { ($_->[3] || $_->[0]) eq $nick }
338         @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
339
340       my $coalesce = scalar @coalesce_tokens > 1;
341       return ($coalesce
342         ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
343         : shift                              @coalesce_tokens)
344         . ($alias && ($coalesce || $renamed_columns{$nick})
345         ?  " AS " . ($renamed_columns{$nick} || $nick)
346         : '');
347     }
348   };
349
350   #===== switches and simple filters ========#
351
352   # special case transdate
353   if (grep { trim($form->{$_}) } qw(transdatefrom transdateto)) {
354     $form->{"l_transdate"} = 1;
355     push @select_tokens, 'transdate';
356     for (qw(transdatefrom transdateto)) {
357       my $value = trim($form->{$_});
358       next unless $value;
359       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
360       push @bind_vars,    $value;
361     }
362   }
363
364   # special case smart search
365   if ($form->{all}) {
366     $form->{"l_$_"} = 1 for qw(partnumber description unit sellprice lastcost cvar_packaging linetotal);
367     push @where_tokens, "p.partnumber ILIKE ? OR p.description ILIKE ?";
368     push @bind_vars,    (like($form->{all})) x 2;
369   }
370
371   # special case insertdate
372   if (grep { trim($form->{$_}) } qw(insertdatefrom insertdateto)) {
373     $form->{"l_insertdate"} = 1;
374     push @select_tokens, 'insertdate';
375
376     my $token_builder = $make_token_builder->();
377     my $token = $token_builder->('insertdate');
378
379     for (qw(insertdatefrom insertdateto)) {
380       my $value = trim($form->{$_});
381       next unless $value;
382       push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
383       push @bind_vars,    $value;
384     }
385   }
386
387   if ($form->{"partsgroup_id"}) {
388     $form->{"l_partsgroup"} = '1'; # show the column
389     push @where_tokens, "pg.id = ?";
390     push @bind_vars, $form->{"partsgroup_id"};
391   }
392
393   if ($form->{shop} ne '') {
394     $form->{l_shop} = '1'; # show the column
395     if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
396       push @where_tokens, 'NOT p.shop';
397       $form->{shop} = 'f';
398     } else {
399       push @where_tokens, 'p.shop';
400     }
401   }
402
403   foreach (@like_filters) {
404     next unless $form->{$_};
405     $form->{"l_$_"} = '1'; # show the column
406     push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
407     push @bind_vars,    like($form->{$_});
408   }
409
410   foreach (@simple_l_switches) {
411     next unless $form->{"l_$_"};
412     push @select_tokens, $_;
413   }
414
415   for ($form->{searchitems}) {
416     push @where_tokens, "p.part_type = 'part'"     if /part/;
417     push @where_tokens, "p.part_type = 'service'"  if /service/;
418     push @where_tokens, "p.part_type = 'assembly'" if /assembly/;
419   }
420
421   for ($form->{itemstatus}) {
422     push @where_tokens, 'p.id NOT IN
423         (SELECT DISTINCT parts_id FROM invoice UNION
424          SELECT DISTINCT parts_id FROM assembly UNION
425          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
426     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
427     push @where_tokens, 'NOT p.obsolete'               if /active/;
428     push @where_tokens, '    p.obsolete',              if /obsolete/;
429     push @where_tokens, 'p.onhand > 0',                if /onhand/;
430     push @where_tokens, 'p.onhand < p.rop',            if /short/;
431   }
432
433   my $q_assembly_lastcost =
434     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
435         FROM assembly a_lc
436         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
437         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
438         WHERE (a_lc.id = p.id)) AS lastcost|;
439   $table_prefix{$q_assembly_lastcost} = ' ';
440
441   # special case makemodel search
442   # all_parts is based upon the assumption that every parameter is named like the column it represents
443   # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
444   # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
445   if ($form->{make}) {
446     push @where_tokens, 'mv.name ILIKE ?';
447     push @bind_vars, like($form->{make});
448   }
449   if ($form->{model}) {
450     push @where_tokens, 'mm.model ILIKE ?';
451     push @bind_vars, like($form->{model});
452   }
453
454   # special case: sorting by partnumber
455   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
456   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
457   # ToDO: implement proper functional sorting
458   # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
459   # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
460   #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
461   #  if $form->{sort} eq 'partnumber';
462
463   #my $order_clause = " ORDER BY $form->{sort} $sort_order";
464
465   my $limit_clause;
466   $limit_clause = " LIMIT 100"                   if $form->{top100};
467   $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
468
469   #=== joins and complicated filters ========#
470
471   my $bsooqr        = any { $form->{$_} } @oe_flags;
472   my @bsooqr_tokens = ();
473
474   push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi'  if $bsooqr;
475   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
476   push @select_tokens, $q_assembly_lastcost                                   if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
477   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
478   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
479   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
480   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
481   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
482   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
483   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
484
485   $joins_needed{partsgroup}  = 1;
486   $joins_needed{pfac}        = 1;
487   $joins_needed{project}     = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
488   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
489   $joins_needed{mv}          = 1 if $joins_needed{makemodel};
490   $joins_needed{cv}          = 1 if $bsooqr;
491   $joins_needed{apoe}        = 1 if $joins_needed{project} || $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
492   $joins_needed{invoice_oi}  = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
493
494   # special case for description search.
495   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
496   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
497   # find the old entries in of @where_tokens and @bind_vars, and adjust them
498   if ($joins_needed{invoice_oi}) {
499     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
500       next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
501       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
502       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
503       last;
504     }
505   }
506
507   # now the master trick: soldtotal.
508   if ($form->{l_soldtotal}) {
509     push @where_tokens, 'NOT ioi.qty = 0';
510     push @group_tokens, @select_tokens;
511      map { s/.*\sAS\s+//si } @group_tokens;
512     push @select_tokens, 'SUM(ioi.qty)';
513   }
514
515   #============= build query ================#
516
517   my $token_builder = $make_token_builder->(\%joins_needed);
518
519   my @sort_cols    = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
520      $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
521   my $sort_order   = ($form->{revers} ? ' DESC' : ' ASC');
522   my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
523
524   my $select_clause = join ', ',    map { $token_builder->($_, 1) } @select_tokens;
525   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
526   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
527   my $group_clause  = @group_tokens ? ' GROUP BY ' . join ', ',    map { $token_builder->($_) } @group_tokens : '';
528
529   my %oe_flag_to_cvar = (
530     bought   => 'invoice',
531     sold     => 'invoice',
532     onorder  => 'orderitems',
533     ordered  => 'orderitems',
534     rfq      => 'orderitems',
535     quoted   => 'orderitems',
536   );
537
538   my ($cvar_where, @cvar_values) = CVar->build_filter_query(
539     module         => 'IC',
540     trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
541     filter         => $form,
542     sub_module     => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
543   );
544
545   if ($cvar_where) {
546     $where_clause .= qq| AND ($cvar_where)|;
547     push @bind_vars, @cvar_values;
548   }
549
550   my $query = <<"  SQL";
551     SELECT DISTINCT $select_clause
552     FROM parts p
553     $join_clause
554     WHERE $where_clause
555     $group_clause
556     $order_clause
557     $limit_clause
558   SQL
559
560   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
561
562   map { $_->{onhand} *= 1 } @{ $form->{parts} };
563
564   # fix qty sign in ap. those are saved negative
565   if ($bsooqr && $form->{bought}) {
566     for my $row (@{ $form->{parts} }) {
567       $row->{qty} *= -1 if $row->{module} eq 'ir';
568     }
569   }
570
571   # post processing for assembly parts lists (bom)
572   # for each part get the assembly parts and add them into the partlist.
573   my @assemblies;
574   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
575     $query =
576       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
577            p.unit, p.notes, p.itime::DATE as insertdate,
578            p.sellprice, p.listprice, p.lastcost,
579            p.rop, p.weight, p.priceupdate,
580            p.image, p.drawing, p.microfiche,
581            pfac.factor
582          FROM parts p
583          INNER JOIN assembly a ON (p.id = a.parts_id)
584          $joins{pfac}
585          WHERE a.id = ?|;
586     my $sth = prepare_query($form, $dbh, $query);
587
588     foreach my $item (@{ $form->{parts} }) {
589       push(@assemblies, $item);
590       do_statement($form, $sth, $query, conv_i($item->{id}));
591
592       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
593         $ref->{assemblyitem} = 1;
594         map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
595         push(@assemblies, $ref);
596       }
597       $sth->finish;
598     }
599
600     # copy assemblies to $form->{parts}
601     $form->{parts} = \@assemblies;
602   }
603
604   if ($form->{l_pricegroups} ) {
605     my $query = <<SQL;
606        SELECT parts_id, price, pricegroup_id
607        FROM prices
608        WHERE parts_id = ?
609 SQL
610
611     my $sth = prepare_query($form, $dbh, $query);
612
613     foreach my $part (@{ $form->{parts} }) {
614       do_statement($form, $sth, $query, conv_i($part->{id}));
615
616       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
617         $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
618       }
619       $sth->finish;
620     }
621   };
622
623
624   $main::lxdebug->leave_sub();
625
626   return @{ $form->{parts} };
627 }
628
629 sub _create_filter_for_priceupdate {
630   $main::lxdebug->enter_sub();
631
632   my $self     = shift;
633   my $myconfig = \%main::myconfig;
634   my $form     = $main::form;
635
636   my @where_values;
637   my $where = '1 = 1';
638
639   foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
640     my $column = $item;
641     $column =~ s/.*\.//;
642     next unless ($form->{$column});
643
644     $where .= qq| AND $item ILIKE ?|;
645     push(@where_values, like($form->{$column}));
646   }
647
648   foreach my $item (qw(description serialnumber)) {
649     next unless ($form->{$item});
650
651     $where .= qq| AND (${item} ILIKE ?)|;
652     push(@where_values, like($form->{$item}));
653   }
654
655
656   # items which were never bought, sold or on an order
657   if ($form->{itemstatus} eq 'orphaned') {
658     $where .=
659       qq| AND (p.onhand = 0)
660           AND p.id NOT IN
661             (
662               SELECT DISTINCT parts_id FROM invoice
663               UNION
664               SELECT DISTINCT parts_id FROM assembly
665               UNION
666               SELECT DISTINCT parts_id FROM orderitems
667             )|;
668
669   } elsif ($form->{itemstatus} eq 'active') {
670     $where .= qq| AND p.obsolete = '0'|;
671
672   } elsif ($form->{itemstatus} eq 'obsolete') {
673     $where .= qq| AND p.obsolete = '1'|;
674
675   } elsif ($form->{itemstatus} eq 'onhand') {
676     $where .= qq| AND p.onhand > 0|;
677
678   } elsif ($form->{itemstatus} eq 'short') {
679     $where .= qq| AND p.onhand < p.rop|;
680
681   }
682
683   foreach my $column (qw(make model)) {
684     next unless ($form->{$column});
685     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
686     push(@where_values, like($form->{$column}));
687   }
688
689   $main::lxdebug->leave_sub();
690
691   return ($where, @where_values);
692 }
693
694 sub get_num_matches_for_priceupdate {
695   $main::lxdebug->enter_sub();
696
697   my $self     = shift;
698
699   my $myconfig = \%main::myconfig;
700   my $form     = $main::form;
701
702   my $dbh      = $form->get_standard_dbh($myconfig);
703
704   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
705
706   my $num_updated = 0;
707   my $query;
708
709   for my $column (qw(sellprice listprice)) {
710     next if ($form->{$column} eq "");
711
712     $query =
713       qq|SELECT COUNT(*)
714          FROM parts
715          WHERE id IN
716            (SELECT p.id
717             FROM parts p
718             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
719             WHERE $where)|;
720     my ($result)  = selectfirst_array_query($form, $dbh, $query, @where_values);
721     $num_updated += $result if (0 <= $result);
722   }
723
724   $query =
725     qq|SELECT COUNT(*)
726        FROM prices
727        WHERE parts_id IN
728          (SELECT p.id
729           FROM parts p
730           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
731           WHERE $where) AND (pricegroup_id = ?)|;
732   my $sth = prepare_query($form, $dbh, $query);
733
734   for my $i (1 .. $form->{price_rows}) {
735     next if ($form->{"price_$i"} eq "");
736
737     my ($result)  = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
738     $num_updated += $result if (0 <= $result);
739   }
740   $sth->finish();
741
742   $main::lxdebug->leave_sub();
743
744   return $num_updated;
745 }
746
747 sub update_prices {
748   my ($self, $myconfig, $form) = @_;
749   $main::lxdebug->enter_sub();
750
751   my $num_updated = SL::DB->client->with_transaction(\&_update_prices, $self, $myconfig, $form);
752
753   $main::lxdebug->leave_sub();
754   return $num_updated;
755 }
756
757 sub _update_prices {
758   my ($self, $myconfig, $form) = @_;
759
760   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
761   my $num_updated = 0;
762
763   # connect to database
764   my $dbh = SL::DB->client->dbh;
765
766   for my $column (qw(sellprice listprice)) {
767     next if ($form->{$column} eq "");
768
769     my $value = $form->parse_amount($myconfig, $form->{$column});
770     my $operator = '+';
771
772     if ($form->{"${column}_type"} eq "percent") {
773       $value = ($value / 100) + 1;
774       $operator = '*';
775     }
776
777     my $query =
778       qq|UPDATE parts SET $column = $column $operator ?
779          WHERE id IN
780            (SELECT p.id
781             FROM parts p
782             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
783             WHERE $where)|;
784     my $result    = do_query($form, $dbh, $query, $value, @where_values);
785     $num_updated += $result if (0 <= $result);
786   }
787
788   my $q_add =
789     qq|UPDATE prices SET price = price + ?
790        WHERE parts_id IN
791          (SELECT p.id
792           FROM parts p
793           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
794           WHERE $where) AND (pricegroup_id = ?)|;
795   my $sth_add = prepare_query($form, $dbh, $q_add);
796
797   my $q_multiply =
798     qq|UPDATE prices SET price = price * ?
799        WHERE parts_id IN
800          (SELECT p.id
801           FROM parts p
802           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
803           WHERE $where) AND (pricegroup_id = ?)|;
804   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
805
806   for my $i (1 .. $form->{price_rows}) {
807     next if ($form->{"price_$i"} eq "");
808
809     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
810     my $result;
811
812     if ($form->{"pricegroup_type_$i"} eq "percent") {
813       $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
814     } else {
815       $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
816     }
817
818     $num_updated += $result if (0 <= $result);
819   }
820
821   $sth_add->finish();
822   $sth_multiply->finish();
823
824   return $num_updated;
825 }
826
827 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
828 sub get_parts {
829   $main::lxdebug->enter_sub();
830
831   my ($self, $myconfig, $form, $sortorder) = @_;
832   my $dbh   = $form->get_standard_dbh;
833   my $order = qq| p.partnumber|;
834   my $where = qq|1 = 1|;
835   my @values;
836
837   if ($sortorder eq "all") {
838     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
839     push(@values, like($form->{partnumber}), like($form->{description}));
840
841   } elsif ($sortorder eq "partnumber") {
842     $where .= qq| AND (partnumber ILIKE ?)|;
843     push(@values, like($form->{partnumber}));
844
845   } elsif ($sortorder eq "description") {
846     $where .= qq| AND (description ILIKE ?)|;
847     push(@values, like($form->{description}));
848     $order = "description";
849
850   }
851
852   my $query =
853     qq|SELECT id, partnumber, description, unit, sellprice
854        FROM parts
855        WHERE $where ORDER BY $order|;
856
857   my $sth = prepare_execute_query($form, $dbh, $query, @values);
858
859   my $j = 0;
860   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
861     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
862       next;
863     }
864
865     $j++;
866     $form->{"id_$j"}          = $ref->{id};
867     $form->{"partnumber_$j"}  = $ref->{partnumber};
868     $form->{"description_$j"} = $ref->{description};
869     $form->{"unit_$j"}        = $ref->{unit};
870     $form->{"sellprice_$j"}   = $ref->{sellprice};
871     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
872   }    #while
873   $form->{rows} = $j;
874   $sth->finish;
875
876   $main::lxdebug->leave_sub();
877
878   return $self;
879 }    #end get_parts()
880
881 # gets sum of sold part with part_id
882 sub get_soldtotal {
883   $main::lxdebug->enter_sub();
884
885   my ($dbh, $id) = @_;
886
887   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
888   my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
889   $sum ||= 0;
890
891   $main::lxdebug->leave_sub();
892
893   return $sum;
894 }    #end get_soldtotal
895
896 sub follow_account_chain {
897   $main::lxdebug->enter_sub(2);
898
899   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
900
901   my @visited_accno_ids = ($accno_id);
902
903   my ($query, $sth);
904
905   $form->{ACCOUNT_CHAIN_BY_ID} ||= {
906     map { $_->{id} => $_ }
907       selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
908     SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
909     FROM chart c
910     LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
911     WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
912 SQL
913
914   while (1) {
915     my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
916     last unless ($ref && $ref->{"is_valid"} &&
917                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
918     $accno_id = $ref->{"new_chart_id"};
919     $accno = $ref->{"accno"};
920     push(@visited_accno_ids, $accno_id);
921   }
922
923   $main::lxdebug->leave_sub(2);
924
925   return ($accno_id, $accno);
926 }
927
928 sub retrieve_accounts {
929   $main::lxdebug->enter_sub;
930
931   my $self     = shift;
932   my $myconfig = shift;
933   my $form     = shift;
934   my $dbh      = $form->get_standard_dbh;
935   my %args     = @_;     # index => part_id
936
937   $form->{taxzone_id} *= 1;
938
939   return unless grep $_, values %args; # shortfuse if no part_id supplied
940
941   # transdate madness.
942   my $transdate = "";
943   if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
944     # use deliverydate for sales and purchase invoice, if it exists
945     # also use deliverydate for credit notes
946     if (!$form->{deliverydate}) {
947       $transdate = $form->{invdate};
948     } else {
949       $transdate = $form->{deliverydate};
950     }
951   } elsif ($form->{script} eq 'ir.pl') {
952     # when a purchase invoice is opened from the report of purchase invoices
953     # $form->{type} isn't set, but $form->{script} is, not sure why this is or
954     # whether this distinction matters in some other scenario. Otherwise one
955     # could probably take out this elsif and add a
956     # " or $form->{script} eq 'ir.pl' "
957     # to the above if-statement
958     if (!$form->{deliverydate}) {
959       $transdate = $form->{invdate};
960     } else {
961       $transdate = $form->{deliverydate};
962     }
963   } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
964     # if credit_note has a deliverydate, use this instead of invdate
965     # useful for credit_notes of invoices from an old period with different tax
966     # if there is no deliverydate then invdate is used, old default (see next elsif)
967     # Falls hier der Stichtag für Steuern anders bestimmt wird,
968     # entsprechend auch bei Taxkeys.pm anpassen
969     $transdate = $form->{deliverydate};
970   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
971     $transdate = $form->{invdate};
972   } else {
973     $transdate = $form->{transdate};
974   }
975
976   if ($transdate eq "") {
977     $transdate = DateTime->today_local->to_lxoffice;
978   } else {
979     $transdate = $dbh->quote($transdate);
980   }
981   #/transdate
982   my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
983
984   my @part_ids = grep { $_ } values %args;
985   my $in       = join ',', ('?') x @part_ids;
986
987   my %accno_by_part = map { $_->{id} => $_ }
988     selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
989     SELECT
990       p.id, p.part_type,
991       bg.inventory_accno_id,
992       tc.income_accno_id AS income_accno_id,
993       tc.expense_accno_id AS expense_accno_id,
994       c1.accno AS inventory_accno,
995       c2.accno AS income_accno,
996       c3.accno AS expense_accno
997     FROM parts p
998     LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
999     LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
1000     LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1001     LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
1002     LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
1003     WHERE
1004     tc.taxzone_id = '$form->{taxzone_id}'
1005     and
1006     p.id IN ($in)
1007 SQL
1008
1009   my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1010     SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1011     FROM tax t
1012     LEFT JOIN chart c ON c.id = t.chart_id
1013     WHERE t.id IN
1014       (SELECT tk.tax_id
1015        FROM taxkeys tk
1016        WHERE tk.chart_id = ? AND startdate <= ?
1017        ORDER BY startdate DESC LIMIT 1)
1018 SQL
1019
1020   while (my ($index => $part_id) = each %args) {
1021     my $ref = $accno_by_part{$part_id} or next;
1022
1023     $ref->{"inventory_accno_id"} = undef unless $ref->{"part_type"} eq 'part';
1024
1025     my %accounts;
1026     for my $type (qw(inventory income expense)) {
1027       next unless $ref->{"${type}_accno_id"};
1028       ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1029         $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1030     }
1031
1032     $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1033
1034     $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1035     $ref = $sth_tax->fetchrow_hashref or next;
1036
1037     $form->{"taxaccounts_$index"} = $ref->{"accno"};
1038     $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1039
1040     $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1041   }
1042
1043   $sth_tax->finish;
1044
1045   $::lxdebug->leave_sub;
1046 }
1047
1048 sub get_basic_part_info {
1049   $main::lxdebug->enter_sub();
1050
1051   my $self     = shift;
1052   my %params   = @_;
1053
1054   Common::check_params(\%params, qw(id));
1055
1056   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1057
1058   if (!scalar @ids) {
1059     $main::lxdebug->leave_sub();
1060     return ();
1061   }
1062
1063   my $myconfig = \%main::myconfig;
1064   my $form     = $main::form;
1065
1066   my $dbh      = $form->get_standard_dbh($myconfig);
1067
1068   my $query    = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1069
1070   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1071
1072   if ('' eq ref $params{id}) {
1073     $info = $info->[0] || { };
1074
1075     $main::lxdebug->leave_sub();
1076     return $info;
1077   }
1078
1079   my %info_map = map { $_->{id} => $_ } @{ $info };
1080
1081   $main::lxdebug->leave_sub();
1082
1083   return %info_map;
1084 }
1085
1086 sub prepare_parts_for_printing {
1087   $main::lxdebug->enter_sub();
1088
1089   my $self     = shift;
1090   my %params   = @_;
1091
1092   my $myconfig = $params{myconfig} || \%main::myconfig;
1093   my $form     = $params{form}     || $main::form;
1094
1095   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1096
1097   my $prefix   = $params{prefix} || 'id_';
1098   my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1099
1100   my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1101
1102   if (!@part_ids) {
1103     $main::lxdebug->leave_sub();
1104     return;
1105   }
1106
1107   my $placeholders = join ', ', ('?') x scalar(@part_ids);
1108   my $query        = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1109                         FROM makemodel mm
1110                         LEFT JOIN vendor v ON (mm.make = v.id)
1111                         WHERE mm.parts_id IN ($placeholders)|;
1112
1113   my %makemodel    = ();
1114
1115   my $sth          = prepare_execute_query($form, $dbh, $query, @part_ids);
1116
1117   while (my $ref = $sth->fetchrow_hashref()) {
1118     $makemodel{$ref->{parts_id}} ||= [];
1119     push @{ $makemodel{$ref->{parts_id}} }, $ref;
1120   }
1121
1122   $sth->finish();
1123
1124   my @columns = qw(ean image microfiche drawing);
1125
1126   $query      = qq|SELECT id, | . join(', ', @columns) . qq|
1127                    FROM parts
1128                    WHERE id IN ($placeholders)|;
1129
1130   my %data    = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1131
1132   my %template_arrays;
1133   map { $template_arrays{$_} = [] } (qw(make model), @columns);
1134
1135   foreach my $i (1 .. $rowcount) {
1136     my $id = $form->{"${prefix}${i}"};
1137
1138     next if (!$id);
1139
1140     foreach (@columns) {
1141       push @{ $template_arrays{$_} }, $data{$id}->{$_};
1142     }
1143
1144     push @{ $template_arrays{make} },  [];
1145     push @{ $template_arrays{model} }, [];
1146
1147     next if (!$makemodel{$id});
1148
1149     foreach my $ref (@{ $makemodel{$id} }) {
1150       map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model);
1151     }
1152   }
1153
1154   my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
1155   my %parts_by_id = map { $_->id => $_ } @$parts;
1156
1157   for my $i (1..$rowcount) {
1158     my $id = $form->{"${prefix}${i}"};
1159     next unless $id;
1160
1161     push @{ $template_arrays{part_type} },  $parts_by_id{$id}->type;
1162   }
1163
1164   return %template_arrays;
1165   $main::lxdebug->leave_sub();
1166 }
1167
1168 sub normalize_text_blocks {
1169   $main::lxdebug->enter_sub();
1170
1171   my $self     = shift;
1172   my %params   = @_;
1173
1174   my $form     = $params{form}     || $main::form;
1175
1176   # check if feature is enabled (select normalize_part_descriptions from defaults)
1177   return unless ($::instance_conf->get_normalize_part_descriptions);
1178
1179   foreach (qw(description notes)) {
1180     $form->{$_} =~ s/\s+$//s;
1181     $form->{$_} =~ s/^\s+//s;
1182     $form->{$_} =~ s/ {2,}/ /g;
1183   }
1184    $main::lxdebug->leave_sub();
1185 }
1186
1187
1188 1;