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, $i);
 
 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 it
 
 689       ($null, my $pricegroup_id) = split /--/, $form->{"sellprice_pg_$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, $row) = @_;
 
1243   $form->{taxzone_id} *=1;
 
1244   my $transdate = ($form->{invdate}) ? "'$form->{invdate}'" : "current_date";
 
1245   my $query = qq|SELECT i.id, i.trans_id, i.base_qty, i.allocated, i.sellprice,
 
1246                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
 
1247                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
 
1248                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid
 
1249                   FROM invoice i, parts p
 
1250                   LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
 
1251                   LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
 
1252                   LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
 
1253                   WHERE i.parts_id = p.id
 
1254                   AND i.parts_id = $id
 
1255                   AND (i.base_qty + i.allocated) < 0
 
1257   my $sth = $dbh->prepare($query);
 
1258   $sth->execute || $form->dberror($query);
 
1263   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1264     if (($qty = (($ref->{base_qty} * -1) - $ref->{allocated})) > $totalqty) {
 
1268     $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|,
 
1271     # total expenses and inventory
 
1272     # sellprice is the cost of the item
 
1273     $linetotal = $form->round_amount(($ref->{sellprice} * $qty) / $basefactor, 2);
 
1276       $ref->{expense_accno} = ($form->{"expense_accno_$row"}) ? $form->{"expense_accno_$row"} : $ref->{expense_accno};
 
1278       $form->{amount}{ $form->{id} }{ $ref->{expense_accno} } += -$linetotal;
 
1279       $form->{expense_inventory} .= " " . $ref->{expense_accno};
 
1280       $ref->{inventory_accno} = ($form->{"inventory_accno_$row"}) ? $form->{"inventory_accno_$row"} : $ref->{inventory_accno};
 
1282       $form->{amount}{ $form->{id} }{ $ref->{inventory_accno} } -= -$linetotal;
 
1283       $form->{expense_inventory} .= " " . $ref->{inventory_accno};
 
1287     $allocated += -$qty;
 
1289     last if (($totalqty -= $qty) <= 0);
 
1294   $main::lxdebug->leave_sub();
 
1299 sub reverse_invoice {
 
1300   $main::lxdebug->enter_sub();
 
1302   my ($dbh, $form) = @_;
 
1304   # reverse inventory items
 
1305   my $query = qq|SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
 
1306                  p.inventory_accno_id
 
1308                  JOIN parts p ON (i.parts_id = p.id)
 
1309                  WHERE i.trans_id = $form->{id}|;
 
1310   my $sth = $dbh->prepare($query);
 
1311   $sth->execute || $form->dberror($query);
 
1313   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1315     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
 
1317       # if the invoice item is not an assemblyitem adjust parts onhand
 
1318       if (!$ref->{assemblyitem}) {
 
1320         # adjust onhand in parts table
 
1321         $form->update_balance($dbh, "parts", "onhand",
 
1322                               qq|id = $ref->{parts_id}|,
 
1326       # loop if it is an assembly
 
1327       next if ($ref->{assembly});
 
1329       # de-allocated purchases
 
1330       $query = qq|SELECT i.id, i.trans_id, i.allocated
 
1332                   WHERE i.parts_id = $ref->{parts_id}
 
1334                   ORDER BY i.trans_id DESC|;
 
1335       my $sth = $dbh->prepare($query);
 
1336       $sth->execute || $form->dberror($query);
 
1338       while (my $inhref = $sth->fetchrow_hashref(NAME_lc)) {
 
1340         if (($ref->{qty} - $inhref->{allocated}) > 0) {
 
1341           $qty = $inhref->{allocated};
 
1345         $form->update_balance($dbh, "invoice", "allocated",
 
1346                               qq|id = $inhref->{id}|,
 
1349         last if (($ref->{qty} -= $qty) <= 0);
 
1358   $query = qq|DELETE FROM acc_trans
 
1359               WHERE trans_id = $form->{id}|;
 
1360   $dbh->do($query) || $form->dberror($query);
 
1362   # delete invoice entries
 
1363   $query = qq|DELETE FROM invoice
 
1364               WHERE trans_id = $form->{id}|;
 
1365   $dbh->do($query) || $form->dberror($query);
 
1367   if ($form->{lizenzen}) {
 
1368     $query = qq|DELETE FROM licenseinvoice
 
1369               WHERE trans_id in (SELECT id FROM invoice WHERE trans_id = $form->{id})|;
 
1370     $dbh->do($query) || $form->dberror($query);
 
1373   $query = qq|DELETE FROM shipto
 
1374               WHERE trans_id = $form->{id} AND module = 'AR'|;
 
1375   $dbh->do($query) || $form->dberror($query);
 
1377   $main::lxdebug->leave_sub();
 
1380 sub delete_invoice {
 
1381   $main::lxdebug->enter_sub();
 
1383   my ($self, $myconfig, $form, $spool) = @_;
 
1385   # connect to database
 
1386   my $dbh = $form->dbconnect_noauto($myconfig);
 
1388   &reverse_invoice($dbh, $form);
 
1391   my $query = qq|DELETE FROM ar
 
1392                  WHERE id = $form->{id}|;
 
1393   $dbh->do($query) || $form->dberror($query);
 
1395   # delete spool files
 
1396   $query = qq|SELECT s.spoolfile FROM status s
 
1397               WHERE s.trans_id = $form->{id}|;
 
1398   my $sth = $dbh->prepare($query);
 
1399   $sth->execute || $self->dberror($query);
 
1402   my @spoolfiles = ();
 
1404   while (($spoolfile) = $sth->fetchrow_array) {
 
1405     push @spoolfiles, $spoolfile;
 
1409   # delete status entries
 
1410   $query = qq|DELETE FROM status
 
1411               WHERE trans_id = $form->{id}|;
 
1412   $dbh->do($query) || $form->dberror($query);
 
1414   my $rc = $dbh->commit;
 
1418     foreach $spoolfile (@spoolfiles) {
 
1419       unlink "$spool/$spoolfile" if $spoolfile;
 
1423   $main::lxdebug->leave_sub();
 
1428 sub retrieve_invoice {
 
1429   $main::lxdebug->enter_sub();
 
1431   my ($self, $myconfig, $form) = @_;
 
1433   # connect to database
 
1434   my $dbh = $form->dbconnect_noauto($myconfig);
 
1440     # get default accounts and last invoice number
 
1441     $query = qq|SELECT (SELECT c.accno FROM chart c
 
1442                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
 
1443                        (SELECT c.accno FROM chart c
 
1444                         WHERE d.income_accno_id = c.id) AS income_accno,
 
1445                        (SELECT c.accno FROM chart c
 
1446                         WHERE d.expense_accno_id = c.id) AS expense_accno,
 
1447                        (SELECT c.accno FROM chart c
 
1448                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
1449                        (SELECT c.accno FROM chart c
 
1450                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
1451                 d.curr AS currencies
 
1454     $query = qq|SELECT (SELECT c.accno FROM chart c
 
1455                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
 
1456                        (SELECT c.accno FROM chart c
 
1457                         WHERE d.income_accno_id = c.id) AS income_accno,
 
1458                        (SELECT c.accno FROM chart c
 
1459                         WHERE d.expense_accno_id = c.id) AS expense_accno,
 
1460                        (SELECT c.accno FROM chart c
 
1461                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
1462                        (SELECT c.accno FROM chart c
 
1463                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
1464                 d.curr AS currencies, current_date AS invdate
 
1467   my $sth = $dbh->prepare($query);
 
1468   $sth->execute || $form->dberror($query);
 
1470   my $ref = $sth->fetchrow_hashref(NAME_lc);
 
1471   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1477     $query = qq|SELECT a.invnumber, a.ordnumber, a.quonumber, a.cusordnumber,
 
1478                 a.transdate AS invdate, a.deliverydate, a.paid, a.storno, a.gldate,
 
1479                 a.shippingpoint, a.shipvia, a.terms, a.notes, a.intnotes, a.taxzone_id,
 
1480                 a.duedate, a.taxincluded, a.curr AS currency, a.shipto_id, a.cp_id,
 
1481                 a.employee_id, e.name AS employee, a.payment_id, a.language_id, a.delivery_customer_id, a.delivery_vendor_id, a.type
 
1483                 LEFT JOIN employee e ON (e.id = a.employee_id)
 
1484                 WHERE a.id = $form->{id}|;
 
1485     $sth = $dbh->prepare($query);
 
1486     $sth->execute || $form->dberror($query);
 
1488     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1489     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1492     $form->{exchangerate} =
 
1493       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
 
1496     $query = qq|SELECT s.* FROM shipto s
 
1497                 WHERE s.trans_id = $form->{id} AND s.module = 'AR'|;
 
1498     $sth = $dbh->prepare($query);
 
1499     $sth->execute || $form->dberror($query);
 
1501     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1503     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1506    if ($form->{delivery_customer_id}) {
 
1507       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_customer_id}|;
 
1508       $sth = $dbh->prepare($query);
 
1509       $sth->execute || $form->dberror($query);
 
1510       ($form->{delivery_customer_string}) = $sth->fetchrow_array();
 
1514     if ($form->{delivery_vendor_id}) {
 
1515       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_vendor_id}|;
 
1516       $sth = $dbh->prepare($query);
 
1517       $sth->execute || $form->dberror($query);
 
1518       ($form->{delivery_vendor_string}) = $sth->fetchrow_array();
 
1522     # get printed, emailed
 
1523     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
 
1525                 WHERE s.trans_id = $form->{id}|;
 
1526     $sth = $dbh->prepare($query);
 
1527     $sth->execute || $form->dberror($query);
 
1529     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1530       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
1531       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
1532       $form->{queued} .= "$ref->{formname} $ref->{spoolfile} "
 
1533         if $ref->{spoolfile};
 
1536     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
1539       $form->{deliverydate} ? $dbh->quote($form->{deliverydate}) :
 
1540       $form->{invdate} ? $dbh->quote($form->{invdate}) :
 
1543     if (!$form->{taxzone_id}) {
 
1544       $form->{taxzone_id} = 0;
 
1546     # retrieve individual items
 
1548                 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
 
1549                 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
 
1550                 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
 
1551                 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice,
 
1552                 i.discount, i.parts_id AS id, i.unit, i.deliverydate,
 
1553                 i.project_id, pr.projectnumber, i.serialnumber,
 
1554                 p.partnumber, p.assembly, p.bin, p.notes AS partnotes, p.inventory_accno_id AS part_inventory_accno_id, i.id AS invoice_pos,
 
1555                 pg.partsgroup, i.pricegroup_id, (SELECT pricegroup FROM pricegroup WHERE id=i.pricegroup_id) as pricegroup,
 
1556                 i.ordnumber, i.transdate, i.cusordnumber, p.formel, i.subtotal
 
1558                 JOIN parts p ON (i.parts_id = p.id)
 
1559                 LEFT JOIN project pr ON (i.project_id = pr.id)
 
1560                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1561                 LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
 
1562                 LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
 
1563                 LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
 
1564                 WHERE i.trans_id = $form->{id}
 
1565                 AND NOT i.assemblyitem = '1'
 
1567     $sth = $dbh->prepare($query);
 
1569     $sth->execute || $form->dberror($query);
 
1570     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1571       if (!$ref->{"part_inventory_accno_id"}) {
 
1572         map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
 
1574       delete($ref->{"part_inventory_accno_id"});
 
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;
 
1600       # get tax rates and description
 
1602         ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
 
1603     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
 
1604               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
 
1605               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)
 
1607       $stw = $dbh->prepare($query);
 
1608       $stw->execute || $form->dberror($query);
 
1609       $ref->{taxaccounts} = "";
 
1611       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
1613         #    if ($customertax{$ref->{accno}}) {
 
1614         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
 
1618         $ref->{taxaccounts} .= "$ptr->{accno} ";
 
1620         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
 
1621           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
1622           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
 
1623           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
1624           $form->{taxaccounts} .= "$ptr->{accno} ";
 
1629       if ($form->{lizenzen}) {
 
1630         $query = qq|SELECT l.licensenumber, l.id AS licenseid
 
1631                  FROM license l, licenseinvoice li
 
1632                  WHERE l.id = li.license_id AND li.trans_id = $ref->{invoice_pos}|;
 
1633         $stg = $dbh->prepare($query);
 
1634         $stg->execute || $form->dberror($query);
 
1635         ($licensenumber, $licenseid) = $stg->fetchrow_array();
 
1637           "<option value=\"$licenseid\">$licensenumber</option>";
 
1640       if ($form->{type} eq "credit_note") {
 
1644       chop $ref->{taxaccounts};
 
1645       push @{ $form->{invoice_details} }, $ref;
 
1650     if ($form->{webdav}) {
 
1651       &webdav_folder($myconfig, $form);
 
1655   my $rc = $dbh->commit;
 
1658   $main::lxdebug->leave_sub();
 
1664   $main::lxdebug->enter_sub();
 
1666   my ($self, $myconfig, $form) = @_;
 
1668   # connect to database
 
1669   my $dbh = $form->dbconnect($myconfig);
 
1671   my $dateformat = $myconfig->{dateformat};
 
1672   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
1676     ? "to_date('$form->{invdate}', '$dateformat')"
 
1679   $form->{customer_id} *= 1;
 
1682   my $query = qq|SELECT c.name AS customer, c.discount, c.creditlimit, c.terms,
 
1683                  c.email, c.cc, c.bcc, c.language_id, c.payment_id AS customer_payment_id,
 
1684                  c.street, c.zipcode, c.city, c.country,
 
1685                  $duedate + c.terms AS duedate, c.notes AS intnotes,
 
1686                  b.discount AS tradediscount, b.description AS business, c.klass as customer_klass, c.taxzone_id
 
1688                  LEFT JOIN business b ON (b.id = c.business_id)
 
1689                  WHERE c.id = $form->{customer_id}|;
 
1690   my $sth = $dbh->prepare($query);
 
1691   $sth->execute || $form->dberror($query);
 
1693   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1695   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1698   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|;
 
1699   my $sth = $dbh->prepare($query);
 
1701   $sth->execute || $form->dberror($query);
 
1703   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1705   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1708   #print(STDERR "DUNNING AMOUTN $form->{dunning_amount}\n");
 
1710   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|;
 
1711   my $sth = $dbh->prepare($query);
 
1713   $sth->execute || $form->dberror($query);
 
1715   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1717   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1719   #print(STDERR "LEVEL $form->{max_dunning_level}\n");
 
1722   #check whether payment_terms are better than old payment_terms
 
1723   if (($form->{payment_id} ne "") && ($form->{customer_payment_id} ne "")) {
 
1724     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})|;
 
1725     my $stw = $dbh->prepare($query);
 
1726     $stw->execute || $form->dberror($query);
 
1727     ($old_ranking, $new_ranking) = $stw->fetchrow_array;
 
1729     if ($new_ranking > $old_ranking) {
 
1730       $form->{payment_id} =$form->{customer_payment_id};
 
1733   if ($form->{payment_id} eq "") {
 
1734     $form->{payment_id} =$form->{customer_payment_id};
 
1737   $form->{creditremaining} = $form->{creditlimit};
 
1738   $query = qq|SELECT SUM(a.amount - a.paid)
 
1740               WHERE a.customer_id = $form->{customer_id}|;
 
1741   $sth = $dbh->prepare($query);
 
1742   $sth->execute || $form->dberror($query);
 
1744   ($form->{creditremaining}) -= $sth->fetchrow_array;
 
1748   $query = qq|SELECT o.amount,
 
1749                 (SELECT e.buy FROM exchangerate e
 
1750                  WHERE e.curr = o.curr
 
1751                  AND e.transdate = o.transdate)
 
1753               WHERE o.customer_id = $form->{customer_id}
 
1754               AND o.quotation = '0'
 
1755               AND o.closed = '0'|;
 
1756   $sth = $dbh->prepare($query);
 
1757   $sth->execute || $form->dberror($query);
 
1759   while (my ($amount, $exch) = $sth->fetchrow_array) {
 
1760     $exch = 1 unless $exch;
 
1761     $form->{creditremaining} -= $amount * $exch;
 
1765   $form->get_contacts($dbh, $form->{customer_id});
 
1766   $form->{cp_id} *= 1;
 
1768   # get contact if selected
 
1769   if ($form->{cp_id}) {
 
1770     $form->get_contact($dbh, $form->{cp_id});
 
1773   # get shipto if we did not converted an order or invoice
 
1774   if (!$form->{shipto}) {
 
1775     map { delete $form->{$_} }
 
1776       qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail);
 
1778     $query = qq|SELECT s.* FROM shipto s
 
1779                 WHERE s.trans_id = $form->{customer_id} AND s.module = 'CT'|;
 
1780     $sth = $dbh->prepare($query);
 
1781     $sth->execute || $form->dberror($query);
 
1783     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1785     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1789   # get taxes we charge for this customer
 
1790   $query = qq|SELECT c.accno
 
1792               JOIN customertax ct ON (ct.chart_id = c.id)
 
1793               WHERE ct.customer_id = $form->{customer_id}|;
 
1794   $sth = $dbh->prepare($query);
 
1795   $sth->execute || $form->dberror($query);
 
1797   my $customertax = ();
 
1798   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1799     $customertax{ $ref->{accno} } = 1;
 
1803   # get shipping addresses
 
1804   $query = qq|SELECT s.shipto_id,s.shiptoname,s.shiptodepartment_1
 
1806               WHERE s.trans_id = $form->{customer_id}|;
 
1807   $sth = $dbh->prepare($query);
 
1808   $sth->execute || $form->dberror($query);
 
1810   my $customertax = ();
 
1811   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1812     push(@{ $form->{SHIPTO} }, $ref);
 
1816   # setup last accounts used for this customer
 
1817   if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
 
1818     $query = qq|SELECT c.accno, c.description, c.link, c.category
 
1820                 JOIN acc_trans ac ON (ac.chart_id = c.id)
 
1821                 JOIN ar a ON (a.id = ac.trans_id)
 
1822                 WHERE a.customer_id = $form->{customer_id}
 
1823                 AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
 
1824                 AND a.id IN (SELECT max(a2.id) FROM ar a2
 
1825                              WHERE a2.customer_id = $form->{customer_id})|;
 
1826     $sth = $dbh->prepare($query);
 
1827     $sth->execute || $form->dberror($query);
 
1830     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1831       if ($ref->{category} eq 'I') {
 
1833         $form->{"AR_amount_$i"} = "$ref->{accno}--$ref->{description}";
 
1835       if ($ref->{category} eq 'A') {
 
1836         $form->{ARselected} = $form->{AR_1} =
 
1837           "$ref->{accno}--$ref->{description}";
 
1841     $form->{rowcount} = $i if ($i && !$form->{type});
 
1846   $main::lxdebug->leave_sub();
 
1850   $main::lxdebug->enter_sub();
 
1852   my ($self, $myconfig, $form) = @_;
 
1854   # connect to database
 
1855   my $dbh = $form->dbconnect($myconfig);
 
1857   my $i = $form->{rowcount};
 
1859   my $where = "NOT p.obsolete = '1'";
 
1861   if ($form->{"partnumber_$i"}) {
 
1862     my $partnumber = $form->like(lc $form->{"partnumber_$i"});
 
1863     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
 
1865   if ($form->{"description_$i"}) {
 
1866     my $description = $form->like(lc $form->{"description_$i"});
 
1867     $where .= " AND lower(p.description) LIKE '$description'";
 
1870   if ($form->{"partsgroup_$i"}) {
 
1871     my $partsgroup = $form->like(lc $form->{"partsgroup_$i"});
 
1872     $where .= " AND lower(pg.partsgroup) LIKE '$partsgroup'";
 
1875   if ($form->{"description_$i"}) {
 
1876     $where .= " ORDER BY p.description";
 
1878     $where .= " ORDER BY p.partnumber";
 
1882   if ($form->{type} eq "invoice") {
 
1884       $form->{deliverydate} ? $dbh->quote($form->{deliverydate}) :
 
1885       $form->{invdate} ? $dbh->quote($form->{invdate}) :
 
1889       $form->{transdate} ? $dbh->quote($form->{transdate}) :
 
1893   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
 
1894                         p.listprice, p.inventory_accno_id,
 
1895                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
 
1896                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
 
1897                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
 
1898                  p.unit, p.assembly, p.bin, p.onhand, p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
 
1899                  pg.partsgroup, p.formel, p.payment_id AS part_payment_id
 
1901                  LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
 
1902                  LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
 
1903                  LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
 
1904                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
 
1906   my $sth = $dbh->prepare($query);
 
1907   $sth->execute || $form->dberror($query);
 
1909   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1911     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
 
1912     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
 
1913     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
 
1914     if (!$ref->{inventory_accno_id}) {
 
1915       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
 
1917     delete($ref->{inventory_accno_id});
 
1919     #set expense_accno=inventory_accno if they are different => bilanz
 
1922     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
 
1923       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}|;
 
1924       my $stw = $dbh->prepare($query);
 
1925       $stw->execute || $form->dberror($query);
 
1926       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
 
1930     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
 
1931       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}|;
 
1932       my $stw = $dbh->prepare($query);
 
1933       $stw->execute || $form->dberror($query);
 
1934       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
 
1938     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
 
1939       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}|;
 
1940       my $stw = $dbh->prepare($query);
 
1941       $stw->execute || $form->dberror($query);
 
1942       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
 
1946     #check whether payment_terms are better than old payment_terms
 
1947     if (($form->{payment_id} ne "") && ($ref->{part_payment_id} ne "")) {
 
1948       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})|;
 
1949       my $stw = $dbh->prepare($query);
 
1950       $stw->execute || $form->dberror($query);
 
1951       ($old_ranking, $new_ranking) = $stw->fetchrow_array;
 
1953       if ($new_ranking <= $old_ranking) {
 
1954         $ref->{part_payment_id} = "";
 
1958     # get tax rates and description
 
1960       ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
 
1961     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
 
1962               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
 
1963               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)
 
1965     $stw = $dbh->prepare($query);
 
1966     $stw->execute || $form->dberror($query);
 
1968     $ref->{taxaccounts} = "";
 
1970     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
1972       #    if ($customertax{$ref->{accno}}) {
 
1973       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
 
1977       $ref->{taxaccounts} .= "$ptr->{accno} ";
 
1979       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
 
1980         $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
1981         $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
 
1982         $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
1983         $form->{taxaccounts} .= "$ptr->{accno} ";
 
1989     chop $ref->{taxaccounts};
 
1990     if ($form->{language_id}) {
 
1991       $query = qq|SELECT tr.translation, tr.longdescription
 
1993                 WHERE tr.language_id=$form->{language_id} AND tr.parts_id=$ref->{id}|;
 
1994       $stw = $dbh->prepare($query);
 
1995       $stw->execute || $form->dberror($query);
 
1996       my ($translation, $longdescription) = $stw->fetchrow_array();
 
1997       if ($translation ne "") {
 
1998         $ref->{description} = $translation;
 
1999         $ref->{longdescription} = $longdescription;
 
2002         $query = qq|SELECT tr.translation, tr.longdescription
 
2004                 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|;
 
2005         $stg = $dbh->prepare($query);
 
2006         $stg->execute || $form->dberror($query);
 
2007         my ($translation) = $stg->fetchrow_array();
 
2008         if ($translation ne "") {
 
2009           $ref->{description} = $translation;
 
2010           $ref->{longdescription} = $longdescription;
 
2017     push @{ $form->{item_list} }, $ref;
 
2019     if ($form->{lizenzen}) {
 
2020       if ($ref->{inventory_accno} > 0) {
 
2022           qq| SELECT l.* FROM license l WHERE l.parts_id = $ref->{id} AND NOT l.id IN (SELECT li.license_id FROM licenseinvoice li)|;
 
2023         $stw = $dbh->prepare($query);
 
2024         $stw->execute || $form->dberror($query);
 
2025         while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
2026           push @{ $form->{LIZENZEN}{ $ref->{id} } }, $ptr;
 
2035   $main::lxdebug->leave_sub();
 
2038 ##########################
 
2039 # get pricegroups from database
 
2040 # build up selected pricegroup
 
2041 # if an exchange rate - change price
 
2044 sub get_pricegroups_for_parts {
 
2046   $main::lxdebug->enter_sub();
 
2048   my ($self, $myconfig, $form) = @_;
 
2050   my $dbh = $form->dbconnect($myconfig);
 
2052   $form->{"PRICES"} = {};
 
2056   my $dimension_units = AM->retrieve_units($myconfig, $form, "dimension");
 
2057   my $service_units = AM->retrieve_units($myconfig, $form, "service");
 
2058   my $all_units = AM->retrieve_units($myconfig, $form);
 
2059   while (($form->{"id_$i"}) or ($form->{"new_id_$i"})) {
 
2060     $form->{"PRICES"}{$i} = [];
 
2062     $id = $form->{"id_$i"};
 
2064     if (!($form->{"id_$i"}) and $form->{"new_id_$i"}) {
 
2066       $id = $form->{"new_id_$i"};
 
2069     ($price, $selectedpricegroup_id) = split /--/,
 
2070       $form->{"sellprice_pg_$i"};
 
2072     $pricegroup_old = $form->{"pricegroup_old_$i"};
 
2073     $form->{"new_pricegroup_$i"} = $selectedpricegroup_id;
 
2074     $form->{"old_pricegroup_$i"} = $pricegroup_old;
 
2075     $price_new = $form->{"price_new_$i"};
 
2077     $price_old = $form->{"price_old_$i"};
 
2079       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|;
 
2081     $pkq = $dbh->prepare($query);
 
2082     $pkq->execute || $form->dberror($query);
 
2083     if (!$form->{"unit_old_$i"}) {
 
2084       # Neue Ware aus der Datenbank. In diesem Fall ist unit_$i die
 
2085       # Einheit, wie sie in den Stammdaten hinterlegt wurde.
 
2086       # Es sollte also angenommen werden, dass diese ausgewaehlt war.
 
2087       $form->{"unit_old_$i"} = $form->{"unit_$i"};
 
2090     # Die zuletzt ausgewaehlte mit der aktuell ausgewaehlten Einheit
 
2091     # vergleichen und bei Unterschied den Preis entsprechend umrechnen.
 
2092     $form->{"selected_unit_$i"} = $form->{"unit_$i"} unless ($form->{"selected_unit_$i"});
 
2094     my $check_units = $form->{"inventory_accno_$i"} ? $dimension_units : $service_units;
 
2095     if (!$check_units->{$form->{"selected_unit_$i"}} ||
 
2096         ($check_units->{$form->{"selected_unit_$i"}}->{"base_unit"} ne
 
2097          $all_units->{$form->{"unit_old_$i"}}->{"base_unit"})) {
 
2098       # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
 
2099       # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
 
2100       # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
 
2101       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};
 
2105     if ($form->{"unit_old_$i"} ne $form->{"selected_unit_$i"}) {
 
2106       if (defined($all_units->{$form->{"unit_old_$i"}}->{"factor"}) &&
 
2107           $all_units->{$form->{"unit_old_$i"}}->{"factor"}) {
 
2108         $basefactor = $all_units->{$form->{"selected_unit_$i"}}->{"factor"} /
 
2109           $all_units->{$form->{"unit_old_$i"}}->{"factor"};
 
2112     if (!$form->{"basefactor_$i"}) {
 
2113       $form->{"basefactor_$i"} = 1;
 
2115     while ($pkr = $pkq->fetchrow_hashref(NAME_lc)) {
 
2117       #       push @{ $form->{PRICES}{$id} }, $pkr;
 
2118       #push @{ $form->{PRICES}{$i} }, $pkr;
 
2120       $pkr->{selected} = '';
 
2122       # if there is an exchange rate change price
 
2123       if (($form->{exchangerate} * 1) != 0) {
 
2125         $pkr->{price} /= $form->{exchangerate};
 
2128       $pkr->{price} *= $form->{"basefactor_$i"};
 
2130       $pkr->{price} *= $basefactor;
 
2132       $pkr->{price} = $form->format_amount($myconfig, $pkr->{price}, 5);
 
2134       if ($selectedpricegroup_id eq undef) {
 
2135         if ($pkr->{pricegroup_id} eq $form->{customer_klass}) {
 
2137           $pkr->{selected}  = ' selected';
 
2139           # no customer pricesgroup set
 
2140           if ($pkr->{price} == $pkr->{default_sellprice}) {
 
2142             $pkr->{price} = $form->{"sellprice_$i"};
 
2146             $form->{"sellprice_$i"} = $pkr->{price};
 
2150           if ($pkr->{price} == $pkr->{default_sellprice}) {
 
2152             $pkr->{price}    = $form->{"sellprice_$i"};
 
2153             $pkr->{selected} = ' selected';
 
2158       if ($selectedpricegroup_id or $selectedpricegroup_id == 0) {
 
2159         if ($selectedpricegroup_id ne $pricegroup_old) {
 
2160           if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
 
2161             $pkr->{selected}  = ' selected';
 
2164           if (($price_new != $form->{"sellprice_$i"}) and ($price_new ne 0)) {
 
2165             if ($pkr->{pricegroup_id} == 0) {
 
2166               $pkr->{price}     = $form->{"sellprice_$i"};
 
2167               $pkr->{selected}  = ' selected';
 
2170             if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
 
2171               $pkr->{selected}  = ' selected';
 
2172               if (    ($pkr->{pricegroup_id} == 0)
 
2173                   and ($pkr->{price} == $form->{"sellprice_$i"})) {
 
2175                 # $pkr->{price}                         = $form->{"sellprice_$i"};
 
2177                 $pkr->{price} = $form->{"sellprice_$i"};
 
2183       push @{ $form->{PRICES}{$i} }, $pkr;
 
2186     $form->{"basefactor_$i"} *= $basefactor;
 
2195   $main::lxdebug->leave_sub();
 
2199   $main::lxdebug->enter_sub();
 
2201   my ($myconfig, $form) = @_;
 
2204     $path = "webdav/rechnungen/" . $form->{invnumber}, last SWITCH
 
2205       if ($form->{vc} eq "customer");
 
2206     $path = "webdav/einkaufsrechnungen/" . $form->{invnumber}, last SWITCH
 
2207       if ($form->{vc} eq "vendor");
 
2211     mkdir($path, 0770) or die "can't make directory $!\n";
 
2215       foreach $file (@files) {
 
2216         $file =~ /\/([^\/]*)$/;
 
2218         $ENV{'SCRIPT_NAME'} =~ /\/([^\/]*)\//;
 
2220         $link  = "http://" . $ENV{'SERVER_NAME'} . "/" . $lxerp . "/" . $file;
 
2221         $form->{WEBDAV}{$fname} = $link;
 
2226   $main::lxdebug->leave_sub();