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