SL::DB::Order: keinen Fehler werfen, wenn Typ noch nicht zu ermitteln.
[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('dbh'        => $self->db->dbh,
172                                     'mode'       => 'ids',
173                                     'from_table' => $_,
174                                     'from_ids'   => $item->{"converted_from_${_}_id"},
175                                     'to_table'   => 'delivery_order_items',
176                                     'to_id'      => $item->{id},
177           ) || die;
178           delete $item->{"converted_from_${_}_id"};
179         }
180       }
181     }
182
183     $self->update_attributes(delivered => 1);
184     1;
185   })) {
186     return undef;
187   }
188
189   return $delivery_order;
190 }
191
192 sub _clone_orderitem_cvar {
193   my ($cvar) = @_;
194
195   my $cloned = $_->clone_and_reset;
196   $cloned->sub_module('orderitems');
197
198   return $cloned;
199 }
200
201 sub new_from {
202   my ($class, $source, %params) = @_;
203
204   croak("Unsupported source object type '" . ref($source) . "'") unless ref($source) eq 'SL::DB::Order';
205   croak("A destination type must be given parameter")            unless $params{destination_type};
206
207   my $destination_type  = delete $params{destination_type};
208   my $src_dst_allowed   = ('sales_quotation'   eq $source->type && 'sales_order'    eq $destination_type)
209                        || ('request_quotation' eq $source->type && 'purchase_order' eq $destination_type);
210   croak("Cannot convert from '" . $source->type . "' to '" . $destination_type . "'") unless $src_dst_allowed;
211
212   my ($item_parent_id_column, $item_parent_column);
213
214   if (ref($source) eq 'SL::DB::Order') {
215     $item_parent_id_column = 'trans_id';
216     $item_parent_column    = 'order';
217   }
218
219   my %args = ( map({ ( $_ => $source->$_ ) } qw(amount cp_id currency_id cusordnumber customer_id delivery_customer_id delivery_term_id delivery_vendor_id
220                                                 department_id employee_id globalproject_id intnotes marge_percent marge_total language_id netamount notes
221                                                 ordnumber payment_id quonumber reqdate salesman_id shippingpoint shipvia taxincluded taxzone_id
222                                                 transaction_description vendor_id
223                                              )),
224                quotation => 0,
225                closed    => 0,
226                delivered => 0,
227                transdate => DateTime->today_local,
228             );
229
230   # Custom shipto addresses (the ones specific to the sales/purchase
231   # record and not to the customer/vendor) are only linked from
232   # shipto → delivery_orders. Meaning delivery_orders.shipto_id
233   # will not be filled in that case.
234   if (!$source->shipto_id && $source->id) {
235     $args{custom_shipto} = $source->custom_shipto->clone($class) if $source->can('custom_shipto') && $source->custom_shipto;
236
237   } else {
238     $args{shipto_id} = $source->shipto_id;
239   }
240
241   my $order = $class->new(%args);
242   $order->assign_attributes(%{ $params{attributes} }) if $params{attributes};
243   my $items = delete($params{items}) || $source->items_sorted;
244   my %item_parents;
245
246   my @items = map {
247     my $source_item      = $_;
248     my $source_item_id   = $_->$item_parent_id_column;
249     my @custom_variables = map { _clone_orderitem_cvar($_) } @{ $source_item->custom_variables };
250
251     $item_parents{$source_item_id} ||= $source_item->$item_parent_column;
252     my $item_parent                  = $item_parents{$source_item_id};
253
254     my $current_oe_item = SL::DB::OrderItem->new(map({ ( $_ => $source_item->$_ ) }
255                                                      qw(active_discount_source active_price_source base_qty cusordnumber
256                                                         description discount lastcost longdescription
257                                                         marge_percent marge_price_factor marge_total
258                                                         ordnumber parts_id price_factor price_factor_id pricegroup_id
259                                                         project_id qty reqdate sellprice serialnumber ship subtotal transdate unit
260                                                      )),
261                                                  custom_variables => \@custom_variables,
262     );
263     $current_oe_item->{"converted_from_orderitems_id"} = $_->{id} if ref($item_parent) eq 'SL::DB::Order';
264     $current_oe_item;
265   } @{ $items };
266
267   @items = grep { $params{item_filter}->($_) } @items if $params{item_filter};
268   @items = grep { $_->qty * 1 } @items if $params{skip_items_zero_qty};
269   @items = grep { $_->qty >=0 } @items if $params{skip_items_negative_qty};
270
271   $order->items(\@items);
272
273   return $order;
274 }
275
276 sub number {
277   my $self = shift;
278
279   return if !$self->type;
280
281   my %number_method = (
282     sales_order       => 'ordnumber',
283     sales_quotation   => 'quonumber',
284     purchase_order    => 'ordnumber',
285     request_quotation => 'quonumber',
286   );
287
288   return $self->${ \ $number_method{$self->type} }(@_);
289 }
290
291 sub customervendor {
292   $_[0]->is_sales ? $_[0]->customer : $_[0]->vendor;
293 }
294
295 sub date {
296   goto &transdate;
297 }
298
299 sub digest {
300   my ($self) = @_;
301
302   sprintf "%s %s %s (%s)",
303     $self->number,
304     $self->customervendor->name,
305     $self->amount_as_number,
306     $self->date->to_kivitendo;
307 }
308
309 1;
310
311 __END__
312
313 =pod
314
315 =encoding utf8
316
317 =head1 NAME
318
319 SL::DB::Order - Order Datenbank Objekt.
320
321 =head1 FUNCTIONS
322
323 =head2 C<type>
324
325 Returns one of the following string types:
326
327 =over 4
328
329 =item sales_order
330
331 =item purchase_order
332
333 =item sales_quotation
334
335 =item request_quotation
336
337 =back
338
339 =head2 C<is_type TYPE>
340
341 Returns true if the order is of the given type.
342
343 =head2 C<convert_to_delivery_order %params>
344
345 Creates a new delivery order with C<$self> as the basis by calling
346 L<SL::DB::DeliveryOrder::new_from>. That delivery order is saved, and
347 C<$self> is linked to the new invoice via
348 L<SL::DB::RecordLink>. C<$self>'s C<delivered> attribute is set to
349 C<true>, and C<$self> is saved.
350
351 The arguments in C<%params> are passed to
352 L<SL::DB::DeliveryOrder::new_from>.
353
354 Returns C<undef> on failure. Otherwise the new delivery order will be
355 returned.
356
357 =head2 C<convert_to_invoice %params>
358
359 Creates a new invoice with C<$self> as the basis by calling
360 L<SL::DB::Invoice::new_from>. That invoice is posted, and C<$self> is
361 linked to the new invoice via L<SL::DB::RecordLink>. C<$self>'s
362 C<closed> attribute is set to C<true>, and C<$self> is saved.
363
364 The arguments in C<%params> are passed to L<SL::DB::Invoice::post>.
365
366 Returns the new invoice instance on success and C<undef> on
367 failure. The whole process is run inside a transaction. On failure
368 nothing is created or changed in the database.
369
370 At the moment only sales quotations and sales orders can be converted.
371
372 =head2 C<new_from $source, %params>
373
374 Creates a new C<SL::DB::Order> instance and copies as much
375 information from C<$source> as possible. At the moment only sales orders from
376 sales quotations and purchase orders from requests for quotations can be
377 created.
378
379 The C<transdate> field will be set to the current date.
380
381 The conversion copies the order items as well.
382
383 Returns the new order instance. The object returned is not
384 saved.
385
386 C<%params> can include the following options
387 (C<destination_type> is mandatory):
388
389 =over 4
390
391 =item C<destination_type>
392
393 (mandatory)
394 The type of the newly created object. Can be C<sales_order> or
395 C<purchase_order> for now.
396
397 =item C<items>
398
399 An optional array reference of RDBO instances for the items to use. If
400 missing then the method C<items_sorted> will be called on
401 C<$source>. This option can be used to override the sorting, to
402 exclude certain positions or to add additional ones.
403
404 =item C<skip_items_negative_qty>
405
406 If trueish then items with a negative quantity are skipped. Items with
407 a quantity of 0 are not affected by this option.
408
409 =item C<skip_items_zero_qty>
410
411 If trueish then items with a quantity of 0 are skipped.
412
413 =item C<item_filter>
414
415 An optional code reference that is called for each item with the item
416 as its sole parameter. Items for which the code reference returns a
417 falsish value will be skipped.
418
419 =item C<attributes>
420
421 An optional hash reference. If it exists then it is passed to C<new>
422 allowing the caller to set certain attributes for the new delivery
423 order.
424
425 =back
426
427 =head2 C<create_sales_process>
428
429 Creates and saves a new sales process. Can only be called for sales
430 orders.
431
432 The newly created process will be linked bidirectionally to both
433 C<$self> and to all sales quotations that are linked to C<$self>.
434
435 Returns the newly created process instance.
436
437 =head1 BUGS
438
439 Nothing here yet.
440
441 =head1 AUTHOR
442
443 Sven Schöling <s.schoeling@linet-services.de>
444
445 =cut