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 delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
106 # Fill $::form from the template.
107 my $today = DateTime->today_local;
108 $::form->{title} = "Add";
109 $::form->{currency} = $template->currency->name;
110 $::form->{direct_debit} = $template->direct_debit;
111 $::form->{globalproject_id} = $template->project_id;
112 $::form->{AR_chart_id} = $template->ar_ap_chart_id;
113 $::form->{transdate} = $today->to_kivitendo;
114 $::form->{duedate} = $today->to_kivitendo;
115 $::form->{rowcount} = @{ $template->items } + 1;
116 $::form->{paidaccounts} = 1;
117 $::form->{$_} = $template->$_ for qw(department_id ordnumber taxincluded employee_id notes);
119 if ($template->customer) {
120 $::form->{customer_id} = $template->customer_id;
121 $::form->{customer} = $template->customer->name;
122 $::form->{duedate} = $template->customer->payment->calc_date(reference_date => $today)->to_kivitendo if $template->customer->payment;
126 foreach my $item (@{ $template->items }) {
129 my $active_taxkey = $item->chart->get_active_taxkey;
130 my $taxes = SL::DB::Manager::Tax->get_all(
131 where => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
132 sort_by => 'taxkey, rate',
135 my $tax = first { $item->tax_id == $_->id } @{ $taxes };
136 $tax //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
137 $tax //= $taxes->[0];
144 $::form->{"AR_amount_chart_id_${row}"} = $item->chart_id;
145 $::form->{"previous_AR_amount_chart_id_${row}"} = $item->chart_id;
146 $::form->{"amount_${row}"} = $::form->format_amount(\%::myconfig, $item->amount1, 2);
147 $::form->{"taxchart_${row}"} = $item->tax_id . '--' . $tax->rate;
148 $::form->{"project_id_${row}"} = $item->project_id;
151 flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
156 sub save_record_template {
157 $::auth->assert('ar_transactions');
159 my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
160 my $js = SL::ClientJS->new(controller => SL::Controller::Base->new);
161 my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
163 $js->dialog->close('#record_template_dialog');
166 $_->{chart_id} && (($_->{tax_id} // '') ne '') && ($_->{amount1} != 0)
168 +{ chart_id => $::form->{"AR_amount_chart_id_${_}"},
169 amount1 => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
170 tax_id => (split m{--}, $::form->{"taxchart_${_}"})[0],
171 project_id => $::form->{"project_id_${_}"} || undef,
173 } (1..($::form->{rowcount} || 1));
175 $template->assign_attributes(
176 template_type => 'ar_transaction',
177 template_name => $new_name,
179 currency_id => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
180 ar_ap_chart_id => $::form->{AR_chart_id} || undef,
181 customer_id => $::form->{customer_id} || undef,
182 department_id => $::form->{department_id} || undef,
183 project_id => $::form->{globalproject_id} || undef,
184 employee_id => $::form->{employee_id} || undef,
185 taxincluded => $::form->{taxincluded} ? 1 : 0,
186 direct_debit => $::form->{direct_debit} ? 1 : 0,
187 ordnumber => $::form->{ordnumber},
188 notes => $::form->{notes},
198 ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
203 ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
208 $main::lxdebug->enter_sub();
210 $main::auth->assert('ar_transactions');
212 my $form = $main::form;
213 my %myconfig = %main::myconfig;
216 if(!exists $form->{addition} && ($form->{id} ne "")) {
217 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
218 $form->{addition} = "ADDED";
221 # /saving the history
223 $form->{title} = "Add";
224 $form->{callback} = "ar.pl?action=add" unless $form->{callback};
226 AR->get_transdate(\%myconfig, $form);
227 $form->{initial_transdate} = $form->{transdate};
228 create_links(dont_save => 1);
229 $form->{transdate} = $form->{initial_transdate};
231 if ($form->{customer_id}) {
232 my $last_used_ar_chart = SL::DB::Customer->load_cached($form->{customer_id})->last_used_ar_chart;
233 $form->{"AR_amount_chart_id_1"} = $last_used_ar_chart->id if $last_used_ar_chart;
237 $main::lxdebug->leave_sub();
241 $main::lxdebug->enter_sub();
243 $main::auth->assert('ar_transactions');
245 my $form = $main::form;
247 # show history button
248 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
249 #/show hhistory button
250 $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
251 $form->{title} = "Edit";
256 $main::lxdebug->leave_sub();
260 $main::lxdebug->enter_sub();
262 $main::auth->assert('ar_transactions');
264 my $form = $main::form;
269 $main::lxdebug->leave_sub();
272 sub _retrieve_invoice_object {
273 return undef if !$::form->{id};
274 return $::form->{invoice_obj} if $::form->{invoice_obj} && $::form->{invoice_obj}->id == $::form->{id};
275 return SL::DB::Invoice->new(id => $::form->{id})->load;
279 $main::lxdebug->enter_sub();
281 $main::auth->assert('ar_transactions');
284 my $form = $main::form;
285 my %myconfig = %main::myconfig;
287 $form->create_links("AR", \%myconfig, "customer");
288 $form->{invoice_obj} = _retrieve_invoice_object();
291 if (!$params{dont_save}) {
292 %saved = map { ($_ => $form->{$_}) } qw(direct_debit id taxincluded);
293 $saved{duedate} = $form->{duedate} if $form->{duedate};
294 $saved{currency} = $form->{currency} if $form->{currency};
297 IS->get_customer(\%myconfig, \%$form);
299 $form->{$_} = $saved{$_} for keys %saved;
300 $form->{rowcount} = 1;
301 $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};
304 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
306 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
308 # build the popup menus
309 $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
311 AR->setup_form($form);
314 ($form->datetonum($form->{transdate}, \%myconfig) <=
315 $form->datetonum($form->{closedto}, \%myconfig));
317 $main::lxdebug->leave_sub();
321 $main::lxdebug->enter_sub();
323 $main::auth->assert('ar_transactions');
325 my $form = $main::form;
326 my %myconfig = %main::myconfig;
327 my $locale = $main::locale;
328 my $cgi = $::request->{cgi};
330 $form->{invoice_obj} = _retrieve_invoice_object();
332 my ($title, $readonly, $exchangerate, $rows);
333 my ($notes, $amount, $project);
335 $form->{initial_focus} = !($form->{amount_1} * 1) ? 'customer_id' : 'row_' . $form->{rowcount};
337 $title = $form->{title};
338 # $locale->text('Add Accounts Receivables Transaction')
339 # $locale->text('Edit Accounts Receivables Transaction')
340 $form->{title} = $locale->text("$title Accounts Receivables Transaction");
342 $readonly = ($form->{id}) ? "readonly" : "";
344 $form->{radier} = ($::instance_conf->get_ar_changeable == 2)
345 ? ($form->current_date(\%myconfig) eq $form->{gldate})
346 : ($::instance_conf->get_ar_changeable == 1);
347 $readonly = ($form->{radier}) ? "" : $readonly;
349 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
350 $form->{exchangerate} = $form->{forex} if $form->{forex};
352 # format exchangerate
353 $form->{exchangerate} = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
355 $rows = max 2, $form->numtextrows($form->{notes}, 50);
357 my @old_project_ids = grep { $_ } map { $form->{"project_id_$_"} } 1..$form->{rowcount};
359 $form->get_lists("projects" => { "key" => "ALL_PROJECTS",
361 "old_id" => \@old_project_ids },
362 "charts" => { "key" => "ALL_CHARTS",
363 "transdate" => $form->{transdate} },
364 "taxcharts" => { "key" => "ALL_TAXCHARTS",
365 "module" => "AR" },);
367 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
369 $_->{link_split} = { map { $_ => 1 } split/:/, $_->{link} } for @{ $form->{ALL_CHARTS} };
371 my %project_labels = map { $_->{id} => $_->{projectnumber} } @{ $form->{"ALL_PROJECTS"} };
373 my (@AR_paid_values, %AR_paid_labels);
374 my $default_ar_amount_chart_id;
376 foreach my $item (@{ $form->{ALL_CHARTS} }) {
377 if ($item->{link_split}{AR_amount}) {
378 $default_ar_amount_chart_id //= $item->{id};
380 } elsif ($item->{link_split}{AR_paid}) {
381 push(@AR_paid_values, $item->{accno});
382 $AR_paid_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
386 my $follow_up_vc = $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id})->name : '';
387 my $follow_up_trans_info = "$form->{invnumber} ($follow_up_vc)";
389 $::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.RecordTemplate.js");
391 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
395 for my $i (1 .. $form->{rowcount}) {
397 amount => $form->{"amount_$i"},
398 tax => $form->{"tax_$i"},
399 project_id => ($i==$form->{rowcount}) ? $form->{globalproject_id} : $form->{"project_id_$i"},
402 my (%taxchart_labels, @taxchart_values, $default_taxchart, $taxchart_to_use);
403 my $amount_chart_id = $form->{"AR_amount_chart_id_$i"} // $default_ar_amount_chart_id;
404 my $chart_has_changed = $::form->{"previous_AR_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AR_amount_chart_id_$i"});
406 foreach my $item ( GL->get_active_taxes_for_chart($amount_chart_id, $transdate) ) {
407 my $key = $item->id . "--" . $item->rate;
408 $first_taxchart //= $item;
409 $default_taxchart = $item if $item->{is_default};
410 $taxchart_to_use = $item if $key eq $form->{"taxchart_$i"};
412 push(@taxchart_values, $key);
413 $taxchart_labels{$key} = $item->taxdescription . " " . $item->rate * 100 . ' %';
416 $taxchart_to_use = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
417 my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
419 $transaction->{selectAR_amount} =
420 $::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" : ""))
421 . $::request->presenter->hidden_tag("previous_AR_amount_chart_id_$i", $amount_chart_id);
423 $transaction->{taxchart} =
424 NTI($cgi->popup_menu('-name' => "taxchart_$i",
425 '-id' => "taxchart_$i",
426 '-style' => 'width:200px',
427 '-values' => \@taxchart_values,
428 '-labels' => \%taxchart_labels,
429 '-default' => $selected_taxchart));
431 push @transactions, $transaction;
434 $form->{invtotal_unformatted} = $form->{invtotal};
436 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
438 my $now = $form->current_date(\%myconfig);
441 for my $i (1 .. $form->{paidaccounts}) {
443 paid => $form->{"paid_$i"},
444 exchangerate => $form->{"exchangerate_$i"} || '',
445 gldate => $form->{"gldate_$i"},
446 acc_trans_id => $form->{"acc_trans_id_$i"},
447 source => $form->{"source_$i"},
448 memo => $form->{"memo_$i"},
449 AR_paid => $form->{"AR_paid_$i"},
450 forex => $form->{"forex_$i"},
451 datepaid => $form->{"datepaid_$i"},
452 paid_project_id => $form->{"paid_project_id_$i"},
453 gldate => $form->{"gldate_$i"},
456 # default account for current assets (i.e. 1801 - SKR04) if no account is selected
457 $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
459 $payment->{selectAR_paid} =
460 NTI($cgi->popup_menu('-name' => "AR_paid_$i",
461 '-id' => "AR_paid_$i",
462 '-values' => \@AR_paid_values,
463 '-labels' => \%AR_paid_labels,
464 '-default' => $payment->{AR_paid} || $form->{accno_arap}));
468 $payment->{changeable} =
469 SL::DB::Default->get->payments_changeable == 0 ? !$payment->{acc_trans_id} # never
470 : SL::DB::Default->get->payments_changeable == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
473 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
474 if ($form->date_closed($payment->{"gldate_$i"})) {
475 $payment->{changeable} = 0;
478 push @payments, $payment;
481 my @empty = grep { $_->{paid} eq '' } @payments;
483 (sort_by { DateTime->from_kivitendo($_->{datepaid}) } grep { $_->{paid} ne '' } @payments),
487 $form->{totalpaid} = sum map { $_->{paid} } @payments;
489 my $employees = SL::DB::Manager::Employee->get_all_sorted(
492 (id => $::form->{employee_id}) x !!$::form->{employee_id},
500 print $::form->parse_html_template('ar/form_header', {
501 paid_missing => $::form->{invtotal} - $::form->{totalpaid},
502 show_exch => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
503 payments => \@payments,
504 transactions => \@transactions,
505 project_labels => \%project_labels,
507 AR_chart_id => $form->{AR_chart_id},
509 follow_up_trans_info => $follow_up_trans_info,
510 today => DateTime->today,
511 currencies => scalar(SL::DB::Manager::Currency->get_all_sorted),
512 employees => $employees,
515 $main::lxdebug->leave_sub();
519 $main::lxdebug->enter_sub();
521 $main::auth->assert('ar_transactions');
523 my $form = $main::form;
524 my %myconfig = %main::myconfig;
525 my $locale = $main::locale;
526 my $cgi = $::request->{cgi};
529 my $follow_ups = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1);
530 if ( @{ $follow_ups} ) {
531 $form->{follow_up_length} = scalar(@{$follow_ups});
532 $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
536 my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
537 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
539 $form->{is_closed} = $transdate <= $closedto;
541 # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
542 $form->{show_storno_button} =
544 !IS->has_storno(\%myconfig, $form, 'ar') &&
545 !IS->is_storno(\%myconfig, $form, 'ar') &&
546 ($form->{totalpaid} == 0 || $form->{totalpaid} eq "");
548 $form->{show_mark_as_paid_button} = $form->{id} && $::instance_conf->get_ar_show_mark_as_paid();
550 print $::form->parse_html_template('ar/form_footer');
552 $main::lxdebug->leave_sub();
556 $::auth->assert('ar_transactions');
558 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
560 $::form->redirect($::locale->text("Marked as paid"));
564 $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
565 $::form->{gldate} = $::form->{transdate} if !$::form->{gldate};
570 $main::lxdebug->enter_sub();
572 $main::auth->assert('ar_transactions');
574 my $form = $main::form;
575 my %myconfig = %main::myconfig;
579 my ($totaltax, $exchangerate);
581 $form->{invtotal} = 0;
583 delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
585 map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
586 qw(exchangerate creditlimit creditremaining);
588 my @flds = qw(amount AR_amount projectnumber oldprojectnumber project_id);
592 for my $i (1 .. $form->{rowcount}) {
593 $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
594 if ($form->{"amount_$i"}) {
597 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
600 ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
602 $totaltax += $form->{"tax_$i"};
603 map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
608 $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
609 $form->{rowcount} = $count + 1;
610 map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
612 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
613 $form->{exchangerate} = $form->{forex} if $form->{forex};
615 $form->{invdate} = $form->{transdate};
617 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
618 IS->get_customer(\%myconfig, $form);
622 ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
624 for my $i (1 .. $form->{paidaccounts}) {
625 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
628 $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
629 } qw(paid exchangerate);
631 $form->{totalpaid} += $form->{"paid_$i"};
633 $form->{"forex_$i"} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
634 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
638 $form->{creditremaining} -=
639 ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
640 $form->{oldinvtotal});
641 $form->{oldinvtotal} = $form->{invtotal};
642 $form->{oldtotalpaid} = $form->{totalpaid};
646 $main::lxdebug->leave_sub();
650 # ToDO: fix $closedto and $invdate
653 $main::lxdebug->enter_sub();
655 $main::auth->assert('ar_transactions');
657 my $form = $main::form;
658 my %myconfig = %main::myconfig;
659 my $locale = $main::locale;
661 $form->mtime_ischanged('ar');
662 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
664 my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
666 for my $i (1 .. $form->{paidaccounts}) {
668 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
669 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
671 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
673 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
674 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
676 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
677 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
678 $form->error($locale->text('Cannot post payment for a closed period!'))
679 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
681 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
682 # $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
683 $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
688 ($form->{AR}) = split /--/, $form->{AR};
689 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
690 if (AR->post_payment(\%myconfig, \%$form)) {
691 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
692 $form->{what_done} = 'invoice';
693 $form->{addition} = "PAYMENT POSTED";
695 $form->redirect($locale->text('Payment posted!'))
697 $form->error($locale->text('Cannot post payment!'));
700 $main::lxdebug->leave_sub();
705 $main::auth->assert('ar_transactions');
707 my $form = $main::form;
714 $main::lxdebug->enter_sub();
716 $main::auth->assert('ar_transactions');
718 my $form = $main::form;
719 my %myconfig = %main::myconfig;
720 my $locale = $main::locale;
724 $form->mtime_ischanged('ar');
728 # check if there is an invoice number, invoice and due date
729 $form->isblank("transdate", $locale->text('Invoice Date missing!'));
730 $form->isblank("duedate", $locale->text('Due Date missing!'));
731 $form->isblank("customer_id", $locale->text('Customer missing!'));
733 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
734 $form->{saved_message} = $::locale->text('You have to specify a department.');
739 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
740 my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
742 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
743 if ($form->date_max_future($transdate, \%myconfig));
745 $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
747 $form->error($locale->text('Zero amount posting!'))
748 unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
750 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
751 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
755 for my $i (1 .. $form->{paidaccounts}) {
756 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
757 $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
759 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
761 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
762 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
764 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
765 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
766 $form->error($locale->text('Cannot post payment for a closed period!'))
767 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
769 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
770 $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
771 $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
776 # if oldcustomer ne customer redo form
777 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
779 $::dispatcher->end_request;
782 $form->{AR}{receivables} = $form->{ARselected};
785 $form->{id} = 0 if $form->{postasnew};
786 $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
789 if(!exists $form->{addition} && $form->{id} ne "") {
790 $form->{snumbers} = "invnumber_$form->{invnumber}";
791 $form->{what_done} = "invoice";
792 $form->{addition} = "POSTED";
795 # /saving the history
797 $form->redirect($locale->text("AR transaction posted.")) unless $inline;
799 $main::lxdebug->leave_sub();
803 $main::lxdebug->enter_sub();
805 $main::auth->assert('ar_transactions');
807 my $form = $main::form;
808 my %myconfig = %main::myconfig;
810 $form->{postasnew} = 1;
812 if(!exists $form->{addition} && $form->{id} ne "") {
813 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
814 $form->{what_done} = "invoice";
815 $form->{addition} = "POSTED AS NEW";
818 # /saving the history
821 $main::lxdebug->leave_sub();
825 $main::lxdebug->enter_sub();
827 $main::auth->assert('ar_transactions');
829 my $form = $main::form;
830 my %myconfig = %main::myconfig;
832 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);
833 $form->{paidaccounts} = 1;
835 $form->{invdate} = $form->current_date(\%myconfig);
838 $main::lxdebug->leave_sub();
842 $main::lxdebug->enter_sub();
844 $main::auth->assert('ar_transactions');
846 my $form = $main::form;
847 my $locale = $main::locale;
849 $form->{title} = $locale->text('Confirm!');
853 delete $form->{header};
856 <form method=post action=$form->{script}>
859 foreach my $key (keys %$form) {
860 next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
861 $form->{$key} =~ s/\"/"/g;
862 print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
866 <h2 class=confirm>$form->{title}</h2>
869 . $locale->text('Are you sure you want to delete Transaction')
870 . qq| $form->{invnumber}</h4>
872 <input name=action class=submit type=submit value="|
873 . $locale->text('Yes') . qq|">
877 $main::lxdebug->leave_sub();
881 $main::lxdebug->enter_sub();
883 $main::auth->assert('ar_transactions');
885 my $form = $main::form;
886 my %myconfig = %main::myconfig;
887 my $locale = $main::locale;
889 if (AR->delete_transaction(\%myconfig, \%$form)) {
891 if(!exists $form->{addition}) {
892 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
893 $form->{what_done} = "invoice";
894 $form->{addition} = "DELETED";
897 # /saving the history
898 $form->redirect($locale->text('Transaction deleted!'));
900 $form->error($locale->text('Cannot delete transaction!'));
902 $main::lxdebug->leave_sub();
906 $main::lxdebug->enter_sub();
908 $main::auth->assert('invoice_edit');
910 my $form = $main::form;
911 my %myconfig = %main::myconfig;
912 my $locale = $main::locale;
913 my $cgi = $::request->{cgi};
915 $form->{title} = $locale->text('AR Transactions');
917 $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
918 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
919 $form->{ALL_BUSINESS_TYPES} = SL::DB::Manager::Business->get_all_sorted;
921 $form->{CT_CUSTOM_VARIABLES} = CVar->get_configs('module' => 'CT');
922 ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
923 $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables' => $form->{CT_CUSTOM_VARIABLES},
924 'include_prefix' => 'l_',
925 'include_value' => 'Y');
927 # constants and subs for template
928 $form->{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
930 $::request->layout->add_javascripts("autocomplete_project.js");
933 print $form->parse_html_template('ar/search', { %myconfig });
935 $main::lxdebug->leave_sub();
938 sub create_subtotal_row {
939 $main::lxdebug->enter_sub();
941 my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
943 my $form = $main::form;
944 my %myconfig = %main::myconfig;
946 my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
948 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
950 $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
952 map { $totals->{$_} = 0 } @{ $subtotal_columns };
954 $main::lxdebug->leave_sub();
959 sub ar_transactions {
960 $main::lxdebug->enter_sub();
962 $main::auth->assert('invoice_edit');
964 my $form = $main::form;
965 my %myconfig = %main::myconfig;
966 my $locale = $main::locale;
968 my ($callback, $href, @columns);
970 report_generator_set_default_sort('transdate', 1);
972 AR->ar_transactions(\%myconfig, \%$form);
974 $form->{title} = $locale->text('AR Transactions');
976 my $report = SL::ReportGenerator->new(\%myconfig, $form);
979 qw(ids transdate id type invnumber ordnumber cusordnumber name netamount tax amount paid
980 datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
981 marge_total marge_percent globalprojectnumber customernumber country ustid taxzone
982 payment_terms charts customertype direct_debit dunning_description department);
984 my $ct_cvar_configs = CVar->get_configs('module' => 'CT');
985 my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
986 my @ct_searchable_custom_variables = grep { $_->{searchable} } @{ $ct_cvar_configs };
988 my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
989 push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
991 my @hidden_variables = map { "l_${_}" } @columns;
992 push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber cusordnumber transaction_description notes project_id transdatefrom transdateto duedatefrom duedateto
993 employee_id salesman_id business_id parts_partnumber parts_description department_id);
994 push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
996 $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
999 'ids' => { raw_header_data => $::request->presenter->checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
1000 'transdate' => { 'text' => $locale->text('Date'), },
1001 'id' => { 'text' => $locale->text('ID'), },
1002 'type' => { 'text' => $locale->text('Type'), },
1003 'invnumber' => { 'text' => $locale->text('Invoice'), },
1004 'ordnumber' => { 'text' => $locale->text('Order'), },
1005 'cusordnumber' => { 'text' => $locale->text('Customer Order Number'), },
1006 'name' => { 'text' => $locale->text('Customer'), },
1007 'netamount' => { 'text' => $locale->text('Amount'), },
1008 'tax' => { 'text' => $locale->text('Tax'), },
1009 'amount' => { 'text' => $locale->text('Total'), },
1010 'paid' => { 'text' => $locale->text('Paid'), },
1011 'datepaid' => { 'text' => $locale->text('Date Paid'), },
1012 'due' => { 'text' => $locale->text('Amount Due'), },
1013 'duedate' => { 'text' => $locale->text('Due Date'), },
1014 'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1015 'notes' => { 'text' => $locale->text('Notes'), },
1016 'salesman' => { 'text' => $locale->text('Salesperson'), },
1017 'employee' => { 'text' => $locale->text('Employee'), },
1018 'shippingpoint' => { 'text' => $locale->text('Shipping Point'), },
1019 'shipvia' => { 'text' => $locale->text('Ship via'), },
1020 'globalprojectnumber' => { 'text' => $locale->text('Document Project Number'), },
1021 'marge_total' => { 'text' => $locale->text('Ertrag'), },
1022 'marge_percent' => { 'text' => $locale->text('Ertrag prozentual'), },
1023 'customernumber' => { 'text' => $locale->text('Customer Number'), },
1024 'country' => { 'text' => $locale->text('Country'), },
1025 'ustid' => { 'text' => $locale->text('USt-IdNr.'), },
1026 'taxzone' => { 'text' => $locale->text('Steuersatz'), },
1027 'payment_terms' => { 'text' => $locale->text('Payment Terms'), },
1028 'charts' => { 'text' => $locale->text('Buchungskonto'), },
1029 'customertype' => { 'text' => $locale->text('Customer type'), },
1030 'direct_debit' => { 'text' => $locale->text('direct debit'), },
1031 'department' => { 'text' => $locale->text('Department'), },
1032 dunning_description => { 'text' => $locale->text('Dunning level'), },
1036 foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
1037 my $sortdir = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1038 $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1041 my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1043 $form->{"l_type"} = "Y";
1044 map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1046 $column_defs{ids}->{visible} = 'HTML';
1048 $report->set_columns(%column_defs);
1049 $report->set_column_order(@columns);
1051 $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
1053 $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1055 CVar->add_custom_variables_to_report('module' => 'CT',
1056 'trans_id_field' => 'customer_id',
1057 'configs' => $ct_cvar_configs,
1058 'column_defs' => \%column_defs,
1059 'data' => $form->{AR});
1062 if ($form->{customer}) {
1063 push @options, $locale->text('Customer') . " : $form->{customer}";
1065 if ($form->{cp_name}) {
1066 push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
1069 if ($form->{department_id}) {
1070 my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
1071 push @options, $locale->text('Department') . " : " . $department->description;
1073 if ($form->{invnumber}) {
1074 push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1076 if ($form->{ordnumber}) {
1077 push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1079 if ($form->{cusordnumber}) {
1080 push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
1082 if ($form->{notes}) {
1083 push @options, $locale->text('Notes') . " : $form->{notes}";
1085 if ($form->{transaction_description}) {
1086 push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1088 if ($form->{parts_partnumber}) {
1089 push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
1091 if ($form->{parts_description}) {
1092 push @options, $locale->text('Part Description') . " : $form->{parts_description}";
1094 if ($form->{transdatefrom}) {
1095 push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1097 if ($form->{transdateto}) {
1098 push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
1100 if ($form->{open}) {
1101 push @options, $locale->text('Open');
1103 if ($form->{employee_id}) {
1104 my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
1105 push @options, $locale->text('Employee') . ' : ' . $employee->name;
1107 if ($form->{salesman_id}) {
1108 my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1109 push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1111 if ($form->{closed}) {
1112 push @options, $locale->text('Closed');
1115 $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
1117 $report->set_options('top_info_text' => join("\n", @options),
1118 'raw_top_info_text' => $form->parse_html_template('ar/ar_transactions_header'),
1119 'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1120 'output_format' => 'HTML',
1121 'title' => $form->{title},
1122 'attachment_basename' => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1124 $report->set_options_from_form();
1125 $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1127 # add sort and escape callback, this one we use for the add sub
1128 $form->{callback} = $href .= "&sort=$form->{sort}";
1130 # escape callback for href
1131 $callback = $form->escape($href);
1133 my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1135 my %totals = map { $_ => 0 } @subtotal_columns;
1136 my %subtotals = map { $_ => 0 } @subtotal_columns;
1140 foreach my $ar (@{ $form->{AR} }) {
1141 $ar->{tax} = $ar->{amount} - $ar->{netamount};
1142 $ar->{due} = $ar->{amount} - $ar->{paid};
1144 map { $subtotals{$_} += $ar->{$_};
1145 $totals{$_} += $ar->{$_} } @subtotal_columns;
1147 $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1148 $totals{marge_percent} = $totals{netamount} ? ($totals{marge_total} * 100 / $totals{netamount} ) : 0;
1150 my $is_storno = $ar->{storno} && $ar->{storno_id};
1151 my $has_storno = $ar->{storno} && !$ar->{storno_id};
1154 $has_storno ? $locale->text("Invoice with Storno (abbreviation)") :
1155 $is_storno ? $locale->text("Storno (one letter abbreviation)") :
1156 $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1157 $ar->{invoice} ? $locale->text("Invoice (one letter abbreviation)") :
1158 $locale->text("AR Transaction (abbreviation)");
1160 map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1162 $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1166 foreach my $column (@columns) {
1168 'data' => $ar->{$column},
1169 'align' => $column_alignment{$column},
1173 $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1174 . "&id=" . E($ar->{id}) . "&callback=${callback}";
1177 raw_data => $::request->presenter->checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
1182 my $row_set = [ $row ];
1184 if (($form->{l_subtotal} eq 'Y')
1185 && (($idx == (scalar @{ $form->{AR} } - 1))
1186 || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1187 push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1190 $report->add_data($row_set);
1195 $report->add_separator();
1196 $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1198 $report->generate_with_headers();
1200 $main::lxdebug->leave_sub();
1204 $main::lxdebug->enter_sub();
1206 $main::auth->assert('ar_transactions');
1208 my $form = $main::form;
1209 my %myconfig = %main::myconfig;
1210 my $locale = $main::locale;
1212 # don't cancel cancelled transactions
1213 if (IS->has_storno(\%myconfig, $form, 'ar')) {
1214 $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1215 $form->error($locale->text("Transaction has already been cancelled!"));
1218 AR->storno($form, \%myconfig, $form->{id});
1220 # saving the history
1221 if(!exists $form->{addition} && $form->{id} ne "") {
1222 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1223 $form->{addition} = "STORNO";
1224 $form->{what_done} = "invoice";
1225 $form->save_history;
1227 # /saving the history
1229 $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1231 $main::lxdebug->leave_sub();