f164997af23e8d5d3403d5837417598829a9aec4
[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 max);
36
37 use SL::AR;
38 use SL::FU;
39 use SL::IS;
40 use SL::PE;
41 use SL::ReportGenerator;
42
43 require "bin/mozilla/arap.pl";
44 require "bin/mozilla/common.pl";
45 require "bin/mozilla/drafts.pl";
46 require "bin/mozilla/reportgenerator.pl";
47
48 use strict;
49 #use warnings;
50
51 # this is for our long dates
52 # $locale->text('January')
53 # $locale->text('February')
54 # $locale->text('March')
55 # $locale->text('April')
56 # $locale->text('May ')
57 # $locale->text('June')
58 # $locale->text('July')
59 # $locale->text('August')
60 # $locale->text('September')
61 # $locale->text('October')
62 # $locale->text('November')
63 # $locale->text('December')
64
65 # this is for our short month
66 # $locale->text('Jan')
67 # $locale->text('Feb')
68 # $locale->text('Mar')
69 # $locale->text('Apr')
70 # $locale->text('May')
71 # $locale->text('Jun')
72 # $locale->text('Jul')
73 # $locale->text('Aug')
74 # $locale->text('Sep')
75 # $locale->text('Oct')
76 # $locale->text('Nov')
77 # $locale->text('Dec')
78
79 sub add {
80   $main::lxdebug->enter_sub();
81
82   $main::auth->assert('general_ledger');
83
84   my $form     = $main::form;
85   my %myconfig = %main::myconfig;
86
87   return $main::lxdebug->leave_sub() if (load_draft_maybe());
88
89   # saving the history
90   if(!exists $form->{addition} && ($form->{id} ne "")) {
91     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
92     $form->{addition} = "ADDED";
93     $form->save_history;
94   }
95   # /saving the history
96
97   $form->{title}    = "Add";
98   $form->{callback} = "ar.pl?action=add&DONT_LOAD_DRAFT=1" unless $form->{callback};
99
100   AR->get_transdate(\%myconfig, $form);
101   $form->{initial_transdate} = $form->{transdate};
102   &create_links;
103   $form->{transdate} = $form->{initial_transdate};
104   &display_form;
105   $main::lxdebug->leave_sub();
106 }
107
108 sub edit {
109   $main::lxdebug->enter_sub();
110
111   $main::auth->assert('general_ledger');
112
113   my $form     = $main::form;
114
115   # show history button
116   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
117   #/show hhistory button
118   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
119   $form->{title} = "Edit";
120
121   &create_links;
122   &display_form;
123
124   $main::lxdebug->leave_sub();
125 }
126
127 sub display_form {
128   $main::lxdebug->enter_sub();
129
130   $main::auth->assert('general_ledger');
131
132   my $form     = $main::form;
133
134   &form_header;
135   &form_footer;
136
137   $main::lxdebug->leave_sub();
138 }
139
140 sub create_links {
141   $main::lxdebug->enter_sub();
142
143   $main::auth->assert('general_ledger');
144
145   my $form     = $main::form;
146   my %myconfig = %main::myconfig;
147
148   my ($duedate, $taxincluded);
149
150   $form->create_links("AR", \%myconfig, "customer");
151   $duedate = $form->{duedate};
152
153   $taxincluded = $form->{taxincluded};
154   my $id = $form->{id};
155   IS->get_customer(\%myconfig, \%$form);
156   $form->{taxincluded} = $taxincluded;
157   $form->{id} = $id;
158
159   $form->{duedate}     = $duedate if $duedate;
160   $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
161   $form->{rowcount}    = 1;
162
163   # notes
164   $form->{notes} = $form->{intnotes} unless $form->{notes};
165
166   # currencies
167   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
168
169   map { $form->{selectcurrency} .= "<option>$_\n" } $form->get_all_currencies(\%myconfig);
170
171   # customers
172   if (@{ $form->{all_customer} || [] }) {
173     $form->{customer} = "$form->{customer}--$form->{customer_id}";
174     map { $form->{selectcustomer} .= "<option>$_->{name}--$_->{id}\n" }
175       (@{ $form->{all_customer} });
176   }
177
178   # departments
179   if (@{ $form->{all_departments} || [] }) {
180     $form->{selectdepartment} = "<option>\n";
181     $form->{department}       = "$form->{department}--$form->{department_id}";
182
183     map {
184       $form->{selectdepartment} .=
185         "<option>$_->{description}--$_->{id}\n"
186     } (@{ $form->{all_departments} || [] });
187   }
188
189   $form->{employee} = "$form->{employee}--$form->{employee_id}";
190
191   # sales staff
192   if (@{ $form->{all_employees} || [] }) {
193     $form->{selectemployee} = "";
194     map { $form->{selectemployee} .= "<option>$_->{name}--$_->{id}\n" }
195       (@{ $form->{all_employees} || [] });
196   }
197
198   # build the popup menus
199   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
200
201   AR->setup_form($form);
202
203   $form->{locked} =
204     ($form->datetonum($form->{transdate}, \%myconfig) <=
205      $form->datetonum($form->{closedto}, \%myconfig));
206
207   $main::lxdebug->leave_sub();
208 }
209
210 sub form_header {
211   $main::lxdebug->enter_sub();
212
213   $main::auth->assert('general_ledger');
214
215   my $form     = $main::form;
216   my %myconfig = %main::myconfig;
217   my $locale   = $main::locale;
218   my $cgi      = $::request->{cgi};
219
220   my ($title, $readonly, $exchangerate, $rows);
221   my ($notes, $department, $customer, $employee, $amount, $project);
222   my ($ARselected);
223
224
225   $title = $form->{title};
226   # $locale->text('Add Accounts Receivables Transaction')
227   # $locale->text('Edit Accounts Receivables Transaction')
228   $form->{title} = $locale->text("$title Accounts Receivables Transaction");
229
230   $form->{javascript} = qq|<script type="text/javascript">
231   <!--
232   function setTaxkey(accno, row) {
233     var taxkey = accno.options[accno.selectedIndex].value;
234     var reg = /--([0-9]*)/;
235     var found = reg.exec(taxkey);
236     var index = found[1];
237     index = parseInt(index);
238     var tax = 'taxchart_' + row;
239     for (var i = 0; i < document.getElementById(tax).options.length; ++i) {
240       var reg2 = new RegExp("^"+ index, "");
241       if (reg2.exec(document.getElementById(tax).options[i].value)) {
242         document.getElementById(tax).options[i].selected = true;
243         break;
244       }
245     }
246   };
247   //-->
248   </script>|;
249   # show history button js
250   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_history.js"></script>|;
251   #/show history button js
252   $readonly = ($form->{id}) ? "readonly" : "";
253
254   $form->{radier} = ($form->current_date(\%myconfig) eq $form->{gldate}) ? 1 : 0;
255   $readonly = ($form->{radier}) ? "" : $readonly;
256
257   # set option selected
258   foreach my $item (qw(customer currency department employee)) {
259     $form->{"select$item"} =~ s/ selected//;
260     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
261   }
262
263   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
264   $form->{exchangerate} = $form->{forex} if $form->{forex};
265
266   $rows = max 2, $form->numtextrows($form->{notes}, 50);
267
268   my @old_project_ids = grep { $_ } map { $form->{"project_id_$_"} } 1..$form->{rowcount};
269
270   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
271                                     "all"       => 0,
272                                     "old_id"    => \@old_project_ids },
273                    "charts"    => { "key"       => "ALL_CHARTS",
274                                     "transdate" => $form->{transdate} },
275                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
276                                     "module"    => "AR" },);
277
278   $_->{link_split} = { map { $_ => 1 } split/:/, $_->{link} } for @{ $form->{ALL_CHARTS} };
279
280   my %project_labels = map { $_->{id} => $_->{projectnumber} } @{ $form->{"ALL_PROJECTS"} };
281
282   my (@AR_amount_values);
283   my (@AR_values);
284   my (@AR_paid_values);
285   my %chart_labels;
286   my %charts;
287   my $taxchart_init;
288
289   foreach my $item (@{ $form->{ALL_CHARTS} }) {
290     if ($item->{link_split}{AR_amount}) {
291       $taxchart_init = $item->{tax_id} if ($taxchart_init eq "");
292       my $key = "$item->{accno}--$item->{tax_id}";
293       push(@AR_amount_values, $key);
294     } elsif ($item->{link_split}{AR}) {
295       push(@AR_values, $item->{accno});
296     } elsif ($item->{link_split}{AR_paid}) {
297       push(@AR_paid_values, $item->{accno});
298     }
299
300     # weirdness for AR_amount
301     $chart_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
302     $chart_labels{"$item->{accno}--$item->{tax_id}"} = "$item->{accno}--$item->{description}";
303
304     $charts{$item->{accno}} = $item;
305   }
306
307   my %taxchart_labels = ();
308   my @taxchart_values = ();
309   my %taxcharts = ();
310   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
311     my $key = "$item->{id}--$item->{rate}";
312     $taxchart_init = $key if ($taxchart_init eq $item->{id});
313     push(@taxchart_values, $key);
314     $taxchart_labels{$key} = "$item->{taxdescription} " . ($item->{rate} * 100) . ' %';
315     $taxcharts{$item->{id}} = $item;
316   }
317
318   $::request->{layout}->focus("#customer");
319
320   my $follow_up_vc         =  $form->{customer};
321   $follow_up_vc            =~ s/--.*?//;
322   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
323
324   $form->{javascript} .=
325     qq|<script type="text/javascript" src="js/show_vc_details.js"></script>| .
326     qq|<script type="text/javascript" src="js/follow_up.js"></script>|;
327
328 #  $amount  = $locale->text('Amount');
329 #  $project = $locale->text('Project');
330
331   my @transactions;
332   for my $i (1 .. $form->{rowcount}) {
333     my $transaction = {
334       amount     => $form->{"amount_$i"},
335       tax        => $form->{"tax_$i"},
336       project_id => $form->{"project_id_$i"},
337     };
338
339     my $selected_accno_full;
340     my ($accno_row) = split(/--/, $form->{"AR_amount_$i"});
341     my $item = $charts{$accno_row};
342     $selected_accno_full = "$item->{accno}--$item->{tax_id}";
343
344     my $selected_taxchart = $form->{"taxchart_$i"};
345     my ($selected_accno, $selected_tax_id) = split(/--/, $selected_accno_full);
346     my ($previous_accno, $previous_tax_id) = split(/--/, $form->{"previous_AR_amount_$i"});
347
348     if ($previous_accno &&
349         ($previous_accno eq $selected_accno) &&
350         ($previous_tax_id ne $selected_tax_id)) {
351       my $item = $taxcharts{$selected_tax_id};
352       $selected_taxchart = "$item->{id}--$item->{rate}";
353     }
354
355     if (!$form->{"taxchart_$i"}) {
356       if ($form->{"AR_amount_$i"} =~ m/.--./) {
357         $selected_taxchart = join '--', map { ($_->{id}, $_->{rate}) } first { $_->{id} == $item->{tax_id} } @{ $form->{ALL_TAXCHARTS} };
358       } else {
359         $selected_taxchart = $taxchart_init;
360       }
361     }
362
363     $transaction->{selectAR_amount} =
364       NTI($cgi->popup_menu('-name' => "AR_amount_$i",
365                            '-id' => "AR_amount_$i",
366                            '-style' => 'width:400px',
367                            '-onChange' => "setTaxkey(this, $i)",
368                            '-values' => \@AR_amount_values,
369                            '-labels' => \%chart_labels,
370                            '-default' => $selected_accno_full))
371       . $cgi->hidden('-name' => "previous_AR_amount_$i",
372                      '-default' => $selected_accno_full);
373
374     $transaction->{taxchart} =
375       NTI($cgi->popup_menu('-name' => "taxchart_$i",
376                            '-id' => "taxchart_$i",
377                            '-style' => 'width:200px',
378                            '-values' => \@taxchart_values,
379                            '-labels' => \%taxchart_labels,
380                            '-default' => $selected_taxchart));
381
382     push @transactions, $transaction;
383   }
384
385   $form->{invtotal_unformatted} = $form->{invtotal};
386
387   $ARselected =
388     NTI($cgi->popup_menu('-name' => "ARselected", '-id' => "ARselected",
389                          '-style' => 'width:400px',
390                          '-values' => \@AR_values, '-labels' => \%chart_labels,
391                          '-default' => $form->{ARselected}));
392
393
394   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
395
396   my $now = $form->current_date(\%myconfig);
397
398   my @payments;
399   for my $i (1 .. $form->{paidaccounts}) {
400     my $payment = {
401       paid             => $form->{"paid_$i"},
402       exchangerate     => $form->{"exchangerate_$i"} || '',
403       gldate           => $form->{"gldate_$i"},
404       acc_trans_id     => $form->{"acc_trans_id_$i"},
405       source           => $form->{"source_$i"},
406       memo             => $form->{"memo_$i"},
407       AR_paid          => $form->{"AR_paid_$i"},
408       forex            => $form->{"forex_$i"},
409       datepaid         => $form->{"datepaid_$i"},
410       paid_project_id  => $form->{"paid_project_id_$i"},
411       gldate           => $form->{"gldate_$i"},
412     };
413
414     $payment->{selectAR_paid} =
415       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
416                            '-id' => "AR_paid_$i",
417                            '-values' => \@AR_paid_values,
418                            '-labels' => \%chart_labels,
419                            '-default' => $payment->{AR_paid}));
420
421
422
423     $payment->{changeable} =
424         $::lx_office_conf{features}->{payments_changeable} == 0 ? !$payment->{acc_trans_id} # never
425       : $::lx_office_conf{features}->{payments_changeable} == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
426       :                                                           1;
427
428     push @payments, $payment;
429   }
430
431   $form->{totalpaid} = sum map { $_->{paid} } @payments;
432
433   $form->header;
434   print $::form->parse_html_template('ar/form_header', {
435     paid_missing         => $::form->{invtotal} - $::form->{totalpaid},
436     show_exch            => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
437     payments             => \@payments,
438     transactions         => \@transactions,
439     project_labels       => \%project_labels,
440     rows                 => $rows,
441     ARselected           => $ARselected,
442     title_str            => $title,
443     follow_up_trans_info => $follow_up_trans_info,
444   });
445
446   $main::lxdebug->leave_sub();
447 }
448
449 sub form_footer {
450   $main::lxdebug->enter_sub();
451
452   $main::auth->assert('general_ledger');
453
454   my $form     = $main::form;
455   my %myconfig = %main::myconfig;
456   my $locale   = $main::locale;
457   my $cgi      = $::request->{cgi};
458
459   my ($transdate, $closedto);
460
461   my $follow_ups_block;
462   if ($form->{id}) {
463     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
464
465     if (@{ $follow_ups} ) {
466       my $num_due       = sum map { $_->{due} * 1 } @{ $follow_ups };
467       $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>|;
468     }
469   }
470
471   print qq|
472
473 $follow_ups_block
474
475 <input name=gldate type=hidden value="| . Q($form->{gldate}) . qq|">
476
477 <input name=callback type=hidden value="$form->{callback}">
478 |
479 . $cgi->hidden('-name' => 'draft_id', '-default' => [$form->{draft_id}])
480 . $cgi->hidden('-name' => 'draft_description', '-default' => [$form->{draft_description}])
481 . qq|
482
483 <br>
484 |;
485
486   if (!$form->{id} && $form->{draft_id}) {
487     print(NTI($cgi->checkbox('-name' => 'remove_draft', '-id' => 'remove_draft',
488                              '-value' => 1, '-checked' => $form->{remove_draft},
489                              '-label' => '')) .
490           qq|&nbsp;<label for="remove_draft">| .
491           $locale->text("Remove draft when posting") .
492           qq|</label><br>|);
493   }
494
495   $transdate = $form->datetonum($form->{transdate}, \%myconfig);
496   $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
497
498   print qq|<input class="submit" type="submit" name="action" id="update_button" value="| . $locale->text('Update') . qq|">\n|;
499
500   # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
501   print qq| <input class=submit type=submit name=action value="| . $locale->text('Storno') . qq|"> |
502     if ($form->{id} && !IS->has_storno(\%myconfig, $form, 'ar') && !IS->is_storno(\%myconfig, $form, 'ar') && (($form->{totalpaid} == 0) || ($form->{totalpaid} eq "")));
503
504   if ($form->{id}) {
505     if ($form->{radier}) {
506       print qq|
507         <input class=submit type=submit name=action value="| . $locale->text('Post') .            qq|">
508         <input class=submit type=submit name=action value="| . $locale->text('Delete') .          qq|"> |;
509     }
510     if ($transdate > $closedto) {
511       print qq|
512         <input class=submit type=submit name=action value="| . $locale->text('Use As Template') . qq|"> |;
513     }
514     print qq|
515         <input class=submit type=submit name=action value="| . $locale->text('Post Payment') .    qq|">
516         <input type="button" class="submit" onclick="follow_up_window()" value="|
517       . $locale->text('Follow-Up')
518       . qq|"> |;
519
520   } else {
521     if ($transdate > $closedto) {
522       print qq| <input class=submit type=submit name=action value="| . $locale->text('Post') .     qq|"> | .
523         NTI($cgi->submit('-name' => 'action', '-value' => $locale->text('Save draft'), '-class' => 'submit'));
524     }
525   }
526
527   # button for saving history
528   if($form->{id} ne "") {
529     print qq| <input type=button class=submit onclick=set_history_window($form->{id}); name=history id=history value=| . $locale->text('history') . qq|> |;
530   }
531   # /button for saving history
532   # mark_as_paid button
533   if($form->{id} ne "") {
534     print qq|<input type="submit" class="submit" name="action" value="|
535           . $locale->text('mark as paid') . qq|">|;
536   }
537   # /mark_as_paid button
538
539   print "
540 </form>
541 ";
542
543   $main::lxdebug->leave_sub();
544 }
545
546 sub mark_as_paid {
547   $main::lxdebug->enter_sub();
548
549   $main::auth->assert('general_ledger');
550
551   my $form     = $main::form;
552   my %myconfig = %main::myconfig;
553
554   &mark_as_paid_common(\%myconfig,"ar");
555
556   $main::lxdebug->leave_sub();
557 }
558
559 sub update {
560   $main::lxdebug->enter_sub();
561
562   $main::auth->assert('general_ledger');
563
564   my $form     = $main::form;
565   my %myconfig = %main::myconfig;
566
567   my $display = shift;
568
569   my ($totaltax, $exchangerate);
570
571   $form->{invtotal} = 0;
572
573   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
574
575   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
576     qw(exchangerate creditlimit creditremaining);
577
578   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
579   my $count = 0;
580   my @a     = ();
581
582   for my $i (1 .. $form->{rowcount}) {
583     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
584     $form->{"tax_$i"} = $form->parse_amount(\%myconfig, $form->{"tax_$i"});
585     if ($form->{"amount_$i"}) {
586       push @a, {};
587       my $j = $#a;
588       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
589       if ($taxkey > 1) {
590         if ($form->{taxincluded}) {
591           $form->{"tax_$i"} = $form->{"amount_$i"} / ($rate + 1) * $rate;
592         } else {
593           $form->{"tax_$i"} = $form->{"amount_$i"} * $rate;
594         }
595       } else {
596         $form->{"tax_$i"} = 0;
597       }
598       $form->{"tax_$i"} = $form->round_amount($form->{"tax_$i"}, 2);
599
600       $totaltax += $form->{"tax_$i"};
601       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
602       $count++;
603     }
604   }
605
606   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
607   $form->{rowcount} = $count + 1;
608   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
609
610   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
611   $form->{exchangerate} = $form->{forex} if $form->{forex};
612
613   $form->{invdate} = $form->{transdate};
614
615   $form->{invdate} = $form->{transdate};
616
617   my %saved_variables = map +( $_ => $form->{$_} ), qw(AR AR_amount_1 taxchart_1 customer_id);
618
619   &check_name("customer");
620
621   # check_name loads customer notes into notes, but ar only knows intnotes, so copy them
622   $form->{notes} = $form->{intnotes} if $saved_variables{customer_id} != $form->{customer_id};
623
624   $form->{AR} = $saved_variables{AR};
625   if ($saved_variables{AR_amount_1} =~ m/.--./) {
626     map { $form->{$_} = $saved_variables{$_} } qw(AR_amount_1 taxchart_1);
627   } else {
628     delete $form->{taxchart_1};
629   }
630
631   $form->{invtotal} =
632     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
633
634   for my $i (1 .. $form->{paidaccounts}) {
635     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
636       map {
637         $form->{"${_}_$i"} =
638           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
639       } qw(paid exchangerate);
640
641       $form->{totalpaid} += $form->{"paid_$i"};
642
643       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
644       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
645     }
646   }
647
648   $form->{creditremaining} -=
649     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
650      $form->{oldinvtotal});
651   $form->{oldinvtotal}  = $form->{invtotal};
652   $form->{oldtotalpaid} = $form->{totalpaid};
653
654   &display_form;
655
656   $main::lxdebug->leave_sub();
657 }
658
659 #
660 # ToDO: fix $closedto and $invdate
661 #
662 sub post_payment {
663   $main::lxdebug->enter_sub();
664
665   $main::auth->assert('general_ledger');
666
667   my $form     = $main::form;
668   my %myconfig = %main::myconfig;
669   my $locale   = $main::locale;
670
671   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
672
673   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
674
675   for my $i (1 .. $form->{paidaccounts}) {
676
677     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
678       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
679
680       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
681
682       $form->error($locale->text('Cannot post payment for a closed period!')) if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
683
684       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
685 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
686         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
687       }
688     }
689   }
690
691   ($form->{AR})      = split /--/, $form->{AR};
692   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
693   $form->redirect($locale->text('Payment posted!')) if (AR->post_payment(\%myconfig, \%$form));
694   $form->error($locale->text('Cannot post payment!'));
695
696   $main::lxdebug->leave_sub();
697 }
698
699 sub _post {
700
701   $main::auth->assert('general_ledger');
702
703   my $form     = $main::form;
704
705   # inline post
706   post(1);
707 }
708
709 sub post {
710   $main::lxdebug->enter_sub();
711
712   $main::auth->assert('general_ledger');
713
714   my $form     = $main::form;
715   my %myconfig = %main::myconfig;
716   my $locale   = $main::locale;
717
718   my ($inline) = @_;
719
720   my ($datepaid);
721
722   # check if there is an invoice number, invoice and due date
723   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
724   $form->isblank("duedate",   $locale->text('Due Date missing!'));
725   $form->isblank("customer",  $locale->text('Customer missing!'));
726
727   if ($myconfig{mandatory_departments} && !$form->{department}) {
728     $form->{saved_message} = $::locale->text('You have to specify a department.');
729     update();
730     exit;
731   }
732
733   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
734   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
735   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
736
737   $form->error($locale->text('Zero amount posting!'))
738     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
739
740   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
741     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
742
743   delete($form->{AR});
744
745   for my $i (1 .. $form->{paidaccounts}) {
746     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
747       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
748
749       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
750
751       $form->error($locale->text('Cannot post payment for a closed period!'))
752         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
753
754       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
755         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
756         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
757       }
758     }
759   }
760
761   # if oldcustomer ne customer redo form
762   my ($customer) = split /--/, $form->{customer};
763   if ($form->{oldcustomer} ne "$customer--$form->{customer_id}") {
764     update();
765     ::end_of_request();
766   }
767
768   $form->{AR}{receivables} = $form->{ARselected};
769   $form->{storno}          = 0;
770
771   $form->{id} = 0 if $form->{postasnew};
772   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
773
774   # saving the history
775   if(!exists $form->{addition} && $form->{id} ne "") {
776     $form->{snumbers} = "invnumber_$form->{invnumber}";
777     $form->{addition} = "POSTED";
778     $form->save_history;
779   }
780   # /saving the history
781   remove_draft() if $form->{remove_draft};
782
783   $form->redirect($locale->text('Transaction posted!')) unless $inline;
784
785   $main::lxdebug->leave_sub();
786 }
787
788 sub post_as_new {
789   $main::lxdebug->enter_sub();
790
791   $main::auth->assert('general_ledger');
792
793   my $form     = $main::form;
794   my %myconfig = %main::myconfig;
795
796   $form->{postasnew} = 1;
797   # saving the history
798   if(!exists $form->{addition} && $form->{id} ne "") {
799     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
800     $form->{addition} = "POSTED AS NEW";
801     $form->save_history;
802   }
803   # /saving the history
804   &post;
805
806   $main::lxdebug->leave_sub();
807 }
808
809 sub use_as_template {
810   $main::lxdebug->enter_sub();
811
812   $main::auth->assert('general_ledger');
813
814   my $form     = $main::form;
815   my %myconfig = %main::myconfig;
816
817   map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
818   $form->{paidaccounts} = 1;
819   $form->{rowcount}--;
820   $form->{invdate} = $form->current_date(\%myconfig);
821   &update;
822
823   $main::lxdebug->leave_sub();
824 }
825
826 sub delete {
827   $main::lxdebug->enter_sub();
828
829   $main::auth->assert('general_ledger');
830
831   my $form     = $main::form;
832   my $locale   = $main::locale;
833
834   $form->{title} = $locale->text('Confirm!');
835
836   $form->header;
837
838   delete $form->{header};
839
840   print qq|
841 <form method=post action=$form->{script}>
842 |;
843
844   foreach my $key (keys %$form) {
845     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
846     $form->{$key} =~ s/\"/&quot;/g;
847     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
848   }
849
850   print qq|
851 <h2 class=confirm>$form->{title}</h2>
852
853 <h4>|
854     . $locale->text('Are you sure you want to delete Transaction')
855     . qq| $form->{invnumber}</h4>
856
857 <input name=action class=submit type=submit value="|
858     . $locale->text('Yes') . qq|">
859 </form>
860 |;
861
862   $main::lxdebug->leave_sub();
863 }
864
865 sub yes {
866   $main::lxdebug->enter_sub();
867
868   $main::auth->assert('general_ledger');
869
870   my $form     = $main::form;
871   my %myconfig = %main::myconfig;
872   my $locale   = $main::locale;
873
874   if (AR->delete_transaction(\%myconfig, \%$form)) {
875     # saving the history
876     if(!exists $form->{addition}) {
877       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
878       $form->{addition} = "DELETED";
879       $form->save_history;
880     }
881     # /saving the history
882     $form->redirect($locale->text('Transaction deleted!'));
883   }
884   $form->error($locale->text('Cannot delete transaction!'));
885
886   $main::lxdebug->leave_sub();
887 }
888
889 sub search {
890   $main::lxdebug->enter_sub();
891
892   $main::auth->assert('general_ledger | invoice_edit');
893
894   my $form     = $main::form;
895   my %myconfig = %main::myconfig;
896   my $locale   = $main::locale;
897   my $cgi      = $::request->{cgi};
898
899   my ($customer, $department);
900   my ($jsscript, $button1, $button2);
901
902   # setup customer selection
903   $form->all_vc(\%myconfig, "customer", "AR");
904
905   $form->{title}    = $locale->text('AR Transactions');
906   $form->{jsscript} = 1;
907
908   # Auch in Rechnungsübersicht nach Kundentyp filtern - jan
909   $form->get_lists("projects"       => { "key" => "ALL_PROJECTS", "all" => 1 },
910                    "departments"    => "ALL_DEPARTMENTS",
911                    "customers"      => "ALL_VC",
912                    "business_types" => "ALL_BUSINESS_TYPES");
913   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
914   $form->{SHOW_BUSINESS_TYPES} = scalar @{ $form->{ALL_BUSINESS_TYPES} } > 0;
915
916   # constants and subs for template
917   $form->{jsscript}  = 1;
918   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
919
920   $form->header;
921   print $form->parse_html_template('ar/search', { %myconfig });
922
923   $main::lxdebug->leave_sub();
924 }
925
926 sub create_subtotal_row {
927   $main::lxdebug->enter_sub();
928
929   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
930
931   my $form     = $main::form;
932   my %myconfig = %main::myconfig;
933
934   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
935
936   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
937
938   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
939
940   map { $totals->{$_} = 0 } @{ $subtotal_columns };
941
942   $main::lxdebug->leave_sub();
943
944   return $row;
945 }
946
947 sub ar_transactions {
948   $main::lxdebug->enter_sub();
949
950   $main::auth->assert('general_ledger | invoice_edit');
951
952   my $form     = $main::form;
953   my %myconfig = %main::myconfig;
954   my $locale   = $main::locale;
955
956   my ($callback, $href, @columns);
957
958   ($form->{customer}, $form->{customer_id}) = split(/--/, $form->{customer});
959
960   report_generator_set_default_sort('transdate', 1);
961
962   AR->ar_transactions(\%myconfig, \%$form);
963
964   $form->{title} = $locale->text('AR Transactions');
965
966   my $report = SL::ReportGenerator->new(\%myconfig, $form);
967
968   @columns =
969     qw(transdate id type invnumber ordnumber name netamount tax amount paid
970        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
971        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone payment_terms charts customertype);
972
973   my @hidden_variables = map { "l_${_}" } @columns;
974   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber transaction_description notes project_id transdatefrom transdateto employee_id salesman_id business_id);
975
976   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
977
978   my %column_defs = (
979     'transdate'               => { 'text' => $locale->text('Date'), },
980     'id'                      => { 'text' => $locale->text('ID'), },
981     'type'                    => { 'text' => $locale->text('Type'), },
982     'invnumber'               => { 'text' => $locale->text('Invoice'), },
983     'ordnumber'               => { 'text' => $locale->text('Order'), },
984     'name'                    => { 'text' => $locale->text('Customer'), },
985     'netamount'               => { 'text' => $locale->text('Amount'), },
986     'tax'                     => { 'text' => $locale->text('Tax'), },
987     'amount'                  => { 'text' => $locale->text('Total'), },
988     'paid'                    => { 'text' => $locale->text('Paid'), },
989     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
990     'due'                     => { 'text' => $locale->text('Amount Due'), },
991     'duedate'                 => { 'text' => $locale->text('Due Date'), },
992     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
993     'notes'                   => { 'text' => $locale->text('Notes'), },
994     'salesman'                => { 'text' => $locale->text('Salesperson'), },
995     'employee'                => { 'text' => $locale->text('Employee'), },
996     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
997     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
998     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
999     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
1000     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
1001     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
1002     'country'                 => { 'text' => $locale->text('Country'), },
1003     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
1004     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
1005     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
1006     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
1007     'customertype'            => { 'text' => $locale->text('Customer type'), },
1008   );
1009
1010   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description)) {
1011     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1012     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1013   }
1014
1015   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1016
1017   $form->{"l_type"} = "Y";
1018   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1019
1020   $report->set_columns(%column_defs);
1021   $report->set_column_order(@columns);
1022
1023   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
1024
1025   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1026
1027   my @options;
1028   if ($form->{customer}) {
1029     push @options, $locale->text('Customer') . " : $form->{customer}";
1030   }
1031   if ($form->{department}) {
1032     my ($department) = split /--/, $form->{department};
1033     push @options, $locale->text('Department') . " : $department";
1034   }
1035   if ($form->{department_id}) {
1036     push @options, $locale->text('Department Id') . " : $form->{department_id}";
1037   }
1038   if ($form->{invnumber}) {
1039     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1040   }
1041   if ($form->{ordnumber}) {
1042     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1043   }
1044   if ($form->{notes}) {
1045     push @options, $locale->text('Notes') . " : $form->{notes}";
1046   }
1047   if ($form->{transaction_description}) {
1048     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1049   }
1050   if ($form->{transdatefrom}) {
1051     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1052   }
1053   if ($form->{transdateto}) {
1054     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
1055   }
1056   if ($form->{open}) {
1057     push @options, $locale->text('Open');
1058   }
1059   if ($form->{employee_id}) {
1060     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
1061     push @options, $locale->text('Employee') . ' : ' . $employee->name;
1062   }
1063   if ($form->{salesman_id}) {
1064     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1065     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1066   }
1067   if ($form->{closed}) {
1068     push @options, $locale->text('Closed');
1069   }
1070
1071   $report->set_options('top_info_text'        => join("\n", @options),
1072                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1073                        'output_format'        => 'HTML',
1074                        'title'                => $form->{title},
1075                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1076     );
1077   $report->set_options_from_form();
1078   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1079
1080   # add sort and escape callback, this one we use for the add sub
1081   $form->{callback} = $href .= "&sort=$form->{sort}";
1082
1083   # escape callback for href
1084   $callback = $form->escape($href);
1085
1086   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1087
1088   my %totals    = map { $_ => 0 } @subtotal_columns;
1089   my %subtotals = map { $_ => 0 } @subtotal_columns;
1090
1091   my $idx = 0;
1092
1093   foreach my $ar (@{ $form->{AR} }) {
1094     $ar->{tax} = $ar->{amount} - $ar->{netamount};
1095     $ar->{due} = $ar->{amount} - $ar->{paid};
1096
1097     map { $subtotals{$_} += $ar->{$_};
1098           $totals{$_}    += $ar->{$_} } @subtotal_columns;
1099
1100     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1101     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1102
1103     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1104
1105     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
1106     my $has_storno = $ar->{storno} && !$ar->{storno_id};
1107
1108     $ar->{type} =
1109       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
1110       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
1111       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1112       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
1113                           $locale->text("AR Transaction (abbreviation)");
1114
1115     my $row = { };
1116
1117     foreach my $column (@columns) {
1118       $row->{$column} = {
1119         'data'  => $ar->{$column},
1120         'align' => $column_alignment{$column},
1121       };
1122     }
1123
1124     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1125       . "&id=" . E($ar->{id}) . "&callback=${callback}";
1126
1127     my $row_set = [ $row ];
1128
1129     if (($form->{l_subtotal} eq 'Y')
1130         && (($idx == (scalar @{ $form->{AR} } - 1))
1131             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1132       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1133     }
1134
1135     $report->add_data($row_set);
1136
1137     $idx++;
1138   }
1139
1140   $report->add_separator();
1141   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1142
1143   $report->generate_with_headers();
1144
1145   $main::lxdebug->leave_sub();
1146 }
1147
1148 sub storno {
1149   $main::lxdebug->enter_sub();
1150
1151   $main::auth->assert('general_ledger');
1152
1153   my $form     = $main::form;
1154   my %myconfig = %main::myconfig;
1155   my $locale   = $main::locale;
1156
1157   # don't cancel cancelled transactions
1158   if (IS->has_storno(\%myconfig, $form, 'ar')) {
1159     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1160     $form->error($locale->text("Transaction has already been cancelled!"));
1161   }
1162
1163   AR->storno($form, \%myconfig, $form->{id});
1164
1165   # saving the history
1166   if(!exists $form->{addition} && $form->{id} ne "") {
1167     $form->{snumbers} = "ordnumber_$form->{ordnumber}";
1168     $form->{addition} = "STORNO";
1169     $form->save_history;
1170   }
1171   # /saving the history
1172
1173   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1174
1175   $main::lxdebug->leave_sub();
1176 }
1177
1178 1;