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 #======================================================================
 
  43   $main::lxdebug->enter_sub();
 
  45   my ($self, $myconfig, $form) = @_;
 
  48   my $dbh = $form->dbconnect($myconfig);
 
  54          c1.accno AS inventory_accno,
 
  55          c2.accno AS income_accno,
 
  56          c3.accno AS expense_accno,
 
  59        LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
 
  60        LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
 
  61        LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
 
  62        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
  64   my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
  66   # copy to $form variables
 
  67   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
 
  71   my %oid = ('Pg'     => 'a.oid',
 
  72              'Oracle' => 'a.rowid');
 
  74   # part or service item
 
  75   $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
 
  76   if ($form->{assembly}) {
 
  77     $form->{item} = 'assembly';
 
  79     # retrieve assembly items
 
  81       qq|SELECT p.id, p.partnumber, p.description,
 
  82            p.sellprice, p.weight, a.qty, a.bom, p.unit,
 
  85          JOIN assembly a ON (a.parts_id = p.id)
 
  86          LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
  88          ORDER BY $oid{$myconfig->{dbdriver}}|;
 
  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     $form->{"price_$i"} = $form->round_amount($form->{"price_$i"}, 5);
 
 129     $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
 130     push @pricegroups, $form->{"pricegroup_id_$i"};
 
 137   $query = qq|SELECT id, pricegroup FROM pricegroup|;
 
 138   $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
 
 140   #find not used pricegroups
 
 141   while ($tmp = pop(@{ $form->{PRICEGROUPS} })) {
 
 143     foreach my $item (@pricegroups) {
 
 144       if ($item eq $tmp->{id}) {
 
 149     push(@pricegroups_not_used, $tmp) unless ($in_use);
 
 152   # if not used pricegroups are avaible
 
 153   if (@pricegroups_not_used) {
 
 155     foreach $name (@pricegroups_not_used) {
 
 156       $form->{"klass_$i"} = "$name->{id}";
 
 157       $form->{"price_$i"} = $form->round_amount($form->{sellprice}, 5);
 
 158       $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
 159       $form->{"pricegroup_id_$i"} = "$name->{id}";
 
 160       $form->{"pricegroup_$i"}    = "$name->{pricegroup}";
 
 166   $form->{price_rows} = $i - 1;
 
 168   unless ($form->{item} eq 'service') {
 
 171     if ($form->{makemodel}) {
 
 172       $query = qq|SELECT m.make, m.model FROM makemodel m | .
 
 173                qq|WHERE m.parts_id = ?|;
 
 174       @values = ($form->{id});
 
 175       $sth = $dbh->prepare($query);
 
 176       $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
 
 179       while (($form->{"make_$i"}, $form->{"model_$i"}) = $sth->fetchrow_array)
 
 184       $form->{makemodel_rows} = $i - 1;
 
 190   $form->{language_values} = "";
 
 191   $query = qq|SELECT language_id, translation FROM translation WHERE parts_id = ?|;
 
 192   my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 193   while ($tr = $trq->fetchrow_hashref(NAME_lc)) {
 
 194     $form->{language_values} .= "---+++---".$tr->{language_id}."--++--".$tr->{translation};
 
 198   # now get accno for taxes
 
 201        FROM chart c, partstax pt
 
 202        WHERE (pt.chart_id = c.id) AND (pt.parts_id = ?)|;
 
 203   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 204   while (($key) = $sth->fetchrow_array) {
 
 205     $form->{amount}{$key} = $key;
 
 211   my @referencing_tables = qw(invoice orderitems invoice inventory rmaitems);
 
 212   my %column_map         = ( );
 
 213   my $parts_id           = conv_i($form->{id});
 
 215   $form->{orphaned}      = 1;
 
 217   foreach my $table (@referencing_tables) {
 
 218     my $column  = $column_map{$table} || 'parts_id';
 
 219     $query      = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
 
 220     my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
 
 223       $form->{orphaned} = 0;
 
 228   $form->{"unit_changeable"} = $form->{orphaned};
 
 232   $main::lxdebug->leave_sub();
 
 235 sub get_pricegroups {
 
 236   $main::lxdebug->enter_sub();
 
 238   my ($self, $myconfig, $form) = @_;
 
 240   my $dbh = $form->dbconnect($myconfig);
 
 243   my $query = qq|SELECT id, pricegroup FROM pricegroup|;
 
 244   my $pricegroups = selectall_hashref_query($form, $dbh, $query);
 
 247   foreach $pg (@{ $pricegroups }) {
 
 248     $form->{"klass_$i"} = "$pg->{id}";
 
 249     $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
 250     $form->{"pricegroup_id_$i"} = "$pg->{id}";
 
 251     $form->{"pricegroup_$i"}    = "$pg->{pricegroup}";
 
 256   $form->{price_rows} = $i - 1;
 
 260   $main::lxdebug->leave_sub();
 
 265 sub retrieve_buchungsgruppen {
 
 266   $main::lxdebug->enter_sub();
 
 268   my ($self, $myconfig, $form) = @_;
 
 272   my $dbh = $form->dbconnect($myconfig);
 
 274   # get buchungsgruppen
 
 275   $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
 
 276   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
 
 278   $main::lxdebug->leave_sub();
 
 282   $main::lxdebug->enter_sub();
 
 284   my ($self, $myconfig, $form) = @_;
 
 286   # connect to database, turn off AutoCommit
 
 287   my $dbh = $form->dbconnect_noauto($myconfig);
 
 290   # make up a unique handle and store in partnumber field
 
 291   # then retrieve the record based on the unique handle to get the id
 
 292   # replace the partnumber field with the actual variable
 
 293   # add records for makemodel
 
 295   # if there is a $form->{id} then replace the old entry
 
 296   # delete all makemodel entries and add the new ones
 
 298   # undo amount formatting
 
 299   map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
 
 300     qw(rop weight listprice sellprice gv lastcost stock);
 
 302   my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
 
 304   $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
 
 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}));
 
 339     my ($count) = selectrow_query($form, $dbh, qq|SELECT COUNT(*) FROM parts WHERE partnumber = ?|, $form->{partnumber});
 
 341       $main::lxdebug->leave_sub();
 
 345     ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
 
 346     do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber) VALUES (?, '')|, $form->{id});
 
 348     $form->{orphaned} = 1;
 
 349     if ($form->{partnumber} eq "" && $form->{"item"} eq "service") {
 
 350       $form->{partnumber} = $form->update_defaults($myconfig, "servicenumber");
 
 352     if ($form->{partnumber} eq "" && $form->{"item"} ne "service") {
 
 353       $form->{partnumber} = $form->update_defaults($myconfig, "articlenumber");
 
 357   my $partsgroup_id = 0;
 
 359   if ($form->{partsgroup}) {
 
 360     ($partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
 
 363   my ($subq_inventory, $subq_expense, $subq_income);
 
 364   if ($form->{"item"} eq "part") {
 
 366       qq|(SELECT bg.inventory_accno_id
 
 367           FROM buchungsgruppen bg
 
 368           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 370     $subq_inventory = "NULL";
 
 373   if ($form->{"item"} ne "assembly") {
 
 375       qq|(SELECT bg.expense_accno_id_0
 
 376           FROM buchungsgruppen bg
 
 377           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 379     $subq_expense = "NULL";
 
 399          buchungsgruppen_id = ?,
 
 401          inventory_accno_id = $subq_inventory,
 
 402          income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
 
 403          expense_accno_id = $subq_expense,
 
 411          not_discountable = ?,
 
 416   @values = ($form->{partnumber},
 
 417              $form->{description},
 
 418              $makemodel ? 't' : 'f',
 
 419              $form->{assembly} ? 't' : 'f',
 
 424              conv_date($form->{priceupdate}),
 
 430              conv_i($form->{buchungsgruppen_id}),
 
 431              conv_i($form->{payment_id}),
 
 432              conv_i($form->{buchungsgruppen_id}),
 
 433              $form->{obsolete} ? 't' : 'f',
 
 436              $form->{shop} ? 't' : 'f',
 
 440              $form->{not_discountable} ? 't' : 'f',
 
 442              conv_i($partsgroup_id),
 
 443              conv_i($form->{price_factor_id}),
 
 446   do_query($form, $dbh, $query, @values);
 
 448   # delete translation records
 
 449   do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
 
 451   if ($form->{language_values} ne "") {
 
 452     foreach $item (split(/---\+\+\+---/, $form->{language_values})) {
 
 453       my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
 
 454       if ($translation ne "") {
 
 455         $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
 
 456                     VALUES ( ?, ?, ?, ? )|;
 
 457         @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
 
 458         do_query($form, $dbh, $query, @values);
 
 463   # delete price records
 
 464   do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
 
 466   # insert price records only if different to sellprice
 
 467   for my $i (1 .. $form->{price_rows}) {
 
 468     if ($form->{"price_$i"} eq "0") {
 
 469       $form->{"price_$i"} = $form->{sellprice};
 
 472         (   $form->{"price_$i"}
 
 473          || $form->{"klass_$i"}
 
 474          || $form->{"pricegroup_id_$i"})
 
 475         and $form->{"price_$i"} != $form->{sellprice}
 
 477       #$klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
 
 478       $price = $form->parse_amount($myconfig, $form->{"price_$i"});
 
 480         $form->parse_amount($myconfig, $form->{"pricegroup_id_$i"});
 
 481       $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) | .
 
 483       @values = (conv_i($form->{id}), conv_i($pricegroup_id), $price);
 
 484       do_query($form, $dbh, $query, @values);
 
 488   # insert makemodel records
 
 489   unless ($form->{item} eq 'service') {
 
 490     for my $i (1 .. $form->{makemodel_rows}) {
 
 491       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
 
 492         map { $form->{"${_}_$i"} =~ s/\'/\'\'/g } qw(make model);
 
 494         $query = qq|INSERT INTO makemodel (parts_id, make, model) | .
 
 495                              qq|VALUES (?, ?, ?)|;
 
 496                     @values = (conv_i($form->{id}), $form->{"make_$i"}, $form->{"model_$i"});
 
 497         do_query($form, $dbh, $query, @values);
 
 503   foreach $item (split(/ /, $form->{taxaccounts})) {
 
 504     if ($form->{"IC_tax_$item"}) {
 
 506         qq|INSERT INTO partstax (parts_id, chart_id)
 
 507            VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
 
 508                         @values = (conv_i($form->{id}), $item);
 
 509       do_query($form, $dbh, $query, @values);
 
 513   # add assembly records
 
 514   if ($form->{item} eq 'assembly') {
 
 516     for my $i (1 .. $form->{assembly_rows}) {
 
 517       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 519       if ($form->{"qty_$i"} != 0) {
 
 520         $form->{"bom_$i"} *= 1;
 
 521         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
 
 522                              qq|VALUES (?, ?, ?, ?)|;
 
 523                     @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
 
 524         do_query($form, $dbh, $query, @values);
 
 531     my $shippingdate = "$a[5]-$a[4]-$a[3]";
 
 533     $form->get_employee($dbh);
 
 537   #set expense_accno=inventory_accno if they are different => bilanz
 
 539     ($form->{expense_accno} != $form->{inventory_accno})
 
 540     ? $form->{inventory_accno}
 
 541     : $form->{expense_accno};
 
 543   # get tax rates and description
 
 545     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
 
 547     qq|SELECT c.accno, c.description, t.rate, t.taxnumber
 
 549        WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
 
 551   $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
 
 553   $form->{taxaccount} = "";
 
 554   while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
 555     $form->{taxaccount} .= "$ptr->{accno} ";
 
 556     if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
 
 557       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
 558       $form->{"$ptr->{accno}_description"} = $ptr->{description};
 
 559       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
 560       $form->{taxaccount2} .= " $ptr->{accno} ";
 
 565   my $rc = $dbh->commit;
 
 568   $main::lxdebug->leave_sub();
 
 573 sub update_assembly {
 
 574   $main::lxdebug->enter_sub();
 
 576   my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
 
 578   my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
 
 579   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
 
 581   while (my ($pid, $aqty) = $sth->fetchrow_array) {
 
 582     &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
 
 587     qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
 
 589   @values = ($qty * ($form->{sellprice} - $sellprice),
 
 590              $qty * ($form->{weight} - $weight), conv_i($id));
 
 591   do_query($form, $dbh, $query, @values);
 
 593   $main::lxdebug->leave_sub();
 
 596 sub retrieve_assemblies {
 
 597   $main::lxdebug->enter_sub();
 
 599   my ($self, $myconfig, $form) = @_;
 
 601   # connect to database
 
 602   my $dbh = $form->dbconnect($myconfig);
 
 604   my $where = qq|NOT p.obsolete|;
 
 607   if ($form->{partnumber}) {
 
 608     $where .= qq| AND (p.partnumber ILIKE ?)|;
 
 609     push(@values, '%' . $form->{partnumber} . '%');
 
 612   if ($form->{description}) {
 
 613     $where .= qq| AND (p.description ILIKE ?)|;
 
 614     push(@values, '%' . $form->{description} . '%');
 
 617   # retrieve assembly items
 
 619     qq|SELECT p.id, p.partnumber, p.description,
 
 620          p.bin, p.onhand, p.rop,
 
 621          (SELECT sum(p2.inventory_accno_id)
 
 622           FROM parts p2, assembly a
 
 623           WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
 
 625        WHERE NOT p.obsolete AND p.assembly $where|;
 
 627   $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
 
 631   $main::lxdebug->leave_sub();
 
 635   $main::lxdebug->enter_sub();
 
 637   my ($self, $myconfig, $form) = @_;
 
 638   my @values = (conv_i($form->{id}));
 
 639   # connect to database, turn off AutoCommit
 
 640   my $dbh = $form->dbconnect_noauto($myconfig);
 
 642   my %columns = ( "assembly" => "id", "parts" => "id" );
 
 644   for my $table (qw(prices partstax makemodel inventory assembly license translation parts)) {
 
 645     my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
 
 646     do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
 
 650   my $rc = $dbh->commit;
 
 653   $main::lxdebug->leave_sub();
 
 659   $main::lxdebug->enter_sub();
 
 661   my ($self, $myconfig, $form) = @_;
 
 663   my $i = $form->{assembly_rows};
 
 665   my $where = qq|1 = 1|;
 
 668   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
 
 670   while (my ($column, $table) = each(%columns)) {
 
 671     next unless ($form->{"${column}_$i"});
 
 672     $where .= qq| AND ${table}.${column} ILIKE ?|;
 
 673     push(@values, '%' . $form->{"${column}_$i"} . '%');
 
 677     $where .= qq| AND NOT (p.id = ?)|;
 
 678     push(@values, conv_i($form->{id}));
 
 682     $where .= qq| ORDER BY p.partnumber|;
 
 684     $where .= qq| ORDER BY p.description|;
 
 687   # connect to database
 
 688   my $dbh = $form->dbconnect($myconfig);
 
 691     qq|SELECT p.id, p.partnumber, p.description, p.sellprice, p.weight, p.onhand, p.unit, pg.partsgroup
 
 693        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 695   $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
 
 699   $main::lxdebug->leave_sub();
 
 704 # Warning, deep magic ahead.
 
 705 # This function gets all parts from the database according to the filters specified
 
 708 #   sort revers  - sorting field + direction
 
 711 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
 
 712 #   partnumber ean description partsgroup microfiche drawing
 
 715 #   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
 
 718 #   itemstatus  = active | onhand | short | obsolete | orphaned
 
 719 #   searchitems = part | assembly | service
 
 722 #   make model                               - makemodel
 
 723 #   serialnumber transdatefrom transdateto   - invoice/orderitems
 
 726 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
 
 727 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
 
 728 #   l_soldtotal                              - aggreg join to display total of sold quantity
 
 729 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 730 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
 
 731 #   l_serialnumber                           - belonges to serialnumber filter
 
 732 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
 
 735 #   l_soldtotal                              - aggreg join to display total of sold quantity
 
 736 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 737 #   masking of onhand in bsooqr mode         - ToDO: fixme
 
 739 # disabled sanity checks and changes:
 
 740 #  - searchitems = assembly will no longer disable bought
 
 741 #  - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
 
 742 #  - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
 
 743 #  - itemstatus = obsolete will no longer disable onhand, short
 
 744 #  - allow sorting by ean
 
 745 #  - serialnumber filter also works if l_serialnumber isn't ticked
 
 746 #  - onhand doesn't get masked by it's oi or invoice counterparts atm. ToDO: fix this
 
 747 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
 
 750   $main::lxdebug->enter_sub();
 
 752   my ($self, $myconfig, $form) = @_;
 
 753   my $dbh = $form->get_standard_dbh($myconfig);
 
 755   $form->{parts} = +{ };
 
 757   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
 
 758   my @makemodel_filters    = qw(make model);
 
 759   my @invoice_oi_filters   = qw(serialnumber soldtotal);
 
 760   my @apoe_filters         = qw(transdate);
 
 761   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
 
 762   my @simple_l_switches    = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
 
 763   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
 
 764   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module);
 
 765   my @deliverydate_flags   = qw(deliverydate);
 
 766 #  my @other_flags          = qw(onhand); # ToDO: implement these
 
 767 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
 
 770     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
 
 771     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
 
 772     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
 
 775          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem, 'invoice'    AS ioi FROM invoice UNION
 
 776          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, 'orderitems' AS ioi FROM orderitems
 
 777        ) AS ioi ON ioi.parts_id = p.id|,
 
 780          SELECT id, transdate, 'ir' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation, NULL AS customer_id,         vendor_id, NULL AS deliverydate FROM ap UNION
 
 781          SELECT id, transdate, 'is' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation,         customer_id, NULL AS vendor_id,         deliverydate FROM ar UNION
 
 782          SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber,          quotation,         customer_id,         vendor_id, NULL AS deliverydate FROM oe
 
 783        ) AS apoe ON ioi.trans_id = apoe.id|,
 
 786            SELECT id, name, 'customer' AS cv FROM customer UNION
 
 787            SELECT id, name, 'vendor'   AS cv FROM vendor
 
 788          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
 
 790   my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
 
 793   #===== switches and simple filters ========#
 
 795   my @select_tokens = qw(id factor);
 
 796   my @where_tokens  = qw(1=1);
 
 797   my @group_tokens  = ();
 
 799   # special case transdate
 
 800   if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
 
 801     $form->{"l_transdate"} = 1;
 
 802     push @select_tokens, 'transdate';
 
 803     for (qw(transdatefrom transdateto)) {
 
 804       next unless $form->{$_};
 
 805       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
 
 806       push @bind_vars,    $form->{$_};
 
 810   my %simple_filter_table_prefix = (
 
 814   foreach (@simple_filters, @makemodel_filters, @invoice_oi_filters) {
 
 815     next unless $form->{$_};
 
 816     $form->{"l_$_"} = '1'; # show the column
 
 817     push @where_tokens, "$simple_filter_table_prefix{$_}$_ ILIKE ?";
 
 818     push @bind_vars,    "%$form->{$_}%";
 
 821   foreach (@simple_l_switches) {
 
 822     next unless $form->{"l_$_"};
 
 823     push @select_tokens, $_;
 
 826   for ($form->{searchitems}) {
 
 827     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
 
 828     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
 
 829     push @where_tokens, 'NOT p.assembly'               if /service/;
 
 830     push @where_tokens, '    p.assembly'               if /assembly/;
 
 833   for ($form->{itemstatus}) {
 
 834     push @where_tokens, 'p.id NOT IN
 
 835         (SELECT DISTINCT parts_id FROM invoice UNION
 
 836          SELECT DISTINCT parts_id FROM assembly UNION
 
 837          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
 
 838     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
 
 839     push @where_tokens, 'NOT p.obsolete'               if /active/;
 
 840     push @where_tokens, '    p.obsolete',              if /obsolete/;
 
 841     push @where_tokens, 'p.onhand > 0',                if /onhand/;
 
 842     push @where_tokens, 'p.onhand < p.rop',            if /short/;
 
 846   my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
 
 847   $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols;
 
 849   my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
 
 851   # special case: sorting by partnumber
 
 852   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
 
 853   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
 
 854   # ToDO: implement proper functional sorting
 
 855   $form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
 
 856     if $form->{sort} eq 'partnumber';
 
 858   my $order_clause = " ORDER BY $form->{sort} $sort_order";
 
 860   my $limit_clause = " LIMIT 100" if $form->{top100};
 
 862   #=== joins and complicated filters ========#
 
 864   my $bsooqr = $form->{bought}  || $form->{sold}
 
 865             || $form->{ordered} || $form->{onorder}
 
 866             || $form->{quoted}  || $form->{rfq};
 
 869   push @select_tokens, @qsooqr_flags                                          if $bsooqr;
 
 870   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
 
 871   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
 
 872   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
 
 873   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
 
 874   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
 
 875   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
 
 876   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
 
 877   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
 
 879   $joins_needed{partsgroup}  = 1;
 
 880   $joins_needed{pfac}        = 1;
 
 881   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
 
 882   $joins_needed{cv}          = 1 if $bsooqr;
 
 883   $joins_needed{apoe}        = 1 if $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
 
 884   $joins_needed{invoice_oi}  = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
 
 886   # special case for description search.
 
 887   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
 
 888   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
 
 889   # find the old entries in of @where_tokens and @bind_vars, and adjust them
 
 890   if ($joins_needed{invoice_oi}) {
 
 891     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
 
 892       next unless $where_tokens[$wi] =~ /^description ILIKE/;
 
 893       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
 
 894       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
 
 899   # now the master trick: soldtotal.
 
 900   if ($form->{l_soldtotal}) {
 
 901     push @where_tokens, 'ioi.qty >= 0';
 
 902     push @group_tokens, @select_tokens;
 
 903     push @select_tokens, 'SUM(ioi.qty)';
 
 906   #============= build query ================#
 
 910      deliverydate => 'apoe.', serialnumber => 'ioi.',
 
 911      transdate    => 'apoe.', trans_id     => 'ioi.',
 
 912      module       => 'apoe.', name         => 'cv.',
 
 913      ordnumber    => 'apoe.', make         => 'mm.',
 
 914      quonumber    => 'apoe.', model        => 'mm.',
 
 915      invnumber    => 'apoe.', partsgroup   => 'pg.',
 
 917      'SUM(ioi.qty)' => ' ',
 
 920   my %renamed_columns = (
 
 921     'factor'       => 'price_factor',
 
 922     'SUM(ioi.qty)' => 'soldtotal',
 
 925   map { $table_prefix{$_} = 'ioi.' } qw(description serialnumber qty unit) if $joins_needed{invoice_oi};
 
 926   map { $renamed_columns{$_} = ' AS ' . $renamed_columns{$_} } keys %renamed_columns;
 
 928   my $select_clause = join ', ',    map { ($table_prefix{$_} || "p.") . $_ . $renamed_columns{$_} } @select_tokens;
 
 929   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
 
 930   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
 
 931   my $group_clause  = ' GROUP BY ' . join ', ',    map { ($table_prefix{$_} || "p.") . $_ } @group_tokens if scalar @group_tokens;
 
 933   my $query = qq|SELECT DISTINCT $select_clause FROM parts p $join_clause WHERE $where_clause $group_clause $order_clause $limit_clause|;
 
 935   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
 
 937   map { $_->{onhand} *= 1 } @{ $form->{parts} };
 
 939 ##  my $where = qq|1 = 1|;
 
 940 ##  my (@values, $var, $flds, $group, $limit);
 
 942 ##  foreach my $item (qw(partnumber drawing microfiche ean pg.partsgroup)) {
 
 943 ##    my $column = $item;
 
 944 ##    $column =~ s/.*\.//; # get rid of table prefixes
 
 945 ##    if ($form->{$column}) {
 
 946 ##      $where .= qq| AND ($item ILIKE ?)|;
 
 947 ##      push(@values, "%$form->{$column}%");
 
 951 ##  # special case for description
 
 952 ##  if ($form->{description}
 
 953 ##      && !(   $form->{bought}  || $form->{sold} || $form->{onorder}
 
 954 ##           || $form->{ordered} || $form->{rfq} || $form->{quoted})) {
 
 955 ##    $where .= qq| AND (p.description ILIKE ?)|;
 
 956 ##    push(@values, "%$form->{description}%");
 
 959 ##  # special case for serialnumber
 
 960 ##  if ($form->{l_serialnumber} && $form->{serialnumber}) {
 
 961 ##    $where .= qq| AND (serialnumber ILIKE ?)|;
 
 962 ##    push(@values, "%$form->{serialnumber}%");
 
 965 ##  if ($form->{searchitems} eq 'part') {
 
 966 ##    $where .= qq| AND (p.inventory_accno_id > 0) |;
 
 969 ##  if ($form->{searchitems} eq 'assembly') {
 
 970 ##    $form->{bought} = "";
 
 971 ##    $where .= qq| AND p.assembly|;
 
 974 ##  if ($form->{searchitems} eq 'service') {
 
 975 ##    $where .= qq| AND (p.inventory_accno_id IS NULL) AND NOT (p.assembly = '1')|;
 
 976 ##    # irrelevant for services
 
 977 ##    map { $form->{$_} = '' } qw(make model);
 
 980 ##  # items which were never bought, sold or on an order
 
 981 ##  if ($form->{itemstatus} eq 'orphaned') {
 
 982 ##    map { $form->{$_} = 0  } qw(onhand short bought sold onorder ordered rfq quoted);
 
 983 ##    map { $form->{$_} = '' } qw(transdatefrom transdateto);
 
 986 ##      qq| AND (p.onhand = 0)
 
 989 ##              SELECT DISTINCT parts_id FROM invoice
 
 991 ##              SELECT DISTINCT parts_id FROM assembly
 
 993 ##              SELECT DISTINCT parts_id FROM orderitems
 
 997 ##  my %status2condition = (
 
 998 ##    active   => " AND (p.obsolete = '0')",
 
 999 ##    obsolete => " AND (p.obsolete = '1')",
 
1000 ##    onhand   => " AND (p.onhand > 0)",
 
1001 ##    short    => " AND (p.onhand < p.rop)",
 
1003 ##  $where .= $status2condition{$form->{itemstatus}};
 
1005 ##  $form->{onhand} = $form->{short} = 0 if ($form->{itemstatus} eq 'obsolete');
 
1008 ##  foreach my $column (qw(make model)) {
 
1009 ##    push @subcolumns, $column if $form->{$column};
 
1011 ##  if (@subcolumns) {
 
1012 ##    $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE | . (join " AND ", map { "($_ ILIKE ?)"; } @subcolumns) . ")";
 
1013 ##    push @values, map { '%' . $form->{$_} . '%' } @subcolumns;
 
1016 ##  if ($form->{l_soldtotal}) {
 
1017 ##    $where .= qq| AND (p.id = i.parts_id) AND (i.qty >= 0)|;
 
1018 ##    $group = qq| GROUP BY p.id, p.partnumber, p.description, p.onhand, p.unit, p.bin, p.sellprice, p.listprice, p.lastcost, p.priceupdate, pg.partsgroup|;
 
1021 ##  $limit = qq| LIMIT 100| if ($form->{top100});
 
1023 ##  # connect to database
 
1024 ##  my $dbh = $form->dbconnect($myconfig);
 
1026 ##  my @sort_cols = qw(id partnumber description partsgroup bin priceupdate onhand
 
1027 ##                     invnumber ordnumber quonumber name drawing microfiche
 
1028 ##                     serialnumber soldtotal deliverydate);
 
1030 ##  my $sortorder = "partnumber";
 
1031 ##  $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } @sort_cols));
 
1032 ##  $sortorder .= " DESC" if ($form->{revers});
 
1036 ##  if ($form->{l_soldtotal}) {
 
1037 ##    $form->{soldtotal} = 'soldtotal';
 
1039 ##      qq|SELECT p.id, p.partnumber, p.description, p.onhand, p.unit,
 
1040 ##           p.bin, p.sellprice, p.listprice, p.lastcost,
 
1041 ##           p.priceupdate, pg.partsgroup,sum(i.qty) AS soldtotal
 
1043 ##         LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id), invoice i
 
1046 ##         ORDER BY $sortorder $limit|;
 
1049 ##      qq|SELECT p.id, p.partnumber, p.description, p.onhand, p.unit,
 
1050 ##           p.bin, p.sellprice, p.listprice, p.lastcost, p.rop, p.weight,
 
1051 ##           p.priceupdate, p.image, p.drawing, p.microfiche,
 
1054 ##         LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1057 ##         ORDER BY $sortorder $limit|;
 
1060 ##  my @all_values = @values;
 
1062 ##  # rebuild query for bought and sold items
 
1063 ##  if (   $form->{bought}
 
1065 ##      || $form->{onorder}
 
1066 ##      || $form->{ordered}
 
1068 ##      || $form->{quoted}) {
 
1071 ##    @all_values = ();
 
1073 ##    if ($form->{bought} || $form->{sold}) {
 
1075 ##      my @invvalues = @values;
 
1076 ##      my $invwhere = "$where";
 
1077 #      $invwhere .= qq| AND i.assemblyitem = '0'|;
 
1079 ##      if ($form->{transdatefrom}) {
 
1080 ##        $invwhere .= qq| AND a.transdate >= ?|;
 
1081 ##        push(@invvalues, $form->{transdatefrom});
 
1084 ##      if ($form->{transdateto}) {
 
1085 ##        $invwhere .= qq| AND a.transdate <= ?|;
 
1086 ##        push(@invvalues, $form->{transdateto});
 
1089 ##      if ($form->{description}) {
 
1090 ##        $invwhere .= qq| AND i.description ILIKE ?|;
 
1091 ##        push(@invvalues, '%' . $form->{description} . '%');
 
1095 ##        qq|p.id, p.partnumber, i.description, i.serialnumber,
 
1096 #           i.qty AS onhand, i.unit, p.bin, i.sellprice,
 
1097 ##           p.listprice, p.lastcost, p.rop, p.weight,
 
1098 ##           p.priceupdate, p.image, p.drawing, p.microfiche,
 
1100 ##           a.invnumber, a.ordnumber, a.quonumber, i.trans_id,
 
1101 ##           ct.name, i.deliverydate|;
 
1103 ##      if ($form->{bought}) {
 
1105 ##          qq|SELECT $flds, 'ir' AS module, '' AS type, 1 AS exchangerate
 
1107 ##             JOIN parts p ON (p.id = i.parts_id)
 
1108 ##             JOIN ap a ON (a.id = i.trans_id)
 
1109 ##             JOIN vendor ct ON (a.vendor_id = ct.id)
 
1110 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1111 ##             WHERE $invwhere|;
 
1113 ##        $union = qq| UNION |;
 
1115 ##        push(@all_values, @invvalues);
 
1118 ##      if ($form->{sold}) {
 
1122 ##             SELECT $flds, 'is' AS module, '' AS type, 1 As exchangerate
 
1124 ##             JOIN parts p ON (p.id = i.parts_id)
 
1125 ##             JOIN ar a ON (a.id = i.trans_id)
 
1126 ##             JOIN customer ct ON (a.customer_id = ct.id)
 
1127 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1128 ##             WHERE $invwhere|;
 
1129 ##        $union = qq| UNION |;
 
1131 ##        push(@all_values, @invvalues);
 
1135 ##    if ($form->{onorder} || $form->{ordered}) {
 
1136 ##      my @ordvalues = @values;
 
1137 ##      my $ordwhere = $where . qq| AND o.quotation = '0'|;
 
1139 ##      if ($form->{transdatefrom}) {
 
1140 ##        $ordwhere .= qq| AND o.transdate >= ?|;
 
1141 ##        push(@ordvalues, $form->{transdatefrom});
 
1144 ##      if ($form->{transdateto}) {
 
1145 ##        $ordwhere .= qq| AND o.transdate <= ?|;
 
1146 ##        push(@ordvalues, $form->{transdateto});
 
1149 ##      if ($form->{description}) {
 
1150 ##        $ordwhere .= qq| AND oi.description ILIKE ?|;
 
1151 ##        push(@ordvalues, '%' . $form->{description} . '%');
 
1154 ##      if ($form->{ordered}) {
 
1158 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
 
1159 ##               oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
 
1160 ##               p.listprice, p.lastcost, p.rop, p.weight,
 
1161 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
 
1163 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
 
1164 ##               ct.name, NULL AS deliverydate,
 
1165 ##               'oe' AS module, 'sales_order' AS type,
 
1166 ##               (SELECT buy FROM exchangerate ex
 
1167 ##                WHERE ex.curr = o.curr AND ex.transdate = o.transdate) AS exchangerate
 
1168 ##             FROM orderitems oi
 
1169 ##             JOIN parts p ON (oi.parts_id = p.id)
 
1170 ##             JOIN oe o ON (oi.trans_id = o.id)
 
1171 ##             JOIN customer ct ON (o.customer_id = ct.id)
 
1172 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1173 ##             WHERE $ordwhere AND (o.customer_id > 0)|;
 
1174 ##        $union = qq| UNION |;
 
1176 ##        push(@all_values, @ordvalues);
 
1179 ##      if ($form->{onorder}) {
 
1183 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
 
1184 ##               oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
 
1185 ##               p.listprice, p.lastcost, p.rop, p.weight,
 
1186 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
 
1188 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
 
1189 ##               ct.name, NULL AS deliverydate,
 
1190 ##               'oe' AS module, 'purchase_order' AS type,
 
1191 ##               (SELECT sell FROM exchangerate ex
 
1192 ##               WHERE ex.curr = o.curr AND (ex.transdate = o.transdate)) AS exchangerate
 
1193 ##             FROM orderitems oi
 
1194 ##             JOIN parts p ON (oi.parts_id = p.id)
 
1195 ##             JOIN oe o ON (oi.trans_id = o.id)
 
1196 ##             JOIN vendor ct ON (o.vendor_id = ct.id)
 
1197 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1198 ##             WHERE $ordwhere AND (o.vendor_id > 0)|;
 
1199 ##        $union = qq| UNION |;
 
1201 ##        push(@all_values, @ordvalues);
 
1206 ##    if ($form->{rfq} || $form->{quoted}) {
 
1207 ##      my $quowhere = $where . qq| AND o.quotation = '1'|;
 
1208 ##      my @quovalues = @values;
 
1210 ##      if ($form->{transdatefrom}) {
 
1211 ##        $quowhere .= qq| AND o.transdate >= ?|;
 
1212 ##        push(@quovalues, $form->{transdatefrom});
 
1215 ##      if ($form->{transdateto}) {
 
1216 ##        $quowhere .= qq| AND o.transdate <= ?|;
 
1217 ##        push(@quovalues, $form->{transdateto});
 
1220 ##      if ($form->{description}) {
 
1221 ##        $quowhere .= qq| AND oi.description ILIKE ?|;
 
1222 ##        push(@quovalues, '%' . $form->{description} . '%');
 
1225 ##      if ($form->{quoted}) {
 
1230 ##               p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
 
1231 ##               oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
 
1232 ##               p.listprice, p.lastcost, p.rop, p.weight,
 
1233 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
 
1235 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
 
1236 ##               ct.name, NULL AS deliverydate, 'oe' AS module, 'sales_quotation' AS type,
 
1237 ##               (SELECT buy FROM exchangerate ex
 
1238 ##                WHERE (ex.curr = o.curr) AND (ex.transdate = o.transdate)) AS exchangerate
 
1239 ##             FROM orderitems oi
 
1240 ##             JOIN parts p ON (oi.parts_id = p.id)
 
1241 ##             JOIN oe o ON (oi.trans_id = o.id)
 
1242 ##             JOIN customer ct ON (o.customer_id = ct.id)
 
1243 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1245 ##             AND o.customer_id > 0|;
 
1246 ##        $union = qq| UNION |;
 
1248 ##        push(@all_values, @quovalues);
 
1251 ##      if ($form->{rfq}) {
 
1255 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
 
1256 ##               oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
 
1257 ##               p.listprice, p.lastcost, p.rop, p.weight,
 
1258 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
 
1260 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
 
1261 ##               ct.name, NULL AS deliverydate,
 
1262 ##               'oe' AS module, 'request_quotation' AS type,
 
1263 ##               (SELECT sell FROM exchangerate ex
 
1264 ##               WHERE (ex.curr = o.curr) AND (ex.transdate = o.transdate)) AS exchangerate
 
1265 ##             FROM orderitems oi
 
1266 ##             JOIN parts p ON (oi.parts_id = p.id)
 
1267 ##             JOIN oe o ON (oi.trans_id = o.id)
 
1268 ##             JOIN vendor ct ON (o.vendor_id = ct.id)
 
1269 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1271 ##             AND o.vendor_id > 0|;
 
1273 ##        push(@all_values, @quovalues);
 
1277 ##    $query .= qq| ORDER BY  | . $sortorder;
 
1281 ##  $form->{parts} = selectall_hashref_query($form, $dbh, $query, @all_values);
 
1284   # include individual items for assemblies
 
1285   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
 
1287       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
 
1289            p.sellprice, p.listprice, p.lastcost,
 
1290            p.rop, p.weight, p.priceupdate,
 
1291            p.image, p.drawing, p.microfiche
 
1292          FROM parts p, assembly a
 
1293          WHERE (p.id = a.parts_id) AND (a.id = ?)|;
 
1294     $sth = prepare_query($form, $dbh, $query);
 
1296     foreach $item (@{ $form->{parts} }) {
 
1297       push(@assemblies, $item);
 
1298       do_statement($form, $sth, $query, conv_i($item->{id}));
 
1300       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1301         $ref->{assemblyitem} = 1;
 
1302         push(@assemblies, $ref);
 
1307     # copy assemblies to $form->{parts}
 
1308     $form->{parts} = \@assemblies;
 
1312   $main::lxdebug->leave_sub();
 
1316   $main::lxdebug->enter_sub();
 
1318   my ($self, $myconfig, $form) = @_;
 
1320   my $where = '1 = 1';
 
1326   if ($item ne 'make') {
 
1327     foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
 
1329       $column =~ s/.*\.//;
 
1330       next unless ($form->{$column});
 
1331       $where .= qq| AND $item ILIKE ?|;
 
1332       push(@where_values, '%' . $form->{$column} . '%');
 
1336   # special case for description
 
1337   if ($form->{description}
 
1338       && !(   $form->{bought}  || $form->{sold} || $form->{onorder}
 
1339            || $form->{ordered} || $form->{rfq} || $form->{quoted})) {
 
1340     $where .= qq| AND (p.description ILIKE ?)|;
 
1341     push(@where_values, '%' . $form->{description} . '%');
 
1344   # special case for serialnumber
 
1345   if ($form->{l_serialnumber} && $form->{serialnumber}) {
 
1346     $where .= qq| AND serialnumber ILIKE ?|;
 
1347     push(@where_values, '%' . $form->{serialnumber} . '%');
 
1351   # items which were never bought, sold or on an order
 
1352   if ($form->{itemstatus} eq 'orphaned') {
 
1353     $form->{onhand}  = $form->{short}   = 0;
 
1354     $form->{bought}  = $form->{sold}    = 0;
 
1355     $form->{onorder} = $form->{ordered} = 0;
 
1356     $form->{rfq}     = $form->{quoted}  = 0;
 
1358     $form->{transdatefrom} = $form->{transdateto} = "";
 
1361       qq| AND (p.onhand = 0)
 
1364               SELECT DISTINCT parts_id FROM invoice
 
1366               SELECT DISTINCT parts_id FROM assembly
 
1368               SELECT DISTINCT parts_id FROM orderitems
 
1372   if ($form->{itemstatus} eq 'active') {
 
1373     $where .= qq| AND p.obsolete = '0'|;
 
1376   if ($form->{itemstatus} eq 'obsolete') {
 
1377     $where .= qq| AND p.obsolete = '1'|;
 
1378     $form->{onhand} = $form->{short} = 0;
 
1381   if ($form->{itemstatus} eq 'onhand') {
 
1382     $where .= qq| AND p.onhand > 0|;
 
1385   if ($form->{itemstatus} eq 'short') {
 
1386     $where .= qq| AND p.onhand < p.rop|;
 
1389   foreach my $column (qw(make model)) {
 
1390     next unless ($form->{$colum});
 
1391     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
 
1392     push(@where_values, '%' . $form->{$column} . '%');
 
1395   # connect to database
 
1396   my $dbh = $form->dbconnect_noauto($myconfig);
 
1398   for my $column (qw(sellprice listprice)) {
 
1399     next if ($form->{$column} eq "");
 
1401     my $value = $form->parse_amount($myconfig, $form->{$column});
 
1404     if ($form->{"${column}_type"} eq "percent") {
 
1405       $value = ($value / 100) + 1;
 
1410       qq|UPDATE parts SET $column = $column $operator ?
 
1414             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1416     do_query($from, $dbh, $query, $value, @where_values);
 
1420     qq|UPDATE prices SET price = price + ?
 
1424           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1425           WHERE $where) AND (pricegroup_id = ?)|;
 
1426   my $sth_add = prepare_query($form, $dbh, $q_add);
 
1429     qq|UPDATE prices SET price = price * ?
 
1433           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1434           WHERE $where) AND (pricegroup_id = ?)|;
 
1435   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
 
1437   for my $i (1 .. $form->{price_rows}) {
 
1438     next if ($form->{"price_$i"} eq "");
 
1440     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
 
1442     if ($form->{"pricegroup_type_$i"} eq "percent") {
 
1443       do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1445       do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1450   $sth_multiply->finish();
 
1452   my $rc= $dbh->commit;
 
1455   $main::lxdebug->leave_sub();
 
1461   $main::lxdebug->enter_sub();
 
1463   my ($self, $module, $myconfig, $form) = @_;
 
1465   # connect to database
 
1466   my $dbh = $form->dbconnect($myconfig);
 
1468   my @values = ('%' . $module . '%');
 
1472       qq|SELECT c.accno, c.description, c.link, c.id,
 
1473            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
 
1474          FROM chart c, parts p
 
1475          WHERE (c.link LIKE ?) AND (p.id = ?)
 
1477     push(@values, conv_i($form->{id}));
 
1481       qq|SELECT c.accno, c.description, c.link, c.id,
 
1482            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
 
1483          FROM chart c, defaults d
 
1488   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1489   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1490     foreach my $key (split(/:/, $ref->{link})) {
 
1491       if ($key =~ /\Q$module\E/) {
 
1492         if (   ($ref->{id} eq $ref->{inventory_accno_id})
 
1493             || ($ref->{id} eq $ref->{income_accno_id})
 
1494             || ($ref->{id} eq $ref->{expense_accno_id})) {
 
1495           push @{ $form->{"${module}_links"}{$key} },
 
1496             { accno       => $ref->{accno},
 
1497               description => $ref->{description},
 
1498               selected    => "selected" };
 
1499           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
 
1501           push @{ $form->{"${module}_links"}{$key} },
 
1502             { accno       => $ref->{accno},
 
1503               description => $ref->{description},
 
1511   # get buchungsgruppen
 
1512   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
 
1515   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
 
1518     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
 
1522   $main::lxdebug->leave_sub();
 
1525 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
 
1527   $main::lxdebug->enter_sub();
 
1529   my ($self, $myconfig, $form, $sortorder) = @_;
 
1530   my $dbh   = $form->dbconnect($myconfig);
 
1531   my $order = qq| p.partnumber|;
 
1532   my $where = qq|1 = 1|;
 
1535   if ($sortorder eq "all") {
 
1536     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
 
1537     push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
 
1539   } elsif ($sortorder eq "partnumber") {
 
1540     $where .= qq| AND (partnumber ILIKE ?)|;
 
1541     push(@values, '%' . $form->{partnumber} . '%');
 
1543   } elsif ($sortorder eq "description") {
 
1544     $where .= qq| AND (description ILIKE ?)|;
 
1545     push(@values, '%' . $form->{description} . '%');
 
1546     $order = "description";
 
1551     qq|SELECT id, partnumber, description, unit, sellprice
 
1553        WHERE $where ORDER BY $order|;
 
1555   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1558   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1559     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
 
1564     $form->{"id_$j"}          = $ref->{id};
 
1565     $form->{"partnumber_$j"}  = $ref->{partnumber};
 
1566     $form->{"description_$j"} = $ref->{description};
 
1567     $form->{"unit_$j"}        = $ref->{unit};
 
1568     $form->{"sellprice_$j"}   = $ref->{sellprice};
 
1569     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
 
1575   $main::lxdebug->leave_sub();
 
1580 # gets sum of sold part with part_id
 
1582   $main::lxdebug->enter_sub();
 
1584   my ($dbh, $id) = @_;
 
1586   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
 
1587   my ($sum) = selectrow_query($form, $dbh, $query, conv_i($id));
 
1590   $main::lxdebug->leave_sub();
 
1593 }    #end get_soldtotal
 
1595 sub retrieve_languages {
 
1596   $main::lxdebug->enter_sub();
 
1598   my ($self, $myconfig, $form) = @_;
 
1600   # connect to database
 
1601   my $dbh = $form->dbconnect($myconfig);
 
1606   if ($form->{language_values} ne "") {
 
1608       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
 
1610          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
 
1611          ORDER BY lower(l.description)|;
 
1612     @values = (conv_i($form->{id}));
 
1615     $query = qq|SELECT id, description
 
1617                 ORDER BY lower(description)|;
 
1620   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
 
1624   $main::lxdebug->leave_sub();
 
1629 sub follow_account_chain {
 
1630   $main::lxdebug->enter_sub(2);
 
1632   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
 
1634   my @visited_accno_ids = ($accno_id);
 
1639     qq|SELECT c.new_chart_id, date($transdate) >= c.valid_from AS is_valid, | .
 
1642     qq|LEFT JOIN chart cnew ON c.new_chart_id = cnew.id | .
 
1643     qq|WHERE (c.id = ?) AND NOT c.new_chart_id ISNULL AND (c.new_chart_id > 0)|;
 
1644   $sth = prepare_query($form, $dbh, $query);
 
1647     do_statement($form, $sth, $query, $accno_id);
 
1648     $ref = $sth->fetchrow_hashref();
 
1649     last unless ($ref && $ref->{"is_valid"} &&
 
1650                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
 
1651     $accno_id = $ref->{"new_chart_id"};
 
1652     $accno = $ref->{"accno"};
 
1653     push(@visited_accno_ids, $accno_id);
 
1656   $main::lxdebug->leave_sub(2);
 
1658   return ($accno_id, $accno);
 
1661 sub retrieve_accounts {
 
1662   $main::lxdebug->enter_sub(2);
 
1664   my ($self, $myconfig, $form, $parts_id, $index) = @_;
 
1666   my ($query, $sth, $dbh);
 
1668   $form->{"taxzone_id"} *= 1;
 
1670   $dbh = $form->get_standard_dbh($myconfig);
 
1673   if ($form->{type} eq "invoice") {
 
1674     if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
 
1675       $transdate = $form->{invdate};
 
1677       $transdate = $form->{deliverydate};
 
1679   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
 
1680     $transdate = $form->{invdate};
 
1682     $transdate = $form->{transdate};
 
1685   if ($transdate eq "") {
 
1686     $transdate = "current_date";
 
1688     $transdate = $dbh->quote($transdate);
 
1693     qq|  p.inventory_accno_id AS is_part, | .
 
1694     qq|  bg.inventory_accno_id, | .
 
1695     qq|  bg.income_accno_id_$form->{taxzone_id} AS income_accno_id, | .
 
1696     qq|  bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id, | .
 
1697     qq|  c1.accno AS inventory_accno, | .
 
1698     qq|  c2.accno AS income_accno, | .
 
1699     qq|  c3.accno AS expense_accno | .
 
1701     qq|LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id | .
 
1702     qq|LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id | .
 
1703     qq|LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id | .
 
1704     qq|LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id | .
 
1706   my $ref = selectfirst_hashref_query($form, $dbh, $query, $parts_id);
 
1708   return $main::lxdebug->leave_sub(2) if (!$ref);
 
1710   $ref->{"inventory_accno_id"} = undef unless ($ref->{"is_part"});
 
1713   foreach my $type (qw(inventory income expense)) {
 
1714     next unless ($ref->{"${type}_accno_id"});
 
1715     ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
 
1716       $self->follow_account_chain($form, $dbh, $transdate,
 
1717                                   $ref->{"${type}_accno_id"},
 
1718                                   $ref->{"${type}_accno"});
 
1721   map({ $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} }
 
1722       qw(inventory income expense));
 
1724   my $inc_exp = $form->{"vc"} eq "customer" ? "income" : "expense";
 
1725   my $accno_id = $accounts{"${inc_exp}_accno_id"};
 
1728     qq|SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber | .
 
1730     qq|LEFT JOIN chart c ON c.id = t.chart_id | .
 
1731     qq|WHERE t.id IN | .
 
1732     qq|  (SELECT tk.tax_id | .
 
1733     qq|   FROM taxkeys tk | .
 
1734     qq|   WHERE tk.chart_id = ? AND startdate <= | . quote_db_date($transdate) .
 
1735     qq|   ORDER BY startdate DESC LIMIT 1) |;
 
1736   $ref = selectfirst_hashref_query($form, $dbh, $query, $accno_id);
 
1739     $main::lxdebug->leave_sub(2);
 
1743   $form->{"taxaccounts_$index"} = $ref->{"accno"};
 
1744   if ($form->{"taxaccounts"} !~ /$ref->{accno}/) {
 
1745     $form->{"taxaccounts"} .= "$ref->{accno} ";
 
1747   map({ $form->{"$ref->{accno}_${_}"} = $ref->{$_}; }
 
1748       qw(rate description taxnumber));
 
1750 #   $main::lxdebug->message(0, "formvars: rate " . $form->{"$ref->{accno}_rate"} .
 
1751 #                           " description " . $form->{"$ref->{accno}_description"} .
 
1752 #                           " taxnumber " . $form->{"$ref->{accno}_taxnumber"} .
 
1753 #                           " || taxaccounts_$index " . $form->{"taxaccounts_$index"} .
 
1754 #                           " || taxaccounts " . $form->{"taxaccounts"});
 
1756   $main::lxdebug->leave_sub(2);
 
1759 sub get_basic_part_info {
 
1760   $main::lxdebug->enter_sub();
 
1765   Common::check_params(\%params, qw(id));
 
1767   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
 
1770     $main::lxdebug->leave_sub();
 
1774   my $myconfig = \%main::myconfig;
 
1775   my $form     = $main::form;
 
1777   my $dbh      = $form->get_standard_dbh($myconfig);
 
1779   my $query    = qq|SELECT id, partnumber, description, unit FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
 
1781   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
 
1783   if ($params{vendor_id}) {
 
1784     $query     = qq|SELECT * FROM parts_vendor WHERE (parts_id = ?) AND (vendor_id = ?)|;
 
1785     my $sth    = prepare_query($form, $dbh, $query);
 
1787     foreach my $part (@{ $info }) {
 
1788       do_statement($form, $sth, $query, $part->{id}, conv_i($params{vendor_id}));
 
1789       $part->{vendor_info} = $sth->fetchrow_hashref();
 
1795   if ('' eq ref $params{id}) {
 
1796     $info = $info->[0] || { };
 
1798     $main::lxdebug->leave_sub();
 
1802   my %info_map = map { $_->{id} => $_ } @{ $info };
 
1804   $main::lxdebug->leave_sub();