1 package SL::DB::DeliveryOrder;
7 use Rose::DB::Object::Helpers qw(as_tree strip);
9 use SL::DB::MetaSetup::DeliveryOrder;
10 use SL::DB::Manager::DeliveryOrder;
11 use SL::DB::Helper::AttrHTML;
12 use SL::DB::Helper::AttrSorted;
13 use SL::DB::Helper::FlattenToForm;
14 use SL::DB::Helper::LinkedRecords;
15 use SL::DB::Helper::TypeDataProxy;
16 use SL::DB::Helper::TransNumberGenerator;
17 use SL::DB::Helper::RecordLink qw(RECORD_ID RECORD_TYPE_REF);
19 use SL::DB::DeliveryOrder::TypeData qw(:types);
20 use SL::DB::Order::TypeData qw(:types);
21 use SL::DB::Reclamation::TypeData qw(:types);
23 use SL::Helper::Number qw(_format_total _round_total);
24 use SL::Helper::ShippedQty;
26 use List::Util qw(first);
27 use List::MoreUtils qw(any pairwise);
28 use Math::Round qw(nhimult);
30 __PACKAGE__->meta->add_relationship(orderitems => { type => 'one to many',
31 class => 'SL::DB::DeliveryOrderItem',
32 column_map => { id => 'delivery_order_id' },
33 manager_args => { with_objects => [ 'part' ] }
37 class => 'SL::DB::Shipto',
38 column_map => { id => 'trans_id' },
39 query_args => [ module => 'DO' ],
43 __PACKAGE__->meta->initialize;
45 __PACKAGE__->attr_html('notes');
46 __PACKAGE__->attr_sorted('items');
48 __PACKAGE__->before_save('_before_save_set_donumber');
49 __PACKAGE__->after_save('_after_save_link_records');
50 __PACKAGE__->after_save('_mark_orders_if_delivered');
54 sub _before_save_set_donumber {
57 $self->create_trans_number if !$self->donumber;
62 sub _after_save_link_records {
65 my @allowed_record_sources = qw(SL::DB::Reclamation SL::DB::Order);
66 my @allowed_item_sources = qw(SL::DB::ReclamationItem SL::DB::OrderItem);
68 SL::DB::Helper::RecordLink::link_records(
70 \@allowed_record_sources,
71 \@allowed_item_sources,
75 sub _mark_orders_if_delivered {
77 my $orders = $self->linked_records(from => 'Order');
78 SL::Helper::ShippedQty->new->calculate($orders)->write_to_objects;
79 foreach my $order (@$orders) {
80 next if $order->is_sales != $self->is_sales;
81 $order->update_attributes(delivered => $order->{delivered});
88 sub items { goto &orderitems; }
89 sub add_items { goto &add_orderitems; }
90 sub payment_terms { goto &payment; }
91 sub record_number { goto &donumber; }
98 require SL::DB::Order;
99 my $orders = SL::DB::Manager::Order->get_all(
101 ordnumber => $self->ordnumber,
102 @{ $params{query} || [] },
106 return first { $_->is_type(SALES_ORDER_TYPE()) } @{ $orders };
114 return shift->type eq shift;
117 sub displayable_type {
119 return $self->type_data->text('type');
122 sub displayable_name {
123 join ' ', grep $_, map $_[0]->$_, qw(displayable_type record_number);
126 sub displayable_state {
130 ($self->closed ? $::locale->text('closed') : $::locale->text('open')),
131 ($self->delivered ? $::locale->text('delivered') : $::locale->text('not delivered'));
142 sub preceding_purchase_order_confirmations {
147 @lrs = grep { $_->record_type eq PURCHASE_ORDER_CONFIRMATION_TYPE() } @{$self->linked_records(from => 'SL::DB::Order')};
149 if ('SL::DB::Order' eq $self->{RECORD_TYPE_REF()}) {
150 my $order = SL::DB::Order->load_cached($self->{RECORD_ID()});
151 push @lrs, $order if $order->record_type eq PURCHASE_ORDER_CONFIRMATION_TYPE();
158 sub _clone_orderitem_cvar {
161 my $cloned = $_->clone_and_reset;
162 $cloned->sub_module('delivery_order_items');
167 sub convert_to_reclamation {
168 my ($self, %params) = @_;
170 $params{destination_type} = $self->is_sales ? SALES_RECLAMATION_TYPE()
171 : PURCHASE_RECLAMATION_TYPE();
173 my $reclamation = SL::DB::Reclamation->new_from($self, %params);
179 my ($class, $source, %params) = @_;
181 my %allowed_sources = map { $_ => 1 } qw(
184 SL::DB::DeliveryOrder
186 unless( $allowed_sources{ref $source} ) {
187 croak("Unsupported source object type '" . ref($source) . "'");
192 employee => SL::DB::Manager::Employee->current,
195 record_type => $params{destination_type},
196 transdate => DateTime->today_local,
199 if ( ref($source) eq 'SL::DB::Order' ) {
200 map{ ( $record_args{$_} = $source->$_ ) } # {{{ for vim folds
220 transaction_description
221 vendor_confirmation_number
224 if ($source->record_type eq PURCHASE_ORDER_CONFIRMATION_TYPE()) {
225 $record_args{ordnumber} = join ' ', map { $_->ordnumber } @{$source->preceding_purchase_orders()};
227 $record_args{ordnumber} = $source->ordnumber;
230 } elsif ( ref($source) eq 'SL::DB::Reclamation' ) {
231 map{ ( $record_args{$_} = $source->$_ ) } # {{{ for vim folds
249 transaction_description
252 $record_args{cp_id} = $source->contact_id;
253 $record_args{cusordnumber} = $source->cv_record_number;
254 $record_args{is_sales} = $source->is_sales;
256 } elsif ( ref($source) eq 'SL::DB::DeliveryOrder' ) {
257 map{ ( $record_args{$_} = $source->$_ ) } # {{{ for vim folds
282 transaction_description
283 vendor_confirmation_number
289 # Custom shipto addresses (the ones specific to the sales/purchase
290 # record and not to the customer/vendor) are only linked from
291 # shipto → delivery_orders. Meaning delivery_orders.shipto_id
292 # will not be filled in that case.
293 if (!$source->shipto_id && $source->id) {
294 $record_args{custom_shipto} = $source->custom_shipto->clone($class) if $source->can('custom_shipto') && $source->custom_shipto;
296 $record_args{shipto_id} = $source->shipto_id;
299 # infer type from legacy fields if not given
300 $record_args{record_type} //= $source->customer_id ? SALES_DELIVERY_ORDER_TYPE()
301 : $source->vendor_id ? PURCHASE_DELIVERY_ORDER_TYPE()
302 : $source->is_sales ? SALES_DELIVERY_ORDER_TYPE()
303 : croak "need some way to set delivery order type from source";
305 my $delivery_order = $class->new(%record_args);
306 $delivery_order->assign_attributes(%{ $params{attributes} }) if $params{attributes};
308 my $items = delete($params{items}) || $source->items_sorted;
309 my @items = ( $delivery_order->is_type(SUPPLIER_DELIVERY_ORDER_TYPE()) && ref($source) ne 'SL::DB::Reclamation' ) ?
311 : map { SL::DB::DeliveryOrderItem->new_from($_, %params) } @{ $items };
313 @items = grep { $params{item_filter}->($_) } @items if $params{item_filter};
314 @items = grep { $_->qty * 1 } @items if $params{skip_items_zero_qty};
315 @items = grep { $_->qty >=0 } @items if $params{skip_items_negative_qty};
317 $delivery_order->items(\@items);
319 unless ($params{no_linked_records}) {
320 $delivery_order->{ RECORD_ID() } = $source->id;
321 $delivery_order->{ RECORD_TYPE_REF() } = ref $source;
324 return $delivery_order;
327 sub new_from_time_recordings {
328 my ($class, $sources, %params) = @_;
329 require SL::DB::Part;
330 require SL::DB::Unit;
332 croak("Unsupported object type in sources") if any { ref($_) ne 'SL::DB::TimeRecording' } @$sources;
333 croak("Cannot create delivery order from source records of different customers") if any { $_->customer_id != $sources->[0]->customer_id } @$sources;
335 # - one item per part (article)
336 # - qty is sum of duration
337 # - description goes to item longdescription
338 # - ordered and summed by date
339 # - each description goes to an ordered list
340 # - (as time recording descriptions are formatted text by now, use stripped text)
341 # - merge same descriptions
344 my $default_part_id = $params{default_part_id} ? $params{default_part_id}
345 : $params{default_partnumber} ? SL::DB::Manager::Part->find_by(partnumber => $params{default_partnumber})->id
347 my $override_part_id = $params{override_part_id} ? $params{override_part_id}
348 : $params{override_partnumber} ? SL::DB::Manager::Part->find_by(partnumber => $params{override_partnumber})->id
351 # check parts and collect entries
354 foreach my $source (@$sources) {
355 next if !$source->duration;
357 my $part_id = $override_part_id;
358 $part_id ||= $source->part_id;
359 $part_id ||= $default_part_id;
361 die 'article not found for entry "' . $source->displayable_times . '"' if !$part_id;
363 if (!$part_by_part_id{$part_id}) {
364 $part_by_part_id{$part_id} = SL::DB::Part->new(id => $part_id)->load;
365 die 'article unit must be time based for entry "' . $source->displayable_times . '"' if !$part_by_part_id{$part_id}->unit_obj->is_time_based;
368 my $date = $source->date->to_kivitendo;
369 $entries->{$part_id}->{$date}->{duration} += $params{rounding}
370 ? nhimult(0.25, ($source->duration_in_hours))
371 : _round_total($source->duration_in_hours);
372 # add content if not already in description
373 my $new_description = '' . $source->description_as_stripped_html;
374 $entries->{$part_id}->{$date}->{content} ||= '';
375 $entries->{$part_id}->{$date}->{content} .= '<li>' . $new_description . '</li>'
376 unless $entries->{$part_id}->{$date}->{content} =~ m/\Q$new_description/;
378 $entries->{$part_id}->{$date}->{date_obj} = $source->start_time || $source->date; # for sorting
383 my $h_unit = SL::DB::Manager::Unit->find_h_unit;
385 my @keys = sort { $part_by_part_id{$a}->partnumber cmp $part_by_part_id{$b}->partnumber } keys %$entries;
386 foreach my $key (@keys) {
388 my $longdescription = '';
390 my @dates = sort { $entries->{$key}->{$a}->{date_obj} <=> $entries->{$key}->{$b}->{date_obj} } keys %{$entries->{$key}};
391 foreach my $date (@dates) {
392 my $entry = $entries->{$key}->{$date};
394 $qty += $entry->{duration};
395 $longdescription .= $date . ' <strong>' . _format_total($entry->{duration}) . ' h</strong>';
396 $longdescription .= '<ul>';
397 $longdescription .= $entry->{content};
398 $longdescription .= '</ul>';
401 my $item = SL::DB::DeliveryOrderItem->new(
402 parts_id => $part_by_part_id{$key}->id,
403 description => $part_by_part_id{$key}->description,
405 base_qty => $h_unit->convert_to($qty, $part_by_part_id{$key}->unit_obj),
407 sellprice => $part_by_part_id{$key}->sellprice, # Todo: use price rules to get sellprice
408 longdescription => $longdescription,
416 if ($params{related_order}) {
417 # collect suitable items in related order
420 foreach my $item (@items) {
421 my $item_to_use = first {$item->parts_id == $_->parts_id} @{ $params{related_order}->items_sorted };
423 die "no suitable item found in related order" if !$item_to_use;
426 $new_attributes{$_} = $item->$_ for qw(qty base_qty unit_obj longdescription);
427 push @items_to_use, $item_to_use;
428 push @new_attributes, \%new_attributes;
431 $delivery_order = $class->new_from($params{related_order}, items => \@items_to_use, %params);
432 pairwise { $a->assign_attributes( %$b) } @{$delivery_order->items}, @new_attributes;
436 record_type => SALES_DELIVERY_ORDER_TYPE,
438 customer_id => $sources->[0]->customer_id,
439 taxzone_id => $sources->[0]->customer->taxzone_id,
440 currency_id => $sources->[0]->customer->currency_id,
441 employee_id => SL::DB::Manager::Employee->current->id,
442 salesman_id => SL::DB::Manager::Employee->current->id,
445 $delivery_order = $class->new(%args);
446 $delivery_order->assign_attributes(%{ $params{attributes} }) if $params{attributes};
449 return $delivery_order;
452 # legacy for compatibility
453 # use type_data cusomtervendor and transfer direction instead
455 if ($_[0]->record_type) {
456 return SL::DB::DeliveryOrder::TypeData::get3($_[0]->record_type, "properties", "is_customer");
458 return $_[0]{is_sales};
462 SL::DB::DeliveryOrder::TypeData::get3($_[0]->record_type, "properties", "is_customer") ? $_[0]->customer : $_[0]->vendor;
465 sub convert_to_invoice {
466 my ($self, %params) = @_;
468 croak("Conversion to invoices is only supported for sales records") unless $self->customer_id;
471 if (!$self->db->with_transaction(sub {
472 require SL::DB::Invoice;
473 $invoice = SL::DB::Invoice->new_from($self, %params)->post || die;
474 $self->update_attributes(closed => 1);
486 sprintf "%s %s (%s)",
488 $self->customervendor->name,
489 $self->date->to_kivitendo;
493 SL::DB::Helper::TypeDataProxy->new(ref $_[0], $_[0]->type);
505 SL::DB::DeliveryOrder - Rose model for delivery orders (table
514 An alias for C<transdate> for compatibility with other sales/purchase models.
516 =item C<displayable_name>
518 Returns a human-readable and translated description of the delivery order, consisting of
519 record type and number, e.g. "Verkaufslieferschein 123".
521 =item C<displayable_state>
523 Returns a human-readable description of the state regarding being
524 closed and delivered.
528 An alias for C<delivery_order_items> for compatibility with other
529 sales/purchase models.
531 =item C<new_from $source, %params>
533 Creates a new C<SL::DB::DeliveryOrder> instance and copies as much
534 information from C<$source> as possible. At the moment only instances
535 of C<SL::DB::Order> (sales quotations, sales orders, requests for
536 quotations and purchase orders) are supported as sources.
538 The conversion copies order items into delivery order items. Dates are copied
539 as appropriate, e.g. the C<transdate> field will be set to the current date.
541 Returns the new delivery order instance. The object returned is not
544 C<%params> can include the following options:
550 An optional array reference of RDBO instances for the items to use. If
551 missing then the method C<items_sorted> will be called on
552 C<$source>. This option can be used to override the sorting, to
553 exclude certain positions or to add additional ones.
555 =item C<skip_items_negative_qty>
557 If trueish then items with a negative quantity are skipped. Items with
558 a quantity of 0 are not affected by this option.
560 =item C<skip_items_zero_qty>
562 If trueish then items with a quantity of 0 are skipped.
566 An optional code reference that is called for each item with the item
567 as its sole parameter. Items for which the code reference returns a
568 falsish value will be skipped.
572 An optional hash reference. If it exists then it is passed to C<new>
573 allowing the caller to set certain attributes for the new delivery
578 =item C<new_from_time_recordings $sources, %params>
580 Creates a new C<SL::DB::DeliveryOrder> instance from the time recordings
581 given as C<$sources>. All time recording entries must belong to the same
582 customer. Time recordings are sorted by article and date. For each article
583 a new delivery order item is created. If no article is associated with an
584 entry, a default article will be used. The article given in the time
585 recording entry can be overriden.
586 Entries of the same date (for each article) are summed together and form a
587 list entry in the long description of the item.
589 The created delivery order object will be returnd but not saved.
591 C<$sources> must be an array reference of C<SL::DB::TimeRecording> instances.
593 C<%params> can include the following options:
599 An optional hash reference. If it exists then it is used to set
600 attributes of the newly created delivery order object.
602 =item C<default_part_id>
604 An optional part id which is used as default value if no part is set
605 in the time recording entry.
607 =item C<default_partnumber>
609 Like C<default_part_id> but given as partnumber, not as id.
611 =item C<override_part_id>
613 An optional part id which is used instead of a value set in the time
616 =item C<override_partnumber>
618 Like C<overrride_part_id> but given as partnumber, not as id.
620 =item C<related_order>
622 An optional C<SL::DB::Order> object. If it exists then it is used to
623 generate the delivery order from that via C<new_from>.
624 The generated items are created from a suitable item of the related
625 order. If no suitable item is found, an exception is thrown.
629 An optional boolean value. If truish, then the durations of the time entries
630 are rounded up to the full quarters of an hour.
636 TODO: Describe sales_order
640 Returns a string describing this record's type: either
641 C<sales_delivery_order> or C<purchase_delivery_order>.
643 =item C<convert_to_invoice %params>
645 Creates a new invoice with C<$self> as the basis by calling
646 L<SL::DB::Invoice::new_from>. That invoice is posted, and C<$self> is
647 linked to the new invoice via L<SL::DB::RecordLink>. C<$self>'s
648 C<closed> attribute is set to C<true>, and C<$self> is saved.
650 The arguments in C<%params> are passed to L<SL::DB::Invoice::new_from>.
652 Returns the new invoice instance on success and C<undef> on
653 failure. The whole process is run inside a transaction. On failure
654 nothing is created or changed in the database.
656 At the moment only sales delivery orders can be converted.
666 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>