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