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