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