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