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