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