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