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