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