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