save_history sollte NICHT jedesmal eine neue datenbankverbindung aufmachen.
[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 POSIX qw(strftime);
35 use List::Util qw(sum);
36
37 use SL::FU;
38 use SL::GL;
39 use SL::IS;
40 use SL::PE;
41 use SL::ReportGenerator;
42
43 require "bin/mozilla/common.pl";
44 require "bin/mozilla/drafts.pl";
45 require "bin/mozilla/reportgenerator.pl";
46
47 use strict;
48
49 # this is for our long dates
50 # $locale->text('January')
51 # $locale->text('February')
52 # $locale->text('March')
53 # $locale->text('April')
54 # $locale->text('May ')
55 # $locale->text('June')
56 # $locale->text('July')
57 # $locale->text('August')
58 # $locale->text('September')
59 # $locale->text('October')
60 # $locale->text('November')
61 # $locale->text('December')
62
63 # this is for our short month
64 # $locale->text('Jan')
65 # $locale->text('Feb')
66 # $locale->text('Mar')
67 # $locale->text('Apr')
68 # $locale->text('May')
69 # $locale->text('Jun')
70 # $locale->text('Jul')
71 # $locale->text('Aug')
72 # $locale->text('Sep')
73 # $locale->text('Oct')
74 # $locale->text('Nov')
75 # $locale->text('Dec')
76
77 sub add {
78   $main::lxdebug->enter_sub();
79
80   $main::auth->assert('general_ledger');
81
82   my $form     = $main::form;
83   my %myconfig = %main::myconfig;
84
85   return $main::lxdebug->leave_sub() if (load_draft_maybe());
86
87   $form->{title} = "Add";
88
89   $form->{callback} = "gl.pl?action=add" unless $form->{callback};
90
91   # we use this only to set a default date
92   # yep. aber er holt hier auch schon ALL_CHARTS. Aufwand / Nutzen? jb
93   GL->transaction(\%myconfig, \%$form);
94
95   $form->{rowcount}  = 2;
96
97   $form->{debit}  = 0;
98   $form->{credit} = 0;
99   $form->{tax}    = 0;
100
101   # departments
102   $form->all_departments(\%myconfig);
103   if (@{ $form->{all_departments} || [] }) {
104     $form->{selectdepartment} = "<option>\n";
105
106     map {
107       $form->{selectdepartment} .=
108         "<option>$_->{description}--$_->{id}\n"
109     } (@{ $form->{all_departments} || [] });
110   }
111
112   $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
113
114   &display_form(1);
115   $main::lxdebug->leave_sub();
116
117 }
118
119 sub prepare_transaction {
120   $main::lxdebug->enter_sub();
121
122   $main::auth->assert('general_ledger');
123
124   my $form     = $main::form;
125   my %myconfig = %main::myconfig;
126
127   GL->transaction(\%myconfig, \%$form);
128
129   $form->{amount} = $form->format_amount(\%myconfig, $form->{amount}, 2);
130
131   # departments
132   $form->all_departments(\%myconfig);
133   if (@{ $form->{all_departments} || [] }) {
134     $form->{selectdepartment} = "<option>\n";
135
136     map {
137       $form->{selectdepartment} .=
138         "<option>$_->{description}--$_->{id}\n"
139     } (@{ $form->{all_departments} || [] });
140   }
141
142   my $i        = 1;
143   my $tax      = 0;
144   my $taxaccno = "";
145   foreach my $ref (@{ $form->{GL} }) {
146     my $j = $i - 1;
147     if ($tax && ($ref->{accno} eq $taxaccno)) {
148       $form->{"tax_$j"}      = abs($ref->{amount});
149       $form->{"taxchart_$j"} = $ref->{id} . "--" . $ref->{taxrate};
150       if ($form->{taxincluded}) {
151         if ($ref->{amount} < 0) {
152           $form->{"debit_$j"} += $form->{"tax_$j"};
153         } else {
154           $form->{"credit_$j"} += $form->{"tax_$j"};
155         }
156       }
157       $form->{"project_id_$j"} = $ref->{project_id};
158
159     } else {
160       $form->{"accno_$i"} = "$ref->{accno}--$ref->{tax_id}";
161       for (qw(fx_transaction source memo)) { $form->{"${_}_$i"} = $ref->{$_} }
162       if ($ref->{amount} < 0) {
163         $form->{totaldebit} -= $ref->{amount};
164         $form->{"debit_$i"} = $ref->{amount} * -1;
165       } else {
166         $form->{totalcredit} += $ref->{amount};
167         $form->{"credit_$i"} = $ref->{amount};
168       }
169       $form->{"taxchart_$i"} = "0--0.00";
170       $form->{"project_id_$i"} = $ref->{project_id};
171       $i++;
172     }
173     if ($ref->{taxaccno} && !$tax) {
174       $taxaccno = $ref->{taxaccno};
175       $tax      = 1;
176     } else {
177       $taxaccno = "";
178       $tax      = 0;
179     }
180   }
181
182   $form->{rowcount} = $i;
183   $form->{locked}   =
184     ($form->datetonum($form->{transdate}, \%myconfig) <=
185      $form->datetonum($form->{closedto}, \%myconfig));
186
187   $main::lxdebug->leave_sub();
188 }
189
190 sub edit {
191   $main::lxdebug->enter_sub();
192
193   $main::auth->assert('general_ledger');
194
195   my $form     = $main::form;
196   my %myconfig = %main::myconfig;
197
198   prepare_transaction();
199
200   $form->{title} = "Edit";
201
202   $form->{show_details} = $myconfig{show_form_details} unless defined $form->{show_details};
203
204   form_header();
205   display_rows();
206   form_footer();
207
208   $main::lxdebug->leave_sub();
209 }
210
211
212 sub search {
213   $main::lxdebug->enter_sub();
214
215   $main::auth->assert('general_ledger');
216
217   my $form     = $main::form;
218   my %myconfig = %main::myconfig;
219   my $locale   = $main::locale;
220   my $cgi      = $main::cgi;
221
222   $form->{title} = $locale->text('Journal');
223
224   $form->all_departments(\%myconfig);
225
226   # departments
227   if (@{ $form->{all_departments} || [] }) {
228     $form->{selectdepartment} = "<option>\n";
229
230     map {
231       $form->{selectdepartment} .=
232         "<option>$_->{description}--$_->{id}\n"
233     } (@{ $form->{all_departments} || [] });
234   }
235
236   my $department = qq|
237         <tr>
238           <th align=right nowrap>| . $locale->text('Department') . qq|</th>
239           <td colspan=3><select name=department>$form->{selectdepartment}</select></td>
240         </tr>
241 | if $form->{selectdepartment};
242
243   $form->get_lists("projects" => { "key" => "ALL_PROJECTS",
244                                    "all" => 1 });
245
246   my %project_labels = ();
247   my @project_values = ("");
248   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
249     push(@project_values, $item->{"id"});
250     $project_labels{$item->{"id"}} = $item->{"projectnumber"};
251   }
252
253   my $projectnumber =
254     NTI($cgi->popup_menu('-name' => "project_id",
255                          '-values' => \@project_values,
256                          '-labels' => \%project_labels));
257
258   # use JavaScript Calendar or not
259   $form->{jsscript} = 1;
260   my $jsscript = "";
261   my ($button1, $button2, $onload);
262   if ($form->{jsscript}) {
263
264     # with JavaScript Calendar
265     $button1 = qq|
266        <td><input name=datefrom id=datefrom size=11 title="$myconfig{dateformat}" onBlur=\"check_right_date_format(this)\">
267        <input type=button name=datefrom id="trigger1" value=|
268       . $locale->text('button') . qq|></td>
269        |;
270     $button2 = qq|
271        <td><input name=dateto id=dateto size=11 title="$myconfig{dateformat}" onBlur=\"check_right_date_format(this)\">
272        <input type=button name=dateto id="trigger2" value=|
273       . $locale->text('button') . qq|></td>
274      |;
275
276     #write Trigger
277     $jsscript =
278       Form->write_trigger(\%myconfig, "2", "datefrom", "BR", "trigger1",
279                           "dateto", "BL", "trigger2");
280   } else {
281
282     # without JavaScript Calendar
283     $button1 =
284       qq|<td><input name=datefrom id=datefrom size=11 title="$myconfig{dateformat}" onBlur=\"check_right_date_format(this)\"></td>|;
285     $button2 =
286       qq|<td><input name=dateto id=dateto size=11 title="$myconfig{dateformat}" onBlur=\"check_right_date_format(this)\"></td>|;
287   }
288   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
289   $form->header;
290   $onload = qq|focus()|;
291   $onload .= qq|;setupDateFormat('|. $myconfig{dateformat} .qq|', '|. $locale->text("Falsches Datumsformat!") .qq|')|;
292   $onload .= qq|;setupPoints('|. $myconfig{numberformat} .qq|', '|. $locale->text("wrongformat") .qq|')|;
293   print qq|
294 <body onLoad="$onload">
295
296 <form method=post action=gl.pl>
297
298 <input type=hidden name=sort value=transdate>
299
300 <table width=100%>
301   <tr>
302     <th class=listtop>$form->{title}</th>
303   </tr>
304   <tr height="5"></tr>
305   <tr>
306     <td>
307       <table>
308         <tr>
309           <th align=right>| . $locale->text('Reference') . qq|</th>
310           <td><input name=reference size=20></td>
311           <th align=right>| . $locale->text('Source') . qq|</th>
312           <td><input name=source size=20></td>
313         </tr>
314         $department
315         <tr>
316           <th align=right>| . $locale->text('Description') . qq|</th>
317           <td colspan=3><input name=description size=40></td>
318         </tr>
319         <tr>
320           <th align=right>| . $locale->text('Notes') . qq|</th>
321           <td colspan=3><input name=notes size=40></td>
322         </tr>
323         <tr>
324           <th align=right>| . $locale->text('Project Number') . qq|</th>
325           <td colspan=3>$projectnumber</td>
326         </tr>
327         <tr>
328           <th align=right>| . $locale->text('From') . qq|</th>
329           $button1
330           <th align=right>| . $locale->text('To (time)') . qq|</th>
331           $button2
332         </tr>
333         <tr>
334           <th align=right>| . $locale->text('Include in Report') . qq|</th>
335           <td colspan=3>
336             <table>
337               <tr>
338                 <td>
339                   <input name="category" class=radio type=radio value=X checked>&nbsp;|
340     . $locale->text('All') . qq|
341                   <input name="category" class=radio type=radio value=A>&nbsp;|
342     . $locale->text('Asset') . qq|
343                   <input name="category" class=radio type=radio value=L>&nbsp;|
344     . $locale->text('Liability') . qq|
345                   <input name="category" class=radio type=radio value=I>&nbsp;|
346     . $locale->text('Revenue') . qq|
347                   <input name="category" class=radio type=radio value=E>&nbsp;|
348     . $locale->text('Expense') . qq|
349                 </td>
350               </tr>
351               <tr>
352                 <table>
353                   <tr>
354                     <td align=right><input name="l_id" class=checkbox type=checkbox value=Y></td>
355                     <td>| . $locale->text('ID') . qq|</td>
356                     <td align=right><input name="l_transdate" class=checkbox type=checkbox value=Y checked></td>
357                     <td>| . $locale->text('Date') . qq|</td>
358                     <td align=right><input name="l_reference" class=checkbox type=checkbox value=Y checked></td>
359                     <td>| . $locale->text('Reference') . qq|</td>
360                     <td align=right><input name="l_description" class=checkbox type=checkbox value=Y checked></td>
361                     <td>| . $locale->text('Description') . qq|</td>
362                     <td align=right><input name="l_notes" class=checkbox type=checkbox value=Y></td>
363                     <td>| . $locale->text('Notes') . qq|</td>
364                   </tr>
365                   <tr>
366                     <td align=right><input name="l_debit" class=checkbox type=checkbox value=Y checked></td>
367                     <td>| . $locale->text('Debit') . qq|</td>
368                     <td align=right><input name="l_credit" class=checkbox type=checkbox value=Y checked></td>
369                     <td>| . $locale->text('Credit') . qq|</td>
370                     <td align=right><input name="l_source" class=checkbox type=checkbox value=Y checked></td>
371                     <td>| . $locale->text('Source') . qq|</td>
372                     <td align=right><input name="l_accno" class=checkbox type=checkbox value=Y checked></td>
373                     <td>| . $locale->text('Account') . qq|</td>
374                   </tr>
375                   <tr>
376                     <td align=right><input name="l_subtotal" class=checkbox type=checkbox value=Y></td>
377                     <td>| . $locale->text('Subtotal') . qq|</td>
378                     <td align=right><input name="l_projectnumbers" class=checkbox type=checkbox value=Y></td>
379                     <td>| . $locale->text('Project Number') . qq|</td>
380                   </tr>
381                 </table>
382               </tr>
383             </table>
384         </tr>
385       </table>
386     </td>
387   </tr>
388   <tr>
389     <td><hr size=3 noshade></td>
390   </tr>
391 </table>
392
393 $jsscript
394
395 <input type=hidden name=nextsub value=generate_report>
396
397 <br>
398 <input class=submit type=submit name=action value="|
399     . $locale->text('Continue') . qq|">
400 </form>
401
402 </body>
403 </html>
404 |;
405   $main::lxdebug->leave_sub();
406 }
407
408 sub create_subtotal_row {
409   $main::lxdebug->enter_sub();
410
411   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
412
413   my $form     = $main::form;
414   my %myconfig = %main::myconfig;
415
416   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
417
418   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
419
420   map { $totals->{$_} = 0 } @{ $subtotal_columns };
421
422   $main::lxdebug->leave_sub();
423
424   return $row;
425 }
426
427 sub generate_report {
428   $main::lxdebug->enter_sub();
429
430   $main::auth->assert('general_ledger');
431
432   my $form     = $main::form;
433   my %myconfig = %main::myconfig;
434   my $locale   = $main::locale;
435
436   report_generator_set_default_sort('transdate', 1);
437
438   GL->all_transactions(\%myconfig, \%$form);
439
440   my %acctype = ('A' => $locale->text('Asset'),
441                  'C' => $locale->text('Contra'),
442                  'L' => $locale->text('Liability'),
443                  'Q' => $locale->text('Equity'),
444                  'I' => $locale->text('Revenue'),
445                  'E' => $locale->text('Expense'),);
446
447   $form->{title} = $locale->text('Journal');
448   if ($form->{category} ne 'X') {
449     $form->{title} .= " : " . $locale->text($acctype{ $form->{category} });
450   }
451
452   $form->{landscape} = 1;
453
454   my $ml = ($form->{ml} =~ /(A|E|Q)/) ? -1 : 1;
455
456   my @columns = qw(
457     transdate      id               reference      description
458     notes          source           debit          debit_accno
459     credit         credit_accno     debit_tax      debit_tax_accno
460     credit_tax     credit_tax_accno projectnumbers balance
461   );
462
463   my @hidden_variables = qw(accno source reference department description notes project_id datefrom dateto category l_subtotal);
464   push @hidden_variables, map { "l_${_}" } @columns;
465
466   my (@options, @date_options);
467   push @options,      $locale->text('Account')     . " : $form->{accno} $form->{account_description}" if ($form->{accno});
468   push @options,      $locale->text('Source')      . " : $form->{source}"                             if ($form->{source});
469   push @options,      $locale->text('Reference')   . " : $form->{reference}"                          if ($form->{reference});
470   push @options,      $locale->text('Description') . " : $form->{description}"                        if ($form->{description});
471   push @options,      $locale->text('Notes')       . " : $form->{notes}"                              if ($form->{notes});
472
473   push @date_options, $locale->text('From'), $locale->date(\%myconfig, $form->{datefrom}, 1)          if ($form->{datefrom});
474   push @date_options, $locale->text('Bis'),  $locale->date(\%myconfig, $form->{dateto},   1)          if ($form->{dateto});
475   push @options,      join(' ', @date_options)                                                        if (scalar @date_options);
476
477   if ($form->{department}) {
478     my ($department) = split /--/, $form->{department};
479     push @options, $locale->text('Department') . " : $department";
480   }
481
482
483   my $callback = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
484
485   $form->{l_credit_accno}     = 'Y';
486   $form->{l_debit_accno}      = 'Y';
487   $form->{l_credit_tax}       = 'Y';
488   $form->{l_debit_tax}        = 'Y';
489   $form->{l_credit_tax_accno} = 'Y';
490   $form->{l_debit_tax_accno}  = 'Y';
491   $form->{l_balance}          = $form->{accno} ? 'Y' : '';
492
493   my %column_defs = (
494     'id'               => { 'text' => $locale->text('ID'), },
495     'transdate'        => { 'text' => $locale->text('Date'), },
496     'reference'        => { 'text' => $locale->text('Reference'), },
497     'source'           => { 'text' => $locale->text('Source'), },
498     'description'      => { 'text' => $locale->text('Description'), },
499     'notes'            => { 'text' => $locale->text('Notes'), },
500     'debit'            => { 'text' => $locale->text('Debit'), },
501     'debit_accno'      => { 'text' => $locale->text('Debit Account'), },
502     'credit'           => { 'text' => $locale->text('Credit'), },
503     'credit_accno'     => { 'text' => $locale->text('Credit Account'), },
504     'debit_tax'        => { 'text' => $locale->text('Debit Tax'), },
505     'debit_tax_accno'  => { 'text' => $locale->text('Debit Tax Account'), },
506     'credit_tax'       => { 'text' => $locale->text('Credit Tax'), },
507     'credit_tax_accno' => { 'text' => $locale->text('Credit Tax Account'), },
508     'balance'          => { 'text' => $locale->text('Balance'), },
509     'projectnumbers'   => { 'text' => $locale->text('Project Numbers'), },
510   );
511
512   foreach my $name (qw(id transdate reference description debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
513     my $sortname                = $name =~ m/accno/ ? 'accno' : $name;
514     my $sortdir                 = $sortname eq $form->{sort} ? 1 - $form->{sortdir} : $form->{sortdir};
515     $column_defs{$name}->{link} = $callback . "&sort=$sortname&sortdir=$sortdir";
516   }
517
518   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
519   map { $column_defs{$_}->{visible} = 0 } qw(debit_accno credit_accno debit_tax_accno credit_tax_accno) if $form->{accno};
520
521   my %column_alignment;
522   map { $column_alignment{$_}     = 'right'  } qw(balance id debit credit debit_tax credit_tax balance);
523   map { $column_alignment{$_}     = 'center' } qw(reference debit_accno credit_accno debit_tax_accno credit_tax_accno);
524   map { $column_alignment{$_}     = 'left' } qw(description source notes);
525   map { $column_defs{$_}->{align} = $column_alignment{$_} } keys %column_alignment;
526
527   my $report = SL::ReportGenerator->new(\%myconfig, $form);
528
529   $report->set_columns(%column_defs);
530   $report->set_column_order(@columns);
531
532   $report->set_export_options('generate_report', @hidden_variables, qw(sort sortdir));
533
534   $report->set_sort_indicator($form->{sort} eq 'accno' ? 'debit_accno' : $form->{sort}, $form->{sortdir});
535
536   $report->set_options('top_info_text'        => join("\n", @options),
537                        'output_format'        => 'HTML',
538                        'title'                => $form->{title},
539                        'attachment_basename'  => $locale->text('general_ledger_list') . strftime('_%Y%m%d', localtime time),
540     );
541   $report->set_options_from_form();
542
543   # add sort to callback
544   $form->{callback} = "$callback&sort=" . E($form->{sort}) . "&sortdir=" . E($form->{sortdir});
545
546
547   my @totals_columns = qw(debit credit debit_tax credit_tax);
548   my %subtotals      = map { $_ => 0 } @totals_columns;
549   my %totals         = map { $_ => 0 } @totals_columns;
550   my $idx            = 0;
551
552   foreach my $ref (@{ $form->{GL} }) {
553
554     my %rows;
555
556     foreach my $key (qw(debit credit debit_tax credit_tax)) {
557       $rows{$key} = [];
558       foreach my $idx (sort keys(%{ $ref->{$key} })) {
559         my $value         = $ref->{$key}->{$idx};
560         $subtotals{$key} += $value;
561         $totals{$key}    += $value;
562         if ($key =~ /debit.*/) {
563           $ml = -1;
564         } else {
565           $ml = 1;
566         }
567         $form->{balance}  = $form->{balance} + $value * $ml;
568         push @{ $rows{$key} }, $form->format_amount(\%myconfig, $value, 2);
569       }
570     }
571
572     foreach my $key (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno ac_transdate source)) {
573       my $col = $key eq 'ac_transdate' ? 'transdate' : $key;
574       $rows{$col} = [ map { $ref->{$key}->{$_} } sort keys(%{ $ref->{$key} }) ];
575     }
576
577     my $row = { };
578     map { $row->{$_} = { 'data' => '', 'align' => $column_alignment{$_} } } @columns;
579
580     my $sh = "";
581     if ($form->{balance} < 0) {
582       $sh = " S";
583       $ml = -1;
584     } elsif ($form->{balance} > 0) {
585       $sh = " H";
586       $ml = 1;
587     }
588     my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
589     $data .= $sh;
590
591     $row->{balance}->{data}        = $data;
592     $row->{projectnumbers}->{data} = join ", ", sort { lc($a) cmp lc($b) } keys %{ $ref->{projectnumbers} };
593
594     map { $row->{$_}->{data} = $ref->{$_} } qw(id reference description notes);
595
596     map { $row->{$_}->{data} = \@{ $rows{$_} }; } qw(transdate debit credit debit_accno credit_accno debit_tax_accno credit_tax_accno source);
597
598     foreach my $col (qw(debit_accno credit_accno debit_tax_accno credit_tax_accno)) {
599       $row->{$col}->{link} = [ map { "${callback}&accno=" . E($_) } @{ $rows{$col} } ];
600     }
601
602     map { $row->{$_}->{data} = \@{ $rows{$_} } if ($ref->{"${_}_accno"} ne "") } qw(debit_tax credit_tax);
603
604     $row->{reference}->{link} = build_std_url("script=$ref->{module}.pl", 'action=edit', 'id=' . E($ref->{id}), 'callback');
605
606     my $row_set = [ $row ];
607
608     if (($form->{l_subtotal} eq 'Y')
609         && (($idx == (scalar @{ $form->{GL} } - 1))
610             || ($ref->{ $form->{sort} } ne $form->{GL}->[$idx + 1]->{ $form->{sort} }))) {
611       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, [ qw(debit credit) ], 'listsubtotal');
612     }
613
614     $report->add_data($row_set);
615
616     $idx++;
617   }
618
619   $report->add_separator();
620
621   # = 0 for balanced ledger
622   my $balanced_ledger = $totals{debit} + $totals{debit_tax} - $totals{credit} - $totals{credit_tax};
623
624   my $row = create_subtotal_row(\%totals, \@columns, \%column_alignment, [ qw(debit credit debit_tax credit_tax) ], 'listtotal');
625
626   my $sh = "";
627   if ($form->{balance} < 0) {
628     $sh = " S";
629     $ml = -1;
630   } elsif ($form->{balance} > 0) {
631     $sh = " H";
632     $ml = 1;
633   }
634   my $data = $form->format_amount(\%myconfig, ($form->{balance} * $ml), 2);
635   $data .= $sh;
636
637   $row->{balance}->{data}        = $data;
638
639   $report->add_data($row);
640
641   my $raw_bottom_info_text;
642
643   if (!$form->{accno} && (abs($balanced_ledger) >  0.001)) {
644     $raw_bottom_info_text .=
645         '<p><span class="unbalanced_ledger">'
646       . $locale->text('Unbalanced Ledger')
647       . ': '
648       . $form->format_amount(\%myconfig, $balanced_ledger, 3)
649       . '</span></p> ';
650   }
651
652   $raw_bottom_info_text .= $form->parse_html_template('gl/generate_report_bottom');
653
654   $report->set_options('raw_bottom_info_text' => $raw_bottom_info_text);
655
656   $report->generate_with_headers();
657
658   $main::lxdebug->leave_sub();
659 }
660
661 sub update {
662   $main::lxdebug->enter_sub();
663
664   $main::auth->assert('general_ledger');
665
666   my $form     = $main::form;
667   my %myconfig = %main::myconfig;
668
669   $form->{oldtransdate} = $form->{transdate};
670
671   my @a           = ();
672   my $count       = 0;
673   my $debittax    = 0;
674   my $credittax   = 0;
675   my $debitcount  = 0;
676   my $creditcount = 0;
677   my ($debitcredit, $amount);
678
679   my @flds =
680     qw(accno debit credit projectnumber fx_transaction source memo tax taxchart);
681
682   for my $i (1 .. $form->{rowcount}) {
683
684     unless (($form->{"debit_$i"} eq "") && ($form->{"credit_$i"} eq "")) {
685       for (qw(debit credit tax)) {
686         $form->{"${_}_$i"} =
687           $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
688       }
689
690       push @a, {};
691       $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
692       if ($debitcredit) {
693         $debitcount++;
694       } else {
695         $creditcount++;
696       }
697
698       if (($debitcount >= 2) && ($creditcount == 2)) {
699         $form->{"credit_$i"} = 0;
700         $form->{"tax_$i"}    = 0;
701         $creditcount--;
702         $form->{creditlock} = 1;
703       }
704       if (($creditcount >= 2) && ($debitcount == 2)) {
705         $form->{"debit_$i"} = 0;
706         $form->{"tax_$i"}   = 0;
707         $debitcount--;
708         $form->{debitlock} = 1;
709       }
710       if (($creditcount == 1) && ($debitcount == 2)) {
711         $form->{creditlock} = 1;
712       }
713       if (($creditcount == 2) && ($debitcount == 1)) {
714         $form->{debitlock} = 1;
715       }
716       if ($debitcredit && $credittax) {
717         $form->{"taxchart_$i"} = "0--0.00";
718       }
719       if (!$debitcredit && $debittax) {
720         $form->{"taxchart_$i"} = "0--0.00";
721       }
722       $amount =
723         ($form->{"debit_$i"} == 0)
724         ? $form->{"credit_$i"}
725         : $form->{"debit_$i"};
726       my $j = $#a;
727       if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
728         $form->{"taxchart_$i"} = "0--0.00";
729         $form->{"tax_$i"}      = 0;
730       }
731       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
732       if ($taxkey > 1) {
733         if ($debitcredit) {
734           $debittax = 1;
735         } else {
736           $credittax = 1;
737         }
738         if ($form->{taxincluded}) {
739           $form->{"tax_$i"} = $amount / ($rate + 1) * $rate;
740         } else {
741           $form->{"tax_$i"} = $amount * $rate;
742         }
743       } else {
744         $form->{"tax_$i"} = 0;
745       }
746
747       for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
748       $count++;
749     }
750   }
751
752   for my $i (1 .. $count) {
753     my $j = $i - 1;
754     for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
755   }
756
757   for my $i ($count + 1 .. $form->{rowcount}) {
758     for (@flds) { delete $form->{"${_}_$i"} }
759   }
760
761   $form->{rowcount} = $count + 1;
762
763   &display_form;
764   $main::lxdebug->leave_sub();
765
766 }
767
768 sub display_form {
769   my ($init) = @_;
770   $main::lxdebug->enter_sub();
771
772   $main::auth->assert('general_ledger');
773
774   my $form     = $main::form;
775   my %myconfig = %main::myconfig;
776
777   &form_header($init);
778
779   #   for $i (1 .. $form->{rowcount}) {
780   #     $form->{totaldebit} += $form->parse_amount(\%myconfig, $form->{"debit_$i"});
781   #     $form->{totalcredit} += $form->parse_amount(\%myconfig, $form->{"credit_$i"});
782   #
783   #     &form_row($i);
784   #   }
785   &display_rows($init);
786   &form_footer;
787   $main::lxdebug->leave_sub();
788
789 }
790
791 sub display_rows {
792   my ($init) = @_;
793   $main::lxdebug->enter_sub();
794
795   $main::auth->assert('general_ledger');
796
797   my $form     = $main::form;
798   my %myconfig = %main::myconfig;
799   my $cgi      = $main::cgi;
800
801   $form->{debit_1}     = 0 if !$form->{"debit_1"};
802   $form->{totaldebit}  = 0;
803   $form->{totalcredit} = 0;
804
805   my %project_labels = ();
806   my @project_values = ("");
807   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
808     push(@project_values, $item->{"id"});
809     $project_labels{$item->{"id"}} = $item->{"projectnumber"};
810   }
811
812   my %chart_labels = ();
813   my @chart_values = ();
814   my %charts = ();
815   my $taxchart_init;
816   foreach my $item (@{ $form->{ALL_CHARTS} }) {
817     if ($item->{charttype} eq 'H'){ #falls Ã¼berschrift
818       next;                         #überspringen (Bug 1150)
819     }
820     my $key = $item->{accno} . "--" . $item->{tax_id};
821     $taxchart_init = $item->{tax_id} unless (@chart_values);
822     push(@chart_values, $key);
823     $chart_labels{$key} = $item->{accno} . "--" . $item->{description};
824     $charts{$item->{accno}} = $item;
825   }
826
827   my %taxchart_labels = ();
828   my @taxchart_values = ();
829   my %taxcharts = ();
830   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
831     my $key = $item->{id} . "--" . $item->{rate};
832     $taxchart_init = $key if ($taxchart_init == $item->{id});
833     push(@taxchart_values, $key);
834     $taxchart_labels{$key} = $item->{taxdescription} . " " . $item->{rate} * 100 . ' %';
835     $taxcharts{$item->{id}} = $item;
836   }
837
838   my ($source, $memo, $source_hidden, $memo_hidden);
839   for my $i (1 .. $form->{rowcount}) {
840     if ($form->{show_details}) {
841       $source = qq|
842       <td><input name="source_$i" value="$form->{"source_$i"}" size="16"></td>|;
843       $memo = qq|
844       <td><input name="memo_$i" value="$form->{"memo_$i"}" size="16"></td>|;
845     } else {
846       $source_hidden = qq|
847       <input type="hidden" name="source_$i" value="$form->{"source_$i"}" size="16">|;
848       $memo_hidden = qq|
849       <input type="hidden" name="memo_$i" value="$form->{"memo_$i"}" size="16">|;
850     }
851
852     my $selected_accno_full;
853     my ($accno_row) = split(/--/, $form->{"accno_$i"});
854     my $item = $charts{$accno_row};
855     $selected_accno_full = "$item->{accno}--$item->{tax_id}";
856
857     my $selected_taxchart = $form->{"taxchart_$i"};
858     my ($selected_accno, $selected_tax_id) = split(/--/, $selected_accno_full);
859     my ($previous_accno, $previous_tax_id) = split(/--/, $form->{"previous_accno_$i"});
860
861     if ($previous_accno &&
862         ($previous_accno eq $selected_accno) &&
863         ($previous_tax_id ne $selected_tax_id)) {
864       my $item = $taxcharts{$selected_tax_id};
865       $selected_taxchart = "$item->{id}--$item->{rate}";
866     }
867
868     $selected_accno      = '' if ($init);
869     $selected_taxchart ||= $taxchart_init;
870
871     my $accno = qq|<td>| .
872       NTI($cgi->popup_menu('-name' => "accno_$i",
873                            '-id' => "accno_$i",
874                            '-onChange' => "setTaxkey($i)",
875                            '-style' => 'width:200px',
876                            '-values' => \@chart_values,
877                            '-labels' => \%chart_labels,
878                            '-default' => $selected_accno_full))
879       . $cgi->hidden('-name' => "previous_accno_$i",
880                      '-default' => $selected_accno_full)
881       . qq|</td>|;
882     my $tax_ddbox = qq|<td>| .
883       NTI($cgi->popup_menu('-name' => "taxchart_$i",
884                            '-id' => "taxchart_$i",
885                            '-style' => 'width:200px',
886                            '-values' => \@taxchart_values,
887                            '-labels' => \%taxchart_labels,
888                            '-default' => $selected_taxchart))
889       . qq|</td>|;
890
891     my ($fx_transaction, $checked);
892     if ($init) {
893       if ($form->{transfer}) {
894         $fx_transaction = qq|
895         <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
896     |;
897       }
898
899     } else {
900       if ($form->{"debit_$i"} != 0) {
901         $form->{totaldebit} += $form->{"debit_$i"};
902         if (!$form->{taxincluded}) {
903           $form->{totaldebit} += $form->{"tax_$i"};
904         }
905       } else {
906         $form->{totalcredit} += $form->{"credit_$i"};
907         if (!$form->{taxincluded}) {
908           $form->{totalcredit} += $form->{"tax_$i"};
909         }
910       }
911
912       for (qw(debit credit tax)) {
913         $form->{"${_}_$i"} =
914           ($form->{"${_}_$i"})
915           ? $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
916           : "";
917       }
918
919       if ($i < $form->{rowcount}) {
920         if ($form->{transfer}) {
921           $checked = ($form->{"fx_transaction_$i"}) ? "1" : "";
922           my $x = ($checked) ? "x" : "";
923           $fx_transaction = qq|
924       <td><input type=hidden name="fx_transaction_$i" value="$checked">$x</td>
925     |;
926         }
927         $form->hide_form("accno_$i");
928
929       } else {
930         if ($form->{transfer}) {
931           $fx_transaction = qq|
932       <td><input name="fx_transaction_$i" class=checkbox type=checkbox value=1></td>
933     |;
934         }
935       }
936     }
937     my $debitreadonly  = "";
938     my $creditreadonly = "";
939     if ($i == $form->{rowcount}) {
940       if ($form->{debitlock}) {
941         $debitreadonly = "readonly";
942       } elsif ($form->{creditlock}) {
943         $creditreadonly = "readonly";
944       }
945     }
946
947     my $projectnumber =
948       NTI($cgi->popup_menu('-name' => "project_id_$i",
949                            '-values' => \@project_values,
950                            '-labels' => \%project_labels,
951                            '-default' => $form->{"project_id_$i"} ));
952     my $projectnumber_hidden = qq|
953     <input type="hidden" name="project_id_$i" value="$form->{"project_id_$i"}">|;
954
955     my $copy2credit = 'onkeyup="copy_debit_to_credit()"' if $i == 1;
956
957     print qq|<tr valign=top>
958     $accno
959     <td id="chart_balance_$i" align="right">&nbsp;</td>
960     $fx_transaction
961     <td><input name="debit_$i" size="8" value="$form->{"debit_$i"}" accesskey=$i $copy2credit $debitreadonly></td>
962     <td><input name="credit_$i" size=8 value="$form->{"credit_$i"}" $creditreadonly></td>
963     <td><input type="hidden" name="tax_$i" value="$form->{"tax_$i"}">$form->{"tax_$i"}</td>
964     $tax_ddbox|;
965
966     if ($form->{show_details}) {
967       print qq|
968     $source
969     $memo
970     <td>$projectnumber</td>
971 |;
972     } else {
973     print qq|
974     $source_hidden
975     $memo_hidden
976     $projectnumber_hidden
977     |;
978     }
979     print qq|
980   </tr>
981 |;
982   }
983
984   $form->hide_form(qw(rowcount selectaccno));
985
986   $main::lxdebug->leave_sub();
987
988 }
989
990 sub form_header {
991   my ($init) = @_;
992   $main::lxdebug->enter_sub();
993
994   $main::auth->assert('general_ledger');
995
996   my $form     = $main::form;
997   my %myconfig = %main::myconfig;
998   my $locale   = $main::locale;
999
1000   my @old_project_ids = ();
1001   map({ push(@old_project_ids, $form->{"project_id_$_"})
1002           if ($form->{"project_id_$_"}); } (1..$form->{"rowcount"}));
1003
1004   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
1005                                     "all"       => 0,
1006                                     "old_id"    => \@old_project_ids },
1007                    "charts"    => { "key"       => "ALL_CHARTS",
1008                                     "transdate" => $form->{transdate} },
1009                    "taxcharts" => "ALL_TAXCHARTS");
1010
1011   GL->get_chart_balances('charts' => $form->{ALL_CHARTS});
1012
1013   my $title      = $form->{title};
1014   $form->{title} = $locale->text("$title General Ledger Transaction");
1015   my $readonly   = ($form->{id}) ? "readonly" : "";
1016
1017   my $show_details_checked = "checked" if $form->{show_details};
1018
1019   my $ob_transaction_checked = "checked" if $form->{ob_transaction};
1020   my $cb_transaction_checked = "checked" if $form->{cb_transaction};
1021
1022   # $locale->text('Add General Ledger Transaction')
1023   # $locale->text('Edit General Ledger Transaction')
1024
1025   map { $form->{$_} =~ s/\"/&quot;/g }
1026     qw(reference description chart taxchart);
1027
1028   $form->{javascript} = qq|<script type="text/javascript">
1029   <!--
1030   function setTaxkey(row) {
1031     var accno  = document.getElementById('accno_' + row);
1032     var taxkey = accno.options[accno.selectedIndex].value;
1033     var reg = /--([0-9]*)/;
1034     var found = reg.exec(taxkey);
1035     var index = found[1];
1036     index = parseInt(index);
1037     var tax = 'taxchart_' + row;
1038     for (var i = 0; i < document.getElementById(tax).options.length; ++i) {
1039       var reg2 = new RegExp("^"+ index, "");
1040       if (reg2.exec(document.getElementById(tax).options[i].value)) {
1041         document.getElementById(tax).options[i].selected = true;
1042         break;
1043       }
1044     }
1045   };
1046
1047   function copy_debit_to_credit() {
1048     var txt = document.getElementsByName('debit_1')[0].value;
1049     document.getElementsByName('credit_2')[0].value = txt;
1050   };
1051   //-->
1052   </script>
1053   <script type="text/javascript" src="js/show_form_details.js"></script>
1054   <script type="text/javascript" src="js/jquery.js"></script>
1055 |;
1056
1057   $form->{selectdepartment} =~ s/ selected//;
1058   $form->{selectdepartment} =~
1059     s/option>\Q$form->{department}\E/option selected>$form->{department}/;
1060
1061   my $description;
1062   if ((my $rows = $form->numtextrows($form->{description}, 50)) > 1) {
1063     $description =
1064       qq|<textarea name=description rows=$rows cols=50 wrap=soft $readonly >$form->{description}</textarea>|;
1065   } else {
1066     $description =
1067       qq|<input name=description size=50 value="$form->{description}" $readonly>|;
1068   }
1069
1070   my $taxincluded = ($form->{taxincluded}) ? "checked" : "";
1071
1072   if ($init) {
1073     $taxincluded = "checked";
1074   }
1075
1076   my $department;
1077   $department = qq|
1078         <tr>
1079           <th align=right nowrap>| . $locale->text('Department') . qq|</th>
1080           <td colspan=3><select name=department>$form->{selectdepartment}</select></td>
1081           <input type=hidden name=selectdepartment value="$form->{selectdepartment}">
1082         </tr>
1083 | if $form->{selectdepartment};
1084   if ($init) {
1085     $form->{fokus} = "gl.reference";
1086   } else {
1087     $form->{fokus} = qq|gl.accno_$form->{rowcount}|;
1088   }
1089
1090   # use JavaScript Calendar or not
1091   $form->{jsscript} = 1;
1092   my $jsscript = "";
1093   my ($button1, $button2);
1094   if ($form->{jsscript}) {
1095
1096     # with JavaScript Calendar
1097     $button1 = qq|
1098        <td><input name=transdate id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" $readonly onBlur=\"check_right_date_format(this)\">
1099        <input type=button name=transdate id="trigger1" value=|
1100       . $locale->text('button') . qq|></td>
1101        |;
1102
1103     #write Trigger
1104     $jsscript =
1105       Form->write_trigger(\%myconfig, "1", "transdate", "BL", "trigger1");
1106   } else {
1107
1108     # without JavaScript Calendar
1109     $button1 =
1110       qq|<td><input name=transdate id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" $readonly onBlur=\"check_right_date_format(this)\"></td>|;
1111   }
1112
1113   $form->{previous_id}     ||= "--";
1114   $form->{previous_gldate} ||= "--";
1115
1116   $jsscript .= $form->parse_html_template('gl/form_header_chart_balances_js');
1117
1118   $form->header;
1119
1120   print qq|
1121 <body onLoad="focus()">
1122
1123 <script type="text/javascript" src="js/follow_up.js"></script>
1124
1125 <form method=post name="gl" action=gl.pl>
1126 |;
1127
1128   $form->hide_form(qw(id closedto locked storno storno_id previous_id previous_gldate));
1129
1130   print qq|
1131 <input type=hidden name=title value="$title">
1132
1133 <input type="hidden" name="follow_up_trans_id_1" value="| . H($form->{id}) . qq|">
1134 <input type="hidden" name="follow_up_trans_type_1" value="gl_transaction">
1135 <input type="hidden" name="follow_up_trans_info_1" value="| . H($form->{id}) . qq|">
1136 <input type="hidden" name="follow_up_rowcount" value="1">
1137
1138 <table width=100%>
1139   <tr>
1140     <th class=listtop>$form->{title}</th>
1141   </tr>| .
1142
1143   ($form->{saved_message} ? qq|
1144   <tr>
1145     <td>$form->{saved_message}</th>
1146   </tr>| : '') .
1147
1148 qq|
1149   <tr height="5"></tr>
1150   <tr>
1151     <td>
1152       <table width=100%>
1153         <tr>
1154           <td colspan="6" align="left">|
1155     . $locale->text("Previous transnumber text")
1156     . " $form->{previous_id} "
1157     . $locale->text("Previous transdate text")
1158     . " $form->{previous_gldate}"
1159     . qq|</td>
1160         </tr>
1161         <tr>
1162           <th align=right>| . $locale->text('Reference') . qq|</th>
1163           <td><input name=reference size=20 value="$form->{reference}" $readonly></td>
1164           <td align=left>
1165             <table>
1166               <tr>
1167                 <th align=right nowrap>| . $locale->text('Date') . qq|</th>
1168                 $button1
1169               </tr>
1170             </table>
1171           </td>
1172         </tr>|;
1173   if ($form->{id}) {
1174     print qq|
1175         <tr>
1176           <th align=right>| . $locale->text('Belegnummer') . qq|</th>
1177           <td><input name=id size=20 value="$form->{id}" $readonly></td>
1178           <td align=left>
1179           <table>
1180               <tr>
1181                 <th align=right width=50%>| . $locale->text('Buchungsdatum') . qq|</th>
1182                 <td align=left><input name=gldate size=11 title="$myconfig{dateformat}" value=$form->{gldate} $readonly onBlur=\"check_right_date_format(this)\"></td>
1183               </tr>
1184             </table>
1185           </td>
1186         </tr>|;
1187   }
1188   print qq|
1189         $department|;
1190   if ($form->{id}) {
1191     print qq|
1192         <tr>
1193           <th align=right width=1%>| . $locale->text('Description') . qq|</th>
1194           <td width=1%>$description</td>
1195           <td>
1196             <table>
1197               <tr>
1198                 <th align=left>| . $locale->text('MwSt. inkl.') . qq|</th>
1199                 <td><input type=checkbox name=taxincluded value=1 $taxincluded></td>
1200               </tr>
1201             </table>
1202          </td>
1203           <td align=left>
1204             <table width=100%>
1205               <tr>
1206                 <th align=right width=50%>| . $locale->text('Mitarbeiter') . qq|</th>
1207                 <td align=left><input name=employee size=20  value="| . H($form->{employee}) . qq|" readonly></td>
1208               </tr>
1209             </table>
1210           </td>
1211         </tr>|;
1212   } else {
1213     print qq|
1214         <tr>
1215           <th align=left width=1%>| . $locale->text('Description') . qq|</th>
1216           <td width=1%>$description</td>
1217           <td>
1218             <table>
1219               <tr>
1220                 <th align=left>| . $locale->text('MwSt. inkl.') . qq|</th>
1221                 <td><input type=checkbox name=taxincluded value=1 $taxincluded></td>
1222               </tr>
1223             </table>
1224          </td>
1225         </tr>|;
1226   }
1227
1228   print qq|
1229       <tr>
1230       <tr><td colspan=4><table><tr>
1231        <td>
1232         | . $locale->text('OB Transaction') . qq|<input type="checkbox" name="ob_transaction" value="1" $ob_transaction_checked>
1233        </td>
1234        <td>
1235         | . $locale->text('CB Transaction') . qq|<input type="checkbox" name="cb_transaction" value="1" $cb_transaction_checked>
1236        </td>
1237       </tr></table></td></tr>
1238       <tr>
1239        <td width="1%" align="right" nowrap>| . $locale->text('Show details') . qq|</td>
1240        <td width="1%"><input type="checkbox" onclick="show_form_details();" name="show_details" value="1" $show_details_checked></td>
1241       </tr>|;
1242
1243   print qq|
1244       <tr>
1245       <td colspan=4>
1246           <table width=100%>
1247            <tr class=listheading>
1248           <th class=listheading style="width:15%">|
1249     . $locale->text('Account') . qq|</th>
1250           <th class=listheading style="width:10%">| . $locale->text('Chart balance') . qq|</th>
1251           <th class=listheading style="width:10%">|
1252     . $locale->text('Debit') . qq|</th>
1253           <th class=listheading style="width:10%">|
1254     . $locale->text('Credit') . qq|</th>
1255           <th class=listheading style="width:10%">|
1256     . $locale->text('Tax') . qq|</th>
1257           <th class=listheading style="width:5%">|
1258     . $locale->text('Taxkey') . qq|</th>|;
1259
1260   if ($form->{show_details}) {
1261     print qq|
1262           <th class=listheading style="width:20%">| . $locale->text('Source') . qq|</th>
1263           <th class=listheading style="width:20%">| . $locale->text('Memo') . qq|</th>
1264           <th class=listheading style="width:20%">| . $locale->text('Project Number') . qq|</th>
1265 |;
1266   }
1267
1268   print qq|
1269         </tr>
1270
1271 $jsscript
1272 |;
1273   $main::lxdebug->leave_sub();
1274
1275 }
1276
1277 sub form_footer {
1278   $main::lxdebug->enter_sub();
1279
1280   $main::auth->assert('general_ledger');
1281
1282   my $form     = $main::form;
1283   my %myconfig = %main::myconfig;
1284   my $locale   = $main::locale;
1285   my $cgi      = $main::cgi;
1286
1287   my $follow_ups_block;
1288   if ($form->{id}) {
1289     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
1290
1291     if (@{ $follow_ups} ) {
1292       my $num_due       = sum map { $_->{due} * 1 } @{ $follow_ups };
1293       $follow_ups_block = qq|<p>| . $locale->text("There are #1 unfinished follow-ups of which #2 are due.", scalar @{ $follow_ups }, $num_due) . qq|</p>|;
1294     }
1295   }
1296
1297   my ($dec) = ($form->{totaldebit} =~ /\.(\d+)/);
1298   $dec = length $dec;
1299   my $decimalplaces = ($dec > 2) ? $dec : 2;
1300   my $radieren = ($form->current_date(\%myconfig) eq $form->{gldate}) ? 1 : 0;
1301
1302   map {
1303     $form->{$_} = $form->format_amount(\%myconfig, $form->{$_}, 2, "&nbsp;")
1304   } qw(totaldebit totalcredit);
1305
1306   print qq|
1307     <tr class=listtotal>
1308     <th colspan="3" align=right class=listtotal> $form->{totaldebit}</th>
1309     <th align=right class=listtotal> $form->{totalcredit}</th>
1310     <td colspan=6></td>
1311     </tr>
1312   </table>
1313   </td>
1314   </tr>
1315 </table>
1316
1317 <input name=callback type=hidden value="$form->{callback}">
1318
1319 $follow_ups_block
1320
1321 <br>
1322 |;
1323
1324   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
1325   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
1326
1327   if ($form->{id}) {
1328
1329     if (!$form->{storno}) {
1330       print qq|<input class=submit type=submit name=action value="| . $locale->text('Storno') . qq|">|;
1331     }
1332
1333     # Löschen und Ã„ndern von Buchungen nicht mehr möglich (GoB) nur am selben Tag möglich
1334     if (!$form->{locked} && $radieren) {
1335       print qq|
1336         <input class=submit type=submit name=action value="| . $locale->text('Post') . qq|" accesskey="b">
1337         <input class=submit type=submit name=action value="| . $locale->text('Delete') . qq|">|;
1338     }
1339
1340     print qq|
1341         <input class=submit type=submit name=action id=update_button value="| . $locale->text('Update') . qq|">
1342         <input type="button" class="submit" onclick="follow_up_window()" value="|
1343       . $locale->text('Follow-Up')
1344       . qq|"> |;
1345
1346   } else {
1347     if ($form->{draft_id}) {
1348       my $remove_draft_checked = 'checked' if ($form->{remove_draft});
1349       print qq|<p>\n|
1350         . qq|  <input name="remove_draft" id="remove_draft" type="checkbox" class="checkbox" ${remove_draft_checked}>|
1351         . qq|  <label for="remove_draft">| . $locale->text('Remove Draft') . qq|</label>\n|
1352         . qq|</p>\n|;
1353     }
1354
1355     print qq|
1356         <input class=submit type=submit name=action id=update_button value="| . $locale->text('Update') . qq|">
1357         <input class=submit type=submit name=action value="| . $locale->text('Post') . qq|"> |
1358         . NTI($cgi->submit('-name' => 'action', '-value' => $locale->text('Save draft'), '-class' => 'submit'))
1359         . $cgi->hidden('-name' => 'draft_id',          '-default' => [$form->{draft_id}])
1360         . $cgi->hidden('-name' => 'draft_description', '-default' => [$form->{draft_description}]);
1361   }
1362
1363   print "
1364   </form>
1365
1366 </body>
1367 </html>
1368 ";
1369   $main::lxdebug->leave_sub();
1370
1371 }
1372
1373 sub delete {
1374   $main::lxdebug->enter_sub();
1375
1376   my $form     = $main::form;
1377   my $locale   = $main::locale;
1378
1379   $form->header;
1380
1381   print qq|
1382 <body>
1383
1384 <form method=post action=gl.pl>
1385 |;
1386
1387   map { $form->{$_} =~ s/\"/&quot;/g } qw(reference description);
1388
1389   delete $form->{header};
1390
1391   foreach my $key (keys %$form) {
1392     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1393     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
1394   }
1395
1396   print qq|
1397 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
1398
1399 <h4>|
1400     . $locale->text('Are you sure you want to delete Transaction')
1401     . qq| $form->{reference}</h4>
1402
1403 <input name=action class=submit type=submit value="|
1404     . $locale->text('Yes') . qq|">
1405 </form>
1406 |;
1407   $main::lxdebug->leave_sub();
1408
1409 }
1410
1411 sub yes {
1412   $main::lxdebug->enter_sub();
1413
1414   my $form     = $main::form;
1415   my %myconfig = %main::myconfig;
1416   my $locale   = $main::locale;
1417
1418   if (GL->delete_transaction(\%myconfig, \%$form)){
1419     # saving the history
1420       if(!exists $form->{addition} && $form->{id} ne "") {
1421         $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1422         $form->{addition} = "DELETED";
1423         $form->save_history;
1424       }
1425     # /saving the history
1426     $form->redirect($locale->text('Transaction deleted!'))
1427   }
1428   $form->error($locale->text('Cannot delete transaction!'));
1429   $main::lxdebug->leave_sub();
1430
1431 }
1432
1433 sub post_transaction {
1434   $main::lxdebug->enter_sub();
1435
1436   my $form     = $main::form;
1437   my %myconfig = %main::myconfig;
1438   my $locale   = $main::locale;
1439
1440   # check if there is something in reference and date
1441   $form->isblank("reference",   $locale->text('Reference missing!'));
1442   $form->isblank("transdate",   $locale->text('Transaction Date missing!'));
1443   $form->isblank("description", $locale->text('Description missing!'));
1444
1445   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
1446   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
1447
1448   my @a           = ();
1449   my $count       = 0;
1450   my $debittax    = 0;
1451   my $credittax   = 0;
1452   my $debitcount  = 0;
1453   my $creditcount = 0;
1454   my $debitcredit;
1455
1456   my @flds = qw(accno debit credit projectnumber fx_transaction source memo tax taxchart);
1457
1458   for my $i (1 .. $form->{rowcount}) {
1459     next if $form->{"debit_$i"} eq "" && $form->{"credit_$i"} eq "";
1460
1461     for (qw(debit credit tax)) {
1462       $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"});
1463     }
1464
1465     push @a, {};
1466     $debitcredit = ($form->{"debit_$i"} == 0) ? "0" : "1";
1467
1468     if ($debitcredit) {
1469       $debitcount++;
1470     } else {
1471       $creditcount++;
1472     }
1473
1474     if (($debitcount >= 2) && ($creditcount == 2)) {
1475       $form->{"credit_$i"} = 0;
1476       $form->{"tax_$i"}    = 0;
1477       $creditcount--;
1478       $form->{creditlock} = 1;
1479     }
1480     if (($creditcount >= 2) && ($debitcount == 2)) {
1481       $form->{"debit_$i"} = 0;
1482       $form->{"tax_$i"}   = 0;
1483       $debitcount--;
1484       $form->{debitlock} = 1;
1485     }
1486     if (($creditcount == 1) && ($debitcount == 2)) {
1487       $form->{creditlock} = 1;
1488     }
1489     if (($creditcount == 2) && ($debitcount == 1)) {
1490       $form->{debitlock} = 1;
1491     }
1492     if ($debitcredit && $credittax) {
1493       $form->{"taxchart_$i"} = "0--0.00";
1494     }
1495     if (!$debitcredit && $debittax) {
1496       $form->{"taxchart_$i"} = "0--0.00";
1497     }
1498     my $amount = ($form->{"debit_$i"} == 0)
1499             ? $form->{"credit_$i"}
1500             : $form->{"debit_$i"};
1501     my $j = $#a;
1502     if (($debitcredit && $credittax) || (!$debitcredit && $debittax)) {
1503       $form->{"taxchart_$i"} = "0--0.00";
1504       $form->{"tax_$i"}      = 0;
1505     }
1506     my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
1507     if ($taxkey > 1) {
1508       if ($debitcredit) {
1509         $debittax = 1;
1510       } else {
1511         $credittax = 1;
1512       }
1513       if ($form->{taxincluded}) {
1514         $form->{"tax_$i"} = $amount / ($rate + 1) * $rate;
1515         if ($debitcredit) {
1516           $form->{"debit_$i"} = $form->{"debit_$i"} - $form->{"tax_$i"};
1517         } else {
1518           $form->{"credit_$i"} = $form->{"credit_$i"} - $form->{"tax_$i"};
1519         }
1520       } else {
1521         $form->{"tax_$i"} = $amount * $rate;
1522       }
1523     } else {
1524       $form->{"tax_$i"} = 0;
1525     }
1526
1527     for (@flds) { $a[$j]->{$_} = $form->{"${_}_$i"} }
1528     $count++;
1529   }
1530
1531   for my $i (1 .. $count) {
1532     my $j = $i - 1;
1533     for (@flds) { $form->{"${_}_$i"} = $a[$j]->{$_} }
1534   }
1535
1536   for my $i ($count + 1 .. $form->{rowcount}) {
1537     for (@flds) { delete $form->{"${_}_$i"} }
1538   }
1539
1540   my ($debit, $credit, $taxtotal);
1541   for my $i (1 .. $form->{rowcount}) {
1542     my $dr  = $form->{"debit_$i"};
1543     my $cr  = $form->{"credit_$i"};
1544     my $tax = $form->{"tax_$i"};
1545     if ($dr && $cr) {
1546       $form->error($locale->text('Cannot post transaction with a debit and credit entry for the same account!'));
1547     }
1548     $debit    += $dr + $tax if $dr;
1549     $credit   += $cr + $tax if $cr;
1550     $taxtotal += $tax if $form->{taxincluded}
1551   }
1552
1553   $form->{taxincluded} = 0 if !$taxtotal;
1554
1555   # this is just for the wise guys
1556   $form->error($locale->text('Cannot post transaction for a closed period!'))
1557     if ($form->date_closed($form->{"transdate"}, \%myconfig));
1558   if ($form->round_amount($debit, 2) != $form->round_amount($credit, 2)) {
1559     $form->error($locale->text('Out of balance transaction!'));
1560   }
1561
1562   if ($form->round_amount($debit, 2) + $form->round_amount($credit, 2) == 0) {
1563     $form->error($locale->text('Empty transaction!'));
1564   }
1565
1566   if ((my $errno = GL->post_transaction(\%myconfig, \%$form)) <= -1) {
1567     $errno *= -1;
1568     my @err;
1569     $err[1] = $locale->text('Cannot have a value in both Debit and Credit!');
1570     $err[2] = $locale->text('Debit and credit out of balance!');
1571     $err[3] = $locale->text('Cannot post a transaction without a value!');
1572
1573     $form->error($err[$errno]);
1574   }
1575   undef($form->{callback});
1576   # saving the history
1577   if(!exists $form->{addition} && $form->{id} ne "") {
1578     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1579     $form->{addition} = "SAVED";
1580     $form->{what_done} = $locale->text("Buchungsnummer") . " = " . $form->{id};
1581     $form->save_history;
1582   }
1583   # /saving the history
1584
1585   $main::lxdebug->leave_sub();
1586 }
1587
1588 sub post {
1589   $main::lxdebug->enter_sub();
1590
1591   $main::auth->assert('general_ledger');
1592
1593   my $form     = $main::form;
1594   my $locale   = $main::locale;
1595
1596   if ($::myconfig{mandatory_departments} && !$form->{department}) {
1597     $form->{saved_message} = $::locale->text('You have to specify a department.');
1598     update();
1599     exit;
1600   }
1601
1602   $form->{title}  = $locale->text("$form->{title} General Ledger Transaction");
1603   $form->{storno} = 0;
1604
1605   post_transaction();
1606
1607   remove_draft() if $form->{remove_draft};
1608
1609   $form->{callback} = build_std_url("action=add", "show_details");
1610   $form->redirect($form->{callback});
1611
1612   $main::lxdebug->leave_sub();
1613 }
1614
1615 sub post_as_new {
1616   $main::lxdebug->enter_sub();
1617
1618   $main::auth->assert('general_ledger');
1619
1620   my $form     = $main::form;
1621
1622   $form->{id} = 0;
1623   &add;
1624   $main::lxdebug->leave_sub();
1625
1626 }
1627
1628 sub storno {
1629   $main::lxdebug->enter_sub();
1630
1631   $main::auth->assert('general_ledger');
1632
1633   my $form     = $main::form;
1634   my %myconfig = %main::myconfig;
1635   my $locale   = $main::locale;
1636
1637   # don't cancel cancelled transactions
1638   if (IS->has_storno(\%myconfig, $form, 'gl')) {
1639     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1640     $form->error($locale->text("Transaction has already been cancelled!"));
1641   }
1642
1643   GL->storno($form, \%myconfig, $form->{id});
1644
1645   # saving the history
1646   if(!exists $form->{addition} && $form->{id} ne "") {
1647     $form->{snumbers} = "ordnumber_$form->{ordnumber}";
1648     $form->{addition} = "STORNO";
1649     $form->save_history;
1650   }
1651   # /saving the history
1652
1653   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1654
1655   $main::lxdebug->leave_sub();
1656 }
1657
1658 sub continue {
1659   call_sub($main::form->{nextsub});
1660 }
1661
1662 1;