1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  17 # This program is free software; you can redistribute it and/or modify
 
  18 # it under the terms of the GNU General Public License as published by
 
  19 # the Free Software Foundation; either version 2 of the License, or
 
  20 # (at your option) any later version.
 
  22 # This program is distributed in the hope that it will be useful,
 
  23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  25 # GNU General Public License for more details.
 
  26 # You should have received a copy of the GNU General Public License
 
  27 # along with this program; if not, write to the Free Software
 
  28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  29 #======================================================================
 
  31 # Inventory Control backend
 
  33 #======================================================================
 
  38 use List::MoreUtils qw(all);
 
  44   $main::lxdebug->enter_sub();
 
  46   my ($self, $myconfig, $form) = @_;
 
  49   my $dbh = $form->dbconnect($myconfig);
 
  55          c1.accno AS inventory_accno,
 
  56          c2.accno AS income_accno,
 
  57          c3.accno AS expense_accno,
 
  60        LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
 
  61        LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
 
  62        LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
 
  63        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
  65   my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
  67   # copy to $form variables
 
  68   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
 
  72   my %oid = ('Pg'     => 'a.oid',
 
  73              'Oracle' => 'a.rowid');
 
  75   # part or service item
 
  76   $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
 
  77   if ($form->{assembly}) {
 
  78     $form->{item} = 'assembly';
 
  80     # retrieve assembly items
 
  82       qq|SELECT p.id, p.partnumber, p.description,
 
  83            p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
 
  84            pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
 
  86          JOIN assembly a ON (a.parts_id = p.id)
 
  87          LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
  88          LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
 
  90          ORDER BY $oid{$myconfig->{dbdriver}}|;
 
  91     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
  93     $form->{assembly_rows} = 0;
 
  94     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
  95       $form->{assembly_rows}++;
 
  96       foreach my $key (keys %{$ref}) {
 
  97         $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
 
 104   # setup accno hash for <option checked> {amount} is used in create_links
 
 105   $form->{amount}{IC}         = $form->{inventory_accno};
 
 106   $form->{amount}{IC_income}  = $form->{income_accno};
 
 107   $form->{amount}{IC_sale}    = $form->{income_accno};
 
 108   $form->{amount}{IC_expense} = $form->{expense_accno};
 
 109   $form->{amount}{IC_cogs}    = $form->{expense_accno};
 
 111   my @pricegroups          = ();
 
 112   my @pricegroups_not_used = ();
 
 116     qq|SELECT p.parts_id, p.pricegroup_id, p.price,
 
 117          (SELECT pg.pricegroup
 
 119           WHERE pg.id = p.pricegroup_id) AS pricegroup
 
 122        ORDER BY pricegroup|;
 
 123   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 127   while (($form->{"klass_$i"}, $form->{"pricegroup_id_$i"},
 
 128           $form->{"price_$i"}, $form->{"pricegroup_$i"})
 
 129          = $sth->fetchrow_array()) {
 
 130     $form->{"price_$i"} = $form->round_amount($form->{"price_$i"}, 5);
 
 131     $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
 132     push @pricegroups, $form->{"pricegroup_id_$i"};
 
 139   $query = qq|SELECT id, pricegroup FROM pricegroup|;
 
 140   $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
 
 142   #find not used pricegroups
 
 143   while ($tmp = pop(@{ $form->{PRICEGROUPS} })) {
 
 145     foreach my $item (@pricegroups) {
 
 146       if ($item eq $tmp->{id}) {
 
 151     push(@pricegroups_not_used, $tmp) unless ($in_use);
 
 154   # if not used pricegroups are avaible
 
 155   if (@pricegroups_not_used) {
 
 157     foreach $name (@pricegroups_not_used) {
 
 158       $form->{"klass_$i"} = "$name->{id}";
 
 159       $form->{"price_$i"} = $form->round_amount($form->{sellprice}, 5);
 
 160       $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
 161       $form->{"pricegroup_id_$i"} = "$name->{id}";
 
 162       $form->{"pricegroup_$i"}    = "$name->{pricegroup}";
 
 168   $form->{price_rows} = $i - 1;
 
 170   unless ($form->{item} eq 'service') {
 
 173     if ($form->{makemodel}) {
 
 174       $query = qq|SELECT m.make, m.model FROM makemodel m | .
 
 175                qq|WHERE m.parts_id = ?|;
 
 176       @values = ($form->{id});
 
 177       $sth = $dbh->prepare($query);
 
 178       $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
 
 181       while (($form->{"make_$i"}, $form->{"model_$i"}) = $sth->fetchrow_array)
 
 186       $form->{makemodel_rows} = $i - 1;
 
 192   $form->{language_values} = "";
 
 193   $query = qq|SELECT language_id, translation, longdescription
 
 196   my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 197   while (my $tr = $trq->fetchrow_hashref(NAME_lc)) {
 
 198     $form->{language_values} .= "---+++---" . join('--++--', @{$tr}{qw(language_id translation longdescription)});
 
 202   # now get accno for taxes
 
 205        FROM chart c, partstax pt
 
 206        WHERE (pt.chart_id = c.id) AND (pt.parts_id = ?)|;
 
 207   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 208   while (($key) = $sth->fetchrow_array) {
 
 209     $form->{amount}{$key} = $key;
 
 215   my @referencing_tables = qw(invoice orderitems inventory rmaitems);
 
 216   my %column_map         = ( );
 
 217   my $parts_id           = conv_i($form->{id});
 
 219   $form->{orphaned}      = 1;
 
 221   foreach my $table (@referencing_tables) {
 
 222     my $column  = $column_map{$table} || 'parts_id';
 
 223     $query      = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
 
 224     my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
 
 227       $form->{orphaned} = 0;
 
 232   $form->{"unit_changeable"} = $form->{orphaned};
 
 236   $main::lxdebug->leave_sub();
 
 239 sub get_pricegroups {
 
 240   $main::lxdebug->enter_sub();
 
 242   my ($self, $myconfig, $form) = @_;
 
 244   my $dbh = $form->dbconnect($myconfig);
 
 247   my $query = qq|SELECT id, pricegroup FROM pricegroup|;
 
 248   my $pricegroups = selectall_hashref_query($form, $dbh, $query);
 
 251   foreach $pg (@{ $pricegroups }) {
 
 252     $form->{"klass_$i"} = "$pg->{id}";
 
 253     $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
 
 254     $form->{"pricegroup_id_$i"} = "$pg->{id}";
 
 255     $form->{"pricegroup_$i"}    = "$pg->{pricegroup}";
 
 260   $form->{price_rows} = $i - 1;
 
 264   $main::lxdebug->leave_sub();
 
 269 sub retrieve_buchungsgruppen {
 
 270   $main::lxdebug->enter_sub();
 
 272   my ($self, $myconfig, $form) = @_;
 
 276   my $dbh = $form->dbconnect($myconfig);
 
 278   # get buchungsgruppen
 
 279   $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
 
 280   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
 
 282   $main::lxdebug->leave_sub();
 
 286   $main::lxdebug->enter_sub();
 
 288   my ($self, $myconfig, $form) = @_;
 
 290   # connect to database, turn off AutoCommit
 
 291   my $dbh = $form->dbconnect_noauto($myconfig);
 
 294   # make up a unique handle and store in partnumber field
 
 295   # then retrieve the record based on the unique handle to get the id
 
 296   # replace the partnumber field with the actual variable
 
 297   # add records for makemodel
 
 299   # if there is a $form->{id} then replace the old entry
 
 300   # delete all makemodel entries and add the new ones
 
 302   # undo amount formatting
 
 303   map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
 
 304     qw(rop weight listprice sellprice gv lastcost);
 
 306   my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
 
 308   $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
 
 312   my $priceupdate = ', priceupdate = current_date';
 
 317     $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
 
 318     my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
 
 320     # if item is part of an assembly adjust all assemblies
 
 321     $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
 
 322     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 323     while (my ($id, $qty) = $sth->fetchrow_array) {
 
 324       &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
 
 328     if ($form->{item} ne 'service') {
 
 329       # delete makemodel records
 
 330       do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
 
 333     if ($form->{item} eq 'assembly') {
 
 334       # delete assembly records
 
 335       do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
 
 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}));
 
 344     # Check whether or not the prices have changed. If they haven't
 
 345     # then 'priceupdate' should not be updated.
 
 346     my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
 
 347     $priceupdate        = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
 
 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     if ($form->{partnumber} eq "" && $form->{"item"} eq "service") {
 
 361       $form->{partnumber} = $form->update_defaults($myconfig, "servicenumber");
 
 363     if ($form->{partnumber} eq "" && $form->{"item"} ne "service") {
 
 364       $form->{partnumber} = $form->update_defaults($myconfig, "articlenumber");
 
 368   my $partsgroup_id = 0;
 
 370   if ($form->{partsgroup}) {
 
 371     ($partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
 
 374   my ($subq_inventory, $subq_expense, $subq_income);
 
 375   if ($form->{"item"} eq "part") {
 
 377       qq|(SELECT bg.inventory_accno_id
 
 378           FROM buchungsgruppen bg
 
 379           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 381     $subq_inventory = "NULL";
 
 384   if ($form->{"item"} ne "assembly") {
 
 386       qq|(SELECT bg.expense_accno_id_0
 
 387           FROM buchungsgruppen bg
 
 388           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
 
 390     $subq_expense = "NULL";
 
 409          buchungsgruppen_id = ?,
 
 411          inventory_accno_id = $subq_inventory,
 
 412          income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
 
 413          expense_accno_id = $subq_expense,
 
 421          not_discountable = ?,
 
 427   @values = ($form->{partnumber},
 
 428              $form->{description},
 
 429              $makemodel ? 't' : 'f',
 
 430              $form->{assembly} ? 't' : 'f',
 
 440              conv_i($form->{buchungsgruppen_id}),
 
 441              conv_i($form->{payment_id}),
 
 442              conv_i($form->{buchungsgruppen_id}),
 
 443              $form->{obsolete} ? 't' : 'f',
 
 446              $form->{shop} ? 't' : 'f',
 
 450              $form->{not_discountable} ? 't' : 'f',
 
 452              conv_i($partsgroup_id),
 
 453              conv_i($form->{price_factor_id}),
 
 456   do_query($form, $dbh, $query, @values);
 
 458   # delete translation records
 
 459   do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
 
 461   if ($form->{language_values} ne "") {
 
 462     foreach $item (split(/---\+\+\+---/, $form->{language_values})) {
 
 463       my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
 
 464       if ($translation ne "") {
 
 465         $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
 
 466                     VALUES ( ?, ?, ?, ? )|;
 
 467         @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
 
 468         do_query($form, $dbh, $query, @values);
 
 473   # delete price records
 
 474   do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
 
 476   # insert price records only if different to sellprice
 
 477   for my $i (1 .. $form->{price_rows}) {
 
 478     if ($form->{"price_$i"} eq "0") {
 
 479       $form->{"price_$i"} = $form->{sellprice};
 
 482         (   $form->{"price_$i"}
 
 483          || $form->{"klass_$i"}
 
 484          || $form->{"pricegroup_id_$i"})
 
 485         and $form->{"price_$i"} != $form->{sellprice}
 
 487       #$klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
 
 488       $price = $form->parse_amount($myconfig, $form->{"price_$i"});
 
 490         $form->parse_amount($myconfig, $form->{"pricegroup_id_$i"});
 
 491       $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) | .
 
 493       @values = (conv_i($form->{id}), conv_i($pricegroup_id), $price);
 
 494       do_query($form, $dbh, $query, @values);
 
 498   # insert makemodel records
 
 499   unless ($form->{item} eq 'service') {
 
 500     for my $i (1 .. $form->{makemodel_rows}) {
 
 501       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
 
 503         $query = qq|INSERT INTO makemodel (parts_id, make, model) | .
 
 504                              qq|VALUES (?, ?, ?)|;
 
 505                     @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"});
 
 507         do_query($form, $dbh, $query, @values);
 
 513   foreach $item (split(/ /, $form->{taxaccounts})) {
 
 514     if ($form->{"IC_tax_$item"}) {
 
 516         qq|INSERT INTO partstax (parts_id, chart_id)
 
 517            VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
 
 518                         @values = (conv_i($form->{id}), $item);
 
 519       do_query($form, $dbh, $query, @values);
 
 523   # add assembly records
 
 524   if ($form->{item} eq 'assembly') {
 
 526     for my $i (1 .. $form->{assembly_rows}) {
 
 527       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 529       if ($form->{"qty_$i"} != 0) {
 
 530         $form->{"bom_$i"} *= 1;
 
 531         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
 
 532                              qq|VALUES (?, ?, ?, ?)|;
 
 533                     @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
 
 534         do_query($form, $dbh, $query, @values);
 
 541     my $shippingdate = "$a[5]-$a[4]-$a[3]";
 
 543     $form->get_employee($dbh);
 
 547   #set expense_accno=inventory_accno if they are different => bilanz
 
 549     ($form->{expense_accno} != $form->{inventory_accno})
 
 550     ? $form->{inventory_accno}
 
 551     : $form->{expense_accno};
 
 553   # get tax rates and description
 
 555     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
 
 557     qq|SELECT c.accno, c.description, t.rate, t.taxnumber
 
 559        WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
 
 561   $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
 
 563   $form->{taxaccount} = "";
 
 564   while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
 565     $form->{taxaccount} .= "$ptr->{accno} ";
 
 566     if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
 
 567       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
 568       $form->{"$ptr->{accno}_description"} = $ptr->{description};
 
 569       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
 570       $form->{taxaccount2} .= " $ptr->{accno} ";
 
 575   my $rc = $dbh->commit;
 
 578   $main::lxdebug->leave_sub();
 
 583 sub update_assembly {
 
 584   $main::lxdebug->enter_sub();
 
 586   my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
 
 588   my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
 
 589   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
 
 591   while (my ($pid, $aqty) = $sth->fetchrow_array) {
 
 592     &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
 
 597     qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
 
 599   @values = ($qty * ($form->{sellprice} - $sellprice),
 
 600              $qty * ($form->{weight} - $weight), conv_i($id));
 
 601   do_query($form, $dbh, $query, @values);
 
 603   $main::lxdebug->leave_sub();
 
 606 sub retrieve_assemblies {
 
 607   $main::lxdebug->enter_sub();
 
 609   my ($self, $myconfig, $form) = @_;
 
 611   # connect to database
 
 612   my $dbh = $form->dbconnect($myconfig);
 
 614   my $where = qq|NOT p.obsolete|;
 
 617   if ($form->{partnumber}) {
 
 618     $where .= qq| AND (p.partnumber ILIKE ?)|;
 
 619     push(@values, '%' . $form->{partnumber} . '%');
 
 622   if ($form->{description}) {
 
 623     $where .= qq| AND (p.description ILIKE ?)|;
 
 624     push(@values, '%' . $form->{description} . '%');
 
 627   # retrieve assembly items
 
 629     qq|SELECT p.id, p.partnumber, p.description,
 
 630          p.bin, p.onhand, p.rop,
 
 631          (SELECT sum(p2.inventory_accno_id)
 
 632           FROM parts p2, assembly a
 
 633           WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
 
 635        WHERE NOT p.obsolete AND p.assembly $where|;
 
 637   $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
 
 641   $main::lxdebug->leave_sub();
 
 645   $main::lxdebug->enter_sub();
 
 647   my ($self, $myconfig, $form) = @_;
 
 648   my @values = (conv_i($form->{id}));
 
 649   # connect to database, turn off AutoCommit
 
 650   my $dbh = $form->dbconnect_noauto($myconfig);
 
 652   my %columns = ( "assembly" => "id", "parts" => "id" );
 
 654   for my $table (qw(prices partstax makemodel inventory assembly license translation parts)) {
 
 655     my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
 
 656     do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
 
 660   my $rc = $dbh->commit;
 
 663   $main::lxdebug->leave_sub();
 
 669   $main::lxdebug->enter_sub();
 
 671   my ($self, $myconfig, $form) = @_;
 
 673   my $i = $form->{assembly_rows};
 
 675   my $where = qq|1 = 1|;
 
 678   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
 
 680   while (my ($column, $table) = each(%columns)) {
 
 681     next unless ($form->{"${column}_$i"});
 
 682     $where .= qq| AND ${table}.${column} ILIKE ?|;
 
 683     push(@values, '%' . $form->{"${column}_$i"} . '%');
 
 687     $where .= qq| AND NOT (p.id = ?)|;
 
 688     push(@values, conv_i($form->{id}));
 
 692     $where .= qq| ORDER BY p.partnumber|;
 
 694     $where .= qq| ORDER BY p.description|;
 
 697   # connect to database
 
 698   my $dbh = $form->dbconnect($myconfig);
 
 701     qq|SELECT p.id, p.partnumber, p.description, p.sellprice, 
 
 702        p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
 
 703        p.price_factor_id, pfac.factor AS price_factor
 
 705        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 706        LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
 
 708   $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
 
 712   $main::lxdebug->leave_sub();
 
 717 # Warning, deep magic ahead.
 
 718 # This function gets all parts from the database according to the filters specified
 
 721 #   sort revers  - sorting field + direction
 
 724 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
 
 725 #   partnumber ean description partsgroup microfiche drawing
 
 728 #   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
 
 731 #   itemstatus  = active | onhand | short | obsolete | orphaned
 
 732 #   searchitems = part | assembly | service
 
 735 #   make model                               - makemodel
 
 736 #   serialnumber transdatefrom transdateto   - invoice/orderitems
 
 739 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
 
 740 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
 
 741 #   l_soldtotal                              - aggreg join to display total of sold quantity
 
 742 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 743 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
 
 744 #   l_serialnumber                           - belonges to serialnumber filter
 
 745 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
 
 746 #   l_soldtotal                              - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
 
 749 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
 
 750 #   masking of onhand in bsooqr mode         - ToDO: fixme
 
 752 # disabled sanity checks and changes:
 
 753 #  - searchitems = assembly will no longer disable bought
 
 754 #  - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
 
 755 #  - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
 
 756 #  - itemstatus = obsolete will no longer disable onhand, short
 
 757 #  - allow sorting by ean
 
 758 #  - serialnumber filter also works if l_serialnumber isn't ticked
 
 759 #  - onhand doesn't get masked by it's oi or invoice counterparts atm. ToDO: fix this
 
 760 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
 
 763   $main::lxdebug->enter_sub();
 
 765   my ($self, $myconfig, $form) = @_;
 
 766   my $dbh = $form->get_standard_dbh($myconfig);
 
 768   $form->{parts}     = +{ };
 
 769   $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
 
 771   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
 
 772   my @makemodel_filters    = qw(make model);
 
 773   my @invoice_oi_filters   = qw(serialnumber soldtotal);
 
 774   my @apoe_filters         = qw(transdate);
 
 775   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
 
 776   my @simple_l_switches    = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
 
 777   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
 
 778   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module);
 
 779   my @deliverydate_flags   = qw(deliverydate);
 
 780 #  my @other_flags          = qw(onhand); # ToDO: implement these
 
 781 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
 
 784     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
 
 785     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
 
 786     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
 
 789          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem, 'invoice'    AS ioi FROM invoice UNION
 
 790          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, 'orderitems' AS ioi FROM orderitems
 
 791        ) AS ioi ON ioi.parts_id = p.id|,
 
 794          SELECT id, transdate, 'ir' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation, NULL AS customer_id,         vendor_id, NULL AS deliverydate, 'invoice'    AS ioi FROM ap UNION
 
 795          SELECT id, transdate, 'is' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation,         customer_id, NULL AS vendor_id,         deliverydate, 'invoice'    AS ioi FROM ar UNION
 
 796          SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber,          quotation,         customer_id,         vendor_id, NULL AS deliverydate, 'orderitems' AS ioi FROM oe
 
 797        ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
 
 800            SELECT id, name, 'customer' AS cv FROM customer UNION
 
 801            SELECT id, name, 'vendor'   AS cv FROM vendor
 
 802          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
 
 804   my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
 
 807   if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
 
 808     @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
 
 811   #===== switches and simple filters ========#
 
 813   my @select_tokens = qw(id factor);
 
 814   my @where_tokens  = qw(1=1);
 
 815   my @group_tokens  = ();
 
 817   # special case transdate
 
 818   if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
 
 819     $form->{"l_transdate"} = 1;
 
 820     push @select_tokens, 'transdate';
 
 821     for (qw(transdatefrom transdateto)) {
 
 822       next unless $form->{$_};
 
 823       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
 
 824       push @bind_vars,    $form->{$_};
 
 828   my %simple_filter_table_prefix = (
 
 832   foreach (@simple_filters, @makemodel_filters, @invoice_oi_filters) {
 
 833     next unless $form->{$_};
 
 834     $form->{"l_$_"} = '1'; # show the column
 
 835     push @where_tokens, "$simple_filter_table_prefix{$_}$_ ILIKE ?";
 
 836     push @bind_vars,    "%$form->{$_}%";
 
 839   foreach (@simple_l_switches) {
 
 840     next unless $form->{"l_$_"};
 
 841     push @select_tokens, $_;
 
 844   for ($form->{searchitems}) {
 
 845     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
 
 846     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
 
 847     push @where_tokens, 'NOT p.assembly'               if /service/;
 
 848     push @where_tokens, '    p.assembly'               if /assembly/;
 
 851   for ($form->{itemstatus}) {
 
 852     push @where_tokens, 'p.id NOT IN
 
 853         (SELECT DISTINCT parts_id FROM invoice UNION
 
 854          SELECT DISTINCT parts_id FROM assembly UNION
 
 855          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
 
 856     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
 
 857     push @where_tokens, 'NOT p.obsolete'               if /active/;
 
 858     push @where_tokens, '    p.obsolete',              if /obsolete/;
 
 859     push @where_tokens, 'p.onhand > 0',                if /onhand/;
 
 860     push @where_tokens, 'p.onhand < p.rop',            if /short/;
 
 863   my $q_assembly_lastcost =
 
 864     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
 
 866         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
 
 867         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
 
 868         WHERE (a_lc.id = p.id)) AS lastcost|;
 
 870   my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
 
 871   $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols;
 
 873   my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
 
 875   # special case: sorting by partnumber
 
 876   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
 
 877   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
 
 878   # ToDO: implement proper functional sorting
 
 879   $form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
 
 880     if $form->{sort} eq 'partnumber';
 
 882   my $order_clause = " ORDER BY $form->{sort} $sort_order";
 
 884   my $limit_clause = " LIMIT 100" if $form->{top100};
 
 886   #=== joins and complicated filters ========#
 
 888   my $bsooqr = $form->{bought}  || $form->{sold}
 
 889             || $form->{ordered} || $form->{onorder}
 
 890             || $form->{quoted}  || $form->{rfq};
 
 893   push @select_tokens, @qsooqr_flags                                          if $bsooqr;
 
 894   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
 
 895   push @select_tokens, $q_assembly_lastcost                                   if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
 
 896   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
 
 897   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
 
 898   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
 
 899   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
 
 900   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
 
 901   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
 
 902   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
 
 904   $joins_needed{partsgroup}  = 1;
 
 905   $joins_needed{pfac}        = 1;
 
 906   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
 
 907   $joins_needed{cv}          = 1 if $bsooqr;
 
 908   $joins_needed{apoe}        = 1 if $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
 
 909   $joins_needed{invoice_oi}  = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
 
 911   # special case for description search.
 
 912   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
 
 913   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
 
 914   # find the old entries in of @where_tokens and @bind_vars, and adjust them
 
 915   if ($joins_needed{invoice_oi}) {
 
 916     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
 
 917       next unless $where_tokens[$wi] =~ /^description ILIKE/;
 
 918       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
 
 919       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
 
 924   # now the master trick: soldtotal.
 
 925   if ($form->{l_soldtotal}) {
 
 926     push @where_tokens, 'ioi.qty >= 0';
 
 927     push @group_tokens, @select_tokens;
 
 928      map { s/.*\sAS\s+//si } @group_tokens;
 
 929     push @select_tokens, 'SUM(ioi.qty)';
 
 932   #============= build query ================#
 
 936      deliverydate => 'apoe.', serialnumber => 'ioi.',
 
 937      transdate    => 'apoe.', trans_id     => 'ioi.',
 
 938      module       => 'apoe.', name         => 'cv.',
 
 939      ordnumber    => 'apoe.', make         => 'mm.',
 
 940      quonumber    => 'apoe.', model        => 'mm.',
 
 941      invnumber    => 'apoe.', partsgroup   => 'pg.',
 
 944      'SUM(ioi.qty)' => ' ',
 
 947   $table_prefix{$q_assembly_lastcost} = ' ';
 
 949   my %renamed_columns = (
 
 950     'factor'       => 'price_factor',
 
 951     'SUM(ioi.qty)' => 'soldtotal',
 
 954   map { $table_prefix{$_} = 'ioi.' } qw(description serialnumber qty unit) if $joins_needed{invoice_oi};
 
 955   map { $renamed_columns{$_} = ' AS ' . $renamed_columns{$_} } keys %renamed_columns;
 
 957   my $select_clause = join ', ',    map { ($table_prefix{$_} || "p.") . $_ . $renamed_columns{$_} } @select_tokens;
 
 958   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
 
 959   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
 
 960   my $group_clause  = ' GROUP BY ' . join ', ',    map { ($table_prefix{$_} || "p.") . $_ } @group_tokens if scalar @group_tokens;
 
 962   my $query = qq|SELECT DISTINCT $select_clause FROM parts p $join_clause WHERE $where_clause $group_clause $order_clause $limit_clause|;
 
 964   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
 
 966   map { $_->{onhand} *= 1 } @{ $form->{parts} };
 
 969   # include individual items for assemblies
 
 970   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
 
 972       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
 
 974            p.sellprice, p.listprice, p.lastcost,
 
 975            p.rop, p.weight, p.priceupdate,
 
 976            p.image, p.drawing, p.microfiche
 
 977          FROM parts p, assembly a
 
 978          WHERE (p.id = a.parts_id) AND (a.id = ?)|;
 
 979     $sth = prepare_query($form, $dbh, $query);
 
 981     foreach $item (@{ $form->{parts} }) {
 
 982       push(@assemblies, $item);
 
 983       do_statement($form, $sth, $query, conv_i($item->{id}));
 
 985       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
 986         $ref->{assemblyitem} = 1;
 
 987         push(@assemblies, $ref);
 
 992     # copy assemblies to $form->{parts}
 
 993     $form->{parts} = \@assemblies;
 
 996   $main::lxdebug->leave_sub();
 
1000   $main::lxdebug->enter_sub();
 
1002   my ($self, $myconfig, $form) = @_;
 
1004   my $where = '1 = 1';
 
1010   if ($item ne 'make') {
 
1011     foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
 
1013       $column =~ s/.*\.//;
 
1014       next unless ($form->{$column});
 
1015       $where .= qq| AND $item ILIKE ?|;
 
1016       push(@where_values, '%' . $form->{$column} . '%');
 
1020   # special case for description
 
1021   if ($form->{description}
 
1022       && !(   $form->{bought}  || $form->{sold} || $form->{onorder}
 
1023            || $form->{ordered} || $form->{rfq} || $form->{quoted})) {
 
1024     $where .= qq| AND (p.description ILIKE ?)|;
 
1025     push(@where_values, '%' . $form->{description} . '%');
 
1028   # special case for serialnumber
 
1029   if ($form->{l_serialnumber} && $form->{serialnumber}) {
 
1030     $where .= qq| AND serialnumber ILIKE ?|;
 
1031     push(@where_values, '%' . $form->{serialnumber} . '%');
 
1035   # items which were never bought, sold or on an order
 
1036   if ($form->{itemstatus} eq 'orphaned') {
 
1037     $form->{onhand}  = $form->{short}   = 0;
 
1038     $form->{bought}  = $form->{sold}    = 0;
 
1039     $form->{onorder} = $form->{ordered} = 0;
 
1040     $form->{rfq}     = $form->{quoted}  = 0;
 
1042     $form->{transdatefrom} = $form->{transdateto} = "";
 
1045       qq| AND (p.onhand = 0)
 
1048               SELECT DISTINCT parts_id FROM invoice
 
1050               SELECT DISTINCT parts_id FROM assembly
 
1052               SELECT DISTINCT parts_id FROM orderitems
 
1056   if ($form->{itemstatus} eq 'active') {
 
1057     $where .= qq| AND p.obsolete = '0'|;
 
1060   if ($form->{itemstatus} eq 'obsolete') {
 
1061     $where .= qq| AND p.obsolete = '1'|;
 
1062     $form->{onhand} = $form->{short} = 0;
 
1065   if ($form->{itemstatus} eq 'onhand') {
 
1066     $where .= qq| AND p.onhand > 0|;
 
1069   if ($form->{itemstatus} eq 'short') {
 
1070     $where .= qq| AND p.onhand < p.rop|;
 
1073   foreach my $column (qw(make model)) {
 
1074     next unless ($form->{$colum});
 
1075     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
 
1076     push(@where_values, '%' . $form->{$column} . '%');
 
1079   # connect to database
 
1080   my $dbh = $form->dbconnect_noauto($myconfig);
 
1082   for my $column (qw(sellprice listprice)) {
 
1083     next if ($form->{$column} eq "");
 
1085     my $value = $form->parse_amount($myconfig, $form->{$column});
 
1088     if ($form->{"${column}_type"} eq "percent") {
 
1089       $value = ($value / 100) + 1;
 
1094       qq|UPDATE parts SET $column = $column $operator ?
 
1098             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1100     do_query($from, $dbh, $query, $value, @where_values);
 
1104     qq|UPDATE prices SET price = price + ?
 
1108           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1109           WHERE $where) AND (pricegroup_id = ?)|;
 
1110   my $sth_add = prepare_query($form, $dbh, $q_add);
 
1113     qq|UPDATE prices SET price = price * ?
 
1117           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1118           WHERE $where) AND (pricegroup_id = ?)|;
 
1119   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
 
1121   for my $i (1 .. $form->{price_rows}) {
 
1122     next if ($form->{"price_$i"} eq "");
 
1124     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
 
1126     if ($form->{"pricegroup_type_$i"} eq "percent") {
 
1127       do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1129       do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
 
1134   $sth_multiply->finish();
 
1136   my $rc= $dbh->commit;
 
1139   $main::lxdebug->leave_sub();
 
1145   $main::lxdebug->enter_sub();
 
1147   my ($self, $module, $myconfig, $form) = @_;
 
1149   # connect to database
 
1150   my $dbh = $form->dbconnect($myconfig);
 
1152   my @values = ('%' . $module . '%');
 
1156       qq|SELECT c.accno, c.description, c.link, c.id,
 
1157            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
 
1158          FROM chart c, parts p
 
1159          WHERE (c.link LIKE ?) AND (p.id = ?)
 
1161     push(@values, conv_i($form->{id}));
 
1165       qq|SELECT c.accno, c.description, c.link, c.id,
 
1166            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
 
1167          FROM chart c, defaults d
 
1172   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1173   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1174     foreach my $key (split(/:/, $ref->{link})) {
 
1175       if ($key =~ /\Q$module\E/) {
 
1176         if (   ($ref->{id} eq $ref->{inventory_accno_id})
 
1177             || ($ref->{id} eq $ref->{income_accno_id})
 
1178             || ($ref->{id} eq $ref->{expense_accno_id})) {
 
1179           push @{ $form->{"${module}_links"}{$key} },
 
1180             { accno       => $ref->{accno},
 
1181               description => $ref->{description},
 
1182               selected    => "selected" };
 
1183           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
 
1185           push @{ $form->{"${module}_links"}{$key} },
 
1186             { accno       => $ref->{accno},
 
1187               description => $ref->{description},
 
1195   # get buchungsgruppen
 
1196   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
 
1199   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
 
1202     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
 
1206   $main::lxdebug->leave_sub();
 
1209 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
 
1211   $main::lxdebug->enter_sub();
 
1213   my ($self, $myconfig, $form, $sortorder) = @_;
 
1214   my $dbh   = $form->dbconnect($myconfig);
 
1215   my $order = qq| p.partnumber|;
 
1216   my $where = qq|1 = 1|;
 
1219   if ($sortorder eq "all") {
 
1220     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
 
1221     push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
 
1223   } elsif ($sortorder eq "partnumber") {
 
1224     $where .= qq| AND (partnumber ILIKE ?)|;
 
1225     push(@values, '%' . $form->{partnumber} . '%');
 
1227   } elsif ($sortorder eq "description") {
 
1228     $where .= qq| AND (description ILIKE ?)|;
 
1229     push(@values, '%' . $form->{description} . '%');
 
1230     $order = "description";
 
1235     qq|SELECT id, partnumber, description, unit, sellprice
 
1237        WHERE $where ORDER BY $order|;
 
1239   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1242   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1243     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
 
1248     $form->{"id_$j"}          = $ref->{id};
 
1249     $form->{"partnumber_$j"}  = $ref->{partnumber};
 
1250     $form->{"description_$j"} = $ref->{description};
 
1251     $form->{"unit_$j"}        = $ref->{unit};
 
1252     $form->{"sellprice_$j"}   = $ref->{sellprice};
 
1253     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
 
1259   $main::lxdebug->leave_sub();
 
1264 # gets sum of sold part with part_id
 
1266   $main::lxdebug->enter_sub();
 
1268   my ($dbh, $id) = @_;
 
1270   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
 
1271   my ($sum) = selectrow_query($form, $dbh, $query, conv_i($id));
 
1274   $main::lxdebug->leave_sub();
 
1277 }    #end get_soldtotal
 
1279 sub retrieve_languages {
 
1280   $main::lxdebug->enter_sub();
 
1282   my ($self, $myconfig, $form) = @_;
 
1284   # connect to database
 
1285   my $dbh = $form->dbconnect($myconfig);
 
1290   if ($form->{language_values} ne "") {
 
1292       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
 
1294          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
 
1295          ORDER BY lower(l.description)|;
 
1296     @values = (conv_i($form->{id}));
 
1299     $query = qq|SELECT id, description
 
1301                 ORDER BY lower(description)|;
 
1304   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
 
1308   $main::lxdebug->leave_sub();
 
1313 sub follow_account_chain {
 
1314   $main::lxdebug->enter_sub(2);
 
1316   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
 
1318   my @visited_accno_ids = ($accno_id);
 
1323     qq|SELECT c.new_chart_id, date($transdate) >= c.valid_from AS is_valid, | .
 
1326     qq|LEFT JOIN chart cnew ON c.new_chart_id = cnew.id | .
 
1327     qq|WHERE (c.id = ?) AND NOT c.new_chart_id ISNULL AND (c.new_chart_id > 0)|;
 
1328   $sth = prepare_query($form, $dbh, $query);
 
1331     do_statement($form, $sth, $query, $accno_id);
 
1332     $ref = $sth->fetchrow_hashref();
 
1333     last unless ($ref && $ref->{"is_valid"} &&
 
1334                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
 
1335     $accno_id = $ref->{"new_chart_id"};
 
1336     $accno = $ref->{"accno"};
 
1337     push(@visited_accno_ids, $accno_id);
 
1340   $main::lxdebug->leave_sub(2);
 
1342   return ($accno_id, $accno);
 
1345 sub retrieve_accounts {
 
1346   $main::lxdebug->enter_sub(2);
 
1348   my ($self, $myconfig, $form, $parts_id, $index) = @_;
 
1350   my ($query, $sth, $dbh);
 
1352   $form->{"taxzone_id"} *= 1;
 
1354   $dbh = $form->get_standard_dbh($myconfig);
 
1357   if ($form->{type} eq "invoice") {
 
1358     if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
 
1359       $transdate = $form->{invdate};
 
1361       $transdate = $form->{deliverydate};
 
1363   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
 
1364     $transdate = $form->{invdate};
 
1366     $transdate = $form->{transdate};
 
1369   if ($transdate eq "") {
 
1370     $transdate = "current_date";
 
1372     $transdate = $dbh->quote($transdate);
 
1377     qq|  p.inventory_accno_id AS is_part, | .
 
1378     qq|  bg.inventory_accno_id, | .
 
1379     qq|  bg.income_accno_id_$form->{taxzone_id} AS income_accno_id, | .
 
1380     qq|  bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id, | .
 
1381     qq|  c1.accno AS inventory_accno, | .
 
1382     qq|  c2.accno AS income_accno, | .
 
1383     qq|  c3.accno AS expense_accno | .
 
1385     qq|LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id | .
 
1386     qq|LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id | .
 
1387     qq|LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id | .
 
1388     qq|LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id | .
 
1390   my $ref = selectfirst_hashref_query($form, $dbh, $query, $parts_id);
 
1392   return $main::lxdebug->leave_sub(2) if (!$ref);
 
1394   $ref->{"inventory_accno_id"} = undef unless ($ref->{"is_part"});
 
1397   foreach my $type (qw(inventory income expense)) {
 
1398     next unless ($ref->{"${type}_accno_id"});
 
1399     ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
 
1400       $self->follow_account_chain($form, $dbh, $transdate,
 
1401                                   $ref->{"${type}_accno_id"},
 
1402                                   $ref->{"${type}_accno"});
 
1405   map({ $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} }
 
1406       qw(inventory income expense));
 
1408   my $inc_exp = $form->{"vc"} eq "customer" ? "income" : "expense";
 
1409   my $accno_id = $accounts{"${inc_exp}_accno_id"};
 
1412     qq|SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber | .
 
1414     qq|LEFT JOIN chart c ON c.id = t.chart_id | .
 
1415     qq|WHERE t.id IN | .
 
1416     qq|  (SELECT tk.tax_id | .
 
1417     qq|   FROM taxkeys tk | .
 
1418     qq|   WHERE tk.chart_id = ? AND startdate <= | . quote_db_date($transdate) .
 
1419     qq|   ORDER BY startdate DESC LIMIT 1) |;
 
1420   $ref = selectfirst_hashref_query($form, $dbh, $query, $accno_id);
 
1423     $main::lxdebug->leave_sub(2);
 
1427   $form->{"taxaccounts_$index"} = $ref->{"accno"};
 
1428   if ($form->{"taxaccounts"} !~ /$ref->{accno}/) {
 
1429     $form->{"taxaccounts"} .= "$ref->{accno} ";
 
1431   map({ $form->{"$ref->{accno}_${_}"} = $ref->{$_}; }
 
1432       qw(rate description taxnumber));
 
1434 #   $main::lxdebug->message(0, "formvars: rate " . $form->{"$ref->{accno}_rate"} .
 
1435 #                           " description " . $form->{"$ref->{accno}_description"} .
 
1436 #                           " taxnumber " . $form->{"$ref->{accno}_taxnumber"} .
 
1437 #                           " || taxaccounts_$index " . $form->{"taxaccounts_$index"} .
 
1438 #                           " || taxaccounts " . $form->{"taxaccounts"});
 
1440   $main::lxdebug->leave_sub(2);
 
1443 sub get_basic_part_info {
 
1444   $main::lxdebug->enter_sub();
 
1449   Common::check_params(\%params, qw(id));
 
1451   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
 
1454     $main::lxdebug->leave_sub();
 
1458   my $myconfig = \%main::myconfig;
 
1459   my $form     = $main::form;
 
1461   my $dbh      = $form->get_standard_dbh($myconfig);
 
1463   my $query    = qq|SELECT id, partnumber, description, unit FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
 
1465   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
 
1467   if ('' eq ref $params{id}) {
 
1468     $info = $info->[0] || { };
 
1470     $main::lxdebug->leave_sub();
 
1474   my %info_map = map { $_->{id} => $_ } @{ $info };
 
1476   $main::lxdebug->leave_sub();
 
1481 sub prepare_parts_for_printing {
 
1482   $main::lxdebug->enter_sub();
 
1487   my $myconfig = \%main::myconfig;
 
1488   my $form     = $main::form;
 
1490   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1492   my $prefix   = $params{prefix} || 'id_';
 
1493   my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
 
1495   my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
 
1498     $main::lxdebug->leave_sub();
 
1502   my $placeholders = join ', ', ('?') x scalar(@part_ids);
 
1503   my $query        = qq|SELECT mm.parts_id, mm.model, v.name AS make
 
1505                         LEFT JOIN vendor v ON (mm.make = cast (v.id as text))
 
1506                         WHERE mm.parts_id IN ($placeholders)|;
 
1510   my $sth          = prepare_execute_query($form, $dbh, $query, @part_ids);
 
1512   while (my $ref = $sth->fetchrow_hashref()) {
 
1513     $makemodel{$ref->{parts_id}} ||= [];
 
1514     push @{ $makemodel{$ref->{parts_id}} }, $ref;
 
1519   my @columns = qw(ean);
 
1521   $query      = qq|SELECT id, | . join(', ', @columns) . qq|
 
1523                    WHERE id IN ($placeholders)|;
 
1525   my %data    = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
 
1527   map { $form->{$_} = [] } (qw(make model), @columns);
 
1529   foreach my $i (1 .. $rowcount) {
 
1530     my $id = $form->{"${prefix}${i}"};
 
1534     foreach (@columns) {
 
1535       push @{ $form->{$_} }, $data{$id}->{$_};
 
1538     push @{ $form->{make} },  [];
 
1539     push @{ $form->{model} }, [];
 
1541     next if (!$makemodel{$id});
 
1543     foreach my $ref (@{ $makemodel{$id} }) {
 
1544       map { push @{ $form->{$_}->[-1] }, $ref->{$_} } qw(make model);
 
1548   $main::lxdebug->leave_sub();