Merge von 774 aus unstable: Bugfix - Nachtrag zu R740 - Bugfix 179
[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 sub delete_transaction {
42   my ($self, $myconfig, $form) = @_;
43   $main::lxdebug->enter_sub();
44
45   # connect to database
46   my $dbh = $form->dbconnect_noauto($myconfig);
47
48   my $query = qq|DELETE FROM gl WHERE id = $form->{id}|;
49   $dbh->do($query) || $form->dberror($query);
50
51   $query = qq|DELETE FROM acc_trans WHERE trans_id = $form->{id}|;
52   $dbh->do($query) || $form->dberror($query);
53
54   # commit and redirect
55   my $rc = $dbh->commit;
56   $dbh->disconnect;
57   $main::lxdebug->leave_sub();
58
59   $rc;
60
61 }
62
63 sub post_transaction {
64   my ($self, $myconfig, $form) = @_;
65   $main::lxdebug->enter_sub();
66
67   my ($debit, $credit) = (0, 0);
68   my $project_id;
69
70   my $i;
71
72   # check if debit and credit balances
73
74   if ($form->{storno}) {
75     $debit               = $debit * -1;
76     $credit              = $credit * -1;
77     $tax                 = $tax * -1;
78     $form->{reference}   = "Storno-" . $form->{reference};
79     $form->{description} = "Storno-" . $form->{description};
80   }
81
82   # connect to database, turn off AutoCommit
83   my $dbh = $form->dbconnect_noauto($myconfig);
84
85   # post the transaction
86   # make up a unique handle and store in reference field
87   # then retrieve the record based on the unique handle to get the id
88   # replace the reference field with the actual variable
89   # add records to acc_trans
90
91   # if there is a $form->{id} replace the old transaction
92   # delete all acc_trans entries and add the new ones
93
94   # escape '
95   map { $form->{$_} =~ s/\'/\'\'/g } qw(reference description notes);
96
97   if (!$form->{taxincluded}) {
98     $form->{taxincluded} = 0;
99   }
100
101   my ($query, $sth);
102
103   if ($form->{id}) {
104
105     # delete individual transactions
106     $query = qq|DELETE FROM acc_trans 
107                 WHERE trans_id = $form->{id}|;
108     $dbh->do($query) || $form->dberror($query);
109
110   } else {
111     my $uid = time;
112     $uid .= $form->{login};
113
114     $query = qq|INSERT INTO gl (reference, employee_id)
115                 VALUES ('$uid', (SELECT e.id FROM employee e
116                                  WHERE e.login = '$form->{login}'))|;
117     $dbh->do($query) || $form->dberror($query);
118
119     $query = qq|SELECT g.id FROM gl g
120                 WHERE g.reference = '$uid'|;
121     $sth = $dbh->prepare($query);
122     $sth->execute || $form->dberror($query);
123
124     ($form->{id}) = $sth->fetchrow_array;
125     $sth->finish;
126
127   }
128
129   my ($null, $department_id) = split /--/, $form->{department};
130   $department_id *= 1;
131
132   $query = qq|UPDATE gl SET 
133               reference = '$form->{reference}',
134               description = '$form->{description}',
135               notes = '$form->{notes}',
136               transdate = '$form->{transdate}',
137               department_id = $department_id,
138               taxincluded = '$form->{taxincluded}'
139               WHERE id = $form->{id}|;
140
141   $dbh->do($query) || $form->dberror($query);
142   ($taxkey, $rate) = split(/--/, $form->{taxkey});
143
144   # insert acc_trans transactions
145   for $i (1 .. $form->{rowcount}) {
146
147     # extract accno
148     my ($accno) = split(/--/, $form->{"accno_$i"});
149     my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
150     my $amount = 0;
151     my $debit  = $form->{"debit_$i"};
152     my $credit = $form->{"credit_$i"};
153     my $tax    = $form->{"tax_$i"};
154
155     if ($credit) {
156       $amount = $credit;
157       $posted = 0;
158     }
159     if ($debit) {
160       $amount = $debit * -1;
161       $tax    = $tax * -1;
162       $posted = 0;
163     }
164
165     # if there is an amount, add the record
166     if ($amount != 0) {
167       $project_id =
168         ($form->{"project_id_$i"}) ? $form->{"project_id_$i"} : 'NULL';
169       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
170                   source, memo, project_id, taxkey)
171                   VALUES
172                   ($form->{id}, (SELECT c.id
173                                  FROM chart c
174                                  WHERE c.accno = '$accno'),
175                    $amount, '$form->{transdate}', |
176         . $dbh->quote($form->{"source_$i"}) . qq|, |
177         . $dbh->quote($form->{"memo_$i"}) . qq|,
178                   $project_id, $taxkey)|;
179
180       $dbh->do($query) || $form->dberror($query);
181     }
182
183     if ($tax != 0) {
184
185       # add taxentry
186       $amount = $tax;
187
188       $project_id =
189         ($form->{"project_id_$i"}) ? $form->{"project_id_$i"} : 'NULL';
190       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
191                   source, memo, project_id, taxkey)
192                   VALUES
193                   ($form->{id}, (SELECT t.chart_id
194                   FROM tax t
195                   WHERE t.taxkey = $taxkey),
196                   $amount, '$form->{transdate}', |
197         . $dbh->quote($form->{"source_$i"}) . qq|, |
198         . $dbh->quote($form->{"memo_$i"}) . qq|,
199                           $project_id, $taxkey)|;
200
201       $dbh->do($query) || $form->dberror($query);
202     }
203   }
204
205   my %audittrail = (tablename => 'gl',
206                     reference => $form->{reference},
207                     formname  => 'transaction',
208                     action    => 'posted',
209                     id        => $form->{id});
210
211   # $form->audittrail($dbh, "", \%audittrail);
212
213   # commit and redirect
214   my $rc = $dbh->commit;
215   $dbh->disconnect;
216   $main::lxdebug->leave_sub();
217
218   $rc;
219
220 }
221
222 sub all_transactions {
223   my ($self, $myconfig, $form) = @_;
224   $main::lxdebug->enter_sub();
225
226   # connect to database
227   my $dbh = $form->dbconnect($myconfig);
228   my ($query, $sth, $source, $null);
229
230   my ($glwhere, $arwhere, $apwhere) = ("1 = 1", "1 = 1", "1 = 1");
231
232   if ($form->{reference}) {
233     $source = $form->like(lc $form->{reference});
234     $glwhere .= " AND lower(g.reference) LIKE '$source'";
235     $arwhere .= " AND lower(a.invnumber) LIKE '$source'";
236     $apwhere .= " AND lower(a.invnumber) LIKE '$source'";
237   }
238   if ($form->{department}) {
239     ($null, $source) = split /--/, $form->{department};
240     $glwhere .= " AND g.department_id = $source";
241     $arwhere .= " AND a.department_id = $source";
242     $apwhere .= " AND a.department_id = $source";
243   }
244
245   if ($form->{source}) {
246     $source = $form->like(lc $form->{source});
247     $glwhere .= " AND lower(ac.source) LIKE '$source'";
248     $arwhere .= " AND lower(ac.source) LIKE '$source'";
249     $apwhere .= " AND lower(ac.source) LIKE '$source'";
250   }
251   if ($form->{datefrom}) {
252     $glwhere .= " AND ac.transdate >= '$form->{datefrom}'";
253     $arwhere .= " AND ac.transdate >= '$form->{datefrom}'";
254     $apwhere .= " AND ac.transdate >= '$form->{datefrom}'";
255   }
256   if ($form->{dateto}) {
257     $glwhere .= " AND ac.transdate <= '$form->{dateto}'";
258     $arwhere .= " AND ac.transdate <= '$form->{dateto}'";
259     $apwhere .= " AND ac.transdate <= '$form->{dateto}'";
260   }
261   if ($form->{description}) {
262     my $description = $form->like(lc $form->{description});
263     $glwhere .= " AND lower(g.description) LIKE '$description'";
264     $arwhere .= " AND lower(ct.name) LIKE '$description'";
265     $apwhere .= " AND lower(ct.name) LIKE '$description'";
266   }
267   if ($form->{notes}) {
268     my $notes = $form->like(lc $form->{notes});
269     $glwhere .= " AND lower(g.notes) LIKE '$notes'";
270     $arwhere .= " AND lower(a.notes) LIKE '$notes'";
271     $apwhere .= " AND lower(a.notes) LIKE '$notes'";
272   }
273   if ($form->{accno}) {
274     $glwhere .= " AND c.accno = '$form->{accno}'";
275     $arwhere .= " AND c.accno = '$form->{accno}'";
276     $apwhere .= " AND c.accno = '$form->{accno}'";
277   }
278   if ($form->{gifi_accno}) {
279     $glwhere .= " AND c.gifi_accno = '$form->{gifi_accno}'";
280     $arwhere .= " AND c.gifi_accno = '$form->{gifi_accno}'";
281     $apwhere .= " AND c.gifi_accno = '$form->{gifi_accno}'";
282   }
283   if ($form->{category} ne 'X') {
284     $glwhere .= " AND gl.id in (SELECT trans_id FROM acc_trans ac2 WHERE ac2.chart_id IN (SELECT id FROM chart c2 WHERE c2.category = '$form->{category}'))";
285     $arwhere .= " AND ar.id in (SELECT trans_id FROM acc_trans ac2 WHERE ac2.chart_id IN (SELECT id FROM chart c2 WHERE c2.category = '$form->{category}'))";
286     $apwhere .= " AND ap.id in (SELECT trans_id FROM acc_trans ac2 WHERE ac2.chart_id IN (SELECT id FROM chart c2 WHERE c2.category = '$form->{category}'))";
287   }
288
289   if ($form->{accno}) {
290
291     # get category for account
292     $query = qq|SELECT c.category
293                 FROM chart c
294                 WHERE c.accno = '$form->{accno}'|;
295     $sth = $dbh->prepare($query);
296
297     $sth->execute || $form->dberror($query);
298     ($form->{ml}) = $sth->fetchrow_array;
299     $sth->finish;
300
301     if ($form->{datefrom}) {
302       $query = qq|SELECT SUM(ac.amount)
303                   FROM acc_trans ac, chart c
304                   WHERE ac.chart_id = c.id
305                   AND c.accno = '$form->{accno}'
306                   AND ac.transdate < date '$form->{datefrom}'
307                   |;
308       $sth = $dbh->prepare($query);
309       $sth->execute || $form->dberror($query);
310
311       ($form->{balance}) = $sth->fetchrow_array;
312       $sth->finish;
313     }
314   }
315
316   if ($form->{gifi_accno}) {
317
318     # get category for account
319     $query = qq|SELECT c.category
320                 FROM chart c
321                 WHERE c.gifi_accno = '$form->{gifi_accno}'|;
322     $sth = $dbh->prepare($query);
323
324     $sth->execute || $form->dberror($query);
325     ($form->{ml}) = $sth->fetchrow_array;
326     $sth->finish;
327
328     if ($form->{datefrom}) {
329       $query = qq|SELECT SUM(ac.amount)
330                   FROM acc_trans ac, chart c
331                   WHERE ac.chart_id = c.id
332                   AND c.gifi_accno = '$form->{gifi_accno}'
333                   AND ac.transdate < date '$form->{datefrom}'
334                   |;
335       $sth = $dbh->prepare($query);
336       $sth->execute || $form->dberror($query);
337
338       ($form->{balance}) = $sth->fetchrow_array;
339       $sth->finish;
340     }
341   }
342
343   my $false = ($myconfig->{dbdriver} eq 'Pg') ? FALSE: q|'0'|;
344
345      my $sortorder = join ', ', $form->sort_columns(qw(transdate reference source description accno));
346      my %ordinal = ( transdate => 6,
347                      reference => 4,
348                      source => 7,
349                   description => 5 );
350      map { $sortorder =~ s/$_/$ordinal{$_}/ } keys %ordinal;
351    
352      if ($form->{sort}) {
353          $sortorder = $form->{sort} . ",";
354      } else {
355         $sortorder = "";
356       }
357   
358   my $query =
359     qq|SELECT g.id, 'gl' AS type, $false AS invoice, g.reference, ac.taxkey, t.taxkey AS sorttax,
360                  g.description, ac.transdate, ac.source, ac.trans_id,
361                  ac.amount, c.accno, c.gifi_accno, g.notes, t.chart_id, ac.oid
362                  FROM gl g, acc_trans ac, chart c LEFT JOIN tax t ON
363                  (t.chart_id=c.id)
364                  WHERE $glwhere
365                  AND ac.chart_id = c.id
366                  AND g.id = ac.trans_id
367         UNION
368                  SELECT a.id, 'ar' AS type, a.invoice, a.invnumber, ac.taxkey, t.taxkey AS sorttax,
369                  ct.name, ac.transdate, ac.source, ac.trans_id,
370                  ac.amount, c.accno, c.gifi_accno, a.notes, t.chart_id, ac.oid
371                  FROM ar a, acc_trans ac, customer ct, chart c LEFT JOIN tax t ON
372                  (t.chart_id=c.id)
373                  WHERE $arwhere
374                  AND ac.chart_id = c.id
375                  AND a.customer_id = ct.id
376                  AND a.id = ac.trans_id
377         UNION
378                  SELECT a.id, 'ap' AS type, a.invoice, a.invnumber, ac.taxkey, t.taxkey AS sorttax,
379                  ct.name, ac.transdate, ac.source, ac.trans_id,
380                  ac.amount, c.accno, c.gifi_accno, a.notes, t.chart_id, ac.oid
381                  FROM ap a, acc_trans ac, vendor ct, chart c LEFT JOIN tax t ON
382                  (t.chart_id=c.id)
383                  WHERE $apwhere
384                  AND ac.chart_id = c.id
385                  AND a.vendor_id = ct.id
386                  AND a.id = ac.trans_id
387                  ORDER BY $sortorder transdate, trans_id, taxkey DESC, sorttax DESC,oid|;
388   my $sth = $dbh->prepare($query);
389   $sth->execute || $form->dberror($query);
390   my $trans_id = "";
391   my $trans_id2 = "";
392   while (my $ref0 = $sth->fetchrow_hashref(NAME_lc)) {
393     $trans_id = $ref0->{id};
394     if ($trans_id != $trans_id2) {
395       if ($trans_id2) {
396         push @{ $form->{GL} }, $ref;
397         $balance = 0;
398       }
399       $ref = $ref0;
400       $trans_id2 = $ref->{id};
401       
402       # gl
403       if ($ref->{type} eq "gl") {
404         $ref->{module} = "gl";
405       }
406       # ap
407       if ($ref->{type} eq "ap") {
408         if ($ref->{invoice}) {
409           $ref->{module} = "ir";
410         } else {
411           $ref->{module} = "ap";
412         }
413       }
414   
415       # ar
416       if ($ref->{type} eq "ar") {
417         if ($ref->{invoice}) {
418           $ref->{module} = "is";
419         } else {
420           $ref->{module} = "ar";
421         }
422       }
423       $balance = $ref->{amount};
424       $i       = 0;
425       $j       = 0;
426       $k       = 0;
427       $l       = 0;
428       if ($ref->{amount} < 0) {
429         if ($ref->{chart_id} > 0) {
430           $ref->{debit_tax}{$i}       = $ref->{amount} * -1;
431           $ref->{debit_tax_accno}{$i} = $ref->{accno};
432         } else {
433           $ref->{debit}{$k}        = $ref->{amount} * -1;
434           $ref->{debit_accno}{$k}  = $ref->{accno};
435           $ref->{debit_taxkey}{$k} = $ref->{taxkey};
436         }
437       } else {
438         if ($ref->{chart_id} > 0) {
439           $ref->{credit_tax}{$j}       = $ref->{amount};
440           $ref->{credit_tax_accno}{$j} = $ref->{accno};
441         } else {
442           $ref->{credit}{$l}        = $ref->{amount};
443           $ref->{credit_accno}{$l}  = $ref->{accno};
444           $ref->{credit_taxkey}{$l} = $ref->{taxkey};
445         }
446       }
447     } else {
448       $ref2 = $ref0;
449       $trans_id2 = $ref2->{id};
450 #      if ($form->{accno} eq ''){ # flo & udo: if general report,
451                                   # then check balance
452 #         while (abs($balance) >= 0.015) {
453 #           my $ref2 = $sth->fetchrow_hashref(NAME_lc)
454 #             || $form->error("Unbalanced ledger!");
455 #     
456           $balance =
457             (int($balance * 100000) + int(100000 * $ref2->{amount})) / 100000;
458           if ($ref2->{amount} < 0) {
459             if ($ref2->{chart_id} > 0) {
460               if ($ref->{debit_tax_accno}{$i} ne "") {
461                 $i++;
462               }
463               $ref->{debit_tax}{$i}       = $ref2->{amount} * -1;
464               $ref->{debit_tax_accno}{$i} = $ref2->{accno};
465             } else {
466               if ($ref->{debit_accno}{$k} ne "") {
467                 $k++;
468               }
469               $ref->{debit}{$k}        = $ref2->{amount} * -1;
470               $ref->{debit_accno}{$k}  = $ref2->{accno};
471               $ref->{debit_taxkey}{$k} = $ref2->{taxkey};
472             }
473           } else {
474             if ($ref2->{chart_id} > 0) {
475               if ($ref->{credit_tax_accno}{$j} ne "") {
476                 $j++;
477               }
478               $ref->{credit_tax}{$j}       = $ref2->{amount};
479               $ref->{credit_tax_accno}{$j} = $ref2->{accno};
480             } else {
481               if ($ref->{credit_accno}{$l} ne "") {
482                 $l++;
483               }
484               $ref->{credit}{$l}        = $ref2->{amount};
485               $ref->{credit_accno}{$l}  = $ref2->{accno};
486               $ref->{credit_taxkey}{$l} = $ref2->{taxkey};
487             }
488           }
489 #         }
490 #       } else {
491 #         # if account-report, then calculate the Balance?!
492 #         # ToDo: Calculate the Balance
493 #         1;
494 #       }
495     }
496        
497     #    print(STDERR Dumper($ref));
498
499   }
500   push @{ $form->{GL} }, $ref;
501   $sth->finish;
502
503   if ($form->{accno}) {
504     $query =
505       qq|SELECT c.description FROM chart c WHERE c.accno = '$form->{accno}'|;
506     $sth = $dbh->prepare($query);
507     $sth->execute || $form->dberror($query);
508
509     ($form->{account_description}) = $sth->fetchrow_array;
510     $sth->finish;
511   }
512   if ($form->{gifi_accno}) {
513     $query =
514       qq|SELECT g.description FROM gifi g WHERE g.accno = '$form->{gifi_accno}'|;
515     $sth = $dbh->prepare($query);
516     $sth->execute || $form->dberror($query);
517
518     ($form->{gifi_account_description}) = $sth->fetchrow_array;
519     $sth->finish;
520   }
521   $main::lxdebug->leave_sub();
522
523   $dbh->disconnect;
524
525 }
526
527 sub transaction {
528   my ($self, $myconfig, $form) = @_;
529   $main::lxdebug->enter_sub();
530
531   my ($query, $sth, $ref);
532
533   # connect to database
534   my $dbh = $form->dbconnect($myconfig);
535
536   if ($form->{id}) {
537     $query = "SELECT closedto, revtrans
538               FROM defaults";
539     $sth = $dbh->prepare($query);
540     $sth->execute || $form->dberror($query);
541
542     ($form->{closedto}, $form->{revtrans}) = $sth->fetchrow_array;
543     $sth->finish;
544
545     $query = "SELECT g.reference, g.description, g.notes, g.transdate,
546               d.description AS department, e.name as employee, g.taxincluded, g.gldate
547               FROM gl g
548             LEFT JOIN department d ON (d.id = g.department_id)  
549             LEFT JOIN employee e ON (e.id = g.employee_id)  
550             WHERE g.id = $form->{id}";
551     $sth = $dbh->prepare($query);
552     $sth->execute || $form->dberror($query);
553     $ref = $sth->fetchrow_hashref(NAME_lc);
554     map { $form->{$_} = $ref->{$_} } keys %$ref;
555     $sth->finish;
556
557     # retrieve individual rows
558     $query = "SELECT c.accno, c.taxkey_id AS accnotaxkey, a.amount, project_id,
559                 (SELECT p.projectnumber FROM project p
560                  WHERE a.project_id = p.id) AS projectnumber, a.taxkey, (SELECT c1.accno FROM chart c1, tax t WHERE t.taxkey=a.taxkey AND c1.id=t.chart_id) AS taxaccno, (SELECT t1.rate FROM tax t1 WHERE t1.taxkey=a.taxkey) AS taxrate 
561               FROM acc_trans a, chart c
562               WHERE a.chart_id = c.id
563               AND a.trans_id = $form->{id}
564               ORDER BY a.oid";
565     $sth = $dbh->prepare($query);
566     $sth->execute || $form->dberror($query);
567
568     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
569       push @{ $form->{GL} }, $ref;
570     }
571
572     # get tax description
573     $query = qq| SELECT * FROM tax t order by t.taxkey|;
574     $sth   = $dbh->prepare($query);
575     $sth->execute || $form->dberror($query);
576     $form->{TAX} = ();
577     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
578       push @{ $form->{TAX} }, $ref;
579     }
580
581     $sth->finish;
582   } else {
583     $query = "SELECT current_date AS transdate, closedto, revtrans
584               FROM defaults";
585     $sth = $dbh->prepare($query);
586     $sth->execute || $form->dberror($query);
587
588     ($form->{transdate}, $form->{closedto}, $form->{revtrans}) =
589       $sth->fetchrow_array;
590
591     # get tax description
592     $query = qq| SELECT * FROM tax t order by t.taxkey|;
593     $sth   = $dbh->prepare($query);
594     $sth->execute || $form->dberror($query);
595     $form->{TAX} = ();
596     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
597       push @{ $form->{TAX} }, $ref;
598     }
599   }
600
601   $sth->finish;
602
603   # get chart of accounts
604   $query = qq|SELECT c.accno, c.description, c.taxkey_id
605               FROM chart c
606               WHERE c.charttype = 'A'
607               ORDER by c.accno|;
608   $sth = $dbh->prepare($query);
609   $sth->execute || $form->dberror($query);
610   $form->{chart} = ();
611   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
612     push @{ $form->{chart} }, $ref;
613   }
614   $sth->finish;
615
616   $sth->finish;
617   $main::lxdebug->leave_sub();
618
619   $dbh->disconnect;
620
621 }
622
623 1;
624