Debitorenbuchungen auf Verwendung des Chart-Pickers umgestellt
[kivitendo-erp.git] / SL / AR.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
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.
21 #
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., 51 Franklin Street, Fifth Floor, Boston,
29 # MA 02110-1335, USA.
30 #======================================================================
31 #
32 # Accounts Receivable module backend routines
33 #
34 #======================================================================
35
36 package AR;
37
38 use Data::Dumper;
39 use SL::DATEV qw(:CONSTANTS);
40 use SL::DBUtils;
41 use SL::IO;
42 use SL::MoreCommon;
43 use SL::DB::Default;
44 use SL::TransNumber;
45 use SL::Util qw(trim);
46 use SL::DB;
47
48 use strict;
49
50 sub post_transaction {
51   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
52   $main::lxdebug->enter_sub();
53
54   my $rc = SL::DB->client->with_transaction(\&_post_transaction, $self, $myconfig, $form, $provided_dbh, $payments_only);
55
56   $::lxdebug->leave_sub;
57   return $rc;
58 }
59
60 sub _post_transaction {
61   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
62
63   my ($query, $sth, $null, $taxrate, $amount, $tax);
64   my $exchangerate = 0;
65   my $i;
66
67   my @values;
68
69   my $dbh = $provided_dbh || SL::DB->client->dbh;
70   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
71
72   # set exchangerate
73   $form->{exchangerate} = ($form->{currency} eq $form->{defaultcurrency}) ? 1 :
74       ( $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy') ||
75         $form->parse_amount($myconfig, $form->{exchangerate}) );
76
77   # get the charts selected
78   $form->{AR_amounts}{"amount_$_"} = $form->{"AR_amount_chart_id_$_"} for (1 .. $form->{rowcount});
79
80   $form->{tax}       = 0; # is this still needed?
81
82   # main calculation of rowcount loop inside Form method, amount_$i and tax_$i get formatted
83   $form->{taxincluded} = 0 unless $form->{taxincluded};
84   ($form->{netamount},$form->{total_tax},$form->{amount}) = $form->calculate_arap('sell', $form->{taxincluded}, $form->{exchangerate});
85
86   # adjust paidaccounts if there is no date in the last row
87   # this does not apply to stornos, where the paid field is set manually
88   unless ($form->{storno}) {
89     $form->{paidaccounts}-- unless $form->{"datepaid_$form->{paidaccounts}"};
90     $form->{paid} = 0;
91
92     # add payments
93     for $i (1 .. $form->{paidaccounts}) {
94       $form->{"paid_$i"} = $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}), 2);
95       $form->{paid}     += $form->{"paid_$i"};
96       $form->{datepaid}  = $form->{"datepaid_$i"};
97     }
98
99   }
100   $form->{paid}   = $form->round_amount($form->{paid} * ($form->{exchangerate} || 1), 2);
101
102   ($null, $form->{employee_id}) = split /--/, $form->{employee};
103
104   $form->get_employee($dbh) unless $form->{employee_id};
105
106   # if we have an id delete old records else make one
107   if (!$payments_only) {
108     if ($form->{id}) {
109       # delete detail records
110       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
111       do_query($form, $dbh, $query, $form->{id});
112
113     } else {
114       $query = qq|SELECT nextval('glid')|;
115       ($form->{id}) = selectrow_query($form, $dbh, $query);
116       $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 = ?))|;
117       do_query($form, $dbh, $query, $form->{id}, $form->{employee_id}, $form->{currency}, $form->{customer_id});
118       if (!$form->{invnumber}) {
119         my $trans_number   = SL::TransNumber->new(type => 'invoice', dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
120         $form->{invnumber} = $trans_number->create_unique;
121       }
122     }
123   }
124
125   # amount for AR account
126   $form->{receivables} = $form->round_amount($form->{amount}, 2) * -1;
127
128   # update exchangerate
129   $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, $form->{exchangerate}, 0)
130     if ($form->{currency} ne $form->{defaultcurrency}) && !$form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy');
131
132   if (!$payments_only) {
133     $query =
134       qq|UPDATE ar set
135            invnumber = ?, ordnumber = ?, transdate = ?, customer_id = ?,
136            taxincluded = ?, amount = ?, duedate = ?, paid = ?,
137            currency_id = (SELECT id FROM currencies WHERE name = ?),
138            netamount = ?, notes = ?, department_id = ?,
139            employee_id = ?, storno = ?, storno_id = ?, globalproject_id = ?,
140            direct_debit = ?
141          WHERE id = ?|;
142     my @values = ($form->{invnumber}, $form->{ordnumber}, conv_date($form->{transdate}), conv_i($form->{customer_id}), $form->{taxincluded} ? 't' : 'f', $form->{amount},
143                   conv_date($form->{duedate}), $form->{paid},
144                   $form->{currency},
145                   $form->{netamount}, $form->{notes}, conv_i($form->{department_id}),
146                   conv_i($form->{employee_id}), $form->{storno} ? 't' : 'f', $form->{storno_id},
147                   conv_i($form->{globalproject_id}), $form->{direct_debit} ? 't' : 'f', conv_i($form->{id}));
148     do_query($form, $dbh, $query, @values);
149
150     # add individual transactions for AR, amount and taxes
151     for $i (1 .. $form->{rowcount}) {
152       if ($form->{"amount_$i"} != 0) {
153         my $project_id = conv_i($form->{"project_id_$i"});
154
155         # insert detail records in acc_trans
156         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
157                      VALUES (?, ?, ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.id = ?))|;
158         @values = (conv_i($form->{id}), $form->{AR_amounts}{"amount_$i"}, conv_i($form->{"amount_$i"}), conv_date($form->{transdate}), $project_id,
159                    conv_i($form->{"taxkey_$i"}), conv_i($form->{"tax_id_$i"}), $form->{AR_amounts}{"amount_$i"});
160         do_query($form, $dbh, $query, @values);
161
162         if ($form->{"tax_$i"} != 0) {
163           # insert detail records in acc_trans
164           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
165                        VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.accno = ?))|;
166           @values = (conv_i($form->{id}), $form->{AR_amounts}{"tax_$i"}, conv_i($form->{"tax_$i"}), conv_date($form->{transdate}), $project_id,
167                      conv_i($form->{"taxkey_$i"}), conv_i($form->{"tax_id_$i"}), $form->{AR_amounts}{"tax_$i"});
168           do_query($form, $dbh, $query, @values);
169         }
170       }
171     }
172
173     # add recievables
174     $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link)
175                  VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?),
176                  (SELECT tax_id
177                   FROM taxkeys
178                   WHERE chart_id = ?
179                   AND startdate <= ?
180                   ORDER BY startdate DESC LIMIT 1),
181                  (SELECT c.link FROM chart c WHERE c.id = ?))|;
182     @values = (conv_i($form->{id}), $form->{AR_chart_id}, conv_i($form->{receivables}), conv_date($form->{transdate}),
183                 $form->{AR_chart_id}, $form->{AR_chart_id}, conv_date($form->{transdate}), $form->{AR_chart_id});
184     do_query($form, $dbh, $query, @values);
185
186   } else {
187     # Record paid amount.
188     $query = qq|UPDATE ar SET paid = ?, datepaid = ? WHERE id = ?|;
189     do_query($form, $dbh, $query,  $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
190   }
191
192   $form->new_lastmtime('ar');
193
194   # add paid transactions
195   for my $i (1 .. $form->{paidaccounts}) {
196
197     if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
198       next;
199     }
200
201     if ($form->{"paid_$i"} != 0) {
202       my $project_id = conv_i($form->{"paid_project_id_$i"});
203
204       $form->{"AR_paid_$i"} =~ s/\"//g;
205       ($form->{AR}{"paid_$i"}) = split(/--/, $form->{"AR_paid_$i"});
206       $form->{"datepaid_$i"} = $form->{transdate}
207         unless ($form->{"datepaid_$i"});
208
209       $form->{"exchangerate_$i"} = ($form->{currency} eq $form->{defaultcurrency}) ? 1 :
210         ( $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy') ||
211           $form->parse_amount($myconfig, $form->{"exchangerate_$i"}) );
212
213       # if there is no amount and invtotal is zero there is no exchangerate
214       $form->{exchangerate} = $form->{"exchangerate_$i"}
215         if ($form->{amount} == 0 && $form->{netamount} == 0);
216
217       # receivables amount
218       $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
219
220       if ($amount != 0) {
221         # add receivable
222         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
223                      VALUES (?, ?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?),
224                      (SELECT tax_id
225                       FROM taxkeys
226                       WHERE chart_id = ?
227                       AND startdate <= ?
228                       ORDER BY startdate DESC LIMIT 1),
229                      (SELECT c.link FROM chart c WHERE c.id = ?))|;
230         @values = (conv_i($form->{id}), $form->{AR_chart_id}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR_chart_id}, $form->{AR_chart_id}, conv_date($form->{"datepaid_$i"}), $form->{AR_chart_id});
231
232         do_query($form, $dbh, $query, @values);
233       }
234
235       if ($form->{"paid_$i"} != 0) {
236         # add payment
237         my $project_id = conv_i($form->{"paid_project_id_$i"});
238         my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
239         $amount = $form->{"paid_$i"} * -1;
240         $query  = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, taxkey, tax_id, chart_link)
241                      VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
242                      (SELECT tax_id
243                       FROM taxkeys
244                       WHERE chart_id= (SELECT id
245                                        FROM chart
246                                        WHERE accno = ?)
247                       AND startdate <= ?
248                       ORDER BY startdate DESC LIMIT 1),
249                      (SELECT c.link FROM chart c WHERE c.accno = ?))|;
250         @values = (conv_i($form->{id}), $form->{AR}{"paid_$i"}, $amount, conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $project_id, $form->{AR}{"paid_$i"},
251                     $form->{AR}{"paid_$i"}, conv_date($form->{"datepaid_$i"}), $form->{AR}{"paid_$i"});
252         do_query($form, $dbh, $query, @values);
253
254         # exchangerate difference for payment
255         $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) * -1, 2);
256
257         if ($amount != 0) {
258           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link)
259                        VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
260                        (SELECT tax_id
261                         FROM taxkeys
262                         WHERE chart_id= (SELECT id
263                                          FROM chart
264                                          WHERE accno = ?)
265                         AND startdate <= ?
266                         ORDER BY startdate DESC LIMIT 1),
267                        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
268           @values = (conv_i($form->{id}), $form->{AR}{"paid_$i"}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR}{"paid_$i"},
269                     $form->{AR}{"paid_$i"}, conv_date($form->{"datepaid_$i"}), $form->{AR}{"paid_$i"});
270           do_query($form, $dbh, $query, @values);
271         }
272
273         # exchangerate gain/loss
274         $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{exchangerate} - $form->{"exchangerate_$i"}) * -1, 2);
275
276         if ($amount != 0) {
277           # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
278           if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
279             $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
280           };
281           if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
282             $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
283           };
284           die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
285           die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
286           my $accno = ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno};
287           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link)
288                        VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
289                        (SELECT tax_id
290                         FROM taxkeys
291                         WHERE chart_id= (SELECT id
292                                          FROM chart
293                                          WHERE accno = ?)
294                         AND startdate <= ?
295                         ORDER BY startdate DESC LIMIT 1),
296                        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
297           @values = (conv_i($form->{id}), $accno, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $accno, $accno, conv_date($form->{"datepaid_$i"}), $accno);
298           do_query($form, $dbh, $query, @values);
299         }
300       }
301
302       # update exchangerate record
303       $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, $form->{"exchangerate_$i"}, 0)
304         if ($form->{currency} ne $form->{defaultcurrency}) && !$form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
305     }
306   }
307
308   IO->set_datepaid(table => 'ar', id => $form->{id}, dbh => $dbh);
309
310   # safety check datev export
311   if ($::instance_conf->get_datev_check_on_ar_transaction) {
312     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
313     $transdate  ||= DateTime->today;
314
315     my $datev = SL::DATEV->new(
316       exporttype => DATEV_ET_BUCHUNGEN,
317       format     => DATEV_FORMAT_KNE,
318       dbh        => $dbh,
319       trans_id   => $form->{id},
320     );
321
322     $datev->export;
323
324     if ($datev->errors) {
325       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
326     }
327   }
328
329   return 1;
330 }
331
332 sub _delete_payments {
333   $main::lxdebug->enter_sub();
334
335   my ($self, $form, $dbh) = @_;
336
337   my @delete_acc_trans_ids;
338
339   # Delete old payment entries from acc_trans.
340   my $query =
341     qq|SELECT acc_trans_id
342        FROM acc_trans
343        WHERE (trans_id = ?) AND fx_transaction
344
345        UNION
346
347        SELECT at.acc_trans_id
348        FROM acc_trans at
349        LEFT JOIN chart c ON (at.chart_id = c.id)
350        WHERE (trans_id = ?) AND (c.link LIKE '%AR_paid%')|;
351   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
352
353   $query =
354     qq|SELECT at.acc_trans_id
355        FROM acc_trans at
356        LEFT JOIN chart c ON (at.chart_id = c.id)
357        WHERE (trans_id = ?)
358          AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
359        ORDER BY at.acc_trans_id
360        OFFSET 1|;
361   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
362
363   if (@delete_acc_trans_ids) {
364     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
365     do_query($form, $dbh, $query);
366   }
367
368   $main::lxdebug->leave_sub();
369 }
370
371 sub post_payment {
372   my ($self, $myconfig, $form, $locale) = @_;
373   $main::lxdebug->enter_sub();
374
375   my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
376
377   $::lxdebug->leave_sub;
378   return $rc;
379 }
380
381 sub _post_payment {
382   my ($self, $myconfig, $form, $locale) = @_;
383
384   my $dbh = SL::DB->client->dbh;
385
386   my (%payments, $old_form, $row, $item, $query, %keep_vars);
387
388   $old_form = save_form();
389
390   # Delete all entries in acc_trans from prior payments.
391   if (SL::DB::Default->get->payments_changeable != 0) {
392     $self->_delete_payments($form, $dbh);
393   }
394
395   # Save the new payments the user made before cleaning up $form.
396   my $payments_re = '^datepaid_\d+$|^gldate_\d+$|^acc_trans_id_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^paid_project_id_\d+$|^AR_paid_\d+$|^paidaccounts$';
397   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
398
399   # Clean up $form so that old content won't tamper the results.
400   %keep_vars = map { $_, 1 } qw(login password id);
401   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
402
403   # Retrieve the invoice from the database.
404   $form->create_links('AR', $myconfig, 'customer', $dbh);
405
406   # Restore the payment options from the user input.
407   map { $form->{$_} = $payments{$_} } keys %payments;
408
409   # Set up the content of $form in the way that AR::post_transaction() expects.
410
411   $self->setup_form($form, 1);
412
413   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
414   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
415
416   # Get the AR chart ID (which is normally done by Form::create_links()).
417   $query =
418     qq|SELECT c.id
419        FROM acc_trans at
420        LEFT JOIN chart c ON (at.chart_id = c.id)
421        WHERE (trans_id = ?)
422          AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
423        ORDER BY at.acc_trans_id
424        LIMIT 1|;
425
426   ($form->{AR_chart_id}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
427
428   # Post the new payments.
429   $self->post_transaction($myconfig, $form, $dbh, 1);
430
431   restore_form($old_form);
432
433   return 1;
434 }
435
436 sub delete_transaction {
437   $main::lxdebug->enter_sub();
438
439   my ($self, $myconfig, $form) = @_;
440
441   SL::DB->client->with_transaction(sub {
442     # acc_trans entries are deleted by database triggers.
443     my $query = qq|DELETE FROM ar WHERE id = ?|;
444     do_query($form, SL::DB->client->dbh, $query, $form->{id});
445     1;
446   }) or do { die SL::DB->client->error };
447
448   $main::lxdebug->leave_sub();
449
450   return 1;
451 }
452
453 sub ar_transactions {
454   $main::lxdebug->enter_sub();
455
456   my ($self, $myconfig, $form) = @_;
457
458   # connect to database
459   my $dbh = $form->get_standard_dbh($myconfig);
460
461   my @values;
462
463   my $query =
464     qq|SELECT DISTINCT a.id, a.invnumber, a.ordnumber, a.cusordnumber, a.transdate, | .
465     qq|  a.duedate, a.netamount, a.amount, a.paid, | .
466     qq|  a.invoice, a.datepaid, a.notes, a.shipvia, | .
467     qq|  a.shippingpoint, a.storno, a.storno_id, a.globalproject_id, | .
468     qq|  a.marge_total, a.marge_percent, | .
469     qq|  a.transaction_description, a.direct_debit, | .
470     qq|  pr.projectnumber AS globalprojectnumber, | .
471     qq|  c.name, c.customernumber, c.country, c.ustid, b.description as customertype, | .
472     qq|  c.id as customer_id, | .
473     qq|  e.name AS employee, | .
474     qq|  e2.name AS salesman, | .
475     qq|  dc.dunning_description, | .
476     qq|  tz.description AS taxzone, | .
477     qq|  pt.description AS payment_terms, | .
478     qq|  d.description AS department, | .
479     qq{  ( SELECT ch.accno || ' -- ' || ch.description
480            FROM acc_trans at
481            LEFT JOIN chart ch ON ch.id = at.chart_id
482            WHERE ch.link ~ 'AR[[:>:]]'
483             AND at.trans_id = a.id
484             LIMIT 1
485           ) AS charts } .
486     qq|FROM ar a | .
487     qq|JOIN customer c ON (a.customer_id = c.id) | .
488     qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
489     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
490     qq|LEFT JOIN employee e2 ON (a.salesman_id = e2.id) | .
491     qq|LEFT JOIN dunning_config dc ON (a.dunning_config_id = dc.id) | .
492     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id)| .
493     qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
494     qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)| .
495     qq|LEFT JOIN business b ON (b.id = c.business_id)| .
496     qq|LEFT JOIN department d ON (d.id = a.department_id)|;
497
498   my $where = "1 = 1";
499
500   unless ( $::auth->assert('show_ar_transactions', 1) ) {
501     $where .= " AND NOT invoice = 'f' ";  # remove ar transactions from Sales -> Reports -> Invoices
502   };
503
504   if ($form->{customernumber}) {
505     $where .= " AND c.customernumber = ?";
506     push(@values, trim($form->{customernumber}));
507   }
508   if ($form->{customer_id}) {
509     $where .= " AND a.customer_id = ?";
510     push(@values, $form->{customer_id});
511   } elsif ($form->{customer}) {
512     $where .= " AND c.name ILIKE ?";
513     push(@values, like($form->{customer}));
514   }
515   if ($form->{"cp_name"}) {
516     $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
517     push(@values, (like($form->{"cp_name"}))x2);
518   }
519   if ($form->{business_id}) {
520     my $business_id = $form->{business_id};
521     $where .= " AND c.business_id = ?";
522     push(@values, $business_id);
523   }
524   if ($form->{department_id}) {
525     $where .= " AND a.department_id = ?";
526     push(@values, $form->{department_id});
527   }
528   foreach my $column (qw(invnumber ordnumber cusordnumber notes transaction_description)) {
529     if ($form->{$column}) {
530       $where .= " AND a.$column ILIKE ?";
531       push(@values, like($form->{$column}));
532     }
533   }
534   if ($form->{"project_id"}) {
535     $where .=
536       qq|AND ((a.globalproject_id = ?) OR EXISTS | .
537       qq|  (SELECT * FROM invoice i | .
538       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
539       qq| OR EXISTS | .
540       qq|  (SELECT * FROM acc_trans at | .
541       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
542       qq|  )|;
543     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
544   }
545
546   if ($form->{transdatefrom}) {
547     $where .= " AND a.transdate >= ?";
548     push(@values, trim($form->{transdatefrom}));
549   }
550   if ($form->{transdateto}) {
551     $where .= " AND a.transdate <= ?";
552     push(@values, trim($form->{transdateto}));
553   }
554   if ($form->{duedatefrom}) {
555     $where .= " AND a.duedate >= ?";
556     push(@values, trim($form->{duedatefrom}));
557   }
558   if ($form->{duedateto}) {
559     $where .= " AND a.duedate <= ?";
560     push(@values, trim($form->{duedateto}));
561   }
562   if ($form->{open} || $form->{closed}) {
563     unless ($form->{open} && $form->{closed}) {
564       $where .= " AND a.amount <> a.paid" if ($form->{open});
565       $where .= " AND a.amount = a.paid"  if ($form->{closed});
566     }
567   }
568
569   if (!$main::auth->assert('sales_all_edit', 1)) {
570     # only show own invoices
571     $where .= " AND a.employee_id = (select id from employee where login= ?)";
572     push (@values, $::myconfig{login});
573   } else {
574     if ($form->{employee_id}) {
575       $where .= " AND a.employee_id = ?";
576       push @values, conv_i($form->{employee_id});
577     }
578     if ($form->{salesman_id}) {
579       $where .= " AND a.salesman_id = ?";
580       push @values, conv_i($form->{salesman_id});
581     }
582   };
583
584   if ($form->{parts_partnumber}) {
585     $where .= <<SQL;
586       AND EXISTS (
587         SELECT invoice.trans_id
588         FROM invoice
589         LEFT JOIN parts ON (invoice.parts_id = parts.id)
590         WHERE (invoice.trans_id = a.id)
591           AND (parts.partnumber ILIKE ?)
592         LIMIT 1
593       )
594 SQL
595     push @values, like($form->{parts_partnumber});
596   }
597
598   if ($form->{parts_description}) {
599     $where .= <<SQL;
600       AND EXISTS (
601         SELECT invoice.trans_id
602         FROM invoice
603         WHERE (invoice.trans_id = a.id)
604           AND (invoice.description ILIKE ?)
605         LIMIT 1
606       )
607 SQL
608     push @values, like($form->{parts_description});
609   }
610
611   my ($cvar_where, @cvar_values) = CVar->build_filter_query('module'         => 'CT',
612                                                             'trans_id_field' => 'c.id',
613                                                             'filter'         => $form,
614                                                            );
615   if ($cvar_where) {
616     $where .= qq| AND ($cvar_where)|;
617     push @values, @cvar_values;
618   }
619
620   my @a = qw(transdate invnumber name);
621   push @a, "employee" if $form->{l_employee};
622   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
623   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
624
625   if (grep({ $_ eq $form->{sort} } qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description))) {
626     $sortorder = $form->{sort} . " $sortdir";
627   }
628
629   $query .= " WHERE $where ORDER BY $sortorder";
630
631   my @result = selectall_hashref_query($form, $dbh, $query, @values);
632
633   $form->{AR} = [ @result ];
634
635   $main::lxdebug->leave_sub();
636 }
637
638 sub get_transdate {
639   $main::lxdebug->enter_sub();
640
641   my ($self, $myconfig, $form) = @_;
642
643   # connect to database
644   my $dbh = SL::DB->client->dbh;
645
646   my $query =
647     "SELECT COALESCE(" .
648     "  (SELECT transdate FROM ar WHERE id = " .
649     "    (SELECT MAX(id) FROM ar) LIMIT 1), " .
650     "  current_date)";
651   ($form->{transdate}) = $dbh->selectrow_array($query);
652
653   $main::lxdebug->leave_sub();
654 }
655
656 sub setup_form {
657   $main::lxdebug->enter_sub();
658
659   my ($self, $form, $for_post_payments) = @_;
660
661   my ($exchangerate, $akey, $j, $k, $index, $taxamount, $totaltax, $taxrate, $diff, $totalwithholding, $withholdingrate,
662       $totalamount, $tax);
663
664   # forex
665   $form->{forex} = $form->{exchangerate};
666   $exchangerate  = $form->{exchangerate} ? $form->{exchangerate} : 1;
667
668   # expected keys: AR, AR_paid, AR_tax, AR_amount
669   foreach my $key (keys %{ $form->{AR_links} }) {
670     $j = 0;
671     $k = 0;
672
673     # if there is a value we have an old entry
674     next unless $form->{acc_trans}{$key};
675
676     # do not use old entries for payments. They come from the form
677     # even if they are not changeable (then they are in hiddens)
678     next if $for_post_payments && $key eq "AR_paid";
679
680     for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
681       if ($key eq "AR_paid") {
682         $j++;
683         $form->{"AR_paid_$j"} = $form->{acc_trans}{$key}->[$i-1]->{accno};
684
685         $form->{"acc_trans_id_$j"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
686         # reverse paid
687         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
688         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
689         $form->{"gldate_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
690         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
691         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
692         $form->{"forex_$j"}           = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
693         $form->{"exchangerate_$i"}    = $form->{"forex_$j"};
694         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
695         $form->{paidaccounts}++;
696
697       } else { # e.g. AR_amount, AR, AR_tax
698
699         $akey = $key;
700         $akey =~ s/AR_//; # e.g. tax, amount, AR, used to store form key tax_$i, amount_$i, ...
701
702         if ($key eq "AR_tax" || $key eq "AP_tax") { # AR_tax
703           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
704           # determine the rounded tax amounts for each account, e.g. tax_1776
705           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
706
707           # 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
708           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
709             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
710             $taxrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
711
712           } else {
713             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
714             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
715           }
716
717           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
718           $form->{"tax_$index"}  = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2); # convert the tax_$i amounts
719           # currently totaltax is the sum of rounded tax amounts, is this correct?
720           $totaltax             += $form->{"tax_$index"};
721
722         } else { # e.g. AR_amount, AR
723           $k++;
724           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
725
726           if ($akey eq 'amount') {
727             $form->{rowcount}++;
728             $totalamount += $form->{"${akey}_$i"};
729
730             $form->{"oldprojectnumber_$k"} = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
731             $form->{"projectnumber_$k"}    = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
732             $form->{taxrate}               = $form->{acc_trans}{$key}->[$i - 1]->{rate};
733             $form->{"project_id_$k"}       = $form->{acc_trans}{$key}->[$i-1]->{project_id};
734
735             $form->{"${key}_chart_id_$k"} = $form->{acc_trans}{$key}->[$i-1]->{chart_id};
736             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
737           }
738         }
739       }
740     }
741   }
742
743   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
744
745   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
746
747     # add tax to amounts and invtotal
748     for my $i (1 .. $form->{rowcount}) {
749       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
750       $tax                  = $form->round_amount($taxamount, 2);
751       $diff                += ($taxamount - $tax);
752       $form->{"amount_$i"} += $form->{"tax_$i"};
753     }
754     $form->{amount_1} += $form->round_amount($diff, 2);
755   }
756
757   $taxamount   = $form->round_amount($taxamount, 2);
758   $form->{tax} = $taxamount;
759
760   $form->{invtotal} = $totalamount + $totaltax;
761
762   $main::lxdebug->leave_sub();
763 }
764
765 sub storno {
766   my ($self, $form, $myconfig, $id) = @_;
767   $main::lxdebug->enter_sub();
768
769   my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
770
771   $::lxdebug->leave_sub;
772   return $rc;
773 }
774
775
776 sub _storno {
777   my ($self, $form, $myconfig, $id) = @_;
778
779   my ($query, $new_id, $storno_row, $acc_trans_rows);
780   my $dbh = SL::DB->client->dbh;
781
782   $query = qq|SELECT nextval('glid')|;
783   ($new_id) = selectrow_query($form, $dbh, $query);
784
785   $query = qq|SELECT * FROM ar WHERE id = ?|;
786   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
787
788   $storno_row->{id}         = $new_id;
789   $storno_row->{storno_id}  = $id;
790   $storno_row->{storno}     = 't';
791   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
792   $storno_row->{amount}    *= -1;
793   $storno_row->{netamount} *= -1;
794   $storno_row->{paid}       = $storno_row->{amount};
795
796   delete @$storno_row{qw(itime mtime)};
797
798   $query = sprintf 'INSERT INTO ar (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
799   do_query($form, $dbh, $query, (values %$storno_row));
800
801   $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
802   do_query($form, $dbh, $query, $id);
803
804   $form->new_lastmtime('ar') if $id == $form->{id};
805
806   # now copy acc_trans entries
807   $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|;
808   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
809
810   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
811   while ($rowref->[-1]{link} =~ /paid/) {
812     splice(@$rowref, -2);
813   }
814
815   for my $row (@$rowref) {
816     delete @$row{qw(itime mtime link acc_trans_id)};
817     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
818     $row->{trans_id}   = $new_id;
819     $row->{amount}    *= -1;
820     do_query($form, $dbh, $query, (values %$row));
821   }
822
823   map { IO->set_datepaid(table => 'ar', id => $_, dbh => $dbh) } ($id, $new_id);
824
825   return 1;
826 }
827
828
829 1;