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