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