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