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