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