Kontenuebersicht und Kontenblatt angepasst, so dass auch bei EUR korrekte Werte angez...
[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 sub all_accounts {
42   $main::lxdebug->enter_sub();
43
44   my ($self, $myconfig, $form, $chart_id) = @_;
45
46   my %amount;
47
48   # connect to database
49   my $dbh = $form->dbconnect($myconfig);
50
51   if ($form->{method} eq "cash") {
52     $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)))) |;
53   } else {
54     $acc_cash_where = " AND ((select date_trunc('year', a.transdate::date)) >= (select date_trunc('year', current_date)))";
55   }
56
57   my $query =
58     qq|SELECT c.accno, SUM(a.amount) AS amount | .
59     qq|FROM chart c, acc_trans a | .
60     qq|WHERE c.id = a.chart_id | .
61     qq|$acc_cash_where| .
62     qq|GROUP BY c.accno|;
63   my $sth = $dbh->prepare($query);
64   $sth->execute || $form->dberror($query);
65
66   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
67     $amount{ $ref->{accno} } = $ref->{amount};
68   }
69   $sth->finish;
70
71   my $where = "AND c.id = $chart_id" if ($chart_id ne '');
72
73   $query = qq{
74     SELECT
75       c.accno,
76       c.id,
77       c.description,
78       c.charttype,
79       c.category,
80       c.link,
81       c.pos_bwa,
82       c.pos_bilanz,
83       c.pos_eur,
84       c.valid_from,
85       c.datevautomatik,
86       comma(tk.startdate::text) AS startdate,
87       comma(tk.taxkey_id::text) AS taxkey,
88       comma(tx.taxdescription || to_char (tx.rate, '99V99' ) || '%') AS taxdescription,
89       comma(tx.taxnumber::text) AS taxaccount,
90       comma(tk.pos_ustva::text) AS tk_ustva,
91       ( SELECT accno
92       FROM chart c2
93       WHERE c2.id = c.id
94       ) AS new_account
95     FROM chart c
96     LEFT JOIN taxkeys tk ON (c.id = tk.chart_id)
97     LEFT JOIN tax tx ON (tk.tax_id = tx.id)
98     WHERE 1=1
99     $where
100     GROUP BY c.accno, c.id, c.description, c.charttype, c.gifi_accno,
101       c.category, c.link, c.pos_bwa, c.pos_bilanz, c.pos_eur, c.valid_from,
102       c.datevautomatik
103     ORDER BY c.accno
104   };
105
106   my $sth = prepare_execute_query($form, $dbh, $query);
107
108   $form->{CA} = [];
109
110   while (my $ca = $sth->fetchrow_hashref(NAME_lc)) {
111     $ca->{amount} = $amount{ $ca->{accno} };
112     if ($ca->{amount} < 0) {
113       $ca->{debit} = $ca->{amount} * -1;
114     } else {
115       $ca->{credit} = $ca->{amount};
116     }
117     push(@{ $form->{CA} }, $ca);
118   }
119
120   $sth->finish;
121   $dbh->disconnect;
122
123   $main::lxdebug->leave_sub();
124 }
125
126 sub all_transactions {
127   $main::lxdebug->enter_sub();
128
129   my ($self, $myconfig, $form) = @_;
130
131   # connect to database
132   my $dbh = $form->dbconnect($myconfig);
133
134   # get chart_id
135   my $query = qq|SELECT id FROM chart WHERE accno = ?|;
136   my @id = selectall_array_query($form, $dbh, $query, $form->{accno});
137
138   my $fromdate_where;
139   my $todate_where;
140
141   my $where = qq|1 = 1|;
142
143   # build WHERE clause from dates if any
144   #  if ($form->{fromdate}) {
145   #    $where .= " AND ac.transdate >= '$form->{fromdate}'";
146   #  }
147   #  if ($form->{todate}) {
148   #    $where .= " AND ac.transdate <= '$form->{todate}'";
149   #  }
150
151   my (@values, @where_values, @subwhere_values);
152   if ($form->{fromdate}) {
153     $where .= qq| AND ac.transdate >= ?|;
154     $subwhere .= qq| AND transdate >= ?|;
155     push(@where_values, conv_date($form->{fromdate}));
156     push(@subwhere_values, conv_date($form->{fromdate}));
157   }
158
159   if ($form->{todate}) {
160     $where .= qq| AND ac.transdate <= ?|;
161     $subwhere .= qq| AND transdate <= ?|;
162     push(@where_values, conv_date($form->{todate}));
163     push(@subwhere_values, conv_date($form->{todate}));
164   }
165
166
167   my $sortorder = join ', ',
168     $form->sort_columns(qw(transdate reference description));
169   my $false = ($myconfig->{dbdriver} eq 'Pg') ? FALSE: q|'0'|;
170
171   # Oracle workaround, use ordinal positions
172   my %ordinal = (transdate   => 4,
173                  reference   => 2,
174                  description => 3);
175   map { $sortorder =~ s/$_/$ordinal{$_}/ } keys %ordinal;
176
177   my ($null, $department_id) = split(/--/, $form->{department});
178   my ($dpt_where, $dpt_join, @department_values);
179   if ($department_id) {
180     $dpt_join = qq| JOIN department t ON (t.id = a.department_id) |;
181     $dpt_where = qq| AND t.id = ? |;
182     @department_values = ($department_id);
183   }
184
185   my ($project, @project_values);
186   if ($form->{project_id}) {
187     $project = qq| AND ac.project_id = ? |;
188     @project_values = (conv_i($form->{project_id}));
189   }
190   my $acc_cash_where = "";
191   my $ar_cash_where = "";
192   my $ap_cash_where = "";
193
194
195   if ($form->{method} eq "cash") {
196     $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<= ?)) |;
197     @where_values = ();
198     push(@where_values, conv_date($form->{fromdate}));
199     push(@where_values, conv_date($form->{todate}));
200     push(@where_values, conv_date($form->{fromdate}));
201     push(@where_values, conv_date($form->{todate}));
202     push(@where_values, conv_date($form->{fromdate}));
203     push(@where_values, conv_date($form->{todate}));
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 = ?  AND $where|;
227       ($form->{last_transaction}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno}, @where_values);
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) AND $where|;
231       ($form->{saldo_old}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{fromdate}, $form->{accno}, @where_values);
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)  AND $where|;
235       ($form->{old_balance_debit}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{fromdate}, $form->{accno}, @where_values);
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)  AND $where|;
238       ($form->{old_balance_credit}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{fromdate}, $form->{accno}, @where_values);
239
240       # get current saldo
241       my $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) AND $where|;
243       ($form->{saldo_new}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno}, @where_values);
244
245       #get current balance
246       my $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)  AND $where|;
248       ($form->{current_balance_debit}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno}, @where_values);
249
250       my $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)  AND $where|;
252       ($form->{current_balance_credit}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno}, @where_values);
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       $query .=
321         qq|UNION ALL | .
322
323         qq|SELECT a.id, a.invnumber, c.name, a.transdate, | .
324         qq|  a.invoice, ac.qty * ac.sellprice AS sellprice, 'ar' as module, | .
325         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 § .
326         qq|FROM ar a | .
327         qq|JOIN invoice ac ON (ac.trans_id = a.id) | .
328         qq|JOIN parts p ON (ac.parts_id = p.id) | .
329         qq|JOIN customer c ON (a.customer_id = c.id) | .
330         $dpt_join .
331         qq|WHERE p.income_accno_id = ? | .
332         $fromdate_where .
333         $todate_where .
334         $dpt_where .
335         $project .
336         $ar_ap_cash_where .
337         qq|UNION ALL | .
338
339         qq|SELECT a.id, a.invnumber, v.name, a.transdate, | .
340         qq|  a.invoice, ac.qty * ac.sellprice AS sellprice, 'ap' as module, | .
341         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 § .
342         qq|FROM ap a | .
343         qq|JOIN invoice ac ON (ac.trans_id = a.id) | .
344         qq|JOIN parts p ON (ac.parts_id = p.id) | .
345         qq|JOIN vendor v ON (a.vendor_id = v.id) | .
346         $dpt_join .
347         qq|WHERE p.expense_accno_id = ? | .
348         $fromdate_where .
349         $todate_where .
350         $dpt_where .
351         $project .
352         $ar_ap_cash_where;
353       push(@values,
354            $id, @department_values, @project_values,
355            $id, @department_values, @project_values);
356
357       $fromdate_where =~ s/a\./ac\./;
358       $todate_where   =~ s/a\./ac\./;
359
360     }
361
362     $union = qq|UNION ALL|;
363   }
364
365   my $sort = grep({ $form->{sort} eq $_ } qw(transdate reference description)) ? $form->{sort} : 'transdate';
366
367   $query .= qq|ORDER BY $sort|;
368   $sth = prepare_execute_query($form, $dbh, $query, @values);
369
370   #get detail information for each transaction
371   $trans_query =
372         qq|SELECT accno, | .
373         qq|amount, transdate FROM acc_trans LEFT JOIN chart ON (chart_id=chart.id) WHERE | .
374         qq|trans_id = ? AND sign(amount) <> sign(?) AND chart_id <> ? AND transdate = ?|;
375   my $trans_sth = $dbh->prepare($trans_query);
376
377   $form->{CA} = [];
378   while (my $ca = $sth->fetchrow_hashref(NAME_lc)) {
379     # ap
380     if ($ca->{module} eq "ap") {
381       $ca->{module} = ($ca->{invoice}) ? 'ir' : 'ap';
382     }
383
384     # ar
385     if ($ca->{module} eq "ar") {
386       $ca->{module} = ($ca->{invoice}) ? 'is' : 'ar';
387     }
388
389     if ($ca->{amount} < 0) {
390       $ca->{debit}  = $ca->{amount} * -1;
391       $ca->{credit} = 0;
392     } else {
393       $ca->{credit} = $ca->{amount};
394       $ca->{debit}  = 0;
395     }
396
397     ($ca->{ustkonto},$ca->{ustrate}) = split /--/, $ca->{taxinfo};
398
399     #get detail information for this transaction
400     $trans_sth->execute($ca->{id}, $ca->{amount}, $ca->{chart_id}, $ca->{transdate}) ||
401     $form->dberror($trans_query . " (" . join(", ", $ca->{id}) . ")");
402     while (my $trans = $trans_sth->fetchrow_hashref(NAME_lc)) {
403       if (($ca->{transdate} eq $trans->{transdate}) && ($ca->{amount} * $trans->{amount} < 0)) {
404         if ($trans->{amount} < 0) {
405           $trans->{debit}  = $trans->{amount} * -1;
406           $trans->{credit} = 0;
407         } else {
408           $trans->{credit} = $trans->{amount};
409           $trans->{debit}  = 0;
410         }
411         push(@{ $ca->{GEGENKONTO} }, $trans);
412       } else {
413         next;
414       }
415     }
416
417     $ca->{index} = join "--", map { $ca->{$_} } qw(id reference description transdate);
418 #     $ca->{index} = $ca->{$form->{sort}};
419     push(@{ $form->{CA} }, $ca);
420
421   }
422
423   $sth->finish;
424   $dbh->disconnect;
425
426   $main::lxdebug->leave_sub();
427 }
428
429 1;