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