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