kein use SL::DB::Object aus SL::DB::Object
[kivitendo-erp.git] / SL / DB / Invoice.pm
1 # This file has been auto-generated only because it didn't exist.
2 # Feel free to modify it at will; it will not be overwritten automatically.
3
4 package SL::DB::Invoice;
5
6 use strict;
7
8 use Carp;
9 use List::Util qw(first);
10
11 use SL::DB::MetaSetup::Invoice;
12 use SL::DB::Manager::Invoice;
13 use SL::DB::Helper::FlattenToForm;
14 use SL::DB::Helper::LinkedRecords;
15 use SL::DB::Helper::PriceTaxCalculator;
16 use SL::DB::Helper::PriceUpdater;
17 use SL::DB::Helper::TransNumberGenerator;
18
19 __PACKAGE__->meta->add_relationship(
20   invoiceitems => {
21     type         => 'one to many',
22     class        => 'SL::DB::InvoiceItem',
23     column_map   => { id => 'trans_id' },
24     manager_args => {
25       with_objects => [ 'part' ]
26     }
27   },
28   storno_invoices => {
29     type          => 'one to many',
30     class         => 'SL::DB::Invoice',
31     column_map    => { id => 'storno_id' },
32   },
33   sepa_export_items => {
34     type            => 'one to many',
35     class           => 'SL::DB::SepaExportItem',
36     column_map      => { id => 'ar_id' },
37     manager_args    => { with_objects => [ 'sepa_export' ] }
38   },
39 );
40
41 __PACKAGE__->meta->initialize;
42
43 # methods
44
45 sub items { goto &invoiceitems; }
46
47 sub items_sorted {
48   my ($self) = @_;
49
50   return [ sort {$a->id <=> $b->id } @{ $self->items } ];
51 }
52
53 sub is_sales {
54   # For compatibility with Order, DeliveryOrder
55   croak 'not an accessor' if @_ > 1;
56   return 1;
57 }
58
59 # it is assumed, that ordnumbers are unique here.
60 sub first_order_by_ordnumber {
61   my $self = shift;
62
63   my $orders = SL::DB::Manager::Order->get_all(
64     query => [
65       ordnumber => $self->ordnumber,
66
67     ],
68   );
69
70   return first { $_->is_type('sales_order') } @{ $orders };
71 }
72
73 sub abschlag_percentage {
74   my $self         = shift;
75   my $order        = $self->first_order_by_ordnumber or return;
76   my $order_amount = $order->netamount               or return;
77   return $self->abschlag
78     ? $self->netamount / $order_amount
79     : undef;
80 }
81
82 sub taxamount {
83   my $self = shift;
84   die 'not a setter method' if @_;
85
86   return ($self->amount || 0) - ($self->netamount || 0);
87 }
88
89 __PACKAGE__->meta->make_attr_helpers(taxamount => 'numeric(15,5)');
90
91 sub closed {
92   my ($self) = @_;
93   return $self->paid >= $self->amount;
94 }
95
96 sub new_from {
97   my ($class, $source, %params) = @_;
98
99   croak("Unsupported source object type '" . ref($source) . "'") unless ref($source) =~ m/^ SL::DB:: (?: Order | DeliveryOrder ) $/x;
100   croak("Cannot create invoices for purchase records")           unless $source->customer_id;
101
102   require SL::DB::Employee;
103
104   my $terms = $source->can('payment_id') && $source->payment_id ? $source->payment_terms->terms_netto : 0;
105
106   my %args = ( map({ ( $_ => $source->$_ ) } qw(customer_id taxincluded shippingpoint shipvia notes intnotes salesman_id cusordnumber ordnumber quonumber
107                                                 department_id cp_id language_id payment_id delivery_customer_id delivery_vendor_id taxzone_id shipto_id
108                                                 globalproject_id transaction_description currency_id)),
109                transdate   => DateTime->today_local,
110                gldate      => DateTime->today_local,
111                duedate     => DateTime->today_local->add(days => $terms * 1),
112                invoice     => 1,
113                type        => 'invoice',
114                storno      => 0,
115                paid        => 0,
116                employee_id => (SL::DB::Manager::Employee->current || SL::DB::Employee->new(id => $source->employee_id))->id,
117             );
118
119   if ($source->type =~ /_order$/) {
120     $args{deliverydate} = $source->reqdate;
121     $args{orddate}      = $source->transdate;
122   } else {
123     $args{quodate}      = $source->transdate;
124   }
125
126   my $invoice = $class->new(%args, %params);
127
128   my @items = map {
129     my $source_item = $_;
130     SL::DB::InvoiceItem->new(map({ ( $_ => $source_item->$_ ) }
131                                  qw(parts_id description qty sellprice discount project_id
132                                     serialnumber pricegroup_id ordnumber transdate cusordnumber unit
133                                     base_qty subtotal longdescription lastcost price_factor_id)),
134                             deliverydate => $source_item->reqdate,
135                             fxsellprice  => $source_item->sellprice,);
136   } @{ $source->items_sorted };
137
138   $invoice->invoiceitems(\@items);
139
140   return $invoice;
141 }
142
143 sub post {
144   my ($self, %params) = @_;
145
146   require SL::DB::Chart;
147   if (!$params{ar_id}) {
148     my $chart = SL::DB::Manager::Chart->get_all(query   => [ SL::DB::Manager::Chart->link_filter('AR') ],
149                                                 sort_by => 'id ASC',
150                                                 limit   => 1)->[0];
151     croak("No AR chart found and no parameter `ar_id' given") unless $chart;
152     $params{ar_id} = $chart->id;
153   }
154
155   my $worker = sub {
156     my %data = $self->calculate_prices_and_taxes;
157
158     $self->_post_create_assemblyitem_entries($data{assembly_items});
159     $self->create_trans_number;
160     $self->save;
161
162     $self->_post_add_acctrans($data{amounts_cogs});
163     $self->_post_add_acctrans($data{amounts});
164     $self->_post_add_acctrans($data{taxes});
165
166     $self->_post_add_acctrans({ $params{ar_id} => $self->amount * -1 });
167
168     $self->_post_update_allocated($data{allocated});
169   };
170
171   if ($self->db->in_transaction) {
172     $worker->();
173   } elsif (!$self->db->do_transaction($worker)) {
174     $::lxdebug->message(LXDebug->WARN(), "convert_to_invoice failed: " . join("\n", (split(/\n/, $self->db->error))[0..2]));
175     return undef;
176   }
177
178   return $self;
179 }
180
181 sub _post_add_acctrans {
182   my ($self, $entries) = @_;
183
184   my $default_tax_id = SL::DB::Manager::Tax->find_by(taxkey => 0)->id;
185   my $chart_link;
186
187   require SL::DB::AccTransaction;
188   require SL::DB::Chart;
189   while (my ($chart_id, $spec) = each %{ $entries }) {
190     $spec = { taxkey => 0, tax_id => $default_tax_id, amount => $spec } unless ref $spec;
191     $chart_link = SL::DB::Manager::Chart->find_by(id => $chart_id)->{'link'};
192     $chart_link ||= '';
193
194     SL::DB::AccTransaction->new(trans_id   => $self->id,
195                                 chart_id   => $chart_id,
196                                 amount     => $spec->{amount},
197                                 tax_id     => $spec->{tax_id},
198                                 taxkey     => $spec->{taxkey},
199                                 project_id => $self->globalproject_id,
200                                 transdate  => $self->transdate,
201                                 chart_link => $chart_link)->save;
202   }
203 }
204
205 sub _post_create_assemblyitem_entries {
206   my ($self, $assembly_entries) = @_;
207
208   my $items = $self->invoiceitems;
209   my @new_items;
210
211   my $item_idx = 0;
212   foreach my $item (@{ $items }) {
213     next if $item->assemblyitem;
214
215     push @new_items, $item;
216     $item_idx++;
217
218     foreach my $assembly_item (@{ $assembly_entries->[$item_idx] || [ ] }) {
219       push @new_items, SL::DB::InvoiceItem->new(parts_id     => $assembly_item->{part},
220                                                 description  => $assembly_item->{part}->description,
221                                                 unit         => $assembly_item->{part}->unit,
222                                                 qty          => $assembly_item->{qty},
223                                                 allocated    => $assembly_item->{allocated},
224                                                 sellprice    => 0,
225                                                 fxsellprice  => 0,
226                                                 assemblyitem => 't');
227     }
228   }
229
230   $self->invoiceitems(\@new_items);
231 }
232
233 sub _post_update_allocated {
234   my ($self, $allocated) = @_;
235
236   while (my ($invoice_id, $diff) = each %{ $allocated }) {
237     SL::DB::Manager::InvoiceItem->update_all(set   => { allocated => { sql => "allocated + $diff" } },
238                                              where => [ id        => $invoice_id ]);
239   }
240 }
241
242 sub invoice_type {
243   my ($self) = @_;
244
245   return 'ar_transaction'     if !$self->invoice;
246   return 'credit_note'        if $self->type eq 'credit_note' && $self->amount < 0 && !$self->storno;
247   return 'invoice_storno'     if $self->type ne 'credit_note' && $self->amount < 0 &&  $self->storno;
248   return 'credit_note_storno' if $self->type eq 'credit_note' && $self->amount > 0 &&  $self->storno;
249   return 'invoice';
250 }
251
252 sub displayable_state {
253   my $self = shift;
254
255   return $self->closed ? $::locale->text('closed') : $::locale->text('open');
256 }
257
258 sub date {
259   goto &transdate;
260 }
261
262 1;
263
264 __END__
265
266 =pod
267
268 =head1 NAME
269
270 SL::DB::Invoice: Rose model for invoices (table "ar")
271
272 =head1 FUNCTIONS
273
274 =over 4
275
276 =item C<new_from $source>
277
278 Creates a new C<SL::DB::Invoice> instance and copies as much
279 information from C<$source> as possible. At the moment only sales
280 orders and sales quotations are supported as sources.
281
282 The conversion copies order items into invoice items. Dates are copied
283 as appropriate, e.g. the C<transdate> field from an order will be
284 copied into the invoice's C<orddate> field.
285
286 Amounts, prices and taxes are not
287 calculated. L<SL::DB::Helper::PriceTaxCalculator::calculate_prices_and_taxes>
288 can be used for this.
289
290 The object returned is not saved.
291
292 =item C<post %params>
293
294 Posts the invoice. Required parameters are:
295
296 =over 2
297
298 =item * C<ar_id>
299
300 The ID of the accounds receivable chart the invoices amounts are
301 posted to. If it is not set then the first chart configured for
302 accounts receivables is used.
303
304 =back
305
306 This function implements several steps:
307
308 =over 2
309
310 =item 1. It calculates all prices, amounts and taxes by calling
311 L<SL::DB::Helper::PriceTaxCalculator::calculate_prices_and_taxes>.
312
313 =item 2. A new and unique invoice number is created.
314
315 =item 3. All amounts for costs of goods sold are recorded in
316 C<acc_trans>.
317
318 =item 4. All amounts for parts, services and assemblies are recorded
319 in C<acc_trans> with their respective charts. This is determined by
320 the part's buchungsgruppen.
321
322 =item 5. The total amount is posted to the accounts receivable chart
323 and recorded in C<acc_trans>.
324
325 =item 6. Items in C<invoice> are updated according to their allocation
326 status (regarding for costs of goold sold). Will only be done if
327 kivitendo is not configured to use Einnahmenüberschussrechnungen.
328
329 =item 7. The invoice and its items are saved.
330
331 =back
332
333 Returns C<$self> on success and C<undef> on failure. The whole process
334 is run inside a transaction. If it fails then nothing is saved to or
335 changed in the database. A new transaction is only started if none is
336 active.
337
338 =item C<basic_info $field>
339
340 See L<SL::DB::Object::basic_info>.
341
342 =back
343
344 =head1 AUTHOR
345
346 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
347
348 =cut