manuelle ergänzung zum vorherigen commit
[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->{taxchart} =
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
552   $main::lxdebug->leave_sub();
553 }
554
555 sub mark_as_paid {
556   $main::lxdebug->enter_sub();
557
558   $main::auth->assert('general_ledger');
559
560   my $form     = $main::form;
561   my %myconfig = %main::myconfig;
562
563   &mark_as_paid_common(\%myconfig,"ar");
564
565   $main::lxdebug->leave_sub();
566 }
567
568 sub update {
569   $main::lxdebug->enter_sub();
570
571   $main::auth->assert('general_ledger');
572
573   my $form     = $main::form;
574   my %myconfig = %main::myconfig;
575
576   my $display = shift;
577
578   my ($totaltax, $exchangerate);
579
580   $form->{invtotal} = 0;
581
582   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
583
584   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
585     qw(exchangerate creditlimit creditremaining);
586
587   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
588   my $count = 0;
589   my @a     = ();
590
591   for my $i (1 .. $form->{rowcount}) {
592     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
593     $form->{"tax_$i"} = $form->parse_amount(\%myconfig, $form->{"tax_$i"});
594     if ($form->{"amount_$i"}) {
595       push @a, {};
596       my $j = $#a;
597       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
598       if ($taxkey > 1) {
599         if ($form->{taxincluded}) {
600           $form->{"tax_$i"} = $form->{"amount_$i"} / ($rate + 1) * $rate;
601         } else {
602           $form->{"tax_$i"} = $form->{"amount_$i"} * $rate;
603         }
604       } else {
605         $form->{"tax_$i"} = 0;
606       }
607       $form->{"tax_$i"} = $form->round_amount($form->{"tax_$i"}, 2);
608
609       $totaltax += $form->{"tax_$i"};
610       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
611       $count++;
612     }
613   }
614
615   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
616   $form->{rowcount} = $count + 1;
617   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
618
619   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
620   $form->{exchangerate} = $form->{forex} if $form->{forex};
621
622   $form->{invdate} = $form->{transdate};
623
624   $form->{invdate} = $form->{transdate};
625
626   my %saved_variables = map +( $_ => $form->{$_} ), qw(AR AR_amount_1 taxchart_1 customer_id);
627
628   &check_name("customer");
629
630   # check_name loads customer notes into notes, but ar only knows intnotes, so copy them
631   $form->{notes} = $form->{intnotes} if $saved_variables{customer_id} != $form->{customer_id};
632
633   $form->{AR} = $saved_variables{AR};
634   if ($saved_variables{AR_amount_1} =~ m/.--./) {
635     map { $form->{$_} = $saved_variables{$_} } qw(AR_amount_1 taxchart_1);
636   } else {
637     delete $form->{taxchart_1};
638   }
639
640   $form->{invtotal} =
641     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
642
643   for my $i (1 .. $form->{paidaccounts}) {
644     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
645       map {
646         $form->{"${_}_$i"} =
647           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
648       } qw(paid exchangerate);
649
650       $form->{totalpaid} += $form->{"paid_$i"};
651
652       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
653       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
654     }
655   }
656
657   $form->{creditremaining} -=
658     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
659      $form->{oldinvtotal});
660   $form->{oldinvtotal}  = $form->{invtotal};
661   $form->{oldtotalpaid} = $form->{totalpaid};
662
663   &display_form;
664
665   $main::lxdebug->leave_sub();
666 }
667
668 #
669 # ToDO: fix $closedto and $invdate
670 #
671 sub post_payment {
672   $main::lxdebug->enter_sub();
673
674   $main::auth->assert('general_ledger');
675
676   my $form     = $main::form;
677   my %myconfig = %main::myconfig;
678   my $locale   = $main::locale;
679
680   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
681
682   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
683
684   for my $i (1 .. $form->{paidaccounts}) {
685
686     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
687       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
688
689       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
690
691       $form->error($locale->text('Cannot post payment for a closed period!')) if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
692
693       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
694 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
695         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
696       }
697     }
698   }
699
700   ($form->{AR})      = split /--/, $form->{AR};
701   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
702   $form->redirect($locale->text('Payment posted!')) if (AR->post_payment(\%myconfig, \%$form));
703   $form->error($locale->text('Cannot post payment!'));
704
705   $main::lxdebug->leave_sub();
706 }
707
708 sub _post {
709
710   $main::auth->assert('general_ledger');
711
712   my $form     = $main::form;
713
714   # inline post
715   post(1);
716 }
717
718 sub post {
719   $main::lxdebug->enter_sub();
720
721   $main::auth->assert('general_ledger');
722
723   my $form     = $main::form;
724   my %myconfig = %main::myconfig;
725   my $locale   = $main::locale;
726
727   my ($inline) = @_;
728
729   my ($datepaid);
730
731   # check if there is an invoice number, invoice and due date
732   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
733   $form->isblank("duedate",   $locale->text('Due Date missing!'));
734   $form->isblank("customer",  $locale->text('Customer missing!'));
735
736   if ($myconfig{mandatory_departments} && !$form->{department}) {
737     $form->{saved_message} = $::locale->text('You have to specify a department.');
738     update();
739     exit;
740   }
741
742   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
743   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
744   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
745
746   $form->error($locale->text('Zero amount posting!'))
747     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
748
749   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
750     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
751
752   delete($form->{AR});
753
754   for my $i (1 .. $form->{paidaccounts}) {
755     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
756       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
757
758       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
759
760       $form->error($locale->text('Cannot post payment for a closed period!'))
761         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
762
763       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
764         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
765         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
766       }
767     }
768   }
769
770   # if oldcustomer ne customer redo form
771   my ($customer) = split /--/, $form->{customer};
772   if ($form->{oldcustomer} ne "$customer--$form->{customer_id}") {
773     update();
774     ::end_of_request();
775   }
776
777   $form->{AR}{receivables} = $form->{ARselected};
778   $form->{storno}          = 0;
779
780   $form->{id} = 0 if $form->{postasnew};
781   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
782
783   # saving the history
784   if(!exists $form->{addition} && $form->{id} ne "") {
785     $form->{snumbers} = "invnumber_$form->{invnumber}";
786     $form->{addition} = "POSTED";
787     $form->save_history;
788   }
789   # /saving the history
790   remove_draft() if $form->{remove_draft};
791
792   $form->redirect($locale->text('Transaction posted!')) unless $inline;
793
794   $main::lxdebug->leave_sub();
795 }
796
797 sub post_as_new {
798   $main::lxdebug->enter_sub();
799
800   $main::auth->assert('general_ledger');
801
802   my $form     = $main::form;
803   my %myconfig = %main::myconfig;
804
805   $form->{postasnew} = 1;
806   # saving the history
807   if(!exists $form->{addition} && $form->{id} ne "") {
808     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
809     $form->{addition} = "POSTED AS NEW";
810     $form->save_history;
811   }
812   # /saving the history
813   &post;
814
815   $main::lxdebug->leave_sub();
816 }
817
818 sub use_as_template {
819   $main::lxdebug->enter_sub();
820
821   $main::auth->assert('general_ledger');
822
823   my $form     = $main::form;
824   my %myconfig = %main::myconfig;
825
826   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);
827   $form->{paidaccounts} = 1;
828   $form->{rowcount}--;
829   $form->{invdate} = $form->current_date(\%myconfig);
830   &update;
831
832   $main::lxdebug->leave_sub();
833 }
834
835 sub delete {
836   $main::lxdebug->enter_sub();
837
838   $main::auth->assert('general_ledger');
839
840   my $form     = $main::form;
841   my $locale   = $main::locale;
842
843   $form->{title} = $locale->text('Confirm!');
844
845   $form->header;
846
847   delete $form->{header};
848
849   print qq|
850 <body>
851
852 <form method=post action=$form->{script}>
853 |;
854
855   foreach my $key (keys %$form) {
856     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
857     $form->{$key} =~ s/\"/&quot;/g;
858     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
859   }
860
861   print qq|
862 <h2 class=confirm>$form->{title}</h2>
863
864 <h4>|
865     . $locale->text('Are you sure you want to delete Transaction')
866     . qq| $form->{invnumber}</h4>
867
868 <input name=action class=submit type=submit value="|
869     . $locale->text('Yes') . qq|">
870 </form>
871 |;
872
873   $main::lxdebug->leave_sub();
874 }
875
876 sub yes {
877   $main::lxdebug->enter_sub();
878
879   $main::auth->assert('general_ledger');
880
881   my $form     = $main::form;
882   my %myconfig = %main::myconfig;
883   my $locale   = $main::locale;
884
885   if (AR->delete_transaction(\%myconfig, \%$form)) {
886     # saving the history
887     if(!exists $form->{addition}) {
888       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
889       $form->{addition} = "DELETED";
890       $form->save_history;
891     }
892     # /saving the history
893     $form->redirect($locale->text('Transaction deleted!'));
894   }
895   $form->error($locale->text('Cannot delete transaction!'));
896
897   $main::lxdebug->leave_sub();
898 }
899
900 sub search {
901   $main::lxdebug->enter_sub();
902
903   $main::auth->assert('general_ledger | invoice_edit');
904
905   my $form     = $main::form;
906   my %myconfig = %main::myconfig;
907   my $locale   = $main::locale;
908   my $cgi      = $::request->{cgi};
909
910   my ($customer, $department);
911   my ($jsscript, $button1, $button2, $onload);
912
913   # setup customer selection
914   $form->all_vc(\%myconfig, "customer", "AR");
915
916   $form->{title}    = $locale->text('AR Transactions');
917   $form->{jsscript} = 1;
918
919   # Auch in RechnungsĂĽbersicht nach Kundentyp filtern - jan
920   $form->get_lists("projects"       => { "key" => "ALL_PROJECTS", "all" => 1 },
921                    "departments"    => "ALL_DEPARTMENTS",
922                    "customers"      => "ALL_VC",
923                    "business_types" => "ALL_BUSINESS_TYPES");
924   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
925   $form->{SHOW_BUSINESS_TYPES} = scalar @{ $form->{ALL_BUSINESS_TYPES} } > 0;
926
927   # constants and subs for template
928   $form->{jsscript}  = 1;
929   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
930
931   $form->header;
932   print $form->parse_html_template('ar/search', { %myconfig });
933
934   $main::lxdebug->leave_sub();
935 }
936
937 sub create_subtotal_row {
938   $main::lxdebug->enter_sub();
939
940   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
941
942   my $form     = $main::form;
943   my %myconfig = %main::myconfig;
944
945   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
946
947   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
948
949   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
950
951   map { $totals->{$_} = 0 } @{ $subtotal_columns };
952
953   $main::lxdebug->leave_sub();
954
955   return $row;
956 }
957
958 sub ar_transactions {
959   $main::lxdebug->enter_sub();
960
961   $main::auth->assert('general_ledger | invoice_edit');
962
963   my $form     = $main::form;
964   my %myconfig = %main::myconfig;
965   my $locale   = $main::locale;
966
967   my ($callback, $href, @columns);
968
969   ($form->{customer}, $form->{customer_id}) = split(/--/, $form->{customer});
970
971   report_generator_set_default_sort('transdate', 1);
972
973   AR->ar_transactions(\%myconfig, \%$form);
974
975   $form->{title} = $locale->text('AR Transactions');
976
977   my $report = SL::ReportGenerator->new(\%myconfig, $form);
978
979   @columns =
980     qw(transdate id type invnumber ordnumber name netamount tax amount paid
981        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
982        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone payment_terms charts customertype);
983
984   my @hidden_variables = map { "l_${_}" } @columns;
985   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber transaction_description notes project_id transdatefrom transdateto employee_id salesman_id business_id);
986
987   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
988
989   my %column_defs = (
990     'transdate'               => { 'text' => $locale->text('Date'), },
991     'id'                      => { 'text' => $locale->text('ID'), },
992     'type'                    => { 'text' => $locale->text('Type'), },
993     'invnumber'               => { 'text' => $locale->text('Invoice'), },
994     'ordnumber'               => { 'text' => $locale->text('Order'), },
995     'name'                    => { 'text' => $locale->text('Customer'), },
996     'netamount'               => { 'text' => $locale->text('Amount'), },
997     'tax'                     => { 'text' => $locale->text('Tax'), },
998     'amount'                  => { 'text' => $locale->text('Total'), },
999     'paid'                    => { 'text' => $locale->text('Paid'), },
1000     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
1001     'due'                     => { 'text' => $locale->text('Amount Due'), },
1002     'duedate'                 => { 'text' => $locale->text('Due Date'), },
1003     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1004     'notes'                   => { 'text' => $locale->text('Notes'), },
1005     'salesman'                => { 'text' => $locale->text('Salesperson'), },
1006     'employee'                => { 'text' => $locale->text('Employee'), },
1007     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
1008     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
1009     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
1010     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
1011     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
1012     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
1013     'country'                 => { 'text' => $locale->text('Country'), },
1014     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
1015     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
1016     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
1017     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
1018     'customertype'            => { 'text' => $locale->text('Customer type'), },
1019   );
1020
1021   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description)) {
1022     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1023     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1024   }
1025
1026   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1027
1028   $form->{"l_type"} = "Y";
1029   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1030
1031   $report->set_columns(%column_defs);
1032   $report->set_column_order(@columns);
1033
1034   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
1035
1036   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1037
1038   my @options;
1039   if ($form->{customer}) {
1040     push @options, $locale->text('Customer') . " : $form->{customer}";
1041   }
1042   if ($form->{department}) {
1043     my ($department) = split /--/, $form->{department};
1044     push @options, $locale->text('Department') . " : $department";
1045   }
1046   if ($form->{department_id}) {
1047     push @options, $locale->text('Department Id') . " : $form->{department_id}";
1048   }
1049   if ($form->{invnumber}) {
1050     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1051   }
1052   if ($form->{ordnumber}) {
1053     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1054   }
1055   if ($form->{notes}) {
1056     push @options, $locale->text('Notes') . " : $form->{notes}";
1057   }
1058   if ($form->{transaction_description}) {
1059     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1060   }
1061   if ($form->{transdatefrom}) {
1062     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1063   }
1064   if ($form->{transdateto}) {
1065     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
1066   }
1067   if ($form->{open}) {
1068     push @options, $locale->text('Open');
1069   }
1070   if ($form->{employee_id}) {
1071     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
1072     push @options, $locale->text('Employee') . ' : ' . $employee->name;
1073   }
1074   if ($form->{salesman_id}) {
1075     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1076     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1077   }
1078   if ($form->{closed}) {
1079     push @options, $locale->text('Closed');
1080   }
1081
1082   $report->set_options('top_info_text'        => join("\n", @options),
1083                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1084                        'output_format'        => 'HTML',
1085                        'title'                => $form->{title},
1086                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1087     );
1088   $report->set_options_from_form();
1089   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1090
1091   # add sort and escape callback, this one we use for the add sub
1092   $form->{callback} = $href .= "&sort=$form->{sort}";
1093
1094   # escape callback for href
1095   $callback = $form->escape($href);
1096
1097   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1098
1099   my %totals    = map { $_ => 0 } @subtotal_columns;
1100   my %subtotals = map { $_ => 0 } @subtotal_columns;
1101
1102   my $idx = 0;
1103
1104   foreach my $ar (@{ $form->{AR} }) {
1105     $ar->{tax} = $ar->{amount} - $ar->{netamount};
1106     $ar->{due} = $ar->{amount} - $ar->{paid};
1107
1108     map { $subtotals{$_} += $ar->{$_};
1109           $totals{$_}    += $ar->{$_} } @subtotal_columns;
1110
1111     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1112     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1113
1114     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1115
1116     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
1117     my $has_storno = $ar->{storno} && !$ar->{storno_id};
1118
1119     $ar->{type} =
1120       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
1121       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
1122       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1123       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
1124                           $locale->text("AR Transaction (abbreviation)");
1125
1126     my $row = { };
1127
1128     foreach my $column (@columns) {
1129       $row->{$column} = {
1130         'data'  => $ar->{$column},
1131         'align' => $column_alignment{$column},
1132       };
1133     }
1134
1135     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1136       . "&id=" . E($ar->{id}) . "&callback=${callback}";
1137
1138     my $row_set = [ $row ];
1139
1140     if (($form->{l_subtotal} eq 'Y')
1141         && (($idx == (scalar @{ $form->{AR} } - 1))
1142             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1143       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1144     }
1145
1146     $report->add_data($row_set);
1147
1148     $idx++;
1149   }
1150
1151   $report->add_separator();
1152   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1153
1154   $report->generate_with_headers();
1155
1156   $main::lxdebug->leave_sub();
1157 }
1158
1159 sub storno {
1160   $main::lxdebug->enter_sub();
1161
1162   $main::auth->assert('general_ledger');
1163
1164   my $form     = $main::form;
1165   my %myconfig = %main::myconfig;
1166   my $locale   = $main::locale;
1167
1168   # don't cancel cancelled transactions
1169   if (IS->has_storno(\%myconfig, $form, 'ar')) {
1170     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1171     $form->error($locale->text("Transaction has already been cancelled!"));
1172   }
1173
1174   AR->storno($form, \%myconfig, $form->{id});
1175
1176   # saving the history
1177   if(!exists $form->{addition} && $form->{id} ne "") {
1178     $form->{snumbers} = "ordnumber_$form->{ordnumber}";
1179     $form->{addition} = "STORNO";
1180     $form->save_history;
1181   }
1182   # /saving the history
1183
1184   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1185
1186   $main::lxdebug->leave_sub();
1187 }
1188
1189 1;