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       if ($form->{onhand} != 0) {
 
 329         &adjust_inventory($dbh, $form, $form->{id}, $form->{onhand} * -1);
 
 332       # delete assembly records
 
 333       do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
 
 335       $form->{onhand} += $form->{stock};
 
 339     do_query($form, $dbh, qq|DELETE FROM partstax WHERE parts_id = ?|, conv_i($form->{id}));
 
 341     # delete translations
 
 342     do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
 
 345     my ($count) = selectrow_query($form, $dbh, qq|SELECT COUNT(*) FROM parts WHERE partnumber = ?|, $form->{partnumber});
 
 347       $main::lxdebug->leave_sub();
 
 351     ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
 
 352     do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber) VALUES (?, '')|, $form->{id});
 
 354     $form->{orphaned} = 1;
 
 355     $form->{onhand} = $form->{stock} if $form->{item} eq 'assembly';
 
 356     if ($form->{partnumber} eq "" && $form->{"item"} eq "service") {
 
 357       $form->{partnumber} = $form->update_defaults($myconfig, "servicenumber");
 
 359     if ($form->{partnumber} eq "" && $form->{"item"} ne "service") {
 
 360       $form->{partnumber} = $form->update_defaults($myconfig, "articlenumber");
 
 364   my $partsgroup_id = 0;
 
 366   if ($form->{partsgroup}) {
 
 367     ($partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
 
 370   my ($subq_inventory, $subq_expense, $subq_income);
 
 371   if ($form->{"item"} eq "part") {
 
 373       qq|(SELECT bg.inventory_accno_id
 
 374           FROM buchungsgruppen bg
 
 375           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 377     $subq_inventory = "NULL";
 
 380   if ($form->{"item"} ne "assembly") {
 
 382       qq|(SELECT bg.expense_accno_id_0
 
 383           FROM buchungsgruppen bg
 
 384           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 386     $subq_expense = "NULL";
 
 406          buchungsgruppen_id = ?,
 
 408          inventory_accno_id = $subq_inventory,
 
 409          income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
 
 410          expense_accno_id = $subq_expense,
 
 418          not_discountable = ?,
 
 423   @values = ($form->{partnumber},
 
 424              $form->{description},
 
 425              $makemodel ? 't' : 'f',
 
 426              $form->{assembly} ? 't' : 'f',
 
 431              conv_date($form->{priceupdate}),
 
 437              conv_i($form->{buchungsgruppen_id}),
 
 438              conv_i($form->{payment_id}),
 
 439              conv_i($form->{buchungsgruppen_id}),
 
 440              $form->{obsolete} ? 't' : 'f',
 
 443              $form->{shop} ? 't' : 'f',
 
 447              $form->{not_discountable} ? 't' : 'f',
 
 449              conv_i($partsgroup_id),
 
 450              conv_i($form->{price_factor_id}),
 
 453   do_query($form, $dbh, $query, @values);
 
 455   # delete translation records
 
 456   do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
 
 458   if ($form->{language_values} ne "") {
 
 459     foreach $item (split(/---\+\+\+---/, $form->{language_values})) {
 
 460       my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
 
 461       if ($translation ne "") {
 
 462         $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
 
 463                     VALUES ( ?, ?, ?, ? )|;
 
 464         @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
 
 465         do_query($form, $dbh, $query, @values);
 
 470   # delete price records
 
 471   do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
 
 473   # insert price records only if different to sellprice
 
 474   for my $i (1 .. $form->{price_rows}) {
 
 475     if ($form->{"price_$i"} eq "0") {
 
 476       $form->{"price_$i"} = $form->{sellprice};
 
 479         (   $form->{"price_$i"}
 
 480          || $form->{"klass_$i"}
 
 481          || $form->{"pricegroup_id_$i"})
 
 482         and $form->{"price_$i"} != $form->{sellprice}
 
 484       #$klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
 
 485       $price = $form->parse_amount($myconfig, $form->{"price_$i"});
 
 487         $form->parse_amount($myconfig, $form->{"pricegroup_id_$i"});
 
 488       $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) | .
 
 490       @values = (conv_i($form->{id}), conv_i($pricegroup_id), $price);
 
 491       do_query($form, $dbh, $query, @values);
 
 495   # insert makemodel records
 
 496   unless ($form->{item} eq 'service') {
 
 497     for my $i (1 .. $form->{makemodel_rows}) {
 
 498       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
 
 499         map { $form->{"${_}_$i"} =~ s/\'/\'\'/g } qw(make model);
 
 501         $query = qq|INSERT INTO makemodel (parts_id, make, model) | .
 
 502                              qq|VALUES (?, ?, ?)|;
 
 503                     @values = (conv_i($form->{id}), $form->{"make_$i"}, $form->{"model_$i"});
 
 504         do_query($form, $dbh, $query, @values);
 
 510   foreach $item (split(/ /, $form->{taxaccounts})) {
 
 511     if ($form->{"IC_tax_$item"}) {
 
 513         qq|INSERT INTO partstax (parts_id, chart_id)
 
 514            VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
 
 515                         @values = (conv_i($form->{id}), $item);
 
 516       do_query($form, $dbh, $query, @values);
 
 520   # add assembly records
 
 521   if ($form->{item} eq 'assembly') {
 
 523     for my $i (1 .. $form->{assembly_rows}) {
 
 524       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 526       if ($form->{"qty_$i"} != 0) {
 
 527         $form->{"bom_$i"} *= 1;
 
 528         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
 
 529                              qq|VALUES (?, ?, ?, ?)|;
 
 530                     @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
 
 531         do_query($form, $dbh, $query, @values);
 
 535     # adjust onhand for the parts
 
 536     if ($form->{onhand} != 0) {
 
 537       &adjust_inventory($dbh, $form, $form->{id}, $form->{onhand});
 
 543     my $shippingdate = "$a[5]-$a[4]-$a[3]";
 
 545     $form->get_employee($dbh);
 
 547     # add inventory record
 
 549       qq|INSERT INTO inventory (warehouse_id, parts_id, qty, shippingdate, employee_id)
 
 550          VALUES (0, ?, ?, '$shippingdate', ?)|;
 
 551     @values = (conv_i($form->{id}), $form->{stock}, conv_i($form->{employee_id}));
 
 552     do_query($form, $dbh, $query, @values);
 
 556   #set expense_accno=inventory_accno if they are different => bilanz
 
 558     ($form->{expense_accno} != $form->{inventory_accno})
 
 559     ? $form->{inventory_accno}
 
 560     : $form->{expense_accno};
 
 562   # get tax rates and description
 
 564     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
 
 566     qq|SELECT c.accno, c.description, t.rate, t.taxnumber
 
 568        WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
 
 570   $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
 
 572   $form->{taxaccount} = "";
 
 573   while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
 574     $form->{taxaccount} .= "$ptr->{accno} ";
 
 575     if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
 
 576       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
 577       $form->{"$ptr->{accno}_description"} = $ptr->{description};
 
 578       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
 579       $form->{taxaccount2} .= " $ptr->{accno} ";
 
 584   my $rc = $dbh->commit;
 
 587   $main::lxdebug->leave_sub();
 
 592 sub update_assembly {
 
 593   $main::lxdebug->enter_sub();
 
 595   my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
 
 597   my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
 
 598   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
 
 600   while (my ($pid, $aqty) = $sth->fetchrow_array) {
 
 601     &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
 
 606     qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
 
 608   @values = ($qty * ($form->{sellprice} - $sellprice),
 
 609              $qty * ($form->{weight} - $weight), conv_i($id));
 
 610   do_query($form, $dbh, $query, @values);
 
 612   $main::lxdebug->leave_sub();
 
 615 sub retrieve_assemblies {
 
 616   $main::lxdebug->enter_sub();
 
 618   my ($self, $myconfig, $form) = @_;
 
 620   # connect to database
 
 621   my $dbh = $form->dbconnect($myconfig);
 
 623   my $where = qq|NOT p.obsolete|;
 
 626   if ($form->{partnumber}) {
 
 627     $where .= qq| AND (p.partnumber ILIKE ?)|;
 
 628     push(@values, '%' . $form->{partnumber} . '%');
 
 631   if ($form->{description}) {
 
 632     $where .= qq| AND (p.description ILIKE ?)|;
 
 633     push(@values, '%' . $form->{description} . '%');
 
 636   # retrieve assembly items
 
 638     qq|SELECT p.id, p.partnumber, p.description,
 
 639          p.bin, p.onhand, p.rop,
 
 640          (SELECT sum(p2.inventory_accno_id)
 
 641           FROM parts p2, assembly a
 
 642           WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
 
 644        WHERE NOT p.obsolete AND p.assembly $where|;
 
 646   $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
 
 650   $main::lxdebug->leave_sub();
 
 653 sub restock_assemblies {
 
 654   $main::lxdebug->enter_sub();
 
 656   my ($self, $myconfig, $form) = @_;
 
 658   # connect to database
 
 659   my $dbh = $form->dbconnect_noauto($myconfig);
 
 661   for my $i (1 .. $form->{rowcount}) {
 
 663     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 665     if ($form->{"qty_$i"} != 0) {
 
 666       &adjust_inventory($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"});
 
 671   my $rc = $dbh->commit;
 
 674   $main::lxdebug->leave_sub();
 
 679 sub adjust_inventory {
 
 680   $main::lxdebug->enter_sub();
 
 682   my ($dbh, $form, $id, $qty) = @_;
 
 685     qq|SELECT p.id, p.inventory_accno_id, p.assembly, a.qty
 
 686        FROM parts p, assembly a
 
 687        WHERE (a.parts_id = p.id) AND (a.id = ?)|;
 
 688   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
 
 690   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
 692     my $allocate = $qty * $ref->{qty};
 
 694     # is it a service item, then loop
 
 695     $ref->{inventory_accno_id} *= 1;
 
 696     next if (($ref->{inventory_accno_id} == 0) && !$ref->{assembly});
 
 698     # adjust parts onhand
 
 699     $form->update_balance($dbh, "parts", "onhand",
 
 707   my $rc = $form->update_balance($dbh, "parts", "onhand", qq|id = ?|, $qty, $id);
 
 709   $main::lxdebug->leave_sub();
 
 715   $main::lxdebug->enter_sub();
 
 717   my ($self, $myconfig, $form) = @_;
 
 718   my @values = (conv_i($form->{id}));
 
 719   # connect to database, turn off AutoCommit
 
 720   my $dbh = $form->dbconnect_noauto($myconfig);
 
 722   my %columns = ( "assembly" => "id", "parts" => "id" );
 
 724   for my $table (qw(prices partstax makemodel inventory assembly license translation parts)) {
 
 725     my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
 
 726     do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
 
 730   my $rc = $dbh->commit;
 
 733   $main::lxdebug->leave_sub();
 
 739   $main::lxdebug->enter_sub();
 
 741   my ($self, $myconfig, $form) = @_;
 
 743   my $i = $form->{assembly_rows};
 
 745   my $where = qq|1 = 1|;
 
 748   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
 
 750   while (my ($column, $table) = each(%columns)) {
 
 751     next unless ($form->{"${column}_$i"});
 
 752     $where .= qq| AND ${table}.${column} ILIKE ?|;
 
 753     push(@values, '%' . $form->{"${column}_$i"} . '%');
 
 757     $where .= qq| AND NOT (p.id = ?)|;
 
 758     push(@values, conv_i($form->{id}));
 
 762     $where .= qq| ORDER BY p.partnumber|;
 
 764     $where .= qq| ORDER BY p.description|;
 
 767   # connect to database
 
 768   my $dbh = $form->dbconnect($myconfig);
 
 771     qq|SELECT p.id, p.partnumber, p.description, p.sellprice, p.weight, p.onhand, p.unit, pg.partsgroup
 
 773        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 775   $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
 
 779   $main::lxdebug->leave_sub();
 
 784 # Warning, deep magic ahead.
 
 785 # This function gets all parts from the database according to the filters specified
 
 788 #   sort revers  - sorting field + direction
 
 791 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
 
 792 #   partnumber ean description partsgroup microfiche drawing
 
 795 #   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
 
 798 #   itemstatus  = active | onhand | short | obsolete | orphaned
 
 799 #   searchitems = part | assembly | service
 
 802 #   make model                               - makemodel
 
 803 #   serialnumber transdatefrom transdateto   - invoice/orderitems
 
 806 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
 
 807 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
 
 808 #   l_soldtotal                              - aggreg join to display total of sold quantity
 
 809 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 810 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
 
 811 #   l_serialnumber                           - belonges to serialnumber filter
 
 812 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
 
 815 #   l_soldtotal                              - aggreg join to display total of sold quantity
 
 816 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 817 #   masking of onhand in bsooqr mode         - ToDO: fixme
 
 819 # disabled sanity checks and changes:
 
 820 #  - searchitems = assembly will no longer disable bought
 
 821 #  - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
 
 822 #  - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
 
 823 #  - itemstatus = obsolete will no longer disable onhand, short
 
 824 #  - allow sorting by ean
 
 825 #  - serialnumber filter also works if l_serialnumber isn't ticked
 
 826 #  - onhand doesn't get masked by it's oi or invoice counterparts atm. ToDO: fix this
 
 827 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
 
 830   $main::lxdebug->enter_sub();
 
 832   my ($self, $myconfig, $form) = @_;
 
 833   my $dbh = $form->get_standard_dbh($myconfig);
 
 835   $form->{parts} = +{ };
 
 837   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
 
 838   my @makemodel_filters    = qw(make model);
 
 839   my @invoice_oi_filters   = qw(serialnumber soldtotal);
 
 840   my @apoe_filters         = qw(transdate);
 
 841   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
 
 842   my @simple_l_switches    = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
 
 843   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
 
 844   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module);
 
 845   my @deliverydate_flags   = qw(deliverydate);
 
 846 #  my @other_flags          = qw(onhand); # ToDO: implement these
 
 847 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
 
 850     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
 
 851     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
 
 852     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
 
 855          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem, 'invoice'    AS ioi FROM invoice UNION
 
 856          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, 'orderitems' AS ioi FROM orderitems
 
 857        ) AS ioi ON ioi.parts_id = p.id|,
 
 860          SELECT id, transdate, 'ir' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation, NULL AS customer_id,         vendor_id, NULL AS deliverydate FROM ap UNION
 
 861          SELECT id, transdate, 'is' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation,         customer_id, NULL AS vendor_id,         deliverydate FROM ar UNION
 
 862          SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber,          quotation,         customer_id,         vendor_id, NULL AS deliverydate FROM oe
 
 863        ) AS apoe ON ioi.trans_id = apoe.id|,
 
 866            SELECT id, name, 'customer' AS cv FROM customer UNION
 
 867            SELECT id, name, 'vendor'   AS cv FROM vendor
 
 868          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
 
 870   my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
 
 873   #===== switches and simple filters ========#
 
 875   my @select_tokens = qw(id factor);
 
 876   my @where_tokens  = qw(1=1);
 
 877   my @group_tokens  = ();
 
 879   # special case transdate
 
 880   if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
 
 881     $form->{"l_transdate"} = 1;
 
 882     push @select_tokens, 'transdate';
 
 883     for (qw(transdatefrom transdateto)) {
 
 884       next unless $form->{$_};
 
 885       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
 
 886       push @bind_vars,    $form->{$_};
 
 890   my %simple_filter_table_prefix = (
 
 894   foreach (@simple_filters, @makemodel_filters, @invoice_oi_filters) {
 
 895     next unless $form->{$_};
 
 896     $form->{"l_$_"} = '1'; # show the column
 
 897     push @where_tokens, "$simple_filter_table_prefix{$_}$_ ILIKE ?";
 
 898     push @bind_vars,    "%$form->{$_}%";
 
 901   foreach (@simple_l_switches) {
 
 902     next unless $form->{"l_$_"};
 
 903     push @select_tokens, $_;
 
 906   for ($form->{searchitems}) {
 
 907     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
 
 908     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
 
 909     push @where_tokens, 'NOT p.assembly'               if /service/;
 
 910     push @where_tokens, '    p.assembly'               if /assembly/;
 
 913   for ($form->{itemstatus}) {
 
 914     push @where_tokens, 'p.id NOT IN
 
 915         (SELECT DISTINCT parts_id FROM invoice UNION
 
 916          SELECT DISTINCT parts_id FROM assembly UNION
 
 917          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
 
 918     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
 
 919     push @where_tokens, 'NOT p.obsolete'               if /active/;
 
 920     push @where_tokens, '    p.obsolete',              if /obsolete/;
 
 921     push @where_tokens, 'p.onhand > 0',                if /onhand/;
 
 922     push @where_tokens, 'p.onhand < p.rop',            if /short/;
 
 926   my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
 
 927   $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols;
 
 929   my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
 
 931   # special case: sorting by partnumber
 
 932   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
 
 933   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
 
 934   # ToDO: implement proper functional sorting
 
 935   $form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
 
 936     if $form->{sort} eq 'partnumber';
 
 938   my $order_clause = " ORDER BY $form->{sort} $sort_order";
 
 940   my $limit_clause = " LIMIT 100" if $form->{top100};
 
 942   #=== joins and complicated filters ========#
 
 944   my $bsooqr = $form->{bought}  || $form->{sold}
 
 945             || $form->{ordered} || $form->{onorder}
 
 946             || $form->{quoted}  || $form->{rfq};
 
 949   push @select_tokens, @qsooqr_flags                                          if $bsooqr;
 
 950   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
 
 951   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
 
 952   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
 
 953   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
 
 954   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
 
 955   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
 
 956   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
 
 957   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
 
 959   $joins_needed{partsgroup}  = 1;
 
 960   $joins_needed{pfac}        = 1;
 
 961   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
 
 962   $joins_needed{cv}          = 1 if $bsooqr;
 
 963   $joins_needed{apoe}        = 1 if $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
 
 964   $joins_needed{invoice_oi}  = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
 
 966   # special case for description search.
 
 967   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
 
 968   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
 
 969   # find the old entries in of @where_tokens and @bind_vars, and adjust them
 
 970   if ($joins_needed{invoice_oi}) {
 
 971     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
 
 972       next unless $where_tokens[$wi] =~ /^description ILIKE/;
 
 973       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
 
 974       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
 
 979   # now the master trick: soldtotal.
 
 980   if ($form->{l_soldtotal}) {
 
 981     push @where_tokens, 'ioi.qty >= 0';
 
 982     push @group_tokens, @select_tokens;
 
 983     push @select_tokens, 'SUM(ioi.qty)';
 
 986   #============= build query ================#
 
 990      deliverydate => 'apoe.', serialnumber => 'ioi.',
 
 991      transdate    => 'apoe.', trans_id     => 'ioi.',
 
 992      module       => 'apoe.', name         => 'cv.',
 
 993      ordnumber    => 'apoe.', make         => 'mm.',
 
 994      quonumber    => 'apoe.', model        => 'mm.',
 
 995      invnumber    => 'apoe.', partsgroup   => 'pg.',
 
 997      'SUM(ioi.qty)' => ' ',
 
1000   my %renamed_columns = (
 
1001     'factor'       => 'price_factor',
 
1002     'SUM(ioi.qty)' => 'soldtotal',
 
1005   map { $table_prefix{$_} = 'ioi.' } qw(description serialnumber qty unit) if $joins_needed{invoice_oi};
 
1006   map { $renamed_columns{$_} = ' AS ' . $renamed_columns{$_} } keys %renamed_columns;
 
1008   my $select_clause = join ', ',    map { ($table_prefix{$_} || "p.") . $_ . $renamed_columns{$_} } @select_tokens;
 
1009   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
 
1010   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
 
1011   my $group_clause  = ' GROUP BY ' . join ', ',    map { ($table_prefix{$_} || "p.") . $_ } @group_tokens if scalar @group_tokens;
 
1013   my $query = qq|SELECT DISTINCT $select_clause FROM parts p $join_clause WHERE $where_clause $group_clause $order_clause $limit_clause|;
 
1015   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
 
1017 ##  my $where = qq|1 = 1|;
 
1018 ##  my (@values, $var, $flds, $group, $limit);
 
1020 ##  foreach my $item (qw(partnumber drawing microfiche ean pg.partsgroup)) {
 
1021 ##    my $column = $item;
 
1022 ##    $column =~ s/.*\.//; # get rid of table prefixes
 
1023 ##    if ($form->{$column}) {
 
1024 ##      $where .= qq| AND ($item ILIKE ?)|;
 
1025 ##      push(@values, "%$form->{$column}%");
 
1029 ##  # special case for description
 
1030 ##  if ($form->{description}
 
1031 ##      && !(   $form->{bought}  || $form->{sold} || $form->{onorder}
 
1032 ##           || $form->{ordered} || $form->{rfq} || $form->{quoted})) {
 
1033 ##    $where .= qq| AND (p.description ILIKE ?)|;
 
1034 ##    push(@values, "%$form->{description}%");
 
1037 ##  # special case for serialnumber
 
1038 ##  if ($form->{l_serialnumber} && $form->{serialnumber}) {
 
1039 ##    $where .= qq| AND (serialnumber ILIKE ?)|;
 
1040 ##    push(@values, "%$form->{serialnumber}%");
 
1043 ##  if ($form->{searchitems} eq 'part') {
 
1044 ##    $where .= qq| AND (p.inventory_accno_id > 0) |;
 
1047 ##  if ($form->{searchitems} eq 'assembly') {
 
1048 ##    $form->{bought} = "";
 
1049 ##    $where .= qq| AND p.assembly|;
 
1052 ##  if ($form->{searchitems} eq 'service') {
 
1053 ##    $where .= qq| AND (p.inventory_accno_id IS NULL) AND NOT (p.assembly = '1')|;
 
1054 ##    # irrelevant for services
 
1055 ##    map { $form->{$_} = '' } qw(make model);
 
1058 ##  # items which were never bought, sold or on an order
 
1059 ##  if ($form->{itemstatus} eq 'orphaned') {
 
1060 ##    map { $form->{$_} = 0  } qw(onhand short bought sold onorder ordered rfq quoted);
 
1061 ##    map { $form->{$_} = '' } qw(transdatefrom transdateto);
 
1064 ##      qq| AND (p.onhand = 0)
 
1067 ##              SELECT DISTINCT parts_id FROM invoice
 
1069 ##              SELECT DISTINCT parts_id FROM assembly
 
1071 ##              SELECT DISTINCT parts_id FROM orderitems
 
1075 ##  my %status2condition = (
 
1076 ##    active   => " AND (p.obsolete = '0')",
 
1077 ##    obsolete => " AND (p.obsolete = '1')",
 
1078 ##    onhand   => " AND (p.onhand > 0)",
 
1079 ##    short    => " AND (p.onhand < p.rop)",
 
1081 ##  $where .= $status2condition{$form->{itemstatus}};
 
1083 ##  $form->{onhand} = $form->{short} = 0 if ($form->{itemstatus} eq 'obsolete');
 
1086 ##  foreach my $column (qw(make model)) {
 
1087 ##    push @subcolumns, $column if $form->{$column};
 
1089 ##  if (@subcolumns) {
 
1090 ##    $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE | . (join " AND ", map { "($_ ILIKE ?)"; } @subcolumns) . ")";
 
1091 ##    push @values, map { '%' . $form->{$_} . '%' } @subcolumns;
 
1094 ##  if ($form->{l_soldtotal}) {
 
1095 ##    $where .= qq| AND (p.id = i.parts_id) AND (i.qty >= 0)|;
 
1096 ##    $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|;
 
1099 ##  $limit = qq| LIMIT 100| if ($form->{top100});
 
1101 ##  # connect to database
 
1102 ##  my $dbh = $form->dbconnect($myconfig);
 
1104 ##  my @sort_cols = qw(id partnumber description partsgroup bin priceupdate onhand
 
1105 ##                     invnumber ordnumber quonumber name drawing microfiche
 
1106 ##                     serialnumber soldtotal deliverydate);
 
1108 ##  my $sortorder = "partnumber";
 
1109 ##  $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } @sort_cols));
 
1110 ##  $sortorder .= " DESC" if ($form->{revers});
 
1114 ##  if ($form->{l_soldtotal}) {
 
1115 ##    $form->{soldtotal} = 'soldtotal';
 
1117 ##      qq|SELECT p.id, p.partnumber, p.description, p.onhand, p.unit,
 
1118 ##           p.bin, p.sellprice, p.listprice, p.lastcost,
 
1119 ##           p.priceupdate, pg.partsgroup,sum(i.qty) AS soldtotal
 
1121 ##         LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id), invoice i
 
1124 ##         ORDER BY $sortorder $limit|;
 
1127 ##      qq|SELECT p.id, p.partnumber, p.description, p.onhand, p.unit,
 
1128 ##           p.bin, p.sellprice, p.listprice, p.lastcost, p.rop, p.weight,
 
1129 ##           p.priceupdate, p.image, p.drawing, p.microfiche,
 
1132 ##         LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1135 ##         ORDER BY $sortorder $limit|;
 
1138 ##  my @all_values = @values;
 
1140 ##  # rebuild query for bought and sold items
 
1141 ##  if (   $form->{bought}
 
1143 ##      || $form->{onorder}
 
1144 ##      || $form->{ordered}
 
1146 ##      || $form->{quoted}) {
 
1149 ##    @all_values = ();
 
1151 ##    if ($form->{bought} || $form->{sold}) {
 
1153 ##      my @invvalues = @values;
 
1154 ##      my $invwhere = "$where";
 
1155 #      $invwhere .= qq| AND i.assemblyitem = '0'|;
 
1157 ##      if ($form->{transdatefrom}) {
 
1158 ##        $invwhere .= qq| AND a.transdate >= ?|;
 
1159 ##        push(@invvalues, $form->{transdatefrom});
 
1162 ##      if ($form->{transdateto}) {
 
1163 ##        $invwhere .= qq| AND a.transdate <= ?|;
 
1164 ##        push(@invvalues, $form->{transdateto});
 
1167 ##      if ($form->{description}) {
 
1168 ##        $invwhere .= qq| AND i.description ILIKE ?|;
 
1169 ##        push(@invvalues, '%' . $form->{description} . '%');
 
1173 ##        qq|p.id, p.partnumber, i.description, i.serialnumber,
 
1174 #           i.qty AS onhand, i.unit, p.bin, i.sellprice,
 
1175 ##           p.listprice, p.lastcost, p.rop, p.weight,
 
1176 ##           p.priceupdate, p.image, p.drawing, p.microfiche,
 
1178 ##           a.invnumber, a.ordnumber, a.quonumber, i.trans_id,
 
1179 ##           ct.name, i.deliverydate|;
 
1181 ##      if ($form->{bought}) {
 
1183 ##          qq|SELECT $flds, 'ir' AS module, '' AS type, 1 AS exchangerate
 
1185 ##             JOIN parts p ON (p.id = i.parts_id)
 
1186 ##             JOIN ap a ON (a.id = i.trans_id)
 
1187 ##             JOIN vendor ct ON (a.vendor_id = ct.id)
 
1188 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1189 ##             WHERE $invwhere|;
 
1191 ##        $union = qq| UNION |;
 
1193 ##        push(@all_values, @invvalues);
 
1196 ##      if ($form->{sold}) {
 
1200 ##             SELECT $flds, 'is' AS module, '' AS type, 1 As exchangerate
 
1202 ##             JOIN parts p ON (p.id = i.parts_id)
 
1203 ##             JOIN ar a ON (a.id = i.trans_id)
 
1204 ##             JOIN customer ct ON (a.customer_id = ct.id)
 
1205 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1206 ##             WHERE $invwhere|;
 
1207 ##        $union = qq| UNION |;
 
1209 ##        push(@all_values, @invvalues);
 
1213 ##    if ($form->{onorder} || $form->{ordered}) {
 
1214 ##      my @ordvalues = @values;
 
1215 ##      my $ordwhere = $where . qq| AND o.quotation = '0'|;
 
1217 ##      if ($form->{transdatefrom}) {
 
1218 ##        $ordwhere .= qq| AND o.transdate >= ?|;
 
1219 ##        push(@ordvalues, $form->{transdatefrom});
 
1222 ##      if ($form->{transdateto}) {
 
1223 ##        $ordwhere .= qq| AND o.transdate <= ?|;
 
1224 ##        push(@ordvalues, $form->{transdateto});
 
1227 ##      if ($form->{description}) {
 
1228 ##        $ordwhere .= qq| AND oi.description ILIKE ?|;
 
1229 ##        push(@ordvalues, '%' . $form->{description} . '%');
 
1232 ##      if ($form->{ordered}) {
 
1236 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
 
1237 ##               oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
 
1238 ##               p.listprice, p.lastcost, p.rop, p.weight,
 
1239 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
 
1241 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
 
1242 ##               ct.name, NULL AS deliverydate,
 
1243 ##               'oe' AS module, 'sales_order' AS type,
 
1244 ##               (SELECT buy FROM exchangerate ex
 
1245 ##                WHERE ex.curr = o.curr AND ex.transdate = o.transdate) AS exchangerate
 
1246 ##             FROM orderitems oi
 
1247 ##             JOIN parts p ON (oi.parts_id = p.id)
 
1248 ##             JOIN oe o ON (oi.trans_id = o.id)
 
1249 ##             JOIN customer ct ON (o.customer_id = ct.id)
 
1250 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1251 ##             WHERE $ordwhere AND (o.customer_id > 0)|;
 
1252 ##        $union = qq| UNION |;
 
1254 ##        push(@all_values, @ordvalues);
 
1257 ##      if ($form->{onorder}) {
 
1261 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
 
1262 ##               oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
 
1263 ##               p.listprice, p.lastcost, p.rop, p.weight,
 
1264 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
 
1266 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
 
1267 ##               ct.name, NULL AS deliverydate,
 
1268 ##               'oe' AS module, 'purchase_order' AS type,
 
1269 ##               (SELECT sell FROM exchangerate ex
 
1270 ##               WHERE ex.curr = o.curr AND (ex.transdate = o.transdate)) AS exchangerate
 
1271 ##             FROM orderitems oi
 
1272 ##             JOIN parts p ON (oi.parts_id = p.id)
 
1273 ##             JOIN oe o ON (oi.trans_id = o.id)
 
1274 ##             JOIN vendor ct ON (o.vendor_id = ct.id)
 
1275 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1276 ##             WHERE $ordwhere AND (o.vendor_id > 0)|;
 
1277 ##        $union = qq| UNION |;
 
1279 ##        push(@all_values, @ordvalues);
 
1284 ##    if ($form->{rfq} || $form->{quoted}) {
 
1285 ##      my $quowhere = $where . qq| AND o.quotation = '1'|;
 
1286 ##      my @quovalues = @values;
 
1288 ##      if ($form->{transdatefrom}) {
 
1289 ##        $quowhere .= qq| AND o.transdate >= ?|;
 
1290 ##        push(@quovalues, $form->{transdatefrom});
 
1293 ##      if ($form->{transdateto}) {
 
1294 ##        $quowhere .= qq| AND o.transdate <= ?|;
 
1295 ##        push(@quovalues, $form->{transdateto});
 
1298 ##      if ($form->{description}) {
 
1299 ##        $quowhere .= qq| AND oi.description ILIKE ?|;
 
1300 ##        push(@quovalues, '%' . $form->{description} . '%');
 
1303 ##      if ($form->{quoted}) {
 
1308 ##               p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
 
1309 ##               oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
 
1310 ##               p.listprice, p.lastcost, p.rop, p.weight,
 
1311 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
 
1313 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
 
1314 ##               ct.name, NULL AS deliverydate, 'oe' AS module, 'sales_quotation' AS type,
 
1315 ##               (SELECT buy FROM exchangerate ex
 
1316 ##                WHERE (ex.curr = o.curr) AND (ex.transdate = o.transdate)) AS exchangerate
 
1317 ##             FROM orderitems oi
 
1318 ##             JOIN parts p ON (oi.parts_id = p.id)
 
1319 ##             JOIN oe o ON (oi.trans_id = o.id)
 
1320 ##             JOIN customer ct ON (o.customer_id = ct.id)
 
1321 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1323 ##             AND o.customer_id > 0|;
 
1324 ##        $union = qq| UNION |;
 
1326 ##        push(@all_values, @quovalues);
 
1329 ##      if ($form->{rfq}) {
 
1333 ##             SELECT p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
 
1334 ##               oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
 
1335 ##               p.listprice, p.lastcost, p.rop, p.weight,
 
1336 ##               p.priceupdate, p.image, p.drawing, p.microfiche,
 
1338 ##               '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
 
1339 ##               ct.name, NULL AS deliverydate,
 
1340 ##               'oe' AS module, 'request_quotation' AS type,
 
1341 ##               (SELECT sell FROM exchangerate ex
 
1342 ##               WHERE (ex.curr = o.curr) AND (ex.transdate = o.transdate)) AS exchangerate
 
1343 ##             FROM orderitems oi
 
1344 ##             JOIN parts p ON (oi.parts_id = p.id)
 
1345 ##             JOIN oe o ON (oi.trans_id = o.id)
 
1346 ##             JOIN vendor ct ON (o.vendor_id = ct.id)
 
1347 ##             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1349 ##             AND o.vendor_id > 0|;
 
1351 ##        push(@all_values, @quovalues);
 
1355 ##    $query .= qq| ORDER BY  | . $sortorder;
 
1359 ##  $form->{parts} = selectall_hashref_query($form, $dbh, $query, @all_values);
 
1362   # include individual items for assemblies
 
1363   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
 
1365       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
 
1367            p.sellprice, p.listprice, p.lastcost,
 
1368            p.rop, p.weight, p.priceupdate,
 
1369            p.image, p.drawing, p.microfiche
 
1370          FROM parts p, assembly a
 
1371          WHERE (p.id = a.parts_id) AND (a.id = ?)|;
 
1372     $sth = prepare_query($form, $dbh, $query);
 
1374     foreach $item (@{ $form->{parts} }) {
 
1375       push(@assemblies, $item);
 
1376       do_statement($form, $sth, $query, conv_i($item->{id}));
 
1378       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1379         $ref->{assemblyitem} = 1;
 
1380         push(@assemblies, $ref);
 
1385     # copy assemblies to $form->{parts}
 
1386     $form->{parts} = \@assemblies;
 
1390   $main::lxdebug->leave_sub();
 
1394   $main::lxdebug->enter_sub();
 
1396   my ($self, $myconfig, $form) = @_;
 
1398   my $where = '1 = 1';
 
1404   if ($item ne 'make') {
 
1405     foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
 
1407       $column =~ s/.*\.//;
 
1408       next unless ($form->{$column});
 
1409       $where .= qq| AND $item ILIKE ?|;
 
1410       push(@where_values, '%' . $form->{$column} . '%');
 
1414   # special case for description
 
1415   if ($form->{description}
 
1416       && !(   $form->{bought}  || $form->{sold} || $form->{onorder}
 
1417            || $form->{ordered} || $form->{rfq} || $form->{quoted})) {
 
1418     $where .= qq| AND (p.description ILIKE ?)|;
 
1419     push(@where_values, '%' . $form->{description} . '%');
 
1422   # special case for serialnumber
 
1423   if ($form->{l_serialnumber} && $form->{serialnumber}) {
 
1424     $where .= qq| AND serialnumber ILIKE ?|;
 
1425     push(@where_values, '%' . $form->{serialnumber} . '%');
 
1429   # items which were never bought, sold or on an order
 
1430   if ($form->{itemstatus} eq 'orphaned') {
 
1431     $form->{onhand}  = $form->{short}   = 0;
 
1432     $form->{bought}  = $form->{sold}    = 0;
 
1433     $form->{onorder} = $form->{ordered} = 0;
 
1434     $form->{rfq}     = $form->{quoted}  = 0;
 
1436     $form->{transdatefrom} = $form->{transdateto} = "";
 
1439       qq| AND (p.onhand = 0)
 
1442               SELECT DISTINCT parts_id FROM invoice
 
1444               SELECT DISTINCT parts_id FROM assembly
 
1446               SELECT DISTINCT parts_id FROM orderitems
 
1450   if ($form->{itemstatus} eq 'active') {
 
1451     $where .= qq| AND p.obsolete = '0'|;
 
1454   if ($form->{itemstatus} eq 'obsolete') {
 
1455     $where .= qq| AND p.obsolete = '1'|;
 
1456     $form->{onhand} = $form->{short} = 0;
 
1459   if ($form->{itemstatus} eq 'onhand') {
 
1460     $where .= qq| AND p.onhand > 0|;
 
1463   if ($form->{itemstatus} eq 'short') {
 
1464     $where .= qq| AND p.onhand < p.rop|;
 
1467   foreach my $column (qw(make model)) {
 
1468     next unless ($form->{$colum});
 
1469     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
 
1470     push(@where_values, '%' . $form->{$column} . '%');
 
1473   # connect to database
 
1474   my $dbh = $form->dbconnect_noauto($myconfig);
 
1476   for my $column (qw(sellprice listprice)) {
 
1477     next if ($form->{$column} eq "");
 
1479     my $value = $form->parse_amount($myconfig, $form->{$column});
 
1482     if ($form->{"${column}_type"} eq "percent") {
 
1483       $value = ($value / 100) + 1;
 
1488       qq|UPDATE parts SET $column = $column $operator ?
 
1492             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1494     do_query($from, $dbh, $query, $value, @where_values);
 
1498     qq|UPDATE prices SET price = price + ?
 
1502           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1503           WHERE $where) AND (pricegroup_id = ?)|;
 
1504   my $sth_add = prepare_query($form, $dbh, $q_add);
 
1507     qq|UPDATE prices SET price = price * ?
 
1511           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1512           WHERE $where) AND (pricegroup_id = ?)|;
 
1513   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
 
1515   for my $i (1 .. $form->{price_rows}) {
 
1516     next if ($form->{"price_$i"} eq "");
 
1518     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
 
1520     if ($form->{"pricegroup_type_$i"} eq "percent") {
 
1521       do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1523       do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1528   $sth_multiply->finish();
 
1530   my $rc= $dbh->commit;
 
1533   $main::lxdebug->leave_sub();
 
1539   $main::lxdebug->enter_sub();
 
1541   my ($self, $module, $myconfig, $form) = @_;
 
1543   # connect to database
 
1544   my $dbh = $form->dbconnect($myconfig);
 
1546   my @values = ('%' . $module . '%');
 
1550       qq|SELECT c.accno, c.description, c.link, c.id,
 
1551            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
 
1552          FROM chart c, parts p
 
1553          WHERE (c.link LIKE ?) AND (p.id = ?)
 
1555     push(@values, conv_i($form->{id}));
 
1559       qq|SELECT c.accno, c.description, c.link, c.id,
 
1560            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
 
1561          FROM chart c, defaults d
 
1566   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1567   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1568     foreach my $key (split(/:/, $ref->{link})) {
 
1569       if ($key =~ /\Q$module\E/) {
 
1570         if (   ($ref->{id} eq $ref->{inventory_accno_id})
 
1571             || ($ref->{id} eq $ref->{income_accno_id})
 
1572             || ($ref->{id} eq $ref->{expense_accno_id})) {
 
1573           push @{ $form->{"${module}_links"}{$key} },
 
1574             { accno       => $ref->{accno},
 
1575               description => $ref->{description},
 
1576               selected    => "selected" };
 
1577           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
 
1579           push @{ $form->{"${module}_links"}{$key} },
 
1580             { accno       => $ref->{accno},
 
1581               description => $ref->{description},
 
1589   # get buchungsgruppen
 
1590   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
 
1593   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
 
1596     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
 
1600   $main::lxdebug->leave_sub();
 
1603 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
 
1605   $main::lxdebug->enter_sub();
 
1607   my ($self, $myconfig, $form, $sortorder) = @_;
 
1608   my $dbh   = $form->dbconnect($myconfig);
 
1609   my $order = qq| p.partnumber|;
 
1610   my $where = qq|1 = 1|;
 
1613   if ($sortorder eq "all") {
 
1614     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
 
1615     push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
 
1617   } elsif ($sortorder eq "partnumber") {
 
1618     $where .= qq| AND (partnumber ILIKE ?)|;
 
1619     push(@values, '%' . $form->{partnumber} . '%');
 
1621   } elsif ($sortorder eq "description") {
 
1622     $where .= qq| AND (description ILIKE ?)|;
 
1623     push(@values, '%' . $form->{description} . '%');
 
1624     $order = "description";
 
1629     qq|SELECT id, partnumber, description, unit, sellprice
 
1631        WHERE $where ORDER BY $order|;
 
1633   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1636   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1637     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
 
1642     $form->{"id_$j"}          = $ref->{id};
 
1643     $form->{"partnumber_$j"}  = $ref->{partnumber};
 
1644     $form->{"description_$j"} = $ref->{description};
 
1645     $form->{"unit_$j"}        = $ref->{unit};
 
1646     $form->{"sellprice_$j"}   = $ref->{sellprice};
 
1647     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
 
1653   $main::lxdebug->leave_sub();
 
1658 # gets sum of sold part with part_id
 
1660   $main::lxdebug->enter_sub();
 
1662   my ($dbh, $id) = @_;
 
1664   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
 
1665   my ($sum) = selectrow_query($form, $dbh, $query, conv_i($id));
 
1668   $main::lxdebug->leave_sub();
 
1671 }    #end get_soldtotal
 
1673 sub retrieve_languages {
 
1674   $main::lxdebug->enter_sub();
 
1676   my ($self, $myconfig, $form) = @_;
 
1678   # connect to database
 
1679   my $dbh = $form->dbconnect($myconfig);
 
1684   if ($form->{language_values} ne "") {
 
1686       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
 
1688          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
 
1689          ORDER BY lower(l.description)|;
 
1690     @values = (conv_i($form->{id}));
 
1693     $query = qq|SELECT id, description
 
1695                 ORDER BY lower(description)|;
 
1698   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
 
1702   $main::lxdebug->leave_sub();
 
1707 sub follow_account_chain {
 
1708   $main::lxdebug->enter_sub(2);
 
1710   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
 
1712   my @visited_accno_ids = ($accno_id);
 
1717     qq|SELECT c.new_chart_id, date($transdate) >= c.valid_from AS is_valid, | .
 
1720     qq|LEFT JOIN chart cnew ON c.new_chart_id = cnew.id | .
 
1721     qq|WHERE (c.id = ?) AND NOT c.new_chart_id ISNULL AND (c.new_chart_id > 0)|;
 
1722   $sth = prepare_query($form, $dbh, $query);
 
1725     do_statement($form, $sth, $query, $accno_id);
 
1726     $ref = $sth->fetchrow_hashref();
 
1727     last unless ($ref && $ref->{"is_valid"} &&
 
1728                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
 
1729     $accno_id = $ref->{"new_chart_id"};
 
1730     $accno = $ref->{"accno"};
 
1731     push(@visited_accno_ids, $accno_id);
 
1734   $main::lxdebug->leave_sub(2);
 
1736   return ($accno_id, $accno);
 
1739 sub retrieve_accounts {
 
1740   $main::lxdebug->enter_sub(2);
 
1742   my ($self, $myconfig, $form, $parts_id, $index) = @_;
 
1744   my ($query, $sth, $dbh);
 
1746   $form->{"taxzone_id"} *= 1;
 
1748   $dbh = $form->get_standard_dbh($myconfig);
 
1751   if ($form->{type} eq "invoice") {
 
1752     if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
 
1753       $transdate = $form->{invdate};
 
1755       $transdate = $form->{deliverydate};
 
1757   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
 
1758     $transdate = $form->{invdate};
 
1760     $transdate = $form->{transdate};
 
1763   if ($transdate eq "") {
 
1764     $transdate = "current_date";
 
1766     $transdate = $dbh->quote($transdate);
 
1771     qq|  p.inventory_accno_id AS is_part, | .
 
1772     qq|  bg.inventory_accno_id, | .
 
1773     qq|  bg.income_accno_id_$form->{taxzone_id} AS income_accno_id, | .
 
1774     qq|  bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id, | .
 
1775     qq|  c1.accno AS inventory_accno, | .
 
1776     qq|  c2.accno AS income_accno, | .
 
1777     qq|  c3.accno AS expense_accno | .
 
1779     qq|LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id | .
 
1780     qq|LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id | .
 
1781     qq|LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id | .
 
1782     qq|LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id | .
 
1784   my $ref = selectfirst_hashref_query($form, $dbh, $query, $parts_id);
 
1786   return $main::lxdebug->leave_sub(2) if (!$ref);
 
1788   $ref->{"inventory_accno_id"} = undef unless ($ref->{"is_part"});
 
1791   foreach my $type (qw(inventory income expense)) {
 
1792     next unless ($ref->{"${type}_accno_id"});
 
1793     ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
 
1794       $self->follow_account_chain($form, $dbh, $transdate,
 
1795                                   $ref->{"${type}_accno_id"},
 
1796                                   $ref->{"${type}_accno"});
 
1799   map({ $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} }
 
1800       qw(inventory income expense));
 
1802   my $inc_exp = $form->{"vc"} eq "customer" ? "income" : "expense";
 
1803   my $accno_id = $accounts{"${inc_exp}_accno_id"};
 
1806     qq|SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber | .
 
1808     qq|LEFT JOIN chart c ON c.id = t.chart_id | .
 
1809     qq|WHERE t.id IN | .
 
1810     qq|  (SELECT tk.tax_id | .
 
1811     qq|   FROM taxkeys tk | .
 
1812     qq|   WHERE tk.chart_id = ? AND startdate <= | . quote_db_date($transdate) .
 
1813     qq|   ORDER BY startdate DESC LIMIT 1) |;
 
1814   $ref = selectfirst_hashref_query($form, $dbh, $query, $accno_id);
 
1817     $main::lxdebug->leave_sub(2);
 
1821   $form->{"taxaccounts_$index"} = $ref->{"accno"};
 
1822   if ($form->{"taxaccounts"} !~ /$ref->{accno}/) {
 
1823     $form->{"taxaccounts"} .= "$ref->{accno} ";
 
1825   map({ $form->{"$ref->{accno}_${_}"} = $ref->{$_}; }
 
1826       qw(rate description taxnumber));
 
1828 #   $main::lxdebug->message(0, "formvars: rate " . $form->{"$ref->{accno}_rate"} .
 
1829 #                           " description " . $form->{"$ref->{accno}_description"} .
 
1830 #                           " taxnumber " . $form->{"$ref->{accno}_taxnumber"} .
 
1831 #                           " || taxaccounts_$index " . $form->{"taxaccounts_$index"} .
 
1832 #                           " || taxaccounts " . $form->{"taxaccounts"});
 
1834   $main::lxdebug->leave_sub(2);
 
1837 sub get_basic_part_info {
 
1838   $main::lxdebug->enter_sub();
 
1843   Common::check_params(\%params, qw(id));
 
1845   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
 
1848     $main::lxdebug->leave_sub();
 
1852   my $myconfig = \%main::myconfig;
 
1853   my $form     = $main::form;
 
1855   my $dbh      = $form->get_standard_dbh($myconfig);
 
1857   my $query    = qq|SELECT id, partnumber, description, unit FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
 
1859   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
 
1861   if ($params{vendor_id}) {
 
1862     $query     = qq|SELECT * FROM parts_vendor WHERE (parts_id = ?) AND (vendor_id = ?)|;
 
1863     my $sth    = prepare_query($form, $dbh, $query);
 
1865     foreach my $part (@{ $info }) {
 
1866       do_statement($form, $sth, $query, $part->{id}, conv_i($params{vendor_id}));
 
1867       $part->{vendor_info} = $sth->fetchrow_hashref();
 
1873   if ('' eq ref $params{id}) {
 
1874     $info = $info->[0] || { };
 
1876     $main::lxdebug->leave_sub();
 
1880   my %info_map = map { $_->{id} => $_ } @{ $info };
 
1882   $main::lxdebug->leave_sub();