b93956a67acccdc59f9d2afc7f61de1a0ec7ca48
[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::LinkedRecords;
14 use SL::DB::Helper::PriceTaxCalculator;
15 use SL::DB::Employee;
16
17 __PACKAGE__->meta->add_relationship(
18   invoiceitems => {
19     type         => 'one to many',
20     class        => 'SL::DB::InvoiceItem',
21     column_map   => { id => 'trans_id' },
22     manager_args => {
23       with_objects => [ 'part' ]
24     }
25   },
26   payment_term => {
27     type       => 'one to one',
28     class      => 'SL::DB::PaymentTerm',
29     column_map => { payment_id => 'id' },
30   },
31 );
32
33 __PACKAGE__->meta->initialize;
34
35 # methods
36
37 sub items { goto &invoiceitems; }
38
39 # it is assumed, that ordnumbers are unique here.
40 sub first_order_by_ordnumber {
41   my $self = shift;
42
43   my $orders = SL::DB::Manager::Order->get_all(
44     query => [
45       ordnumber => $self->ordnumber,
46
47     ],
48   );
49
50   return first { $_->is_type('sales_order') } @{ $orders };
51 }
52
53 sub abschlag_percentage {
54   my $self         = shift;
55   my $order        = $self->first_order_by_ordnumber or return;
56   my $order_amount = $order->netamount               or return;
57   return $self->abschlag
58     ? $self->netamount / $order_amount
59     : undef;
60 }
61
62 sub taxamount {
63   my $self = shift;
64   die 'not a setter method' if @_;
65
66   return $self->amount - $self->netamount;
67 }
68
69 __PACKAGE__->meta->make_attr_helpers(taxamount => 'numeric(15,5)');
70
71 sub closed {
72   my ($self) = @_;
73   return $self->paid >= $self->amount;
74 }
75
76 sub new_from {
77   my ($class, $source, %params) = @_;
78
79   croak("Unsupported source object type '" . ref($source) . "'") unless ref($source) =~ m/^ SL::DB:: (?: Order | DeliveryOrder ) $/x;
80   croak("Cannot create invoices for purchase records")           unless $source->customer_id;
81
82   my $terms = $source->can('payment_id') && $source->payment_id ? $source->payment_term->terms_netto : 0;
83
84   my %args = ( map({ ( $_ => $source->$_ ) } qw(customer_id taxincluded shippingpoint shipvia notes intnotes curr salesman_id cusordnumber ordnumber quonumber
85                                                 department_id cp_id language_id payment_id delivery_customer_id delivery_vendor_id taxzone_id shipto_id
86                                                 globalproject_id transaction_description)),
87                transdate   => DateTime->today_local,
88                gldate      => DateTime->today_local,
89                duedate     => DateTime->today_local->add(days => $terms * 1),
90                invoice     => 1,
91                type        => 'invoice',
92                storno      => 0,
93                employee_id => (SL::DB::Manager::Employee->current || SL::DB::Employee->new(id => $source->employee_id))->id,
94             );
95
96   if ($source->type =~ /_order$/) {
97     $args{deliverydate} = $source->reqdate;
98     $args{orddate}      = $source->transdate;
99   } else {
100     $args{quodate}      = $source->transdate;
101   }
102
103   my $invoice = $class->new(%args, %params);
104
105   my @items = map {
106     my $source_item = $_;
107     SL::DB::InvoiceItem->new(map({ ( $_ => $source_item->$_ ) }
108                                  qw(parts_id description qty sellprice discount project_id
109                                     serialnumber pricegroup_id ordnumber transdate cusordnumber unit
110                                     base_qty subtotal longdescription lastcost price_factor_id)),
111                             deliverydate => $source_item->reqdate);
112   } @{ $source->items };
113
114   $invoice->invoiceitems(\@items);
115
116   return $invoice;
117 }
118
119 sub post {
120   my ($self, %params) = @_;
121
122   $self->db->do_transaction(sub {
123     1;                          # dummy instruction for Emacs ;)
124
125     my %data = $self->calculate_prices_and_taxes;
126
127     $self->_post_create_assemblyitem_entries($data{assembly_items});
128
129     $self->save;
130
131     $self->_post_add_acctrans($data{amounts_cogs});
132     $self->_post_add_acctrans($data{amounts});
133     $self->_post_add_acctrans($data{taxes});
134
135     $self->_post_update_allocated($data{allocated});
136
137     die;
138   });
139 }
140
141 sub _post_add_acctrans {
142   my ($self, $entries) = @_;
143
144   while (my ($chart_id, $spec) = each %{ $entries }) {
145     $spec = { taxkey => 0, amount => $spec } unless ref $spec;
146     SL::DB::AccTrans->new(trans_id   => $self->id,
147                           chart_id   => $chart_id,
148                           amount     => $spec->{amount},
149                           taxkey     => $spec->{taxkey},
150                           project_id => $self->project_id,
151                           transdate  => $self->transdate)->save;
152   }
153 }
154
155 sub _post_create_assemblyitem_entries {
156   my ($self, $assembly_entries) = @_;
157
158   my $items = $self->invoiceitems;
159   my @new_items;
160
161   my $item_idx = 0;
162   foreach my $item (@{ $items }) {
163     next if $item->assemblyitem;
164
165     push @new_items, $item;
166     $item_idx++;
167
168     foreach my $assembly_item (@{ $assembly_entries->[$item_idx] || [ ] }) {
169       push @new_items, SL::DB::InvoiceItem->new(parts_id     => $assembly_item->{part},
170                                                 description  => $assembly_item->{part}->description,
171                                                 unit         => $assembly_item->{part}->unit,
172                                                 qty          => $assembly_item->{qty},
173                                                 allocated    => $assembly_item->{allocated},
174                                                 sellprice    => 0,
175                                                 fxsellprice  => 0,
176                                                 assemblyitem => 't');
177     }
178   }
179
180   $self->invoiceitems(\@new_items);
181 }
182
183 sub _post_update_allocated {
184   my ($self, $allocated) = @_;
185
186   while (my ($invoice_id, $diff) = each %{ $allocated }) {
187     SL::DB::Manager::InvoiceItem->update_all(set   => { allocated => { sql => [ 'allocated + ?', $diff ] } },
188                                              where => [ id        => $invoice_id ]);
189   }
190 }
191
192 >>>>>>> b6be290... Prototypisiertes Buchen von Rechnungen
193 1;