Wechselkurse.
[kivitendo-erp.git] / bin / mozilla / ar.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) 2001
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 # Accounts Receivables
31 #
32 #======================================================================
33
34 use POSIX qw(strftime);
35 use List::Util qw(sum);
36
37 use SL::AR;
38 use SL::FU;
39 use SL::IS;
40 use SL::PE;
41 use SL::ReportGenerator;
42
43 # use strict;
44 #use warnings;
45
46 # imports
47 our ($cgi, $form, $lxdebug, $locale, %myconfig);
48
49 require "bin/mozilla/arap.pl";
50 require "bin/mozilla/common.pl";
51 require "bin/mozilla/drafts.pl";
52 require "bin/mozilla/reportgenerator.pl";
53
54 1;
55
56 # end of main
57
58 # this is for our long dates
59 # $locale->text('January')
60 # $locale->text('February')
61 # $locale->text('March')
62 # $locale->text('April')
63 # $locale->text('May ')
64 # $locale->text('June')
65 # $locale->text('July')
66 # $locale->text('August')
67 # $locale->text('September')
68 # $locale->text('October')
69 # $locale->text('November')
70 # $locale->text('December')
71
72 # this is for our short month
73 # $locale->text('Jan')
74 # $locale->text('Feb')
75 # $locale->text('Mar')
76 # $locale->text('Apr')
77 # $locale->text('May')
78 # $locale->text('Jun')
79 # $locale->text('Jul')
80 # $locale->text('Aug')
81 # $locale->text('Sep')
82 # $locale->text('Oct')
83 # $locale->text('Nov')
84 # $locale->text('Dec')
85
86 sub add {
87   $lxdebug->enter_sub();
88
89   $auth->assert('general_ledger');
90
91   return $lxdebug->leave_sub() if (load_draft_maybe());
92
93   # saving the history
94   if(!exists $form->{addition} && ($form->{id} ne "")) {
95     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
96         $form->{addition} = "ADDED";
97         $form->save_history($form->dbconnect(\%myconfig));
98   }
99   # /saving the history 
100   
101   $form->{title}    = "Add";
102   $form->{callback} = "ar.pl?action=add" unless $form->{callback};
103
104   AR->get_transdate(\%myconfig, $form);
105   $form->{initial_transdate} = $form->{transdate};
106   &create_links;
107   $form->{transdate} = $form->{initial_transdate};
108   &display_form;
109   $lxdebug->leave_sub();
110 }
111
112 sub edit {
113   $lxdebug->enter_sub();
114
115   $auth->assert('general_ledger');
116
117   # show history button
118   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
119   #/show hhistory button
120   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
121   $form->{title} = "Edit";
122
123   &create_links;
124   &display_form;
125
126   $lxdebug->leave_sub();
127 }
128
129 sub display_form {
130   $lxdebug->enter_sub();
131
132   $auth->assert('general_ledger');
133
134   &form_header;
135   &form_footer;
136
137   $lxdebug->leave_sub();
138 }
139
140 sub create_links {
141   $lxdebug->enter_sub();
142
143   $auth->assert('general_ledger');
144
145   my ($duedate, $taxincluded, @curr);
146
147   $form->create_links("AR", \%myconfig, "customer");
148   $duedate = $form->{duedate};
149
150   $taxincluded = $form->{taxincluded};
151   my $id = $form->{id};
152   IS->get_customer(\%myconfig, \%$form);
153   $form->{taxincluded} = $taxincluded;
154   $form->{id} = $id;
155
156   $form->{duedate}     = $duedate if $duedate;
157   $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
158   $form->{rowcount}    = 1;
159
160   # notes
161   $form->{notes} = $form->{intnotes} unless $form->{notes};
162
163   # currencies
164   @curr = split(/:/, $form->{currencies});
165   chomp $curr[0];
166   $form->{defaultcurrency} = $curr[0];
167
168   map { $form->{selectcurrency} .= "<option>$_\n" } @curr;
169
170   # customers
171   if (@{ $form->{all_customer} }) {
172     $form->{customer} = "$form->{customer}--$form->{customer_id}";
173     map { $form->{selectcustomer} .= "<option>$_->{name}--$_->{id}\n" }
174       (@{ $form->{all_customer} });
175   }
176
177   # departments
178   if (@{ $form->{all_departments} }) {
179     $form->{selectdepartment} = "<option>\n";
180     $form->{department}       = "$form->{department}--$form->{department_id}";
181
182     map {
183       $form->{selectdepartment} .=
184         "<option>$_->{description}--$_->{id}\n"
185     } (@{ $form->{all_departments} });
186   }
187
188   $form->{employee} = "$form->{employee}--$form->{employee_id}";
189
190   # sales staff
191   if (@{ $form->{all_employees} }) {
192     $form->{selectemployee} = "";
193     map { $form->{selectemployee} .= "<option>$_->{name}--$_->{id}\n" }
194       (@{ $form->{all_employees} });
195   }
196
197   # build the popup menus
198   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
199
200   AR->setup_form($form);
201
202   $form->{locked} =
203     ($form->datetonum($form->{transdate}, \%myconfig) <=
204      $form->datetonum($form->{closedto}, \%myconfig));
205
206   $lxdebug->leave_sub();
207 }
208
209 sub form_header {
210   $lxdebug->enter_sub();
211
212   $auth->assert('general_ledger');
213
214   my ($title, $readonly, $exchangerate, $rows);
215   my ($taxincluded, $notes, $department, $customer, $employee, $amount, $project);
216   my ($jsscript, $button1, $button2, $onload);
217   my ($selectAR_amount, $selectAR_paid, $korrektur_checked, $ARselected, $tax);
218   my (@column_index, %column_data);
219
220
221   $title = $form->{title};
222   $form->{title} = $locale->text("$title Accounts Receivables Transaction");
223
224   $form->{taxincluded} = ($form->{taxincluded}) ? "checked" : "";
225
226   # $locale->text('Add Accounts Receivables Transaction')
227   # $locale->text('Edit Accounts Receivables Transaction')
228   $form->{javascript} = qq|<script type="text/javascript">
229   <!--
230   function setTaxkey(accno, row) {
231     var taxkey = accno.options[accno.selectedIndex].value;
232     var reg = /--([0-9]*)/;
233     var found = reg.exec(taxkey);
234     var index = found[1];
235     index = parseInt(index);
236     var tax = 'taxchart_' + row;
237     for (var i = 0; i < document.getElementById(tax).options.length; ++i) {
238       var reg2 = new RegExp("^"+ index, "");
239       if (reg2.exec(document.getElementById(tax).options[i].value)) {
240         document.getElementById(tax).options[i].selected = true;
241         break;
242       }
243     }
244   };
245   //-->
246   </script>|;
247   # show history button js
248   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_history.js"></script>|;
249   #/show history button js
250   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
251   $readonly = ($form->{id}) ? "readonly" : "";
252
253   $form->{radier} =
254     ($form->current_date(\%myconfig) eq $form->{gldate}) ? 1 : 0;
255   $readonly = ($form->{radier}) ? "" : $readonly;
256
257   # set option selected
258   foreach my $item (qw(customer currency department employee)) {
259     $form->{"select$item"} =~ s/ selected//;
260     $form->{"select$item"} =~
261       s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
262   }
263
264   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
265   $form->{exchangerate} = $form->{forex} if $form->{forex};
266
267   # format amounts
268   $form->{exchangerate} =
269     $form->format_amount(\%myconfig, $form->{exchangerate});
270
271   if ($form->{exchangerate} == 0) {
272     $form->{exchangerate} = "";
273   }
274
275   $form->{creditlimit} =
276     $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
277   $form->{creditremaining} =
278     $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
279
280   $exchangerate = qq|
281 <input type=hidden name=forex value=$form->{forex}>
282 |;
283   if ($form->{currency} ne $form->{defaultcurrency}) {
284     if ($form->{forex}) {
285       $exchangerate .= qq|
286         <th align=right>| . $locale->text('Exchangerate') . qq|</th>
287         <td><input type=hidden name=exchangerate value=$form->{exchangerate}>$form->{exchangerate}</td>
288 |;
289     } else {
290       $exchangerate .= qq|
291         <th align=right>| . $locale->text('Exchangerate') . qq|</th>
292         <td><input name=exchangerate size=10 value=$form->{exchangerate}></td>
293 |;
294     }
295   }
296
297   $taxincluded = qq|
298               <tr>
299                 <td align=right><input name=taxincluded class=checkbox type=checkbox value=1 $form->{taxincluded}></td>
300                 <th align=left nowrap>| . $locale->text('Tax Included') . qq|</th>
301               </tr>
302 |;
303
304   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
305     $rows = 2;
306   }
307   $notes =
308     qq|<textarea name=notes rows=$rows cols=50 wrap=soft>$form->{notes}</textarea>|;
309
310   $department = qq|
311               <tr>
312                 <th align="right" nowrap>| . $locale->text('Department') . qq|</th>
313                 <td colspan=3><select name=department>$form->{selectdepartment}</select>
314                 <input type=hidden name=selectdepartment value="$form->{selectdepartment}">
315                 </td>
316               </tr>
317 | if $form->{selectdepartment};
318
319   my $n = ($form->{creditremaining} =~ /-/) ? "0" : "1";
320
321   $customer = ($form->{selectcustomer}) 
322     ? qq|<select name="customer" onchange="document.getElementById('update_button').click();">$form->{selectcustomer}</select>| 
323     : qq|<input name=customer value="$form->{customer}" size=35>|;
324
325   $employee = qq|
326                 <input type=hidden name=employee value="$form->{employee}">
327 |;
328
329   if ($form->{selectemployee}) {
330     $employee = qq|
331               <tr>
332                 <th align=right nowrap>| . $locale->text('Salesperson') . qq|</th>
333                 <td  colspan=2><select name=employee>$form->{selectemployee}</select></td>
334                 <input type=hidden name=selectemployee value="$form->{selectemployee}">
335               </tr>
336 |;
337   }
338
339   my @old_project_ids = ();
340   map({ push(@old_project_ids, $form->{"project_id_$_"})
341           if ($form->{"project_id_$_"}); } (1..$form->{"rowcount"}));
342
343   $form->get_lists("projects" => { "key" => "ALL_PROJECTS",
344                                    "all" => 0,
345                                    "old_id" => \@old_project_ids },
346                    "charts" => { "key" => "ALL_CHARTS",
347                                  "transdate" => $form->{transdate} },
348                    "taxcharts" => "ALL_TAXCHARTS");
349
350   map({ $_->{link_split} = [ split(/:/, $_->{link}) ]; }
351       @{ $form->{ALL_CHARTS} });
352
353   my %project_labels = ();
354   my @project_values = ("");
355   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
356     push(@project_values, $item->{"id"});
357     $project_labels{$item->{"id"}} = $item->{"projectnumber"};
358   }
359
360   my (%AR_amount_labels, @AR_amount_values);
361   my (%AR_labels, @AR_values);
362   my (%AR_paid_labels, @AR_paid_values);
363   my %charts;
364   my $taxchart_init;
365
366   foreach my $item (@{ $form->{ALL_CHARTS} }) {
367     if (grep({ $_ eq "AR_amount" } @{ $item->{link_split} })) {
368       $taxchart_init = $item->{tax_id} if ($taxchart_init eq "");
369       my $key = "$item->{accno}--$item->{tax_id}";
370       push(@AR_amount_values, $key);
371       $AR_amount_labels{$key} =
372         "$item->{accno}--$item->{description}";
373
374     } elsif (grep({ $_ eq "AR" } @{ $item->{link_split} })) {
375       push(@AR_values, $item->{accno});
376       $AR_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
377
378     } elsif (grep({ $_ eq "AR_paid" } @{ $item->{link_split} })) {
379       push(@AR_paid_values, $item->{accno});
380       $AR_paid_labels{$item->{accno}} =
381         "$item->{accno}--$item->{description}";
382     }
383
384     $charts{$item->{accno}} = $item;
385   }
386
387   my %taxchart_labels = ();
388   my @taxchart_values = ();
389   my %taxcharts = ();
390   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
391     my $key = "$item->{id}--$item->{rate}";
392     $taxchart_init = $key if ($taxchart_init eq $item->{id});
393     push(@taxchart_values, $key);
394     $taxchart_labels{$key} =
395       "$item->{taxdescription} " . ($item->{rate} * 100) . ' %';
396     $taxcharts{$item->{id}} = $item;
397   }
398
399   $form->{fokus} = "arledger.customer";
400
401   # use JavaScript Calendar or not
402   $form->{jsscript} = 1;
403   $jsscript = "";
404   if ($form->{jsscript}) {
405
406     # with JavaScript Calendar
407     $button1 = qq|
408        <td><input name=transdate id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\"></td>
409        <td><input type=button name=transdate id="trigger1" value=|
410       . $locale->text('button') . qq|></td>
411        |;
412     $button2 = qq|
413        <td><input name=duedate id=duedate size=11 title="$myconfig{dateformat}" value="$form->{duedate}" onBlur=\"check_right_date_format(this)\"></td>
414        <td><input type=button name=duedate id="trigger2" value=|
415       . $locale->text('button') . qq|></td></td>
416      |;
417
418     #write Trigger
419     $jsscript =
420       Form->write_trigger(\%myconfig, "2", "transdate", "BL", "trigger1",
421                           "duedate", "BL", "trigger2");
422   } else {
423
424     # without JavaScript Calendar
425     $button1 =
426       qq|<td><input name=transdate id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\"></td>|;
427     $button2 =
428       qq|<td><input name=duedate id=duedate size=11 title="$myconfig{dateformat}" value="$form->{duedate}" onBlur=\"check_right_date_format(this)\"></td>|;
429   }
430
431   my $follow_up_vc         =  $form->{customer};
432   $follow_up_vc            =~ s/--.*?//;
433   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
434
435   $form->{javascript} .=
436     qq|<script type="text/javascript" src="js/common.js"></script>| .
437     qq|<script type="text/javascript" src="js/show_vc_details.js"></script>| .
438     qq|<script type="text/javascript" src="js/follow_up.js"></script>|;
439
440   $form->header;
441   $onload = qq|focus()|;
442   $onload .= qq|;setupDateFormat('|. $myconfig{dateformat} .qq|', '|. $locale->text("Falsches Datumsformat!") .qq|')|;
443   $onload .= qq|;setupPoints('|. $myconfig{numberformat} .qq|', '|. $locale->text("wrongformat") .qq|')|;
444   print qq|
445 <body onLoad="$onload">
446
447 <form method=post name="arledger" action=$form->{script}>
448
449 <input type=hidden name=id value=$form->{id}>
450 <input type=hidden name=sort value=$form->{sort}>
451 <input type=hidden name=closedto value=$form->{closedto}>
452 <input type=hidden name=locked value=$form->{locked}>
453 <input type=hidden name=title value="$title">
454 <input type="hidden" name="follow_up_trans_id_1" value="| . H($form->{id}) . qq|">
455 <input type="hidden" name="follow_up_trans_type_1" value="ar_transaction">
456 <input type="hidden" name="follow_up_trans_info_1" value="| . H($follow_up_trans_info) . qq|">
457 <input type="hidden" name="follow_up_rowcount" value="1">
458
459 | . ($form->{saved_message} ? qq|<p>$form->{saved_message}</p>| : "") . qq|
460
461 <table width=100%>
462   <tr class=listtop>
463     <th class=listtop>$form->{title}</th>
464   </tr>
465   <tr height="5"></tr>
466   <tr valign=top>
467     <td>
468       <table width=100%>
469         <tr valign=top>
470           <td>
471             <table>
472               <tr>
473                 <th align="right" nowrap>| . $locale->text('Customer') . qq|</th>
474                 <td colspan=3>$customer <input type="button" value="?" onclick="show_vc_details('customer')"></td>
475                 <input type=hidden name=selectcustomer value="$form->{selectcustomer}">
476                 <input type=hidden name=oldcustomer value="$form->{oldcustomer}">
477                 <input type=hidden name=customer_id value="$form->{customer_id}">
478                 <input type=hidden name=terms value=$form->{terms}>
479               </tr>
480               <tr>
481                 <td></td>
482                 <td colspan=3>
483                   <table width=100%>
484                     <tr>
485                       <th align=left nowrap>| . $locale->text('Credit Limit') . qq|</th>
486                       <td>$form->{creditlimit}</td>
487                       <th align=left nowrap>| . $locale->text('Remaining') . qq|</th>
488                       <td class="plus$n">$form->{creditremaining}</td>
489                       <input type=hidden name=creditlimit value=$form->{creditlimit}>
490                       <input type=hidden name=creditremaining value=$form->{creditremaining}>
491                     </tr>
492                   </table>
493                 </td>
494               </tr>
495               <tr>
496                 <th align=right>| . $locale->text('Currency') . qq|</th>
497                 <td><select name=currency>$form->{selectcurrency}</select></td>
498                 <input type=hidden name=selectcurrency value="$form->{selectcurrency}">
499                 <input type=hidden name=defaultcurrency value=$form->{defaultcurrency}>
500                 <input type=hidden name=fxgain_accno value=$form->{fxgain_accno}>
501                 <input type=hidden name=fxloss_accno value=$form->{fxloss_accno}>
502                 $exchangerate
503               </tr>
504               $department
505               $taxincluded
506             </table>
507           </td>
508           <td align=right>
509             <table>
510               $employee
511               <tr>
512                 <th align=right nowrap>| . $locale->text('Invoice Number') . qq|</th>
513                 <td><input name=invnumber size=11 value="$form->{invnumber}"></td>
514               </tr>
515               <tr>
516                 <th align=right nowrap>| . $locale->text('Order Number') . qq|</th>
517                 <td><input name=ordnumber size=11 value="$form->{ordnumber}"></td>
518               </tr>
519               <tr>
520                 <th align=right nowrap>| . $locale->text('Invoice Date') . qq|</th>
521                 $button1
522               </tr>
523               <tr>
524                 <th align=right nowrap>| . $locale->text('Due Date') . qq|</th>
525                 $button2
526               </tr>
527      </table>
528           </td>
529         </tr>
530       </table>
531     </td>
532   </tr>
533
534 $jsscript
535   <input type=hidden name=rowcount value=$form->{rowcount}>
536   <tr>
537       <td>
538           <table width=100%>
539            <tr class=listheading>
540           <th class=listheading style="width:15%">|
541     . $locale->text('Account') . qq|</th>
542           <th class=listheading style="width:10%">|
543     . $locale->text('Amount') . qq|</th>
544           <th class=listheading style="width:10%">|
545     . $locale->text('Tax') . qq|</th>
546           <th class=listheading style="width:5%">|
547     . $locale->text('Korrektur') . qq|</th>
548           <th class=listheading style="width:10%">|
549     . $locale->text('Taxkey') . qq|</th>
550           <th class=listheading style="width:10%">|
551     . $locale->text('Project') . qq|</th>
552         </tr>
553 |;
554
555   $amount  = $locale->text('Amount');
556   $project = $locale->text('Project');
557
558   for my $i (1 .. $form->{rowcount}) {
559
560     # format amounts
561     $form->{"amount_$i"} =
562       $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
563     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
564
565     my $selected_accno_full;
566     my ($accno_row) = split(/--/, $form->{"AR_amount_$i"});
567     my $item = $charts{$accno_row};
568     $selected_accno_full = "$item->{accno}--$item->{tax_id}";
569
570     my $selected_taxchart = $form->{"taxchart_$i"};
571     my ($selected_accno, $selected_tax_id) = split(/--/, $selected_accno_full);
572     my ($previous_accno, $previous_tax_id) = split(/--/, $form->{"previous_AR_amount_$i"});
573
574     if ($previous_accno &&
575         ($previous_accno eq $selected_accno) &&
576         ($previous_tax_id ne $selected_tax_id)) {
577       my $item = $taxcharts{$selected_tax_id};
578       $selected_taxchart = "$item->{id}--$item->{rate}";
579     }
580
581     $selected_taxchart = $taxchart_init unless ($form->{"taxchart_$i"});
582
583     $selectAR_amount =
584       NTI($cgi->popup_menu('-name' => "AR_amount_$i",
585                            '-id' => "AR_amount_$i",
586                            '-style' => 'width:400px',
587                            '-onChange' => "setTaxkey(this, $i)",
588                            '-values' => \@AR_amount_values,
589                            '-labels' => \%AR_amount_labels,
590                            '-default' => $selected_accno_full))
591       . $cgi->hidden('-name' => "previous_AR_amount_$i",
592                      '-default' => $selected_accno_full);
593
594     $tax = qq|<td>| .
595       NTI($cgi->popup_menu('-name' => "taxchart_$i",
596                            '-id' => "taxchart_$i",
597                            '-style' => 'width:200px',
598                            '-values' => \@taxchart_values,
599                            '-labels' => \%taxchart_labels,
600                            '-default' => $selected_taxchart))
601       . qq|</td>|;
602
603     $korrektur_checked = ($form->{"korrektur_$i"} ? 'checked' : '');
604
605     my $projectnumber =
606       NTI($cgi->popup_menu('-name' => "project_id_$i",
607                            '-values' => \@project_values,
608                            '-labels' => \%project_labels,
609                            '-default' => $form->{"project_id_$i"} ));
610
611     print qq|
612         <tr>
613           <td>$selectAR_amount</td>
614           <td><input name="amount_$i" size=10 value=$form->{"amount_$i"}></td>
615           <td><input name="tax_$i" size=10 value=$form->{"tax_$i"}></td>
616           <td><input type="checkbox" name="korrektur_$i" value="1" $korrektur_checked></td>
617           $tax
618           <td>$projectnumber</td>
619         </tr>
620 |;
621     $amount  = "";
622     $project = "";
623   }
624
625   $form->{invtotal_unformatted} = $form->{invtotal};
626   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
627
628   $ARselected =
629     NTI($cgi->popup_menu('-name' => "ARselected", '-id' => "ARselected",
630                          '-style' => 'width:400px',
631                          '-values' => \@AR_values, '-labels' => \%AR_labels,
632                          '-default' => $form->{ARselected}));
633
634   print qq|
635         <tr>
636           <td colspan=6>
637             <hr noshade>
638           </td>
639         </tr>
640         <tr>
641           <td>${ARselected}</td>
642           <th align=left>$form->{invtotal}</th>
643
644           <input type=hidden name=oldinvtotal value=$form->{oldinvtotal}>
645           <input type=hidden name=oldtotalpaid value=$form->{oldtotalpaid}>
646
647           <input type=hidden name=taxaccounts value="$form->{taxaccounts}">
648
649           <td colspan=4></td>
650
651
652         </tr>
653         </table>
654         </td>
655     </tr>
656     <tr>
657       <td>
658         <table width=100%>
659         <tr>
660           <th align=left width=1%>| . $locale->text('Notes') . qq|</th>
661           <td align=left>$notes</td>
662         </tr>
663       </table>
664     </td>
665   </tr>
666   <tr>
667     <td>
668       <table width=100%>
669         <tr class=listheading>
670           <th colspan=7 class=listheading>|
671     . $locale->text('Incoming Payments') . qq|</th>
672         </tr>
673 |;
674
675   if ($form->{currency} eq $form->{defaultcurrency}) {
676     @column_index = qw(datepaid source memo paid AR_paid paid_project_id);
677   } else {
678     @column_index = qw(datepaid source memo paid exchangerate AR_paid paid_project_id);
679   }
680
681   $column_data{datepaid}     = "<th>" . $locale->text('Date') . "</th>";
682   $column_data{paid}         = "<th>" . $locale->text('Amount') . "</th>";
683   $column_data{exchangerate} = "<th>" . $locale->text('Exch') . "</th>";
684   $column_data{AR_paid}      = "<th>" . $locale->text('Account') . "</th>";
685   $column_data{source}       = "<th>" . $locale->text('Source') . "</th>";
686   $column_data{memo}         = "<th>" . $locale->text('Memo') . "</th>"; 
687   $column_data{paid_project_id} = "<th>" . $locale->text('Project Number') . "</th>"; 
688
689   print "
690         <tr>
691 ";
692   map { print "$column_data{$_}\n" } @column_index;
693   print "
694         </tr>
695 ";
696
697   my @triggers  = ();
698   my $totalpaid = 0;
699
700   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
701   for my $i (1 .. $form->{paidaccounts}) {
702     print "
703         <tr>
704 ";
705
706     $selectAR_paid =
707       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
708                            '-id' => "AR_paid_$i",
709                            '-values' => \@AR_paid_values,
710                            '-labels' => \%AR_paid_labels,
711                            '-default' => $form->{"AR_paid_$i"}));
712
713     $totalpaid += $form->{"paid_$i"};
714
715     # format amounts
716     if ($form->{"paid_$i"}) {
717       $form->{"paid_$i"} =
718         $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
719     }
720     $form->{"exchangerate_$i"} =
721       $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
722
723     if ($form->{"exchangerate_$i"} == 0) {
724       $form->{"exchangerate_$i"} = "";
725     }
726
727     $exchangerate = qq|&nbsp;|;
728     if ($form->{currency} ne $form->{defaultcurrency}) {
729       if ($form->{"forex_$i"}) {
730         $exchangerate =
731           qq|<input type=hidden name="exchangerate_$i" value=$form->{"exchangerate_$i"}>$form->{"exchangerate_$i"}|;
732       } else {
733         $exchangerate =
734           qq|<input name="exchangerate_$i" size=10 value=$form->{"exchangerate_$i"}>|;
735       }
736     }
737
738     $exchangerate .= qq|
739 <input type=hidden name="forex_$i" value=$form->{"forex_$i"}>
740 |;
741
742     $column_data{paid} =
743       qq|<td align=center><input name="paid_$i" size=11 value="$form->{"paid_$i"}" onBlur=\"check_right_number_format(this)\"></td>|;
744     $column_data{AR_paid} =
745       qq|<td align=center>${selectAR_paid}</td>|;
746     $column_data{exchangerate} = qq|<td align=center>$exchangerate</td>|;
747     $column_data{datepaid}     =
748       qq|<td align=center><input name="datepaid_$i" id="datepaid_$i" size=11 value="$form->{"datepaid_$i"}" onBlur=\"check_right_date_format(this)\">
749          <input type="button" name="datepaid_$i" id="trigger_datepaid_$i" value="?"></td>|;
750     $column_data{source} =
751       qq|<td align=center><input name="source_$i" size=11 value="$form->{"source_$i"}"></td>|;
752     $column_data{memo} =
753       qq|<td align=center><input name="memo_$i" size=11 value="$form->{"memo_$i"}"></td>|;
754
755     $column_data{paid_project_id} =
756       qq|<td>|
757       . NTI($cgi->popup_menu('-name' => "paid_project_id_$i",
758                              '-values' => \@project_values,
759                              '-labels' => \%project_labels,
760                              '-default' => $form->{"paid_project_id_$i"} ))
761       . qq|</td>|;
762
763     map { print qq|$column_data{$_}\n| } @column_index;
764
765     print "
766         </tr>
767 ";
768     push(@triggers, "datepaid_$i", "BL", "trigger_datepaid_$i");
769   }
770
771   my $paid_missing = $form->{invtotal_unformatted} - $totalpaid;
772
773   print qq|
774         <tr>
775           <td></td>
776           <td></td>
777           <td align="center">| . $locale->text('Total') . qq|</td>
778           <td align="center">| . H($form->format_amount(\%myconfig, $totalpaid, 2)) . qq|</td>
779         </tr>
780         <tr>
781           <td></td>
782           <td></td>
783           <td align="center">| . $locale->text('Missing amount') . qq|</td>
784           <td align="center">| . H($form->format_amount(\%myconfig, $paid_missing, 2)) . qq|</td>
785         </tr>
786 | . $form->write_trigger(\%myconfig, scalar(@triggers) / 3, @triggers) .
787     qq|
788 <input type=hidden name=paidaccounts value=$form->{paidaccounts}>
789
790       </table>
791     </td>
792   </tr>
793   <tr>
794     <td><hr size=3 noshade></td>
795   </tr>
796 </table>
797 |;
798
799   $lxdebug->leave_sub();
800 }
801
802 sub form_footer {
803   $lxdebug->enter_sub();
804
805   $auth->assert('general_ledger');
806
807   my ($transdate, $closedto);
808
809   my $follow_ups_block;
810   if ($form->{id}) {
811     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
812
813     if (@{ $follow_ups} ) {
814       my $num_due       = sum map { $_->{due} * 1 } @{ $follow_ups };
815       $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>|;
816     }
817   }
818
819   print qq|
820
821 $follow_ups_block
822
823 <input name=gldate type=hidden value="| . Q($form->{gldate}) . qq|">
824
825 <input name=callback type=hidden value="$form->{callback}">
826 |
827 . $cgi->hidden('-name' => 'draft_id', '-default' => [$form->{draft_id}])
828 . $cgi->hidden('-name' => 'draft_description', '-default' => [$form->{draft_description}])
829 . qq|
830
831 <br>
832 |;
833
834   if (!$form->{id} && $form->{draft_id}) {
835     print(NTI($cgi->checkbox('-name' => 'remove_draft', '-id' => 'remove_draft',
836                              '-value' => 1, '-checked' => $form->{remove_draft},
837                              '-label' => '')) .
838           qq|&nbsp;<label for="remove_draft">| .
839           $locale->text("Remove draft when posting") .
840           qq|</label><br>|);
841   }
842
843   $transdate = $form->datetonum($form->{transdate}, \%myconfig);
844   $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
845
846   print qq|<input class="submit" type="submit" name="action" id="update_button" value="| . $locale->text('Update') . qq|">\n|;
847
848   # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
849   print qq| <input class=submit type=submit name=action value="| . $locale->text('Storno') . qq|"> |
850     if ($form->{id} && !IS->has_storno(\%myconfig, $form, 'ar') && !IS->is_storno(\%myconfig, $form, 'ar'));
851
852   if ($form->{id}) {
853     if ($form->{radier}) {
854       print qq|
855         <input class=submit type=submit name=action value="| . $locale->text('Post') .            qq|">
856         <input class=submit type=submit name=action value="| . $locale->text('Delete') .          qq|"> |;
857     }
858     if ($transdate > $closedto) {
859       print qq|
860         <input class=submit type=submit name=action value="| . $locale->text('Use As Template') . qq|"> |;
861     }
862     print qq|
863         <input class=submit type=submit name=action value="| . $locale->text('Post Payment') .    qq|">
864         <input type="button" class="submit" onclick="follow_up_window()" value="|
865       . $locale->text('Follow-Up')
866       . qq|"> |;
867
868   } else {
869     if ($transdate > $closedto) {
870       print qq| <input class=submit type=submit name=action value="| . $locale->text('Post') .     qq|"> | .
871         NTI($cgi->submit('-name' => 'action', '-value' => $locale->text('Save draft'), '-class' => 'submit'));
872     }
873   }
874
875   if ($form->{menubar}) {
876     require "bin/mozilla/menu.pl";
877     &menubar;
878   }
879   # button for saving history
880   if($form->{id} ne "") {
881     print qq| <input type=button class=submit onclick=set_history_window($form->{id}); name=history id=history value=| . $locale->text('history') . qq|> |;
882   }
883   # /button for saving history
884   # mark_as_paid button 
885   if($form->{id} ne "") {  
886     print qq|<input type="submit" class="submit" name="action" value="| 
887           . $locale->text('mark as paid') . qq|">|;
888   }
889   # /mark_as_paid button
890
891   print "
892 </form>
893
894 </body>
895 </html>
896 ";
897
898   $lxdebug->leave_sub();
899 }
900
901 sub mark_as_paid {
902   $lxdebug->enter_sub();
903
904   $auth->assert('general_ledger');
905
906   &mark_as_paid_common(\%myconfig,"ar");  
907
908   $lxdebug->leave_sub();
909 }
910
911 sub update {
912   $lxdebug->enter_sub();
913
914   $auth->assert('general_ledger');
915
916   my $display = shift;
917
918   my ($totaltax, $exchangerate, $totalpaid);
919
920   $form->{invtotal} = 0;
921
922   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
923     qw(exchangerate creditlimit creditremaining);
924
925   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
926   my $count = 0;
927   my @a     = ();
928
929   for my $i (1 .. $form->{rowcount}) {
930     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
931     $form->{"tax_$i"} = $form->parse_amount(\%myconfig, $form->{"tax_$i"});
932     if ($form->{"amount_$i"}) {
933       push @a, {};
934       my $j = $#a;
935       if (!$form->{"korrektur_$i"}) {
936         my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
937         if ($taxkey > 1) {
938           if ($form->{taxincluded}) {
939             $form->{"tax_$i"} = $form->{"amount_$i"} / ($rate + 1) * $rate;
940           } else {
941             $form->{"tax_$i"} = $form->{"amount_$i"} * $rate;
942           }
943         } else {
944           $form->{"tax_$i"} = 0;
945         }
946       }
947       $form->{"tax_$i"} = $form->round_amount($form->{"tax_$i"}, 2);
948
949       $totaltax += $form->{"tax_$i"};
950       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
951       $count++;
952     }
953   }
954
955   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
956   $form->{rowcount} = $count + 1;
957   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
958
959   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
960   $form->{exchangerate} = $form->{forex} if $form->{forex};
961
962   $form->{invdate} = $form->{transdate};
963   my $save_AR = $form->{AR};
964   check_name("customer");
965   $form->{AR} = $save_AR;
966
967   $form->{invtotal} =
968     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
969
970   for my $i (1 .. $form->{paidaccounts}) {
971     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
972       map {
973         $form->{"${_}_$i"} =
974           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
975       } qw(paid exchangerate);
976
977       $totalpaid += $form->{"paid_$i"};
978
979       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
980       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
981     }
982   }
983
984   $form->{creditremaining} -=
985     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
986      $form->{oldinvtotal});
987   $form->{oldinvtotal}  = $form->{invtotal};
988   $form->{oldtotalpaid} = $totalpaid;
989
990   &display_form;
991
992   $lxdebug->leave_sub();
993 }
994
995 #
996 # ToDO: fix $closedto and $invdate
997 #
998 sub post_payment {
999   $lxdebug->enter_sub();
1000
1001   $auth->assert('general_ledger');
1002
1003   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1004
1005   for my $i (1 .. $form->{paidaccounts}) {
1006
1007     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
1008       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1009
1010       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1011
1012 #      $form->error($locale->text('Cannot post payment for a closed period!')) if ($datepaid <= $closedto);
1013
1014       if ($form->{currency} ne $form->{defaultcurrency}) {
1015 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
1016         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
1017       }
1018     }
1019   }
1020
1021   ($form->{AR})      = split /--/, $form->{AR};
1022   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
1023   $form->redirect($locale->text('Payment posted!')) if (AR->post_payment(\%myconfig, \%$form));
1024   $form->error($locale->text('Cannot post payment!'));
1025
1026   $lxdebug->leave_sub();
1027 }
1028
1029 sub _post {
1030
1031   $auth->assert('general_ledger');
1032
1033   # inline post
1034   post(1);
1035 }
1036
1037 sub post {
1038   $lxdebug->enter_sub();
1039
1040   $auth->assert('general_ledger');
1041
1042   my ($inline) = @_;
1043
1044   my ($datepaid);
1045
1046   # check if there is an invoice number, invoice and due date
1047   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
1048   $form->isblank("duedate",   $locale->text('Due Date missing!'));
1049   $form->isblank("customer",  $locale->text('Customer missing!'));
1050
1051   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
1052   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
1053   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($transdate <= $closedto);
1054
1055   $form->error($locale->text('Zero amount posting!')) 
1056     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
1057
1058   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1059     if ($form->{currency} ne $form->{defaultcurrency});
1060
1061   delete($form->{AR});
1062
1063   for my $i (1 .. $form->{paidaccounts}) {
1064     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
1065       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1066
1067       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1068
1069       $form->error($locale->text('Cannot post payment for a closed period!'))
1070         if ($datepaid <= $closedto);
1071
1072       if ($form->{currency} ne $form->{defaultcurrency}) {
1073         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
1074         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
1075       }
1076     }
1077   }
1078
1079   # if oldcustomer ne customer redo form
1080   my ($customer) = split /--/, $form->{customer};
1081   if ($form->{oldcustomer} ne "$customer--$form->{customer_id}") {
1082     update();
1083     exit;
1084   }
1085
1086   $form->{AR}{receivables} = $form->{ARselected};
1087   $form->{storno}          = 0;
1088
1089   $lxdebug->message(0, $form->{amount});
1090   $form->{id} = 0 if $form->{postasnew};
1091   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
1092
1093   # saving the history
1094   if(!exists $form->{addition} && $form->{id} ne "") {
1095     $form->{snumbers} = "invnumber_$form->{invnumber}";
1096     $form->{addition} = "POSTED";
1097     $form->save_history($form->dbconnect(\%myconfig));
1098   }
1099   # /saving the history 
1100   remove_draft() if $form->{remove_draft};
1101
1102   $form->redirect($locale->text('Transaction posted!')) unless $inline;
1103
1104   $lxdebug->leave_sub();
1105 }
1106
1107 sub post_as_new {
1108   $lxdebug->enter_sub();
1109
1110   $auth->assert('general_ledger');
1111
1112   $form->{postasnew} = 1;
1113   # saving the history
1114   if(!exists $form->{addition} && $form->{id} ne "") {
1115     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1116         $form->{addition} = "POSTED AS NEW";
1117         $form->save_history($form->dbconnect(\%myconfig));
1118   }
1119   # /saving the history 
1120   &post;
1121
1122   $lxdebug->leave_sub();
1123 }
1124
1125 sub use_as_template {
1126   $lxdebug->enter_sub();
1127
1128   $auth->assert('general_ledger');
1129
1130   map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
1131   $form->{paidaccounts} = 1;
1132   $form->{rowcount}--;
1133   $form->{invdate} = $form->current_date(\%myconfig);
1134   &update;
1135
1136   $lxdebug->leave_sub();
1137 }
1138
1139 sub delete {
1140   $lxdebug->enter_sub();
1141
1142   $auth->assert('general_ledger');
1143
1144   $form->{title} = $locale->text('Confirm!');
1145
1146   $form->header;
1147
1148   delete $form->{header};
1149
1150   print qq|
1151 <body>
1152
1153 <form method=post action=$form->{script}>
1154 |;
1155
1156   foreach my $key (keys %$form) {
1157     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1158     $form->{$key} =~ s/\"/&quot;/g;
1159     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1160   }
1161
1162   print qq|
1163 <h2 class=confirm>$form->{title}</h2>
1164
1165 <h4>|
1166     . $locale->text('Are you sure you want to delete Transaction')
1167     . qq| $form->{invnumber}</h4>
1168
1169 <input name=action class=submit type=submit value="|
1170     . $locale->text('Yes') . qq|">
1171 </form>
1172
1173 </body>
1174 </html>
1175 |;
1176
1177   $lxdebug->leave_sub();
1178 }
1179
1180 sub yes {
1181   $lxdebug->enter_sub();
1182
1183   $auth->assert('general_ledger');
1184
1185   if (AR->delete_transaction(\%myconfig, \%$form)) {
1186     # saving the history
1187     if(!exists $form->{addition}) {
1188       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1189           $form->{addition} = "DELETED";
1190           $form->save_history($form->dbconnect(\%myconfig));
1191     }
1192     # /saving the history 
1193     $form->redirect($locale->text('Transaction deleted!'));
1194   }
1195   $form->error($locale->text('Cannot delete transaction!'));
1196
1197   $lxdebug->leave_sub();
1198 }
1199
1200 sub search {
1201   $lxdebug->enter_sub();
1202
1203   $auth->assert('general_ledger | invoice_edit');
1204
1205   my ($customer, $department);
1206   my ($jsscript, $button1, $button2, $onload);
1207
1208   # setup customer selection
1209   $form->all_vc(\%myconfig, "customer", "AR");
1210
1211   if (@{ $form->{all_customer} }) {
1212     map { $customer .= "<option>$_->{name}--$_->{id}\n" }
1213       @{ $form->{all_customer} };
1214     $customer = qq|<select name=customer><option>\n$customer</select>|;
1215   } else {
1216     $customer = qq|<input name=customer size=35>|;
1217   }
1218
1219   # departments
1220   if (@{ $form->{all_departments} }) {
1221     $form->{selectdepartment} = "<option>\n";
1222
1223     map {
1224       $form->{selectdepartment} .=
1225         "<option>$_->{description}--$_->{id}\n"
1226     } (@{ $form->{all_departments} });
1227   }
1228
1229   $department = qq|
1230         <tr>
1231           <th align=right nowrap>| . $locale->text('Department') . qq|</th>
1232           <td colspan=3><select name=department>$form->{selectdepartment}</select></td>
1233         </tr>
1234 | if $form->{selectdepartment};
1235
1236   $form->{title} = $locale->text('AR Transactions');
1237   
1238   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
1239   
1240   # use JavaScript Calendar or not
1241   $form->{jsscript} = 1;
1242   $jsscript = "";
1243   if ($form->{jsscript}) {
1244
1245     # with JavaScript Calendar
1246     $button1 = qq|
1247        <td><input name=transdatefrom id=transdatefrom size=11 title="$myconfig{dateformat}" onBlur=\"check_right_date_format(this)\">
1248        <input type=button name=transdatefrom id="trigger1" value=|
1249       . $locale->text('button') . qq|></td>
1250       |;
1251     $button2 = qq|
1252        <td><input name=transdateto id=transdateto size=11 title="$myconfig{dateformat}" onBlur=\"check_right_date_format(this)\">
1253        <input type=button name=transdateto name=transdateto id="trigger2" value=|
1254       . $locale->text('button') . qq|></td>
1255      |;
1256
1257     #write Trigger
1258     $jsscript =
1259       Form->write_trigger(\%myconfig, "2", "transdatefrom", "BR", "trigger1",
1260                           "transdateto", "BL", "trigger2");
1261   } else {
1262
1263     # without JavaScript Calendar
1264     $button1 = qq|
1265                               <td><input name=transdatefrom id=transdatefrom size=11 title="$myconfig{dateformat}" onBlur=\"check_right_date_format(this)\"></td>|;
1266     $button2 = qq|
1267                               <td><input name=transdateto id=transdateto size=11 title="$myconfig{dateformat}" onBlur=\"check_right_date_format(this)\"></td>|;
1268   }
1269
1270   $form->get_lists("projects" => { "key" => "ALL_PROJECTS",
1271                                    "all" => 1 });
1272
1273   my %labels = ();
1274   my @values = ("");
1275   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
1276     push(@values, $item->{"id"});
1277     $labels{$item->{"id"}} = $item->{"projectnumber"};
1278   }
1279   my $projectnumber =
1280     NTI($cgi->popup_menu('-name' => 'project_id', '-values' => \@values,
1281                          '-labels' => \%labels));
1282
1283   $form->{fokus} = "search.customer";
1284   $form->header;
1285   $onload = qq|focus()|;
1286   $onload .= qq|;setupDateFormat('|. $myconfig{dateformat} .qq|', '|. $locale->text("Falsches Datumsformat!") .qq|')|;
1287   $onload .= qq|;setupPoints('|. $myconfig{numberformat} .qq|', '|. $locale->text("wrongformat") .qq|')|;
1288   print qq|
1289 <body onLoad="$onload">
1290
1291 <form method=post name="search" action=$form->{script}>
1292
1293 <table width=100%>
1294   <tr><th class=listtop>$form->{title}</th></tr>
1295   <tr height="5"></tr>
1296   <tr>
1297     <td>
1298       <table>
1299         <tr>
1300           <th align=right>| . $locale->text('Customer') . qq|</th>
1301           <td colspan=3>$customer</td>
1302         </tr>
1303         $department
1304         <tr>
1305           <th align=right nowrap>| . $locale->text('Invoice Number') . qq|</th>
1306           <td colspan=3><input name=invnumber size=20></td>
1307         </tr>
1308         <tr>
1309           <th align=right nowrap>| . $locale->text('Order Number') . qq|</th>
1310           <td colspan=3><input name=ordnumber size=20></td>
1311         </tr>
1312        <tr>
1313          <th align=right nowrap>| . $locale->text('Transaction description') . qq|</th>
1314          <td colspan=3><input name=transaction_description size=40></td>
1315        </tr>
1316         <tr>
1317           <th align=right nowrap>| . $locale->text('Notes') . qq|</th>
1318           <td colspan=3><input name=notes size=40></td>
1319         </tr>
1320         <tr>
1321           <th align="right">| . $locale->text("Project Number") . qq|</th>
1322           <td colspan="3">$projectnumber</td>
1323         </tr>
1324         <tr>
1325           <th align=right nowrap>| . $locale->text('From') . qq|</th>
1326           $button1
1327           <th align=right>| . $locale->text('Bis') . qq|</th>
1328           $button2
1329         </tr>
1330         <input type=hidden name=sort value=transdate>
1331       </table>
1332     </td>
1333   </tr>
1334   <tr>
1335     <td>
1336       <table>
1337         <tr>
1338           <th align=right nowrap>| . $locale->text('Include in Report') . qq|</th>
1339           <td>
1340             <table width=100%>
1341               <tr>
1342                 <td align=right><input name=open class=checkbox type=checkbox value=Y checked></td>
1343                 <td nowrap>| . $locale->text('Open') . qq|</td>
1344                 <td align=right><input name=closed class=checkbox type=checkbox value=Y></td>
1345                 <td nowrap>| . $locale->text('Closed') . qq|</td>
1346               </tr>
1347               <tr>
1348                 <td align=right><input name="l_id" class=checkbox type=checkbox value=Y></td>
1349                 <td nowrap>| . $locale->text('ID') . qq|</td>
1350                 <td align=right><input name="l_invnumber" class=checkbox type=checkbox value=Y checked></td>
1351                 <td nowrap>| . $locale->text('Invoice Number') . qq|</td>
1352                 <td align=right><input name="l_ordnumber" class=checkbox type=checkbox value=Y></td>
1353                 <td nowrap>| . $locale->text('Order Number') . qq|</td>
1354                 <td align=right><input name="l_transdate" class=checkbox type=checkbox value=Y checked></td>
1355                 <td nowrap>| . $locale->text('Invoice Date') . qq|</td>
1356               </tr>
1357               <tr>
1358                 <td align=right><input name="l_name" class=checkbox type=checkbox value=Y checked></td>
1359                 <td nowrap>| . $locale->text('Customer') . qq|</td>
1360                 <td align=right><input name="l_netamount" class=checkbox type=checkbox value=Y></td>
1361                 <td nowrap>| . $locale->text('Amount') . qq|</td>
1362                 <td align=right><input name="l_tax" class=checkbox type=checkbox value=Y></td>
1363                 <td nowrap>| . $locale->text('Tax') . qq|</td>
1364                 <td align=right><input name="l_amount" class=checkbox type=checkbox value=Y checked></td>
1365                 <td nowrap>| . $locale->text('Total') . qq|</td>
1366               </tr>
1367               <tr>
1368                 <td align=right><input name="l_datepaid" class=checkbox type=checkbox value=Y></td>
1369                 <td nowrap>| . $locale->text('Date Paid') . qq|</td>
1370                 <td align=right><input name="l_paid" class=checkbox type=checkbox value=Y checked></td>
1371                 <td nowrap>| . $locale->text('Paid') . qq|</td>
1372                 <td align=right><input name="l_duedate" class=checkbox type=checkbox value=Y></td>
1373                 <td nowrap>| . $locale->text('Due Date') . qq|</td>
1374                 <td align=right><input name="l_due" class=checkbox type=checkbox value=Y></td>
1375                 <td nowrap>| . $locale->text('Amount Due') . qq|</td>
1376               </tr>
1377               <tr>
1378                 <td align=right><input name="l_notes" class=checkbox type=checkbox value=Y></td>
1379                 <td nowrap>| . $locale->text('Notes') . qq|</td>
1380                 <td align=right><input name="l_employee" class=checkbox type=checkbox value=Y></td>
1381                 <td nowrap>| . $locale->text('Salesperson') . qq|</td>
1382                 <td align=right><input name="l_shippingpoint" class=checkbox type=checkbox value=Y></td>
1383                 <td nowrap>| . $locale->text('Shipping Point') . qq|</td>
1384                 <td align=right><input name="l_shipvia" class=checkbox type=checkbox value=Y></td>
1385                 <td nowrap>| . $locale->text('Ship via') . qq|</td>
1386               </tr>
1387               <tr>
1388                 <td align=right><input name="l_marge_total" class=checkbox type=checkbox value=Y></td><td> |
1389     .             $locale->text('Ertrag') . qq|</td>
1390                 <td align=right><input name="l_marge_percent" class=checkbox type=checkbox value=Y></td><td> |
1391     .             $locale->text('Ertrag prozentual') . qq|</td>
1392               </tr>
1393               <tr>
1394                 <td align=right><input name="l_subtotal" class=checkbox type=checkbox value=Y></td>
1395                 <td nowrap>| . $locale->text('Subtotal') . qq|</td>
1396                 <td align=right><input name="l_globalprojectnumber" class=checkbox type=checkbox value=Y></td>
1397                 <td nowrap>| . $locale->text('Project Number') . qq|</td>
1398                 <td align=right><input name="l_transaction_description" class=checkbox type=checkbox value=Y></td>
1399                 <td nowrap>| . $locale->text('Transaction description') . qq|</td>
1400               </tr>
1401             </table>
1402           </td>
1403         </tr>
1404       </table>
1405     </td>
1406   </tr>
1407   <tr>
1408     <td><hr size=3 noshade></td>
1409   </tr>
1410 </table>
1411
1412 <input type=hidden name=nextsub value=$form->{nextsub}>
1413
1414 <br>
1415 <input class=submit type=submit name=action value="|
1416     . $locale->text('Continue') . qq|">
1417
1418 </form>
1419
1420 </body>
1421
1422 $jsscript
1423
1424 </html>
1425 |;
1426
1427   $lxdebug->leave_sub();
1428 }
1429
1430 sub create_subtotal_row {
1431   $lxdebug->enter_sub();
1432
1433   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
1434
1435   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
1436
1437   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
1438
1439   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
1440
1441   map { $totals->{$_} = 0 } @{ $subtotal_columns };
1442
1443   $lxdebug->leave_sub();
1444
1445   return $row;
1446 }
1447
1448 sub ar_transactions {
1449   $lxdebug->enter_sub();
1450
1451   $auth->assert('general_ledger | invoice_edit');
1452
1453   my ($callback, $href, @columns);
1454
1455   $form->{customer} = $form->unescape($form->{customer});
1456   ($form->{customer}, $form->{customer_id}) = split(/--/, $form->{customer});
1457
1458   $form->{sort} ||= 'transdate';
1459
1460   AR->ar_transactions(\%myconfig, \%$form);
1461
1462   $form->{title} = $locale->text('AR Transactions');
1463
1464   my $report = SL::ReportGenerator->new(\%myconfig, $form);
1465
1466   @columns =
1467     qw(transdate id type invnumber ordnumber name netamount tax amount paid
1468        datepaid due duedate transaction_description notes employee shippingpoint shipvia
1469        marge_total marge_percent globalprojectnumber);
1470
1471   my @hidden_variables = map { "l_${_}" } @columns;
1472   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber transaction_description notes project_id transdatefrom transdateto);
1473
1474   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
1475
1476   my %column_defs = (
1477     'transdate'               => { 'text' => $locale->text('Date'), },
1478     'id'                      => { 'text' => $locale->text('ID'), },
1479     'type'                    => { 'text' => $locale->text('Type'), },
1480     'invnumber'               => { 'text' => $locale->text('Invoice'), },
1481     'ordnumber'               => { 'text' => $locale->text('Order'), },
1482     'name'                    => { 'text' => $locale->text('Customer'), },
1483     'netamount'               => { 'text' => $locale->text('Amount'), },
1484     'tax'                     => { 'text' => $locale->text('Tax'), },
1485     'amount'                  => { 'text' => $locale->text('Total'), },
1486     'paid'                    => { 'text' => $locale->text('Paid'), },
1487     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
1488     'due'                     => { 'text' => $locale->text('Amount Due'), },
1489     'duedate'                 => { 'text' => $locale->text('Due Date'), },
1490     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1491     'notes'                   => { 'text' => $locale->text('Notes'), },
1492     'employee'                => { 'text' => $locale->text('Salesperson'), },
1493     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
1494     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
1495     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
1496     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
1497     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
1498   );
1499
1500   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid
1501                        employee shippingpoint shipvia)) {
1502     $column_defs{$name}->{link} = $href . "&sort=$name";
1503   }
1504
1505   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1506
1507   $form->{"l_type"} = "Y";
1508   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1509
1510   $report->set_columns(%column_defs);
1511   $report->set_column_order(@columns);
1512
1513   $report->set_export_options('ar_transactions', @hidden_variables);
1514
1515   $report->set_sort_indicator($form->{sort}, 1);
1516
1517   my @options;
1518   if ($form->{customer}) {
1519     push @options, $locale->text('Customer') . " : $form->{customer}";
1520   }
1521   if ($form->{department}) {
1522     my ($department) = split /--/, $form->{department};
1523     push @options, $locale->text('Department') . " : $department";
1524   }
1525   if ($form->{invnumber}) {
1526     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1527   }
1528   if ($form->{ordnumber}) {
1529     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1530   }
1531   if ($form->{notes}) {
1532     push @options, $locale->text('Notes') . " : $form->{notes}";
1533   }
1534   if ($form->{transaction_description}) {
1535     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1536   }
1537   if ($form->{transdatefrom}) {
1538     push @options, $locale->text('From') . "&nbsp;" . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1539   }
1540   if ($form->{transdateto}) {
1541     push @options, $locale->text('Bis') . "&nbsp;" . $locale->date(\%myconfig, $form->{transdateto}, 1);
1542   }
1543   if ($form->{open}) {
1544     push @options, $locale->text('Open');
1545   }
1546   if ($form->{closed}) {
1547     push @options, $locale->text('Closed');
1548   }
1549
1550   $report->set_options('top_info_text'        => join("\n", @options),
1551                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1552                        'output_format'        => 'HTML',
1553                        'title'                => $form->{title},
1554                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1555     );
1556   $report->set_options_from_form();
1557
1558   # add sort and escape callback, this one we use for the add sub
1559   $form->{callback} = $href .= "&sort=$form->{sort}";
1560
1561   # escape callback for href
1562   $callback = $form->escape($href);
1563
1564   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1565
1566   my %totals    = map { $_ => 0 } @subtotal_columns;
1567   my %subtotals = map { $_ => 0 } @subtotal_columns;
1568
1569   my $idx = 0;
1570
1571   foreach my $ar (@{ $form->{AR} }) {
1572     $ar->{tax} = $ar->{amount} - $ar->{netamount};
1573     $ar->{due} = $ar->{amount} - $ar->{paid};
1574
1575     map { $subtotals{$_} += $ar->{$_};
1576           $totals{$_}    += $ar->{$_} } @subtotal_columns;
1577
1578     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1579     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1580
1581     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1582
1583     my $is_storno  = $ar->{storno} && !$ar->{storno_id};
1584     my $has_storno = $ar->{storno} && $ar->{storno_id};
1585
1586     $ar->{type} =
1587       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
1588       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
1589       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1590       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
1591                           $locale->text("AR Transaction (abbreviation)");
1592
1593     my $row = { };
1594
1595     foreach my $column (@columns) {
1596       $row->{$column} = {
1597         'data'  => $ar->{$column},
1598         'align' => $column_alignment{$column},
1599       };
1600     }
1601
1602     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1603       . "&id=" . E($ar->{id}) . "&callback=${callback}";
1604
1605     my $row_set = [ $row ];
1606
1607     if (($form->{l_subtotal} eq 'Y')
1608         && (($idx == (scalar @{ $form->{AR} } - 1))
1609             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1610       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1611     }
1612
1613     $report->add_data($row_set);
1614
1615     $idx++;
1616   }
1617
1618   $report->add_separator();
1619   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1620
1621   $report->generate_with_headers();
1622
1623   $lxdebug->leave_sub();
1624 }
1625
1626 sub storno {
1627   $lxdebug->enter_sub();
1628
1629   $auth->assert('general_ledger');
1630
1631   # don't cancel cancelled transactions
1632   if (IS->has_storno(\%myconfig, $form, 'ar')) {
1633     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1634     $form->error($locale->text("Transaction has already been cancelled!"));
1635   }
1636
1637   AR->storno($form, \%myconfig, $form->{id});
1638
1639   # saving the history
1640   if(!exists $form->{addition} && $form->{id} ne "") {
1641     $form->{snumbers} = "ordnumber_$form->{ordnumber}";
1642     $form->{addition} = "STORNO";
1643     $form->save_history($form->dbconnect(\%myconfig));
1644   }
1645   # /saving the history 
1646
1647   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id}); 
1648
1649   $lxdebug->leave_sub();
1650 }