c079b4e75a9ad9734c64ff9a10eb145701146c52
[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     $payment->{selectAR_paid} =
413       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
414                            '-id' => "AR_paid_$i",
415                            '-values' => \@AR_paid_values,
416                            '-labels' => \%chart_labels,
417                            '-default' => $payment->{AR_paid}));
418
419
420
421     $payment->{changeable} =
422         SL::DB::Default->get->payments_changeable == 0 ? !$payment->{acc_trans_id} # never
423       : SL::DB::Default->get->payments_changeable == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
424       :                                                           1;
425
426     push @payments, $payment;
427   }
428
429   $form->{totalpaid} = sum map { $_->{paid} } @payments;
430
431   $form->header;
432   print $::form->parse_html_template('ar/form_header', {
433     paid_missing         => $::form->{invtotal} - $::form->{totalpaid},
434     show_exch            => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
435     payments             => \@payments,
436     transactions         => \@transactions,
437     project_labels       => \%project_labels,
438     rows                 => $rows,
439     ARselected           => $ARselected,
440     title_str            => $title,
441     follow_up_trans_info => $follow_up_trans_info,
442   });
443
444   $main::lxdebug->leave_sub();
445 }
446
447 sub form_footer {
448   $main::lxdebug->enter_sub();
449
450   $main::auth->assert('general_ledger');
451
452   my $form     = $main::form;
453   my %myconfig = %main::myconfig;
454   my $locale   = $main::locale;
455   my $cgi      = $::request->{cgi};
456
457   if ( $form->{id} ) {
458     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
459     if ( @{ $follow_ups} ) {
460       $form->{follow_up_length} = scalar(@{$follow_ups});
461       $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
462     }
463   }
464
465   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
466   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
467
468   $form->{is_closed} = $transdate <= $closedto;
469
470   # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
471   $form->{show_storno_button} =
472     $form->{id} &&
473     !IS->has_storno(\%myconfig, $form, 'ar') &&
474     !IS->is_storno(\%myconfig, $form, 'ar') &&
475     ($form->{totalpaid} == 0 || $form->{totalpaid} eq "");
476
477   $form->{show_mark_as_paid_button} = $form->{id} && $::instance_conf->get_ar_show_mark_as_paid();
478
479   print $::form->parse_html_template('ar/form_footer');
480
481   $main::lxdebug->leave_sub();
482 }
483
484 sub mark_as_paid {
485   $main::lxdebug->enter_sub();
486
487   $main::auth->assert('general_ledger');
488
489   my $form     = $main::form;
490   my %myconfig = %main::myconfig;
491
492   &mark_as_paid_common(\%myconfig,"ar");
493
494   $main::lxdebug->leave_sub();
495 }
496
497 sub update {
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   my $display = shift;
506
507   my ($totaltax, $exchangerate);
508
509   $form->{invtotal} = 0;
510
511   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
512
513   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
514     qw(exchangerate creditlimit creditremaining);
515
516   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
517   my $count = 0;
518   my @a     = ();
519
520   for my $i (1 .. $form->{rowcount}) {
521     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
522     $form->{"tax_$i"} = $form->parse_amount(\%myconfig, $form->{"tax_$i"});
523     if ($form->{"amount_$i"}) {
524       push @a, {};
525       my $j = $#a;
526       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
527       if ($taxkey > 1) {
528         if ($form->{taxincluded}) {
529           $form->{"tax_$i"} = $form->{"amount_$i"} / ($rate + 1) * $rate;
530         } else {
531           $form->{"tax_$i"} = $form->{"amount_$i"} * $rate;
532         }
533       } else {
534         $form->{"tax_$i"} = 0;
535       }
536       $form->{"tax_$i"} = $form->round_amount($form->{"tax_$i"}, 2);
537
538       $totaltax += $form->{"tax_$i"};
539       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
540       $count++;
541     }
542   }
543
544   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
545   $form->{rowcount} = $count + 1;
546   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
547
548   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
549   $form->{exchangerate} = $form->{forex} if $form->{forex};
550
551   $form->{invdate} = $form->{transdate};
552
553   $form->{invdate} = $form->{transdate};
554
555   my %saved_variables = map +( $_ => $form->{$_} ), qw(AR AR_amount_1 taxchart_1 customer_id notes);
556
557   &check_name("customer");
558
559   $form->{AR} = $saved_variables{AR};
560   if ($saved_variables{AR_amount_1} =~ m/.--./) {
561     map { $form->{$_} = $saved_variables{$_} } qw(AR_amount_1 taxchart_1);
562   } else {
563     delete $form->{taxchart_1};
564   }
565
566   $form->{invtotal} =
567     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
568
569   for my $i (1 .. $form->{paidaccounts}) {
570     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
571       map {
572         $form->{"${_}_$i"} =
573           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
574       } qw(paid exchangerate);
575
576       $form->{totalpaid} += $form->{"paid_$i"};
577
578       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
579       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
580     }
581   }
582
583   $form->{creditremaining} -=
584     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
585      $form->{oldinvtotal});
586   $form->{oldinvtotal}  = $form->{invtotal};
587   $form->{oldtotalpaid} = $form->{totalpaid};
588
589   &display_form;
590
591   $main::lxdebug->leave_sub();
592 }
593
594 #
595 # ToDO: fix $closedto and $invdate
596 #
597 sub post_payment {
598   $main::lxdebug->enter_sub();
599
600   $main::auth->assert('general_ledger');
601
602   my $form     = $main::form;
603   my %myconfig = %main::myconfig;
604   my $locale   = $main::locale;
605
606   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
607
608   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
609
610   for my $i (1 .. $form->{paidaccounts}) {
611
612     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
613       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
614
615       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
616
617       $form->error($locale->text('Cannot post payment for a closed period!')) if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
618
619       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
620 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
621         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
622       }
623     }
624   }
625
626   ($form->{AR})      = split /--/, $form->{AR};
627   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
628   $form->redirect($locale->text('Payment posted!')) if (AR->post_payment(\%myconfig, \%$form));
629   $form->error($locale->text('Cannot post payment!'));
630
631   $main::lxdebug->leave_sub();
632 }
633
634 sub _post {
635
636   $main::auth->assert('general_ledger');
637
638   my $form     = $main::form;
639
640   # inline post
641   post(1);
642 }
643
644 sub post {
645   $main::lxdebug->enter_sub();
646
647   $main::auth->assert('general_ledger');
648
649   my $form     = $main::form;
650   my %myconfig = %main::myconfig;
651   my $locale   = $main::locale;
652
653   my ($inline) = @_;
654
655   my ($datepaid);
656
657   # check if there is an invoice number, invoice and due date
658   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
659   $form->isblank("duedate",   $locale->text('Due Date missing!'));
660   $form->isblank("customer",  $locale->text('Customer missing!'));
661
662   if ($myconfig{mandatory_departments} && !$form->{department}) {
663     $form->{saved_message} = $::locale->text('You have to specify a department.');
664     update();
665     exit;
666   }
667
668   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
669   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
670
671   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
672     if ($form->date_max_future($transdate, \%myconfig));
673   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
674
675   $form->error($locale->text('Zero amount posting!'))
676     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
677
678   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
679     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
680
681   delete($form->{AR});
682
683   for my $i (1 .. $form->{paidaccounts}) {
684     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
685       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
686
687       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
688
689       $form->error($locale->text('Cannot post payment for a closed period!'))
690         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
691
692       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
693         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
694         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
695       }
696     }
697   }
698
699   # if oldcustomer ne customer redo form
700   my ($customer) = split /--/, $form->{customer};
701   if ($form->{oldcustomer} ne "$customer--$form->{customer_id}") {
702     update();
703     ::end_of_request();
704   }
705
706   $form->{AR}{receivables} = $form->{ARselected};
707   $form->{storno}          = 0;
708
709   $form->{id} = 0 if $form->{postasnew};
710   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
711
712   # saving the history
713   if(!exists $form->{addition} && $form->{id} ne "") {
714     $form->{snumbers} = "invnumber_$form->{invnumber}";
715     $form->{addition} = "POSTED";
716     $form->save_history;
717   }
718   # /saving the history
719   remove_draft() if $form->{remove_draft};
720
721   $form->redirect($locale->text('Transaction posted!')) unless $inline;
722
723   $main::lxdebug->leave_sub();
724 }
725
726 sub post_as_new {
727   $main::lxdebug->enter_sub();
728
729   $main::auth->assert('general_ledger');
730
731   my $form     = $main::form;
732   my %myconfig = %main::myconfig;
733
734   $form->{postasnew} = 1;
735   # saving the history
736   if(!exists $form->{addition} && $form->{id} ne "") {
737     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
738     $form->{addition} = "POSTED AS NEW";
739     $form->save_history;
740   }
741   # /saving the history
742   &post;
743
744   $main::lxdebug->leave_sub();
745 }
746
747 sub use_as_new {
748   $main::lxdebug->enter_sub();
749
750   $main::auth->assert('general_ledger');
751
752   my $form     = $main::form;
753   my %myconfig = %main::myconfig;
754
755   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);
756   $form->{paidaccounts} = 1;
757   $form->{rowcount}--;
758   $form->{invdate} = $form->current_date(\%myconfig);
759   &update;
760
761   $main::lxdebug->leave_sub();
762 }
763
764 sub delete {
765   $main::lxdebug->enter_sub();
766
767   $main::auth->assert('general_ledger');
768
769   my $form     = $main::form;
770   my $locale   = $main::locale;
771
772   $form->{title} = $locale->text('Confirm!');
773
774   $form->header;
775
776   delete $form->{header};
777
778   print qq|
779 <form method=post action=$form->{script}>
780 |;
781
782   foreach my $key (keys %$form) {
783     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
784     $form->{$key} =~ s/\"/&quot;/g;
785     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
786   }
787
788   print qq|
789 <h2 class=confirm>$form->{title}</h2>
790
791 <h4>|
792     . $locale->text('Are you sure you want to delete Transaction')
793     . qq| $form->{invnumber}</h4>
794
795 <input name=action class=submit type=submit value="|
796     . $locale->text('Yes') . qq|">
797 </form>
798 |;
799
800   $main::lxdebug->leave_sub();
801 }
802
803 sub yes {
804   $main::lxdebug->enter_sub();
805
806   $main::auth->assert('general_ledger');
807
808   my $form     = $main::form;
809   my %myconfig = %main::myconfig;
810   my $locale   = $main::locale;
811
812   if (AR->delete_transaction(\%myconfig, \%$form)) {
813     # saving the history
814     if(!exists $form->{addition}) {
815       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
816       $form->{addition} = "DELETED";
817       $form->save_history;
818     }
819     # /saving the history
820     $form->redirect($locale->text('Transaction deleted!'));
821   }
822   $form->error($locale->text('Cannot delete transaction!'));
823
824   $main::lxdebug->leave_sub();
825 }
826
827 sub search {
828   $main::lxdebug->enter_sub();
829
830   $main::auth->assert('general_ledger | invoice_edit');
831
832   my $form     = $main::form;
833   my %myconfig = %main::myconfig;
834   my $locale   = $main::locale;
835   my $cgi      = $::request->{cgi};
836
837   my ($customer, $department);
838   my ($jsscript, $button1, $button2);
839
840   # setup customer selection
841   $form->all_vc(\%myconfig, "customer", "AR");
842
843   $form->{title}    = $locale->text('AR Transactions');
844   $form->{jsscript} = 1;
845
846   # Auch in Rechnungsübersicht nach Kundentyp filtern - jan
847   $form->get_lists("projects"       => { "key" => "ALL_PROJECTS", "all" => 1 },
848                    "departments"    => "ALL_DEPARTMENTS",
849                    "customers"      => "ALL_VC",
850                    "business_types" => "ALL_BUSINESS_TYPES");
851   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
852   $form->{SHOW_BUSINESS_TYPES} = scalar @{ $form->{ALL_BUSINESS_TYPES} } > 0;
853
854   # constants and subs for template
855   $form->{jsscript}  = 1;
856   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
857
858   $form->header;
859   print $form->parse_html_template('ar/search', { %myconfig });
860
861   $main::lxdebug->leave_sub();
862 }
863
864 sub create_subtotal_row {
865   $main::lxdebug->enter_sub();
866
867   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
868
869   my $form     = $main::form;
870   my %myconfig = %main::myconfig;
871
872   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
873
874   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
875
876   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
877
878   map { $totals->{$_} = 0 } @{ $subtotal_columns };
879
880   $main::lxdebug->leave_sub();
881
882   return $row;
883 }
884
885 sub ar_transactions {
886   $main::lxdebug->enter_sub();
887
888   $main::auth->assert('general_ledger | invoice_edit');
889
890   my $form     = $main::form;
891   my %myconfig = %main::myconfig;
892   my $locale   = $main::locale;
893
894   my ($callback, $href, @columns);
895
896   ($form->{customer}, $form->{customer_id}) = split(/--/, $form->{customer});
897
898   report_generator_set_default_sort('transdate', 1);
899
900   AR->ar_transactions(\%myconfig, \%$form);
901
902   $form->{title} = $locale->text('AR Transactions');
903
904   my $report = SL::ReportGenerator->new(\%myconfig, $form);
905
906   @columns =
907     qw(transdate id type invnumber ordnumber name netamount tax amount paid
908        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
909        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone payment_terms charts customertype);
910
911   my @hidden_variables = map { "l_${_}" } @columns;
912   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber transaction_description notes project_id transdatefrom transdateto employee_id salesman_id business_id);
913
914   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
915
916   my %column_defs = (
917     'transdate'               => { 'text' => $locale->text('Date'), },
918     'id'                      => { 'text' => $locale->text('ID'), },
919     'type'                    => { 'text' => $locale->text('Type'), },
920     'invnumber'               => { 'text' => $locale->text('Invoice'), },
921     'ordnumber'               => { 'text' => $locale->text('Order'), },
922     'name'                    => { 'text' => $locale->text('Customer'), },
923     'netamount'               => { 'text' => $locale->text('Amount'), },
924     'tax'                     => { 'text' => $locale->text('Tax'), },
925     'amount'                  => { 'text' => $locale->text('Total'), },
926     'paid'                    => { 'text' => $locale->text('Paid'), },
927     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
928     'due'                     => { 'text' => $locale->text('Amount Due'), },
929     'duedate'                 => { 'text' => $locale->text('Due Date'), },
930     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
931     'notes'                   => { 'text' => $locale->text('Notes'), },
932     'salesman'                => { 'text' => $locale->text('Salesperson'), },
933     'employee'                => { 'text' => $locale->text('Employee'), },
934     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
935     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
936     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
937     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
938     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
939     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
940     'country'                 => { 'text' => $locale->text('Country'), },
941     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
942     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
943     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
944     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
945     'customertype'            => { 'text' => $locale->text('Customer type'), },
946   );
947
948   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description)) {
949     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
950     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
951   }
952
953   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
954
955   $form->{"l_type"} = "Y";
956   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
957
958   $report->set_columns(%column_defs);
959   $report->set_column_order(@columns);
960
961   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
962
963   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
964
965   my @options;
966   if ($form->{customer}) {
967     push @options, $locale->text('Customer') . " : $form->{customer}";
968   }
969   if ($form->{department}) {
970     my ($department) = split /--/, $form->{department};
971     push @options, $locale->text('Department') . " : $department";
972   }
973   if ($form->{department_id}) {
974     push @options, $locale->text('Department Id') . " : $form->{department_id}";
975   }
976   if ($form->{invnumber}) {
977     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
978   }
979   if ($form->{ordnumber}) {
980     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
981   }
982   if ($form->{notes}) {
983     push @options, $locale->text('Notes') . " : $form->{notes}";
984   }
985   if ($form->{transaction_description}) {
986     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
987   }
988   if ($form->{transdatefrom}) {
989     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
990   }
991   if ($form->{transdateto}) {
992     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
993   }
994   if ($form->{open}) {
995     push @options, $locale->text('Open');
996   }
997   if ($form->{employee_id}) {
998     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
999     push @options, $locale->text('Employee') . ' : ' . $employee->name;
1000   }
1001   if ($form->{salesman_id}) {
1002     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1003     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1004   }
1005   if ($form->{closed}) {
1006     push @options, $locale->text('Closed');
1007   }
1008
1009   $report->set_options('top_info_text'        => join("\n", @options),
1010                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1011                        'output_format'        => 'HTML',
1012                        'title'                => $form->{title},
1013                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1014     );
1015   $report->set_options_from_form();
1016   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1017
1018   # add sort and escape callback, this one we use for the add sub
1019   $form->{callback} = $href .= "&sort=$form->{sort}";
1020
1021   # escape callback for href
1022   $callback = $form->escape($href);
1023
1024   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1025
1026   my %totals    = map { $_ => 0 } @subtotal_columns;
1027   my %subtotals = map { $_ => 0 } @subtotal_columns;
1028
1029   my $idx = 0;
1030
1031   foreach my $ar (@{ $form->{AR} }) {
1032     $ar->{tax} = $ar->{amount} - $ar->{netamount};
1033     $ar->{due} = $ar->{amount} - $ar->{paid};
1034
1035     map { $subtotals{$_} += $ar->{$_};
1036           $totals{$_}    += $ar->{$_} } @subtotal_columns;
1037
1038     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1039     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1040
1041     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1042
1043     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
1044     my $has_storno = $ar->{storno} && !$ar->{storno_id};
1045
1046     $ar->{type} =
1047       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
1048       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
1049       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1050       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
1051                           $locale->text("AR Transaction (abbreviation)");
1052
1053     my $row = { };
1054
1055     foreach my $column (@columns) {
1056       $row->{$column} = {
1057         'data'  => $ar->{$column},
1058         'align' => $column_alignment{$column},
1059       };
1060     }
1061
1062     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1063       . "&id=" . E($ar->{id}) . "&callback=${callback}";
1064
1065     my $row_set = [ $row ];
1066
1067     if (($form->{l_subtotal} eq 'Y')
1068         && (($idx == (scalar @{ $form->{AR} } - 1))
1069             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1070       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1071     }
1072
1073     $report->add_data($row_set);
1074
1075     $idx++;
1076   }
1077
1078   $report->add_separator();
1079   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1080
1081   $report->generate_with_headers();
1082
1083   $main::lxdebug->leave_sub();
1084 }
1085
1086 sub storno {
1087   $main::lxdebug->enter_sub();
1088
1089   $main::auth->assert('general_ledger');
1090
1091   my $form     = $main::form;
1092   my %myconfig = %main::myconfig;
1093   my $locale   = $main::locale;
1094
1095   # don't cancel cancelled transactions
1096   if (IS->has_storno(\%myconfig, $form, 'ar')) {
1097     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1098     $form->error($locale->text("Transaction has already been cancelled!"));
1099   }
1100
1101   AR->storno($form, \%myconfig, $form->{id});
1102
1103   # saving the history
1104   if(!exists $form->{addition} && $form->{id} ne "") {
1105     $form->{snumbers} = "ordnumber_$form->{ordnumber}";
1106     $form->{addition} = "STORNO";
1107     $form->save_history;
1108   }
1109   # /saving the history
1110
1111   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1112
1113   $main::lxdebug->leave_sub();
1114 }
1115
1116 1;