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