single-dbh: Fehler in Transaktionen immer weiterwerfen
[kivitendo-erp.git] / SL / GL.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 # General ledger backend code
32 #
33 # CHANGE LOG:
34 #   DS. 2000-07-04  Created
35 #   DS. 2001-06-12  Changed relations from accno to chart_id
36 #
37 #======================================================================
38
39 package GL;
40
41 use Data::Dumper;
42 use SL::DATEV qw(:CONSTANTS);
43 use SL::DBUtils;
44 use SL::Util qw(trim);
45 use SL::DB;
46
47 use strict;
48
49 sub delete_transaction {
50   my ($self, $myconfig, $form) = @_;
51   $main::lxdebug->enter_sub();
52
53   SL::DB->with_transaction(sub {
54     do_query($form, SL::DB->client->dbh, qq|DELETE FROM gl WHERE id = ?|, conv_i($form->{id}));
55     1;
56   }) or do { die SL::DB->client->error };
57
58   $main::lxdebug->leave_sub();
59 }
60
61 sub post_transaction {
62   my ($self, $myconfig, $form) = @_;
63   $main::lxdebug->enter_sub();
64
65   my $rc = SL::DB->client->with_transaction(\&_post_transaction, $self, $myconfig, $form);
66
67   $::lxdebug->leave_sub;
68   return $rc;
69 }
70
71 sub _post_transaction {
72   my ($self, $myconfig, $form) = @_;
73   $main::lxdebug->enter_sub();
74
75   my ($debit, $credit) = (0, 0);
76   my $project_id;
77
78   my $i;
79
80   my $dbh = SL::DB->client->dbh;
81
82   # post the transaction
83   # make up a unique handle and store in reference field
84   # then retrieve the record based on the unique handle to get the id
85   # replace the reference field with the actual variable
86   # add records to acc_trans
87
88   # if there is a $form->{id} replace the old transaction
89   # delete all acc_trans entries and add the new ones
90
91   if (!$form->{taxincluded}) {
92     $form->{taxincluded} = 0;
93   }
94
95   my ($query, $sth, @values, $taxkey, $rate, $posted);
96
97   if ($form->{id}) {
98
99     # delete individual transactions
100     $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
101     @values = (conv_i($form->{id}));
102     do_query($form, $dbh, $query, @values);
103
104   } else {
105     $query = qq|SELECT nextval('glid')|;
106     ($form->{id}) = selectrow_query($form, $dbh, $query);
107
108     $query =
109       qq|INSERT INTO gl (id, employee_id) | .
110       qq|VALUES (?, (SELECT id FROM employee WHERE login = ?))|;
111     @values = ($form->{id}, $::myconfig{login});
112     do_query($form, $dbh, $query, @values);
113   }
114
115   my ($null, $department_id) = split(/--/, $form->{department});
116
117   $form->{ob_transaction} *= 1;
118   $form->{cb_transaction} *= 1;
119
120   $query =
121     qq|UPDATE gl SET
122          reference = ?, description = ?, notes = ?,
123          transdate = ?, department_id = ?, taxincluded = ?,
124          storno = ?, storno_id = ?, ob_transaction = ?, cb_transaction = ?
125        WHERE id = ?|;
126
127   @values = ($form->{reference}, $form->{description}, $form->{notes},
128              conv_date($form->{transdate}), conv_i($department_id), $form->{taxincluded} ? 't' : 'f',
129              $form->{storno} ? 't' : 'f', conv_i($form->{storno_id}), $form->{ob_transaction} ? 't' : 'f', $form->{cb_transaction} ? 't' : 'f',
130              conv_i($form->{id}));
131   do_query($form, $dbh, $query, @values);
132
133   # insert acc_trans transactions
134   for $i (1 .. $form->{rowcount}) {
135     # extract accno
136     my ($accno) = split(/--/, $form->{"accno_$i"});
137     ($form->{"tax_id_$i"}) = split(/--/, $form->{"taxchart_$i"});
138     if ($form->{"tax_id_$i"} ne "") {
139       $query = qq|SELECT taxkey, rate FROM tax WHERE id = ?|;
140       ($taxkey, $rate) = selectrow_query($form, $dbh, $query, conv_i($form->{"tax_id_$i"}));
141     }
142
143     my $amount = 0;
144     my $debit  = $form->{"debit_$i"};
145     my $credit = $form->{"credit_$i"};
146     my $tax    = $form->{"tax_$i"};
147
148     if ($credit) {
149       $amount = $credit;
150       $posted = 0;
151     }
152     if ($debit) {
153       $amount = $debit * -1;
154       $tax    = $tax * -1;
155       $posted = 0;
156     }
157
158     $project_id = conv_i($form->{"project_id_$i"});
159
160     # if there is an amount, add the record
161     if ($amount != 0) {
162       $query =
163         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
164                                   source, memo, project_id, taxkey, ob_transaction, cb_transaction, tax_id, chart_link)
165            VALUES (?, (SELECT id FROM chart WHERE accno = ?),
166                    ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT link FROM chart WHERE accno = ?))|;
167       @values = (conv_i($form->{id}), $accno, $amount, conv_date($form->{transdate}),
168                  $form->{"source_$i"}, $form->{"memo_$i"}, $project_id, $taxkey, $form->{ob_transaction} ? 't' : 'f', $form->{cb_transaction} ? 't' : 'f', conv_i($form->{"tax_id_$i"}), $accno);
169       do_query($form, $dbh, $query, @values);
170     }
171
172     if ($tax != 0) {
173       # add taxentry
174       $query =
175         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
176                                   source, memo, project_id, taxkey, tax_id, chart_link)
177            VALUES (?, (SELECT chart_id FROM tax WHERE id = ?),
178                    ?, ?, ?, ?, ?, ?, ?, (SELECT link
179                                          FROM chart
180                                          WHERE id = (SELECT chart_id
181                                                      FROM tax
182                                                      WHERE id = ?)))|;
183       @values = (conv_i($form->{id}), conv_i($form->{"tax_id_$i"}),
184                  $tax, conv_date($form->{transdate}), $form->{"source_$i"},
185                  $form->{"memo_$i"}, $project_id, $taxkey, conv_i($form->{"tax_id_$i"}), conv_i($form->{"tax_id_$i"}));
186       do_query($form, $dbh, $query, @values);
187     }
188   }
189
190   if ($form->{storno} && $form->{storno_id}) {
191     do_query($form, $dbh, qq|UPDATE gl SET storno = 't' WHERE id = ?|, conv_i($form->{storno_id}));
192   }
193
194   # safety check datev export
195   if ($::instance_conf->get_datev_check_on_gl_transaction) {
196     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
197     $transdate  ||= DateTime->today;
198
199     my $datev = SL::DATEV->new(
200       exporttype => DATEV_ET_BUCHUNGEN,
201       format     => DATEV_FORMAT_KNE,
202       dbh        => $dbh,
203       trans_id   => $form->{id},
204     );
205
206     $datev->export;
207
208     if ($datev->errors) {
209       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
210     }
211   }
212
213   return 1;
214 }
215
216 sub all_transactions {
217   my ($self, $myconfig, $form) = @_;
218   $main::lxdebug->enter_sub();
219
220   # connect to database
221   my $dbh = $form->dbconnect($myconfig);
222   my ($query, $sth, $source, $null, $space);
223
224   my ($glwhere, $arwhere, $apwhere) = ("1 = 1", "1 = 1", "1 = 1");
225   my (@glvalues, @arvalues, @apvalues);
226
227   if ($form->{reference}) {
228     $glwhere .= qq| AND g.reference ILIKE ?|;
229     $arwhere .= qq| AND a.invnumber ILIKE ?|;
230     $apwhere .= qq| AND a.invnumber ILIKE ?|;
231     push(@glvalues, like($form->{reference}));
232     push(@arvalues, like($form->{reference}));
233     push(@apvalues, like($form->{reference}));
234   }
235
236   if ($form->{department}) {
237     my ($null, $department) = split /--/, $form->{department};
238     $glwhere .= qq| AND g.department_id = ?|;
239     $arwhere .= qq| AND a.department_id = ?|;
240     $apwhere .= qq| AND a.department_id = ?|;
241     push(@glvalues, $department);
242     push(@arvalues, $department);
243     push(@apvalues, $department);
244   }
245
246   if ($form->{source}) {
247     $glwhere .= " AND ac.trans_id IN (SELECT trans_id from acc_trans WHERE source ILIKE ?)";
248     $arwhere .= " AND ac.trans_id IN (SELECT trans_id from acc_trans WHERE source ILIKE ?)";
249     $apwhere .= " AND ac.trans_id IN (SELECT trans_id from acc_trans WHERE source ILIKE ?)";
250     push(@glvalues, like($form->{source}));
251     push(@arvalues, like($form->{source}));
252     push(@apvalues, like($form->{source}));
253   }
254
255   # default Datumseinschränkung falls nicht oder falsch übergeben (sollte nie passieren)
256   $form->{datesort} = 'transdate' unless $form->{datesort} =~ /^(transdate|gldate)$/;
257
258   if (trim($form->{datefrom})) {
259     $glwhere .= " AND ac.$form->{datesort} >= ?";
260     $arwhere .= " AND ac.$form->{datesort} >= ?";
261     $apwhere .= " AND ac.$form->{datesort} >= ?";
262     push(@glvalues, trim($form->{datefrom}));
263     push(@arvalues, trim($form->{datefrom}));
264     push(@apvalues, trim($form->{datefrom}));
265   }
266
267   if (trim($form->{dateto})) {
268     $glwhere .= " AND ac.$form->{datesort} <= ?";
269     $arwhere .= " AND ac.$form->{datesort} <= ?";
270     $apwhere .= " AND ac.$form->{datesort} <= ?";
271     push(@glvalues, trim($form->{dateto}));
272     push(@arvalues, trim($form->{dateto}));
273     push(@apvalues, trim($form->{dateto}));
274   }
275
276   if (trim($form->{description})) {
277     $glwhere .= " AND g.description ILIKE ?";
278     $arwhere .= " AND ct.name ILIKE ?";
279     $apwhere .= " AND ct.name ILIKE ?";
280     push(@glvalues, like($form->{description}));
281     push(@arvalues, like($form->{description}));
282     push(@apvalues, like($form->{description}));
283   }
284
285   if ($form->{employee_id}) {
286     $glwhere .= " AND g.employee_id = ? ";
287     $arwhere .= " AND a.employee_id = ? ";
288     $apwhere .= " AND a.employee_id = ? ";
289     push(@glvalues, conv_i($form->{employee_id}));
290     push(@arvalues, conv_i($form->{employee_id}));
291     push(@apvalues, conv_i($form->{employee_id}));
292   }
293
294   if (trim($form->{notes})) {
295     $glwhere .= " AND g.notes ILIKE ?";
296     $arwhere .= " AND a.notes ILIKE ?";
297     $apwhere .= " AND a.notes ILIKE ?";
298     push(@glvalues, like($form->{notes}));
299     push(@arvalues, like($form->{notes}));
300     push(@apvalues, like($form->{notes}));
301   }
302
303   if ($form->{accno}) {
304     $glwhere .= " AND c.accno = '$form->{accno}'";
305     $arwhere .= " AND c.accno = '$form->{accno}'";
306     $apwhere .= " AND c.accno = '$form->{accno}'";
307   }
308
309   if ($form->{category} ne 'X') {
310     $glwhere .= qq| AND g.id in (SELECT trans_id FROM acc_trans ac2 WHERE ac2.chart_id IN (SELECT id FROM chart c2 WHERE c2.category = ?))|;
311     $arwhere .= qq| AND a.id in (SELECT trans_id FROM acc_trans ac2 WHERE ac2.chart_id IN (SELECT id FROM chart c2 WHERE c2.category = ?))|;
312     $apwhere .= qq| AND a.id in (SELECT trans_id FROM acc_trans ac2 WHERE ac2.chart_id IN (SELECT id FROM chart c2 WHERE c2.category = ?))|;
313     push(@glvalues, $form->{category});
314     push(@arvalues, $form->{category});
315     push(@apvalues, $form->{category});
316   }
317
318   if ($form->{project_id}) {
319     $glwhere .= qq| AND g.id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE project_id = ?)|;
320     $arwhere .=
321       qq| AND ((a.globalproject_id = ?) OR
322                (a.id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE project_id = ?)))|;
323     $apwhere .=
324       qq| AND ((a.globalproject_id = ?) OR
325                (a.id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE project_id = ?)))|;
326     my $project_id = conv_i($form->{project_id});
327     push(@glvalues, $project_id);
328     push(@arvalues, $project_id, $project_id);
329     push(@apvalues, $project_id, $project_id);
330   }
331
332   my ($project_columns, $project_join);
333   if ($form->{"l_projectnumbers"}) {
334     $project_columns = qq|, ac.project_id, pr.projectnumber|;
335     $project_join = qq|LEFT JOIN project pr ON (ac.project_id = pr.id)|;
336   }
337
338   if ($form->{accno}) {
339     # get category for account
340     $query = qq|SELECT category FROM chart WHERE accno = ?|;
341     ($form->{ml}) = selectrow_query($form, $dbh, $query, $form->{accno});
342
343     if ($form->{datefrom}) {
344       $query =
345         qq|SELECT SUM(ac.amount)
346            FROM acc_trans ac
347            LEFT JOIN chart c ON (ac.chart_id = c.id)
348            WHERE (c.accno = ?) AND (ac.$form->{datesort} < ?)|;
349       ($form->{balance}) = selectrow_query($form, $dbh, $query, $form->{accno}, conv_date($form->{datefrom}));
350     }
351   }
352
353   my %sort_columns =  (
354     'id'           => [ qw(id)                   ],
355     'transdate'    => [ qw(transdate id)         ],
356     'gldate'       => [ qw(gldate id)         ],
357     'reference'    => [ qw(lower_reference id)   ],
358     'description'  => [ qw(lower_description id) ],
359     'accno'        => [ qw(accno transdate id)   ],
360     );
361   my %lowered_columns =  (
362     'reference'       => { 'gl' => 'g.reference',   'arap' => 'a.invnumber', },
363     'source'          => { 'gl' => 'ac.source',     'arap' => 'ac.source',   },
364     'description'     => { 'gl' => 'g.description', 'arap' => 'ct.name',     },
365     );
366
367   # sortdir = sort direction (ascending or descending)
368   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
369   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : $form->{datesort};  # default used to be transdate
370   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
371
372   my %columns_for_sorting = ( 'gl' => '', 'arap' => '', );
373   foreach my $spec (@{ $sort_columns{$sortkey} }) {
374     next if ($spec !~ m/^lower_(.*)$/);
375
376     my $column = $1;
377     map { $columns_for_sorting{$_} .= sprintf(', lower(%s) AS lower_%s', $lowered_columns{$column}->{$_}, $column) } qw(gl arap);
378   }
379
380   $query =
381     qq|SELECT
382         ac.acc_trans_id, g.id, 'gl' AS type, FALSE AS invoice, g.reference, ac.taxkey, c.link,
383         g.description, ac.transdate, ac.gldate, ac.source, ac.trans_id,
384         ac.amount, c.accno, g.notes, t.chart_id,
385         CASE WHEN (COALESCE(e.name, '') = '') THEN e.login ELSE e.name END AS employee
386         $project_columns
387         $columns_for_sorting{gl}
388       FROM gl g
389       LEFT JOIN employee e ON (g.employee_id = e.id),
390       acc_trans ac $project_join, chart c
391       LEFT JOIN tax t ON (t.chart_id = c.id)
392       WHERE $glwhere
393         AND (ac.chart_id = c.id)
394         AND (g.id = ac.trans_id)
395
396       UNION
397
398       SELECT ac.acc_trans_id, a.id, 'ar' AS type, a.invoice, a.invnumber, ac.taxkey, c.link,
399         ct.name, ac.transdate, ac.gldate, ac.source, ac.trans_id,
400         ac.amount, c.accno, a.notes, t.chart_id,
401         CASE WHEN (COALESCE(e.name, '') = '') THEN e.login ELSE e.name END AS employee
402         $project_columns
403         $columns_for_sorting{arap}
404       FROM ar a
405       LEFT JOIN employee e ON (a.employee_id = e.id),
406       acc_trans ac $project_join, customer ct, chart c
407       LEFT JOIN tax t ON (t.chart_id=c.id)
408       WHERE $arwhere
409         AND (ac.chart_id = c.id)
410         AND (a.customer_id = ct.id)
411         AND (a.id = ac.trans_id)
412
413       UNION
414
415       SELECT ac.acc_trans_id, a.id, 'ap' AS type, a.invoice, a.invnumber, ac.taxkey, c.link,
416         ct.name, ac.transdate, ac.gldate, ac.source, ac.trans_id,
417         ac.amount, c.accno, a.notes, t.chart_id,
418         CASE WHEN (COALESCE(e.name, '') = '') THEN e.login ELSE e.name END AS employee
419         $project_columns
420         $columns_for_sorting{arap}
421       FROM ap a
422       LEFT JOIN employee e ON (a.employee_id = e.id),
423       acc_trans ac $project_join, vendor ct, chart c
424       LEFT JOIN tax t ON (t.chart_id=c.id)
425       WHERE $apwhere
426         AND (ac.chart_id = c.id)
427         AND (a.vendor_id = ct.id)
428         AND (a.id = ac.trans_id)
429
430       ORDER BY $sortorder, acc_trans_id $sortdir|;
431 #      ORDER BY gldate DESC, id DESC, acc_trans_id DESC
432
433   my @values = (@glvalues, @arvalues, @apvalues);
434
435   # Show all $query in Debuglevel LXDebug::QUERY
436   my $callingdetails = (caller (0))[3];
437   dump_query(LXDebug->QUERY(), "$callingdetails", $query, @values);
438
439   $sth = prepare_execute_query($form, $dbh, $query, @values);
440   my $trans_id  = "";
441   my $trans_id2 = "";
442   my $balance;
443
444   my ($i, $j, $k, $l, $ref, $ref2);
445
446   $form->{GL} = [];
447   while (my $ref0 = $sth->fetchrow_hashref("NAME_lc")) {
448
449     $trans_id = $ref0->{id};
450
451     my $source = $ref0->{source};
452     undef($ref0->{source});
453
454     if ($trans_id != $trans_id2) { # first line of a booking
455
456       if ($trans_id2) {
457         push(@{ $form->{GL} }, $ref);
458         $balance = 0;
459       }
460
461       $ref       = $ref0;
462       $trans_id2 = $ref->{id};
463
464       # gl
465       if ($ref->{type} eq "gl") {
466         $ref->{module} = "gl";
467       }
468
469       # ap
470       if ($ref->{type} eq "ap") {
471         if ($ref->{invoice}) {
472           $ref->{module} = "ir";
473         } else {
474           $ref->{module} = "ap";
475         }
476       }
477
478       # ar
479       if ($ref->{type} eq "ar") {
480         if ($ref->{invoice}) {
481           $ref->{module} = "is";
482         } else {
483           $ref->{module} = "ar";
484         }
485       }
486
487       $ref->{"projectnumbers"} = {};
488       $ref->{"projectnumbers"}->{$ref->{"projectnumber"}} = 1 if ($ref->{"projectnumber"});
489
490       $balance = $ref->{amount};
491
492       # Linenumbers of General Ledger
493       $k       = 0; # Debit      # AP      # Soll
494       $l       = 0; # Credit     # AR      # Haben
495       $i       = 0; # Debit Tax  # AP_tax  # VSt
496       $j       = 0; # Credit Tax # AR_tax  # USt
497
498       if ($ref->{chart_id} > 0) { # all tax accounts first line, no line increasing
499         if ($ref->{amount} < 0) {
500           if ($ref->{link} =~ /AR_tax/) {
501             $ref->{credit_tax}{$j}       = $ref->{amount};
502             $ref->{credit_tax_accno}{$j} = $ref->{accno};
503          }
504           if ($ref->{link} =~ /AP_tax/) {
505             $ref->{debit_tax}{$i}       = $ref->{amount} * -1;
506             $ref->{debit_tax_accno}{$i} = $ref->{accno};
507           }
508         } else {
509           if ($ref->{link} =~ /AR_tax/) {
510             $ref->{credit_tax}{$j}       = $ref->{amount};
511             $ref->{credit_tax_accno}{$j} = $ref->{accno};
512           }
513           if ($ref->{link} =~ /AP_tax/) {
514             $ref->{debit_tax}{$i}       = $ref->{amount} * -1;
515             $ref->{debit_tax_accno}{$i} = $ref->{accno};
516           }
517         }
518       } else { #all other accounts first line
519
520         if ($ref->{amount} < 0) {
521           $ref->{debit}{$k}        = $ref->{amount} * -1;
522           $ref->{debit_accno}{$k}  = $ref->{accno};
523           $ref->{debit_taxkey}{$k} = $ref->{taxkey};
524           $ref->{ac_transdate}{$k} = $ref->{transdate};
525           $ref->{source}{$k}       = $source;
526         } else {
527           $ref->{credit}{$l}        = $ref->{amount} * 1;
528           $ref->{credit_accno}{$l}  = $ref->{accno};
529           $ref->{credit_taxkey}{$l} = $ref->{taxkey};
530           $ref->{ac_transdate}{$l}  = $ref->{transdate};
531           $ref->{source}{$l}        = $source;
532         }
533       }
534
535     } else { # following lines of a booking, line increasing
536
537       $ref2      = $ref0;
538 #      $trans_old = $trans_id2;   # doesn't seem to be used anymore
539       $trans_id2 = $ref2->{id};
540
541       $balance =
542         (int($balance * 100000) + int(100000 * $ref2->{amount})) / 100000;
543
544       $ref->{"projectnumbers"}->{$ref2->{"projectnumber"}} = 1 if ($ref2->{"projectnumber"});
545
546       if ($ref2->{chart_id} > 0) { # all tax accounts, following lines
547         if ($ref2->{amount} < 0) {
548           if ($ref2->{link} =~ /AR_tax/) {
549             if ($ref->{credit_tax_accno}{$j} ne "") {
550               $j++;
551             }
552             $ref->{credit_tax}{$j}       = $ref2->{amount};
553             $ref->{credit_tax_accno}{$j} = $ref2->{accno};
554           }
555           if ($ref2->{link} =~ /AP_tax/) {
556             if ($ref->{debit_tax_accno}{$i} ne "") {
557               $i++;
558             }
559             $ref->{debit_tax}{$i}       = $ref2->{amount} * -1;
560             $ref->{debit_tax_accno}{$i} = $ref2->{accno};
561           }
562         } else {
563           if ($ref2->{link} =~ /AR_tax/) {
564             if ($ref->{credit_tax_accno}{$j} ne "") {
565               $j++;
566             }
567             $ref->{credit_tax}{$j}       = $ref2->{amount};
568             $ref->{credit_tax_accno}{$j} = $ref2->{accno};
569           }
570           if ($ref2->{link} =~ /AP_tax/) {
571             if ($ref->{debit_tax_accno}{$i} ne "") {
572               $i++;
573             }
574             $ref->{debit_tax}{$i}       = $ref2->{amount} * -1;
575             $ref->{debit_tax_accno}{$i} = $ref2->{accno};
576           }
577         }
578       } else { # all other accounts, following lines
579         if ($ref2->{amount} < 0) {
580           if ($ref->{debit_accno}{$k} ne "") {
581             $k++;
582           }
583           if ($ref->{source}{$k} ne "") {
584             $space = " | ";
585           } else {
586             $space = "";
587           }
588           $ref->{debit}{$k}        = $ref2->{amount} * - 1;
589           $ref->{debit_accno}{$k}  = $ref2->{accno};
590           $ref->{debit_taxkey}{$k} = $ref2->{taxkey};
591           $ref->{ac_transdate}{$k} = $ref2->{transdate};
592           $ref->{source}{$k}       = $source . $space . $ref->{source}{$k};
593         } else {
594           if ($ref->{credit_accno}{$l} ne "") {
595             $l++;
596           }
597           if ($ref->{source}{$l} ne "") {
598             $space = " | ";
599           } else {
600             $space = "";
601           }
602           $ref->{credit}{$l}        = $ref2->{amount};
603           $ref->{credit_accno}{$l}  = $ref2->{accno};
604           $ref->{credit_taxkey}{$l} = $ref2->{taxkey};
605           $ref->{ac_transdate}{$l}  = $ref2->{transdate};
606           $ref->{source}{$l}        = $ref->{source}{$l} . $space . $source;
607         }
608       }
609     }
610   }
611
612   push @{ $form->{GL} }, $ref;
613   $sth->finish;
614
615   if ($form->{accno}) {
616     $query = qq|SELECT c.description FROM chart c WHERE c.accno = ?|;
617     ($form->{account_description}) = selectrow_query($form, $dbh, $query, $form->{accno});
618   }
619
620   $dbh->disconnect;
621
622   $main::lxdebug->leave_sub();
623 }
624
625 sub transaction {
626   my ($self, $myconfig, $form) = @_;
627   $main::lxdebug->enter_sub();
628
629   my ($query, $sth, $ref, @values);
630
631   # connect to database
632   my $dbh = $form->dbconnect($myconfig);
633
634   $query = qq|SELECT closedto, revtrans FROM defaults|;
635   ($form->{closedto}, $form->{revtrans}) = selectrow_query($form, $dbh, $query);
636
637   $query = qq|SELECT id, gldate
638               FROM gl
639               WHERE id = (SELECT max(id) FROM gl)|;
640   ($form->{previous_id}, $form->{previous_gldate}) = selectrow_query($form, $dbh, $query);
641
642   if ($form->{id}) {
643     $query =
644       qq|SELECT g.reference, g.description, g.notes, g.transdate, g.storno, g.storno_id,
645            d.description AS department, e.name AS employee, g.taxincluded, g.gldate,
646          g.ob_transaction, g.cb_transaction
647          FROM gl g
648          LEFT JOIN department d ON (d.id = g.department_id)
649          LEFT JOIN employee e ON (e.id = g.employee_id)
650          WHERE g.id = ?|;
651     $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
652     map { $form->{$_} = $ref->{$_} } keys %$ref;
653
654     # retrieve individual rows
655     $query =
656       qq|SELECT c.accno, t.taxkey AS accnotaxkey, a.amount, a.memo, a.source,
657            a.transdate, a.cleared, a.project_id, p.projectnumber,
658            a.taxkey, t.rate AS taxrate, t.id,
659            (SELECT c1.accno
660             FROM chart c1, tax t1
661             WHERE (t1.id = t.id) AND (c1.id = t.chart_id)) AS taxaccno,
662            (SELECT tk.tax_id
663             FROM taxkeys tk
664             WHERE (tk.chart_id = a.chart_id) AND (tk.startdate <= a.transdate)
665             ORDER BY tk.startdate desc LIMIT 1) AS tax_id
666          FROM acc_trans a
667          JOIN chart c ON (c.id = a.chart_id)
668          LEFT JOIN project p ON (p.id = a.project_id)
669          LEFT JOIN tax t ON (t.id = a.tax_id)
670          WHERE (a.trans_id = ?)
671            AND (a.fx_transaction = '0')
672          ORDER BY a.acc_trans_id, a.transdate|;
673     $form->{GL} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
674
675   } else {
676     $query =
677       qq|SELECT COALESCE(
678            (SELECT transdate
679             FROM gl
680             WHERE id = (SELECT MAX(id) FROM gl)
681             LIMIT 1),
682            current_date)|;
683     ($form->{transdate}) = selectrow_query($form, $dbh, $query);
684   }
685
686   # get tax description
687   $query = qq|SELECT * FROM tax ORDER BY taxkey|;
688   $form->{TAX} = selectall_hashref_query($form, $dbh, $query);
689
690   # get chart of accounts
691   $query =
692     qq|SELECT c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id
693        FROM chart c
694        LEFT JOIN taxkeys tk ON (tk.id =
695          (SELECT id
696           FROM taxkeys
697           WHERE (taxkeys.chart_id = c.id)
698             AND (startdate <= ?)
699           ORDER BY startdate DESC
700           LIMIT 1))
701        ORDER BY c.accno|;
702   $form->{chart} = selectall_hashref_query($form, $dbh, $query, conv_date($form->{transdate}));
703
704   $dbh->disconnect;
705
706   $main::lxdebug->leave_sub();
707 }
708
709 sub storno {
710   my ($self, $form, $myconfig, $id) = @_;
711   $main::lxdebug->enter_sub();
712
713   my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
714
715   $::lxdebug->leave_sub;
716   return $rc;
717 }
718
719 sub _storno {
720   my ($self, $form, $myconfig, $id) = @_;
721
722   my ($query, $new_id, $storno_row, $acc_trans_rows);
723   my $dbh = SL::DB->client->dbh;
724
725   $query = qq|SELECT nextval('glid')|;
726   ($new_id) = selectrow_query($form, $dbh, $query);
727
728   $query = qq|SELECT * FROM gl WHERE id = ?|;
729   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
730
731   $storno_row->{id}          = $new_id;
732   $storno_row->{storno_id}   = $id;
733   $storno_row->{storno}      = 't';
734   $storno_row->{reference}   = 'Storno-' . $storno_row->{reference};
735
736   $query = qq|SELECT id FROM employee WHERE login = ?|;
737   my ($employee_id) = selectrow_query($form, $dbh, $query, $::myconfig{login});
738   $storno_row->{employee_id} = $employee_id;
739
740   delete @$storno_row{qw(itime mtime gldate)};
741
742   $query = sprintf 'INSERT INTO gl (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
743   do_query($form, $dbh, $query, (values %$storno_row));
744
745   $query = qq|UPDATE gl SET storno = 't' WHERE id = ?|;
746   do_query($form, $dbh, $query, $id);
747
748   # now copy acc_trans entries
749   $query = qq|SELECT * FROM acc_trans WHERE trans_id = ?|;
750   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
751
752   for my $row (@$rowref) {
753     delete @$row{qw(itime mtime acc_trans_id gldate)};
754     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
755     $row->{trans_id}   = $new_id;
756     $row->{amount}    *= -1;
757     do_query($form, $dbh, $query, (values %$row));
758   }
759
760   return 1;
761 }
762
763 sub get_chart_balances {
764   $main::lxdebug->enter_sub();
765
766   my $self     = shift;
767   my %params   = @_;
768
769   Common::check_params(\%params, qw(charts));
770
771   my $myconfig = \%main::myconfig;
772   my $form     = $main::form;
773
774   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
775
776   my @ids      = map { $_->{id} } @{ $params{charts} };
777
778   if (!@ids) {
779     $main::lxdebug->leave_sub();
780     return;
781   }
782
783   my $query = qq|SELECT chart_id, SUM(amount) AS sum
784                  FROM acc_trans
785                  WHERE chart_id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)
786                  GROUP BY chart_id|;
787
788   my %balances = selectall_as_map($form, $dbh, $query, 'chart_id', 'sum', @ids);
789
790   foreach my $chart (@{ $params{charts} }) {
791     $chart->{balance} = $balances{ $chart->{id} } || 0;
792   }
793
794   $main::lxdebug->leave_sub();
795 }
796
797 sub get_tax_dropdown {
798   my ($self, $accno) = @_;
799
800   my $myconfig = \%main::myconfig;
801   my $form = $main::form;
802
803   my $dbh = $form->get_standard_dbh($myconfig);
804
805   my $query = qq|SELECT category FROM chart WHERE accno = ?|;
806   my ($category) = selectrow_query($form, $dbh, $query, $accno);
807
808   $query = qq|SELECT * FROM tax WHERE chart_categories like '%$category%' order by taxkey, rate|;
809
810   my $sth = prepare_execute_query($form, $dbh, $query);
811
812   my @tax_accounts = ();
813   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
814     push(@tax_accounts, $ref);
815   }
816
817   return @tax_accounts;
818 }
819
820 1;