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