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, @wanted_vars) = @_;
 
 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)};
 
 420   if (scalar(@wanted_vars) > 0) {
 
 422     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
 
 423     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
 
 426   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 429   if ($form->{delivery_customer_id}) {
 
 430     my $query = qq|SELECT ct.*, ct.notes as customernotes
 
 432                  WHERE ct.id = $form->{delivery_customer_id} limit 1|;
 
 433     my $sth = $dbh->prepare($query);
 
 434     $sth->execute || $form->dberror($query);
 
 436     $ref = $sth->fetchrow_hashref(NAME_lc);
 
 439     map { $form->{"dc_$_"} = $ref->{$_} } keys %$ref;
 
 442   if ($form->{delivery_vendor_id}) {
 
 443     my $query = qq|SELECT ct.*, ct.notes as customernotes
 
 445                  WHERE ct.id = $form->{delivery_vendor_id} limit 1|;
 
 446     my $sth = $dbh->prepare($query);
 
 447     $sth->execute || $form->dberror($query);
 
 449     $ref = $sth->fetchrow_hashref(NAME_lc);
 
 452     map { $form->{"dv_$_"} = $ref->{$_} } keys %$ref;
 
 456   $main::lxdebug->leave_sub();
 
 460   $main::lxdebug->enter_sub();
 
 462   my ($self, $myconfig, $form) = @_;
 
 464   # connect to database, turn off autocommit
 
 465   my $dbh = $form->dbconnect_noauto($myconfig);
 
 467   my ($query, $sth, $null, $project_id, $deliverydate);
 
 468   my $exchangerate = 0;
 
 470   ($null, $form->{employee_id}) = split /--/, $form->{employee};
 
 471   unless ($form->{employee_id}) {
 
 472     $form->get_employee($dbh);
 
 475   $form->{contact_id} = $form->{cp_id};
 
 476   $form->{contact_id} *= 1;
 
 477   $form->{payment_id} *= 1;
 
 478   $form->{language_id} *= 1;
 
 479   $form->{taxzone_id} *= 1;
 
 480   $form->{delivery_customer_id} *= 1;
 
 481   $form->{delivery_vendor_id} *= 1;
 
 482   $form->{storno} *= 1;
 
 483   $form->{shipto_id} *= 1;
 
 486   ($null, $form->{department_id}) = split(/--/, $form->{department});
 
 487   $form->{department_id} *= 1;
 
 489   my $service_units = AM->retrieve_units($myconfig,$form,"service");
 
 490   my $part_units = AM->retrieve_units($myconfig,$form,"dimension");
 
 496     &reverse_invoice($dbh, $form);
 
 499     my $uid = rand() . time;
 
 501     $uid .= $form->{login};
 
 503     $uid = substr($uid, 2, 75);
 
 505     $query = qq|INSERT INTO ar (invnumber, employee_id)
 
 506                 VALUES ('$uid', $form->{employee_id})|;
 
 507     $dbh->do($query) || $form->dberror($query);
 
 509     $query = qq|SELECT a.id FROM ar a
 
 510                 WHERE a.invnumber = '$uid'|;
 
 511     $sth = $dbh->prepare($query);
 
 512     $sth->execute || $form->dberror($query);
 
 514     ($form->{id}) = $sth->fetchrow_array;
 
 518   map { $form->{$_} =~ s/\'/\'\'/g }
 
 519     (qw(invnumber shippingpoint shipvia notes intnotes message));
 
 521   my ($netamount, $invoicediff) = (0, 0);
 
 522   my ($amount, $linetotal, $lastincomeaccno);
 
 524   if ($form->{currency} eq $form->{defaultcurrency}) {
 
 525     $form->{exchangerate} = 1;
 
 528       $form->check_exchangerate($myconfig, $form->{currency},
 
 529                                 $form->{transdate}, 'buy');
 
 532   $form->{exchangerate} =
 
 535     : $form->parse_amount($myconfig, $form->{exchangerate});
 
 537   $form->{expense_inventory} = "";
 
 539   foreach my $i (1 .. $form->{rowcount}) {
 
 540     if ($form->{type} eq "credit_note") {
 
 541       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"}) * -1;
 
 542       $form->{shipped} = 1;   
 
 544       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 549     if ($form->{storno}) {
 
 550       $form->{"qty_$i"} *= -1;
 
 553     if ($form->{"qty_$i"} != 0) {
 
 556       $query = qq|SELECT p.unit
 
 558                   WHERE p.id = $form->{"id_$i"}|;
 
 559       $sth = $dbh->prepare($query);
 
 560       $sth->execute || $form->dberror($query);
 
 562       my ($item_unit) = $sth->fetchrow_array();
 
 565       if ($form->{"inventory_accno_$i"}) {
 
 566         if (defined($part_units->{$item_unit}->{factor}) && $part_units->{$item_unit}->{factor} ne '' && $part_units->{$item_unit}->{factor} ne '0') {
 
 567           $basefactor = $part_units->{$form->{"unit_$i"}}->{factor} / $part_units->{$item_unit}->{factor};
 
 571         $baseqty = $form->{"qty_$i"} * $basefactor;
 
 573         if (defined($service_units->{$item_unit}->{factor}) && $service_units->{$item_unit}->{factor} ne '' && $service_units->{$item_unit}->{factor} ne '0') {
 
 574           $basefactor = $service_units->{$form->{"unit_$i"}}->{factor} / $service_units->{$item_unit}->{factor};
 
 578         $baseqty = $form->{"qty_$i"} * $basefactor;
 
 581       map { $form->{"${_}_$i"} =~ s/\'/\'\'/g }
 
 582         (qw(partnumber description unit));
 
 584       # undo discount formatting
 
 585       $form->{"discount_$i"} =
 
 586         $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
 
 588       my ($allocated, $taxrate) = (0, 0);
 
 591       # keep entered selling price
 
 593         $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 595       my ($dec) = ($fxsellprice =~ /\.(\d+)/);
 
 597       my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 601         $form->round_amount($fxsellprice * $form->{"discount_$i"},
 
 603       $form->{"sellprice_$i"} = $fxsellprice - $discount;
 
 606       map { $taxrate += $form->{"${_}_rate"} } split / /,
 
 607         $form->{"taxaccounts_$i"};
 
 609       # round linetotal to 2 decimal places
 
 611         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
 
 613       if ($form->{taxincluded}) {
 
 614         $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
 
 615         $form->{"sellprice_$i"} =
 
 616           $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
 
 618         $taxamount = $linetotal * $taxrate;
 
 621       $netamount += $linetotal;
 
 623       if ($taxamount != 0) {
 
 625           $form->{amount}{ $form->{id} }{$_} +=
 
 626             $taxamount * $form->{"${_}_rate"} / $taxrate
 
 627         } split / /, $form->{"taxaccounts_$i"};
 
 630       # add amount to income, $form->{amount}{trans_id}{accno}
 
 632         $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
 
 635         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) *
 
 636         $form->{exchangerate};
 
 637       $linetotal = $form->round_amount($linetotal, 2);
 
 639       # this is the difference from the inventory
 
 640       $invoicediff += ($amount - $linetotal);
 
 642       $form->{amount}{ $form->{id} }{ $form->{"income_accno_$i"} } +=
 
 645       $lastincomeaccno = $form->{"income_accno_$i"};
 
 647       # adjust and round sellprice
 
 648       $form->{"sellprice_$i"} =
 
 649         $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate},
 
 652       if ($form->{"inventory_accno_$i"} || $form->{"assembly_$i"}) {
 
 654         # adjust parts onhand quantity
 
 656         if ($form->{"assembly_$i"}) {
 
 658           # do not update if assembly consists of all services
 
 659           $query = qq|SELECT sum(p.inventory_accno_id)
 
 661                       JOIN assembly a ON (a.parts_id = p.id)
 
 662                       WHERE a.id = $form->{"id_$i"}|;
 
 663           $sth = $dbh->prepare($query);
 
 664           $sth->execute || $form->dberror($query);
 
 666           if ($sth->fetchrow_array) {
 
 667             $form->update_balance($dbh, "parts", "onhand",
 
 668                                   qq|id = $form->{"id_$i"}|,
 
 670               unless $form->{shipped};
 
 674           # record assembly item as allocated
 
 675           &process_assembly($dbh, $form, $form->{"id_$i"}, $baseqty);
 
 677           $form->update_balance($dbh, "parts", "onhand",
 
 678                                 qq|id = $form->{"id_$i"}|,
 
 680             unless $form->{shipped};
 
 682           $allocated = &cogs($dbh, $form, $form->{"id_$i"}, $baseqty, $basefactor, $i);
 
 686       $project_id = 'NULL';
 
 687       if ($form->{"projectnumber_$i"}) {
 
 688         $project_id = $form->{"projectnumber_$i"};
 
 691         ($form->{"deliverydate_$i"})
 
 692         ? qq|'$form->{"deliverydate_$i"}'|
 
 695       # get pricegroup_id and save it
 
 696       ($null, my $pricegroup_id) = split /--/, $form->{"sellprice_pg_$i"};
 
 698       my $subtotal = $form->{"subtotal_$i"} * 1;
 
 700       # save detail record in invoice table
 
 701       $query = qq|INSERT INTO invoice (trans_id, parts_id, description,longdescription, qty,
 
 702                   sellprice, fxsellprice, discount, allocated, assemblyitem,
 
 703                   unit, deliverydate, project_id, serialnumber, pricegroup_id,
 
 704                   ordnumber, transdate, cusordnumber, base_qty, subtotal)
 
 705                   VALUES ($form->{id}, $form->{"id_$i"},
 
 706                   '$form->{"description_$i"}', '$form->{"longdescription_$i"}', $form->{"qty_$i"},
 
 707                   $form->{"sellprice_$i"}, $fxsellprice,
 
 708                   $form->{"discount_$i"}, $allocated, 'f',
 
 709                   '$form->{"unit_$i"}', $deliverydate, (SELECT id from project where projectnumber = '$project_id'),
 
 710                   '$form->{"serialnumber_$i"}', '$pricegroup_id',
 
 711                   '$form->{"ordnumber_$i"}', '$form->{"transdate_$i"}', '$form->{"cusordnumber_$i"}', $baseqty, '$subtotal')|;
 
 712       $dbh->do($query) || $form->dberror($query);
 
 714       if ($form->{lizenzen}) {
 
 715         if ($form->{"licensenumber_$i"}) {
 
 717             qq|SELECT i.id FROM invoice i WHERE i.trans_id=$form->{id} ORDER BY i.oid DESC LIMIT 1|;
 
 718           $sth = $dbh->prepare($query);
 
 719           $sth->execute || $form->dberror($query);
 
 721           ($invoice_row_id) = $sth->fetchrow_array;
 
 725             qq|INSERT INTO licenseinvoice (trans_id, license_id) VALUES ($invoice_row_id, $form->{"licensenumber_$i"})|;
 
 726           $dbh->do($query) || $form->dberror($query);
 
 733   $form->{datepaid} = $form->{invdate};
 
 735   # total payments, don't move we need it here
 
 736   for my $i (1 .. $form->{paidaccounts}) {
 
 737     if ($form->{type} eq "credit_note") {
 
 738       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"}) * -1;
 
 740       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
 
 742     $form->{paid} += $form->{"paid_$i"};
 
 743     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
 
 746   my ($tax, $diff) = (0, 0);
 
 748   $netamount = $form->round_amount($netamount, 2);
 
 750   # figure out rounding errors for total amount vs netamount + taxes
 
 751   if ($form->{taxincluded}) {
 
 753     $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
 
 754     $diff += $amount - $netamount * $form->{exchangerate};
 
 755     $netamount = $amount;
 
 757     foreach my $item (split / /, $form->{taxaccounts}) {
 
 758       $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
 
 759       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
 
 760       $tax += $form->{amount}{ $form->{id} }{$item};
 
 761       $netamount -= $form->{amount}{ $form->{id} }{$item};
 
 764     $invoicediff += $diff;
 
 765     ######## this only applies to tax included
 
 766     if ($lastincomeaccno) {
 
 767       $form->{amount}{ $form->{id} }{$lastincomeaccno} += $invoicediff;
 
 771     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
 
 772     $diff      = $amount - $netamount * $form->{exchangerate};
 
 773     $netamount = $amount;
 
 774     foreach my $item (split / /, $form->{taxaccounts}) {
 
 775       $form->{amount}{ $form->{id} }{$item} =
 
 776         $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
 
 779                  $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate},
 
 782         $amount - $form->{amount}{ $form->{id} }{$item} *
 
 783         $form->{exchangerate};
 
 784       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
 
 785       $tax += $form->{amount}{ $form->{id} }{$item};
 
 789   $form->{amount}{ $form->{id} }{ $form->{AR} } = $netamount + $tax;
 
 791     $form->round_amount($form->{paid} * $form->{exchangerate} + $diff, 2);
 
 794   $form->{amount}{ $form->{id} }{ $form->{AR} } *= -1;
 
 796   # update exchangerate
 
 797   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 798     $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate},
 
 799                                $form->{exchangerate}, 0);
 
 802   foreach my $trans_id (keys %{ $form->{amount} }) {
 
 803     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
 
 804       next unless ($form->{expense_inventory} =~ /$accno/);
 
 806           ($form->{amount}{$trans_id}{$accno} =
 
 807            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
 
 810         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
 812                     VALUES ($trans_id, (SELECT c.id FROM chart c
 
 813                                         WHERE c.accno = '$accno'),
 
 814                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
 
 815                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'))|;
 
 816         $dbh->do($query) || $form->dberror($query);
 
 817         $form->{amount}{$trans_id}{$accno} = 0;
 
 821     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
 
 823           ($form->{amount}{$trans_id}{$accno} =
 
 824            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
 
 827         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
 829                     VALUES ($trans_id, (SELECT id FROM chart
 
 830                                         WHERE accno = '$accno'),
 
 831                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
 
 832                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'))|;
 
 833         $dbh->do($query) || $form->dberror($query);
 
 838   # deduct payment differences from diff
 
 839   for my $i (1 .. $form->{paidaccounts}) {
 
 840     if ($form->{"paid_$i"} != 0) {
 
 842         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
 
 843       $diff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
 
 847   # force AR entry if 0
 
 848   #  $form->{amount}{$form->{id}}{$form->{AR}} = 1 if ($form->{amount}{$form->{id}}{$form->{AR}} == 0);
 
 850   # record payments and offsetting AR
 
 851   if (!$form->{storno}) {
 
 852     for my $i (1 .. $form->{paidaccounts}) {
 
 854       if ($form->{"paid_$i"} != 0) {
 
 855         my ($accno) = split /--/, $form->{"AR_paid_$i"};
 
 856         $form->{"datepaid_$i"} = $form->{invdate}
 
 857           unless ($form->{"datepaid_$i"});
 
 858         $form->{datepaid} = $form->{"datepaid_$i"};
 
 862         if ($form->{currency} eq $form->{defaultcurrency}) {
 
 863           $form->{"exchangerate_$i"} = 1;
 
 866             $form->check_exchangerate($myconfig, $form->{currency},
 
 867                                       $form->{"datepaid_$i"}, 'buy');
 
 869           $form->{"exchangerate_$i"} =
 
 872             : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
 877           $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $diff,
 
 880         if ($form->{amount}{ $form->{id} }{ $form->{AR} } != 0) {
 
 881           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
 883                       VALUES ($form->{id}, (SELECT c.id FROM chart c
 
 884                                           WHERE c.accno = '$form->{AR}'),
 
 885                       $amount, '$form->{"datepaid_$i"}')|;
 
 886           $dbh->do($query) || $form->dberror($query);
 
 890         $form->{"paid_$i"} *= -1;
 
 892         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
 
 894                     VALUES ($form->{id}, (SELECT c.id FROM chart c
 
 895                                         WHERE c.accno = '$accno'),
 
 896                     $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
 
 897                     '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
 
 898         $dbh->do($query) || $form->dberror($query);
 
 900         # exchangerate difference
 
 901         $form->{fx}{$accno}{ $form->{"datepaid_$i"} } +=
 
 902           $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $diff;
 
 906           $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
 
 907           $form->{"exchangerate_$i"};
 
 909           $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
 
 912           $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
 
 918         # update exchange rate
 
 919         if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 920           $form->update_exchangerate($dbh, $form->{currency},
 
 921                                     $form->{"datepaid_$i"},
 
 922                                     $form->{"exchangerate_$i"}, 0);
 
 928   # record exchange rate differences and gains/losses
 
 929   foreach my $accno (keys %{ $form->{fx} }) {
 
 930     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
 
 932           ($form->{fx}{$accno}{$transdate} =
 
 933            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
 
 937         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
 938                     transdate, cleared, fx_transaction)
 
 940                            (SELECT c.id FROM chart c
 
 941                             WHERE c.accno = '$accno'),
 
 942                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1')|;
 
 943         $dbh->do($query) || $form->dberror($query);
 
 948   $amount = $netamount + $tax;
 
 950   # set values which could be empty to 0
 
 952   $form->{taxincluded} *= 1;
 
 953   my $datepaid = ($form->{paid})    ? qq|'$form->{datepaid}'| : "NULL";
 
 954   my $duedate  = ($form->{duedate}) ? qq|'$form->{duedate}'|  : "NULL";
 
 956     ($form->{deliverydate}) ? qq|'$form->{deliverydate}'| : "NULL";
 
 958   # fill in subject if there is none
 
 959   $form->{subject} = qq|$form->{label} $form->{invnumber}|
 
 960     unless $form->{subject};
 
 962   # if there is a message stuff it into the intnotes
 
 963   my $cc  = "Cc: $form->{cc}\\r\n"   if $form->{cc};
 
 964   my $bcc = "Bcc: $form->{bcc}\\r\n" if $form->{bcc};
 
 965   my $now = scalar localtime;
 
 966   $form->{intnotes} .= qq|\r
 
 967 \r| if $form->{intnotes};
 
 969   $form->{intnotes} .= qq|[email]\r
 
 972 $cc${bcc}Subject: $form->{subject}\r
 
 974 Message: $form->{message}\r| if $form->{message};
 
 977   $query = qq|UPDATE ar set
 
 978               invnumber = '$form->{invnumber}',
 
 979               ordnumber = '$form->{ordnumber}',
 
 980               quonumber = '$form->{quonumber}',
 
 981               cusordnumber = '$form->{cusordnumber}',
 
 982               transdate = '$form->{invdate}',
 
 983               customer_id = $form->{customer_id},
 
 985               netamount = $netamount,
 
 986               paid = $form->{paid},
 
 987               datepaid = $datepaid,
 
 989               deliverydate = $deliverydate,
 
 991               shippingpoint = '$form->{shippingpoint}',
 
 992               shipvia = '$form->{shipvia}',
 
 993               terms = $form->{terms},
 
 994               notes = '$form->{notes}',
 
 995               intnotes = '$form->{intnotes}',
 
 996               taxincluded = '$form->{taxincluded}',
 
 997               curr = '$form->{currency}',
 
 998               department_id = $form->{department_id},
 
 999               payment_id = $form->{payment_id},
 
1000               type = '$form->{type}',
 
1001               language_id = $form->{language_id},
 
1002               taxzone_id = $form->{taxzone_id},
 
1003               shipto_id = $form->{shipto_id},
 
1004               delivery_customer_id = $form->{delivery_customer_id},
 
1005               delivery_vendor_id = $form->{delivery_vendor_id},
 
1006               employee_id = $form->{employee_id},
 
1007               storno = '$form->{storno}',
 
1008               cp_id = $form->{contact_id}
 
1009               WHERE id = $form->{id}
 
1011   $dbh->do($query) || $form->dberror($query);
 
1013   if ($form->{storno}) {
 
1014     $query = qq| update ar set paid=paid+amount where id=$form->{storno_id}|;
 
1015     $dbh->do($query) || $form->dberror($query);
 
1016     $query = qq| update ar set storno='$form->{storno}' where id=$form->{storno_id}|;
 
1017     $dbh->do($query) || $form->dberror($query);
 
1018     $query = qq§ update ar set intnotes='Rechnung storniert am $form->{invdate} ' || intnotes where id=$form->{storno_id}§;
 
1019     $dbh->do($query) || $form->dberror($query);
 
1021     $query = qq| update ar set paid=amount where id=$form->{id}|;
 
1022     $dbh->do($query) || $form->dberror($query);
 
1025   $form->{pago_total} = $amount;
 
1028   $form->{name} = $form->{customer};
 
1029   $form->{name} =~ s/--$form->{customer_id}//;
 
1031   if (!$form->{shipto_id}) {
 
1032     $form->add_shipto($dbh, $form->{id}, "AR");
 
1035   # save printed, emailed and queued
 
1036   $form->save_status($dbh);
 
1038   if ($form->{webdav}) {
 
1039     &webdav_folder($myconfig, $form);
 
1042   my $rc = $dbh->commit;
 
1045   $main::lxdebug->leave_sub();
 
1051   $main::lxdebug->enter_sub();
 
1053   my ($self, $myconfig, $form, $locale) = @_;
 
1055   # connect to database, turn off autocommit
 
1056   my $dbh = $form->dbconnect_noauto($myconfig);
 
1058   $form->{datepaid} = $form->{invdate};
 
1060   # total payments, don't move we need it here
 
1061   for my $i (1 .. $form->{paidaccounts}) {
 
1062     if ($form->{type} eq "credit_note") {
 
1063       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"}) * -1;
 
1065       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
 
1067     $form->{paid} += $form->{"paid_$i"};
 
1068     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
 
1071   $form->{exchangerate} =
 
1072       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
 
1075   # record payments and offsetting AR
 
1076   for my $i (1 .. $form->{paidaccounts}) {
 
1078     if ($form->{"paid_$i"} != 0) {
 
1079       my ($accno) = split /--/, $form->{"AR_paid_$i"};
 
1080       $form->{"datepaid_$i"} = $form->{invdate}
 
1081         unless ($form->{"datepaid_$i"});
 
1082       $form->{datepaid} = $form->{"datepaid_$i"};
 
1085       if (($form->{currency} eq $form->{defaultcurrency}) || ($form->{defaultcurrency} eq "")) {
 
1086         $form->{"exchangerate_$i"} = 1;
 
1089           $form->check_exchangerate($myconfig, $form->{currency},
 
1090                                     $form->{"datepaid_$i"}, 'buy');
 
1092         $form->{"exchangerate_$i"} =
 
1095           : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
1100         $form->round_amount($form->{"paid_$i"} * $form->{"exchangerate"},
 
1104       $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
 
1105                                       WHERE c.accno = '$form->{AR}') AND amount=$amount AND transdate='$form->{"datepaid_$i"}'|;
 
1106       $dbh->do($query) || $form->dberror($query);
 
1108       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
1110                   VALUES ($form->{id}, (SELECT c.id FROM chart c
 
1111                                       WHERE c.accno = '$form->{AR}'),
 
1112                   $amount, '$form->{"datepaid_$i"}')|;
 
1113       $dbh->do($query) || $form->dberror($query);
 
1117       $form->{"paid_$i"} *= -1;
 
1119       $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
 
1120                                       WHERE c.accno = '$accno') AND amount=$form->{"paid_$i"} AND transdate='$form->{"datepaid_$i"}' AND source='$form->{"source_$i"}' AND memo='$form->{"memo_$i"}'|;
 
1121       $dbh->do($query) || $form->dberror($query);
 
1123       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
 
1125                   VALUES ($form->{id}, (SELECT c.id FROM chart c
 
1126                                       WHERE c.accno = '$accno'),
 
1127                   $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
 
1128                   '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
 
1129       $dbh->do($query) || $form->dberror($query);
 
1134         $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
 
1135         $form->{"exchangerate_$i"};
 
1137         $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
 
1140         $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
 
1146       # update exchange rate
 
1147       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
1148         $form->update_exchangerate($dbh, $form->{currency},
 
1149                                    $form->{"datepaid_$i"},
 
1150                                    $form->{"exchangerate_$i"}, 0);
 
1155   # record exchange rate differences and gains/losses
 
1156   foreach my $accno (keys %{ $form->{fx} }) {
 
1157     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
 
1159           ($form->{fx}{$accno}{$transdate} =
 
1160            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
 
1163         $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
 
1164                                         WHERE c.accno = '$accno') AND amount=$form->{fx}{$accno}{$transdate} AND transdate='$transdate' AND cleared='0' AND fx_transaction='1'|;
 
1165         $dbh->do($query) || $form->dberror($query);
 
1166         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
 
1167                     transdate, cleared, fx_transaction)
 
1168                     VALUES ($form->{id},
 
1169                            (SELECT c.id FROM chart c
 
1170                             WHERE c.accno = '$accno'),
 
1171                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1')|;
 
1172         $dbh->do($query) || $form->dberror($query);
 
1176   my $datepaid = ($form->{paid})    ? qq|'$form->{datepaid}'| : "NULL";
 
1179   my $query = qq|UPDATE ar set
 
1180               paid = $form->{paid},
 
1181               datepaid = $datepaid
 
1182               WHERE id=$form->{id}|;
 
1184   $dbh->do($query) || $form->dberror($query);
 
1186   my $rc = $dbh->commit;
 
1189   $main::lxdebug->leave_sub();
 
1194 sub process_assembly {
 
1195   $main::lxdebug->enter_sub();
 
1197   my ($dbh, $form, $id, $totalqty) = @_;
 
1199   my $query = qq|SELECT a.parts_id, a.qty, p.assembly,
 
1200                  p.partnumber, p.description, p.unit,
 
1201                  p.inventory_accno_id, p.income_accno_id,
 
1204                  JOIN parts p ON (a.parts_id = p.id)
 
1206   my $sth = $dbh->prepare($query);
 
1207   $sth->execute || $form->dberror($query);
 
1209   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1213     $ref->{inventory_accno_id} *= 1;
 
1214     $ref->{expense_accno_id}   *= 1;
 
1216     map { $ref->{$_} =~ s/\'/\'\'/g } (qw(partnumber description unit));
 
1218     # multiply by number of assemblies
 
1219     $ref->{qty} *= $totalqty;
 
1221     if ($ref->{assembly}) {
 
1222       &process_assembly($dbh, $form, $ref->{parts_id}, $ref->{qty});
 
1225       if ($ref->{inventory_accno_id}) {
 
1226         $allocated = &cogs($dbh, $form, $ref->{parts_id}, $ref->{qty});
 
1230     # save detail record for individual assembly item in invoice table
 
1231     $query = qq|INSERT INTO invoice (trans_id, description, parts_id, qty,
 
1232                 sellprice, fxsellprice, allocated, assemblyitem, unit)
 
1234                 ($form->{id}, '$ref->{description}',
 
1235                 $ref->{parts_id}, $ref->{qty}, 0, 0, $allocated, 't',
 
1237     $dbh->do($query) || $form->dberror($query);
 
1243   $main::lxdebug->leave_sub();
 
1247   $main::lxdebug->enter_sub();
 
1249   my ($dbh, $form, $id, $totalqty, $basefactor, $row) = @_;
 
1250   $form->{taxzone_id} *=1;
 
1251   my $transdate = ($form->{invdate}) ? "'$form->{invdate}'" : "current_date";
 
1252   my $query = qq|SELECT i.id, i.trans_id, i.base_qty, i.allocated, i.sellprice,
 
1253                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
 
1254                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
 
1255                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid
 
1256                   FROM invoice i, parts p
 
1257                   LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
 
1258                   LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
 
1259                   LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
 
1260                   WHERE i.parts_id = p.id
 
1261                   AND i.parts_id = $id
 
1262                   AND (i.base_qty + i.allocated) < 0
 
1264   my $sth = $dbh->prepare($query);
 
1265   $sth->execute || $form->dberror($query);
 
1270   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1271     if (($qty = (($ref->{base_qty} * -1) - $ref->{allocated})) > $totalqty) {
 
1275     $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|,
 
1278     # total expenses and inventory
 
1279     # sellprice is the cost of the item
 
1280     $linetotal = $form->round_amount(($ref->{sellprice} * $qty) / $basefactor, 2);
 
1283       $ref->{expense_accno} = ($form->{"expense_accno_$row"}) ? $form->{"expense_accno_$row"} : $ref->{expense_accno};
 
1285       $form->{amount}{ $form->{id} }{ $ref->{expense_accno} } += -$linetotal;
 
1286       $form->{expense_inventory} .= " " . $ref->{expense_accno};
 
1287       $ref->{inventory_accno} = ($form->{"inventory_accno_$row"}) ? $form->{"inventory_accno_$row"} : $ref->{inventory_accno};
 
1289       $form->{amount}{ $form->{id} }{ $ref->{inventory_accno} } -= -$linetotal;
 
1290       $form->{expense_inventory} .= " " . $ref->{inventory_accno};
 
1294     $allocated += -$qty;
 
1296     last if (($totalqty -= $qty) <= 0);
 
1301   $main::lxdebug->leave_sub();
 
1306 sub reverse_invoice {
 
1307   $main::lxdebug->enter_sub();
 
1309   my ($dbh, $form) = @_;
 
1311   # reverse inventory items
 
1312   my $query = qq|SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
 
1313                  p.inventory_accno_id
 
1315                  JOIN parts p ON (i.parts_id = p.id)
 
1316                  WHERE i.trans_id = $form->{id}|;
 
1317   my $sth = $dbh->prepare($query);
 
1318   $sth->execute || $form->dberror($query);
 
1320   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1322     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
 
1324       # if the invoice item is not an assemblyitem adjust parts onhand
 
1325       if (!$ref->{assemblyitem}) {
 
1327         # adjust onhand in parts table
 
1328         $form->update_balance($dbh, "parts", "onhand",
 
1329                               qq|id = $ref->{parts_id}|,
 
1333       # loop if it is an assembly
 
1334       next if ($ref->{assembly});
 
1336       # de-allocated purchases
 
1337       $query = qq|SELECT i.id, i.trans_id, i.allocated
 
1339                   WHERE i.parts_id = $ref->{parts_id}
 
1341                   ORDER BY i.trans_id DESC|;
 
1342       my $sth = $dbh->prepare($query);
 
1343       $sth->execute || $form->dberror($query);
 
1345       while (my $inhref = $sth->fetchrow_hashref(NAME_lc)) {
 
1347         if (($ref->{qty} - $inhref->{allocated}) > 0) {
 
1348           $qty = $inhref->{allocated};
 
1352         $form->update_balance($dbh, "invoice", "allocated",
 
1353                               qq|id = $inhref->{id}|,
 
1356         last if (($ref->{qty} -= $qty) <= 0);
 
1365   $query = qq|DELETE FROM acc_trans
 
1366               WHERE trans_id = $form->{id}|;
 
1367   $dbh->do($query) || $form->dberror($query);
 
1369   # delete invoice entries
 
1370   $query = qq|DELETE FROM invoice
 
1371               WHERE trans_id = $form->{id}|;
 
1372   $dbh->do($query) || $form->dberror($query);
 
1374   if ($form->{lizenzen}) {
 
1375     $query = qq|DELETE FROM licenseinvoice
 
1376               WHERE trans_id in (SELECT id FROM invoice WHERE trans_id = $form->{id})|;
 
1377     $dbh->do($query) || $form->dberror($query);
 
1380   $query = qq|DELETE FROM shipto
 
1381               WHERE trans_id = $form->{id} AND module = 'AR'|;
 
1382   $dbh->do($query) || $form->dberror($query);
 
1384   $main::lxdebug->leave_sub();
 
1387 sub delete_invoice {
 
1388   $main::lxdebug->enter_sub();
 
1390   my ($self, $myconfig, $form, $spool) = @_;
 
1392   # connect to database
 
1393   my $dbh = $form->dbconnect_noauto($myconfig);
 
1395   &reverse_invoice($dbh, $form);
 
1398   my $query = qq|DELETE FROM ar
 
1399                  WHERE id = $form->{id}|;
 
1400   $dbh->do($query) || $form->dberror($query);
 
1402   # delete spool files
 
1403   $query = qq|SELECT s.spoolfile FROM status s
 
1404               WHERE s.trans_id = $form->{id}|;
 
1405   my $sth = $dbh->prepare($query);
 
1406   $sth->execute || $self->dberror($query);
 
1409   my @spoolfiles = ();
 
1411   while (($spoolfile) = $sth->fetchrow_array) {
 
1412     push @spoolfiles, $spoolfile;
 
1416   # delete status entries
 
1417   $query = qq|DELETE FROM status
 
1418               WHERE trans_id = $form->{id}|;
 
1419   $dbh->do($query) || $form->dberror($query);
 
1421   my $rc = $dbh->commit;
 
1425     foreach $spoolfile (@spoolfiles) {
 
1426       unlink "$spool/$spoolfile" if $spoolfile;
 
1430   $main::lxdebug->leave_sub();
 
1435 sub retrieve_invoice {
 
1436   $main::lxdebug->enter_sub();
 
1438   my ($self, $myconfig, $form) = @_;
 
1440   # connect to database
 
1441   my $dbh = $form->dbconnect_noauto($myconfig);
 
1447     # get default accounts and last invoice number
 
1448     $query = qq|SELECT (SELECT c.accno FROM chart c
 
1449                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
 
1450                        (SELECT c.accno FROM chart c
 
1451                         WHERE d.income_accno_id = c.id) AS income_accno,
 
1452                        (SELECT c.accno FROM chart c
 
1453                         WHERE d.expense_accno_id = c.id) AS expense_accno,
 
1454                        (SELECT c.accno FROM chart c
 
1455                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
1456                        (SELECT c.accno FROM chart c
 
1457                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
1458                 d.curr AS currencies
 
1461     $query = qq|SELECT (SELECT c.accno FROM chart c
 
1462                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
 
1463                        (SELECT c.accno FROM chart c
 
1464                         WHERE d.income_accno_id = c.id) AS income_accno,
 
1465                        (SELECT c.accno FROM chart c
 
1466                         WHERE d.expense_accno_id = c.id) AS expense_accno,
 
1467                        (SELECT c.accno FROM chart c
 
1468                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
1469                        (SELECT c.accno FROM chart c
 
1470                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
 
1471                 d.curr AS currencies, current_date AS invdate
 
1474   my $sth = $dbh->prepare($query);
 
1475   $sth->execute || $form->dberror($query);
 
1477   my $ref = $sth->fetchrow_hashref(NAME_lc);
 
1478   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1484     $query = qq|SELECT a.invnumber, a.ordnumber, a.quonumber, a.cusordnumber,
 
1485                 a.transdate AS invdate, a.deliverydate, a.paid, a.storno, a.gldate,
 
1486                 a.shippingpoint, a.shipvia, a.terms, a.notes, a.intnotes, a.taxzone_id,
 
1487                 a.duedate, a.taxincluded, a.curr AS currency, a.shipto_id, a.cp_id,
 
1488                 a.employee_id, e.name AS employee, a.payment_id, a.language_id, a.delivery_customer_id, a.delivery_vendor_id, a.type
 
1490                 LEFT JOIN employee e ON (e.id = a.employee_id)
 
1491                 WHERE a.id = $form->{id}|;
 
1492     $sth = $dbh->prepare($query);
 
1493     $sth->execute || $form->dberror($query);
 
1495     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1496     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1499     $form->{exchangerate} =
 
1500       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
 
1503     $query = qq|SELECT s.* FROM shipto s
 
1504                 WHERE s.trans_id = $form->{id} AND s.module = 'AR'|;
 
1505     $sth = $dbh->prepare($query);
 
1506     $sth->execute || $form->dberror($query);
 
1508     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1510     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1513    if ($form->{delivery_customer_id}) {
 
1514       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_customer_id}|;
 
1515       $sth = $dbh->prepare($query);
 
1516       $sth->execute || $form->dberror($query);
 
1517       ($form->{delivery_customer_string}) = $sth->fetchrow_array();
 
1521     if ($form->{delivery_vendor_id}) {
 
1522       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_vendor_id}|;
 
1523       $sth = $dbh->prepare($query);
 
1524       $sth->execute || $form->dberror($query);
 
1525       ($form->{delivery_vendor_string}) = $sth->fetchrow_array();
 
1529     # get printed, emailed
 
1530     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
 
1532                 WHERE s.trans_id = $form->{id}|;
 
1533     $sth = $dbh->prepare($query);
 
1534     $sth->execute || $form->dberror($query);
 
1536     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1537       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
 
1538       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
 
1539       $form->{queued} .= "$ref->{formname} $ref->{spoolfile} "
 
1540         if $ref->{spoolfile};
 
1543     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
 
1546       $form->{deliverydate} ? $dbh->quote($form->{deliverydate}) :
 
1547       $form->{invdate} ? $dbh->quote($form->{invdate}) :
 
1550     if (!$form->{taxzone_id}) {
 
1551       $form->{taxzone_id} = 0;
 
1553     # retrieve individual items
 
1555                 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
 
1556                 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
 
1557                 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
 
1558                 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice,
 
1559                 i.discount, i.parts_id AS id, i.unit, i.deliverydate,
 
1560                 i.project_id, pr.projectnumber, i.serialnumber,
 
1561                 p.partnumber, p.assembly, p.bin, p.notes AS partnotes, p.inventory_accno_id AS part_inventory_accno_id, i.id AS invoice_pos,
 
1562                 pg.partsgroup, i.pricegroup_id, (SELECT pricegroup FROM pricegroup WHERE id=i.pricegroup_id) as pricegroup,
 
1563                 i.ordnumber, i.transdate, i.cusordnumber, p.formel, i.subtotal
 
1565                 JOIN parts p ON (i.parts_id = p.id)
 
1566                 LEFT JOIN project pr ON (i.project_id = pr.id)
 
1567                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
 
1568                 LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
 
1569                 LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
 
1570                 LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
 
1571                 WHERE i.trans_id = $form->{id}
 
1572                 AND NOT i.assemblyitem = '1'
 
1574     $sth = $dbh->prepare($query);
 
1576     $sth->execute || $form->dberror($query);
 
1577     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1578       if (!$ref->{"part_inventory_accno_id"}) {
 
1579         map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
 
1581       delete($ref->{"part_inventory_accno_id"});
 
1583     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
 
1584       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}|;
 
1585       my $stw = $dbh->prepare($query);
 
1586       $stw->execute || $form->dberror($query);
 
1587       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
 
1591     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
 
1592       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}|;
 
1593       my $stw = $dbh->prepare($query);
 
1594       $stw->execute || $form->dberror($query);
 
1595       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
 
1599     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
 
1600       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}|;
 
1601       my $stw = $dbh->prepare($query);
 
1602       $stw->execute || $form->dberror($query);
 
1603       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
 
1607       # get tax rates and description
 
1609         ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
 
1610     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
 
1611               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
 
1612               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)
 
1614       $stw = $dbh->prepare($query);
 
1615       $stw->execute || $form->dberror($query);
 
1616       $ref->{taxaccounts} = "";
 
1618       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
1620         #    if ($customertax{$ref->{accno}}) {
 
1621         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
 
1625         $ref->{taxaccounts} .= "$ptr->{accno} ";
 
1627         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
 
1628           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
1629           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
 
1630           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
1631           $form->{taxaccounts} .= "$ptr->{accno} ";
 
1636       if ($form->{lizenzen}) {
 
1637         $query = qq|SELECT l.licensenumber, l.id AS licenseid
 
1638                  FROM license l, licenseinvoice li
 
1639                  WHERE l.id = li.license_id AND li.trans_id = $ref->{invoice_pos}|;
 
1640         $stg = $dbh->prepare($query);
 
1641         $stg->execute || $form->dberror($query);
 
1642         ($licensenumber, $licenseid) = $stg->fetchrow_array();
 
1644           "<option value=\"$licenseid\">$licensenumber</option>";
 
1647       if ($form->{type} eq "credit_note") {
 
1651       chop $ref->{taxaccounts};
 
1652       push @{ $form->{invoice_details} }, $ref;
 
1657     if ($form->{webdav}) {
 
1658       &webdav_folder($myconfig, $form);
 
1662   my $rc = $dbh->commit;
 
1665   $main::lxdebug->leave_sub();
 
1671   $main::lxdebug->enter_sub();
 
1673   my ($self, $myconfig, $form) = @_;
 
1675   # connect to database
 
1676   my $dbh = $form->dbconnect($myconfig);
 
1678   my $dateformat = $myconfig->{dateformat};
 
1679   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
1683     ? "to_date('$form->{invdate}', '$dateformat')"
 
1686   $form->{customer_id} *= 1;
 
1689   my $query = qq|SELECT c.name AS customer, c.discount, c.creditlimit, c.terms,
 
1690                  c.email, c.cc, c.bcc, c.language_id, c.payment_id AS customer_payment_id,
 
1691                  c.street, c.zipcode, c.city, c.country,
 
1692                  $duedate + c.terms AS duedate, c.notes AS intnotes,
 
1693                  b.discount AS tradediscount, b.description AS business, c.klass as customer_klass, c.taxzone_id
 
1695                  LEFT JOIN business b ON (b.id = c.business_id)
 
1696                  WHERE c.id = $form->{customer_id}|;
 
1697   my $sth = $dbh->prepare($query);
 
1698   $sth->execute || $form->dberror($query);
 
1700   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1702   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1705   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|;
 
1706   my $sth = $dbh->prepare($query);
 
1708   $sth->execute || $form->dberror($query);
 
1710   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1712   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1715   #print(STDERR "DUNNING AMOUTN $form->{dunning_amount}\n");
 
1717   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|;
 
1718   my $sth = $dbh->prepare($query);
 
1720   $sth->execute || $form->dberror($query);
 
1722   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1724   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1726   #print(STDERR "LEVEL $form->{max_dunning_level}\n");
 
1729   #check whether payment_terms are better than old payment_terms
 
1730   if (($form->{payment_id} ne "") && ($form->{customer_payment_id} ne "")) {
 
1731     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})|;
 
1732     my $stw = $dbh->prepare($query);
 
1733     $stw->execute || $form->dberror($query);
 
1734     ($old_ranking, $new_ranking) = $stw->fetchrow_array;
 
1736     if ($new_ranking > $old_ranking) {
 
1737       $form->{payment_id} =$form->{customer_payment_id};
 
1740   if ($form->{payment_id} eq "") {
 
1741     $form->{payment_id} =$form->{customer_payment_id};
 
1744   $form->{creditremaining} = $form->{creditlimit};
 
1745   $query = qq|SELECT SUM(a.amount - a.paid)
 
1747               WHERE a.customer_id = $form->{customer_id}|;
 
1748   $sth = $dbh->prepare($query);
 
1749   $sth->execute || $form->dberror($query);
 
1751   ($form->{creditremaining}) -= $sth->fetchrow_array;
 
1755   $query = qq|SELECT o.amount,
 
1756                 (SELECT e.buy FROM exchangerate e
 
1757                  WHERE e.curr = o.curr
 
1758                  AND e.transdate = o.transdate)
 
1760               WHERE o.customer_id = $form->{customer_id}
 
1761               AND o.quotation = '0'
 
1762               AND o.closed = '0'|;
 
1763   $sth = $dbh->prepare($query);
 
1764   $sth->execute || $form->dberror($query);
 
1766   while (my ($amount, $exch) = $sth->fetchrow_array) {
 
1767     $exch = 1 unless $exch;
 
1768     $form->{creditremaining} -= $amount * $exch;
 
1772   $form->get_contacts($dbh, $form->{customer_id});
 
1773   $form->{cp_id} *= 1;
 
1775   # get contact if selected
 
1776   if ($form->{cp_id}) {
 
1777     $form->get_contact($dbh, $form->{cp_id});
 
1780   # get shipto if we did not converted an order or invoice
 
1781   if (!$form->{shipto}) {
 
1782     map { delete $form->{$_} }
 
1783       qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail);
 
1785     $query = qq|SELECT s.* FROM shipto s
 
1786                 WHERE s.trans_id = $form->{customer_id} AND s.module = 'CT'|;
 
1787     $sth = $dbh->prepare($query);
 
1788     $sth->execute || $form->dberror($query);
 
1790     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1792     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1796   # get taxes we charge for this customer
 
1797   $query = qq|SELECT c.accno
 
1799               JOIN customertax ct ON (ct.chart_id = c.id)
 
1800               WHERE ct.customer_id = $form->{customer_id}|;
 
1801   $sth = $dbh->prepare($query);
 
1802   $sth->execute || $form->dberror($query);
 
1804   my $customertax = ();
 
1805   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1806     $customertax{ $ref->{accno} } = 1;
 
1810   # get shipping addresses
 
1811   $query = qq|SELECT s.shipto_id,s.shiptoname,s.shiptodepartment_1
 
1813               WHERE s.trans_id = $form->{customer_id}|;
 
1814   $sth = $dbh->prepare($query);
 
1815   $sth->execute || $form->dberror($query);
 
1817   my $customertax = ();
 
1818   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1819     push(@{ $form->{SHIPTO} }, $ref);
 
1823   # setup last accounts used for this customer
 
1824   if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
 
1825     $query = qq|SELECT c.accno, c.description, c.link, c.category
 
1827                 JOIN acc_trans ac ON (ac.chart_id = c.id)
 
1828                 JOIN ar a ON (a.id = ac.trans_id)
 
1829                 WHERE a.customer_id = $form->{customer_id}
 
1830                 AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
 
1831                 AND a.id IN (SELECT max(a2.id) FROM ar a2
 
1832                              WHERE a2.customer_id = $form->{customer_id})|;
 
1833     $sth = $dbh->prepare($query);
 
1834     $sth->execute || $form->dberror($query);
 
1837     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1838       if ($ref->{category} eq 'I') {
 
1840         $form->{"AR_amount_$i"} = "$ref->{accno}--$ref->{description}";
 
1842       if ($ref->{category} eq 'A') {
 
1843         $form->{ARselected} = $form->{AR_1} =
 
1844           "$ref->{accno}--$ref->{description}";
 
1848     $form->{rowcount} = $i if ($i && !$form->{type});
 
1853   $main::lxdebug->leave_sub();
 
1857   $main::lxdebug->enter_sub();
 
1859   my ($self, $myconfig, $form) = @_;
 
1861   # connect to database
 
1862   my $dbh = $form->dbconnect($myconfig);
 
1864   my $i = $form->{rowcount};
 
1866   my $where = "NOT p.obsolete = '1'";
 
1868   if ($form->{"partnumber_$i"}) {
 
1869     my $partnumber = $form->like(lc $form->{"partnumber_$i"});
 
1870     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
 
1872   if ($form->{"description_$i"}) {
 
1873     my $description = $form->like(lc $form->{"description_$i"});
 
1874     $where .= " AND lower(p.description) LIKE '$description'";
 
1877   if ($form->{"partsgroup_$i"}) {
 
1878     my $partsgroup = $form->like(lc $form->{"partsgroup_$i"});
 
1879     $where .= " AND lower(pg.partsgroup) LIKE '$partsgroup'";
 
1882   if ($form->{"description_$i"}) {
 
1883     $where .= " ORDER BY p.description";
 
1885     $where .= " ORDER BY p.partnumber";
 
1889   if ($form->{type} eq "invoice") {
 
1891       $form->{deliverydate} ? $dbh->quote($form->{deliverydate}) :
 
1892       $form->{invdate} ? $dbh->quote($form->{invdate}) :
 
1896       $form->{transdate} ? $dbh->quote($form->{transdate}) :
 
1900   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
 
1901                         p.listprice, p.inventory_accno_id,
 
1902                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
 
1903                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
 
1904                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
 
1905                  p.unit, p.assembly, p.bin, p.onhand, p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
 
1906                  pg.partsgroup, p.formel, p.payment_id AS part_payment_id
 
1908                  LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
 
1909                  LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
 
1910                  LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
 
1911                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_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} = "";
 
1965     # get tax rates and description
 
1967       ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
 
1968     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
 
1969               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
 
1970               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)
 
1972     $stw = $dbh->prepare($query);
 
1973     $stw->execute || $form->dberror($query);
 
1975     $ref->{taxaccounts} = "";
 
1977     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
1979       #    if ($customertax{$ref->{accno}}) {
 
1980       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
 
1984       $ref->{taxaccounts} .= "$ptr->{accno} ";
 
1986       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
 
1987         $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
 
1988         $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
 
1989         $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
 
1990         $form->{taxaccounts} .= "$ptr->{accno} ";
 
1996     chop $ref->{taxaccounts};
 
1997     if ($form->{language_id}) {
 
1998       $query = qq|SELECT tr.translation, tr.longdescription
 
2000                 WHERE tr.language_id=$form->{language_id} AND tr.parts_id=$ref->{id}|;
 
2001       $stw = $dbh->prepare($query);
 
2002       $stw->execute || $form->dberror($query);
 
2003       my ($translation, $longdescription) = $stw->fetchrow_array();
 
2004       if ($translation ne "") {
 
2005         $ref->{description} = $translation;
 
2006         $ref->{longdescription} = $longdescription;
 
2009         $query = qq|SELECT tr.translation, tr.longdescription
 
2011                 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|;
 
2012         $stg = $dbh->prepare($query);
 
2013         $stg->execute || $form->dberror($query);
 
2014         my ($translation) = $stg->fetchrow_array();
 
2015         if ($translation ne "") {
 
2016           $ref->{description} = $translation;
 
2017           $ref->{longdescription} = $longdescription;
 
2024     push @{ $form->{item_list} }, $ref;
 
2026     if ($form->{lizenzen}) {
 
2027       if ($ref->{inventory_accno} > 0) {
 
2029           qq| SELECT l.* FROM license l WHERE l.parts_id = $ref->{id} AND NOT l.id IN (SELECT li.license_id FROM licenseinvoice li)|;
 
2030         $stw = $dbh->prepare($query);
 
2031         $stw->execute || $form->dberror($query);
 
2032         while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
 
2033           push @{ $form->{LIZENZEN}{ $ref->{id} } }, $ptr;
 
2042   $main::lxdebug->leave_sub();
 
2045 ##########################
 
2046 # get pricegroups from database
 
2047 # build up selected pricegroup
 
2048 # if an exchange rate - change price
 
2051 sub get_pricegroups_for_parts {
 
2053   $main::lxdebug->enter_sub();
 
2055   my ($self, $myconfig, $form) = @_;
 
2057   my $dbh = $form->dbconnect($myconfig);
 
2059   $form->{"PRICES"} = {};
 
2063   my $dimension_units = AM->retrieve_units($myconfig, $form, "dimension");
 
2064   my $service_units = AM->retrieve_units($myconfig, $form, "service");
 
2065   my $all_units = AM->retrieve_units($myconfig, $form);
 
2066   while (($form->{"id_$i"}) or ($form->{"new_id_$i"})) {
 
2067     $form->{"PRICES"}{$i} = [];
 
2069     $id = $form->{"id_$i"};
 
2071     if (!($form->{"id_$i"}) and $form->{"new_id_$i"}) {
 
2073       $id = $form->{"new_id_$i"};
 
2076     ($price, $selectedpricegroup_id) = split /--/,
 
2077       $form->{"sellprice_pg_$i"};
 
2079     $pricegroup_old = $form->{"pricegroup_old_$i"};
 
2080     $form->{"new_pricegroup_$i"} = $selectedpricegroup_id;
 
2081     $form->{"old_pricegroup_$i"} = $pricegroup_old;
 
2082     $price_new = $form->{"price_new_$i"};
 
2084     $price_old = $form->{"price_old_$i"};
 
2086       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|;
 
2088     $pkq = $dbh->prepare($query);
 
2089     $pkq->execute || $form->dberror($query);
 
2090     if (!$form->{"unit_old_$i"}) {
 
2091       # Neue Ware aus der Datenbank. In diesem Fall ist unit_$i die
 
2092       # Einheit, wie sie in den Stammdaten hinterlegt wurde.
 
2093       # Es sollte also angenommen werden, dass diese ausgewaehlt war.
 
2094       $form->{"unit_old_$i"} = $form->{"unit_$i"};
 
2097     # Die zuletzt ausgewaehlte mit der aktuell ausgewaehlten Einheit
 
2098     # vergleichen und bei Unterschied den Preis entsprechend umrechnen.
 
2099     $form->{"selected_unit_$i"} = $form->{"unit_$i"} unless ($form->{"selected_unit_$i"});
 
2101     my $check_units = $form->{"inventory_accno_$i"} ? $dimension_units : $service_units;
 
2102     if (!$check_units->{$form->{"selected_unit_$i"}} ||
 
2103         ($check_units->{$form->{"selected_unit_$i"}}->{"base_unit"} ne
 
2104          $all_units->{$form->{"unit_old_$i"}}->{"base_unit"})) {
 
2105       # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
 
2106       # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
 
2107       # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
 
2108       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};
 
2112     if ($form->{"unit_old_$i"} ne $form->{"selected_unit_$i"}) {
 
2113       if (defined($all_units->{$form->{"unit_old_$i"}}->{"factor"}) &&
 
2114           $all_units->{$form->{"unit_old_$i"}}->{"factor"}) {
 
2115         $basefactor = $all_units->{$form->{"selected_unit_$i"}}->{"factor"} /
 
2116           $all_units->{$form->{"unit_old_$i"}}->{"factor"};
 
2119     if (!$form->{"basefactor_$i"}) {
 
2120       $form->{"basefactor_$i"} = 1;
 
2122     while ($pkr = $pkq->fetchrow_hashref(NAME_lc)) {
 
2124       #       push @{ $form->{PRICES}{$id} }, $pkr;
 
2125       #push @{ $form->{PRICES}{$i} }, $pkr;
 
2127       $pkr->{selected} = '';
 
2129       # if there is an exchange rate change price
 
2130       if (($form->{exchangerate} * 1) != 0) {
 
2132         $pkr->{price} /= $form->{exchangerate};
 
2135       $pkr->{price} *= $form->{"basefactor_$i"};
 
2137       $pkr->{price} *= $basefactor;
 
2139       $pkr->{price} = $form->format_amount($myconfig, $pkr->{price}, 5);
 
2141       if ($selectedpricegroup_id eq undef) {
 
2142         if ($pkr->{pricegroup_id} eq $form->{customer_klass}) {
 
2144           $pkr->{selected}  = ' selected';
 
2146           # no customer pricesgroup set
 
2147           if ($pkr->{price} == $pkr->{default_sellprice}) {
 
2149             $pkr->{price} = $form->{"sellprice_$i"};
 
2153             $form->{"sellprice_$i"} = $pkr->{price};
 
2157           if ($pkr->{price} == $pkr->{default_sellprice}) {
 
2159             $pkr->{price}    = $form->{"sellprice_$i"};
 
2160             $pkr->{selected} = ' selected';
 
2165       if ($selectedpricegroup_id or $selectedpricegroup_id == 0) {
 
2166         if ($selectedpricegroup_id ne $pricegroup_old) {
 
2167           if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
 
2168             $pkr->{selected}  = ' selected';
 
2171           if (($price_new != $form->{"sellprice_$i"}) and ($price_new ne 0)) {
 
2172             if ($pkr->{pricegroup_id} == 0) {
 
2173               $pkr->{price}     = $form->{"sellprice_$i"};
 
2174               $pkr->{selected}  = ' selected';
 
2177             if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
 
2178               $pkr->{selected}  = ' selected';
 
2179               if (    ($pkr->{pricegroup_id} == 0)
 
2180                   and ($pkr->{price} == $form->{"sellprice_$i"})) {
 
2182                 # $pkr->{price}                         = $form->{"sellprice_$i"};
 
2184                 $pkr->{price} = $form->{"sellprice_$i"};
 
2190       push @{ $form->{PRICES}{$i} }, $pkr;
 
2193     $form->{"basefactor_$i"} *= $basefactor;
 
2202   $main::lxdebug->leave_sub();
 
2206   $main::lxdebug->enter_sub();
 
2208   my ($myconfig, $form) = @_;
 
2211     $path = "webdav/rechnungen/" . $form->{invnumber}, last SWITCH
 
2212       if ($form->{vc} eq "customer");
 
2213     $path = "webdav/einkaufsrechnungen/" . $form->{invnumber}, last SWITCH
 
2214       if ($form->{vc} eq "vendor");
 
2218     mkdir($path, 0770) or die "can't make directory $!\n";
 
2222       foreach $file (@files) {
 
2223         $file =~ /\/([^\/]*)$/;
 
2225         $ENV{'SCRIPT_NAME'} =~ /\/([^\/]*)\//;
 
2227         $link  = "http://" . $ENV{'SERVER_NAME'} . "/" . $lxerp . "/" . $file;
 
2228         $form->{WEBDAV}{$fname} = $link;
 
2233   $main::lxdebug->leave_sub();