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