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