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