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