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