Projekt

Allgemein

Profil

Herunterladen (29 KB) Statistiken
| Zweig: | Markierung: | Revision:
82515b2d Sven Schöling
package SL::DB::Invoice;

use strict;

73df5fb5 Moritz Bunkus
use Carp;
4f43ec85 Geoffrey Richardson
use List::Util qw(first sum);
82515b2d Sven Schöling
2f56fd8d Tamino Steinert
use Rose::DB::Object::Helpers qw(has_loaded_related forget_related as_tree strip);
82515b2d Sven Schöling
use SL::DB::MetaSetup::Invoice;
use SL::DB::Manager::Invoice;
15f58ff3 Geoffrey Richardson
use SL::DB::Helper::Payment qw(:ALL);
a34c05f3 Moritz Bunkus
use SL::DB::Helper::AttrHTML;
f63af42d Moritz Bunkus
use SL::DB::Helper::AttrSorted;
c692dae1 Moritz Bunkus
use SL::DB::Helper::FlattenToForm;
e9fb6244 Moritz Bunkus
use SL::DB::Helper::LinkedRecords;
80eceeda Moritz Bunkus
use SL::DB::Helper::PDF_A;
e9fb6244 Moritz Bunkus
use SL::DB::Helper::PriceTaxCalculator;
2209370e Moritz Bunkus
use SL::DB::Helper::PriceUpdater;
320b8908 Sven Schöling
use SL::DB::Helper::RecordLink qw(RECORD_ID RECORD_TYPE_REF RECORD_ITEM_ID RECORD_ITEM_TYPE_REF);
d8275f6e Jan Büren
use SL::DB::Helper::SalesPurchaseInvoice;
b9dbc9e3 Moritz Bunkus
use SL::DB::Helper::TransNumberGenerator;
edb6e61e Tamino Steinert
use SL::DB::Helper::ZUGFeRD qw(:CREATE);
f6ed86ef Geoffrey Richardson
use SL::Locale::String qw(t8);
82515b2d Sven Schöling
__PACKAGE__->meta->add_relationship(
invoiceitems => {
type => 'one to many',
class => 'SL::DB::InvoiceItem',
column_map => { id => 'trans_id' },
manager_args => {
0845c4b7 Moritz Bunkus
with_objects => [ 'part' ]
82515b2d Sven Schöling
}
},
1d0a5eee Moritz Bunkus
storno_invoices => {
type => 'one to many',
class => 'SL::DB::Invoice',
column_map => { id => 'storno_id' },
},
fc1490e8 Moritz Bunkus
sepa_export_items => {
type => 'one to many',
class => 'SL::DB::SepaExportItem',
column_map => { id => 'ar_id' },
manager_args => { with_objects => [ 'sepa_export' ] }
},
a64b214d Moritz Bunkus
sepa_exports => {
type => 'many to many',
map_class => 'SL::DB::SepaExportItem',
map_from => 'ar',
map_to => 'sepa_export',
},
325c539c Moritz Bunkus
custom_shipto => {
type => 'one to one',
class => 'SL::DB::Shipto',
column_map => { id => 'trans_id' },
query_args => [ module => 'AR' ],
},
0395c036 Geoffrey Richardson
transactions => {
type => 'one to many',
class => 'SL::DB::AccTransaction',
column_map => { id => 'trans_id' },
manager_args => {
with_objects => [ 'chart' ],
sort_by => 'acc_trans_id ASC',
},
},
9508e215 Werner Hahn
dunnings => {
type => 'one to many',
class => 'SL::DB::Dunning',
column_map => { id => 'trans_id' },
manager_args => { with_objects => [ 'dunnings' ] }
},
82515b2d Sven Schöling
);

__PACKAGE__->meta->initialize;

a34c05f3 Moritz Bunkus
__PACKAGE__->attr_html('notes');
f63af42d Moritz Bunkus
__PACKAGE__->attr_sorted('items');
a34c05f3 Moritz Bunkus
57d6293d Moritz Bunkus
__PACKAGE__->before_save('_before_save_set_invnumber');
320b8908 Sven Schöling
__PACKAGE__->after_save('_after_save_link_records');
57d6293d Moritz Bunkus
# hooks

sub _before_save_set_invnumber {
my ($self) = @_;

$self->create_trans_number if !$self->invnumber;

return 1;
}

320b8908 Sven Schöling
sub _after_save_link_records {
my ($self) = @_;

my @allowed_record_sources = qw(SL::DB::Reclamation SL::DB::Order SL::DB::DeliveryOrder);
my @allowed_item_sources = qw(SL::DB::ReclamationItem SL::DB::OrderItem SL::DB::DeliveryOrderItem);

SL::DB::Helper::RecordLink::link_records(
$self,
\@allowed_record_sources,
\@allowed_item_sources,
close_source_quotations => 1,
);
}

82515b2d Sven Schöling
# methods

0845c4b7 Moritz Bunkus
sub items { goto &invoiceitems; }
ae906113 Moritz Bunkus
sub add_items { goto &add_invoiceitems; }
4f7e0fa9 Geoffrey Richardson
sub record_number { goto &invnumber; };
74554bc7 Tamino Steinert
sub record_type { goto &invoice_type; };
4ac74078 Moritz Bunkus
a93f1e39 Moritz Bunkus
sub is_sales {
# For compatibility with Order, DeliveryOrder
croak 'not an accessor' if @_ > 1;
return 1;
}

82515b2d Sven Schöling
# it is assumed, that ordnumbers are unique here.
sub first_order_by_ordnumber {
my $self = shift;

my $orders = SL::DB::Manager::Order->get_all(
query => [
ordnumber => $self->ordnumber,

],
);

return first { $_->is_type('sales_order') } @{ $orders };
}

sub abschlag_percentage {
my $self = shift;
my $order = $self->first_order_by_ordnumber or return;
my $order_amount = $order->netamount or return;
return $self->abschlag
? $self->netamount / $order_amount
: undef;
}

sub taxamount {
my $self = shift;
die 'not a setter method' if @_;

55049b81 Sven Schöling
return ($self->amount || 0) - ($self->netamount || 0);
82515b2d Sven Schöling
}

78034f24 Sven Schöling
__PACKAGE__->meta->make_attr_helpers(taxamount => 'numeric(15,5)');

dce860e3 Moritz Bunkus
sub closed {
my ($self) = @_;
return $self->paid >= $self->amount;
}

fab2b3f1 Tamino Steinert
sub convert_to_reclamation {
my ($self, %params) = @_;
$params{destination_type} = $self->is_sales ? 'sales_reclamation'
: 'purchase_reclamation';

require SL::DB::Reclamation;
my $reclamation = SL::DB::Reclamation->new_from($self, %params);

return $reclamation;
}

2714604a Moritz Bunkus
sub _clone_orderitem_delivery_order_item_cvar {
my ($cvar) = @_;

da6a187a Moritz Bunkus
my $cloned = $_->clone_and_reset;
2714604a Moritz Bunkus
$cloned->sub_module('invoice');

return $cloned;
}

73df5fb5 Moritz Bunkus
sub new_from {
my ($class, $source, %params) = @_;

croak("Unsupported source object type '" . ref($source) . "'") unless ref($source) =~ m/^ SL::DB:: (?: Order | DeliveryOrder ) $/x;
croak("Cannot create invoices for purchase records") unless $source->customer_id;

e4b46220 Sven Schöling
require SL::DB::Employee;

6ee486a5 Moritz Bunkus
my (@columns, @item_columns, $item_parent_id_column, $item_parent_column);
73df5fb5 Moritz Bunkus
d81f55ce Moritz Bunkus
if (ref($source) eq 'SL::DB::Order') {
1baea8cb Moritz Bunkus
@columns = qw(quonumber delivery_customer_id delivery_vendor_id tax_point);
d81f55ce Moritz Bunkus
@item_columns = qw(subtotal);

6ee486a5 Moritz Bunkus
$item_parent_id_column = 'trans_id';
$item_parent_column = 'order';

d81f55ce Moritz Bunkus
} else {
@columns = qw(donumber);
6ee486a5 Moritz Bunkus
$item_parent_id_column = 'delivery_order_id';
$item_parent_column = 'delivery_order';
d81f55ce Moritz Bunkus
}

464f44ac Moritz Bunkus
my $terms = $source->can('payment_id') ? $source->payment_terms : undef;
c65e8fcc Martin Helmling
$terms = $source->customer->payment_terms if !defined $terms && $source->customer;
464f44ac Moritz Bunkus
d81f55ce Moritz Bunkus
my %args = ( map({ ( $_ => $source->$_ ) } qw(customer_id taxincluded shippingpoint shipvia notes intnotes salesman_id cusordnumber ordnumber department_id
844a541e Moritz Bunkus
cp_id language_id taxzone_id tax_point globalproject_id transaction_description currency_id delivery_term_id
billing_address_id), @columns),
424269dc Geoffrey Richardson
transdate => $params{transdate} // DateTime->today_local,
73df5fb5 Moritz Bunkus
gldate => DateTime->today_local,
464f44ac Moritz Bunkus
duedate => $terms ? $terms->calc_date(reference_date => DateTime->today_local) : DateTime->today_local,
73df5fb5 Moritz Bunkus
invoice => 1,
type => 'invoice',
storno => 0,
22150c52 Moritz Bunkus
paid => 0,
73df5fb5 Moritz Bunkus
employee_id => (SL::DB::Manager::Employee->current || SL::DB::Employee->new(id => $source->employee_id))->id,
);

c65e8fcc Martin Helmling
$args{payment_id} = ( $terms ? $terms->id : $source->payment_id);

35429440 Bernd Bleßmann
if ($source->type =~ /_delivery_order$/) {
$args{deliverydate} = $source->reqdate;
if (my $order = SL::DB::Manager::Order->find_by(ordnumber => $source->ordnumber)) {
$args{orddate} = $order->transdate;
}

} elsif ($source->type =~ /_order$/) {
73df5fb5 Moritz Bunkus
$args{deliverydate} = $source->reqdate;
$args{orddate} = $source->transdate;
35429440 Bernd Bleßmann
73df5fb5 Moritz Bunkus
} else {
$args{quodate} = $source->transdate;
}

0eb90109 Moritz Bunkus
# Custom shipto addresses (the ones specific to the sales/purchase
# record and not to the customer/vendor) are only linked from shipto
# → ar. Meaning ar.shipto_id will not be filled in that
# case.
if (!$source->shipto_id && $source->id) {
$args{custom_shipto} = $source->custom_shipto->clone($class) if $source->can('custom_shipto') && $source->custom_shipto;

} else {
$args{shipto_id} = $source->shipto_id;
}

6473dcb1 Moritz Bunkus
my $invoice = $class->new(%args);
$invoice->assign_attributes(%{ $params{attributes} }) if $params{attributes};
53aad992 Moritz Bunkus
my $items = delete($params{items}) || $source->items_sorted;
6ee486a5 Moritz Bunkus
my %item_parents;
73df5fb5 Moritz Bunkus
480f1f35 Moritz Bunkus
if ($params{honor_recurring_billing_mode}) {
$items = [
grep { !$_->can('recurring_billing_mode')
|| ($_->recurring_billing_mode eq 'always')
|| (($_->recurring_billing_mode eq 'once') && !$_->recurring_billing_invoice_id)
} @{ $items }
];
}

73df5fb5 Moritz Bunkus
my @items = map {
2714604a Moritz Bunkus
my $source_item = $_;
6ee486a5 Moritz Bunkus
my $source_item_id = $_->$item_parent_id_column;
2714604a Moritz Bunkus
my @custom_variables = map { _clone_orderitem_delivery_order_item_cvar($_) } @{ $source_item->custom_variables };

6ee486a5 Moritz Bunkus
$item_parents{$source_item_id} ||= $source_item->$item_parent_column;
my $item_parent = $item_parents{$source_item_id};
34420ddb Jan Büren
my $current_invoice_item =
SL::DB::InvoiceItem->new(map({ ( $_ => $source_item->$_ ) }
qw(parts_id description qty sellprice discount project_id serialnumber pricegroup_id transdate cusordnumber unit
base_qty longdescription lastcost price_factor_id active_discount_source active_price_source), @item_columns),
deliverydate => $source_item->reqdate,
fxsellprice => $source_item->sellprice,
custom_variables => \@custom_variables,
ordnumber => ref($item_parent) eq 'SL::DB::Order' ? $item_parent->ordnumber : $source_item->ordnumber,
donumber => ref($item_parent) eq 'SL::DB::DeliveryOrder' ? $item_parent->donumber : $source_item->can('donumber') ? $source_item->donumber : '',
);

c84c3960 Sven Schöling
$current_invoice_item->{RECORD_ITEM_ID()} = $_->{id};
$current_invoice_item->{RECORD_ITEM_TYPE_REF()} = ref $source_item;
34420ddb Jan Büren
$current_invoice_item;
53aad992 Moritz Bunkus
} @{ $items };
73df5fb5 Moritz Bunkus
c84c3960 Sven Schöling
$invoice->{RECORD_ID()} = $source->id;
$invoice->{RECORD_TYPE_REF()} = ref $source;

bbb98e03 Moritz Bunkus
@items = grep { $params{item_filter}->($_) } @items if $params{item_filter};
fff57e55 Moritz Bunkus
@items = grep { $_->qty * 1 } @items if $params{skip_items_zero_qty};
f9fdf190 Moritz Bunkus
@items = grep { $_->qty >=0 } @items if $params{skip_items_negative_qty};
fff57e55 Moritz Bunkus
73df5fb5 Moritz Bunkus
$invoice->invoiceitems(\@items);

return $invoice;
}

dce860e3 Moritz Bunkus
sub post {
my ($self, %params) = @_;

bce4bcf8 Geoffrey Richardson
die "not an invoice" unless $self->invoice;

e4b46220 Sven Schöling
require SL::DB::Chart;
ed3be965 Moritz Bunkus
if (!$params{ar_id}) {
72e40323 Geoffrey Richardson
my $chart;
if ($::instance_conf->get_ar_chart_id) {
$chart = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_ar_chart_id);
} else {
$chart = SL::DB::Manager::Chart->get_all(query => [ SL::DB::Manager::Chart->link_filter('AR') ],
sort_by => 'id ASC',
limit => 1)->[0];
};
6418adee Geoffrey Richardson
croak("No AR chart found and no parameter 'ar_id' given") unless $chart;
ed3be965 Moritz Bunkus
$params{ar_id} = $chart->id;
}
dd04aff2 Moritz Bunkus
96670fe8 Moritz Bunkus
if (!$self->db->with_transaction(sub {
dce860e3 Moritz Bunkus
my %data = $self->calculate_prices_and_taxes;

$self->_post_create_assemblyitem_entries($data{assembly_items});
$self->save;

$self->_post_add_acctrans($data{amounts_cogs});
$self->_post_add_acctrans($data{amounts});
45d6fc38 Bernd Bleßmann
$self->_post_add_acctrans($data{taxes_by_chart_id});
04caff2d Rolf Fluehmann
dd04aff2 Moritz Bunkus
$self->_post_add_acctrans({ $params{ar_id} => $self->amount * -1 });

dce860e3 Moritz Bunkus
$self->_post_update_allocated($data{allocated});
abd56be1 Rolf Fluehmann
$self->_post_book_rounding($data{rounding});
22150c52 Moritz Bunkus
96670fe8 Moritz Bunkus
1;
})) {
0e25aa33 Moritz Bunkus
$::lxdebug->message(LXDebug->WARN(), "convert_to_invoice failed: " . join("\n", (split(/\n/, $self->db->error))[0..2]));
22150c52 Moritz Bunkus
return undef;
}
dce860e3 Moritz Bunkus
22150c52 Moritz Bunkus
return $self;
dce860e3 Moritz Bunkus
}

sub _post_add_acctrans {
my ($self, $entries) = @_;

03ff37cb Niclas Zimmermann
my $default_tax_id = SL::DB::Manager::Tax->find_by(taxkey => 0)->id;
3af5e2e0 Niclas Zimmermann
my $chart_link;
03ff37cb Niclas Zimmermann
e4b46220 Sven Schöling
require SL::DB::AccTransaction;
require SL::DB::Chart;
dce860e3 Moritz Bunkus
while (my ($chart_id, $spec) = each %{ $entries }) {
03ff37cb Niclas Zimmermann
$spec = { taxkey => 0, tax_id => $default_tax_id, amount => $spec } unless ref $spec;
3af5e2e0 Niclas Zimmermann
$chart_link = SL::DB::Manager::Chart->find_by(id => $chart_id)->{'link'};
$chart_link ||= '';

6f2c9845 Bernd Bleßmann
if ($spec->{amount} != 0) {
SL::DB::AccTransaction->new(trans_id => $self->id,
chart_id => $chart_id,
amount => $spec->{amount},
tax_id => $spec->{tax_id},
taxkey => $spec->{taxkey},
project_id => $self->globalproject_id,
transdate => $self->transdate,
chart_link => $chart_link)->save;
}
dce860e3 Moritz Bunkus
}
}

abd56be1 Rolf Fluehmann
sub _post_book_rounding {
my ($self, $rounding) = @_;

my $tax_id = SL::DB::Manager::Tax->find_by(taxkey => 0)->id;
my $rnd_accno = $rounding == 0 ? 0
: $rounding > 0 ? SL::DB::Default->get->rndgain_accno_id
: SL::DB::Default->get->rndloss_accno_id
;
if ($rnd_accno != 0) {
SL::DB::AccTransaction->new(trans_id => $self->id,
chart_id => $rnd_accno,
amount => $rounding,
tax_id => $tax_id,
taxkey => 0,
project_id => $self->globalproject_id,
transdate => $self->transdate,
chart_link => $rnd_accno)->save;
}
}

4f43ec85 Geoffrey Richardson
sub add_ar_amount_row {
my ($self, %params ) = @_;

# only allow this method for ar invoices (Debitorenbuchung)
die "not an ar invoice" if $self->invoice and not $self->customer_id;

die "add_ar_amount_row needs a chart object as chart param" unless $params{chart} && $params{chart}->isa('SL::DB::Chart');
f7cdb6db Geoffrey Richardson
die "chart must be an AR_amount chart" unless $params{chart}->link =~ /AR_amount/;
4f43ec85 Geoffrey Richardson
my $acc_trans = [];

my $roundplaces = 2;
my ($netamount,$taxamount);

$netamount = $params{amount} * 1;
my $tax = SL::DB::Manager::Tax->find_by(id => $params{tax_id}) || die "Can't find tax with id " . $params{tax_id};

if ( $tax and $tax->rate != 0 ) {
($netamount, $taxamount) = Form->calculate_tax($params{amount}, $tax->rate, $self->taxincluded, $roundplaces);
};
73e9f6e3 Bernd Bleßmann
return unless $netamount; # netamount mustn't be zero

4f43ec85 Geoffrey Richardson
my $sign = $self->customer_id ? 1 : -1;
my $acc = SL::DB::AccTransaction->new(
amount => $netamount * $sign,
chart_id => $params{chart}->id,
chart_link => $params{chart}->link,
transdate => $self->transdate,
df183815 Geoffrey Richardson
gldate => $self->gldate,
4f43ec85 Geoffrey Richardson
taxkey => $tax->taxkey,
tax_id => $tax->id,
project_id => $params{project_id},
);

$self->add_transactions( $acc );
push( @$acc_trans, $acc );

if ( $taxamount ) {
my $acc = SL::DB::AccTransaction->new(
amount => $taxamount * $sign,
chart_id => $tax->chart_id,
chart_link => $tax->chart->link,
transdate => $self->transdate,
df183815 Geoffrey Richardson
gldate => $self->gldate,
4f43ec85 Geoffrey Richardson
taxkey => $tax->taxkey,
tax_id => $tax->id,
);
$self->add_transactions( $acc );
push( @$acc_trans, $acc );
};
return $acc_trans;
};

sub create_ar_row {
my ($self, %params) = @_;
# to be called after adding all AR_amount rows, adds an AR row

# only allow this method for ar invoices (Debitorenbuchung)
die if $self->invoice and not $self->customer_id;
die "create_ar_row needs a chart object as a parameter" unless $params{chart} and ref($params{chart}) eq 'SL::DB::Chart';

my @transactions = @{$self->transactions};
# die "invoice has no acc_transactions" unless scalar @transactions > 0;
return 0 unless scalar @transactions > 0;

my $chart = $params{chart} || SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_ar_chart_id);
die "illegal chart in create_ar_row" unless $chart;

die "receivables chart must have link 'AR'" unless $chart->link eq 'AR';

my $acc_trans = [];

# hardcoded entry for no tax: tax_id and taxkey should be 0
my $tax = SL::DB::Manager::Tax->find_by(id => 0, taxkey => 0) || die "Can't find tax with id 0 and taxkey 0";

my $sign = $self->customer_id ? -1 : 1;
my $acc = SL::DB::AccTransaction->new(
amount => $self->amount * $sign,
chart_id => $params{chart}->id,
chart_link => $params{chart}->link,
transdate => $self->transdate,
taxkey => $tax->taxkey,
tax_id => $tax->id,
);
$self->add_transactions( $acc );
push( @$acc_trans, $acc );
return $acc_trans;
11185756 Jan Büren
}
4f43ec85 Geoffrey Richardson
sub validate_acc_trans {
my ($self, %params) = @_;
# should be able to check unsaved invoice objects with several acc_trans lines

die "validate_acc_trans can't check invoice object with empty transactions" unless $self->transactions;

my @transactions = @{$self->transactions};
# die "invoice has no acc_transactions" unless scalar @transactions > 0;
return 0 unless scalar @transactions > 0;
return 0 unless $self->has_loaded_related('transactions');
if ( $params{debug} ) {
printf("starting validatation of invoice %s with trans_id %s and taxincluded %s\n", $self->invnumber, $self->id, $self->taxincluded);
foreach my $acc ( @transactions ) {
printf("chart: %s amount: %s tax_id: %s link: %s\n", $acc->chart->accno, $acc->amount, $acc->tax_id, $acc->chart->link);
};
};

my $acc_trans_sum = sum map { $_->amount } @transactions;

unless ( $::form->round_amount($acc_trans_sum, 10) == 0 ) {
my $string = "sum of acc_transactions isn't 0: $acc_trans_sum\n";

if ( $params{debug} ) {
foreach my $trans ( @transactions ) {
$string .= sprintf(" %s %s %s\n", $trans->chart->accno, $trans->taxkey, $trans->amount);
};
};
return 0;
};

# only use the first AR entry, so it also works for paid invoices
my @ar_transactions = map { $_->amount } grep { $_->chart_link eq 'AR' } @transactions;
my $ar_sum = $ar_transactions[0];
# my $ar_sum = sum map { $_->amount } grep { $_->chart_link eq 'AR' } @transactions;

unless ( $::form->round_amount($ar_sum * -1,2) == $::form->round_amount($self->amount,2) ) {
if ( $params{debug} ) {
printf("debug: (ar_sum) %s = %s (amount)\n", $::form->round_amount($ar_sum * -1,2) , $::form->round_amount($self->amount, 2) );
foreach my $trans ( @transactions ) {
printf(" %s %s %s %s\n", $trans->chart->accno, $trans->taxkey, $trans->amount, $trans->chart->link);
};
};
die sprintf("sum of ar (%s) isn't equal to invoice amount (%s)", $::form->round_amount($ar_sum * -1,2), $::form->round_amount($self->amount,2));
};

return 1;
};

sub recalculate_amounts {
my ($self, %params) = @_;
# calculate and set amount and netamount from acc_trans objects

croak ("Can only recalculate amounts for ar transactions") if $self->invoice;

return undef unless $self->has_loaded_related('transactions');

my ($netamount, $taxamount);

my @transactions = @{$self->transactions};

foreach my $acc ( @transactions ) {
$netamount += $acc->amount if $acc->chart->link =~ /AR_amount/;
$taxamount += $acc->amount if $acc->chart->link =~ /AR_tax/;
};

$self->amount($netamount+$taxamount);
$self->netamount($netamount);
};


dce860e3 Moritz Bunkus
sub _post_create_assemblyitem_entries {
my ($self, $assembly_entries) = @_;

my $items = $self->invoiceitems;
my @new_items;

my $item_idx = 0;
foreach my $item (@{ $items }) {
next if $item->assemblyitem;

push @new_items, $item;
$item_idx++;

foreach my $assembly_item (@{ $assembly_entries->[$item_idx] || [ ] }) {
push @new_items, SL::DB::InvoiceItem->new(parts_id => $assembly_item->{part},
description => $assembly_item->{part}->description,
unit => $assembly_item->{part}->unit,
qty => $assembly_item->{qty},
allocated => $assembly_item->{allocated},
sellprice => 0,
fxsellprice => 0,
assemblyitem => 't');
}
}

$self->invoiceitems(\@new_items);
}

sub _post_update_allocated {
my ($self, $allocated) = @_;

while (my ($invoice_id, $diff) = each %{ $allocated }) {
22150c52 Moritz Bunkus
SL::DB::Manager::InvoiceItem->update_all(set => { allocated => { sql => "allocated + $diff" } },
dce860e3 Moritz Bunkus
where => [ id => $invoice_id ]);
}
}

2746ccd0 Sven Schöling
sub invoice_type {
my ($self) = @_;

return 'ar_transaction' if !$self->invoice;
30784a4d Bernd Bleßmann
return 'invoice_for_advance_payment_storno' if $self->type eq 'invoice_for_advance_payment' && $self->amount < 0 && $self->storno;
return 'invoice_for_advance_payment' if $self->type eq 'invoice_for_advance_payment';
475b7a3f Bernd Bleßmann
return 'final_invoice' if $self->type eq 'final_invoice';
5a1dbe03 Jan Büren
# stornoed credit_notes are still credit notes and not invoices
return 'credit_note' if $self->type eq 'credit_note' && $self->amount < 0;
2746ccd0 Sven Schöling
return 'invoice_storno' if $self->type ne 'credit_note' && $self->amount < 0 && $self->storno;
return 'credit_note_storno' if $self->type eq 'credit_note' && $self->amount > 0 && $self->storno;
return 'invoice';
}

sub displayable_state {
my $self = shift;

return $self->closed ? $::locale->text('closed') : $::locale->text('open');
}

001155e4 Sven Schöling
sub displayable_type {
my ($self) = @_;

return t8('AR Transaction') if $self->invoice_type eq 'ar_transaction';
return t8('Credit Note') if $self->invoice_type eq 'credit_note';
return t8('Invoice') . "(" . t8('Storno') . ")" if $self->invoice_type eq 'invoice_storno';
return t8('Credit Note') . "(" . t8('Storno') . ")" if $self->invoice_type eq 'credit_note_storno';
30784a4d Bernd Bleßmann
return t8('Invoice for Advance Payment') if $self->invoice_type eq 'invoice_for_advance_payment';
return t8('Invoice for Advance Payment') . "(" . t8('Storno') . ")" if $self->invoice_type eq 'invoice_for_advance_payment_storno';
475b7a3f Bernd Bleßmann
return t8('Final Invoice') if $self->invoice_type eq 'final_invoice';
001155e4 Sven Schöling
return t8('Invoice');
}

a7114646 Geoffrey Richardson
sub displayable_name {
join ' ', grep $_, map $_[0]->$_, qw(displayable_type record_number);
};

f6ed86ef Geoffrey Richardson
sub abbreviation {
49f5b7f7 Geoffrey Richardson
my ($self) = @_;
f6ed86ef Geoffrey Richardson
49f5b7f7 Geoffrey Richardson
return t8('AR Transaction (abbreviation)') if $self->invoice_type eq 'ar_transaction';
return t8('Credit note (one letter abbreviation)') if $self->invoice_type eq 'credit_note';
return t8('Invoice (one letter abbreviation)') . "(" . t8('Storno (one letter abbreviation)') . ")" if $self->invoice_type eq 'invoice_storno';
return t8('Credit note (one letter abbreviation)') . "(" . t8('Storno (one letter abbreviation)') . ")" if $self->invoice_type eq 'credit_note_storno';
30784a4d Bernd Bleßmann
return t8('Invoice for Advance Payment (one letter abbreviation)') if $self->invoice_type eq 'invoice_for_advance_payment';
return t8('Invoice for Advance Payment with Storno (abbreviation)') if $self->invoice_type eq 'invoice_for_advance_payment_storno';
475b7a3f Bernd Bleßmann
return t8('Final Invoice (one letter abbreviation)') if $self->invoice_type eq 'final_invoice';
f6ed86ef Geoffrey Richardson
return t8('Invoice (one letter abbreviation)');
}

a5e4f9ca Geoffrey Richardson
sub oneline_summary {
my $self = shift;

0abce1b8 Geoffrey Richardson
return sprintf("%s: %s %s %s (%s)", $self->abbreviation, $self->invnumber, $self->customer->name,
$::form->format_amount(\%::myconfig, $self->amount,2), $self->transdate->to_kivitendo);
a5e4f9ca Geoffrey Richardson
}

16c6be41 Moritz Bunkus
sub date {
goto &transdate;
}

704f339f Sven Schöling
sub reqdate {
goto &duedate;
}

1e2673bb Sven Schöling
sub customervendor {
goto &customer;
}

6a12a968 Niclas Zimmermann
sub link {
my ($self) = @_;

my $html;
0aa885f4 Sven Schöling
$html = $self->presenter->sales_invoice(display => 'inline') if $self->invoice;
$html = $self->presenter->ar_transaction(display => 'inline') if !$self->invoice;
6a12a968 Niclas Zimmermann
return $html;
}

b186a8eb Moritz Bunkus
sub mark_as_paid {
my ($self) = @_;

$self->update_attributes(paid => $self->amount);
}

0b36b225 Moritz Bunkus
sub effective_tax_point {
my ($self) = @_;

return $self->tax_point || $self->deliverydate || $self->transdate;
}

5a6d7c03 Geoffrey Richardson
sub netamount_base_currency {
my ($self) = @_;

return $self->netamount; # already matches base currency
}

82515b2d Sven Schöling
1;
6834acd9 Moritz Bunkus
__END__

=pod

6418adee Geoffrey Richardson
=encoding UTF-8

6834acd9 Moritz Bunkus
=head1 NAME

SL::DB::Invoice: Rose model for invoices (table "ar")

=head1 FUNCTIONS

=over 4

074e54e7 Moritz Bunkus
=item C<new_from $source, %params>
6834acd9 Moritz Bunkus
Creates a new C<SL::DB::Invoice> instance and copies as much
information from C<$source> as possible. At the moment only sales
orders and sales quotations are supported as sources.

The conversion copies order items into invoice items. Dates are copied
as appropriate, e.g. the C<transdate> field from an order will be
copied into the invoice's C<orddate> field.

074e54e7 Moritz Bunkus
C<%params> can include the following options:

=over 2

53aad992 Moritz Bunkus
=item C<items>

An optional array reference of RDBO instances for the items to use. If
missing then the method C<items_sorted> will be called on
C<$source>. This option can be used to override the sorting, to
exclude certain positions or to add additional ones.

f9fdf190 Moritz Bunkus
=item C<skip_items_negative_qty>

If trueish then items with a negative quantity are skipped. Items with
a quantity of 0 are not affected by this option.

fff57e55 Moritz Bunkus
=item C<skip_items_zero_qty>

If trueish then items with a quantity of 0 are skipped.

bbb98e03 Moritz Bunkus
=item C<item_filter>

An optional code reference that is called for each item with the item
as its sole parameter. Items for which the code reference returns a
falsish value will be skipped.

074e54e7 Moritz Bunkus
=item C<attributes>

An optional hash reference. If it exists then it is passed to C<new>
20118160 Jan Büren
allowing the caller to set certain attributes for the new invoice.
For example to set a different transdate (default is the current date),
call the method like this:

my %params;
$params{attributes}{transdate} = '28.08.2015';
$invoice = SL::DB::Invoice->new_from($self, %params)->post || die;
074e54e7 Moritz Bunkus
=back

6834acd9 Moritz Bunkus
Amounts, prices and taxes are not
calculated. L<SL::DB::Helper::PriceTaxCalculator::calculate_prices_and_taxes>
can be used for this.

The object returned is not saved.

=item C<post %params>

Posts the invoice. Required parameters are:

=over 2

=item * C<ar_id>

6418adee Geoffrey Richardson
The ID of the accounts receivable chart the invoice's amounts are
ed3be965 Moritz Bunkus
posted to. If it is not set then the first chart configured for
accounts receivables is used.
6834acd9 Moritz Bunkus
=back

This function implements several steps:

=over 2

=item 1. It calculates all prices, amounts and taxes by calling
L<SL::DB::Helper::PriceTaxCalculator::calculate_prices_and_taxes>.

=item 2. A new and unique invoice number is created.

=item 3. All amounts for costs of goods sold are recorded in
C<acc_trans>.

=item 4. All amounts for parts, services and assemblies are recorded
in C<acc_trans> with their respective charts. This is determined by
the part's buchungsgruppen.

=item 5. The total amount is posted to the accounts receivable chart
and recorded in C<acc_trans>.

=item 6. Items in C<invoice> are updated according to their allocation
6418adee Geoffrey Richardson
status (regarding costs of goods sold). Will only be done if
4bacfb02 Moritz Bunkus
kivitendo is not configured to use Einnahmenüberschussrechnungen.
6834acd9 Moritz Bunkus
=item 7. The invoice and its items are saved.

=back

78600d89 Moritz Bunkus
Returns C<$self> on success and C<undef> on failure. The whole process
is run inside a transaction. If it fails then nothing is saved to or
6418adee Geoffrey Richardson
changed in the database. A new transaction is only started if none are
78600d89 Moritz Bunkus
active.
6834acd9 Moritz Bunkus
=item C<basic_info $field>

See L<SL::DB::Object::basic_info>.

d90966c7 Geoffrey Richardson
=item C<closed>

Returns 1 or 0, depending on whether the invoice is closed or not. Currently
cc685942 Jan Büren
invoices that are overpaid also count as closed and credit notes in general.
d90966c7 Geoffrey Richardson
4f43ec85 Geoffrey Richardson
=item C<recalculate_amounts %params>

Calculate and set amount and netamount from acc_trans objects by summing up the
values of acc_trans objects with AR_amount and AR_tax link charts.
amount and netamount are set to the calculated values.

=item C<validate_acc_trans>

Checks if the sum of all associated acc_trans objects is 0 and checks whether
the amount of the AR acc_transaction matches the AR amount. Only the first AR
line is checked, because the sum of all AR lines is 0 for paid invoices.

Returns 0 or 1.

Can be called with a debug parameter which writes debug info to STDOUT, which is
useful in console mode or while writing tests.

my $ar = SL::DB::Manager::Invoice->get_first();
$ar->validate_acc_trans(debug => 1);

=item C<create_ar_row %params>

Creates a new acc_trans entry for the receivable (AR) entry of an existing AR
invoice object, which already has some income and tax acc_trans entries.

The acc_trans entry is also returned inside an array ref.

Mandatory params are

=over 2

=item * chart as an RDBO object, e.g. for bank. Must be a 'paid' chart.

=back

Currently the amount of the invoice object is used for the acc_trans amount.
5ef5314c Geoffrey Richardson
Use C<recalculate_amounts> before calling this method if amount isn't known
4f43ec85 Geoffrey Richardson
yet or you didn't set it manually.

=item C<add_ar_amount_row %params>

Add a new entry for an existing AR invoice object. Creates an acc_trans entry,
and also adds an acc_trans tax entry, if the tax has an associated tax chart.
Also all acc_trans entries that were created are returned inside an array ref.

Mandatory params are

=over 2

=item * chart as an RDBO object, should be an income chart (link = AR_amount)

=item * tax_id

=item * amount

=back

b186a8eb Moritz Bunkus
=item C<mark_as_paid>

Marks the invoice as paid by setting its C<paid> member to the value of C<amount>.

6834acd9 Moritz Bunkus
=back

20118160 Jan Büren
=head1 TODO
6418adee Geoffrey Richardson
20118160 Jan Büren
As explained in the new_from example, it is possible to set transdate to a new value.
From a user / programm point of view transdate is more than holy and there should be
some validity checker available for controller code. At least the same logic like in
Form.pm from ar.pl should be available:
# see old stuff ar.pl post
#$form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
# if ($form->date_max_future($transdate, \%myconfig));
#$form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));

6834acd9 Moritz Bunkus
=head1 AUTHOR

Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>

=cut