70291ad6172e916baf9a51090f980a545bd8b8c1
[kivitendo-erp.git] / SL / DB / Invoice.pm
1 package SL::DB::Invoice;
2
3 use strict;
4
5 use Carp;
6 use List::Util qw(first);
7
8 use Rose::DB::Object::Helpers ();
9 use SL::DB::MetaSetup::Invoice;
10 use SL::DB::Manager::Invoice;
11 use SL::DB::Helper::Payment qw(:ALL);
12 use SL::DB::Helper::AttrHTML;
13 use SL::DB::Helper::AttrSorted;
14 use SL::DB::Helper::FlattenToForm;
15 use SL::DB::Helper::LinkedRecords;
16 use SL::DB::Helper::PriceTaxCalculator;
17 use SL::DB::Helper::PriceUpdater;
18 use SL::DB::Helper::TransNumberGenerator;
19 use SL::Locale::String qw(t8);
20 use SL::DB::CustomVariable;
21
22 __PACKAGE__->meta->add_relationship(
23   invoiceitems => {
24     type         => 'one to many',
25     class        => 'SL::DB::InvoiceItem',
26     column_map   => { id => 'trans_id' },
27     manager_args => {
28       with_objects => [ 'part' ]
29     }
30   },
31   storno_invoices => {
32     type          => 'one to many',
33     class         => 'SL::DB::Invoice',
34     column_map    => { id => 'storno_id' },
35   },
36   sepa_export_items => {
37     type            => 'one to many',
38     class           => 'SL::DB::SepaExportItem',
39     column_map      => { id => 'ar_id' },
40     manager_args    => { with_objects => [ 'sepa_export' ] }
41   },
42   sepa_exports      => {
43     type            => 'many to many',
44     map_class       => 'SL::DB::SepaExportItem',
45     map_from        => 'ar',
46     map_to          => 'sepa_export',
47   },
48   custom_shipto     => {
49     type            => 'one to one',
50     class           => 'SL::DB::Shipto',
51     column_map      => { id => 'trans_id' },
52     query_args      => [ module => 'AR' ],
53   },
54   transactions   => {
55     type         => 'one to many',
56     class        => 'SL::DB::AccTransaction',
57     column_map   => { id => 'trans_id' },
58     manager_args => {
59       with_objects => [ 'chart' ],
60       sort_by      => 'acc_trans_id ASC',
61     },
62   },
63 );
64
65 __PACKAGE__->meta->initialize;
66
67 __PACKAGE__->attr_html('notes');
68 __PACKAGE__->attr_sorted('items');
69
70 __PACKAGE__->before_save('_before_save_set_invnumber');
71
72 # hooks
73
74 sub _before_save_set_invnumber {
75   my ($self) = @_;
76
77   $self->create_trans_number if !$self->invnumber;
78
79   return 1;
80 }
81
82 # methods
83
84 sub items { goto &invoiceitems; }
85 sub add_items { goto &add_invoiceitems; }
86 sub record_number { goto &invnumber; };
87
88 sub is_sales {
89   # For compatibility with Order, DeliveryOrder
90   croak 'not an accessor' if @_ > 1;
91   return 1;
92 }
93
94 # it is assumed, that ordnumbers are unique here.
95 sub first_order_by_ordnumber {
96   my $self = shift;
97
98   my $orders = SL::DB::Manager::Order->get_all(
99     query => [
100       ordnumber => $self->ordnumber,
101
102     ],
103   );
104
105   return first { $_->is_type('sales_order') } @{ $orders };
106 }
107
108 sub abschlag_percentage {
109   my $self         = shift;
110   my $order        = $self->first_order_by_ordnumber or return;
111   my $order_amount = $order->netamount               or return;
112   return $self->abschlag
113     ? $self->netamount / $order_amount
114     : undef;
115 }
116
117 sub taxamount {
118   my $self = shift;
119   die 'not a setter method' if @_;
120
121   return ($self->amount || 0) - ($self->netamount || 0);
122 }
123
124 __PACKAGE__->meta->make_attr_helpers(taxamount => 'numeric(15,5)');
125
126 sub closed {
127   my ($self) = @_;
128   return $self->paid >= $self->amount;
129 }
130
131 sub _clone_orderitem_delivery_order_item_cvar {
132   my ($cvar) = @_;
133
134   my $cloned = Rose::DB::Object::Helpers::clone_and_reset($_);
135   $cloned->sub_module('invoice');
136
137   return $cloned;
138 }
139
140 sub new_from {
141   my ($class, $source, %params) = @_;
142
143   croak("Unsupported source object type '" . ref($source) . "'") unless ref($source) =~ m/^ SL::DB:: (?: Order | DeliveryOrder ) $/x;
144   croak("Cannot create invoices for purchase records")           unless $source->customer_id;
145
146   require SL::DB::Employee;
147
148   my (@columns, @item_columns, $item_parent_id_column, $item_parent_column);
149
150   if (ref($source) eq 'SL::DB::Order') {
151     @columns      = qw(quonumber delivery_customer_id delivery_vendor_id);
152     @item_columns = qw(subtotal);
153
154     $item_parent_id_column = 'trans_id';
155     $item_parent_column    = 'order';
156
157   } else {
158     @columns      = qw(donumber);
159
160     $item_parent_id_column = 'delivery_order_id';
161     $item_parent_column    = 'delivery_order';
162   }
163
164   my $terms = $source->can('payment_id') ? $source->payment_terms : undef;
165
166   my %args = ( map({ ( $_ => $source->$_ ) } qw(customer_id taxincluded shippingpoint shipvia notes intnotes salesman_id cusordnumber ordnumber department_id
167                                                 cp_id language_id taxzone_id shipto_id globalproject_id transaction_description currency_id delivery_term_id payment_id), @columns),
168                transdate   => DateTime->today_local,
169                gldate      => DateTime->today_local,
170                duedate     => $terms ? $terms->calc_date(reference_date => DateTime->today_local) : DateTime->today_local,
171                invoice     => 1,
172                type        => 'invoice',
173                storno      => 0,
174                paid        => 0,
175                employee_id => (SL::DB::Manager::Employee->current || SL::DB::Employee->new(id => $source->employee_id))->id,
176             );
177
178   if ($source->type =~ /_order$/) {
179     $args{deliverydate} = $source->reqdate;
180     $args{orddate}      = $source->transdate;
181   } else {
182     $args{quodate}      = $source->transdate;
183   }
184
185   my $invoice = $class->new(%args);
186   $invoice->assign_attributes(%{ $params{attributes} }) if $params{attributes};
187   my $items   = delete($params{items}) || $source->items_sorted;
188   my %item_parents;
189
190   my @items = map {
191     my $source_item      = $_;
192     my $source_item_id   = $_->$item_parent_id_column;
193     my @custom_variables = map { _clone_orderitem_delivery_order_item_cvar($_) } @{ $source_item->custom_variables };
194
195     $item_parents{$source_item_id} ||= $source_item->$item_parent_column;
196     my $item_parent                  = $item_parents{$source_item_id};
197     my $current_invoice_item =
198       SL::DB::InvoiceItem->new(map({ ( $_ => $source_item->$_ ) }
199                                    qw(parts_id description qty sellprice discount project_id serialnumber pricegroup_id transdate cusordnumber unit
200                                       base_qty longdescription lastcost price_factor_id active_discount_source active_price_source), @item_columns),
201                                deliverydate     => $source_item->reqdate,
202                                fxsellprice      => $source_item->sellprice,
203                                custom_variables => \@custom_variables,
204                                ordnumber        => ref($item_parent) eq 'SL::DB::Order'         ? $item_parent->ordnumber : $source_item->ordnumber,
205                                donumber         => ref($item_parent) eq 'SL::DB::DeliveryOrder' ? $item_parent->donumber  : $source_item->can('donumber') ? $source_item->donumber : '',
206                              );
207
208     $current_invoice_item->{"converted_from_orderitems_id"}           = $_->{id} if ref($item_parent) eq 'SL::DB::Order';
209     $current_invoice_item->{"converted_from_delivery_order_items_id"} = $_->{id} if ref($item_parent) eq 'SL::DB::DeliveryOrder';
210     $current_invoice_item;
211   } @{ $items };
212
213   @items = grep { $params{item_filter}->($_) } @items if $params{item_filter};
214   @items = grep { $_->qty * 1 } @items if $params{skip_items_zero_qty};
215   @items = grep { $_->qty >=0 } @items if $params{skip_items_negative_qty};
216
217   $invoice->invoiceitems(\@items);
218
219   return $invoice;
220 }
221
222 sub post {
223   my ($self, %params) = @_;
224
225   die "not an invoice" unless $self->invoice;
226
227   require SL::DB::Chart;
228   if (!$params{ar_id}) {
229     my $chart = SL::DB::Manager::Chart->get_all(query   => [ SL::DB::Manager::Chart->link_filter('AR') ],
230                                                 sort_by => 'id ASC',
231                                                 limit   => 1)->[0];
232     croak("No AR chart found and no parameter 'ar_id' given") unless $chart;
233     $params{ar_id} = $chart->id;
234   }
235
236   my $worker = sub {
237     my %data = $self->calculate_prices_and_taxes;
238
239     $self->_post_create_assemblyitem_entries($data{assembly_items});
240     $self->save;
241
242     $self->_post_add_acctrans($data{amounts_cogs});
243     $self->_post_add_acctrans($data{amounts});
244     $self->_post_add_acctrans($data{taxes});
245
246     $self->_post_add_acctrans({ $params{ar_id} => $self->amount * -1 });
247
248     $self->_post_update_allocated($data{allocated});
249   };
250
251   if ($self->db->in_transaction) {
252     $worker->();
253   } elsif (!$self->db->do_transaction($worker)) {
254     $::lxdebug->message(LXDebug->WARN(), "convert_to_invoice failed: " . join("\n", (split(/\n/, $self->db->error))[0..2]));
255     return undef;
256   }
257
258   return $self;
259 }
260
261 sub _post_add_acctrans {
262   my ($self, $entries) = @_;
263
264   my $default_tax_id = SL::DB::Manager::Tax->find_by(taxkey => 0)->id;
265   my $chart_link;
266
267   require SL::DB::AccTransaction;
268   require SL::DB::Chart;
269   while (my ($chart_id, $spec) = each %{ $entries }) {
270     $spec = { taxkey => 0, tax_id => $default_tax_id, amount => $spec } unless ref $spec;
271     $chart_link = SL::DB::Manager::Chart->find_by(id => $chart_id)->{'link'};
272     $chart_link ||= '';
273
274     SL::DB::AccTransaction->new(trans_id   => $self->id,
275                                 chart_id   => $chart_id,
276                                 amount     => $spec->{amount},
277                                 tax_id     => $spec->{tax_id},
278                                 taxkey     => $spec->{taxkey},
279                                 project_id => $self->globalproject_id,
280                                 transdate  => $self->transdate,
281                                 chart_link => $chart_link)->save;
282   }
283 }
284
285 sub _post_create_assemblyitem_entries {
286   my ($self, $assembly_entries) = @_;
287
288   my $items = $self->invoiceitems;
289   my @new_items;
290
291   my $item_idx = 0;
292   foreach my $item (@{ $items }) {
293     next if $item->assemblyitem;
294
295     push @new_items, $item;
296     $item_idx++;
297
298     foreach my $assembly_item (@{ $assembly_entries->[$item_idx] || [ ] }) {
299       push @new_items, SL::DB::InvoiceItem->new(parts_id     => $assembly_item->{part},
300                                                 description  => $assembly_item->{part}->description,
301                                                 unit         => $assembly_item->{part}->unit,
302                                                 qty          => $assembly_item->{qty},
303                                                 allocated    => $assembly_item->{allocated},
304                                                 sellprice    => 0,
305                                                 fxsellprice  => 0,
306                                                 assemblyitem => 't');
307     }
308   }
309
310   $self->invoiceitems(\@new_items);
311 }
312
313 sub _post_update_allocated {
314   my ($self, $allocated) = @_;
315
316   while (my ($invoice_id, $diff) = each %{ $allocated }) {
317     SL::DB::Manager::InvoiceItem->update_all(set   => { allocated => { sql => "allocated + $diff" } },
318                                              where => [ id        => $invoice_id ]);
319   }
320 }
321
322 sub invoice_type {
323   my ($self) = @_;
324
325   return 'ar_transaction'     if !$self->invoice;
326   return 'credit_note'        if $self->type eq 'credit_note' && $self->amount < 0 && !$self->storno;
327   return 'invoice_storno'     if $self->type ne 'credit_note' && $self->amount < 0 &&  $self->storno;
328   return 'credit_note_storno' if $self->type eq 'credit_note' && $self->amount > 0 &&  $self->storno;
329   return 'invoice';
330 }
331
332 sub displayable_state {
333   my $self = shift;
334
335   return $self->closed ? $::locale->text('closed') : $::locale->text('open');
336 }
337
338 sub displayable_type {
339   my ($self) = @_;
340
341   return t8('AR Transaction')                         if $self->invoice_type eq 'ar_transaction';
342   return t8('Credit Note')                            if $self->invoice_type eq 'credit_note';
343   return t8('Invoice') . "(" . t8('Storno') . ")"     if $self->invoice_type eq 'invoice_storno';
344   return t8('Credit Note') . "(" . t8('Storno') . ")" if $self->invoice_type eq 'credit_note_storno';
345   return t8('Invoice');
346 }
347
348 sub displayable_name {
349   join ' ', grep $_, map $_[0]->$_, qw(displayable_type record_number);
350 };
351
352 sub abbreviation {
353   my ($self) = @_;
354
355   return t8('AR Transaction (abbreviation)')         if $self->invoice_type eq 'ar_transaction';
356   return t8('Credit note (one letter abbreviation)') if $self->invoice_type eq 'credit_note';
357   return t8('Invoice (one letter abbreviation)') . "(" . t8('Storno (one letter abbreviation)') . ")" if $self->invoice_type eq 'invoice_storno';
358   return t8('Credit note (one letter abbreviation)') . "(" . t8('Storno (one letter abbreviation)') . ")"  if $self->invoice_type eq 'credit_note_storno';
359   return t8('Invoice (one letter abbreviation)');
360 }
361
362 sub date {
363   goto &transdate;
364 }
365
366 sub reqdate {
367   goto &duedate;
368 }
369
370 sub customervendor {
371   goto &customer;
372 }
373
374 sub link {
375   my ($self) = @_;
376
377   my $html;
378   $html   = SL::Presenter->get->sales_invoice($self, display => 'inline') if $self->invoice;
379   $html   = SL::Presenter->get->ar_transaction($self, display => 'inline') if !$self->invoice;
380
381   return $html;
382 }
383
384 1;
385
386 __END__
387
388 =pod
389
390 =encoding UTF-8
391
392 =head1 NAME
393
394 SL::DB::Invoice: Rose model for invoices (table "ar")
395
396 =head1 FUNCTIONS
397
398 =over 4
399
400 =item C<new_from $source, %params>
401
402 Creates a new C<SL::DB::Invoice> instance and copies as much
403 information from C<$source> as possible. At the moment only sales
404 orders and sales quotations are supported as sources.
405
406 The conversion copies order items into invoice items. Dates are copied
407 as appropriate, e.g. the C<transdate> field from an order will be
408 copied into the invoice's C<orddate> field.
409
410 C<%params> can include the following options:
411
412 =over 2
413
414 =item C<items>
415
416 An optional array reference of RDBO instances for the items to use. If
417 missing then the method C<items_sorted> will be called on
418 C<$source>. This option can be used to override the sorting, to
419 exclude certain positions or to add additional ones.
420
421 =item C<skip_items_negative_qty>
422
423 If trueish then items with a negative quantity are skipped. Items with
424 a quantity of 0 are not affected by this option.
425
426 =item C<skip_items_zero_qty>
427
428 If trueish then items with a quantity of 0 are skipped.
429
430 =item C<item_filter>
431
432 An optional code reference that is called for each item with the item
433 as its sole parameter. Items for which the code reference returns a
434 falsish value will be skipped.
435
436 =item C<attributes>
437
438 An optional hash reference. If it exists then it is passed to C<new>
439 allowing the caller to set certain attributes for the new invoice.
440 For example to set a different transdate (default is the current date),
441 call the method like this:
442
443    my %params;
444    $params{attributes}{transdate} = '28.08.2015';
445    $invoice = SL::DB::Invoice->new_from($self, %params)->post || die;
446
447 =back
448
449 Amounts, prices and taxes are not
450 calculated. L<SL::DB::Helper::PriceTaxCalculator::calculate_prices_and_taxes>
451 can be used for this.
452
453 The object returned is not saved.
454
455 =item C<post %params>
456
457 Posts the invoice. Required parameters are:
458
459 =over 2
460
461 =item * C<ar_id>
462
463 The ID of the accounts receivable chart the invoice's amounts are
464 posted to. If it is not set then the first chart configured for
465 accounts receivables is used.
466
467 =back
468
469 This function implements several steps:
470
471 =over 2
472
473 =item 1. It calculates all prices, amounts and taxes by calling
474 L<SL::DB::Helper::PriceTaxCalculator::calculate_prices_and_taxes>.
475
476 =item 2. A new and unique invoice number is created.
477
478 =item 3. All amounts for costs of goods sold are recorded in
479 C<acc_trans>.
480
481 =item 4. All amounts for parts, services and assemblies are recorded
482 in C<acc_trans> with their respective charts. This is determined by
483 the part's buchungsgruppen.
484
485 =item 5. The total amount is posted to the accounts receivable chart
486 and recorded in C<acc_trans>.
487
488 =item 6. Items in C<invoice> are updated according to their allocation
489 status (regarding costs of goods sold). Will only be done if
490 kivitendo is not configured to use Einnahmenüberschussrechnungen.
491
492 =item 7. The invoice and its items are saved.
493
494 =back
495
496 Returns C<$self> on success and C<undef> on failure. The whole process
497 is run inside a transaction. If it fails then nothing is saved to or
498 changed in the database. A new transaction is only started if none are
499 active.
500
501 =item C<basic_info $field>
502
503 See L<SL::DB::Object::basic_info>.
504
505 =back
506
507 =head1 TODO
508
509  As explained in the new_from example, it is possible to set transdate to a new value.
510  From a user / programm point of view transdate is more than holy and there should be
511  some validity checker available for controller code. At least the same logic like in
512  Form.pm from ar.pl should be available:
513   # see old stuff ar.pl post
514   #$form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
515   #  if ($form->date_max_future($transdate, \%myconfig));
516   #$form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
517
518 =head1 AUTHOR
519
520 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
521
522 =cut