Rechungssuche - Department bei selectbox richtig suchen.
[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" unless $form->{callback};
99
100   AR->get_transdate(\%myconfig, $form);
101   $form->{initial_transdate} = $form->{transdate};
102   &create_links;
103   $form->{transdate} = $form->{initial_transdate};
104   &display_form;
105   $main::lxdebug->leave_sub();
106 }
107
108 sub edit {
109   $main::lxdebug->enter_sub();
110
111   $main::auth->assert('general_ledger');
112
113   my $form     = $main::form;
114
115   # show history button
116   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
117   #/show hhistory button
118   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
119   $form->{title} = "Edit";
120
121   &create_links;
122   &display_form;
123
124   $main::lxdebug->leave_sub();
125 }
126
127 sub display_form {
128   $main::lxdebug->enter_sub();
129
130   $main::auth->assert('general_ledger');
131
132   my $form     = $main::form;
133
134   &form_header;
135   &form_footer;
136
137   $main::lxdebug->leave_sub();
138 }
139
140 sub create_links {
141   $main::lxdebug->enter_sub();
142
143   $main::auth->assert('general_ledger');
144
145   my $form     = $main::form;
146   my %myconfig = %main::myconfig;
147
148   my ($duedate, $taxincluded);
149
150   $form->create_links("AR", \%myconfig, "customer");
151   $duedate = $form->{duedate};
152
153   $taxincluded = $form->{taxincluded};
154   my $id = $form->{id};
155   IS->get_customer(\%myconfig, \%$form);
156   $form->{taxincluded} = $taxincluded;
157   $form->{id} = $id;
158
159   $form->{duedate}     = $duedate if $duedate;
160   $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
161   $form->{rowcount}    = 1;
162
163   # notes
164   $form->{notes} = $form->{intnotes} unless $form->{notes};
165
166   # currencies
167   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
168
169   map { $form->{selectcurrency} .= "<option>$_\n" } $form->get_all_currencies(\%myconfig);
170
171   # customers
172   if (@{ $form->{all_customer} || [] }) {
173     $form->{customer} = "$form->{customer}--$form->{customer_id}";
174     map { $form->{selectcustomer} .= "<option>$_->{name}--$_->{id}\n" }
175       (@{ $form->{all_customer} });
176   }
177
178   # departments
179   if (@{ $form->{all_departments} || [] }) {
180     $form->{selectdepartment} = "<option>\n";
181     $form->{department}       = "$form->{department}--$form->{department_id}";
182
183     map {
184       $form->{selectdepartment} .=
185         "<option>$_->{description}--$_->{id}\n"
186     } (@{ $form->{all_departments} || [] });
187   }
188
189   $form->{employee} = "$form->{employee}--$form->{employee_id}";
190
191   # sales staff
192   if (@{ $form->{all_employees} || [] }) {
193     $form->{selectemployee} = "";
194     map { $form->{selectemployee} .= "<option>$_->{name}--$_->{id}\n" }
195       (@{ $form->{all_employees} || [] });
196   }
197
198   # build the popup menus
199   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
200
201   AR->setup_form($form);
202
203   $form->{locked} =
204     ($form->datetonum($form->{transdate}, \%myconfig) <=
205      $form->datetonum($form->{closedto}, \%myconfig));
206
207   $main::lxdebug->leave_sub();
208 }
209
210 sub form_header {
211   $main::lxdebug->enter_sub();
212
213   $main::auth->assert('general_ledger');
214
215   my $form     = $main::form;
216   my %myconfig = %main::myconfig;
217   my $locale   = $main::locale;
218   my $cgi      = $main::cgi;
219
220   my ($title, $readonly, $exchangerate, $rows);
221   my ($taxincluded, $notes, $department, $customer, $employee, $amount, $project);
222   my ($jsscript, $button1, $button2, $onload);
223   my ($selectAR_amount, $selectAR_paid, $ARselected, $tax);
224   my (@column_index, %column_data);
225
226
227   $title = $form->{title};
228   $form->{title} = $locale->text("$title Accounts Receivables Transaction");
229
230   $form->{taxincluded} = ($form->{taxincluded}) ? "checked" : "";
231
232   # $locale->text('Add Accounts Receivables Transaction')
233   # $locale->text('Edit Accounts Receivables Transaction')
234   $form->{javascript} = qq|<script type="text/javascript">
235   <!--
236   function setTaxkey(accno, row) {
237     var taxkey = accno.options[accno.selectedIndex].value;
238     var reg = /--([0-9]*)/;
239     var found = reg.exec(taxkey);
240     var index = found[1];
241     index = parseInt(index);
242     var tax = 'taxchart_' + row;
243     for (var i = 0; i < document.getElementById(tax).options.length; ++i) {
244       var reg2 = new RegExp("^"+ index, "");
245       if (reg2.exec(document.getElementById(tax).options[i].value)) {
246         document.getElementById(tax).options[i].selected = true;
247         break;
248       }
249     }
250   };
251   //-->
252   </script>|;
253   # show history button js
254   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_history.js"></script>|;
255   #/show history button js
256   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
257   $readonly = ($form->{id}) ? "readonly" : "";
258
259   $form->{radier} =
260     ($form->current_date(\%myconfig) eq $form->{gldate}) ? 1 : 0;
261   $readonly = ($form->{radier}) ? "" : $readonly;
262
263   # set option selected
264   foreach my $item (qw(customer currency department employee)) {
265     $form->{"select$item"} =~ s/ selected//;
266     $form->{"select$item"} =~
267       s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
268   }
269
270   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
271   $form->{exchangerate} = $form->{forex} if $form->{forex};
272
273   # format amounts
274   $form->{exchangerate} =
275     $form->format_amount(\%myconfig, $form->{exchangerate});
276
277   if ($form->{exchangerate} == 0) {
278     $form->{exchangerate} = "";
279   }
280
281   $form->{creditlimit} =
282     $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
283   $form->{creditremaining} =
284     $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
285
286   $exchangerate = qq|
287 <input type=hidden name=forex value=$form->{forex}>
288 |;
289   if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
290     if ($form->{forex}) {
291       $exchangerate .= qq|
292         <th align=right>| . $locale->text('Exchangerate') . qq|</th>
293         <td><input type=hidden name=exchangerate value=$form->{exchangerate}>$form->{exchangerate}</td>
294 |;
295     } else {
296       $exchangerate .= qq|
297         <th align=right>| . $locale->text('Exchangerate') . qq|</th>
298         <td><input name=exchangerate size=10 value=$form->{exchangerate}></td>
299 |;
300     }
301   }
302
303   $taxincluded = qq|
304               <tr>
305                 <td align=right><input name=taxincluded class=checkbox type=checkbox value=1 $form->{taxincluded}></td>
306                 <th align=left nowrap>| . $locale->text('Tax Included') . qq|</th>
307               </tr>
308 |;
309
310   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
311     $rows = 2;
312   }
313   $notes =
314     qq|<textarea name=notes rows=$rows cols=50 wrap=soft>$form->{notes}</textarea>|;
315
316   $department = qq|
317               <tr>
318                 <th align="right" nowrap>| . $locale->text('Department') . qq|</th>
319                 <td colspan=3><select name=department>$form->{selectdepartment}</select>
320                 <input type=hidden name=selectdepartment value="$form->{selectdepartment}">
321                 </td>
322               </tr>
323 | if $form->{selectdepartment};
324
325   my $n = ($form->{creditremaining} =~ /-/) ? "0" : "1";
326
327   $customer = ($form->{selectcustomer})
328     ? qq|<select name="customer" onchange="document.getElementById('update_button').click();">$form->{selectcustomer}</select>|
329     : qq|<input name=customer value="$form->{customer}" size=35>|;
330
331   $employee = qq|
332                 <input type=hidden name=employee value="$form->{employee}">
333 |;
334
335   if ($form->{selectemployee}) {
336     $employee = qq|
337               <tr>
338                 <th align=right nowrap>| . $locale->text('Salesperson') . qq|</th>
339                 <td  colspan=2><select name=employee>$form->{selectemployee}</select></td>
340                 <input type=hidden name=selectemployee value="$form->{selectemployee}">
341               </tr>
342 |;
343   }
344
345   my @old_project_ids = ();
346   map({ push(@old_project_ids, $form->{"project_id_$_"})
347           if ($form->{"project_id_$_"}); } (1..$form->{"rowcount"}));
348
349   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
350                                     "all"       => 0,
351                                     "old_id"    => \@old_project_ids },
352                    "charts"    => { "key"       => "ALL_CHARTS",
353                                     "transdate" => $form->{transdate} },
354                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
355                                     "module"    => "AR" },);
356
357   map({ $_->{link_split} = [ split(/:/, $_->{link}) ]; }
358       @{ $form->{ALL_CHARTS} });
359
360   my %project_labels = ();
361   my @project_values = ("");
362   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
363     push(@project_values, $item->{"id"});
364     $project_labels{$item->{"id"}} = $item->{"projectnumber"};
365   }
366
367   my (%AR_amount_labels, @AR_amount_values);
368   my (%AR_labels, @AR_values);
369   my (%AR_paid_labels, @AR_paid_values);
370   my %charts;
371   my $taxchart_init;
372
373   foreach my $item (@{ $form->{ALL_CHARTS} }) {
374     if (grep({ $_ eq "AR_amount" } @{ $item->{link_split} })) {
375       $taxchart_init = $item->{tax_id} if ($taxchart_init eq "");
376       my $key = "$item->{accno}--$item->{tax_id}";
377       push(@AR_amount_values, $key);
378       $AR_amount_labels{$key} =
379         "$item->{accno}--$item->{description}";
380
381     } elsif (grep({ $_ eq "AR" } @{ $item->{link_split} })) {
382       push(@AR_values, $item->{accno});
383       $AR_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
384
385     } elsif (grep({ $_ eq "AR_paid" } @{ $item->{link_split} })) {
386       push(@AR_paid_values, $item->{accno});
387       $AR_paid_labels{$item->{accno}} =
388         "$item->{accno}--$item->{description}";
389     }
390
391     $charts{$item->{accno}} = $item;
392   }
393
394   my %taxchart_labels = ();
395   my @taxchart_values = ();
396   my %taxcharts = ();
397   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
398     my $key = "$item->{id}--$item->{rate}";
399     $taxchart_init = $key if ($taxchart_init eq $item->{id});
400     push(@taxchart_values, $key);
401     $taxchart_labels{$key} =
402       "$item->{taxdescription} " . ($item->{rate} * 100) . ' %';
403     $taxcharts{$item->{id}} = $item;
404   }
405
406   $form->{fokus} = "arledger.customer";
407
408   # use JavaScript Calendar or not
409   $form->{jsscript} = 1;
410   $jsscript = "";
411   if ($form->{jsscript}) {
412
413     # with JavaScript Calendar
414     $button1 = qq|
415        <td><input name=transdate id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\"></td>
416        <td><input type=button name=transdate id="trigger1" value=|
417       . $locale->text('button') . qq|></td>
418        |;
419     $button2 = qq|
420        <td><input name=duedate id=duedate size=11 title="$myconfig{dateformat}" value="$form->{duedate}" onBlur=\"check_right_date_format(this)\"></td>
421        <td><input type=button name=duedate id="trigger2" value=|
422       . $locale->text('button') . qq|></td></td>
423      |;
424
425     #write Trigger
426     $jsscript =
427       Form->write_trigger(\%myconfig, "2", "transdate", "BL", "trigger1",
428                           "duedate", "BL", "trigger2");
429   } else {
430
431     # without JavaScript Calendar
432     $button1 =
433       qq|<td><input name=transdate id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\"></td>|;
434     $button2 =
435       qq|<td><input name=duedate id=duedate size=11 title="$myconfig{dateformat}" value="$form->{duedate}" onBlur=\"check_right_date_format(this)\"></td>|;
436   }
437
438   my $follow_up_vc         =  $form->{customer};
439   $follow_up_vc            =~ s/--.*?//;
440   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
441
442   $form->{javascript} .=
443     qq|<script type="text/javascript" src="js/common.js"></script>| .
444     qq|<script type="text/javascript" src="js/show_vc_details.js"></script>| .
445     qq|<script type="text/javascript" src="js/follow_up.js"></script>|;
446
447   $form->header;
448   $onload = qq|focus()|;
449   $onload .= qq|;setupDateFormat('|. $myconfig{dateformat} .qq|', '|. $locale->text("Falsches Datumsformat!") .qq|')|;
450   $onload .= qq|;setupPoints('|. $myconfig{numberformat} .qq|', '|. $locale->text("wrongformat") .qq|')|;
451   print qq|
452 <body onLoad="$onload">
453
454 <form method=post name="arledger" action=$form->{script}>
455
456 <input type=hidden name=id value=$form->{id}>
457 <input type=hidden name=sort value=$form->{sort}>
458 <input type=hidden name=closedto value=$form->{closedto}>
459 <input type=hidden name=locked value=$form->{locked}>
460 <input type=hidden name=title value="$title">
461 <input type="hidden" name="follow_up_trans_id_1" value="| . H($form->{id}) . qq|">
462 <input type="hidden" name="follow_up_trans_type_1" value="ar_transaction">
463 <input type="hidden" name="follow_up_trans_info_1" value="| . H($follow_up_trans_info) . qq|">
464 <input type="hidden" name="follow_up_rowcount" value="1">
465
466 | . ($form->{saved_message} ? qq|<p>$form->{saved_message}</p>| : "") . qq|
467
468 <table width=100%>
469   <tr class=listtop>
470     <th class=listtop>$form->{title}</th>
471   </tr>
472   <tr height="5"></tr>
473   <tr valign=top>
474     <td>
475       <table width=100%>
476         <tr valign=top>
477           <td>
478             <table>
479               <tr>
480                 <th align="right" nowrap>| . $locale->text('Customer') . qq|</th>
481                 <td colspan=3>$customer <input type="button" value="| . $locale->text('Details (one letter abbreviation)') . qq|" onclick="show_vc_details('customer')"></td>
482                 <input type=hidden name=selectcustomer value="$form->{selectcustomer}">
483                 <input type=hidden name=oldcustomer value="$form->{oldcustomer}">
484                 <input type=hidden name=customer_id value="$form->{customer_id}">
485                 <input type=hidden name=terms value=$form->{terms}>
486               </tr>
487               <tr>
488                 <td></td>
489                 <td colspan=3>
490                   <table width=100%>
491                     <tr>
492                       <th align=left nowrap>| . $locale->text('Credit Limit') . qq|</th>
493                       <td>$form->{creditlimit}</td>
494                       <th align=left nowrap>| . $locale->text('Remaining') . qq|</th>
495                       <td class="plus$n">$form->{creditremaining}</td>
496                       <input type=hidden name=creditlimit value=$form->{creditlimit}>
497                       <input type=hidden name=creditremaining value=$form->{creditremaining}>
498                     </tr>
499                   </table>
500                 </td>
501               </tr>
502               <tr>
503                 <th align=right>| . $locale->text('Currency') . qq|</th>
504                 <td><select name=currency>$form->{selectcurrency}</select></td>
505                 <input type=hidden name=selectcurrency value="$form->{selectcurrency}">
506                 <input type=hidden name=defaultcurrency value=$form->{defaultcurrency}>
507                 <input type=hidden name=fxgain_accno value=$form->{fxgain_accno}>
508                 <input type=hidden name=fxloss_accno value=$form->{fxloss_accno}>
509                 $exchangerate
510               </tr>
511               $department
512               $taxincluded
513             </table>
514           </td>
515           <td align=right>
516             <table>
517               $employee
518               <tr>
519                 <th align=right nowrap>| . $locale->text('Invoice Number') . qq|</th>
520                 <td><input name=invnumber size=11 value="$form->{invnumber}"></td>
521               </tr>
522               <tr>
523                 <th align=right nowrap>| . $locale->text('Order Number') . qq|</th>
524                 <td><input name=ordnumber size=11 value="$form->{ordnumber}"></td>
525               </tr>
526               <tr>
527                 <th align=right nowrap>| . $locale->text('Invoice Date') . qq|</th>
528                 $button1
529               </tr>
530               <tr>
531                 <th align=right nowrap>| . $locale->text('Due Date') . qq|</th>
532                 $button2
533               </tr>
534      </table>
535           </td>
536         </tr>
537       </table>
538     </td>
539   </tr>
540
541 $jsscript
542   <input type=hidden name=rowcount value=$form->{rowcount}>
543   <tr>
544       <td>
545           <table width=100%>
546            <tr class=listheading>
547           <th class=listheading style="width:15%">|
548     . $locale->text('Account') . qq|</th>
549           <th class=listheading style="width:10%">|
550     . $locale->text('Amount') . qq|</th>
551           <th class=listheading style="width:10%">|
552     . $locale->text('Tax') . qq|</th>
553           <th class=listheading style="width:5%">|
554     . $locale->text('Taxkey') . qq|</th>
555           <th class=listheading style="width:10%">|
556     . $locale->text('Project') . qq|</th>
557         </tr>
558 |;
559
560   $amount  = $locale->text('Amount');
561   $project = $locale->text('Project');
562
563   for my $i (1 .. $form->{rowcount}) {
564
565     # format amounts
566     $form->{"amount_$i"} =
567       $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
568     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
569
570     my $selected_accno_full;
571     my ($accno_row) = split(/--/, $form->{"AR_amount_$i"});
572     my $item = $charts{$accno_row};
573     $selected_accno_full = "$item->{accno}--$item->{tax_id}";
574
575     my $selected_taxchart = $form->{"taxchart_$i"};
576     my ($selected_accno, $selected_tax_id) = split(/--/, $selected_accno_full);
577     my ($previous_accno, $previous_tax_id) = split(/--/, $form->{"previous_AR_amount_$i"});
578
579     if ($previous_accno &&
580         ($previous_accno eq $selected_accno) &&
581         ($previous_tax_id ne $selected_tax_id)) {
582       my $item = $taxcharts{$selected_tax_id};
583       $selected_taxchart = "$item->{id}--$item->{rate}";
584     }
585
586     if (!$form->{"taxchart_$i"}) {
587       if ($form->{"AR_amount_$i"} =~ m/.--./) {
588         $selected_taxchart = join '--', map { ($_->{id}, $_->{rate}) } first { $_->{id} == $item->{tax_id} } @{ $form->{ALL_TAXCHARTS} };
589       } else {
590         $selected_taxchart = $taxchart_init;
591       }
592     }
593
594     $selectAR_amount =
595       NTI($cgi->popup_menu('-name' => "AR_amount_$i",
596                            '-id' => "AR_amount_$i",
597                            '-style' => 'width:400px',
598                            '-onChange' => "setTaxkey(this, $i)",
599                            '-values' => \@AR_amount_values,
600                            '-labels' => \%AR_amount_labels,
601                            '-default' => $selected_accno_full))
602       . $cgi->hidden('-name' => "previous_AR_amount_$i",
603                      '-default' => $selected_accno_full);
604
605     $tax = qq|<td>| .
606       NTI($cgi->popup_menu('-name' => "taxchart_$i",
607                            '-id' => "taxchart_$i",
608                            '-style' => 'width:200px',
609                            '-values' => \@taxchart_values,
610                            '-labels' => \%taxchart_labels,
611                            '-default' => $selected_taxchart))
612       . qq|</td>|;
613
614     my $projectnumber =
615       NTI($cgi->popup_menu('-name' => "project_id_$i",
616                            '-values' => \@project_values,
617                            '-labels' => \%project_labels,
618                            '-default' => $form->{"project_id_$i"} ));
619
620     print qq|
621         <tr>
622           <td>$selectAR_amount</td>
623           <td><input name="amount_$i" size=10 value=$form->{"amount_$i"}></td>
624           <td><input type="hidden" name="tax_$i" value="$form->{"tax_$i"}">$form->{"tax_$i"}</td>
625           $tax
626           <td>$projectnumber</td>
627         </tr>
628 |;
629     $amount  = "";
630     $project = "";
631   }
632
633   $form->{invtotal_unformatted} = $form->{invtotal};
634   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
635
636   $ARselected =
637     NTI($cgi->popup_menu('-name' => "ARselected", '-id' => "ARselected",
638                          '-style' => 'width:400px',
639                          '-values' => \@AR_values, '-labels' => \%AR_labels,
640                          '-default' => $form->{ARselected}));
641
642   print qq|
643         <tr>
644           <td colspan=6>
645             <hr noshade>
646           </td>
647         </tr>
648         <tr>
649           <td>${ARselected}</td>
650           <th align=left>$form->{invtotal}</th>
651
652           <input type=hidden name=oldinvtotal value=$form->{oldinvtotal}>
653           <input type=hidden name=oldtotalpaid value=$form->{oldtotalpaid}>
654
655           <input type=hidden name=taxaccounts value="$form->{taxaccounts}">
656
657           <td colspan=4></td>
658
659
660         </tr>
661         </table>
662         </td>
663     </tr>
664     <tr>
665       <td>
666         <table width=100%>
667         <tr>
668           <th align=left width=1%>| . $locale->text('Notes') . qq|</th>
669           <td align=left>$notes</td>
670         </tr>
671       </table>
672     </td>
673   </tr>
674   <tr>
675     <td>
676       <table width=100%>
677         <tr class=listheading>
678           <th colspan=7 class=listheading>|
679     . $locale->text('Incoming Payments') . qq|</th>
680         </tr>
681 |;
682
683   if ($form->{defaultcurrency} && ($form->{currency} eq $form->{defaultcurrency})) {
684     @column_index = qw(datepaid source memo paid AR_paid paid_project_id);
685   } else {
686     @column_index = qw(datepaid source memo paid exchangerate AR_paid paid_project_id);
687   }
688
689   $column_data{datepaid}     = "<th>" . $locale->text('Date') . "</th>";
690   $column_data{paid}         = "<th>" . $locale->text('Amount') . "</th>";
691   $column_data{exchangerate} = "<th>" . $locale->text('Exch') . "</th>";
692   $column_data{AR_paid}      = "<th>" . $locale->text('Account') . "</th>";
693   $column_data{source}       = "<th>" . $locale->text('Source') . "</th>";
694   $column_data{memo}         = "<th>" . $locale->text('Memo') . "</th>";
695   $column_data{paid_project_id} = "<th>" . $locale->text('Project Number') . "</th>";
696
697   print "
698         <tr>
699 ";
700   map { print "$column_data{$_}\n" } @column_index;
701   print "
702         </tr>
703 ";
704
705   my @triggers  = ();
706   $form->{totalpaid} = 0;
707
708   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
709   for my $i (1 .. $form->{paidaccounts}) {
710     print "
711         <tr>
712 ";
713
714     $selectAR_paid =
715       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
716                            '-id' => "AR_paid_$i",
717                            '-values' => \@AR_paid_values,
718                            '-labels' => \%AR_paid_labels,
719                            '-default' => $form->{"AR_paid_$i"}));
720
721     $form->{totalpaid} += $form->{"paid_$i"};
722
723     # format amounts
724     if ($form->{"paid_$i"}) {
725       $form->{"paid_$i"} =
726         $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
727     }
728     $form->{"exchangerate_$i"} =
729       $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
730
731     if ($form->{"exchangerate_$i"} == 0) {
732       $form->{"exchangerate_$i"} = "";
733     }
734
735     $exchangerate = qq|&nbsp;|;
736     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
737       if ($form->{"forex_$i"}) {
738         $exchangerate =
739           qq|<input type=hidden name="exchangerate_$i" value=$form->{"exchangerate_$i"}>$form->{"exchangerate_$i"}|;
740       } else {
741         $exchangerate =
742           qq|<input name="exchangerate_$i" size=10 value=$form->{"exchangerate_$i"}>|;
743       }
744     }
745
746     $exchangerate .= qq|
747 <input type=hidden name="forex_$i" value=$form->{"forex_$i"}>
748 |;
749
750     $column_data{paid} =
751       qq|<td align=center><input name="paid_$i" size=11 value="$form->{"paid_$i"}" onBlur=\"check_right_number_format(this)\"></td>|;
752     $column_data{AR_paid} =
753       qq|<td align=center>${selectAR_paid}</td>|;
754     $column_data{exchangerate} = qq|<td align=center>$exchangerate</td>|;
755     $column_data{datepaid}     =
756       qq|<td align=center><input name="datepaid_$i" id="datepaid_$i" size=11 value="$form->{"datepaid_$i"}" onBlur=\"check_right_date_format(this)\">
757          <input type="button" name="datepaid_$i" id="trigger_datepaid_$i" value="?"></td>|;
758     $column_data{source} =
759       qq|<td align=center><input name="source_$i" size=11 value="$form->{"source_$i"}"></td>|;
760     $column_data{memo} =
761       qq|<td align=center><input name="memo_$i" size=11 value="$form->{"memo_$i"}"></td>|;
762
763     $column_data{paid_project_id} =
764       qq|<td>|
765       . NTI($cgi->popup_menu('-name' => "paid_project_id_$i",
766                              '-values' => \@project_values,
767                              '-labels' => \%project_labels,
768                              '-default' => $form->{"paid_project_id_$i"} ))
769       . qq|</td>|;
770
771     map { print qq|$column_data{$_}\n| } @column_index;
772
773     print "
774         </tr>
775 ";
776     push(@triggers, "datepaid_$i", "BL", "trigger_datepaid_$i");
777   }
778
779   my $paid_missing = $form->{invtotal_unformatted} - $form->{totalpaid};
780
781   print qq|
782         <tr>
783           <td></td>
784           <td></td>
785           <td align="center">| . $locale->text('Total') . qq|</td>
786           <td align="center">| . H($form->format_amount(\%myconfig, $form->{totalpaid}, 2)) . qq|</td>
787         </tr>
788         <tr>
789           <td></td>
790           <td></td>
791           <td align="center">| . $locale->text('Missing amount') . qq|</td>
792           <td align="center">| . H($form->format_amount(\%myconfig, $paid_missing, 2)) . qq|</td>
793         </tr>
794 | . $form->write_trigger(\%myconfig, scalar(@triggers) / 3, @triggers) .
795     qq|
796 <input type=hidden name=paidaccounts value=$form->{paidaccounts}>
797
798       </table>
799     </td>
800   </tr>
801   <tr>
802     <td><hr size=3 noshade></td>
803   </tr>
804 </table>
805 |;
806
807   $main::lxdebug->leave_sub();
808 }
809
810 sub form_footer {
811   $main::lxdebug->enter_sub();
812
813   $main::auth->assert('general_ledger');
814
815   my $form     = $main::form;
816   my %myconfig = %main::myconfig;
817   my $locale   = $main::locale;
818   my $cgi      = $main::cgi;
819
820   my ($transdate, $closedto);
821
822   my $follow_ups_block;
823   if ($form->{id}) {
824     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
825
826     if (@{ $follow_ups} ) {
827       my $num_due       = sum map { $_->{due} * 1 } @{ $follow_ups };
828       $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>|;
829     }
830   }
831
832   print qq|
833
834 $follow_ups_block
835
836 <input name=gldate type=hidden value="| . Q($form->{gldate}) . qq|">
837
838 <input name=callback type=hidden value="$form->{callback}">
839 |
840 . $cgi->hidden('-name' => 'draft_id', '-default' => [$form->{draft_id}])
841 . $cgi->hidden('-name' => 'draft_description', '-default' => [$form->{draft_description}])
842 . qq|
843
844 <br>
845 |;
846
847   if (!$form->{id} && $form->{draft_id}) {
848     print(NTI($cgi->checkbox('-name' => 'remove_draft', '-id' => 'remove_draft',
849                              '-value' => 1, '-checked' => $form->{remove_draft},
850                              '-label' => '')) .
851           qq|&nbsp;<label for="remove_draft">| .
852           $locale->text("Remove draft when posting") .
853           qq|</label><br>|);
854   }
855
856   $transdate = $form->datetonum($form->{transdate}, \%myconfig);
857   $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
858
859   print qq|<input class="submit" type="submit" name="action" id="update_button" value="| . $locale->text('Update') . qq|">\n|;
860
861   # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
862   print qq| <input class=submit type=submit name=action value="| . $locale->text('Storno') . qq|"> |
863     if ($form->{id} && !IS->has_storno(\%myconfig, $form, 'ar') && !IS->is_storno(\%myconfig, $form, 'ar') && (($form->{totalpaid} == 0) || ($form->{totalpaid} eq "")));
864
865   if ($form->{id}) {
866     if ($form->{radier}) {
867       print qq|
868         <input class=submit type=submit name=action value="| . $locale->text('Post') .            qq|">
869         <input class=submit type=submit name=action value="| . $locale->text('Delete') .          qq|"> |;
870     }
871     if ($transdate > $closedto) {
872       print qq|
873         <input class=submit type=submit name=action value="| . $locale->text('Use As Template') . qq|"> |;
874     }
875     print qq|
876         <input class=submit type=submit name=action value="| . $locale->text('Post Payment') .    qq|">
877         <input type="button" class="submit" onclick="follow_up_window()" value="|
878       . $locale->text('Follow-Up')
879       . qq|"> |;
880
881   } else {
882     if ($transdate > $closedto) {
883       print qq| <input class=submit type=submit name=action value="| . $locale->text('Post') .     qq|"> | .
884         NTI($cgi->submit('-name' => 'action', '-value' => $locale->text('Save draft'), '-class' => 'submit'));
885     }
886   }
887
888   if ($form->{menubar}) {
889     require "bin/mozilla/menu.pl";
890     &menubar;
891   }
892   # button for saving history
893   if($form->{id} ne "") {
894     print qq| <input type=button class=submit onclick=set_history_window($form->{id}); name=history id=history value=| . $locale->text('history') . qq|> |;
895   }
896   # /button for saving history
897   # mark_as_paid button
898   if($form->{id} ne "") {
899     print qq|<input type="submit" class="submit" name="action" value="|
900           . $locale->text('mark as paid') . qq|">|;
901   }
902   # /mark_as_paid button
903
904   print "
905 </form>
906
907 </body>
908 </html>
909 ";
910
911   $main::lxdebug->leave_sub();
912 }
913
914 sub mark_as_paid {
915   $main::lxdebug->enter_sub();
916
917   $main::auth->assert('general_ledger');
918
919   my $form     = $main::form;
920   my %myconfig = %main::myconfig;
921
922   &mark_as_paid_common(\%myconfig,"ar");
923
924   $main::lxdebug->leave_sub();
925 }
926
927 sub update {
928   $main::lxdebug->enter_sub();
929
930   $main::auth->assert('general_ledger');
931
932   my $form     = $main::form;
933   my %myconfig = %main::myconfig;
934
935   my $display = shift;
936
937   my ($totaltax, $exchangerate);
938
939   $form->{invtotal} = 0;
940
941   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
942
943   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
944     qw(exchangerate creditlimit creditremaining);
945
946   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
947   my $count = 0;
948   my @a     = ();
949
950   for my $i (1 .. $form->{rowcount}) {
951     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
952     $form->{"tax_$i"} = $form->parse_amount(\%myconfig, $form->{"tax_$i"});
953     if ($form->{"amount_$i"}) {
954       push @a, {};
955       my $j = $#a;
956       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
957       if ($taxkey > 1) {
958         if ($form->{taxincluded}) {
959           $form->{"tax_$i"} = $form->{"amount_$i"} / ($rate + 1) * $rate;
960         } else {
961           $form->{"tax_$i"} = $form->{"amount_$i"} * $rate;
962         }
963       } else {
964         $form->{"tax_$i"} = 0;
965       }
966       $form->{"tax_$i"} = $form->round_amount($form->{"tax_$i"}, 2);
967
968       $totaltax += $form->{"tax_$i"};
969       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
970       $count++;
971     }
972   }
973
974   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
975   $form->{rowcount} = $count + 1;
976   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
977
978   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
979   $form->{exchangerate} = $form->{forex} if $form->{forex};
980
981   $form->{invdate} = $form->{transdate};
982
983   $form->{invdate} = $form->{transdate};
984
985   my %saved_variables = map +( $_ => $form->{$_} ), qw(AR AR_amount_1 taxchart_1);
986
987   &check_name("customer");
988
989   $form->{AR} = $saved_variables{AR};
990   if ($saved_variables{AR_amount_1} =~ m/.--./) {
991     map { $form->{$_} = $saved_variables{$_} } qw(AR_amount_1 taxchart_1);
992   } else {
993     delete $form->{taxchart_1};
994   }
995
996   $form->{invtotal} =
997     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
998
999   for my $i (1 .. $form->{paidaccounts}) {
1000     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
1001       map {
1002         $form->{"${_}_$i"} =
1003           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
1004       } qw(paid exchangerate);
1005
1006       $form->{totalpaid} += $form->{"paid_$i"};
1007
1008       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
1009       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
1010     }
1011   }
1012
1013   $form->{creditremaining} -=
1014     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
1015      $form->{oldinvtotal});
1016   $form->{oldinvtotal}  = $form->{invtotal};
1017   $form->{oldtotalpaid} = $form->{totalpaid};
1018
1019   &display_form;
1020
1021   $main::lxdebug->leave_sub();
1022 }
1023
1024 #
1025 # ToDO: fix $closedto and $invdate
1026 #
1027 sub post_payment {
1028   $main::lxdebug->enter_sub();
1029
1030   $main::auth->assert('general_ledger');
1031
1032   my $form     = $main::form;
1033   my %myconfig = %main::myconfig;
1034   my $locale   = $main::locale;
1035
1036   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1037
1038   my $invdate = $form->datetonum($form->{transdate}, \%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     ::end_of_request();
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;
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;
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;
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->{department_id}) {
1402     push @options, $locale->text('Department Id') . " : $form->{department_id}";
1403   }
1404   if ($form->{invnumber}) {
1405     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1406   }
1407   if ($form->{ordnumber}) {
1408     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1409   }
1410   if ($form->{notes}) {
1411     push @options, $locale->text('Notes') . " : $form->{notes}";
1412   }
1413   if ($form->{transaction_description}) {
1414     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1415   }
1416   if ($form->{transdatefrom}) {
1417     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1418   }
1419   if ($form->{transdateto}) {
1420     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
1421   }
1422   if ($form->{open}) {
1423     push @options, $locale->text('Open');
1424   }
1425   if ($form->{closed}) {
1426     push @options, $locale->text('Closed');
1427   }
1428
1429   $report->set_options('top_info_text'        => join("\n", @options),
1430                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1431                        'output_format'        => 'HTML',
1432                        'title'                => $form->{title},
1433                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1434     );
1435   $report->set_options_from_form();
1436
1437   # add sort and escape callback, this one we use for the add sub
1438   $form->{callback} = $href .= "&sort=$form->{sort}";
1439
1440   # escape callback for href
1441   $callback = $form->escape($href);
1442
1443   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1444
1445   my %totals    = map { $_ => 0 } @subtotal_columns;
1446   my %subtotals = map { $_ => 0 } @subtotal_columns;
1447
1448   my $idx = 0;
1449
1450   foreach my $ar (@{ $form->{AR} }) {
1451     $ar->{tax} = $ar->{amount} - $ar->{netamount};
1452     $ar->{due} = $ar->{amount} - $ar->{paid};
1453
1454     map { $subtotals{$_} += $ar->{$_};
1455           $totals{$_}    += $ar->{$_} } @subtotal_columns;
1456
1457     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1458     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1459
1460     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1461
1462     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
1463     my $has_storno = $ar->{storno} && !$ar->{storno_id};
1464
1465     $ar->{type} =
1466       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
1467       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
1468       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1469       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
1470                           $locale->text("AR Transaction (abbreviation)");
1471
1472     my $row = { };
1473
1474     foreach my $column (@columns) {
1475       $row->{$column} = {
1476         'data'  => $ar->{$column},
1477         'align' => $column_alignment{$column},
1478       };
1479     }
1480
1481     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1482       . "&id=" . E($ar->{id}) . "&callback=${callback}";
1483
1484     my $row_set = [ $row ];
1485
1486     if (($form->{l_subtotal} eq 'Y')
1487         && (($idx == (scalar @{ $form->{AR} } - 1))
1488             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1489       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1490     }
1491
1492     $report->add_data($row_set);
1493
1494     $idx++;
1495   }
1496
1497   $report->add_separator();
1498   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1499
1500   $report->generate_with_headers();
1501
1502   $main::lxdebug->leave_sub();
1503 }
1504
1505 sub storno {
1506   $main::lxdebug->enter_sub();
1507
1508   $main::auth->assert('general_ledger');
1509
1510   my $form     = $main::form;
1511   my %myconfig = %main::myconfig;
1512   my $locale   = $main::locale;
1513
1514   # don't cancel cancelled transactions
1515   if (IS->has_storno(\%myconfig, $form, 'ar')) {
1516     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1517     $form->error($locale->text("Transaction has already been cancelled!"));
1518   }
1519
1520   AR->storno($form, \%myconfig, $form->{id});
1521
1522   # saving the history
1523   if(!exists $form->{addition} && $form->{id} ne "") {
1524     $form->{snumbers} = "ordnumber_$form->{ordnumber}";
1525     $form->{addition} = "STORNO";
1526     $form->save_history;
1527   }
1528   # /saving the history
1529
1530   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1531
1532   $main::lxdebug->leave_sub();
1533 }
1534
1535 1;