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., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  29 #======================================================================
 
  31 # Inventory Control backend
 
  33 #======================================================================
 
  38 use List::MoreUtils qw(all any uniq);
 
  43 use SL::HTML::Restrict;
 
  45 use SL::Util qw(trim);
 
  50   $main::lxdebug->enter_sub();
 
  52   my ($self, $myconfig, $form) = @_;
 
  55   my $dbh = $form->get_standard_dbh;
 
  61          c1.accno AS inventory_accno,
 
  62          c2.accno AS income_accno,
 
  63          c3.accno AS expense_accno,
 
  66        LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
 
  67        LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
 
  68        LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
 
  69        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
  71   my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
  73   # copy to $form variables
 
  74   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
 
  76   $form->{mtime} = $form->{itime} if !$form->{mtime};
 
  77   $form->{lastmtime} = $form->{mtime};
 
  80   # part or service item
 
  81   $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
 
  82   if ($form->{assembly}) {
 
  83     $form->{item} = 'assembly';
 
  85     # retrieve assembly items
 
  87       qq|SELECT p.id, p.partnumber, p.description,
 
  88            p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
 
  89            pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
 
  91          JOIN assembly a ON (a.parts_id = p.id)
 
  92          LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
  93          LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
 
  96     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
  98     $form->{assembly_rows} = 0;
 
  99     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 100       $form->{assembly_rows}++;
 
 101       foreach my $key (keys %{$ref}) {
 
 102         $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
 
 109   # setup accno hash for <option checked> {amount} is used in create_links
 
 110   $form->{amount}{IC}         = $form->{inventory_accno};
 
 111   $form->{amount}{IC_income}  = $form->{income_accno};
 
 112   $form->{amount}{IC_sale}    = $form->{income_accno};
 
 113   $form->{amount}{IC_expense} = $form->{expense_accno};
 
 114   $form->{amount}{IC_cogs}    = $form->{expense_accno};
 
 118     SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
 
 120     LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
 
 121     ORDER BY lower(pg.pricegroup)
 
 125   foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
 
 126     $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
 
 129   $form->{price_rows} = $row - 1;
 
 132   if ($form->{makemodel}) {
 
 134     $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
 
 135              qq|WHERE m.parts_id = ? order by m.sortorder asc|;
 
 136     my @values = ($form->{id});
 
 137     $sth = $dbh->prepare($query);
 
 138     $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
 
 142     while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
 
 143               $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
 
 148     $form->{makemodel_rows} = $i - 1;
 
 153   $query = qq|SELECT language_id, translation, longdescription
 
 156   $form->{translations} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
 159   my @referencing_tables = qw(invoice orderitems inventory);
 
 160   my %column_map         = ( );
 
 161   my $parts_id           = conv_i($form->{id});
 
 163   $form->{orphaned}      = 1;
 
 165   foreach my $table (@referencing_tables) {
 
 166     my $column  = $column_map{$table} || 'parts_id';
 
 167     $query      = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
 
 168     my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
 
 171       $form->{orphaned} = 0;
 
 176   $form->{"unit_changeable"} = $form->{orphaned};
 
 178   Common::webdav_folder($form) if $::lx_office_conf{features}{webdav};
 
 180   $main::lxdebug->leave_sub();
 
 183 sub get_pricegroups {
 
 184   $main::lxdebug->enter_sub();
 
 186   my ($self, $myconfig, $form) = @_;
 
 188   my $dbh = $form->get_standard_dbh;
 
 191   my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
 
 192   my $pricegroups = selectall_hashref_query($form, $dbh, $query);
 
 195   foreach my $pg (@{ $pricegroups }) {
 
 196     $form->{"klass_$i"} = "$pg->{id}";
 
 197     $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
 198     $form->{"pricegroup_id_$i"} = "$pg->{id}";
 
 199     $form->{"pricegroup_$i"}    = "$pg->{pricegroup}";
 
 204   $form->{price_rows} = $i - 1;
 
 206   $main::lxdebug->leave_sub();
 
 211 sub retrieve_buchungsgruppen {
 
 212   $main::lxdebug->enter_sub();
 
 214   my ($self, $myconfig, $form) = @_;
 
 218   my $dbh = $form->get_standard_dbh;
 
 220   # get buchungsgruppen
 
 221   $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
 
 222   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
 
 224   $main::lxdebug->leave_sub();
 
 228   $main::lxdebug->enter_sub();
 
 230   my ($self, $myconfig, $form) = @_;
 
 232   # connect to database, turn off AutoCommit
 
 233   my $dbh = $form->get_standard_dbh;
 
 234   my $restricter = SL::HTML::Restrict->create;
 
 237   # make up a unique handle and store in partnumber field
 
 238   # then retrieve the record based on the unique handle to get the id
 
 239   # replace the partnumber field with the actual variable
 
 240   # add records for makemodel
 
 242   # if there is a $form->{id} then replace the old entry
 
 243   # delete all makemodel entries and add the new ones
 
 245   # undo amount formatting
 
 246   map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
 
 247     qw(rop weight listprice sellprice gv lastcost);
 
 249   my $makemodel = ($form->{make_1} || $form->{model_1} || ($form->{makemodel_rows} > 1)) ? 1 : 0;
 
 251   $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
 
 255   my $priceupdate = ', priceupdate = current_date';
 
 258     my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
 
 259     if (!$trans_number->is_unique) {
 
 260       $::lxdebug->leave_sub;
 
 265     $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
 
 266     my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
 
 268     # if item is part of an assembly adjust all assemblies
 
 269     $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
 
 270     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 271     while (my ($id, $qty) = $sth->fetchrow_array) {
 
 272       &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
 
 276     # delete makemodel records
 
 277     do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
 
 279     if ($form->{item} eq 'assembly') {
 
 280       # delete assembly records
 
 281       do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
 
 284     # delete translations
 
 285     do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
 
 287     # Check whether or not the prices have changed. If they haven't
 
 288     # then 'priceupdate' should not be updated.
 
 289     my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
 
 290     $priceupdate        = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
 
 293     my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
 
 295     if ($form->{partnumber} && !$trans_number->is_unique) {
 
 296       $::lxdebug->leave_sub;
 
 300     $form->{partnumber} ||= $trans_number->create_unique;
 
 302     ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
 
 303     do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit});
 
 305     $form->{orphaned} = 1;
 
 307   my $partsgroup_id = undef;
 
 309   if ($form->{partsgroup}) {
 
 310     (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
 
 313   my ($subq_inventory, $subq_expense, $subq_income);
 
 314   if ($form->{"item"} eq "part") {
 
 316       qq|(SELECT bg.inventory_accno_id
 
 317           FROM buchungsgruppen bg
 
 318           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 320     $subq_inventory = "NULL";
 
 323   if ($form->{"item"} ne "assembly") {
 
 325       qq|(SELECT tc.expense_accno_id
 
 326           FROM taxzone_charts tc
 
 327           WHERE tc.buchungsgruppen_id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq| and tc.taxzone_id = 0)|;
 
 329     $subq_expense = "NULL";
 
 332   normalize_text_blocks();
 
 351          buchungsgruppen_id = ?,
 
 353          inventory_accno_id = $subq_inventory,
 
 354          income_accno_id = (SELECT tc.income_accno_id FROM taxzone_charts tc WHERE tc.taxzone_id = 0 and tc.buchungsgruppen_id = ?),
 
 355          expense_accno_id = $subq_expense,
 
 364          not_discountable = ?,
 
 370   @values = ($form->{partnumber},
 
 371              $form->{description},
 
 372              $makemodel ? 't' : 'f',
 
 373              $form->{assembly} ? 't' : 'f',
 
 379              $restricter->process($form->{notes}),
 
 382              conv_i($form->{warehouse_id}),
 
 383              conv_i($form->{bin_id}),
 
 384              conv_i($form->{buchungsgruppen_id}),
 
 385              conv_i($form->{payment_id}),
 
 386              conv_i($form->{buchungsgruppen_id}),
 
 387              $form->{obsolete} ? 't' : 'f',
 
 390              $form->{shop} ? 't' : 'f',
 
 394              $form->{has_sernumber} ? 't' : 'f',
 
 395              $form->{not_discountable} ? 't' : 'f',
 
 397              conv_i($partsgroup_id),
 
 398              conv_i($form->{price_factor_id}),
 
 401   do_query($form, $dbh, $query, @values);
 
 403   $form->new_lastmtime('parts');
 
 405   # delete translation records
 
 406   do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
 
 408   my @translations = grep { $_->{language_id} && $_->{translation} } @{ $form->{translations} || [] };
 
 410     $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
 
 411                 VALUES ( ?, ?, ?, ? )|;
 
 412     $sth   = $dbh->prepare($query);
 
 414     foreach my $translation (@translations) {
 
 415       do_statement($form, $sth, $query, conv_i($form->{id}), conv_i($translation->{language_id}), $translation->{translation}, $restricter->process($translation->{longdescription}));
 
 421   # delete price records
 
 422   do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
 
 424   $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
 
 425   $sth   = prepare_query($form, $dbh, $query);
 
 427   for my $i (1 .. $form->{price_rows}) {
 
 428     my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
 
 431     @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
 
 432     do_statement($form, $sth, $query, @values);
 
 437   # insert makemodel records
 
 440     for my $i (1 .. $form->{makemodel_rows}) {
 
 441       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
 
 443         $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
 
 444         if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
 
 446             if ($form->{"lastupdate_$i"} eq "") {
 
 447                 $lastupdate = 'now()';
 
 449                 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
 
 452             $lastupdate = 'now()';
 
 454         $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
 
 455                  qq|VALUES (?, ?, ?, ?, ?, ?)|;
 
 456         @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
 
 458         do_query($form, $dbh, $query, @values);
 
 462   # add assembly records
 
 463   if ($form->{item} eq 'assembly') {
 
 464     # check additional assembly row
 
 465     my $i = $form->{assembly_rows};
 
 466     # if last row is not empty add them
 
 467     if ($form->{"partnumber_$i"} ne "") {
 
 468       $query = qq|SELECT id FROM parts WHERE partnumber = ?|;
 
 469       my ($partid) = selectrow_query($form, $dbh, $query,$form->{"partnumber_$i"} );
 
 471         $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
 
 472         $form->{"id_$i"} = $partid;
 
 473         $form->{"bom_$i"} = 0;
 
 474         $form->{assembly_rows}++;
 
 477         $::form->error($::locale->text("uncorrect partnumber ").$form->{"partnumber_$i"});
 
 481     for my $i (1 .. $form->{assembly_rows}) {
 
 482       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 484       if ($form->{"qty_$i"} != 0) {
 
 485         $form->{"bom_$i"} *= 1;
 
 486         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
 
 487                  qq|VALUES (?, ?, ?, ?)|;
 
 488         @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
 
 489         do_query($form, $dbh, $query, @values);
 
 495     my $shippingdate = "$a[5]-$a[4]-$a[3]";
 
 497     $form->get_employee($dbh);
 
 501   #set expense_accno=inventory_accno if they are different => bilanz
 
 503     ($form->{expense_accno} != $form->{inventory_accno})
 
 504     ? $form->{inventory_accno}
 
 505     : $form->{expense_accno};
 
 507   # get tax rates and description
 
 509     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
 
 511     qq|SELECT c.accno, c.description, t.rate, t.taxnumber
 
 513        WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
 
 515   my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
 
 517   $form->{taxaccount} = "";
 
 518   while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
 
 519     $form->{taxaccount} .= "$ptr->{accno} ";
 
 520     if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
 
 521       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
 522       $form->{"$ptr->{accno}_description"} = $ptr->{description};
 
 523       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
 524       $form->{taxaccount2} .= " $ptr->{accno} ";
 
 528   CVar->save_custom_variables(dbh           => $dbh,
 
 530                               trans_id      => $form->{id},
 
 534   # Delete saved custom variable values for configs that have been
 
 535   # marked invalid for this part.
 
 537     DELETE FROM custom_variables
 
 538     WHERE (config_id IN (
 
 540         FROM custom_variables_validity val
 
 541         LEFT JOIN custom_variable_configs val_cfg ON (val.config_id = val_cfg.id)
 
 542         WHERE (val_cfg.module = 'IC')
 
 543           AND (val.trans_id   = ?)))
 
 546   do_query($form, $dbh, $query, ($form->{id}) x 2);
 
 549   my $rc = $dbh->commit;
 
 551   $main::lxdebug->leave_sub();
 
 556 sub update_assembly {
 
 557   $main::lxdebug->enter_sub();
 
 559   my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
 
 561   my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
 
 562   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
 
 564   while (my ($pid, $aqty) = $sth->fetchrow_array) {
 
 565     &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
 
 570     qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
 
 572   my @values = ($qty * ($form->{sellprice} - $sellprice),
 
 573              $qty * ($form->{weight} - $weight), conv_i($id));
 
 574   do_query($form, $dbh, $query, @values);
 
 576   $form->new_lastmtime('parts') if $id == $form->{id};
 
 578   $main::lxdebug->leave_sub();
 
 581 sub retrieve_assemblies {
 
 582   $main::lxdebug->enter_sub();
 
 584   my ($self, $myconfig, $form) = @_;
 
 586   # connect to database
 
 587   my $dbh = $form->get_standard_dbh;
 
 589   my $where = qq|NOT p.obsolete|;
 
 592   if ($form->{partnumber}) {
 
 593     $where .= qq| AND (p.partnumber ILIKE ?)|;
 
 594     push(@values, like($form->{partnumber}));
 
 597   if ($form->{description}) {
 
 598     $where .= qq| AND (p.description ILIKE ?)|;
 
 599     push(@values, like($form->{description}));
 
 602   # retrieve assembly items
 
 604     qq|SELECT p.id, p.partnumber, p.description,
 
 606          (SELECT sum(p2.inventory_accno_id)
 
 607           FROM parts p2, assembly a
 
 608           WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
 
 610        WHERE NOT p.obsolete AND p.assembly $where|;
 
 612   $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
 
 614   $main::lxdebug->leave_sub();
 
 618   $main::lxdebug->enter_sub();
 
 620   my ($self, $myconfig, $form) = @_;
 
 621   my @values = (conv_i($form->{id}));
 
 622   # connect to database, turn off AutoCommit
 
 623   my $dbh = $form->get_standard_dbh;
 
 625   my %columns = ( "assembly" => "id", "parts" => "id" );
 
 627   for my $table (qw(prices makemodel inventory assembly translation parts)) {
 
 628     my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
 
 629     do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
 
 633   my $rc = $dbh->commit;
 
 635   $main::lxdebug->leave_sub();
 
 641   $main::lxdebug->enter_sub();
 
 643   my ($self, $myconfig, $form) = @_;
 
 645   my $i = $form->{assembly_rows};
 
 647   my $where = qq|1 = 1|;
 
 650   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
 
 652   while (my ($column, $table) = each(%columns)) {
 
 653     next unless ($form->{"${column}_$i"});
 
 654     $where .= qq| AND ${table}.${column} ILIKE ?|;
 
 655     push(@values, like($form->{"${column}_$i"}));
 
 659     $where .= qq| AND NOT (p.id = ?)|;
 
 660     push(@values, conv_i($form->{id}));
 
 663   # Search for part ID overrides all other criteria.
 
 664   if ($form->{"id_${i}"}) {
 
 665     $where  = qq|p.id = ?|;
 
 666     @values = ($form->{"id_${i}"});
 
 669   if ($form->{partnumber}) {
 
 670     $where .= qq| ORDER BY p.partnumber|;
 
 672     $where .= qq| ORDER BY p.description|;
 
 675   # connect to database
 
 676   my $dbh = $form->get_standard_dbh;
 
 679     qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
 
 680        p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
 
 681        p.price_factor_id, pfac.factor AS price_factor, p.notes as longdescription
 
 683        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 684        LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
 
 686   $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
 
 688   $main::lxdebug->leave_sub();
 
 693 # Warning, deep magic ahead.
 
 694 # This function gets all parts from the database according to the filters specified
 
 697 #   sort revers  - sorting field + direction
 
 700 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
 
 701 #   partnumber ean description partsgroup microfiche drawing
 
 704 #   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
 
 707 #   itemstatus  = active | onhand | short | obsolete | orphaned
 
 708 #   searchitems = part | assembly | service
 
 711 #   make model                               - makemodel
 
 712 #   serialnumber transdatefrom transdateto   - invoice/orderitems
 
 715 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
 
 716 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
 
 717 #   l_soldtotal                              - aggreg join to display total of sold quantity
 
 718 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 719 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
 
 720 #   l_serialnumber                           - belonges to serialnumber filter
 
 721 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
 
 722 #   l_soldtotal                              - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
 
 725 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 727 #   search by overrides of description
 
 729 # disabled sanity checks and changes:
 
 730 #  - searchitems = assembly will no longer disable bought
 
 731 #  - searchitems = service  will no longer disable make and model, although services don't have make/model, it doesn't break the query
 
 732 #  - itemstatus  = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
 
 733 #  - itemstatus  = obsolete will no longer disable onhand, short
 
 734 #  - allow sorting by ean
 
 735 #  - serialnumber filter also works if l_serialnumber isn't ticked
 
 736 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
 
 739   $main::lxdebug->enter_sub();
 
 741   my ($self, $myconfig, $form) = @_;
 
 742   my $dbh = $form->get_standard_dbh($myconfig);
 
 744   $form->{parts}     = +{ };
 
 745   $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
 
 747   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
 
 748   my @project_filters      = qw(projectnumber projectdescription);
 
 749   my @makemodel_filters    = qw(make model);
 
 750   my @invoice_oi_filters   = qw(serialnumber soldtotal);
 
 751   my @apoe_filters         = qw(transdate);
 
 752   my @like_filters         = (@simple_filters, @invoice_oi_filters);
 
 753   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
 
 754   my @simple_l_switches    = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image shop insertdate));
 
 755   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
 
 756   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module qty);
 
 757   my @deliverydate_flags   = qw(deliverydate);
 
 758 #  my @other_flags          = qw(onhand); # ToDO: implement these
 
 759 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
 
 761   my @select_tokens = qw(id factor);
 
 762   my @where_tokens  = qw(1=1);
 
 763   my @group_tokens  = ();
 
 765   my %joins_needed  = ();
 
 768     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
 
 769     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
 
 770     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
 
 773          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem,         deliverydate, 'invoice'    AS ioi, project_id, id FROM invoice UNION
 
 774          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
 
 775        ) AS ioi ON ioi.parts_id = p.id|,
 
 778          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
 
 779          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
 
 780          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
 
 781        ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
 
 784            SELECT id, name, 'customer' AS cv FROM customer UNION
 
 785            SELECT id, name, 'vendor'   AS cv FROM vendor
 
 786          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
 
 787     mv         => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
 
 788     project    => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
 
 790   my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
 
 793      deliverydate => 'apoe.', serialnumber => 'ioi.',
 
 794      transdate    => 'apoe.', trans_id     => 'ioi.',
 
 795      module       => 'apoe.', name         => 'cv.',
 
 796      ordnumber    => 'apoe.', make         => 'mm.',
 
 797      quonumber    => 'apoe.', model        => 'mm.',
 
 798      invnumber    => 'apoe.', partsgroup   => 'pg.',
 
 799      lastcost     => 'p.',  , soldtotal    => ' ',
 
 800      factor       => 'pfac.', projectnumber => 'pj.',
 
 801      'SUM(ioi.qty)' => ' ',   projectdescription => 'pj.',
 
 804      serialnumber => 'ioi.',
 
 805      quotation    => 'apoe.',
 
 811   # if the join condition in these blocks are met, the column
 
 812   # of the scecified table will gently override (coalesce actually) the original value
 
 813   # use it to conditionally coalesce values from subtables
 
 814   my @column_override = (
 
 815     #  column name,   prefix,  joins_needed,  nick name (in case column is named like another)
 
 816     [ 'description',  'ioi.',  'invoice_oi'  ],
 
 817     [ 'deliverydate', 'ioi.',  'invoice_oi'  ],
 
 818     [ 'transdate',    'apoe.', 'apoe'        ],
 
 819     [ 'unit',         'ioi.',  'invoice_oi'  ],
 
 820     [ 'sellprice',    'ioi.',  'invoice_oi'  ],
 
 823   # careful with renames. these are HARD, and any filters done on the original column will break
 
 824   my %renamed_columns = (
 
 825     'factor'       => 'price_factor',
 
 826     'SUM(ioi.qty)' => 'soldtotal',
 
 827     'ioi.id'       => 'ioi_id',
 
 829     'projectdescription' => 'projectdescription',
 
 830     'insertdate'   => 'insertdate',
 
 834     projectdescription => 'description',
 
 835     insertdate         => 'itime::DATE',
 
 838   if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
 
 839     @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
 
 842   my $make_token_builder = sub {
 
 843     my $joins_needed = shift;
 
 845       my ($nick, $alias) = @_;
 
 846       my ($col) = $real_column{$nick} || $nick;
 
 847       my @coalesce_tokens =
 
 848         map  { ($_->[1] || 'p.') . $_->[0] }
 
 849         grep { !$_->[2] || $joins_needed->{$_->[2]} }
 
 850         grep { ($_->[3] || $_->[0]) eq $nick }
 
 851         @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
 
 853       my $coalesce = scalar @coalesce_tokens > 1;
 
 855         ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
 
 856         : shift                              @coalesce_tokens)
 
 857         . ($alias && ($coalesce || $renamed_columns{$nick})
 
 858         ?  " AS " . ($renamed_columns{$nick} || $nick)
 
 863   #===== switches and simple filters ========#
 
 865   # special case transdate
 
 866   if (grep { trim($form->{$_}) } qw(transdatefrom transdateto)) {
 
 867     $form->{"l_transdate"} = 1;
 
 868     push @select_tokens, 'transdate';
 
 869     for (qw(transdatefrom transdateto)) {
 
 870       my $value = trim($form->{$_});
 
 872       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
 
 873       push @bind_vars,    $value;
 
 877   # special case smart search
 
 879     $form->{"l_$_"} = 1 for qw(partnumber description unit sellprice lastcost cvar_packaging linetotal);
 
 880     push @where_tokens, "p.partnumber ILIKE ? OR p.description ILIKE ?";
 
 881     push @bind_vars,    "%$form->{all}%", "%$form->{all}%";
 
 884   # special case insertdate
 
 885   if (grep { trim($form->{$_}) } qw(insertdatefrom insertdateto)) {
 
 886     $form->{"l_insertdate"} = 1;
 
 887     push @select_tokens, 'insertdate';
 
 889     my $token_builder = $make_token_builder->();
 
 890     my $token = $token_builder->('insertdate');
 
 892     for (qw(insertdatefrom insertdateto)) {
 
 893       my $value = trim($form->{$_});
 
 895       push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
 
 896       push @bind_vars,    $value;
 
 900   if ($form->{"partsgroup_id"}) {
 
 901     $form->{"l_partsgroup"} = '1'; # show the column
 
 902     push @where_tokens, "pg.id = ?";
 
 903     push @bind_vars, $form->{"partsgroup_id"};
 
 906   if ($form->{shop} ne '') {
 
 907     $form->{l_shop} = '1'; # show the column
 
 908     if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
 
 909       push @where_tokens, 'NOT p.shop';
 
 912       push @where_tokens, 'p.shop';
 
 916   foreach (@like_filters) {
 
 917     next unless $form->{$_};
 
 918     $form->{"l_$_"} = '1'; # show the column
 
 919     push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
 
 920     push @bind_vars,    like($form->{$_});
 
 923   foreach (@simple_l_switches) {
 
 924     next unless $form->{"l_$_"};
 
 925     push @select_tokens, $_;
 
 928   for ($form->{searchitems}) {
 
 929     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
 
 930     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
 
 931     push @where_tokens, 'NOT p.assembly'               if /service/;
 
 932     push @where_tokens, '    p.assembly'               if /assembly/;
 
 935   for ($form->{itemstatus}) {
 
 936     push @where_tokens, 'p.id NOT IN
 
 937         (SELECT DISTINCT parts_id FROM invoice UNION
 
 938          SELECT DISTINCT parts_id FROM assembly UNION
 
 939          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
 
 940     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
 
 941     push @where_tokens, 'NOT p.obsolete'               if /active/;
 
 942     push @where_tokens, '    p.obsolete',              if /obsolete/;
 
 943     push @where_tokens, 'p.onhand > 0',                if /onhand/;
 
 944     push @where_tokens, 'p.onhand < p.rop',            if /short/;
 
 947   my $q_assembly_lastcost =
 
 948     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
 
 950         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
 
 951         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
 
 952         WHERE (a_lc.id = p.id)) AS lastcost|;
 
 953   $table_prefix{$q_assembly_lastcost} = ' ';
 
 955   # special case makemodel search
 
 956   # all_parts is based upon the assumption that every parameter is named like the column it represents
 
 957   # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
 
 958   # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
 
 960     push @where_tokens, 'mv.name ILIKE ?';
 
 961     push @bind_vars, like($form->{make});
 
 963   if ($form->{model}) {
 
 964     push @where_tokens, 'mm.model ILIKE ?';
 
 965     push @bind_vars, like($form->{model});
 
 968   # special case: sorting by partnumber
 
 969   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
 
 970   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
 
 971   # ToDO: implement proper functional sorting
 
 972   # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
 
 973   # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
 
 974   #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
 
 975   #  if $form->{sort} eq 'partnumber';
 
 977   #my $order_clause = " ORDER BY $form->{sort} $sort_order";
 
 980   $limit_clause = " LIMIT 100"                   if $form->{top100};
 
 981   $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
 
 983   #=== joins and complicated filters ========#
 
 985   my $bsooqr        = any { $form->{$_} } @oe_flags;
 
 986   my @bsooqr_tokens = ();
 
 988   push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi'  if $bsooqr;
 
 989   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
 
 990   push @select_tokens, $q_assembly_lastcost                                   if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
 
 991   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
 
 992   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
 
 993   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
 
 994   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
 
 995   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
 
 996   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
 
 997   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
 
 999   $joins_needed{partsgroup}  = 1;
 
1000   $joins_needed{pfac}        = 1;
 
1001   $joins_needed{project}     = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
 
1002   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
 
1003   $joins_needed{mv}          = 1 if $joins_needed{makemodel};
 
1004   $joins_needed{cv}          = 1 if $bsooqr;
 
1005   $joins_needed{apoe}        = 1 if $joins_needed{project} || $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
 
1006   $joins_needed{invoice_oi}  = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
 
1008   # special case for description search.
 
1009   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
 
1010   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
 
1011   # find the old entries in of @where_tokens and @bind_vars, and adjust them
 
1012   if ($joins_needed{invoice_oi}) {
 
1013     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
 
1014       next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
 
1015       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
 
1016       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
 
1021   # now the master trick: soldtotal.
 
1022   if ($form->{l_soldtotal}) {
 
1023     push @where_tokens, 'NOT ioi.qty = 0';
 
1024     push @group_tokens, @select_tokens;
 
1025      map { s/.*\sAS\s+//si } @group_tokens;
 
1026     push @select_tokens, 'SUM(ioi.qty)';
 
1029   #============= build query ================#
 
1031   my $token_builder = $make_token_builder->(\%joins_needed);
 
1033   my @sort_cols    = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
 
1034      $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
 
1035   my $sort_order   = ($form->{revers} ? ' DESC' : ' ASC');
 
1036   my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
 
1038   my $select_clause = join ', ',    map { $token_builder->($_, 1) } @select_tokens;
 
1039   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
 
1040   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
 
1041   my $group_clause  = @group_tokens ? ' GROUP BY ' . join ', ',    map { $token_builder->($_) } @group_tokens : '';
 
1043   my %oe_flag_to_cvar = (
 
1044     bought   => 'invoice',
 
1046     onorder  => 'orderitems',
 
1047     ordered  => 'orderitems',
 
1048     rfq      => 'orderitems',
 
1049     quoted   => 'orderitems',
 
1052   my ($cvar_where, @cvar_values) = CVar->build_filter_query(
 
1054     trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
 
1056     sub_module     => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
 
1060     $where_clause .= qq| AND ($cvar_where)|;
 
1061     push @bind_vars, @cvar_values;
 
1064   my $query = <<"  SQL";
 
1065     SELECT DISTINCT $select_clause
 
1074   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
 
1076   map { $_->{onhand} *= 1 } @{ $form->{parts} };
 
1078   # fix qty sign in ap. those are saved negative
 
1079   if ($bsooqr && $form->{bought}) {
 
1080     for my $row (@{ $form->{parts} }) {
 
1081       $row->{qty} *= -1 if $row->{module} eq 'ir';
 
1085   # post processing for assembly parts lists (bom)
 
1086   # for each part get the assembly parts and add them into the partlist.
 
1088   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
 
1090       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
 
1091            p.unit, p.notes, p.itime::DATE as insertdate,
 
1092            p.sellprice, p.listprice, p.lastcost,
 
1093            p.rop, p.weight, p.priceupdate,
 
1094            p.image, p.drawing, p.microfiche,
 
1097          INNER JOIN assembly a ON (p.id = a.parts_id)
 
1100     my $sth = prepare_query($form, $dbh, $query);
 
1102     foreach my $item (@{ $form->{parts} }) {
 
1103       push(@assemblies, $item);
 
1104       do_statement($form, $sth, $query, conv_i($item->{id}));
 
1106       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1107         $ref->{assemblyitem} = 1;
 
1108         map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
 
1109         push(@assemblies, $ref);
 
1114     # copy assemblies to $form->{parts}
 
1115     $form->{parts} = \@assemblies;
 
1118   if ($form->{l_pricegroups} ) {
 
1120        SELECT parts_id, price, pricegroup_id
 
1125     my $sth = prepare_query($form, $dbh, $query);
 
1127     foreach my $part (@{ $form->{parts} }) {
 
1128       do_statement($form, $sth, $query, conv_i($part->{id}));
 
1130       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1131         $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
 
1138   $main::lxdebug->leave_sub();
 
1140   return @{ $form->{parts} };
 
1143 sub _create_filter_for_priceupdate {
 
1144   $main::lxdebug->enter_sub();
 
1147   my $myconfig = \%main::myconfig;
 
1148   my $form     = $main::form;
 
1151   my $where = '1 = 1';
 
1153   foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
 
1155     $column =~ s/.*\.//;
 
1156     next unless ($form->{$column});
 
1158     $where .= qq| AND $item ILIKE ?|;
 
1159     push(@where_values, like($form->{$column}));
 
1162   foreach my $item (qw(description serialnumber)) {
 
1163     next unless ($form->{$item});
 
1165     $where .= qq| AND (${item} ILIKE ?)|;
 
1166     push(@where_values, like($form->{$item}));
 
1170   # items which were never bought, sold or on an order
 
1171   if ($form->{itemstatus} eq 'orphaned') {
 
1173       qq| AND (p.onhand = 0)
 
1176               SELECT DISTINCT parts_id FROM invoice
 
1178               SELECT DISTINCT parts_id FROM assembly
 
1180               SELECT DISTINCT parts_id FROM orderitems
 
1183   } elsif ($form->{itemstatus} eq 'active') {
 
1184     $where .= qq| AND p.obsolete = '0'|;
 
1186   } elsif ($form->{itemstatus} eq 'obsolete') {
 
1187     $where .= qq| AND p.obsolete = '1'|;
 
1189   } elsif ($form->{itemstatus} eq 'onhand') {
 
1190     $where .= qq| AND p.onhand > 0|;
 
1192   } elsif ($form->{itemstatus} eq 'short') {
 
1193     $where .= qq| AND p.onhand < p.rop|;
 
1197   foreach my $column (qw(make model)) {
 
1198     next unless ($form->{$column});
 
1199     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
 
1200     push(@where_values, like($form->{$column}));
 
1203   $main::lxdebug->leave_sub();
 
1205   return ($where, @where_values);
 
1208 sub get_num_matches_for_priceupdate {
 
1209   $main::lxdebug->enter_sub();
 
1213   my $myconfig = \%main::myconfig;
 
1214   my $form     = $main::form;
 
1216   my $dbh      = $form->get_standard_dbh($myconfig);
 
1218   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
 
1220   my $num_updated = 0;
 
1223   for my $column (qw(sellprice listprice)) {
 
1224     next if ($form->{$column} eq "");
 
1232             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1234     my ($result)  = selectfirst_array_query($form, $dbh, $query, @where_values);
 
1235     $num_updated += $result if (0 <= $result);
 
1244           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1245           WHERE $where) AND (pricegroup_id = ?)|;
 
1246   my $sth = prepare_query($form, $dbh, $query);
 
1248   for my $i (1 .. $form->{price_rows}) {
 
1249     next if ($form->{"price_$i"} eq "");
 
1251     my ($result)  = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1252     $num_updated += $result if (0 <= $result);
 
1256   $main::lxdebug->leave_sub();
 
1258   return $num_updated;
 
1262   $main::lxdebug->enter_sub();
 
1264   my ($self, $myconfig, $form) = @_;
 
1266   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
 
1267   my $num_updated = 0;
 
1269   # connect to database
 
1270   my $dbh = $form->get_standard_dbh;
 
1272   for my $column (qw(sellprice listprice)) {
 
1273     next if ($form->{$column} eq "");
 
1275     my $value = $form->parse_amount($myconfig, $form->{$column});
 
1278     if ($form->{"${column}_type"} eq "percent") {
 
1279       $value = ($value / 100) + 1;
 
1284       qq|UPDATE parts SET $column = $column $operator ?
 
1288             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1290     my $result    = do_query($form, $dbh, $query, $value, @where_values);
 
1291     $num_updated += $result if (0 <= $result);
 
1295     qq|UPDATE prices SET price = price + ?
 
1299           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1300           WHERE $where) AND (pricegroup_id = ?)|;
 
1301   my $sth_add = prepare_query($form, $dbh, $q_add);
 
1304     qq|UPDATE prices SET price = price * ?
 
1308           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1309           WHERE $where) AND (pricegroup_id = ?)|;
 
1310   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
 
1312   for my $i (1 .. $form->{price_rows}) {
 
1313     next if ($form->{"price_$i"} eq "");
 
1315     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
 
1318     if ($form->{"pricegroup_type_$i"} eq "percent") {
 
1319       $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1321       $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1324     $num_updated += $result if (0 <= $result);
 
1328   $sth_multiply->finish();
 
1330   my $rc= $dbh->commit;
 
1332   $main::lxdebug->leave_sub();
 
1334   return $num_updated;
 
1338   $main::lxdebug->enter_sub();
 
1340   my ($self, $module, $myconfig, $form) = @_;
 
1342   # connect to database
 
1343   my $dbh = $form->get_standard_dbh;
 
1345   my @values = ('%' . $module . '%');
 
1350       qq|SELECT c.accno, c.description, c.link, c.id,
 
1351            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
 
1352          FROM chart c, parts p
 
1353          WHERE (c.link LIKE ?) AND (p.id = ?)
 
1355     push(@values, conv_i($form->{id}));
 
1359       qq|SELECT c.accno, c.description, c.link, c.id,
 
1360            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
 
1361          FROM chart c, defaults d
 
1366   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1367   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1368     foreach my $key (split(/:/, $ref->{link})) {
 
1369       if ($key =~ /\Q$module\E/) {
 
1370         if (   ($ref->{id} eq $ref->{inventory_accno_id})
 
1371             || ($ref->{id} eq $ref->{income_accno_id})
 
1372             || ($ref->{id} eq $ref->{expense_accno_id})) {
 
1373           push @{ $form->{"${module}_links"}{$key} },
 
1374             { accno       => $ref->{accno},
 
1375               description => $ref->{description},
 
1376               selected    => "selected" };
 
1377           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
 
1379           push @{ $form->{"${module}_links"}{$key} },
 
1380             { accno       => $ref->{accno},
 
1381               description => $ref->{description},
 
1389   # get buchungsgruppen
 
1390   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
 
1393   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
 
1396     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
 
1399   $main::lxdebug->leave_sub();
 
1402 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
 
1404   $main::lxdebug->enter_sub();
 
1406   my ($self, $myconfig, $form, $sortorder) = @_;
 
1407   my $dbh   = $form->get_standard_dbh;
 
1408   my $order = qq| p.partnumber|;
 
1409   my $where = qq|1 = 1|;
 
1412   if ($sortorder eq "all") {
 
1413     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
 
1414     push(@values, like($form->{partnumber}), like($form->{description}));
 
1416   } elsif ($sortorder eq "partnumber") {
 
1417     $where .= qq| AND (partnumber ILIKE ?)|;
 
1418     push(@values, like($form->{partnumber}));
 
1420   } elsif ($sortorder eq "description") {
 
1421     $where .= qq| AND (description ILIKE ?)|;
 
1422     push(@values, like($form->{description}));
 
1423     $order = "description";
 
1428     qq|SELECT id, partnumber, description, unit, sellprice
 
1430        WHERE $where ORDER BY $order|;
 
1432   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1435   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1436     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
 
1441     $form->{"id_$j"}          = $ref->{id};
 
1442     $form->{"partnumber_$j"}  = $ref->{partnumber};
 
1443     $form->{"description_$j"} = $ref->{description};
 
1444     $form->{"unit_$j"}        = $ref->{unit};
 
1445     $form->{"sellprice_$j"}   = $ref->{sellprice};
 
1446     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
 
1451   $main::lxdebug->leave_sub();
 
1456 # gets sum of sold part with part_id
 
1458   $main::lxdebug->enter_sub();
 
1460   my ($dbh, $id) = @_;
 
1462   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
 
1463   my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
 
1466   $main::lxdebug->leave_sub();
 
1469 }    #end get_soldtotal
 
1471 sub retrieve_languages {
 
1472   $main::lxdebug->enter_sub();
 
1474   my ($self, $myconfig, $form) = @_;
 
1476   # connect to database
 
1477   my $dbh = $form->get_standard_dbh;
 
1483   if ($form->{language_values} ne "") {
 
1485       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
 
1487          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
 
1488          ORDER BY lower(l.description)|;
 
1489     @values = (conv_i($form->{id}));
 
1492     $query = qq|SELECT id, description
 
1494                 ORDER BY lower(description)|;
 
1497   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
 
1499   $main::lxdebug->leave_sub();
 
1504 sub follow_account_chain {
 
1505   $main::lxdebug->enter_sub(2);
 
1507   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
 
1509   my @visited_accno_ids = ($accno_id);
 
1513   $form->{ACCOUNT_CHAIN_BY_ID} ||= {
 
1514     map { $_->{id} => $_ }
 
1515       selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
 
1516     SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
 
1518     LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
 
1519     WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
 
1523     my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
 
1524     last unless ($ref && $ref->{"is_valid"} &&
 
1525                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
 
1526     $accno_id = $ref->{"new_chart_id"};
 
1527     $accno = $ref->{"accno"};
 
1528     push(@visited_accno_ids, $accno_id);
 
1531   $main::lxdebug->leave_sub(2);
 
1533   return ($accno_id, $accno);
 
1536 sub retrieve_accounts {
 
1537   $main::lxdebug->enter_sub;
 
1540   my $myconfig = shift;
 
1542   my $dbh      = $form->get_standard_dbh;
 
1543   my %args     = @_;     # index => part_id
 
1545   $form->{taxzone_id} *= 1;
 
1547   return unless grep $_, values %args; # shortfuse if no part_id supplied
 
1549   # transdate madness.
 
1551   if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
 
1552     # use deliverydate for sales and purchase invoice, if it exists
 
1553     # also use deliverydate for credit notes
 
1554     if (!$form->{deliverydate}) {
 
1555       $transdate = $form->{invdate};
 
1557       $transdate = $form->{deliverydate};
 
1559   } elsif ($form->{script} eq 'ir.pl') {
 
1560     # when a purchase invoice is opened from the report of purchase invoices
 
1561     # $form->{type} isn't set, but $form->{script} is, not sure why this is or
 
1562     # whether this distinction matters in some other scenario. Otherwise one
 
1563     # could probably take out this elsif and add a
 
1564     # " or $form->{script} eq 'ir.pl' "
 
1565     # to the above if-statement
 
1566     if (!$form->{deliverydate}) {
 
1567       $transdate = $form->{invdate};
 
1569       $transdate = $form->{deliverydate};
 
1571   } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
 
1572     # if credit_note has a deliverydate, use this instead of invdate
 
1573     # useful for credit_notes of invoices from an old period with different tax
 
1574     # if there is no deliverydate then invdate is used, old default (see next elsif)
 
1575     # Falls hier der Stichtag für Steuern anders bestimmt wird,
 
1576     # entsprechend auch bei Taxkeys.pm anpassen
 
1577     $transdate = $form->{deliverydate};
 
1578   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
 
1579     $transdate = $form->{invdate};
 
1581     $transdate = $form->{transdate};
 
1584   if ($transdate eq "") {
 
1585     $transdate = DateTime->today_local->to_lxoffice;
 
1587     $transdate = $dbh->quote($transdate);
 
1590   my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
 
1592   my @part_ids = grep { $_ } values %args;
 
1593   my $in       = join ',', ('?') x @part_ids;
 
1595   my %accno_by_part = map { $_->{id} => $_ }
 
1596     selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
 
1598       p.id, p.inventory_accno_id AS is_part,
 
1599       bg.inventory_accno_id,
 
1600       tc.income_accno_id AS income_accno_id,
 
1601       tc.expense_accno_id AS expense_accno_id,
 
1602       c1.accno AS inventory_accno,
 
1603       c2.accno AS income_accno,
 
1604       c3.accno AS expense_accno
 
1606     LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
 
1607     LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
 
1608     LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
 
1609     LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
 
1610     LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
 
1612     tc.taxzone_id = '$form->{taxzone_id}'
 
1617   my $sth_tax = prepare_query($::form, $dbh, <<SQL);
 
1618     SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
 
1620     LEFT JOIN chart c ON c.id = t.chart_id
 
1624        WHERE tk.chart_id = ? AND startdate <= ?
 
1625        ORDER BY startdate DESC LIMIT 1)
 
1628   while (my ($index => $part_id) = each %args) {
 
1629     my $ref = $accno_by_part{$part_id} or next;
 
1631     $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
 
1634     for my $type (qw(inventory income expense)) {
 
1635       next unless $ref->{"${type}_accno_id"};
 
1636       ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
 
1637         $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
 
1640     $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
 
1642     $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
 
1643     $ref = $sth_tax->fetchrow_hashref or next;
 
1645     $form->{"taxaccounts_$index"} = $ref->{"accno"};
 
1646     $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
 
1648     $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
 
1653   $::lxdebug->leave_sub;
 
1656 sub get_basic_part_info {
 
1657   $main::lxdebug->enter_sub();
 
1662   Common::check_params(\%params, qw(id));
 
1664   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
 
1667     $main::lxdebug->leave_sub();
 
1671   my $myconfig = \%main::myconfig;
 
1672   my $form     = $main::form;
 
1674   my $dbh      = $form->get_standard_dbh($myconfig);
 
1676   my $query    = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
 
1678   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
 
1680   if ('' eq ref $params{id}) {
 
1681     $info = $info->[0] || { };
 
1683     $main::lxdebug->leave_sub();
 
1687   my %info_map = map { $_->{id} => $_ } @{ $info };
 
1689   $main::lxdebug->leave_sub();
 
1694 sub prepare_parts_for_printing {
 
1695   $main::lxdebug->enter_sub();
 
1700   my $myconfig = $params{myconfig} || \%main::myconfig;
 
1701   my $form     = $params{form}     || $main::form;
 
1703   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1705   my $prefix   = $params{prefix} || 'id_';
 
1706   my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
 
1708   my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
 
1711     $main::lxdebug->leave_sub();
 
1715   my $placeholders = join ', ', ('?') x scalar(@part_ids);
 
1716   my $query        = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
 
1718                         LEFT JOIN vendor v ON (mm.make = v.id)
 
1719                         WHERE mm.parts_id IN ($placeholders)|;
 
1723   my $sth          = prepare_execute_query($form, $dbh, $query, @part_ids);
 
1725   while (my $ref = $sth->fetchrow_hashref()) {
 
1726     $makemodel{$ref->{parts_id}} ||= [];
 
1727     push @{ $makemodel{$ref->{parts_id}} }, $ref;
 
1732   my @columns = qw(ean image microfiche drawing);
 
1734   $query      = qq|SELECT id, | . join(', ', @columns) . qq|
 
1736                    WHERE id IN ($placeholders)|;
 
1738   my %data    = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
 
1740   my %template_arrays;
 
1741   map { $template_arrays{$_} = [] } (qw(make model), @columns);
 
1743   foreach my $i (1 .. $rowcount) {
 
1744     my $id = $form->{"${prefix}${i}"};
 
1748     foreach (@columns) {
 
1749       push @{ $template_arrays{$_} }, $data{$id}->{$_};
 
1752     push @{ $template_arrays{make} },  [];
 
1753     push @{ $template_arrays{model} }, [];
 
1755     next if (!$makemodel{$id});
 
1757     foreach my $ref (@{ $makemodel{$id} }) {
 
1758       map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model);
 
1762   my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
 
1763   my %parts_by_id = map { $_->id => $_ } @$parts;
 
1765   for my $i (1..$rowcount) {
 
1766     my $id = $form->{"${prefix}${i}"};
 
1769     push @{ $template_arrays{part_type} },  $parts_by_id{$id}->type;
 
1772   return %template_arrays;
 
1773   $main::lxdebug->leave_sub();
 
1776 sub normalize_text_blocks {
 
1777   $main::lxdebug->enter_sub();
 
1782   my $form     = $params{form}     || $main::form;
 
1784   # check if feature is enabled (select normalize_part_descriptions from defaults)
 
1785   return unless ($::instance_conf->get_normalize_part_descriptions);
 
1787   foreach (qw(description notes)) {
 
1788     $form->{$_} =~ s/\s+$//s;
 
1789     $form->{$_} =~ s/^\s+//s;
 
1790     $form->{$_} =~ s/ {2,}/ /g;
 
1792    $main::lxdebug->leave_sub();