tax_id in acc_trans
[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
45 use strict;
46
47 sub delete_transaction {
48   my ($self, $myconfig, $form) = @_;
49   $main::lxdebug->enter_sub();
50
51   # connect to database
52   my $dbh = $form->dbconnect_noauto($myconfig);
53
54   # acc_trans entries are deleted by database triggers.
55   do_query($form, $dbh, qq|DELETE FROM gl WHERE id = ?|, conv_i($form->{id}));
56
57   # commit and redirect
58   my $rc = $dbh->commit;
59   $dbh->disconnect;
60   $main::lxdebug->leave_sub();
61
62   $rc;
63
64 }
65
66 sub post_transaction {
67   my ($self, $myconfig, $form) = @_;
68   $main::lxdebug->enter_sub();
69
70   my ($debit, $credit) = (0, 0);
71   my $project_id;
72
73   my $i;
74
75   # connect to database, turn off AutoCommit
76   my $dbh = $form->dbconnect_noauto($myconfig);
77
78   # post the transaction
79   # make up a unique handle and store in reference field
80   # then retrieve the record based on the unique handle to get the id
81   # replace the reference field with the actual variable
82   # add records to acc_trans
83
84   # if there is a $form->{id} replace the old transaction
85   # delete all acc_trans entries and add the new ones
86
87   if (!$form->{taxincluded}) {
88     $form->{taxincluded} = 0;
89   }
90
91   my ($query, $sth, @values, $taxkey, $rate, $posted);
92
93   if ($form->{id}) {
94
95     # delete individual transactions
96     $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
97     @values = (conv_i($form->{id}));
98     do_query($form, $dbh, $query, @values);
99
100   } else {
101     $query = qq|SELECT nextval('glid')|;
102     ($form->{id}) = selectrow_query($form, $dbh, $query);
103
104     $query =
105       qq|INSERT INTO gl (id, employee_id) | .
106       qq|VALUES (?, (SELECT id FROM employee WHERE login = ?))|;
107     @values = ($form->{id}, $form->{login});
108     do_query($form, $dbh, $query, @values);
109   }
110
111   my ($null, $department_id) = split(/--/, $form->{department});
112
113   $form->{ob_transaction} *= 1;
114   $form->{cb_transaction} *= 1;
115
116   $query =
117     qq|UPDATE gl SET
118          reference = ?, description = ?, notes = ?,
119          transdate = ?, department_id = ?, taxincluded = ?,
120          storno = ?, storno_id = ?, ob_transaction = ?, cb_transaction = ?
121        WHERE id = ?|;
122
123   @values = ($form->{reference}, $form->{description}, $form->{notes},
124              conv_date($form->{transdate}), conv_i($department_id), $form->{taxincluded} ? 't' : 'f',
125              $form->{storno} ? 't' : 'f', conv_i($form->{storno_id}), $form->{ob_transaction} ? 't' : 'f', $form->{cb_transaction} ? 't' : 'f',
126              conv_i($form->{id}));
127   do_query($form, $dbh, $query, @values);
128
129   # insert acc_trans transactions
130   for $i (1 .. $form->{rowcount}) {
131     # extract accno
132     my ($accno) = split(/--/, $form->{"accno_$i"});
133     ($form->{"tax_id_$i"}) = split(/--/, $form->{"taxchart_$i"});
134     if ($form->{"tax_id_$i"} ne "") {
135       $query = qq|SELECT taxkey, rate FROM tax WHERE id = ?|;
136       ($taxkey, $rate) = selectrow_query($form, $dbh, $query, conv_i($form->{"tax_id_$i"}));
137     }
138
139     my $amount = 0;
140     my $debit  = $form->{"debit_$i"};
141     my $credit = $form->{"credit_$i"};
142     my $tax    = $form->{"tax_$i"};
143
144     if ($credit) {
145       $amount = $credit;
146       $posted = 0;
147     }
148     if ($debit) {
149       $amount = $debit * -1;
150       $tax    = $tax * -1;
151       $posted = 0;
152     }
153
154     $project_id = conv_i($form->{"project_id_$i"});
155
156     # if there is an amount, add the record
157     if ($amount != 0) {
158       $query =
159         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
160                                   source, memo, project_id, taxkey, ob_transaction, cb_transaction, tax_id)
161            VALUES (?, (SELECT id FROM chart WHERE accno = ?),
162                    ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
163       @values = (conv_i($form->{id}), $accno, $amount, conv_date($form->{transdate}),
164                  $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"}));
165       do_query($form, $dbh, $query, @values);
166     }
167
168     if ($tax != 0) {
169       # add taxentry
170       $query =
171         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
172                                   source, memo, project_id, taxkey, tax_id)
173            VALUES (?, (SELECT chart_id FROM tax WHERE id = ?),
174                    ?, ?, ?, ?, ?, ?, ?)|;
175       @values = (conv_i($form->{id}), conv_i($form->{"tax_id_$i"}),
176                  $tax, conv_date($form->{transdate}), $form->{"source_$i"},
177                  $form->{"memo_$i"}, $project_id, $taxkey, conv_i($form->{"tax_id_$i"}));
178       do_query($form, $dbh, $query, @values);
179     }
180   }
181
182   if ($form->{storno} && $form->{storno_id}) {
183     do_query($form, $dbh, qq|UPDATE gl SET storno = 't' WHERE id = ?|, conv_i($form->{storno_id}));
184   }
185
186   # safety check datev export
187   if ($::instance_conf->get_datev_check_on_gl_transaction) {
188     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
189     $transdate  ||= DateTime->today;
190
191     my $datev = SL::DATEV->new(
192       exporttype => DATEV_ET_BUCHUNGEN,
193       format     => DATEV_FORMAT_KNE,
194       dbh        => $dbh,
195       from       => $transdate,
196       to         => $transdate,
197     );
198
199     $datev->export;
200
201     if ($datev->errors) {
202       $dbh->rollback;
203       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
204     }
205   }
206
207   # commit and redirect
208   my $rc = $dbh->commit;
209   $dbh->disconnect;
210   $main::lxdebug->leave_sub();
211
212   return $rc;
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, '%' . $form->{reference} . '%');
231     push(@arvalues, '%' . $form->{reference} . '%');
232     push(@apvalues, '%' . $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, '%' . $form->{source} . '%');
250     push(@arvalues, '%' . $form->{source} . '%');
251     push(@apvalues, '%' . $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 ($form->{datefrom}) {
258     $glwhere .= " AND ac.$form->{datesort} >= ?";
259     $arwhere .= " AND ac.$form->{datesort} >= ?";
260     $apwhere .= " AND ac.$form->{datesort} >= ?";
261     push(@glvalues, $form->{datefrom});
262     push(@arvalues, $form->{datefrom});
263     push(@apvalues, $form->{datefrom});
264   }
265
266   if ($form->{dateto}) {
267     $glwhere .= " AND ac.$form->{datesort} <= ?";
268     $arwhere .= " AND ac.$form->{datesort} <= ?";
269     $apwhere .= " AND ac.$form->{datesort} <= ?";
270     push(@glvalues, $form->{dateto});
271     push(@arvalues, $form->{dateto});
272     push(@apvalues, $form->{dateto});
273   }
274
275   if ($form->{description}) {
276     $glwhere .= " AND g.description ILIKE ?";
277     $arwhere .= " AND ct.name ILIKE ?";
278     $apwhere .= " AND ct.name ILIKE ?";
279     push(@glvalues, '%' . $form->{description} . '%');
280     push(@arvalues, '%' . $form->{description} . '%');
281     push(@apvalues, '%' . $form->{description} . '%');
282   }
283  
284   if ($form->{employee} =~ /--/) {
285     ($form->{employee_id},$form->{employee_name}) = split(/--/,$form->{employee});
286   #if ($form->{employee_id}) {
287     $glwhere .= " AND g.employee_id = ? ";
288     $arwhere .= " AND a.employee_id = ? ";
289     $apwhere .= " AND a.employee_id = ? ";
290     push(@glvalues, conv_i($form->{employee_id}));
291     push(@arvalues, conv_i($form->{employee_id}));
292     push(@apvalues, conv_i($form->{employee_id}));
293   }
294
295   if ($form->{notes}) {
296     $glwhere .= " AND g.notes ILIKE ?";
297     $arwhere .= " AND a.notes ILIKE ?";
298     $apwhere .= " AND a.notes ILIKE ?";
299     push(@glvalues, '%' . $form->{notes} . '%');
300     push(@arvalues, '%' . $form->{notes} . '%');
301     push(@apvalues, '%' . $form->{notes} . '%');
302   }
303
304   if ($form->{accno}) {
305     $glwhere .= " AND c.accno = '$form->{accno}'";
306     $arwhere .= " AND c.accno = '$form->{accno}'";
307     $apwhere .= " AND c.accno = '$form->{accno}'";
308   }
309
310   if ($form->{category} ne 'X') {
311     $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 = ?))|;
312     $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 = ?))|;
313     $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 = ?))|;
314     push(@glvalues, $form->{category});
315     push(@arvalues, $form->{category});
316     push(@apvalues, $form->{category});
317   }
318
319   if ($form->{project_id}) {
320     $glwhere .= qq| AND g.id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE project_id = ?)|;
321     $arwhere .=
322       qq| AND ((a.globalproject_id = ?) OR
323                (a.id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE project_id = ?)))|;
324     $apwhere .=
325       qq| AND ((a.globalproject_id = ?) OR
326                (a.id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE project_id = ?)))|;
327     my $project_id = conv_i($form->{project_id});
328     push(@glvalues, $project_id);
329     push(@arvalues, $project_id, $project_id);
330     push(@apvalues, $project_id, $project_id);
331   }
332
333   my ($project_columns, $project_join);
334   if ($form->{"l_projectnumbers"}) {
335     $project_columns = qq|, ac.project_id, pr.projectnumber|;
336     $project_join = qq|LEFT JOIN project pr ON (ac.project_id = pr.id)|;
337   }
338
339   if ($form->{accno}) {
340     # get category for account
341     $query = qq|SELECT category FROM chart WHERE accno = ?|;
342     ($form->{ml}) = selectrow_query($form, $dbh, $query, $form->{accno});
343
344     if ($form->{datefrom}) {
345       $query =
346         qq|SELECT SUM(ac.amount)
347            FROM acc_trans ac
348            LEFT JOIN chart c ON (ac.chart_id = c.id)
349            WHERE (c.accno = ?) AND (ac.$form->{datesort} < ?)|;
350       ($form->{balance}) = selectrow_query($form, $dbh, $query, $form->{accno}, conv_date($form->{datefrom}));
351     }
352   }
353
354   my $false = ($myconfig->{dbdriver} eq 'Pg') ? "FALSE" : q|'0'|;
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
673            (t.id =
674              (SELECT tk.tax_id
675               FROM taxkeys tk
676               WHERE (tk.taxkey_id = a.taxkey) AND
677                 ((CASE WHEN a.chart_id IN
678                     (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
679                   THEN tk.chart_id = a.chart_id
680                   ELSE 1 = 1
681                   END)
682                  OR (c.link LIKE '%tax%'))
683                 AND (startdate <= a.transdate)
684               ORDER BY startdate DESC LIMIT 1))
685          WHERE (a.trans_id = ?)
686            AND (a.fx_transaction = '0')
687          ORDER BY a.acc_trans_id, a.transdate|;
688     $form->{GL} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
689
690   } else {
691     $query =
692       qq|SELECT COALESCE(
693            (SELECT transdate
694             FROM gl
695             WHERE id = (SELECT MAX(id) FROM gl)
696             LIMIT 1),
697            current_date)|;
698     ($form->{transdate}) = selectrow_query($form, $dbh, $query);
699   }
700
701   # get tax description
702   $query = qq|SELECT * FROM tax ORDER BY taxkey|;
703   $form->{TAX} = selectall_hashref_query($form, $dbh, $query);
704
705   # get chart of accounts
706   $query =
707     qq|SELECT c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id
708        FROM chart c
709        LEFT JOIN taxkeys tk ON (tk.id =
710          (SELECT id
711           FROM taxkeys
712           WHERE (taxkeys.chart_id = c.id)
713             AND (startdate <= ?)
714           ORDER BY startdate DESC
715           LIMIT 1))
716        ORDER BY c.accno|;
717   $form->{chart} = selectall_hashref_query($form, $dbh, $query, conv_date($form->{transdate}));
718
719   $dbh->disconnect;
720
721   $main::lxdebug->leave_sub();
722 }
723
724 sub storno {
725   $main::lxdebug->enter_sub();
726
727   my ($self, $form, $myconfig, $id) = @_;
728
729   my ($query, $new_id, $storno_row, $acc_trans_rows);
730   my $dbh = $form->get_standard_dbh($myconfig);
731
732   $query = qq|SELECT nextval('glid')|;
733   ($new_id) = selectrow_query($form, $dbh, $query);
734
735   $query = qq|SELECT * FROM gl WHERE id = ?|;
736   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
737
738   $storno_row->{id}        = $new_id;
739   $storno_row->{storno_id} = $id;
740   $storno_row->{storno}    = 't';
741   $storno_row->{reference} = 'Storno-' . $storno_row->{reference};
742
743   delete @$storno_row{qw(itime mtime gldate)};
744
745   $query = sprintf 'INSERT INTO gl (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
746   do_query($form, $dbh, $query, (values %$storno_row));
747
748   $query = qq|UPDATE gl SET storno = 't' WHERE id = ?|;
749   do_query($form, $dbh, $query, $id);
750
751   # now copy acc_trans entries
752   $query = qq|SELECT * FROM acc_trans WHERE trans_id = ?|;
753   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
754
755   for my $row (@$rowref) {
756     delete @$row{qw(itime mtime acc_trans_id gldate)};
757     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
758     $row->{trans_id}   = $new_id;
759     $row->{amount}    *= -1;
760     do_query($form, $dbh, $query, (values %$row));
761   }
762
763   $dbh->commit;
764
765   $main::lxdebug->leave_sub();
766 }
767
768 sub get_chart_balances {
769   $main::lxdebug->enter_sub();
770
771   my $self     = shift;
772   my %params   = @_;
773
774   Common::check_params(\%params, qw(charts));
775
776   my $myconfig = \%main::myconfig;
777   my $form     = $main::form;
778
779   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
780
781   my @ids      = map { $_->{id} } @{ $params{charts} };
782
783   if (!@ids) {
784     $main::lxdebug->leave_sub();
785     return;
786   }
787
788   my $query = qq|SELECT chart_id, SUM(amount) AS sum
789                  FROM acc_trans
790                  WHERE chart_id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)
791                  GROUP BY chart_id|;
792
793   my %balances = selectall_as_map($form, $dbh, $query, 'chart_id', 'sum', @ids);
794
795   foreach my $chart (@{ $params{charts} }) {
796     $chart->{balance} = $balances{ $chart->{id} } || 0;
797   }
798
799   $main::lxdebug->leave_sub();
800 }
801
802
803 1;