Projekt

Allgemein

Profil

Herunterladen (62,4 KB) Statistiken
| Zweig: | Markierung: | Revision:
d319704a Moritz Bunkus
#=====================================================================
# LX-Office ERP
# Copyright (C) 2004
# Based on SQL-Ledger Version 2.1.9
# Web http://www.lx-office.org
#
#=====================================================================
# SQL-Ledger Accounting
# Copyright (c) 2001
#
# Author: Dieter Simader
# Email: dsimader@sql-ledger.org
# Web: http://www.sql-ledger.org
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
f7b15d43 Christian Wittmer
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1335, USA.
d319704a Moritz Bunkus
#======================================================================
#
# Accounts Payables
#
#======================================================================

e71494c1 Moritz Bunkus
use POSIX qw(strftime);
7e2bc8a0 Moritz Bunkus
use List::Util qw(first max sum);
0d37f1e8 Moritz Bunkus
use List::UtilsBy qw(sort_by);
e71494c1 Moritz Bunkus
d319704a Moritz Bunkus
use SL::AP;
7a7f33b5 Moritz Bunkus
use SL::FU;
0fa80981 Moritz Bunkus
use SL::GL;
850ba82b Bernd Bleßmann
use SL::Helper::Flash qw(flash flash_later);
d319704a Moritz Bunkus
use SL::IR;
6d544157 Sven Schöling
use SL::IS;
e71494c1 Moritz Bunkus
use SL::ReportGenerator;
b3259be1 Jan Büren
use SL::DB::BankTransactionAccTrans;
9e30e4f6 Jan Büren
use SL::DB::Chart;
122f91e7 Moritz Bunkus
use SL::DB::Currency;
97954312 Bernd Bleßmann
use SL::DB::Default;
b008860a Bernd Bleßmann
use SL::DB::InvoiceItem;
6e083cb8 Bernd Bleßmann
use SL::DB::Order;
8b5bed7f Sven Schöling
use SL::DB::PaymentTerm;
267cb279 Moritz Bunkus
use SL::DB::PurchaseInvoice;
7e2bc8a0 Moritz Bunkus
use SL::DB::RecordTemplate;
use SL::DB::Tax;
822fc676 Bernd Bleßmann
use SL::DB::ValidityToken;
b008860a Bernd Bleßmann
use SL::Presenter::ItemsList;
9d0aef99 Jan Büren
use SL::Webdav;
use SL::Locale::String qw(t8);
d319704a Moritz Bunkus
a4b22a8f Moritz Bunkus
require "bin/mozilla/common.pl";
18da4a96 Moritz Bunkus
require "bin/mozilla/reportgenerator.pl";
d319704a Moritz Bunkus
088b52b5 Sven Schöling
use strict;

d319704a Moritz Bunkus
1;

# end of main

# this is for our long dates
# $locale->text('January')
# $locale->text('February')
# $locale->text('March')
# $locale->text('April')
# $locale->text('May ')
# $locale->text('June')
# $locale->text('July')
# $locale->text('August')
# $locale->text('September')
# $locale->text('October')
# $locale->text('November')
# $locale->text('December')

# this is for our short month
# $locale->text('Jan')
# $locale->text('Feb')
# $locale->text('Mar')
# $locale->text('Apr')
# $locale->text('May')
# $locale->text('Jun')
# $locale->text('Jul')
# $locale->text('Aug')
# $locale->text('Sep')
# $locale->text('Oct')
# $locale->text('Nov')
# $locale->text('Dec')

894ac4ca Moritz Bunkus
sub _may_view_or_edit_this_invoice {
return 1 if $::auth->assert('ap_transactions', 1); # may edit all invoices
return 0 if !$::form->{id}; # creating new invoices isn't allowed without invoice_edit
return 0 if !$::form->{globalproject_id}; # existing records without a project ID are not allowed
return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
}

sub _assert_access {
my $cache = $::request->cache('ap.pl::_assert_access');

$cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice() if !exists $cache->{_may_view_or_edit_this_invoice};
$::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if ! $cache->{_may_view_or_edit_this_invoice};
}

7e2bc8a0 Moritz Bunkus
sub load_record_template {
$::auth->assert('ap_transactions');

# Load existing template and verify that its one for this module.
my $template = SL::DB::RecordTemplate
->new(id => $::form->{id})
->load(
with_object => [ qw(customer payment currency record_items record_items.chart) ],
);

die "invalid template type" unless $template->template_type eq 'ap_transaction';

$template->substitute_variables;

# Clean the current $::form before rebuilding it from the template.
24097357 Moritz Bunkus
my $form_defaults = delete $::form->{form_defaults};
7e2bc8a0 Moritz Bunkus
delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };

# Fill $::form from the template.
my $today = DateTime->today_local;
$::form->{title} = "Add";
$::form->{currency} = $template->currency->name;
$::form->{direct_debit} = $template->direct_debit;
$::form->{globalproject_id} = $template->project_id;
e21e2190 Sven Schöling
$::form->{payment_id} = $template->payment_id;
7e2bc8a0 Moritz Bunkus
$::form->{AP_chart_id} = $template->ar_ap_chart_id;
$::form->{transdate} = $today->to_kivitendo;
$::form->{duedate} = $today->to_kivitendo;
101b9705 Moritz Bunkus
$::form->{rowcount} = @{ $template->items };
7e2bc8a0 Moritz Bunkus
$::form->{paidaccounts} = 1;
02476401 Bernd Bleßmann
$::form->{$_} = $template->$_ for qw(department_id ordnumber taxincluded notes transaction_description);
7e2bc8a0 Moritz Bunkus
if ($template->vendor) {
$::form->{vendor_id} = $template->vendor_id;
$::form->{vendor} = $template->vendor->name;
ba629467 Bernd Bleßmann
$::form->{duedate} = $template->vendor->payment->calc_date(reference_date => $today)->to_kivitendo if $template->vendor->payment;
7e2bc8a0 Moritz Bunkus
}

my $row = 0;
foreach my $item (@{ $template->items }) {
$row++;

my $active_taxkey = $item->chart->get_active_taxkey;
my $taxes = SL::DB::Manager::Tax->get_all(
where => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
sort_by => 'taxkey, rate',
);

my $tax = first { $item->tax_id == $_->id } @{ $taxes };
$tax //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
$tax //= $taxes->[0];

if (!$tax) {
$row--;
next;
}

$::form->{"AP_amount_chart_id_${row}"} = $item->chart_id;
$::form->{"previous_AP_amount_chart_id_${row}"} = $item->chart_id;
$::form->{"amount_${row}"} = $::form->format_amount(\%::myconfig, $item->amount1, 2);
$::form->{"taxchart_${row}"} = $item->tax_id . '--' . $tax->rate;
$::form->{"project_id_${row}"} = $item->project_id;
}

24097357 Moritz Bunkus
$::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };

7e2bc8a0 Moritz Bunkus
flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
ce5a051e Jan Büren
flash('info', $::locale->text("Payment bookings disallowed. After the booking this record may be " .
"suggested with the amount of '#1' or otherwise has to be choosen manually." .
" No automatic payment booking will be done to chart '#2'.",
da6ff55e Jan Büren
$form_defaults->{paid_1_suggestion},
$form_defaults->{AP_paid_1_suggestion},
)) if $::form->{no_payment_bookings};
7e2bc8a0 Moritz Bunkus
822fc676 Bernd Bleßmann
$::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST())->token;

101b9705 Moritz Bunkus
update(
keep_rows_without_amount => 1,
dont_add_new_row => 1,
);
7e2bc8a0 Moritz Bunkus
}

1ca98d42 Moritz Bunkus
sub save_record_template {
$::auth->assert('ap_transactions');

my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
my $js = SL::ClientJS->new(controller => SL::Controller::Base->new);
my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});

$js->dialog->close('#record_template_dialog');

my @items = grep {
101b9705 Moritz Bunkus
$_->{chart_id} && (($_->{tax_id} // '') ne '')
1ca98d42 Moritz Bunkus
} map {
+{ chart_id => $::form->{"AP_amount_chart_id_${_}"},
amount1 => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
tax_id => (split m{--}, $::form->{"taxchart_${_}"})[0],
project_id => $::form->{"project_id_${_}"} || undef,
}
} (1..($::form->{rowcount} || 1));

$template->assign_attributes(
ba629467 Bernd Bleßmann
template_type => 'ap_transaction',
template_name => $new_name,

currency_id => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
ar_ap_chart_id => $::form->{AP_chart_id} || undef,
vendor_id => $::form->{vendor_id} || undef,
department_id => $::form->{department_id} || undef,
project_id => $::form->{globalproject_id} || undef,
payment_id => $::form->{payment_id} || undef,
taxincluded => $::form->{taxincluded} ? 1 : 0,
direct_debit => $::form->{direct_debit} ? 1 : 0,
ordnumber => $::form->{ordnumber},
notes => $::form->{notes},
02476401 Bernd Bleßmann
transaction_description => $::form->{transaction_description},
1ca98d42 Moritz Bunkus
ba629467 Bernd Bleßmann
items => \@items,
1ca98d42 Moritz Bunkus
);

eval {
$template->save;
1;
} or do {
return $js
->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
->render;
};

return $js
->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
->render;
}

d319704a Moritz Bunkus
sub add {
088b52b5 Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my %myconfig = %main::myconfig;
d319704a Moritz Bunkus
25d67207 Martin Helmling
$main::auth->assert('ap_transactions');
8c7e4493 Moritz Bunkus
d319704a Moritz Bunkus
$form->{title} = "Add";

62726dfd Sven Schöling
$form->{callback} = "ap.pl?action=add" unless $form->{callback};
d319704a Moritz Bunkus
2387a1fc Moritz Bunkus
AP->get_transdate(\%myconfig, $form);
d0b49f67 Moritz Bunkus
$form->{initial_transdate} = $form->{transdate};
d623e974 Moritz Bunkus
create_links(dont_save => 1);
d0b49f67 Moritz Bunkus
$form->{transdate} = $form->{initial_transdate};
40cfb5ee Geoffrey Richardson
0fa80981 Moritz Bunkus
if ($form->{vendor_id}) {
8b5bed7f Sven Schöling
my $vendor = SL::DB::Vendor->load_cached($form->{vendor_id});

# set initial payment terms
$form->{payment_id} = $vendor->payment_id;

my $last_used_ap_chart = $vendor->last_used_ap_chart;
0fa80981 Moritz Bunkus
$form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
}

822fc676 Bernd Bleßmann
if (!$form->{form_validity_token}) {
$form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST())->token;
}

d319704a Moritz Bunkus
&display_form;

088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

sub edit {
088b52b5 Sven Schöling
$main::lxdebug->enter_sub();

894ac4ca Moritz Bunkus
# Delay access check to after the invoice's been loaded in
# "create_links" so that project-specific invoice rights can be
# evaluated.
d319704a Moritz Bunkus
894ac4ca Moritz Bunkus
my $form = $main::form;
8c7e4493 Moritz Bunkus
d319704a Moritz Bunkus
$form->{title} = "Edit";

d623e974 Moritz Bunkus
create_links();
d319704a Moritz Bunkus
&display_form;

088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

sub display_form {
088b52b5 Sven Schöling
$main::lxdebug->enter_sub();
d319704a Moritz Bunkus
894ac4ca Moritz Bunkus
_assert_access();
088b52b5 Sven Schöling
894ac4ca Moritz Bunkus
my $form = $main::form;
8c7e4493 Moritz Bunkus
9d0aef99 Jan Büren
# get all files stored in the webdav folder
if ($form->{invnumber} && $::instance_conf->get_webdav) {
my $webdav = SL::Webdav->new(
type => 'accounts_payable',
number => $form->{invnumber},
);
my @all_objects = $webdav->get_all_objects;
@{ $form->{WEBDAV} } = map { { name => $_->filename,
type => t8('File'),
359506e5 Jan Büren
link => File::Spec->catfile($_->full_filedescriptor),
9d0aef99 Jan Büren
} } @all_objects;
}
d319704a Moritz Bunkus
&form_header;
&form_footer;

088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

sub create_links {
088b52b5 Sven Schöling
$main::lxdebug->enter_sub();

894ac4ca Moritz Bunkus
# Delay access check to after the invoice's been loaded so that
# project-specific invoice rights can be evaluated.

d623e974 Moritz Bunkus
my %params = @_;

088b52b5 Sven Schöling
my $form = $main::form;
my %myconfig = %main::myconfig;
d319704a Moritz Bunkus
$form->create_links("AP", \%myconfig, "vendor");
894ac4ca Moritz Bunkus
_assert_access();

d623e974 Moritz Bunkus
my %saved;
if (!$params{dont_save}) {
%saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
$saved{duedate} = $form->{duedate} if $form->{duedate};
76785737 Geoffrey Richardson
$saved{currency} = $form->{currency} if $form->{currency};
e50ac26b Geoffrey Richardson
$saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
66da2b7d Jan Büren
$saved{intnotes} = $form->{intnotes} if $form->{intnotes};
d623e974 Moritz Bunkus
}
d319704a Moritz Bunkus
IR->get_vendor(\%myconfig, \%$form);
d623e974 Moritz Bunkus
$form->{$_} = $saved{$_} for keys %saved;
30175d89 Philip Reetz
$form->{rowcount} = 1;
ec8a10a0 Werner Hahn
$form->{AP_chart_id} = $form->{acc_trans} && $form->{acc_trans}->{AP} ? $form->{acc_trans}->{AP}->[0]->{chart_id} : $::instance_conf->get_ap_chart_id || $form->{AP_links}->{AP}->[0]->{chart_id};
d319704a Moritz Bunkus
# build the popup menus
$form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";

2dcf4554 Moritz Bunkus
$::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
d319704a Moritz Bunkus
$form->{employee} = "$form->{employee}--$form->{employee_id}";

1118dab9 Moritz Bunkus
AP->setup_form($form);
d319704a Moritz Bunkus
088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

0d37f1e8 Moritz Bunkus
sub _sort_payments {
83b760fb Martin Helmling
my @fields = qw(acc_trans_id gldate datepaid source memo paid AP_paid paid_project_id);
0d37f1e8 Moritz Bunkus
my @payments =
grep { $_->{paid} != 0 }
map {
my $idx = $_;
+{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
} (1..$::form->{paidaccounts});

@payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;

$::form->{paidaccounts} = max scalar(@payments), 1;

foreach my $idx (1 .. scalar(@payments)) {
my $payment = $payments[$idx - 1];
$::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
}
}

d319704a Moritz Bunkus
sub form_header {
088b52b5 Sven Schöling
$main::lxdebug->enter_sub();
d319704a Moritz Bunkus
894ac4ca Moritz Bunkus
_assert_access();

088b52b5 Sven Schöling
my $form = $main::form;
my %myconfig = %main::myconfig;
my $locale = $main::locale;
5494f687 Sven Schöling
my $cgi = $::request->{cgi};
8c7e4493 Moritz Bunkus
267cb279 Moritz Bunkus
$::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};

2dcf4554 Moritz Bunkus
$form->{initial_focus} = !($form->{amount_1} * 1) ? 'vendor_id' : 'row_' . $form->{rowcount};
0fa80981 Moritz Bunkus
46231fcc Thomas Heck
$form->{title_} = $form->{title};
6959bb5e Moritz Bunkus
$form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
d319704a Moritz Bunkus
# type=submit $locale->text('Add Accounts Payables Transaction')
# type=submit $locale->text('Edit Accounts Payables Transaction')

40a94352 Jan Büren
# currencies
$form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
36a93d2e Jan Büren
if ($form->{currency} ne $form->{defaultcurrency} && !$form->{exchangerate}) {
($form->{exchangerate}, $form->{record_forex}) = $form->{id}
? $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, "sell", $form->{id}, 'ap')
: $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, "sell");
46231fcc Thomas Heck
}
fb37acdc Moritz Bunkus
d319704a Moritz Bunkus
# format amounts
ae45c5b7 Sven Schöling
$form->{creditlimit} = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
$form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
d319704a Moritz Bunkus
088b52b5 Sven Schöling
my $rows;
d319704a Moritz Bunkus
if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
$rows = 2;
}
46231fcc Thomas Heck
$form->{textarea_rows} = $rows;

$form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
d319704a Moritz Bunkus
affd886b Sven Schöling
$form->get_lists("charts" => { "key" => "ALL_CHARTS",
797ad4c5 Moritz Bunkus
"transdate" => $form->{transdate} },
2a670c1c Jan Büren
);
d0b49f67 Moritz Bunkus
46231fcc Thomas Heck
map(
{ $_->{link_split} = [ split(/:/, $_->{link}) ]; }
@{ $form->{ALL_CHARTS} }
);
f01741e3 Moritz Bunkus
2b37ad3a Jan Büren
$form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
40cfb5ee Geoffrey Richardson
affd886b Sven Schöling
my %project_labels = map { $_->id => $_->projectnumber } @{ SL::DB::Manager::Project->get_all };
f01741e3 Moritz Bunkus
22ad5a29 Jan Büren
my (%charts, %bank_accounts);
0fa80981 Moritz Bunkus
my $default_ap_amount_chart_id;
22ad5a29 Jan Büren
# don't add manual bookings for charts which are assigned to real bank accounts
67da170f Cem Aydin
# and are flagged for use with bank import
22ad5a29 Jan Büren
my $bank_accounts = SL::DB::Manager::BankAccount->get_all();
foreach my $bank (@{ $bank_accounts }) {
67da170f Cem Aydin
if ($bank->use_with_bank_import) {
my $accno_paid_bank = $bank->chart->accno;
$bank_accounts{$accno_paid_bank} = 1;
}
22ad5a29 Jan Büren
}
d0b49f67 Moritz Bunkus
foreach my $item (@{ $form->{ALL_CHARTS} }) {
9fe00490 Thomas Heck
if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
0fa80981 Moritz Bunkus
$default_ap_amount_chart_id //= $item->{id};
9fe00490 Thomas Heck
0fa80981 Moritz Bunkus
} elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
22ad5a29 Jan Büren
next if $bank_accounts{$item->{accno}};
9fe00490 Thomas Heck
push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
d0b49f67 Moritz Bunkus
}

$charts{$item->{accno}} = $item;
}

2dcf4554 Moritz Bunkus
my $follow_up_vc = $form->{vendor_id} ? SL::DB::Vendor->load_cached($form->{vendor_id})->name : '';
7a7f33b5 Moritz Bunkus
my $follow_up_trans_info = "$form->{invnumber} ($follow_up_vc)";

31d15c5a Sven Schöling
$::request->layout->add_javascripts("autocomplete_chart.js", "show_vc_details.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.SalesPurchase.js", "kivi.GL.js", "kivi.RecordTemplate.js", "kivi.File.js", "kivi.AP.js", "kivi.CustomerVendor.js", "kivi.Validator.js", "autocomplete_project.js");
4baae198 Moritz Bunkus
# $form->{totalpaid} is used by the action bar setup to determine
# whether or not canceling is allowed. Therefore it must be
# calculated prior to the action bar setup.
$form->{totalpaid} = sum map { $form->{"paid_${_}"} } (1..$form->{paidaccounts});

4507456b Moritz Bunkus
setup_ap_display_form_action_bar();

9fe00490 Thomas Heck
$form->header();
5c95eda7 Jan Büren
# get the correct date for tax
my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
my $taxdate = $deliverydate ? $deliverydate : $transdate;
# helper for loop
52b04172 Jan Büren
my $first_taxchart;

088b52b5 Sven Schöling
for my $i (1 .. $form->{rowcount}) {
d319704a Moritz Bunkus
# format amounts
46231fcc Thomas Heck
$form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
30175d89 Philip Reetz
$form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
d0b49f67 Moritz Bunkus
0fa80981 Moritz Bunkus
my ($default_taxchart, $taxchart_to_use);
731991d4 Geoffrey Richardson
my $used_tax_id;
if ( $form->{"taxchart_$i"} ) {
($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
}
967813e1 Moritz Bunkus
my $amount_chart_id = $form->{"AP_amount_chart_id_$i"} || $default_ap_amount_chart_id;
d0b49f67 Moritz Bunkus
5c95eda7 Jan Büren
my @taxcharts = GL->get_active_taxes_for_chart($amount_chart_id, $taxdate, $used_tax_id);
6e594d28 Moritz Bunkus
foreach my $item (@taxcharts) {
0fa80981 Moritz Bunkus
my $key = $item->id . "--" . $item->rate;
$first_taxchart //= $item;
$default_taxchart = $item if $item->{is_default};
$taxchart_to_use = $item if $key eq $form->{"taxchart_$i"};
d0b49f67 Moritz Bunkus
}

967813e1 Moritz Bunkus
$taxchart_to_use //= $default_taxchart // $first_taxchart;
0fa80981 Moritz Bunkus
my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
$form->{"selected_taxchart_$i"} = $selected_taxchart;
$form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
6e594d28 Moritz Bunkus
$form->{"taxcharts_$i"} = \@taxcharts;
57342517 Jan Büren
# reverse charge hack for template, display two taxes
5a1856a8 Jan Büren
if ($taxchart_to_use->reverse_charge_chart_id) {
57342517 Jan Büren
my $tmpnetamount;
5a1856a8 Jan Büren
($tmpnetamount, $form->{"tax_reverse_$i"}) = $form->calculate_tax($form->parse_amount(\%myconfig, $form->{"amount_$i"}),
$taxchart_to_use->rate, $form->{taxincluded}, 2 );

57342517 Jan Büren
$form->{"tax_charge_$i"} = $form->{"tax_reverse_$i"} * -1;
$form->{"tax_reverse_$i"} = $form->format_amount(\%myconfig, $form->{"tax_reverse_$i"}, 2);
$form->{"tax_charge_$i"} = $form->format_amount(\%myconfig, $form->{"tax_charge_$i"}, 2);
}
d319704a Moritz Bunkus
}

9fe00490 Thomas Heck
$form->{taxchart_value_title_sub} = sub {
my $item = shift;
return [
$item->{id} .'--'. $item->{rate},
2302fc97 Geoffrey Richardson
$item->{taxkey} . ' - ' . $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
9fe00490 Thomas Heck
];
};

$form->{AP_paid_value_title_sub} = sub {
my $item = shift;
return [
$item->{accno},
$item->{accno} .'--'. $item->{description}
];
};

4d20c181 Moritz Bunkus
$form->{invtotal_unformatted} = $form->{invtotal};
30175d89 Philip Reetz
$form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
d319704a Moritz Bunkus
0d37f1e8 Moritz Bunkus
_sort_payments();

46231fcc Thomas Heck
if ( $form->{'paid_'. $form->{paidaccounts}} ) {
$form->{paidaccounts}++;
}
5be8f312 Jan Büren
# default account for current assets (i.e. 1801 - SKR04)
$form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);

088b52b5 Sven Schöling
for my $i (1 .. $form->{paidaccounts}) {
36a93d2e Jan Büren
# hook for calc of of fx_paid and check if banktransaction has a record exchangerate
if ($form->{"exchangerate_$i"}) {
my $bt_acc_trans = SL::DB::Manager::BankTransactionAccTrans->find_by(acc_trans_id => $form->{"acc_trans_id_$i"});
if ($bt_acc_trans) {
if ($bt_acc_trans->bank_transaction->exchangerate > 0) {
$form->{"exchangerate_$i"} = $bt_acc_trans->bank_transaction->exchangerate;
$form->{"forex_$i"} = $form->{"exchangerate_$i"};
$form->{"record_forex_$i"} = 1;
}
}
$form->{"fx_paid_$i"} = $form->{"paid_$i"} / $form->{"exchangerate_$i"};
$form->{"fx_totalpaid"} += $form->{"fx_paid_$i"};
} # end hook fx_paid
d319704a Moritz Bunkus
# format amounts
53beea8b Philip Reetz
if ($form->{"paid_$i"}) {
46231fcc Thomas Heck
$form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
53beea8b Philip Reetz
}
fb37acdc Moritz Bunkus
if ($form->{"exchangerate_$i"} == 0) {
$form->{"exchangerate_$i"} = "";
f9c86f3f Bernd Bleßmann
} else {
$form->{"exchangerate_$i"} =
$form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
fb37acdc Moritz Bunkus
}
d319704a Moritz Bunkus
890e057f Bernd Bleßmann
my $changeable = 1;
97954312 Bernd Bleßmann
if (SL::DB::Default->get->payments_changeable == 0) {
890e057f Bernd Bleßmann
# never
$changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
}
97954312 Bernd Bleßmann
if (SL::DB::Default->get->payments_changeable == 2) {
890e057f Bernd Bleßmann
# on the same day
$changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
}
79b83b02 Bernd Bleßmann
60fd9199 Frank Messerschmidt
#deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
if ($form->date_closed($form->{"gldate_$i"})) {
$changeable = 0;
}

46231fcc Thomas Heck
$form->{'paidaccount_changeable_'. $i} = $changeable;
79b83b02 Bernd Bleßmann
9fe00490 Thomas Heck
$form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
9e30e4f6 Jan Büren
# accno and description as info text
$form->{'AP_paid_readonly_desc_' . $i} = $form->{'AP_paid_' . $i} ?
$form->{'AP_paid_' . $i} . " " . SL::DB::Manager::Chart->find_by(accno => $form->{'AP_paid_' . $i})->description
: '';
d319704a Moritz Bunkus
}
36a93d2e Jan Büren
$form->{paid_missing} = $::form->{is_linked_bank_transaction} && $form->{invoice_obj}->forex ?
$form->{invoice_obj}->open_amount
: $form->{invtotal_unformatted} - $form->{totalpaid};
46231fcc Thomas Heck
fc131333 Jan Büren
$form->{payment_id} = $form->{invoice_obj}->{payment_id} // $form->{payment_id};
8c204ce4 Moritz Bunkus
print $form->parse_html_template('ap/form_header', {
today => DateTime->today,
122f91e7 Moritz Bunkus
currencies => SL::DB::Manager::Currency->get_all_sorted,
fc131333 Jan Büren
payment_terms => SL::DB::Manager::PaymentTerm->get_all_sorted(query => [ or => [ obsolete => 0, id => $form->{payment_id}*1 ]]),
8c204ce4 Moritz Bunkus
});
d319704a Moritz Bunkus
088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

sub form_footer {
8c8f6da3 Thomas Heck
$::lxdebug->enter_sub;
894ac4ca Moritz Bunkus
_assert_access();
088b52b5 Sven Schöling
8c8f6da3 Thomas Heck
my $num_due;
my $num_follow_ups;
if ($::form->{id}) {
a7b92129 Waldemar Toews
my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
8c7e4493 Moritz Bunkus
8c8f6da3 Thomas Heck
if (@{ $follow_ups }) {
$num_due = sum map { $_->{due} * 1 } @{ $follow_ups };
$num_follow_ups = scalar @{ $follow_ups }
7a7f33b5 Moritz Bunkus
}
}

8c8f6da3 Thomas Heck
my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
my $closedto = $::form->datetonum($::form->{closedto}, \%::myconfig);
d319704a Moritz Bunkus
8c8f6da3 Thomas Heck
my $storno = $::form->{id}
&& !IS->has_storno(\%::myconfig, $::form, 'ap')
&& !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
&& ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
d319704a Moritz Bunkus
8c8f6da3 Thomas Heck
$::form->header;
print $::form->parse_html_template('ap/form_footer', {
50c2f228 Bernd Bleßmann
num_due => $num_due,
num_follow_ups => $num_follow_ups,
8c8f6da3 Thomas Heck
});
1118dab9 Moritz Bunkus
8c8f6da3 Thomas Heck
$::lxdebug->leave_sub;
d319704a Moritz Bunkus
}

ce47a234 Thomas Kasulke
sub mark_as_paid {
59adfa36 Moritz Bunkus
$::auth->assert('ap_transactions');
8c7e4493 Moritz Bunkus
59adfa36 Moritz Bunkus
SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
8c7e4493 Moritz Bunkus
59adfa36 Moritz Bunkus
$::form->redirect($::locale->text("Marked as paid"));
ce47a234 Thomas Kasulke
}

301fdeba Bernd Bleßmann
sub block_or_unblock_sepa_transfer {
$::auth->assert('ap_transactions');

my $invoice = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load;
$invoice->update_attributes(is_sepa_blocked => 0) if $::form->{unblock_sepa} && $invoice->is_sepa_blocked;
$invoice->update_attributes(is_sepa_blocked => 1) if !$::form->{unblock_sepa} && !$invoice->is_sepa_blocked;

$::form->redirect($::form->{unblock_sepa} ? t8('Bank transfer via SEPA is unblocked') : t8('Bank transfer via SEPA is blocked'));
}

46aa98a9 Martin Helmling
sub show_draft {
$::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
$::form->{gldate} = $::form->{transdate} if !$::form->{gldate};
822fc676 Bernd Bleßmann
$::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST())->token;
46aa98a9 Martin Helmling
update();
}

d319704a Moritz Bunkus
sub update {
101b9705 Moritz Bunkus
my %params = @_;

088b52b5 Sven Schöling
$main::lxdebug->enter_sub();
d319704a Moritz Bunkus
088b52b5 Sven Schöling
my $form = $main::form;
my %myconfig = %main::myconfig;

25d67207 Martin Helmling
$main::auth->assert('ap_transactions');
8c7e4493 Moritz Bunkus
d319704a Moritz Bunkus
my $display = shift;

$form->{invtotal} = 0;

8f8ad003 Moritz Bunkus
delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };

d319704a Moritz Bunkus
map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
qw(exchangerate creditlimit creditremaining);

51f0fec1 Moritz Bunkus
my @flds = qw(amount AP_amount_chart_id projectnumber oldprojectnumber project_id taxchart tax);
088b52b5 Sven Schöling
my $count = 0;
my (@a, $j, $totaltax);
for my $i (1 .. $form->{rowcount}) {
0e68056c Geoffrey Richardson
$form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
101b9705 Moritz Bunkus
if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
d319704a Moritz Bunkus
push @a, {};
30175d89 Philip Reetz
$j = $#a;
088b52b5 Sven Schöling
my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
0e68056c Geoffrey Richardson
# calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
my $tmpnetamount;
($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
30175d89 Philip Reetz
$totaltax += $form->{"tax_$i"};
d319704a Moritz Bunkus
map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
$count++;
}
}
$form->redo_rows(\@flds, \@a, $count, $form->{rowcount});

30175d89 Philip Reetz
map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
d319704a Moritz Bunkus
$form->{invdate} = $form->{transdate};
84783219 Moritz Bunkus
2dcf4554 Moritz Bunkus
if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
IR->get_vendor(\%::myconfig, $form);
8b5bed7f Sven Schöling
my $vendor = SL::DB::Vendor->load_cached($form->{vendor_id});

# reset payment to new vendor
$form->{payment_id} = $vendor->payment_id;

4d041eef Jan Büren
if (($form->{rowcount} == 1) && ($form->{amount_1} == 0)) {
8b5bed7f Sven Schöling
my $last_used_ap_chart = $vendor->last_used_ap_chart;
4d041eef Jan Büren
$form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
}
2dcf4554 Moritz Bunkus
}
84783219 Moritz Bunkus
101b9705 Moritz Bunkus
$form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
d319704a Moritz Bunkus
$form->{invtotal} =
($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;

088b52b5 Sven Schöling
my $totalpaid;
for my $i (1 .. $form->{paidaccounts}) {
04a2f2e7 Moritz Bunkus
if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
d319704a Moritz Bunkus
map {
$form->{"${_}_$i"} =
$form->parse_amount(\%myconfig, $form->{"${_}_$i"})
} qw(paid exchangerate);

$totalpaid += $form->{"paid_$i"};

a53233e5 Sven Schöling
$form->{"forex_$i"} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
$form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
d319704a Moritz Bunkus
}
}

$form->{creditremaining} -=
($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
$form->{oldinvtotal});
$form->{oldinvtotal} = $form->{invtotal};
$form->{oldtotalpaid} = $totalpaid;

101b9705 Moritz Bunkus
display_form();
d319704a Moritz Bunkus
088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

bdaa8c2f Philip Reetz
sub post_payment {
088b52b5 Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my %myconfig = %main::myconfig;
my $locale = $main::locale;
a326f385 Moritz Bunkus
25d67207 Martin Helmling
$main::auth->assert('ap_transactions');
d735aab3 Martin Helmling
$form->mtime_ischanged('ap');
8c7e4493 Moritz Bunkus
a326f385 Moritz Bunkus
$form->{defaultcurrency} = $form->get_default_currency(\%myconfig);

662ded38 Sven Schöling
my $invdate = $form->datetonum($form->{transdate}, \%myconfig);

088b52b5 Sven Schöling
for my $i (1 .. $form->{paidaccounts}) {
eb8bed3f Moritz Bunkus
if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
088b52b5 Sven Schöling
my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
bdaa8c2f Philip Reetz
$form->isblank("datepaid_$i", $locale->text('Payment date missing!'));

60fd9199 Frank Messerschmidt
$form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));

#Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
# (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
bdaa8c2f Philip Reetz
$form->error($locale->text('Cannot post payment for a closed period!'))
60fd9199 Frank Messerschmidt
if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
bdaa8c2f Philip Reetz
bea3f989 Moritz Bunkus
if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
bdaa8c2f Philip Reetz
$form->{"exchangerate_$i"} = $form->{exchangerate}
662ded38 Sven Schöling
if ($invdate == $datepaid);
bdaa8c2f Philip Reetz
$form->isblank("exchangerate_$i",
$locale->text('Exchangerate for payment missing!'));
}
}
}

($form->{AP}) = split /--/, $form->{AP};
($form->{AP_paid}) = split /--/, $form->{AP_paid};
7a98647b Geoffrey Richardson
if (AP->post_payment(\%myconfig, \%$form)) {
$form->{snumbers} = qq|invnumber_| . $form->{invnumber};
$form->{what_done} = 'invoice';
$form->{addition} = "PAYMENT POSTED";
$form->save_history;
$form->redirect($locale->text('Payment posted!'))
} else {
bdaa8c2f Philip Reetz
$form->error($locale->text('Cannot post payment!'));
7a98647b Geoffrey Richardson
};
bdaa8c2f Philip Reetz

088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
bdaa8c2f Philip Reetz
}


d319704a Moritz Bunkus
sub post {
088b52b5 Sven Schöling
$main::lxdebug->enter_sub();
d319704a Moritz Bunkus
088b52b5 Sven Schöling
my $form = $main::form;
my %myconfig = %main::myconfig;
my $locale = $main::locale;

25d67207 Martin Helmling
$main::auth->assert('ap_transactions');
d735aab3 Martin Helmling
$form->mtime_ischanged('ap');
8c7e4493 Moritz Bunkus
55a380fc Bernd Bleßmann
my ($inline) = @_;

4e9b1b02 Geoffrey Richardson
# check if there is a vendor, invoice, due date and invnumber
1e92b81c Jan Büren
$form->isblank("transdate", $locale->text("Invoice Date missing!"));
$form->isblank("duedate", $locale->text("Due Date missing!"));
$form->isblank("vendor_id", $locale->text('Vendor missing!'));
$form->isblank("invnumber", $locale->text('Invoice Number missing!'));
$form->isblank("AP_chart_id", $locale->text('No contra account selected!'));
d319704a Moritz Bunkus
40cfb5ee Geoffrey Richardson
if ($myconfig{mandatory_departments} && !$form->{department_id}) {
05174f19 Sven Schöling
$form->{saved_message} = $::locale->text('You have to specify a department.');
update();
exit;
}

088b52b5 Sven Schöling
my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
a11d7a85 Jan Büren
$form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
if ($form->date_max_future($form->{"transdate"}, \%myconfig));
9e06d0e4 Philip Reetz
$form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
eb8bed3f Moritz Bunkus
my $zero_amount_posting = 1;
088b52b5 Sven Schöling
for my $i (1 .. $form->{rowcount}) {
5a1856a8 Jan Büren
# no taxincluded for reverse charge
my ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
my $tax = SL::DB::Manager::Tax->find_by(id => $used_tax_id);
if ($tax->reverse_charge_chart_id && $form->{taxincluded}) {
57342517 Jan Büren
$form->error($locale->text('Cannot Post AP transaction with tax included!'));
}
5a1856a8 Jan Büren
eb8bed3f Moritz Bunkus
if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
$zero_amount_posting = 0;
}
}
d319704a Moritz Bunkus
eb8bed3f Moritz Bunkus
$form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
d319704a Moritz Bunkus
eaa30664 Jan Büren
if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
$form->isblank("exchangerate", $locale->text('Exchangerate missing!'));
$form->error($locale->text('Cannot post invoice with negative exchange rate'))
unless ($form->parse_amount(\%myconfig, $form->{"exchangerate"}) > 0);
}

d319704a Moritz Bunkus
delete($form->{AP});

088b52b5 Sven Schöling
for my $i (1 .. $form->{paidaccounts}) {
04a2f2e7 Moritz Bunkus
if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
088b52b5 Sven Schöling
my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
d319704a Moritz Bunkus
$form->isblank("datepaid_$i", $locale->text('Payment date missing!'));

60fd9199 Frank Messerschmidt
$form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));

#Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
# (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
d319704a Moritz Bunkus
$form->error($locale->text('Cannot post payment for a closed period!'))
60fd9199 Frank Messerschmidt
if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
d319704a Moritz Bunkus
bea3f989 Moritz Bunkus
if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
d319704a Moritz Bunkus
$form->{"exchangerate_$i"} = $form->{exchangerate}
if ($transdate == $datepaid);
$form->isblank("exchangerate_$i",
$locale->text('Exchangerate for payment missing!'));
}

}
}

# if old vendor ne vendor redo form
2dcf4554 Moritz Bunkus
if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
d319704a Moritz Bunkus
&update;
09479f02 Moritz Bunkus
$::dispatcher->end_request;
d319704a Moritz Bunkus
}
91ea86b4 Moritz Bunkus
$form->{storno} = 0;
d319704a Moritz Bunkus
bde667c2 Moritz Bunkus
if (AP->post_transaction(\%myconfig, \%$form)) {
9d0aef99 Jan Büren
# create webdav folder
if ($::instance_conf->get_webdav) {
SL::Webdav->new(type => 'accounts_payable',
number => $form->{invnumber},
)->webdav_path;
}
bde667c2 Moritz Bunkus
# saving the history
if(!exists $form->{addition} && $form->{id} ne "") {
281696eb Geoffrey Richardson
$form->{snumbers} = qq|invnumber_| . $form->{invnumber};
$form->{addition} = "POSTED";
$form->{what_done} = "invoice";
a590a651 Sven Schöling
$form->save_history;
bde667c2 Moritz Bunkus
}
850ba82b Bernd Bleßmann
if (!$inline) {
my $msg = $locale->text("AP transaction '#1' posted (ID: #2)", $form->{invnumber}, $form->{id});
if ($form->{callback} =~ /BankTransaction/) {
# no restore_from_session_id needed. we like to have a newly generated
# list of invoices for bank transactions
SL::Helper::Flash::flash_later('info', $msg);
print $form->redirect_header($form->{callback});
$::dispatcher->end_request;

dbf9afad Bernd Bleßmann
} elsif ('doc-tab' eq $form->{after_action}) {
850ba82b Bernd Bleßmann
# Redirect with callback containing a fragment does not work (by now)
# because the callback info is stored in the session an parsing the
# callback parameters does not support fragments (see SL::Form::redirect).
# So use flash_later for the message and redirect_headers for redirecting.
my $add_doc_url = build_std_url("script=ap.pl", 'action=edit', 'id=' . E($form->{id}), 'fragment=ui-tabs-docs');
SL::Helper::Flash::flash_later('info', $msg);
print $form->redirect_header($add_doc_url);
$::dispatcher->end_request;

} else {
$form->redirect($msg);
}
39bdd9e0 Jan Büren
}
a2198456 Jan Büren
92483c53 Jan Büren
} else {
$form->error($locale->text('Cannot post transaction!'));
bde667c2 Moritz Bunkus
}
d319704a Moritz Bunkus
088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

3cd3e832 Moritz Bunkus
sub use_as_new {
088b52b5 Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my %myconfig = %main::myconfig;
98764afa Philip Reetz
25d67207 Martin Helmling
$main::auth->assert('ap_transactions');
8c7e4493 Moritz Bunkus
6e083cb8 Bernd Bleßmann
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 convert_from_oe_id);
98764afa Philip Reetz
$form->{paidaccounts} = 1;
$form->{rowcount}--;
088b52b5 Sven Schöling
4507456b Moritz Bunkus
my $today = DateTime->today_local;
$form->{transdate} = $today->to_kivitendo;
$form->{duedate} = $form->{transdate};
d319704a Moritz Bunkus
4507456b Moritz Bunkus
if ($form->{vendor_id}) {
my $payment_terms = SL::DB::Vendor->load_cached($form->{vendor_id})->payment;
$form->{duedate} = $payment_terms->calc_date(reference_date => $today)->to_kivitendo if $payment_terms;
d319704a Moritz Bunkus
}

822fc676 Bernd Bleßmann
$form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST())->token;

4507456b Moritz Bunkus
&update;
d319704a Moritz Bunkus
088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

4507456b Moritz Bunkus
sub delete {
088b52b5 Sven Schöling
my $form = $main::form;
my %myconfig = %main::myconfig;
my $locale = $main::locale;
8c7e4493 Moritz Bunkus
25d67207 Martin Helmling
$main::auth->assert('ap_transactions');
8c7e4493 Moritz Bunkus
8cd05ad6 Moritz Bunkus
if (AP->delete_transaction(\%myconfig, \%$form)) {
dacb62eb Thomas Kasulke
# saving the history
if(!exists $form->{addition}) {
281696eb Geoffrey Richardson
$form->{snumbers} = qq|invnumber_| . $form->{invnumber};
$form->{addition} = "DELETED";
$form->{what_done} = "invoice";
a590a651 Sven Schöling
$form->save_history;
dacb62eb Thomas Kasulke
}
7011fd23 Sven Schöling
# /saving the history
dacb62eb Thomas Kasulke
$form->redirect($locale->text('Transaction deleted!'));
}
d319704a Moritz Bunkus
$form->error($locale->text('Cannot delete transaction!'));
}

sub search {
088b52b5 Sven Schöling
$main::lxdebug->enter_sub();
d319704a Moritz Bunkus
088b52b5 Sven Schöling
my $form = $main::form;
my %myconfig = %main::myconfig;
my $locale = $main::locale;
8c7e4493 Moritz Bunkus
9ea32302 Moritz Bunkus
$form->{title} = $locale->text('Vendor Invoices & AP Transactions');
d319704a Moritz Bunkus
4a4ae0b3 Bernd Bleßmann
$::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department ->get_all_sorted;
$::form->{ALL_TAXZONES} = SL::DB::Manager::TaxZone ->get_all_sorted;
d53433f8 Tamino Steinert
$::form->{ALL_PAYMENT_TERMS} = SL::DB::Manager::PaymentTerm->get_all_sorted;
2391833d Bernd Bleßmann
ddaf7f50 Sven Schöling
# constants and subs for template
$form->{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
a4b22a8f Moritz Bunkus
cf9865dc Moritz Bunkus
$::request->layout->add_javascripts("autocomplete_project.js");

b755a636 Moritz Bunkus
setup_ap_search_action_bar();

d319704a Moritz Bunkus
$form->header;
ddaf7f50 Sven Schöling
print $form->parse_html_template('ap/search', { %myconfig });
d319704a Moritz Bunkus
088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

e71494c1 Moritz Bunkus
sub create_subtotal_row {
088b52b5 Sven Schöling
$main::lxdebug->enter_sub();
e71494c1 Moritz Bunkus
my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;

088b52b5 Sven Schöling
my $form = $main::form;
my %myconfig = %main::myconfig;

e71494c1 Moritz Bunkus
my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };

map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };

$row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);

map { $totals->{$_} = 0 } @{ $subtotal_columns };

088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
e71494c1 Moritz Bunkus
return $row;
}

d319704a Moritz Bunkus
sub ap_transactions {
088b52b5 Sven Schöling
$main::lxdebug->enter_sub();
d319704a Moritz Bunkus
088b52b5 Sven Schöling
my $form = $main::form;
my %myconfig = %main::myconfig;
my $locale = $main::locale;

262108d0 Moritz Bunkus
report_generator_set_default_sort('transdate', 1);
e71494c1 Moritz Bunkus
d319704a Moritz Bunkus
AP->ap_transactions(\%myconfig, \%$form);

9ea32302 Moritz Bunkus
$form->{title} = $locale->text('Vendor Invoices & AP Transactions');
d319704a Moritz Bunkus
e71494c1 Moritz Bunkus
my $report = SL::ReportGenerator->new(\%myconfig, $form);

my @columns =
qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
25517b3d Bernd Bleßmann
due duedate transaction_description notes employee globalprojectnumber department
a0b82b1e Jan Büren
vendornumber country ustid taxzone payment_terms charts debit_chart direct_debit
b008860a Bernd Bleßmann
insertdate items);
e71494c1 Moritz Bunkus
my @hidden_variables = map { "l_${_}" } @columns;
8a0c3bd1 Bernd Bleßmann
push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id
43b9f08f Bernd Bleßmann
transdatefrom transdateto duedatefrom duedateto datepaidfrom datepaidto
159ba2d4 Tamino Steinert
parts_partnumber parts_description department_id taxzone_id payment_id
fulltext);
e71494c1 Moritz Bunkus
my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);

my %column_defs = (
'transdate' => { 'text' => $locale->text('Date'), },
'id' => { 'text' => $locale->text('ID'), },
'type' => { 'text' => $locale->text('Type'), },
'invnumber' => { 'text' => $locale->text('Invoice'), },
'ordnumber' => { 'text' => $locale->text('Order'), },
'name' => { 'text' => $locale->text('Vendor'), },
'netamount' => { 'text' => $locale->text('Amount'), },
'tax' => { 'text' => $locale->text('Tax'), },
'amount' => { 'text' => $locale->text('Total'), },
'paid' => { 'text' => $locale->text('Paid'), },
'datepaid' => { 'text' => $locale->text('Date Paid'), },
'due' => { 'text' => $locale->text('Amount Due'), },
'duedate' => { 'text' => $locale->text('Due Date'), },
'transaction_description' => { 'text' => $locale->text('Transaction description'), },
'notes' => { 'text' => $locale->text('Notes'), },
e31afd79 Geoffrey Richardson
'employee' => { 'text' => $locale->text('Employee'), },
d8e0c6d8 Bernd Bleßmann
'globalprojectnumber' => { 'text' => $locale->text('Document Project Number'), },
25517b3d Bernd Bleßmann
'department' => { 'text' => $locale->text('Department'), },
875f08f3 Sven Schöling
'vendornumber' => { 'text' => $locale->text('Vendor Number'), },
'country' => { 'text' => $locale->text('Country'), },
'ustid' => { 'text' => $locale->text('USt-IdNr.'), },
88f11e29 Geoffrey Richardson
'taxzone' => { 'text' => $locale->text('Tax rate'), },
875f08f3 Sven Schöling
'payment_terms' => { 'text' => $locale->text('Payment Terms'), },
0070a250 Andreas Rudin
'charts' => { 'text' => $locale->text('Chart'), },
d333cdb7 Jan Büren
'debit_chart' => { 'text' => $locale->text('Debit Account'), },
c98c318c Moritz Bunkus
'direct_debit' => { 'text' => $locale->text('direct debit'), },
a0b82b1e Jan Büren
'insertdate' => { 'text' => $locale->text('Insert Date'), },
b008860a Bernd Bleßmann
'items' => { 'text' => $locale->text('Positions'), },
e71494c1 Moritz Bunkus
);

ac06e257 Bernd Bleßmann
foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit department taxzone)) {
262108d0 Moritz Bunkus
my $sortdir = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
$column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
e71494c1 Moritz Bunkus
}

my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);

$form->{"l_type"} = "Y";
map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;

$report->set_columns(%column_defs);
$report->set_column_order(@columns);

19688fca Moritz Bunkus
$report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
e71494c1 Moritz Bunkus
262108d0 Moritz Bunkus
$report->set_sort_indicator($form->{sort}, $form->{sortdir});
f5e4c22b Moritz Bunkus
94ca2a65 Bernd Bleßmann
my $department_description;
$department_description = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
457c1bb0 Jan Büren
my $project_description;
$project_description = SL::DB::Manager::Project->find_by(id => $form->{project_id})->description if $form->{project_id};
94ca2a65 Bernd Bleßmann
e71494c1 Moritz Bunkus
my @options;
58265754 Moritz Bunkus
push @options, $locale->text('Vendor') . " : $form->{vendor}" if ($form->{vendor});
b98b8e3f Sven Schöling
push @options, $locale->text('Contact Person') . " : $form->{cp_name}" if ($form->{cp_name});
94ca2a65 Bernd Bleßmann
push @options, $locale->text('Department') . " : $department_description" if ($form->{department_id});
457c1bb0 Jan Büren
push @options, $locale->text('Project') . " : $project_description" if ($project_description);
58265754 Moritz Bunkus
push @options, $locale->text('Invoice Number') . " : $form->{invnumber}" if ($form->{invnumber});
push @options, $locale->text('Order Number') . " : $form->{ordnumber}" if ($form->{ordnumber});
push @options, $locale->text('Notes') . " : $form->{notes}" if ($form->{notes});
push @options, $locale->text('Transaction description') . " : $form->{transaction_description}" if ($form->{transaction_description});
612e3ebe Moritz Bunkus
push @options, $locale->text('Part Description') . " : $form->{parts_description}" if $form->{parts_description};
push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}" if $form->{parts_partnumber};
159ba2d4 Tamino Steinert
push @options, $locale->text('Full Text') . " : $form->{fulltext}" if ($form->{fulltext});
58265754 Moritz Bunkus
push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1) if ($form->{transdatefrom});
push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1) if ($form->{transdateto});
43b9f08f Bernd Bleßmann
push @options, $locale->text('Due Date') . " " . $locale->text('from') . " " . $locale->date(\%myconfig, $form->{duedatefrom}, 1) if ($form->{duedatefrom});
push @options, $locale->text('Due Date') . " " . $locale->text('to') . " " . $locale->date(\%myconfig, $form->{duedateto}, 1) if ($form->{duedateto});
push @options, $locale->text('Date Paid') . " " . $locale->text('from') . " " . $locale->date(\%myconfig, $form->{datepaidfrom}, 1) if ($form->{datepaidfrom});
push @options, $locale->text('Date Paid') . " " . $locale->text('to') . " " . $locale->date(\%myconfig, $form->{datepaidto}, 1) if ($form->{datepaidto});
58265754 Moritz Bunkus
push @options, $locale->text('Open') if ($form->{open});
push @options, $locale->text('Closed') if ($form->{closed});
d53433f8 Tamino Steinert
if ($form->{payment_id}) {
my $payment_term = SL::DB::Manager::PaymentTerm->find_by( id => $form->{payment_id} );
push @options, $locale->text('Payment Term') . " : " . $payment_term->description;
}
d319704a Moritz Bunkus
e71494c1 Moritz Bunkus
$report->set_options('top_info_text' => join("\n", @options),
'output_format' => 'HTML',
'title' => $form->{title},
19688fca Moritz Bunkus
'attachment_basename' => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
e71494c1 Moritz Bunkus
);
$report->set_options_from_form();
a873249c Moritz Bunkus
$locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
d319704a Moritz Bunkus
e71494c1 Moritz Bunkus
# add sort and escape callback, this one we use for the add sub
$form->{callback} = $href .= "&sort=$form->{sort}";
84bed7a6 Moritz Bunkus
e71494c1 Moritz Bunkus
# escape callback for href
088b52b5 Sven Schöling
my $callback = $form->escape($href);
d319704a Moritz Bunkus
e71494c1 Moritz Bunkus
my @subtotal_columns = qw(netamount amount paid due);
d319704a Moritz Bunkus
e71494c1 Moritz Bunkus
my %totals = map { $_ => 0 } @subtotal_columns;
my %subtotals = map { $_ => 0 } @subtotal_columns;
d319704a Moritz Bunkus
e71494c1 Moritz Bunkus
my $idx = 0;
d319704a Moritz Bunkus
088b52b5 Sven Schöling
foreach my $ap (@{ $form->{AP} }) {
e71494c1 Moritz Bunkus
$ap->{tax} = $ap->{amount} - $ap->{netamount};
$ap->{due} = $ap->{amount} - $ap->{paid};
d319704a Moritz Bunkus
e71494c1 Moritz Bunkus
map { $subtotals{$_} += $ap->{$_};
$totals{$_} += $ap->{$_} } @subtotal_columns;
d319704a Moritz Bunkus
e71494c1 Moritz Bunkus
map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
d319704a Moritz Bunkus
09685616 Moritz Bunkus
my $is_storno = $ap->{storno} && $ap->{storno_id};
my $has_storno = $ap->{storno} && !$ap->{storno_id};

if ($ap->{invoice}) {
$ap->{type} =
$has_storno ? $locale->text("Invoice with Storno (abbreviation)")
: $is_storno ? $locale->text("Storno (one letter abbreviation)")
: $locale->text("Invoice (one letter abbreviation)");
} else {
$ap->{type} =
$has_storno ? $locale->text("AP Transaction with Storno (abbreviation)")
: $is_storno ? $locale->text("AP Transaction Storno (one letter abbreviation)")
: $locale->text("AP Transaction (abbreviation)");
}
d319704a Moritz Bunkus
c98c318c Moritz Bunkus
$ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');

e71494c1 Moritz Bunkus
my $row = { };
d319704a Moritz Bunkus
e71494c1 Moritz Bunkus
foreach my $column (@columns) {
b008860a Bernd Bleßmann
next if ($column eq 'items');

e71494c1 Moritz Bunkus
$row->{$column} = {
'data' => $ap->{$column},
'align' => $column_alignment{$column},
};
d319704a Moritz Bunkus
}

e71494c1 Moritz Bunkus
$row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
. "&id=" . E($ap->{id}) . "&callback=${callback}";
d319704a Moritz Bunkus
b008860a Bernd Bleßmann
if ($form->{l_items}) {
my $items = SL::DB::Manager::InvoiceItem->get_all_sorted(where => [id => $ap->{item_ids}]);
$row->{items}->{raw_data} = SL::Presenter::ItemsList::items_list($items) if lc($report->{options}->{output_format}) eq 'html';
$row->{items}->{data} = SL::Presenter::ItemsList::items_list($items, as_text => 1) if lc($report->{options}->{output_format}) ne 'html';
}

e71494c1 Moritz Bunkus
my $row_set = [ $row ];
d319704a Moritz Bunkus
e71494c1 Moritz Bunkus
if (($form->{l_subtotal} eq 'Y')
&& (($idx == (scalar @{ $form->{AP} } - 1))
|| ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
}
d319704a Moritz Bunkus
e71494c1 Moritz Bunkus
$report->add_data($row_set);
d319704a Moritz Bunkus
e71494c1 Moritz Bunkus
$idx++;
d319704a Moritz Bunkus
}

e71494c1 Moritz Bunkus
$report->add_separator();
$report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
d319704a Moritz Bunkus
b755a636 Moritz Bunkus
setup_ap_transactions_action_bar();
e71494c1 Moritz Bunkus
$report->generate_with_headers();
d319704a Moritz Bunkus
088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}
6d544157 Sven Schöling
sub storno {
088b52b5 Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my %myconfig = %main::myconfig;
my $locale = $main::locale;
6d544157 Sven Schöling
25d67207 Martin Helmling
$main::auth->assert('ap_transactions');
8c7e4493 Moritz Bunkus
6d544157 Sven Schöling
if (IS->has_storno(\%myconfig, $form, 'ap')) {
$form->{title} = $locale->text("Cancel Accounts Payables Transaction");
$form->error($locale->text("Transaction has already been cancelled!"));
}

16a12c3c Niclas Zimmermann
$form->error($locale->text('Cannot post storno for a closed period!'))
if ( $form->date_closed($form->{transdate}, \%myconfig));

2b3f8b3a Sven Schöling
AP->storno($form, \%myconfig, $form->{id});
6d544157 Sven Schöling
# saving the history
if(!exists $form->{addition} && $form->{id} ne "") {
281696eb Geoffrey Richardson
$form->{snumbers} = qq|invnumber_| . $form->{invnumber};
$form->{addition} = "STORNO";
$form->{what_done} = "invoice";
a590a651 Sven Schöling
$form->save_history;
6d544157 Sven Schöling
}
7011fd23 Sven Schöling
# /saving the history
6d544157 Sven Schöling
7011fd23 Sven Schöling
$form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
2b3f8b3a Sven Schöling
088b52b5 Sven Schöling
$main::lxdebug->leave_sub();
6d544157 Sven Schöling
}
4507456b Moritz Bunkus
6e083cb8 Bernd Bleßmann
sub add_from_purchase_order {
$main::auth->assert('ap_transactions');

return if !$::form->{id};

my $order_id = delete $::form->{id};
83a84630 Bernd Bleßmann
my $order = SL::DB::Order->new(id => $order_id)->load(with => [ 'vendor', 'currency', 'payment_terms' ]);
6e083cb8 Bernd Bleßmann
return if $order->type ne 'purchase_order';

my $today = DateTime->today_local;
ba629467 Bernd Bleßmann
$::form->{title} = "Add";
$::form->{vc} = 'vendor';
$::form->{vendor_id} = $order->customervendor->id;
$::form->{vendor} = $order->vendor->name;
$::form->{convert_from_oe_id} = $order->id;
$::form->{globalproject_id} = $order->globalproject_id;
$::form->{ordnumber} = $order->number;
$::form->{department_id} = $order->department_id;
caaa17be Bernd Bleßmann
$::form->{transaction_description} = $order->transaction_description;
ba629467 Bernd Bleßmann
$::form->{currency} = $order->currency->name;
$::form->{taxincluded} = 1; # we use amount below, so tax is included
$::form->{transdate} = $today->to_kivitendo;
$::form->{duedate} = $today->to_kivitendo;
$::form->{duedate} = $order->payment_terms->calc_date(reference_date => $today)->to_kivitendo if $order->payment_terms;
$::form->{deliverydate} = $order->reqdate->to_kivitendo if $order->reqdate;
6e083cb8 Bernd Bleßmann
create_links();

my $config_po_ap_workflow_chart_id = $::instance_conf->get_workflow_po_ap_chart_id;

my ($first_taxchart, $default_taxchart, $taxchart_to_use);
my @taxcharts = ();
@taxcharts = GL->get_active_taxes_for_chart($config_po_ap_workflow_chart_id, $::form->{transdate}) if (defined $config_po_ap_workflow_chart_id);
foreach my $item (@taxcharts) {
$first_taxchart //= $item;
$default_taxchart = $item if $item->{is_default};
}
$taxchart_to_use = $default_taxchart // $first_taxchart;

my %pat = $order->calculate_prices_and_taxes;
my $row = 1;
foreach my $amount_chart (keys %{$pat{amounts}}) {
my $tax = SL::DB::Manager::Tax->find_by(id => $pat{amounts}->{$amount_chart}->{tax_id});
# If tax chart from order for this amount is active, use it. Use default or first tax chart for selected chart else.
if (defined $config_po_ap_workflow_chart_id) {
$taxchart_to_use = (first {$_->{id} == $tax->id} @taxcharts) // $taxchart_to_use;
} else {
$taxchart_to_use = $tax;
}

$::form->{"AP_amount_chart_id_$row"} = $config_po_ap_workflow_chart_id // $amount_chart;
$::form->{"previous_AP_amount_chart_id_$row"} = $::form->{"AP_amount_chart_id_$row"};
$::form->{"amount_$row"} = $::form->format_amount(\%::myconfig, $pat{amounts}->{$amount_chart}->{amount} * (1 + $tax->rate), 2);
$::form->{"taxchart_$row"} = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
$::form->{"project_id_$row"} = $order->globalproject_id;

$row++;
}

my $last_used_ap_chart = SL::DB::Vendor->load_cached($::form->{vendor_id})->last_used_ap_chart;
$::form->{"AP_amount_chart_id_$row"} = $last_used_ap_chart->id if $last_used_ap_chart;
$::form->{rowcount} = $row;

822fc676 Bernd Bleßmann
$::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST())->token;

6e083cb8 Bernd Bleßmann
update(
keep_rows_without_amount => 1,
dont_add_new_row => 1,
);
}

b755a636 Moritz Bunkus
sub setup_ap_search_action_bar {
my %params = @_;

for my $bar ($::request->layout->get('actionbar')) {
$bar->add(
action => [
$::locale->text('Search'),
submit => [ '#form', { action => "ap_transactions" } ],
8b217e89 Sven Schöling
checks => [ 'kivi.validate_form' ],
b755a636 Moritz Bunkus
accesskey => 'enter',
],
);
}
8b217e89 Sven Schöling
$::request->layout->add_javascripts('kivi.Validator.js');
b755a636 Moritz Bunkus
}

sub setup_ap_transactions_action_bar {
894ac4ca Moritz Bunkus
my %params = @_;
a8dac8db Jan Büren
my $may_edit_create = $::auth->assert('ap_transactions', 1);
b755a636 Moritz Bunkus
for my $bar ($::request->layout->get('actionbar')) {
$bar->add(
combobox => [
action => [ t8('Add') ],
link => [
t8('Purchase Invoice'),
894ac4ca Moritz Bunkus
link => [ 'ir.pl?action=add' ],
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,

b755a636 Moritz Bunkus
],
link => [
t8('AP Transaction'),
894ac4ca Moritz Bunkus
link => [ 'ap.pl?action=add' ],
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
b755a636 Moritz Bunkus
],
], # end of combobox "Add"
);
}
}

4507456b Moritz Bunkus
sub setup_ap_display_form_action_bar {
my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
my $closedto = $::form->datetonum($::form->{closedto}, \%::myconfig);
my $is_closed = $transdate <= $closedto;

0048944b freiphone
my $change_never = $::instance_conf->get_ap_changeable == 0;
my $change_on_same_day_only = $::instance_conf->get_ap_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
4507456b Moritz Bunkus
my $is_storno = IS->is_storno(\%::myconfig, $::form, 'ap', $::form->{id});
my $has_storno = IS->has_storno(\%::myconfig, $::form, 'ap');

a8dac8db Jan Büren
my $may_edit_create = $::auth->assert('ap_transactions', 1);
894ac4ca Moritz Bunkus
6c19cff0 Jan Büren
my $has_sepa_exports;
301fdeba Bernd Bleßmann
my $is_sepa_blocked;
6c19cff0 Jan Büren
if ($::form->{id}) {
my $invoice = SL::DB::Manager::PurchaseInvoice->find_by(id => $::form->{id});
$has_sepa_exports = 1 if ($invoice->find_sepa_export_items()->[0]);
301fdeba Bernd Bleßmann
$is_sepa_blocked = !!$invoice->is_sepa_blocked;
6c19cff0 Jan Büren
}

b3259be1 Jan Büren
my $is_linked_bank_transaction;
if ($::form->{id}
&& SL::DB::Manager::BankTransactionAccTrans->find_by(ap_id => $::form->{id})) {

$is_linked_bank_transaction = 1;
}
57342517 Jan Büren
my $is_linked_gl_transaction;
if ($::form->{id} && SL::DB::Manager::ApGl->find_by(ap_id => $::form->{id})) {
$is_linked_gl_transaction = 1;
}
93d8a5ea Jan Büren
# add readonly state in $::form
$::form->{readonly} = !$may_edit_create ? 1
: $is_closed ? 1
: $is_storno ? 1
: $has_storno ? 1
: ($::form->{id} && $change_never) ? 1
: ($::form->{id} && $change_on_same_day_only) ? 1
: $is_linked_bank_transaction ? 1
: $has_sepa_exports ? 1
: 0;
36a93d2e Jan Büren
# and is_linked_bank_transaction
$::form->{is_linked_bank_transaction} = $is_linked_bank_transaction;
b3259be1 Jan Büren
dbf9afad Bernd Bleßmann
my $create_post_action = sub {
# $_[0]: description
# $_[1]: after_action
action => [
36a93d2e Jan Büren
dbf9afad Bernd Bleßmann
$_[0],
submit => [ '#form', { action => "post", after_action => $_[1] } ],
checks => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting', 'kivi.AP.check_duplicate_invnumber' ],
disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
: $is_closed ? t8('The billing period has already been locked.')
: $is_storno ? t8('A canceled invoice cannot be posted.')
: ($::form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
: ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
: $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
: undef,
],
};

my @post_entries;
if ($::instance_conf->get_ap_add_doc && $::instance_conf->get_doc_storage) {
@post_entries = ( $create_post_action->(t8('Post'), 'doc-tab'),
$create_post_action->(t8('Post and new booking')) );
} elsif ($::instance_conf->get_doc_storage) {
@post_entries = ( $create_post_action->(t8('Post')),
$create_post_action->(t8('Post and upload document'), 'doc-tab') );
} else {
@post_entries = ( $create_post_action->(t8('Post')) );
}

4507456b Moritz Bunkus
for my $bar ($::request->layout->get('actionbar')) {
$bar->add(
action => [
t8('Update'),
submit => [ '#form', { action => "update" } ],
id => 'update_button',
8b217e89 Sven Schöling
checks => [ 'kivi.validate_form' ],
4507456b Moritz Bunkus
accesskey => 'enter',
894ac4ca Moritz Bunkus
disabled => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
4507456b Moritz Bunkus
],
combobox => [
dbf9afad Bernd Bleßmann
@post_entries,
4507456b Moritz Bunkus
action => [
t8('Post Payment'),
submit => [ '#form', { action => "post_payment" } ],
8b217e89 Sven Schöling
checks => [ 'kivi.validate_form' ],
b3259be1 Jan Büren
disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
: !$::form->{id} ? t8('This invoice has not been posted yet.')
: $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
: undef,
4507456b Moritz Bunkus
],
301fdeba Bernd Bleßmann
action => [ $is_sepa_blocked ? t8('Unblock Bank transfer via SEPA') : t8('Block Bank transfer via SEPA'),
submit => [ '#form', { action => "block_or_unblock_sepa_transfer", unblock_sepa => !!$is_sepa_blocked } ],
disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
: !$::form->{id} ? t8('This invoice has not been posted yet.')
: undef,
],
4507456b Moritz Bunkus
action => [ t8('Mark as paid'),
submit => [ '#form', { action => "mark_as_paid" } ],
confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
894ac4ca Moritz Bunkus
disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
: !$::form->{id} ? t8('This invoice has not been posted yet.')
: undef,
4507456b Moritz Bunkus
only_if => $::instance_conf->get_is_show_mark_as_paid,
],
], # end of combobox "Post"

combobox => [
action => [ t8('Storno'),
submit => [ '#form', { action => "storno" } ],
8b217e89 Sven Schöling
checks => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting' ],
4507456b Moritz Bunkus
confirm => t8('Do you really want to cancel this invoice?'),
894ac4ca Moritz Bunkus
disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
: !$::form->{id} ? t8('This invoice has not been posted yet.')
: $has_storno ? t8('This invoice has been canceled already.')
: $is_storno ? t8('Reversal invoices cannot be canceled.')
: $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
: $has_sepa_exports ? t8('This invoice has been linked with a sepa export, undo this first.')
e8666b84 Jan Büren
: $is_linked_gl_transaction ? t8('This transaction is linked with a gl transaction. Please delete the ap transaction booking if needed.')
: $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
894ac4ca Moritz Bunkus
: undef,
4507456b Moritz Bunkus
],
action => [ t8('Delete'),
submit => [ '#form', { action => "delete" } ],
confirm => t8('Do you really want to delete this object?'),
b3259be1 Jan Büren
disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
: !$::form->{id} ? t8('This invoice has not been posted yet.')
: $is_closed ? t8('The billing period has already been locked.')
: $has_sepa_exports ? t8('This invoice has been linked with a sepa export, undo this first.')
: $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
234b70f2 Jan Büren
# : $is_linked_gl_transaction ? undef # linked transactions can be deleted, if period is not closed
57342517 Jan Büren
: $change_never ? t8('Changing invoices has been disabled in the configuration.')
: $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
: $has_storno ? t8('This invoice has been canceled already.')
b3259be1 Jan Büren
: undef,
4507456b Moritz Bunkus
],
], # end of combobox "Storno"

'separator',

combobox => [
action => [ t8('Workflow') ],
action => [
t8('Use As New'),
submit => [ '#form', { action => "use_as_new" } ],
8b217e89 Sven Schöling
checks => [ 'kivi.validate_form' ],
894ac4ca Moritz Bunkus
disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
: !$::form->{id} ? t8('This invoice has not been posted yet.')
: undef,
4507456b Moritz Bunkus
],
], # end of combobox "Workflow"

combobox => [
action => [ t8('more') ],
action => [
t8('History'),
call => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
],
action => [
t8('Follow-Up'),
call => [ 'follow_up_window' ],
disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
],
action => [
t8('Record templates'),
894ac4ca Moritz Bunkus
call => [ 'kivi.RecordTemplate.popup', 'ap_transaction' ],
disabled => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
4507456b Moritz Bunkus
],
action => [
t8('Drafts'),
call => [ 'kivi.Draft.popup', 'ap', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
894ac4ca Moritz Bunkus
disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
: $::form->{id} ? t8('This invoice has already been posted.')
: $is_closed ? t8('The billing period has already been locked.')
: undef,
4507456b Moritz Bunkus
],
], # end of combobox "more"
);
}
8b217e89 Sven Schöling
$::request->layout->add_javascripts('kivi.Validator.js');
4507456b Moritz Bunkus
}