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