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