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