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 #======================================================================
33 #======================================================================
35 use POSIX qw(strftime);
36 use List::Util qw(first max sum);
37 use List::UtilsBy qw(sort_by);
42 use SL::Helper::Flash qw(flash);
45 use SL::ReportGenerator;
48 use SL::DB::PurchaseInvoice;
49 use SL::DB::RecordTemplate;
52 use SL::Locale::String qw(t8);
54 require "bin/mozilla/common.pl";
55 require "bin/mozilla/reportgenerator.pl";
63 # this is for our long dates
64 # $locale->text('January')
65 # $locale->text('February')
66 # $locale->text('March')
67 # $locale->text('April')
68 # $locale->text('May ')
69 # $locale->text('June')
70 # $locale->text('July')
71 # $locale->text('August')
72 # $locale->text('September')
73 # $locale->text('October')
74 # $locale->text('November')
75 # $locale->text('December')
77 # this is for our short month
78 # $locale->text('Jan')
79 # $locale->text('Feb')
80 # $locale->text('Mar')
81 # $locale->text('Apr')
82 # $locale->text('May')
83 # $locale->text('Jun')
84 # $locale->text('Jul')
85 # $locale->text('Aug')
86 # $locale->text('Sep')
87 # $locale->text('Oct')
88 # $locale->text('Nov')
89 # $locale->text('Dec')
91 sub load_record_template {
92 $::auth->assert('ap_transactions');
94 # Load existing template and verify that its one for this module.
95 my $template = SL::DB::RecordTemplate
96 ->new(id => $::form->{id})
98 with_object => [ qw(customer payment currency record_items record_items.chart) ],
101 die "invalid template type" unless $template->template_type eq 'ap_transaction';
103 $template->substitute_variables;
105 # Clean the current $::form before rebuilding it from the template.
106 my $form_defaults = delete $::form->{form_defaults};
107 delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
109 # Fill $::form from the template.
110 my $today = DateTime->today_local;
111 $::form->{title} = "Add";
112 $::form->{currency} = $template->currency->name;
113 $::form->{direct_debit} = $template->direct_debit;
114 $::form->{globalproject_id} = $template->project_id;
115 $::form->{AP_chart_id} = $template->ar_ap_chart_id;
116 $::form->{transdate} = $today->to_kivitendo;
117 $::form->{duedate} = $today->to_kivitendo;
118 $::form->{rowcount} = @{ $template->items };
119 $::form->{paidaccounts} = 1;
120 $::form->{$_} = $template->$_ for qw(department_id ordnumber taxincluded notes);
122 if ($template->vendor) {
123 $::form->{vendor_id} = $template->vendor_id;
124 $::form->{vendor} = $template->vendor->name;
125 $::form->{duedate} = $template->vendor->payment->calc_date(reference_date => $today)->to_kivitendo if $template->vendor->payment;
129 foreach my $item (@{ $template->items }) {
132 my $active_taxkey = $item->chart->get_active_taxkey;
133 my $taxes = SL::DB::Manager::Tax->get_all(
134 where => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
135 sort_by => 'taxkey, rate',
138 my $tax = first { $item->tax_id == $_->id } @{ $taxes };
139 $tax //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
140 $tax //= $taxes->[0];
147 $::form->{"AP_amount_chart_id_${row}"} = $item->chart_id;
148 $::form->{"previous_AP_amount_chart_id_${row}"} = $item->chart_id;
149 $::form->{"amount_${row}"} = $::form->format_amount(\%::myconfig, $item->amount1, 2);
150 $::form->{"taxchart_${row}"} = $item->tax_id . '--' . $tax->rate;
151 $::form->{"project_id_${row}"} = $item->project_id;
154 $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
156 flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
159 keep_rows_without_amount => 1,
160 dont_add_new_row => 1,
164 sub save_record_template {
165 $::auth->assert('ap_transactions');
167 my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
168 my $js = SL::ClientJS->new(controller => SL::Controller::Base->new);
169 my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
171 $js->dialog->close('#record_template_dialog');
174 $_->{chart_id} && (($_->{tax_id} // '') ne '')
176 +{ chart_id => $::form->{"AP_amount_chart_id_${_}"},
177 amount1 => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
178 tax_id => (split m{--}, $::form->{"taxchart_${_}"})[0],
179 project_id => $::form->{"project_id_${_}"} || undef,
181 } (1..($::form->{rowcount} || 1));
183 $template->assign_attributes(
184 template_type => 'ap_transaction',
185 template_name => $new_name,
187 currency_id => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
188 ar_ap_chart_id => $::form->{AP_chart_id} || undef,
189 vendor_id => $::form->{vendor_id} || undef,
190 department_id => $::form->{department_id} || undef,
191 project_id => $::form->{globalproject_id} || undef,
192 taxincluded => $::form->{taxincluded} ? 1 : 0,
193 direct_debit => $::form->{direct_debit} ? 1 : 0,
194 ordnumber => $::form->{ordnumber},
195 notes => $::form->{notes},
205 ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
210 ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
215 $main::lxdebug->enter_sub();
217 my $form = $main::form;
218 my %myconfig = %main::myconfig;
220 $main::auth->assert('ap_transactions');
222 $form->{title} = "Add";
224 $form->{callback} = "ap.pl?action=add" unless $form->{callback};
226 AP->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->{vendor_id}) {
232 my $last_used_ap_chart = SL::DB::Vendor->load_cached($form->{vendor_id})->last_used_ap_chart;
233 $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
238 $main::lxdebug->leave_sub();
242 $main::lxdebug->enter_sub();
244 my $form = $main::form;
246 $main::auth->assert('ap_transactions');
248 $form->{title} = "Edit";
253 $main::lxdebug->leave_sub();
257 $main::lxdebug->enter_sub();
259 my $form = $main::form;
261 $main::auth->assert('ap_transactions');
263 # get all files stored in the webdav folder
264 if ($form->{invnumber} && $::instance_conf->get_webdav) {
265 my $webdav = SL::Webdav->new(
266 type => 'accounts_payable',
267 number => $form->{invnumber},
269 my @all_objects = $webdav->get_all_objects;
270 @{ $form->{WEBDAV} } = map { { name => $_->filename,
272 link => File::Spec->catfile($_->full_filedescriptor),
278 $main::lxdebug->leave_sub();
282 $main::lxdebug->enter_sub();
286 my $form = $main::form;
287 my %myconfig = %main::myconfig;
289 $main::auth->assert('ap_transactions');
291 $form->create_links("AP", \%myconfig, "vendor");
293 if (!$params{dont_save}) {
294 %saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
295 $saved{duedate} = $form->{duedate} if $form->{duedate};
296 $saved{currency} = $form->{currency} if $form->{currency};
297 $saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
300 IR->get_vendor(\%myconfig, \%$form);
302 $form->{$_} = $saved{$_} for keys %saved;
303 $form->{rowcount} = 1;
304 $form->{AP_chart_id} = $form->{acc_trans} && $form->{acc_trans}->{AP} ? $form->{acc_trans}->{AP}->[0]->{chart_id} : $form->{AP_links}->{AP}->[0]->{chart_id};
306 # build the popup menus
307 $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
310 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
312 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
314 $form->{employee} = "$form->{employee}--$form->{employee_id}";
316 AP->setup_form($form);
318 $main::lxdebug->leave_sub();
322 my @fields = qw(acc_trans_id gldate datepaid source memo paid AP_paid paid_project_id);
324 grep { $_->{paid} != 0 }
327 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
328 } (1..$::form->{paidaccounts});
330 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
332 $::form->{paidaccounts} = max scalar(@payments), 1;
334 foreach my $idx (1 .. scalar(@payments)) {
335 my $payment = $payments[$idx - 1];
336 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
341 $main::lxdebug->enter_sub();
343 my $form = $main::form;
344 my %myconfig = %main::myconfig;
345 my $locale = $main::locale;
346 my $cgi = $::request->{cgi};
348 $main::auth->assert('ap_transactions');
350 $::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
352 $form->{initial_focus} = !($form->{amount_1} * 1) ? 'vendor_id' : 'row_' . $form->{rowcount};
354 $form->{title_} = $form->{title};
355 $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
357 # type=submit $locale->text('Add Accounts Payables Transaction')
358 # type=submit $locale->text('Edit Accounts Payables Transaction')
360 my $readonly = $form->{id} ? "readonly" : "";
362 $form->{radier} = ($::instance_conf->get_ap_changeable == 2)
363 ? ($form->current_date(\%myconfig) eq $form->{gldate})
364 : ($::instance_conf->get_ap_changeable == 1);
365 $readonly = $form->{radier} ? "" : $readonly;
367 $form->{readonly} = $readonly;
369 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
370 if ( $form->{forex} ) {
371 $form->{exchangerate} = $form->{forex};
375 $form->{exchangerate} = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
376 $form->{creditlimit} = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
377 $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
380 if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
383 $form->{textarea_rows} = $rows;
385 $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
387 my @old_project_ids = ();
390 if ($form->{"project_id_$_"}) {
391 push(@old_project_ids, $form->{"project_id_$_"});
394 (1..$form->{"rowcount"})
397 $form->get_lists("projects" => { "key" => "ALL_PROJECTS",
399 "old_id" => \@old_project_ids },
400 "charts" => { "key" => "ALL_CHARTS",
401 "transdate" => $form->{transdate} },
402 "taxcharts" => { "key" => "ALL_TAXCHARTS",
403 "module" => "AP" },);
406 { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
407 @{ $form->{ALL_CHARTS} }
410 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
412 my %project_labels = ();
413 foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
414 $project_labels{$item->{id}} = $item->{projectnumber};
418 my $default_ap_amount_chart_id;
420 foreach my $item (@{ $form->{ALL_CHARTS} }) {
421 if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
422 $default_ap_amount_chart_id //= $item->{id};
424 } elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
425 push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
428 $charts{$item->{accno}} = $item;
431 my $follow_up_vc = $form->{vendor_id} ? SL::DB::Vendor->load_cached($form->{vendor_id})->name : '';
432 my $follow_up_trans_info = "$form->{invnumber} ($follow_up_vc)";
434 $::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", "kivi.File.js", "kivi.AP.js");
435 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
438 # $form->{totalpaid} is used by the action bar setup to determine
439 # whether or not canceling is allowed. Therefore it must be
440 # calculated prior to the action bar setup.
441 $form->{totalpaid} = sum map { $form->{"paid_${_}"} } (1..$form->{paidaccounts});
443 setup_ap_display_form_action_bar();
447 for my $i (1 .. $form->{rowcount}) {
450 $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
451 $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
453 my ($default_taxchart, $taxchart_to_use);
454 my $amount_chart_id = $form->{"AP_amount_chart_id_$i"} || $default_ap_amount_chart_id;
455 my $chart_has_changed = $::form->{"previous_AP_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AP_amount_chart_id_$i"});
456 my @taxcharts = GL->get_active_taxes_for_chart($amount_chart_id, $transdate);
458 foreach my $item (@taxcharts) {
459 my $key = $item->id . "--" . $item->rate;
460 $first_taxchart //= $item;
461 $default_taxchart = $item if $item->{is_default};
462 $taxchart_to_use = $item if $key eq $form->{"taxchart_$i"};
465 $taxchart_to_use = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
466 my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
467 $form->{"selected_taxchart_$i"} = $selected_taxchart;
468 $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
469 $form->{"taxcharts_$i"} = \@taxcharts;
472 $form->{taxchart_value_title_sub} = sub {
475 $item->{id} .'--'. $item->{rate},
476 $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
480 $form->{AP_paid_value_title_sub} = sub {
484 $item->{accno} .'--'. $item->{description}
488 $form->{invtotal_unformatted} = $form->{invtotal};
489 $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
493 if ( $form->{'paid_'. $form->{paidaccounts}} ) {
494 $form->{paidaccounts}++;
497 # default account for current assets (i.e. 1801 - SKR04)
498 $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
500 for my $i (1 .. $form->{paidaccounts}) {
502 if ($form->{"paid_$i"}) {
503 $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
505 if ($form->{"exchangerate_$i"} == 0) {
506 $form->{"exchangerate_$i"} = "";
508 $form->{"exchangerate_$i"} =
509 $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
513 if (SL::DB::Default->get->payments_changeable == 0) {
515 $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
517 if (SL::DB::Default->get->payments_changeable == 2) {
519 $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
522 #deaktivieren von gebuchten Zahlungen ausserhalb der BĂ¼cherkontrolle, vorher prĂ¼fen ob heute eingegeben
523 if ($form->date_closed($form->{"gldate_$i"})) {
527 $form->{'paidaccount_changeable_'. $i} = $changeable;
529 $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
532 $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
534 print $form->parse_html_template('ap/form_header', {
535 today => DateTime->today,
536 currencies => SL::DB::Manager::Currency->get_all_sorted,
539 $main::lxdebug->leave_sub();
543 $::lxdebug->enter_sub;
544 $::auth->assert('ap_transactions');
549 my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
551 if (@{ $follow_ups }) {
552 $num_due = sum map { $_->{due} * 1 } @{ $follow_ups };
553 $num_follow_ups = scalar @{ $follow_ups }
557 my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
558 my $closedto = $::form->datetonum($::form->{closedto}, \%::myconfig);
560 my $storno = $::form->{id}
561 && !IS->has_storno(\%::myconfig, $::form, 'ap')
562 && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
563 && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
566 print $::form->parse_html_template('ap/form_footer', {
568 num_follow_ups => $num_follow_ups,
571 $::lxdebug->leave_sub;
575 $::auth->assert('ap_transactions');
577 SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
579 $::form->redirect($::locale->text("Marked as paid"));
583 $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
584 $::form->{gldate} = $::form->{transdate} if !$::form->{gldate};
591 $main::lxdebug->enter_sub();
593 my $form = $main::form;
594 my %myconfig = %main::myconfig;
596 $main::auth->assert('ap_transactions');
600 $form->{invtotal} = 0;
602 delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
604 map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
605 qw(exchangerate creditlimit creditremaining);
607 my @flds = qw(amount AP_amount projectnumber oldprojectnumber project_id taxchart);
609 my (@a, $j, $totaltax);
610 for my $i (1 .. $form->{rowcount}) {
611 $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
612 if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
615 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
617 # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
619 ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
621 $totaltax += $form->{"tax_$i"};
622 map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
626 $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
628 map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
630 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
631 $form->{exchangerate} = $form->{forex} if $form->{forex};
633 $form->{invdate} = $form->{transdate};
635 if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
636 IR->get_vendor(\%::myconfig, $form);
639 $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
642 ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
645 for my $i (1 .. $form->{paidaccounts}) {
646 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
649 $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
650 } qw(paid exchangerate);
652 $totalpaid += $form->{"paid_$i"};
654 $form->{"forex_$i"} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
655 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
659 $form->{creditremaining} -=
660 ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
661 $form->{oldinvtotal});
662 $form->{oldinvtotal} = $form->{invtotal};
663 $form->{oldtotalpaid} = $totalpaid;
667 $main::lxdebug->leave_sub();
672 $main::lxdebug->enter_sub();
674 my $form = $main::form;
675 my %myconfig = %main::myconfig;
676 my $locale = $main::locale;
678 $main::auth->assert('ap_transactions');
679 $form->mtime_ischanged('ap');
681 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
683 my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
685 for my $i (1 .. $form->{paidaccounts}) {
686 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
687 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
689 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
691 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
692 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
694 #Zusätzlich noch das Buchungsdatum in die BĂ¼cherkontrolle einbeziehen
695 # (Dient zur PrĂ¼fung ob ZE oder ZA geprĂ¼ft werden soll)
696 $form->error($locale->text('Cannot post payment for a closed period!'))
697 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
699 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
700 $form->{"exchangerate_$i"} = $form->{exchangerate}
701 if ($invdate == $datepaid);
702 $form->isblank("exchangerate_$i",
703 $locale->text('Exchangerate for payment missing!'));
708 ($form->{AP}) = split /--/, $form->{AP};
709 ($form->{AP_paid}) = split /--/, $form->{AP_paid};
710 if (AP->post_payment(\%myconfig, \%$form)) {
711 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
712 $form->{what_done} = 'invoice';
713 $form->{addition} = "PAYMENT POSTED";
715 $form->redirect($locale->text('Payment posted!'))
717 $form->error($locale->text('Cannot post payment!'));
721 $main::lxdebug->leave_sub();
726 $main::lxdebug->enter_sub();
728 my $form = $main::form;
729 my %myconfig = %main::myconfig;
730 my $locale = $main::locale;
732 $main::auth->assert('ap_transactions');
733 $form->mtime_ischanged('ap');
737 # check if there is a vendor, invoice, due date and invnumber
738 $form->isblank("transdate", $locale->text("Invoice Date missing!"));
739 $form->isblank("duedate", $locale->text("Due Date missing!"));
740 $form->isblank("vendor_id", $locale->text('Vendor missing!'));
741 $form->isblank("invnumber", $locale->text('Invoice Number missing!'));
743 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
744 $form->{saved_message} = $::locale->text('You have to specify a department.');
749 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
750 my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
752 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
753 if ($form->date_max_future($form->{"transdate"}, \%myconfig));
754 $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
756 my $zero_amount_posting = 1;
757 for my $i (1 .. $form->{rowcount}) {
758 if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
759 $zero_amount_posting = 0;
764 $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
766 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
767 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
770 for my $i (1 .. $form->{paidaccounts}) {
771 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
772 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
774 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
776 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
777 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
779 #Zusätzlich noch das Buchungsdatum in die BĂ¼cherkontrolle einbeziehen
780 # (Dient zur PrĂ¼fung ob ZE oder ZA geprĂ¼ft werden soll)
781 $form->error($locale->text('Cannot post payment for a closed period!'))
782 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
784 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
785 $form->{"exchangerate_$i"} = $form->{exchangerate}
786 if ($transdate == $datepaid);
787 $form->isblank("exchangerate_$i",
788 $locale->text('Exchangerate for payment missing!'));
794 # if old vendor ne vendor redo form
795 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
797 $::dispatcher->end_request;
801 $form->{id} = 0 if $form->{postasnew};
803 if (AP->post_transaction(\%myconfig, \%$form)) {
804 # create webdav folder
805 if ($::instance_conf->get_webdav) {
806 SL::Webdav->new(type => 'accounts_payable',
807 number => $form->{invnumber},
811 if(!exists $form->{addition} && $form->{id} ne "") {
812 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
813 $form->{addition} = "POSTED";
814 $form->{what_done} = "invoice";
817 # /saving the history
818 # Dieser Text wird niemals ausgegeben: Probleme beim redirect?
819 $form->redirect($locale->text('AP transaction posted.')) unless $inline;
821 $form->error($locale->text('Cannot post transaction!'));
824 $main::lxdebug->leave_sub();
828 $main::lxdebug->enter_sub();
830 my $form = $main::form;
831 my %myconfig = %main::myconfig;
833 $main::auth->assert('ap_transactions');
835 $form->{postasnew} = 1;
837 if(!exists $form->{addition} && $form->{id} ne "") {
838 # does this work? post_as_new for ap doesn't immediately save the
839 # invoice, because the invnumber has to be entered by hand.
840 # And the value of $form->{postasnew} isn't checked when calling post
841 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
842 $form->{addition} = "POSTED AS NEW";
843 $form->{what_done} = "invoice";
846 # /saving the history
849 $main::lxdebug->leave_sub();
853 $main::lxdebug->enter_sub();
855 my $form = $main::form;
856 my %myconfig = %main::myconfig;
858 $main::auth->assert('ap_transactions');
860 map { delete $form->{$_} } qw(printed emailed queued invnumber deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
861 $form->{paidaccounts} = 1;
864 my $today = DateTime->today_local;
865 $form->{transdate} = $today->to_kivitendo;
866 $form->{duedate} = $form->{transdate};
868 if ($form->{vendor_id}) {
869 my $payment_terms = SL::DB::Vendor->load_cached($form->{vendor_id})->payment;
870 $form->{duedate} = $payment_terms->calc_date(reference_date => $today)->to_kivitendo if $payment_terms;
875 $main::lxdebug->leave_sub();
879 my $form = $main::form;
880 my %myconfig = %main::myconfig;
881 my $locale = $main::locale;
883 $main::auth->assert('ap_transactions');
885 if (AP->delete_transaction(\%myconfig, \%$form)) {
887 if(!exists $form->{addition}) {
888 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
889 $form->{addition} = "DELETED";
890 $form->{what_done} = "invoice";
893 # /saving the history
894 $form->redirect($locale->text('Transaction deleted!'));
896 $form->error($locale->text('Cannot delete transaction!'));
900 $main::lxdebug->enter_sub();
902 $main::auth->assert('vendor_invoice_edit');
904 my $form = $main::form;
905 my %myconfig = %main::myconfig;
906 my $locale = $main::locale;
908 $form->{title} = $locale->text('AP Transactions');
910 $form->get_lists(projects => { "key" => "ALL_PROJECTS", "all" => 1 });
912 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
913 # constants and subs for template
914 $form->{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
916 $::request->layout->add_javascripts("autocomplete_project.js");
919 print $form->parse_html_template('ap/search', { %myconfig });
921 $main::lxdebug->leave_sub();
924 sub create_subtotal_row {
925 $main::lxdebug->enter_sub();
927 my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
929 my $form = $main::form;
930 my %myconfig = %main::myconfig;
932 my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
934 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
936 $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
938 map { $totals->{$_} = 0 } @{ $subtotal_columns };
940 $main::lxdebug->leave_sub();
945 sub ap_transactions {
946 $main::lxdebug->enter_sub();
948 my $form = $main::form;
949 my %myconfig = %main::myconfig;
950 my $locale = $main::locale;
952 $main::auth->assert('vendor_invoice_edit');
954 report_generator_set_default_sort('transdate', 1);
956 AP->ap_transactions(\%myconfig, \%$form);
958 $form->{title} = $locale->text('AP Transactions');
960 my $report = SL::ReportGenerator->new(\%myconfig, $form);
963 qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
964 due duedate transaction_description notes employee globalprojectnumber
965 vendornumber country ustid taxzone payment_terms charts direct_debit);
967 my @hidden_variables = map { "l_${_}" } @columns;
968 push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto
969 parts_partnumber parts_description);
971 my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
974 'transdate' => { 'text' => $locale->text('Date'), },
975 'id' => { 'text' => $locale->text('ID'), },
976 'type' => { 'text' => $locale->text('Type'), },
977 'invnumber' => { 'text' => $locale->text('Invoice'), },
978 'ordnumber' => { 'text' => $locale->text('Order'), },
979 'name' => { 'text' => $locale->text('Vendor'), },
980 'netamount' => { 'text' => $locale->text('Amount'), },
981 'tax' => { 'text' => $locale->text('Tax'), },
982 'amount' => { 'text' => $locale->text('Total'), },
983 'paid' => { 'text' => $locale->text('Paid'), },
984 'datepaid' => { 'text' => $locale->text('Date Paid'), },
985 'due' => { 'text' => $locale->text('Amount Due'), },
986 'duedate' => { 'text' => $locale->text('Due Date'), },
987 'transaction_description' => { 'text' => $locale->text('Transaction description'), },
988 'notes' => { 'text' => $locale->text('Notes'), },
989 'employee' => { 'text' => $locale->text('Employee'), },
990 'globalprojectnumber' => { 'text' => $locale->text('Document Project Number'), },
991 'vendornumber' => { 'text' => $locale->text('Vendor Number'), },
992 'country' => { 'text' => $locale->text('Country'), },
993 'ustid' => { 'text' => $locale->text('USt-IdNr.'), },
994 'taxzone' => { 'text' => $locale->text('Tax rate'), },
995 'payment_terms' => { 'text' => $locale->text('Payment Terms'), },
996 'charts' => { 'text' => $locale->text('Buchungskonto'), },
997 'direct_debit' => { 'text' => $locale->text('direct debit'), },
1000 foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
1001 my $sortdir = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1002 $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1005 my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1007 $form->{"l_type"} = "Y";
1008 map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1010 $report->set_columns(%column_defs);
1011 $report->set_column_order(@columns);
1013 $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
1015 $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1018 push @options, $locale->text('Vendor') . " : $form->{vendor}" if ($form->{vendor});
1019 push @options, $locale->text('Contact Person') . " : $form->{cp_name}" if ($form->{cp_name});
1020 push @options, $locale->text('Department') . " : $form->{department}" if ($form->{department});
1021 push @options, $locale->text('Invoice Number') . " : $form->{invnumber}" if ($form->{invnumber});
1022 push @options, $locale->text('Order Number') . " : $form->{ordnumber}" if ($form->{ordnumber});
1023 push @options, $locale->text('Notes') . " : $form->{notes}" if ($form->{notes});
1024 push @options, $locale->text('Transaction description') . " : $form->{transaction_description}" if ($form->{transaction_description});
1025 push @options, $locale->text('Part Description') . " : $form->{parts_description}" if $form->{parts_description};
1026 push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}" if $form->{parts_partnumber};
1027 push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1) if ($form->{transdatefrom});
1028 push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1) if ($form->{transdateto});
1029 push @options, $locale->text('Open') if ($form->{open});
1030 push @options, $locale->text('Closed') if ($form->{closed});
1032 $report->set_options('top_info_text' => join("\n", @options),
1033 'raw_bottom_info_text' => $form->parse_html_template('ap/ap_transactions_bottom'),
1034 'output_format' => 'HTML',
1035 'title' => $form->{title},
1036 'attachment_basename' => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
1038 $report->set_options_from_form();
1039 $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1041 # add sort and escape callback, this one we use for the add sub
1042 $form->{callback} = $href .= "&sort=$form->{sort}";
1044 # escape callback for href
1045 my $callback = $form->escape($href);
1047 my @subtotal_columns = qw(netamount amount paid due);
1049 my %totals = map { $_ => 0 } @subtotal_columns;
1050 my %subtotals = map { $_ => 0 } @subtotal_columns;
1054 foreach my $ap (@{ $form->{AP} }) {
1055 $ap->{tax} = $ap->{amount} - $ap->{netamount};
1056 $ap->{due} = $ap->{amount} - $ap->{paid};
1058 map { $subtotals{$_} += $ap->{$_};
1059 $totals{$_} += $ap->{$_} } @subtotal_columns;
1061 map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
1063 my $is_storno = $ap->{storno} && $ap->{storno_id};
1064 my $has_storno = $ap->{storno} && !$ap->{storno_id};
1066 if ($ap->{invoice}) {
1068 $has_storno ? $locale->text("Invoice with Storno (abbreviation)")
1069 : $is_storno ? $locale->text("Storno (one letter abbreviation)")
1070 : $locale->text("Invoice (one letter abbreviation)");
1073 $has_storno ? $locale->text("AP Transaction with Storno (abbreviation)")
1074 : $is_storno ? $locale->text("AP Transaction Storno (one letter abbreviation)")
1075 : $locale->text("AP Transaction (abbreviation)");
1078 $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1082 foreach my $column (@columns) {
1084 'data' => $ap->{$column},
1085 'align' => $column_alignment{$column},
1089 $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
1090 . "&id=" . E($ap->{id}) . "&callback=${callback}";
1092 my $row_set = [ $row ];
1094 if (($form->{l_subtotal} eq 'Y')
1095 && (($idx == (scalar @{ $form->{AP} } - 1))
1096 || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
1097 push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1100 $report->add_data($row_set);
1105 $report->add_separator();
1106 $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1108 $report->generate_with_headers();
1110 $main::lxdebug->leave_sub();
1114 $main::lxdebug->enter_sub();
1116 my $form = $main::form;
1117 my %myconfig = %main::myconfig;
1118 my $locale = $main::locale;
1120 $main::auth->assert('ap_transactions');
1122 if (IS->has_storno(\%myconfig, $form, 'ap')) {
1123 $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
1124 $form->error($locale->text("Transaction has already been cancelled!"));
1127 $form->error($locale->text('Cannot post storno for a closed period!'))
1128 if ( $form->date_closed($form->{transdate}, \%myconfig));
1130 AP->storno($form, \%myconfig, $form->{id});
1132 # saving the history
1133 if(!exists $form->{addition} && $form->{id} ne "") {
1134 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1135 $form->{addition} = "STORNO";
1136 $form->{what_done} = "invoice";
1137 $form->save_history;
1139 # /saving the history
1141 $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1143 $main::lxdebug->leave_sub();
1146 sub setup_ap_display_form_action_bar {
1147 my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
1148 my $closedto = $::form->datetonum($::form->{closedto}, \%::myconfig);
1149 my $is_closed = $transdate <= $closedto;
1151 my $change_never = $::instance_conf->get_ar_changeable == 0;
1152 my $change_on_same_day_only = $::instance_conf->get_ar_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
1154 my $is_storno = IS->is_storno(\%::myconfig, $::form, 'ap', $::form->{id});
1155 my $has_storno = IS->has_storno(\%::myconfig, $::form, 'ap');
1157 for my $bar ($::request->layout->get('actionbar')) {
1161 submit => [ '#form', { action => "update" } ],
1162 id => 'update_button',
1163 accesskey => 'enter',
1169 submit => [ '#form', { action => "post" } ],
1170 checks => [ 'kivi.AP.check_fields_before_posting' ],
1171 disabled => $is_closed ? t8('The billing period has already been locked.')
1172 : $is_storno ? t8('A canceled invoice cannot be posted.')
1173 : ($::form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
1174 : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
1179 submit => [ '#form', { action => "post_payment" } ],
1180 disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1182 action => [ t8('Mark as paid'),
1183 submit => [ '#form', { action => "mark_as_paid" } ],
1184 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
1185 disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1186 only_if => $::instance_conf->get_is_show_mark_as_paid,
1188 ], # end of combobox "Post"
1191 action => [ t8('Storno'),
1192 submit => [ '#form', { action => "storno" } ],
1193 checks => [ 'kivi.AP.check_fields_before_posting' ],
1194 confirm => t8('Do you really want to cancel this invoice?'),
1195 disabled => !$::form->{id} ? t8('This invoice has not been posted yet.')
1196 : $has_storno ? t8('This invoice has been canceled already.')
1197 : $is_storno ? t8('Reversal invoices cannot be canceled.')
1198 : $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
1201 action => [ t8('Delete'),
1202 submit => [ '#form', { action => "delete" } ],
1203 confirm => t8('Do you really want to delete this object?'),
1204 disabled => !$::form->{id} ? t8('This invoice has not been posted yet.')
1205 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
1206 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
1207 : $has_storno ? t8('This invoice has been canceled already.')
1208 : $is_closed ? t8('The billing period has already been locked.')
1211 ], # end of combobox "Storno"
1216 action => [ t8('Workflow') ],
1219 submit => [ '#form', { action => "use_as_new" } ],
1220 disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1222 ], # end of combobox "Workflow"
1225 action => [ t8('more') ],
1228 call => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
1229 disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1233 call => [ 'follow_up_window' ],
1234 disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1237 t8('Record templates'),
1238 call => [ 'kivi.RecordTemplate.popup', 'ap_transaction' ],
1242 call => [ 'kivi.Draft.popup', 'ap', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
1243 disabled => $::form->{id} ? t8('This invoice has already been posted.')
1244 : $is_closed ? t8('The billing period has already been locked.')
1247 ], # end of combobox "more"