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 #======================================================================
 
  40   $main::lxdebug->enter_sub();
 
  42   my ($self, $myconfig, $form) = @_;
 
  45   my $dbh = $form->dbconnect($myconfig);
 
  51          c1.accno AS inventory_accno,
 
  52          c2.accno AS income_accno,
 
  53          c3.accno AS expense_accno,
 
  56        LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
 
  57        LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
 
  58        LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
 
  59        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
  61   my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
  63   # copy to $form variables
 
  64   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
 
  66   my %oid = ('Pg'     => 'a.oid',
 
  67              'Oracle' => 'a.rowid');
 
  69   # part or service item
 
  70   $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
 
  71   if ($form->{assembly}) {
 
  72     $form->{item} = 'assembly';
 
  74     # retrieve assembly items
 
  76       qq|SELECT p.id, p.partnumber, p.description,
 
  77            p.sellprice, p.weight, a.qty, a.bom, p.unit,
 
  80          JOIN assembly a ON (a.parts_id = p.id)
 
  81          LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
  83          ORDER BY $oid{$myconfig->{dbdriver}}|;
 
  84     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
  86     $form->{assembly_rows} = 0;
 
  87     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
  88       $form->{assembly_rows}++;
 
  89       foreach my $key (keys %{$ref}) {
 
  90         $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
 
  97   # setup accno hash for <option checked> {amount} is used in create_links
 
  98   $form->{amount}{IC}         = $form->{inventory_accno};
 
  99   $form->{amount}{IC_income}  = $form->{income_accno};
 
 100   $form->{amount}{IC_sale}    = $form->{income_accno};
 
 101   $form->{amount}{IC_expense} = $form->{expense_accno};
 
 102   $form->{amount}{IC_cogs}    = $form->{expense_accno};
 
 104   my @pricegroups          = ();
 
 105   my @pricegroups_not_used = ();
 
 109     qq|SELECT p.parts_id, p.pricegroup_id, p.price,
 
 110          (SELECT pg.pricegroup
 
 112           WHERE pg.id = p.pricegroup_id) AS pricegroup
 
 115        ORDER BY pricegroup|;
 
 116   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 120   while (($form->{"klass_$i"}, $form->{"pricegroup_id_$i"},
 
 121           $form->{"price_$i"}, $form->{"pricegroup_$i"})
 
 122          = $sth->fetchrow_array()) {
 
 123     $form->{"price_$i"} = $form->round_amount($form->{"price_$i"}, 5);
 
 124     $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
 125     push @pricegroups, $form->{"pricegroup_id_$i"};
 
 132   $query = qq|SELECT id, pricegroup FROM pricegroup|;
 
 133   $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
 
 135   #find not used pricegroups
 
 136   while ($tmp = pop(@{ $form->{PRICEGROUPS} })) {
 
 138     foreach my $item (@pricegroups) {
 
 139       if ($item eq $tmp->{id}) {
 
 144     push(@pricegroups_not_used, $tmp) unless ($in_use);
 
 147   # if not used pricegroups are avaible
 
 148   if (@pricegroups_not_used) {
 
 150     foreach $name (@pricegroups_not_used) {
 
 151       $form->{"klass_$i"} = "$name->{id}";
 
 152       $form->{"price_$i"} = $form->round_amount($form->{sellprice}, 5);
 
 153       $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
 154       $form->{"pricegroup_id_$i"} = "$name->{id}";
 
 155       $form->{"pricegroup_$i"}    = "$name->{pricegroup}";
 
 161   $form->{price_rows} = $i - 1;
 
 163   unless ($form->{item} eq 'service') {
 
 166     if ($form->{makemodel}) {
 
 167       $query = qq|SELECT m.make, m.model FROM makemodel m | .
 
 168                qq|WHERE m.parts_id = ?|;
 
 169       @values = ($form->{id});
 
 170       $sth = $dbh->prepare($query);
 
 171       $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
 
 174       while (($form->{"make_$i"}, $form->{"model_$i"}) = $sth->fetchrow_array)
 
 179       $form->{makemodel_rows} = $i - 1;
 
 185   $form->{language_values} = "";
 
 186   $query = qq|SELECT language_id, translation FROM translation WHERE parts_id = ?|;
 
 187   my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 188   while ($tr = $trq->fetchrow_hashref(NAME_lc)) {
 
 189     $form->{language_values} .= "---+++---".$tr->{language_id}."--++--".$tr->{translation};
 
 193   # now get accno for taxes
 
 196        FROM chart c, partstax pt
 
 197        WHERE (pt.chart_id = c.id) AND (pt.parts_id = ?)|;
 
 198   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 199   while (($key) = $sth->fetchrow_array) {
 
 200     $form->{amount}{$key} = $key;
 
 209        WHERE (i.parts_id = ?)
 
 215        WHERE (o.parts_id = ?)
 
 221        WHERE (a.parts_id = ?)|;
 
 222   @values = (conv_i($form->{id}), conv_i($form->{id}), conv_i($form->{id}));
 
 223   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, @values);
 
 224   $form->{orphaned} = !$form->{orphaned};
 
 226   $form->{"unit_changeable"} = 1;
 
 227   foreach my $table (qw(invoice assembly orderitems inventory license)) {
 
 228     $query = qq|SELECT COUNT(*) FROM $table WHERE parts_id = ?|;
 
 229     my ($count) = selectrow_query($form, $dbh, $query, conv_i($form->{"id"}));
 
 232       $form->{"unit_changeable"} = 0;
 
 239   $main::lxdebug->leave_sub();
 
 242 sub get_pricegroups {
 
 243   $main::lxdebug->enter_sub();
 
 245   my ($self, $myconfig, $form) = @_;
 
 247   my $dbh = $form->dbconnect($myconfig);
 
 250   my $query = qq|SELECT id, pricegroup FROM pricegroup|;
 
 251   my $pricegroups = selectall_hashref_query($form, $dbh, $query);
 
 254   foreach $pg (@{ $pricegroups }) {
 
 255     $form->{"klass_$i"} = "$pg->{id}";
 
 256     $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
 257     $form->{"pricegroup_id_$i"} = "$pg->{id}";
 
 258     $form->{"pricegroup_$i"}    = "$pg->{pricegroup}";
 
 263   $form->{price_rows} = $i - 1;
 
 267   $main::lxdebug->leave_sub();
 
 270 sub retrieve_buchungsgruppen {
 
 271   $main::lxdebug->enter_sub();
 
 273   my ($self, $myconfig, $form) = @_;
 
 277   my $dbh = $form->dbconnect($myconfig);
 
 279   # get buchungsgruppen
 
 280   $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
 
 281   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
 
 283   $main::lxdebug->leave_sub();
 
 287   $main::lxdebug->enter_sub();
 
 289   my ($self, $myconfig, $form) = @_;
 
 291   # connect to database, turn off AutoCommit
 
 292   my $dbh = $form->dbconnect_noauto($myconfig);
 
 295   # make up a unique handle and store in partnumber field
 
 296   # then retrieve the record based on the unique handle to get the id
 
 297   # replace the partnumber field with the actual variable
 
 298   # add records for makemodel
 
 300   # if there is a $form->{id} then replace the old entry
 
 301   # delete all makemodel entries and add the new ones
 
 303   # undo amount formatting
 
 304   map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
 
 305     qw(rop weight listprice sellprice gv lastcost stock);
 
 307   my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
 
 309   $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
 
 316     $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
 
 317     my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
 
 319     # if item is part of an assembly adjust all assemblies
 
 320     $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
 
 321     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 322     while (my ($id, $qty) = $sth->fetchrow_array) {
 
 323       &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
 
 327     if ($form->{item} ne 'service') {
 
 328       # delete makemodel records
 
 329       do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
 
 332     if ($form->{item} eq 'assembly') {
 
 333       if ($form->{onhand} != 0) {
 
 334         &adjust_inventory($dbh, $form, $form->{id}, $form->{onhand} * -1);
 
 337       # delete assembly records
 
 338       do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
 
 340       $form->{onhand} += $form->{stock};
 
 344     do_query($form, $dbh, qq|DELETE FROM partstax WHERE parts_id = ?|, conv_i($form->{id}));
 
 346     # delete translations
 
 347     do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
 
 350     my ($count) = selectrow_query($form, $dbh, qq|SELECT COUNT(*) FROM parts WHERE partnumber = ?|, $form->{partnumber});
 
 352       $main::lxdebug->leave_sub();
 
 356     ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
 
 357     do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber) VALUES (?, '')|, $form->{id});
 
 359     $form->{orphaned} = 1;
 
 360     $form->{onhand} = $form->{stock} if $form->{item} eq 'assembly';
 
 361     if ($form->{partnumber} eq "" && $form->{"item"} eq "service") {
 
 362       $form->{partnumber} = $form->update_defaults($myconfig, "servicenumber");
 
 364     if ($form->{partnumber} eq "" && $form->{"item"} ne "service") {
 
 365       $form->{partnumber} = $form->update_defaults($myconfig, "articlenumber");
 
 369   my $partsgroup_id = 0;
 
 371   if ($form->{partsgroup}) {
 
 372     ($partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
 
 375   my ($subq_inventory, $subq_expense, $subq_income);
 
 376   if ($form->{"item"} eq "part") {
 
 378       qq|(SELECT bg.inventory_accno_id
 
 379           FROM buchungsgruppen bg
 
 380           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 382     $subq_inventory = "NULL";
 
 385   if ($form->{"item"} ne "assembly") {
 
 387       qq|(SELECT bg.expense_accno_id_0
 
 388           FROM buchungsgruppen bg
 
 389           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 391     $subq_expense = "NULL";
 
 411          buchungsgruppen_id = ?,
 
 413          inventory_accno_id = $subq_inventory,
 
 414          income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
 
 415          expense_accno_id = $subq_expense,
 
 423          not_discountable = ?,
 
 428   @values = ($form->{partnumber},
 
 429              $form->{description},
 
 430              $makemodel ? 't' : 'f',
 
 431              $form->{assembly} ? 't' : 'f',
 
 436              conv_date($form->{priceupdate}),
 
 442              conv_i($form->{buchungsgruppen_id}),
 
 443              conv_i($form->{payment_id}),
 
 444              conv_i($form->{buchungsgruppen_id}),
 
 445              $form->{obsolete} ? 't' : 'f',
 
 448              $form->{shop} ? 't' : 'f',
 
 452              $form->{not_discountable} ? 't' : 'f',
 
 454              conv_i($partsgroup_id),
 
 455              conv_i($form->{price_factor_id}),
 
 458   do_query($form, $dbh, $query, @values);
 
 460   # delete translation records
 
 461   do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
 
 463   if ($form->{language_values} ne "") {
 
 464     foreach $item (split(/---\+\+\+---/, $form->{language_values})) {
 
 465       my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
 
 466       if ($translation ne "") {
 
 467         $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
 
 468                     VALUES ( ?, ?, ?, ? )|;
 
 469         @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
 
 470         do_query($form, $dbh, $query, @values);
 
 475   # delete price records
 
 476   do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
 
 478   # insert price records only if different to sellprice
 
 479   for my $i (1 .. $form->{price_rows}) {
 
 480     if ($form->{"price_$i"} eq "0") {
 
 481       $form->{"price_$i"} = $form->{sellprice};
 
 484         (   $form->{"price_$i"}
 
 485          || $form->{"klass_$i"}
 
 486          || $form->{"pricegroup_id_$i"})
 
 487         and $form->{"price_$i"} != $form->{sellprice}
 
 489       #$klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
 
 490       $price = $form->parse_amount($myconfig, $form->{"price_$i"});
 
 492         $form->parse_amount($myconfig, $form->{"pricegroup_id_$i"});
 
 493       $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) | .
 
 495       @values = (conv_i($form->{id}), conv_i($pricegroup_id), $price);
 
 496       do_query($form, $dbh, $query, @values);
 
 500   # insert makemodel records
 
 501   unless ($form->{item} eq 'service') {
 
 502     for my $i (1 .. $form->{makemodel_rows}) {
 
 503       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
 
 504         map { $form->{"${_}_$i"} =~ s/\'/\'\'/g } qw(make model);
 
 506         $query = qq|INSERT INTO makemodel (parts_id, make, model) | .
 
 507                              qq|VALUES (?, ?, ?)|;
 
 508                     @values = (conv_i($form->{id}), $form->{"make_$i"}, $form->{"model_$i"});
 
 509         do_query($form, $dbh, $query, @values);
 
 515   foreach $item (split(/ /, $form->{taxaccounts})) {
 
 516     if ($form->{"IC_tax_$item"}) {
 
 518         qq|INSERT INTO partstax (parts_id, chart_id)
 
 519            VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
 
 520                         @values = (conv_i($form->{id}), $item);
 
 521       do_query($form, $dbh, $query, @values);
 
 525   # add assembly records
 
 526   if ($form->{item} eq 'assembly') {
 
 528     for my $i (1 .. $form->{assembly_rows}) {
 
 529       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 531       if ($form->{"qty_$i"} != 0) {
 
 532         $form->{"bom_$i"} *= 1;
 
 533         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
 
 534                              qq|VALUES (?, ?, ?, ?)|;
 
 535                     @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
 
 536         do_query($form, $dbh, $query, @values);
 
 540     # adjust onhand for the parts
 
 541     if ($form->{onhand} != 0) {
 
 542       &adjust_inventory($dbh, $form, $form->{id}, $form->{onhand});
 
 548     my $shippingdate = "$a[5]-$a[4]-$a[3]";
 
 550     $form->get_employee($dbh);
 
 552     # add inventory record
 
 554       qq|INSERT INTO inventory (warehouse_id, parts_id, qty, shippingdate, employee_id)
 
 555          VALUES (0, ?, ?, '$shippingdate', ?)|;
 
 556     @values = (conv_i($form->{id}), $form->{stock}, conv_i($form->{employee_id}));
 
 557     do_query($form, $dbh, $query, @values);
 
 561   #set expense_accno=inventory_accno if they are different => bilanz
 
 563     ($form->{expense_accno} != $form->{inventory_accno})
 
 564     ? $form->{inventory_accno}
 
 565     : $form->{expense_accno};
 
 567   # get tax rates and description
 
 569     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
 
 571     qq|SELECT c.accno, c.description, t.rate, t.taxnumber
 
 573        WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
 
 575   $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
 
 577   $form->{taxaccount} = "";
 
 578   while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
 579     $form->{taxaccount} .= "$ptr->{accno} ";
 
 580     if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
 
 581       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
 582       $form->{"$ptr->{accno}_description"} = $ptr->{description};
 
 583       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
 584       $form->{taxaccount2} .= " $ptr->{accno} ";
 
 589   my $rc = $dbh->commit;
 
 592   $main::lxdebug->leave_sub();
 
 597 sub update_assembly {
 
 598   $main::lxdebug->enter_sub();
 
 600   my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
 
 602   my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
 
 603   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
 
 605   while (my ($pid, $aqty) = $sth->fetchrow_array) {
 
 606     &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
 
 611     qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
 
 613   @values = ($qty * ($form->{sellprice} - $sellprice),
 
 614              $qty * ($form->{weight} - $weight), conv_i($id));
 
 615   do_query($form, $dbh, $query, @values);
 
 617   $main::lxdebug->leave_sub();
 
 620 sub retrieve_assemblies {
 
 621   $main::lxdebug->enter_sub();
 
 623   my ($self, $myconfig, $form) = @_;
 
 625   # connect to database
 
 626   my $dbh = $form->dbconnect($myconfig);
 
 628   my $where = qq|NOT p.obsolete|;
 
 631   if ($form->{partnumber}) {
 
 632     $where .= qq| AND (p.partnumber ILIKE ?)|;
 
 633     push(@values, '%' . $form->{partnumber} . '%');
 
 636   if ($form->{description}) {
 
 637     $where .= qq| AND (p.description ILIKE ?)|;
 
 638     push(@values, '%' . $form->{description} . '%');
 
 641   # retrieve assembly items
 
 643     qq|SELECT p.id, p.partnumber, p.description,
 
 644          p.bin, p.onhand, p.rop,
 
 645          (SELECT sum(p2.inventory_accno_id)
 
 646           FROM parts p2, assembly a
 
 647           WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
 
 649        WHERE NOT p.obsolete AND p.assembly $where|;
 
 651   $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
 
 655   $main::lxdebug->leave_sub();
 
 658 sub restock_assemblies {
 
 659   $main::lxdebug->enter_sub();
 
 661   my ($self, $myconfig, $form) = @_;
 
 663   # connect to database
 
 664   my $dbh = $form->dbconnect_noauto($myconfig);
 
 666   for my $i (1 .. $form->{rowcount}) {
 
 668     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 670     if ($form->{"qty_$i"} != 0) {
 
 671       &adjust_inventory($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"});
 
 676   my $rc = $dbh->commit;
 
 679   $main::lxdebug->leave_sub();
 
 684 sub adjust_inventory {
 
 685   $main::lxdebug->enter_sub();
 
 687   my ($dbh, $form, $id, $qty) = @_;
 
 690     qq|SELECT p.id, p.inventory_accno_id, p.assembly, a.qty
 
 691        FROM parts p, assembly a
 
 692        WHERE (a.parts_id = p.id) AND (a.id = ?)|;
 
 693   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
 
 695   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
 697     my $allocate = $qty * $ref->{qty};
 
 699     # is it a service item, then loop
 
 700     $ref->{inventory_accno_id} *= 1;
 
 701     next if (($ref->{inventory_accno_id} == 0) && !$ref->{assembly});
 
 703     # adjust parts onhand
 
 704     $form->update_balance($dbh, "parts", "onhand",
 
 712   my $rc = $form->update_balance($dbh, "parts", "onhand", qq|id = ?|, $qty, $id);
 
 714   $main::lxdebug->leave_sub();
 
 720   $main::lxdebug->enter_sub();
 
 722   my ($self, $myconfig, $form) = @_;
 
 723   my @values = (conv_i($form->{id}));
 
 724   # connect to database, turn off AutoCommit
 
 725   my $dbh = $form->dbconnect_noauto($myconfig);
 
 727   my %columns = ( "assembly" => "id", "alternate" => "id", "parts" => "id" );
 
 729   for my $table (qw(prices partstax makemodel inventory assembly parts)) {
 
 730     my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
 
 731     do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
 
 735   my $rc = $dbh->commit;
 
 738   $main::lxdebug->leave_sub();
 
 744   $main::lxdebug->enter_sub();
 
 746   my ($self, $myconfig, $form) = @_;
 
 748   my $i = $form->{assembly_rows};
 
 750   my $where = qq|1 = 1|;
 
 753   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
 
 755   while (my ($column, $table) = each(%columns)) {
 
 756     next unless ($form->{"${column}_$i"});
 
 757     $where .= qq| AND ${table}.${column} ILIKE ?|;
 
 758     push(@values, '%' . $form->{"${column}_$i"} . '%');
 
 762     $where .= qq| AND NOT (p.id = ?)|;
 
 763     push(@values, conv_i($form->{id}));
 
 767     $where .= qq| ORDER BY p.partnumber|;
 
 769     $where .= qq| ORDER BY p.description|;
 
 772   # connect to database
 
 773   my $dbh = $form->dbconnect($myconfig);
 
 776     qq|SELECT p.id, p.partnumber, p.description, p.sellprice, p.weight, p.onhand, p.unit, pg.partsgroup
 
 778        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 780   $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
 
 784   $main::lxdebug->leave_sub();
 
 789 # Warning, deep magic ahead.
 
 790 # This function gets all parts from the database according to the filters specified
 
 793 #   sort revers  - sorting field + direction
 
 796 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
 
 797 #   partnumber ean description partsgroup microfiche drawing
 
 800 #   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
 
 803 #   itemstatus  = active | onhand | short | obsolete | orphaned
 
 804 #   searchitems = part | assembly | service
 
 807 #   make model                               - makemodel
 
 808 #   serialnumber transdatefrom transdateto   - invoice/orderitems
 
 811 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
 
 812 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
 
 813 #   l_soldtotal                              - aggreg join to display total of sold quantity
 
 814 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 815 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
 
 816 #   l_serialnumber                           - belonges to serialnumber filter
 
 817 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
 
 820 #   l_soldtotal                              - aggreg join to display total of sold quantity
 
 821 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 822 #   masking of onhand in bsooqr mode         - ToDO: fixme
 
 824 # disabled sanity checks and changes:
 
 825 #  - searchitems = assembly will no longer disable bought
 
 826 #  - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
 
 827 #  - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
 
 828 #  - itemstatus = obsolete will no longer disable onhand, short
 
 829 #  - allow sorting by ean
 
 830 #  - serialnumber filter also works if l_serialnumber isn't ticked
 
 831 #  - onhand doesn't get masked by it's oi or invoice counterparts atm. ToDO: fix this
 
 832 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
 
 835   $main::lxdebug->enter_sub();
 
 837   my ($self, $myconfig, $form) = @_;
 
 838   my $dbh = $form->get_standard_dbh($myconfig);
 
 840   $form->{parts} = +{ };
 
 842   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
 
 843   my @makemodel_filters    = qw(make model);
 
 844   my @invoice_oi_filters   = qw(serialnumber soldtotal);
 
 845   my @apoe_filters         = qw(transdate);
 
 846   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
 
 847   my @simple_l_switches    = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
 
 848   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
 
 849   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module);
 
 850   my @deliverydate_flags   = qw(deliverydate);
 
 851 #  my @other_flags          = qw(onhand); # ToDO: implement these
 
 852 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
 
 855     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
 
 856     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
 
 857     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
 
 860          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem, 'invoice'    AS ioi FROM invoice UNION
 
 861          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, 'orderitems' AS ioi FROM orderitems
 
 862        ) AS ioi ON ioi.parts_id = p.id|,
 
 865          SELECT id, transdate, 'ir' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation, NULL AS customer_id,         vendor_id, NULL AS deliverydate FROM ap UNION
 
 866          SELECT id, transdate, 'is' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation,         customer_id, NULL AS vendor_id,         deliverydate FROM ar UNION
 
 867          SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber,          quotation,         customer_id,         vendor_id, NULL AS deliverydate FROM oe
 
 868        ) AS apoe ON ioi.trans_id = apoe.id|,
 
 871            SELECT id, name, 'customer' AS cv FROM customer UNION
 
 872            SELECT id, name, 'vendor'   AS cv FROM vendor
 
 873          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
 
 875   my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
 
 878   #===== switches and simple filters ========#
 
 880   my @select_tokens = qw(id factor);
 
 881   my @where_tokens  = qw(1=1);
 
 882   my @group_tokens  = ();
 
 884   # special case transdate
 
 885   if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
 
 886     $form->{"l_transdate"} = 1;
 
 887     push @select_tokens, 'transdate';
 
 888     for (qw(transdatefrom transdateto)) {
 
 889       next unless $form->{$_};
 
 890       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
 
 891       push @bind_vars,    $form->{$_};
 
 895   my %simple_filter_table_prefix = (
 
 899   foreach (@simple_filters, @makemodel_filters, @invoice_oi_filters) {
 
 900     next unless $form->{$_};
 
 901     $form->{"l_$_"} = '1'; # show the column
 
 902     push @where_tokens, "$simple_filter_table_prefix{$_}$_ ILIKE ?";
 
 903     push @bind_vars,    "%$form->{$_}%";
 
 906   foreach (@simple_l_switches) {
 
 907     next unless $form->{"l_$_"};
 
 908     push @select_tokens, $_;
 
 911   for ($form->{searchitems}) {
 
 912     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
 
 913     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
 
 914     push @where_tokens, 'NOT p.assembly'               if /service/;
 
 915     push @where_tokens, '    p.assembly'               if /assembly/;
 
 918   for ($form->{itemstatus}) {
 
 919     push @where_tokens, 'p.id NOT IN
 
 920         (SELECT DISTINCT parts_id FROM invoice UNION
 
 921          SELECT DISTINCT parts_id FROM assembly UNION
 
 922          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
 
 923     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
 
 924     push @where_tokens, 'NOT p.obsolete'               if /active/;
 
 925     push @where_tokens, '    p.obsolete',              if /obsolete/;
 
 926     push @where_tokens, 'p.onhand > 0',                if /onhand/;
 
 927     push @where_tokens, 'p.onhand < p.rop',            if /short/;
 
 931   my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
 
 932   $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols;
 
 934   my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
 
 936   # special case: sorting by partnumber
 
 937   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
 
 938   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
 
 939   # ToDO: implement proper functional sorting
 
 940   $form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
 
 941     if $form->{sort} eq 'partnumber';
 
 943   my $order_clause = " ORDER BY $form->{sort} $sort_order";
 
 945   my $limit_clause = " LIMIT 100" if $form->{top100};
 
 947   #=== joins and complicated filters ========#
 
 949   my $bsooqr = $form->{bought}  || $form->{sold}
 
 950             || $form->{ordered} || $form->{onorder}
 
 951             || $form->{quoted}  || $form->{rfq};
 
 954   push @select_tokens, @qsooqr_flags                                          if $bsooqr;
 
 955   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
 
 956   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
 
 957   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
 
 958   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
 
 959   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
 
 960   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
 
 961   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
 
 962   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
 
 964   $joins_needed{partsgroup}  = 1;
 
 965   $joins_needed{pfac}        = 1;
 
 966   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
 
 967   $joins_needed{cv}          = 1 if $bsooqr;
 
 968   $joins_needed{apoe}        = 1 if $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
 
 969   $joins_needed{invoice_oi}  = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
 
 971   # special case for description search.
 
 972   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
 
 973   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
 
 974   # find the old entries in of @where_tokens and @bind_vars, and adjust them
 
 975   if ($joins_needed{invoice_oi}) {
 
 976     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
 
 977       next unless $where_tokens[$wi] =~ /^description ILIKE/;
 
 978       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
 
 979       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
 
 984   # now the master trick: soldtotal.
 
 985   if ($form->{l_soldtotal}) {
 
 986     push @where_tokens, 'ioi.qty >= 0';
 
 987     push @group_tokens, @select_tokens;
 
 988     push @select_tokens, 'SUM(ioi.qty)';
 
 991   #============= build query ================#
 
 995      deliverydate => 'apoe.', serialnumber => 'ioi.',
 
 996      transdate    => 'apoe.', trans_id     => 'ioi.',
 
 997      module       => 'apoe.', name         => 'cv.',
 
 998      ordnumber    => 'apoe.', make         => 'mm.',
 
 999      quonumber    => 'apoe.', model        => 'mm.',
 
1000      invnumber    => 'apoe.', partsgroup   => 'pg.',
 
1002      'SUM(ioi.qty)' => ' ',
 
1005   my %renamed_columns = (
 
1006     'factor'       => 'price_factor',
 
1007     'SUM(ioi.qty)' => 'soldtotal',
 
1010   map { $table_prefix{$_} = 'ioi.' } qw(description serialnumber qty unit) if $joins_needed{invoice_oi};
 
1011   map { $renamed_columns{$_} = ' AS ' . $renamed_columns{$_} } keys %renamed_columns;
 
1013   my $select_clause = join ', ',    map { ($table_prefix{$_} || "p.") . $_ . $renamed_columns{$_} } @select_tokens;
 
1014   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
 
1015   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
 
1016   my $group_clause  = ' GROUP BY ' . join ', ',    map { ($table_prefix{$_} || "p.") . $_ } @group_tokens if scalar @group_tokens;
 
1018   my $query = qq|SELECT DISTINCT $select_clause FROM parts p $join_clause WHERE $where_clause $group_clause $order_clause $limit_clause|;
 
1020   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
 
1022 ##  my $where = qq|1 = 1|;
 
1023 ##  my (@values, $var, $flds, $group, $limit);
 
1025 ##  foreach my $item (qw(partnumber drawing microfiche ean pg.partsgroup)) {
 
1026 ##    my $column = $item;
 
1027 ##    $column =~ s/.*\.//; # get rid of table prefixes
 
1028 ##    if ($form->{$column}) {
 
1029 ##      $where .= qq| AND ($item ILIKE ?)|;
 
1030 ##      push(@values, "%$form->{$column}%");
 
1034 ##  # special case for description
 
1035 ##  if ($form->{description}
 
1036 ##      && !(   $form->{bought}  || $form->{sold} || $form->{onorder}
 
1037 ##           || $form->{ordered} || $form->{rfq} || $form->{quoted})) {
 
1038 ##    $where .= qq| AND (p.description ILIKE ?)|;
 
1039 ##    push(@values, "%$form->{description}%");
 
1042 ##  # special case for serialnumber
 
1043 ##  if ($form->{l_serialnumber} && $form->{serialnumber}) {
 
1044 ##    $where .= qq| AND (serialnumber ILIKE ?)|;
 
1045 ##    push(@values, "%$form->{serialnumber}%");
 
1048 ##  if ($form->{searchitems} eq 'part') {
 
1049 ##    $where .= qq| AND (p.inventory_accno_id > 0) |;
 
1052 ##  if ($form->{searchitems} eq 'assembly') {
 
1053 ##    $form->{bought} = "";
 
1054 ##    $where .= qq| AND p.assembly|;
 
1057 ##  if ($form->{searchitems} eq 'service') {
 
1058 ##    $where .= qq| AND (p.inventory_accno_id IS NULL) AND NOT (p.assembly = '1')|;
 
1059 ##    # irrelevant for services
 
1060 ##    map { $form->{$_} = '' } qw(make model);
 
1063 ##  # items which were never bought, sold or on an order
 
1064 ##  if ($form->{itemstatus} eq 'orphaned') {
 
1065 ##    map { $form->{$_} = 0  } qw(onhand short bought sold onorder ordered rfq quoted);
 
1066 ##    map { $form->{$_} = '' } qw(transdatefrom transdateto);
 
1069 ##      qq| AND (p.onhand = 0)
 
1072 ##              SELECT DISTINCT parts_id FROM invoice
 
1074 ##              SELECT DISTINCT parts_id FROM assembly
 
1076 ##              SELECT DISTINCT parts_id FROM orderitems
 
1080 ##  my %status2condition = (
 
1081 ##    active   => " AND (p.obsolete = '0')",
 
1082 ##    obsolete => " AND (p.obsolete = '1')",
 
1083 ##    onhand   => " AND (p.onhand > 0)",
 
1084 ##    short    => " AND (p.onhand < p.rop)",
 
1086 ##  $where .= $status2condition{$form->{itemstatus}};
 
1088 ##  $form->{onhand} = $form->{short} = 0 if ($form->{itemstatus} eq 'obsolete');
 
1091 ##  foreach my $column (qw(make model)) {
 
1092 ##    push @subcolumns, $column if $form->{$column};
 
1094 ##  if (@subcolumns) {
 
1095 ##    $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE | . (join " AND ", map { "($_ ILIKE ?)"; } @subcolumns) . ")";
 
1096 ##    push @values, map { '%' . $form->{$_} . '%' } @subcolumns;
 
1099 ##  if ($form->{l_soldtotal}) {
 
1100 ##    $where .= qq| AND (p.id = i.parts_id) AND (i.qty >= 0)|;
 
1101 ##    $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|;
 
1104 ##  $limit = qq| LIMIT 100| if ($form->{top100});
 
1106 ##  # connect to database
 
1107 ##  my $dbh = $form->dbconnect($myconfig);
 
1109 ##  my @sort_cols = qw(id partnumber description partsgroup bin priceupdate onhand
 
1110 ##                     invnumber ordnumber quonumber name drawing microfiche
 
1111 ##                     serialnumber soldtotal deliverydate);
 
1113 ##  my $sortorder = "partnumber";
 
1114 ##  $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } @sort_cols));
 
1115 ##  $sortorder .= " DESC" if ($form->{revers});
 
1119 ##  if ($form->{l_soldtotal}) {
 
1120 ##    $form->{soldtotal} = 'soldtotal';
 
1122 ##      qq|SELECT p.id, p.partnumber, p.description, p.onhand, p.unit,
 
1123 ##           p.bin, p.sellprice, p.listprice, p.lastcost,
 
1124 ##           p.priceupdate, pg.partsgroup,sum(i.qty) AS soldtotal
 
1126 ##         LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id), invoice i
 
1129 ##         ORDER BY $sortorder $limit|;
 
1132 ##      qq|SELECT p.id, p.partnumber, p.description, p.onhand, p.unit,
 
1133 ##           p.bin, p.sellprice, p.listprice, p.lastcost, p.rop, p.weight,
 
1134 ##           p.priceupdate, p.image, p.drawing, p.microfiche,
 
1137 ##         LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1140 ##         ORDER BY $sortorder $limit|;
 
1143 ##  my @all_values = @values;
 
1145 ##  # rebuild query for bought and sold items
 
1146 ##  if (   $form->{bought}
 
1148 ##      || $form->{onorder}
 
1149 ##      || $form->{ordered}
 
1151 ##      || $form->{quoted}) {
 
1154 ##    @all_values = ();
 
1156 ##    if ($form->{bought} || $form->{sold}) {
 
1158 ##      my @invvalues = @values;
 
1159 ##      my $invwhere = "$where";
 
1160 #      $invwhere .= qq| AND i.assemblyitem = '0'|;
 
1162 ##      if ($form->{transdatefrom}) {
 
1163 ##        $invwhere .= qq| AND a.transdate >= ?|;
 
1164 ##        push(@invvalues, $form->{transdatefrom});
 
1167 ##      if ($form->{transdateto}) {
 
1168 ##        $invwhere .= qq| AND a.transdate <= ?|;
 
1169 ##        push(@invvalues, $form->{transdateto});
 
1172 ##      if ($form->{description}) {
 
1173 ##        $invwhere .= qq| AND i.description ILIKE ?|;
 
1174 ##        push(@invvalues, '%' . $form->{description} . '%');
 
1178 ##        qq|p.id, p.partnumber, i.description, i.serialnumber,
 
1179 #           i.qty AS onhand, i.unit, p.bin, i.sellprice,
 
1180 ##           p.listprice, p.lastcost, p.rop, p.weight,
 
1181 ##           p.priceupdate, p.image, p.drawing, p.microfiche,
 
1183 ##           a.invnumber, a.ordnumber, a.quonumber, i.trans_id,
 
1184 ##           ct.name, i.deliverydate|;
 
1186 ##      if ($form->{bought}) {
 
1188 ##          qq|SELECT $flds, 'ir' AS module, '' AS type, 1 AS exchangerate
 
1190 ##             JOIN parts p ON (p.id = i.parts_id)
 
1191 ##             JOIN ap a ON (a.id = i.trans_id)
 
1192 ##             JOIN vendor ct ON (a.vendor_id = ct.id)
 
1193 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1194 ##             WHERE $invwhere|;
 
1196 ##        $union = qq| UNION |;
 
1198 ##        push(@all_values, @invvalues);
 
1201 ##      if ($form->{sold}) {
 
1205 ##             SELECT $flds, 'is' AS module, '' AS type, 1 As exchangerate
 
1207 ##             JOIN parts p ON (p.id = i.parts_id)
 
1208 ##             JOIN ar a ON (a.id = i.trans_id)
 
1209 ##             JOIN customer ct ON (a.customer_id = ct.id)
 
1210 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1211 ##             WHERE $invwhere|;
 
1212 ##        $union = qq| UNION |;
 
1214 ##        push(@all_values, @invvalues);
 
1218 ##    if ($form->{onorder} || $form->{ordered}) {
 
1219 ##      my @ordvalues = @values;
 
1220 ##      my $ordwhere = $where . qq| AND o.quotation = '0'|;
 
1222 ##      if ($form->{transdatefrom}) {
 
1223 ##        $ordwhere .= qq| AND o.transdate >= ?|;
 
1224 ##        push(@ordvalues, $form->{transdatefrom});
 
1227 ##      if ($form->{transdateto}) {
 
1228 ##        $ordwhere .= qq| AND o.transdate <= ?|;
 
1229 ##        push(@ordvalues, $form->{transdateto});
 
1232 ##      if ($form->{description}) {
 
1233 ##        $ordwhere .= qq| AND oi.description ILIKE ?|;
 
1234 ##        push(@ordvalues, '%' . $form->{description} . '%');
 
1237 ##      if ($form->{ordered}) {
 
1241 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
 
1242 ##               oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
 
1243 ##               p.listprice, p.lastcost, p.rop, p.weight,
 
1244 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
 
1246 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
 
1247 ##               ct.name, NULL AS deliverydate,
 
1248 ##               'oe' AS module, 'sales_order' AS type,
 
1249 ##               (SELECT buy FROM exchangerate ex
 
1250 ##                WHERE ex.curr = o.curr AND ex.transdate = o.transdate) AS exchangerate
 
1251 ##             FROM orderitems oi
 
1252 ##             JOIN parts p ON (oi.parts_id = p.id)
 
1253 ##             JOIN oe o ON (oi.trans_id = o.id)
 
1254 ##             JOIN customer ct ON (o.customer_id = ct.id)
 
1255 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1256 ##             WHERE $ordwhere AND (o.customer_id > 0)|;
 
1257 ##        $union = qq| UNION |;
 
1259 ##        push(@all_values, @ordvalues);
 
1262 ##      if ($form->{onorder}) {
 
1266 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
 
1267 ##               oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
 
1268 ##               p.listprice, p.lastcost, p.rop, p.weight,
 
1269 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
 
1271 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
 
1272 ##               ct.name, NULL AS deliverydate,
 
1273 ##               'oe' AS module, 'purchase_order' AS type,
 
1274 ##               (SELECT sell FROM exchangerate ex
 
1275 ##               WHERE ex.curr = o.curr AND (ex.transdate = o.transdate)) AS exchangerate
 
1276 ##             FROM orderitems oi
 
1277 ##             JOIN parts p ON (oi.parts_id = p.id)
 
1278 ##             JOIN oe o ON (oi.trans_id = o.id)
 
1279 ##             JOIN vendor ct ON (o.vendor_id = ct.id)
 
1280 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1281 ##             WHERE $ordwhere AND (o.vendor_id > 0)|;
 
1282 ##        $union = qq| UNION |;
 
1284 ##        push(@all_values, @ordvalues);
 
1289 ##    if ($form->{rfq} || $form->{quoted}) {
 
1290 ##      my $quowhere = $where . qq| AND o.quotation = '1'|;
 
1291 ##      my @quovalues = @values;
 
1293 ##      if ($form->{transdatefrom}) {
 
1294 ##        $quowhere .= qq| AND o.transdate >= ?|;
 
1295 ##        push(@quovalues, $form->{transdatefrom});
 
1298 ##      if ($form->{transdateto}) {
 
1299 ##        $quowhere .= qq| AND o.transdate <= ?|;
 
1300 ##        push(@quovalues, $form->{transdateto});
 
1303 ##      if ($form->{description}) {
 
1304 ##        $quowhere .= qq| AND oi.description ILIKE ?|;
 
1305 ##        push(@quovalues, '%' . $form->{description} . '%');
 
1308 ##      if ($form->{quoted}) {
 
1313 ##               p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
 
1314 ##               oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
 
1315 ##               p.listprice, p.lastcost, p.rop, p.weight,
 
1316 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
 
1318 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
 
1319 ##               ct.name, NULL AS deliverydate, 'oe' AS module, 'sales_quotation' AS type,
 
1320 ##               (SELECT buy FROM exchangerate ex
 
1321 ##                WHERE (ex.curr = o.curr) AND (ex.transdate = o.transdate)) AS exchangerate
 
1322 ##             FROM orderitems oi
 
1323 ##             JOIN parts p ON (oi.parts_id = p.id)
 
1324 ##             JOIN oe o ON (oi.trans_id = o.id)
 
1325 ##             JOIN customer ct ON (o.customer_id = ct.id)
 
1326 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1328 ##             AND o.customer_id > 0|;
 
1329 ##        $union = qq| UNION |;
 
1331 ##        push(@all_values, @quovalues);
 
1334 ##      if ($form->{rfq}) {
 
1338 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
 
1339 ##               oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
 
1340 ##               p.listprice, p.lastcost, p.rop, p.weight,
 
1341 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
 
1343 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
 
1344 ##               ct.name, NULL AS deliverydate,
 
1345 ##               'oe' AS module, 'request_quotation' AS type,
 
1346 ##               (SELECT sell FROM exchangerate ex
 
1347 ##               WHERE (ex.curr = o.curr) AND (ex.transdate = o.transdate)) AS exchangerate
 
1348 ##             FROM orderitems oi
 
1349 ##             JOIN parts p ON (oi.parts_id = p.id)
 
1350 ##             JOIN oe o ON (oi.trans_id = o.id)
 
1351 ##             JOIN vendor ct ON (o.vendor_id = ct.id)
 
1352 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1354 ##             AND o.vendor_id > 0|;
 
1356 ##        push(@all_values, @quovalues);
 
1360 ##    $query .= qq| ORDER BY  | . $sortorder;
 
1364 ##  $form->{parts} = selectall_hashref_query($form, $dbh, $query, @all_values);
 
1367   # include individual items for assemblies
 
1368   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
 
1370       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
 
1372            p.sellprice, p.listprice, p.lastcost,
 
1373            p.rop, p.weight, p.priceupdate,
 
1374            p.image, p.drawing, p.microfiche
 
1375          FROM parts p, assembly a
 
1376          WHERE (p.id = a.parts_id) AND (a.id = ?)|;
 
1377     $sth = prepare_query($form, $dbh, $query);
 
1379     foreach $item (@{ $form->{parts} }) {
 
1380       push(@assemblies, $item);
 
1381       do_statement($form, $sth, $query, conv_i($item->{id}));
 
1383       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1384         $ref->{assemblyitem} = 1;
 
1385         push(@assemblies, $ref);
 
1390     # copy assemblies to $form->{parts}
 
1391     $form->{parts} = \@assemblies;
 
1395   $main::lxdebug->leave_sub();
 
1399   $main::lxdebug->enter_sub();
 
1401   my ($self, $myconfig, $form) = @_;
 
1403   my $where = '1 = 1';
 
1409   if ($item ne 'make') {
 
1410     foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
 
1412       $column =~ s/.*\.//;
 
1413       next unless ($form->{$column});
 
1414       $where .= qq| AND $item ILIKE ?|;
 
1415       push(@where_values, '%' . $form->{$column} . '%');
 
1419   # special case for description
 
1420   if ($form->{description}
 
1421       && !(   $form->{bought}  || $form->{sold} || $form->{onorder}
 
1422            || $form->{ordered} || $form->{rfq} || $form->{quoted})) {
 
1423     $where .= qq| AND (p.description ILIKE ?)|;
 
1424     push(@where_values, '%' . $form->{description} . '%');
 
1427   # special case for serialnumber
 
1428   if ($form->{l_serialnumber} && $form->{serialnumber}) {
 
1429     $where .= qq| AND serialnumber ILIKE ?|;
 
1430     push(@where_values, '%' . $form->{serialnumber} . '%');
 
1434   # items which were never bought, sold or on an order
 
1435   if ($form->{itemstatus} eq 'orphaned') {
 
1436     $form->{onhand}  = $form->{short}   = 0;
 
1437     $form->{bought}  = $form->{sold}    = 0;
 
1438     $form->{onorder} = $form->{ordered} = 0;
 
1439     $form->{rfq}     = $form->{quoted}  = 0;
 
1441     $form->{transdatefrom} = $form->{transdateto} = "";
 
1444       qq| AND (p.onhand = 0)
 
1447               SELECT DISTINCT parts_id FROM invoice
 
1449               SELECT DISTINCT parts_id FROM assembly
 
1451               SELECT DISTINCT parts_id FROM orderitems
 
1455   if ($form->{itemstatus} eq 'active') {
 
1456     $where .= qq| AND p.obsolete = '0'|;
 
1459   if ($form->{itemstatus} eq 'obsolete') {
 
1460     $where .= qq| AND p.obsolete = '1'|;
 
1461     $form->{onhand} = $form->{short} = 0;
 
1464   if ($form->{itemstatus} eq 'onhand') {
 
1465     $where .= qq| AND p.onhand > 0|;
 
1468   if ($form->{itemstatus} eq 'short') {
 
1469     $where .= qq| AND p.onhand < p.rop|;
 
1472   foreach my $column (qw(make model)) {
 
1473     next unless ($form->{$colum});
 
1474     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
 
1475     push(@where_values, '%' . $form->{$column} . '%');
 
1478   # connect to database
 
1479   my $dbh = $form->dbconnect_noauto($myconfig);
 
1481   for my $column (qw(sellprice listprice)) {
 
1482     next if ($form->{$column} eq "");
 
1484     my $value = $form->parse_amount($myconfig, $form->{$column});
 
1487     if ($form->{"${column}_type"} eq "percent") {
 
1488       $value = ($value / 100) + 1;
 
1493       qq|UPDATE parts SET $column = $column $operator ?
 
1497             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1499     do_query($from, $dbh, $query, $value, @where_values);
 
1503     qq|UPDATE prices SET price = price + ?
 
1507           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1508           WHERE $where) AND (pricegroup_id = ?)|;
 
1509   my $sth_add = prepare_query($form, $dbh, $q_add);
 
1512     qq|UPDATE prices SET price = price * ?
 
1516           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1517           WHERE $where) AND (pricegroup_id = ?)|;
 
1518   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
 
1520   for my $i (1 .. $form->{price_rows}) {
 
1521     next if ($form->{"price_$i"} eq "");
 
1523     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
 
1525     if ($form->{"pricegroup_type_$i"} eq "percent") {
 
1526       do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1528       do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1533   $sth_multiply->finish();
 
1535   my $rc= $dbh->commit;
 
1538   $main::lxdebug->leave_sub();
 
1544   $main::lxdebug->enter_sub();
 
1546   my ($self, $module, $myconfig, $form) = @_;
 
1548   # connect to database
 
1549   my $dbh = $form->dbconnect($myconfig);
 
1551   my @values = ('%' . $module . '%');
 
1555       qq|SELECT c.accno, c.description, c.link, c.id,
 
1556            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
 
1557          FROM chart c, parts p
 
1558          WHERE (c.link LIKE ?) AND (p.id = ?)
 
1560     push(@values, conv_i($form->{id}));
 
1564       qq|SELECT c.accno, c.description, c.link, c.id,
 
1565            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
 
1566          FROM chart c, defaults d
 
1571   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1572   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1573     foreach my $key (split(/:/, $ref->{link})) {
 
1574       if ($key =~ /\Q$module\E/) {
 
1575         if (   ($ref->{id} eq $ref->{inventory_accno_id})
 
1576             || ($ref->{id} eq $ref->{income_accno_id})
 
1577             || ($ref->{id} eq $ref->{expense_accno_id})) {
 
1578           push @{ $form->{"${module}_links"}{$key} },
 
1579             { accno       => $ref->{accno},
 
1580               description => $ref->{description},
 
1581               selected    => "selected" };
 
1582           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
 
1584           push @{ $form->{"${module}_links"}{$key} },
 
1585             { accno       => $ref->{accno},
 
1586               description => $ref->{description},
 
1594   # get buchungsgruppen
 
1595   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
 
1598   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
 
1601     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
 
1605   $main::lxdebug->leave_sub();
 
1608 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
 
1610   $main::lxdebug->enter_sub();
 
1612   my ($self, $myconfig, $form, $sortorder) = @_;
 
1613   my $dbh   = $form->dbconnect($myconfig);
 
1614   my $order = qq| p.partnumber|;
 
1615   my $where = qq|1 = 1|;
 
1618   if ($sortorder eq "all") {
 
1619     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
 
1620     push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
 
1622   } elsif ($sortorder eq "partnumber") {
 
1623     $where .= qq| AND (partnumber ILIKE ?)|;
 
1624     push(@values, '%' . $form->{partnumber} . '%');
 
1626   } elsif ($sortorder eq "description") {
 
1627     $where .= qq| AND (description ILIKE ?)|;
 
1628     push(@values, '%' . $form->{description} . '%');
 
1629     $order = "description";
 
1634     qq|SELECT id, partnumber, description, unit, sellprice
 
1636        WHERE $where ORDER BY $order|;
 
1638   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1641   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1642     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
 
1647     $form->{"id_$j"}          = $ref->{id};
 
1648     $form->{"partnumber_$j"}  = $ref->{partnumber};
 
1649     $form->{"description_$j"} = $ref->{description};
 
1650     $form->{"unit_$j"}        = $ref->{unit};
 
1651     $form->{"sellprice_$j"}   = $ref->{sellprice};
 
1652     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
 
1658   $main::lxdebug->leave_sub();
 
1663 # gets sum of sold part with part_id
 
1665   $main::lxdebug->enter_sub();
 
1667   my ($dbh, $id) = @_;
 
1669   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
 
1670   my ($sum) = selectrow_query($form, $dbh, $query, conv_i($id));
 
1673   $main::lxdebug->leave_sub();
 
1676 }    #end get_soldtotal
 
1678 sub retrieve_languages {
 
1679   $main::lxdebug->enter_sub();
 
1681   my ($self, $myconfig, $form) = @_;
 
1683   # connect to database
 
1684   my $dbh = $form->dbconnect($myconfig);
 
1689   if ($form->{language_values} ne "") {
 
1691       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
 
1693          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
 
1694          ORDER BY lower(l.description)|;
 
1695     @values = (conv_i($form->{id}));
 
1698     $query = qq|SELECT id, description
 
1700                 ORDER BY lower(description)|;
 
1703   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
 
1707   $main::lxdebug->leave_sub();
 
1712 sub follow_account_chain {
 
1713   $main::lxdebug->enter_sub(2);
 
1715   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
 
1717   my @visited_accno_ids = ($accno_id);
 
1722     qq|SELECT c.new_chart_id, date($transdate) >= c.valid_from AS is_valid, | .
 
1725     qq|LEFT JOIN chart cnew ON c.new_chart_id = cnew.id | .
 
1726     qq|WHERE (c.id = ?) AND NOT c.new_chart_id ISNULL AND (c.new_chart_id > 0)|;
 
1727   $sth = prepare_query($form, $dbh, $query);
 
1730     do_statement($form, $sth, $query, $accno_id);
 
1731     $ref = $sth->fetchrow_hashref();
 
1732     last unless ($ref && $ref->{"is_valid"} &&
 
1733                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
 
1734     $accno_id = $ref->{"new_chart_id"};
 
1735     $accno = $ref->{"accno"};
 
1736     push(@visited_accno_ids, $accno_id);
 
1739   $main::lxdebug->leave_sub(2);
 
1741   return ($accno_id, $accno);
 
1744 sub retrieve_accounts {
 
1745   $main::lxdebug->enter_sub(2);
 
1747   my ($self, $myconfig, $form, $parts_id, $index) = @_;
 
1749   my ($query, $sth, $dbh);
 
1751   $form->{"taxzone_id"} *= 1;
 
1753   $dbh = $form->get_standard_dbh($myconfig);
 
1756   if ($form->{type} eq "invoice") {
 
1757     if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
 
1758       $transdate = $form->{invdate};
 
1760       $transdate = $form->{deliverydate};
 
1762   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
 
1763     $transdate = $form->{invdate};
 
1765     $transdate = $form->{transdate};
 
1768   if ($transdate eq "") {
 
1769     $transdate = "current_date";
 
1771     $transdate = $dbh->quote($transdate);
 
1776     qq|  p.inventory_accno_id AS is_part, | .
 
1777     qq|  bg.inventory_accno_id, | .
 
1778     qq|  bg.income_accno_id_$form->{taxzone_id} AS income_accno_id, | .
 
1779     qq|  bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id, | .
 
1780     qq|  c1.accno AS inventory_accno, | .
 
1781     qq|  c2.accno AS income_accno, | .
 
1782     qq|  c3.accno AS expense_accno | .
 
1784     qq|LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id | .
 
1785     qq|LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id | .
 
1786     qq|LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id | .
 
1787     qq|LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id | .
 
1789   my $ref = selectfirst_hashref_query($form, $dbh, $query, $parts_id);
 
1791   return $main::lxdebug->leave_sub(2) if (!$ref);
 
1793   $ref->{"inventory_accno_id"} = undef unless ($ref->{"is_part"});
 
1796   foreach my $type (qw(inventory income expense)) {
 
1797     next unless ($ref->{"${type}_accno_id"});
 
1798     ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
 
1799       $self->follow_account_chain($form, $dbh, $transdate,
 
1800                                   $ref->{"${type}_accno_id"},
 
1801                                   $ref->{"${type}_accno"});
 
1804   map({ $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} }
 
1805       qw(inventory income expense));
 
1807   my $inc_exp = $form->{"vc"} eq "customer" ? "income" : "expense";
 
1808   my $accno_id = $accounts{"${inc_exp}_accno_id"};
 
1811     qq|SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber | .
 
1813     qq|LEFT JOIN chart c ON c.id = t.chart_id | .
 
1814     qq|WHERE t.id IN | .
 
1815     qq|  (SELECT tk.tax_id | .
 
1816     qq|   FROM taxkeys tk | .
 
1817     qq|   WHERE tk.chart_id = ? AND startdate <= | . quote_db_date($transdate) .
 
1818     qq|   ORDER BY startdate DESC LIMIT 1) |;
 
1819   $ref = selectfirst_hashref_query($form, $dbh, $query, $accno_id);
 
1822     $main::lxdebug->leave_sub(2);
 
1826   $form->{"taxaccounts_$index"} = $ref->{"accno"};
 
1827   if ($form->{"taxaccounts"} !~ /$ref->{accno}/) {
 
1828     $form->{"taxaccounts"} .= "$ref->{accno} ";
 
1830   map({ $form->{"$ref->{accno}_${_}"} = $ref->{$_}; }
 
1831       qw(rate description taxnumber));
 
1833 #   $main::lxdebug->message(0, "formvars: rate " . $form->{"$ref->{accno}_rate"} .
 
1834 #                           " description " . $form->{"$ref->{accno}_description"} .
 
1835 #                           " taxnumber " . $form->{"$ref->{accno}_taxnumber"} .
 
1836 #                           " || taxaccounts_$index " . $form->{"taxaccounts_$index"} .
 
1837 #                           " || taxaccounts " . $form->{"taxaccounts"});
 
1839   $main::lxdebug->leave_sub(2);