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