8 use List::Util qw(max);
 
   9 use List::MoreUtils qw(any);
 
  11 use SL::DB::MetaSetup::Order;
 
  12 use SL::DB::Manager::Order;
 
  13 use SL::DB::Helper::AttrHTML;
 
  14 use SL::DB::Helper::AttrSorted;
 
  15 use SL::DB::Helper::FlattenToForm;
 
  16 use SL::DB::Helper::LinkedRecords;
 
  17 use SL::DB::Helper::PriceTaxCalculator;
 
  18 use SL::DB::Helper::PriceUpdater;
 
  19 use SL::DB::Helper::TransNumberGenerator;
 
  21 use Rose::DB::Object::Helpers qw(as_tree);
 
  23 __PACKAGE__->meta->add_relationship(
 
  25     type         => 'one to many',
 
  26     class        => 'SL::DB::OrderItem',
 
  27     column_map   => { id => 'trans_id' },
 
  29       with_objects => [ 'part' ]
 
  32   periodic_invoices_config => {
 
  34     class                  => 'SL::DB::PeriodicInvoicesConfig',
 
  35     column_map             => { id => 'oe_id' },
 
  39     class                  => 'SL::DB::Shipto',
 
  40     column_map             => { id => 'trans_id' },
 
  41     query_args             => [ module => 'OE' ],
 
  45 __PACKAGE__->meta->initialize;
 
  47 __PACKAGE__->attr_html('notes');
 
  48 __PACKAGE__->attr_sorted('items');
 
  50 __PACKAGE__->before_save('_before_save_set_ord_quo_number');
 
  54 sub _before_save_set_ord_quo_number {
 
  57   # ordnumber is 'NOT NULL'. Therefore make sure it's always set to at
 
  58   # least an empty string, even if we're saving a quotation.
 
  59   $self->ordnumber('') if !$self->ordnumber;
 
  61   my $field = $self->quotation ? 'quonumber' : 'ordnumber';
 
  62   $self->create_trans_number if !$self->$field;
 
  69 sub items { goto &orderitems; }
 
  70 sub add_items { goto &add_orderitems; }
 
  71 sub record_number { goto &number; }
 
  76   return 'sales_order'       if $self->customer_id && ! $self->quotation;
 
  77   return 'purchase_order'    if $self->vendor_id   && ! $self->quotation;
 
  78   return 'sales_quotation'   if $self->customer_id &&   $self->quotation;
 
  79   return 'request_quotation' if $self->vendor_id   &&   $self->quotation;
 
  85   return shift->type eq shift;
 
  88 sub displayable_type {
 
  89   my $type = shift->type;
 
  91   return $::locale->text('Sales quotation')   if $type eq 'sales_quotation';
 
  92   return $::locale->text('Request quotation') if $type eq 'request_quotation';
 
  93   return $::locale->text('Sales Order')       if $type eq 'sales_order';
 
  94   return $::locale->text('Purchase Order')    if $type eq 'purchase_order';
 
  99 sub displayable_name {
 
 100   join ' ', grep $_, map $_[0]->$_, qw(displayable_type record_number);
 
 104   croak 'not an accessor' if @_ > 1;
 
 105   return !!shift->customer_id;
 
 112   if ($self->quotation) {
 
 115     require SL::DB::Invoice;
 
 116     return SL::DB::Manager::Invoice->get_all(
 
 118         ordnumber => $self->ordnumber,
 
 119         @{ $params{query} || [] },
 
 125 sub displayable_state {
 
 128   return $self->closed ? $::locale->text('closed') : $::locale->text('open');
 
 131 sub abschlag_invoices {
 
 132   return shift()->invoices(query => [ abschlag => 1 ]);
 
 136   return shift()->invoices(query => [ abschlag => 0 ]);
 
 139 sub convert_to_invoice {
 
 140   my ($self, %params) = @_;
 
 142   croak("Conversion to invoices is only supported for sales records") unless $self->customer_id;
 
 145   if (!$self->db->with_transaction(sub {
 
 146     require SL::DB::Invoice;
 
 147     $invoice = SL::DB::Invoice->new_from($self)->post(%params) || die;
 
 148     $self->link_to_record($invoice);
 
 149     $self->update_attributes(closed => 1);
 
 158 sub convert_to_delivery_order {
 
 159   my ($self, @args) = @_;
 
 162   if (!$self->db->with_transaction(sub {
 
 163     require SL::DB::DeliveryOrder;
 
 164     $delivery_order = SL::DB::DeliveryOrder->new_from($self, @args);
 
 165     $delivery_order->save;
 
 166     $self->link_to_record($delivery_order);
 
 167     # TODO extend link_to_record for items, otherwise long-term no d.r.y.
 
 168     foreach my $item (@{ $delivery_order->items }) {
 
 169       foreach (qw(orderitems)) {    # expand if needed (delivery_order_items)
 
 170         if ($item->{"converted_from_${_}_id"}) {
 
 171           die unless $item->{id};
 
 172           RecordLinks->create_links('dbh'        => $self->db->dbh,
 
 175                                     'from_ids'   => $item->{"converted_from_${_}_id"},
 
 176                                     'to_table'   => 'delivery_order_items',
 
 177                                     'to_id'      => $item->{id},
 
 179           delete $item->{"converted_from_${_}_id"};
 
 184     $self->update_attributes(delivered => 1);
 
 190   return $delivery_order;
 
 193 sub _clone_orderitem_cvar {
 
 196   my $cloned = $_->clone_and_reset;
 
 197   $cloned->sub_module('orderitems');
 
 203   my ($class, $source, %params) = @_;
 
 205   croak("Unsupported source object type '" . ref($source) . "'") unless ref($source) eq 'SL::DB::Order';
 
 206   croak("A destination type must be given as parameter")         unless $params{destination_type};
 
 208   my $destination_type  = delete $params{destination_type};
 
 211     { from => 'sales_quotation',   to => 'sales_order',       abbr => 'sqso' },
 
 212     { from => 'request_quotation', to => 'purchase_order',    abbr => 'rqpo' },
 
 213     { from => 'sales_quotation',   to => 'sales_quotation',   abbr => 'sqsq' },
 
 214     { from => 'sales_order',       to => 'sales_order',       abbr => 'soso' },
 
 215     { from => 'request_quotation', to => 'request_quotation', abbr => 'rqrq' },
 
 216     { from => 'purchase_order',    to => 'purchase_order',    abbr => 'popo' },
 
 217     { from => 'sales_order',       to => 'purchase_order',    abbr => 'sopo' },
 
 218     { from => 'purchase_order',    to => 'sales_order',       abbr => 'poso' },
 
 220   my $from_to = (grep { $_->{from} eq $source->type && $_->{to} eq $destination_type} @from_tos)[0];
 
 221   croak("Cannot convert from '" . $source->type . "' to '" . $destination_type . "'") if !$from_to;
 
 223   my $is_abbr_any = sub {
 
 224     # foreach my $abbr (@_) {
 
 225     #   croak "no such abbreviation: '$abbr'" if !grep { $_->{abbr} eq $abbr } @from_tos;
 
 227     any { $from_to->{abbr} eq $_ } @_;
 
 230   my ($item_parent_id_column, $item_parent_column);
 
 232   if (ref($source) eq 'SL::DB::Order') {
 
 233     $item_parent_id_column = 'trans_id';
 
 234     $item_parent_column    = 'order';
 
 237   my %args = ( map({ ( $_ => $source->$_ ) } qw(amount cp_id currency_id cusordnumber customer_id delivery_customer_id delivery_term_id delivery_vendor_id
 
 238                                                 department_id employee_id globalproject_id intnotes marge_percent marge_total language_id netamount notes
 
 239                                                 ordnumber payment_id quonumber reqdate salesman_id shippingpoint shipvia taxincluded taxzone_id
 
 240                                                 transaction_description vendor_id
 
 242                quotation => !!($destination_type =~ m{quotation$}),
 
 245                transdate => DateTime->today_local,
 
 248   if ( $is_abbr_any->(qw(sopo poso)) ) {
 
 249     $args{ordnumber} = undef;
 
 250     $args{reqdate}   = DateTime->today_local->next_workday();
 
 251     $args{employee}  = SL::DB::Manager::Employee->current;
 
 253   if ( $is_abbr_any->(qw(sopo)) ) {
 
 254     $args{customer_id}      = undef;
 
 255     $args{salesman_id}      = undef;
 
 256     $args{payment_id}       = undef;
 
 257     $args{delivery_term_id} = undef;
 
 259   if ( $is_abbr_any->(qw(poso)) ) {
 
 260     $args{vendor_id} = undef;
 
 263   # Custom shipto addresses (the ones specific to the sales/purchase
 
 264   # record and not to the customer/vendor) are only linked from
 
 265   # shipto → order. Meaning order.shipto_id
 
 266   # will not be filled in that case.
 
 267   if (!$source->shipto_id && $source->id) {
 
 268     $args{custom_shipto} = $source->custom_shipto->clone($class) if $source->can('custom_shipto') && $source->custom_shipto;
 
 271     $args{shipto_id} = $source->shipto_id;
 
 274   my $order = $class->new(%args);
 
 275   $order->assign_attributes(%{ $params{attributes} }) if $params{attributes};
 
 276   my $items = delete($params{items}) || $source->items_sorted;
 
 280     my $source_item      = $_;
 
 281     my $source_item_id   = $_->$item_parent_id_column;
 
 282     my @custom_variables = map { _clone_orderitem_cvar($_) } @{ $source_item->custom_variables };
 
 284     $item_parents{$source_item_id} ||= $source_item->$item_parent_column;
 
 285     my $item_parent                  = $item_parents{$source_item_id};
 
 287     my $current_oe_item = SL::DB::OrderItem->new(map({ ( $_ => $source_item->$_ ) }
 
 288                                                      qw(active_discount_source active_price_source base_qty cusordnumber
 
 289                                                         description discount lastcost longdescription
 
 290                                                         marge_percent marge_price_factor marge_total
 
 291                                                         ordnumber parts_id price_factor price_factor_id pricegroup_id
 
 292                                                         project_id qty reqdate sellprice serialnumber ship subtotal transdate unit
 
 294                                                  custom_variables => \@custom_variables,
 
 296     if ( $is_abbr_any->(qw(sopo)) ) {
 
 297       $current_oe_item->sellprice($source_item->lastcost);
 
 298       $current_oe_item->discount(0);
 
 300     if ( $is_abbr_any->(qw(poso)) ) {
 
 301       $current_oe_item->lastcost($source_item->sellprice);
 
 303     $current_oe_item->{"converted_from_orderitems_id"} = $_->{id} if ref($item_parent) eq 'SL::DB::Order';
 
 307   @items = grep { $params{item_filter}->($_) } @items if $params{item_filter};
 
 308   @items = grep { $_->qty * 1 } @items if $params{skip_items_zero_qty};
 
 309   @items = grep { $_->qty >=0 } @items if $params{skip_items_negative_qty};
 
 311   $order->items(\@items);
 
 319   return if !$self->type;
 
 321   my %number_method = (
 
 322     sales_order       => 'ordnumber',
 
 323     sales_quotation   => 'quonumber',
 
 324     purchase_order    => 'ordnumber',
 
 325     request_quotation => 'quonumber',
 
 328   return $self->${ \ $number_method{$self->type} }(@_);
 
 332   $_[0]->is_sales ? $_[0]->customer : $_[0]->vendor;
 
 342   sprintf "%s %s %s (%s)",
 
 344     $self->customervendor->name,
 
 345     $self->amount_as_number,
 
 346     $self->date->to_kivitendo;
 
 359 SL::DB::Order - Order Datenbank Objekt.
 
 365 Returns one of the following string types:
 
 373 =item sales_quotation
 
 375 =item request_quotation
 
 379 =head2 C<is_type TYPE>
 
 381 Returns true if the order is of the given type.
 
 383 =head2 C<convert_to_delivery_order %params>
 
 385 Creates a new delivery order with C<$self> as the basis by calling
 
 386 L<SL::DB::DeliveryOrder::new_from>. That delivery order is saved, and
 
 387 C<$self> is linked to the new invoice via
 
 388 L<SL::DB::RecordLink>. C<$self>'s C<delivered> attribute is set to
 
 389 C<true>, and C<$self> is saved.
 
 391 The arguments in C<%params> are passed to
 
 392 L<SL::DB::DeliveryOrder::new_from>.
 
 394 Returns C<undef> on failure. Otherwise the new delivery order will be
 
 397 =head2 C<convert_to_invoice %params>
 
 399 Creates a new invoice with C<$self> as the basis by calling
 
 400 L<SL::DB::Invoice::new_from>. That invoice is posted, and C<$self> is
 
 401 linked to the new invoice via L<SL::DB::RecordLink>. C<$self>'s
 
 402 C<closed> attribute is set to C<true>, and C<$self> is saved.
 
 404 The arguments in C<%params> are passed to L<SL::DB::Invoice::post>.
 
 406 Returns the new invoice instance on success and C<undef> on
 
 407 failure. The whole process is run inside a transaction. On failure
 
 408 nothing is created or changed in the database.
 
 410 At the moment only sales quotations and sales orders can be converted.
 
 412 =head2 C<new_from $source, %params>
 
 414 Creates a new C<SL::DB::Order> instance and copies as much
 
 415 information from C<$source> as possible. At the moment only records with the
 
 416 same destination type as the source type and sales orders from
 
 417 sales quotations and purchase orders from requests for quotations can be
 
 420 The C<transdate> field will be set to the current date.
 
 422 The conversion copies the order items as well.
 
 424 Returns the new order instance. The object returned is not
 
 427 C<%params> can include the following options
 
 428 (C<destination_type> is mandatory):
 
 432 =item C<destination_type>
 
 435 The type of the newly created object. Can be C<sales_quotation>,
 
 436 C<sales_order>, C<purchase_quotation> or C<purchase_order> for now.
 
 440 An optional array reference of RDBO instances for the items to use. If
 
 441 missing then the method C<items_sorted> will be called on
 
 442 C<$source>. This option can be used to override the sorting, to
 
 443 exclude certain positions or to add additional ones.
 
 445 =item C<skip_items_negative_qty>
 
 447 If trueish then items with a negative quantity are skipped. Items with
 
 448 a quantity of 0 are not affected by this option.
 
 450 =item C<skip_items_zero_qty>
 
 452 If trueish then items with a quantity of 0 are skipped.
 
 456 An optional code reference that is called for each item with the item
 
 457 as its sole parameter. Items for which the code reference returns a
 
 458 falsish value will be skipped.
 
 462 An optional hash reference. If it exists then it is passed to C<new>
 
 463 allowing the caller to set certain attributes for the new delivery
 
 468 =head2 C<create_sales_process>
 
 470 Creates and saves a new sales process. Can only be called for sales
 
 473 The newly created process will be linked bidirectionally to both
 
 474 C<$self> and to all sales quotations that are linked to C<$self>.
 
 476 Returns the newly created process instance.
 
 484 Sven Schöling <s.schoeling@linet-services.de>