026cf6a01db7871ee155d2be441bf0c15a93752e
[kivitendo-erp.git] / bin / mozilla / gl.pl
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) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
29 #
30 # Genereal Ledger
31 #
32 #======================================================================
33
34 use utf8;
35 use strict;
36
37 use POSIX qw(strftime);
38 use List::Util qw(sum);
39
40 use SL::FU;
41 use SL::GL;
42 use SL::IS;
43 use SL::PE;
44 use SL::ReportGenerator;
45
46 require "bin/mozilla/common.pl";
47 require "bin/mozilla/drafts.pl";
48 require "bin/mozilla/reportgenerator.pl";
49
50 # this is for our long dates
51 # $locale->text('January')
52 # $locale->text('February')
53 # $locale->text('March')
54 # $locale->text('April')
55 # $locale->text('May ')
56 # $locale->text('June')
57 # $locale->text('July')
58 # $locale->text('August')
59 # $locale->text('September')
60 # $locale->text('October')
61 # $locale->text('November')
62 # $locale->text('December')
63
64 # this is for our short month
65 # $locale->text('Jan')
66 # $locale->text('Feb')
67 # $locale->text('Mar')
68 # $locale->text('Apr')
69 # $locale->text('May')
70 # $locale->text('Jun')
71 # $locale->text('Jul')
72 # $locale->text('Aug')
73 # $locale->text('Sep')
74 # $locale->text('Oct')
75 # $locale->text('Nov')
76 # $locale->text('Dec')
77
78 sub add {
79   $main::lxdebug->enter_sub();
80
81   $main::auth->assert('general_ledger');
82
83   my $form     = $main::form;
84   my %myconfig = %main::myconfig;
85
86   return $main::lxdebug->leave_sub() if (load_draft_maybe());
87
88   $form->{title} = "Add";
89
90   $form->{callback} = "gl.pl?action=add" unless $form->{callback};
91
92   # we use this only to set a default date
93   # yep. aber er holt hier auch schon ALL_CHARTS. Aufwand / Nutzen? jb
94   GL->transaction(\%myconfig, \%$form);
95
96   $form->{rowcount}  = 2;
97
98   $form->{debit}  = 0;
99   $form->{credit} = 0;
100   $form->{tax}    = 0;
101
102   # departments
103   $form->all_departments(\%myconfig);
104   if (@{ $form->{all_departments} || [] }) {
105     $form->{selectdepartment} = "<option>\n";
106
107     map {
108       $form->{selectdepartment} .=
109         "<option>$_->{description}--$_->{id}\n"
110     } (@{ $form->{all_departments} || [] });
111   }
112
113   $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
114
115   &display_form(1);
116   $main::lxdebug->leave_sub();
117
118 }
119
120 sub prepare_transaction {
121   $main::lxdebug->enter_sub();
122
123   $main::auth->assert('general_ledger');
124
125   my $form     = $main::form;
126   my %myconfig = %main::myconfig;
127
128   GL->transaction(\%myconfig, \%$form);
129
130   $form->{amount} = $form->format_amount(\%myconfig, $form->{amount}, 2);
131
132   # departments
133   $form->all_departments(\%myconfig);
134   if (@{ $form->{all_departments} || [] }) {
135     $form->{selectdepartment} = "<option>\n";
136
137     map {
138       $form->{selectdepartment} .=
139         "<option>$_->{description}--$_->{id}\n"
140     } (@{ $form->{all_departments} || [] });
141   }
142
143   my $i        = 1;
144   my $tax      = 0;
145   my $taxaccno = "";
146   foreach my $ref (@{ $form->{GL} }) {
147     my $j = $i - 1;
148     if ($tax && ($ref->{accno} eq $taxaccno)) {
149       $form->{"tax_$j"}      = abs($ref->{amount});
150       $form->{"taxchart_$j"} = $ref->{id} . "--" . $ref->{taxrate};
151       if ($form->{taxincluded}) {
152         if ($ref->{amount} < 0) {
153           $form->{"debit_$j"} += $form->{"tax_$j"};
154         } else {
155           $form->{"credit_$j"} += $form->{"tax_$j"};
156         }
157       }
158       $form->{"project_id_$j"} = $ref->{project_id};
159
160     } else {
161       $form->{"accno_$i"} = "$ref->{accno}--$ref->{tax_id}";
162       for (qw(fx_transaction source memo)) { $form->{"${_}_$i"} = $ref->{$_} }
163       if ($ref->{amount} < 0) {
164         $form->{totaldebit} -= $ref->{amount};
165         $form->{"debit_$i"} = $ref->{amount} * -1;
166       } else {
167         $form->{totalcredit} += $ref->{amount};
168         $form->{"credit_$i"} = $ref->{amount};
169       }
170       $form->{"taxchart_$i"} = "0--0.00";
171       $form->{"project_id_$i"} = $ref->{project_id};
172       $i++;
173     }
174     if ($ref->{taxaccno} && !$tax) {
175       $taxaccno = $ref->{taxaccno};
176       $tax      = 1;
177     } else {
178       $taxaccno = "";
179       $tax      = 0;
180     }
181   }
182
183   $form->{rowcount} = $i;
184   $form->{locked}   =
185     ($form->datetonum($form->{transdate}, \%myconfig) <=
186      $form->datetonum($form->{closedto}, \%myconfig));
187
188   $main::lxdebug->leave_sub();
189 }
190
191 sub edit {
192   $main::lxdebug->enter_sub();
193
194   $main::auth->assert('general_ledger');
195
196   my $form     = $main::form;
197   my %myconfig = %main::myconfig;
198
199   prepare_transaction();
200
201   $form->{title} = "Edit";
202
203   $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
204
205   form_header();
206   display_rows();
207   form_footer();
208
209   $main::lxdebug->leave_sub();
210 }
211
212
213 sub search {
214   $::lxdebug->enter_sub;
215   $::auth->assert('general_ledger');
216
217   $::form->all_departments(\%::myconfig);
218   $::form->get_lists(
219     projects  => { key => "ALL_PROJECTS", all => 1 },
220   );
221   $::form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
222
223   $::form->header;
224   print $::form->parse_html_template('gl/search', {
225     department_label => sub { ("$_[0]{description}--$_[0]{id}")x2 },
226     employee_label => sub { "$_[0]{id}--$_[0]{name}" },
227   });
228
229   $::lxdebug->leave_sub;
230 }
231
232 sub create_subtotal_row {
233   $main::lxdebug->enter_sub();
234
235   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
236
237   my $form     = $main::form;
238   my %myconfig = %main::myconfig;
239
240   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
241
242   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
243
244   map { $totals->{$_} = 0 } @{ $subtotal_columns };
245
246   $main::lxdebug->leave_sub();
247
248   return $row;
249 }
250
251 sub generate_report {
252   $main::lxdebug->enter_sub();
253
254   $main::auth->assert('general_ledger');
255
256   my $form     = $main::form;
257   my %myconfig = %main::myconfig;
258   my $locale   = $main::locale;
259
260   # generate_report wird beim ersten Aufruf per Weiter-Knopf und POST mit der hidden Variablen sort mit Wert "datesort" (früher "transdate" als Defaultsortiervariable) Ã¼bertragen
261
262   # <form method=post action=gl.pl>
263   # <input type=hidden name=sort value=datesort>    # form->{sort} setzen
264   # <input type=hidden name=nextsub value=generate_report>
265
266   # anhand von neuer Variable datesort wird jetzt $form->{sort} auf transdate oder gldate gesetzt
267   # damit ist die Hidden Variable "sort" wahrscheinlich sogar Ã¼berflüssig
268
269   # Ã¤ndert man die Sortierreihenfolge per Klick auf eine der Ãœberschriften wird die Variable "sort" per GET Ã¼bergeben, z.B. id,transdate, gldate, ...
270   # gl.pl?action=generate_report&employee=18383--Jan%20B%c3%bcren&datesort=transdate&category=X&l_transdate=Y&l_gldate=Y&l_id=Y&l_reference=Y&l_description=Y&l_source=Y&l_debit=Y&l_credit=Y&sort=gldate&sortdir=0
271
272   if ( $form->{sort} eq 'datesort' ) {   # sollte bei einem Post (Aufruf aus Suchmaske) immer wahr sein
273       # je nachdem ob in Suchmaske "transdate" oder "gldate" ausgesucht wurde erstes Suchergebnis entsprechend sortieren
274       $form->{sort} = $form->{datesort};
275   };
276
277   # was passiert hier?
278   report_generator_set_default_sort("$form->{datesort}", 1);
279 #  report_generator_set_default_sort('transdate', 1);
280
281   GL->all_transactions(\%myconfig, \%$form);
282
283   my %acctype = ('A' => $locale->text('Asset'),
284                  'C' => $locale->text('Contra'),
285                  'L' => $locale->text('Liability'),
286                  'Q' => $locale->text('Equity'),
287                  'I' => $locale->text('Revenue'),
288                  'E' => $locale->text('Expense'),);
289
290   $form->{title} = $locale->text('Journal');
291   if ($form->{category} ne 'X') {
292     $form->{title} .= " : " . $locale->text($acctype{ $form->{category} });
293   }
294
295   $form->{landscape} = 1;
296
297   my $ml = ($form->{ml} =~ /(A|E|Q)/) ? -1 : 1;
298
299   my @columns = qw(
300     gldate         transdate        id             reference      description
301     notes          source           debit          debit_accno
302     credit         credit_accno     debit_tax      debit_tax_accno
303     credit_tax     credit_tax_accno projectnumbers balance employee
304   );
305
306   # add employee here, so that variable is still known and passed in url when choosing a different sort order in resulting table
307   my @hidden_variables = qw(accno source reference department description notes project_id datefrom dateto employee_id datesort category l_subtotal);
308   push @hidden_variables, map { "l_${_}" } @columns;
309
310   my $employee = $form->{employee_id} ? SL::DB::Employee->new(id => $form->{employee_id})->load->name : '';
311
312   my (@options, @date_options);
313   push @options,      $locale->text('Account')     . " : $form->{accno} $form->{account_description}" if ($form->{accno});
314   push @options,      $locale->text('Source')      . " : $form->{source}"                             if ($form->{source});
315   push @options,      $locale->text('Reference')   . " : $form->{reference}"                          if ($form->{reference});
316   push @options,      $locale->text('Description') . " : $form->{description}"                        if ($form->{description});
317   push @options,      $locale->text('Notes')       . " : $form->{notes}"                              if ($form->{notes});
318   push @options,      $locale->text('Employee')    . " : $employee"                                   if $employee;
319   my $datesorttext = $form->{datesort} eq 'transdate' ? $locale->text('Invoice Date') :  $locale->text('Booking Date');
320   push @date_options,      "$datesorttext"                              if ($form->{datesort} and ($form->{datefrom} or $form->{dateto}));
321   push @date_options, $locale->text('From'), $locale->date(\%myconfig, $form->{datefrom}, 1)          if ($form->{datefrom});
322   push @date_options, $locale->text('Bis'),  $locale->date(\%myconfig, $form->{dateto},   1)          if ($form->{dateto});
323   push @options,      join(' ', @date_options)                                                        if (scalar @date_options);
324
325   if ($form->{department}) {
326     my ($department) = split /--/, $form->{department};
327     push @options, $locale->text('Department') . " : $department";
328   }
329
330
331   my $callback = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
332
333   $form->{l_credit_accno}     = 'Y';
334   $form->{l_debit_accno}      = 'Y';
335   $form->{l_credit_tax}       = 'Y';
336   $form->{l_debit_tax}        = 'Y';
337 #  $form->{l_gldate}           = 'Y';  # Spalte mit gldate immer anzeigen
338   $form->{l_credit_tax_accno} = 'Y';
339   $form->{l_datesort} = 'Y';
340   $form->{l_debit_tax_accno}  = 'Y';
341   $form->{l_balance}          = $form->{accno} ? 'Y' : '';
342
343   my %column_defs = (
344     'id'               => { 'text' => $locale->text('ID'), },
345     'transdate'        => { 'text' => $locale->text('Invoice Date'), },
346     'gldate'           => { 'text' => $locale->text('Booking Date'), },
347     'reference'        => { 'text' => $locale->text('Reference'), },
348     'source'           => { 'text' => $locale->text('Source'), },
349     'description'      => { 'text' => $locale->text('Description'), },
350     'notes'            => { 'text' => $locale->text('Notes'), },
351     'debit'            => { 'text' => $locale->text('Debit'), },
352     'debit_accno'      => { 'text' => $locale->text('Debit Account'), },
353     'credit'           => { 'text' => $locale->text('Credit'), },
354     'credit_accno'     => { 'text' => $locale->text('Credit Account'), },
355     'debit_tax'        => { 'text' => $locale->text('Debit Tax'), },
356     'debit_tax_accno'  => { 'text' => $locale->text('Debit Tax Account'), },
357     'credit_tax'       => { 'text' => $locale->text('Credit Tax'), },
358     'credit_tax_accno' => { 'text' => $locale->text('Credit Tax Account'), },
359     'balance'          => { 'text' => $locale->text('Balance'), },
360     'projectnumbers'   => { 'text' => $locale->text('Project Numbers'), },
361     'employee'         => { 'text' => $locale->text('Employee'), },
362   );
363
364   foreach my $name (qw(id transdate gldate reference description debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
365     my $sortname                = $name =~ m/accno/ ? 'accno' : $name;
366     my $sortdir                 = $sortname eq $form->{sort} ? 1 - $form->{sortdir} : $form->{sortdir};
367     $column_defs{$name}->{link} = $callback . "&sort=$sortname&sortdir=$sortdir";
368   }
369
370   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
371   map { $column_defs{$_}->{visible} = 0 } qw(debit_accno credit_accno debit_tax_accno credit_tax_accno) if $form->{accno};
372
373   my %column_alignment;
374   map { $column_alignment{$_}     = 'right'  } qw(balance id debit credit debit_tax credit_tax balance);
375   map { $column_alignment{$_}     = 'center' } qw(transdate gldate reference debit_accno credit_accno debit_tax_accno credit_tax_accno);
376   map { $column_alignment{$_}     = 'left' } qw(description source notes);
377   map { $column_defs{$_}->{align} = $column_alignment{$_} } keys %column_alignment;
378
379   my $report = SL::ReportGenerator->new(\%myconfig, $form);
380
381   $report->set_columns(%column_defs);
382   $report->set_column_order(@columns);
383
384   $report->set_export_options('generate_report', @hidden_variables, qw(sort sortdir));
385
386   $report->set_sort_indicator($form->{sort} eq 'accno' ? 'debit_accno' : $form->{sort}, $form->{sortdir});
387
388   $report->set_options('top_info_text'        => join("\n", @options),
389                        'output_format'        => 'HTML',
390                        'title'                => $form->{title},
391                        'attachment_basename'  => $locale->text('general_ledger_list') . strftime('_%Y%m%d', localtime time),
392     );
393   $report->set_options_from_form();
394   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
395
396   # add sort to callback
397   $form->{callback} = "$callback&sort=" . E($form->{sort}) . "&sortdir=" . E($form->{sortdir});
398
399
400   my @totals_columns = qw(debit credit debit_tax credit_tax);
401   my %subtotals      = map { $_ => 0 } @totals_columns;
402   my %totals         = map { $_ => 0 } @totals_columns;
403   my $idx            = 0;
404
405   foreach my $ref (@{ $form->{GL} }) {
406
407     my %rows;
408
409     foreach my $key (qw(debit credit debit_tax credit_tax)) {
410       $rows{$key} = [];
411       foreach my $idx (sort keys(%{ $ref->{$key} })) {
412         my $value         = $ref->{$key}->{$idx};
413         $subtotals{$key} += $value;
414         $totals{$key}    += $value;
415         if ($key =~ /debit.*/) {
416           $ml = -1;
417         } else {
418           $ml = 1;
419         }
420         $form->{balance}  = $form->{balance} + $value * $ml;
421         push @{ $rows{$key} }, $form->format_amount(\%myconfig, $value, 2);
422       }
423     }
424
425     foreach my $key (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno ac_transdate source)) {
426       my $col = $key eq 'ac_transdate' ? 'transdate' : $key;
427       $rows{$col} = [ map { $ref->{$key}->{$_} } sort keys(%{ $ref->{$key} }) ];
428     }
429
430     my $row = { };
431     map { $row->{$_} = { 'data' => '', 'align' => $column_alignment{$_} } } @columns;
432
433     my $sh = "";
434     if ($form->{balance} < 0) {
435       $sh = " S";
436       $ml = -1;
437     } elsif ($form->{balance} > 0) {
438       $sh = " H";
439       $ml = 1;
440     }
441     my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
442     $data .= $sh;
443
444     $row->{balance}->{data}        = $data;
445     $row->{projectnumbers}->{data} = join ", ", sort { lc($a) cmp lc($b) } keys %{ $ref->{projectnumbers} };
446
447     map { $row->{$_}->{data} = $ref->{$_} } qw(id reference description notes gldate employee);
448
449     map { $row->{$_}->{data} = \@{ $rows{$_} }; } qw(transdate debit credit debit_accno credit_accno debit_tax_accno credit_tax_accno source);
450
451     foreach my $col (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
452       $row->{$col}->{link} = [ map { "${callback}&accno=" . E($_) } @{ $rows{$col} } ];
453     }
454
455     map { $row->{$_}->{data} = \@{ $rows{$_} } if ($ref->{"${_}_accno"} ne "") } qw(debit_tax credit_tax);
456
457     $row->{reference}->{link} = build_std_url("script=$ref->{module}.pl", 'action=edit', 'id=' . E($ref->{id}), 'callback');
458
459     my $row_set = [ $row ];
460
461     if ( ($form->{l_subtotal} eq 'Y' && !$form->{report_generator_csv_options_for_import} )
462         && (($idx == (scalar @{ $form->{GL} } - 1))
463             || ($ref->{ $form->{sort} } ne $form->{GL}->[$idx + 1]->{ $form->{sort} }))) {
464       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, [ qw(debit credit) ], 'listsubtotal');
465     }
466
467     $report->add_data($row_set);
468
469     $idx++;
470   }
471
472   # = 0 for balanced ledger
473   my $balanced_ledger = $totals{debit} + $totals{debit_tax} - $totals{credit} - $totals{credit_tax};
474
475   my $row = create_subtotal_row(\%totals, \@columns, \%column_alignment, [ qw(debit credit debit_tax credit_tax) ], 'listtotal');
476
477   my $sh = "";
478   if ($form->{balance} < 0) {
479     $sh = " S";
480     $ml = -1;
481   } elsif ($form->{balance} > 0) {
482     $sh = " H";
483     $ml = 1;
484   }
485   my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
486   $data .= $sh;
487
488   $row->{balance}->{data}        = $data;
489
490   if ( !$form->{report_generator_csv_options_for_import} ) {
491     $report->add_separator();
492     $report->add_data($row);
493   }
494
495   my $raw_bottom_info_text;
496
497   if (!$form->{accno} && (abs($balanced_ledger) >  0.001)) {
498     $raw_bottom_info_text .=
499         '<p><span class="unbalanced_ledger">'
500       . $locale->text('Unbalanced Ledger')
501       . ': '
502       . $form->format_amount(\%myconfig, $balanced_ledger, 3)
503       . '</span></p> ';
504   }
505
506   $raw_bottom_info_text .= $form->parse_html_template('gl/generate_report_bottom');
507
508   $report->set_options('raw_bottom_info_text' => $raw_bottom_info_text);
509
510   $report->generate_with_headers();
511
512   $main::lxdebug->leave_sub();
513 }
514
515 sub update {
516   $main::lxdebug->enter_sub();
517
518   $main::auth->assert('general_ledger');
519
520   my $form     = $main::form;
521   my %myconfig = %main::myconfig;
522
523   $form->{oldtransdate} = $form->{transdate};
524
525   my @a           = ();
526   my $count       = 0;
527   my $debittax    = 0;
528   my $credittax   = 0;
529   my $debitcount  = 0;
530   my $creditcount = 0;
531   my ($debitcredit, $amount);
532
533   my @flds =
534     qw(accno debit credit projectnumber fx_transaction source memo tax taxchart);
535
536   for my $i (1 .. $form->{rowcount}) {
537
538     unless (($form->{"debit_$i"} eq "") && ($form->{"credit_$i"} eq "")) {
539       for (qw(debit credit tax)) {
540         $form->{"${_}_$i"} =
541           $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
542       }
543
544       push @a, {};
545       $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
546       if ($debitcredit) {
547         $debitcount++;
548       } else {
549         $creditcount++;
550       }
551
552       if (($debitcount >= 2) && ($creditcount == 2)) {
553         $form->{"credit_$i"} = 0;
554         $form->{"tax_$i"}    = 0;
555         $creditcount--;
556         $form->{creditlock} = 1;
557       }
558       if (($creditcount >= 2) && ($debitcount == 2)) {
559         $form->{"debit_$i"} = 0;
560         $form->{"tax_$i"}   = 0;
561         $debitcount--;
562         $form->{debitlock} = 1;
563       }
564       if (($creditcount == 1) && ($debitcount == 2)) {
565         $form->{creditlock} = 1;
566       }
567       if (($creditcount == 2) && ($debitcount == 1)) {
568         $form->{debitlock} = 1;
569       }
570       if ($debitcredit && $credittax) {
571         $form->{"taxchart_$i"} = "0--0.00";
572       }
573       if (!$debitcredit && $debittax) {
574         $form->{"taxchart_$i"} = "0--0.00";
575       }
576       $amount =
577         ($form->{"debit_$i"} == 0)
578         ? $form->{"credit_$i"}
579         : $form->{"debit_$i"};
580       my $j = $#a;
581       if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
582         $form->{"taxchart_$i"} = "0--0.00";
583         $form->{"tax_$i"}      = 0;
584       }
585       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
586       if ($taxkey > 1) {
587         if ($debitcredit) {
588           $debittax = 1;
589         } else {
590           $credittax = 1;
591         }
592       };
593       my ($tmpnetamount,$tmpdiff);
594       ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
595
596       for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
597       $count++;
598     }
599   }
600
601   for my $i (1 .. $count) {
602     my $j = $i - 1;
603     for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
604   }
605
606   for my $i ($count + 1 .. $form->{rowcount}) {
607     for (@flds) { delete $form->{"${_}_$i"} }
608   }
609
610   $form->{rowcount} = $count + 1;
611
612   &display_form;
613   $main::lxdebug->leave_sub();
614
615 }
616
617 sub display_form {
618   my ($init) = @_;
619   $main::lxdebug->enter_sub();
620
621   $main::auth->assert('general_ledger');
622
623   my $form     = $main::form;
624   my %myconfig = %main::myconfig;
625
626   &form_header($init);
627
628   #   for $i (1 .. $form->{rowcount}) {
629   #     $form->{totaldebit} += $form->parse_amount(\%myconfig, $form->{"debit_$i"});
630   #     $form->{totalcredit} += $form->parse_amount(\%myconfig, $form->{"credit_$i"});
631   #
632   #     &form_row($i);
633   #   }
634   &display_rows($init);
635   &form_footer;
636   $main::lxdebug->leave_sub();
637
638 }
639
640 sub display_rows {
641   my ($init) = @_;
642   $main::lxdebug->enter_sub();
643
644   $main::auth->assert('general_ledger');
645
646   my $form     = $main::form;
647   my %myconfig = %main::myconfig;
648   my $cgi      = $::request->{cgi};
649
650   $form->{debit_1}     = 0 if !$form->{"debit_1"};
651   $form->{totaldebit}  = 0;
652   $form->{totalcredit} = 0;
653
654   my %project_labels = ();
655   my @project_values = ("");
656   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
657     push(@project_values, $item->{"id"});
658     $project_labels{$item->{"id"}} = $item->{"projectnumber"};
659   }
660
661   my %chart_labels = ();
662   my @chart_values = ();
663   my %charts = ();
664   my $taxchart_init;
665   foreach my $item (@{ $form->{ALL_CHARTS} }) {
666     if ($item->{charttype} eq 'H'){ #falls ÃƒÅ’berschrift
667       next;                         #ÃŒberspringen (Bug 1150)
668     }
669     my $key = $item->{accno} . "--" . $item->{tax_id};
670     $taxchart_init = $item->{tax_id} unless (@chart_values);
671     push(@chart_values, $key);
672     $chart_labels{$key} = $item->{accno} . "--" . $item->{description};
673     $charts{$item->{accno}} = $item;
674   }
675
676   my ($source, $memo, $source_hidden, $memo_hidden);
677   for my $i (1 .. $form->{rowcount}) {
678     if ($form->{show_details}) {
679       $source = qq|
680       <td><input name="source_$i" value="$form->{"source_$i"}" size="16"></td>|;
681       $memo = qq|
682       <td><input name="memo_$i" value="$form->{"memo_$i"}" size="16"></td>|;
683     } else {
684       $source_hidden = qq|
685       <input type="hidden" name="source_$i" value="$form->{"source_$i"}" size="16">|;
686       $memo_hidden = qq|
687       <input type="hidden" name="memo_$i" value="$form->{"memo_$i"}" size="16">|;
688     }
689
690     my $selected_accno_full;
691     my ($accno_row) = split(/--/, $form->{"accno_$i"});
692     my $item = $charts{$accno_row};
693     $selected_accno_full = "$item->{accno}--$item->{tax_id}";
694
695     my $selected_taxchart = $form->{"taxchart_$i"};
696     my ($selected_accno, $selected_tax_id) = split(/--/, $selected_accno_full);
697     my ($previous_accno, $previous_tax_id) = split(/--/, $form->{"previous_accno_$i"});
698
699     my %taxchart_labels = ();
700     my @taxchart_values = ();
701     my %taxcharts = ();
702     my $filter_accno;
703     $filter_accno = $::form->{ALL_CHARTS}[0]->{accno};
704     $filter_accno = $selected_accno if (!$init and $i < $form->{rowcount});
705     foreach my $item ( GL->get_tax_dropdown($filter_accno) ) {
706       my $key = $item->{id} . "--" . $item->{rate};
707       $taxchart_init = $key if ($taxchart_init == $item->{id});
708       push(@taxchart_values, $key);
709       $taxchart_labels{$key} = $item->{taxdescription} . " " . $item->{rate} * 100 . ' %';
710       $taxcharts{$item->{id}} = $item;
711     }
712
713     if ($previous_accno &&
714         ($previous_accno eq $selected_accno) &&
715         ($previous_tax_id ne $selected_tax_id)) {
716       my $item = $taxcharts{$selected_tax_id};
717       $selected_taxchart = "$item->{id}--$item->{rate}";
718     }
719
720     $selected_accno      = '' if ($init);
721     $selected_taxchart ||= $taxchart_init;
722
723     my $accno = qq|<td>| .
724       NTI($cgi->popup_menu('-name' => "accno_$i",
725                            '-id' => "accno_$i",
726                            '-onChange' => "updateTaxes($i);",
727                            '-style' => 'width:200px',
728                            '-values' => \@chart_values,
729                            '-labels' => \%chart_labels,
730                            '-default' => $selected_accno_full))
731       . $cgi->hidden('-name' => "previous_accno_$i",
732                      '-default' => $selected_accno_full)
733       . qq|</td>|;
734     my $tax_ddbox = qq|<td>| .
735       NTI($cgi->popup_menu('-name' => "taxchart_$i",
736             '-id' => "taxchart_$i",
737             '-style' => 'width:200px',
738             '-values' => \@taxchart_values,
739             '-labels' => \%taxchart_labels,
740             '-default' => $selected_taxchart))
741       . qq|</td>|;
742
743     my ($fx_transaction, $checked);
744     if ($init) {
745       if ($form->{transfer}) {
746         $fx_transaction = qq|
747         <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
748     |;
749       }
750
751     } else {
752       if ($form->{"debit_$i"} != 0) {
753         $form->{totaldebit} += $form->{"debit_$i"};
754         if (!$form->{taxincluded}) {
755           $form->{totaldebit} += $form->{"tax_$i"};
756         }
757       } else {
758         $form->{totalcredit} += $form->{"credit_$i"};
759         if (!$form->{taxincluded}) {
760           $form->{totalcredit} += $form->{"tax_$i"};
761         }
762       }
763
764       for (qw(debit credit tax)) {
765         $form->{"${_}_$i"} =
766           ($form->{"${_}_$i"})
767           ? $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
768           : "";
769       }
770
771       if ($i < $form->{rowcount}) {
772         if ($form->{transfer}) {
773           $checked = ($form->{"fx_transaction_$i"}) ? "1" : "";
774           my $x = ($checked) ? "x" : "";
775           $fx_transaction = qq|
776       <td><input type=hidden name="fx_transaction_$i" value="$checked">$x</td>
777     |;
778         }
779         $form->hide_form("accno_$i");
780
781       } else {
782         if ($form->{transfer}) {
783           $fx_transaction = qq|
784       <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
785     |;
786         }
787       }
788     }
789     my $debitreadonly  = "";
790     my $creditreadonly = "";
791     if ($i == $form->{rowcount}) {
792       if ($form->{debitlock}) {
793         $debitreadonly = "readonly";
794       } elsif ($form->{creditlock}) {
795         $creditreadonly = "readonly";
796       }
797     }
798
799     my $projectnumber =
800       NTI($cgi->popup_menu('-name' => "project_id_$i",
801                            '-values' => \@project_values,
802                            '-labels' => \%project_labels,
803                            '-default' => $form->{"project_id_$i"} ));
804     my $projectnumber_hidden = qq|
805     <input type="hidden" name="project_id_$i" value="$form->{"project_id_$i"}">|;
806
807     my $copy2credit = $i == 1 ? 'onkeyup="copy_debit_to_credit()"' : '';
808
809     print qq|<tr valign=top>
810     $accno
811     <td id="chart_balance_$i" align="right">&nbsp;</td>
812     $fx_transaction
813     <td><input name="debit_$i" size="8" value="$form->{"debit_$i"}" accesskey=$i $copy2credit $debitreadonly></td>
814     <td><input name="credit_$i" size=8 value="$form->{"credit_$i"}" $creditreadonly></td>
815     <td><input type="hidden" name="tax_$i" value="$form->{"tax_$i"}">$form->{"tax_$i"}</td>
816     $tax_ddbox|;
817
818     if ($form->{show_details}) {
819       print qq|
820     $source
821     $memo
822     <td>$projectnumber</td>
823 |;
824     } else {
825     print qq|
826     $source_hidden
827     $memo_hidden
828     $projectnumber_hidden
829     |;
830     }
831     print qq|
832   </tr>
833 |;
834   }
835
836   $form->hide_form(qw(rowcount selectaccno));
837
838   $main::lxdebug->leave_sub();
839
840 }
841
842 sub _get_radieren {
843   return ($::instance_conf->get_gl_changeable == 2) ? ($::form->current_date(\%::myconfig) eq $::form->{gldate}) : ($::instance_conf->get_gl_changeable == 1);
844 }
845
846 sub form_header {
847   $::lxdebug->enter_sub;
848   $::auth->assert('general_ledger');
849
850   my ($init) = @_;
851
852   my @old_project_ids = grep { $_ } map{ $::form->{"project_id_$_"} } 1..$::form->{rowcount};
853
854   $::form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
855                                     "all"       => 0,
856                                     "old_id"    => \@old_project_ids },
857                    "charts"    => { "key"       => "ALL_CHARTS",
858                                     "transdate" => $::form->{transdate} });
859
860   GL->get_chart_balances('charts' => $::form->{ALL_CHARTS});
861
862   my $title      = $::form->{title};
863   $::form->{title} = $::locale->text("$title General Ledger Transaction");
864   # $locale->text('Add General Ledger Transaction')
865   # $locale->text('Edit General Ledger Transaction')
866
867   map { $::form->{$_} =~ s/\"/&quot;/g }
868     qw(chart taxchart);
869
870   $::form->{selectdepartment} =~ s/ selected//;
871   $::form->{selectdepartment} =~
872     s/option>\Q$::form->{department}\E/option selected>$::form->{department}/;
873
874   if ($init) {
875     $::request->{layout}->focus("#reference");
876     $::form->{taxincluded} = "1";
877   } else {
878     $::request->{layout}->focus("#accno_$::form->{rowcount}");
879   }
880
881   $::form->{previous_id}     ||= "--";
882   $::form->{previous_gldate} ||= "--";
883
884   $::form->header;
885   print $::form->parse_html_template('gl/form_header', {
886     hide_title => $title,
887     readonly   => $::form->{id} && ($::form->{locked} || !_get_radieren()),
888   });
889
890   $::lxdebug->leave_sub;
891
892 }
893
894 sub form_footer {
895   $::lxdebug->enter_sub;
896   $::auth->assert('general_ledger');
897
898   my ($follow_ups, $follow_ups_due);
899
900   if ($::form->{id}) {
901     $follow_ups     = FU->follow_ups('trans_id' => $::form->{id});
902     $follow_ups_due = sum map { $_->{due} * 1 } @{ $follow_ups || [] };
903   }
904
905   print $::form->parse_html_template('gl/form_footer', {
906     radieren       => _get_radieren(),
907     follow_ups     => $follow_ups,
908     follow_ups_due => $follow_ups_due,
909   });
910
911   $::lxdebug->leave_sub;
912 }
913
914 sub delete {
915   $main::lxdebug->enter_sub();
916
917   my $form     = $main::form;
918   my $locale   = $main::locale;
919
920   $form->header;
921
922   print qq|
923 <form method=post action=gl.pl>
924 |;
925
926   map { $form->{$_} =~ s/\"/&quot;/g } qw(reference description);
927
928   delete $form->{header};
929
930   foreach my $key (keys %$form) {
931     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
932     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
933   }
934
935   print qq|
936 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
937
938 <h4>|
939     . $locale->text('Are you sure you want to delete Transaction')
940     . qq| $form->{reference}</h4>
941
942 <input name=action class=submit type=submit value="|
943     . $locale->text('Yes') . qq|">
944 </form>
945 |;
946   $main::lxdebug->leave_sub();
947
948 }
949
950 sub yes {
951   $main::lxdebug->enter_sub();
952
953   my $form     = $main::form;
954   my %myconfig = %main::myconfig;
955   my $locale   = $main::locale;
956
957   if (GL->delete_transaction(\%myconfig, \%$form)){
958     # saving the history
959       if(!exists $form->{addition} && $form->{id} ne "") {
960         $form->{snumbers} = qq|gltransaction_| . $form->{id};
961         $form->{addition} = "DELETED";
962         $form->{what_done} = "gl_transaction";
963         $form->save_history;
964       }
965     # /saving the history
966     $form->redirect($locale->text('Transaction deleted!'))
967   }
968   $form->error($locale->text('Cannot delete transaction!'));
969   $main::lxdebug->leave_sub();
970
971 }
972
973 sub post_transaction {
974   $main::lxdebug->enter_sub();
975
976   my $form     = $main::form;
977   my %myconfig = %main::myconfig;
978   my $locale   = $main::locale;
979
980   # check if there is something in reference and date
981   $form->isblank("reference",   $locale->text('Reference missing!'));
982   $form->isblank("transdate",   $locale->text('Transaction Date missing!'));
983   $form->isblank("description", $locale->text('Description missing!'));
984
985   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
986   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
987
988   my @a           = ();
989   my $count       = 0;
990   my $debittax    = 0;
991   my $credittax   = 0;
992   my $debitcount  = 0;
993   my $creditcount = 0;
994   my $debitcredit;
995   my %split_safety = ();
996
997   my $dbh = $form->dbconnect_noauto(\%myconfig);
998   my ($notax_id) = selectrow_query($form, $dbh, "SELECT id FROM tax WHERE taxkey = 0 LIMIT 1", );
999   $dbh->disconnect;
1000
1001   my @flds = qw(accno debit credit projectnumber fx_transaction source memo tax taxchart);
1002
1003   for my $i (1 .. $form->{rowcount}) {
1004     next if $form->{"debit_$i"} eq "" && $form->{"credit_$i"} eq "";
1005
1006     for (qw(debit credit tax)) {
1007       $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
1008     }
1009
1010     push @a, {};
1011     $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
1012
1013     $split_safety{   $form->{"debit_$i"}  <=> 0 }++;
1014     $split_safety{ - $form->{"credit_$i"} <=> 0 }++;
1015
1016     if ($debitcredit) {
1017       $debitcount++;
1018     } else {
1019       $creditcount++;
1020     }
1021
1022     if (($debitcount >= 2) && ($creditcount == 2)) {
1023       $form->{"credit_$i"} = 0;
1024       $form->{"tax_$i"}    = 0;
1025       $creditcount--;
1026       $form->{creditlock} = 1;
1027     }
1028     if (($creditcount >= 2) && ($debitcount == 2)) {
1029       $form->{"debit_$i"} = 0;
1030       $form->{"tax_$i"}   = 0;
1031       $debitcount--;
1032       $form->{debitlock} = 1;
1033     }
1034     if (($creditcount == 1) && ($debitcount == 2)) {
1035       $form->{creditlock} = 1;
1036     }
1037     if (($creditcount == 2) && ($debitcount == 1)) {
1038       $form->{debitlock} = 1;
1039     }
1040     if ($debitcredit && $credittax) {
1041       $form->{"taxchart_$i"} = "$notax_id--0.00";
1042     }
1043     if (!$debitcredit && $debittax) {
1044       $form->{"taxchart_$i"} = "$notax_id--0.00";
1045     }
1046     my $amount = ($form->{"debit_$i"} == 0)
1047             ? $form->{"credit_$i"}
1048             : $form->{"debit_$i"};
1049     my $j = $#a;
1050     if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
1051       $form->{"taxchart_$i"} = "$notax_id--0.00";
1052       $form->{"tax_$i"}      = 0;
1053     }
1054     my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
1055     if ($taxkey > 1) {
1056       if ($debitcredit) {
1057         $debittax = 1;
1058       } else {
1059         $credittax = 1;
1060       }
1061
1062       my ($tmpnetamount,$tmpdiff);
1063       ($tmpnetamount,$form->{"tax_$i"},$tmpdiff) = $form->calculate_tax($amount,$rate,$form->{taxincluded} *= 1,2);
1064       if ($debitcredit) {
1065         $form->{"debit_$i"} = $tmpnetamount;
1066       } else {
1067         $form->{"credit_$i"} = $tmpnetamount;
1068       }
1069
1070     } else {
1071       $form->{"tax_$i"} = 0;
1072     }
1073
1074     for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
1075     $count++;
1076   }
1077
1078   if ($split_safety{-1} > 1 && $split_safety{1} > 1) {
1079     $::form->error($::locale->text("Split entry detected. The values you have entered will result in an entry with more than one position on both debit and credit. " .
1080                                    "Due to known problems involving accounting software kivitendo does not allow these."));
1081   }
1082
1083   for my $i (1 .. $count) {
1084     my $j = $i - 1;
1085     for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
1086   }
1087
1088   for my $i ($count + 1 .. $form->{rowcount}) {
1089     for (@flds) { delete $form->{"${_}_$i"} }
1090   }
1091
1092   my ($debit, $credit, $taxtotal);
1093   for my $i (1 .. $form->{rowcount}) {
1094     my $dr  = $form->{"debit_$i"};
1095     my $cr  = $form->{"credit_$i"};
1096     my $tax = $form->{"tax_$i"};
1097     if ($dr && $cr) {
1098       $form->error($locale->text('Cannot post transaction with a debit and credit entry for the same account!'));
1099     }
1100     $debit    += $dr + $tax if $dr;
1101     $credit   += $cr + $tax if $cr;
1102     $taxtotal += $tax if $form->{taxincluded}
1103   }
1104
1105   $form->{taxincluded} = 0 if !$taxtotal;
1106
1107   # this is just for the wise guys
1108
1109   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1110     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
1111   $form->error($locale->text('Cannot post transaction for a closed period!'))
1112     if ($form->date_closed($form->{"transdate"}, \%myconfig));
1113   if ($form->round_amount($debit, 2) != $form->round_amount($credit, 2)) {
1114     $form->error($locale->text('Out of balance transaction!'));
1115   }
1116
1117   if ($form->round_amount($debit, 2) + $form->round_amount($credit, 2) == 0) {
1118     $form->error($locale->text('Empty transaction!'));
1119   }
1120
1121   if ((my $errno = GL->post_transaction(\%myconfig, \%$form)) <= -1) {
1122     $errno *= -1;
1123     my @err;
1124     $err[1] = $locale->text('Cannot have a value in both Debit and Credit!');
1125     $err[2] = $locale->text('Debit and credit out of balance!');
1126     $err[3] = $locale->text('Cannot post a transaction without a value!');
1127
1128     $form->error($err[$errno]);
1129   }
1130   undef($form->{callback});
1131   # saving the history
1132   if(!exists $form->{addition} && $form->{id} ne "") {
1133     $form->{snumbers} = qq|gltransaction_| . $form->{id};
1134     $form->{addition} = "POSTED";
1135     $form->{what_done} = "gl transaction";
1136     $form->save_history;
1137   }
1138   # /saving the history
1139
1140   $main::lxdebug->leave_sub();
1141 }
1142
1143 sub post {
1144   $main::lxdebug->enter_sub();
1145
1146   $main::auth->assert('general_ledger');
1147
1148   my $form     = $main::form;
1149   my $locale   = $main::locale;
1150
1151   if ($::myconfig{mandatory_departments} && !$form->{department}) {
1152     $form->{saved_message} = $::locale->text('You have to specify a department.');
1153     update();
1154     exit;
1155   }
1156
1157   $form->{title}  = $locale->text("$form->{title} General Ledger Transaction");
1158   $form->{storno} = 0;
1159
1160   post_transaction();
1161
1162   remove_draft() if $form->{remove_draft};
1163
1164   $form->{callback} = build_std_url("action=add&DONT_LOAD_DRAFT=1", "show_details");
1165   $form->redirect($form->{callback});
1166
1167   $main::lxdebug->leave_sub();
1168 }
1169
1170 sub post_as_new {
1171   $main::lxdebug->enter_sub();
1172
1173   $main::auth->assert('general_ledger');
1174
1175   my $form     = $main::form;
1176
1177   $form->{id} = 0;
1178   &add;
1179   $main::lxdebug->leave_sub();
1180
1181 }
1182
1183 sub storno {
1184   $main::lxdebug->enter_sub();
1185
1186   $main::auth->assert('general_ledger');
1187
1188   my $form     = $main::form;
1189   my %myconfig = %main::myconfig;
1190   my $locale   = $main::locale;
1191
1192   # don't cancel cancelled transactions
1193   if (IS->has_storno(\%myconfig, $form, 'gl')) {
1194     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1195     $form->error($locale->text("Transaction has already been cancelled!"));
1196   }
1197
1198   GL->storno($form, \%myconfig, $form->{id});
1199
1200   # saving the history
1201   if(!exists $form->{addition} && $form->{id} ne "") {
1202     $form->{snumbers} = qq|gltransaction_| . $form->{id};
1203     $form->{addition} = "STORNO";
1204     $form->{what_done} = "gl_transaction";
1205     $form->save_history;
1206   }
1207   # /saving the history
1208
1209   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1210
1211   $main::lxdebug->leave_sub();
1212 }
1213
1214 sub continue {
1215   call_sub($main::form->{nextsub});
1216 }
1217
1218 sub get_tax_dropdown {
1219   $main::lxdebug->enter_sub();
1220
1221   my $form = $main::form;
1222   my @tax_accounts = GL->get_tax_dropdown($form->{accno});
1223
1224   foreach my $item (@tax_accounts) {
1225     $item->{taxdescription} = $::locale->{iconv_utf8}->convert($item->{taxdescription});
1226     $item->{taxdescription} .= ' ' . $form->round_amount($item->{rate} * 100);
1227   }
1228
1229   $form->{TAX_ACCOUNTS} = [ @tax_accounts ];
1230
1231   print $form->ajax_response_header, $form->parse_html_template("gl/update_tax_accounts");
1232
1233   $main::lxdebug->leave_sub();
1234
1235 }
1236
1237 1;