1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  17 # This program is free software; you can redistribute it and/or modify
 
  18 # it under the terms of the GNU General Public License as published by
 
  19 # the Free Software Foundation; either version 2 of the License, or
 
  20 # (at your option) any later version.
 
  22 # This program is distributed in the hope that it will be useful,
 
  23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  25 # GNU General Public License for more details.
 
  26 # You should have received a copy of the GNU General Public License
 
  27 # along with this program; if not, write to the Free Software
 
  28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  29 #======================================================================
 
  31 # Accounts Payables database backend routines
 
  33 #======================================================================
 
  37 use SL::DATEV qw(:CONSTANTS);
 
  46 sub post_transaction {
 
  47   $main::lxdebug->enter_sub();
 
  49   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
 
  50   my $rc = 0; # return code auf false setzen
 
  52   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
 
  54   my ($null, $taxrate, $amount);
 
  57   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
  58   delete $form->{currency} unless $form->{defaultcurrency};
 
  60   ($null, $form->{department_id}) = split(/--/, $form->{department});
 
  62   if ($form->{currency} eq $form->{defaultcurrency}) {
 
  63     $form->{exchangerate} = 1;
 
  65     $exchangerate         = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
  66     $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
 
  69   for my $i (1 .. $form->{rowcount}) {
 
  70     $form->{AP_amounts}{"amount_$i"} =
 
  71       (split(/--/, $form->{"AP_amount_$i"}))[0];
 
  73   ($form->{AP_amounts}{payables}) = split(/--/, $form->{APselected});
 
  74   ($form->{AP_payables})          = split(/--/, $form->{APselected});
 
  76   # reverse and parse amounts
 
  77   for my $i (1 .. $form->{rowcount}) {
 
  78     $form->{"amount_$i"} =
 
  80                          $form->parse_amount($myconfig, $form->{"amount_$i"}) *
 
  81                            $form->{exchangerate} * -1,
 
  83     $amount += ($form->{"amount_$i"} * -1);
 
  85     # parse tax_$i for later
 
  86     $form->{"tax_$i"} = $form->parse_amount($myconfig, $form->{"tax_$i"}) * -1;
 
  90   $form->{amount} = $amount;
 
  92   # taxincluded doesn't make sense if there is no amount
 
  93   $form->{taxincluded} = 0 if ($form->{amount} == 0);
 
  95   for my $i (1 .. $form->{rowcount}) {
 
  96     ($form->{"tax_id_$i"}, undef) = split /--/, $form->{"taxchart_$i"};
 
  99       qq|SELECT c.accno, t.taxkey, t.rate | .
 
 100       qq|FROM tax t LEFT JOIN chart c on (c.id=t.chart_id) | .
 
 101       qq|WHERE t.id = ? | .
 
 102       qq|ORDER BY c.accno|;
 
 103     my $sth = $dbh->prepare($query);
 
 104     $sth->execute($form->{"tax_id_$i"}) || $form->dberror($query . " (" . $form->{"tax_id_$i"} . ")");
 
 105     ($form->{AP_amounts}{"tax_$i"}, $form->{"taxkey_$i"}, $form->{"taxrate_$i"}) = $sth->fetchrow_array();
 
 110     if ($form->{taxincluded} *= 1) {
 
 111       $tax = $form->{"amount_$i"} - ($form->{"amount_$i"} / ($form->{"taxrate_$i"} + 1));
 
 112       $amount = $form->{"amount_$i"} - $tax;
 
 113       $form->{"amount_$i"} = $form->round_amount($amount, 2);
 
 114       $diff += $amount - $form->{"amount_$i"};
 
 115       $form->{"tax_$i"} = $form->round_amount($tax, 2);
 
 116       $form->{netamount} += $form->{"amount_$i"};
 
 118       $form->{"tax_$i"} = $form->{"amount_$i"} * $form->{"taxrate_$i"};
 
 119       $form->{netamount} += $form->{"amount_$i"};
 
 121     $form->{total_tax} += $form->{"tax_$i"} * -1;
 
 124   # adjust paidaccounts if there is no date in the last row
 
 125   $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
 
 127   $form->{invpaid} = 0;
 
 128   $form->{netamount} *= -1;
 
 131   for my $i (1 .. $form->{paidaccounts}) {
 
 133       $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
 
 136     $form->{invpaid} += $form->{"paid_$i"};
 
 137     $form->{datepaid} = $form->{"datepaid_$i"};
 
 142     $form->round_amount($form->{invpaid} * $form->{exchangerate}, 2);
 
 144   # store invoice total, this goes into ap table
 
 145   $form->{invtotal} = $form->{netamount} + $form->{total_tax};
 
 147   # amount for total AP
 
 148   $form->{payables} = $form->{invtotal};
 
 150   # update exchangerate
 
 151   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 152     $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, 0,
 
 153                                $form->{exchangerate});
 
 156   my ($query, $sth, @values);
 
 158   if (!$payments_only) {
 
 159     # if we have an id delete old records
 
 162       # delete detail records
 
 163       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
 
 164       do_query($form, $dbh, $query, $form->{id});
 
 167       my $uid = rand() . time;
 
 169       $uid .= $form->{login};
 
 171       $uid = substr($uid, 2, 75);
 
 174         qq|INSERT INTO ap (invnumber, employee_id) | .
 
 175         qq|VALUES (?, (SELECT e.id FROM employee e WHERE e.login = ?))|;
 
 176       do_query($form, $dbh, $query, $uid, $form->{login});
 
 178       $query = qq|SELECT a.id FROM ap a
 
 179                   WHERE a.invnumber = ?|;
 
 180       ($form->{id}) = selectrow_query($form, $dbh, $query, $uid);
 
 183     $form->{invnumber} = $form->{id} unless $form->{invnumber};
 
 185     $query = qq|UPDATE ap SET
 
 186                 invnumber = ?, transdate = ?, ordnumber = ?, vendor_id = ?, taxincluded = ?,
 
 187                 amount = ?, duedate = ?, paid = ?, netamount = ?,
 
 188                 curr = ?, notes = ?, department_id = ?, storno = ?, storno_id = ?,
 
 189                 globalproject_id = ?, direct_debit = ?
 
 191     @values = ($form->{invnumber}, conv_date($form->{transdate}),
 
 192                   $form->{ordnumber}, conv_i($form->{vendor_id}),
 
 193                   $form->{taxincluded} ? 't' : 'f', $form->{invtotal},
 
 194                   conv_date($form->{duedate}), $form->{invpaid},
 
 196                   $form->{currency}, $form->{notes},
 
 197                   conv_i($form->{department_id}), $form->{storno},
 
 198                   $form->{storno_id}, conv_i($form->{globalproject_id}),
 
 199                   $form->{direct_debit} ? 't' : 'f',
 
 201     do_query($form, $dbh, $query, @values);
 
 203     # add individual transactions
 
 204     for my $i (1 .. $form->{rowcount}) {
 
 205       if ($form->{"amount_$i"} != 0) {
 
 207         $project_id = conv_i($form->{"project_id_$i"});
 
 209         # insert detail records in acc_trans
 
 211           qq|INSERT INTO acc_trans | .
 
 212           qq|  (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id)| .
 
 213           qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
 
 215         @values = ($form->{id}, $form->{AP_amounts}{"amount_$i"},
 
 216                    $form->{"amount_$i"}, conv_date($form->{transdate}),
 
 217                    $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}));
 
 218         do_query($form, $dbh, $query, @values);
 
 220         if ($form->{"tax_$i"} != 0) {
 
 221           # insert detail records in acc_trans
 
 223             qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, | .
 
 224             qq|  project_id, taxkey, tax_id) | .
 
 225             qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
 
 227           @values = ($form->{id}, $form->{AP_amounts}{"tax_$i"},
 
 228                      $form->{"tax_$i"}, conv_date($form->{transdate}),
 
 229                      $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}));
 
 230           do_query($form, $dbh, $query, @values);
 
 238       qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id) | .
 
 239       qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, | .
 
 240       qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| . 
 
 241       qq|        (SELECT tax_id| . 
 
 243       qq|         WHERE chart_id= (SELECT id | . 
 
 245       qq|                          WHERE accno = ?)| . 
 
 246       qq|         AND startdate <= ?| . 
 
 247       qq|         ORDER BY startdate DESC LIMIT 1))|;
 
 248     @values = ($form->{id}, $form->{AP_amounts}{payables}, $form->{payables},
 
 249                conv_date($form->{transdate}), $form->{AP_amounts}{payables}, $form->{AP_amounts}{payables}, conv_date($form->{transdate}));
 
 250     do_query($form, $dbh, $query, @values);
 
 253   # if there is no amount but a payment record a payable
 
 254   if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 255     $form->{payables} = $form->{invpaid};
 
 258   # add paid transactions
 
 259   for my $i (1 .. $form->{paidaccounts}) {
 
 261     if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
 
 265     if ($form->{"paid_$i"} != 0) {
 
 266       my $project_id = conv_i($form->{"paid_project_id_$i"});
 
 269       if ($form->{currency} eq $form->{defaultcurrency}) {
 
 270         $form->{"exchangerate_$i"} = 1;
 
 272         $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 273         $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
 275       $form->{"AP_paid_$i"} =~ s/\"//g;
 
 279       ($form->{"AP_paid_account_$i"}) = split(/--/, $form->{"AP_paid_$i"});
 
 280       $form->{"datepaid_$i"} = $form->{transdate}
 
 281         unless ($form->{"datepaid_$i"});
 
 283       # if there is no amount and invtotal is zero there is no exchangerate
 
 284       if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 285         $form->{exchangerate} = $form->{"exchangerate_$i"};
 
 289         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} * -1,
 
 291       if ($form->{payables}) {
 
 293           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id) | .
 
 294           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, | .
 
 295           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
 
 296           qq|        (SELECT tax_id| . 
 
 298           qq|         WHERE chart_id= (SELECT id | . 
 
 300           qq|                          WHERE accno = ?)| . 
 
 301           qq|         AND startdate <= ?| . 
 
 302           qq|         ORDER BY startdate DESC LIMIT 1))|;
 
 303         @values = ($form->{id}, $form->{AP_payables}, $amount,
 
 304                    conv_date($form->{"datepaid_$i"}), $project_id,
 
 305                    $form->{AP_payables}, $form->{AP_payables}, conv_date($form->{"datepaid_$i"}));
 
 306         do_query($form, $dbh, $query, @values);
 
 308       $form->{payables} = $amount;
 
 311       my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
 
 313         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, taxkey, tax_id) | .
 
 314         qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, | .
 
 315         qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | . 
 
 316         qq|        (SELECT tax_id| .
 
 318         qq|         WHERE chart_id= (SELECT id | . 
 
 320         qq|                          WHERE accno = ?)| . 
 
 321         qq|         AND startdate <= ?| . 
 
 322         qq|         ORDER BY startdate DESC LIMIT 1))|;
 
 323       @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $form->{"paid_$i"},
 
 324                  conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"},
 
 325                  $form->{"memo_$i"}, $project_id, $form->{"AP_paid_account_$i"},
 
 326                  $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}));
 
 327       do_query($form, $dbh, $query, @values);
 
 329       # add exchange rate difference
 
 331         $form->round_amount($form->{"paid_$i"} *
 
 332                             ($form->{"exchangerate_$i"} - 1), 2);
 
 335           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id) | .
 
 336           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 337           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 338           qq|        (SELECT tax_id| . 
 
 340           qq|         WHERE chart_id= (SELECT id | . 
 
 342           qq|                          WHERE accno = ?)| . 
 
 343           qq|         AND startdate <= ?| . 
 
 344           qq|         ORDER BY startdate DESC LIMIT 1))|;
 
 345         @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $amount,
 
 346                    conv_date($form->{"datepaid_$i"}), $project_id,
 
 347                    $form->{"AP_paid_account_$i"},
 
 348                    $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}));
 
 349         do_query($form, $dbh, $query, @values);
 
 352       # exchangerate gain/loss
 
 354         $form->round_amount($form->{"paid_$i"} *
 
 355                             ($form->{exchangerate} -
 
 356                              $form->{"exchangerate_$i"}), 2);
 
 360           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id) | .
 
 361           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 362           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?)| .
 
 363           qq|        (SELECT tax_id| . 
 
 365           qq|         WHERE chart_id= (SELECT id | . 
 
 367           qq|                          WHERE accno = ?)| . 
 
 368           qq|         AND startdate <= ?| . 
 
 369           qq|         ORDER BY startdate DESC LIMIT 1))|;
 
 370         @values = ($form->{id}, ($amount > 0) ?
 
 371                    $form->{fxgain_accno} : $form->{fxloss_accno},
 
 372                    $amount, conv_date($form->{"datepaid_$i"}), $project_id,
 
 374                    $form->{fxgain_accno} : $form->{fxloss_accno},
 
 375                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno}, conv_date($form->{"datepaid_$i"}));
 
 376         do_query($form, $dbh, $query, @values);
 
 379       # update exchange rate record
 
 380       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 381         $form->update_exchangerate($dbh, $form->{currency},
 
 382                                    $form->{"datepaid_$i"},
 
 383                                    0, $form->{"exchangerate_$i"});
 
 388   if ($payments_only) {
 
 389     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
 
 390     do_query($form, $dbh, $query,  $form->{invpaid}, $form->{invpaid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
 
 393   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
 
 395   # safety check datev export
 
 396   if ($::instance_conf->get_datev_check_on_ap_transaction) {
 
 397     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
 
 398     $transdate  ||= DateTime->today;
 
 400     my $datev = SL::DATEV->new(
 
 401       exporttype => DATEV_ET_BUCHUNGEN,
 
 402       format     => DATEV_FORMAT_KNE,
 
 410     if ($datev->errors) {
 
 412       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
 
 416   if (!$provided_dbh) {
 
 421   $rc = 1; #  Den return-code auf true setzen, aber nur falls beim commit alles i.O. ist
 
 423   $main::lxdebug->leave_sub();
 
 428 sub delete_transaction {
 
 429   $main::lxdebug->enter_sub();
 
 431   my ($self, $myconfig, $form) = @_;
 
 433   # connect to database
 
 434   my $dbh = $form->dbconnect_noauto($myconfig);
 
 436   # acc_trans entries are deleted by database triggers.
 
 437   my $query = qq|DELETE FROM ap WHERE id = ?|;
 
 438   do_query($form, $dbh, $query, $form->{id});
 
 440   my $rc = $dbh->commit;
 
 443   $main::lxdebug->leave_sub();
 
 448 sub ap_transactions {
 
 449   $main::lxdebug->enter_sub();
 
 451   my ($self, $myconfig, $form) = @_;
 
 453   # connect to database
 
 454   my $dbh = $form->get_standard_dbh($myconfig);
 
 457     qq|SELECT a.id, a.invnumber, a.transdate, a.duedate, a.amount, a.paid, | .
 
 458     qq|  a.ordnumber, v.name, a.invoice, a.netamount, a.datepaid, a.notes, | .
 
 459     qq|  a.globalproject_id, a.storno, a.storno_id, | .
 
 460     qq|  pr.projectnumber AS globalprojectnumber, | .
 
 461     qq|  e.name AS employee, | .
 
 462     qq|  v.vendornumber, v.country, v.ustid, | .
 
 463     qq|  tz.description AS taxzone, | .
 
 464     qq|  pt.description AS payment_terms, | .
 
 465     qq{  ( SELECT ch.accno || ' -- ' || ch.description
 
 467            LEFT JOIN chart ch ON ch.id = at.chart_id
 
 468            WHERE ch.link ~ 'AP[[:>:]]'
 
 469             AND at.trans_id = a.id
 
 473     qq|JOIN vendor v ON (a.vendor_id = v.id) | .
 
 474     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
 
 475     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id) | .
 
 476     qq|LEFT JOIN tax_zones tz ON (tz.id = v.taxzone_id)| .
 
 477     qq|LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)|;
 
 482   if ($form->{vendor_id}) {
 
 483     $where .= " AND a.vendor_id = ?";
 
 484     push(@values, $form->{vendor_id});
 
 485   } elsif ($form->{vendor}) {
 
 486     $where .= " AND v.name ILIKE ?";
 
 487     push(@values, $form->like($form->{vendor}));
 
 489   if ($form->{department}) {
 
 490     # Ã¤hnlich wie commit 0bbfb33b6aa8e38bb6c81d1684ab7d08e5b5c5af abteilung
 
 491     # wird so nicht mehr als zeichenkette zusammengebaut
 
 492     # hätte zu ee9f9f9aa4c3b9d5d20ab10a45c12bcaa6aa78d0 auffallen können ;-) jan
 
 493     #my ($null, $department_id) = split /--/, $form->{department};
 
 494     $where .= " AND a.department_id = ?";
 
 495     push(@values, $form->{department});
 
 497   if ($form->{invnumber}) {
 
 498     $where .= " AND a.invnumber ILIKE ?";
 
 499     push(@values, $form->like($form->{invnumber}));
 
 501   if ($form->{ordnumber}) {
 
 502     $where .= " AND a.ordnumber ILIKE ?";
 
 503     push(@values, $form->like($form->{ordnumber}));
 
 505   if ($form->{notes}) {
 
 506     $where .= " AND lower(a.notes) LIKE ?";
 
 507     push(@values, $form->like($form->{notes}));
 
 509   if ($form->{project_id}) {
 
 511       qq|AND ((a.globalproject_id = ?) OR EXISTS | .
 
 512       qq|  (SELECT * FROM invoice i | .
 
 513       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
 
 515       qq|  (SELECT * FROM acc_trans at | .
 
 516       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
 
 518     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
 
 521   if ($form->{transdatefrom}) {
 
 522     $where .= " AND a.transdate >= ?";
 
 523     push(@values, $form->{transdatefrom});
 
 525   if ($form->{transdateto}) {
 
 526     $where .= " AND a.transdate <= ?";
 
 527     push(@values, $form->{transdateto});
 
 529   if ($form->{open} || $form->{closed}) {
 
 530     unless ($form->{open} && $form->{closed}) {
 
 531       $where .= " AND a.amount <> a.paid" if ($form->{open});
 
 532       $where .= " AND a.amount = a.paid"  if ($form->{closed});
 
 537     substr($where, 0, 4, " WHERE ");
 
 541   my @a = qw(transdate invnumber name);
 
 542   push @a, "employee" if $form->{l_employee};
 
 543   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 544   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
 
 546   if (grep({ $_ eq $form->{sort} } qw(transdate id invnumber ordnumber name netamount tax amount paid datepaid due duedate notes employee transaction_description))) {
 
 547     $sortorder = $form->{sort} . " $sortdir";
 
 550   $query .= " ORDER BY $sortorder";
 
 552   my @result = selectall_hashref_query($form, $dbh, $query, @values);
 
 554   $form->{AP} = [ @result ];
 
 556   $main::lxdebug->leave_sub();
 
 560   $main::lxdebug->enter_sub();
 
 562   my ($self, $myconfig, $form) = @_;
 
 564   # connect to database
 
 565   my $dbh = $form->dbconnect($myconfig);
 
 569     "  (SELECT transdate FROM ap WHERE id = " .
 
 570     "    (SELECT MAX(id) FROM ap) LIMIT 1), " .
 
 572   ($form->{transdate}) = $dbh->selectrow_array($query);
 
 576   $main::lxdebug->leave_sub();
 
 579 sub _delete_payments {
 
 580   $main::lxdebug->enter_sub();
 
 582   my ($self, $form, $dbh) = @_;
 
 584   my @delete_acc_trans_ids;
 
 586   # Delete old payment entries from acc_trans.
 
 588     qq|SELECT acc_trans_id
 
 590        WHERE (trans_id = ?) AND fx_transaction
 
 594        SELECT at.acc_trans_id
 
 596        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 597        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
 
 598   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
 
 601     qq|SELECT at.acc_trans_id
 
 603        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 605          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 606        ORDER BY at.acc_trans_id
 
 608   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 610   if (@delete_acc_trans_ids) {
 
 611     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
 
 612     do_query($form, $dbh, $query);
 
 615   $main::lxdebug->leave_sub();
 
 619   $main::lxdebug->enter_sub();
 
 621   my ($self, $myconfig, $form, $locale) = @_;
 
 623   # connect to database, turn off autocommit
 
 624   my $dbh = $form->dbconnect_noauto($myconfig);
 
 626   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
 628   $old_form = save_form();
 
 630   # Delete all entries in acc_trans from prior payments.
 
 631   if (SL::DB::Default->get->payments_changeable != 0) {
 
 632     $self->_delete_payments($form, $dbh);
 
 635   # Save the new payments the user made before cleaning up $form.
 
 636   my $payments_re = '^datepaid_\d+$|^gldate_\d+$|^acc_trans_id_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^paid_project_id_\d+$|^AP_paid_\d+$|^paidaccounts$';
 
 637   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
 
 639   # Clean up $form so that old content won't tamper the results.
 
 640   %keep_vars = map { $_, 1 } qw(login password id);
 
 641   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
 
 643   # Retrieve the invoice from the database.
 
 644   $form->create_links('AP', $myconfig, 'vendor', $dbh);
 
 646   # Restore the payment options from the user input.
 
 647   map { $form->{$_} = $payments{$_} } keys %payments;
 
 649   # Set up the content of $form in the way that AR::post_transaction() expects.
 
 651   $self->setup_form($form, 1);
 
 653   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
 
 654   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
 655   delete $form->{currency} unless $form->{defaultcurrency};
 
 661        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 663          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 664        ORDER BY at.acc_trans_id
 
 667   ($form->{APselected}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 669   # Post the new payments.
 
 670   $self->post_transaction($myconfig, $form, $dbh, 1);
 
 672   restore_form($old_form);
 
 674   my $rc = $dbh->commit();
 
 677   $main::lxdebug->leave_sub();
 
 683   $main::lxdebug->enter_sub();
 
 685   my ($self, $form, $for_post_payments) = @_;
 
 687   my ($exchangerate, $i, $j, $k, $key, $akey, $ref, $index, $taxamount, $totalamount, $totaltax, $totalwithholding, $withholdingrate,
 
 688       $taxincluded, $tax, $diff);
 
 691   $form->{forex} = $form->{exchangerate};
 
 692   $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
 
 694   foreach $key (keys %{ $form->{AP_links} }) {
 
 695     foreach $ref (@{ $form->{AP_links}{$key} }) {
 
 696       if ($key eq "AP_paid") {
 
 697         $form->{"select$key"} .= "<option value=\"$ref->{accno}\">$ref->{accno}--$ref->{description}</option>\n";
 
 699         $form->{"select$key"} .= "<option value=\"$ref->{accno}--$ref->{tax_id}\">$ref->{accno}--$ref->{description}</option>\n";
 
 703     $form->{$key} = $form->{"select$key"};
 
 708     # if there is a value we have an old entry
 
 709     next unless $form->{acc_trans}{$key};
 
 711     # do not use old entries for payments. They come from the form
 
 712     # even if they are not changeable (then they are in hiddens)
 
 713     next if $for_post_payments && $key eq "AP_paid";
 
 715     for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 717       if ($key eq "AP_paid") {
 
 719         $form->{"AP_paid_$j"}         = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 720         $form->{"acc_trans_id_$j"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 721         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount};
 
 722         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 723         $form->{"gldate_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 724         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 725         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 727         $form->{"exchangerate_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 728         $form->{"forex_$j"}           = $form->{"exchangerate_$i"};
 
 729         $form->{"AP_paid_$j"}         = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 730         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
 
 731         $form->{paidaccounts}++;
 
 737         if (($key eq "AP_tax") || ($key eq "AR_tax")) {
 
 738           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 739           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 741           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
 
 742             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 744             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 745             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
 
 748           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
 
 749           $form->{"tax_$index"}  = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
 
 750           $totaltax             += $form->{"tax_$index"};
 
 754           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 756           if ($akey eq 'amount') {
 
 758             $form->{"${akey}_$i"} *= -1;
 
 759             $totalamount          += $form->{"${akey}_$i"};
 
 760             $form->{taxrate}       = $form->{acc_trans}{$key}->[$i - 1]->{rate};
 
 762             $form->{"projectnumber_$k"}    = "$form->{acc_trans}{$key}->[$i-1]->{projectnumber}";
 
 763             $form->{"oldprojectnumber_$k"} = $form->{"projectnumber_$k"};
 
 764             $form->{"project_id_$k"}       = "$form->{acc_trans}{$key}->[$i-1]->{project_id}";
 
 767           $form->{"${key}_$k"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 769           my $q_description    = quotemeta($form->{acc_trans}{$key}->[$i-1]->{description});
 
 770           $form->{"select${key}"} =~
 
 772                 ($form->{acc_trans}{$key}->[$i-1]->{accno}--[^\"]*)
 
 774               $form->{acc_trans}{$key}->[$i-1]->{accno}
 
 778           $form->{"${key}_$k"} = $1;
 
 781             $form->{APselected} = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 783           } elsif ($akey eq 'amount') {
 
 784             $form->{"${key}_$k"}   = $form->{acc_trans}{$key}->[$i-1]->{accno} . "--" . $form->{acc_trans}{$key}->[$i-1]->{id};
 
 785             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
 
 792   $form->{taxincluded}  = $taxincluded if ($form->{id});
 
 793   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
 
 795   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
 
 796     # add tax to amounts and invtotal
 
 797     for $i (1 .. $form->{rowcount}) {
 
 798       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
 
 799       $tax                  = $form->round_amount($taxamount, 2);
 
 800       $diff                += ($taxamount - $tax);
 
 801       $form->{"amount_$i"} += $form->{"tax_$i"};
 
 804     $form->{amount_1} += $form->round_amount($diff, 2);
 
 807   $taxamount        = $form->round_amount($taxamount, 2);
 
 808   $form->{invtotal} = $totalamount + $totaltax;
 
 810   $main::lxdebug->leave_sub();
 
 814   $main::lxdebug->enter_sub();
 
 816   my ($self, $form, $myconfig, $id) = @_;
 
 818   my ($query, $new_id, $storno_row, $acc_trans_rows);
 
 819   my $dbh = $form->get_standard_dbh($myconfig);
 
 821   $query = qq|SELECT nextval('glid')|;
 
 822   ($new_id) = selectrow_query($form, $dbh, $query);
 
 824   $query = qq|SELECT * FROM ap WHERE id = ?|;
 
 825   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
 
 827   $storno_row->{id}         = $new_id;
 
 828   $storno_row->{storno_id}  = $id;
 
 829   $storno_row->{storno}     = 't';
 
 830   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
 
 831   $storno_row->{amount}    *= -1;
 
 832   $storno_row->{netamount} *= -1;
 
 833   $storno_row->{paid}       = $storno_row->{amount};
 
 835   delete @$storno_row{qw(itime mtime)};
 
 837   $query = sprintf 'INSERT INTO ap (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
 
 838   do_query($form, $dbh, $query, (values %$storno_row));
 
 840   $query = qq|UPDATE ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 841   do_query($form, $dbh, $query, $id);
 
 843   # now copy acc_trans entries
 
 844   $query = qq|SELECT a.*, c.link FROM acc_trans a LEFT JOIN chart c ON a.chart_id = c.id WHERE a.trans_id = ? ORDER BY a.acc_trans_id|;
 
 845   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
 
 847   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
 
 848   while ($rowref->[-1]{link} =~ /paid/) {
 
 849     splice(@$rowref, -2);
 
 852   for my $row (@$rowref) {
 
 853     delete @$row{qw(itime mtime link acc_trans_id)};
 
 854     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
 
 855     $row->{trans_id}   = $new_id;
 
 856     $row->{amount}    *= -1;
 
 857     do_query($form, $dbh, $query, (values %$row));
 
 860   map { IO->set_datepaid(table => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);
 
 864   $main::lxdebug->leave_sub();