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