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