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