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