1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
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.
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,
29 #======================================================================
31 # Accounts Receivables
33 #======================================================================
35 use POSIX qw(strftime);
36 use List::Util qw(sum first max);
37 use List::UtilsBy qw(sort_by);
40 use SL::Controller::Base;
50 use SL::DB::RecordTemplate;
52 use SL::Helper::Flash qw(flash);
53 use SL::ReportGenerator;
55 require "bin/mozilla/common.pl";
56 require "bin/mozilla/reportgenerator.pl";
61 # this is for our long dates
62 # $locale->text('January')
63 # $locale->text('February')
64 # $locale->text('March')
65 # $locale->text('April')
66 # $locale->text('May ')
67 # $locale->text('June')
68 # $locale->text('July')
69 # $locale->text('August')
70 # $locale->text('September')
71 # $locale->text('October')
72 # $locale->text('November')
73 # $locale->text('December')
75 # this is for our short month
76 # $locale->text('Jan')
77 # $locale->text('Feb')
78 # $locale->text('Mar')
79 # $locale->text('Apr')
80 # $locale->text('May')
81 # $locale->text('Jun')
82 # $locale->text('Jul')
83 # $locale->text('Aug')
84 # $locale->text('Sep')
85 # $locale->text('Oct')
86 # $locale->text('Nov')
87 # $locale->text('Dec')
89 sub load_record_template {
90 $::auth->assert('ar_transactions');
92 # Load existing template and verify that its one for this module.
93 my $template = SL::DB::RecordTemplate
94 ->new(id => $::form->{id})
96 with_object => [ qw(customer payment currency record_items record_items.chart) ],
99 die "invalid template type" unless $template->template_type eq 'ar_transaction';
101 $template->substitute_variables;
103 # Clean the current $::form before rebuilding it from the template.
104 my $form_defaults = delete $::form->{form_defaults};
105 delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
107 # Fill $::form from the template.
108 my $today = DateTime->today_local;
109 $::form->{title} = "Add";
110 $::form->{currency} = $template->currency->name;
111 $::form->{direct_debit} = $template->direct_debit;
112 $::form->{globalproject_id} = $template->project_id;
113 $::form->{AR_chart_id} = $template->ar_ap_chart_id;
114 $::form->{transdate} = $today->to_kivitendo;
115 $::form->{duedate} = $today->to_kivitendo;
116 $::form->{rowcount} = @{ $template->items };
117 $::form->{paidaccounts} = 1;
118 $::form->{$_} = $template->$_ for qw(department_id ordnumber taxincluded employee_id notes);
120 if ($template->customer) {
121 $::form->{customer_id} = $template->customer_id;
122 $::form->{customer} = $template->customer->name;
123 $::form->{duedate} = $template->customer->payment->calc_date(reference_date => $today)->to_kivitendo if $template->customer->payment;
127 foreach my $item (@{ $template->items }) {
130 my $active_taxkey = $item->chart->get_active_taxkey;
131 my $taxes = SL::DB::Manager::Tax->get_all(
132 where => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
133 sort_by => 'taxkey, rate',
136 my $tax = first { $item->tax_id == $_->id } @{ $taxes };
137 $tax //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
138 $tax //= $taxes->[0];
145 $::form->{"AR_amount_chart_id_${row}"} = $item->chart_id;
146 $::form->{"previous_AR_amount_chart_id_${row}"} = $item->chart_id;
147 $::form->{"amount_${row}"} = $::form->format_amount(\%::myconfig, $item->amount1, 2);
148 $::form->{"taxchart_${row}"} = $item->tax_id . '--' . $tax->rate;
149 $::form->{"project_id_${row}"} = $item->project_id;
152 $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
154 flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
157 keep_rows_without_amount => 1,
158 dont_add_new_row => 1,
162 sub save_record_template {
163 $::auth->assert('ar_transactions');
165 my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
166 my $js = SL::ClientJS->new(controller => SL::Controller::Base->new);
167 my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
169 $js->dialog->close('#record_template_dialog');
172 $_->{chart_id} && (($_->{tax_id} // '') ne '')
174 +{ chart_id => $::form->{"AR_amount_chart_id_${_}"},
175 amount1 => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
176 tax_id => (split m{--}, $::form->{"taxchart_${_}"})[0],
177 project_id => $::form->{"project_id_${_}"} || undef,
179 } (1..($::form->{rowcount} || 1));
181 $template->assign_attributes(
182 template_type => 'ar_transaction',
183 template_name => $new_name,
185 currency_id => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
186 ar_ap_chart_id => $::form->{AR_chart_id} || undef,
187 customer_id => $::form->{customer_id} || undef,
188 department_id => $::form->{department_id} || undef,
189 project_id => $::form->{globalproject_id} || undef,
190 employee_id => $::form->{employee_id} || undef,
191 taxincluded => $::form->{taxincluded} ? 1 : 0,
192 direct_debit => $::form->{direct_debit} ? 1 : 0,
193 ordnumber => $::form->{ordnumber},
194 notes => $::form->{notes},
204 ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
209 ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
214 $main::lxdebug->enter_sub();
216 $main::auth->assert('ar_transactions');
218 my $form = $main::form;
219 my %myconfig = %main::myconfig;
222 if(!exists $form->{addition} && ($form->{id} ne "")) {
223 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
224 $form->{addition} = "ADDED";
227 # /saving the history
229 $form->{title} = "Add";
230 $form->{callback} = "ar.pl?action=add" unless $form->{callback};
232 AR->get_transdate(\%myconfig, $form);
233 $form->{initial_transdate} = $form->{transdate};
234 create_links(dont_save => 1);
235 $form->{transdate} = $form->{initial_transdate};
237 if ($form->{customer_id}) {
238 my $last_used_ar_chart = SL::DB::Customer->load_cached($form->{customer_id})->last_used_ar_chart;
239 $form->{"AR_amount_chart_id_1"} = $last_used_ar_chart->id if $last_used_ar_chart;
243 $main::lxdebug->leave_sub();
247 $main::lxdebug->enter_sub();
249 $main::auth->assert('ar_transactions');
251 my $form = $main::form;
253 # show history button
254 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
255 #/show hhistory button
256 $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
257 $form->{title} = "Edit";
262 $main::lxdebug->leave_sub();
266 $main::lxdebug->enter_sub();
268 $main::auth->assert('ar_transactions');
270 my $form = $main::form;
275 $main::lxdebug->leave_sub();
278 sub _retrieve_invoice_object {
279 return undef if !$::form->{id};
280 return $::form->{invoice_obj} if $::form->{invoice_obj} && $::form->{invoice_obj}->id == $::form->{id};
281 return SL::DB::Invoice->new(id => $::form->{id})->load;
285 $main::lxdebug->enter_sub();
287 $main::auth->assert('ar_transactions');
290 my $form = $main::form;
291 my %myconfig = %main::myconfig;
293 $form->create_links("AR", \%myconfig, "customer");
294 $form->{invoice_obj} = _retrieve_invoice_object();
297 if (!$params{dont_save}) {
298 %saved = map { ($_ => $form->{$_}) } qw(direct_debit id taxincluded);
299 $saved{duedate} = $form->{duedate} if $form->{duedate};
300 $saved{currency} = $form->{currency} if $form->{currency};
303 IS->get_customer(\%myconfig, \%$form);
305 $form->{$_} = $saved{$_} for keys %saved;
306 $form->{rowcount} = 1;
307 $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};
310 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
312 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
314 # build the popup menus
315 $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
317 AR->setup_form($form);
320 ($form->datetonum($form->{transdate}, \%myconfig) <=
321 $form->datetonum($form->{closedto}, \%myconfig));
323 $main::lxdebug->leave_sub();
327 $main::lxdebug->enter_sub();
329 $main::auth->assert('ar_transactions');
331 my $form = $main::form;
332 my %myconfig = %main::myconfig;
333 my $locale = $main::locale;
334 my $cgi = $::request->{cgi};
336 $form->{invoice_obj} = _retrieve_invoice_object();
338 my ($title, $readonly, $exchangerate, $rows);
339 my ($notes, $amount, $project);
341 $form->{initial_focus} = !($form->{amount_1} * 1) ? 'customer_id' : 'row_' . $form->{rowcount};
343 $title = $form->{title};
344 # $locale->text('Add Accounts Receivables Transaction')
345 # $locale->text('Edit Accounts Receivables Transaction')
346 $form->{title} = $locale->text("$title Accounts Receivables Transaction");
348 $readonly = ($form->{id}) ? "readonly" : "";
350 $form->{radier} = ($::instance_conf->get_ar_changeable == 2)
351 ? ($form->current_date(\%myconfig) eq $form->{gldate})
352 : ($::instance_conf->get_ar_changeable == 1);
353 $readonly = ($form->{radier}) ? "" : $readonly;
355 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
356 $form->{exchangerate} = $form->{forex} if $form->{forex};
358 # format exchangerate
359 $form->{exchangerate} = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
361 $rows = max 2, $form->numtextrows($form->{notes}, 50);
363 my @old_project_ids = grep { $_ } map { $form->{"project_id_$_"} } 1..$form->{rowcount};
365 $form->get_lists("projects" => { "key" => "ALL_PROJECTS",
367 "old_id" => \@old_project_ids },
368 "charts" => { "key" => "ALL_CHARTS",
369 "transdate" => $form->{transdate} },
370 "taxcharts" => { "key" => "ALL_TAXCHARTS",
371 "module" => "AR" },);
373 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
375 $_->{link_split} = { map { $_ => 1 } split/:/, $_->{link} } for @{ $form->{ALL_CHARTS} };
377 my %project_labels = map { $_->{id} => $_->{projectnumber} } @{ $form->{"ALL_PROJECTS"} };
379 my (@AR_paid_values, %AR_paid_labels);
380 my $default_ar_amount_chart_id;
382 foreach my $item (@{ $form->{ALL_CHARTS} }) {
383 if ($item->{link_split}{AR_amount}) {
384 $default_ar_amount_chart_id //= $item->{id};
386 } elsif ($item->{link_split}{AR_paid}) {
387 push(@AR_paid_values, $item->{accno});
388 $AR_paid_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
392 my $follow_up_vc = $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id})->name : '';
393 my $follow_up_trans_info = "$form->{invnumber} ($follow_up_vc)";
395 $::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", "kivi.File.js", "kivi.RecordTemplate.js");
397 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
401 for my $i (1 .. $form->{rowcount}) {
403 amount => $form->{"amount_$i"},
404 tax => $form->{"tax_$i"},
405 project_id => ($i==$form->{rowcount}) ? $form->{globalproject_id} : $form->{"project_id_$i"},
408 my (%taxchart_labels, @taxchart_values, $default_taxchart, $taxchart_to_use);
409 my $amount_chart_id = $form->{"AR_amount_chart_id_$i"} // $default_ar_amount_chart_id;
410 my $chart_has_changed = $::form->{"previous_AR_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AR_amount_chart_id_$i"});
412 foreach my $item ( GL->get_active_taxes_for_chart($amount_chart_id, $transdate) ) {
413 my $key = $item->id . "--" . $item->rate;
414 $first_taxchart //= $item;
415 $default_taxchart = $item if $item->{is_default};
416 $taxchart_to_use = $item if $key eq $form->{"taxchart_$i"};
418 push(@taxchart_values, $key);
419 $taxchart_labels{$key} = $item->taxdescription . " " . $item->rate * 100 . ' %';
422 $taxchart_to_use = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
423 my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
425 $transaction->{selectAR_amount} =
426 $::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" : ""))
427 . $::request->presenter->hidden_tag("previous_AR_amount_chart_id_$i", $amount_chart_id);
429 $transaction->{taxchart} =
430 NTI($cgi->popup_menu('-name' => "taxchart_$i",
431 '-id' => "taxchart_$i",
432 '-style' => 'width:200px',
433 '-values' => \@taxchart_values,
434 '-labels' => \%taxchart_labels,
435 '-default' => $selected_taxchart));
437 push @transactions, $transaction;
440 $form->{invtotal_unformatted} = $form->{invtotal};
442 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
444 my $now = $form->current_date(\%myconfig);
447 for my $i (1 .. $form->{paidaccounts}) {
449 paid => $form->{"paid_$i"},
450 exchangerate => $form->{"exchangerate_$i"} || '',
451 gldate => $form->{"gldate_$i"},
452 acc_trans_id => $form->{"acc_trans_id_$i"},
453 source => $form->{"source_$i"},
454 memo => $form->{"memo_$i"},
455 AR_paid => $form->{"AR_paid_$i"},
456 forex => $form->{"forex_$i"},
457 datepaid => $form->{"datepaid_$i"},
458 paid_project_id => $form->{"paid_project_id_$i"},
459 gldate => $form->{"gldate_$i"},
462 # default account for current assets (i.e. 1801 - SKR04) if no account is selected
463 $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
465 $payment->{selectAR_paid} =
466 NTI($cgi->popup_menu('-name' => "AR_paid_$i",
467 '-id' => "AR_paid_$i",
468 '-values' => \@AR_paid_values,
469 '-labels' => \%AR_paid_labels,
470 '-default' => $payment->{AR_paid} || $form->{accno_arap}));
474 $payment->{changeable} =
475 SL::DB::Default->get->payments_changeable == 0 ? !$payment->{acc_trans_id} # never
476 : SL::DB::Default->get->payments_changeable == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
479 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
480 if ($form->date_closed($payment->{"gldate_$i"})) {
481 $payment->{changeable} = 0;
484 push @payments, $payment;
487 my @empty = grep { $_->{paid} eq '' } @payments;
489 (sort_by { DateTime->from_kivitendo($_->{datepaid}) } grep { $_->{paid} ne '' } @payments),
493 $form->{totalpaid} = sum map { $_->{paid} } @payments;
495 my $employees = SL::DB::Manager::Employee->get_all_sorted(
498 (id => $::form->{employee_id}) x !!$::form->{employee_id},
506 print $::form->parse_html_template('ar/form_header', {
507 paid_missing => $::form->{invtotal} - $::form->{totalpaid},
508 show_exch => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
509 payments => \@payments,
510 transactions => \@transactions,
511 project_labels => \%project_labels,
513 AR_chart_id => $form->{AR_chart_id},
515 follow_up_trans_info => $follow_up_trans_info,
516 today => DateTime->today,
517 currencies => scalar(SL::DB::Manager::Currency->get_all_sorted),
518 employees => $employees,
521 $main::lxdebug->leave_sub();
525 $main::lxdebug->enter_sub();
527 $main::auth->assert('ar_transactions');
529 my $form = $main::form;
530 my %myconfig = %main::myconfig;
531 my $locale = $main::locale;
532 my $cgi = $::request->{cgi};
535 my $follow_ups = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1);
536 if ( @{ $follow_ups} ) {
537 $form->{follow_up_length} = scalar(@{$follow_ups});
538 $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
542 my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
543 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
545 $form->{is_closed} = $transdate <= $closedto;
547 # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
548 $form->{show_storno_button} =
550 !IS->has_storno(\%myconfig, $form, 'ar') &&
551 !IS->is_storno(\%myconfig, $form, 'ar') &&
552 ($form->{totalpaid} == 0 || $form->{totalpaid} eq "");
554 $form->{show_mark_as_paid_button} = $form->{id} && $::instance_conf->get_ar_show_mark_as_paid();
556 print $::form->parse_html_template('ar/form_footer');
558 $main::lxdebug->leave_sub();
562 $::auth->assert('ar_transactions');
564 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
566 $::form->redirect($::locale->text("Marked as paid"));
570 $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
571 $::form->{gldate} = $::form->{transdate} if !$::form->{gldate};
577 $main::lxdebug->enter_sub();
579 $main::auth->assert('ar_transactions');
581 my $form = $main::form;
582 my %myconfig = %main::myconfig;
586 my ($totaltax, $exchangerate);
588 $form->{invtotal} = 0;
590 delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
592 map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
593 qw(exchangerate creditlimit creditremaining);
595 my @flds = qw(amount AR_amount projectnumber oldprojectnumber project_id);
599 for my $i (1 .. $form->{rowcount}) {
600 $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
601 if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
604 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
607 ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
609 $totaltax += $form->{"tax_$i"};
610 map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
615 $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
616 $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
617 map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
619 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
620 $form->{exchangerate} = $form->{forex} if $form->{forex};
622 $form->{invdate} = $form->{transdate};
624 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
625 IS->get_customer(\%myconfig, $form);
629 ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
631 for my $i (1 .. $form->{paidaccounts}) {
632 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
635 $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
636 } qw(paid exchangerate);
638 $form->{totalpaid} += $form->{"paid_$i"};
640 $form->{"forex_$i"} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
641 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
645 $form->{creditremaining} -=
646 ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
647 $form->{oldinvtotal});
648 $form->{oldinvtotal} = $form->{invtotal};
649 $form->{oldtotalpaid} = $form->{totalpaid};
653 $main::lxdebug->leave_sub();
657 # ToDO: fix $closedto and $invdate
660 $main::lxdebug->enter_sub();
662 $main::auth->assert('ar_transactions');
664 my $form = $main::form;
665 my %myconfig = %main::myconfig;
666 my $locale = $main::locale;
668 $form->mtime_ischanged('ar');
669 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
671 my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
673 for my $i (1 .. $form->{paidaccounts}) {
675 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
676 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
678 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
680 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
681 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
683 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
684 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
685 $form->error($locale->text('Cannot post payment for a closed period!'))
686 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
688 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
689 # $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
690 $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
695 ($form->{AR}) = split /--/, $form->{AR};
696 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
697 if (AR->post_payment(\%myconfig, \%$form)) {
698 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
699 $form->{what_done} = 'invoice';
700 $form->{addition} = "PAYMENT POSTED";
702 $form->redirect($locale->text('Payment posted!'))
704 $form->error($locale->text('Cannot post payment!'));
707 $main::lxdebug->leave_sub();
712 $main::auth->assert('ar_transactions');
714 my $form = $main::form;
721 $main::lxdebug->enter_sub();
723 $main::auth->assert('ar_transactions');
725 my $form = $main::form;
726 my %myconfig = %main::myconfig;
727 my $locale = $main::locale;
731 $form->mtime_ischanged('ar');
735 # check if there is an invoice number, invoice and due date
736 $form->isblank("transdate", $locale->text('Invoice Date missing!'));
737 $form->isblank("duedate", $locale->text('Due Date missing!'));
738 $form->isblank("customer_id", $locale->text('Customer missing!'));
740 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
741 $form->{saved_message} = $::locale->text('You have to specify a department.');
746 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
747 my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
749 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
750 if ($form->date_max_future($transdate, \%myconfig));
752 $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
754 $form->error($locale->text('Zero amount posting!'))
755 unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
757 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
758 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
762 for my $i (1 .. $form->{paidaccounts}) {
763 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
764 $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
766 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
768 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
769 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
771 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
772 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
773 $form->error($locale->text('Cannot post payment for a closed period!'))
774 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
776 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
777 $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
778 $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
783 # if oldcustomer ne customer redo form
784 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
786 $::dispatcher->end_request;
789 $form->{AR}{receivables} = $form->{ARselected};
792 $form->{id} = 0 if $form->{postasnew};
793 $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
796 if(!exists $form->{addition} && $form->{id} ne "") {
797 $form->{snumbers} = "invnumber_$form->{invnumber}";
798 $form->{what_done} = "invoice";
799 $form->{addition} = "POSTED";
802 # /saving the history
804 $form->redirect($locale->text("AR transaction posted.")) unless $inline;
806 $main::lxdebug->leave_sub();
810 $main::lxdebug->enter_sub();
812 $main::auth->assert('ar_transactions');
814 my $form = $main::form;
815 my %myconfig = %main::myconfig;
817 $form->{postasnew} = 1;
819 if(!exists $form->{addition} && $form->{id} ne "") {
820 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
821 $form->{what_done} = "invoice";
822 $form->{addition} = "POSTED AS NEW";
825 # /saving the history
828 $main::lxdebug->leave_sub();
832 $main::lxdebug->enter_sub();
834 $main::auth->assert('ar_transactions');
836 my $form = $main::form;
837 my %myconfig = %main::myconfig;
839 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);
840 $form->{paidaccounts} = 1;
842 $form->{invdate} = $form->current_date(\%myconfig);
845 $main::lxdebug->leave_sub();
849 $main::lxdebug->enter_sub();
851 $main::auth->assert('ar_transactions');
853 my $form = $main::form;
854 my $locale = $main::locale;
856 $form->{title} = $locale->text('Confirm!');
860 delete $form->{header};
863 <form method=post action=$form->{script}>
866 foreach my $key (keys %$form) {
867 next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
868 $form->{$key} =~ s/\"/"/g;
869 print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
873 <h2 class=confirm>$form->{title}</h2>
876 . $locale->text('Are you sure you want to delete Transaction')
877 . qq| $form->{invnumber}</h4>
879 <input name=action class=submit type=submit value="|
880 . $locale->text('Yes') . qq|">
884 $main::lxdebug->leave_sub();
888 $main::lxdebug->enter_sub();
890 $main::auth->assert('ar_transactions');
892 my $form = $main::form;
893 my %myconfig = %main::myconfig;
894 my $locale = $main::locale;
896 if (AR->delete_transaction(\%myconfig, \%$form)) {
898 if(!exists $form->{addition}) {
899 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
900 $form->{what_done} = "invoice";
901 $form->{addition} = "DELETED";
904 # /saving the history
905 $form->redirect($locale->text('Transaction deleted!'));
907 $form->error($locale->text('Cannot delete transaction!'));
909 $main::lxdebug->leave_sub();
912 sub setup_ar_search_action_bar {
915 for my $bar ($::request->layout->get('actionbar')) {
918 $::locale->text('Search'),
919 submit => [ '#form' ],
920 accesskey => 'enter',
926 sub setup_ar_transactions_action_bar {
929 for my $bar ($::request->layout->get('actionbar')) {
932 $::locale->text('Print'),
933 call => [ 'kivi.MassInvoiceCreatePrint.showMassPrintOptionsOrDownloadDirectly' ],
934 disabled => !$params{num_rows} ? $::locale->text('The report doesn\'t contain entries.') : undef,
938 action => [ $::locale->text('Create new') ],
940 $::locale->text('AR Transaction'),
941 submit => [ '#create_new_form', { action => 'ar_transaction' } ],
944 $::locale->text('Sales Invoice'),
945 submit => [ '#create_new_form', { action => 'sales_invoice' } ],
947 ], # end of combobox "Create new"
953 $main::lxdebug->enter_sub();
955 $main::auth->assert('invoice_edit');
957 my $form = $main::form;
958 my %myconfig = %main::myconfig;
959 my $locale = $main::locale;
960 my $cgi = $::request->{cgi};
962 $form->{title} = $locale->text('AR Transactions');
964 $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
965 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
966 $form->{ALL_BUSINESS_TYPES} = SL::DB::Manager::Business->get_all_sorted;
968 $form->{CT_CUSTOM_VARIABLES} = CVar->get_configs('module' => 'CT');
969 ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
970 $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables' => $form->{CT_CUSTOM_VARIABLES},
971 'include_prefix' => 'l_',
972 'include_value' => 'Y');
974 # constants and subs for template
975 $form->{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
977 $::request->layout->add_javascripts("autocomplete_project.js");
979 setup_ar_search_action_bar();
982 print $form->parse_html_template('ar/search', { %myconfig });
984 $main::lxdebug->leave_sub();
987 sub create_subtotal_row {
988 $main::lxdebug->enter_sub();
990 my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
992 my $form = $main::form;
993 my %myconfig = %main::myconfig;
995 my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
997 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
999 $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
1001 map { $totals->{$_} = 0 } @{ $subtotal_columns };
1003 $main::lxdebug->leave_sub();
1008 sub ar_transactions {
1009 $main::lxdebug->enter_sub();
1011 $main::auth->assert('invoice_edit');
1013 my $form = $main::form;
1014 my %myconfig = %main::myconfig;
1015 my $locale = $main::locale;
1017 my ($callback, $href, @columns);
1019 report_generator_set_default_sort('transdate', 1);
1021 AR->ar_transactions(\%myconfig, \%$form);
1023 $form->{title} = $locale->text('AR Transactions');
1025 my $report = SL::ReportGenerator->new(\%myconfig, $form);
1028 qw(ids transdate id type invnumber ordnumber cusordnumber name netamount tax amount paid
1029 datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
1030 marge_total marge_percent globalprojectnumber customernumber country ustid taxzone
1031 payment_terms charts customertype direct_debit dunning_description department);
1033 my $ct_cvar_configs = CVar->get_configs('module' => 'CT');
1034 my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
1035 my @ct_searchable_custom_variables = grep { $_->{searchable} } @{ $ct_cvar_configs };
1037 my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
1038 push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
1040 my @hidden_variables = map { "l_${_}" } @columns;
1041 push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber cusordnumber transaction_description notes project_id transdatefrom transdateto duedatefrom duedateto
1042 employee_id salesman_id business_id parts_partnumber parts_description department_id);
1043 push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
1045 $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
1048 'ids' => { raw_header_data => $::request->presenter->checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
1049 'transdate' => { 'text' => $locale->text('Date'), },
1050 'id' => { 'text' => $locale->text('ID'), },
1051 'type' => { 'text' => $locale->text('Type'), },
1052 'invnumber' => { 'text' => $locale->text('Invoice'), },
1053 'ordnumber' => { 'text' => $locale->text('Order'), },
1054 'cusordnumber' => { 'text' => $locale->text('Customer Order Number'), },
1055 'name' => { 'text' => $locale->text('Customer'), },
1056 'netamount' => { 'text' => $locale->text('Amount'), },
1057 'tax' => { 'text' => $locale->text('Tax'), },
1058 'amount' => { 'text' => $locale->text('Total'), },
1059 'paid' => { 'text' => $locale->text('Paid'), },
1060 'datepaid' => { 'text' => $locale->text('Date Paid'), },
1061 'due' => { 'text' => $locale->text('Amount Due'), },
1062 'duedate' => { 'text' => $locale->text('Due Date'), },
1063 'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1064 'notes' => { 'text' => $locale->text('Notes'), },
1065 'salesman' => { 'text' => $locale->text('Salesperson'), },
1066 'employee' => { 'text' => $locale->text('Employee'), },
1067 'shippingpoint' => { 'text' => $locale->text('Shipping Point'), },
1068 'shipvia' => { 'text' => $locale->text('Ship via'), },
1069 'globalprojectnumber' => { 'text' => $locale->text('Document Project Number'), },
1070 'marge_total' => { 'text' => $locale->text('Ertrag'), },
1071 'marge_percent' => { 'text' => $locale->text('Ertrag prozentual'), },
1072 'customernumber' => { 'text' => $locale->text('Customer Number'), },
1073 'country' => { 'text' => $locale->text('Country'), },
1074 'ustid' => { 'text' => $locale->text('USt-IdNr.'), },
1075 'taxzone' => { 'text' => $locale->text('Steuersatz'), },
1076 'payment_terms' => { 'text' => $locale->text('Payment Terms'), },
1077 'charts' => { 'text' => $locale->text('Buchungskonto'), },
1078 'customertype' => { 'text' => $locale->text('Customer type'), },
1079 'direct_debit' => { 'text' => $locale->text('direct debit'), },
1080 'department' => { 'text' => $locale->text('Department'), },
1081 dunning_description => { 'text' => $locale->text('Dunning level'), },
1085 foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
1086 my $sortdir = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1087 $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1090 my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1092 $form->{"l_type"} = "Y";
1093 map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1095 $column_defs{ids}->{visible} = 'HTML';
1097 $report->set_columns(%column_defs);
1098 $report->set_column_order(@columns);
1100 $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
1102 $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1104 CVar->add_custom_variables_to_report('module' => 'CT',
1105 'trans_id_field' => 'customer_id',
1106 'configs' => $ct_cvar_configs,
1107 'column_defs' => \%column_defs,
1108 'data' => $form->{AR});
1111 if ($form->{customer}) {
1112 push @options, $locale->text('Customer') . " : $form->{customer}";
1114 if ($form->{cp_name}) {
1115 push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
1118 if ($form->{department_id}) {
1119 my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
1120 push @options, $locale->text('Department') . " : " . $department->description;
1122 if ($form->{invnumber}) {
1123 push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1125 if ($form->{ordnumber}) {
1126 push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1128 if ($form->{cusordnumber}) {
1129 push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
1131 if ($form->{notes}) {
1132 push @options, $locale->text('Notes') . " : $form->{notes}";
1134 if ($form->{transaction_description}) {
1135 push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1137 if ($form->{parts_partnumber}) {
1138 push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
1140 if ($form->{parts_description}) {
1141 push @options, $locale->text('Part Description') . " : $form->{parts_description}";
1143 if ($form->{transdatefrom}) {
1144 push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1146 if ($form->{transdateto}) {
1147 push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
1149 if ($form->{open}) {
1150 push @options, $locale->text('Open');
1152 if ($form->{employee_id}) {
1153 my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
1154 push @options, $locale->text('Employee') . ' : ' . $employee->name;
1156 if ($form->{salesman_id}) {
1157 my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1158 push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1160 if ($form->{closed}) {
1161 push @options, $locale->text('Closed');
1164 $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
1166 $report->set_options('top_info_text' => join("\n", @options),
1167 'raw_top_info_text' => $form->parse_html_template('ar/ar_transactions_header'),
1168 'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1169 'output_format' => 'HTML',
1170 'title' => $form->{title},
1171 'attachment_basename' => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1173 $report->set_options_from_form();
1174 $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1176 # add sort and escape callback, this one we use for the add sub
1177 $form->{callback} = $href .= "&sort=$form->{sort}";
1179 # escape callback for href
1180 $callback = $form->escape($href);
1182 my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1184 my %totals = map { $_ => 0 } @subtotal_columns;
1185 my %subtotals = map { $_ => 0 } @subtotal_columns;
1189 foreach my $ar (@{ $form->{AR} }) {
1190 $ar->{tax} = $ar->{amount} - $ar->{netamount};
1191 $ar->{due} = $ar->{amount} - $ar->{paid};
1193 map { $subtotals{$_} += $ar->{$_};
1194 $totals{$_} += $ar->{$_} } @subtotal_columns;
1196 $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1197 $totals{marge_percent} = $totals{netamount} ? ($totals{marge_total} * 100 / $totals{netamount} ) : 0;
1199 my $is_storno = $ar->{storno} && $ar->{storno_id};
1200 my $has_storno = $ar->{storno} && !$ar->{storno_id};
1203 $has_storno ? $locale->text("Invoice with Storno (abbreviation)") :
1204 $is_storno ? $locale->text("Storno (one letter abbreviation)") :
1205 $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1206 $ar->{invoice} ? $locale->text("Invoice (one letter abbreviation)") :
1207 $locale->text("AR Transaction (abbreviation)");
1209 map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1211 $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1215 foreach my $column (@columns) {
1217 'data' => $ar->{$column},
1218 'align' => $column_alignment{$column},
1222 $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1223 . "&id=" . E($ar->{id}) . "&callback=${callback}";
1226 raw_data => $::request->presenter->checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
1231 my $row_set = [ $row ];
1233 if (($form->{l_subtotal} eq 'Y')
1234 && (($idx == (scalar @{ $form->{AR} } - 1))
1235 || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1236 push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1239 $report->add_data($row_set);
1244 $report->add_separator();
1245 $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1247 $::request->layout->add_javascripts('kivi.MassInvoiceCreatePrint.js');
1248 setup_ar_transactions_action_bar(num_rows => scalar(@{ $form->{AR} }));
1250 $report->generate_with_headers(action_bar => 1);
1252 $main::lxdebug->leave_sub();
1256 $main::lxdebug->enter_sub();
1258 $main::auth->assert('ar_transactions');
1260 my $form = $main::form;
1261 my %myconfig = %main::myconfig;
1262 my $locale = $main::locale;
1264 # don't cancel cancelled transactions
1265 if (IS->has_storno(\%myconfig, $form, 'ar')) {
1266 $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1267 $form->error($locale->text("Transaction has already been cancelled!"));
1270 AR->storno($form, \%myconfig, $form->{id});
1272 # saving the history
1273 if(!exists $form->{addition} && $form->{id} ne "") {
1274 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1275 $form->{addition} = "STORNO";
1276 $form->{what_done} = "invoice";
1277 $form->save_history;
1279 # /saving the history
1281 $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1283 $main::lxdebug->leave_sub();