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);
 
  42 use SL::Util qw(trim);
 
  47 sub post_transaction {
 
  48   $main::lxdebug->enter_sub();
 
  50   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
 
  51   my $rc = 0; # return code auf false setzen
 
  53   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
 
  55   my ($null, $taxrate, $amount);
 
  58   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
  59   $form->{taxincluded} = 0 unless $form->{taxincluded};
 
  61   ($null, $form->{department_id}) = split(/--/, $form->{department});
 
  63   if ($form->{currency} eq $form->{defaultcurrency}) {
 
  64     $form->{exchangerate} = 1;
 
  66     $exchangerate         = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
  67     $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
 
  70   for my $i (1 .. $form->{rowcount}) {
 
  71     $form->{AP_amounts}{"amount_$i"} =
 
  72       (split(/--/, $form->{"AP_amount_$i"}))[0];
 
  75   ($form->{AP_amounts}{payables}) = split(/--/, $form->{APselected});
 
  76   ($form->{AP_payables})          = split(/--/, $form->{APselected});
 
  78   # calculate the totals while calculating and reformatting the $amount_$i and $tax_$i
 
  79   ($form->{netamount},$form->{total_tax},$form->{invtotal}) = $form->calculate_arap('buy',$form->{taxincluded}, $form->{exchangerate});
 
  81   # adjust paidaccounts if there is no date in the last row
 
  82   $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
 
  87   for my $i (1 .. $form->{paidaccounts}) {
 
  89       $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
 
  92     $form->{invpaid} += $form->{"paid_$i"};
 
  93     $form->{datepaid} = $form->{"datepaid_$i"};
 
  98     $form->round_amount($form->{invpaid} * $form->{exchangerate}, 2);
 
 100   # # store invoice total, this goes into ap table
 
 101   # $form->{invtotal} = $form->{netamount} + $form->{total_tax};
 
 103   # amount for total AP
 
 104   $form->{payables} = $form->{invtotal};
 
 106   # update exchangerate
 
 107   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 108     $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, 0,
 
 109                                $form->{exchangerate});
 
 112   my ($query, $sth, @values);
 
 114   if (!$payments_only) {
 
 115     # if we have an id delete old records
 
 118       # delete detail records
 
 119       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
 
 120       do_query($form, $dbh, $query, $form->{id});
 
 124       ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
 
 127         qq|INSERT INTO ap (id, invnumber, employee_id,currency_id, taxzone_id) | .
 
 128         qq|VALUES (?, ?, (SELECT e.id FROM employee e WHERE e.login = ?),
 
 129                       (SELECT id FROM currencies WHERE name = ?), (SELECT taxzone_id FROM vendor WHERE id = ?) )|;
 
 130       do_query($form, $dbh, $query, $form->{id}, $form->{invnumber}, $::myconfig{login}, $form->{currency}, $form->{vendor_id});
 
 134     $query = qq|UPDATE ap SET invnumber = ?,
 
 135                 transdate = ?, ordnumber = ?, vendor_id = ?, taxincluded = ?,
 
 136                 amount = ?, duedate = ?, paid = ?, netamount = ?,
 
 137                 currency_id = (SELECT id FROM currencies WHERE name = ?), notes = ?, department_id = ?, storno = ?, storno_id = ?,
 
 138                 globalproject_id = ?, direct_debit = ?
 
 140     @values = ($form->{invnumber}, conv_date($form->{transdate}),
 
 141                   $form->{ordnumber}, conv_i($form->{vendor_id}),
 
 142                   $form->{taxincluded} ? 't' : 'f', $form->{invtotal},
 
 143                   conv_date($form->{duedate}), $form->{invpaid},
 
 145                   $form->{currency}, $form->{notes},
 
 146                   conv_i($form->{department_id}), $form->{storno},
 
 147                   $form->{storno_id}, conv_i($form->{globalproject_id}),
 
 148                   $form->{direct_debit} ? 't' : 'f',
 
 150     do_query($form, $dbh, $query, @values);
 
 152     $form->new_lastmtime('ap');
 
 154     # add individual transactions
 
 155     for my $i (1 .. $form->{rowcount}) {
 
 156       if ($form->{"amount_$i"} != 0) {
 
 158         $project_id = conv_i($form->{"project_id_$i"});
 
 160         # insert detail records in acc_trans
 
 162           qq|INSERT INTO acc_trans | .
 
 163           qq|  (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)| .
 
 164           qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
 
 165           qq|  ?, ?, ?, ?, ?,| .
 
 166           qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 167         @values = ($form->{id}, $form->{AP_amounts}{"amount_$i"},
 
 168                    $form->{"amount_$i"}, conv_date($form->{transdate}),
 
 169                    $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
 
 170                    $form->{AP_amounts}{"amount_$i"});
 
 171         do_query($form, $dbh, $query, @values);
 
 173         if ($form->{"tax_$i"} != 0) {
 
 174           # insert detail records in acc_trans
 
 176             qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, | .
 
 177             qq|  project_id, taxkey, tax_id, chart_link) | .
 
 178             qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
 
 179             qq|  ?, ?, ?, ?, ?,| .
 
 180             qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 181           @values = ($form->{id}, $form->{AP_amounts}{"tax_$i"},
 
 182                      $form->{"tax_$i"}, conv_date($form->{transdate}),
 
 183                      $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
 
 184                      $form->{AP_amounts}{"tax_$i"});
 
 185           do_query($form, $dbh, $query, @values);
 
 193       qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) | .
 
 194       qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, | .
 
 195       qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
 
 196       qq|        (SELECT tax_id| .
 
 198       qq|         WHERE chart_id= (SELECT id | .
 
 200       qq|                          WHERE accno = ?)| .
 
 201       qq|         AND startdate <= ?| .
 
 202       qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 203       qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 204     @values = ($form->{id}, $form->{AP_amounts}{payables}, $form->{payables},
 
 205                conv_date($form->{transdate}), $form->{AP_amounts}{payables}, $form->{AP_amounts}{payables}, conv_date($form->{transdate}),
 
 206                $form->{AP_amounts}{payables});
 
 207     do_query($form, $dbh, $query, @values);
 
 210   # if there is no amount but a payment record a payable
 
 211   if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 212     $form->{payables} = $form->{invpaid};
 
 215   # add paid transactions
 
 216   for my $i (1 .. $form->{paidaccounts}) {
 
 218     if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
 
 222     if ($form->{"paid_$i"} != 0) {
 
 223       my $project_id = conv_i($form->{"paid_project_id_$i"});
 
 226       if ($form->{currency} eq $form->{defaultcurrency}) {
 
 227         $form->{"exchangerate_$i"} = 1;
 
 229         $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 230         $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
 232       $form->{"AP_paid_$i"} =~ s/\"//g;
 
 236       ($form->{"AP_paid_account_$i"}) = split(/--/, $form->{"AP_paid_$i"});
 
 237       $form->{"datepaid_$i"} = $form->{transdate}
 
 238         unless ($form->{"datepaid_$i"});
 
 240       # if there is no amount and invtotal is zero there is no exchangerate
 
 241       if ($form->{amount} == 0 && $form->{invtotal} == 0) {
 
 242         $form->{exchangerate} = $form->{"exchangerate_$i"};
 
 246         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} * -1,
 
 248       if ($form->{payables}) {
 
 250           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link) | .
 
 251           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, | .
 
 252           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
 
 253           qq|        (SELECT tax_id| .
 
 255           qq|         WHERE chart_id= (SELECT id | .
 
 257           qq|                          WHERE accno = ?)| .
 
 258           qq|         AND startdate <= ?| .
 
 259           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 260           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 261         @values = ($form->{id}, $form->{AP_payables}, $amount,
 
 262                    conv_date($form->{"datepaid_$i"}), $project_id,
 
 263                    $form->{AP_payables}, $form->{AP_payables}, conv_date($form->{"datepaid_$i"}),
 
 264                    $form->{AP_payables});
 
 265         do_query($form, $dbh, $query, @values);
 
 267       $form->{payables} = $amount;
 
 270       my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
 
 272         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, taxkey, tax_id, chart_link) | .
 
 273         qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, | .
 
 274         qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 275         qq|        (SELECT tax_id| .
 
 277         qq|         WHERE chart_id= (SELECT id | .
 
 279         qq|                          WHERE accno = ?)| .
 
 280         qq|         AND startdate <= ?| .
 
 281         qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 282         qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 283       @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $form->{"paid_$i"},
 
 284                  conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"},
 
 285                  $form->{"memo_$i"}, $project_id, $form->{"AP_paid_account_$i"},
 
 286                  $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
 
 287                  $form->{"AP_paid_account_$i"});
 
 288       do_query($form, $dbh, $query, @values);
 
 290       # add exchange rate difference
 
 292         $form->round_amount($form->{"paid_$i"} *
 
 293                             ($form->{"exchangerate_$i"} - 1), 2);
 
 296           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 297           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 298           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
 
 299           qq|        (SELECT tax_id| .
 
 301           qq|         WHERE chart_id= (SELECT id | .
 
 303           qq|                          WHERE accno = ?)| .
 
 304           qq|         AND startdate <= ?| .
 
 305           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 306           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 307         @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $amount,
 
 308                    conv_date($form->{"datepaid_$i"}), $project_id,
 
 309                    $form->{"AP_paid_account_$i"},
 
 310                    $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
 
 311                    $form->{"AP_paid_account_$i"});
 
 312         do_query($form, $dbh, $query, @values);
 
 315       # exchangerate gain/loss
 
 317         $form->round_amount($form->{"paid_$i"} *
 
 318                             ($form->{exchangerate} -
 
 319                              $form->{"exchangerate_$i"}), 2);
 
 323           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 324           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 325           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
 
 326           qq|        (SELECT tax_id| .
 
 328           qq|         WHERE chart_id= (SELECT id | .
 
 330           qq|                          WHERE accno = ?)| .
 
 331           qq|         AND startdate <= ?| .
 
 332           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 333           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 334         @values = ($form->{id},
 
 335                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 336                    $amount, conv_date($form->{"datepaid_$i"}), $project_id,
 
 337                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 338                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno}, conv_date($form->{"datepaid_$i"}),
 
 339                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno});
 
 340         do_query($form, $dbh, $query, @values);
 
 343       # update exchange rate record
 
 344       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 345         $form->update_exchangerate($dbh, $form->{currency},
 
 346                                    $form->{"datepaid_$i"},
 
 347                                    0, $form->{"exchangerate_$i"});
 
 352   if ($payments_only) {
 
 353     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
 
 354     do_query($form, $dbh, $query,  $form->{invpaid}, $form->{invpaid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
 
 355     $form->new_lastmtime('ap');
 
 358   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
 
 360   # safety check datev export
 
 361   if ($::instance_conf->get_datev_check_on_ap_transaction) {
 
 362     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
 
 363     $transdate  ||= DateTime->today;
 
 365     my $datev = SL::DATEV->new(
 
 366       exporttype => DATEV_ET_BUCHUNGEN,
 
 367       format     => DATEV_FORMAT_KNE,
 
 369       trans_id   => $form->{id},
 
 374     if ($datev->errors) {
 
 376       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
 
 380   if (!$provided_dbh) {
 
 385   $rc = 1; #  Den return-code auf true setzen, aber nur falls beim commit alles i.O. ist
 
 387   $main::lxdebug->leave_sub();
 
 392 sub delete_transaction {
 
 393   $main::lxdebug->enter_sub();
 
 395   my ($self, $myconfig, $form) = @_;
 
 397   # connect to database
 
 398   my $dbh = $form->dbconnect_noauto($myconfig);
 
 400   # acc_trans entries are deleted by database triggers.
 
 401   my $query = qq|DELETE FROM ap WHERE id = ?|;
 
 402   do_query($form, $dbh, $query, $form->{id});
 
 404   my $rc = $dbh->commit;
 
 407   $main::lxdebug->leave_sub();
 
 412 sub ap_transactions {
 
 413   $main::lxdebug->enter_sub();
 
 415   my ($self, $myconfig, $form) = @_;
 
 417   # connect to database
 
 418   my $dbh = $form->get_standard_dbh($myconfig);
 
 421     qq|SELECT a.id, a.invnumber, a.transdate, a.duedate, a.amount, a.paid, | .
 
 422     qq|  a.ordnumber, v.name, a.invoice, a.netamount, a.datepaid, a.notes, | .
 
 423     qq|  a.globalproject_id, a.storno, a.storno_id, a.direct_debit, | .
 
 424     qq|  pr.projectnumber AS globalprojectnumber, | .
 
 425     qq|  e.name AS employee, | .
 
 426     qq|  v.vendornumber, v.country, v.ustid, | .
 
 427     qq|  tz.description AS taxzone, | .
 
 428     qq|  pt.description AS payment_terms, | .
 
 429     qq{  ( SELECT ch.accno || ' -- ' || ch.description
 
 431            LEFT JOIN chart ch ON ch.id = at.chart_id
 
 432            WHERE ch.link ~ 'AP[[:>:]]'
 
 433             AND at.trans_id = a.id
 
 437     qq|JOIN vendor v ON (a.vendor_id = v.id) | .
 
 438     qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
 
 439     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
 
 440     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id) | .
 
 441     qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
 
 442     qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)|;
 
 446   unless ( $::auth->assert('show_ap_transactions', 1) ) {
 
 447     $where .= " AND NOT invoice = 'f' ";  # remove ap transactions from Sales -> Reports -> Invoices
 
 452   if ($form->{vendor_id}) {
 
 453     $where .= " AND a.vendor_id = ?";
 
 454     push(@values, $form->{vendor_id});
 
 455   } elsif ($form->{vendor}) {
 
 456     $where .= " AND v.name ILIKE ?";
 
 457     push(@values, like($form->{vendor}));
 
 459   if ($form->{"cp_name"}) {
 
 460     $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
 
 461     push(@values, (like($form->{"cp_name"}))x2);
 
 463   if ($form->{department}) {
 
 464     # Ã¤hnlich wie commit 0bbfb33b6aa8e38bb6c81d1684ab7d08e5b5c5af abteilung
 
 465     # wird so nicht mehr als zeichenkette zusammengebaut
 
 466     # hätte zu ee9f9f9aa4c3b9d5d20ab10a45c12bcaa6aa78d0 auffallen können ;-) jan
 
 467     #my ($null, $department_id) = split /--/, $form->{department};
 
 468     $where .= " AND a.department_id = ?";
 
 469     push(@values, $form->{department});
 
 471   if ($form->{invnumber}) {
 
 472     $where .= " AND a.invnumber ILIKE ?";
 
 473     push(@values, like($form->{invnumber}));
 
 475   if ($form->{ordnumber}) {
 
 476     $where .= " AND a.ordnumber ILIKE ?";
 
 477     push(@values, like($form->{ordnumber}));
 
 479   if ($form->{notes}) {
 
 480     $where .= " AND lower(a.notes) LIKE ?";
 
 481     push(@values, like($form->{notes}));
 
 483   if ($form->{project_id}) {
 
 485       qq| AND ((a.globalproject_id = ?) OR EXISTS | .
 
 486       qq|  (SELECT * FROM invoice i | .
 
 487       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
 
 489       qq|  (SELECT * FROM acc_trans at | .
 
 490       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
 
 492     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
 
 495   if ($form->{transdatefrom}) {
 
 496     $where .= " AND a.transdate >= ?";
 
 497     push(@values, trim($form->{transdatefrom}));
 
 499   if ($form->{transdateto}) {
 
 500     $where .= " AND a.transdate <= ?";
 
 501     push(@values, trim($form->{transdateto}));
 
 503   if ($form->{open} || $form->{closed}) {
 
 504     unless ($form->{open} && $form->{closed}) {
 
 505       $where .= " AND a.amount <> a.paid" if ($form->{open});
 
 506       $where .= " AND a.amount = a.paid"  if ($form->{closed});
 
 510   if ($form->{parts_partnumber}) {
 
 513         SELECT invoice.trans_id
 
 515         LEFT JOIN parts ON (invoice.parts_id = parts.id)
 
 516         WHERE (invoice.trans_id = a.id)
 
 517           AND (parts.partnumber ILIKE ?)
 
 521     push @values, like($form->{parts_partnumber});
 
 524   if ($form->{parts_description}) {
 
 527         SELECT invoice.trans_id
 
 529         WHERE (invoice.trans_id = a.id)
 
 530           AND (invoice.description ILIKE ?)
 
 534     push @values, like($form->{parts_description});
 
 538     substr($where, 0, 4, " WHERE ");
 
 542   my @a = qw(transdate invnumber name);
 
 543   push @a, "employee" if $form->{l_employee};
 
 544   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 545   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
 
 547   if (grep({ $_ eq $form->{sort} } qw(transdate id invnumber ordnumber name netamount tax amount paid datepaid due duedate notes employee transaction_description direct_debit))) {
 
 548     $sortorder = $form->{sort} . " $sortdir";
 
 551   $query .= " ORDER BY $sortorder";
 
 553   my @result = selectall_hashref_query($form, $dbh, $query, @values);
 
 555   $form->{AP} = [ @result ];
 
 557   $main::lxdebug->leave_sub();
 
 561   $main::lxdebug->enter_sub();
 
 563   my ($self, $myconfig, $form) = @_;
 
 565   # connect to database
 
 566   my $dbh = $form->dbconnect($myconfig);
 
 570     "  (SELECT transdate FROM ap WHERE id = " .
 
 571     "    (SELECT MAX(id) FROM ap) LIMIT 1), " .
 
 573   ($form->{transdate}) = $dbh->selectrow_array($query);
 
 577   $main::lxdebug->leave_sub();
 
 580 sub _delete_payments {
 
 581   $main::lxdebug->enter_sub();
 
 583   my ($self, $form, $dbh) = @_;
 
 585   my @delete_acc_trans_ids;
 
 587   # Delete old payment entries from acc_trans.
 
 589     qq|SELECT acc_trans_id
 
 591        WHERE (trans_id = ?) AND fx_transaction
 
 595        SELECT at.acc_trans_id
 
 597        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 598        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
 
 599   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
 
 602     qq|SELECT at.acc_trans_id
 
 604        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 606          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 607        ORDER BY at.acc_trans_id
 
 609   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 611   if (@delete_acc_trans_ids) {
 
 612     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
 
 613     do_query($form, $dbh, $query);
 
 616   $main::lxdebug->leave_sub();
 
 620   $main::lxdebug->enter_sub();
 
 622   my ($self, $myconfig, $form, $locale) = @_;
 
 624   # connect to database, turn off autocommit
 
 625   my $dbh = $form->dbconnect_noauto($myconfig);
 
 627   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
 629   $old_form = save_form();
 
 631   # Delete all entries in acc_trans from prior payments.
 
 632   if (SL::DB::Default->get->payments_changeable != 0) {
 
 633     $self->_delete_payments($form, $dbh);
 
 636   # Save the new payments the user made before cleaning up $form.
 
 637   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$';
 
 638   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
 
 640   # Clean up $form so that old content won't tamper the results.
 
 641   %keep_vars = map { $_, 1 } qw(login password id);
 
 642   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
 
 644   # Retrieve the invoice from the database.
 
 645   $form->create_links('AP', $myconfig, 'vendor', $dbh);
 
 647   # Restore the payment options from the user input.
 
 648   map { $form->{$_} = $payments{$_} } keys %payments;
 
 650   # Set up the content of $form in the way that AR::post_transaction() expects.
 
 652   $self->setup_form($form, 1);
 
 654   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
 
 655   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
 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,
 
 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->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} * -1 / $exchangerate, 2);
 
 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->{paidaccounts} = 1            if not defined $form->{paidaccounts};
 
 794   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
 
 795     # add tax to amounts and invtotal
 
 796     for $i (1 .. $form->{rowcount}) {
 
 797       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
 
 798       $tax                  = $form->round_amount($taxamount, 2);
 
 799       $diff                += ($taxamount - $tax);
 
 800       $form->{"amount_$i"} += $form->{"tax_$i"};
 
 803     $form->{amount_1} += $form->round_amount($diff, 2);
 
 806   $taxamount        = $form->round_amount($taxamount, 2);
 
 807   $form->{invtotal} = $totalamount + $totaltax;
 
 809   $main::lxdebug->leave_sub();
 
 813   $main::lxdebug->enter_sub();
 
 815   my ($self, $form, $myconfig, $id) = @_;
 
 817   my ($query, $new_id, $storno_row, $acc_trans_rows);
 
 818   my $dbh = $form->get_standard_dbh($myconfig);
 
 820   $query = qq|SELECT nextval('glid')|;
 
 821   ($new_id) = selectrow_query($form, $dbh, $query);
 
 823   $query = qq|SELECT * FROM ap WHERE id = ?|;
 
 824   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
 
 826   $storno_row->{id}         = $new_id;
 
 827   $storno_row->{storno_id}  = $id;
 
 828   $storno_row->{storno}     = 't';
 
 829   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
 
 830   $storno_row->{amount}    *= -1;
 
 831   $storno_row->{netamount} *= -1;
 
 832   $storno_row->{paid}       = $storno_row->{amount};
 
 834   delete @$storno_row{qw(itime mtime)};
 
 836   $query = sprintf 'INSERT INTO ap (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
 
 837   do_query($form, $dbh, $query, (values %$storno_row));
 
 839   $query = qq|UPDATE ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 840   do_query($form, $dbh, $query, $id);
 
 842   $form->new_lastmtime('ap') if $id == $form->{id};
 
 844   # now copy acc_trans entries
 
 845   $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|;
 
 846   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
 
 848   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
 
 849   while ($rowref->[-1]{link} =~ /paid/) {
 
 850     splice(@$rowref, -2);
 
 853   for my $row (@$rowref) {
 
 854     delete @$row{qw(itime mtime link acc_trans_id)};
 
 855     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
 
 856     $row->{trans_id}   = $new_id;
 
 857     $row->{amount}    *= -1;
 
 858     do_query($form, $dbh, $query, (values %$row));
 
 861   map { IO->set_datepaid(table => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);
 
 865   $main::lxdebug->leave_sub();