epic-s6ts
[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       array_agg(tk.startdate) AS startdates,
105       array_agg(tk.taxkey_id) AS taxkeys,
106       array_agg(tx.taxdescription || to_char (tx.rate, '99V99' ) || '%') AS taxdescriptions,
107       array_agg(taxchart.accno) AS taxaccounts,
108       array_agg(tk.pos_ustva) AS pos_ustvas,
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     LEFT JOIN chart taxchart ON (taxchart.id = tx.chart_id)
117     WHERE 1=1
118     $where
119     GROUP BY c.accno, c.id, c.description, c.charttype,
120       c.category, c.link, c.pos_bwa, c.pos_bilanz, c.pos_eur, c.valid_from,
121       c.datevautomatik
122     ORDER BY c.accno
123   };
124
125   my $sth = prepare_execute_query($form, $dbh, $query);
126
127   $form->{CA} = [];
128
129   while (my $ca = $sth->fetchrow_hashref("NAME_lc")) {
130     $ca->{amount} = $amount{ $ca->{accno} };
131     if ($ca->{amount} < 0) {
132       $ca->{debit} = $ca->{amount} * -1;
133     } else {
134       $ca->{credit} = $ca->{amount};
135     }
136     push(@{ $form->{CA} }, $ca);
137   }
138
139   $sth->finish;
140
141   $main::lxdebug->leave_sub();
142 }
143
144 sub all_transactions {
145   $main::lxdebug->enter_sub();
146
147   my ($self, $myconfig, $form) = @_;
148
149   my $dbh = SL::DB->client->dbh;
150
151   # get chart_id
152   my $query = qq|SELECT id FROM chart WHERE accno = ?|;
153   my @id = selectall_array_query($form, $dbh, $query, $form->{accno});
154
155   my $fromdate_where;
156   my $todate_where;
157
158   my $where = qq|1 = 1|;
159
160   # build WHERE clause from dates if any
161   #  if ($form->{fromdate}) {
162   #    $where .= " AND ac.transdate >= '$form->{fromdate}'";
163   #  }
164   #  if ($form->{todate}) {
165   #    $where .= " AND ac.transdate <= '$form->{todate}'";
166   #  }
167
168   my (@values, @where_values, @subwhere_values, $subwhere);
169   if ($form->{fromdate}) {
170     $where .= qq| AND ac.transdate >= ?|;
171     $subwhere .= qq| AND transdate >= ?|;
172     push(@where_values, conv_date($form->{fromdate}));
173     push(@subwhere_values, conv_date($form->{fromdate}));
174   }
175
176   if ($form->{todate}) {
177     $where .= qq| AND ac.transdate <= ?|;
178     $subwhere .= qq| AND transdate <= ?|;
179     push(@where_values, conv_date($form->{todate}));
180     push(@subwhere_values, conv_date($form->{todate}));
181   }
182
183
184   my $sortorder = join ', ',
185     $form->sort_columns(qw(transdate reference description));
186
187   my ($null, $department_id) = split(/--/, $form->{department});
188   my ($dpt_where, $dpt_join, @department_values);
189   if ($department_id) {
190     $dpt_join = qq| JOIN department t ON (t.id = a.department_id) |;
191     $dpt_where = qq| AND t.id = ? |;
192     @department_values = ($department_id);
193   }
194
195   my ($project, @project_values);
196   if ($form->{project_id}) {
197     $project = qq| AND ac.project_id = ? |;
198     @project_values = (conv_i($form->{project_id}));
199   }
200
201   if ($form->{accno}) {
202
203     # get category for account
204     $query = qq|SELECT category FROM chart WHERE accno = ?|;
205     ($form->{category}) = selectrow_query($form, $dbh, $query, $form->{accno});
206
207     if ($form->{fromdate}) {
208       # get beginning balances
209       $query =
210         qq|SELECT SUM(ac.amount) AS amount
211             FROM acc_trans ac
212             JOIN chart c ON (ac.chart_id = c.id)
213             WHERE ((select date_trunc('year', ac.transdate::date)) = (select date_trunc('year', ?::date))) AND ac.ob_transaction
214               $project
215             AND c.accno = ?|;
216
217       ($form->{beginning_balance}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno});
218
219       # get last transaction date
220       my $todate = ($form->{todate}) ? " AND ac.transdate <= '$form->{todate}' " : "";
221       $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 = ?|;
222       ($form->{last_transaction}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno});
223
224       # get old saldo
225       $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)|;
226       ($form->{saldo_old}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{fromdate}, $form->{accno});
227
228       #get old balance
229       $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)|;
230       ($form->{old_balance_debit}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{fromdate}, $form->{accno});
231
232       $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)|;
233       ($form->{old_balance_credit}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{fromdate}, $form->{accno});
234
235       # get current saldo
236       $todate = ($form->{todate} ne "") ? " AND ac.transdate <= '$form->{todate}' " : "";
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))) $todate AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)|;
238       ($form->{saldo_new}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno});
239
240       #get current balance
241       $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 ac.amount < 0 AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)|;
243       ($form->{current_balance_debit}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno});
244
245       $todate = ($form->{todate} ne "") ? " AND ac.transdate <= '$form->{todate}' " : "";
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))) $todate AND c.accno = ? AND ac.amount > 0 AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)|;
247       ($form->{current_balance_credit}) = selectrow_query($form, $dbh, $query, $form->{fromdate}, $form->{accno});
248     }
249   }
250
251   $query = "";
252   my $union = "";
253   @values = ();
254
255   foreach my $id (@id) {
256
257     # NOTE: Postgres is really picky about the order of implicit CROSS
258     #  JOINs with ',' if you alias the tables and want to use the
259     #  alias later in another JOIN.  the alias you want to use has to
260     #  be the most recent in the list, otherwise Postgres will
261     #  overwrite the alias internally and complain.  For this reason,
262     #  in the next 3 SELECTs, the 'a' alias is last in the list.
263     #  Don't change this, and if you do, substitute the ',' with CROSS
264     #  JOIN ... that also works.
265
266     # get all transactions
267     $query =
268       qq|SELECT ac.itime, a.id, a.reference, a.description, ac.transdate, ac.chart_id, | .
269       qq|  FALSE AS invoice, ac.amount, 'gl' as module, | .
270       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 § .
271       qq|FROM acc_trans ac, gl a | .
272       $dpt_join .
273       qq|WHERE | . $where . $dpt_where . $project .
274       qq|  AND ac.chart_id = ? | .
275       qq| AND ac.trans_id = a.id | .
276       qq| AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) | .
277
278       qq|UNION ALL | .
279
280       qq|SELECT ac.itime, a.id, a.invnumber, c.name, ac.transdate, ac.chart_id, | .
281       qq|  a.invoice, ac.amount, 'ar' as module, | .
282       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  § .
283       qq|FROM acc_trans ac, customer c, ar a | .
284       $dpt_join .
285       qq|WHERE | . $where . $dpt_where . $project .
286       qq| AND ac.chart_id = ? | .
287       qq| AND ac.trans_id = a.id | .
288       qq| AND a.customer_id = c.id | .
289       qq| AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)| .
290
291       qq|UNION ALL | .
292
293       qq|SELECT ac.itime, a.id, a.invnumber, v.name, ac.transdate, ac.chart_id, | .
294       qq|  a.invoice, ac.amount, 'ap' as module, | .
295       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  § .
296       qq|FROM acc_trans ac, vendor v, ap a | .
297       $dpt_join .
298       qq|WHERE | . $where . $dpt_where . $project .
299       qq| AND ac.chart_id = ? | .
300       qq| AND ac.trans_id = a.id | .
301       qq| AND a.vendor_id = v.id | .
302       qq| AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)|;
303     push(@values,
304          @where_values, @department_values, @project_values, $id,
305          @where_values, @department_values, @project_values, $id,
306          @where_values, @department_values, @project_values, $id);
307
308     $union = qq|UNION ALL |;
309
310     if ($form->{project_id}) {
311
312       $fromdate_where =~ s/ac\./a\./;
313       $todate_where   =~ s/ac\./a\./;
314
315 # strict check 20.10.2009 sschoeling
316 # the previous version contained the var $ar_ap_cash_where, which was ONLY set by
317 # RP->trial_balance() I tried to figure out which bizarre flow through the
318 # program would happen to set that var, so that it would be used here later on,
319 # (which would be nonsense, since you would normally load chart before
320 # calculating balance of said charts) and then decided that any mechanic that
321 # complex should fail anyway.
322
323 # if anyone is missing a time check on charts, that broke around the time
324 # trial_balance was rewritten, this would be it
325
326       $query .=
327         qq|UNION ALL | .
328
329         qq|SELECT ac.itime, a.id, a.invnumber, c.name, a.transdate, | .
330         qq|  a.invoice, ac.qty * ac.sellprice AS sellprice, 'ar' as module, | .
331         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 § .
332         qq|FROM ar a | .
333         qq|JOIN invoice ac ON (ac.trans_id = a.id) | .
334         qq|JOIN parts p ON (ac.parts_id = p.id) | .
335         qq|JOIN customer c ON (a.customer_id = c.id) | .
336         $dpt_join .
337         qq|WHERE p.income_accno_id = ? | .
338         $fromdate_where .
339         $todate_where .
340         $dpt_where .
341         $project .
342         qq|UNION ALL | .
343
344         qq|SELECT ac.itime, a.id, a.invnumber, v.name, a.transdate, | .
345         qq|  a.invoice, ac.qty * ac.sellprice AS sellprice, 'ap' as module, | .
346         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 § .
347         qq|FROM ap a | .
348         qq|JOIN invoice ac ON (ac.trans_id = a.id) | .
349         qq|JOIN parts p ON (ac.parts_id = p.id) | .
350         qq|JOIN vendor v ON (a.vendor_id = v.id) | .
351         $dpt_join .
352         qq|WHERE p.expense_accno_id = ? | .
353         $fromdate_where .
354         $todate_where .
355         $dpt_where .
356         $project;
357       push(@values,
358            $id, @department_values, @project_values,
359            $id, @department_values, @project_values);
360
361       $fromdate_where =~ s/a\./ac\./;
362       $todate_where   =~ s/a\./ac\./;
363
364     }
365
366     $union = qq|UNION ALL|;
367   }
368
369   my $sort = grep({ $form->{sort} eq $_ } qw(transdate reference description)) ? $form->{sort} : 'transdate';
370   $sort = ($sort eq 'transdate') ? 'transdate, itime' : $sort;
371   my $sort2 = ($sort eq 'reference') ? 'transdate, itime' : 'reference';
372   $query .= qq|ORDER BY $sort , $sort2 |;
373   my $sth = prepare_execute_query($form, $dbh, $query, @values);
374
375   #get detail information for each transaction
376   my $trans_query =
377         qq|SELECT accno, | .
378         qq|amount, transdate FROM acc_trans LEFT JOIN chart ON (chart_id=chart.id) WHERE | .
379         qq|trans_id = ? AND sign(amount) <> sign(?) AND chart_id <> ? AND transdate = ?|;
380   my $trans_sth = $dbh->prepare($trans_query);
381
382   $form->{CA} = [];
383   while (my $ca = $sth->fetchrow_hashref("NAME_lc")) {
384     # ap
385     if ($ca->{module} eq "ap") {
386       $ca->{module} = ($ca->{invoice}) ? 'ir' : 'ap';
387     }
388
389     # ar
390     if ($ca->{module} eq "ar") {
391       $ca->{module} = ($ca->{invoice}) ? 'is' : 'ar';
392     }
393
394     if ($ca->{amount} < 0) {
395       $ca->{debit}  = $ca->{amount} * -1;
396       $ca->{credit} = 0;
397     } else {
398       $ca->{credit} = $ca->{amount};
399       $ca->{debit}  = 0;
400     }
401
402     ($ca->{ustkonto},$ca->{ustrate}) = split /--/, $ca->{taxinfo};
403
404     #get detail information for this transaction
405     $trans_sth->execute($ca->{id}, $ca->{amount}, $ca->{chart_id}, $ca->{transdate}) ||
406     $form->dberror($trans_query . " (" . join(", ", $ca->{id}) . ")");
407     while (my $trans = $trans_sth->fetchrow_hashref("NAME_lc")) {
408       if (($ca->{transdate} eq $trans->{transdate}) && ($ca->{amount} * $trans->{amount} < 0)) {
409         if ($trans->{amount} < 0) {
410           $trans->{debit}  = $trans->{amount} * -1;
411           $trans->{credit} = 0;
412         } else {
413           $trans->{credit} = $trans->{amount};
414           $trans->{debit}  = 0;
415         }
416         push(@{ $ca->{GEGENKONTO} }, $trans);
417       } else {
418         next;
419       }
420     }
421
422     $ca->{index} = join "--", map { $ca->{$_} } qw(id reference description transdate);
423 #     $ca->{index} = $ca->{$form->{sort}};
424     push(@{ $form->{CA} }, $ca);
425
426   }
427
428   $sth->finish;
429
430   $main::lxdebug->leave_sub();
431 }
432
433 1;