fix FSF address
[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., 51 Franklin Street, Fifth Floor, Boston,
29 # MA 02110-1335, USA.
30 #======================================================================
31 #
32 # General ledger backend code
33 #
34 # CHANGE LOG:
35 #   DS. 2000-07-04  Created
36 #   DS. 2001-06-12  Changed relations from accno to chart_id
37 #
38 #======================================================================
39
40 package GL;
41
42 use Data::Dumper;
43 use SL::DATEV qw(:CONSTANTS);
44 use SL::DBUtils;
45 use SL::Util qw(trim);
46 use SL::DB;
47
48 use strict;
49
50 sub delete_transaction {
51   my ($self, $myconfig, $form) = @_;
52   $main::lxdebug->enter_sub();
53
54   SL::DB->client->with_transaction(sub {
55     do_query($form, SL::DB->client->dbh, qq|DELETE FROM gl WHERE id = ?|, conv_i($form->{id}));
56     1;
57   }) or do { die SL::DB->client->error };
58
59   $main::lxdebug->leave_sub();
60 }
61
62 sub post_transaction {
63   my ($self, $myconfig, $form) = @_;
64   $main::lxdebug->enter_sub();
65
66   my $rc = SL::DB->client->with_transaction(\&_post_transaction, $self, $myconfig, $form);
67
68   $::lxdebug->leave_sub;
69   return $rc;
70 }
71
72 sub _post_transaction {
73   my ($self, $myconfig, $form) = @_;
74   $main::lxdebug->enter_sub();
75
76   my ($debit, $credit) = (0, 0);
77   my $project_id;
78
79   my $i;
80
81   my $dbh = SL::DB->client->dbh;
82
83   # post the transaction
84   # make up a unique handle and store in reference field
85   # then retrieve the record based on the unique handle to get the id
86   # replace the reference field with the actual variable
87   # add records to acc_trans
88
89   # if there is a $form->{id} replace the old transaction
90   # delete all acc_trans entries and add the new ones
91
92   if (!$form->{taxincluded}) {
93     $form->{taxincluded} = 0;
94   }
95
96   my ($query, $sth, @values, $taxkey, $rate, $posted);
97
98   if ($form->{id}) {
99
100     # delete individual transactions
101     $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
102     @values = (conv_i($form->{id}));
103     do_query($form, $dbh, $query, @values);
104
105   } else {
106     $query = qq|SELECT nextval('glid')|;
107     ($form->{id}) = selectrow_query($form, $dbh, $query);
108
109     $query =
110       qq|INSERT INTO gl (id, employee_id) | .
111       qq|VALUES (?, (SELECT id FROM employee WHERE login = ?))|;
112     @values = ($form->{id}, $::myconfig{login});
113     do_query($form, $dbh, $query, @values);
114   }
115
116   my ($null, $department_id) = split(/--/, $form->{department});
117
118   $form->{ob_transaction} *= 1;
119   $form->{cb_transaction} *= 1;
120
121   $query =
122     qq|UPDATE gl SET
123          reference = ?, description = ?, notes = ?,
124          transdate = ?, department_id = ?, taxincluded = ?,
125          storno = ?, storno_id = ?, ob_transaction = ?, cb_transaction = ?
126        WHERE id = ?|;
127
128   @values = ($form->{reference}, $form->{description}, $form->{notes},
129              conv_date($form->{transdate}), conv_i($department_id), $form->{taxincluded} ? 't' : 'f',
130              $form->{storno} ? 't' : 'f', conv_i($form->{storno_id}), $form->{ob_transaction} ? 't' : 'f', $form->{cb_transaction} ? 't' : 'f',
131              conv_i($form->{id}));
132   do_query($form, $dbh, $query, @values);
133
134   # insert acc_trans transactions
135   for $i (1 .. $form->{rowcount}) {
136     # extract accno
137     my ($accno) = split(/--/, $form->{"accno_$i"});
138     ($form->{"tax_id_$i"}) = split(/--/, $form->{"taxchart_$i"});
139     if ($form->{"tax_id_$i"} ne "") {
140       $query = qq|SELECT taxkey, rate FROM tax WHERE id = ?|;
141       ($taxkey, $rate) = selectrow_query($form, $dbh, $query, conv_i($form->{"tax_id_$i"}));
142     }
143
144     my $amount = 0;
145     my $debit  = $form->{"debit_$i"};
146     my $credit = $form->{"credit_$i"};
147     my $tax    = $form->{"tax_$i"};
148
149     if ($credit) {
150       $amount = $credit;
151       $posted = 0;
152     }
153     if ($debit) {
154       $amount = $debit * -1;
155       $tax    = $tax * -1;
156       $posted = 0;
157     }
158
159     $project_id = conv_i($form->{"project_id_$i"});
160
161     # if there is an amount, add the record
162     if ($amount != 0) {
163       $query =
164         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
165                                   source, memo, project_id, taxkey, ob_transaction, cb_transaction, tax_id, chart_link)
166            VALUES (?, (SELECT id FROM chart WHERE accno = ?),
167                    ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT link FROM chart WHERE accno = ?))|;
168       @values = (conv_i($form->{id}), $accno, $amount, conv_date($form->{transdate}),
169                  $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);
170       do_query($form, $dbh, $query, @values);
171     }
172
173     if ($tax != 0) {
174       # add taxentry
175       $query =
176         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
177                                   source, memo, project_id, taxkey, tax_id, chart_link)
178            VALUES (?, (SELECT chart_id FROM tax WHERE id = ?),
179                    ?, ?, ?, ?, ?, ?, ?, (SELECT link
180                                          FROM chart
181                                          WHERE id = (SELECT chart_id
182                                                      FROM tax
183                                                      WHERE id = ?)))|;
184       @values = (conv_i($form->{id}), conv_i($form->{"tax_id_$i"}),
185                  $tax, conv_date($form->{transdate}), $form->{"source_$i"},
186                  $form->{"memo_$i"}, $project_id, $taxkey, conv_i($form->{"tax_id_$i"}), conv_i($form->{"tax_id_$i"}));
187       do_query($form, $dbh, $query, @values);
188     }
189   }
190
191   if ($form->{storno} && $form->{storno_id}) {
192     do_query($form, $dbh, qq|UPDATE gl SET storno = 't' WHERE id = ?|, conv_i($form->{storno_id}));
193   }
194
195   # safety check datev export
196   if ($::instance_conf->get_datev_check_on_gl_transaction) {
197     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
198     $transdate  ||= DateTime->today;
199
200     my $datev = SL::DATEV->new(
201       exporttype => DATEV_ET_BUCHUNGEN,
202       format     => DATEV_FORMAT_KNE,
203       dbh        => $dbh,
204       trans_id   => $form->{id},
205     );
206
207     $datev->export;
208
209     if ($datev->errors) {
210       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
211     }
212   }
213
214   return 1;
215 }
216
217 sub all_transactions {
218   my ($self, $myconfig, $form) = @_;
219   $main::lxdebug->enter_sub();
220
221   my $dbh = SL::DB->client->dbh;
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   $main::lxdebug->leave_sub();
621 }
622
623 sub transaction {
624   my ($self, $myconfig, $form) = @_;
625   $main::lxdebug->enter_sub();
626
627   my ($query, $sth, $ref, @values);
628
629   my $dbh = SL::DB->client->dbh;
630
631   $query = qq|SELECT closedto, revtrans FROM defaults|;
632   ($form->{closedto}, $form->{revtrans}) = selectrow_query($form, $dbh, $query);
633
634   $query = qq|SELECT id, gldate
635               FROM gl
636               WHERE id = (SELECT max(id) FROM gl)|;
637   ($form->{previous_id}, $form->{previous_gldate}) = selectrow_query($form, $dbh, $query);
638
639   if ($form->{id}) {
640     $query =
641       qq|SELECT g.reference, g.description, g.notes, g.transdate, g.storno, g.storno_id,
642            d.description AS department, e.name AS employee, g.taxincluded, g.gldate,
643          g.ob_transaction, g.cb_transaction
644          FROM gl g
645          LEFT JOIN department d ON (d.id = g.department_id)
646          LEFT JOIN employee e ON (e.id = g.employee_id)
647          WHERE g.id = ?|;
648     $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
649     map { $form->{$_} = $ref->{$_} } keys %$ref;
650
651     # retrieve individual rows
652     $query =
653       qq|SELECT c.accno, t.taxkey AS accnotaxkey, a.amount, a.memo, a.source,
654            a.transdate, a.cleared, a.project_id, p.projectnumber,
655            a.taxkey, t.rate AS taxrate, t.id,
656            (SELECT c1.accno
657             FROM chart c1, tax t1
658             WHERE (t1.id = t.id) AND (c1.id = t.chart_id)) AS taxaccno,
659            (SELECT tk.tax_id
660             FROM taxkeys tk
661             WHERE (tk.chart_id = a.chart_id) AND (tk.startdate <= a.transdate)
662             ORDER BY tk.startdate desc LIMIT 1) AS tax_id
663          FROM acc_trans a
664          JOIN chart c ON (c.id = a.chart_id)
665          LEFT JOIN project p ON (p.id = a.project_id)
666          LEFT JOIN tax t ON (t.id = a.tax_id)
667          WHERE (a.trans_id = ?)
668            AND (a.fx_transaction = '0')
669          ORDER BY a.acc_trans_id, a.transdate|;
670     $form->{GL} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
671
672   } else {
673     $query =
674       qq|SELECT COALESCE(
675            (SELECT transdate
676             FROM gl
677             WHERE id = (SELECT MAX(id) FROM gl)
678             LIMIT 1),
679            current_date)|;
680     ($form->{transdate}) = selectrow_query($form, $dbh, $query);
681   }
682
683   # get tax description
684   $query = qq|SELECT * FROM tax ORDER BY taxkey|;
685   $form->{TAX} = selectall_hashref_query($form, $dbh, $query);
686
687   # get chart of accounts
688   $query =
689     qq|SELECT c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id
690        FROM chart c
691        LEFT JOIN taxkeys tk ON (tk.id =
692          (SELECT id
693           FROM taxkeys
694           WHERE (taxkeys.chart_id = c.id)
695             AND (startdate <= ?)
696           ORDER BY startdate DESC
697           LIMIT 1))
698        ORDER BY c.accno|;
699   $form->{chart} = selectall_hashref_query($form, $dbh, $query, conv_date($form->{transdate}));
700
701   $main::lxdebug->leave_sub();
702 }
703
704 sub storno {
705   my ($self, $form, $myconfig, $id) = @_;
706   $main::lxdebug->enter_sub();
707
708   my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
709
710   $::lxdebug->leave_sub;
711   return $rc;
712 }
713
714 sub _storno {
715   my ($self, $form, $myconfig, $id) = @_;
716
717   my ($query, $new_id, $storno_row, $acc_trans_rows);
718   my $dbh = SL::DB->client->dbh;
719
720   $query = qq|SELECT nextval('glid')|;
721   ($new_id) = selectrow_query($form, $dbh, $query);
722
723   $query = qq|SELECT * FROM gl WHERE id = ?|;
724   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
725
726   $storno_row->{id}          = $new_id;
727   $storno_row->{storno_id}   = $id;
728   $storno_row->{storno}      = 't';
729   $storno_row->{reference}   = 'Storno-' . $storno_row->{reference};
730
731   $query = qq|SELECT id FROM employee WHERE login = ?|;
732   my ($employee_id) = selectrow_query($form, $dbh, $query, $::myconfig{login});
733   $storno_row->{employee_id} = $employee_id;
734
735   delete @$storno_row{qw(itime mtime gldate)};
736
737   $query = sprintf 'INSERT INTO gl (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
738   do_query($form, $dbh, $query, (values %$storno_row));
739
740   $query = qq|UPDATE gl SET storno = 't' WHERE id = ?|;
741   do_query($form, $dbh, $query, $id);
742
743   # now copy acc_trans entries
744   $query = qq|SELECT * FROM acc_trans WHERE trans_id = ?|;
745   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
746
747   for my $row (@$rowref) {
748     delete @$row{qw(itime mtime acc_trans_id gldate)};
749     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
750     $row->{trans_id}   = $new_id;
751     $row->{amount}    *= -1;
752     do_query($form, $dbh, $query, (values %$row));
753   }
754
755   return 1;
756 }
757
758 sub get_chart_balances {
759   $main::lxdebug->enter_sub();
760
761   my $self     = shift;
762   my %params   = @_;
763
764   Common::check_params(\%params, qw(charts));
765
766   my $myconfig = \%main::myconfig;
767   my $form     = $main::form;
768
769   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
770
771   my @ids      = map { $_->{id} } @{ $params{charts} };
772
773   if (!@ids) {
774     $main::lxdebug->leave_sub();
775     return;
776   }
777
778   my $query = qq|SELECT chart_id, SUM(amount) AS sum
779                  FROM acc_trans
780                  WHERE chart_id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)
781                  GROUP BY chart_id|;
782
783   my %balances = selectall_as_map($form, $dbh, $query, 'chart_id', 'sum', @ids);
784
785   foreach my $chart (@{ $params{charts} }) {
786     $chart->{balance} = $balances{ $chart->{id} } || 0;
787   }
788
789   $main::lxdebug->leave_sub();
790 }
791
792 sub get_tax_dropdown {
793   my ($self, $accno) = @_;
794
795   my $myconfig = \%main::myconfig;
796   my $form = $main::form;
797
798   my $dbh = $form->get_standard_dbh($myconfig);
799
800   my $query = qq|SELECT category FROM chart WHERE accno = ?|;
801   my ($category) = selectrow_query($form, $dbh, $query, $accno);
802
803   $query = qq|SELECT * FROM tax WHERE chart_categories like '%$category%' order by taxkey, rate|;
804
805   my $sth = prepare_execute_query($form, $dbh, $query);
806
807   my @tax_accounts = ();
808   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
809     push(@tax_accounts, $ref);
810   }
811
812   return @tax_accounts;
813 }
814
815 1;