Merge branch 'gifi'
[kivitendo-erp.git] / SL / CA.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 # chart of accounts
31 #
32 # CHANGE LOG:
33 #   DS. 2000-07-04  Created
34 #
35 #======================================================================
36
37 use utf8;
38 use strict;
39
40 package CA;
41 use Data::Dumper;
42 use SL::DBUtils;
43
44 sub all_accounts {
45   $main::lxdebug->enter_sub();
46
47   my ($self, $myconfig, $form, $chart_id) = @_;
48
49   my (%amount, $acc_cash_where);
50
51   # connect to database
52   my $dbh = $form->dbconnect($myconfig);
53
54   # bug 1071 Warum sollte bei Erreichen eines neuen Jahres die Kontenübersicht nur noch die
55   # bereits bebuchten Konten anzeigen?
56   # Folgende Erweiterung:
57   # 1.) Gehe zurück bis zu dem Datum an dem die Bücher geschlossen wurden
58   # 2.) Falls die Bücher noch nie geschlossen wurden, gehe zurück bis zum Bearbeitungsstart
59   # COALESCE((SELECT closedto FROM defaults),(SELECT itime FROM defaults))
60   # PROBLEM: Das date_trunc schneidet auf den 1.1.20XX ab und KEINE Buchungen werden angezeigt
61   # Lösung: date_trunc rausgeworfen und nicht mehr auf itime geprüft, sondern auf die erste Buchung
62   # in transdate jan 11.04.2011
63
64   my $closedto_sql = "COALESCE((SELECT closedto FROM defaults),
65                                (SELECT transdate from acc_trans order by transdate limit 1))";
66
67   if ($form->{method} eq "cash") {  # EÜR
68     $acc_cash_where = qq| AND (a.trans_id IN (SELECT id FROM ar WHERE datepaid>= $closedto_sql
69                           UNION SELECT id FROM ap WHERE datepaid>= $closedto_sql
70                           UNION SELECT id FROM gl WHERE transdate>= $closedto_sql
71                         )) |;
72   } else {  # Bilanzierung
73     $acc_cash_where = " AND (a.transdate >= $closedto_sql) ";
74   }
75
76   my $query =
77     qq|SELECT c.accno, SUM(a.amount) AS amount | .
78     qq|FROM chart c, acc_trans a | .
79     qq|WHERE c.id = a.chart_id | .
80     qq|$acc_cash_where| .
81     qq|GROUP BY c.accno|;
82
83   foreach my $ref (selectall_hashref_query($form, $dbh, $query)) {
84     $amount{ $ref->{accno} } = $ref->{amount};
85   }
86
87   my $where = $chart_id ne '' ? "AND c.id = $chart_id" : '';
88
89   $query = qq{
90     SELECT
91       c.accno,
92       c.id,
93       c.description,
94       c.charttype,
95       c.category,
96       c.link,
97       c.pos_bwa,
98       c.pos_bilanz,
99       c.pos_eur,
100       c.valid_from,
101       c.datevautomatik,
102       comma(tk.startdate::text) AS startdate,
103       comma(tk.taxkey_id::text) AS taxkey,
104       comma(tx.taxdescription || to_char (tx.rate, '99V99' ) || '%') AS taxdescription,
105       comma(tx.taxnumber::text) AS taxaccount,
106       comma(tk.pos_ustva::text) AS tk_ustva,
107       ( SELECT accno
108       FROM chart c2
109       WHERE c2.id = c.id
110       ) AS new_account
111     FROM chart c
112     LEFT JOIN taxkeys tk ON (c.id = tk.chart_id)
113     LEFT JOIN tax tx ON (tk.tax_id = tx.id)
114     WHERE 1=1
115     $where
116     GROUP BY c.accno, c.id, c.description, c.charttype,
117       c.category, c.link, c.pos_bwa, c.pos_bilanz, c.pos_eur, c.valid_from,
118       c.datevautomatik
119     ORDER BY c.accno
120   };
121
122   my $sth = prepare_execute_query($form, $dbh, $query);
123
124   $form->{CA} = [];
125
126   while (my $ca = $sth->fetchrow_hashref("NAME_lc")) {
127     $ca->{amount} = $amount{ $ca->{accno} };
128     if ($ca->{amount} < 0) {
129       $ca->{debit} = $ca->{amount} * -1;
130     } else {
131       $ca->{credit} = $ca->{amount};
132     }
133     push(@{ $form->{CA} }, $ca);
134   }
135
136   $sth->finish;
137   $dbh->disconnect;
138
139   $main::lxdebug->leave_sub();
140 }
141
142 sub all_transactions {
143   $main::lxdebug->enter_sub();
144
145   my ($self, $myconfig, $form) = @_;
146
147   # connect to database
148   my $dbh = $form->dbconnect($myconfig);
149
150   # get chart_id
151   my $query = qq|SELECT id FROM chart WHERE accno = ?|;
152   my @id = selectall_array_query($form, $dbh, $query, $form->{accno});
153
154   my $fromdate_where;
155   my $todate_where;
156
157   my $where = qq|1 = 1|;
158
159   # build WHERE clause from dates if any
160   #  if ($form->{fromdate}) {
161   #    $where .= " AND ac.transdate >= '$form->{fromdate}'";
162   #  }
163   #  if ($form->{todate}) {
164   #    $where .= " AND ac.transdate <= '$form->{todate}'";
165   #  }
166
167   my (@values, @where_values, @subwhere_values, $subwhere);
168   if ($form->{fromdate}) {
169     $where .= qq| AND ac.transdate >= ?|;
170     $subwhere .= qq| AND transdate >= ?|;
171     push(@where_values, conv_date($form->{fromdate}));
172     push(@subwhere_values, conv_date($form->{fromdate}));
173   }
174
175   if ($form->{todate}) {
176     $where .= qq| AND ac.transdate <= ?|;
177     $subwhere .= qq| AND transdate <= ?|;
178     push(@where_values, conv_date($form->{todate}));
179     push(@subwhere_values, conv_date($form->{todate}));
180   }
181
182
183   my $sortorder = join ', ',
184     $form->sort_columns(qw(transdate reference description));
185   my $false = ($myconfig->{dbdriver} eq 'Pg') ? "FALSE" : q|'0'|;
186
187   # Oracle workaround, use ordinal positions
188   my %ordinal = (transdate   => 4,
189                  reference   => 2,
190                  description => 3);
191   map { $sortorder =~ s/$_/$ordinal{$_}/ } keys %ordinal;
192
193   my ($null, $department_id) = split(/--/, $form->{department});
194   my ($dpt_where, $dpt_join, @department_values);
195   if ($department_id) {
196     $dpt_join = qq| JOIN department t ON (t.id = a.department_id) |;
197     $dpt_where = qq| AND t.id = ? |;
198     @department_values = ($department_id);
199   }
200
201   my ($project, @project_values);
202   if ($form->{project_id}) {
203     $project = qq| AND ac.project_id = ? |;
204     @project_values = (conv_i($form->{project_id}));
205   }
206
207   if ($form->{accno}) {
208
209     # get category for account
210     $query = qq|SELECT category FROM chart WHERE accno = ?|;
211     ($form->{category}) = selectrow_query($form, $dbh, $query, $form->{accno});
212
213     if ($form->{fromdate}) {
214       # get beginning balances
215       $query =
216         qq|SELECT SUM(ac.amount) AS amount
217             FROM acc_trans ac
218             JOIN chart c ON (ac.chart_id = c.id)
219             WHERE ((select date_trunc('year', ac.transdate::date)) = (select date_trunc('year', ?::date))) AND ac.ob_transaction
220               $project
221             AND c.accno = ?|;
222
223       ($form->{beginning_balance}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno});
224
225       # get last transaction date
226       my $todate = ($form->{todate}) ? " AND ac.transdate <= '$form->{todate}' " : "";
227       $query = qq|SELECT max(ac.transdate) FROM acc_trans ac LEFT JOIN chart c ON (ac.chart_id = c.id) WHERE ((select date_trunc('year', ac.transdate::date)) >= (select date_trunc('year', ?::date))) $todate AND c.accno = ?|;
228       ($form->{last_transaction}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno});
229
230       # get old saldo
231       $query = qq|SELECT sum(ac.amount) FROM acc_trans ac LEFT JOIN chart c ON (ac.chart_id = c.id) WHERE ((select date_trunc('year', ac.transdate::date)) >= (select date_trunc('year', ?::date))) AND ac.transdate < ? AND c.accno = ?  AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)|;
232       ($form->{saldo_old}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{fromdate}, $form->{accno});
233
234       #get old balance
235       $query = qq|SELECT sum(ac.amount) FROM acc_trans ac LEFT JOIN chart c ON (ac.chart_id = c.id) WHERE ((select date_trunc('year', ac.transdate::date)) >= (select date_trunc('year', ?::date))) AND ac.transdate < ? AND c.accno = ? AND ac.amount < 0 AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)|;
236       ($form->{old_balance_debit}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{fromdate}, $form->{accno});
237
238       $query = qq|SELECT sum(ac.amount) FROM acc_trans ac LEFT JOIN chart c ON (ac.chart_id = c.id) WHERE ((select date_trunc('year', ac.transdate::date)) >= (select date_trunc('year', ?::date))) AND ac.transdate < ? AND c.accno = ? AND ac.amount > 0 AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)|;
239       ($form->{old_balance_credit}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{fromdate}, $form->{accno});
240
241       # get current saldo
242       $todate = ($form->{todate} ne "") ? " AND ac.transdate <= '$form->{todate}' " : "";
243       $query = qq|SELECT sum(ac.amount) FROM acc_trans ac LEFT JOIN chart c ON (ac.chart_id = c.id) WHERE ((select date_trunc('year', ac.transdate::date)) >= (select date_trunc('year', ?::date))) $todate AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)|;
244       ($form->{saldo_new}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno});
245
246       #get current balance
247       $todate = ($form->{todate} ne "") ? " AND ac.transdate <= '$form->{todate}' " : "";
248       $query = qq|SELECT sum(ac.amount) FROM acc_trans ac LEFT JOIN chart c ON (ac.chart_id = c.id) WHERE ((select date_trunc('year', ac.transdate::date)) >= (select date_trunc('year', ?::date))) $todate AND c.accno = ? AND ac.amount < 0 AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)|;
249       ($form->{current_balance_debit}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno});
250
251       $todate = ($form->{todate} ne "") ? " AND ac.transdate <= '$form->{todate}' " : "";
252       $query = qq|SELECT sum(ac.amount) FROM acc_trans ac LEFT JOIN chart c ON (ac.chart_id = c.id)WHERE ((select date_trunc('year', ac.transdate::date)) >= (select date_trunc('year', ?::date))) $todate AND c.accno = ? AND ac.amount > 0 AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)|;
253       ($form->{current_balance_credit}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno});
254     }
255   }
256
257   $query = "";
258   my $union = "";
259   @values = ();
260
261   foreach my $id (@id) {
262
263     # NOTE: Postgres is really picky about the order of implicit CROSS
264     #  JOINs with ',' if you alias the tables and want to use the
265     #  alias later in another JOIN.  the alias you want to use has to
266     #  be the most recent in the list, otherwise Postgres will
267     #  overwrite the alias internally and complain.  For this reason,
268     #  in the next 3 SELECTs, the 'a' alias is last in the list.
269     #  Don't change this, and if you do, substitute the ',' with CROSS
270     #  JOIN ... that also works.
271
272     # get all transactions
273     $query =
274       qq|SELECT a.id, a.reference, a.description, ac.transdate, ac.chart_id, | .
275       qq|  $false AS invoice, ac.amount, 'gl' as module, | .
276       qq§(SELECT accno||'--'||rate FROM tax LEFT JOIN chart ON (tax.chart_id=chart.id) WHERE tax.id = (SELECT tax_id FROM taxkeys WHERE taxkey_id = ac.taxkey AND taxkeys.startdate <= ac.transdate ORDER BY taxkeys.startdate DESC LIMIT 1)) AS taxinfo, ac.source || ' ' || ac.memo AS memo § .
277       qq|FROM acc_trans ac, gl a | .
278       $dpt_join .
279       qq|WHERE | . $where . $dpt_where . $project .
280       qq|  AND ac.chart_id = ? | .
281       qq| AND ac.trans_id = a.id | .
282       qq| AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) | .
283
284       qq|UNION ALL | .
285
286       qq|SELECT a.id, a.invnumber, c.name, ac.transdate, ac.chart_id, | .
287       qq|  a.invoice, ac.amount, 'ar' as module, | .
288       qq§(SELECT accno||'--'||rate FROM tax LEFT JOIN chart ON (tax.chart_id=chart.id) WHERE tax.id = (SELECT tax_id FROM taxkeys WHERE taxkey_id = ac.taxkey AND taxkeys.startdate <= ac.transdate ORDER BY taxkeys.startdate DESC LIMIT 1)) AS taxinfo, ac.source || ' ' || ac.memo AS memo  § .
289       qq|FROM acc_trans ac, customer c, ar a | .
290       $dpt_join .
291       qq|WHERE | . $where . $dpt_where . $project .
292       qq| AND ac.chart_id = ? | .
293       qq| AND ac.trans_id = a.id | .
294       qq| AND a.customer_id = c.id | .
295       qq| AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)| .
296
297       qq|UNION ALL | .
298
299       qq|SELECT a.id, a.invnumber, v.name, ac.transdate, ac.chart_id, | .
300       qq|  a.invoice, ac.amount, 'ap' as module, | .
301       qq§(SELECT accno||'--'||rate FROM tax LEFT JOIN chart ON (tax.chart_id=chart.id) WHERE tax.id = (SELECT tax_id FROM taxkeys WHERE taxkey_id = ac.taxkey AND taxkeys.startdate <= ac.transdate ORDER BY taxkeys.startdate DESC LIMIT 1)) AS taxinfo, ac.source || ' ' || ac.memo AS memo  § .
302       qq|FROM acc_trans ac, vendor v, ap a | .
303       $dpt_join .
304       qq|WHERE | . $where . $dpt_where . $project .
305       qq| AND ac.chart_id = ? | .
306       qq| AND ac.trans_id = a.id | .
307       qq| AND a.vendor_id = v.id | .
308       qq| AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)|;
309     push(@values,
310          @where_values, @department_values, @project_values, $id,
311          @where_values, @department_values, @project_values, $id,
312          @where_values, @department_values, @project_values, $id);
313
314     $union = qq|UNION ALL |;
315
316     if ($form->{project_id}) {
317
318       $fromdate_where =~ s/ac\./a\./;
319       $todate_where   =~ s/ac\./a\./;
320
321 # strict check 20.10.2009 sschoeling
322 # the previous version contained the var $ar_ap_cash_where, which was ONLY set by
323 # RP->trial_balance() I tried to figure out which bizarre flow through the
324 # program would happen to set that var, so that it would be used here later on,
325 # (which would be nonsense, since you would normally load chart before
326 # claculating balance of said charts) and then decided that any mechanic that
327 # complex should fail anyway.
328
329 # if anyone is missing a time check on charts, that broke arounf the time
330 # trial_balance was rewritten, this would be it
331
332       $query .=
333         qq|UNION ALL | .
334
335         qq|SELECT a.id, a.invnumber, c.name, a.transdate, | .
336         qq|  a.invoice, ac.qty * ac.sellprice AS sellprice, 'ar' as module, | .
337         qq§(SELECT accno||'--'||rate FROM tax LEFT JOIN chart ON (tax.chart_id=chart.id) WHERE tax.id = (SELECT tax_id FROM taxkeys WHERE taxkey_id = ac.taxkey AND taxkeys.startdate <= ac.transdate ORDER BY taxkeys.startdate DESC LIMIT 1)) AS taxinfo § .
338         qq|FROM ar a | .
339         qq|JOIN invoice ac ON (ac.trans_id = a.id) | .
340         qq|JOIN parts p ON (ac.parts_id = p.id) | .
341         qq|JOIN customer c ON (a.customer_id = c.id) | .
342         $dpt_join .
343         qq|WHERE p.income_accno_id = ? | .
344         $fromdate_where .
345         $todate_where .
346         $dpt_where .
347         $project .
348         qq|UNION ALL | .
349
350         qq|SELECT a.id, a.invnumber, v.name, a.transdate, | .
351         qq|  a.invoice, ac.qty * ac.sellprice AS sellprice, 'ap' as module, | .
352         qq§(SELECT accno||'--'||rate FROM tax LEFT JOIN chart ON (tax.chart_id=chart.id) WHERE tax.id = (SELECT tax_id FROM taxkeys WHERE taxkey_id = ac.taxkey AND taxkeys.startdate <= ac.transdate ORDER BY taxkeys.startdate DESC LIMIT 1)) AS taxinfo § .
353         qq|FROM ap a | .
354         qq|JOIN invoice ac ON (ac.trans_id = a.id) | .
355         qq|JOIN parts p ON (ac.parts_id = p.id) | .
356         qq|JOIN vendor v ON (a.vendor_id = v.id) | .
357         $dpt_join .
358         qq|WHERE p.expense_accno_id = ? | .
359         $fromdate_where .
360         $todate_where .
361         $dpt_where .
362         $project;
363       push(@values,
364            $id, @department_values, @project_values,
365            $id, @department_values, @project_values);
366
367       $fromdate_where =~ s/a\./ac\./;
368       $todate_where   =~ s/a\./ac\./;
369
370     }
371
372     $union = qq|UNION ALL|;
373   }
374
375   my $sort = grep({ $form->{sort} eq $_ } qw(transdate reference description)) ? $form->{sort} : 'transdate';
376
377   $query .= qq|ORDER BY $sort|;
378   my $sth = prepare_execute_query($form, $dbh, $query, @values);
379
380   #get detail information for each transaction
381   my $trans_query =
382         qq|SELECT accno, | .
383         qq|amount, transdate FROM acc_trans LEFT JOIN chart ON (chart_id=chart.id) WHERE | .
384         qq|trans_id = ? AND sign(amount) <> sign(?) AND chart_id <> ? AND transdate = ?|;
385   my $trans_sth = $dbh->prepare($trans_query);
386
387   $form->{CA} = [];
388   while (my $ca = $sth->fetchrow_hashref("NAME_lc")) {
389     # ap
390     if ($ca->{module} eq "ap") {
391       $ca->{module} = ($ca->{invoice}) ? 'ir' : 'ap';
392     }
393
394     # ar
395     if ($ca->{module} eq "ar") {
396       $ca->{module} = ($ca->{invoice}) ? 'is' : 'ar';
397     }
398
399     if ($ca->{amount} < 0) {
400       $ca->{debit}  = $ca->{amount} * -1;
401       $ca->{credit} = 0;
402     } else {
403       $ca->{credit} = $ca->{amount};
404       $ca->{debit}  = 0;
405     }
406
407     ($ca->{ustkonto},$ca->{ustrate}) = split /--/, $ca->{taxinfo};
408
409     #get detail information for this transaction
410     $trans_sth->execute($ca->{id}, $ca->{amount}, $ca->{chart_id}, $ca->{transdate}) ||
411     $form->dberror($trans_query . " (" . join(", ", $ca->{id}) . ")");
412     while (my $trans = $trans_sth->fetchrow_hashref("NAME_lc")) {
413       if (($ca->{transdate} eq $trans->{transdate}) && ($ca->{amount} * $trans->{amount} < 0)) {
414         if ($trans->{amount} < 0) {
415           $trans->{debit}  = $trans->{amount} * -1;
416           $trans->{credit} = 0;
417         } else {
418           $trans->{credit} = $trans->{amount};
419           $trans->{debit}  = 0;
420         }
421         push(@{ $ca->{GEGENKONTO} }, $trans);
422       } else {
423         next;
424       }
425     }
426
427     $ca->{index} = join "--", map { $ca->{$_} } qw(id reference description transdate);
428 #     $ca->{index} = $ca->{$form->{sort}};
429     push(@{ $form->{CA} }, $ca);
430
431   }
432
433   $sth->finish;
434   $dbh->disconnect;
435
436   $main::lxdebug->leave_sub();
437 }
438
439 1;