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