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