DeliveryOrder->new_from: kein $custom_shipto-Objekt zurückgeben
[kivitendo-erp.git] / SL / DB / Order.pm
1 package SL::DB::Order;
2
3 use utf8;
4 use strict;
5
6 use Carp;
7 use DateTime;
8 use List::Util qw(max);
9
10 use SL::DB::MetaSetup::Order;
11 use SL::DB::Manager::Order;
12 use SL::DB::Helper::AttrHTML;
13 use SL::DB::Helper::AttrSorted;
14 use SL::DB::Helper::FlattenToForm;
15 use SL::DB::Helper::LinkedRecords;
16 use SL::DB::Helper::PriceTaxCalculator;
17 use SL::DB::Helper::PriceUpdater;
18 use SL::DB::Helper::TransNumberGenerator;
19 use SL::RecordLinks;
20 use Rose::DB::Object::Helpers qw(as_tree);
21
22 __PACKAGE__->meta->add_relationship(
23   orderitems => {
24     type         => 'one to many',
25     class        => 'SL::DB::OrderItem',
26     column_map   => { id => 'trans_id' },
27     manager_args => {
28       with_objects => [ 'part' ]
29     }
30   },
31   periodic_invoices_config => {
32     type                   => 'one to one',
33     class                  => 'SL::DB::PeriodicInvoicesConfig',
34     column_map             => { id => 'oe_id' },
35   },
36   custom_shipto            => {
37     type                   => 'one to one',
38     class                  => 'SL::DB::Shipto',
39     column_map             => { id => 'trans_id' },
40     query_args             => [ module => 'OE' ],
41   },
42 );
43
44 __PACKAGE__->meta->initialize;
45
46 __PACKAGE__->attr_html('notes');
47 __PACKAGE__->attr_sorted('items');
48
49 __PACKAGE__->before_save('_before_save_set_ord_quo_number');
50
51 # hooks
52
53 sub _before_save_set_ord_quo_number {
54   my ($self) = @_;
55
56   # ordnumber is 'NOT NULL'. Therefore make sure it's always set to at
57   # least an empty string, even if we're saving a quotation.
58   $self->ordnumber('') if !$self->ordnumber;
59
60   my $field = $self->quotation ? 'quonumber' : 'ordnumber';
61   $self->create_trans_number if !$self->$field;
62
63   return 1;
64 }
65
66 # methods
67
68 sub items { goto &orderitems; }
69 sub add_items { goto &add_orderitems; }
70 sub record_number { goto &number; }
71
72 sub type {
73   my $self = shift;
74
75   return 'sales_order'       if $self->customer_id && ! $self->quotation;
76   return 'purchase_order'    if $self->vendor_id   && ! $self->quotation;
77   return 'sales_quotation'   if $self->customer_id &&   $self->quotation;
78   return 'request_quotation' if $self->vendor_id   &&   $self->quotation;
79
80   return;
81 }
82
83 sub is_type {
84   return shift->type eq shift;
85 }
86
87 sub displayable_type {
88   my $type = shift->type;
89
90   return $::locale->text('Sales quotation')   if $type eq 'sales_quotation';
91   return $::locale->text('Request quotation') if $type eq 'request_quotation';
92   return $::locale->text('Sales Order')       if $type eq 'sales_order';
93   return $::locale->text('Purchase Order')    if $type eq 'purchase_order';
94
95   die 'invalid type';
96 }
97
98 sub displayable_name {
99   join ' ', grep $_, map $_[0]->$_, qw(displayable_type record_number);
100 };
101
102 sub is_sales {
103   croak 'not an accessor' if @_ > 1;
104   return !!shift->customer_id;
105 }
106
107 sub invoices {
108   my $self   = shift;
109   my %params = @_;
110
111   if ($self->quotation) {
112     return [];
113   } else {
114     require SL::DB::Invoice;
115     return SL::DB::Manager::Invoice->get_all(
116       query => [
117         ordnumber => $self->ordnumber,
118         @{ $params{query} || [] },
119       ]
120     );
121   }
122 }
123
124 sub displayable_state {
125   my ($self) = @_;
126
127   return $self->closed ? $::locale->text('closed') : $::locale->text('open');
128 }
129
130 sub abschlag_invoices {
131   return shift()->invoices(query => [ abschlag => 1 ]);
132 }
133
134 sub end_invoice {
135   return shift()->invoices(query => [ abschlag => 0 ]);
136 }
137
138 sub convert_to_invoice {
139   my ($self, %params) = @_;
140
141   croak("Conversion to invoices is only supported for sales records") unless $self->customer_id;
142
143   my $invoice;
144   if (!$self->db->with_transaction(sub {
145     require SL::DB::Invoice;
146     $invoice = SL::DB::Invoice->new_from($self)->post(%params) || die;
147     $self->link_to_record($invoice);
148     $self->update_attributes(closed => 1);
149     1;
150   })) {
151     return undef;
152   }
153
154   return $invoice;
155 }
156
157 sub convert_to_delivery_order {
158   my ($self, @args) = @_;
159
160   my $delivery_order;
161   if (!$self->db->with_transaction(sub {
162     require SL::DB::DeliveryOrder;
163     $delivery_order = SL::DB::DeliveryOrder->new_from($self, @args);
164     $delivery_order->save;
165     $self->link_to_record($delivery_order);
166     # TODO extend link_to_record for items, otherwise long-term no d.r.y.
167     foreach my $item (@{ $delivery_order->items }) {
168       foreach (qw(orderitems)) {    # expand if needed (delivery_order_items)
169         if ($item->{"converted_from_${_}_id"}) {
170           die unless $item->{id};
171           RecordLinks->create_links('mode'       => 'ids',
172                                     'from_table' => $_,
173                                     'from_ids'   => $item->{"converted_from_${_}_id"},
174                                     'to_table'   => 'delivery_order_items',
175                                     'to_id'      => $item->{id},
176           ) || die;
177           delete $item->{"converted_from_${_}_id"};
178         }
179       }
180     }
181
182     $self->update_attributes(delivered => 1);
183     1;
184   })) {
185     return undef;
186   }
187
188   return $delivery_order;
189 }
190
191 sub number {
192   my $self = shift;
193
194   my %number_method = (
195     sales_order       => 'ordnumber',
196     sales_quotation   => 'quonumber',
197     purchase_order    => 'ordnumber',
198     request_quotation => 'quonumber',
199   );
200
201   return $self->${ \ $number_method{$self->type} }(@_);
202 }
203
204 sub customervendor {
205   $_[0]->is_sales ? $_[0]->customer : $_[0]->vendor;
206 }
207
208 sub date {
209   goto &transdate;
210 }
211
212 sub digest {
213   my ($self) = @_;
214
215   sprintf "%s %s %s (%s)",
216     $self->number,
217     $self->customervendor->name,
218     $self->amount_as_number,
219     $self->date->to_kivitendo;
220 }
221
222 1;
223
224 __END__
225
226 =head1 NAME
227
228 SL::DB::Order - Order Datenbank Objekt.
229
230 =head1 FUNCTIONS
231
232 =head2 C<type>
233
234 Returns one of the following string types:
235
236 =over 4
237
238 =item sales_order
239
240 =item purchase_order
241
242 =item sales_quotation
243
244 =item request_quotation
245
246 =back
247
248 =head2 C<is_type TYPE>
249
250 Returns true if the order is of the given type.
251
252 =head2 C<convert_to_delivery_order %params>
253
254 Creates a new delivery order with C<$self> as the basis by calling
255 L<SL::DB::DeliveryOrder::new_from>. That delivery order is saved, and
256 C<$self> is linked to the new invoice via
257 L<SL::DB::RecordLink>. C<$self>'s C<delivered> attribute is set to
258 C<true>, and C<$self> is saved.
259
260 The arguments in C<%params> are passed to
261 L<SL::DB::DeliveryOrder::new_from>.
262
263 Returns C<undef> on failure. Otherwise the new delivery order will be
264 returned.
265
266 =head2 C<convert_to_invoice %params>
267
268 Creates a new invoice with C<$self> as the basis by calling
269 L<SL::DB::Invoice::new_from>. That invoice is posted, and C<$self> is
270 linked to the new invoice via L<SL::DB::RecordLink>. C<$self>'s
271 C<closed> attribute is set to C<true>, and C<$self> is saved.
272
273 The arguments in C<%params> are passed to L<SL::DB::Invoice::post>.
274
275 Returns the new invoice instance on success and C<undef> on
276 failure. The whole process is run inside a transaction. On failure
277 nothing is created or changed in the database.
278
279 At the moment only sales quotations and sales orders can be converted.
280
281 =head2 C<create_sales_process>
282
283 Creates and saves a new sales process. Can only be called for sales
284 orders.
285
286 The newly created process will be linked bidirectionally to both
287 C<$self> and to all sales quotations that are linked to C<$self>.
288
289 Returns the newly created process instance.
290
291 =head1 BUGS
292
293 Nothing here yet.
294
295 =head1 AUTHOR
296
297 Sven Schöling <s.schoeling@linet-services.de>
298
299 =cut