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