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