Helfer-Modul zum Erzeugen von eindeutigen Belegnummern
[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::Helper::TransNumberGenerator;
16 use SL::DB::Employee;
17
18 __PACKAGE__->meta->add_relationship(
19   invoiceitems => {
20     type         => 'one to many',
21     class        => 'SL::DB::InvoiceItem',
22     column_map   => { id => 'trans_id' },
23     manager_args => {
24       with_objects => [ 'part' ]
25     }
26   },
27   payment_term => {
28     type       => 'one to one',
29     class      => 'SL::DB::PaymentTerm',
30     column_map => { payment_id => 'id' },
31   },
32 );
33
34 __PACKAGE__->meta->initialize;
35
36 # methods
37
38 sub items { goto &invoiceitems; }
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 - $self->netamount;
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                employee_id => (SL::DB::Manager::Employee->current || SL::DB::Employee->new(id => $source->employee_id))->id,
95             );
96
97   if ($source->type =~ /_order$/) {
98     $args{deliverydate} = $source->reqdate;
99     $args{orddate}      = $source->transdate;
100   } else {
101     $args{quodate}      = $source->transdate;
102   }
103
104   my $invoice = $class->new(%args, %params);
105
106   my @items = map {
107     my $source_item = $_;
108     SL::DB::InvoiceItem->new(map({ ( $_ => $source_item->$_ ) }
109                                  qw(parts_id description qty sellprice discount project_id
110                                     serialnumber pricegroup_id ordnumber transdate cusordnumber unit
111                                     base_qty subtotal longdescription lastcost price_factor_id)),
112                             deliverydate => $source_item->reqdate);
113   } @{ $source->items };
114
115   $invoice->invoiceitems(\@items);
116
117   return $invoice;
118 }
119
120 sub post {
121   my ($self, %params) = @_;
122
123   $self->db->do_transaction(sub {
124     1;                          # dummy instruction for Emacs ;)
125
126     my %data = $self->calculate_prices_and_taxes;
127
128     $self->_post_create_assemblyitem_entries($data{assembly_items});
129
130     $self->save;
131
132     $self->_post_add_acctrans($data{amounts_cogs});
133     $self->_post_add_acctrans($data{amounts});
134     $self->_post_add_acctrans($data{taxes});
135
136     $self->_post_update_allocated($data{allocated});
137
138     die;
139   });
140 }
141
142 sub _post_add_acctrans {
143   my ($self, $entries) = @_;
144
145   while (my ($chart_id, $spec) = each %{ $entries }) {
146     $spec = { taxkey => 0, amount => $spec } unless ref $spec;
147     SL::DB::AccTrans->new(trans_id   => $self->id,
148                           chart_id   => $chart_id,
149                           amount     => $spec->{amount},
150                           taxkey     => $spec->{taxkey},
151                           project_id => $self->project_id,
152                           transdate  => $self->transdate)->save;
153   }
154 }
155
156 sub _post_create_assemblyitem_entries {
157   my ($self, $assembly_entries) = @_;
158
159   my $items = $self->invoiceitems;
160   my @new_items;
161
162   my $item_idx = 0;
163   foreach my $item (@{ $items }) {
164     next if $item->assemblyitem;
165
166     push @new_items, $item;
167     $item_idx++;
168
169     foreach my $assembly_item (@{ $assembly_entries->[$item_idx] || [ ] }) {
170       push @new_items, SL::DB::InvoiceItem->new(parts_id     => $assembly_item->{part},
171                                                 description  => $assembly_item->{part}->description,
172                                                 unit         => $assembly_item->{part}->unit,
173                                                 qty          => $assembly_item->{qty},
174                                                 allocated    => $assembly_item->{allocated},
175                                                 sellprice    => 0,
176                                                 fxsellprice  => 0,
177                                                 assemblyitem => 't');
178     }
179   }
180
181   $self->invoiceitems(\@new_items);
182 }
183
184 sub _post_update_allocated {
185   my ($self, $allocated) = @_;
186
187   while (my ($invoice_id, $diff) = each %{ $allocated }) {
188     SL::DB::Manager::InvoiceItem->update_all(set   => { allocated => { sql => [ 'allocated + ?', $diff ] } },
189                                              where => [ id        => $invoice_id ]);
190   }
191 }
192
193 >>>>>>> b6be290... Prototypisiertes Buchen von Rechnungen
194 1;