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