059bfc415e5a35bafaa8a715d8e400de53f6b7fc
[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     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
439     if ($form->date_closed($payment->{"gldate_$i"})) {
440         $payment->{changeable} = 0;
441     }
442
443     push @payments, $payment;
444   }
445
446   my @empty = grep { $_->{paid} eq '' } @payments;
447   @payments = (
448     (sort_by { DateTime->from_kivitendo($_->{datepaid}) } grep { $_->{paid} ne '' } @payments),
449     @empty,
450   );
451
452   $form->{totalpaid} = sum map { $_->{paid} } @payments;
453
454   $form->header;
455   print $::form->parse_html_template('ar/form_header', {
456     paid_missing         => $::form->{invtotal} - $::form->{totalpaid},
457     show_exch            => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
458     payments             => \@payments,
459     transactions         => \@transactions,
460     project_labels       => \%project_labels,
461     rows                 => $rows,
462     ARselected           => $ARselected,
463     title_str            => $title,
464     follow_up_trans_info => $follow_up_trans_info,
465     today                => DateTime->today,
466   });
467
468   $main::lxdebug->leave_sub();
469 }
470
471 sub form_footer {
472   $main::lxdebug->enter_sub();
473
474   $main::auth->assert('general_ledger');
475
476   my $form     = $main::form;
477   my %myconfig = %main::myconfig;
478   my $locale   = $main::locale;
479   my $cgi      = $::request->{cgi};
480
481   if ( $form->{id} ) {
482     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
483     if ( @{ $follow_ups} ) {
484       $form->{follow_up_length} = scalar(@{$follow_ups});
485       $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
486     }
487   }
488
489   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
490   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
491
492   $form->{is_closed} = $transdate <= $closedto;
493
494   # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
495   $form->{show_storno_button} =
496     $form->{id} &&
497     !IS->has_storno(\%myconfig, $form, 'ar') &&
498     !IS->is_storno(\%myconfig, $form, 'ar') &&
499     ($form->{totalpaid} == 0 || $form->{totalpaid} eq "");
500
501   $form->{show_mark_as_paid_button} = $form->{id} && $::instance_conf->get_ar_show_mark_as_paid();
502
503   print $::form->parse_html_template('ar/form_footer');
504
505   $main::lxdebug->leave_sub();
506 }
507
508 sub mark_as_paid {
509   $main::lxdebug->enter_sub();
510
511   $main::auth->assert('general_ledger');
512
513   my $form     = $main::form;
514   my %myconfig = %main::myconfig;
515
516   &mark_as_paid_common(\%myconfig,"ar");
517
518   $main::lxdebug->leave_sub();
519 }
520
521 sub update {
522   $main::lxdebug->enter_sub();
523
524   $main::auth->assert('general_ledger');
525
526   my $form     = $main::form;
527   my %myconfig = %main::myconfig;
528
529   my $display = shift;
530
531   my ($totaltax, $exchangerate);
532
533   $form->{invtotal} = 0;
534
535   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
536
537   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
538     qw(exchangerate creditlimit creditremaining);
539
540   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
541   my $count = 0;
542   my @a     = ();
543
544   for my $i (1 .. $form->{rowcount}) {
545     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
546     if ($form->{"amount_$i"}) {
547       push @a, {};
548       my $j = $#a;
549       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
550
551       my $tmpnetamount;
552       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
553
554       $totaltax += $form->{"tax_$i"};
555       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
556       $count++;
557     }
558   }
559
560   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
561   $form->{rowcount} = $count + 1;
562   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
563
564   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
565   $form->{exchangerate} = $form->{forex} if $form->{forex};
566
567   $form->{invdate} = $form->{transdate};
568
569   my %saved_variables = map +( $_ => $form->{$_} ), qw(AR AR_amount_1 taxchart_1 customer_id notes);
570
571   &check_name("customer");
572
573   $form->{AR} = $saved_variables{AR};
574   if ($saved_variables{AR_amount_1} =~ m/.--./) {
575     map { $form->{$_} = $saved_variables{$_} } qw(AR_amount_1 taxchart_1);
576   } else {
577     delete $form->{taxchart_1};
578   }
579
580   $form->{invtotal} =
581     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
582
583   for my $i (1 .. $form->{paidaccounts}) {
584     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
585       map {
586         $form->{"${_}_$i"} =
587           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
588       } qw(paid exchangerate);
589
590       $form->{totalpaid} += $form->{"paid_$i"};
591
592       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
593       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
594     }
595   }
596
597   $form->{creditremaining} -=
598     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
599      $form->{oldinvtotal});
600   $form->{oldinvtotal}  = $form->{invtotal};
601   $form->{oldtotalpaid} = $form->{totalpaid};
602
603   &display_form;
604
605   $main::lxdebug->leave_sub();
606 }
607
608 #
609 # ToDO: fix $closedto and $invdate
610 #
611 sub post_payment {
612   $main::lxdebug->enter_sub();
613
614   $main::auth->assert('general_ledger');
615
616   my $form     = $main::form;
617   my %myconfig = %main::myconfig;
618   my $locale   = $main::locale;
619
620   $form->mtime_ischanged('ar');
621   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
622
623   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
624
625   for my $i (1 .. $form->{paidaccounts}) {
626
627     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
628       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
629
630       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
631
632       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
633         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
634
635       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
636       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
637       $form->error($locale->text('Cannot post payment for a closed period!'))
638         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
639
640       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
641 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
642         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
643       }
644     }
645   }
646
647   ($form->{AR})      = split /--/, $form->{AR};
648   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
649   if (AR->post_payment(\%myconfig, \%$form)) {
650     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
651     $form->{what_done} = 'invoice';
652     $form->{addition}  = "PAYMENT POSTED";
653     $form->save_history;
654     $form->redirect($locale->text('Payment posted!'))
655   } else {
656     $form->error($locale->text('Cannot post payment!'));
657   };
658
659   $main::lxdebug->leave_sub();
660 }
661
662 sub _post {
663
664   $main::auth->assert('general_ledger');
665
666   my $form     = $main::form;
667
668   # inline post
669   post(1);
670 }
671
672 sub post {
673   $main::lxdebug->enter_sub();
674
675   $main::auth->assert('general_ledger');
676
677   my $form     = $main::form;
678   my %myconfig = %main::myconfig;
679   my $locale   = $main::locale;
680
681   my ($inline) = @_;
682
683   $form->mtime_ischanged('ar');
684
685   my ($datepaid);
686
687   # check if there is an invoice number, invoice and due date
688   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
689   $form->isblank("duedate",   $locale->text('Due Date missing!'));
690   $form->isblank("customer",  $locale->text('Customer missing!'));
691
692   if ($myconfig{mandatory_departments} && !$form->{department}) {
693     $form->{saved_message} = $::locale->text('You have to specify a department.');
694     update();
695     exit;
696   }
697
698   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
699   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
700
701   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
702     if ($form->date_max_future($transdate, \%myconfig));
703
704   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
705
706   $form->error($locale->text('Zero amount posting!'))
707     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
708
709   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
710     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
711
712   delete($form->{AR});
713
714   for my $i (1 .. $form->{paidaccounts}) {
715     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
716       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
717
718       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
719
720       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
721         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
722
723       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
724       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
725       $form->error($locale->text('Cannot post payment for a closed period!'))
726         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
727
728       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
729         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
730         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
731       }
732     }
733   }
734
735   # if oldcustomer ne customer redo form
736   my ($customer) = split /--/, $form->{customer};
737   if ($form->{oldcustomer} ne "$customer--$form->{customer_id}") {
738     update();
739     $::dispatcher->end_request;
740   }
741
742   $form->{AR}{receivables} = $form->{ARselected};
743   $form->{storno}          = 0;
744
745   $form->{id} = 0 if $form->{postasnew};
746   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
747
748   # saving the history
749   if(!exists $form->{addition} && $form->{id} ne "") {
750     $form->{snumbers}  = "invnumber_$form->{invnumber}";
751     $form->{what_done} = "invoice";
752     $form->{addition}  = "POSTED";
753     $form->save_history;
754   }
755   # /saving the history
756
757   $form->redirect($locale->text('Transaction posted!')) unless $inline;
758
759   $main::lxdebug->leave_sub();
760 }
761
762 sub post_as_new {
763   $main::lxdebug->enter_sub();
764
765   $main::auth->assert('general_ledger');
766
767   my $form     = $main::form;
768   my %myconfig = %main::myconfig;
769
770   $form->{postasnew} = 1;
771   # saving the history
772   if(!exists $form->{addition} && $form->{id} ne "") {
773     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
774     $form->{what_done} = "invoice";
775     $form->{addition}  = "POSTED AS NEW";
776     $form->save_history;
777   }
778   # /saving the history
779   &post;
780
781   $main::lxdebug->leave_sub();
782 }
783
784 sub use_as_new {
785   $main::lxdebug->enter_sub();
786
787   $main::auth->assert('general_ledger');
788
789   my $form     = $main::form;
790   my %myconfig = %main::myconfig;
791
792   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);
793   $form->{paidaccounts} = 1;
794   $form->{rowcount}--;
795   $form->{invdate} = $form->current_date(\%myconfig);
796   &update;
797
798   $main::lxdebug->leave_sub();
799 }
800
801 sub delete {
802   $main::lxdebug->enter_sub();
803
804   $main::auth->assert('general_ledger');
805
806   my $form     = $main::form;
807   my $locale   = $main::locale;
808
809   $form->{title} = $locale->text('Confirm!');
810
811   $form->header;
812
813   delete $form->{header};
814
815   print qq|
816 <form method=post action=$form->{script}>
817 |;
818
819   foreach my $key (keys %$form) {
820     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
821     $form->{$key} =~ s/\"/&quot;/g;
822     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
823   }
824
825   print qq|
826 <h2 class=confirm>$form->{title}</h2>
827
828 <h4>|
829     . $locale->text('Are you sure you want to delete Transaction')
830     . qq| $form->{invnumber}</h4>
831
832 <input name=action class=submit type=submit value="|
833     . $locale->text('Yes') . qq|">
834 </form>
835 |;
836
837   $main::lxdebug->leave_sub();
838 }
839
840 sub yes {
841   $main::lxdebug->enter_sub();
842
843   $main::auth->assert('general_ledger');
844
845   my $form     = $main::form;
846   my %myconfig = %main::myconfig;
847   my $locale   = $main::locale;
848
849   if (AR->delete_transaction(\%myconfig, \%$form)) {
850     # saving the history
851     if(!exists $form->{addition}) {
852       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
853       $form->{what_done} = "invoice";
854       $form->{addition}  = "DELETED";
855       $form->save_history;
856     }
857     # /saving the history
858     $form->redirect($locale->text('Transaction deleted!'));
859   }
860   $form->error($locale->text('Cannot delete transaction!'));
861
862   $main::lxdebug->leave_sub();
863 }
864
865 sub search {
866   $main::lxdebug->enter_sub();
867
868   $main::auth->assert('invoice_edit');
869
870   my $form     = $main::form;
871   my %myconfig = %main::myconfig;
872   my $locale   = $main::locale;
873   my $cgi      = $::request->{cgi};
874
875   # setup customer selection
876   $form->all_vc(\%myconfig, "customer", "AR");
877
878   $form->{title}    = $locale->text('AR Transactions');
879
880   # Auch in Rechnungsübersicht nach Kundentyp filtern - jan
881   $form->get_lists("projects"       => { "key" => "ALL_PROJECTS", "all" => 1 },
882                    "departments"    => "ALL_DEPARTMENTS",
883                    "customers"      => "ALL_VC",
884                    "business_types" => "ALL_BUSINESS_TYPES");
885   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
886   $form->{SHOW_BUSINESS_TYPES} = scalar @{ $form->{ALL_BUSINESS_TYPES} } > 0;
887
888   $form->{CT_CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
889   ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
890    $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CT_CUSTOM_VARIABLES},
891                                                                               'include_prefix' => 'l_',
892                                                                               'include_value'  => 'Y');
893
894   # constants and subs for template
895   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
896
897   $form->header;
898   print $form->parse_html_template('ar/search', { %myconfig });
899
900   $main::lxdebug->leave_sub();
901 }
902
903 sub create_subtotal_row {
904   $main::lxdebug->enter_sub();
905
906   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
907
908   my $form     = $main::form;
909   my %myconfig = %main::myconfig;
910
911   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
912
913   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
914
915   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
916
917   map { $totals->{$_} = 0 } @{ $subtotal_columns };
918
919   $main::lxdebug->leave_sub();
920
921   return $row;
922 }
923
924 sub ar_transactions {
925   $main::lxdebug->enter_sub();
926
927   $main::auth->assert('invoice_edit');
928
929   my $form     = $main::form;
930   my %myconfig = %main::myconfig;
931   my $locale   = $main::locale;
932
933   my ($callback, $href, @columns);
934
935   ($form->{customer}, $form->{customer_id}) = split(/--/, $form->{customer});
936
937   report_generator_set_default_sort('transdate', 1);
938
939   AR->ar_transactions(\%myconfig, \%$form);
940
941   $form->{title} = $locale->text('AR Transactions');
942
943   my $report = SL::ReportGenerator->new(\%myconfig, $form);
944
945   @columns =
946     qw(ids transdate id type invnumber ordnumber cusordnumber name netamount tax amount paid
947        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
948        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone payment_terms charts customertype direct_debit dunning_description);
949
950   my $ct_cvar_configs                 = CVar->get_configs('module' => 'CT');
951   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
952   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
953
954   my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
955   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
956
957   my @hidden_variables = map { "l_${_}" } @columns;
958   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber cusordnumber transaction_description notes project_id transdatefrom transdateto duedatefrom duedateto
959                                            employee_id salesman_id business_id parts_partnumber parts_description);
960   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
961
962   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
963
964   my %column_defs = (
965     'ids'                     => { raw_header_data => $::request->presenter->checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
966     'transdate'               => { 'text' => $locale->text('Date'), },
967     'id'                      => { 'text' => $locale->text('ID'), },
968     'type'                    => { 'text' => $locale->text('Type'), },
969     'invnumber'               => { 'text' => $locale->text('Invoice'), },
970     'ordnumber'               => { 'text' => $locale->text('Order'), },
971     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
972     'name'                    => { 'text' => $locale->text('Customer'), },
973     'netamount'               => { 'text' => $locale->text('Amount'), },
974     'tax'                     => { 'text' => $locale->text('Tax'), },
975     'amount'                  => { 'text' => $locale->text('Total'), },
976     'paid'                    => { 'text' => $locale->text('Paid'), },
977     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
978     'due'                     => { 'text' => $locale->text('Amount Due'), },
979     'duedate'                 => { 'text' => $locale->text('Due Date'), },
980     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
981     'notes'                   => { 'text' => $locale->text('Notes'), },
982     'salesman'                => { 'text' => $locale->text('Salesperson'), },
983     'employee'                => { 'text' => $locale->text('Employee'), },
984     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
985     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
986     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
987     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
988     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
989     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
990     'country'                 => { 'text' => $locale->text('Country'), },
991     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
992     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
993     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
994     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
995     'customertype'            => { 'text' => $locale->text('Customer type'), },
996     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
997     dunning_description       => { 'text' => $locale->text('Dunning level'), },
998     %column_defs_cvars,
999   );
1000
1001   foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
1002     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1003     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1004   }
1005
1006   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1007
1008   $form->{"l_type"} = "Y";
1009   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1010
1011   $column_defs{ids}->{visible} = 'HTML';
1012
1013   $report->set_columns(%column_defs);
1014   $report->set_column_order(@columns);
1015
1016   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
1017
1018   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1019
1020   CVar->add_custom_variables_to_report('module'         => 'CT',
1021                                        'trans_id_field' => 'customer_id',
1022                                        'configs'        => $ct_cvar_configs,
1023                                        'column_defs'    => \%column_defs,
1024                                        'data'           => $form->{AR});
1025
1026   my @options;
1027   if ($form->{customer}) {
1028     push @options, $locale->text('Customer') . " : $form->{customer}";
1029   }
1030   if ($form->{cp_name}) {
1031     push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
1032   }
1033   if ($form->{department}) {
1034     my ($department) = split /--/, $form->{department};
1035     push @options, $locale->text('Department') . " : $department";
1036   }
1037   if ($form->{department_id}) {
1038     push @options, $locale->text('Department Id') . " : $form->{department_id}";
1039   }
1040   if ($form->{invnumber}) {
1041     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1042   }
1043   if ($form->{ordnumber}) {
1044     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1045   }
1046   if ($form->{cusordnumber}) {
1047     push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
1048   }
1049   if ($form->{notes}) {
1050     push @options, $locale->text('Notes') . " : $form->{notes}";
1051   }
1052   if ($form->{transaction_description}) {
1053     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1054   }
1055   if ($form->{parts_partnumber}) {
1056     push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
1057   }
1058   if ($form->{parts_description}) {
1059     push @options, $locale->text('Part Description') . " : $form->{parts_description}";
1060   }
1061   if ($form->{transdatefrom}) {
1062     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1063   }
1064   if ($form->{transdateto}) {
1065     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
1066   }
1067   if ($form->{open}) {
1068     push @options, $locale->text('Open');
1069   }
1070   if ($form->{employee_id}) {
1071     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
1072     push @options, $locale->text('Employee') . ' : ' . $employee->name;
1073   }
1074   if ($form->{salesman_id}) {
1075     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1076     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1077   }
1078   if ($form->{closed}) {
1079     push @options, $locale->text('Closed');
1080   }
1081
1082   $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
1083
1084   $report->set_options('top_info_text'        => join("\n", @options),
1085                        'raw_top_info_text'    => $form->parse_html_template('ar/ar_transactions_header'),
1086                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1087                        'output_format'        => 'HTML',
1088                        'title'                => $form->{title},
1089                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1090     );
1091   $report->set_options_from_form();
1092   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1093
1094   # add sort and escape callback, this one we use for the add sub
1095   $form->{callback} = $href .= "&sort=$form->{sort}";
1096
1097   # escape callback for href
1098   $callback = $form->escape($href);
1099
1100   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1101
1102   my %totals    = map { $_ => 0 } @subtotal_columns;
1103   my %subtotals = map { $_ => 0 } @subtotal_columns;
1104
1105   my $idx = 0;
1106
1107   foreach my $ar (@{ $form->{AR} }) {
1108     $ar->{tax} = $ar->{amount} - $ar->{netamount};
1109     $ar->{due} = $ar->{amount} - $ar->{paid};
1110
1111     map { $subtotals{$_} += $ar->{$_};
1112           $totals{$_}    += $ar->{$_} } @subtotal_columns;
1113
1114     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1115     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1116
1117     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1118
1119     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
1120     my $has_storno = $ar->{storno} && !$ar->{storno_id};
1121
1122     $ar->{type} =
1123       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
1124       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
1125       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1126       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
1127                           $locale->text("AR Transaction (abbreviation)");
1128
1129     $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1130
1131     my $row = { };
1132
1133     foreach my $column (@columns) {
1134       $row->{$column} = {
1135         'data'  => $ar->{$column},
1136         'align' => $column_alignment{$column},
1137       };
1138     }
1139
1140     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1141       . "&id=" . E($ar->{id}) . "&callback=${callback}";
1142
1143     $row->{ids} = {
1144       raw_data =>  $::request->presenter->checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
1145       valign   => 'center',
1146       align    => 'center',
1147     };
1148
1149     my $row_set = [ $row ];
1150
1151     if (($form->{l_subtotal} eq 'Y')
1152         && (($idx == (scalar @{ $form->{AR} } - 1))
1153             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1154       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1155     }
1156
1157     $report->add_data($row_set);
1158
1159     $idx++;
1160   }
1161
1162   $report->add_separator();
1163   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1164
1165   $report->generate_with_headers();
1166
1167   $main::lxdebug->leave_sub();
1168 }
1169
1170 sub storno {
1171   $main::lxdebug->enter_sub();
1172
1173   $main::auth->assert('general_ledger');
1174
1175   my $form     = $main::form;
1176   my %myconfig = %main::myconfig;
1177   my $locale   = $main::locale;
1178
1179   # don't cancel cancelled transactions
1180   if (IS->has_storno(\%myconfig, $form, 'ar')) {
1181     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1182     $form->error($locale->text("Transaction has already been cancelled!"));
1183   }
1184
1185   AR->storno($form, \%myconfig, $form->{id});
1186
1187   # saving the history
1188   if(!exists $form->{addition} && $form->{id} ne "") {
1189     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1190     $form->{addition}  = "STORNO";
1191     $form->{what_done} = "invoice";
1192     $form->save_history;
1193   }
1194   # /saving the history
1195
1196   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1197
1198   $main::lxdebug->leave_sub();
1199 }
1200
1201 1;