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