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