Part Controller - falschen Code aus kivi.Order.js wieder entfernt
[kivitendo-erp.git] / SL / AR.pm
index c52a00f..b4b6867 100644 (file)
--- a/SL/AR.pm
+++ b/SL/AR.pm
@@ -40,12 +40,23 @@ use SL::DBUtils;
 use SL::IO;
 use SL::MoreCommon;
 use SL::DB::Default;
+use SL::TransNumber;
+use SL::Util qw(trim);
+use SL::DB;
 
 use strict;
 
 sub post_transaction {
+  my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
   $main::lxdebug->enter_sub();
 
+  my $rc = SL::DB->client->with_transaction(\&_post_transaction, $self, $myconfig, $form, $provided_dbh, $payments_only);
+
+  $::lxdebug->leave_sub;
+  return $rc;
+}
+
+sub _post_transaction {
   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
 
   my ($query, $sth, $null, $taxrate, $amount, $tax);
@@ -54,7 +65,7 @@ sub post_transaction {
 
   my @values;
 
-  my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
+  my $dbh = $provided_dbh || SL::DB->client->dbh;
   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
   # set exchangerate
@@ -68,40 +79,11 @@ sub post_transaction {
   $form->{AR_amounts}{receivables} = $form->{ARselected};
   $form->{AR}{receivables}         = $form->{ARselected};
 
-  # parsing
-  for $i (1 .. $form->{rowcount}) {
-    $form->{"amount_$i"} = $form->round_amount($form->parse_amount($myconfig, $form->{"amount_$i"}) * $form->{exchangerate}, 2);
-    $form->{amount}     += $form->{"amount_$i"};
-    $form->{"tax_$i"}    = $form->parse_amount($myconfig, $form->{"tax_$i"});
-  }
-
-  # this is for ar
-  $form->{tax}       = 0;
-  $form->{netamount} = 0;
-  $form->{total_tax} = 0;
+  $form->{tax}       = 0; # is this still needed?
 
-  # taxincluded doesn't make sense if there is no amount
-  $form->{taxincluded} = 0 unless $form->{amount};
-
-  for $i (1 .. $form->{rowcount}) {
-    ($form->{"tax_id_$i"}) = split /--/, $form->{"taxchart_$i"};
-
-    $query = qq|SELECT c.accno, t.taxkey, t.rate FROM tax t LEFT JOIN chart c ON (c.id = t.chart_id) WHERE t.id = ? ORDER BY c.accno|;
-    ($form->{AR_amounts}{"tax_$i"}, $form->{"taxkey_$i"}, $form->{"taxrate_$i"}) = selectrow_query($form, $dbh, $query, $form->{"tax_id_$i"});
-
-    if ($form->{taxincluded} *= 1) {
-      $tax = $form->{"korrektur_$i"}
-        ? $form->{"tax_$i"}
-        : $form->{"amount_$i"} - ($form->{"amount_$i"} / ($form->{"taxrate_$i"} + 1)); # should be same as taxrate * amount / (taxrate + 1)
-      $form->{"amount_$i"} = $form->round_amount($form->{"amount_$i"} - $tax, 2);
-      $form->{"tax_$i"}    = $form->round_amount($tax, 2);
-    } else {
-      $form->{"tax_$i"}    = $form->{"amount_$i"} * $form->{"taxrate_$i"} unless $form->{"korrektur_$i"};
-      $form->{"tax_$i"}    = $form->round_amount($form->{"tax_$i"} * $form->{exchangerate}, 2);
-    }
-    $form->{netamount}  += $form->{"amount_$i"};
-    $form->{total_tax}  += $form->{"tax_$i"};
-  }
+  # main calculation of rowcount loop inside Form method, amount_$i and tax_$i get formatted
+  $form->{taxincluded} = 0 unless $form->{taxincluded};
+  ($form->{netamount},$form->{total_tax},$form->{amount}) = $form->calculate_arap('sell', $form->{taxincluded}, $form->{exchangerate});
 
   # adjust paidaccounts if there is no date in the last row
   # this does not apply to stornos, where the paid field is set manually
@@ -116,7 +98,6 @@ sub post_transaction {
       $form->{datepaid}  = $form->{"datepaid_$i"};
     }
 
-    $form->{amount} = $form->{netamount} + $form->{total_tax};
   }
   $form->{paid}   = $form->round_amount($form->{paid} * ($form->{exchangerate} || 1), 2);
 
@@ -134,9 +115,12 @@ sub post_transaction {
     } else {
       $query = qq|SELECT nextval('glid')|;
       ($form->{id}) = selectrow_query($form, $dbh, $query);
-      $query = qq|INSERT INTO ar (id, invnumber, employee_id, currency_id) VALUES (?, 'dummy', ?, (SELECT id FROM currencies WHERE name=?))|;
-      do_query($form, $dbh, $query, $form->{id}, $form->{employee_id}, $form->{currency});
-      $form->{invnumber} = $form->update_defaults($myconfig, "invnumber", $dbh) unless $form->{invnumber};
+      $query = qq|INSERT INTO ar (id, invnumber, employee_id, currency_id, taxzone_id) VALUES (?, 'dummy', ?, (SELECT id FROM currencies WHERE name=?), (SELECT taxzone_id FROM customer WHERE id = ?))|;
+      do_query($form, $dbh, $query, $form->{id}, $form->{employee_id}, $form->{currency}, $form->{customer_id});
+      if (!$form->{invnumber}) {
+        my $trans_number   = SL::TransNumber->new(type => 'invoice', dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
+        $form->{invnumber} = $trans_number->create_unique;
+      }
     }
   }
 
@@ -155,12 +139,15 @@ sub post_transaction {
       qq|UPDATE ar set
            invnumber = ?, ordnumber = ?, transdate = ?, customer_id = ?,
            taxincluded = ?, amount = ?, duedate = ?, paid = ?,
+           currency_id = (SELECT id FROM currencies WHERE name = ?),
            netamount = ?, notes = ?, department_id = ?,
            employee_id = ?, storno = ?, storno_id = ?, globalproject_id = ?,
            direct_debit = ?
          WHERE id = ?|;
     my @values = ($form->{invnumber}, $form->{ordnumber}, conv_date($form->{transdate}), conv_i($form->{customer_id}), $form->{taxincluded} ? 't' : 'f', $form->{amount},
-                  conv_date($form->{duedate}), $form->{paid}, $form->{netamount}, $form->{notes}, conv_i($form->{department_id}),
+                  conv_date($form->{duedate}), $form->{paid},
+                  $form->{currency},
+                  $form->{netamount}, $form->{notes}, conv_i($form->{department_id}),
                   conv_i($form->{employee_id}), $form->{storno} ? 't' : 'f', $form->{storno_id},
                   conv_i($form->{globalproject_id}), $form->{direct_debit} ? 't' : 'f', conv_i($form->{id}));
     do_query($form, $dbh, $query, @values);
@@ -209,6 +196,8 @@ sub post_transaction {
     do_query($form, $dbh, $query,  $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
   }
 
+  $form->new_lastmtime('ar');
+
   # add paid transactions
   for my $i (1 .. $form->{paidaccounts}) {
 
@@ -295,6 +284,15 @@ sub post_transaction {
         $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{exchangerate} - $form->{"exchangerate_$i"}) * -1, 2);
 
         if ($amount != 0) {
+          # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
+          if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
+            $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
+          };
+          if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
+            $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
+          };
+          die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
+          die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
           my $accno = ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno};
           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link)
                        VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
@@ -328,26 +326,17 @@ sub post_transaction {
       exporttype => DATEV_ET_BUCHUNGEN,
       format     => DATEV_FORMAT_KNE,
       dbh        => $dbh,
-      from       => $transdate,
-      to         => $transdate,
       trans_id   => $form->{id},
     );
 
     $datev->export;
 
     if ($datev->errors) {
-      $dbh->rollback;
       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
     }
   }
 
-  my $rc = 1;
-  if (!$provided_dbh) {
-    $rc = $dbh->commit();
-    $dbh->disconnect();
-  }
-
-  $main::lxdebug->leave_sub() and return $rc;
+  return 1;
 }
 
 sub _delete_payments {
@@ -390,12 +379,19 @@ sub _delete_payments {
 }
 
 sub post_payment {
+  my ($self, $myconfig, $form, $locale) = @_;
   $main::lxdebug->enter_sub();
 
+  my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
+
+  $::lxdebug->leave_sub;
+  return $rc;
+}
+
+sub _post_payment {
   my ($self, $myconfig, $form, $locale) = @_;
 
-  # connect to database, turn off autocommit
-  my $dbh = $form->dbconnect_noauto($myconfig);
+  my $dbh = SL::DB->client->dbh;
 
   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
@@ -444,12 +440,7 @@ sub post_payment {
 
   restore_form($old_form);
 
-  my $rc = $dbh->commit();
-  $dbh->disconnect();
-
-  $main::lxdebug->leave_sub();
-
-  return $rc;
+  return 1;
 }
 
 sub delete_transaction {
@@ -457,20 +448,16 @@ sub delete_transaction {
 
   my ($self, $myconfig, $form) = @_;
 
-  # connect to database, turn AutoCommit off
-  my $dbh = $form->dbconnect_noauto($myconfig);
-
-  # acc_trans entries are deleted by database triggers.
-  my $query = qq|DELETE FROM ar WHERE id = ?|;
-  do_query($form, $dbh, $query, $form->{id});
-
-  # commit
-  my $rc = $dbh->commit;
-  $dbh->disconnect;
+  SL::DB->client->with_transaction(sub {
+    # acc_trans entries are deleted by database triggers.
+    my $query = qq|DELETE FROM ar WHERE id = ?|;
+    do_query($form, SL::DB->client->dbh, $query, $form->{id});
+    1;
+  }) or do { die SL::DB->client->error };
 
   $main::lxdebug->leave_sub();
 
-  return $rc;
+  return 1;
 }
 
 sub ar_transactions {
@@ -484,19 +471,21 @@ sub ar_transactions {
   my @values;
 
   my $query =
-    qq|SELECT DISTINCT a.id, a.invnumber, a.ordnumber, a.transdate, | .
+    qq|SELECT DISTINCT a.id, a.invnumber, a.ordnumber, a.cusordnumber, a.transdate, | .
     qq|  a.duedate, a.netamount, a.amount, a.paid, | .
-    qq|  a.invoice, a.datepaid, a.terms, a.notes, a.shipvia, | .
+    qq|  a.invoice, a.datepaid, a.notes, a.shipvia, | .
     qq|  a.shippingpoint, a.storno, a.storno_id, a.globalproject_id, | .
     qq|  a.marge_total, a.marge_percent, | .
-    qq|  a.transaction_description, | .
+    qq|  a.transaction_description, a.direct_debit, | .
     qq|  pr.projectnumber AS globalprojectnumber, | .
     qq|  c.name, c.customernumber, c.country, c.ustid, b.description as customertype, | .
     qq|  c.id as customer_id, | .
     qq|  e.name AS employee, | .
     qq|  e2.name AS salesman, | .
+    qq|  dc.dunning_description, | .
     qq|  tz.description AS taxzone, | .
     qq|  pt.description AS payment_terms, | .
+    qq|  d.description AS department, | .
     qq{  ( SELECT ch.accno || ' -- ' || ch.description
            FROM acc_trans at
            LEFT JOIN chart ch ON ch.id = at.chart_id
@@ -506,8 +495,10 @@ sub ar_transactions {
           ) AS charts } .
     qq|FROM ar a | .
     qq|JOIN customer c ON (a.customer_id = c.id) | .
+    qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
     qq|LEFT JOIN employee e2 ON (a.salesman_id = e2.id) | .
+    qq|LEFT JOIN dunning_config dc ON (a.dunning_config_id = dc.id) | .
     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id)| .
     qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
     qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)| .
@@ -522,14 +513,18 @@ sub ar_transactions {
 
   if ($form->{customernumber}) {
     $where .= " AND c.customernumber = ?";
-    push(@values, $form->{customernumber});
+    push(@values, trim($form->{customernumber}));
   }
   if ($form->{customer_id}) {
     $where .= " AND a.customer_id = ?";
     push(@values, $form->{customer_id});
   } elsif ($form->{customer}) {
     $where .= " AND c.name ILIKE ?";
-    push(@values, $form->like($form->{customer}));
+    push(@values, like($form->{customer}));
+  }
+  if ($form->{"cp_name"}) {
+    $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
+    push(@values, (like($form->{"cp_name"}))x2);
   }
   if ($form->{business_id}) {
     my $business_id = $form->{business_id};
@@ -542,14 +537,14 @@ sub ar_transactions {
     push(@values, $department_id);
   }
   if ($form->{department}) {
-    my $department = "%" . $form->{department} . "%";
+    my $department = like($form->{department});
     $where .= " AND d.description ILIKE ?";
     push(@values, $department);
   }
-  foreach my $column (qw(invnumber ordnumber notes transaction_description)) {
+  foreach my $column (qw(invnumber ordnumber cusordnumber notes transaction_description)) {
     if ($form->{$column}) {
       $where .= " AND a.$column ILIKE ?";
-      push(@values, $form->like($form->{$column}));
+      push(@values, like($form->{$column}));
     }
   }
   if ($form->{"project_id"}) {
@@ -566,11 +561,19 @@ sub ar_transactions {
 
   if ($form->{transdatefrom}) {
     $where .= " AND a.transdate >= ?";
-    push(@values, $form->{transdatefrom});
+    push(@values, trim($form->{transdatefrom}));
   }
   if ($form->{transdateto}) {
     $where .= " AND a.transdate <= ?";
-    push(@values, $form->{transdateto});
+    push(@values, trim($form->{transdateto}));
+  }
+  if ($form->{duedatefrom}) {
+    $where .= " AND a.duedate >= ?";
+    push(@values, trim($form->{duedatefrom}));
+  }
+  if ($form->{duedateto}) {
+    $where .= " AND a.duedate <= ?";
+    push(@values, trim($form->{duedateto}));
   }
   if ($form->{open} || $form->{closed}) {
     unless ($form->{open} && $form->{closed}) {
@@ -582,7 +585,7 @@ sub ar_transactions {
   if (!$main::auth->assert('sales_all_edit', 1)) {
     # only show own invoices
     $where .= " AND a.employee_id = (select id from employee where login= ?)";
-    push (@values, $form->{login});
+    push (@values, $::myconfig{login});
   } else {
     if ($form->{employee_id}) {
       $where .= " AND a.employee_id = ?";
@@ -594,12 +597,48 @@ sub ar_transactions {
     }
   };
 
+  if ($form->{parts_partnumber}) {
+    $where .= <<SQL;
+      AND EXISTS (
+        SELECT invoice.trans_id
+        FROM invoice
+        LEFT JOIN parts ON (invoice.parts_id = parts.id)
+        WHERE (invoice.trans_id = a.id)
+          AND (parts.partnumber ILIKE ?)
+        LIMIT 1
+      )
+SQL
+    push @values, like($form->{parts_partnumber});
+  }
+
+  if ($form->{parts_description}) {
+    $where .= <<SQL;
+      AND EXISTS (
+        SELECT invoice.trans_id
+        FROM invoice
+        WHERE (invoice.trans_id = a.id)
+          AND (invoice.description ILIKE ?)
+        LIMIT 1
+      )
+SQL
+    push @values, like($form->{parts_description});
+  }
+
+  my ($cvar_where, @cvar_values) = CVar->build_filter_query('module'         => 'CT',
+                                                            'trans_id_field' => 'c.id',
+                                                            'filter'         => $form,
+                                                           );
+  if ($cvar_where) {
+    $where .= qq| AND ($cvar_where)|;
+    push @values, @cvar_values;
+  }
+
   my @a = qw(transdate invnumber name);
   push @a, "employee" if $form->{l_employee};
   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
 
-  if (grep({ $_ eq $form->{sort} } qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description))) {
+  if (grep({ $_ eq $form->{sort} } qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description))) {
     $sortorder = $form->{sort} . " $sortdir";
   }
 
@@ -618,7 +657,7 @@ sub get_transdate {
   my ($self, $myconfig, $form) = @_;
 
   # connect to database
-  my $dbh = $form->dbconnect($myconfig);
+  my $dbh = SL::DB->client->dbh;
 
   my $query =
     "SELECT COALESCE(" .
@@ -627,8 +666,6 @@ sub get_transdate {
     "  current_date)";
   ($form->{transdate}) = $dbh->selectrow_array($query);
 
-  $dbh->disconnect;
-
   $main::lxdebug->leave_sub();
 }
 
@@ -644,6 +681,7 @@ sub setup_form {
   $form->{forex} = $form->{exchangerate};
   $exchangerate  = $form->{exchangerate} ? $form->{exchangerate} : 1;
 
+  # expected keys: AR, AR_paid, AR_tax, AR_amount
   foreach my $key (keys %{ $form->{AR_links} }) {
     $j = 0;
     $k = 0;
@@ -672,15 +710,17 @@ sub setup_form {
         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
         $form->{paidaccounts}++;
 
-      } else {
+      } else { # e.g. AR_amount, AR, AR_tax
 
         $akey = $key;
-        $akey =~ s/AR_//;
+        $akey =~ s/AR_//; # e.g. tax, amount, AR, used to store form key tax_$i, amount_$i, ...
 
-        if ($key eq "AR_tax" || $key eq "AP_tax") {
+        if ($key eq "AR_tax" || $key eq "AP_tax") { # AR_tax
           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
+          # determine the rounded tax amounts for each account, e.g. tax_1776
           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
+          # check e.g. $form->{1776_rate}, does this make sense for AR_tax charts? Is this ever valid? If it was, totaltax would be calculated twice
           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
             $taxrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
@@ -691,10 +731,11 @@ sub setup_form {
           }
 
           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
-          $form->{"tax_$index"}  = $form->{acc_trans}{$key}->[$i - 1]->{amount};
+          $form->{"tax_$index"}  = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2); # convert the tax_$i amounts
+          # currently totaltax is the sum of rounded tax amounts, is this correct?
           $totaltax             += $form->{"tax_$index"};
 
-        } else {
+        } else { # e.g. AR_amount, AR
           $k++;
           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
 
@@ -745,12 +786,21 @@ sub setup_form {
 }
 
 sub storno {
+  my ($self, $form, $myconfig, $id) = @_;
   $main::lxdebug->enter_sub();
 
+  my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
+
+  $::lxdebug->leave_sub;
+  return $rc;
+}
+
+
+sub _storno {
   my ($self, $form, $myconfig, $id) = @_;
 
   my ($query, $new_id, $storno_row, $acc_trans_rows);
-  my $dbh = $form->get_standard_dbh($myconfig);
+  my $dbh = SL::DB->client->dbh;
 
   $query = qq|SELECT nextval('glid')|;
   ($new_id) = selectrow_query($form, $dbh, $query);
@@ -774,6 +824,8 @@ sub storno {
   $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
   do_query($form, $dbh, $query, $id);
 
+  $form->new_lastmtime('ar') if $id == $form->{id};
+
   # now copy acc_trans entries
   $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|;
   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
@@ -793,11 +845,8 @@ sub storno {
 
   map { IO->set_datepaid(table => 'ar', id => $_, dbh => $dbh) } ($id, $new_id);
 
-  $dbh->commit;
-
-  $main::lxdebug->leave_sub();
+  return 1;
 }
 
 
 1;
-