Inner Join vermeiden um leere Rechnungen nicht zu verlieren
[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::DBUtils;
39 use SL::MoreCommon;
40
41 our (%myconfig, $form);
42
43 sub post_transaction {
44   $main::lxdebug->enter_sub();
45
46   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
47
48   my ($query, $sth, $null, $taxrate, $amount, $tax);
49   my $exchangerate = 0;
50   my $i;
51
52   my @values;
53
54   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
55   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
56
57   # set exchangerate
58   $form->{exchangerate} = ($form->{currency} eq $form->{defaultcurrency}) ? 1 :
59       ( $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy') ||
60         $form->parse_amount($myconfig, $form->{exchangerate}) );
61
62   # get the charts selected
63   map { ($form->{AR_amounts}{"amount_$_"}) = split /--/, $form->{"AR_amount_$_"} } 1 .. $form->{rowcount};
64
65   $form->{AR_amounts}{receivables} = $form->{ARselected};
66   $form->{AR}{receivables}         = $form->{ARselected};
67
68   # parsing
69   for $i (1 .. $form->{rowcount}) {
70     $form->{"amount_$i"} = $form->round_amount($form->parse_amount($myconfig, $form->{"amount_$i"}) * $form->{exchangerate}, 2);
71     $form->{amount}     += $form->{"amount_$i"};
72     $form->{"tax_$i"}    = $form->parse_amount($myconfig, $form->{"tax_$i"});
73   }
74
75   # this is for ar
76   $form->{tax}       = 0;
77   $form->{netamount} = 0;
78   $form->{total_tax} = 0;
79
80   # taxincluded doesn't make sense if there is no amount
81   $form->{taxincluded} = 0 unless $form->{amount};
82
83   for $i (1 .. $form->{rowcount}) {
84     ($form->{"tax_id_$i"}) = split /--/, $form->{"taxchart_$i"};
85
86     $query = qq|SELECT c.accno, t.taxkey, t.rate FROM tax t LEFT JOIN chart c ON (c.id = t.chart_id) WHERE t.id = ? ORDER BY c.accno|;
87     ($form->{AR_amounts}{"tax_$i"}, $form->{"taxkey_$i"}, $form->{"taxrate_$i"}) = selectrow_query($form, $dbh, $query, $form->{"tax_id_$i"});
88
89     if ($form->{taxincluded} *= 1) {
90       $tax = $form->{"korrektur_$i"}
91         ? $form->{"tax_$i"}
92         : $form->{"amount_$i"} - ($form->{"amount_$i"} / ($form->{"taxrate_$i"} + 1)); # should be same as taxrate * amount / (taxrate + 1)
93       $form->{"amount_$i"} = $form->round_amount($form->{"amount_$i"} - $tax, 2);
94       $form->{"tax_$i"}    = $form->round_amount($tax, 2);
95     } else {
96       $form->{"tax_$i"}    = $form->{"amount_$i"} * $form->{"taxrate_$i"} unless $form->{"korrektur_$i"};
97       $form->{"tax_$i"}    = $form->round_amount($form->{"tax_$i"} * $form->{exchangerate}, 2);
98     }
99     $form->{netamount}  += $form->{"amount_$i"};
100     $form->{total_tax}  += $form->{"tax_$i"};
101   }
102
103   # adjust paidaccounts if there is no date in the last row
104   # this does not apply to stornos, where the paid field is set manually
105   unless ($form->{storno}) {
106     $form->{paidaccounts}-- unless $form->{"datepaid_$form->{paidaccounts}"};
107     $form->{paid} = 0;
108
109     # add payments
110     for $i (1 .. $form->{paidaccounts}) {
111       $form->{"paid_$i"} = $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}), 2);
112       $form->{paid}     += $form->{"paid_$i"};
113       $form->{datepaid}  = $form->{"datepaid_$i"};
114     }
115
116     $form->{amount} = $form->{netamount} + $form->{total_tax};
117   }
118   $form->{paid}   = $form->round_amount($form->{paid} * ($form->{exchangerate} || 1), 2);
119
120   ($null, $form->{employee_id}) = split /--/, $form->{employee};
121
122   $form->get_employee($dbh) unless $form->{employee_id};
123
124   # if we have an id delete old records else make one
125   if (!$payments_only) {
126     if ($form->{id}) {
127       # delete detail records
128       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
129       do_query($form, $dbh, $query, $form->{id});
130
131     } else {
132       $query = qq|SELECT nextval('glid')|;
133       ($form->{id}) = selectrow_query($form, $dbh, $query);
134       $query = qq|INSERT INTO ar (id, invnumber, employee_id) VALUES (?, 'dummy', ?)|;
135       do_query($form, $dbh, $query, $form->{id}, $form->{employee_id});
136       $form->{invnumber} = $form->update_defaults($myconfig, "invnumber", $dbh) unless $form->{invnumber};
137     }
138   }
139
140   # update department
141   ($null, $form->{department_id}) = split(/--/, $form->{department});
142   $form->{department_id} *= 1;
143
144   # record last payment date in ar table
145   $form->{datepaid} ||= $form->{transdate} ;
146   my $datepaid = ($form->{paid} != 0) ? $form->{datepaid} : undef;
147
148   # amount for AR account
149   $form->{receivables} = $form->round_amount($form->{amount}, 2) * -1;
150
151   # update exchangerate
152   $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, $form->{exchangerate}, 0)
153     if ($form->{currency} ne $form->{defaultcurrency}) && !$form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy');
154
155   if (!$payments_only) {
156     $query =
157       qq|UPDATE ar set
158            invnumber = ?, ordnumber = ?, transdate = ?, customer_id = ?,
159            taxincluded = ?, amount = ?, duedate = ?, paid = ?, datepaid = ?,
160            netamount = ?, curr = ?, notes = ?, department_id = ?,
161            employee_id = ?, storno = ?, storno_id = ?
162          WHERE id = ?|;
163     my @values = ($form->{invnumber}, $form->{ordnumber}, conv_date($form->{transdate}), conv_i($form->{customer_id}), $form->{taxincluded} ? 't' : 'f', $form->{amount},
164                   conv_date($form->{duedate}), $form->{paid}, conv_date($datepaid), $form->{netamount}, $form->{currency}, $form->{notes}, conv_i($form->{department_id}),
165                   conv_i($form->{employee_id}), $form->{storno} ? 't' : 'f', $form->{storno_id}, conv_i($form->{id}));
166     do_query($form, $dbh, $query, @values);
167
168     # add individual transactions for AR, amount and taxes
169     for $i (1 .. $form->{rowcount}) {
170       if ($form->{"amount_$i"} != 0) {
171         my $project_id = conv_i($form->{"project_id_$i"});
172
173         # insert detail records in acc_trans
174         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey)
175                      VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), ?, ?, ?, ?)|;
176         @values = (conv_i($form->{id}), conv_i($form->{AR_amounts}{"amount_$i"}), conv_i($form->{"amount_$i"}), conv_date($form->{transdate}), $project_id,
177                    conv_i($form->{"taxkey_$i"}));
178         do_query($form, $dbh, $query, @values);
179
180         if ($form->{"tax_$i"} != 0) {
181           # insert detail records in acc_trans
182           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey)
183                        VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), ?, ?, ?, ?)|;
184           @values = (conv_i($form->{id}), conv_i($form->{AR_amounts}{"tax_$i"}), conv_i($form->{"tax_$i"}), conv_date($form->{transdate}), $project_id,
185                      conv_i($form->{"taxkey_$i"}));
186           do_query($form, $dbh, $query, @values);
187         }
188       }
189     }
190
191     # add recievables
192     $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey)
193                  VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
194     @values = (conv_i($form->{id}), $form->{AR_amounts}{receivables}, conv_i($form->{receivables}), conv_date($form->{transdate}), $form->{AR_amounts}{receivables});
195     do_query($form, $dbh, $query, @values);
196
197   } else {
198     # Record paid amount.
199     $query = qq|UPDATE ar SET paid = ?, datepaid = ? WHERE id = ?|;
200     do_query($form, $dbh, $query,  $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
201   }
202
203   # add paid transactions
204   for my $i (1 .. $form->{paidaccounts}) {
205     if ($form->{"paid_$i"} != 0) {
206       my $project_id = conv_i($form->{"paid_project_id_$i"});
207
208       $form->{"AR_paid_$i"} =~ s/\"//g;
209       ($form->{AR}{"paid_$i"}) = split(/--/, $form->{"AR_paid_$i"});
210       $form->{"datepaid_$i"} = $form->{transdate}
211         unless ($form->{"datepaid_$i"});
212
213       $form->{"exchangerate_$i"} = ($form->{currency} eq $form->{defaultcurrency}) ? 1 :
214         ( $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy') ||
215           $form->parse_amount($myconfig, $form->{"exchangerate_$i"}) );
216
217       # if there is no amount and invtotal is zero there is no exchangerate
218       $form->{exchangerate} = $form->{"exchangerate_$i"}
219         if ($form->{amount} == 0 && $form->{netamount} == 0);
220
221       # receivables amount
222       $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
223
224       if ($amount != 0) {
225         # add receivable
226         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey)
227                      VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
228         @values = (conv_i($form->{id}), $form->{AR}{receivables}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR}{receivables});
229         do_query($form, $dbh, $query, @values);
230       }
231
232       if ($form->{"paid_$i"} != 0) {
233         my $project_id = conv_i($form->{"paid_project_id_$i"});
234         # add payment
235         $amount = $form->{"paid_$i"} * -1;
236         $query  = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, project_id, taxkey)
237                      VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
238         @values = (conv_i($form->{id}), $form->{AR}{"paid_$i"}, $amount, conv_date($form->{"datepaid_$i"}), $form->{"source_$i"}, $form->{"memo_$i"}, $project_id, $form->{AR}{"paid_$i"});
239         do_query($form, $dbh, $query, @values);
240
241         # exchangerate difference for payment
242         $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) * -1, 2);
243
244         if ($amount != 0) {
245           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey)
246                        VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
247           @values = (conv_i($form->{id}), $form->{AR}{"paid_$i"}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR}{"paid_$i"});
248           do_query($form, $dbh, $query, @values);
249         }
250
251         # exchangerate gain/loss
252         $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{exchangerate} - $form->{"exchangerate_$i"}) * -1, 2);
253
254         if ($amount != 0) {
255           $accno = ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno};
256           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey)
257                        VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
258           @values = (conv_i($form->{id}), $accno, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $accno);
259           do_query($form, $dbh, $query, @values);
260         }
261       }
262
263       # update exchangerate record
264       $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, $form->{"exchangerate_$i"}, 0)
265         if ($form->{currency} ne $form->{defaultcurrency}) && !$form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
266     }
267   }
268
269   my $rc = 1;
270   if (!$provided_dbh) {
271     $rc = $dbh->commit();
272     $dbh->disconnect();
273   }
274
275   $main::lxdebug->leave_sub() and return $rc;
276 }
277
278 sub _delete_payments {
279   $main::lxdebug->enter_sub();
280
281   my ($self, $form, $dbh) = @_;
282
283   my @delete_acc_trans_ids;
284
285   # Delete old payment entries from acc_trans.
286   my $query =
287     qq|SELECT acc_trans_id
288        FROM acc_trans
289        WHERE (trans_id = ?) AND fx_transaction
290
291        UNION
292
293        SELECT at.acc_trans_id
294        FROM acc_trans at
295        LEFT JOIN chart c ON (at.chart_id = c.id)
296        WHERE (trans_id = ?) AND (c.link LIKE '%AR_paid%')|;
297   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
298
299   $query =
300     qq|SELECT at.acc_trans_id
301        FROM acc_trans at
302        LEFT JOIN chart c ON (at.chart_id = c.id)
303        WHERE (trans_id = ?)
304          AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
305        ORDER BY at.acc_trans_id
306        OFFSET 1|;
307   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
308
309   if (@delete_acc_trans_ids) {
310     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
311     do_query($form, $dbh, $query);
312   }
313
314   $main::lxdebug->leave_sub();
315 }
316
317 sub post_payment {
318   $main::lxdebug->enter_sub();
319
320   my ($self, $myconfig, $form, $locale) = @_;
321
322   # connect to database, turn off autocommit
323   my $dbh = $form->dbconnect_noauto($myconfig);
324
325   my (%payments, $old_form, $row, $item, $query, %keep_vars);
326
327   $old_form = save_form();
328
329   # Delete all entries in acc_trans from prior payments.
330   $self->_delete_payments($form, $dbh);
331
332   # Save the new payments the user made before cleaning up $form.
333   my $payments_re = '^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^paid_project_id_\d+$|^AR_paid_\d+$|^paidaccounts$';
334   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
335
336   # Clean up $form so that old content won't tamper the results.
337   %keep_vars = map { $_, 1 } qw(login password id);
338   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
339
340   # Retrieve the invoice from the database.
341   $form->create_links('AR', $myconfig, 'customer', $dbh);
342
343   # Restore the payment options from the user input.
344   map { $form->{$_} = $payments{$_} } keys %payments;
345
346   # Set up the content of $form in the way that AR::post_transaction() expects.
347
348   $self->setup_form($form);
349
350   ($form->{defaultcurrency}) = selectrow_query($form, $dbh, qq|SELECT curr FROM defaults|);
351   $form->{defaultcurrency}   = (split m/:/, $form->{defaultcurrency})[0];
352   $form->{currency}          = $form->{defaultcurrency} if ($form->{defaultcurrency} && ($form->{currency} =~ m/^\s*$/));
353
354   $form->{exchangerate}      = $form->format_amount($myconfig, $form->{exchangerate});
355
356   # Get the AR accno (which is normally done by Form::create_links()).
357   $query =
358     qq|SELECT c.accno
359        FROM acc_trans at
360        LEFT JOIN chart c ON (at.chart_id = c.id)
361        WHERE (trans_id = ?)
362          AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
363        ORDER BY at.acc_trans_id
364        LIMIT 1|;
365
366   ($form->{ARselected}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
367
368   # Post the new payments.
369   $self->post_transaction($myconfig, $form, $dbh, 1);
370
371   restore_form($old_form);
372
373   my $rc = $dbh->commit();
374   $dbh->disconnect();
375
376   $main::lxdebug->leave_sub();
377
378   return $rc;
379 }
380
381 sub delete_transaction {
382   $main::lxdebug->enter_sub();
383
384   my ($self, $myconfig, $form) = @_;
385
386   # connect to database, turn AutoCommit off
387   my $dbh = $form->dbconnect_noauto($myconfig);
388
389   my $query = qq|DELETE FROM ar WHERE id = ?|;
390   do_query($form, $dbh, $query, $form->{id});
391
392   $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
393   do_query($form, $dbh, $query, $form->{id});
394
395   # commit
396   my $rc = $dbh->commit;
397   $dbh->disconnect;
398
399   $main::lxdebug->leave_sub();
400
401   return $rc;
402 }
403
404 sub ar_transactions {
405   $main::lxdebug->enter_sub();
406
407   my ($self, $myconfig, $form) = @_;
408
409   # connect to database
410   my $dbh = $form->get_standard_dbh($myconfig);
411
412   my @values;
413
414   my $query =
415     qq|SELECT DISTINCT a.id, a.invnumber, a.ordnumber, a.transdate, | .
416     qq|  a.duedate, a.netamount, a.amount, a.paid, | .
417     qq|  a.invoice, a.datepaid, a.terms, a.notes, a.shipvia, | .
418     qq|  a.shippingpoint, a.storno, a.storno_id, a.globalproject_id, | .
419     qq|  a.marge_total, a.marge_percent, | .
420     qq|  a.transaction_description, | .
421     qq|  pr.projectnumber AS globalprojectnumber, | .
422     qq|  c.name, c.customernumber, c.country, c.ustid, | .
423     qq|  e.name AS employee, | .
424     qq|  e2.name AS salesman, | .
425     qq|  tz.description AS taxzone, | .
426     qq|  pt.description AS payment_terms, | .
427     qq{  ( SELECT ch.accno || ' -- ' || ch.description
428            FROM acc_trans at
429            LEFT JOIN chart ch ON ch.id = at.chart_id
430            WHERE ch.link ~ 'AR[[:>:]]'
431             AND at.trans_id = a.id
432             LIMIT 1
433           ) AS charts } .
434     qq|FROM ar a | .
435     qq|JOIN customer c ON (a.customer_id = c.id) | .
436     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
437     qq|LEFT JOIN employee e2 ON (a.salesman_id = e2.id) | .
438     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id)| .
439     qq|LEFT JOIN tax_zones tz ON (tz.id = c.taxzone_id)| .
440     qq|LEFT JOIN payment_terms pt ON (pt.id = c.payment_id)|;
441
442   my $where = "1 = 1";
443   if ($form->{customer_id}) {
444     $where .= " AND a.customer_id = ?";
445     push(@values, $form->{customer_id});
446   } elsif ($form->{customer}) {
447     $where .= " AND c.name ILIKE ?";
448     push(@values, $form->like($form->{customer}));
449   }
450   if ($form->{department}) {
451     my ($null, $department_id) = split /--/, $form->{department};
452     $where .= " AND a.department_id = ?";
453     push(@values, $department_id);
454   }
455   foreach my $column (qw(invnumber ordnumber notes transaction_description)) {
456     if ($form->{$column}) {
457       $where .= " AND a.$column ILIKE ?";
458       push(@values, $form->like($form->{$column}));
459     }
460   }
461   if ($form->{"project_id"}) {
462     $where .=
463       qq|AND ((a.globalproject_id = ?) OR EXISTS | .
464       qq|  (SELECT * FROM invoice i | .
465       qq|   WHERE i.project_id = ? AND i.trans_id = a.id))|;
466     push(@values, $form->{"project_id"}, $form->{"project_id"});
467   }
468
469   if ($form->{transdatefrom}) {
470     $where .= " AND a.transdate >= ?";
471     push(@values, $form->{transdatefrom});
472   }
473   if ($form->{transdateto}) {
474     $where .= " AND a.transdate <= ?";
475     push(@values, $form->{transdateto});
476   }
477   if ($form->{open} || $form->{closed}) {
478     unless ($form->{open} && $form->{closed}) {
479       $where .= " AND a.amount <> a.paid" if ($form->{open});
480       $where .= " AND a.amount = a.paid"  if ($form->{closed});
481     }
482   }
483
484   my @a = qw(transdate invnumber name);
485   push @a, "employee" if $form->{l_employee};
486   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
487   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
488
489   if (grep({ $_ eq $form->{sort} } qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description))) {
490     $sortorder = $form->{sort} . " $sortdir";
491   }
492
493   $query .= " WHERE $where ORDER BY $sortorder";
494
495   my @result = selectall_hashref_query($form, $dbh, $query, @values);
496
497   $form->{AR} = [ @result ];
498
499   $main::lxdebug->leave_sub();
500 }
501
502 sub get_transdate {
503   $main::lxdebug->enter_sub();
504
505   my ($self, $myconfig, $form) = @_;
506
507   # connect to database
508   my $dbh = $form->dbconnect($myconfig);
509
510   my $query =
511     "SELECT COALESCE(" .
512     "  (SELECT transdate FROM ar WHERE id = " .
513     "    (SELECT MAX(id) FROM ar) LIMIT 1), " .
514     "  current_date)";
515   ($form->{transdate}) = $dbh->selectrow_array($query);
516
517   $dbh->disconnect;
518
519   $main::lxdebug->leave_sub();
520 }
521
522 sub setup_form {
523   $main::lxdebug->enter_sub();
524
525   my ($self, $form) = @_;
526
527   my ($exchangerate, $key, $akey, $i, $j, $k, $index, $taxamount, $totaltax, $taxrate, $diff);
528
529   # forex
530   $form->{forex} = $form->{exchangerate};
531   $exchangerate  = $form->{exchangerate} ? $form->{exchangerate} : 1;
532
533   foreach $key (keys %{ $form->{AR_links} }) {
534     # if there is a value we have an old entry
535     $j = 0;
536     $k = 0;
537
538     for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
539       if ($key eq "AR_paid") {
540         $j++;
541         $form->{"AR_paid_$j"} = $form->{acc_trans}{$key}->[$i-1]->{accno};
542
543         # reverse paid
544         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
545         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
546         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
547         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
548         $form->{"forex_$j"}           = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
549         $form->{"exchangerate_$i"}    = $form->{"forex_$j"};
550         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
551         $form->{paidaccounts}++;
552
553       } else {
554
555         $akey = $key;
556         $akey =~ s/AR_//;
557
558         if ($key eq "AR_tax" || $key eq "AP_tax") {
559           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
560           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
561
562           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
563             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
564             $taxrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
565
566           } else {
567             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
568             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
569           }
570
571           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
572           $form->{"tax_$index"}  = $form->{acc_trans}{$key}->[$i - 1]->{amount};
573           $totaltax             += $form->{"tax_$index"};
574
575         } else {
576           $k++;
577           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
578
579           if ($akey eq 'amount') {
580             $form->{rowcount}++;
581             $totalamount += $form->{"${akey}_$i"};
582
583             $form->{"oldprojectnumber_$k"} = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
584             $form->{"projectnumber_$k"}    = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
585             $form->{taxrate}               = $form->{acc_trans}{$key}->[$i - 1]->{rate};
586             $form->{"project_id_$k"}       = $form->{acc_trans}{$key}->[$i-1]->{project_id};
587           }
588
589           $form->{"${key}_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
590
591           if ($akey eq "AR") {
592             $form->{ARselected} = $form->{acc_trans}{$key}->[$i-1]->{accno};
593
594           } elsif ($akey eq "amount") {
595             $form->{"${key}_$k"}   = $form->{acc_trans}{$key}->[$i-1]->{accno} . "--" . $form->{acc_trans}{$key}->[$i-1]->{id};
596             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
597           }
598         }
599       }
600     }
601   }
602
603   $form->{taxincluded}  = $taxincluded if ($form->{id});
604   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
605
606   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
607
608     # add tax to amounts and invtotal
609     for $i (1 .. $form->{rowcount}) {
610       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
611       $tax                  = $form->round_amount($taxamount, 2);
612       $diff                += ($taxamount - $tax);
613       $form->{"amount_$i"} += $form->{"tax_$i"};
614     }
615     $form->{amount_1} += $form->round_amount($diff, 2);
616   }
617
618   $taxamount   = $form->round_amount($taxamount, 2);
619   $form->{tax} = $taxamount;
620
621   $form->{invtotal} = $totalamount + $totaltax;
622
623   $main::lxdebug->leave_sub();
624 }
625
626 sub storno {
627   $main::lxdebug->enter_sub();
628
629   my ($self, $form, $myconfig, $id) = @_;
630
631   my ($query, $new_id, $storno_row, $acc_trans_rows);
632   my $dbh = $form->get_standard_dbh($myconfig);
633
634   $query = qq|SELECT nextval('glid')|;
635   ($new_id) = selectrow_query($form, $dbh, $query);
636
637   $query = qq|SELECT * FROM ar WHERE id = ?|;
638   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
639
640   $storno_row->{id}         = $new_id;
641   $storno_row->{storno_id}  = $id;
642   $storno_row->{storno}     = 't';
643   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
644   $storno_row->{amount}    *= -1;
645   $storno_row->{netamount} *= -1;
646   $storno_row->{paid}       = $storno_row->{amount};
647
648   delete @$storno_row{qw(itime mtime)};
649
650   $query = sprintf 'INSERT INTO ar (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
651   do_query($form, $dbh, $query, (values %$storno_row));
652
653   $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
654   do_query($form, $dbh, $query, $id);
655
656   # now copy acc_trans entries
657   $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|;
658   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
659
660   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
661   while ($rowref->[-1]{link} =~ /paid/) {
662     splice(@$rowref, -2);
663   }
664
665   for my $row (@$rowref) {
666     delete @$row{qw(itime mtime link)};
667     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
668     $row->{trans_id}   = $new_id;
669     $row->{amount}    *= -1;
670     do_query($form, $dbh, $query, (values %$row));
671   }
672
673   $dbh->commit;
674
675   $main::lxdebug->leave_sub();
676 }
677
678
679 1;
680