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);
 
  45   $main::lxdebug->enter_sub();
 
  47   my ($self, $myconfig, $form) = @_;
 
  50   my $dbh = $form->dbconnect($myconfig);
 
  56          c1.accno AS inventory_accno,
 
  57          c2.accno AS income_accno,
 
  58          c3.accno AS expense_accno,
 
  61        LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
 
  62        LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
 
  63        LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
 
  64        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
  66   my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
  68   # copy to $form variables
 
  69   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
 
  73   # part or service item
 
  74   $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
 
  75   if ($form->{assembly}) {
 
  76     $form->{item} = 'assembly';
 
  78     # retrieve assembly items
 
  80       qq|SELECT p.id, p.partnumber, p.description,
 
  81            p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
 
  82            pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
 
  84          JOIN assembly a ON (a.parts_id = p.id)
 
  85          LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
  86          LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
 
  89     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
  91     $form->{assembly_rows} = 0;
 
  92     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
  93       $form->{assembly_rows}++;
 
  94       foreach my $key (keys %{$ref}) {
 
  95         $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
 
 102   # setup accno hash for <option checked> {amount} is used in create_links
 
 103   $form->{amount}{IC}         = $form->{inventory_accno};
 
 104   $form->{amount}{IC_income}  = $form->{income_accno};
 
 105   $form->{amount}{IC_sale}    = $form->{income_accno};
 
 106   $form->{amount}{IC_expense} = $form->{expense_accno};
 
 107   $form->{amount}{IC_cogs}    = $form->{expense_accno};
 
 109   my @pricegroups          = ();
 
 110   my @pricegroups_not_used = ();
 
 114     qq|SELECT p.parts_id, p.pricegroup_id, p.price,
 
 115          (SELECT pg.pricegroup
 
 117           WHERE pg.id = p.pricegroup_id) AS pricegroup
 
 120        ORDER BY pricegroup|;
 
 121   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 125   while (($form->{"klass_$i"}, $form->{"pricegroup_id_$i"},
 
 126           $form->{"price_$i"}, $form->{"pricegroup_$i"})
 
 127          = $sth->fetchrow_array()) {
 
 128     push @pricegroups, $form->{"pricegroup_id_$i"};
 
 135   $query = qq|SELECT id, pricegroup FROM pricegroup|;
 
 136   $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
 
 138   #find not used pricegroups
 
 139   while (my $tmp = pop(@{ $form->{PRICEGROUPS} })) {
 
 141     foreach my $item (@pricegroups) {
 
 142       if ($item eq $tmp->{id}) {
 
 147     push(@pricegroups_not_used, $tmp) unless ($in_use);
 
 150   # if not used pricegroups are avaible
 
 151   if (@pricegroups_not_used) {
 
 153     foreach my $name (@pricegroups_not_used) {
 
 154       $form->{"klass_$i"} = "$name->{id}";
 
 155       $form->{"pricegroup_id_$i"} = "$name->{id}";
 
 156       $form->{"pricegroup_$i"}    = "$name->{pricegroup}";
 
 162   $form->{price_rows} = $i - 1;
 
 164   unless ($form->{item} eq 'service') {
 
 167     if ($form->{makemodel}) {
 
 168       $query = qq|SELECT m.make, m.model FROM makemodel m | .
 
 169                qq|WHERE m.parts_id = ?|;
 
 170       my @values = ($form->{id});
 
 171       $sth = $dbh->prepare($query);
 
 172       $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
 
 175       while (($form->{"make_$i"}, $form->{"model_$i"}) = $sth->fetchrow_array)
 
 180       $form->{makemodel_rows} = $i - 1;
 
 186   $form->{language_values} = "";
 
 187   $query = qq|SELECT language_id, translation, longdescription
 
 190   my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 191   while (my $tr = $trq->fetchrow_hashref("NAME_lc")) {
 
 192     $form->{language_values} .= "---+++---" . join('--++--', @{$tr}{qw(language_id translation longdescription)});
 
 196   # now get accno for taxes
 
 199        FROM chart c, partstax pt
 
 200        WHERE (pt.chart_id = c.id) AND (pt.parts_id = ?)|;
 
 201   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 202   while (my ($key) = $sth->fetchrow_array) {
 
 203     $form->{amount}{$key} = $key;
 
 209   my @referencing_tables = qw(invoice orderitems inventory rmaitems);
 
 210   my %column_map         = ( );
 
 211   my $parts_id           = conv_i($form->{id});
 
 213   $form->{orphaned}      = 1;
 
 215   foreach my $table (@referencing_tables) {
 
 216     my $column  = $column_map{$table} || 'parts_id';
 
 217     $query      = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
 
 218     my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
 
 221       $form->{orphaned} = 0;
 
 226   $form->{"unit_changeable"} = $form->{orphaned};
 
 230   $main::lxdebug->leave_sub();
 
 233 sub get_pricegroups {
 
 234   $main::lxdebug->enter_sub();
 
 236   my ($self, $myconfig, $form) = @_;
 
 238   my $dbh = $form->dbconnect($myconfig);
 
 241   my $query = qq|SELECT id, pricegroup FROM pricegroup|;
 
 242   my $pricegroups = selectall_hashref_query($form, $dbh, $query);
 
 245   foreach my $pg (@{ $pricegroups }) {
 
 246     $form->{"klass_$i"} = "$pg->{id}";
 
 247     $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
 248     $form->{"pricegroup_id_$i"} = "$pg->{id}";
 
 249     $form->{"pricegroup_$i"}    = "$pg->{pricegroup}";
 
 254   $form->{price_rows} = $i - 1;
 
 258   $main::lxdebug->leave_sub();
 
 263 sub retrieve_buchungsgruppen {
 
 264   $main::lxdebug->enter_sub();
 
 266   my ($self, $myconfig, $form) = @_;
 
 270   my $dbh = $form->dbconnect($myconfig);
 
 272   # get buchungsgruppen
 
 273   $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
 
 274   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
 
 276   $main::lxdebug->leave_sub();
 
 280   $main::lxdebug->enter_sub();
 
 282   my ($self, $myconfig, $form) = @_;
 
 284   # connect to database, turn off AutoCommit
 
 285   my $dbh = $form->dbconnect_noauto($myconfig);
 
 288   # make up a unique handle and store in partnumber field
 
 289   # then retrieve the record based on the unique handle to get the id
 
 290   # replace the partnumber field with the actual variable
 
 291   # add records for makemodel
 
 293   # if there is a $form->{id} then replace the old entry
 
 294   # delete all makemodel entries and add the new ones
 
 296   # undo amount formatting
 
 297   map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
 
 298     qw(rop weight listprice sellprice gv lastcost);
 
 300   my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
 
 302   $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
 
 306   my $priceupdate = ', priceupdate = current_date';
 
 311     $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
 
 312     my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
 
 314     # if item is part of an assembly adjust all assemblies
 
 315     $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
 
 316     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 317     while (my ($id, $qty) = $sth->fetchrow_array) {
 
 318       &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
 
 322     if ($form->{item} ne 'service') {
 
 323       # delete makemodel records
 
 324       do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
 
 327     if ($form->{item} eq 'assembly') {
 
 328       # delete assembly records
 
 329       do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
 
 333     do_query($form, $dbh, qq|DELETE FROM partstax WHERE parts_id = ?|, conv_i($form->{id}));
 
 335     # delete translations
 
 336     do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
 
 338     # Check whether or not the prices have changed. If they haven't
 
 339     # then 'priceupdate' should not be updated.
 
 340     my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
 
 341     $priceupdate        = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
 
 344     my ($count) = selectrow_query($form, $dbh, qq|SELECT COUNT(*) FROM parts WHERE partnumber = ?|, $form->{partnumber});
 
 346       $main::lxdebug->leave_sub();
 
 350     ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
 
 351     do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber) VALUES (?, '')|, $form->{id});
 
 353     $form->{orphaned} = 1;
 
 354     if ($form->{partnumber} eq "" && $form->{"item"} eq "service") {
 
 355       $form->{partnumber} = $form->update_defaults($myconfig, "servicenumber");
 
 357     if ($form->{partnumber} eq "" && $form->{"item"} ne "service") {
 
 358       $form->{partnumber} = $form->update_defaults($myconfig, "articlenumber");
 
 362   my $partsgroup_id = 0;
 
 364   if ($form->{partsgroup}) {
 
 365     (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
 
 368   my ($subq_inventory, $subq_expense, $subq_income);
 
 369   if ($form->{"item"} eq "part") {
 
 371       qq|(SELECT bg.inventory_accno_id
 
 372           FROM buchungsgruppen bg
 
 373           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 375     $subq_inventory = "NULL";
 
 378   if ($form->{"item"} ne "assembly") {
 
 380       qq|(SELECT bg.expense_accno_id_0
 
 381           FROM buchungsgruppen bg
 
 382           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 384     $subq_expense = "NULL";
 
 403          buchungsgruppen_id = ?,
 
 405          inventory_accno_id = $subq_inventory,
 
 406          income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
 
 407          expense_accno_id = $subq_expense,
 
 415          not_discountable = ?,
 
 421   @values = ($form->{partnumber},
 
 422              $form->{description},
 
 423              $makemodel ? 't' : 'f',
 
 424              $form->{assembly} ? 't' : 'f',
 
 434              conv_i($form->{buchungsgruppen_id}),
 
 435              conv_i($form->{payment_id}),
 
 436              conv_i($form->{buchungsgruppen_id}),
 
 437              $form->{obsolete} ? 't' : 'f',
 
 440              $form->{shop} ? 't' : 'f',
 
 444              $form->{not_discountable} ? 't' : 'f',
 
 446              conv_i($partsgroup_id),
 
 447              conv_i($form->{price_factor_id}),
 
 450   do_query($form, $dbh, $query, @values);
 
 452   # delete translation records
 
 453   do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
 
 455   if ($form->{language_values} ne "") {
 
 456     foreach my $item (split(/---\+\+\+---/, $form->{language_values})) {
 
 457       my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
 
 458       if ($translation ne "") {
 
 459         $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
 
 460                     VALUES ( ?, ?, ?, ? )|;
 
 461         @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
 
 462         do_query($form, $dbh, $query, @values);
 
 467   # delete price records
 
 468   do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
 
 470   # insert price records only if different to sellprice
 
 471   for my $i (1 .. $form->{price_rows}) {
 
 472     my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
 
 474       $form->{"price_$i"} = $form->{sellprice};
 
 478          || $form->{"klass_$i"}
 
 479          || $form->{"pricegroup_id_$i"})
 
 480         and $price != $form->{sellprice}
 
 482       #$klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
 
 483       $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) | .
 
 485       @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
 
 486       do_query($form, $dbh, $query, @values);
 
 490   # insert makemodel records
 
 491   unless ($form->{item} eq 'service') {
 
 492     for my $i (1 .. $form->{makemodel_rows}) {
 
 493       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
 
 495         $query = qq|INSERT INTO makemodel (parts_id, make, model) | .
 
 496                              qq|VALUES (?, ?, ?)|;
 
 497                     @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"});
 
 499         do_query($form, $dbh, $query, @values);
 
 505   foreach my $item (split(/ /, $form->{taxaccounts})) {
 
 506     if ($form->{"IC_tax_$item"}) {
 
 508         qq|INSERT INTO partstax (parts_id, chart_id)
 
 509            VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
 
 510                         @values = (conv_i($form->{id}), $item);
 
 511       do_query($form, $dbh, $query, @values);
 
 515   # add assembly records
 
 516   if ($form->{item} eq 'assembly') {
 
 518     for my $i (1 .. $form->{assembly_rows}) {
 
 519       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 521       if ($form->{"qty_$i"} != 0) {
 
 522         $form->{"bom_$i"} *= 1;
 
 523         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
 
 524                              qq|VALUES (?, ?, ?, ?)|;
 
 525                     @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
 
 526         do_query($form, $dbh, $query, @values);
 
 533     my $shippingdate = "$a[5]-$a[4]-$a[3]";
 
 535     $form->get_employee($dbh);
 
 539   #set expense_accno=inventory_accno if they are different => bilanz
 
 541     ($form->{expense_accno} != $form->{inventory_accno})
 
 542     ? $form->{inventory_accno}
 
 543     : $form->{expense_accno};
 
 545   # get tax rates and description
 
 547     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
 
 549     qq|SELECT c.accno, c.description, t.rate, t.taxnumber
 
 551        WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
 
 553   my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
 
 555   $form->{taxaccount} = "";
 
 556   while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
 
 557     $form->{taxaccount} .= "$ptr->{accno} ";
 
 558     if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
 
 559       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
 560       $form->{"$ptr->{accno}_description"} = $ptr->{description};
 
 561       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
 562       $form->{taxaccount2} .= " $ptr->{accno} ";
 
 566   CVar->save_custom_variables('dbh'       => $dbh,
 
 568                               'trans_id'  => $form->{id},
 
 569                               'variables' => $form);
 
 572   my $rc = $dbh->commit;
 
 575   $main::lxdebug->leave_sub();
 
 580 sub update_assembly {
 
 581   $main::lxdebug->enter_sub();
 
 583   my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
 
 585   my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
 
 586   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
 
 588   while (my ($pid, $aqty) = $sth->fetchrow_array) {
 
 589     &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
 
 594     qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
 
 596   my @values = ($qty * ($form->{sellprice} - $sellprice),
 
 597              $qty * ($form->{weight} - $weight), conv_i($id));
 
 598   do_query($form, $dbh, $query, @values);
 
 600   $main::lxdebug->leave_sub();
 
 603 sub retrieve_assemblies {
 
 604   $main::lxdebug->enter_sub();
 
 606   my ($self, $myconfig, $form) = @_;
 
 608   # connect to database
 
 609   my $dbh = $form->dbconnect($myconfig);
 
 611   my $where = qq|NOT p.obsolete|;
 
 614   if ($form->{partnumber}) {
 
 615     $where .= qq| AND (p.partnumber ILIKE ?)|;
 
 616     push(@values, '%' . $form->{partnumber} . '%');
 
 619   if ($form->{description}) {
 
 620     $where .= qq| AND (p.description ILIKE ?)|;
 
 621     push(@values, '%' . $form->{description} . '%');
 
 624   # retrieve assembly items
 
 626     qq|SELECT p.id, p.partnumber, p.description,
 
 627          p.bin, p.onhand, p.rop,
 
 628          (SELECT sum(p2.inventory_accno_id)
 
 629           FROM parts p2, assembly a
 
 630           WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
 
 632        WHERE NOT p.obsolete AND p.assembly $where|;
 
 634   $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
 
 638   $main::lxdebug->leave_sub();
 
 642   $main::lxdebug->enter_sub();
 
 644   my ($self, $myconfig, $form) = @_;
 
 645   my @values = (conv_i($form->{id}));
 
 646   # connect to database, turn off AutoCommit
 
 647   my $dbh = $form->dbconnect_noauto($myconfig);
 
 649   my %columns = ( "assembly" => "id", "parts" => "id" );
 
 651   for my $table (qw(prices partstax makemodel inventory assembly license translation parts)) {
 
 652     my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
 
 653     do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
 
 657   my $rc = $dbh->commit;
 
 660   $main::lxdebug->leave_sub();
 
 666   $main::lxdebug->enter_sub();
 
 668   my ($self, $myconfig, $form) = @_;
 
 670   my $i = $form->{assembly_rows};
 
 672   my $where = qq|1 = 1|;
 
 675   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
 
 677   while (my ($column, $table) = each(%columns)) {
 
 678     next unless ($form->{"${column}_$i"});
 
 679     $where .= qq| AND ${table}.${column} ILIKE ?|;
 
 680     push(@values, '%' . $form->{"${column}_$i"} . '%');
 
 684     $where .= qq| AND NOT (p.id = ?)|;
 
 685     push(@values, conv_i($form->{id}));
 
 688   if ($form->{partnumber}) {
 
 689     $where .= qq| ORDER BY p.partnumber|;
 
 691     $where .= qq| ORDER BY p.description|;
 
 694   # connect to database
 
 695   my $dbh = $form->dbconnect($myconfig);
 
 698     qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
 
 699        p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
 
 700        p.price_factor_id, pfac.factor AS price_factor
 
 702        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 703        LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
 
 705   $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
 
 709   $main::lxdebug->leave_sub();
 
 714 # Warning, deep magic ahead.
 
 715 # This function gets all parts from the database according to the filters specified
 
 718 #   sort revers  - sorting field + direction
 
 721 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
 
 722 #   partnumber ean description partsgroup microfiche drawing
 
 725 #   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
 
 728 #   itemstatus  = active | onhand | short | obsolete | orphaned
 
 729 #   searchitems = part | assembly | service
 
 732 #   make model                               - makemodel
 
 733 #   serialnumber transdatefrom transdateto   - invoice/orderitems
 
 736 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
 
 737 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
 
 738 #   l_soldtotal                              - aggreg join to display total of sold quantity
 
 739 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 740 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
 
 741 #   l_serialnumber                           - belonges to serialnumber filter
 
 742 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
 
 743 #   l_soldtotal                              - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
 
 746 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 748 #   search by overrides of description
 
 750 # disabled sanity checks and changes:
 
 751 #  - searchitems = assembly will no longer disable bought
 
 752 #  - searchitems = service  will no longer disable make and model, although services don't have make/model, it doesn't break the query
 
 753 #  - itemstatus  = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
 
 754 #  - itemstatus  = obsolete will no longer disable onhand, short
 
 755 #  - allow sorting by ean
 
 756 #  - serialnumber filter also works if l_serialnumber isn't ticked
 
 757 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
 
 760   $main::lxdebug->enter_sub();
 
 762   my ($self, $myconfig, $form) = @_;
 
 763   my $dbh = $form->get_standard_dbh($myconfig);
 
 765   $form->{parts}     = +{ };
 
 766   $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
 
 768   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
 
 769   my @makemodel_filters    = qw(make model);
 
 770   my @invoice_oi_filters   = qw(serialnumber soldtotal);
 
 771   my @apoe_filters         = qw(transdate);
 
 772   my @like_filters         = (@simple_filters, @makemodel_filters, @invoice_oi_filters);
 
 773   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
 
 774   my @simple_l_switches    = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
 
 775   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
 
 776   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module qty);
 
 777   my @deliverydate_flags   = qw(deliverydate);
 
 778 #  my @other_flags          = qw(onhand); # ToDO: implement these
 
 779 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
 
 781   my @select_tokens = qw(id factor);
 
 782   my @where_tokens  = qw(1=1);
 
 783   my @group_tokens  = ();
 
 785   my %joins_needed  = ();
 
 788     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
 
 789     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
 
 790     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
 
 793          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem,         deliverydate, 'invoice'    AS ioi FROM invoice UNION
 
 794          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi FROM orderitems
 
 795        ) AS ioi ON ioi.parts_id = p.id|,
 
 798          SELECT id, transdate, 'ir' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation, NULL AS customer_id,         vendor_id, NULL AS deliverydate, 'invoice'    AS ioi FROM ap UNION
 
 799          SELECT id, transdate, 'is' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation,         customer_id, NULL AS vendor_id,         deliverydate, 'invoice'    AS ioi FROM ar UNION
 
 800          SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber,          quotation,         customer_id,         vendor_id, NULL AS deliverydate, 'orderitems' AS ioi FROM oe
 
 801        ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
 
 804            SELECT id, name, 'customer' AS cv FROM customer UNION
 
 805            SELECT id, name, 'vendor'   AS cv FROM vendor
 
 806          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
 
 808   my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
 
 811      deliverydate => 'apoe.', serialnumber => 'ioi.',
 
 812      transdate    => 'apoe.', trans_id     => 'ioi.',
 
 813      module       => 'apoe.', name         => 'cv.',
 
 814      ordnumber    => 'apoe.', make         => 'mm.',
 
 815      quonumber    => 'apoe.', model        => 'mm.',
 
 816      invnumber    => 'apoe.', partsgroup   => 'pg.',
 
 819      'SUM(ioi.qty)' => ' ',
 
 822      serialnumber => 'ioi.',
 
 823      quotation    => 'apoe.',
 
 827   # if the join condition in these blocks are met, the column
 
 828   # of the scecified table will gently override (coalesce actually) the original value
 
 829   # use it to conditionally coalesce values from subtables
 
 830   my @column_override = (
 
 831     #  column name,   prefix,  joins_needed
 
 832     [ 'description',  'ioi.',  'invoice_oi'  ],
 
 833     [ 'deliverydate', 'ioi.',  'invoice_oi'  ],
 
 834     [ 'transdate',    'apoe.', 'apoe'        ],
 
 835     [ 'unit',         'ioi.',  'invoice_oi'  ],
 
 838   # careful with renames. these are HARD, and any filters done on the original column will break
 
 839   my %renamed_columns = (
 
 840     'factor'       => 'price_factor',
 
 841     'SUM(ioi.qty)' => 'soldtotal',
 
 844   if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
 
 845     @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
 
 848   my $make_token_builder = sub {
 
 849     my $joins_needed = shift;
 
 851       my ($col, $alias) = @_;
 
 852       my @coalesce_tokens =
 
 853         map  { ($_->[1] || 'p.') . $_->[0] }
 
 854         grep { !$_->[2] || $joins_needed->{$_->[2]} }
 
 855         grep {  $_->[0] eq $col }
 
 856         @column_override, [ $col, $table_prefix{$col} ];
 
 858       my $coalesce = scalar @coalesce_tokens > 1;
 
 860         ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
 
 861         : shift                              @coalesce_tokens)
 
 862         . ($alias && ($coalesce || $renamed_columns{$col})
 
 863         ?  " AS " . ($renamed_columns{$col} || $col)
 
 868   #===== switches and simple filters ========#
 
 870   # special case transdate
 
 871   if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
 
 872     $form->{"l_transdate"} = 1;
 
 873     push @select_tokens, 'transdate';
 
 874     for (qw(transdatefrom transdateto)) {
 
 875       next unless $form->{$_};
 
 876       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
 
 877       push @bind_vars,    $form->{$_};
 
 881   foreach (@like_filters) {
 
 882     next unless $form->{$_};
 
 883     $form->{"l_$_"} = '1'; # show the column
 
 884     push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
 
 885     push @bind_vars,    "%$form->{$_}%";
 
 888   foreach (@simple_l_switches) {
 
 889     next unless $form->{"l_$_"};
 
 890     push @select_tokens, $_;
 
 893   for ($form->{searchitems}) {
 
 894     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
 
 895     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
 
 896     push @where_tokens, 'NOT p.assembly'               if /service/;
 
 897     push @where_tokens, '    p.assembly'               if /assembly/;
 
 900   for ($form->{itemstatus}) {
 
 901     push @where_tokens, 'p.id NOT IN
 
 902         (SELECT DISTINCT parts_id FROM invoice UNION
 
 903          SELECT DISTINCT parts_id FROM assembly UNION
 
 904          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
 
 905     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
 
 906     push @where_tokens, 'NOT p.obsolete'               if /active/;
 
 907     push @where_tokens, '    p.obsolete',              if /obsolete/;
 
 908     push @where_tokens, 'p.onhand > 0',                if /onhand/;
 
 909     push @where_tokens, 'p.onhand < p.rop',            if /short/;
 
 912   my $q_assembly_lastcost =
 
 913     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
 
 915         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
 
 916         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
 
 917         WHERE (a_lc.id = p.id)) AS lastcost|;
 
 918   $table_prefix{$q_assembly_lastcost} = ' ';
 
 920   # special case: sorting by partnumber
 
 921   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
 
 922   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
 
 923   # ToDO: implement proper functional sorting
 
 924   # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
 
 925   # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
 
 926   #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
 
 927   #  if $form->{sort} eq 'partnumber';
 
 929   #my $order_clause = " ORDER BY $form->{sort} $sort_order";
 
 931   my $limit_clause = " LIMIT 100" if $form->{top100};
 
 933   #=== joins and complicated filters ========#
 
 935   my $bsooqr        = any { $form->{$_} } @oe_flags;
 
 936   my @bsooqr_tokens = ();
 
 938   push @select_tokens, @qsooqr_flags, 'quotation', 'cv'                       if $bsooqr;
 
 939   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
 
 940   push @select_tokens, $q_assembly_lastcost                                   if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
 
 941   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
 
 942   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
 
 943   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
 
 944   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
 
 945   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
 
 946   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
 
 947   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
 
 949   $joins_needed{partsgroup}  = 1;
 
 950   $joins_needed{pfac}        = 1;
 
 951   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
 
 952   $joins_needed{cv}          = 1 if $bsooqr;
 
 953   $joins_needed{apoe}        = 1 if $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
 
 954   $joins_needed{invoice_oi}  = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
 
 956   # in bsoorq, use qtys instead of onhand
 
 957   if ($joins_needed{invoice_oi}) {
 
 958     $renamed_columns{onhand} = 'onhand_before_bsooqr';
 
 959     $renamed_columns{qty}    = 'onhand';
 
 962   # special case for description search.
 
 963   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
 
 964   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
 
 965   # find the old entries in of @where_tokens and @bind_vars, and adjust them
 
 966   if ($joins_needed{invoice_oi}) {
 
 967     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
 
 968       next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
 
 969       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
 
 970       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
 
 975   # now the master trick: soldtotal.
 
 976   if ($form->{l_soldtotal}) {
 
 977     push @where_tokens, 'ioi.qty >= 0';
 
 978     push @group_tokens, @select_tokens;
 
 979      map { s/.*\sAS\s+//si } @group_tokens;
 
 980     push @select_tokens, 'SUM(ioi.qty)';
 
 983   #============= build query ================#
 
 985   my $token_builder = $make_token_builder->(\%joins_needed);
 
 987   my @sort_cols    = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
 
 988      $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
 
 989   my $sort_order   = ($form->{revers} ? ' DESC' : ' ASC');
 
 990   my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
 
 992   my $select_clause = join ', ',    map { $token_builder->($_, 1) } @select_tokens;
 
 993   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
 
 994   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
 
 995   my $group_clause  = ' GROUP BY ' . join ', ',    map { $token_builder->($_) } @group_tokens if scalar @group_tokens;
 
 997   my ($cvar_where, @cvar_values) = CVar->build_filter_query('module'         => 'IC',
 
 998                                                             'trans_id_field' => 'p.id',
 
1002     $where_clause .= qq| AND ($cvar_where)|;
 
1003     push @bind_vars, @cvar_values;
 
1006   my $query = qq|SELECT DISTINCT $select_clause FROM parts p $join_clause WHERE $where_clause $group_clause $order_clause $limit_clause|;
 
1008   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
 
1010   map { $_->{onhand} *= 1 } @{ $form->{parts} };
 
1012   # post processing for assembly parts lists (bom)
 
1013   # for each part get the assembly parts and add them into the partlist.
 
1015   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
 
1017       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
 
1019            p.sellprice, p.listprice, p.lastcost,
 
1020            p.rop, p.weight, p.priceupdate,
 
1021            p.image, p.drawing, p.microfiche,
 
1024          INNER JOIN assembly a ON (p.id = a.parts_id)
 
1027     my $sth = prepare_query($form, $dbh, $query);
 
1029     foreach my $item (@{ $form->{parts} }) {
 
1030       push(@assemblies, $item);
 
1031       do_statement($form, $sth, $query, conv_i($item->{id}));
 
1033       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1034         $ref->{assemblyitem} = 1;
 
1035         map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
 
1036         push(@assemblies, $ref);
 
1041     # copy assemblies to $form->{parts}
 
1042     $form->{parts} = \@assemblies;
 
1045   $main::lxdebug->leave_sub();
 
1048 sub _create_filter_for_priceupdate {
 
1049   $main::lxdebug->enter_sub();
 
1052   my $myconfig = \%main::myconfig;
 
1053   my $form     = $main::form;
 
1056   my $where = '1 = 1';
 
1058   foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
 
1060     $column =~ s/.*\.//;
 
1061     next unless ($form->{$column});
 
1063     $where .= qq| AND $item ILIKE ?|;
 
1064     push(@where_values, '%' . $form->{$column} . '%');
 
1067   foreach my $item (qw(description serialnumber)) {
 
1068     next unless ($form->{$item});
 
1070     $where .= qq| AND (${item} ILIKE ?)|;
 
1071     push(@where_values, '%' . $form->{$item} . '%');
 
1075   # items which were never bought, sold or on an order
 
1076   if ($form->{itemstatus} eq 'orphaned') {
 
1078       qq| AND (p.onhand = 0)
 
1081               SELECT DISTINCT parts_id FROM invoice
 
1083               SELECT DISTINCT parts_id FROM assembly
 
1085               SELECT DISTINCT parts_id FROM orderitems
 
1088   } elsif ($form->{itemstatus} eq 'active') {
 
1089     $where .= qq| AND p.obsolete = '0'|;
 
1091   } elsif ($form->{itemstatus} eq 'obsolete') {
 
1092     $where .= qq| AND p.obsolete = '1'|;
 
1094   } elsif ($form->{itemstatus} eq 'onhand') {
 
1095     $where .= qq| AND p.onhand > 0|;
 
1097   } elsif ($form->{itemstatus} eq 'short') {
 
1098     $where .= qq| AND p.onhand < p.rop|;
 
1102   foreach my $column (qw(make model)) {
 
1103     next unless ($form->{$column});
 
1104     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
 
1105     push(@where_values, '%' . $form->{$column} . '%');
 
1108   $main::lxdebug->leave_sub();
 
1110   return ($where, @where_values);
 
1113 sub get_num_matches_for_priceupdate {
 
1114   $main::lxdebug->enter_sub();
 
1118   my $myconfig = \%main::myconfig;
 
1119   my $form     = $main::form;
 
1121   my $dbh      = $form->get_standard_dbh($myconfig);
 
1123   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
 
1125   my $num_updated = 0;
 
1128   for my $column (qw(sellprice listprice)) {
 
1129     next if ($form->{$column} eq "");
 
1137             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1139     my ($result)  = selectfirst_array_query($form, $dbh, $query, @where_values);
 
1140     $num_updated += $result if (0 <= $result);
 
1149           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1150           WHERE $where) AND (pricegroup_id = ?)|;
 
1151   my $sth = prepare_query($form, $dbh, $query);
 
1153   for my $i (1 .. $form->{price_rows}) {
 
1154     next if ($form->{"price_$i"} eq "");
 
1156     my ($result)  = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1157     $num_updated += $result if (0 <= $result);
 
1161   $main::lxdebug->leave_sub();
 
1163   return $num_updated;
 
1167   $main::lxdebug->enter_sub();
 
1169   my ($self, $myconfig, $form) = @_;
 
1171   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
 
1172   my $num_updated = 0;
 
1174   # connect to database
 
1175   my $dbh = $form->dbconnect_noauto($myconfig);
 
1177   for my $column (qw(sellprice listprice)) {
 
1178     next if ($form->{$column} eq "");
 
1180     my $value = $form->parse_amount($myconfig, $form->{$column});
 
1183     if ($form->{"${column}_type"} eq "percent") {
 
1184       $value = ($value / 100) + 1;
 
1189       qq|UPDATE parts SET $column = $column $operator ?
 
1193             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1195     my $result    = do_query($form, $dbh, $query, $value, @where_values);
 
1196     $num_updated += $result if (0 <= $result);
 
1200     qq|UPDATE prices SET price = price + ?
 
1204           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1205           WHERE $where) AND (pricegroup_id = ?)|;
 
1206   my $sth_add = prepare_query($form, $dbh, $q_add);
 
1209     qq|UPDATE prices SET price = price * ?
 
1213           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1214           WHERE $where) AND (pricegroup_id = ?)|;
 
1215   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
 
1217   for my $i (1 .. $form->{price_rows}) {
 
1218     next if ($form->{"price_$i"} eq "");
 
1220     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
 
1223     if ($form->{"pricegroup_type_$i"} eq "percent") {
 
1224       $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1226       $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1229     $num_updated += $result if (0 <= $result);
 
1233   $sth_multiply->finish();
 
1235   my $rc= $dbh->commit;
 
1238   $main::lxdebug->leave_sub();
 
1240   return $num_updated;
 
1244   $main::lxdebug->enter_sub();
 
1246   my ($self, $module, $myconfig, $form) = @_;
 
1248   # connect to database
 
1249   my $dbh = $form->dbconnect($myconfig);
 
1251   my @values = ('%' . $module . '%');
 
1256       qq|SELECT c.accno, c.description, c.link, c.id,
 
1257            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
 
1258          FROM chart c, parts p
 
1259          WHERE (c.link LIKE ?) AND (p.id = ?)
 
1261     push(@values, conv_i($form->{id}));
 
1265       qq|SELECT c.accno, c.description, c.link, c.id,
 
1266            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
 
1267          FROM chart c, defaults d
 
1272   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1273   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1274     foreach my $key (split(/:/, $ref->{link})) {
 
1275       if ($key =~ /\Q$module\E/) {
 
1276         if (   ($ref->{id} eq $ref->{inventory_accno_id})
 
1277             || ($ref->{id} eq $ref->{income_accno_id})
 
1278             || ($ref->{id} eq $ref->{expense_accno_id})) {
 
1279           push @{ $form->{"${module}_links"}{$key} },
 
1280             { accno       => $ref->{accno},
 
1281               description => $ref->{description},
 
1282               selected    => "selected" };
 
1283           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
 
1285           push @{ $form->{"${module}_links"}{$key} },
 
1286             { accno       => $ref->{accno},
 
1287               description => $ref->{description},
 
1295   # get buchungsgruppen
 
1296   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
 
1299   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
 
1302     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
 
1306   $main::lxdebug->leave_sub();
 
1309 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
 
1311   $main::lxdebug->enter_sub();
 
1313   my ($self, $myconfig, $form, $sortorder) = @_;
 
1314   my $dbh   = $form->dbconnect($myconfig);
 
1315   my $order = qq| p.partnumber|;
 
1316   my $where = qq|1 = 1|;
 
1319   if ($sortorder eq "all") {
 
1320     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
 
1321     push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
 
1323   } elsif ($sortorder eq "partnumber") {
 
1324     $where .= qq| AND (partnumber ILIKE ?)|;
 
1325     push(@values, '%' . $form->{partnumber} . '%');
 
1327   } elsif ($sortorder eq "description") {
 
1328     $where .= qq| AND (description ILIKE ?)|;
 
1329     push(@values, '%' . $form->{description} . '%');
 
1330     $order = "description";
 
1335     qq|SELECT id, partnumber, description, unit, sellprice
 
1337        WHERE $where ORDER BY $order|;
 
1339   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1342   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1343     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
 
1348     $form->{"id_$j"}          = $ref->{id};
 
1349     $form->{"partnumber_$j"}  = $ref->{partnumber};
 
1350     $form->{"description_$j"} = $ref->{description};
 
1351     $form->{"unit_$j"}        = $ref->{unit};
 
1352     $form->{"sellprice_$j"}   = $ref->{sellprice};
 
1353     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
 
1359   $main::lxdebug->leave_sub();
 
1364 # gets sum of sold part with part_id
 
1366   $main::lxdebug->enter_sub();
 
1368   my ($dbh, $id) = @_;
 
1370   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
 
1371   my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
 
1374   $main::lxdebug->leave_sub();
 
1377 }    #end get_soldtotal
 
1379 sub retrieve_languages {
 
1380   $main::lxdebug->enter_sub();
 
1382   my ($self, $myconfig, $form) = @_;
 
1384   # connect to database
 
1385   my $dbh = $form->dbconnect($myconfig);
 
1391   if ($form->{language_values} ne "") {
 
1393       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
 
1395          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
 
1396          ORDER BY lower(l.description)|;
 
1397     @values = (conv_i($form->{id}));
 
1400     $query = qq|SELECT id, description
 
1402                 ORDER BY lower(description)|;
 
1405   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
 
1409   $main::lxdebug->leave_sub();
 
1414 sub follow_account_chain {
 
1415   $main::lxdebug->enter_sub(2);
 
1417   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
 
1419   my @visited_accno_ids = ($accno_id);
 
1424     qq|SELECT c.new_chart_id, date($transdate) >= c.valid_from AS is_valid, | .
 
1427     qq|LEFT JOIN chart cnew ON c.new_chart_id = cnew.id | .
 
1428     qq|WHERE (c.id = ?) AND NOT c.new_chart_id ISNULL AND (c.new_chart_id > 0)|;
 
1429   $sth = prepare_query($form, $dbh, $query);
 
1432     do_statement($form, $sth, $query, $accno_id);
 
1433     my $ref = $sth->fetchrow_hashref();
 
1434     last unless ($ref && $ref->{"is_valid"} &&
 
1435                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
 
1436     $accno_id = $ref->{"new_chart_id"};
 
1437     $accno = $ref->{"accno"};
 
1438     push(@visited_accno_ids, $accno_id);
 
1441   $main::lxdebug->leave_sub(2);
 
1443   return ($accno_id, $accno);
 
1446 sub retrieve_accounts {
 
1447   $main::lxdebug->enter_sub(2);
 
1449   my ($self, $myconfig, $form, $parts_id, $index) = @_;
 
1451   my ($query, $sth, $dbh);
 
1453   $form->{"taxzone_id"} *= 1;
 
1455   $dbh = $form->get_standard_dbh($myconfig);
 
1458   if ($form->{type} eq "invoice") {
 
1459     if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
 
1460       $transdate = $form->{invdate};
 
1462       $transdate = $form->{deliverydate};
 
1464   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
 
1465     $transdate = $form->{invdate};
 
1467     $transdate = $form->{transdate};
 
1470   if ($transdate eq "") {
 
1471     $transdate = "current_date";
 
1473     $transdate = $dbh->quote($transdate);
 
1478     qq|  p.inventory_accno_id AS is_part, | .
 
1479     qq|  bg.inventory_accno_id, | .
 
1480     qq|  bg.income_accno_id_$form->{taxzone_id} AS income_accno_id, | .
 
1481     qq|  bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id, | .
 
1482     qq|  c1.accno AS inventory_accno, | .
 
1483     qq|  c2.accno AS income_accno, | .
 
1484     qq|  c3.accno AS expense_accno | .
 
1486     qq|LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id | .
 
1487     qq|LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id | .
 
1488     qq|LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id | .
 
1489     qq|LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id | .
 
1491   my $ref = selectfirst_hashref_query($form, $dbh, $query, $parts_id);
 
1493   return $main::lxdebug->leave_sub(2) if (!$ref);
 
1495   $ref->{"inventory_accno_id"} = undef unless ($ref->{"is_part"});
 
1498   foreach my $type (qw(inventory income expense)) {
 
1499     next unless ($ref->{"${type}_accno_id"});
 
1500     ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
 
1501       $self->follow_account_chain($form, $dbh, $transdate,
 
1502                                   $ref->{"${type}_accno_id"},
 
1503                                   $ref->{"${type}_accno"});
 
1506   map({ $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} }
 
1507       qw(inventory income expense));
 
1509   my $inc_exp = $form->{"vc"} eq "customer" ? "income" : "expense";
 
1510   my $accno_id = $accounts{"${inc_exp}_accno_id"};
 
1513     qq|SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber | .
 
1515     qq|LEFT JOIN chart c ON c.id = t.chart_id | .
 
1516     qq|WHERE t.id IN | .
 
1517     qq|  (SELECT tk.tax_id | .
 
1518     qq|   FROM taxkeys tk | .
 
1519     qq|   WHERE tk.chart_id = ? AND startdate <= | . quote_db_date($transdate) .
 
1520     qq|   ORDER BY startdate DESC LIMIT 1) |;
 
1521   $ref = selectfirst_hashref_query($form, $dbh, $query, $accno_id);
 
1524     $main::lxdebug->leave_sub(2);
 
1528   $form->{"taxaccounts_$index"} = $ref->{"accno"};
 
1529   if ($form->{"taxaccounts"} !~ /$ref->{accno}/) {
 
1530     $form->{"taxaccounts"} .= "$ref->{accno} ";
 
1532   map({ $form->{"$ref->{accno}_${_}"} = $ref->{$_}; }
 
1533       qw(rate description taxnumber));
 
1535 #   $main::lxdebug->message(0, "formvars: rate " . $form->{"$ref->{accno}_rate"} .
 
1536 #                           " description " . $form->{"$ref->{accno}_description"} .
 
1537 #                           " taxnumber " . $form->{"$ref->{accno}_taxnumber"} .
 
1538 #                           " || taxaccounts_$index " . $form->{"taxaccounts_$index"} .
 
1539 #                           " || taxaccounts " . $form->{"taxaccounts"});
 
1541   $main::lxdebug->leave_sub(2);
 
1544 sub get_basic_part_info {
 
1545   $main::lxdebug->enter_sub();
 
1550   Common::check_params(\%params, qw(id));
 
1552   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
 
1555     $main::lxdebug->leave_sub();
 
1559   my $myconfig = \%main::myconfig;
 
1560   my $form     = $main::form;
 
1562   my $dbh      = $form->get_standard_dbh($myconfig);
 
1564   my $query    = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
 
1566   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
 
1568   if ('' eq ref $params{id}) {
 
1569     $info = $info->[0] || { };
 
1571     $main::lxdebug->leave_sub();
 
1575   my %info_map = map { $_->{id} => $_ } @{ $info };
 
1577   $main::lxdebug->leave_sub();
 
1582 sub prepare_parts_for_printing {
 
1583   $main::lxdebug->enter_sub();
 
1588   my $myconfig = \%main::myconfig;
 
1589   my $form     = $main::form;
 
1591   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1593   my $prefix   = $params{prefix} || 'id_';
 
1594   my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
 
1596   my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
 
1599     $main::lxdebug->leave_sub();
 
1603   my $placeholders = join ', ', ('?') x scalar(@part_ids);
 
1604   my $query        = qq|SELECT mm.parts_id, mm.model, v.name AS make
 
1606                         LEFT JOIN vendor v ON (mm.make = cast (v.id as text))
 
1607                         WHERE mm.parts_id IN ($placeholders)|;
 
1611   my $sth          = prepare_execute_query($form, $dbh, $query, @part_ids);
 
1613   while (my $ref = $sth->fetchrow_hashref()) {
 
1614     $makemodel{$ref->{parts_id}} ||= [];
 
1615     push @{ $makemodel{$ref->{parts_id}} }, $ref;
 
1620   my @columns = qw(ean image microfiche drawing weight);
 
1622   $query      = qq|SELECT id, | . join(', ', @columns) . qq|
 
1624                    WHERE id IN ($placeholders)|;
 
1626   my %data    = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
 
1628   map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
 
1630   foreach my $i (1 .. $rowcount) {
 
1631     my $id = $form->{"${prefix}${i}"};
 
1635     foreach (@columns) {
 
1636       push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
 
1639     push @{ $form->{TEMPLATE_ARRAYS}{make} },  [];
 
1640     push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
 
1642     next if (!$makemodel{$id});
 
1644     foreach my $ref (@{ $makemodel{$id} }) {
 
1645       map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
 
1649   $main::lxdebug->leave_sub();