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 #======================================================================
 
  41   $main::lxdebug->enter_sub();
 
  43   my ($self, $myconfig, $form, $locale) = @_;
 
  45   $form->{duedate} = $form->{invdate} unless ($form->{duedate});
 
  48   my $dbh = $form->dbconnect($myconfig);
 
  50   my $query = qq|SELECT date '$form->{duedate}' - date '$form->{invdate}'
 
  53   my $sth = $dbh->prepare($query);
 
  54   $sth->execute || $form->dberror($query);
 
  56   ($form->{terms}) = $sth->fetchrow_array;
 
  64   my %oid = ('Pg'     => 'oid',
 
  67   # sort items by partsgroup
 
  68   for $i (1 .. $form->{rowcount}) {
 
  70     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
 
  71       $partsgroup = $form->{"partsgroup_$i"};
 
  73     push @partsgroup, [$i, $partsgroup];
 
  86   my $nodiscount_subtotal = 0;
 
  87   my $discount_subtotal = 0;
 
  89   my $subtotal_header = 0;
 
  93   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
 
  96     if ($item->[1] ne $sameitem) {
 
  97       push(@{ $form->{description} }, qq|$item->[1]|);
 
  98       $sameitem = $item->[1];
 
 100       map { push(@{ $form->{$_} }, "") }
 
 101         qw(runningnumber number serialnumber bin partnotes qty unit deliverydate sellprice listprice netprice discount linetotal);
 
 104     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 106     if ($form->{"qty_$i"} != 0) {
 
 108       # add number, description and qty to $form->{number},
 
 109       if ($form->{"subtotal_$i"} && !$subtotal_header) {
 
 110         $subtotal_header = $i;
 
 111         $position = int($position);
 
 114       } elsif ($subtotal_header) {
 
 116         $position = int($position);
 
 117         $position = $position.".".$subposition;
 
 119         $position = int($position);
 
 122       push(@{ $form->{runningnumber} }, $position);
 
 123       push(@{ $form->{number} },        qq|$form->{"partnumber_$i"}|);
 
 124       push(@{ $form->{serialnumber} },  qq|$form->{"serialnumber_$i"}|);
 
 125       push(@{ $form->{bin} },           qq|$form->{"bin_$i"}|);
 
 126       push(@{ $form->{"partnotes"} },   qq|$form->{"partnotes_$i"}|);
 
 127       push(@{ $form->{description} },   qq|$form->{"description_$i"}|);
 
 128       push(@{ $form->{longdescription} },   qq|$form->{"longdescription_$i"}|);
 
 129       push(@{ $form->{qty} },
 
 130            $form->format_amount($myconfig, $form->{"qty_$i"}));
 
 131       push(@{ $form->{unit} },            qq|$form->{"unit_$i"}|);
 
 132       push(@{ $form->{deliverydate_oe} }, qq|$form->{"deliverydate_$i"}|);
 
 134       push(@{ $form->{sellprice} },    $form->{"sellprice_$i"});
 
 135       push(@{ $form->{ordnumber_oe} }, qq|$form->{"ordnumber_$i"}|);
 
 136       push(@{ $form->{transdate_oe} }, qq|$form->{"transdate_$i"}|);
 
 137       push(@{ $form->{invnumber} }, qq|$form->{"invnumber"}|);
 
 138       push(@{ $form->{invdate} }, qq|$form->{"invdate"}|);
 
 140       if ($form->{lizenzen}) {
 
 141         if ($form->{"licensenumber_$i"}) {
 
 143             qq|SELECT l.licensenumber, l.validuntil FROM license l WHERE l.id = $form->{"licensenumber_$i"}|;
 
 144           $sth = $dbh->prepare($query);
 
 145           $sth->execute || $form->dberror($query);
 
 147           ($licensenumber, $validuntil) = $sth->fetchrow_array;
 
 148           push(@{ $form->{licensenumber} }, $licensenumber);
 
 149           push(@{ $form->{validuntil} },
 
 150                $locale->date($myconfig, $validuntil, 0));
 
 153           push(@{ $form->{licensenumber} }, "");
 
 154           push(@{ $form->{validuntil} },    "");
 
 159       push(@{ $form->{listprice} }, $form->{"listprice_$i"});
 
 161       my $sellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 162       my ($dec) = ($sellprice =~ /\.(\d+)/);
 
 164       my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 168                             $sellprice * $form->parse_amount($myconfig,
 
 169                                                  $form->{"discount_$i"}) / 100,
 
 173         $form->round_amount($form->{"qty_$i"} * $i_discount, $decimalplaces);
 
 175       # keep a netprice as well, (sellprice - discount)
 
 176       $form->{"netprice_$i"} = $sellprice - $i_discount;
 
 178       push(@{ $form->{netprice} },
 
 179            ($form->{"netprice_$i"} != 0)
 
 180            ? $form->format_amount(
 
 181                                  $myconfig, $form->{"netprice_$i"},
 
 187         $form->round_amount($form->{"qty_$i"} * $form->{"netprice_$i"}, 2);
 
 189       my $nodiscount_linetotal =
 
 190         $form->round_amount($form->{"qty_$i"} * $sellprice, 2);
 
 194         ? $form->format_amount($myconfig, $discount * -1, $decimalplaces)
 
 196       $linetotal = ($linetotal != 0) ? $linetotal : " ";
 
 198       push(@{ $form->{discount} },   $discount);
 
 199       push(@{ $form->{p_discount} }, $form->{"discount_$i"});
 
 200       if (($form->{"discount_$i"} ne "") && ($form->{"discount_$i"} != 0)) {
 
 201         $form->{discount_p} = $form->{"discount_$i"};
 
 203       $form->{total} += $linetotal;
 
 204       $discount_subtotal += $linetotal;
 
 205       $form->{nodiscount_total} += $nodiscount_linetotal;
 
 206       $nodiscount_subtotal += $nodiscount_linetotal;
 
 207       $form->{discount_total} += $form->parse_amount($myconfig, $discount);
 
 209       if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
 
 210         $discount_subtotal = $form->format_amount($myconfig, $discount_subtotal, 2);
 
 211         push(@{ $form->{discount_sub} },  $discount_subtotal);
 
 212         $nodiscount_subtotal = $form->format_amount($myconfig, $nodiscount_subtotal, 2);
 
 213         push(@{ $form->{nodiscount_sub} }, $nodiscount_subtotal);
 
 214         $discount_subtotal = 0;
 
 215         $nodiscount_subtotal = 0;
 
 216         $subtotal_header = 0;
 
 218         push(@{ $form->{discount_sub} }, "");
 
 219         push(@{ $form->{nodiscount_sub} }, "");
 
 222       if ($linetotal == $netto_linetotal) {
 
 223         $nodiscount += $linetotal;
 
 226       push(@{ $form->{linetotal} },
 
 227            $form->format_amount($myconfig, $linetotal, 2));
 
 228       push(@{ $form->{nodiscount_linetotal} },
 
 229            $form->format_amount($myconfig, $nodiscount_linetotal, 2));
 
 233       @taxaccounts = split / /, $form->{"taxaccounts_$i"};
 
 237       map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
 
 239       if ($form->{taxincluded}) {
 
 242         $taxamount = $linetotal * $taxrate / (1 + $taxrate);
 
 243         $taxbase = $linetotal - $taxamount;
 
 245         $taxamount = $linetotal * $taxrate;
 
 246         $taxbase   = $linetotal;
 
 249       if ($form->round_amount($taxrate, 7) == 0) {
 
 250         if ($form->{taxincluded}) {
 
 251           foreach $item (@taxaccounts) {
 
 253               $form->round_amount($linetotal * $form->{"${item}_rate"} /
 
 254                                     (1 + abs($form->{"${item}_rate"})),
 
 257             $taxaccounts{$item} += $taxamount;
 
 258             $taxdiff            += $taxamount;
 
 260             $taxbase{$item} += $taxbase;
 
 262           $taxaccounts{ $taxaccounts[0] } += $taxdiff;
 
 264           foreach $item (@taxaccounts) {
 
 265             $taxaccounts{$item} += $linetotal * $form->{"${item}_rate"};
 
 266             $taxbase{$item}     += $taxbase;
 
 270         foreach $item (@taxaccounts) {
 
 271           $taxaccounts{$item} +=
 
 272             $taxamount * $form->{"${item}_rate"} / $taxrate;
 
 273           $taxbase{$item} += $taxbase;
 
 276       $tax_rate = $taxrate * 100;
 
 277       push(@{ $form->{tax_rate} }, qq|$tax_rate|);
 
 278       if ($form->{"assembly_$i"}) {
 
 281         # get parts and push them onto the stack
 
 283         if ($form->{groupitems}) {
 
 285             qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
 
 287           $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
 
 290         $query = qq|SELECT p.partnumber, p.description, p.unit, a.qty,
 
 293                     JOIN parts p ON (a.parts_id = p.id)
 
 294                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
 296                     AND a.id = '$form->{"id_$i"}'
 
 298         $sth = $dbh->prepare($query);
 
 299         $sth->execute || $form->dberror($query);
 
 301         while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
 302           if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
 
 303             map { push(@{ $form->{$_} }, "") }
 
 304               qw(runningnumber number serialnumber unit qty bin sellprice listprice netprice discount linetotal nodiscount_linetotal);
 
 305             $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
 
 306             push(@{ $form->{description} }, $sameitem);
 
 309           map { $form->{"a_$_"} = $ref->{$_} } qw(partnumber description);
 
 311           push(@{ $form->{description} },
 
 312                $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}
 
 314                  . qq| -- $form->{"a_partnumber"}, $form->{"a_description"}|);
 
 315           map { push(@{ $form->{$_} }, "") }
 
 316             qw(number unit qty runningnumber serialnumber bin sellprice listprice netprice discount linetotal nodiscount_linetotal);
 
 324   foreach my $item (sort keys %taxaccounts) {
 
 325     push(@{ $form->{taxbase} },
 
 326           $form->format_amount($myconfig, $taxbase{$item}, 2));
 
 328     $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
 
 330     push(@{ $form->{tax} }, $form->format_amount($myconfig, $taxamount, 2));
 
 331     push(@{ $form->{taxdescription} }, $form->{"${item}_description"});
 
 332     push(@{ $form->{taxrate} },
 
 333           $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
 
 334     push(@{ $form->{taxnumber} }, $form->{"${item}_taxnumber"});
 
 337   for my $i (1 .. $form->{paidaccounts}) {
 
 338     if ($form->{"paid_$i"}) {
 
 339       push(@{ $form->{payment} }, $form->{"paid_$i"});
 
 340       my ($accno, $description) = split /--/, $form->{"AR_paid_$i"};
 
 341       push(@{ $form->{paymentaccount} }, $description);
 
 342       push(@{ $form->{paymentdate} },    $form->{"datepaid_$i"});
 
 343       push(@{ $form->{paymentsource} },  $form->{"source_$i"});
 
 345       $form->{paid} += $form->parse_amount($myconfig, $form->{"paid_$i"});
 
 349   $form->{subtotal} = $form->format_amount($myconfig, $form->{total}, 2);
 
 350   $yesdiscount = $form->{nodiscount_total} - $nodiscount;
 
 351   $form->{nodiscount_subtotal} = $form->format_amount($myconfig, $form->{nodiscount_total}, 2);
 
 352   $form->{discount_total} = $form->format_amount($myconfig, $form->{discount_total}, 2);
 
 353   $form->{nodiscount} = $form->format_amount($myconfig, $nodiscount, 2);
 
 354   $form->{yesdiscount} = $form->format_amount($myconfig, $yesdiscount, 2);
 
 357     ($form->{taxincluded}) ? $form->{total} : $form->{total} + $tax;
 
 359     $form->format_amount($myconfig, $form->{invtotal} - $form->{paid}, 2);
 
 360   $form->{invtotal} = $form->format_amount($myconfig, $form->{invtotal}, 2);
 
 361   $form->set_payment_options($myconfig, $form->{invdate});
 
 362   $form->{paid} = $form->format_amount($myconfig, $form->{paid}, 2);
 
 364   $form->{username} = $myconfig->{name};
 
 368   $main::lxdebug->leave_sub();
 
 371 sub project_description {
 
 372   $main::lxdebug->enter_sub();
 
 374   my ($self, $dbh, $id) = @_;
 
 376   my $query = qq|SELECT p.description
 
 379   my $sth = $dbh->prepare($query);
 
 380   $sth->execute || $form->dberror($query);
 
 382   ($_) = $sth->fetchrow_array;
 
 386   $main::lxdebug->leave_sub();
 
 391 sub customer_details {
 
 392   $main::lxdebug->enter_sub();
 
 394   my ($self, $myconfig, $form) = @_;
 
 396   # connect to database
 
 397   my $dbh = $form->dbconnect($myconfig);
 
 399   # get contact id, set it if nessessary
 
 403   if ($form->{cp_id}) {
 
 404     $contact = "and cp.cp_id = $form->{cp_id}";
 
 407   # get rest for the customer
 
 408   my $query = qq|SELECT ct.*, cp.*, ct.notes as customernotes
 
 410                  LEFT JOIN contacts cp on ct.id = cp.cp_cv_id
 
 411                  WHERE ct.id = $form->{customer_id} $contact order by cp.cp_id limit 1|;
 
 412   my $sth = $dbh->prepare($query);
 
 413   $sth->execute || $form->dberror($query);
 
 415   $ref = $sth->fetchrow_hashref(NAME_lc);
 
 417   # remove id and taxincluded before copy back
 
 418   delete @$ref{qw(id taxincluded)};
 
 419   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 422   if ($form->{delivery_customer_id}) {
 
 423     my $query = qq|SELECT ct.*, ct.notes as customernotes
 
 425                  WHERE ct.id = $form->{delivery_customer_id} limit 1|;
 
 426     my $sth = $dbh->prepare($query);
 
 427     $sth->execute || $form->dberror($query);
 
 429     $ref = $sth->fetchrow_hashref(NAME_lc);
 
 432     map { $form->{"dc_$_"} = $ref->{$_} } keys %$ref;
 
 435   if ($form->{delivery_vendor_id}) {
 
 436     my $query = qq|SELECT ct.*, ct.notes as customernotes
 
 438                  WHERE ct.id = $form->{delivery_vendor_id} limit 1|;
 
 439     my $sth = $dbh->prepare($query);
 
 440     $sth->execute || $form->dberror($query);
 
 442     $ref = $sth->fetchrow_hashref(NAME_lc);
 
 445     map { $form->{"dv_$_"} = $ref->{$_} } keys %$ref;
 
 449   $main::lxdebug->leave_sub();
 
 453   $main::lxdebug->enter_sub();
 
 455   my ($self, $myconfig, $form) = @_;
 
 457   # connect to database, turn off autocommit
 
 458   my $dbh = $form->dbconnect_noauto($myconfig);
 
 460   my ($query, $sth, $null, $project_id, $deliverydate);
 
 461   my $exchangerate = 0;
 
 463   ($null, $form->{employee_id}) = split /--/, $form->{employee};
 
 464   unless ($form->{employee_id}) {
 
 465     $form->get_employee($dbh);
 
 468   $form->{contact_id} = $form->{cp_id};
 
 469   $form->{contact_id} *= 1;
 
 470   $form->{payment_id} *= 1;
 
 471   $form->{language_id} *= 1;
 
 472   $form->{taxzone_id} *= 1;
 
 473   $form->{delivery_customer_id} *= 1;
 
 474   $form->{delivery_vendor_id} *= 1;
 
 475   $form->{storno} *= 1;
 
 476   $form->{shipto_id} *= 1;
 
 479   ($null, $form->{department_id}) = split(/--/, $form->{department});
 
 480   $form->{department_id} *= 1;
 
 482   my $service_units = AM->retrieve_units($myconfig,$form,"service");
 
 483   my $part_units = AM->retrieve_units($myconfig,$form,"dimension");
 
 489     &reverse_invoice($dbh, $form);
 
 492     my $uid = rand() . time;
 
 494     $uid .= $form->{login};
 
 496     $uid = substr($uid, 2, 75);
 
 498     $query = qq|INSERT INTO ar (invnumber, employee_id)
 
 499                 VALUES ('$uid', $form->{employee_id})|;
 
 500     $dbh->do($query) || $form->dberror($query);
 
 502     $query = qq|SELECT a.id FROM ar a
 
 503                 WHERE a.invnumber = '$uid'|;
 
 504     $sth = $dbh->prepare($query);
 
 505     $sth->execute || $form->dberror($query);
 
 507     ($form->{id}) = $sth->fetchrow_array;
 
 511   map { $form->{$_} =~ s/\'/\'\'/g }
 
 512     (qw(invnumber shippingpoint shipvia notes intnotes message));
 
 514   my ($netamount, $invoicediff) = (0, 0);
 
 515   my ($amount, $linetotal, $lastincomeaccno);
 
 517   if ($form->{currency} eq $form->{defaultcurrency}) {
 
 518     $form->{exchangerate} = 1;
 
 521       $form->check_exchangerate($myconfig, $form->{currency},
 
 522                                 $form->{transdate}, 'buy');
 
 525   $form->{exchangerate} =
 
 528     : $form->parse_amount($myconfig, $form->{exchangerate});
 
 530   $form->{expense_inventory} = "";
 
 532   foreach my $i (1 .. $form->{rowcount}) {
 
 533     if ($form->{type} eq "credit_note") {
 
 534       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"}) * -1;
 
 535       $form->{shipped} = 1;   
 
 537       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 542     if ($form->{storno}) {
 
 543       $form->{"qty_$i"} *= -1;
 
 546     if ($form->{"qty_$i"} != 0) {
 
 549       $query = qq|SELECT p.unit
 
 551                   WHERE p.id = $form->{"id_$i"}|;
 
 552       $sth = $dbh->prepare($query);
 
 553       $sth->execute || $form->dberror($query);
 
 555       my ($item_unit) = $sth->fetchrow_array();
 
 558       if ($form->{"inventory_accno_$i"}) {
 
 559         if (defined($part_units->{$item_unit}->{factor}) && $part_units->{$item_unit}->{factor} ne '' && $part_units->{$item_unit}->{factor} ne '0') {
 
 560           $basefactor = $part_units->{$form->{"unit_$i"}}->{factor} / $part_units->{$item_unit}->{factor};
 
 564         $baseqty = $form->{"qty_$i"} * $basefactor;
 
 566         if (defined($service_units->{$item_unit}->{factor}) && $service_units->{$item_unit}->{factor} ne '' && $service_units->{$item_unit}->{factor} ne '0') {
 
 567           $basefactor = $service_units->{$form->{"unit_$i"}}->{factor} / $service_units->{$item_unit}->{factor};
 
 571         $baseqty = $form->{"qty_$i"} * $basefactor;
 
 574       map { $form->{"${_}_$i"} =~ s/\'/\'\'/g }
 
 575         (qw(partnumber description unit));
 
 577       # undo discount formatting
 
 578       $form->{"discount_$i"} =
 
 579         $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
 
 581       my ($allocated, $taxrate) = (0, 0);
 
 584       # keep entered selling price
 
 586         $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 588       my ($dec) = ($fxsellprice =~ /\.(\d+)/);
 
 590       my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 594         $form->round_amount($fxsellprice * $form->{"discount_$i"},
 
 596       $form->{"sellprice_$i"} = $fxsellprice - $discount;
 
 599       map { $taxrate += $form->{"${_}_rate"} } split / /,
 
 600         $form->{"taxaccounts_$i"};
 
 602       # round linetotal to 2 decimal places
 
 604         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
 
 606       if ($form->{taxincluded}) {
 
 607         $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
 
 608         $form->{"sellprice_$i"} =
 
 609           $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
 
 611         $taxamount = $linetotal * $taxrate;
 
 614       $netamount += $linetotal;
 
 616       if ($taxamount != 0) {
 
 618           $form->{amount}{ $form->{id} }{$_} +=
 
 619             $taxamount * $form->{"${_}_rate"} / $taxrate
 
 620         } split / /, $form->{"taxaccounts_$i"};
 
 623       # add amount to income, $form->{amount}{trans_id}{accno}
 
 625         $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
 
 628         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) *
 
 629         $form->{exchangerate};
 
 630       $linetotal = $form->round_amount($linetotal, 2);
 
 632       # this is the difference from the inventory
 
 633       $invoicediff += ($amount - $linetotal);
 
 635       $form->{amount}{ $form->{id} }{ $form->{"income_accno_$i"} } +=
 
 638       $lastincomeaccno = $form->{"income_accno_$i"};
 
 640       # adjust and round sellprice
 
 641       $form->{"sellprice_$i"} =
 
 642         $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate},
 
 645       if ($form->{"inventory_accno_$i"} || $form->{"assembly_$i"}) {
 
 647         # adjust parts onhand quantity
 
 649         if ($form->{"assembly_$i"}) {
 
 651           # do not update if assembly consists of all services
 
 652           $query = qq|SELECT sum(p.inventory_accno_id)
 
 654                       JOIN assembly a ON (a.parts_id = p.id)
 
 655                       WHERE a.id = $form->{"id_$i"}|;
 
 656           $sth = $dbh->prepare($query);
 
 657           $sth->execute || $form->dberror($query);
 
 659           if ($sth->fetchrow_array) {
 
 660             $form->update_balance($dbh, "parts", "onhand",
 
 661                                   qq|id = $form->{"id_$i"}|,
 
 663               unless $form->{shipped};
 
 667           # record assembly item as allocated
 
 668           &process_assembly($dbh, $form, $form->{"id_$i"}, $baseqty);
 
 670           $form->update_balance($dbh, "parts", "onhand",
 
 671                                 qq|id = $form->{"id_$i"}|,
 
 673             unless $form->{shipped};
 
 675           $allocated = &cogs($dbh, $form, $form->{"id_$i"}, $baseqty, $basefactor);
 
 679       $project_id = 'NULL';
 
 680       if ($form->{"projectnumber_$i"}) {
 
 681         $project_id = $form->{"projectnumber_$i"};
 
 684         ($form->{"deliverydate_$i"})
 
 685         ? qq|'$form->{"deliverydate_$i"}'|
 
 688       # get pricegroup_id and save ist
 
 689       ($null, my $pricegroup_id) = split /--/, $form->{"sellprice_drag_$i"};
 
 691       my $subtotal = $form->{"subtotal_$i"} * 1;
 
 693       # save detail record in invoice table
 
 694       $query = qq|INSERT INTO invoice (trans_id, parts_id, description,longdescription, qty,
 
 695                   sellprice, fxsellprice, discount, allocated, assemblyitem,
 
 696                   unit, deliverydate, project_id, serialnumber, pricegroup_id,
 
 697                   ordnumber, transdate, cusordnumber, base_qty, subtotal)
 
 698                   VALUES ($form->{id}, $form->{"id_$i"},
 
 699                   '$form->{"description_$i"}', '$form->{"longdescription_$i"}', $form->{"qty_$i"},
 
 700                   $form->{"sellprice_$i"}, $fxsellprice,
 
 701                   $form->{"discount_$i"}, $allocated, 'f',
 
 702                   '$form->{"unit_$i"}', $deliverydate, (SELECT id from project where projectnumber = '$project_id'),
 
 703                   '$form->{"serialnumber_$i"}', '$pricegroup_id',
 
 704                   '$form->{"ordnumber_$i"}', '$form->{"transdate_$i"}', '$form->{"cusordnumber_$i"}', $baseqty, '$subtotal')|;
 
 705       $dbh->do($query) || $form->dberror($query);
 
 707       if ($form->{lizenzen}) {
 
 708         if ($form->{"licensenumber_$i"}) {
 
 710             qq|SELECT i.id FROM invoice i WHERE i.trans_id=$form->{id} ORDER BY i.oid DESC LIMIT 1|;
 
 711           $sth = $dbh->prepare($query);
 
 712           $sth->execute || $form->dberror($query);
 
 714           ($invoice_row_id) = $sth->fetchrow_array;
 
 718             qq|INSERT INTO licenseinvoice (trans_id, license_id) VALUES ($invoice_row_id, $form->{"licensenumber_$i"})|;
 
 719           $dbh->do($query) || $form->dberror($query);
 
 726   $form->{datepaid} = $form->{invdate};
 
 728   # total payments, don't move we need it here
 
 729   for my $i (1 .. $form->{paidaccounts}) {
 
 730     if ($form->{type} eq "credit_note") {
 
 731       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"}) * -1;
 
 733       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
 
 735     $form->{paid} += $form->{"paid_$i"};
 
 736     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
 
 739   my ($tax, $diff) = (0, 0);
 
 741   $netamount = $form->round_amount($netamount, 2);
 
 743   # figure out rounding errors for total amount vs netamount + taxes
 
 744   if ($form->{taxincluded}) {
 
 746     $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
 
 747     $diff += $amount - $netamount * $form->{exchangerate};
 
 748     $netamount = $amount;
 
 750     foreach my $item (split / /, $form->{taxaccounts}) {
 
 751       $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
 
 752       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
 
 753       $tax += $form->{amount}{ $form->{id} }{$item};
 
 754       $netamount -= $form->{amount}{ $form->{id} }{$item};
 
 757     $invoicediff += $diff;
 
 758     ######## this only applies to tax included
 
 759     if ($lastincomeaccno) {
 
 760       $form->{amount}{ $form->{id} }{$lastincomeaccno} += $invoicediff;
 
 764     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
 
 765     $diff      = $amount - $netamount * $form->{exchangerate};
 
 766     $netamount = $amount;
 
 767     foreach my $item (split / /, $form->{taxaccounts}) {
 
 768       $form->{amount}{ $form->{id} }{$item} =
 
 769         $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
 
 772                  $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate},
 
 775         $amount - $form->{amount}{ $form->{id} }{$item} *
 
 776         $form->{exchangerate};
 
 777       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
 
 778       $tax += $form->{amount}{ $form->{id} }{$item};
 
 782   $form->{amount}{ $form->{id} }{ $form->{AR} } = $netamount + $tax;
 
 784     $form->round_amount($form->{paid} * $form->{exchangerate} + $diff, 2);
 
 787   $form->{amount}{ $form->{id} }{ $form->{AR} } *= -1;
 
 789   # update exchangerate
 
 790   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 791     $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate},
 
 792                                $form->{exchangerate}, 0);
 
 795   foreach my $trans_id (keys %{ $form->{amount} }) {
 
 796     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
 
 797       next unless ($form->{expense_inventory} =~ /$accno/);
 
 799           ($form->{amount}{$trans_id}{$accno} =
 
 800            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
 
 803         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
 805                     VALUES ($trans_id, (SELECT c.id FROM chart c
 
 806                                         WHERE c.accno = '$accno'),
 
 807                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
 
 808                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'))|;
 
 809         $dbh->do($query) || $form->dberror($query);
 
 810         $form->{amount}{$trans_id}{$accno} = 0;
 
 814     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
 
 816           ($form->{amount}{$trans_id}{$accno} =
 
 817            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
 
 820         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
 822                     VALUES ($trans_id, (SELECT id FROM chart
 
 823                                         WHERE accno = '$accno'),
 
 824                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
 
 825                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'))|;
 
 826         $dbh->do($query) || $form->dberror($query);
 
 831   # deduct payment differences from diff
 
 832   for my $i (1 .. $form->{paidaccounts}) {
 
 833     if ($form->{"paid_$i"} != 0) {
 
 835         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
 
 836       $diff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
 
 840   # force AR entry if 0
 
 841   #  $form->{amount}{$form->{id}}{$form->{AR}} = 1 if ($form->{amount}{$form->{id}}{$form->{AR}} == 0);
 
 843   # record payments and offsetting AR
 
 844   if (!$form->{storno}) {
 
 845     for my $i (1 .. $form->{paidaccounts}) {
 
 847       if ($form->{"paid_$i"} != 0) {
 
 848         my ($accno) = split /--/, $form->{"AR_paid_$i"};
 
 849         $form->{"datepaid_$i"} = $form->{invdate}
 
 850           unless ($form->{"datepaid_$i"});
 
 851         $form->{datepaid} = $form->{"datepaid_$i"};
 
 855         if ($form->{currency} eq $form->{defaultcurrency}) {
 
 856           $form->{"exchangerate_$i"} = 1;
 
 859             $form->check_exchangerate($myconfig, $form->{currency},
 
 860                                       $form->{"datepaid_$i"}, 'buy');
 
 862           $form->{"exchangerate_$i"} =
 
 865             : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
 870           $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $diff,
 
 873         if ($form->{amount}{ $form->{id} }{ $form->{AR} } != 0) {
 
 874           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
 876                       VALUES ($form->{id}, (SELECT c.id FROM chart c
 
 877                                           WHERE c.accno = '$form->{AR}'),
 
 878                       $amount, '$form->{"datepaid_$i"}')|;
 
 879           $dbh->do($query) || $form->dberror($query);
 
 883         $form->{"paid_$i"} *= -1;
 
 885         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
 
 887                     VALUES ($form->{id}, (SELECT c.id FROM chart c
 
 888                                         WHERE c.accno = '$accno'),
 
 889                     $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
 
 890                     '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
 
 891         $dbh->do($query) || $form->dberror($query);
 
 893         # exchangerate difference
 
 894         $form->{fx}{$accno}{ $form->{"datepaid_$i"} } +=
 
 895           $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $diff;
 
 899           $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
 
 900           $form->{"exchangerate_$i"};
 
 902           $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
 
 905           $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
 
 911         # update exchange rate
 
 912         if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 913           $form->update_exchangerate($dbh, $form->{currency},
 
 914                                     $form->{"datepaid_$i"},
 
 915                                     $form->{"exchangerate_$i"}, 0);
 
 921   # record exchange rate differences and gains/losses
 
 922   foreach my $accno (keys %{ $form->{fx} }) {
 
 923     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
 
 925           ($form->{fx}{$accno}{$transdate} =
 
 926            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
 
 930         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
 931                     transdate, cleared, fx_transaction)
 
 933                            (SELECT c.id FROM chart c
 
 934                             WHERE c.accno = '$accno'),
 
 935                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1')|;
 
 936         $dbh->do($query) || $form->dberror($query);
 
 941   $amount = $netamount + $tax;
 
 943   # set values which could be empty to 0
 
 945   $form->{taxincluded} *= 1;
 
 946   my $datepaid = ($form->{paid})    ? qq|'$form->{datepaid}'| : "NULL";
 
 947   my $duedate  = ($form->{duedate}) ? qq|'$form->{duedate}'|  : "NULL";
 
 949     ($form->{deliverydate}) ? qq|'$form->{deliverydate}'| : "NULL";
 
 951   # fill in subject if there is none
 
 952   $form->{subject} = qq|$form->{label} $form->{invnumber}|
 
 953     unless $form->{subject};
 
 955   # if there is a message stuff it into the intnotes
 
 956   my $cc  = "Cc: $form->{cc}\\r\n"   if $form->{cc};
 
 957   my $bcc = "Bcc: $form->{bcc}\\r\n" if $form->{bcc};
 
 958   my $now = scalar localtime;
 
 959   $form->{intnotes} .= qq|\r
 
 960 \r| if $form->{intnotes};
 
 962   $form->{intnotes} .= qq|[email]\r
 
 965 $cc${bcc}Subject: $form->{subject}\r
 
 967 Message: $form->{message}\r| if $form->{message};
 
 970   $query = qq|UPDATE ar set
 
 971               invnumber = '$form->{invnumber}',
 
 972               ordnumber = '$form->{ordnumber}',
 
 973               quonumber = '$form->{quonumber}',
 
 974               cusordnumber = '$form->{cusordnumber}',
 
 975               transdate = '$form->{invdate}',
 
 976               customer_id = $form->{customer_id},
 
 978               netamount = $netamount,
 
 979               paid = $form->{paid},
 
 980               datepaid = $datepaid,
 
 982               deliverydate = $deliverydate,
 
 984               shippingpoint = '$form->{shippingpoint}',
 
 985               shipvia = '$form->{shipvia}',
 
 986               terms = $form->{terms},
 
 987               notes = '$form->{notes}',
 
 988               intnotes = '$form->{intnotes}',
 
 989               taxincluded = '$form->{taxincluded}',
 
 990               curr = '$form->{currency}',
 
 991               department_id = $form->{department_id},
 
 992               payment_id = $form->{payment_id},
 
 993               type = '$form->{type}',
 
 994               language_id = $form->{language_id},
 
 995               taxzone_id = $form->{taxzone_id},
 
 996               shipto_id = $form->{shipto_id},
 
 997               delivery_customer_id = $form->{delivery_customer_id},
 
 998               delivery_vendor_id = $form->{delivery_vendor_id},
 
 999               employee_id = $form->{employee_id},
 
1000               storno = '$form->{storno}',
 
1001               cp_id = $form->{contact_id}
 
1002               WHERE id = $form->{id}
 
1004   $dbh->do($query) || $form->dberror($query);
 
1006   if ($form->{storno}) {
 
1007     $query = qq| update ar set paid=paid+amount where id=$form->{storno_id}|;
 
1008     $dbh->do($query) || $form->dberror($query);
 
1009     $query = qq| update ar set storno='$form->{storno}' where id=$form->{storno_id}|;
 
1010     $dbh->do($query) || $form->dberror($query);
 
1011     $query = qq§ update ar set intnotes='Rechnung storniert am $form->{invdate} ' || intnotes where id=$form->{storno_id}§;
 
1012     $dbh->do($query) || $form->dberror($query);
 
1014     $query = qq| update ar set paid=amount where id=$form->{id}|;
 
1015     $dbh->do($query) || $form->dberror($query);
 
1018   $form->{pago_total} = $amount;
 
1021   $form->{name} = $form->{customer};
 
1022   $form->{name} =~ s/--$form->{customer_id}//;
 
1024   if (!$form->{shipto_id}) {
 
1025     $form->add_shipto($dbh, $form->{id}, "AR");
 
1028   # save printed, emailed and queued
 
1029   $form->save_status($dbh);
 
1031   if ($form->{webdav}) {
 
1032     &webdav_folder($myconfig, $form);
 
1035   my $rc = $dbh->commit;
 
1038   $main::lxdebug->leave_sub();
 
1044   $main::lxdebug->enter_sub();
 
1046   my ($self, $myconfig, $form, $locale) = @_;
 
1048   # connect to database, turn off autocommit
 
1049   my $dbh = $form->dbconnect_noauto($myconfig);
 
1051   $form->{datepaid} = $form->{invdate};
 
1053   # total payments, don't move we need it here
 
1054   for my $i (1 .. $form->{paidaccounts}) {
 
1055     if ($form->{type} eq "credit_note") {
 
1056       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"}) * -1;
 
1058       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
 
1060     $form->{paid} += $form->{"paid_$i"};
 
1061     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
 
1064   $form->{exchangerate} =
 
1065       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
 
1068   # record payments and offsetting AR
 
1069   for my $i (1 .. $form->{paidaccounts}) {
 
1071     if ($form->{"paid_$i"} != 0) {
 
1072       my ($accno) = split /--/, $form->{"AR_paid_$i"};
 
1073       $form->{"datepaid_$i"} = $form->{invdate}
 
1074         unless ($form->{"datepaid_$i"});
 
1075       $form->{datepaid} = $form->{"datepaid_$i"};
 
1078       if (($form->{currency} eq $form->{defaultcurrency}) || ($form->{defaultcurrency} eq "")) {
 
1079         $form->{"exchangerate_$i"} = 1;
 
1082           $form->check_exchangerate($myconfig, $form->{currency},
 
1083                                     $form->{"datepaid_$i"}, 'buy');
 
1085         $form->{"exchangerate_$i"} =
 
1088           : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
1093         $form->round_amount($form->{"paid_$i"} * $form->{"exchangerate"},
 
1097       $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
 
1098                                       WHERE c.accno = '$form->{AR}') AND amount=$amount AND transdate='$form->{"datepaid_$i"}'|;
 
1099       $dbh->do($query) || $form->dberror($query);
 
1101       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
1103                   VALUES ($form->{id}, (SELECT c.id FROM chart c
 
1104                                       WHERE c.accno = '$form->{AR}'),
 
1105                   $amount, '$form->{"datepaid_$i"}')|;
 
1106       $dbh->do($query) || $form->dberror($query);
 
1110       $form->{"paid_$i"} *= -1;
 
1112       $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
 
1113                                       WHERE c.accno = '$accno') AND amount=$form->{"paid_$i"} AND transdate='$form->{"datepaid_$i"}' AND source='$form->{"source_$i"}' AND memo='$form->{"memo_$i"}'|;
 
1114       $dbh->do($query) || $form->dberror($query);
 
1116       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
 
1118                   VALUES ($form->{id}, (SELECT c.id FROM chart c
 
1119                                       WHERE c.accno = '$accno'),
 
1120                   $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
 
1121                   '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
 
1122       $dbh->do($query) || $form->dberror($query);
 
1127         $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
 
1128         $form->{"exchangerate_$i"};
 
1130         $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
 
1133         $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
 
1139       # update exchange rate
 
1140       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
1141         $form->update_exchangerate($dbh, $form->{currency},
 
1142                                    $form->{"datepaid_$i"},
 
1143                                    $form->{"exchangerate_$i"}, 0);
 
1148   # record exchange rate differences and gains/losses
 
1149   foreach my $accno (keys %{ $form->{fx} }) {
 
1150     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
 
1152           ($form->{fx}{$accno}{$transdate} =
 
1153            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
 
1156         $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
 
1157                                         WHERE c.accno = '$accno') AND amount=$form->{fx}{$accno}{$transdate} AND transdate='$transdate' AND cleared='0' AND fx_transaction='1'|;
 
1158         $dbh->do($query) || $form->dberror($query);
 
1159         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
1160                     transdate, cleared, fx_transaction)
 
1161                     VALUES ($form->{id},
 
1162                            (SELECT c.id FROM chart c
 
1163                             WHERE c.accno = '$accno'),
 
1164                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1')|;
 
1165         $dbh->do($query) || $form->dberror($query);
 
1169   my $datepaid = ($form->{paid})    ? qq|'$form->{datepaid}'| : "NULL";
 
1172   my $query = qq|UPDATE ar set
 
1173               paid = $form->{paid},
 
1174               datepaid = $datepaid
 
1175               WHERE id=$form->{id}|;
 
1177   $dbh->do($query) || $form->dberror($query);
 
1179   my $rc = $dbh->commit;
 
1182   $main::lxdebug->leave_sub();
 
1187 sub process_assembly {
 
1188   $main::lxdebug->enter_sub();
 
1190   my ($dbh, $form, $id, $totalqty) = @_;
 
1192   my $query = qq|SELECT a.parts_id, a.qty, p.assembly,
 
1193                  p.partnumber, p.description, p.unit,
 
1194                  p.inventory_accno_id, p.income_accno_id,
 
1197                  JOIN parts p ON (a.parts_id = p.id)
 
1199   my $sth = $dbh->prepare($query);
 
1200   $sth->execute || $form->dberror($query);
 
1202   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1206     $ref->{inventory_accno_id} *= 1;
 
1207     $ref->{expense_accno_id}   *= 1;
 
1209     map { $ref->{$_} =~ s/\'/\'\'/g } (qw(partnumber description unit));
 
1211     # multiply by number of assemblies
 
1212     $ref->{qty} *= $totalqty;
 
1214     if ($ref->{assembly}) {
 
1215       &process_assembly($dbh, $form, $ref->{parts_id}, $ref->{qty});
 
1218       if ($ref->{inventory_accno_id}) {
 
1219         $allocated = &cogs($dbh, $form, $ref->{parts_id}, $ref->{qty});
 
1223     # save detail record for individual assembly item in invoice table
 
1224     $query = qq|INSERT INTO invoice (trans_id, description, parts_id, qty,
 
1225                 sellprice, fxsellprice, allocated, assemblyitem, unit)
 
1227                 ($form->{id}, '$ref->{description}',
 
1228                 $ref->{parts_id}, $ref->{qty}, 0, 0, $allocated, 't',
 
1230     $dbh->do($query) || $form->dberror($query);
 
1236   $main::lxdebug->leave_sub();
 
1240   $main::lxdebug->enter_sub();
 
1242   my ($dbh, $form, $id, $totalqty, $basefactor) = @_;
 
1244   my $query = qq|SELECT i.id, i.trans_id, i.base_qty, i.allocated, i.sellprice,
 
1245                    (SELECT c.accno FROM chart c
 
1246                     WHERE p.inventory_accno_id = c.id) AS inventory_accno,
 
1247                    (SELECT c.accno FROM chart c
 
1248                     WHERE p.expense_accno_id = c.id) AS expense_accno
 
1249                   FROM invoice i, parts p
 
1250                   WHERE i.parts_id = p.id
 
1251                   AND i.parts_id = $id
 
1252                   AND (i.base_qty + i.allocated) < 0
 
1254   my $sth = $dbh->prepare($query);
 
1255   $sth->execute || $form->dberror($query);
 
1260   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1261     if (($qty = (($ref->{base_qty} * -1) - $ref->{allocated})) > $totalqty) {
 
1265     $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|,
 
1268     # total expenses and inventory
 
1269     # sellprice is the cost of the item
 
1270     $linetotal = $form->round_amount(($ref->{sellprice} * $qty) / $basefactor, 2);
 
1275       $form->{amount}{ $form->{id} }{ $ref->{expense_accno} } += -$linetotal;
 
1276       $form->{expense_inventory} .= " " . $ref->{expense_accno};
 
1279       $form->{amount}{ $form->{id} }{ $ref->{inventory_accno} } -= -$linetotal;
 
1280       $form->{expense_inventory} .= " " . $ref->{inventory_accno};
 
1284     $allocated += -$qty;
 
1286     last if (($totalqty -= $qty) <= 0);
 
1291   $main::lxdebug->leave_sub();
 
1296 sub reverse_invoice {
 
1297   $main::lxdebug->enter_sub();
 
1299   my ($dbh, $form) = @_;
 
1301   # reverse inventory items
 
1302   my $query = qq|SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
 
1303                  p.inventory_accno_id
 
1305                  JOIN parts p ON (i.parts_id = p.id)
 
1306                  WHERE i.trans_id = $form->{id}|;
 
1307   my $sth = $dbh->prepare($query);
 
1308   $sth->execute || $form->dberror($query);
 
1310   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1312     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
 
1314       # if the invoice item is not an assemblyitem adjust parts onhand
 
1315       if (!$ref->{assemblyitem}) {
 
1317         # adjust onhand in parts table
 
1318         $form->update_balance($dbh, "parts", "onhand",
 
1319                               qq|id = $ref->{parts_id}|,
 
1323       # loop if it is an assembly
 
1324       next if ($ref->{assembly});
 
1326       # de-allocated purchases
 
1327       $query = qq|SELECT i.id, i.trans_id, i.allocated
 
1329                   WHERE i.parts_id = $ref->{parts_id}
 
1331                   ORDER BY i.trans_id DESC|;
 
1332       my $sth = $dbh->prepare($query);
 
1333       $sth->execute || $form->dberror($query);
 
1335       while (my $inhref = $sth->fetchrow_hashref(NAME_lc)) {
 
1337         if (($ref->{qty} - $inhref->{allocated}) > 0) {
 
1338           $qty = $inhref->{allocated};
 
1342         $form->update_balance($dbh, "invoice", "allocated",
 
1343                               qq|id = $inhref->{id}|,
 
1346         last if (($ref->{qty} -= $qty) <= 0);
 
1355   $query = qq|DELETE FROM acc_trans
 
1356               WHERE trans_id = $form->{id}|;
 
1357   $dbh->do($query) || $form->dberror($query);
 
1359   # delete invoice entries
 
1360   $query = qq|DELETE FROM invoice
 
1361               WHERE trans_id = $form->{id}|;
 
1362   $dbh->do($query) || $form->dberror($query);
 
1364   if ($form->{lizenzen}) {
 
1365     $query = qq|DELETE FROM licenseinvoice
 
1366               WHERE trans_id in (SELECT id FROM invoice WHERE trans_id = $form->{id})|;
 
1367     $dbh->do($query) || $form->dberror($query);
 
1370   $query = qq|DELETE FROM shipto
 
1371               WHERE trans_id = $form->{id} AND module = 'AR'|;
 
1372   $dbh->do($query) || $form->dberror($query);
 
1374   $main::lxdebug->leave_sub();
 
1377 sub delete_invoice {
 
1378   $main::lxdebug->enter_sub();
 
1380   my ($self, $myconfig, $form, $spool) = @_;
 
1382   # connect to database
 
1383   my $dbh = $form->dbconnect_noauto($myconfig);
 
1385   &reverse_invoice($dbh, $form);
 
1388   my $query = qq|DELETE FROM ar
 
1389                  WHERE id = $form->{id}|;
 
1390   $dbh->do($query) || $form->dberror($query);
 
1392   # delete spool files
 
1393   $query = qq|SELECT s.spoolfile FROM status s
 
1394               WHERE s.trans_id = $form->{id}|;
 
1395   my $sth = $dbh->prepare($query);
 
1396   $sth->execute || $self->dberror($query);
 
1399   my @spoolfiles = ();
 
1401   while (($spoolfile) = $sth->fetchrow_array) {
 
1402     push @spoolfiles, $spoolfile;
 
1406   # delete status entries
 
1407   $query = qq|DELETE FROM status
 
1408               WHERE trans_id = $form->{id}|;
 
1409   $dbh->do($query) || $form->dberror($query);
 
1411   my $rc = $dbh->commit;
 
1415     foreach $spoolfile (@spoolfiles) {
 
1416       unlink "$spool/$spoolfile" if $spoolfile;
 
1420   $main::lxdebug->leave_sub();
 
1425 sub retrieve_invoice {
 
1426   $main::lxdebug->enter_sub();
 
1428   my ($self, $myconfig, $form) = @_;
 
1430   # connect to database
 
1431   my $dbh = $form->dbconnect_noauto($myconfig);
 
1437     # get default accounts and last invoice number
 
1438     $query = qq|SELECT (SELECT c.accno FROM chart c
 
1439                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
 
1440                        (SELECT c.accno FROM chart c
 
1441                         WHERE d.income_accno_id = c.id) AS income_accno,
 
1442                        (SELECT c.accno FROM chart c
 
1443                         WHERE d.expense_accno_id = c.id) AS expense_accno,
 
1444                        (SELECT c.accno FROM chart c
 
1445                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
1446                        (SELECT c.accno FROM chart c
 
1447                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
1448                 d.curr AS currencies
 
1451     $query = qq|SELECT (SELECT c.accno FROM chart c
 
1452                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
 
1453                        (SELECT c.accno FROM chart c
 
1454                         WHERE d.income_accno_id = c.id) AS income_accno,
 
1455                        (SELECT c.accno FROM chart c
 
1456                         WHERE d.expense_accno_id = c.id) AS expense_accno,
 
1457                        (SELECT c.accno FROM chart c
 
1458                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
1459                        (SELECT c.accno FROM chart c
 
1460                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
1461                 d.curr AS currencies, current_date AS invdate
 
1464   my $sth = $dbh->prepare($query);
 
1465   $sth->execute || $form->dberror($query);
 
1467   my $ref = $sth->fetchrow_hashref(NAME_lc);
 
1468   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1474     $query = qq|SELECT a.invnumber, a.ordnumber, a.quonumber, a.cusordnumber,
 
1475                 a.transdate AS invdate, a.deliverydate, a.paid, a.storno,
 
1476                 a.shippingpoint, a.shipvia, a.terms, a.notes, a.intnotes, a.taxzone_id,
 
1477                 a.duedate, a.taxincluded, a.curr AS currency, a.shipto_id, a.cp_id,
 
1478                 a.employee_id, e.name AS employee, a.payment_id, a.language_id, a.delivery_customer_id, a.delivery_vendor_id, a.type
 
1480                 LEFT JOIN employee e ON (e.id = a.employee_id)
 
1481                 WHERE a.id = $form->{id}|;
 
1482     $sth = $dbh->prepare($query);
 
1483     $sth->execute || $form->dberror($query);
 
1485     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1486     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1489     $form->{exchangerate} =
 
1490       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
 
1493     $query = qq|SELECT s.* FROM shipto s
 
1494                 WHERE s.trans_id = $form->{id} AND s.module = 'AR'|;
 
1495     $sth = $dbh->prepare($query);
 
1496     $sth->execute || $form->dberror($query);
 
1498     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1500     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1503    if ($form->{delivery_customer_id}) {
 
1504       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_customer_id}|;
 
1505       $sth = $dbh->prepare($query);
 
1506       $sth->execute || $form->dberror($query);
 
1507       ($form->{delivery_customer_string}) = $sth->fetchrow_array();
 
1511     if ($form->{delivery_vendor_id}) {
 
1512       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_vendor_id}|;
 
1513       $sth = $dbh->prepare($query);
 
1514       $sth->execute || $form->dberror($query);
 
1515       ($form->{delivery_vendor_string}) = $sth->fetchrow_array();
 
1519     # get printed, emailed
 
1520     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
 
1522                 WHERE s.trans_id = $form->{id}|;
 
1523     $sth = $dbh->prepare($query);
 
1524     $sth->execute || $form->dberror($query);
 
1526     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1527       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
1528       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
1529       $form->{queued} .= "$ref->{formname} $ref->{spoolfile} "
 
1530         if $ref->{spoolfile};
 
1533     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
1535     my $transdate = "current_date";
 
1536     if($form->{invdate}) {
 
1537      $transdate = "'$form->{invdate}'";
 
1540     if(!$form->{taxzone_id}) {
 
1541       $form->{taxzone_id} = 0;
 
1543     # retrieve individual items
 
1545                 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
 
1546                 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
 
1547                 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
 
1548                 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice,
 
1549                 i.discount, i.parts_id AS id, i.unit, i.deliverydate,
 
1550                 i.project_id, pr.projectnumber, i.serialnumber,
 
1551                 p.partnumber, p.assembly, p.bin, p.notes AS partnotes, p.inventory_accno_id AS part_inventory_accno_id, i.id AS invoice_pos,
 
1552                 pg.partsgroup, i.pricegroup_id, (SELECT pricegroup FROM pricegroup WHERE id=i.pricegroup_id) as pricegroup,
 
1553                 i.ordnumber, i.transdate, i.cusordnumber, p.alu, p.formel, i.subtotal
 
1555                 JOIN parts p ON (i.parts_id = p.id)
 
1556                 LEFT JOIN project pr ON (i.project_id = pr.id)
 
1557                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1558                 LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
 
1559                 LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
 
1560                 LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
 
1561                 WHERE i.trans_id = $form->{id}
 
1562                 AND NOT i.assemblyitem = '1'
 
1564     $sth = $dbh->prepare($query);
 
1566     $sth->execute || $form->dberror($query);
 
1567     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1568       if (!$ref->{"part_inventory_accno_id"}) {
 
1569         map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
 
1571       delete($ref->{"part_inventory_accno_id"});
 
1573       #set expense_accno=inventory_accno if they are different => bilanz
 
1576     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
 
1577       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}|;
 
1578       my $stw = $dbh->prepare($query);
 
1579       $stw->execute || $form->dberror($query);
 
1580       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
 
1584     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
 
1585       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}|;
 
1586       my $stw = $dbh->prepare($query);
 
1587       $stw->execute || $form->dberror($query);
 
1588       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
 
1592     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
 
1593       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}|;
 
1594       my $stw = $dbh->prepare($query);
 
1595       $stw->execute || $form->dberror($query);
 
1596       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
 
1601         ($ref->{expense_accno} != $ref->{inventory_accno})
 
1602         ? $ref->{inventory_accno}
 
1603         : $ref->{expense_accno};
 
1605       # get tax rates and description
 
1607         ($form->{vc} eq "customer") ? $ref->{income_accno} : $vendor_accno;
 
1608       $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
 
1609                  FROM tax t LEFT join chart c ON (c.id=t.chart_id)
 
1610                  WHERE t.taxkey in (SELECT taxkey_id from chart where accno = '$accno_id')
 
1612       $stw = $dbh->prepare($query);
 
1613       $stw->execute || $form->dberror($query);
 
1614       $ref->{taxaccounts} = "";
 
1616       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
1618         #    if ($customertax{$ref->{accno}}) {
 
1619         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
 
1623         $ref->{taxaccounts} .= "$ptr->{accno} ";
 
1625         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
 
1626           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
1627           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
 
1628           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
1629           $form->{taxaccounts} .= "$ptr->{accno} ";
 
1634       if ($form->{lizenzen}) {
 
1635         $query = qq|SELECT l.licensenumber, l.id AS licenseid
 
1636                  FROM license l, licenseinvoice li
 
1637                  WHERE l.id = li.license_id AND li.trans_id = $ref->{invoice_pos}|;
 
1638         $stg = $dbh->prepare($query);
 
1639         $stg->execute || $form->dberror($query);
 
1640         ($licensenumber, $licenseid) = $stg->fetchrow_array();
 
1642           "<option value=\"$licenseid\">$licensenumber</option>";
 
1645       if ($form->{type} eq "credit_note") {
 
1649       chop $ref->{taxaccounts};
 
1650       push @{ $form->{invoice_details} }, $ref;
 
1655     if ($form->{webdav}) {
 
1656       &webdav_folder($myconfig, $form);
 
1660   my $rc = $dbh->commit;
 
1663   $main::lxdebug->leave_sub();
 
1669   $main::lxdebug->enter_sub();
 
1671   my ($self, $myconfig, $form) = @_;
 
1673   # connect to database
 
1674   my $dbh = $form->dbconnect($myconfig);
 
1676   my $dateformat = $myconfig->{dateformat};
 
1677   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
1681     ? "to_date('$form->{invdate}', '$dateformat')"
 
1684   $form->{customer_id} *= 1;
 
1687   my $query = qq|SELECT c.name AS customer, c.discount, c.creditlimit, c.terms,
 
1688                  c.email, c.cc, c.bcc, c.language_id, c.payment_id AS customer_payment_id,
 
1689                  c.street, c.zipcode, c.city, c.country,
 
1690                  $duedate + c.terms AS duedate, c.notes AS intnotes,
 
1691                  b.discount AS tradediscount, b.description AS business, c.klass as customer_klass, c.taxzone_id
 
1693                  LEFT JOIN business b ON (b.id = c.business_id)
 
1694                  WHERE c.id = $form->{customer_id}|;
 
1695   my $sth = $dbh->prepare($query);
 
1696   $sth->execute || $form->dberror($query);
 
1698   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1700   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1703   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|;
 
1704   my $sth = $dbh->prepare($query);
 
1706   $sth->execute || $form->dberror($query);
 
1708   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1710   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1713   #print(STDERR "DUNNING AMOUTN $form->{dunning_amount}\n");
 
1715   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|;
 
1716   my $sth = $dbh->prepare($query);
 
1718   $sth->execute || $form->dberror($query);
 
1720   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1722   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1724   #print(STDERR "LEVEL $form->{max_dunning_level}\n");
 
1727   #check whether payment_terms are better than old payment_terms
 
1728   if (($form->{payment_id} ne "") && ($form->{customer_payment_id} ne "")) {
 
1729     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})|;
 
1730     my $stw = $dbh->prepare($query);
 
1731     $stw->execute || $form->dberror($query);
 
1732     ($old_ranking, $new_ranking) = $stw->fetchrow_array;
 
1734     if ($new_ranking > $old_ranking) {
 
1735       $form->{payment_id} =$form->{customer_payment_id};
 
1738   if ($form->{payment_id} eq "") {
 
1739     $form->{payment_id} =$form->{customer_payment_id};
 
1742   $form->{creditremaining} = $form->{creditlimit};
 
1743   $query = qq|SELECT SUM(a.amount - a.paid)
 
1745               WHERE a.customer_id = $form->{customer_id}|;
 
1746   $sth = $dbh->prepare($query);
 
1747   $sth->execute || $form->dberror($query);
 
1749   ($form->{creditremaining}) -= $sth->fetchrow_array;
 
1753   $query = qq|SELECT o.amount,
 
1754                 (SELECT e.buy FROM exchangerate e
 
1755                  WHERE e.curr = o.curr
 
1756                  AND e.transdate = o.transdate)
 
1758               WHERE o.customer_id = $form->{customer_id}
 
1759               AND o.quotation = '0'
 
1760               AND o.closed = '0'|;
 
1761   $sth = $dbh->prepare($query);
 
1762   $sth->execute || $form->dberror($query);
 
1764   while (my ($amount, $exch) = $sth->fetchrow_array) {
 
1765     $exch = 1 unless $exch;
 
1766     $form->{creditremaining} -= $amount * $exch;
 
1770   $form->get_contacts($dbh, $form->{customer_id});
 
1771   $form->{cp_id} *= 1;
 
1773   # get contact if selected
 
1774   if ($form->{cp_id}) {
 
1775     $form->get_contact($dbh, $form->{cp_id});
 
1778   # get shipto if we did not converted an order or invoice
 
1779   if (!$form->{shipto}) {
 
1780     map { delete $form->{$_} }
 
1781       qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail);
 
1783     $query = qq|SELECT s.* FROM shipto s
 
1784                 WHERE s.trans_id = $form->{customer_id} AND s.module = 'CT'|;
 
1785     $sth = $dbh->prepare($query);
 
1786     $sth->execute || $form->dberror($query);
 
1788     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1790     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1794   # get taxes we charge for this customer
 
1795   $query = qq|SELECT c.accno
 
1797               JOIN customertax ct ON (ct.chart_id = c.id)
 
1798               WHERE ct.customer_id = $form->{customer_id}|;
 
1799   $sth = $dbh->prepare($query);
 
1800   $sth->execute || $form->dberror($query);
 
1802   my $customertax = ();
 
1803   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1804     $customertax{ $ref->{accno} } = 1;
 
1808   # get shipping addresses
 
1809   $query = qq|SELECT s.id,s.shiptoname
 
1811               WHERE s.trans_id = $form->{customer_id}|;
 
1812   $sth = $dbh->prepare($query);
 
1813   $sth->execute || $form->dberror($query);
 
1815   my $customertax = ();
 
1816   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1817     push(@{ $form->{SHIPTO} }, $ref);
 
1821   # setup last accounts used for this customer
 
1822   if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
 
1823     $query = qq|SELECT c.accno, c.description, c.link, c.category
 
1825                 JOIN acc_trans ac ON (ac.chart_id = c.id)
 
1826                 JOIN ar a ON (a.id = ac.trans_id)
 
1827                 WHERE a.customer_id = $form->{customer_id}
 
1828                 AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
 
1829                 AND a.id IN (SELECT max(a2.id) FROM ar a2
 
1830                              WHERE a2.customer_id = $form->{customer_id})|;
 
1831     $sth = $dbh->prepare($query);
 
1832     $sth->execute || $form->dberror($query);
 
1835     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1836       if ($ref->{category} eq 'I') {
 
1838         $form->{"AR_amount_$i"} = "$ref->{accno}--$ref->{description}";
 
1840       if ($ref->{category} eq 'A') {
 
1841         $form->{ARselected} = $form->{AR_1} =
 
1842           "$ref->{accno}--$ref->{description}";
 
1846     $form->{rowcount} = $i if ($i && !$form->{type});
 
1851   $main::lxdebug->leave_sub();
 
1855   $main::lxdebug->enter_sub();
 
1857   my ($self, $myconfig, $form) = @_;
 
1859   my $i = $form->{rowcount};
 
1861   my $where = "NOT p.obsolete = '1'";
 
1863   if ($form->{"partnumber_$i"}) {
 
1864     my $partnumber = $form->like(lc $form->{"partnumber_$i"});
 
1865     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
 
1867   if ($form->{"description_$i"}) {
 
1868     my $description = $form->like(lc $form->{"description_$i"});
 
1869     $where .= " AND lower(p.description) LIKE '$description'";
 
1872   if ($form->{"partsgroup_$i"}) {
 
1873     my $partsgroup = $form->like(lc $form->{"partsgroup_$i"});
 
1874     $where .= " AND lower(pg.partsgroup) LIKE '$partsgroup'";
 
1877   if ($form->{"description_$i"}) {
 
1878     $where .= " ORDER BY p.description";
 
1880     $where .= " ORDER BY p.partnumber";
 
1884   if ($form->{type} eq "invoice") {
 
1885     $transdate = "'$form->{invdate}'";
 
1886   } elsif ($form->{type} eq "sales_order") {
 
1887     $transdate = "'$form->{transdate}'";
 
1888   } elsif ($form->{type} eq "sales_quotation") {
 
1889     $transdate = "'$form->{transdate}'";
 
1892   if ($transdate eq "") {
 
1893     $transdate = "current_date";
 
1896   # connect to database
 
1897   my $dbh = $form->dbconnect($myconfig);
 
1899   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
 
1900                         p.listprice, p.inventory_accno_id,
 
1901                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
 
1902                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
 
1903                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
 
1904                  p.unit, p.assembly, p.bin, p.onhand, p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
 
1905                  pg.partsgroup, p.formel, p.alu, p.payment_id AS part_payment_id, adr.adr_description
 
1907                  LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
 
1908                  LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
 
1909                  LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
 
1910                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
 
1911                  LEFT JOIN adr adr ON (adr.id = p.adr_id)
 
1913   my $sth = $dbh->prepare($query);
 
1914   $sth->execute || $form->dberror($query);
 
1916   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1918     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
 
1919     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
 
1920     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
 
1921     if (!$ref->{inventory_accno_id}) {
 
1922       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
 
1924     delete($ref->{inventory_accno_id});
 
1926     #set expense_accno=inventory_accno if they are different => bilanz
 
1929     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
 
1930       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}|;
 
1931       my $stw = $dbh->prepare($query);
 
1932       $stw->execute || $form->dberror($query);
 
1933       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
 
1937     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
 
1938       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}|;
 
1939       my $stw = $dbh->prepare($query);
 
1940       $stw->execute || $form->dberror($query);
 
1941       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
 
1945     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
 
1946       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}|;
 
1947       my $stw = $dbh->prepare($query);
 
1948       $stw->execute || $form->dberror($query);
 
1949       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
 
1953     #check whether payment_terms are better than old payment_terms
 
1954     if (($form->{payment_id} ne "") && ($ref->{part_payment_id} ne "")) {
 
1955       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})|;
 
1956       my $stw = $dbh->prepare($query);
 
1957       $stw->execute || $form->dberror($query);
 
1958       ($old_ranking, $new_ranking) = $stw->fetchrow_array;
 
1960       if ($new_ranking <= $old_ranking) {
 
1961         $ref->{part_payment_id} = "";
 
1967       ($ref->{expense_accno} != $ref->{inventory_accno})
 
1968       ? $ref->{inventory_accno}
 
1969       : $ref->{expense_accno};
 
1971     # get tax rates and description
 
1973       ($form->{vc} eq "customer") ? $ref->{income_accno} : $vendor_accno;
 
1974     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
 
1975               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
 
1976               WHERE t.taxkey in (SELECT c2.taxkey_id from chart c2 where c2.accno = '$accno_id')
 
1978     $stw = $dbh->prepare($query);
 
1979     $stw->execute || $form->dberror($query);
 
1981     $ref->{taxaccounts} = "";
 
1983     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
1985       #    if ($customertax{$ref->{accno}}) {
 
1986       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
 
1990       $ref->{taxaccounts} .= "$ptr->{accno} ";
 
1992       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
 
1993         $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
1994         $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
 
1995         $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
1996         $form->{taxaccounts} .= "$ptr->{accno} ";
 
2002     chop $ref->{taxaccounts};
 
2003     if ($form->{language_id}) {
 
2004       $query = qq|SELECT tr.translation, tr.longdescription
 
2006                 WHERE tr.language_id=$form->{language_id} AND tr.parts_id=$ref->{id}|;
 
2007       $stw = $dbh->prepare($query);
 
2008       $stw->execute || $form->dberror($query);
 
2009       my ($translation, $longdescription) = $stw->fetchrow_array();
 
2010       if ($translation ne "") {
 
2011         $ref->{description} = $translation;
 
2012         $ref->{longdescription} = $longdescription;
 
2015         $query = qq|SELECT tr.translation, tr.longdescription
 
2017                 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|;
 
2018         $stg = $dbh->prepare($query);
 
2019         $stg->execute || $form->dberror($query);
 
2020         my ($translation) = $stg->fetchrow_array();
 
2021         if ($translation ne "") {
 
2022           $ref->{description} = $translation;
 
2023           $ref->{longdescription} = $longdescription;
 
2030     push @{ $form->{item_list} }, $ref;
 
2032     if ($form->{lizenzen}) {
 
2033       if ($ref->{inventory_accno} > 0) {
 
2035           qq| SELECT l.* FROM license l WHERE l.parts_id = $ref->{id} AND NOT l.id IN (SELECT li.license_id FROM licenseinvoice li)|;
 
2036         $stw = $dbh->prepare($query);
 
2037         $stw->execute || $form->dberror($query);
 
2038         while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
2039           push @{ $form->{LIZENZEN}{ $ref->{id} } }, $ptr;
 
2048   $main::lxdebug->leave_sub();
 
2051 ##########################
 
2052 # get pricegroups from database
 
2053 # build up selected pricegroup
 
2054 # if an exchange rate - change price
 
2057 sub get_pricegroups_for_parts {
 
2059   $main::lxdebug->enter_sub();
 
2061   my ($self, $myconfig, $form) = @_;
 
2063   my $dbh = $form->dbconnect($myconfig);
 
2067   my $dimension_units = AM->retrieve_units($myconfig, $form, "dimension");
 
2068   my $service_units = AM->retrieve_units($myconfig, $form, "service");
 
2069   my $all_units = AM->retrieve_units($myconfig, $form);
 
2070   while (($form->{"id_$i"}) or ($form->{"new_id_$i"})) {
 
2072     $id = $form->{"id_$i"};
 
2074     if (!($form->{"id_$i"}) and $form->{"new_id_$i"}) {
 
2076       $id = $form->{"new_id_$i"};
 
2079     ($price, $selectedpricegroup_id) = split /--/,
 
2080       $form->{"sellprice_drag_$i"};
 
2082     $pricegroup_old = $form->{"pricegroup_old_$i"};
 
2083     $form->{"new_pricegroup_$i"} = $selectedpricegroup_id;
 
2084     $form->{"old_pricegroup_$i"} = $pricegroup_old;
 
2085     $price_new = $form->{"price_new_$i"};
 
2087     $price_old = $form->{"price_old_$i"};
 
2089       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|;
 
2091     $pkq = $dbh->prepare($query);
 
2092     $pkq->execute || $form->dberror($query);
 
2093     if (!$form->{"unit_old_$i"}) {
 
2094       # Neue Ware aus der Datenbank. In diesem Fall ist unit_$i die
 
2095       # Einheit, wie sie in den Stammdaten hinterlegt wurde.
 
2096       # Es sollte also angenommen werden, dass diese ausgewaehlt war.
 
2097       $form->{"unit_old_$i"} = $form->{"unit_$i"};
 
2100     # Die zuletzt ausgewaehlte mit der aktuell ausgewaehlten Einheit
 
2101     # vergleichen und bei Unterschied den Preis entsprechend umrechnen.
 
2102     $form->{"selected_unit_$i"} = $form->{"unit_$i"} unless ($form->{"selected_unit_$i"});
 
2104     my $check_units = $form->{"inventory_accno_$i"} ? $dimension_units : $service_units;
 
2105     if (!$check_units->{$form->{"selected_unit_$i"}} ||
 
2106         ($check_units->{$form->{"selected_unit_$i"}}->{"base_unit"} ne
 
2107          $all_units->{$form->{"unit_old_$i"}}->{"base_unit"})) {
 
2108       # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
 
2109       # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
 
2110       # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
 
2111       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};
 
2115     if ($form->{"unit_old_$i"} ne $form->{"selected_unit_$i"}) {
 
2116       if (defined($all_units->{$form->{"unit_old_$i"}}->{"factor"}) &&
 
2117           $all_units->{$form->{"unit_old_$i"}}->{"factor"}) {
 
2118         $basefactor = $all_units->{$form->{"selected_unit_$i"}}->{"factor"} /
 
2119           $all_units->{$form->{"unit_old_$i"}}->{"factor"};
 
2122     if (!$form->{"basefactor_$i"}) {
 
2123       $form->{"basefactor_$i"} = 1;
 
2125     while ($pkr = $pkq->fetchrow_hashref(NAME_lc)) {
 
2127       #       push @{ $form->{PRICES}{$id} }, $pkr;
 
2128       #push @{ $form->{PRICES}{$i} }, $pkr;
 
2130       $pkr->{selected} = '';
 
2132       # if there is an exchange rate change price
 
2133       if (($form->{exchangerate} * 1) != 0) {
 
2135         $pkr->{price} /= $form->{exchangerate};
 
2138       $pkr->{price} *= $form->{"basefactor_$i"};
 
2140       $pkr->{price} *= $basefactor;
 
2142       $pkr->{price} = $form->format_amount($myconfig, $pkr->{price}, 5);
 
2144       if ($selectedpricegroup_id eq undef) {
 
2145         if ($pkr->{pricegroup_id} eq $form->{customer_klass}) {
 
2147           $pkr->{selected}  = ' selected';
 
2149           # no customer pricesgroup set
 
2150           if ($pkr->{price} == $pkr->{default_sellprice}) {
 
2152             $pkr->{price} = $form->{"sellprice_$i"};
 
2156             $form->{"sellprice_$i"} = $pkr->{price};
 
2160           if ($pkr->{price} == $pkr->{default_sellprice}) {
 
2162             $pkr->{price}    = $form->{"sellprice_$i"};
 
2163             $pkr->{selected} = ' selected';
 
2168       if ($selectedpricegroup_id or $selectedpricegroup_id == 0) {
 
2169         if ($selectedpricegroup_id ne $pricegroup_old) {
 
2170           if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
 
2171             $pkr->{selected}  = ' selected';
 
2174           if (($price_new != $form->{"sellprice_$i"}) and ($price_new ne 0)) {
 
2175             if ($pkr->{pricegroup_id} == 0) {
 
2176               $pkr->{price}     = $form->{"sellprice_$i"};
 
2177               $pkr->{selected}  = ' selected';
 
2180             if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
 
2181               $pkr->{selected}  = ' selected';
 
2182               if (    ($pkr->{pricegroup_id} == 0)
 
2183                   and ($pkr->{price} == $form->{"sellprice_$i"})) {
 
2185                 # $pkr->{price}                         = $form->{"sellprice_$i"};
 
2187                 $pkr->{price} = $form->{"sellprice_$i"};
 
2193       push @{ $form->{PRICES}{$i} }, $pkr;
 
2196     $form->{"basefactor_$i"} *= $basefactor;
 
2205   $main::lxdebug->leave_sub();
 
2209   $main::lxdebug->enter_sub();
 
2211   my ($myconfig, $form) = @_;
 
2214     $path = "webdav/rechnungen/" . $form->{invnumber}, last SWITCH
 
2215       if ($form->{vc} eq "customer");
 
2216     $path = "webdav/einkaufsrechnungen/" . $form->{invnumber}, last SWITCH
 
2217       if ($form->{vc} eq "vendor");
 
2221     mkdir($path, 0770) or die "can't make directory $!\n";
 
2225       foreach $file (@files) {
 
2226         $file =~ /\/([^\/]*)$/;
 
2228         $ENV{'SCRIPT_NAME'} =~ /\/([^\/]*)\//;
 
2230         $link  = "http://" . $ENV{'SERVER_NAME'} . "/" . $lxerp . "/" . $file;
 
2231         $form->{WEBDAV}{$fname} = $link;
 
2236   $main::lxdebug->leave_sub();