1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  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.
 
  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,
 
  30 #======================================================================
 
  32 # Inventory Control backend
 
  34 #======================================================================
 
  39 use List::MoreUtils qw(all any uniq);
 
  44 use SL::HTML::Restrict;
 
  46 use SL::Util qw(trim);
 
  53   $main::lxdebug->enter_sub();
 
  55   my ($self, $myconfig, $form) = @_;
 
  57   my $dbh = $form->get_standard_dbh;
 
  60   my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
 
  61   my $pricegroups = selectall_hashref_query($form, $dbh, $query);
 
  64   foreach my $pg (@{ $pricegroups }) {
 
  65     $form->{"price_$i"}         = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
  66     $form->{"pricegroup_id_$i"} = "$pg->{id}";
 
  67     $form->{"pricegroup_$i"}    = "$pg->{pricegroup}";
 
  72   $form->{price_rows} = $i - 1;
 
  74   $main::lxdebug->leave_sub();
 
  79 sub retrieve_buchungsgruppen {
 
  80   $main::lxdebug->enter_sub();
 
  82   my ($self, $myconfig, $form) = @_;
 
  86   my $dbh = $form->get_standard_dbh;
 
  89   $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
 
  90   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
 
  92   $main::lxdebug->leave_sub();
 
  97   $main::lxdebug->enter_sub();
 
  99   my ($self, $myconfig, $form) = @_;
 
 101   my $i = $form->{assembly_rows};
 
 103   my $where = qq|1 = 1|;
 
 106   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
 
 108   while (my ($column, $table) = each(%columns)) {
 
 109     next unless ($form->{"${column}_$i"});
 
 110     $where .= qq| AND ${table}.${column} ILIKE ?|;
 
 111     push(@values, like($form->{"${column}_$i"}));
 
 115     $where .= qq| AND NOT (p.id = ?)|;
 
 116     push(@values, conv_i($form->{id}));
 
 119   # Search for part ID overrides all other criteria.
 
 120   if ($form->{"id_${i}"}) {
 
 121     $where  = qq|p.id = ?|;
 
 122     @values = ($form->{"id_${i}"});
 
 125   if ($form->{partnumber}) {
 
 126     $where .= qq| ORDER BY p.partnumber|;
 
 128     $where .= qq| ORDER BY p.description|;
 
 132     qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
 
 134        p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
 
 135        p.price_factor_id, pfac.factor AS price_factor, p.notes as longdescription
 
 137        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 138        LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
 
 140   $form->{item_list} = selectall_hashref_query($form, SL::DB->client->dbh, $query, @values);
 
 142   $main::lxdebug->leave_sub();
 
 147 # Warning, deep magic ahead.
 
 148 # This function gets all parts from the database according to the filters specified
 
 151 #   sort revers  - sorting field + direction
 
 154 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
 
 155 #   partnumber ean description partsgroup microfiche drawing
 
 158 #   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
 
 161 #   itemstatus  = active | onhand | short | obsolete | orphaned
 
 162 #   searchitems = part | assembly | service
 
 165 #   make model                               - makemodel
 
 166 #   serialnumber transdatefrom transdateto   - invoice/orderitems
 
 169 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
 
 170 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
 
 171 #   l_soldtotal                              - aggreg join to display total of sold quantity
 
 172 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 173 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
 
 174 #   l_serialnumber                           - belonges to serialnumber filter
 
 175 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
 
 176 #   l_soldtotal                              - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
 
 179 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 181 #   search by overrides of description
 
 183 # disabled sanity checks and changes:
 
 184 #  - searchitems = assembly will no longer disable bought
 
 185 #  - searchitems = service  will no longer disable make and model, although services don't have make/model, it doesn't break the query
 
 186 #  - itemstatus  = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
 
 187 #  - itemstatus  = obsolete will no longer disable onhand, short
 
 188 #  - allow sorting by ean
 
 189 #  - serialnumber filter also works if l_serialnumber isn't ticked
 
 190 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
 
 193   $main::lxdebug->enter_sub();
 
 195   my ($self, $myconfig, $form) = @_;
 
 196   my $dbh = $form->get_standard_dbh($myconfig);
 
 198   $form->{parts}     = +{ };
 
 199   $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
 
 201   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
 
 202   my @project_filters      = qw(projectnumber projectdescription);
 
 203   my @makemodel_filters    = qw(make model);
 
 204   my @invoice_oi_filters   = qw(serialnumber soldtotal);
 
 205   my @apoe_filters         = qw(transdate);
 
 206   my @like_filters         = (@simple_filters, @invoice_oi_filters);
 
 207   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
 
 208   my @simple_l_switches    = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image shop insertdate));
 
 209   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
 
 210   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module qty);
 
 211   my @deliverydate_flags   = qw(deliverydate);
 
 212 #  my @other_flags          = qw(onhand); # ToDO: implement these
 
 213 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
 
 215   my @select_tokens = qw(id factor part_type classification_id);
 
 216   my @where_tokens  = qw(1=1);
 
 217   my @group_tokens  = ();
 
 219   my %joins_needed  = ();
 
 222     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
 
 223     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
 
 224     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
 
 227          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem,         deliverydate, 'invoice'    AS ioi, project_id, id FROM invoice UNION
 
 228          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
 
 229        ) AS ioi ON ioi.parts_id = p.id|,
 
 232          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
 
 233          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
 
 234          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
 
 235        ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
 
 238            SELECT id, name, 'customer' AS cv FROM customer UNION
 
 239            SELECT id, name, 'vendor'   AS cv FROM vendor
 
 240          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
 
 241     mv         => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
 
 242     project    => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
 
 244   my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
 
 247      deliverydate => 'apoe.', serialnumber => 'ioi.',
 
 248      transdate    => 'apoe.', trans_id     => 'ioi.',
 
 249      module       => 'apoe.', name         => 'cv.',
 
 250      ordnumber    => 'apoe.', make         => 'mm.',
 
 251      quonumber    => 'apoe.', model        => 'mm.',
 
 252      invnumber    => 'apoe.', partsgroup   => 'pg.',
 
 253      lastcost     => 'p.',  , soldtotal    => ' ',
 
 254      factor       => 'pfac.', projectnumber => 'pj.',
 
 255      'SUM(ioi.qty)' => ' ',   projectdescription => 'pj.',
 
 258      serialnumber => 'ioi.',
 
 259      quotation    => 'apoe.',
 
 265   # if the join condition in these blocks are met, the column
 
 266   # of the scecified table will gently override (coalesce actually) the original value
 
 267   # use it to conditionally coalesce values from subtables
 
 268   my @column_override = (
 
 269     #  column name,   prefix,  joins_needed,  nick name (in case column is named like another)
 
 270     [ 'description',  'ioi.',  'invoice_oi'  ],
 
 271     [ 'deliverydate', 'ioi.',  'invoice_oi'  ],
 
 272     [ 'transdate',    'apoe.', 'apoe'        ],
 
 273     [ 'unit',         'ioi.',  'invoice_oi'  ],
 
 274     [ 'sellprice',    'ioi.',  'invoice_oi'  ],
 
 277   # careful with renames. these are HARD, and any filters done on the original column will break
 
 278   my %renamed_columns = (
 
 279     'factor'       => 'price_factor',
 
 280     'SUM(ioi.qty)' => 'soldtotal',
 
 281     'ioi.id'       => 'ioi_id',
 
 283     'projectdescription' => 'projectdescription',
 
 284     'insertdate'   => 'insertdate',
 
 288     projectdescription => 'description',
 
 289     insertdate         => 'itime::DATE',
 
 292   if ($form->{l_assembly} && $form->{l_lastcost}) {
 
 293     @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
 
 296   my $make_token_builder = sub {
 
 297     my $joins_needed = shift;
 
 299       my ($nick, $alias) = @_;
 
 300       my ($col) = $real_column{$nick} || $nick;
 
 301       my @coalesce_tokens =
 
 302         map  { ($_->[1] || 'p.') . $_->[0] }
 
 303         grep { !$_->[2] || $joins_needed->{$_->[2]} }
 
 304         grep { ($_->[3] || $_->[0]) eq $nick }
 
 305         @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
 
 307       my $coalesce = scalar @coalesce_tokens > 1;
 
 309         ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
 
 310         : shift                              @coalesce_tokens)
 
 311         . ($alias && ($coalesce || $renamed_columns{$nick})
 
 312         ?  " AS " . ($renamed_columns{$nick} || $nick)
 
 317   #===== switches and simple filters ========#
 
 319   # special case transdate
 
 320   if (grep { trim($form->{$_}) } qw(transdatefrom transdateto)) {
 
 321     $form->{"l_transdate"} = 1;
 
 322     push @select_tokens, 'transdate';
 
 323     for (qw(transdatefrom transdateto)) {
 
 324       my $value = trim($form->{$_});
 
 326       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
 
 327       push @bind_vars,    $value;
 
 331   # special case smart search
 
 333     $form->{"l_$_"} = 1 for qw(partnumber description unit sellprice lastcost cvar_packaging linetotal);
 
 334     push @where_tokens, "p.partnumber ILIKE ? OR p.description ILIKE ?";
 
 335     push @bind_vars,    (like($form->{all})) x 2;
 
 338   # special case insertdate
 
 339   if (grep { trim($form->{$_}) } qw(insertdatefrom insertdateto)) {
 
 340     $form->{"l_insertdate"} = 1;
 
 341     push @select_tokens, 'insertdate';
 
 343     my $token_builder = $make_token_builder->();
 
 344     my $token = $token_builder->('insertdate');
 
 346     for (qw(insertdatefrom insertdateto)) {
 
 347       my $value = trim($form->{$_});
 
 349       push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
 
 350       push @bind_vars,    $value;
 
 354   if ($form->{"partsgroup_id"}) {
 
 355     $form->{"l_partsgroup"} = '1'; # show the column
 
 356     push @where_tokens, "pg.id = ?";
 
 357     push @bind_vars, $form->{"partsgroup_id"};
 
 360   if ($form->{shop} ne '') {
 
 361     $form->{l_shop} = '1'; # show the column
 
 362     if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
 
 363       push @where_tokens, 'NOT p.shop';
 
 366       push @where_tokens, 'p.shop';
 
 370   foreach (@like_filters) {
 
 371     next unless $form->{$_};
 
 372     $form->{"l_$_"} = '1'; # show the column
 
 373     push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
 
 374     push @bind_vars,    like($form->{$_});
 
 377   foreach (@simple_l_switches) {
 
 378     next unless $form->{"l_$_"};
 
 379     push @select_tokens, $_;
 
 382   for ($form->{searchitems}) {
 
 383     push @where_tokens, "p.part_type = 'part'"       if /part/;
 
 384     push @where_tokens, "p.part_type = 'service'"    if /service/;
 
 385     push @where_tokens, "p.part_type = 'assembly'"   if /assembly/;
 
 386     push @where_tokens, "p.part_type = 'assortment'" if /assortment/;
 
 388   if ( $form->{classification_id} > 0 ) {
 
 389     push @where_tokens, "p.classification_id = ?";
 
 390     push @bind_vars, $form->{classification_id};
 
 393   for ($form->{itemstatus}) {
 
 394     push @where_tokens, 'p.id NOT IN
 
 395         (SELECT DISTINCT parts_id FROM invoice UNION
 
 396          SELECT DISTINCT parts_id FROM assembly UNION
 
 397          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
 
 398     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
 
 399     push @where_tokens, 'NOT p.obsolete'               if /active/;
 
 400     push @where_tokens, '    p.obsolete',              if /obsolete/;
 
 401     push @where_tokens, 'p.onhand > 0',                if /onhand/;
 
 402     push @where_tokens, 'p.onhand < p.rop',            if /short/;
 
 405   my $q_assembly_lastcost =
 
 406     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
 
 408         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
 
 409         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
 
 410         WHERE (a_lc.id = p.id)) AS lastcost|;
 
 411   $table_prefix{$q_assembly_lastcost} = ' ';
 
 413   # special case makemodel search
 
 414   # all_parts is based upon the assumption that every parameter is named like the column it represents
 
 415   # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
 
 416   # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
 
 418     push @where_tokens, 'mv.name ILIKE ?';
 
 419     push @bind_vars, like($form->{make});
 
 421   if ($form->{model}) {
 
 422     push @where_tokens, 'mm.model ILIKE ?';
 
 423     push @bind_vars, like($form->{model});
 
 426   # special case: sorting by partnumber
 
 427   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
 
 428   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
 
 429   # ToDO: implement proper functional sorting
 
 430   # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
 
 431   # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
 
 432   #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
 
 433   #  if $form->{sort} eq 'partnumber';
 
 435   #my $order_clause = " ORDER BY $form->{sort} $sort_order";
 
 438   $limit_clause = " LIMIT 100"                   if $form->{top100};
 
 439   $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
 
 441   #=== joins and complicated filters ========#
 
 443   my $bsooqr        = any { $form->{$_} } @oe_flags;
 
 444   my @bsooqr_tokens = ();
 
 446   push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi'  if $bsooqr;
 
 447   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
 
 448   push @select_tokens, $q_assembly_lastcost                                   if $form->{l_assembly} && $form->{l_lastcost};
 
 449   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
 
 450   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
 
 451   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
 
 452   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
 
 453   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
 
 454   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
 
 455   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
 
 457   $joins_needed{partsgroup}  = 1;
 
 458   $joins_needed{pfac}        = 1;
 
 459   $joins_needed{project}     = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
 
 460   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
 
 461   $joins_needed{mv}          = 1 if $joins_needed{makemodel};
 
 462   $joins_needed{cv}          = 1 if $bsooqr;
 
 463   $joins_needed{apoe}        = 1 if $joins_needed{project} || $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
 
 464   $joins_needed{invoice_oi}  = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
 
 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];
 
 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)';
 
 487   #============= build query ================#
 
 489   my $token_builder = $make_token_builder->(\%joins_needed);
 
 491   my @sort_cols    = (@simple_filters, qw(id priceupdate 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');
 
 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 : '';
 
 501   my %oe_flag_to_cvar = (
 
 504     onorder  => 'orderitems',
 
 505     ordered  => 'orderitems',
 
 507     quoted   => 'orderitems',
 
 510   my ($cvar_where, @cvar_values) = CVar->build_filter_query(
 
 512     trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
 
 514     sub_module     => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
 
 518     $where_clause .= qq| AND ($cvar_where)|;
 
 519     push @bind_vars, @cvar_values;
 
 522   my $query = <<"  SQL";
 
 523     SELECT DISTINCT $select_clause
 
 532   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
 
 534   map { $_->{onhand} *= 1 } @{ $form->{parts} };
 
 536   # fix qty sign in ap. those are saved negative
 
 537   if ($bsooqr && $form->{bought}) {
 
 538     for my $row (@{ $form->{parts} }) {
 
 539       $row->{qty} *= -1 if $row->{module} eq 'ir';
 
 543   # post processing for assembly parts lists (bom)
 
 544   # for each part get the assembly parts and add them into the partlist.
 
 546   if ($form->{l_assembly} && $form->{bom}) {
 
 548       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
 
 549            p.unit, p.notes, p.itime::DATE as insertdate,
 
 550            p.sellprice, p.listprice, p.lastcost,
 
 551            p.rop, p.weight, p.priceupdate,
 
 552            p.image, p.drawing, p.microfiche,
 
 555          INNER JOIN assembly a ON (p.id = a.parts_id)
 
 558     my $sth = prepare_query($form, $dbh, $query);
 
 560     foreach my $item (@{ $form->{parts} }) {
 
 561       push(@assemblies, $item);
 
 562       do_statement($form, $sth, $query, conv_i($item->{id}));
 
 564       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 565         $ref->{assemblyitem} = 1;
 
 566         map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
 
 567         push(@assemblies, $ref);
 
 572     # copy assemblies to $form->{parts}
 
 573     $form->{parts} = \@assemblies;
 
 576   if ($form->{l_pricegroups} ) {
 
 578        SELECT parts_id, price, pricegroup_id
 
 583     my $sth = prepare_query($form, $dbh, $query);
 
 585     foreach my $part (@{ $form->{parts} }) {
 
 586       do_statement($form, $sth, $query, conv_i($part->{id}));
 
 588       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 589         $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
 
 595   $main::lxdebug->leave_sub();
 
 597   return @{ $form->{parts} };
 
 600 sub _create_filter_for_priceupdate {
 
 601   $main::lxdebug->enter_sub();
 
 604   my $myconfig = \%main::myconfig;
 
 605   my $form     = $main::form;
 
 610   foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
 
 613     next unless ($form->{$column});
 
 615     $where .= qq| AND $item ILIKE ?|;
 
 616     push(@where_values, like($form->{$column}));
 
 619   foreach my $item (qw(description serialnumber)) {
 
 620     next unless ($form->{$item});
 
 622     $where .= qq| AND (${item} ILIKE ?)|;
 
 623     push(@where_values, like($form->{$item}));
 
 627   # items which were never bought, sold or on an order
 
 628   if ($form->{itemstatus} eq 'orphaned') {
 
 630       qq| AND (p.onhand = 0)
 
 633               SELECT DISTINCT parts_id FROM invoice
 
 635               SELECT DISTINCT parts_id FROM assembly
 
 637               SELECT DISTINCT parts_id FROM orderitems
 
 640   } elsif ($form->{itemstatus} eq 'active') {
 
 641     $where .= qq| AND p.obsolete = '0'|;
 
 643   } elsif ($form->{itemstatus} eq 'obsolete') {
 
 644     $where .= qq| AND p.obsolete = '1'|;
 
 646   } elsif ($form->{itemstatus} eq 'onhand') {
 
 647     $where .= qq| AND p.onhand > 0|;
 
 649   } elsif ($form->{itemstatus} eq 'short') {
 
 650     $where .= qq| AND p.onhand < p.rop|;
 
 654   foreach my $column (qw(make model)) {
 
 655     next unless ($form->{$column});
 
 656     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
 
 657     push(@where_values, like($form->{$column}));
 
 660   $main::lxdebug->leave_sub();
 
 662   return ($where, @where_values);
 
 665 sub get_num_matches_for_priceupdate {
 
 666   $main::lxdebug->enter_sub();
 
 670   my $myconfig = \%main::myconfig;
 
 671   my $form     = $main::form;
 
 673   my $dbh      = $form->get_standard_dbh($myconfig);
 
 675   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
 
 680   for my $column (qw(sellprice listprice)) {
 
 681     next if ($form->{$column} eq "");
 
 689             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 691     my ($result)  = selectfirst_array_query($form, $dbh, $query, @where_values);
 
 692     $num_updated += $result if (0 <= $result);
 
 701           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 702           WHERE $where) AND (pricegroup_id = ?)|;
 
 703   my $sth = prepare_query($form, $dbh, $query);
 
 705   for my $i (1 .. $form->{price_rows}) {
 
 706     next if ($form->{"price_$i"} eq "");
 
 708     my ($result)  = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
 709     $num_updated += $result if (0 <= $result);
 
 713   $main::lxdebug->leave_sub();
 
 719   my ($self, $myconfig, $form) = @_;
 
 720   $main::lxdebug->enter_sub();
 
 722   my $num_updated = SL::DB->client->with_transaction(\&_update_prices, $self, $myconfig, $form);
 
 724   $main::lxdebug->leave_sub();
 
 729   my ($self, $myconfig, $form) = @_;
 
 731   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
 
 734   # connect to database
 
 735   my $dbh = SL::DB->client->dbh;
 
 737   for my $column (qw(sellprice listprice)) {
 
 738     next if ($form->{$column} eq "");
 
 740     my $value = $form->parse_amount($myconfig, $form->{$column});
 
 743     if ($form->{"${column}_type"} eq "percent") {
 
 744       $value = ($value / 100) + 1;
 
 749       qq|UPDATE parts SET $column = $column $operator ?
 
 753             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 755     my $result    = do_query($form, $dbh, $query, $value, @where_values);
 
 756     $num_updated += $result if (0 <= $result);
 
 760     qq|UPDATE prices SET price = price + ?
 
 764           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 765           WHERE $where) AND (pricegroup_id = ?)|;
 
 766   my $sth_add = prepare_query($form, $dbh, $q_add);
 
 769     qq|UPDATE prices SET price = price * ?
 
 773           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 774           WHERE $where) AND (pricegroup_id = ?)|;
 
 775   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
 
 777   for my $i (1 .. $form->{price_rows}) {
 
 778     next if ($form->{"price_$i"} eq "");
 
 780     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
 
 783     if ($form->{"pricegroup_type_$i"} eq "percent") {
 
 784       $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
 786       $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
 789     $num_updated += $result if (0 <= $result);
 
 793   $sth_multiply->finish();
 
 798 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
 
 800   $main::lxdebug->enter_sub();
 
 802   my ($self, $myconfig, $form, $sortorder) = @_;
 
 803   my $dbh   = $form->get_standard_dbh;
 
 804   my $order = qq| p.partnumber|;
 
 805   my $where = qq|1 = 1|;
 
 808   if ($sortorder eq "all") {
 
 809     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
 
 810     push(@values, like($form->{partnumber}), like($form->{description}));
 
 812   } elsif ($sortorder eq "partnumber") {
 
 813     $where .= qq| AND (partnumber ILIKE ?)|;
 
 814     push(@values, like($form->{partnumber}));
 
 816   } elsif ($sortorder eq "description") {
 
 817     $where .= qq| AND (description ILIKE ?)|;
 
 818     push(@values, like($form->{description}));
 
 819     $order = "description";
 
 824     qq|SELECT id, partnumber, description, unit, sellprice,
 
 827        WHERE $where ORDER BY $order|;
 
 829   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
 832   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 833     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
 
 838     $form->{"type_and_classific_$j"} = $::request->presenter->type_abbreviation($ref->{part_type}).
 
 839                                        $::request->presenter->classification_abbreviation($ref->{classification_id});
 
 840     $form->{"id_$j"}          = $ref->{id};
 
 841     $form->{"partnumber_$j"}  = $ref->{partnumber};
 
 842     $form->{"description_$j"} = $ref->{description};
 
 843     $form->{"unit_$j"}        = $ref->{unit};
 
 844     $form->{"sellprice_$j"}   = $ref->{sellprice};
 
 845     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
 
 850   $main::lxdebug->leave_sub();
 
 855 # gets sum of sold part with part_id
 
 857   $main::lxdebug->enter_sub();
 
 861   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
 
 862   my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
 
 865   $main::lxdebug->leave_sub();
 
 870 sub follow_account_chain {
 
 871   $main::lxdebug->enter_sub(2);
 
 873   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
 
 875   my @visited_accno_ids = ($accno_id);
 
 879   $form->{ACCOUNT_CHAIN_BY_ID} ||= {
 
 880     map { $_->{id} => $_ }
 
 881       selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
 
 882     SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
 
 884     LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
 
 885     WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
 
 889     my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
 
 890     last unless ($ref && $ref->{"is_valid"} &&
 
 891                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
 
 892     $accno_id = $ref->{"new_chart_id"};
 
 893     $accno = $ref->{"accno"};
 
 894     push(@visited_accno_ids, $accno_id);
 
 897   $main::lxdebug->leave_sub(2);
 
 899   return ($accno_id, $accno);
 
 902 sub retrieve_accounts {
 
 903   $main::lxdebug->enter_sub;
 
 906   my $myconfig = shift;
 
 908   my $dbh      = $form->get_standard_dbh;
 
 909   my %args     = @_;     # index => part_id
 
 911   $form->{taxzone_id} *= 1;
 
 913   return unless grep $_, values %args; # shortfuse if no part_id supplied
 
 917   if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
 
 918     # use deliverydate for sales and purchase invoice, if it exists
 
 919     # also use deliverydate for credit notes
 
 920     if (!$form->{deliverydate}) {
 
 921       $transdate = $form->{invdate};
 
 923       $transdate = $form->{deliverydate};
 
 925   } elsif ($form->{script} eq 'ir.pl') {
 
 926     # when a purchase invoice is opened from the report of purchase invoices
 
 927     # $form->{type} isn't set, but $form->{script} is, not sure why this is or
 
 928     # whether this distinction matters in some other scenario. Otherwise one
 
 929     # could probably take out this elsif and add a
 
 930     # " or $form->{script} eq 'ir.pl' "
 
 931     # to the above if-statement
 
 932     if (!$form->{deliverydate}) {
 
 933       $transdate = $form->{invdate};
 
 935       $transdate = $form->{deliverydate};
 
 937   } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
 
 938     # if credit_note has a deliverydate, use this instead of invdate
 
 939     # useful for credit_notes of invoices from an old period with different tax
 
 940     # if there is no deliverydate then invdate is used, old default (see next elsif)
 
 941     # Falls hier der Stichtag für Steuern anders bestimmt wird,
 
 942     # entsprechend auch bei Taxkeys.pm anpassen
 
 943     $transdate = $form->{deliverydate};
 
 944   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
 
 945     $transdate = $form->{invdate};
 
 947     $transdate = $form->{transdate};
 
 950   if ($transdate eq "") {
 
 951     $transdate = DateTime->today_local->to_lxoffice;
 
 953     $transdate = $dbh->quote($transdate);
 
 956   my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
 
 958   my @part_ids = grep { $_ } values %args;
 
 959   my $in       = join ',', ('?') x @part_ids;
 
 961   my %accno_by_part = map { $_->{id} => $_ }
 
 962     selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
 
 965       bg.inventory_accno_id,
 
 966       tc.income_accno_id AS income_accno_id,
 
 967       tc.expense_accno_id AS expense_accno_id,
 
 968       c1.accno AS inventory_accno,
 
 969       c2.accno AS income_accno,
 
 970       c3.accno AS expense_accno
 
 972     LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
 
 973     LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
 
 974     LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
 
 975     LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
 
 976     LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
 
 978     tc.taxzone_id = '$form->{taxzone_id}'
 
 983   my $sth_tax = prepare_query($::form, $dbh, <<SQL);
 
 984     SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
 
 986     LEFT JOIN chart c ON c.id = t.chart_id
 
 990        WHERE tk.chart_id = ? AND startdate <= ?
 
 991        ORDER BY startdate DESC LIMIT 1)
 
 994   while (my ($index => $part_id) = each %args) {
 
 995     my $ref = $accno_by_part{$part_id} or next;
 
 997     $ref->{"inventory_accno_id"} = undef unless $ref->{"part_type"} eq 'part';
 
1000     for my $type (qw(inventory income expense)) {
 
1001       next unless $ref->{"${type}_accno_id"};
 
1002       ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
 
1003         $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
 
1006     $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
 
1008     $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
 
1009     $ref = $sth_tax->fetchrow_hashref or next;
 
1011     $form->{"taxaccounts_$index"} = $ref->{"accno"};
 
1012     $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
 
1014     $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
 
1019   $::lxdebug->leave_sub;
 
1022 sub get_basic_part_info {
 
1023   $main::lxdebug->enter_sub();
 
1028   Common::check_params(\%params, qw(id));
 
1030   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
 
1033     $main::lxdebug->leave_sub();
 
1037   my $myconfig = \%main::myconfig;
 
1038   my $form     = $main::form;
 
1040   my $dbh      = $form->get_standard_dbh($myconfig);
 
1042   my $query    = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
 
1044   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
 
1046   if ('' eq ref $params{id}) {
 
1047     $info = $info->[0] || { };
 
1049     $main::lxdebug->leave_sub();
 
1053   my %info_map = map { $_->{id} => $_ } @{ $info };
 
1055   $main::lxdebug->leave_sub();
 
1060 sub prepare_parts_for_printing {
 
1061   $main::lxdebug->enter_sub();
 
1066   my $myconfig = $params{myconfig} || \%main::myconfig;
 
1067   my $form     = $params{form}     || $main::form;
 
1069   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1071   my $prefix   = $params{prefix} || 'id_';
 
1072   my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
 
1074   my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
 
1077     $main::lxdebug->leave_sub();
 
1081   my $placeholders = join ', ', ('?') x scalar(@part_ids);
 
1082   my $query        = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
 
1084                         LEFT JOIN vendor v ON (mm.make = v.id)
 
1085                         WHERE mm.parts_id IN ($placeholders)|;
 
1089   my $sth          = prepare_execute_query($form, $dbh, $query, @part_ids);
 
1091   while (my $ref = $sth->fetchrow_hashref()) {
 
1092     $makemodel{$ref->{parts_id}} ||= [];
 
1093     push @{ $makemodel{$ref->{parts_id}} }, $ref;
 
1098   my @columns = qw(ean image microfiche drawing);
 
1100   $query      = qq|SELECT id, | . join(', ', @columns) . qq|
 
1102                    WHERE id IN ($placeholders)|;
 
1104   my %data    = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
 
1106   my %template_arrays;
 
1107   map { $template_arrays{$_} = [] } (qw(make model), @columns);
 
1109   foreach my $i (1 .. $rowcount) {
 
1110     my $id = $form->{"${prefix}${i}"};
 
1114     foreach (@columns) {
 
1115       push @{ $template_arrays{$_} }, $data{$id}->{$_};
 
1118     push @{ $template_arrays{make} },  [];
 
1119     push @{ $template_arrays{model} }, [];
 
1121     next if (!$makemodel{$id});
 
1123     foreach my $ref (@{ $makemodel{$id} }) {
 
1124       map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model);
 
1128   my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
 
1129   my %parts_by_id = map { $_->id => $_ } @$parts;
 
1131   for my $i (1..$rowcount) {
 
1132     my $id = $form->{"${prefix}${i}"};
 
1134     my $prt = $parts_by_id{$id};
 
1135     my $type_abbr = $::request->presenter->type_abbreviation($prt->part_type);
 
1136     push @{ $template_arrays{part_type} }, $type_abbr;
 
1137     push @{ $template_arrays{type_and_classific}},  $type_abbr.$::request->presenter->classification_abbreviation($prt->classification_id);
 
1140   $main::lxdebug->leave_sub();
 
1141   return %template_arrays;
 
1144 sub normalize_text_blocks {
 
1145   $main::lxdebug->enter_sub();
 
1150   my $form     = $params{form}     || $main::form;
 
1152   # check if feature is enabled (select normalize_part_descriptions from defaults)
 
1153   return unless ($::instance_conf->get_normalize_part_descriptions);
 
1155   foreach (qw(description notes)) {
 
1156     $form->{$_} =~ s/\s+$//s;
 
1157     $form->{$_} =~ s/^\s+//s;
 
1158     $form->{$_} =~ s/ {2,}/ /g;
 
1160    $main::lxdebug->leave_sub();