]> wagnertech.de Git - mfinanz.git/blob - SL/IC.pm
Merge branch 'master' of http://wagnertech.de/git/mfinanz
[mfinanz.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 | order_locked | 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 notes);
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',  price_factor_description => 'pfac.description as price_factor_description');
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 LATERAL (
205                       SELECT string_agg(mv.vendornumber || ' ' || mv.name, ', ') AS make,
206                              string_agg(mm.model, ', ')                          AS model
207                         FROM makemodel mm
208                              LEFT JOIN vendor mv ON (mv.id = mm.make)
209                       WHERE  mm.parts_id = p.id
210                    ) mm ON TRUE",
211     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
212     invoice_oi =>
213       q|LEFT JOIN (
214          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem,         deliverydate, 'invoice'    AS ioi, project_id, id FROM invoice UNION
215          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
216        ) AS ioi ON ioi.parts_id = p.id|,
217     apoe       =>
218       q|LEFT JOIN (
219          SELECT id, transdate, 'ir' AS module, ordnumber, quonumber,         invnumber, 'purchase_invoice' AS record_type, NULL AS customer_id,         vendor_id,    NULL AS deliverydate, globalproject_id, 'invoice'    AS ioi FROM ap UNION
220          SELECT id, transdate, 'is' AS module, ordnumber, quonumber,         invnumber, 'sales_invoice'    AS record_type,         customer_id, NULL AS vendor_id,            deliverydate, globalproject_id, 'invoice'    AS ioi FROM ar UNION
221          SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber,                       record_type::text,   customer_id,         vendor_id, reqdate AS deliverydate, globalproject_id, 'orderitems' AS ioi FROM oe
222        ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
223     cv         =>
224       q|LEFT JOIN (
225            SELECT id, name, 'customer' AS cv FROM customer UNION
226            SELECT id, name, 'vendor'   AS cv FROM vendor
227          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
228     project    => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
229     warehouse  => 'LEFT JOIN warehouse AS wh ON wh.id = p.warehouse_id',
230     bin        => 'LEFT JOIN bin ON bin.id = p.bin_id',
231   );
232   my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac project warehouse bin);
233
234   my %table_prefix = (
235      deliverydate => 'apoe.', serialnumber => 'ioi.',
236      transdate    => 'apoe.', trans_id     => 'ioi.',
237      module       => 'apoe.', name         => 'cv.',
238      ordnumber    => 'apoe.', make         => 'mm.',
239      quonumber    => 'apoe.', model        => 'mm.',
240      invnumber    => 'apoe.', partsgroup   => 'pg.',
241      lastcost     => 'p.',  , soldtotal    => ' ',
242      factor       => 'pfac.', projectnumber => 'pj.',
243      'SUM(ioi.qty)' => ' ',   projectdescription => 'pj.',
244      description  => 'p.',
245      qty          => 'ioi.',
246      serialnumber => 'ioi.',
247      record_type  => 'apoe.',
248      cv           => 'cv.',
249      "ioi.id"     => ' ',
250      "ioi.ioi"    => ' ',
251   );
252
253   # if the join condition in these blocks are met, the column
254   # of the specified table will gently override (coalesce actually) the original value
255   # use it to conditionally coalesce values from subtables
256   my @column_override = (
257     #  column name,   prefix,  joins_needed,  nick name (in case column is named like another)
258     [ 'description',  'ioi.',  'invoice_oi'  ],
259     [ 'deliverydate', 'ioi.',  'invoice_oi'  ],
260     [ 'transdate',    'apoe.', 'apoe'        ],
261     [ 'unit',         'ioi.',  'invoice_oi'  ],
262     [ 'sellprice',    'ioi.',  'invoice_oi'  ],
263   );
264
265   # careful with renames. these are HARD, and any filters done on the original column will break
266   my %renamed_columns = (
267     'factor'       => 'price_factor',
268     'SUM(ioi.qty)' => 'soldtotal',
269     'ioi.id'       => 'ioi_id',
270     'ioi.ioi'      => 'ioi',
271     'projectdescription' => 'projectdescription',
272     'insertdate'   => 'insertdate',
273   );
274
275   my %real_column = (
276     projectdescription => 'description',
277     insertdate         => 'itime::DATE',
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 linetotal);
318     $form->{l_service}    = 1 if $form->{searchitems} eq 'service'    || $form->{searchitems} eq '';
319     $form->{l_assembly}   = 1 if $form->{searchitems} eq 'assembly'   || $form->{searchitems} eq '';
320     $form->{l_part}       = 1 if $form->{searchitems} eq 'part'       || $form->{searchitems} eq '';
321     $form->{l_assortment} = 1 if $form->{searchitems} eq 'assortment' || $form->{searchitems} eq '';
322     push @where_tokens, "p.partnumber ILIKE ? OR p.description ILIKE ?";
323     push @bind_vars,    (like($form->{all})) x 2;
324   }
325
326   # special case insertdate
327   if (grep { trim($form->{$_}) } qw(insertdatefrom insertdateto)) {
328     $form->{"l_insertdate"} = 1;
329     push @select_tokens, 'insertdate';
330
331     my $token_builder = $make_token_builder->();
332     my $token = $token_builder->('insertdate');
333
334     for (qw(insertdatefrom insertdateto)) {
335       my $value = trim($form->{$_});
336       next unless $value;
337       push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
338       push @bind_vars,    $value;
339     }
340   }
341
342   if ($form->{"partsgroup_id"}) {
343     $form->{"l_partsgroup"} = '1'; # show the column
344     push @where_tokens, "pg.id = ?";
345     push @bind_vars, $form->{"partsgroup_id"};
346   }
347
348   if ($form->{shop} ne '') {
349     $form->{l_shop} = '1'; # show the column
350     if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
351       push @where_tokens, 'NOT p.shop';
352       $form->{shop} = 'f';
353     } else {
354       push @where_tokens, 'p.shop';
355     }
356   }
357
358   foreach (@like_filters) {
359     next unless $form->{$_};
360     $form->{"l_$_"} = '1'; # show the column
361     push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
362     push @bind_vars,    like($form->{$_});
363   }
364
365   foreach (@simple_l_switches) {
366     next unless $form->{"l_$_"};
367     push @select_tokens, $_;
368   }
369
370   # Oder Bedingungen fuer Ware Dienstleistung Erzeugnis:
371   if ($form->{l_part} || $form->{l_assembly} || $form->{l_service} || $form->{l_assortment}) {
372       my @or_tokens = ();
373       push @or_tokens, "p.part_type = 'service'"    if $form->{l_service};
374       push @or_tokens, "p.part_type = 'assembly'"   if $form->{l_assembly};
375       push @or_tokens, "p.part_type = 'part'"       if $form->{l_part};
376       push @or_tokens, "p.part_type = 'assortment'" if $form->{l_assortment};
377       push @where_tokens, join ' OR ', map { "($_)" } @or_tokens;
378   }
379   else {
380       # gar keine Teile
381       push @where_tokens, q|'F' = 'T'|;
382   }
383
384   if ( $form->{classification_id} > 0 ) {
385     push @where_tokens, "p.classification_id = ?";
386     push @bind_vars, $form->{classification_id};
387   }
388
389   for ($form->{itemstatus}) {
390     push @where_tokens, 'p.id NOT IN
391         (SELECT DISTINCT parts_id FROM invoice UNION
392          SELECT DISTINCT parts_id FROM assembly UNION
393          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
394     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
395     push @where_tokens, 'NOT p.obsolete'               if /active/;
396     push @where_tokens, '    p.obsolete',              if /obsolete/;
397     push @where_tokens, 'p.onhand > 0',                if /onhand/;
398     push @where_tokens, 'p.onhand < p.rop',            if /short/;
399     push @where_tokens, 'p.order_locked',              if /order_locked/;
400   }
401
402   my $q_assembly_lastcost =
403     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
404         FROM assembly a_lc
405         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
406         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
407         WHERE (a_lc.id = p.id)) AS assembly_lastcost|;
408   $table_prefix{$q_assembly_lastcost} = ' ';
409
410   # special case makemodel search
411   # all_parts is based upon the assumption that every parameter is named like the column it represents
412   # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
413   # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
414   # the lateral join mm already creates a string consisting of vendornumbers and vendornames in mm.make
415   # and the models in mm.make
416   if ($form->{make}) {
417     push @where_tokens, 'mm.make ILIKE ?';
418     push @bind_vars, like($form->{make});
419   }
420   if ($form->{model}) {
421     push @where_tokens, 'mm.model ILIKE ?';
422     push @bind_vars, like($form->{model});
423   }
424
425   # special case: sorting by partnumber
426   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
427   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
428   # ToDO: implement proper functional sorting
429   # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
430   # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
431   #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
432   #  if $form->{sort} eq 'partnumber';
433
434   #my $order_clause = " ORDER BY $form->{sort} $sort_order";
435
436   my $limit_clause;
437   $limit_clause = " LIMIT 100"                   if $form->{top100};
438   $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
439
440   #=== joins and complicated filters ========#
441
442   my $bsooqr        = any { $form->{$_} } @oe_flags;
443   my @bsooqr_tokens = ();
444
445   push @select_tokens, @qsooqr_flags, 'record_type', 'cv', 'ioi.id', 'ioi.ioi'  if $bsooqr;
446   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
447   push @select_tokens, $q_assembly_lastcost                                   if $form->{l_assembly} && $form->{l_lastcost};
448   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
449   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
450   push @bsooqr_tokens, q|module = 'oe' AND record_type = 'sales_order'|       if $form->{ordered};
451   push @bsooqr_tokens, q|module = 'oe' AND record_type = 'purchase_order'|    if $form->{onorder};
452   push @bsooqr_tokens, q|module = 'oe' AND record_type = 'sales_quotation'|   if $form->{quoted};
453   push @bsooqr_tokens, q|module = 'oe' AND record_type = 'request_quotation'| if $form->{rfq};
454   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
455
456   $joins_needed{partsgroup}  = 1;
457   $joins_needed{pfac}        = 1;
458   $joins_needed{project}     = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
459   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
460   $joins_needed{cv}          = 1 if $bsooqr;
461   $joins_needed{apoe}        = 1 if $joins_needed{project} || $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
462   $joins_needed{invoice_oi}  = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
463   $joins_needed{bin}         = 1 if $form->{l_bin};
464   $joins_needed{warehouse}   = 1 if $form->{l_warehouse};
465
466   # special case for description search.
467   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
468   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
469   # find the old entries in of @where_tokens and @bind_vars, and adjust them
470   if ($joins_needed{invoice_oi}) {
471     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
472       next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
473       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
474       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
475       last;
476     }
477   }
478
479   # now the master trick: soldtotal.
480   if ($form->{l_soldtotal}) {
481     push @where_tokens, 'NOT ioi.qty = 0';
482     push @group_tokens, @select_tokens;
483      map { s/.*\sAS\s+//si } @group_tokens;
484     push @select_tokens, 'SUM(ioi.qty)';
485   }
486
487   #============= build query ================#
488
489   my $token_builder = $make_token_builder->(\%joins_needed);
490
491   my @sort_cols    = (@simple_filters, qw(id onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
492      $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
493   my $sort_order   = ($form->{revers} ? ' DESC' : ' ASC');
494   my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
495
496   my $select_clause = join ', ',    map { $token_builder->($_, 1) } @select_tokens;
497   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
498   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
499   my $group_clause  = @group_tokens ? ' GROUP BY ' . join ', ',    map { $token_builder->($_) } @group_tokens : '';
500
501   # key of %no_simple_l_switch is the logical l_switch.
502   # the assigned value is the 'not so simple
503   # select token'
504   my $no_simple_select_clause;
505   foreach my $no_simple_l_switch (keys %no_simple_l_switches) {
506     next unless $form->{"l_${no_simple_l_switch}"};
507     $no_simple_select_clause .= ', '. $no_simple_l_switches{$no_simple_l_switch};
508   }
509   $select_clause .= $no_simple_select_clause;
510
511   my %oe_flag_to_cvar = (
512     bought   => 'invoice',
513     sold     => 'invoice',
514     onorder  => 'orderitems',
515     ordered  => 'orderitems',
516     rfq      => 'orderitems',
517     quoted   => 'orderitems',
518   );
519
520   my ($cvar_where, @cvar_values) = CVar->build_filter_query(
521     module         => 'IC',
522     trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
523     filter         => $form,
524     sub_module     => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
525   );
526
527   if ($cvar_where) {
528     $where_clause .= qq| AND ($cvar_where)|;
529     push @bind_vars, @cvar_values;
530   }
531
532   # simple search for assemblies by items used in assemblies
533   if ($form->{bom} eq '2' && $form->{l_assembly}) {
534     # assembly_qty is the column name
535     $form->{l_assembly_qty} = 1;
536     # nuke where clause and bind vars
537     $where_clause = ' 1=1 AND p.id in (SELECT id from assembly where parts_id IN ' .
538                     ' (select id from parts where 1=1';
539     @bind_vars    = ();
540     # use only like filter for items used in assemblies
541     foreach (@like_filters) {
542       next unless $form->{$_};
543       $form->{"l_$_"} = '1'; # show the column
544       $where_clause .= " AND $_ ILIKE ? ";
545       push @bind_vars,    like($form->{$_});
546     }
547     $where_clause .='))';
548   }
549
550   my $query = <<"  SQL";
551     SELECT DISTINCT $select_clause
552     FROM parts p
553     $join_clause
554     WHERE $where_clause
555     $group_clause
556     $order_clause
557     $limit_clause
558   SQL
559   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
560
561   map { $_->{onhand} *= 1 } @{ $form->{parts} };
562
563   # fix qty sign in ap. those are saved negative
564   if ($bsooqr && $form->{bought}) {
565     for my $row (@{ $form->{parts} }) {
566       $row->{qty} *= -1 if $row->{module} eq 'ir';
567     }
568   }
569
570   # post processing for assembly parts lists (bom)
571   # for each part get the assembly parts and add them into the partlist.
572   my @assemblies;
573   if ($form->{l_assembly} && $form->{bom}) {
574     $query =
575       qq|SELECT p.id, p.partnumber, p.description, a.qty AS assembly_qty,
576            p.unit, p.notes, p.itime::DATE as insertdate,
577            p.sellprice, p.listprice, p.lastcost,
578            p.rop, p.weight,
579            p.image, p.drawing, p.microfiche,
580            pfac.factor
581          FROM parts p
582          INNER JOIN assembly a ON (p.id = a.parts_id)
583          $joins{pfac}
584          WHERE a.id = ?|;
585     my $sth = prepare_query($form, $dbh, $query);
586
587     foreach my $item (@{ $form->{parts} }) {
588       push(@assemblies, $item);
589       do_statement($form, $sth, $query, conv_i($item->{id}));
590
591       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
592         $ref->{assemblyitem} = 1;
593         map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
594         push(@assemblies, $ref);
595       }
596       $sth->finish;
597     }
598
599     # copy assemblies to $form->{parts}
600     $form->{parts} = \@assemblies;
601   }
602
603   if ($form->{l_pricegroups} ) {
604     my $query = <<SQL;
605        SELECT parts_id, price, pricegroup_id
606        FROM prices
607        WHERE parts_id = ?
608 SQL
609
610     my $sth = prepare_query($form, $dbh, $query);
611
612     foreach my $part (@{ $form->{parts} }) {
613       do_statement($form, $sth, $query, conv_i($part->{id}));
614
615       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
616         $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
617       }
618       $sth->finish;
619     }
620   }
621
622   $main::lxdebug->leave_sub();
623
624   return $form->{parts};
625 }
626
627 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
628 sub get_parts {
629   $main::lxdebug->enter_sub();
630
631   my ($self, $myconfig, $form, $sortorder) = @_;
632   my $dbh   = $form->get_standard_dbh;
633   my $order = qq| p.partnumber|;
634   my $where = qq|1 = 1|;
635   my @values;
636
637   if ($sortorder eq "all") {
638     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
639     push(@values, like($form->{partnumber}), like($form->{description}));
640
641   } elsif ($sortorder eq "partnumber") {
642     $where .= qq| AND (partnumber ILIKE ?)|;
643     push(@values, like($form->{partnumber}));
644
645   } elsif ($sortorder eq "description") {
646     $where .= qq| AND (description ILIKE ?)|;
647     push(@values, like($form->{description}));
648     $order = "description";
649
650   }
651
652   my $query =
653     qq|SELECT id, partnumber, description, unit, sellprice,
654        classification_id
655        FROM parts
656        WHERE $where ORDER BY $order|;
657
658   my $sth = prepare_execute_query($form, $dbh, $query, @values);
659
660   my $j = 0;
661   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
662     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
663       next;
664     }
665
666     $j++;
667     $form->{"type_and_classific_$j"} = type_abbreviation($ref->{part_type}).
668                                        classification_abbreviation($ref->{classification_id});
669     $form->{"id_$j"}          = $ref->{id};
670     $form->{"partnumber_$j"}  = $ref->{partnumber};
671     $form->{"description_$j"} = $ref->{description};
672     $form->{"unit_$j"}        = $ref->{unit};
673     $form->{"sellprice_$j"}   = $ref->{sellprice};
674     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
675   }    #while
676   $form->{rows} = $j;
677   $sth->finish;
678
679   $main::lxdebug->leave_sub();
680
681   return $self;
682 }    #end get_parts()
683
684 # gets sum of sold part with part_id
685 sub get_soldtotal {
686   $main::lxdebug->enter_sub();
687
688   my ($dbh, $id) = @_;
689
690   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
691   my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
692   $sum ||= 0;
693
694   $main::lxdebug->leave_sub();
695
696   return $sum;
697 }    #end get_soldtotal
698
699 sub follow_account_chain {
700   $main::lxdebug->enter_sub(2);
701
702   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
703
704   my @visited_accno_ids = ($accno_id);
705
706   my ($query, $sth);
707
708   $form->{ACCOUNT_CHAIN_BY_ID} ||= {
709     map { $_->{id} => $_ }
710       selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
711     SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
712     FROM chart c
713     LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
714     WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
715 SQL
716
717   while (1) {
718     my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
719     last unless ($ref && $ref->{"is_valid"} &&
720                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
721     $accno_id = $ref->{"new_chart_id"};
722     $accno = $ref->{"accno"};
723     push(@visited_accno_ids, $accno_id);
724   }
725
726   $main::lxdebug->leave_sub(2);
727
728   return ($accno_id, $accno);
729 }
730
731 sub retrieve_accounts {
732   $main::lxdebug->enter_sub;
733
734   my $self     = shift;
735   my $myconfig = shift;
736   my $form     = shift;
737   my $dbh      = $form->get_standard_dbh;
738   my %args     = @_;     # index => part_id
739
740   $form->{taxzone_id} *= 1;
741
742   return unless grep $_, values %args; # shortfuse if no part_id supplied
743
744   # transdate madness.
745   my $transdate = "";
746   if ( (any {$form->{type} eq $_} qw(invoice credit_note invoice_for_advance_payment final_invoice)) or ($form->{script} eq 'ir.pl') ) {
747     # use deliverydate for sales and purchase invoice, if it exists
748     # also use deliverydate for credit notes
749     $transdate = $form->{tax_point} || $form->{deliverydate} || $form->{invdate};
750   } else {
751     my $deliverydate;
752     $deliverydate = $form->{reqdate} if any { $_ eq $form->{type} } qw(sales_order request_quotation purchase_order);
753     $transdate = $form->{tax_point} || $deliverydate || $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.id as tax_id, t.rate,
791            c.accno as taxnumber
792     FROM tax t
793     LEFT JOIN chart c ON c.id = t.chart_id
794     WHERE t.id IN
795       (SELECT tk.tax_id
796        FROM taxkeys tk
797        WHERE tk.chart_id = ? AND startdate <= ?
798        ORDER BY startdate DESC LIMIT 1)
799 SQL
800   my $sth_tax = prepare_query($::form, $dbh, $query_tax);
801
802   while (my ($index => $part_id) = each %args) {
803     my $ref = $accno_by_part{$part_id} or next;
804
805     $ref->{"inventory_accno_id"} = undef unless $ref->{"part_type"} eq 'part';
806
807     my %accounts;
808     for my $type (qw(inventory income expense)) {
809       next unless $ref->{"${type}_accno_id"};
810       ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
811         $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
812     }
813
814     $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
815     $form->{"${_}_accno_id_$index"} = $accounts{"${_}_accno_id"} for qw(inventory expense); # only for purchase_invoice
816
817     $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate)) || $::form->dberror($query_tax);
818     my $tax_ref;
819     $tax_ref = $sth_tax->fetchrow_hashref or next;
820
821     $form->{"expense_accno_tax_id_$index"} = $tax_ref->{tax_id}; # only for purchase_invoice
822
823     $form->{"taxaccounts_$index"} = $tax_ref->{"accno"};
824     $form->{"taxaccounts"} .= "$tax_ref->{accno} "if $form->{"taxaccounts"} !~ /$tax_ref->{accno}/;
825
826     $form->{"$tax_ref->{accno}_${_}"} = $tax_ref->{$_} for qw(rate description taxnumber tax_id);
827   }
828
829   $sth_tax->finish;
830
831   $::lxdebug->leave_sub;
832 }
833
834 sub get_basic_part_info {
835   $main::lxdebug->enter_sub();
836
837   my $self     = shift;
838   my %params   = @_;
839
840   Common::check_params(\%params, qw(id));
841
842   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
843
844   if (!scalar @ids) {
845     $main::lxdebug->leave_sub();
846     return ();
847   }
848
849   my $myconfig = \%main::myconfig;
850   my $form     = $main::form;
851
852   my $dbh      = $form->get_standard_dbh($myconfig);
853
854   my $query    = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
855
856   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
857
858   if ('' eq ref $params{id}) {
859     $info = $info->[0] || { };
860
861     $main::lxdebug->leave_sub();
862     return $info;
863   }
864
865   my %info_map = map { $_->{id} => $_ } @{ $info };
866
867   $main::lxdebug->leave_sub();
868
869   return %info_map;
870 }
871
872 sub prepare_parts_for_printing {
873   $main::lxdebug->enter_sub();
874
875   my $self     = shift;
876   my %params   = @_;
877
878   my $myconfig = $params{myconfig} || \%main::myconfig;
879   my $form     = $params{form}     || $main::form;
880
881   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
882
883   my $prefix   = $params{prefix} || 'id_';
884   my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
885
886   my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
887
888   if (!@part_ids) {
889     $main::lxdebug->leave_sub();
890     return;
891   }
892
893   my $placeholders = join ', ', ('?') x scalar(@part_ids);
894   my $query        = qq|SELECT mm.parts_id, mm.model,
895                         mm.part_description AS mm_part_description,
896                         mm.part_longdescription AS mm_part_longdescription,
897                         mm.lastcost, v.name AS make
898                         FROM makemodel mm
899                         LEFT JOIN vendor v ON (mm.make = v.id)
900                         WHERE mm.parts_id IN ($placeholders)|;
901
902   my %makemodel    = ();
903
904   my $sth          = prepare_execute_query($form, $dbh, $query, @part_ids);
905
906   while (my $ref = $sth->fetchrow_hashref()) {
907     $makemodel{$ref->{parts_id}} ||= [];
908     push @{ $makemodel{$ref->{parts_id}} }, $ref;
909   }
910
911   $sth->finish();
912
913
914   $query            = qq|SELECT bm.parts_id,
915                          bm.model                AS business_model,
916                          bm.part_description     AS bm_part_description,
917                          bm.part_longdescription AS bm_part_longdescription,
918                          b.description           AS business_make
919                          FROM business_models bm
920                          LEFT JOIN business b ON (bm.business_id = b.id)
921                          WHERE bm.parts_id IN ($placeholders)|;
922
923   my %businessmodel = ();
924
925   $sth              = prepare_execute_query($form, $dbh, $query, @part_ids);
926
927   while (my $ref = $sth->fetchrow_hashref()) {
928     $businessmodel{$ref->{parts_id}} ||= [];
929     push @{ $businessmodel{$ref->{parts_id}} }, $ref;
930   }
931
932   $sth->finish();
933
934   $query           = qq|SELECT
935                         cp.parts_id,
936                         cp.customer_partnumber  AS customer_model,
937                         cp.part_description     AS cm_part_description,
938                         cp.part_longdescription AS cm_part_longdescription,
939                         c.name                  AS customer_make
940                         FROM part_customer_prices cp
941                         LEFT JOIN customer c ON (cp.customer_id = c.id)
942                         WHERE cp.parts_id IN ($placeholders)|;
943
944   my %customermodel = ();
945
946   $sth              = prepare_execute_query($form, $dbh, $query, @part_ids);
947
948   while (my $ref = $sth->fetchrow_hashref()) {
949     $customermodel{$ref->{parts_id}} ||= [];
950     push @{ $customermodel{$ref->{parts_id}} }, $ref;
951   }
952
953   $sth->finish();
954
955   my @columns = qw(ean image microfiche drawing tariff_code);
956
957   $query      = qq|SELECT id, | . join(', ', @columns) . qq|
958                    FROM parts
959                    WHERE id IN ($placeholders)|;
960
961   my %data    = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
962
963   my %template_arrays;
964   map { $template_arrays{$_} = [] } (qw(make model mm_part_description mm_part_longdescription business_make business_model bm_part_description bm_part_longdescription customer_make customer_model cm_part_description cm_part_longdescription), @columns);
965
966   foreach my $i (1 .. $rowcount) {
967     my $id = $form->{"${prefix}${i}"};
968
969     next if (!$id);
970
971     foreach (@columns) {
972       push @{ $template_arrays{$_} }, $data{$id}->{$_};
973     }
974
975     push @{ $template_arrays{make} },  [];
976     push @{ $template_arrays{model} }, [];
977     push @{ $template_arrays{mm_part_description} },     [];
978     push @{ $template_arrays{mm_part_longdescription} }, [];
979
980     if ($makemodel{$id}) {
981       foreach my $ref (@{ $makemodel{$id} }) {
982         map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model mm_part_description mm_part_longdescription);
983       }
984     }
985
986     push @{ $template_arrays{business_make} },           [];
987     push @{ $template_arrays{business_model} },          [];
988     push @{ $template_arrays{bm_part_description} },     [];
989     push @{ $template_arrays{bm_part_longdescription} }, [];
990
991     if ($businessmodel{$id}) {
992       foreach my $ref (@{ $businessmodel{$id} }) {
993         map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(business_make business_model bm_part_description bm_part_longdescription);
994       }
995     }
996
997     push @{ $template_arrays{customer_make} },  [];
998     push @{ $template_arrays{customer_model} }, [];
999     push @{ $template_arrays{cm_part_description} },     [];
1000     push @{ $template_arrays{cm_part_longdescription} }, [];
1001
1002     if ($customermodel{$id}) {
1003       foreach my $ref (@{ $customermodel{$id} }) {
1004         push @{ $template_arrays{$_}->[-1] }, $ref->{$_} for qw(customer_make customer_model cm_part_description cm_part_longdescription);
1005       }
1006     }
1007
1008   }
1009
1010   my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
1011   my %parts_by_id = map { $_->id => $_ } @$parts;
1012
1013   for my $i (1..$rowcount) {
1014     my $id = $form->{"${prefix}${i}"};
1015     next unless $id;
1016     my $prt = $parts_by_id{$id};
1017     my $type_abbr = type_abbreviation($prt->part_type);
1018     push @{ $template_arrays{part_type}         }, $prt->part_type;
1019     push @{ $template_arrays{part_abbreviation} }, $type_abbr;
1020     push @{ $template_arrays{type_and_classific}}, $type_abbr . classification_abbreviation($prt->classification_id);
1021     push @{ $template_arrays{separate}  }, separate_abbreviation($prt->classification_id);
1022   }
1023
1024   $main::lxdebug->leave_sub();
1025   return %template_arrays;
1026 }
1027
1028 1;