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