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