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