mebil
[kivitendo-erp.git] / SL / GL.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 # General ledger backend code
32 #
33 # CHANGE LOG:
34 #   DS. 2000-07-04  Created
35 #   DS. 2001-06-12  Changed relations from accno to chart_id
36 #
37 #======================================================================
38
39 package GL;
40
41 use Data::Dumper;
42 use SL::DATEV qw(:CONSTANTS);
43 use SL::DBUtils;
44
45 use strict;
46
47 sub delete_transaction {
48   my ($self, $myconfig, $form) = @_;
49   $main::lxdebug->enter_sub();
50
51   # connect to database
52   my $dbh = $form->dbconnect_noauto($myconfig);
53
54   # acc_trans entries are deleted by database triggers.
55   do_query($form, $dbh, qq|DELETE FROM gl WHERE id = ?|, conv_i($form->{id}));
56
57   # commit and redirect
58   my $rc = $dbh->commit;
59   $dbh->disconnect;
60   $main::lxdebug->leave_sub();
61
62   $rc;
63
64 }
65
66 sub post_transaction {
67   my ($self, $myconfig, $form) = @_;
68   $main::lxdebug->enter_sub();
69
70   my ($debit, $credit) = (0, 0);
71   my $project_id;
72
73   my $i;
74
75   # connect to database, turn off AutoCommit
76   my $dbh = $form->dbconnect_noauto($myconfig);
77
78   # post the transaction
79   # make up a unique handle and store in reference field
80   # then retrieve the record based on the unique handle to get the id
81   # replace the reference field with the actual variable
82   # add records to acc_trans
83
84   # if there is a $form->{id} replace the old transaction
85   # delete all acc_trans entries and add the new ones
86
87   if (!$form->{taxincluded}) {
88     $form->{taxincluded} = 0;
89   }
90
91   my ($query, $sth, @values, $taxkey, $rate, $posted);
92
93   if ($form->{id}) {
94
95     # delete individual transactions
96     $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
97     @values = (conv_i($form->{id}));
98     do_query($form, $dbh, $query, @values);
99
100   } else {
101     $query = qq|SELECT nextval('glid')|;
102     ($form->{id}) = selectrow_query($form, $dbh, $query);
103
104     $query =
105       qq|INSERT INTO gl (id, employee_id) | .
106       qq|VALUES (?, (SELECT id FROM employee WHERE login = ?))|;
107     @values = ($form->{id}, $::myconfig{login});
108     do_query($form, $dbh, $query, @values);
109   }
110
111   my ($null, $department_id) = split(/--/, $form->{department});
112
113   $form->{ob_transaction} *= 1;
114   $form->{cb_transaction} *= 1;
115
116   $query =
117     qq|UPDATE gl SET
118          reference = ?, description = ?, notes = ?,
119          transdate = ?, department_id = ?, taxincluded = ?,
120          storno = ?, storno_id = ?, ob_transaction = ?, cb_transaction = ?
121        WHERE id = ?|;
122
123   @values = ($form->{reference}, $form->{description}, $form->{notes},
124              conv_date($form->{transdate}), conv_i($department_id), $form->{taxincluded} ? 't' : 'f',
125              $form->{storno} ? 't' : 'f', conv_i($form->{storno_id}), $form->{ob_transaction} ? 't' : 'f', $form->{cb_transaction} ? 't' : 'f',
126              conv_i($form->{id}));
127   do_query($form, $dbh, $query, @values);
128
129   # insert acc_trans transactions
130   for $i (1 .. $form->{rowcount}) {
131     # extract accno
132     my ($accno) = split(/--/, $form->{"accno_$i"});
133     ($form->{"tax_id_$i"}) = split(/--/, $form->{"taxchart_$i"});
134     if ($form->{"tax_id_$i"} ne "") {
135       $query = qq|SELECT taxkey, rate FROM tax WHERE id = ?|;
136       ($taxkey, $rate) = selectrow_query($form, $dbh, $query, conv_i($form->{"tax_id_$i"}));
137     }
138
139     my $amount = 0;
140     my $debit  = $form->{"debit_$i"};
141     my $credit = $form->{"credit_$i"};
142     my $tax    = $form->{"tax_$i"};
143
144     if ($credit) {
145       $amount = $credit;
146       $posted = 0;
147     }
148     if ($debit) {
149       $amount = $debit * -1;
150       $tax    = $tax * -1;
151       $posted = 0;
152     }
153
154     $project_id = conv_i($form->{"project_id_$i"});
155
156     # if there is an amount, add the record
157     if ($amount != 0) {
158       $query =
159         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
160                                   source, memo, project_id, taxkey, ob_transaction, cb_transaction, tax_id, chart_link)
161            VALUES (?, (SELECT id FROM chart WHERE accno = ?),
162                    ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT link FROM chart WHERE accno = ?))|;
163       @values = (conv_i($form->{id}), $accno, $amount, conv_date($form->{transdate}),
164                  $form->{"source_$i"}, $form->{"memo_$i"}, $project_id, $taxkey, $form->{ob_transaction} ? 't' : 'f', $form->{cb_transaction} ? 't' : 'f', conv_i($form->{"tax_id_$i"}), $accno);
165       do_query($form, $dbh, $query, @values);
166     }
167
168     if ($tax != 0) {
169       # add taxentry
170       $query =
171         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
172                                   source, memo, project_id, taxkey, tax_id, chart_link)
173            VALUES (?, (SELECT chart_id FROM tax WHERE id = ?),
174                    ?, ?, ?, ?, ?, ?, ?, (SELECT link
175                                          FROM chart
176                                          WHERE id = (SELECT chart_id
177                                                      FROM tax
178                                                      WHERE id = ?)))|;
179       @values = (conv_i($form->{id}), conv_i($form->{"tax_id_$i"}),
180                  $tax, conv_date($form->{transdate}), $form->{"source_$i"},
181                  $form->{"memo_$i"}, $project_id, $taxkey, conv_i($form->{"tax_id_$i"}), conv_i($form->{"tax_id_$i"}));
182       do_query($form, $dbh, $query, @values);
183     }
184   }
185
186   if ($form->{storno} && $form->{storno_id}) {
187     do_query($form, $dbh, qq|UPDATE gl SET storno = 't' WHERE id = ?|, conv_i($form->{storno_id}));
188   }
189
190   # safety check datev export
191   if ($::instance_conf->get_datev_check_on_gl_transaction) {
192     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
193     $transdate  ||= DateTime->today;
194
195     my $datev = SL::DATEV->new(
196       exporttype => DATEV_ET_BUCHUNGEN,
197       format     => DATEV_FORMAT_KNE,
198       dbh        => $dbh,
199       trans_id   => $form->{id},
200     );
201
202     $datev->export;
203
204     if ($datev->errors) {
205       $dbh->rollback;
206       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
207     }
208   }
209
210   # commit and redirect
211   my $rc = $dbh->commit;
212   $dbh->disconnect;
213   $main::lxdebug->leave_sub();
214
215   return $rc;
216 }
217
218 sub all_transactions {
219   my ($self, $myconfig, $form) = @_;
220   $main::lxdebug->enter_sub();
221
222   # connect to database
223   my $dbh = $form->dbconnect($myconfig);
224   my ($query, $sth, $source, $null, $space);
225
226   my ($glwhere, $arwhere, $apwhere) = ("1 = 1", "1 = 1", "1 = 1");
227   my (@glvalues, @arvalues, @apvalues);
228
229   if ($form->{reference}) {
230     $glwhere .= qq| AND g.reference ILIKE ?|;
231     $arwhere .= qq| AND a.invnumber ILIKE ?|;
232     $apwhere .= qq| AND a.invnumber ILIKE ?|;
233     push(@glvalues, '%' . $form->{reference} . '%');
234     push(@arvalues, '%' . $form->{reference} . '%');
235     push(@apvalues, '%' . $form->{reference} . '%');
236   }
237
238   if ($form->{department}) {
239     my ($null, $department) = split /--/, $form->{department};
240     $glwhere .= qq| AND g.department_id = ?|;
241     $arwhere .= qq| AND a.department_id = ?|;
242     $apwhere .= qq| AND a.department_id = ?|;
243     push(@glvalues, $department);
244     push(@arvalues, $department);
245     push(@apvalues, $department);
246   }
247
248   if ($form->{source}) {
249     $glwhere .= " AND ac.trans_id IN (SELECT trans_id from acc_trans WHERE source ILIKE ?)";
250     $arwhere .= " AND ac.trans_id IN (SELECT trans_id from acc_trans WHERE source ILIKE ?)";
251     $apwhere .= " AND ac.trans_id IN (SELECT trans_id from acc_trans WHERE source ILIKE ?)";
252     push(@glvalues, '%' . $form->{source} . '%');
253     push(@arvalues, '%' . $form->{source} . '%');
254     push(@apvalues, '%' . $form->{source} . '%');
255   }
256
257   # default Datumseinschränkung falls nicht oder falsch Ã¼bergeben (sollte nie passieren)
258   $form->{datesort} = 'transdate' unless $form->{datesort} =~ /^(transdate|gldate)$/;
259
260   if ($form->{datefrom}) {
261     $glwhere .= " AND ac.$form->{datesort} >= ?";
262     $arwhere .= " AND ac.$form->{datesort} >= ?";
263     $apwhere .= " AND ac.$form->{datesort} >= ?";
264     push(@glvalues, $form->{datefrom});
265     push(@arvalues, $form->{datefrom});
266     push(@apvalues, $form->{datefrom});
267   }
268
269   if ($form->{dateto}) {
270     $glwhere .= " AND ac.$form->{datesort} <= ?";
271     $arwhere .= " AND ac.$form->{datesort} <= ?";
272     $apwhere .= " AND ac.$form->{datesort} <= ?";
273     push(@glvalues, $form->{dateto});
274     push(@arvalues, $form->{dateto});
275     push(@apvalues, $form->{dateto});
276   }
277
278   if ($form->{description}) {
279     $glwhere .= " AND g.description ILIKE ?";
280     $arwhere .= " AND ct.name ILIKE ?";
281     $apwhere .= " AND ct.name ILIKE ?";
282     push(@glvalues, '%' . $form->{description} . '%');
283     push(@arvalues, '%' . $form->{description} . '%');
284     push(@apvalues, '%' . $form->{description} . '%');
285   }
286
287   if ($form->{employee_id}) {
288     $glwhere .= " AND g.employee_id = ? ";
289     $arwhere .= " AND a.employee_id = ? ";
290     $apwhere .= " AND a.employee_id = ? ";
291     push(@glvalues, conv_i($form->{employee_id}));
292     push(@arvalues, conv_i($form->{employee_id}));
293     push(@apvalues, conv_i($form->{employee_id}));
294   }
295
296   if ($form->{notes}) {
297     $glwhere .= " AND g.notes ILIKE ?";
298     $arwhere .= " AND a.notes ILIKE ?";
299     $apwhere .= " AND a.notes ILIKE ?";
300     push(@glvalues, '%' . $form->{notes} . '%');
301     push(@arvalues, '%' . $form->{notes} . '%');
302     push(@apvalues, '%' . $form->{notes} . '%');
303   }
304
305   if ($form->{accno}) {
306     $glwhere .= " AND c.accno = '$form->{accno}'";
307     $arwhere .= " AND c.accno = '$form->{accno}'";
308     $apwhere .= " AND c.accno = '$form->{accno}'";
309   }
310
311   if ($form->{category} ne 'X') {
312     $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 = ?))|;
313     $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 = ?))|;
314     $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 = ?))|;
315     push(@glvalues, $form->{category});
316     push(@arvalues, $form->{category});
317     push(@apvalues, $form->{category});
318   }
319
320   if ($form->{project_id}) {
321     $glwhere .= qq| AND g.id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE project_id = ?)|;
322     $arwhere .=
323       qq| AND ((a.globalproject_id = ?) OR
324                (a.id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE project_id = ?)))|;
325     $apwhere .=
326       qq| AND ((a.globalproject_id = ?) OR
327                (a.id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE project_id = ?)))|;
328     my $project_id = conv_i($form->{project_id});
329     push(@glvalues, $project_id);
330     push(@arvalues, $project_id, $project_id);
331     push(@apvalues, $project_id, $project_id);
332   }
333
334   my ($project_columns, $project_join);
335   if ($form->{"l_projectnumbers"}) {
336     $project_columns = qq|, ac.project_id, pr.projectnumber|;
337     $project_join = qq|LEFT JOIN project pr ON (ac.project_id = pr.id)|;
338   }
339
340   if ($form->{accno}) {
341     # get category for account
342     $query = qq|SELECT category FROM chart WHERE accno = ?|;
343     ($form->{ml}) = selectrow_query($form, $dbh, $query, $form->{accno});
344
345     if ($form->{datefrom}) {
346       $query =
347         qq|SELECT SUM(ac.amount)
348            FROM acc_trans ac
349            LEFT JOIN chart c ON (ac.chart_id = c.id)
350            WHERE (c.accno = ?) AND (ac.$form->{datesort} < ?)|;
351       ($form->{balance}) = selectrow_query($form, $dbh, $query, $form->{accno}, conv_date($form->{datefrom}));
352     }
353   }
354
355   my %sort_columns =  (
356     'id'           => [ qw(id)                   ],
357     'transdate'    => [ qw(transdate id)         ],
358     'gldate'       => [ qw(gldate id)         ],
359     'reference'    => [ qw(lower_reference id)   ],
360     'description'  => [ qw(lower_description id) ],
361     'accno'        => [ qw(accno transdate id)   ],
362     );
363   my %lowered_columns =  (
364     'reference'       => { 'gl' => 'g.reference',   'arap' => 'a.invnumber', },
365     'source'          => { 'gl' => 'ac.source',     'arap' => 'ac.source',   },
366     'description'     => { 'gl' => 'g.description', 'arap' => 'ct.name',     },
367     );
368
369   # sortdir = sort direction (ascending or descending)
370   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
371   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : $form->{datesort};  # default used to be transdate
372   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
373
374   my %columns_for_sorting = ( 'gl' => '', 'arap' => '', );
375   foreach my $spec (@{ $sort_columns{$sortkey} }) {
376     next if ($spec !~ m/^lower_(.*)$/);
377
378     my $column = $1;
379     map { $columns_for_sorting{$_} .= sprintf(', lower(%s) AS lower_%s', $lowered_columns{$column}->{$_}, $column) } qw(gl arap);
380   }
381
382   $query =
383     qq|SELECT
384         ac.acc_trans_id, g.id, 'gl' AS type, FALSE AS invoice, g.reference, ac.taxkey, c.link,
385         g.description, ac.transdate, ac.gldate, ac.source, ac.trans_id,
386         ac.amount, c.accno, g.notes, t.chart_id,
387         CASE WHEN (COALESCE(e.name, '') = '') THEN e.login ELSE e.name END AS employee
388         $project_columns
389         $columns_for_sorting{gl}
390       FROM gl g
391       LEFT JOIN employee e ON (g.employee_id = e.id),
392       acc_trans ac $project_join, chart c
393       LEFT JOIN tax t ON (t.chart_id = c.id)
394       WHERE $glwhere
395         AND (ac.chart_id = c.id)
396         AND (g.id = ac.trans_id)
397
398       UNION
399
400       SELECT ac.acc_trans_id, a.id, 'ar' AS type, a.invoice, a.invnumber, ac.taxkey, c.link,
401         ct.name, ac.transdate, ac.gldate, ac.source, ac.trans_id,
402         ac.amount, c.accno, a.notes, t.chart_id,
403         CASE WHEN (COALESCE(e.name, '') = '') THEN e.login ELSE e.name END AS employee
404         $project_columns
405         $columns_for_sorting{arap}
406       FROM ar a
407       LEFT JOIN employee e ON (a.employee_id = e.id),
408       acc_trans ac $project_join, customer ct, chart c
409       LEFT JOIN tax t ON (t.chart_id=c.id)
410       WHERE $arwhere
411         AND (ac.chart_id = c.id)
412         AND (a.customer_id = ct.id)
413         AND (a.id = ac.trans_id)
414
415       UNION
416
417       SELECT ac.acc_trans_id, a.id, 'ap' AS type, a.invoice, a.invnumber, ac.taxkey, c.link,
418         ct.name, ac.transdate, ac.gldate, ac.source, ac.trans_id,
419         ac.amount, c.accno, a.notes, t.chart_id,
420         CASE WHEN (COALESCE(e.name, '') = '') THEN e.login ELSE e.name END AS employee
421         $project_columns
422         $columns_for_sorting{arap}
423       FROM ap a
424       LEFT JOIN employee e ON (a.employee_id = e.id),
425       acc_trans ac $project_join, vendor ct, chart c
426       LEFT JOIN tax t ON (t.chart_id=c.id)
427       WHERE $apwhere
428         AND (ac.chart_id = c.id)
429         AND (a.vendor_id = ct.id)
430         AND (a.id = ac.trans_id)
431
432       ORDER BY $sortorder, acc_trans_id $sortdir|;
433 #      ORDER BY gldate DESC, id DESC, acc_trans_id DESC
434
435   my @values = (@glvalues, @arvalues, @apvalues);
436
437   # Show all $query in Debuglevel LXDebug::QUERY
438   my $callingdetails = (caller (0))[3];
439   dump_query(LXDebug->QUERY(), "$callingdetails", $query, @values);
440
441   $sth = prepare_execute_query($form, $dbh, $query, @values);
442   my $trans_id  = "";
443   my $trans_id2 = "";
444   my $balance;
445
446   my ($i, $j, $k, $l, $ref, $ref2);
447
448   $form->{GL} = [];
449   while (my $ref0 = $sth->fetchrow_hashref("NAME_lc")) {
450
451     $trans_id = $ref0->{id};
452
453     my $source = $ref0->{source};
454     undef($ref0->{source});
455
456     if ($trans_id != $trans_id2) { # first line of a booking
457
458       if ($trans_id2) {
459         push(@{ $form->{GL} }, $ref);
460         $balance = 0;
461       }
462
463       $ref       = $ref0;
464       $trans_id2 = $ref->{id};
465
466       # gl
467       if ($ref->{type} eq "gl") {
468         $ref->{module} = "gl";
469       }
470
471       # ap
472       if ($ref->{type} eq "ap") {
473         if ($ref->{invoice}) {
474           $ref->{module} = "ir";
475         } else {
476           $ref->{module} = "ap";
477         }
478       }
479
480       # ar
481       if ($ref->{type} eq "ar") {
482         if ($ref->{invoice}) {
483           $ref->{module} = "is";
484         } else {
485           $ref->{module} = "ar";
486         }
487       }
488
489       $ref->{"projectnumbers"} = {};
490       $ref->{"projectnumbers"}->{$ref->{"projectnumber"}} = 1 if ($ref->{"projectnumber"});
491
492       $balance = $ref->{amount};
493
494       # Linenumbers of General Ledger
495       $k       = 0; # Debit      # AP      # Soll
496       $l       = 0; # Credit     # AR      # Haben
497       $i       = 0; # Debit Tax  # AP_tax  # VSt
498       $j       = 0; # Credit Tax # AR_tax  # USt
499
500       if ($ref->{chart_id} > 0) { # all tax accounts first line, no line increasing
501         if ($ref->{amount} < 0) {
502           if ($ref->{link} =~ /AR_tax/) {
503             $ref->{credit_tax}{$j}       = $ref->{amount};
504             $ref->{credit_tax_accno}{$j} = $ref->{accno};
505          }
506           if ($ref->{link} =~ /AP_tax/) {
507             $ref->{debit_tax}{$i}       = $ref->{amount} * -1;
508             $ref->{debit_tax_accno}{$i} = $ref->{accno};
509           }
510         } else {
511           if ($ref->{link} =~ /AR_tax/) {
512             $ref->{credit_tax}{$j}       = $ref->{amount};
513             $ref->{credit_tax_accno}{$j} = $ref->{accno};
514           }
515           if ($ref->{link} =~ /AP_tax/) {
516             $ref->{debit_tax}{$i}       = $ref->{amount} * -1;
517             $ref->{debit_tax_accno}{$i} = $ref->{accno};
518           }
519         }
520       } else { #all other accounts first line
521
522         if ($ref->{amount} < 0) {
523           $ref->{debit}{$k}        = $ref->{amount} * -1;
524           $ref->{debit_accno}{$k}  = $ref->{accno};
525           $ref->{debit_taxkey}{$k} = $ref->{taxkey};
526           $ref->{ac_transdate}{$k} = $ref->{transdate};
527           $ref->{source}{$k}       = $source;
528         } else {
529           $ref->{credit}{$l}        = $ref->{amount} * 1;
530           $ref->{credit_accno}{$l}  = $ref->{accno};
531           $ref->{credit_taxkey}{$l} = $ref->{taxkey};
532           $ref->{ac_transdate}{$l}  = $ref->{transdate};
533           $ref->{source}{$l}        = $source;
534         }
535       }
536
537     } else { # following lines of a booking, line increasing
538
539       $ref2      = $ref0;
540 #      $trans_old = $trans_id2;   # doesn't seem to be used anymore
541       $trans_id2 = $ref2->{id};
542
543       $balance =
544         (int($balance * 100000) + int(100000 * $ref2->{amount})) / 100000;
545
546       $ref->{"projectnumbers"}->{$ref2->{"projectnumber"}} = 1 if ($ref2->{"projectnumber"});
547
548       if ($ref2->{chart_id} > 0) { # all tax accounts, following lines
549         if ($ref2->{amount} < 0) {
550           if ($ref2->{link} =~ /AR_tax/) {
551             if ($ref->{credit_tax_accno}{$j} ne "") {
552               $j++;
553             }
554             $ref->{credit_tax}{$j}       = $ref2->{amount};
555             $ref->{credit_tax_accno}{$j} = $ref2->{accno};
556           }
557           if ($ref2->{link} =~ /AP_tax/) {
558             if ($ref->{debit_tax_accno}{$i} ne "") {
559               $i++;
560             }
561             $ref->{debit_tax}{$i}       = $ref2->{amount} * -1;
562             $ref->{debit_tax_accno}{$i} = $ref2->{accno};
563           }
564         } else {
565           if ($ref2->{link} =~ /AR_tax/) {
566             if ($ref->{credit_tax_accno}{$j} ne "") {
567               $j++;
568             }
569             $ref->{credit_tax}{$j}       = $ref2->{amount};
570             $ref->{credit_tax_accno}{$j} = $ref2->{accno};
571           }
572           if ($ref2->{link} =~ /AP_tax/) {
573             if ($ref->{debit_tax_accno}{$i} ne "") {
574               $i++;
575             }
576             $ref->{debit_tax}{$i}       = $ref2->{amount} * -1;
577             $ref->{debit_tax_accno}{$i} = $ref2->{accno};
578           }
579         }
580       } else { # all other accounts, following lines
581         if ($ref2->{amount} < 0) {
582           if ($ref->{debit_accno}{$k} ne "") {
583             $k++;
584           }
585           if ($ref->{source}{$k} ne "") {
586             $space = " | ";
587           } else {
588             $space = "";
589           }
590           $ref->{debit}{$k}        = $ref2->{amount} * - 1;
591           $ref->{debit_accno}{$k}  = $ref2->{accno};
592           $ref->{debit_taxkey}{$k} = $ref2->{taxkey};
593           $ref->{ac_transdate}{$k} = $ref2->{transdate};
594           $ref->{source}{$k}       = $source . $space . $ref->{source}{$k};
595         } else {
596           if ($ref->{credit_accno}{$l} ne "") {
597             $l++;
598           }
599           if ($ref->{source}{$l} ne "") {
600             $space = " | ";
601           } else {
602             $space = "";
603           }
604           $ref->{credit}{$l}        = $ref2->{amount};
605           $ref->{credit_accno}{$l}  = $ref2->{accno};
606           $ref->{credit_taxkey}{$l} = $ref2->{taxkey};
607           $ref->{ac_transdate}{$l}  = $ref2->{transdate};
608           $ref->{source}{$l}        = $ref->{source}{$l} . $space . $source;
609         }
610       }
611     }
612   }
613
614   push @{ $form->{GL} }, $ref;
615   $sth->finish;
616
617   if ($form->{accno}) {
618     $query = qq|SELECT c.description FROM chart c WHERE c.accno = ?|;
619     ($form->{account_description}) = selectrow_query($form, $dbh, $query, $form->{accno});
620   }
621
622   $dbh->disconnect;
623
624   $main::lxdebug->leave_sub();
625 }
626
627 sub transaction {
628   my ($self, $myconfig, $form) = @_;
629   $main::lxdebug->enter_sub();
630
631   my ($query, $sth, $ref, @values);
632
633   # connect to database
634   my $dbh = $form->dbconnect($myconfig);
635
636   $query = qq|SELECT closedto, revtrans FROM defaults|;
637   ($form->{closedto}, $form->{revtrans}) = selectrow_query($form, $dbh, $query);
638
639   $query = qq|SELECT id, gldate
640               FROM gl
641               WHERE id = (SELECT max(id) FROM gl)|;
642   ($form->{previous_id}, $form->{previous_gldate}) = selectrow_query($form, $dbh, $query);
643
644   if ($form->{id}) {
645     $query =
646       qq|SELECT g.reference, g.description, g.notes, g.transdate, g.storno, g.storno_id,
647            d.description AS department, e.name AS employee, g.taxincluded, g.gldate,
648          g.ob_transaction, g.cb_transaction
649          FROM gl g
650          LEFT JOIN department d ON (d.id = g.department_id)
651          LEFT JOIN employee e ON (e.id = g.employee_id)
652          WHERE g.id = ?|;
653     $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
654     map { $form->{$_} = $ref->{$_} } keys %$ref;
655
656     # retrieve individual rows
657     $query =
658       qq|SELECT c.accno, t.taxkey AS accnotaxkey, a.amount, a.memo, a.source,
659            a.transdate, a.cleared, a.project_id, p.projectnumber,
660            a.taxkey, t.rate AS taxrate, t.id,
661            (SELECT c1.accno
662             FROM chart c1, tax t1
663             WHERE (t1.id = t.id) AND (c1.id = t.chart_id)) AS taxaccno,
664            (SELECT tk.tax_id
665             FROM taxkeys tk
666             WHERE (tk.chart_id = a.chart_id) AND (tk.startdate <= a.transdate)
667             ORDER BY tk.startdate desc LIMIT 1) AS tax_id
668          FROM acc_trans a
669          JOIN chart c ON (c.id = a.chart_id)
670          LEFT JOIN project p ON (p.id = a.project_id)
671          LEFT JOIN tax t ON (t.id = a.tax_id)
672          WHERE (a.trans_id = ?)
673            AND (a.fx_transaction = '0')
674          ORDER BY a.acc_trans_id, a.transdate|;
675     $form->{GL} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
676
677   } else {
678     $query =
679       qq|SELECT COALESCE(
680            (SELECT transdate
681             FROM gl
682             WHERE id = (SELECT MAX(id) FROM gl)
683             LIMIT 1),
684            current_date)|;
685     ($form->{transdate}) = selectrow_query($form, $dbh, $query);
686   }
687
688   # get tax description
689   $query = qq|SELECT * FROM tax ORDER BY taxkey|;
690   $form->{TAX} = selectall_hashref_query($form, $dbh, $query);
691
692   # get chart of accounts
693   $query =
694     qq|SELECT c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id
695        FROM chart c
696        LEFT JOIN taxkeys tk ON (tk.id =
697          (SELECT id
698           FROM taxkeys
699           WHERE (taxkeys.chart_id = c.id)
700             AND (startdate <= ?)
701           ORDER BY startdate DESC
702           LIMIT 1))
703        ORDER BY c.accno|;
704   $form->{chart} = selectall_hashref_query($form, $dbh, $query, conv_date($form->{transdate}));
705
706   $dbh->disconnect;
707
708   $main::lxdebug->leave_sub();
709 }
710
711 sub storno {
712   $main::lxdebug->enter_sub();
713
714   my ($self, $form, $myconfig, $id) = @_;
715
716   my ($query, $new_id, $storno_row, $acc_trans_rows);
717   my $dbh = $form->get_standard_dbh($myconfig);
718
719   $query = qq|SELECT nextval('glid')|;
720   ($new_id) = selectrow_query($form, $dbh, $query);
721
722   $query = qq|SELECT * FROM gl WHERE id = ?|;
723   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
724
725   $storno_row->{id}          = $new_id;
726   $storno_row->{storno_id}   = $id;
727   $storno_row->{storno}      = 't';
728   $storno_row->{reference}   = 'Storno-' . $storno_row->{reference};
729
730   $query = qq|SELECT id FROM employee WHERE login = ?|;
731   my ($employee_id) = selectrow_query($form, $dbh, $query, $::myconfig{login});
732   $storno_row->{employee_id} = $employee_id;
733
734   delete @$storno_row{qw(itime mtime gldate)};
735
736   $query = sprintf 'INSERT INTO gl (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
737   do_query($form, $dbh, $query, (values %$storno_row));
738
739   $query = qq|UPDATE gl SET storno = 't' WHERE id = ?|;
740   do_query($form, $dbh, $query, $id);
741
742   # now copy acc_trans entries
743   $query = qq|SELECT * FROM acc_trans WHERE trans_id = ?|;
744   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
745
746   for my $row (@$rowref) {
747     delete @$row{qw(itime mtime acc_trans_id gldate)};
748     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
749     $row->{trans_id}   = $new_id;
750     $row->{amount}    *= -1;
751     do_query($form, $dbh, $query, (values %$row));
752   }
753
754   $dbh->commit;
755
756   $main::lxdebug->leave_sub();
757 }
758
759 sub get_chart_balances {
760   $main::lxdebug->enter_sub();
761
762   my $self     = shift;
763   my %params   = @_;
764
765   Common::check_params(\%params, qw(charts));
766
767   my $myconfig = \%main::myconfig;
768   my $form     = $main::form;
769
770   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
771
772   my @ids      = map { $_->{id} } @{ $params{charts} };
773
774   if (!@ids) {
775     $main::lxdebug->leave_sub();
776     return;
777   }
778
779   my $query = qq|SELECT chart_id, SUM(amount) AS sum
780                  FROM acc_trans
781                  WHERE chart_id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)
782                  GROUP BY chart_id|;
783
784   my %balances = selectall_as_map($form, $dbh, $query, 'chart_id', 'sum', @ids);
785
786   foreach my $chart (@{ $params{charts} }) {
787     $chart->{balance} = $balances{ $chart->{id} } || 0;
788   }
789
790   $main::lxdebug->leave_sub();
791 }
792
793 sub get_tax_dropdown {
794   my ($self, $accno) = @_;
795
796   my $myconfig = \%main::myconfig;
797   my $form = $main::form;
798
799   my $dbh = $form->get_standard_dbh($myconfig);
800
801   my $query = qq|SELECT category FROM chart WHERE accno = ?|;
802   my ($category) = selectrow_query($form, $dbh, $query, $accno);
803
804   $query = qq|SELECT * FROM tax WHERE chart_categories like '%$category%' order by taxkey, rate|;
805
806   my $sth = prepare_execute_query($form, $dbh, $query);
807
808   my @tax_accounts = ();
809   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
810     push(@tax_accounts, $ref);
811   }
812
813   return @tax_accounts;
814 }
815
816 1;