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