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