Merge branch 'master' into dev
[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, chart_link)
161            VALUES (?, (SELECT id FROM chart WHERE accno = ?),
162                    ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT link FROM chart WHERE accno = ?))|;
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"}), $accno);
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, chart_link)
173            VALUES (?, (SELECT chart_id FROM tax WHERE id = ?),
174                    ?, ?, ?, ?, ?, ?, ?, (SELECT link 
175                                          FROM chart 
176                                          WHERE id = (SELECT chart_id 
177                                                      FROM tax 
178                                                      WHERE id = ?)))|;
179       @values = (conv_i($form->{id}), conv_i($form->{"tax_id_$i"}),
180                  $tax, conv_date($form->{transdate}), $form->{"source_$i"},
181                  $form->{"memo_$i"}, $project_id, $taxkey, conv_i($form->{"tax_id_$i"}), conv_i($form->{"tax_id_$i"}));
182       do_query($form, $dbh, $query, @values);
183     }
184   }
185
186   if ($form->{storno} && $form->{storno_id}) {
187     do_query($form, $dbh, qq|UPDATE gl SET storno = 't' WHERE id = ?|, conv_i($form->{storno_id}));
188   }
189
190   # safety check datev export
191   if ($::instance_conf->get_datev_check_on_gl_transaction) {
192     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
193     $transdate  ||= DateTime->today;
194
195     my $datev = SL::DATEV->new(
196       exporttype => DATEV_ET_BUCHUNGEN,
197       format     => DATEV_FORMAT_KNE,
198       dbh        => $dbh,
199       from       => $transdate,
200       to         => $transdate,
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, '%' . $form->{reference} . '%');
235     push(@arvalues, '%' . $form->{reference} . '%');
236     push(@apvalues, '%' . $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, '%' . $form->{source} . '%');
254     push(@arvalues, '%' . $form->{source} . '%');
255     push(@apvalues, '%' . $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 ($form->{datefrom}) {
262     $glwhere .= " AND ac.$form->{datesort} >= ?";
263     $arwhere .= " AND ac.$form->{datesort} >= ?";
264     $apwhere .= " AND ac.$form->{datesort} >= ?";
265     push(@glvalues, $form->{datefrom});
266     push(@arvalues, $form->{datefrom});
267     push(@apvalues, $form->{datefrom});
268   }
269
270   if ($form->{dateto}) {
271     $glwhere .= " AND ac.$form->{datesort} <= ?";
272     $arwhere .= " AND ac.$form->{datesort} <= ?";
273     $apwhere .= " AND ac.$form->{datesort} <= ?";
274     push(@glvalues, $form->{dateto});
275     push(@arvalues, $form->{dateto});
276     push(@apvalues, $form->{dateto});
277   }
278
279   if ($form->{description}) {
280     $glwhere .= " AND g.description ILIKE ?";
281     $arwhere .= " AND ct.name ILIKE ?";
282     $apwhere .= " AND ct.name ILIKE ?";
283     push(@glvalues, '%' . $form->{description} . '%');
284     push(@arvalues, '%' . $form->{description} . '%');
285     push(@apvalues, '%' . $form->{description} . '%');
286   }
287
288   if ($form->{employee} =~ /--/) {
289     ($form->{employee_id},$form->{employee_name}) = split(/--/,$form->{employee});
290   #if ($form->{employee_id}) {
291     $glwhere .= " AND g.employee_id = ? ";
292     $arwhere .= " AND a.employee_id = ? ";
293     $apwhere .= " AND a.employee_id = ? ";
294     push(@glvalues, conv_i($form->{employee_id}));
295     push(@arvalues, conv_i($form->{employee_id}));
296     push(@apvalues, conv_i($form->{employee_id}));
297   }
298
299   if ($form->{notes}) {
300     $glwhere .= " AND g.notes ILIKE ?";
301     $arwhere .= " AND a.notes ILIKE ?";
302     $apwhere .= " AND a.notes ILIKE ?";
303     push(@glvalues, '%' . $form->{notes} . '%');
304     push(@arvalues, '%' . $form->{notes} . '%');
305     push(@apvalues, '%' . $form->{notes} . '%');
306   }
307
308   if ($form->{accno}) {
309     $glwhere .= " AND c.accno = '$form->{accno}'";
310     $arwhere .= " AND c.accno = '$form->{accno}'";
311     $apwhere .= " AND c.accno = '$form->{accno}'";
312   }
313
314   if ($form->{category} ne 'X') {
315     $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 = ?))|;
316     $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 = ?))|;
317     $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 = ?))|;
318     push(@glvalues, $form->{category});
319     push(@arvalues, $form->{category});
320     push(@apvalues, $form->{category});
321   }
322
323   if ($form->{project_id}) {
324     $glwhere .= qq| AND g.id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE project_id = ?)|;
325     $arwhere .=
326       qq| AND ((a.globalproject_id = ?) OR
327                (a.id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE project_id = ?)))|;
328     $apwhere .=
329       qq| AND ((a.globalproject_id = ?) OR
330                (a.id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE project_id = ?)))|;
331     my $project_id = conv_i($form->{project_id});
332     push(@glvalues, $project_id);
333     push(@arvalues, $project_id, $project_id);
334     push(@apvalues, $project_id, $project_id);
335   }
336
337   my ($project_columns, $project_join);
338   if ($form->{"l_projectnumbers"}) {
339     $project_columns = qq|, ac.project_id, pr.projectnumber|;
340     $project_join = qq|LEFT JOIN project pr ON (ac.project_id = pr.id)|;
341   }
342
343   if ($form->{accno}) {
344     # get category for account
345     $query = qq|SELECT category FROM chart WHERE accno = ?|;
346     ($form->{ml}) = selectrow_query($form, $dbh, $query, $form->{accno});
347
348     if ($form->{datefrom}) {
349       $query =
350         qq|SELECT SUM(ac.amount)
351            FROM acc_trans ac
352            LEFT JOIN chart c ON (ac.chart_id = c.id)
353            WHERE (c.accno = ?) AND (ac.$form->{datesort} < ?)|;
354       ($form->{balance}) = selectrow_query($form, $dbh, $query, $form->{accno}, conv_date($form->{datefrom}));
355     }
356   }
357
358   my $false = ($myconfig->{dbdriver} eq 'Pg') ? "FALSE" : q|'0'|;
359
360   my %sort_columns =  (
361     'id'           => [ qw(id)                   ],
362     'transdate'    => [ qw(transdate id)         ],
363     'gldate'       => [ qw(gldate id)         ],
364     'reference'    => [ qw(lower_reference id)   ],
365     'description'  => [ qw(lower_description id) ],
366     'accno'        => [ qw(accno transdate id)   ],
367     );
368   my %lowered_columns =  (
369     'reference'       => { 'gl' => 'g.reference',   'arap' => 'a.invnumber', },
370     'source'          => { 'gl' => 'ac.source',     'arap' => 'ac.source',   },
371     'description'     => { 'gl' => 'g.description', 'arap' => 'ct.name',     },
372     );
373
374   # sortdir = sort direction (ascending or descending)
375   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
376   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : $form->{datesort};  # default used to be transdate
377   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
378
379   my %columns_for_sorting = ( 'gl' => '', 'arap' => '', );
380   foreach my $spec (@{ $sort_columns{$sortkey} }) {
381     next if ($spec !~ m/^lower_(.*)$/);
382
383     my $column = $1;
384     map { $columns_for_sorting{$_} .= sprintf(', lower(%s) AS lower_%s', $lowered_columns{$column}->{$_}, $column) } qw(gl arap);
385   }
386
387   $query =
388     qq|SELECT
389         ac.acc_trans_id, g.id, 'gl' AS type, $false AS invoice, g.reference, ac.taxkey, c.link,
390         g.description, ac.transdate, ac.gldate, ac.source, ac.trans_id,
391         ac.amount, c.accno, g.notes, t.chart_id,
392         CASE WHEN (COALESCE(e.name, '') = '') THEN e.login ELSE e.name END AS employee
393         $project_columns
394         $columns_for_sorting{gl}
395       FROM gl g
396       LEFT JOIN employee e ON (g.employee_id = e.id),
397       acc_trans ac $project_join, chart c
398       LEFT JOIN tax t ON (t.chart_id = c.id)
399       WHERE $glwhere
400         AND (ac.chart_id = c.id)
401         AND (g.id = ac.trans_id)
402
403       UNION
404
405       SELECT ac.acc_trans_id, a.id, 'ar' AS type, a.invoice, a.invnumber, ac.taxkey, c.link,
406         ct.name, ac.transdate, ac.gldate, ac.source, ac.trans_id,
407         ac.amount, c.accno, a.notes, t.chart_id,
408         CASE WHEN (COALESCE(e.name, '') = '') THEN e.login ELSE e.name END AS employee
409         $project_columns
410         $columns_for_sorting{arap}
411       FROM ar a
412       LEFT JOIN employee e ON (a.employee_id = e.id),
413       acc_trans ac $project_join, customer ct, chart c
414       LEFT JOIN tax t ON (t.chart_id=c.id)
415       WHERE $arwhere
416         AND (ac.chart_id = c.id)
417         AND (a.customer_id = ct.id)
418         AND (a.id = ac.trans_id)
419
420       UNION
421
422       SELECT ac.acc_trans_id, a.id, 'ap' AS type, a.invoice, a.invnumber, ac.taxkey, c.link,
423         ct.name, ac.transdate, ac.gldate, ac.source, ac.trans_id,
424         ac.amount, c.accno, a.notes, t.chart_id,
425         CASE WHEN (COALESCE(e.name, '') = '') THEN e.login ELSE e.name END AS employee
426         $project_columns
427         $columns_for_sorting{arap}
428       FROM ap a
429       LEFT JOIN employee e ON (a.employee_id = e.id),
430       acc_trans ac $project_join, vendor ct, chart c
431       LEFT JOIN tax t ON (t.chart_id=c.id)
432       WHERE $apwhere
433         AND (ac.chart_id = c.id)
434         AND (a.vendor_id = ct.id)
435         AND (a.id = ac.trans_id)
436
437       ORDER BY $sortorder, acc_trans_id $sortdir|;
438 #      ORDER BY gldate DESC, id DESC, acc_trans_id DESC
439
440   my @values = (@glvalues, @arvalues, @apvalues);
441
442   # Show all $query in Debuglevel LXDebug::QUERY
443   my $callingdetails = (caller (0))[3];
444   dump_query(LXDebug->QUERY(), "$callingdetails", $query, @values);
445
446   $sth = prepare_execute_query($form, $dbh, $query, @values);
447   my $trans_id  = "";
448   my $trans_id2 = "";
449   my $balance;
450
451   my ($i, $j, $k, $l, $ref, $ref2);
452
453   $form->{GL} = [];
454   while (my $ref0 = $sth->fetchrow_hashref("NAME_lc")) {
455
456     $trans_id = $ref0->{id};
457
458     my $source = $ref0->{source};
459     undef($ref0->{source});
460
461     if ($trans_id != $trans_id2) { # first line of a booking
462
463       if ($trans_id2) {
464         push(@{ $form->{GL} }, $ref);
465         $balance = 0;
466       }
467
468       $ref       = $ref0;
469       $trans_id2 = $ref->{id};
470
471       # gl
472       if ($ref->{type} eq "gl") {
473         $ref->{module} = "gl";
474       }
475
476       # ap
477       if ($ref->{type} eq "ap") {
478         if ($ref->{invoice}) {
479           $ref->{module} = "ir";
480         } else {
481           $ref->{module} = "ap";
482         }
483       }
484
485       # ar
486       if ($ref->{type} eq "ar") {
487         if ($ref->{invoice}) {
488           $ref->{module} = "is";
489         } else {
490           $ref->{module} = "ar";
491         }
492       }
493
494       $ref->{"projectnumbers"} = {};
495       $ref->{"projectnumbers"}->{$ref->{"projectnumber"}} = 1 if ($ref->{"projectnumber"});
496
497       $balance = $ref->{amount};
498
499       # Linenumbers of General Ledger
500       $k       = 0; # Debit      # AP      # Soll
501       $l       = 0; # Credit     # AR      # Haben
502       $i       = 0; # Debit Tax  # AP_tax  # VSt
503       $j       = 0; # Credit Tax # AR_tax  # USt
504
505       if ($ref->{chart_id} > 0) { # all tax accounts first line, no line increasing
506         if ($ref->{amount} < 0) {
507           if ($ref->{link} =~ /AR_tax/) {
508             $ref->{credit_tax}{$j}       = $ref->{amount};
509             $ref->{credit_tax_accno}{$j} = $ref->{accno};
510          }
511           if ($ref->{link} =~ /AP_tax/) {
512             $ref->{debit_tax}{$i}       = $ref->{amount} * -1;
513             $ref->{debit_tax_accno}{$i} = $ref->{accno};
514           }
515         } else {
516           if ($ref->{link} =~ /AR_tax/) {
517             $ref->{credit_tax}{$j}       = $ref->{amount};
518             $ref->{credit_tax_accno}{$j} = $ref->{accno};
519           }
520           if ($ref->{link} =~ /AP_tax/) {
521             $ref->{debit_tax}{$i}       = $ref->{amount} * -1;
522             $ref->{debit_tax_accno}{$i} = $ref->{accno};
523           }
524         }
525       } else { #all other accounts first line
526
527         if ($ref->{amount} < 0) {
528           $ref->{debit}{$k}        = $ref->{amount} * -1;
529           $ref->{debit_accno}{$k}  = $ref->{accno};
530           $ref->{debit_taxkey}{$k} = $ref->{taxkey};
531           $ref->{ac_transdate}{$k} = $ref->{transdate};
532           $ref->{source}{$k}       = $source;
533         } else {
534           $ref->{credit}{$l}        = $ref->{amount} * 1;
535           $ref->{credit_accno}{$l}  = $ref->{accno};
536           $ref->{credit_taxkey}{$l} = $ref->{taxkey};
537           $ref->{ac_transdate}{$l}  = $ref->{transdate};
538           $ref->{source}{$l}        = $source;
539         }
540       }
541
542     } else { # following lines of a booking, line increasing
543
544       $ref2      = $ref0;
545 #      $trans_old = $trans_id2;   # doesn't seem to be used anymore
546       $trans_id2 = $ref2->{id};
547
548       $balance =
549         (int($balance * 100000) + int(100000 * $ref2->{amount})) / 100000;
550
551       $ref->{"projectnumbers"}->{$ref2->{"projectnumber"}} = 1 if ($ref2->{"projectnumber"});
552
553       if ($ref2->{chart_id} > 0) { # all tax accounts, following lines
554         if ($ref2->{amount} < 0) {
555           if ($ref2->{link} =~ /AR_tax/) {
556             if ($ref->{credit_tax_accno}{$j} ne "") {
557               $j++;
558             }
559             $ref->{credit_tax}{$j}       = $ref2->{amount};
560             $ref->{credit_tax_accno}{$j} = $ref2->{accno};
561           }
562           if ($ref2->{link} =~ /AP_tax/) {
563             if ($ref->{debit_tax_accno}{$i} ne "") {
564               $i++;
565             }
566             $ref->{debit_tax}{$i}       = $ref2->{amount} * -1;
567             $ref->{debit_tax_accno}{$i} = $ref2->{accno};
568           }
569         } else {
570           if ($ref2->{link} =~ /AR_tax/) {
571             if ($ref->{credit_tax_accno}{$j} ne "") {
572               $j++;
573             }
574             $ref->{credit_tax}{$j}       = $ref2->{amount};
575             $ref->{credit_tax_accno}{$j} = $ref2->{accno};
576           }
577           if ($ref2->{link} =~ /AP_tax/) {
578             if ($ref->{debit_tax_accno}{$i} ne "") {
579               $i++;
580             }
581             $ref->{debit_tax}{$i}       = $ref2->{amount} * -1;
582             $ref->{debit_tax_accno}{$i} = $ref2->{accno};
583           }
584         }
585       } else { # all other accounts, following lines
586         if ($ref2->{amount} < 0) {
587           if ($ref->{debit_accno}{$k} ne "") {
588             $k++;
589           }
590           if ($ref->{source}{$k} ne "") {
591             $space = " | ";
592           } else {
593             $space = "";
594           }
595           $ref->{debit}{$k}        = $ref2->{amount} * - 1;
596           $ref->{debit_accno}{$k}  = $ref2->{accno};
597           $ref->{debit_taxkey}{$k} = $ref2->{taxkey};
598           $ref->{ac_transdate}{$k} = $ref2->{transdate};
599           $ref->{source}{$k}       = $source . $space . $ref->{source}{$k};
600         } else {
601           if ($ref->{credit_accno}{$l} ne "") {
602             $l++;
603           }
604           if ($ref->{source}{$l} ne "") {
605             $space = " | ";
606           } else {
607             $space = "";
608           }
609           $ref->{credit}{$l}        = $ref2->{amount};
610           $ref->{credit_accno}{$l}  = $ref2->{accno};
611           $ref->{credit_taxkey}{$l} = $ref2->{taxkey};
612           $ref->{ac_transdate}{$l}  = $ref2->{transdate};
613           $ref->{source}{$l}        = $ref->{source}{$l} . $space . $source;
614         }
615       }
616     }
617   }
618
619   push @{ $form->{GL} }, $ref;
620   $sth->finish;
621
622   if ($form->{accno}) {
623     $query = qq|SELECT c.description FROM chart c WHERE c.accno = ?|;
624     ($form->{account_description}) = selectrow_query($form, $dbh, $query, $form->{accno});
625   }
626
627   $dbh->disconnect;
628
629   $main::lxdebug->leave_sub();
630 }
631
632 sub transaction {
633   my ($self, $myconfig, $form) = @_;
634   $main::lxdebug->enter_sub();
635
636   my ($query, $sth, $ref, @values);
637
638   # connect to database
639   my $dbh = $form->dbconnect($myconfig);
640
641   $query = qq|SELECT closedto, revtrans FROM defaults|;
642   ($form->{closedto}, $form->{revtrans}) = selectrow_query($form, $dbh, $query);
643
644   $query = qq|SELECT id, gldate
645               FROM gl
646               WHERE id = (SELECT max(id) FROM gl)|;
647   ($form->{previous_id}, $form->{previous_gldate}) = selectrow_query($form, $dbh, $query);
648
649   if ($form->{id}) {
650     $query =
651       qq|SELECT g.reference, g.description, g.notes, g.transdate, g.storno, g.storno_id,
652            d.description AS department, e.name AS employee, g.taxincluded, g.gldate,
653          g.ob_transaction, g.cb_transaction
654          FROM gl g
655          LEFT JOIN department d ON (d.id = g.department_id)
656          LEFT JOIN employee e ON (e.id = g.employee_id)
657          WHERE g.id = ?|;
658     $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
659     map { $form->{$_} = $ref->{$_} } keys %$ref;
660
661     # retrieve individual rows
662     $query =
663       qq|SELECT c.accno, t.taxkey AS accnotaxkey, a.amount, a.memo, a.source,
664            a.transdate, a.cleared, a.project_id, p.projectnumber,
665            a.taxkey, t.rate AS taxrate, t.id,
666            (SELECT c1.accno
667             FROM chart c1, tax t1
668             WHERE (t1.id = t.id) AND (c1.id = t.chart_id)) AS taxaccno,
669            (SELECT tk.tax_id
670             FROM taxkeys tk
671             WHERE (tk.chart_id = a.chart_id) AND (tk.startdate <= a.transdate)
672             ORDER BY tk.startdate desc LIMIT 1) AS tax_id
673          FROM acc_trans a
674          JOIN chart c ON (c.id = a.chart_id)
675          LEFT JOIN project p ON (p.id = a.project_id)
676          LEFT JOIN tax t ON
677            (t.id =
678              (SELECT tk.tax_id
679               FROM taxkeys tk
680               WHERE (tk.taxkey_id = a.taxkey) AND
681                 ((CASE WHEN a.chart_id IN
682                     (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
683                   THEN tk.chart_id = a.chart_id
684                   ELSE 1 = 1
685                   END)
686                  OR (c.link LIKE '%tax%'))
687                 AND (startdate <= a.transdate)
688               ORDER BY startdate DESC LIMIT 1))
689          WHERE (a.trans_id = ?)
690            AND (a.fx_transaction = '0')
691          ORDER BY a.acc_trans_id, a.transdate|;
692     $form->{GL} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
693
694   } else {
695     $query =
696       qq|SELECT COALESCE(
697            (SELECT transdate
698             FROM gl
699             WHERE id = (SELECT MAX(id) FROM gl)
700             LIMIT 1),
701            current_date)|;
702     ($form->{transdate}) = selectrow_query($form, $dbh, $query);
703   }
704
705   # get tax description
706   $query = qq|SELECT * FROM tax ORDER BY taxkey|;
707   $form->{TAX} = selectall_hashref_query($form, $dbh, $query);
708
709   # get chart of accounts
710   $query =
711     qq|SELECT c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id
712        FROM chart c
713        LEFT JOIN taxkeys tk ON (tk.id =
714          (SELECT id
715           FROM taxkeys
716           WHERE (taxkeys.chart_id = c.id)
717             AND (startdate <= ?)
718           ORDER BY startdate DESC
719           LIMIT 1))
720        ORDER BY c.accno|;
721   $form->{chart} = selectall_hashref_query($form, $dbh, $query, conv_date($form->{transdate}));
722
723   $dbh->disconnect;
724
725   $main::lxdebug->leave_sub();
726 }
727
728 sub storno {
729   $main::lxdebug->enter_sub();
730
731   my ($self, $form, $myconfig, $id) = @_;
732
733   my ($query, $new_id, $storno_row, $acc_trans_rows);
734   my $dbh = $form->get_standard_dbh($myconfig);
735
736   $query = qq|SELECT nextval('glid')|;
737   ($new_id) = selectrow_query($form, $dbh, $query);
738
739   $query = qq|SELECT * FROM gl WHERE id = ?|;
740   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
741
742   $storno_row->{id}        = $new_id;
743   $storno_row->{storno_id} = $id;
744   $storno_row->{storno}    = 't';
745   $storno_row->{reference} = 'Storno-' . $storno_row->{reference};
746
747   delete @$storno_row{qw(itime mtime gldate)};
748
749   $query = sprintf 'INSERT INTO gl (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
750   do_query($form, $dbh, $query, (values %$storno_row));
751
752   $query = qq|UPDATE gl SET storno = 't' WHERE id = ?|;
753   do_query($form, $dbh, $query, $id);
754
755   # now copy acc_trans entries
756   $query = qq|SELECT * FROM acc_trans WHERE trans_id = ?|;
757   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
758
759   for my $row (@$rowref) {
760     delete @$row{qw(itime mtime acc_trans_id gldate)};
761     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
762     $row->{trans_id}   = $new_id;
763     $row->{amount}    *= -1;
764     do_query($form, $dbh, $query, (values %$row));
765   }
766
767   $dbh->commit;
768
769   $main::lxdebug->leave_sub();
770 }
771
772 sub get_chart_balances {
773   $main::lxdebug->enter_sub();
774
775   my $self     = shift;
776   my %params   = @_;
777
778   Common::check_params(\%params, qw(charts));
779
780   my $myconfig = \%main::myconfig;
781   my $form     = $main::form;
782
783   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
784
785   my @ids      = map { $_->{id} } @{ $params{charts} };
786
787   if (!@ids) {
788     $main::lxdebug->leave_sub();
789     return;
790   }
791
792   my $query = qq|SELECT chart_id, SUM(amount) AS sum
793                  FROM acc_trans
794                  WHERE chart_id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)
795                  GROUP BY chart_id|;
796
797   my %balances = selectall_as_map($form, $dbh, $query, 'chart_id', 'sum', @ids);
798
799   foreach my $chart (@{ $params{charts} }) {
800     $chart->{balance} = $balances{ $chart->{id} } || 0;
801   }
802
803   $main::lxdebug->leave_sub();
804 }
805
806
807 1;