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