8 use List::Util qw(max);
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;
20 use Rose::DB::Object::Helpers qw(as_tree);
22 __PACKAGE__->meta->add_relationship(
24 type => 'one to many',
25 class => 'SL::DB::OrderItem',
26 column_map => { id => 'trans_id' },
28 with_objects => [ 'part' ]
31 periodic_invoices_config => {
33 class => 'SL::DB::PeriodicInvoicesConfig',
34 column_map => { id => 'oe_id' },
38 class => 'SL::DB::Shipto',
39 column_map => { id => 'trans_id' },
40 query_args => [ module => 'OE' ],
44 __PACKAGE__->meta->initialize;
46 __PACKAGE__->attr_html('notes');
47 __PACKAGE__->attr_sorted('items');
49 __PACKAGE__->before_save('_before_save_set_ord_quo_number');
53 sub _before_save_set_ord_quo_number {
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;
60 my $field = $self->quotation ? 'quonumber' : 'ordnumber';
61 $self->create_trans_number if !$self->$field;
68 sub items { goto &orderitems; }
69 sub add_items { goto &add_orderitems; }
70 sub record_number { goto &number; }
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;
84 return shift->type eq shift;
87 sub displayable_type {
88 my $type = shift->type;
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';
98 sub displayable_name {
99 join ' ', grep $_, map $_[0]->$_, qw(displayable_type record_number);
103 croak 'not an accessor' if @_ > 1;
104 return !!shift->customer_id;
111 if ($self->quotation) {
114 require SL::DB::Invoice;
115 return SL::DB::Manager::Invoice->get_all(
117 ordnumber => $self->ordnumber,
118 @{ $params{query} || [] },
124 sub displayable_state {
127 return $self->closed ? $::locale->text('closed') : $::locale->text('open');
130 sub abschlag_invoices {
131 return shift()->invoices(query => [ abschlag => 1 ]);
135 return shift()->invoices(query => [ abschlag => 0 ]);
138 sub convert_to_invoice {
139 my ($self, %params) = @_;
141 croak("Conversion to invoices is only supported for sales records") unless $self->customer_id;
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);
157 sub convert_to_delivery_order {
158 my ($self, @args) = @_;
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,
174 'from_ids' => $item->{"converted_from_${_}_id"},
175 'to_table' => 'delivery_order_items',
176 'to_id' => $item->{id},
178 delete $item->{"converted_from_${_}_id"};
183 $self->update_attributes(delivered => 1);
189 return $delivery_order;
192 sub _clone_orderitem_cvar {
195 my $cloned = $_->clone_and_reset;
196 $cloned->sub_module('orderitems');
202 my ($class, $source, %params) = @_;
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};
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 || ('sales_quotation' eq $source->type && 'sales_quotation' eq $destination_type)
211 || ('sales_order' eq $source->type && 'sales_order' eq $destination_type)
212 || ('request_quotation' eq $source->type && 'request_quotation' eq $destination_type)
213 || ('purchase_order' eq $source->type && 'purchase_order' eq $destination_type);
214 croak("Cannot convert from '" . $source->type . "' to '" . $destination_type . "'") unless $src_dst_allowed;
216 my ($item_parent_id_column, $item_parent_column);
218 if (ref($source) eq 'SL::DB::Order') {
219 $item_parent_id_column = 'trans_id';
220 $item_parent_column = 'order';
223 my %args = ( map({ ( $_ => $source->$_ ) } qw(amount cp_id currency_id cusordnumber customer_id delivery_customer_id delivery_term_id delivery_vendor_id
224 department_id employee_id globalproject_id intnotes marge_percent marge_total language_id netamount notes
225 ordnumber payment_id quonumber reqdate salesman_id shippingpoint shipvia taxincluded taxzone_id
226 transaction_description vendor_id
228 quotation => !!($destination_type =~ m{quotation$}),
231 transdate => DateTime->today_local,
234 # Custom shipto addresses (the ones specific to the sales/purchase
235 # record and not to the customer/vendor) are only linked from
236 # shipto → order. Meaning order.shipto_id
237 # will not be filled in that case.
238 if (!$source->shipto_id && $source->id) {
239 $args{custom_shipto} = $source->custom_shipto->clone($class) if $source->can('custom_shipto') && $source->custom_shipto;
242 $args{shipto_id} = $source->shipto_id;
245 my $order = $class->new(%args);
246 $order->assign_attributes(%{ $params{attributes} }) if $params{attributes};
247 my $items = delete($params{items}) || $source->items_sorted;
251 my $source_item = $_;
252 my $source_item_id = $_->$item_parent_id_column;
253 my @custom_variables = map { _clone_orderitem_cvar($_) } @{ $source_item->custom_variables };
255 $item_parents{$source_item_id} ||= $source_item->$item_parent_column;
256 my $item_parent = $item_parents{$source_item_id};
258 my $current_oe_item = SL::DB::OrderItem->new(map({ ( $_ => $source_item->$_ ) }
259 qw(active_discount_source active_price_source base_qty cusordnumber
260 description discount lastcost longdescription
261 marge_percent marge_price_factor marge_total
262 ordnumber parts_id price_factor price_factor_id pricegroup_id
263 project_id qty reqdate sellprice serialnumber ship subtotal transdate unit
265 custom_variables => \@custom_variables,
267 $current_oe_item->{"converted_from_orderitems_id"} = $_->{id} if ref($item_parent) eq 'SL::DB::Order';
271 @items = grep { $params{item_filter}->($_) } @items if $params{item_filter};
272 @items = grep { $_->qty * 1 } @items if $params{skip_items_zero_qty};
273 @items = grep { $_->qty >=0 } @items if $params{skip_items_negative_qty};
275 $order->items(\@items);
283 return if !$self->type;
285 my %number_method = (
286 sales_order => 'ordnumber',
287 sales_quotation => 'quonumber',
288 purchase_order => 'ordnumber',
289 request_quotation => 'quonumber',
292 return $self->${ \ $number_method{$self->type} }(@_);
296 $_[0]->is_sales ? $_[0]->customer : $_[0]->vendor;
306 sprintf "%s %s %s (%s)",
308 $self->customervendor->name,
309 $self->amount_as_number,
310 $self->date->to_kivitendo;
323 SL::DB::Order - Order Datenbank Objekt.
329 Returns one of the following string types:
337 =item sales_quotation
339 =item request_quotation
343 =head2 C<is_type TYPE>
345 Returns true if the order is of the given type.
347 =head2 C<convert_to_delivery_order %params>
349 Creates a new delivery order with C<$self> as the basis by calling
350 L<SL::DB::DeliveryOrder::new_from>. That delivery order is saved, and
351 C<$self> is linked to the new invoice via
352 L<SL::DB::RecordLink>. C<$self>'s C<delivered> attribute is set to
353 C<true>, and C<$self> is saved.
355 The arguments in C<%params> are passed to
356 L<SL::DB::DeliveryOrder::new_from>.
358 Returns C<undef> on failure. Otherwise the new delivery order will be
361 =head2 C<convert_to_invoice %params>
363 Creates a new invoice with C<$self> as the basis by calling
364 L<SL::DB::Invoice::new_from>. That invoice is posted, and C<$self> is
365 linked to the new invoice via L<SL::DB::RecordLink>. C<$self>'s
366 C<closed> attribute is set to C<true>, and C<$self> is saved.
368 The arguments in C<%params> are passed to L<SL::DB::Invoice::post>.
370 Returns the new invoice instance on success and C<undef> on
371 failure. The whole process is run inside a transaction. On failure
372 nothing is created or changed in the database.
374 At the moment only sales quotations and sales orders can be converted.
376 =head2 C<new_from $source, %params>
378 Creates a new C<SL::DB::Order> instance and copies as much
379 information from C<$source> as possible. At the moment only records with the
380 same destination type as the source type and sales orders from
381 sales quotations and purchase orders from requests for quotations can be
384 The C<transdate> field will be set to the current date.
386 The conversion copies the order items as well.
388 Returns the new order instance. The object returned is not
391 C<%params> can include the following options
392 (C<destination_type> is mandatory):
396 =item C<destination_type>
399 The type of the newly created object. Can be C<sales_quotation>,
400 C<sales_order>, C<purchase_quotation> or C<purchase_order> for now.
404 An optional array reference of RDBO instances for the items to use. If
405 missing then the method C<items_sorted> will be called on
406 C<$source>. This option can be used to override the sorting, to
407 exclude certain positions or to add additional ones.
409 =item C<skip_items_negative_qty>
411 If trueish then items with a negative quantity are skipped. Items with
412 a quantity of 0 are not affected by this option.
414 =item C<skip_items_zero_qty>
416 If trueish then items with a quantity of 0 are skipped.
420 An optional code reference that is called for each item with the item
421 as its sole parameter. Items for which the code reference returns a
422 falsish value will be skipped.
426 An optional hash reference. If it exists then it is passed to C<new>
427 allowing the caller to set certain attributes for the new delivery
432 =head2 C<create_sales_process>
434 Creates and saves a new sales process. Can only be called for sales
437 The newly created process will be linked bidirectionally to both
438 C<$self> and to all sales quotations that are linked to C<$self>.
440 Returns the newly created process instance.
448 Sven Schöling <s.schoeling@linet-services.de>