1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (C) 1998-2002
 
  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 invoicing module
 
  33 #======================================================================
 
  43   $main::lxdebug->enter_sub();
 
  45   my ($self, $myconfig, $form, $locale) = @_;
 
  47   $form->{duedate} = $form->{invdate} unless ($form->{duedate});
 
  50   my $dbh = $form->dbconnect($myconfig);
 
  52   my $query = qq|SELECT date '$form->{duedate}' - date '$form->{invdate}'
 
  55   my $sth = $dbh->prepare($query);
 
  56   $sth->execute || $form->dberror($query);
 
  58   ($form->{terms}) = $sth->fetchrow_array;
 
  61   my (@project_ids, %projectnumbers);
 
  63   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
 
  65   # sort items by partsgroup
 
  66   for $i (1 .. $form->{rowcount}) {
 
  68     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
  69       $partsgroup = $form->{"partsgroup_$i"};
 
  71     push @partsgroup, [$i, $partsgroup];
 
  72     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
 
  76     $query = "SELECT id, projectnumber FROM project WHERE id IN (" .
 
  77       join(", ", map({ "?" } @project_ids)) . ")";
 
  78     $sth = $dbh->prepare($query);
 
  79     $sth->execute(@project_ids) ||
 
  80       $form->dberror($query . " (" . join(", ", @project_ids) . ")");
 
  81     while (my $ref = $sth->fetchrow_hashref()) {
 
  82       $projectnumbers{$ref->{id}} = $ref->{projectnumber};
 
  87   $form->{"globalprojectnumber"} =
 
  88     $projectnumbers{$form->{"globalproject_id"}};
 
  95   my %oid = ('Pg'     => 'oid',
 
  98   # sort items by partsgroup
 
  99   for $i (1 .. $form->{rowcount}) {
 
 101     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
 102       $partsgroup = $form->{"partsgroup_$i"};
 
 104     push @partsgroup, [$i, $partsgroup];
 
 117   my $nodiscount_subtotal = 0;
 
 118   my $discount_subtotal = 0;
 
 120   my $subtotal_header = 0;
 
 124     qw(runningnumber number description longdescription qty ship unit bin
 
 125        deliverydate_oe ordnumber_oe transdate_oe licensenumber validuntil
 
 126        partnotes serialnumber reqdate sellprice listprice netprice
 
 127        discount p_discount discount_sub nodiscount_sub
 
 128        linetotal  nodiscount_linetotal tax_rate projectnumber);
 
 131     qw(taxbase tax taxdescription taxrate taxnumber);
 
 133   map({ $form->{$_} = [] } (@arrays, @tax_arrays));
 
 135   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
 138     if ($item->[1] ne $sameitem) {
 
 139       push(@{ $form->{description} }, qq|$item->[1]|);
 
 140       $sameitem = $item->[1];
 
 142       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 145     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 147     if ($form->{"id_$i"} != 0) {
 
 149       # add number, description and qty to $form->{number},
 
 150       if ($form->{"subtotal_$i"} && !$subtotal_header) {
 
 151         $subtotal_header = $i;
 
 152         $position = int($position);
 
 155       } elsif ($subtotal_header) {
 
 157         $position = int($position);
 
 158         $position = $position.".".$subposition;
 
 160         $position = int($position);
 
 163       push(@{ $form->{runningnumber} }, $position);
 
 164       push(@{ $form->{number} },        qq|$form->{"partnumber_$i"}|);
 
 165       push(@{ $form->{serialnumber} },  qq|$form->{"serialnumber_$i"}|);
 
 166       push(@{ $form->{bin} },           qq|$form->{"bin_$i"}|);
 
 167       push(@{ $form->{"partnotes"} },   qq|$form->{"partnotes_$i"}|);
 
 168       push(@{ $form->{description} },   qq|$form->{"description_$i"}|);
 
 169       push(@{ $form->{longdescription} },   qq|$form->{"longdescription_$i"}|);
 
 170       push(@{ $form->{qty} },
 
 171            $form->format_amount($myconfig, $form->{"qty_$i"}));
 
 172       push(@{ $form->{unit} },            qq|$form->{"unit_$i"}|);
 
 173       push(@{ $form->{deliverydate_oe} }, qq|$form->{"deliverydate_$i"}|);
 
 175       push(@{ $form->{sellprice} },    $form->{"sellprice_$i"});
 
 176       push(@{ $form->{ordnumber_oe} }, qq|$form->{"ordnumber_$i"}|);
 
 177       push(@{ $form->{transdate_oe} }, qq|$form->{"transdate_$i"}|);
 
 178       push(@{ $form->{invnumber} }, qq|$form->{"invnumber"}|);
 
 179       push(@{ $form->{invdate} }, qq|$form->{"invdate"}|);
 
 181       if ($form->{lizenzen}) {
 
 182         if ($form->{"licensenumber_$i"}) {
 
 184             qq|SELECT l.licensenumber, l.validuntil FROM license l WHERE l.id = $form->{"licensenumber_$i"}|;
 
 185           $sth = $dbh->prepare($query);
 
 186           $sth->execute || $form->dberror($query);
 
 188           ($licensenumber, $validuntil) = $sth->fetchrow_array;
 
 189           push(@{ $form->{licensenumber} }, $licensenumber);
 
 190           push(@{ $form->{validuntil} },
 
 191                $locale->date($myconfig, $validuntil, 0));
 
 194           push(@{ $form->{licensenumber} }, "");
 
 195           push(@{ $form->{validuntil} },    "");
 
 200       push(@{ $form->{listprice} }, $form->{"listprice_$i"});
 
 202       my $sellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 203       my ($dec) = ($sellprice =~ /\.(\d+)/);
 
 205       my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 209                             $sellprice * $form->parse_amount($myconfig,
 
 210                                                  $form->{"discount_$i"}) / 100,
 
 214         $form->round_amount($form->{"qty_$i"} * $i_discount, $decimalplaces);
 
 216       # keep a netprice as well, (sellprice - discount)
 
 217       $form->{"netprice_$i"} = $sellprice - $i_discount;
 
 219       push(@{ $form->{netprice} },
 
 220            ($form->{"netprice_$i"} != 0)
 
 221            ? $form->format_amount(
 
 222                                  $myconfig, $form->{"netprice_$i"},
 
 228         $form->round_amount($form->{"qty_$i"} * $form->{"netprice_$i"}, 2);
 
 230       my $nodiscount_linetotal =
 
 231         $form->round_amount($form->{"qty_$i"} * $sellprice, 2);
 
 235         ? $form->format_amount($myconfig, $discount * -1, $decimalplaces)
 
 237       $linetotal = ($linetotal != 0) ? $linetotal : " ";
 
 239       push(@{ $form->{discount} },   $discount);
 
 240       push(@{ $form->{p_discount} }, $form->{"discount_$i"});
 
 241       if (($form->{"discount_$i"} ne "") && ($form->{"discount_$i"} != 0)) {
 
 242         $form->{discount_p} = $form->{"discount_$i"};
 
 244       $form->{total} += $linetotal;
 
 245       $discount_subtotal += $linetotal;
 
 246       $form->{nodiscount_total} += $nodiscount_linetotal;
 
 247       $nodiscount_subtotal += $nodiscount_linetotal;
 
 248       $form->{discount_total} += $form->parse_amount($myconfig, $discount);
 
 250       if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
 
 251         $discount_subtotal = $form->format_amount($myconfig, $discount_subtotal, 2);
 
 252         push(@{ $form->{discount_sub} },  $discount_subtotal);
 
 253         $nodiscount_subtotal = $form->format_amount($myconfig, $nodiscount_subtotal, 2);
 
 254         push(@{ $form->{nodiscount_sub} }, $nodiscount_subtotal);
 
 255         $discount_subtotal = 0;
 
 256         $nodiscount_subtotal = 0;
 
 257         $subtotal_header = 0;
 
 259         push(@{ $form->{discount_sub} }, "");
 
 260         push(@{ $form->{nodiscount_sub} }, "");
 
 263       if ($linetotal == $netto_linetotal) {
 
 264         $nodiscount += $linetotal;
 
 267       push(@{ $form->{linetotal} },
 
 268            $form->format_amount($myconfig, $linetotal, 2));
 
 269       push(@{ $form->{nodiscount_linetotal} },
 
 270            $form->format_amount($myconfig, $nodiscount_linetotal, 2));
 
 272       push(@{ $form->{projectnumber} }, $projectnumbers{$form->{"project_id_$i"}});
 
 274       @taxaccounts = split / /, $form->{"taxaccounts_$i"};
 
 278       map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
 
 280       if ($form->{taxincluded}) {
 
 283         $taxamount = $linetotal * $taxrate / (1 + $taxrate);
 
 284         $taxbase = $linetotal - $taxamount;
 
 286         $taxamount = $linetotal * $taxrate;
 
 287         $taxbase   = $linetotal;
 
 290       if ($form->round_amount($taxrate, 7) == 0) {
 
 291         if ($form->{taxincluded}) {
 
 292           foreach $item (@taxaccounts) {
 
 294               $form->round_amount($linetotal * $form->{"${item}_rate"} /
 
 295                                     (1 + abs($form->{"${item}_rate"})),
 
 298             $taxaccounts{$item} += $taxamount;
 
 299             $taxdiff            += $taxamount;
 
 301             $taxbase{$item} += $taxbase;
 
 303           $taxaccounts{ $taxaccounts[0] } += $taxdiff;
 
 305           foreach $item (@taxaccounts) {
 
 306             $taxaccounts{$item} += $linetotal * $form->{"${item}_rate"};
 
 307             $taxbase{$item}     += $taxbase;
 
 311         foreach $item (@taxaccounts) {
 
 312           $taxaccounts{$item} +=
 
 313             $taxamount * $form->{"${item}_rate"} / $taxrate;
 
 314           $taxbase{$item} += $taxbase;
 
 317       $tax_rate = $taxrate * 100;
 
 318       push(@{ $form->{tax_rate} }, qq|$tax_rate|);
 
 319       if ($form->{"assembly_$i"}) {
 
 322         # get parts and push them onto the stack
 
 324         if ($form->{groupitems}) {
 
 326             qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
 
 328           $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
 
 331         $query = qq|SELECT p.partnumber, p.description, p.unit, a.qty,
 
 334                     JOIN parts p ON (a.parts_id = p.id)
 
 335                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 337                     AND a.id = '$form->{"id_$i"}'
 
 339         $sth = $dbh->prepare($query);
 
 340         $sth->execute || $form->dberror($query);
 
 342         while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
 343           if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
 344             map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 345             $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
 346             push(@{ $form->{description} }, $sameitem);
 
 349           map { $form->{"a_$_"} = $ref->{$_} } qw(partnumber description);
 
 351           push(@{ $form->{description} },
 
 352                $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}
 
 354                  . qq| -- $form->{"a_partnumber"}, $form->{"a_description"}|);
 
 355           map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
 
 363   foreach my $item (sort keys %taxaccounts) {
 
 364     push(@{ $form->{taxbase} },
 
 365           $form->format_amount($myconfig, $taxbase{$item}, 2));
 
 367     $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
 
 369     push(@{ $form->{tax} }, $form->format_amount($myconfig, $taxamount, 2));
 
 370     push(@{ $form->{taxdescription} }, $form->{"${item}_description"});
 
 371     push(@{ $form->{taxrate} },
 
 372           $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
 
 373     push(@{ $form->{taxnumber} }, $form->{"${item}_taxnumber"});
 
 376   for my $i (1 .. $form->{paidaccounts}) {
 
 377     if ($form->{"paid_$i"}) {
 
 378       push(@{ $form->{payment} }, $form->{"paid_$i"});
 
 379       my ($accno, $description) = split /--/, $form->{"AR_paid_$i"};
 
 380       push(@{ $form->{paymentaccount} }, $description);
 
 381       push(@{ $form->{paymentdate} },    $form->{"datepaid_$i"});
 
 382       push(@{ $form->{paymentsource} },  $form->{"source_$i"});
 
 384       $form->{paid} += $form->parse_amount($myconfig, $form->{"paid_$i"});
 
 388   $form->{subtotal} = $form->format_amount($myconfig, $form->{total}, 2);
 
 389   $yesdiscount = $form->{nodiscount_total} - $nodiscount;
 
 390   $form->{nodiscount_subtotal} = $form->format_amount($myconfig, $form->{nodiscount_total}, 2);
 
 391   $form->{discount_total} = $form->format_amount($myconfig, $form->{discount_total}, 2);
 
 392   $form->{nodiscount} = $form->format_amount($myconfig, $nodiscount, 2);
 
 393   $form->{yesdiscount} = $form->format_amount($myconfig, $yesdiscount, 2);
 
 396     ($form->{taxincluded}) ? $form->{total} : $form->{total} + $tax;
 
 398     $form->format_amount($myconfig, $form->{invtotal} - $form->{paid}, 2);
 
 400   $form->{invtotal} = $form->format_amount($myconfig, $form->{invtotal}, 2);
 
 401   $form->{paid} = $form->format_amount($myconfig, $form->{paid}, 2);
 
 402   $form->set_payment_options($myconfig, $form->{invdate});
 
 404   $form->{username} = $myconfig->{name};
 
 408   $main::lxdebug->leave_sub();
 
 411 sub project_description {
 
 412   $main::lxdebug->enter_sub();
 
 414   my ($self, $dbh, $id) = @_;
 
 416   my $query = qq|SELECT p.description
 
 419   my $sth = $dbh->prepare($query);
 
 420   $sth->execute || $form->dberror($query);
 
 422   ($_) = $sth->fetchrow_array;
 
 426   $main::lxdebug->leave_sub();
 
 431 sub customer_details {
 
 432   $main::lxdebug->enter_sub();
 
 434   my ($self, $myconfig, $form, @wanted_vars) = @_;
 
 436   # connect to database
 
 437   my $dbh = $form->dbconnect($myconfig);
 
 439   # get contact id, set it if nessessary
 
 443   if ($form->{cp_id}) {
 
 444     $contact = "and cp.cp_id = $form->{cp_id}";
 
 447   # get rest for the customer
 
 448   my $query = qq|SELECT ct.*, cp.*, ct.notes as customernotes
 
 450                  LEFT JOIN contacts cp on ct.id = cp.cp_cv_id
 
 451                  WHERE ct.id = $form->{customer_id} $contact order by cp.cp_id limit 1|;
 
 452   my $sth = $dbh->prepare($query);
 
 453   $sth->execute || $form->dberror($query);
 
 455   $ref = $sth->fetchrow_hashref(NAME_lc);
 
 457   # remove id and taxincluded before copy back
 
 458   delete @$ref{qw(id taxincluded)};
 
 460   @wanted_vars = grep({ $_ } @wanted_vars);
 
 461   if (scalar(@wanted_vars) > 0) {
 
 463     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
 
 464     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
 
 467   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 470   if ($form->{delivery_customer_id}) {
 
 471     my $query = qq|SELECT ct.*, ct.notes as customernotes
 
 473                  WHERE ct.id = $form->{delivery_customer_id} limit 1|;
 
 474     my $sth = $dbh->prepare($query);
 
 475     $sth->execute || $form->dberror($query);
 
 477     $ref = $sth->fetchrow_hashref(NAME_lc);
 
 480     map { $form->{"dc_$_"} = $ref->{$_} } keys %$ref;
 
 483   if ($form->{delivery_vendor_id}) {
 
 484     my $query = qq|SELECT ct.*, ct.notes as customernotes
 
 486                  WHERE ct.id = $form->{delivery_vendor_id} limit 1|;
 
 487     my $sth = $dbh->prepare($query);
 
 488     $sth->execute || $form->dberror($query);
 
 490     $ref = $sth->fetchrow_hashref(NAME_lc);
 
 493     map { $form->{"dv_$_"} = $ref->{$_} } keys %$ref;
 
 497   $main::lxdebug->leave_sub();
 
 501   $main::lxdebug->enter_sub();
 
 503   my ($self, $myconfig, $form) = @_;
 
 505   # connect to database, turn off autocommit
 
 506   my $dbh = $form->dbconnect_noauto($myconfig);
 
 508   my ($query, $sth, $null, $project_id, $deliverydate);
 
 509   my $exchangerate = 0;
 
 511   ($null, $form->{employee_id}) = split /--/, $form->{employee};
 
 512   unless ($form->{employee_id}) {
 
 513     $form->get_employee($dbh);
 
 516   $form->{payment_id} *= 1;
 
 517   $form->{language_id} *= 1;
 
 518   $form->{taxzone_id} *= 1;
 
 519   $form->{delivery_customer_id} *= 1;
 
 520   $form->{delivery_vendor_id} *= 1;
 
 521   $form->{storno} *= 1;
 
 522   $form->{shipto_id} *= 1;
 
 525   ($null, $form->{department_id}) = split(/--/, $form->{department});
 
 526   $form->{department_id} *= 1;
 
 528   my $service_units = AM->retrieve_units($myconfig,$form,"service");
 
 529   my $part_units = AM->retrieve_units($myconfig,$form,"dimension");
 
 535     &reverse_invoice($dbh, $form);
 
 538     my $uid = rand() . time;
 
 540     $uid .= $form->{login};
 
 542     $uid = substr($uid, 2, 75);
 
 544     $query = qq|INSERT INTO ar (invnumber, employee_id)
 
 545                 VALUES ('$uid', $form->{employee_id})|;
 
 546     $dbh->do($query) || $form->dberror($query);
 
 548     $query = qq|SELECT a.id FROM ar a
 
 549                 WHERE a.invnumber = '$uid'|;
 
 550     $sth = $dbh->prepare($query);
 
 551     $sth->execute || $form->dberror($query);
 
 553     ($form->{id}) = $sth->fetchrow_array;
 
 557   map { $form->{$_} =~ s/\'/\'\'/g }
 
 558     (qw(invnumber shippingpoint shipvia notes intnotes message));
 
 560   my ($netamount, $invoicediff) = (0, 0);
 
 561   my ($amount, $linetotal, $lastincomeaccno);
 
 563   if ($form->{currency} eq $form->{defaultcurrency}) {
 
 564     $form->{exchangerate} = 1;
 
 567       $form->check_exchangerate($myconfig, $form->{currency},
 
 568                                 $form->{transdate}, 'buy');
 
 571   $form->{exchangerate} =
 
 574     : $form->parse_amount($myconfig, $form->{exchangerate});
 
 576   $form->{expense_inventory} = "";
 
 578   foreach my $i (1 .. $form->{rowcount}) {
 
 579     if ($form->{type} eq "credit_note") {
 
 580       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"}) * -1;
 
 581       $form->{shipped} = 1;   
 
 583       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 588     if ($form->{storno}) {
 
 589       $form->{"qty_$i"} *= -1;
 
 592     if ($form->{"id_$i"}) {
 
 595       $query = qq|SELECT p.unit
 
 597                   WHERE p.id = $form->{"id_$i"}|;
 
 598       $sth = $dbh->prepare($query);
 
 599       $sth->execute || $form->dberror($query);
 
 601       my ($item_unit) = $sth->fetchrow_array();
 
 604       if ($form->{"inventory_accno_$i"}) {
 
 605         if (defined($part_units->{$item_unit}->{factor}) && $part_units->{$item_unit}->{factor} ne '' && $part_units->{$item_unit}->{factor} ne '0') {
 
 606           $basefactor = $part_units->{$form->{"unit_$i"}}->{factor} / $part_units->{$item_unit}->{factor};
 
 610         $baseqty = $form->{"qty_$i"} * $basefactor;
 
 612         if (defined($service_units->{$item_unit}->{factor}) && $service_units->{$item_unit}->{factor} ne '' && $service_units->{$item_unit}->{factor} ne '0') {
 
 613           $basefactor = $service_units->{$form->{"unit_$i"}}->{factor} / $service_units->{$item_unit}->{factor};
 
 617         $baseqty = $form->{"qty_$i"} * $basefactor;
 
 620       map { $form->{"${_}_$i"} =~ s/\'/\'\'/g }
 
 621         (qw(partnumber description unit));
 
 623       # undo discount formatting
 
 624       $form->{"discount_$i"} =
 
 625         $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
 
 627       my ($allocated, $taxrate) = (0, 0);
 
 630       # keep entered selling price
 
 632         $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 634       my ($dec) = ($fxsellprice =~ /\.(\d+)/);
 
 636       my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 640         $form->round_amount($fxsellprice * $form->{"discount_$i"},
 
 642       $form->{"sellprice_$i"} = $fxsellprice - $discount;
 
 645       map { $taxrate += $form->{"${_}_rate"} } split / /,
 
 646         $form->{"taxaccounts_$i"};
 
 648       # round linetotal to 2 decimal places
 
 650         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
 
 652       if ($form->{taxincluded}) {
 
 653         $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
 
 654         $form->{"sellprice_$i"} =
 
 655           $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
 
 657         $taxamount = $linetotal * $taxrate;
 
 660       $netamount += $linetotal;
 
 662       if ($taxamount != 0) {
 
 664           $form->{amount}{ $form->{id} }{$_} +=
 
 665             $taxamount * $form->{"${_}_rate"} / $taxrate
 
 666         } split / /, $form->{"taxaccounts_$i"};
 
 669       # add amount to income, $form->{amount}{trans_id}{accno}
 
 671         $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
 
 674         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) *
 
 675         $form->{exchangerate};
 
 676       $linetotal = $form->round_amount($linetotal, 2);
 
 678       # this is the difference from the inventory
 
 679       $invoicediff += ($amount - $linetotal);
 
 681       $form->{amount}{ $form->{id} }{ $form->{"income_accno_$i"} } +=
 
 684       $lastincomeaccno = $form->{"income_accno_$i"};
 
 686       # adjust and round sellprice
 
 687       $form->{"sellprice_$i"} =
 
 688         $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate},
 
 691       if ($form->{"inventory_accno_$i"} || $form->{"assembly_$i"}) {
 
 693         # adjust parts onhand quantity
 
 695         if ($form->{"assembly_$i"}) {
 
 697           # do not update if assembly consists of all services
 
 698           $query = qq|SELECT sum(p.inventory_accno_id)
 
 700                       JOIN assembly a ON (a.parts_id = p.id)
 
 701                       WHERE a.id = $form->{"id_$i"}|;
 
 702           $sth = $dbh->prepare($query);
 
 703           $sth->execute || $form->dberror($query);
 
 705           if ($sth->fetchrow_array) {
 
 706             $form->update_balance($dbh, "parts", "onhand",
 
 707                                   qq|id = $form->{"id_$i"}|,
 
 709               unless $form->{shipped};
 
 713           # record assembly item as allocated
 
 714           &process_assembly($dbh, $form, $form->{"id_$i"}, $baseqty);
 
 716           $form->update_balance($dbh, "parts", "onhand",
 
 717                                 qq|id = $form->{"id_$i"}|,
 
 719             unless $form->{shipped};
 
 721           $allocated = &cogs($dbh, $form, $form->{"id_$i"}, $baseqty, $basefactor, $i);
 
 726         ($form->{"deliverydate_$i"})
 
 727         ? qq|'$form->{"deliverydate_$i"}'|
 
 730       # get pricegroup_id and save it
 
 731       ($null, my $pricegroup_id) = split /--/, $form->{"sellprice_pg_$i"};
 
 733       my $subtotal = $form->{"subtotal_$i"} * 1;
 
 735       # save detail record in invoice table
 
 736       $query = qq|INSERT INTO invoice (trans_id, parts_id, description,longdescription, qty,
 
 737                   sellprice, fxsellprice, discount, allocated, assemblyitem,
 
 738                   unit, deliverydate, project_id, serialnumber, pricegroup_id,
 
 739                   ordnumber, transdate, cusordnumber, base_qty, subtotal)
 
 740                   VALUES ($form->{id}, $form->{"id_$i"},
 
 741                   '$form->{"description_$i"}', '$form->{"longdescription_$i"}', $form->{"qty_$i"},
 
 742                   $form->{"sellprice_$i"}, $fxsellprice,
 
 743                   $form->{"discount_$i"}, $allocated, 'f',
 
 744                   '$form->{"unit_$i"}', $deliverydate, | . conv_i($form->{"project_id_$i"}) . qq|,
 
 745                   '$form->{"serialnumber_$i"}', '$pricegroup_id',
 
 746                   '$form->{"ordnumber_$i"}', '$form->{"transdate_$i"}', '$form->{"cusordnumber_$i"}', $baseqty, '$subtotal')|;
 
 747       $dbh->do($query) || $form->dberror($query);
 
 749       if ($form->{lizenzen}) {
 
 750         if ($form->{"licensenumber_$i"}) {
 
 752             qq|SELECT i.id FROM invoice i WHERE i.trans_id=$form->{id} ORDER BY i.oid DESC LIMIT 1|;
 
 753           $sth = $dbh->prepare($query);
 
 754           $sth->execute || $form->dberror($query);
 
 756           ($invoice_row_id) = $sth->fetchrow_array;
 
 760             qq|INSERT INTO licenseinvoice (trans_id, license_id) VALUES ($invoice_row_id, $form->{"licensenumber_$i"})|;
 
 761           $dbh->do($query) || $form->dberror($query);
 
 768   $form->{datepaid} = $form->{invdate};
 
 770   # total payments, don't move we need it here
 
 771   for my $i (1 .. $form->{paidaccounts}) {
 
 772     if ($form->{type} eq "credit_note") {
 
 773       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"}) * -1;
 
 775       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
 
 777     $form->{paid} += $form->{"paid_$i"};
 
 778     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
 
 781   my ($tax, $diff) = (0, 0);
 
 783   $netamount = $form->round_amount($netamount, 2);
 
 785   # figure out rounding errors for total amount vs netamount + taxes
 
 786   if ($form->{taxincluded}) {
 
 788     $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
 
 789     $diff += $amount - $netamount * $form->{exchangerate};
 
 790     $netamount = $amount;
 
 792     foreach my $item (split / /, $form->{taxaccounts}) {
 
 793       $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
 
 794       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
 
 795       $tax += $form->{amount}{ $form->{id} }{$item};
 
 796       $netamount -= $form->{amount}{ $form->{id} }{$item};
 
 799     $invoicediff += $diff;
 
 800     ######## this only applies to tax included
 
 801     if ($lastincomeaccno) {
 
 802       $form->{amount}{ $form->{id} }{$lastincomeaccno} += $invoicediff;
 
 806     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
 
 807     $diff      = $amount - $netamount * $form->{exchangerate};
 
 808     $netamount = $amount;
 
 809     foreach my $item (split / /, $form->{taxaccounts}) {
 
 810       $form->{amount}{ $form->{id} }{$item} =
 
 811         $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
 
 814                  $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate},
 
 817         $amount - $form->{amount}{ $form->{id} }{$item} *
 
 818         $form->{exchangerate};
 
 819       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
 
 820       $tax += $form->{amount}{ $form->{id} }{$item};
 
 824   $form->{amount}{ $form->{id} }{ $form->{AR} } = $netamount + $tax;
 
 826     $form->round_amount($form->{paid} * $form->{exchangerate} + $diff, 2);
 
 829   $form->{amount}{ $form->{id} }{ $form->{AR} } *= -1;
 
 831   # update exchangerate
 
 832   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 833     $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate},
 
 834                                $form->{exchangerate}, 0);
 
 837   $project_id = conv_i($form->{"globalproject_id"});
 
 839   foreach my $trans_id (keys %{ $form->{amount} }) {
 
 840     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
 
 841       next unless ($form->{expense_inventory} =~ /$accno/);
 
 843           ($form->{amount}{$trans_id}{$accno} =
 
 844            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
 
 847         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
 848                     transdate, taxkey, project_id)
 
 849                     VALUES ($trans_id, (SELECT c.id FROM chart c
 
 850                                         WHERE c.accno = '$accno'),
 
 851                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
 
 852                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'), ?)|;
 
 853         do_query($form, $dbh, $query, $project_id);
 
 854         $form->{amount}{$trans_id}{$accno} = 0;
 
 858     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
 
 860           ($form->{amount}{$trans_id}{$accno} =
 
 861            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
 
 864         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
 865                     transdate, taxkey, project_id)
 
 866                     VALUES ($trans_id, (SELECT id FROM chart
 
 867                                         WHERE accno = '$accno'),
 
 868                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
 
 869                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'), ?)|;
 
 870         do_query($form, $dbh, $query, $project_id);
 
 875   # deduct payment differences from diff
 
 876   for my $i (1 .. $form->{paidaccounts}) {
 
 877     if ($form->{"paid_$i"} != 0) {
 
 879         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
 
 880       $diff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
 
 884   # force AR entry if 0
 
 885   #  $form->{amount}{$form->{id}}{$form->{AR}} = 1 if ($form->{amount}{$form->{id}}{$form->{AR}} == 0);
 
 887   # record payments and offsetting AR
 
 888   if (!$form->{storno}) {
 
 889     for my $i (1 .. $form->{paidaccounts}) {
 
 891       if ($form->{"paid_$i"} != 0) {
 
 892         my ($accno) = split /--/, $form->{"AR_paid_$i"};
 
 893         $form->{"datepaid_$i"} = $form->{invdate}
 
 894           unless ($form->{"datepaid_$i"});
 
 895         $form->{datepaid} = $form->{"datepaid_$i"};
 
 899         if ($form->{currency} eq $form->{defaultcurrency}) {
 
 900           $form->{"exchangerate_$i"} = 1;
 
 903             $form->check_exchangerate($myconfig, $form->{currency},
 
 904                                       $form->{"datepaid_$i"}, 'buy');
 
 906           $form->{"exchangerate_$i"} =
 
 909             : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
 914           $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $diff,
 
 917         if ($form->{amount}{ $form->{id} }{ $form->{AR} } != 0) {
 
 918           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
 919                       transdate, project_id)
 
 920                       VALUES ($form->{id}, (SELECT c.id FROM chart c
 
 921                                           WHERE c.accno = '$form->{AR}'),
 
 922                       $amount, '$form->{"datepaid_$i"}', ?)|;
 
 923           do_query($form, $dbh, $query, $project_id);
 
 927         $form->{"paid_$i"} *= -1;
 
 929         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
 
 931                     VALUES ($form->{id}, (SELECT c.id FROM chart c
 
 932                                         WHERE c.accno = '$accno', project_id),
 
 933                     $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
 
 934                     '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
 
 935         do_query($form, $dbh, $query, $project_id);
 
 937         # exchangerate difference
 
 938         $form->{fx}{$accno}{ $form->{"datepaid_$i"} } +=
 
 939           $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $diff;
 
 943           $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
 
 944           $form->{"exchangerate_$i"};
 
 946           $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
 
 949           $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
 
 955         # update exchange rate
 
 956         if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 957           $form->update_exchangerate($dbh, $form->{currency},
 
 958                                     $form->{"datepaid_$i"},
 
 959                                     $form->{"exchangerate_$i"}, 0);
 
 965   # record exchange rate differences and gains/losses
 
 966   foreach my $accno (keys %{ $form->{fx} }) {
 
 967     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
 
 969           ($form->{fx}{$accno}{$transdate} =
 
 970            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
 
 974         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
 975                     transdate, cleared, fx_transaction, project_id)
 
 977                            (SELECT c.id FROM chart c
 
 978                             WHERE c.accno = '$accno'),
 
 979                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1', ?)|;
 
 980         do_query($form, $dbh, $query, $project_id);
 
 985   $amount = $netamount + $tax;
 
 987   # set values which could be empty to 0
 
 989   $form->{taxincluded} *= 1;
 
 990   my $datepaid = ($form->{paid})    ? qq|'$form->{datepaid}'| : "NULL";
 
 991   my $duedate  = ($form->{duedate}) ? qq|'$form->{duedate}'|  : "NULL";
 
 993     ($form->{deliverydate}) ? qq|'$form->{deliverydate}'| : "NULL";
 
 995   # fill in subject if there is none
 
 996   $form->{subject} = qq|$form->{label} $form->{invnumber}|
 
 997     unless $form->{subject};
 
 999   # if there is a message stuff it into the intnotes
 
1000   my $cc  = "Cc: $form->{cc}\\r\n"   if $form->{cc};
 
1001   my $bcc = "Bcc: $form->{bcc}\\r\n" if $form->{bcc};
 
1002   my $now = scalar localtime;
 
1003   $form->{intnotes} .= qq|\r
 
1004 \r| if $form->{intnotes};
 
1006   $form->{intnotes} .= qq|[email]\r
 
1008 To: $form->{email}\r
 
1009 $cc${bcc}Subject: $form->{subject}\r
 
1011 Message: $form->{message}\r| if $form->{message};
 
1014   $query = qq|UPDATE ar set
 
1015               invnumber = '$form->{invnumber}',
 
1016               ordnumber = '$form->{ordnumber}',
 
1017               quonumber = '$form->{quonumber}',
 
1018               cusordnumber = '$form->{cusordnumber}',
 
1019               transdate = '$form->{invdate}',
 
1020               orddate = | . conv_dateq($form->{orddate}) . qq|,
 
1021               quodate = | . conv_dateq($form->{quodate}) . qq|,
 
1022               customer_id = $form->{customer_id},
 
1024               netamount = $netamount,
 
1025               paid = $form->{paid},
 
1026               datepaid = $datepaid,
 
1028               deliverydate = $deliverydate,
 
1030               shippingpoint = '$form->{shippingpoint}',
 
1031               shipvia = '$form->{shipvia}',
 
1032               terms = $form->{terms},
 
1033               notes = '$form->{notes}',
 
1034               intnotes = '$form->{intnotes}',
 
1035               taxincluded = '$form->{taxincluded}',
 
1036               curr = '$form->{currency}',
 
1037               department_id = $form->{department_id},
 
1038               payment_id = $form->{payment_id},
 
1039               type = '$form->{type}',
 
1040               language_id = $form->{language_id},
 
1041               taxzone_id = $form->{taxzone_id},
 
1042               shipto_id = $form->{shipto_id},
 
1043               delivery_customer_id = $form->{delivery_customer_id},
 
1044               delivery_vendor_id = $form->{delivery_vendor_id},
 
1045               employee_id = $form->{employee_id},
 
1046               storno = '$form->{storno}',
 
1047               globalproject_id = | . conv_i($form->{"globalproject_id"}, 'NULL') . qq|,
 
1048               cp_id = | . conv_i($form->{"cp_id"}, 'NULL') . qq|
 
1049               WHERE id = $form->{id}
 
1051   $dbh->do($query) || $form->dberror($query);
 
1053   if ($form->{storno}) {
 
1054     $query = qq| update ar set paid=paid+amount where id=$form->{storno_id}|;
 
1055     $dbh->do($query) || $form->dberror($query);
 
1056     $query = qq| update ar set storno='$form->{storno}' where id=$form->{storno_id}|;
 
1057     $dbh->do($query) || $form->dberror($query);
 
1058     $query = qq§ update ar set intnotes='Rechnung storniert am $form->{invdate} ' || intnotes where id=$form->{storno_id}§;
 
1059     $dbh->do($query) || $form->dberror($query);
 
1061     $query = qq| update ar set paid=amount where id=$form->{id}|;
 
1062     $dbh->do($query) || $form->dberror($query);
 
1065   $form->{pago_total} = $amount;
 
1068   $form->{name} = $form->{customer};
 
1069   $form->{name} =~ s/--$form->{customer_id}//;
 
1071   if (!$form->{shipto_id}) {
 
1072     $form->add_shipto($dbh, $form->{id}, "AR");
 
1075   # save printed, emailed and queued
 
1076   $form->save_status($dbh);
 
1078   Common::webdav_folder($form) if ($main::webdav);
 
1080   my $rc = $dbh->commit;
 
1083   $main::lxdebug->leave_sub();
 
1089   $main::lxdebug->enter_sub();
 
1091   my ($self, $myconfig, $form, $locale) = @_;
 
1093   # connect to database, turn off autocommit
 
1094   my $dbh = $form->dbconnect_noauto($myconfig);
 
1096   $form->{datepaid} = $form->{invdate};
 
1098   # total payments, don't move we need it here
 
1099   for my $i (1 .. $form->{paidaccounts}) {
 
1100     if ($form->{type} eq "credit_note") {
 
1101       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"}) * -1;
 
1103       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
 
1105     $form->{paid} += $form->{"paid_$i"};
 
1106     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
 
1109   $form->{exchangerate} =
 
1110       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
 
1113   my $project_id = conv_i($form->{"globalproject_id"});
 
1115   # record payments and offsetting AR
 
1116   for my $i (1 .. $form->{paidaccounts}) {
 
1118     if ($form->{"paid_$i"} != 0) {
 
1119       my ($accno) = split /--/, $form->{"AR_paid_$i"};
 
1120       $form->{"datepaid_$i"} = $form->{invdate}
 
1121         unless ($form->{"datepaid_$i"});
 
1122       $form->{datepaid} = $form->{"datepaid_$i"};
 
1125       if (($form->{currency} eq $form->{defaultcurrency}) || ($form->{defaultcurrency} eq "")) {
 
1126         $form->{"exchangerate_$i"} = 1;
 
1129           $form->check_exchangerate($myconfig, $form->{currency},
 
1130                                     $form->{"datepaid_$i"}, 'buy');
 
1132         $form->{"exchangerate_$i"} =
 
1135           : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
1140         $form->round_amount($form->{"paid_$i"} * $form->{"exchangerate"},
 
1144       $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
 
1145                                       WHERE c.accno = '$form->{AR}') AND amount=$amount AND transdate='$form->{"datepaid_$i"}'|;
 
1146       $dbh->do($query) || $form->dberror($query);
 
1148       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
1149                   transdate, project_id)
 
1150                   VALUES ($form->{id}, (SELECT c.id FROM chart c
 
1151                                       WHERE c.accno = '$form->{AR}'),
 
1152                   $amount, '$form->{"datepaid_$i"}', ?)|;
 
1153       do_query($form, $dbh, $query, $project_id);
 
1157       $form->{"paid_$i"} *= -1;
 
1159       $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
 
1160                                       WHERE c.accno = '$accno') AND amount=$form->{"paid_$i"} AND transdate='$form->{"datepaid_$i"}' AND source='$form->{"source_$i"}' AND memo='$form->{"memo_$i"}'|;
 
1161       $dbh->do($query) || $form->dberror($query);
 
1163       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
 
1164                   source, memo, project_id)
 
1165                   VALUES ($form->{id}, (SELECT c.id FROM chart c
 
1166                                       WHERE c.accno = '$accno'),
 
1167                   $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
 
1168                   '$form->{"source_$i"}', '$form->{"memo_$i"}', ?)|;
 
1169       do_query($form, $dbh, $query, $project_id);
 
1174         $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
 
1175         $form->{"exchangerate_$i"};
 
1177         $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
 
1180         $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
 
1186       # update exchange rate
 
1187       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
1188         $form->update_exchangerate($dbh, $form->{currency},
 
1189                                    $form->{"datepaid_$i"},
 
1190                                    $form->{"exchangerate_$i"}, 0);
 
1195   # record exchange rate differences and gains/losses
 
1196   foreach my $accno (keys %{ $form->{fx} }) {
 
1197     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
 
1199           ($form->{fx}{$accno}{$transdate} =
 
1200            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
 
1203         $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
 
1204                                         WHERE c.accno = '$accno') AND amount=$form->{fx}{$accno}{$transdate} AND transdate='$transdate' AND cleared='0' AND fx_transaction='1'|;
 
1205         $dbh->do($query) || $form->dberror($query);
 
1206         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
1207                     transdate, cleared, fx_transaction, project_id)
 
1208                     VALUES ($form->{id},
 
1209                            (SELECT c.id FROM chart c
 
1210                             WHERE c.accno = '$accno'),
 
1211                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1', ?)|;
 
1212         do_query($form, $dbh, $query, $project_id);
 
1216   my $datepaid = ($form->{paid})    ? qq|'$form->{datepaid}'| : "NULL";
 
1219   my $query = qq|UPDATE ar set
 
1220               paid = $form->{paid},
 
1221               datepaid = $datepaid
 
1222               WHERE id=$form->{id}|;
 
1224   $dbh->do($query) || $form->dberror($query);
 
1226   my $rc = $dbh->commit;
 
1229   $main::lxdebug->leave_sub();
 
1234 sub process_assembly {
 
1235   $main::lxdebug->enter_sub();
 
1237   my ($dbh, $form, $id, $totalqty) = @_;
 
1239   my $query = qq|SELECT a.parts_id, a.qty, p.assembly,
 
1240                  p.partnumber, p.description, p.unit,
 
1241                  p.inventory_accno_id, p.income_accno_id,
 
1244                  JOIN parts p ON (a.parts_id = p.id)
 
1246   my $sth = $dbh->prepare($query);
 
1247   $sth->execute || $form->dberror($query);
 
1249   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1253     $ref->{inventory_accno_id} *= 1;
 
1254     $ref->{expense_accno_id}   *= 1;
 
1256     map { $ref->{$_} =~ s/\'/\'\'/g } (qw(partnumber description unit));
 
1258     # multiply by number of assemblies
 
1259     $ref->{qty} *= $totalqty;
 
1261     if ($ref->{assembly}) {
 
1262       &process_assembly($dbh, $form, $ref->{parts_id}, $ref->{qty});
 
1265       if ($ref->{inventory_accno_id}) {
 
1266         $allocated = &cogs($dbh, $form, $ref->{parts_id}, $ref->{qty});
 
1270     # save detail record for individual assembly item in invoice table
 
1271     $query = qq|INSERT INTO invoice (trans_id, description, parts_id, qty,
 
1272                 sellprice, fxsellprice, allocated, assemblyitem, unit)
 
1274                 ($form->{id}, '$ref->{description}',
 
1275                 $ref->{parts_id}, $ref->{qty}, 0, 0, $allocated, 't',
 
1277     $dbh->do($query) || $form->dberror($query);
 
1283   $main::lxdebug->leave_sub();
 
1287   $main::lxdebug->enter_sub();
 
1289   my ($dbh, $form, $id, $totalqty, $basefactor, $row) = @_;
 
1290   $form->{taxzone_id} *=1;
 
1291   my $transdate = ($form->{invdate}) ? "'$form->{invdate}'" : "current_date";
 
1292   my $query = qq|SELECT i.id, i.trans_id, i.base_qty, i.allocated, i.sellprice,
 
1293                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
 
1294                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
 
1295                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid
 
1296                   FROM invoice i, parts p
 
1297                   LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
 
1298                   LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
 
1299                   LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
 
1300                   WHERE i.parts_id = p.id
 
1301                   AND i.parts_id = $id
 
1302                   AND (i.base_qty + i.allocated) < 0
 
1304   my $sth = $dbh->prepare($query);
 
1305   $sth->execute || $form->dberror($query);
 
1310   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1311     if (($qty = (($ref->{base_qty} * -1) - $ref->{allocated})) > $totalqty) {
 
1315     $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|,
 
1318     # total expenses and inventory
 
1319     # sellprice is the cost of the item
 
1320     $linetotal = $form->round_amount(($ref->{sellprice} * $qty) / $basefactor, 2);
 
1323       $ref->{expense_accno} = ($form->{"expense_accno_$row"}) ? $form->{"expense_accno_$row"} : $ref->{expense_accno};
 
1325       $form->{amount}{ $form->{id} }{ $ref->{expense_accno} } += -$linetotal;
 
1326       $form->{expense_inventory} .= " " . $ref->{expense_accno};
 
1327       $ref->{inventory_accno} = ($form->{"inventory_accno_$row"}) ? $form->{"inventory_accno_$row"} : $ref->{inventory_accno};
 
1329       $form->{amount}{ $form->{id} }{ $ref->{inventory_accno} } -= -$linetotal;
 
1330       $form->{expense_inventory} .= " " . $ref->{inventory_accno};
 
1334     $allocated += -$qty;
 
1336     last if (($totalqty -= $qty) <= 0);
 
1341   $main::lxdebug->leave_sub();
 
1346 sub reverse_invoice {
 
1347   $main::lxdebug->enter_sub();
 
1349   my ($dbh, $form) = @_;
 
1351   # reverse inventory items
 
1352   my $query = qq|SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
 
1353                  p.inventory_accno_id
 
1355                  JOIN parts p ON (i.parts_id = p.id)
 
1356                  WHERE i.trans_id = $form->{id}|;
 
1357   my $sth = $dbh->prepare($query);
 
1358   $sth->execute || $form->dberror($query);
 
1360   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1362     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
 
1364       # if the invoice item is not an assemblyitem adjust parts onhand
 
1365       if (!$ref->{assemblyitem}) {
 
1367         # adjust onhand in parts table
 
1368         $form->update_balance($dbh, "parts", "onhand",
 
1369                               qq|id = $ref->{parts_id}|,
 
1373       # loop if it is an assembly
 
1374       next if ($ref->{assembly});
 
1376       # de-allocated purchases
 
1377       $query = qq|SELECT i.id, i.trans_id, i.allocated
 
1379                   WHERE i.parts_id = $ref->{parts_id}
 
1381                   ORDER BY i.trans_id DESC|;
 
1382       my $sth = $dbh->prepare($query);
 
1383       $sth->execute || $form->dberror($query);
 
1385       while (my $inhref = $sth->fetchrow_hashref(NAME_lc)) {
 
1387         if (($ref->{qty} - $inhref->{allocated}) > 0) {
 
1388           $qty = $inhref->{allocated};
 
1392         $form->update_balance($dbh, "invoice", "allocated",
 
1393                               qq|id = $inhref->{id}|,
 
1396         last if (($ref->{qty} -= $qty) <= 0);
 
1405   $query = qq|DELETE FROM acc_trans
 
1406               WHERE trans_id = $form->{id}|;
 
1407   $dbh->do($query) || $form->dberror($query);
 
1409   # delete invoice entries
 
1410   $query = qq|DELETE FROM invoice
 
1411               WHERE trans_id = $form->{id}|;
 
1412   $dbh->do($query) || $form->dberror($query);
 
1414   if ($form->{lizenzen}) {
 
1415     $query = qq|DELETE FROM licenseinvoice
 
1416               WHERE trans_id in (SELECT id FROM invoice WHERE trans_id = $form->{id})|;
 
1417     $dbh->do($query) || $form->dberror($query);
 
1420   $query = qq|DELETE FROM shipto
 
1421               WHERE trans_id = $form->{id} AND module = 'AR'|;
 
1422   $dbh->do($query) || $form->dberror($query);
 
1424   $main::lxdebug->leave_sub();
 
1427 sub delete_invoice {
 
1428   $main::lxdebug->enter_sub();
 
1430   my ($self, $myconfig, $form, $spool) = @_;
 
1432   # connect to database
 
1433   my $dbh = $form->dbconnect_noauto($myconfig);
 
1435   &reverse_invoice($dbh, $form);
 
1438   my $query = qq|DELETE FROM ar
 
1439                  WHERE id = $form->{id}|;
 
1440   $dbh->do($query) || $form->dberror($query);
 
1442   # delete spool files
 
1443   $query = qq|SELECT s.spoolfile FROM status s
 
1444               WHERE s.trans_id = $form->{id}|;
 
1445   my $sth = $dbh->prepare($query);
 
1446   $sth->execute || $self->dberror($query);
 
1449   my @spoolfiles = ();
 
1451   while (($spoolfile) = $sth->fetchrow_array) {
 
1452     push @spoolfiles, $spoolfile;
 
1456   # delete status entries
 
1457   $query = qq|DELETE FROM status
 
1458               WHERE trans_id = $form->{id}|;
 
1459   $dbh->do($query) || $form->dberror($query);
 
1461   my $rc = $dbh->commit;
 
1465     foreach $spoolfile (@spoolfiles) {
 
1466       unlink "$spool/$spoolfile" if $spoolfile;
 
1470   $main::lxdebug->leave_sub();
 
1475 sub retrieve_invoice {
 
1476   $main::lxdebug->enter_sub();
 
1478   my ($self, $myconfig, $form) = @_;
 
1480   # connect to database
 
1481   my $dbh = $form->dbconnect_noauto($myconfig);
 
1487     # get default accounts and last invoice number
 
1488     $query = qq|SELECT (SELECT c.accno FROM chart c
 
1489                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
 
1490                        (SELECT c.accno FROM chart c
 
1491                         WHERE d.income_accno_id = c.id) AS income_accno,
 
1492                        (SELECT c.accno FROM chart c
 
1493                         WHERE d.expense_accno_id = c.id) AS expense_accno,
 
1494                        (SELECT c.accno FROM chart c
 
1495                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
1496                        (SELECT c.accno FROM chart c
 
1497                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
1498                 d.curr AS currencies
 
1501     $query = qq|SELECT (SELECT c.accno FROM chart c
 
1502                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
 
1503                        (SELECT c.accno FROM chart c
 
1504                         WHERE d.income_accno_id = c.id) AS income_accno,
 
1505                        (SELECT c.accno FROM chart c
 
1506                         WHERE d.expense_accno_id = c.id) AS expense_accno,
 
1507                        (SELECT c.accno FROM chart c
 
1508                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
1509                        (SELECT c.accno FROM chart c
 
1510                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
1511                 d.curr AS currencies, current_date AS invdate
 
1514   my $sth = $dbh->prepare($query);
 
1515   $sth->execute || $form->dberror($query);
 
1517   my $ref = $sth->fetchrow_hashref(NAME_lc);
 
1518   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1524     $query = qq|SELECT a.invnumber, a.ordnumber, a.quonumber, a.cusordnumber,
 
1525                 a.orddate, a.quodate, a.globalproject_id,
 
1526                 a.transdate AS invdate, a.deliverydate, a.paid, a.storno, a.gldate,
 
1527                 a.shippingpoint, a.shipvia, a.terms, a.notes, a.intnotes, a.taxzone_id,
 
1528                 a.duedate, a.taxincluded, a.curr AS currency, a.shipto_id, a.cp_id,
 
1529                 a.employee_id, e.name AS employee, a.payment_id, a.language_id, a.delivery_customer_id, a.delivery_vendor_id, a.type
 
1531                 LEFT JOIN employee e ON (e.id = a.employee_id)
 
1532                 WHERE a.id = $form->{id}|;
 
1533     $sth = $dbh->prepare($query);
 
1534     $sth->execute || $form->dberror($query);
 
1536     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1537     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1540     $form->{exchangerate} =
 
1541       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
 
1544     $query = qq|SELECT s.* FROM shipto s
 
1545                 WHERE s.trans_id = $form->{id} AND s.module = 'AR'|;
 
1546     $sth = $dbh->prepare($query);
 
1547     $sth->execute || $form->dberror($query);
 
1549     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1551     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1554    if ($form->{delivery_customer_id}) {
 
1555       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_customer_id}|;
 
1556       $sth = $dbh->prepare($query);
 
1557       $sth->execute || $form->dberror($query);
 
1558       ($form->{delivery_customer_string}) = $sth->fetchrow_array();
 
1562     if ($form->{delivery_vendor_id}) {
 
1563       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_vendor_id}|;
 
1564       $sth = $dbh->prepare($query);
 
1565       $sth->execute || $form->dberror($query);
 
1566       ($form->{delivery_vendor_string}) = $sth->fetchrow_array();
 
1570     # get printed, emailed
 
1571     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
 
1573                 WHERE s.trans_id = $form->{id}|;
 
1574     $sth = $dbh->prepare($query);
 
1575     $sth->execute || $form->dberror($query);
 
1577     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1578       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
1579       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
1580       $form->{queued} .= "$ref->{formname} $ref->{spoolfile} "
 
1581         if $ref->{spoolfile};
 
1584     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
1587       $form->{deliverydate} ? $dbh->quote($form->{deliverydate}) :
 
1588       $form->{invdate} ? $dbh->quote($form->{invdate}) :
 
1591     if (!$form->{taxzone_id}) {
 
1592       $form->{taxzone_id} = 0;
 
1594     # retrieve individual items
 
1596                 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
 
1597                 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
 
1598                 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
 
1599                 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice,
 
1600                 i.discount, i.parts_id AS id, i.unit, i.deliverydate,
 
1601                 i.project_id, pr.projectnumber, i.serialnumber,
 
1602                 p.partnumber, p.assembly, p.bin, p.notes AS partnotes, p.inventory_accno_id AS part_inventory_accno_id, i.id AS invoice_pos,
 
1603                 pg.partsgroup, i.pricegroup_id, (SELECT pricegroup FROM pricegroup WHERE id=i.pricegroup_id) as pricegroup,
 
1604                 i.ordnumber, i.transdate, i.cusordnumber, p.formel, i.subtotal
 
1606                 JOIN parts p ON (i.parts_id = p.id)
 
1607                 LEFT JOIN project pr ON (i.project_id = pr.id)
 
1608                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1609                 LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
 
1610                 LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
 
1611                 LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
 
1612                 WHERE i.trans_id = $form->{id}
 
1613                 AND NOT i.assemblyitem = '1'
 
1615     $sth = $dbh->prepare($query);
 
1617     $sth->execute || $form->dberror($query);
 
1618     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1619       if (!$ref->{"part_inventory_accno_id"}) {
 
1620         map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
 
1622       delete($ref->{"part_inventory_accno_id"});
 
1624     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
 
1625       my $query = qq| SELECT accno AS inventory_accno, new_chart_id AS inventory_new_chart, date($transdate) - valid_from AS inventory_valid FROM chart WHERE id = $ref->{inventory_new_chart}|;
 
1626       my $stw = $dbh->prepare($query);
 
1627       $stw->execute || $form->dberror($query);
 
1628       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
 
1632     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
 
1633       my $query = qq| SELECT accno AS income_accno, new_chart_id AS income_new_chart, date($transdate) - valid_from AS income_valid FROM chart WHERE id = $ref->{income_new_chart}|;
 
1634       my $stw = $dbh->prepare($query);
 
1635       $stw->execute || $form->dberror($query);
 
1636       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
 
1640     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
 
1641       my $query = qq| SELECT accno AS expense_accno, new_chart_id AS expense_new_chart, date($transdate) - valid_from AS expense_valid FROM chart WHERE id = $ref->{expense_new_chart}|;
 
1642       my $stw = $dbh->prepare($query);
 
1643       $stw->execute || $form->dberror($query);
 
1644       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
 
1648       # get tax rates and description
 
1650         ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
 
1651     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
 
1652               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
 
1653               WHERE t.id in (SELECT tk.tax_id from taxkeys tk where tk.chart_id = (SELECT id from chart WHERE accno='$accno_id') AND startdate<=$transdate ORDER BY startdate desc LIMIT 1)
 
1655       $stw = $dbh->prepare($query);
 
1656       $stw->execute || $form->dberror($query);
 
1657       $ref->{taxaccounts} = "";
 
1659       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
1661         #    if ($customertax{$ref->{accno}}) {
 
1662         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
 
1666         $ref->{taxaccounts} .= "$ptr->{accno} ";
 
1668         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
 
1669           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
1670           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
 
1671           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
1672           $form->{taxaccounts} .= "$ptr->{accno} ";
 
1677       if ($form->{lizenzen}) {
 
1678         $query = qq|SELECT l.licensenumber, l.id AS licenseid
 
1679                  FROM license l, licenseinvoice li
 
1680                  WHERE l.id = li.license_id AND li.trans_id = $ref->{invoice_pos}|;
 
1681         $stg = $dbh->prepare($query);
 
1682         $stg->execute || $form->dberror($query);
 
1683         ($licensenumber, $licenseid) = $stg->fetchrow_array();
 
1685           "<option value=\"$licenseid\">$licensenumber</option>";
 
1688       if ($form->{type} eq "credit_note") {
 
1692       chop $ref->{taxaccounts};
 
1693       push @{ $form->{invoice_details} }, $ref;
 
1698     Common::webdav_folder($form) if ($main::webdav);
 
1701   my $rc = $dbh->commit;
 
1704   $main::lxdebug->leave_sub();
 
1710   $main::lxdebug->enter_sub();
 
1712   my ($self, $myconfig, $form) = @_;
 
1714   # connect to database
 
1715   my $dbh = $form->dbconnect($myconfig);
 
1717   my $dateformat = $myconfig->{dateformat};
 
1718   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
1722     ? "to_date('$form->{invdate}', '$dateformat')"
 
1725   $form->{customer_id} *= 1;
 
1728   my $query = qq|SELECT c.name AS customer, c.discount, c.creditlimit, c.terms,
 
1729                  c.email, c.cc, c.bcc, c.language_id, c.payment_id AS customer_payment_id,
 
1730                  c.street, c.zipcode, c.city, c.country,
 
1731                  $duedate + c.terms AS duedate, c.notes AS intnotes,
 
1732                  b.discount AS tradediscount, b.description AS business, c.klass as customer_klass, c.taxzone_id
 
1734                  LEFT JOIN business b ON (b.id = c.business_id)
 
1735                  WHERE c.id = $form->{customer_id}|;
 
1736   my $sth = $dbh->prepare($query);
 
1737   $sth->execute || $form->dberror($query);
 
1739   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1741   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1744   my $query = qq|SELECT sum(a.amount-a.paid) AS dunning_amount FROM ar a WHERE a.paid < a.amount AND a.customer_id=$form->{customer_id} AND a.dunning_id IS NOT NULL|;
 
1745   my $sth = $dbh->prepare($query);
 
1747   $sth->execute || $form->dberror($query);
 
1749   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1751   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1754   #print(STDERR "DUNNING AMOUTN $form->{dunning_amount}\n");
 
1756   my $query = qq|SELECT dnn.dunning_description AS max_dunning_level FROM dunning_config dnn WHERE id in (select dunning_id from ar WHERE paid < amount AND customer_id=$form->{customer_id} AND dunning_id IS NOT NULL) ORDER BY dunning_level DESC LIMIT 1|;
 
1757   my $sth = $dbh->prepare($query);
 
1759   $sth->execute || $form->dberror($query);
 
1761   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1763   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1765   #print(STDERR "LEVEL $form->{max_dunning_level}\n");
 
1768   #check whether payment_terms are better than old payment_terms
 
1769   if (($form->{payment_id} ne "") && ($form->{customer_payment_id} ne "")) {
 
1770     my $query = qq|select (select ranking from payment_terms WHERE id = $form->{payment_id}), (select ranking from payment_terms WHERE id = $form->{customer_payment_id})|;
 
1771     my $stw = $dbh->prepare($query);
 
1772     $stw->execute || $form->dberror($query);
 
1773     ($old_ranking, $new_ranking) = $stw->fetchrow_array;
 
1775     if ($new_ranking > $old_ranking) {
 
1776       $form->{payment_id} =$form->{customer_payment_id};
 
1779   if ($form->{payment_id} eq "") {
 
1780     $form->{payment_id} =$form->{customer_payment_id};
 
1783   $form->{creditremaining} = $form->{creditlimit};
 
1784   $query = qq|SELECT SUM(a.amount - a.paid)
 
1786               WHERE a.customer_id = $form->{customer_id}|;
 
1787   $sth = $dbh->prepare($query);
 
1788   $sth->execute || $form->dberror($query);
 
1790   ($form->{creditremaining}) -= $sth->fetchrow_array;
 
1794   $query = qq|SELECT o.amount,
 
1795                 (SELECT e.buy FROM exchangerate e
 
1796                  WHERE e.curr = o.curr
 
1797                  AND e.transdate = o.transdate)
 
1799               WHERE o.customer_id = $form->{customer_id}
 
1800               AND o.quotation = '0'
 
1801               AND o.closed = '0'|;
 
1802   $sth = $dbh->prepare($query);
 
1803   $sth->execute || $form->dberror($query);
 
1805   while (my ($amount, $exch) = $sth->fetchrow_array) {
 
1806     $exch = 1 unless $exch;
 
1807     $form->{creditremaining} -= $amount * $exch;
 
1811   # get shipto if we did not converted an order or invoice
 
1812   if (!$form->{shipto}) {
 
1813     map { delete $form->{$_} }
 
1814       qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail);
 
1816     $query = qq|SELECT s.* FROM shipto s
 
1817                 WHERE s.trans_id = $form->{customer_id} AND s.module = 'CT'|;
 
1818     $sth = $dbh->prepare($query);
 
1819     $sth->execute || $form->dberror($query);
 
1821     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1823     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1827   # get taxes we charge for this customer
 
1828   $query = qq|SELECT c.accno
 
1830               JOIN customertax ct ON (ct.chart_id = c.id)
 
1831               WHERE ct.customer_id = $form->{customer_id}|;
 
1832   $sth = $dbh->prepare($query);
 
1833   $sth->execute || $form->dberror($query);
 
1835   my $customertax = ();
 
1836   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1837     $customertax{ $ref->{accno} } = 1;
 
1841   # setup last accounts used for this customer
 
1842   if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
 
1843     $query = qq|SELECT c.accno, c.description, c.link, c.category
 
1845                 JOIN acc_trans ac ON (ac.chart_id = c.id)
 
1846                 JOIN ar a ON (a.id = ac.trans_id)
 
1847                 WHERE a.customer_id = $form->{customer_id}
 
1848                 AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
 
1849                 AND a.id IN (SELECT max(a2.id) FROM ar a2
 
1850                              WHERE a2.customer_id = $form->{customer_id})|;
 
1851     $sth = $dbh->prepare($query);
 
1852     $sth->execute || $form->dberror($query);
 
1855     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1856       if ($ref->{category} eq 'I') {
 
1858         $form->{"AR_amount_$i"} = "$ref->{accno}--$ref->{description}";
 
1860       if ($ref->{category} eq 'A') {
 
1861         $form->{ARselected} = $form->{AR_1} =
 
1862           "$ref->{accno}--$ref->{description}";
 
1866     $form->{rowcount} = $i if ($i && !$form->{type});
 
1871   $main::lxdebug->leave_sub();
 
1875   $main::lxdebug->enter_sub();
 
1877   my ($self, $myconfig, $form) = @_;
 
1879   # connect to database
 
1880   my $dbh = $form->dbconnect($myconfig);
 
1882   my $i = $form->{rowcount};
 
1884   my $where = "NOT p.obsolete = '1'";
 
1886   if ($form->{"partnumber_$i"}) {
 
1887     my $partnumber = $form->like(lc $form->{"partnumber_$i"});
 
1888     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
 
1890   if ($form->{"description_$i"}) {
 
1891     my $description = $form->like(lc $form->{"description_$i"});
 
1892     $where .= " AND lower(p.description) LIKE '$description'";
 
1895   if ($form->{"partsgroup_$i"}) {
 
1896     my $partsgroup = $form->like(lc $form->{"partsgroup_$i"});
 
1897     $where .= " AND lower(pg.partsgroup) LIKE '$partsgroup'";
 
1900   if ($form->{"description_$i"}) {
 
1901     $where .= " ORDER BY p.description";
 
1903     $where .= " ORDER BY p.partnumber";
 
1907   if ($form->{type} eq "invoice") {
 
1909       $form->{deliverydate} ? $dbh->quote($form->{deliverydate}) :
 
1910       $form->{invdate} ? $dbh->quote($form->{invdate}) :
 
1914       $form->{transdate} ? $dbh->quote($form->{transdate}) :
 
1918   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
 
1919                         p.listprice, p.inventory_accno_id,
 
1920                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
 
1921                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
 
1922                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
 
1923                  p.unit, p.assembly, p.bin, p.onhand, p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
 
1924                  pg.partsgroup, p.formel, p.payment_id AS part_payment_id
 
1926                  LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
 
1927                  LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
 
1928                  LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
 
1929                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
 
1931   my $sth = $dbh->prepare($query);
 
1932   $sth->execute || $form->dberror($query);
 
1934   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1936     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
 
1937     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
 
1938     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
 
1939     if (!$ref->{inventory_accno_id}) {
 
1940       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
 
1942     delete($ref->{inventory_accno_id});
 
1944     #set expense_accno=inventory_accno if they are different => bilanz
 
1947     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
 
1948       my $query = qq| SELECT accno AS inventory_accno, new_chart_id AS inventory_new_chart, date($transdate) - valid_from AS inventory_valid FROM chart WHERE id = $ref->{inventory_new_chart}|;
 
1949       my $stw = $dbh->prepare($query);
 
1950       $stw->execute || $form->dberror($query);
 
1951       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
 
1955     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
 
1956       my $query = qq| SELECT accno AS income_accno, new_chart_id AS income_new_chart, date($transdate) - valid_from AS income_valid FROM chart WHERE id = $ref->{income_new_chart}|;
 
1957       my $stw = $dbh->prepare($query);
 
1958       $stw->execute || $form->dberror($query);
 
1959       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
 
1963     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
 
1964       my $query = qq| SELECT accno AS expense_accno, new_chart_id AS expense_new_chart, date($transdate) - valid_from AS expense_valid FROM chart WHERE id = $ref->{expense_new_chart}|;
 
1965       my $stw = $dbh->prepare($query);
 
1966       $stw->execute || $form->dberror($query);
 
1967       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
 
1971     #check whether payment_terms are better than old payment_terms
 
1972     if (($form->{payment_id} ne "") && ($ref->{part_payment_id} ne "")) {
 
1973       my $query = qq|select (select ranking from payment_terms WHERE id = $form->{payment_id}), (select ranking from payment_terms WHERE id = $ref->{part_payment_id})|;
 
1974       my $stw = $dbh->prepare($query);
 
1975       $stw->execute || $form->dberror($query);
 
1976       ($old_ranking, $new_ranking) = $stw->fetchrow_array;
 
1978       if ($new_ranking <= $old_ranking) {
 
1979         $ref->{part_payment_id} = "";
 
1983     # get tax rates and description
 
1985       ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
 
1986     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
 
1987               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
 
1988               WHERE t.id in (SELECT tk.tax_id from taxkeys tk where tk.chart_id = (SELECT id from chart WHERE accno='$accno_id') AND startdate<=$transdate ORDER BY startdate desc LIMIT 1)
 
1990     $stw = $dbh->prepare($query);
 
1991     $stw->execute || $form->dberror($query);
 
1993     $ref->{taxaccounts} = "";
 
1995     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
1997       #    if ($customertax{$ref->{accno}}) {
 
1998       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
 
2002       $ref->{taxaccounts} .= "$ptr->{accno} ";
 
2004       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
 
2005         $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
2006         $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
 
2007         $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
2008         $form->{taxaccounts} .= "$ptr->{accno} ";
 
2014     chop $ref->{taxaccounts};
 
2015     if ($form->{language_id}) {
 
2016       $query = qq|SELECT tr.translation, tr.longdescription
 
2018                 WHERE tr.language_id=$form->{language_id} AND tr.parts_id=$ref->{id}|;
 
2019       $stw = $dbh->prepare($query);
 
2020       $stw->execute || $form->dberror($query);
 
2021       my ($translation, $longdescription) = $stw->fetchrow_array();
 
2022       if ($translation ne "") {
 
2023         $ref->{description} = $translation;
 
2024         $ref->{longdescription} = $longdescription;
 
2027         $query = qq|SELECT tr.translation, tr.longdescription
 
2029                 WHERE tr.language_id in (select id from language where article_code=(select article_code from language where id = $form->{language_id})) AND tr.parts_id=$ref->{id} LIMIT 1|;
 
2030         $stg = $dbh->prepare($query);
 
2031         $stg->execute || $form->dberror($query);
 
2032         my ($translation) = $stg->fetchrow_array();
 
2033         if ($translation ne "") {
 
2034           $ref->{description} = $translation;
 
2035           $ref->{longdescription} = $longdescription;
 
2042     push @{ $form->{item_list} }, $ref;
 
2044     if ($form->{lizenzen}) {
 
2045       if ($ref->{inventory_accno} > 0) {
 
2047           qq| SELECT l.* FROM license l WHERE l.parts_id = $ref->{id} AND NOT l.id IN (SELECT li.license_id FROM licenseinvoice li)|;
 
2048         $stw = $dbh->prepare($query);
 
2049         $stw->execute || $form->dberror($query);
 
2050         while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
2051           push @{ $form->{LIZENZEN}{ $ref->{id} } }, $ptr;
 
2060   $main::lxdebug->leave_sub();
 
2063 ##########################
 
2064 # get pricegroups from database
 
2065 # build up selected pricegroup
 
2066 # if an exchange rate - change price
 
2069 sub get_pricegroups_for_parts {
 
2071   $main::lxdebug->enter_sub();
 
2073   my ($self, $myconfig, $form) = @_;
 
2075   my $dbh = $form->dbconnect($myconfig);
 
2077   $form->{"PRICES"} = {};
 
2081   my $dimension_units = AM->retrieve_units($myconfig, $form, "dimension");
 
2082   my $service_units = AM->retrieve_units($myconfig, $form, "service");
 
2083   my $all_units = AM->retrieve_units($myconfig, $form);
 
2084   while (($form->{"id_$i"}) or ($form->{"new_id_$i"})) {
 
2085     $form->{"PRICES"}{$i} = [];
 
2087     $id = $form->{"id_$i"};
 
2089     if (!($form->{"id_$i"}) and $form->{"new_id_$i"}) {
 
2091       $id = $form->{"new_id_$i"};
 
2094     ($price, $selectedpricegroup_id) = split /--/,
 
2095       $form->{"sellprice_pg_$i"};
 
2097     $pricegroup_old = $form->{"pricegroup_old_$i"};
 
2098     $form->{"new_pricegroup_$i"} = $selectedpricegroup_id;
 
2099     $form->{"old_pricegroup_$i"} = $pricegroup_old;
 
2100     $price_new = $form->{"price_new_$i"};
 
2102     $price_old = $form->{"price_old_$i"};
 
2104       qq|SELECT pricegroup_id, (SELECT p.sellprice from parts p where p.id = $id) as default_sellprice,(SELECT pg.pricegroup FROM pricegroup pg WHERE id=pricegroup_id) AS pricegroup, price, '' AS selected FROM prices WHERE parts_id = $id UNION SELECT 0 as pricegroup_id,(SELECT sellprice FROM parts WHERE id=$id) as default_sellprice,'' as pricegroup, (SELECT DISTINCT sellprice from parts where id=$id) as price, 'selected' AS selected from prices ORDER BY pricegroup|;
 
2106     $pkq = $dbh->prepare($query);
 
2107     $pkq->execute || $form->dberror($query);
 
2108     if (!$form->{"unit_old_$i"}) {
 
2109       # Neue Ware aus der Datenbank. In diesem Fall ist unit_$i die
 
2110       # Einheit, wie sie in den Stammdaten hinterlegt wurde.
 
2111       # Es sollte also angenommen werden, dass diese ausgewaehlt war.
 
2112       $form->{"unit_old_$i"} = $form->{"unit_$i"};
 
2115     # Die zuletzt ausgewaehlte mit der aktuell ausgewaehlten Einheit
 
2116     # vergleichen und bei Unterschied den Preis entsprechend umrechnen.
 
2117     $form->{"selected_unit_$i"} = $form->{"unit_$i"} unless ($form->{"selected_unit_$i"});
 
2119     my $check_units = $form->{"inventory_accno_$i"} ? $dimension_units : $service_units;
 
2120     if (!$check_units->{$form->{"selected_unit_$i"}} ||
 
2121         ($check_units->{$form->{"selected_unit_$i"}}->{"base_unit"} ne
 
2122          $all_units->{$form->{"unit_old_$i"}}->{"base_unit"})) {
 
2123       # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
 
2124       # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
 
2125       # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
 
2126       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};
 
2130     if ($form->{"unit_old_$i"} ne $form->{"selected_unit_$i"}) {
 
2131       if (defined($all_units->{$form->{"unit_old_$i"}}->{"factor"}) &&
 
2132           $all_units->{$form->{"unit_old_$i"}}->{"factor"}) {
 
2133         $basefactor = $all_units->{$form->{"selected_unit_$i"}}->{"factor"} /
 
2134           $all_units->{$form->{"unit_old_$i"}}->{"factor"};
 
2137     if (!$form->{"basefactor_$i"}) {
 
2138       $form->{"basefactor_$i"} = 1;
 
2140     while ($pkr = $pkq->fetchrow_hashref(NAME_lc)) {
 
2142       #       push @{ $form->{PRICES}{$id} }, $pkr;
 
2143       #push @{ $form->{PRICES}{$i} }, $pkr;
 
2145       $pkr->{selected} = '';
 
2147       # if there is an exchange rate change price
 
2148       if (($form->{exchangerate} * 1) != 0) {
 
2150         $pkr->{price} /= $form->{exchangerate};
 
2153       $pkr->{price} *= $form->{"basefactor_$i"};
 
2155       $pkr->{price} *= $basefactor;
 
2157       $pkr->{price} = $form->format_amount($myconfig, $pkr->{price}, 5);
 
2159       if ($selectedpricegroup_id eq undef) {
 
2160         if ($pkr->{pricegroup_id} eq $form->{customer_klass}) {
 
2162           $pkr->{selected}  = ' selected';
 
2164           # no customer pricesgroup set
 
2165           if ($pkr->{price} == $pkr->{default_sellprice}) {
 
2167             $pkr->{price} = $form->{"sellprice_$i"};
 
2171             $form->{"sellprice_$i"} = $pkr->{price};
 
2175           if ($pkr->{price} == $pkr->{default_sellprice}) {
 
2177             $pkr->{price}    = $form->{"sellprice_$i"};
 
2178             $pkr->{selected} = ' selected';
 
2183       if ($selectedpricegroup_id or $selectedpricegroup_id == 0) {
 
2184         if ($selectedpricegroup_id ne $pricegroup_old) {
 
2185           if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
 
2186             $pkr->{selected}  = ' selected';
 
2189           if (($price_new != $form->{"sellprice_$i"}) and ($price_new ne 0)) {
 
2190             if ($pkr->{pricegroup_id} == 0) {
 
2191               $pkr->{price}     = $form->{"sellprice_$i"};
 
2192               $pkr->{selected}  = ' selected';
 
2195             if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
 
2196               $pkr->{selected}  = ' selected';
 
2197               if (    ($pkr->{pricegroup_id} == 0)
 
2198                   and ($pkr->{price} == $form->{"sellprice_$i"})) {
 
2200                 # $pkr->{price}                         = $form->{"sellprice_$i"};
 
2202                 $pkr->{price} = $form->{"sellprice_$i"};
 
2208       push @{ $form->{PRICES}{$i} }, $pkr;
 
2211     $form->{"basefactor_$i"} *= $basefactor;
 
2220   $main::lxdebug->leave_sub();