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);
 
 322         # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
 
 323         if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
 
 324           $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
 
 326         if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
 
 327           $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
 
 329         die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
 
 330         die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
 
 332           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
 
 333           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
 
 334           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
 
 335           qq|        (SELECT tax_id| .
 
 337           qq|         WHERE chart_id= (SELECT id | .
 
 339           qq|                          WHERE accno = ?)| .
 
 340           qq|         AND startdate <= ?| .
 
 341           qq|         ORDER BY startdate DESC LIMIT 1),| .
 
 342           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
 
 343         @values = ($form->{id},
 
 344                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 345                    $amount, conv_date($form->{"datepaid_$i"}), $project_id,
 
 346                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
 
 347                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno}, conv_date($form->{"datepaid_$i"}),
 
 348                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno});
 
 349         do_query($form, $dbh, $query, @values);
 
 352       # update exchange rate record
 
 353       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
 
 354         $form->update_exchangerate($dbh, $form->{currency},
 
 355                                    $form->{"datepaid_$i"},
 
 356                                    0, $form->{"exchangerate_$i"});
 
 361   if ($payments_only) {
 
 362     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
 
 363     do_query($form, $dbh, $query,  $form->{invpaid}, $form->{invpaid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
 
 364     $form->new_lastmtime('ap');
 
 367   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
 
 369   # safety check datev export
 
 370   if ($::instance_conf->get_datev_check_on_ap_transaction) {
 
 371     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
 
 372     $transdate  ||= DateTime->today;
 
 374     my $datev = SL::DATEV->new(
 
 375       exporttype => DATEV_ET_BUCHUNGEN,
 
 376       format     => DATEV_FORMAT_KNE,
 
 378       trans_id   => $form->{id},
 
 383     if ($datev->errors) {
 
 385       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
 
 389   if (!$provided_dbh) {
 
 394   $rc = 1; #  Den return-code auf true setzen, aber nur falls beim commit alles i.O. ist
 
 396   $main::lxdebug->leave_sub();
 
 401 sub delete_transaction {
 
 402   $main::lxdebug->enter_sub();
 
 404   my ($self, $myconfig, $form) = @_;
 
 406   # connect to database
 
 407   my $dbh = $form->dbconnect_noauto($myconfig);
 
 409   # acc_trans entries are deleted by database triggers.
 
 410   my $query = qq|DELETE FROM ap WHERE id = ?|;
 
 411   do_query($form, $dbh, $query, $form->{id});
 
 413   my $rc = $dbh->commit;
 
 416   $main::lxdebug->leave_sub();
 
 421 sub ap_transactions {
 
 422   $main::lxdebug->enter_sub();
 
 424   my ($self, $myconfig, $form) = @_;
 
 426   # connect to database
 
 427   my $dbh = $form->get_standard_dbh($myconfig);
 
 430     qq|SELECT a.id, a.invnumber, a.transdate, a.duedate, a.amount, a.paid, | .
 
 431     qq|  a.ordnumber, v.name, a.invoice, a.netamount, a.datepaid, a.notes, | .
 
 432     qq|  a.globalproject_id, a.storno, a.storno_id, a.direct_debit, | .
 
 433     qq|  pr.projectnumber AS globalprojectnumber, | .
 
 434     qq|  e.name AS employee, | .
 
 435     qq|  v.vendornumber, v.country, v.ustid, | .
 
 436     qq|  tz.description AS taxzone, | .
 
 437     qq|  pt.description AS payment_terms, | .
 
 438     qq{  ( SELECT ch.accno || ' -- ' || ch.description
 
 440            LEFT JOIN chart ch ON ch.id = at.chart_id
 
 441            WHERE ch.link ~ 'AP[[:>:]]'
 
 442             AND at.trans_id = a.id
 
 446     qq|JOIN vendor v ON (a.vendor_id = v.id) | .
 
 447     qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
 
 448     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
 
 449     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id) | .
 
 450     qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
 
 451     qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)|;
 
 455   unless ( $::auth->assert('show_ap_transactions', 1) ) {
 
 456     $where .= " AND NOT invoice = 'f' ";  # remove ap transactions from Sales -> Reports -> Invoices
 
 461   if ($form->{vendor_id}) {
 
 462     $where .= " AND a.vendor_id = ?";
 
 463     push(@values, $form->{vendor_id});
 
 464   } elsif ($form->{vendor}) {
 
 465     $where .= " AND v.name ILIKE ?";
 
 466     push(@values, like($form->{vendor}));
 
 468   if ($form->{"cp_name"}) {
 
 469     $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
 
 470     push(@values, (like($form->{"cp_name"}))x2);
 
 472   if ($form->{department}) {
 
 473     # ähnlich wie commit 0bbfb33b6aa8e38bb6c81d1684ab7d08e5b5c5af abteilung
 
 474     # wird so nicht mehr als zeichenkette zusammengebaut
 
 475     # hätte zu ee9f9f9aa4c3b9d5d20ab10a45c12bcaa6aa78d0 auffallen können ;-) jan
 
 476     #my ($null, $department_id) = split /--/, $form->{department};
 
 477     $where .= " AND a.department_id = ?";
 
 478     push(@values, $form->{department});
 
 480   if ($form->{invnumber}) {
 
 481     $where .= " AND a.invnumber ILIKE ?";
 
 482     push(@values, like($form->{invnumber}));
 
 484   if ($form->{ordnumber}) {
 
 485     $where .= " AND a.ordnumber ILIKE ?";
 
 486     push(@values, like($form->{ordnumber}));
 
 488   if ($form->{notes}) {
 
 489     $where .= " AND lower(a.notes) LIKE ?";
 
 490     push(@values, like($form->{notes}));
 
 492   if ($form->{project_id}) {
 
 494       qq| AND ((a.globalproject_id = ?) OR EXISTS | .
 
 495       qq|  (SELECT * FROM invoice i | .
 
 496       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
 
 498       qq|  (SELECT * FROM acc_trans at | .
 
 499       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
 
 501     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
 
 504   if ($form->{transdatefrom}) {
 
 505     $where .= " AND a.transdate >= ?";
 
 506     push(@values, trim($form->{transdatefrom}));
 
 508   if ($form->{transdateto}) {
 
 509     $where .= " AND a.transdate <= ?";
 
 510     push(@values, trim($form->{transdateto}));
 
 512   if ($form->{open} || $form->{closed}) {
 
 513     unless ($form->{open} && $form->{closed}) {
 
 514       $where .= " AND a.amount <> a.paid" if ($form->{open});
 
 515       $where .= " AND a.amount = a.paid"  if ($form->{closed});
 
 519   if ($form->{parts_partnumber}) {
 
 522         SELECT invoice.trans_id
 
 524         LEFT JOIN parts ON (invoice.parts_id = parts.id)
 
 525         WHERE (invoice.trans_id = a.id)
 
 526           AND (parts.partnumber ILIKE ?)
 
 530     push @values, like($form->{parts_partnumber});
 
 533   if ($form->{parts_description}) {
 
 536         SELECT invoice.trans_id
 
 538         WHERE (invoice.trans_id = a.id)
 
 539           AND (invoice.description ILIKE ?)
 
 543     push @values, like($form->{parts_description});
 
 547     substr($where, 0, 4, " WHERE ");
 
 551   my @a = qw(transdate invnumber name);
 
 552   push @a, "employee" if $form->{l_employee};
 
 553   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
 554   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
 
 556   if (grep({ $_ eq $form->{sort} } qw(transdate id invnumber ordnumber name netamount tax amount paid datepaid due duedate notes employee transaction_description direct_debit))) {
 
 557     $sortorder = $form->{sort} . " $sortdir";
 
 560   $query .= " ORDER BY $sortorder";
 
 562   my @result = selectall_hashref_query($form, $dbh, $query, @values);
 
 564   $form->{AP} = [ @result ];
 
 566   $main::lxdebug->leave_sub();
 
 570   $main::lxdebug->enter_sub();
 
 572   my ($self, $myconfig, $form) = @_;
 
 574   # connect to database
 
 575   my $dbh = $form->dbconnect($myconfig);
 
 579     "  (SELECT transdate FROM ap WHERE id = " .
 
 580     "    (SELECT MAX(id) FROM ap) LIMIT 1), " .
 
 582   ($form->{transdate}) = $dbh->selectrow_array($query);
 
 586   $main::lxdebug->leave_sub();
 
 589 sub _delete_payments {
 
 590   $main::lxdebug->enter_sub();
 
 592   my ($self, $form, $dbh) = @_;
 
 594   my @delete_acc_trans_ids;
 
 596   # Delete old payment entries from acc_trans.
 
 598     qq|SELECT acc_trans_id
 
 600        WHERE (trans_id = ?) AND fx_transaction
 
 604        SELECT at.acc_trans_id
 
 606        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 607        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
 
 608   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
 
 611     qq|SELECT at.acc_trans_id
 
 613        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 615          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 616        ORDER BY at.acc_trans_id
 
 618   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 620   if (@delete_acc_trans_ids) {
 
 621     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
 
 622     do_query($form, $dbh, $query);
 
 625   $main::lxdebug->leave_sub();
 
 629   $main::lxdebug->enter_sub();
 
 631   my ($self, $myconfig, $form, $locale) = @_;
 
 633   # connect to database, turn off autocommit
 
 634   my $dbh = $form->dbconnect_noauto($myconfig);
 
 636   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
 638   $old_form = save_form();
 
 640   # Delete all entries in acc_trans from prior payments.
 
 641   if (SL::DB::Default->get->payments_changeable != 0) {
 
 642     $self->_delete_payments($form, $dbh);
 
 645   # Save the new payments the user made before cleaning up $form.
 
 646   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$';
 
 647   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
 
 649   # Clean up $form so that old content won't tamper the results.
 
 650   %keep_vars = map { $_, 1 } qw(login password id);
 
 651   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
 
 653   # Retrieve the invoice from the database.
 
 654   $form->create_links('AP', $myconfig, 'vendor', $dbh);
 
 656   # Restore the payment options from the user input.
 
 657   map { $form->{$_} = $payments{$_} } keys %payments;
 
 659   # Set up the content of $form in the way that AR::post_transaction() expects.
 
 661   $self->setup_form($form, 1);
 
 663   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
 
 664   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
 670        LEFT JOIN chart c ON (at.chart_id = c.id)
 
 672          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
 673        ORDER BY at.acc_trans_id
 
 676   ($form->{APselected}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
 
 678   # Post the new payments.
 
 679   $self->post_transaction($myconfig, $form, $dbh, 1);
 
 681   restore_form($old_form);
 
 683   my $rc = $dbh->commit();
 
 686   $main::lxdebug->leave_sub();
 
 692   $main::lxdebug->enter_sub();
 
 694   my ($self, $form, $for_post_payments) = @_;
 
 696   my ($exchangerate, $i, $j, $k, $key, $akey, $ref, $index, $taxamount, $totalamount, $totaltax, $totalwithholding, $withholdingrate,
 
 700   $form->{forex} = $form->{exchangerate};
 
 701   $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
 
 703   foreach $key (keys %{ $form->{AP_links} }) {
 
 704     foreach $ref (@{ $form->{AP_links}{$key} }) {
 
 705       if ($key eq "AP_paid") {
 
 706         $form->{"select$key"} .= "<option value=\"$ref->{accno}\">$ref->{accno}--$ref->{description}</option>\n";
 
 708         $form->{"select$key"} .= "<option value=\"$ref->{accno}--$ref->{tax_id}\">$ref->{accno}--$ref->{description}</option>\n";
 
 712     $form->{$key} = $form->{"select$key"};
 
 717     # if there is a value we have an old entry
 
 718     next unless $form->{acc_trans}{$key};
 
 720     # do not use old entries for payments. They come from the form
 
 721     # even if they are not changeable (then they are in hiddens)
 
 722     next if $for_post_payments && $key eq "AP_paid";
 
 724     for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 726       if ($key eq "AP_paid") {
 
 728         $form->{"AP_paid_$j"}         = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 729         $form->{"acc_trans_id_$j"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 730         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount};
 
 731         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 732         $form->{"gldate_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 733         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 734         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 736         $form->{"exchangerate_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 737         $form->{"forex_$j"}           = $form->{"exchangerate_$i"};
 
 738         $form->{"AP_paid_$j"}         = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 739         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
 
 740         $form->{paidaccounts}++;
 
 746         if (($key eq "AP_tax") || ($key eq "AR_tax")) {
 
 747           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 748           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 750           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
 
 751             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 753             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
 
 754             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
 
 757           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
 
 758           $form->{"tax_$index"}  = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} * -1 / $exchangerate, 2);
 
 759           $totaltax             += $form->{"tax_$index"};
 
 763           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
 765           if ($akey eq 'amount') {
 
 767             $form->{"${akey}_$i"} *= -1;
 
 768             $totalamount          += $form->{"${akey}_$i"};
 
 769             $form->{taxrate}       = $form->{acc_trans}{$key}->[$i - 1]->{rate};
 
 771             $form->{"projectnumber_$k"}    = "$form->{acc_trans}{$key}->[$i-1]->{projectnumber}";
 
 772             $form->{"oldprojectnumber_$k"} = $form->{"projectnumber_$k"};
 
 773             $form->{"project_id_$k"}       = "$form->{acc_trans}{$key}->[$i-1]->{project_id}";
 
 776           $form->{"${key}_$k"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 778           my $q_description    = quotemeta($form->{acc_trans}{$key}->[$i-1]->{description});
 
 779           $form->{"select${key}"} =~
 
 781                 ($form->{acc_trans}{$key}->[$i-1]->{accno}--[^\"]*)
 
 783               $form->{acc_trans}{$key}->[$i-1]->{accno}
 
 787           $form->{"${key}_$k"} = $1;
 
 790             $form->{APselected} = $form->{acc_trans}{$key}->[$i-1]->{accno};
 
 792           } elsif ($akey eq 'amount') {
 
 793             $form->{"${key}_$k"}   = $form->{acc_trans}{$key}->[$i-1]->{accno} . "--" . $form->{acc_trans}{$key}->[$i-1]->{id};
 
 794             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
 
 801   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
 
 803   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
 
 804     # add tax to amounts and invtotal
 
 805     for $i (1 .. $form->{rowcount}) {
 
 806       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
 
 807       $tax                  = $form->round_amount($taxamount, 2);
 
 808       $diff                += ($taxamount - $tax);
 
 809       $form->{"amount_$i"} += $form->{"tax_$i"};
 
 812     $form->{amount_1} += $form->round_amount($diff, 2);
 
 815   $taxamount        = $form->round_amount($taxamount, 2);
 
 816   $form->{invtotal} = $totalamount + $totaltax;
 
 818   $main::lxdebug->leave_sub();
 
 822   $main::lxdebug->enter_sub();
 
 824   my ($self, $form, $myconfig, $id) = @_;
 
 826   my ($query, $new_id, $storno_row, $acc_trans_rows);
 
 827   my $dbh = $form->get_standard_dbh($myconfig);
 
 829   $query = qq|SELECT nextval('glid')|;
 
 830   ($new_id) = selectrow_query($form, $dbh, $query);
 
 832   $query = qq|SELECT * FROM ap WHERE id = ?|;
 
 833   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
 
 835   $storno_row->{id}         = $new_id;
 
 836   $storno_row->{storno_id}  = $id;
 
 837   $storno_row->{storno}     = 't';
 
 838   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
 
 839   $storno_row->{amount}    *= -1;
 
 840   $storno_row->{netamount} *= -1;
 
 841   $storno_row->{paid}       = $storno_row->{amount};
 
 843   delete @$storno_row{qw(itime mtime)};
 
 845   $query = sprintf 'INSERT INTO ap (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
 
 846   do_query($form, $dbh, $query, (values %$storno_row));
 
 848   $query = qq|UPDATE ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 849   do_query($form, $dbh, $query, $id);
 
 851   $form->new_lastmtime('ap') if $id == $form->{id};
 
 853   # now copy acc_trans entries
 
 854   $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|;
 
 855   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
 
 857   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
 
 858   while ($rowref->[-1]{link} =~ /paid/) {
 
 859     splice(@$rowref, -2);
 
 862   for my $row (@$rowref) {
 
 863     delete @$row{qw(itime mtime link acc_trans_id)};
 
 864     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
 
 865     $row->{trans_id}   = $new_id;
 
 866     $row->{amount}    *= -1;
 
 867     do_query($form, $dbh, $query, (values %$row));
 
 870   map { IO->set_datepaid(table => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);
 
 874   $main::lxdebug->leave_sub();