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