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);
 
  48   $main::lxdebug->enter_sub();
 
  50   my ($self, $myconfig, $form) = @_;
 
  53   my $dbh = $form->dbconnect($myconfig);
 
  59          c1.accno AS inventory_accno,
 
  60          c2.accno AS income_accno,
 
  61          c3.accno AS expense_accno,
 
  64        LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
 
  65        LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
 
  66        LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
 
  67        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
  69   my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
  71   # copy to $form variables
 
  72   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
 
  76   # part or service item
 
  77   $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
 
  78   if ($form->{assembly}) {
 
  79     $form->{item} = 'assembly';
 
  81     # retrieve assembly items
 
  83       qq|SELECT p.id, p.partnumber, p.description,
 
  84            p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
 
  85            pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
 
  87          JOIN assembly a ON (a.parts_id = p.id)
 
  88          LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
  89          LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
 
  92     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
  94     $form->{assembly_rows} = 0;
 
  95     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
  96       $form->{assembly_rows}++;
 
  97       foreach my $key (keys %{$ref}) {
 
  98         $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
 
 105   # setup accno hash for <option checked> {amount} is used in create_links
 
 106   $form->{amount}{IC}         = $form->{inventory_accno};
 
 107   $form->{amount}{IC_income}  = $form->{income_accno};
 
 108   $form->{amount}{IC_sale}    = $form->{income_accno};
 
 109   $form->{amount}{IC_expense} = $form->{expense_accno};
 
 110   $form->{amount}{IC_cogs}    = $form->{expense_accno};
 
 114     SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
 
 116     LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
 
 117     ORDER BY lower(pg.pricegroup)
 
 121   foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
 
 122     $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
 
 125   $form->{price_rows} = $row - 1;
 
 128   if ($form->{makemodel}) {
 
 130     $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
 
 131              qq|WHERE m.parts_id = ? order by m.sortorder asc|;
 
 132     my @values = ($form->{id});
 
 133     $sth = $dbh->prepare($query);
 
 134     $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
 
 138     while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
 
 139               $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
 
 144     $form->{makemodel_rows} = $i - 1;
 
 149   $form->{language_values} = "";
 
 150   $query = qq|SELECT language_id, translation, longdescription
 
 153   my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 154   while (my $tr = $trq->fetchrow_hashref("NAME_lc")) {
 
 155     $form->{language_values} .= "---+++---" . join('--++--', @{$tr}{qw(language_id translation longdescription)});
 
 160   my @referencing_tables = qw(invoice orderitems inventory);
 
 161   my %column_map         = ( );
 
 162   my $parts_id           = conv_i($form->{id});
 
 164   $form->{orphaned}      = 1;
 
 166   foreach my $table (@referencing_tables) {
 
 167     my $column  = $column_map{$table} || 'parts_id';
 
 168     $query      = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
 
 169     my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
 
 172       $form->{orphaned} = 0;
 
 177   $form->{"unit_changeable"} = $form->{orphaned};
 
 181   $main::lxdebug->leave_sub();
 
 184 sub get_pricegroups {
 
 185   $main::lxdebug->enter_sub();
 
 187   my ($self, $myconfig, $form) = @_;
 
 189   my $dbh = $form->dbconnect($myconfig);
 
 192   my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
 
 193   my $pricegroups = selectall_hashref_query($form, $dbh, $query);
 
 196   foreach my $pg (@{ $pricegroups }) {
 
 197     $form->{"klass_$i"} = "$pg->{id}";
 
 198     $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
 199     $form->{"pricegroup_id_$i"} = "$pg->{id}";
 
 200     $form->{"pricegroup_$i"}    = "$pg->{pricegroup}";
 
 205   $form->{price_rows} = $i - 1;
 
 209   $main::lxdebug->leave_sub();
 
 214 sub retrieve_buchungsgruppen {
 
 215   $main::lxdebug->enter_sub();
 
 217   my ($self, $myconfig, $form) = @_;
 
 221   my $dbh = $form->dbconnect($myconfig);
 
 223   # get buchungsgruppen
 
 224   $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
 
 225   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
 
 227   $main::lxdebug->leave_sub();
 
 231   $main::lxdebug->enter_sub();
 
 233   my ($self, $myconfig, $form) = @_;
 
 235   # connect to database, turn off AutoCommit
 
 236   my $dbh = $form->get_standard_dbh;
 
 239   # make up a unique handle and store in partnumber field
 
 240   # then retrieve the record based on the unique handle to get the id
 
 241   # replace the partnumber field with the actual variable
 
 242   # add records for makemodel
 
 244   # if there is a $form->{id} then replace the old entry
 
 245   # delete all makemodel entries and add the new ones
 
 247   # undo amount formatting
 
 248   map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
 
 249     qw(rop weight listprice sellprice gv lastcost);
 
 251   my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
 
 253   $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
 
 257   my $priceupdate = ', priceupdate = current_date';
 
 260     my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
 
 261     if (!$trans_number->is_unique) {
 
 262       $::lxdebug->leave_sub;
 
 267     $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
 
 268     my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
 
 270     # if item is part of an assembly adjust all assemblies
 
 271     $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
 
 272     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 273     while (my ($id, $qty) = $sth->fetchrow_array) {
 
 274       &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
 
 278     # delete makemodel records
 
 279     do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
 
 281     if ($form->{item} eq 'assembly') {
 
 282       # delete assembly records
 
 283       do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
 
 286     # delete translations
 
 287     do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
 
 289     # Check whether or not the prices have changed. If they haven't
 
 290     # then 'priceupdate' should not be updated.
 
 291     my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
 
 292     $priceupdate        = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
 
 295     my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
 
 297     if ($form->{partnumber} && !$trans_number->is_unique) {
 
 298       $::lxdebug->leave_sub;
 
 302     $form->{partnumber} ||= $trans_number->create_unique;
 
 304     ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
 
 305     do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit});
 
 307     $form->{orphaned} = 1;
 
 309   my $partsgroup_id = undef;
 
 311   if ($form->{partsgroup}) {
 
 312     (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
 
 315   my ($subq_inventory, $subq_expense, $subq_income);
 
 316   if ($form->{"item"} eq "part") {
 
 318       qq|(SELECT bg.inventory_accno_id
 
 319           FROM buchungsgruppen bg
 
 320           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 322     $subq_inventory = "NULL";
 
 325   if ($form->{"item"} ne "assembly") {
 
 327       qq|(SELECT bg.expense_accno_id_0
 
 328           FROM buchungsgruppen bg
 
 329           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 331     $subq_expense = "NULL";
 
 350          buchungsgruppen_id = ?,
 
 352          inventory_accno_id = $subq_inventory,
 
 353          income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
 
 354          expense_accno_id = $subq_expense,
 
 363          not_discountable = ?,
 
 369   @values = ($form->{partnumber},
 
 370              $form->{description},
 
 371              $makemodel ? 't' : 'f',
 
 372              $form->{assembly} ? 't' : 'f',
 
 382              conv_i($form->{buchungsgruppen_id}),
 
 383              conv_i($form->{payment_id}),
 
 384              conv_i($form->{buchungsgruppen_id}),
 
 385              $form->{obsolete} ? 't' : 'f',
 
 388              $form->{shop} ? 't' : 'f',
 
 392              $form->{has_sernumber} ? 't' : 'f',
 
 393              $form->{not_discountable} ? 't' : 'f',
 
 395              conv_i($partsgroup_id),
 
 396              conv_i($form->{price_factor_id}),
 
 399   do_query($form, $dbh, $query, @values);
 
 401   # delete translation records
 
 402   do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
 
 404   if ($form->{language_values} ne "") {
 
 405     foreach my $item (split(/---\+\+\+---/, $form->{language_values})) {
 
 406       my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
 
 407       if ($translation ne "") {
 
 408         $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
 
 409                     VALUES ( ?, ?, ?, ? )|;
 
 410         @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
 
 411         do_query($form, $dbh, $query, @values);
 
 416   # delete price records
 
 417   do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
 
 419   $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
 
 420   $sth   = prepare_query($form, $dbh, $query);
 
 422   # insert price records only if different to sellprice
 
 423   for my $i (1 .. $form->{price_rows}) {
 
 424     my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
 
 425     next unless $price && ($price != $form->{sellprice});
 
 427     @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
 
 428     do_statement($form, $sth, $query, @values);
 
 433   # insert makemodel records
 
 436     for my $i (1 .. $form->{makemodel_rows}) {
 
 437       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
 
 439         $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
 
 440         if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
 
 442             if ($form->{"lastupdate_$i"} eq "") {
 
 443                 $lastupdate = 'now()';
 
 445                 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
 
 448             $lastupdate = 'now()';
 
 450         $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
 
 451                  qq|VALUES (?, ?, ?, ?, ?, ?)|;
 
 452         @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
 
 454         do_query($form, $dbh, $query, @values);
 
 458   # add assembly records
 
 459   if ($form->{item} eq 'assembly') {
 
 461     for my $i (1 .. $form->{assembly_rows}) {
 
 462       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 464       if ($form->{"qty_$i"} != 0) {
 
 465         $form->{"bom_$i"} *= 1;
 
 466         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
 
 467                  qq|VALUES (?, ?, ?, ?)|;
 
 468         @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
 
 469         do_query($form, $dbh, $query, @values);
 
 476     my $shippingdate = "$a[5]-$a[4]-$a[3]";
 
 478     $form->get_employee($dbh);
 
 482   #set expense_accno=inventory_accno if they are different => bilanz
 
 484     ($form->{expense_accno} != $form->{inventory_accno})
 
 485     ? $form->{inventory_accno}
 
 486     : $form->{expense_accno};
 
 488   # get tax rates and description
 
 490     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
 
 492     qq|SELECT c.accno, c.description, t.rate, t.taxnumber
 
 494        WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
 
 496   my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
 
 498   $form->{taxaccount} = "";
 
 499   while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
 
 500     $form->{taxaccount} .= "$ptr->{accno} ";
 
 501     if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
 
 502       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
 503       $form->{"$ptr->{accno}_description"} = $ptr->{description};
 
 504       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
 505       $form->{taxaccount2} .= " $ptr->{accno} ";
 
 509   CVar->save_custom_variables(dbh           => $dbh,
 
 511                               trans_id      => $form->{id},
 
 516   my $rc = $dbh->commit;
 
 518   $main::lxdebug->leave_sub();
 
 523 sub update_assembly {
 
 524   $main::lxdebug->enter_sub();
 
 526   my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
 
 528   my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
 
 529   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
 
 531   while (my ($pid, $aqty) = $sth->fetchrow_array) {
 
 532     &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
 
 537     qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
 
 539   my @values = ($qty * ($form->{sellprice} - $sellprice),
 
 540              $qty * ($form->{weight} - $weight), conv_i($id));
 
 541   do_query($form, $dbh, $query, @values);
 
 543   $main::lxdebug->leave_sub();
 
 546 sub retrieve_assemblies {
 
 547   $main::lxdebug->enter_sub();
 
 549   my ($self, $myconfig, $form) = @_;
 
 551   # connect to database
 
 552   my $dbh = $form->dbconnect($myconfig);
 
 554   my $where = qq|NOT p.obsolete|;
 
 557   if ($form->{partnumber}) {
 
 558     $where .= qq| AND (p.partnumber ILIKE ?)|;
 
 559     push(@values, '%' . $form->{partnumber} . '%');
 
 562   if ($form->{description}) {
 
 563     $where .= qq| AND (p.description ILIKE ?)|;
 
 564     push(@values, '%' . $form->{description} . '%');
 
 567   # retrieve assembly items
 
 569     qq|SELECT p.id, p.partnumber, p.description,
 
 570          p.bin, p.onhand, p.rop,
 
 571          (SELECT sum(p2.inventory_accno_id)
 
 572           FROM parts p2, assembly a
 
 573           WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
 
 575        WHERE NOT p.obsolete AND p.assembly $where|;
 
 577   $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
 
 581   $main::lxdebug->leave_sub();
 
 585   $main::lxdebug->enter_sub();
 
 587   my ($self, $myconfig, $form) = @_;
 
 588   my @values = (conv_i($form->{id}));
 
 589   # connect to database, turn off AutoCommit
 
 590   my $dbh = $form->dbconnect_noauto($myconfig);
 
 592   my %columns = ( "assembly" => "id", "parts" => "id" );
 
 594   for my $table (qw(prices makemodel inventory assembly translation parts)) {
 
 595     my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
 
 596     do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
 
 600   my $rc = $dbh->commit;
 
 603   $main::lxdebug->leave_sub();
 
 609   $main::lxdebug->enter_sub();
 
 611   my ($self, $myconfig, $form) = @_;
 
 613   my $i = $form->{assembly_rows};
 
 615   my $where = qq|1 = 1|;
 
 618   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
 
 620   while (my ($column, $table) = each(%columns)) {
 
 621     next unless ($form->{"${column}_$i"});
 
 622     $where .= qq| AND ${table}.${column} ILIKE ?|;
 
 623     push(@values, '%' . $form->{"${column}_$i"} . '%');
 
 627     $where .= qq| AND NOT (p.id = ?)|;
 
 628     push(@values, conv_i($form->{id}));
 
 631   # Search for part ID overrides all other criteria.
 
 632   if ($form->{"id_${i}"}) {
 
 633     $where  = qq|p.id = ?|;
 
 634     @values = ($form->{"id_${i}"});
 
 637   if ($form->{partnumber}) {
 
 638     $where .= qq| ORDER BY p.partnumber|;
 
 640     $where .= qq| ORDER BY p.description|;
 
 643   # connect to database
 
 644   my $dbh = $form->dbconnect($myconfig);
 
 647     qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
 
 648        p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
 
 649        p.price_factor_id, pfac.factor AS price_factor
 
 651        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 652        LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
 
 654   $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
 
 658   $main::lxdebug->leave_sub();
 
 663 # Warning, deep magic ahead.
 
 664 # This function gets all parts from the database according to the filters specified
 
 667 #   sort revers  - sorting field + direction
 
 670 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
 
 671 #   partnumber ean description partsgroup microfiche drawing
 
 674 #   l_partnumber l_description l_listprice l_sellprice l_lastcost l_priceupdate l_weight l_unit l_bin l_rop l_image l_drawing l_microfiche l_partsgroup
 
 677 #   itemstatus  = active | onhand | short | obsolete | orphaned
 
 678 #   searchitems = part | assembly | service
 
 681 #   make model                               - makemodel
 
 682 #   serialnumber transdatefrom transdateto   - invoice/orderitems
 
 685 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
 
 686 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
 
 687 #   l_soldtotal                              - aggreg join to display total of sold quantity
 
 688 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 689 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
 
 690 #   l_serialnumber                           - belonges to serialnumber filter
 
 691 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
 
 692 #   l_soldtotal                              - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
 
 695 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 697 #   search by overrides of description
 
 699 # disabled sanity checks and changes:
 
 700 #  - searchitems = assembly will no longer disable bought
 
 701 #  - searchitems = service  will no longer disable make and model, although services don't have make/model, it doesn't break the query
 
 702 #  - itemstatus  = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
 
 703 #  - itemstatus  = obsolete will no longer disable onhand, short
 
 704 #  - allow sorting by ean
 
 705 #  - serialnumber filter also works if l_serialnumber isn't ticked
 
 706 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
 
 709   $main::lxdebug->enter_sub();
 
 711   my ($self, $myconfig, $form) = @_;
 
 712   my $dbh = $form->get_standard_dbh($myconfig);
 
 714   $form->{parts}     = +{ };
 
 715   $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
 
 717   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
 
 718   my @project_filters      = qw(projectnumber projectdescription);
 
 719   my @makemodel_filters    = qw(make model);
 
 720   my @invoice_oi_filters   = qw(serialnumber soldtotal);
 
 721   my @apoe_filters         = qw(transdate);
 
 722   my @like_filters         = (@simple_filters, @invoice_oi_filters);
 
 723   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
 
 724   my @simple_l_switches    = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit bin rop image));
 
 725   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
 
 726   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module qty);
 
 727   my @deliverydate_flags   = qw(deliverydate);
 
 728 #  my @other_flags          = qw(onhand); # ToDO: implement these
 
 729 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
 
 731   my @select_tokens = qw(id factor);
 
 732   my @where_tokens  = qw(1=1);
 
 733   my @group_tokens  = ();
 
 735   my %joins_needed  = ();
 
 738     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
 
 739     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
 
 740     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
 
 743          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem,         deliverydate, 'invoice'    AS ioi, project_id, id FROM invoice UNION
 
 744          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
 
 745        ) AS ioi ON ioi.parts_id = p.id|,
 
 748          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
 
 749          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
 
 750          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
 
 751        ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
 
 754            SELECT id, name, 'customer' AS cv FROM customer UNION
 
 755            SELECT id, name, 'vendor'   AS cv FROM vendor
 
 756          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
 
 757     mv         => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
 
 758     project    => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
 
 760   my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
 
 763      deliverydate => 'apoe.', serialnumber => 'ioi.',
 
 764      transdate    => 'apoe.', trans_id     => 'ioi.',
 
 765      module       => 'apoe.', name         => 'cv.',
 
 766      ordnumber    => 'apoe.', make         => 'mm.',
 
 767      quonumber    => 'apoe.', model        => 'mm.',
 
 768      invnumber    => 'apoe.', partsgroup   => 'pg.',
 
 769      lastcost     => 'p.',  , soldtotal    => ' ',
 
 770      factor       => 'pfac.', projectnumber => 'pj.',
 
 771      'SUM(ioi.qty)' => ' ',   projectdescription => 'pj.',
 
 774      serialnumber => 'ioi.',
 
 775      quotation    => 'apoe.',
 
 781   # if the join condition in these blocks are met, the column
 
 782   # of the scecified table will gently override (coalesce actually) the original value
 
 783   # use it to conditionally coalesce values from subtables
 
 784   my @column_override = (
 
 785     #  column name,   prefix,  joins_needed,  nick name (in case column is named like another)
 
 786     [ 'description',  'ioi.',  'invoice_oi'  ],
 
 787     [ 'deliverydate', 'ioi.',  'invoice_oi'  ],
 
 788     [ 'transdate',    'apoe.', 'apoe'        ],
 
 789     [ 'unit',         'ioi.',  'invoice_oi'  ],
 
 790     [ 'sellprice',    'ioi.',  'invoice_oi'  ],
 
 793   # careful with renames. these are HARD, and any filters done on the original column will break
 
 794   my %renamed_columns = (
 
 795     'factor'       => 'price_factor',
 
 796     'SUM(ioi.qty)' => 'soldtotal',
 
 797     'ioi.id'       => 'ioi_id',
 
 799     'projectdescription' => 'projectdescription',
 
 803     projectdescription => 'description',
 
 806   if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
 
 807     @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
 
 810   my $make_token_builder = sub {
 
 811     my $joins_needed = shift;
 
 813       my ($nick, $alias) = @_;
 
 814       my ($col) = $real_column{$nick} || $nick;
 
 815       my @coalesce_tokens =
 
 816         map  { ($_->[1] || 'p.') . $_->[0] }
 
 817         grep { !$_->[2] || $joins_needed->{$_->[2]} }
 
 818         grep { ($_->[3] || $_->[0]) eq $nick }
 
 819         @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
 
 821       my $coalesce = scalar @coalesce_tokens > 1;
 
 823         ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
 
 824         : shift                              @coalesce_tokens)
 
 825         . ($alias && ($coalesce || $renamed_columns{$nick})
 
 826         ?  " AS " . ($renamed_columns{$nick} || $nick)
 
 831   #===== switches and simple filters ========#
 
 833   # special case transdate
 
 834   if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
 
 835     $form->{"l_transdate"} = 1;
 
 836     push @select_tokens, 'transdate';
 
 837     for (qw(transdatefrom transdateto)) {
 
 838       next unless $form->{$_};
 
 839       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
 
 840       push @bind_vars,    $form->{$_};
 
 844   if ($form->{"partsgroup_id"}) {
 
 845     $form->{"l_partsgroup"} = '1'; # show the column
 
 846     push @where_tokens, "pg.id = ?";
 
 847     push @bind_vars, $form->{"partsgroup_id"};
 
 850   foreach (@like_filters) {
 
 851     next unless $form->{$_};
 
 852     $form->{"l_$_"} = '1'; # show the column
 
 853     push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
 
 854     push @bind_vars,    "%$form->{$_}%";
 
 857   foreach (@simple_l_switches) {
 
 858     next unless $form->{"l_$_"};
 
 859     push @select_tokens, $_;
 
 862   for ($form->{searchitems}) {
 
 863     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
 
 864     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
 
 865     push @where_tokens, 'NOT p.assembly'               if /service/;
 
 866     push @where_tokens, '    p.assembly'               if /assembly/;
 
 869   for ($form->{itemstatus}) {
 
 870     push @where_tokens, 'p.id NOT IN
 
 871         (SELECT DISTINCT parts_id FROM invoice UNION
 
 872          SELECT DISTINCT parts_id FROM assembly UNION
 
 873          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
 
 874     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
 
 875     push @where_tokens, 'NOT p.obsolete'               if /active/;
 
 876     push @where_tokens, '    p.obsolete',              if /obsolete/;
 
 877     push @where_tokens, 'p.onhand > 0',                if /onhand/;
 
 878     push @where_tokens, 'p.onhand < p.rop',            if /short/;
 
 881   my $q_assembly_lastcost =
 
 882     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
 
 884         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
 
 885         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
 
 886         WHERE (a_lc.id = p.id)) AS lastcost|;
 
 887   $table_prefix{$q_assembly_lastcost} = ' ';
 
 889   # special case makemodel search
 
 890   # all_parts is based upon the assumption that every parameter is named like the column it represents
 
 891   # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
 
 892   # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
 
 894     push @where_tokens, 'mv.name ILIKE ?';
 
 895     push @bind_vars, "%$form->{make}%";
 
 897   if ($form->{model}) {
 
 898     push @where_tokens, 'mm.model ILIKE ?';
 
 899     push @bind_vars, "%$form->{model}%";
 
 902   # special case: sorting by partnumber
 
 903   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
 
 904   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
 
 905   # ToDO: implement proper functional sorting
 
 906   # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
 
 907   # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
 
 908   #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
 
 909   #  if $form->{sort} eq 'partnumber';
 
 911   #my $order_clause = " ORDER BY $form->{sort} $sort_order";
 
 914   $limit_clause = " LIMIT 100"                   if $form->{top100};
 
 915   $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
 
 917   #=== joins and complicated filters ========#
 
 919   my $bsooqr        = any { $form->{$_} } @oe_flags;
 
 920   my @bsooqr_tokens = ();
 
 922   push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi'  if $bsooqr;
 
 923   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
 
 924   push @select_tokens, $q_assembly_lastcost                                   if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
 
 925   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
 
 926   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
 
 927   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
 
 928   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
 
 929   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
 
 930   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
 
 931   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
 
 933   $joins_needed{partsgroup}  = 1;
 
 934   $joins_needed{pfac}        = 1;
 
 935   $joins_needed{project}     = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
 
 936   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
 
 937   $joins_needed{mv}          = 1 if $joins_needed{makemodel};
 
 938   $joins_needed{cv}          = 1 if $bsooqr;
 
 939   $joins_needed{apoe}        = 1 if $joins_needed{project} || $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
 
 940   $joins_needed{invoice_oi}  = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
 
 942   # special case for description search.
 
 943   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
 
 944   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
 
 945   # find the old entries in of @where_tokens and @bind_vars, and adjust them
 
 946   if ($joins_needed{invoice_oi}) {
 
 947     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
 
 948       next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
 
 949       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
 
 950       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
 
 955   # now the master trick: soldtotal.
 
 956   if ($form->{l_soldtotal}) {
 
 957     push @where_tokens, 'NOT ioi.qty = 0';
 
 958     push @group_tokens, @select_tokens;
 
 959      map { s/.*\sAS\s+//si } @group_tokens;
 
 960     push @select_tokens, 'SUM(ioi.qty)';
 
 963   #============= build query ================#
 
 965   my $token_builder = $make_token_builder->(\%joins_needed);
 
 967   my @sort_cols    = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
 
 968      $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
 
 969   my $sort_order   = ($form->{revers} ? ' DESC' : ' ASC');
 
 970   my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
 
 972   my $select_clause = join ', ',    map { $token_builder->($_, 1) } @select_tokens;
 
 973   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
 
 974   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
 
 975   my $group_clause  = @group_tokens ? ' GROUP BY ' . join ', ',    map { $token_builder->($_) } @group_tokens : '';
 
 977   my %oe_flag_to_cvar = (
 
 980     onorder  => 'orderitems',
 
 981     ordered  => 'orderitems',
 
 983     quoted   => 'orderitems',
 
 986   my ($cvar_where, @cvar_values) = CVar->build_filter_query(
 
 988     trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
 
 990     sub_module     => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
 
 994     $where_clause .= qq| AND ($cvar_where)|;
 
 995     push @bind_vars, @cvar_values;
 
 998   my $query = <<"  SQL";
 
 999     SELECT DISTINCT $select_clause
 
1008   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
 
1010   map { $_->{onhand} *= 1 } @{ $form->{parts} };
 
1012   # fix qty sign in ap. those are saved negative
 
1013   if ($bsooqr && $form->{bought}) {
 
1014     for my $row (@{ $form->{parts} }) {
 
1015       $row->{qty} *= -1 if $row->{module} eq 'ir';
 
1019   # post processing for assembly parts lists (bom)
 
1020   # for each part get the assembly parts and add them into the partlist.
 
1022   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
 
1024       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
 
1025            p.unit, p.bin, p.notes,
 
1026            p.sellprice, p.listprice, p.lastcost,
 
1027            p.rop, p.weight, p.priceupdate,
 
1028            p.image, p.drawing, p.microfiche,
 
1031          INNER JOIN assembly a ON (p.id = a.parts_id)
 
1034     my $sth = prepare_query($form, $dbh, $query);
 
1036     foreach my $item (@{ $form->{parts} }) {
 
1037       push(@assemblies, $item);
 
1038       do_statement($form, $sth, $query, conv_i($item->{id}));
 
1040       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1041         $ref->{assemblyitem} = 1;
 
1042         map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
 
1043         push(@assemblies, $ref);
 
1048     # copy assemblies to $form->{parts}
 
1049     $form->{parts} = \@assemblies;
 
1052   if ($form->{l_pricegroups} ) {
 
1054        SELECT parts_id, price, pricegroup_id
 
1059     my $sth = prepare_query($form, $dbh, $query);
 
1061     foreach my $part (@{ $form->{parts} }) {
 
1062       do_statement($form, $sth, $query, conv_i($part->{id}));
 
1064       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1065         $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
 
1072   $main::lxdebug->leave_sub();
 
1074   return wantarray ? @{ $form->{parts} } : $form->{parts};
 
1077 sub _create_filter_for_priceupdate {
 
1078   $main::lxdebug->enter_sub();
 
1081   my $myconfig = \%main::myconfig;
 
1082   my $form     = $main::form;
 
1085   my $where = '1 = 1';
 
1087   foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
 
1089     $column =~ s/.*\.//;
 
1090     next unless ($form->{$column});
 
1092     $where .= qq| AND $item ILIKE ?|;
 
1093     push(@where_values, '%' . $form->{$column} . '%');
 
1096   foreach my $item (qw(description serialnumber)) {
 
1097     next unless ($form->{$item});
 
1099     $where .= qq| AND (${item} ILIKE ?)|;
 
1100     push(@where_values, '%' . $form->{$item} . '%');
 
1104   # items which were never bought, sold or on an order
 
1105   if ($form->{itemstatus} eq 'orphaned') {
 
1107       qq| AND (p.onhand = 0)
 
1110               SELECT DISTINCT parts_id FROM invoice
 
1112               SELECT DISTINCT parts_id FROM assembly
 
1114               SELECT DISTINCT parts_id FROM orderitems
 
1117   } elsif ($form->{itemstatus} eq 'active') {
 
1118     $where .= qq| AND p.obsolete = '0'|;
 
1120   } elsif ($form->{itemstatus} eq 'obsolete') {
 
1121     $where .= qq| AND p.obsolete = '1'|;
 
1123   } elsif ($form->{itemstatus} eq 'onhand') {
 
1124     $where .= qq| AND p.onhand > 0|;
 
1126   } elsif ($form->{itemstatus} eq 'short') {
 
1127     $where .= qq| AND p.onhand < p.rop|;
 
1131   foreach my $column (qw(make model)) {
 
1132     next unless ($form->{$column});
 
1133     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
 
1134     push(@where_values, '%' . $form->{$column} . '%');
 
1137   $main::lxdebug->leave_sub();
 
1139   return ($where, @where_values);
 
1142 sub get_num_matches_for_priceupdate {
 
1143   $main::lxdebug->enter_sub();
 
1147   my $myconfig = \%main::myconfig;
 
1148   my $form     = $main::form;
 
1150   my $dbh      = $form->get_standard_dbh($myconfig);
 
1152   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
 
1154   my $num_updated = 0;
 
1157   for my $column (qw(sellprice listprice)) {
 
1158     next if ($form->{$column} eq "");
 
1166             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1168     my ($result)  = selectfirst_array_query($form, $dbh, $query, @where_values);
 
1169     $num_updated += $result if (0 <= $result);
 
1178           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1179           WHERE $where) AND (pricegroup_id = ?)|;
 
1180   my $sth = prepare_query($form, $dbh, $query);
 
1182   for my $i (1 .. $form->{price_rows}) {
 
1183     next if ($form->{"price_$i"} eq "");
 
1185     my ($result)  = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1186     $num_updated += $result if (0 <= $result);
 
1190   $main::lxdebug->leave_sub();
 
1192   return $num_updated;
 
1196   $main::lxdebug->enter_sub();
 
1198   my ($self, $myconfig, $form) = @_;
 
1200   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
 
1201   my $num_updated = 0;
 
1203   # connect to database
 
1204   my $dbh = $form->dbconnect_noauto($myconfig);
 
1206   for my $column (qw(sellprice listprice)) {
 
1207     next if ($form->{$column} eq "");
 
1209     my $value = $form->parse_amount($myconfig, $form->{$column});
 
1212     if ($form->{"${column}_type"} eq "percent") {
 
1213       $value = ($value / 100) + 1;
 
1218       qq|UPDATE parts SET $column = $column $operator ?
 
1222             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1224     my $result    = do_query($form, $dbh, $query, $value, @where_values);
 
1225     $num_updated += $result if (0 <= $result);
 
1229     qq|UPDATE prices SET price = price + ?
 
1233           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1234           WHERE $where) AND (pricegroup_id = ?)|;
 
1235   my $sth_add = prepare_query($form, $dbh, $q_add);
 
1238     qq|UPDATE prices SET price = price * ?
 
1242           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1243           WHERE $where) AND (pricegroup_id = ?)|;
 
1244   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
 
1246   for my $i (1 .. $form->{price_rows}) {
 
1247     next if ($form->{"price_$i"} eq "");
 
1249     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
 
1252     if ($form->{"pricegroup_type_$i"} eq "percent") {
 
1253       $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1255       $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1258     $num_updated += $result if (0 <= $result);
 
1262   $sth_multiply->finish();
 
1264   my $rc= $dbh->commit;
 
1267   $main::lxdebug->leave_sub();
 
1269   return $num_updated;
 
1273   $main::lxdebug->enter_sub();
 
1275   my ($self, $module, $myconfig, $form) = @_;
 
1277   # connect to database
 
1278   my $dbh = $form->dbconnect($myconfig);
 
1280   my @values = ('%' . $module . '%');
 
1285       qq|SELECT c.accno, c.description, c.link, c.id,
 
1286            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
 
1287          FROM chart c, parts p
 
1288          WHERE (c.link LIKE ?) AND (p.id = ?)
 
1290     push(@values, conv_i($form->{id}));
 
1294       qq|SELECT c.accno, c.description, c.link, c.id,
 
1295            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
 
1296          FROM chart c, defaults d
 
1301   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1302   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1303     foreach my $key (split(/:/, $ref->{link})) {
 
1304       if ($key =~ /\Q$module\E/) {
 
1305         if (   ($ref->{id} eq $ref->{inventory_accno_id})
 
1306             || ($ref->{id} eq $ref->{income_accno_id})
 
1307             || ($ref->{id} eq $ref->{expense_accno_id})) {
 
1308           push @{ $form->{"${module}_links"}{$key} },
 
1309             { accno       => $ref->{accno},
 
1310               description => $ref->{description},
 
1311               selected    => "selected" };
 
1312           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
 
1314           push @{ $form->{"${module}_links"}{$key} },
 
1315             { accno       => $ref->{accno},
 
1316               description => $ref->{description},
 
1324   # get buchungsgruppen
 
1325   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
 
1328   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
 
1331     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
 
1335   $main::lxdebug->leave_sub();
 
1338 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
 
1340   $main::lxdebug->enter_sub();
 
1342   my ($self, $myconfig, $form, $sortorder) = @_;
 
1343   my $dbh   = $form->dbconnect($myconfig);
 
1344   my $order = qq| p.partnumber|;
 
1345   my $where = qq|1 = 1|;
 
1348   if ($sortorder eq "all") {
 
1349     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
 
1350     push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
 
1352   } elsif ($sortorder eq "partnumber") {
 
1353     $where .= qq| AND (partnumber ILIKE ?)|;
 
1354     push(@values, '%' . $form->{partnumber} . '%');
 
1356   } elsif ($sortorder eq "description") {
 
1357     $where .= qq| AND (description ILIKE ?)|;
 
1358     push(@values, '%' . $form->{description} . '%');
 
1359     $order = "description";
 
1364     qq|SELECT id, partnumber, description, unit, sellprice
 
1366        WHERE $where ORDER BY $order|;
 
1368   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1371   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1372     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
 
1377     $form->{"id_$j"}          = $ref->{id};
 
1378     $form->{"partnumber_$j"}  = $ref->{partnumber};
 
1379     $form->{"description_$j"} = $ref->{description};
 
1380     $form->{"unit_$j"}        = $ref->{unit};
 
1381     $form->{"sellprice_$j"}   = $ref->{sellprice};
 
1382     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
 
1388   $main::lxdebug->leave_sub();
 
1393 # gets sum of sold part with part_id
 
1395   $main::lxdebug->enter_sub();
 
1397   my ($dbh, $id) = @_;
 
1399   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
 
1400   my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
 
1403   $main::lxdebug->leave_sub();
 
1406 }    #end get_soldtotal
 
1408 sub retrieve_languages {
 
1409   $main::lxdebug->enter_sub();
 
1411   my ($self, $myconfig, $form) = @_;
 
1413   # connect to database
 
1414   my $dbh = $form->dbconnect($myconfig);
 
1420   if ($form->{language_values} ne "") {
 
1422       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
 
1424          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
 
1425          ORDER BY lower(l.description)|;
 
1426     @values = (conv_i($form->{id}));
 
1429     $query = qq|SELECT id, description
 
1431                 ORDER BY lower(description)|;
 
1434   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
 
1438   $main::lxdebug->leave_sub();
 
1443 sub follow_account_chain {
 
1444   $main::lxdebug->enter_sub(2);
 
1446   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
 
1448   my @visited_accno_ids = ($accno_id);
 
1452   $form->{ACCOUNT_CHAIN_BY_ID} ||= {
 
1453     map { $_->{id} => $_ }
 
1454       selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
 
1455     SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
 
1457     LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
 
1458     WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
 
1462     my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
 
1463     last unless ($ref && $ref->{"is_valid"} &&
 
1464                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
 
1465     $accno_id = $ref->{"new_chart_id"};
 
1466     $accno = $ref->{"accno"};
 
1467     push(@visited_accno_ids, $accno_id);
 
1470   $main::lxdebug->leave_sub(2);
 
1472   return ($accno_id, $accno);
 
1475 sub retrieve_accounts {
 
1476   $main::lxdebug->enter_sub;
 
1479   my $myconfig = shift;
 
1481   my $dbh      = $form->get_standard_dbh;
 
1482   my %args     = @_;     # index => part_id
 
1484   $form->{taxzone_id} *= 1;
 
1486   return unless grep $_, values %args; # shortfuse if no part_id supplied
 
1488   # transdate madness.
 
1490   if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
 
1491     # use deliverydate for sales and purchase invoice, if it exists
 
1492     # also use deliverydate for credit notes
 
1493     if (!$form->{deliverydate}) {
 
1494       $transdate = $form->{invdate};
 
1496       $transdate = $form->{deliverydate};
 
1498   } elsif ($form->{script} eq 'ir.pl') {
 
1499     # when a purchase invoice is opened from the report of purchase invoices 
 
1500     # $form->{type} isn't set, but $form->{script} is, not sure why this is or
 
1501     # whether this distinction matters in some other scenario. Otherwise one
 
1502     # could probably take out this elsif and add a
 
1503     # " or $form->{script} eq 'ir.pl' "
 
1504     # to the above if-statement
 
1505     if (!$form->{deliverydate}) {
 
1506       $transdate = $form->{invdate};
 
1508       $transdate = $form->{deliverydate};
 
1510   } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
 
1511     # if credit_note has a deliverydate, use this instead of invdate
 
1512     # useful for credit_notes of invoices from an old period with different tax
 
1513     # if there is no deliverydate then invdate is used, old default (see next elsif)
 
1514     # Falls hier der Stichtag für Steuern anders bestimmt wird,
 
1515     # entsprechend auch bei Taxkeys.pm anpassen
 
1516     $transdate = $form->{deliverydate};
 
1517   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
 
1518     $transdate = $form->{invdate};
 
1520     $transdate = $form->{transdate};
 
1523   if ($transdate eq "") {
 
1524     $transdate = DateTime->today_local->to_lxoffice;
 
1526     $transdate = $dbh->quote($transdate);
 
1529   my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
 
1531   my @part_ids = grep { $_ } values %args;
 
1532   my $in       = join ',', ('?') x @part_ids;
 
1534   my %accno_by_part = map { $_->{id} => $_ }
 
1535     selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
 
1537       p.id, p.inventory_accno_id AS is_part,
 
1538       bg.inventory_accno_id,
 
1539       bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
 
1540       bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
 
1541       c1.accno AS inventory_accno,
 
1542       c2.accno AS income_accno,
 
1543       c3.accno AS expense_accno
 
1545     LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
 
1546     LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
 
1547     LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
 
1548     LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
 
1552   my $sth_tax = prepare_query($::form, $dbh, <<SQL);
 
1553     SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
 
1555     LEFT JOIN chart c ON c.id = t.chart_id
 
1559        WHERE tk.chart_id = ? AND startdate <= ?
 
1560        ORDER BY startdate DESC LIMIT 1)
 
1563   while (my ($index => $part_id) = each %args) {
 
1564     my $ref = $accno_by_part{$part_id} or next;
 
1566     $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
 
1569     for my $type (qw(inventory income expense)) {
 
1570       next unless $ref->{"${type}_accno_id"};
 
1571       ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
 
1572         $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
 
1575     $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
 
1577     $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
 
1578     $ref = $sth_tax->fetchrow_hashref or next;
 
1580     $form->{"taxaccounts_$index"} = $ref->{"accno"};
 
1581     $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
 
1583     $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
 
1588   $::lxdebug->leave_sub;
 
1591 sub get_basic_part_info {
 
1592   $main::lxdebug->enter_sub();
 
1597   Common::check_params(\%params, qw(id));
 
1599   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
 
1602     $main::lxdebug->leave_sub();
 
1606   my $myconfig = \%main::myconfig;
 
1607   my $form     = $main::form;
 
1609   my $dbh      = $form->get_standard_dbh($myconfig);
 
1611   my $query    = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
 
1613   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
 
1615   if ('' eq ref $params{id}) {
 
1616     $info = $info->[0] || { };
 
1618     $main::lxdebug->leave_sub();
 
1622   my %info_map = map { $_->{id} => $_ } @{ $info };
 
1624   $main::lxdebug->leave_sub();
 
1629 sub prepare_parts_for_printing {
 
1630   $main::lxdebug->enter_sub();
 
1635   my $myconfig = $params{myconfig} || \%main::myconfig;
 
1636   my $form     = $params{form}     || $main::form;
 
1638   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1640   my $prefix   = $params{prefix} || 'id_';
 
1641   my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
 
1643   my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
 
1646     $main::lxdebug->leave_sub();
 
1650   my $placeholders = join ', ', ('?') x scalar(@part_ids);
 
1651   my $query        = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
 
1653                         LEFT JOIN vendor v ON (mm.make = v.id)
 
1654                         WHERE mm.parts_id IN ($placeholders)|;
 
1658   my $sth          = prepare_execute_query($form, $dbh, $query, @part_ids);
 
1660   while (my $ref = $sth->fetchrow_hashref()) {
 
1661     $makemodel{$ref->{parts_id}} ||= [];
 
1662     push @{ $makemodel{$ref->{parts_id}} }, $ref;
 
1667   my @columns = qw(ean image microfiche drawing weight);
 
1669   $query      = qq|SELECT id, | . join(', ', @columns) . qq|
 
1671                    WHERE id IN ($placeholders)|;
 
1673   my %data    = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
 
1675   map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
 
1677   foreach my $i (1 .. $rowcount) {
 
1678     my $id = $form->{"${prefix}${i}"};
 
1682     foreach (@columns) {
 
1683       push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
 
1686     push @{ $form->{TEMPLATE_ARRAYS}{make} },  [];
 
1687     push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
 
1689     next if (!$makemodel{$id});
 
1691     foreach my $ref (@{ $makemodel{$id} }) {
 
1692       map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
 
1696   $main::lxdebug->leave_sub();