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