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