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