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