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