"Order.pm.html#L1772" data-txt="1772">
title_key => 'full_name_dep',
default => $self->order->cp_id,
with_empty => 1,
style => 'width: 300px',
);
}

# build the selection box for the additional billing address
#
# Needed, if customer/vendor changed.
sub build_billing_address_select {
my ($self) = @_;

return '' if $self->cv ne 'customer';

select_tag('order.billing_address_id',
[ {displayable_id => '', id => ''}, $self->order->{$self->cv}->additional_billing_addresses ],
value_key => 'id',
title_key => 'displayable_id',
default => $self->order->billing_address_id,
with_empty => 0,
style => 'width: 300px',
);
}

# build the selection box for shiptos
#
# Needed, if customer/vendor changed.
sub build_shipto_select {
my ($self) = @_;

select_tag('order.shipto_id',
[ {displayable_id => t8("No/individual shipping address"), shipto_id => ''}, $self->order->{$self->cv}->shipto ],
value_key => 'shipto_id',
title_key => 'displayable_id',
default => $self->order->shipto_id,
with_empty => 0,
style => 'width: 300px',
);
}

# build the inputs for the cusom shipto dialog
#
# Needed, if customer/vendor changed.
sub build_shipto_inputs {
my ($self) = @_;

my $content = $self->p->render('common/_ship_to_dialog',
vc_obj => $self->order->customervendor,
cs_obj => $self->order->custom_shipto,
cvars => $self->order->custom_shipto->cvars_by_config,
id_selector => '#order_shipto_id');

div_tag($content, id => 'shipto_inputs');
}

# render the info line for business
#
# Needed, if customer/vendor changed.
sub build_business_info_row
{
$_[0]->p->render('order/tabs/_business_info_row', SELF => $_[0]);
}

# build the rows for displaying taxes
#
# Called if amounts where recalculated and redisplayed.
sub build_tax_rows {
my ($self) = @_;

my $rows_as_html;
foreach my $tax (sort { $a->{tax}->rate cmp $b->{tax}->rate } @{ $self->{taxes} }) {
$rows_as_html .= $self->p->render(
'order/tabs/_tax_row',
SELF => $self,
TAX => $tax,
TAXINCLUDED => $self->order->taxincluded,
QUOTATION => $self->order->quotation
);
}
return $rows_as_html;
}


sub render_price_dialog {
my ($self, $record_item) = @_;

my $price_source = SL::PriceSource->new(record_item => $record_item, record => $self->order);

$self->js
->run(
'kivi.io.price_chooser_dialog',
t8('Available Prices'),
$self->render('order/tabs/_price_sources_dialog', { output => 0 }, price_source => $price_source)
)
->reinit_widgets;

# if (@errors) {
# $self->js->text('#dialog_flash_error_content', join ' ', @errors);
# $self->js->show('#dialog_flash_error');
# }

$self->js->render;
}

sub load_order {
my ($self) = @_;

return if !$::form->{id};

$self->order(SL::DB::Order->new(id => $::form->{id})->load);

# Add an empty custom shipto to the order, so that the dialog can render the cvar inputs.
# You need a custom shipto object to call cvars_by_config to get the cvars.
$self->order->custom_shipto(SL::DB::Shipto->new(module => 'OE', custom_variables => [])) if !$self->order->custom_shipto;

return $self->order;
}

# load or create a new order object
#
# And assign changes from the form to this object.
# If the order is loaded from db, check if items are deleted in the form,
# remove them form the object and collect them for removing from db on saving.
# Then create/update items from form (via make_item) and add them.
sub make_order {
my ($self) = @_;

# add_items adds items to an order with no items for saving, but they cannot
# be retrieved via items until the order is saved. Adding empty items to new
# order here solves this problem.
my $order;
$order = SL::DB::Order->new(id => $::form->{id})->load(with => [ 'orderitems', 'orderitems.part' ]) if $::form->{id};
$order ||= SL::DB::Order->new(orderitems => [],
quotation => (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type())),
currency_id => $::instance_conf->get_currency_id(),);

my $cv_id_method = $self->cv . '_id';
if (!$::form->{id} && $::form->{$cv_id_method}) {
$order->$cv_id_method($::form->{$cv_id_method});
setup_order_from_cv($order);
}

my $form_orderitems = delete $::form->{order}->{orderitems};
my $form_periodic_invoices_config = delete $::form->{order}->{periodic_invoices_config};

$order->assign_attributes(%{$::form->{order}});

$self->setup_custom_shipto_from_form($order, $::form);

if (my $periodic_invoices_config_attrs = $form_periodic_invoices_config ? SL::YAML::Load($form_periodic_invoices_config) : undef) {
my $periodic_invoices_config = $order->periodic_invoices_config || $order->periodic_invoices_config(SL::DB::PeriodicInvoicesConfig->new);
$periodic_invoices_config->assign_attributes(%$periodic_invoices_config_attrs);
}

# remove deleted items
$self->item_ids_to_delete([]);
foreach my $idx (reverse 0..$#{$order->orderitems}) {
my $item = $order->orderitems->[$idx];
if (none { $item->id == $_->{id} } @{$form_orderitems}) {
splice @{$order->orderitems}, $idx, 1;
push @{$self->item_ids_to_delete}, $item->id;
}
}

my @items;
my $pos = 1;
foreach my $form_attr (@{$form_orderitems}) {
my $item = make_item($order, $form_attr);
$item->position($pos);
push @items, $item;
$pos++;
}
$order->add_items(grep {!$_->id} @items);

return $order;
}

# create or update items from form
#
# Make item objects from form values. For items already existing read from db.
# Create a new item else. And assign attributes.
sub make_item {
my ($record, $attr) = @_;

my $item;
$item = first { $_->id == $attr->{id} } @{$record->items} if $attr->{id};

my $is_new = !$item;

# add_custom_variables adds cvars to an orderitem with no cvars for saving, but
# they cannot be retrieved via custom_variables until the order/orderitem is
# saved. Adding empty custom_variables to new orderitem here solves this problem.
$item ||= SL::DB::OrderItem->new(custom_variables => []);

$item->assign_attributes(%$attr);

if ($is_new) {
my $texts = get_part_texts($item->part, $record->language_id);
$item->longdescription($texts->{longdescription}) if !defined $attr->{longdescription};
$item->project_id($record->globalproject_id) if !defined $attr->{project_id};
$item->lastcost($record->is_sales ? $item->part->lastcost : 0) if !defined $attr->{lastcost_as_number};
}

return $item;
}

# create a new item
#
# This is used to add one item
sub new_item {
my ($record, $attr) = @_;

my $item = SL::DB::OrderItem->new;

# Remove attributes where the user left or set the inputs empty.
# So these attributes will be undefined and we can distinguish them
# from zero later on.
for (qw(qty_as_number sellprice_as_number discount_as_percent)) {
delete $attr->{$_} if $attr->{$_} eq '';
}

$item->assign_attributes(%$attr);
$item->qty(1.0) if !$item->qty;
$item->unit($item->part->unit) if !$item->unit;

my ($price_src, $discount_src) = get_best_price_and_discount_source($record, $item, 0);

my %new_attr;
$new_attr{description} = $item->part->description if ! $item->description;
$new_attr{qty} = 1.0 if ! $item->qty;
$new_attr{price_factor_id} = $item->part->price_factor_id if ! $item->price_factor_id;
$new_attr{sellprice} = $price_src->price;
$new_attr{discount} = $discount_src->discount;
$new_attr{active_price_source} = $price_src;
$new_attr{active_discount_source} = $discount_src;
$new_attr{longdescription} = $item->part->notes if ! defined $attr->{longdescription};
$new_attr{project_id} = $record->globalproject_id;
$new_attr{lastcost} = $record->is_sales ? $item->part->lastcost : 0;

# add_custom_variables adds cvars to an orderitem with no cvars for saving, but
# they cannot be retrieved via custom_variables until the order/orderitem is
# saved. Adding empty custom_variables to new orderitem here solves this problem.
$new_attr{custom_variables} = [];

my $texts = get_part_texts($item->part, $record->language_id, description => $new_attr{description}, longdescription => $new_attr{longdescription});

$item->assign_attributes(%new_attr, %{ $texts });

return $item;
}

sub setup_order_from_cv {
my ($order) = @_;

$order->$_($order->customervendor->$_) for (qw(taxzone_id payment_id delivery_term_id currency_id language_id));

$order->intnotes($order->customervendor->notes);

return if !$order->is_sales;

$order->salesman_id($order->customer->salesman_id || SL::DB::Manager::Employee->current->id);
$order->taxincluded(defined($order->customer->taxincluded_checked)
? $order->customer->taxincluded_checked
: $::myconfig{taxincluded_checked});

my $address = $order->customer->default_billing_address;;
$order->billing_address_id($address ? $address->id : undef);
}

# setup custom shipto from form
#
# The dialog returns form variables starting with 'shipto' and cvars starting
# with 'shiptocvar_'.
# Mark it to be deleted if a shipto from master data is selected
# (i.e. order has a shipto).
# Else, update or create a new custom shipto. If the fields are empty, it
# will not be saved on save.
sub setup_custom_shipto_from_form {
my ($self, $order, $form) = @_;

if ($order->shipto) {
$self->is_custom_shipto_to_delete(1);
} else {
my $custom_shipto = $order->custom_shipto || $order->custom_shipto(SL::DB::Shipto->new(module => 'OE', custom_variables => []));

my $shipto_cvars = {map { my ($key) = m{^shiptocvar_(.+)}; $key => delete $form->{$_}} grep { m{^shiptocvar_} } keys %$form};
my $shipto_attrs = {map { $_ => delete $form->{$_}} grep { m{^shipto} } keys %$form};

$custom_shipto->assign_attributes(%$shipto_attrs);
$custom_shipto->cvar_by_name($_)->value($shipto_cvars->{$_}) for keys %$shipto_cvars;
}
}

# recalculate prices and taxes
#
# Using the PriceTaxCalculator. Store linetotals in the item objects.
sub recalc {
my ($self) = @_;

my %pat = $self->order->calculate_prices_and_taxes();

$self->{taxes} = [];
foreach my $tax_id (keys %{ $pat{taxes_by_tax_id} }) {
my $netamount = sum0 map { $pat{amounts}->{$_}->{amount} } grep { $pat{amounts}->{$_}->{tax_id} == $tax_id } keys %{ $pat{amounts} };

push(@{ $self->{taxes} }, { amount => $pat{taxes_by_tax_id}->{$tax_id},
netamount => $netamount,
tax => SL::DB::Tax->new(id => $tax_id)->load });
}
pairwise { $a->{linetotal} = $b->{linetotal} } @{$self->order->items_sorted}, @{$pat{items}};
}

# get data for saving, printing, ..., that is not changed in the form
#
# Only cvars for now.
sub get_unalterable_data {
my ($self) = @_;

foreach my $item (@{ $self->order->items }) {
# autovivify all cvars that are not in the form (cvars_by_config can do it).
# workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
foreach my $var (@{ $item->cvars_by_config }) {
$var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
}
$item->parse_custom_variable_values;
}
}

# delete the order
#
# And remove related files in the spool directory
sub delete {
my ($self) = @_;

my $errors = [];
my $db = $self->order->db;

$db->with_transaction(
sub {
my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $self->order->id ]) };
$self->order->delete;
my $spool = $::lx_office_conf{paths}->{spool};
unlink map { "$spool/$_" } @spoolfiles if $spool;

$self->save_history('DELETED');

1;
}) || push(@{$errors}, $db->error);

return $errors;
}

# save the order
#
# And delete items that are deleted in the form.
sub save {
my ($self) = @_;

$self->recalc();
$self->get_unalterable_data();

my $errors = [];
my $db = $self->order->db;

# check for new or updated phone note
if ($::form->{phone_note}->{subject} || $::form->{phone_note}->{body}) {
if (!$::form->{phone_note}->{subject} || !$::form->{phone_note}->{body}) {
return [t8('Phone note needs a subject and a body.')];
}

my $phone_note;
if ($::form->{phone_note}->{id}) {
$phone_note = first { $_->id == $::form->{phone_note}->{id} } @{$self->order->phone_notes};
return [t8('Phone note not found for this order.')] if !$phone_note;
}

$phone_note = SL::DB::Note->new() if !$phone_note;
my $is_new = !$phone_note->id;

$phone_note->assign_attributes(%{ $::form->{phone_note} },
trans_id => $self->order->id,
trans_module => 'oe',
employee => SL::DB::Manager::Employee->current);

$self->order->add_phone_notes($phone_note) if $is_new;
}

$db->with_transaction(sub {
my $validity_token;
if (!$self->order->id) {
$validity_token = SL::DB::Manager::ValidityToken->fetch_valid_token(
scope => SL::DB::ValidityToken::SCOPE_ORDER_SAVE(),
token => $::form->{form_validity_token},
);

die $::locale->text('The form is not valid anymore.') if !$validity_token;
}

# delete custom shipto if it is to be deleted or if it is empty
if ($self->order->custom_shipto && ($self->is_custom_shipto_to_delete || $self->order->custom_shipto->is_empty)) {
$self->order->custom_shipto->delete if $self->order->custom_shipto->shipto_id;
$self->order->custom_shipto(undef);
}

SL::DB::OrderItem->new(id => $_)->delete for @{$self->item_ids_to_delete || []};
$self->order->save(cascade => 1);
# create first version if none exists
SL::DB::OrderVersion->new(oe_id => $self->order->id, version => 1)->save unless scalar @{ $self->order->order_version };

# link records
if ($::form->{converted_from_oe_id}) {
my @converted_from_oe_ids = split ' ', $::form->{converted_from_oe_id};

foreach my $converted_from_oe_id (@converted_from_oe_ids) {
my $src = SL::DB::Order->new(id => $converted_from_oe_id)->load;
$src->update_attributes(closed => 1) if $src->type =~ /_quotation$/;
$src->link_to_record($self->order);
}
if (scalar @{ $::form->{converted_from_orderitems_ids} || [] }) {
my $idx = 0;
foreach (@{ $self->order->items_sorted }) {
my $from_id = $::form->{converted_from_orderitems_ids}->[$idx];
next if !$from_id;
SL::DB::RecordLink->new(from_table => 'orderitems',
from_id => $from_id,
to_table => 'orderitems',
to_id => $_->id
)->save;
$idx++;
}
}

$self->link_requirement_specs_linking_to_created_from_objects(@converted_from_oe_ids);
}
if ($::form->{converted_from_reclamation_id}) {
my @converted_from_reclamation_ids = split ' ', $::form->{converted_from_reclamation_id};

foreach my $converted_from_reclamation_id (@converted_from_reclamation_ids) {
my $src = SL::DB::Reclamation->new(id => $converted_from_reclamation_id)->load;
$src->link_to_record($self->order);
}
if (scalar @{ $::form->{converted_from_reclamation_items_ids} || [] }) {
my $idx = 0;
foreach (@{ $self->order->items_sorted }) {
my $from_id = $::form->{converted_from_reclamation_items_ids}->[$idx];
next if !$from_id;
SL::DB::RecordLink->new(from_table => 'reclamation_items',
from_id => $from_id,
to_table => 'orderitems',
to_id => $_->id
)->save;
$idx++;
}
}
}

$self->set_project_in_linked_requirement_specs if $self->order->globalproject_id;

$self->save_history('SAVED');

$validity_token->delete if $validity_token;
delete $::form->{form_validity_token};

1;
}) || push(@{$errors}, $db->error);

return $errors;
}

sub pre_render {
my ($self) = @_;

$self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
$self->{all_currencies} = SL::DB::Manager::Currency->get_all_sorted();
$self->{all_departments} = SL::DB::Manager::Department->get_all_sorted();
$self->{all_languages} = SL::DB::Manager::Language->get_all_sorted( query => [ or => [ obsolete => 0, id => $self->order->language_id ] ] );
$self->{all_employees} = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->employee_id,
deleted => 0 ] ],
sort_by => 'name');
$self->{all_salesmen} = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->salesman_id,
deleted => 0 ] ],
sort_by => 'name');
$self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id => $self->order->payment_id,
obsolete => 0 ] ]);
$self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_valid($self->order->delivery_term_id);
$self->{all_statuses} = SL::DB::Manager::OrderStatus->get_all_sorted(where => [ or => [ id => $self->order->order_status_id,
obsolete => 0, ] ] );
$self->{current_employee_id} = SL::DB::Manager::Employee->current->id;
$self->{periodic_invoices_status} = $self->get_periodic_invoices_status($self->order->periodic_invoices_config);
$self->{order_probabilities} = [ map { { title => ($_ * 10) . '%', id => $_ * 10 } } (0..10) ];
$self->{positions_scrollbar_height} = SL::Helper::UserPreferences::PositionsScrollbar->new()->get_height();

my $print_form = Form->new('');
$print_form->{type} = $self->type;
$print_form->{printers} = SL::DB::Manager::Printer->get_all_sorted;
$self->{print_options} = SL::Helper::PrintOptions->get_print_options(
form => $print_form,
options => {dialog_name_prefix => 'print_options.',
show_headers => 1,
no_queue => 1,
no_postscript => 1,
no_opendocument => 0,
no_html => 0},
);

foreach my $item (@{$self->order->orderitems}) {
my $price_source = SL::PriceSource->new(record_item => $item, record => $self->order);
$item->active_price_source( $price_source->price_from_source( $item->active_price_source ));
$item->active_discount_source($price_source->discount_from_source($item->active_discount_source));
}

if (any { $self->type eq $_ } (sales_order_type(), purchase_order_type())) {
# Calculate shipped qtys here to prevent calling calculate for every item via the items method.
# Do not use write_to_objects to prevent order->delivered to be set, because this should be
# the value from db, which can be set manually or is set when linked delivery orders are saved.
SL::Helper::ShippedQty->new->calculate($self->order)->write_to(\@{$self->order->items});
}

if ($self->order->number && $::instance_conf->get_webdav) {
my $webdav = SL::Webdav->new(
type => $self->type,
number => $self->order->number,
);
my @all_objects = $webdav->get_all_objects;
@{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
type => t8('File'),
link => File::Spec->catfile($_->full_filedescriptor),
} } @all_objects;
}

if ( (any { $self->type eq $_ } (sales_quotation_type(), sales_order_type()))
&& $::instance_conf->get_transport_cost_reminder_article_number_id ) {
$self->{template_args}->{transport_cost_reminder_article} = SL::DB::Part->new(id => $::instance_conf->get_transport_cost_reminder_article_number_id)->load;
}
$self->{template_args}->{longdescription_dialog_size_percentage} = SL::Helper::UserPreferences::DisplayPreferences->new()->get_longdescription_dialog_size_percentage();

$self->get_item_cvpartnumber($_) for @{$self->order->items_sorted};

$self->{template_args}->{num_phone_notes} = scalar @{ $self->order->phone_notes || [] };

$::request->{layout}->use_javascript("${_}.js") for qw(kivi.Validator kivi.SalesPurchase kivi.Order kivi.File ckeditor/ckeditor ckeditor/adapters/jquery
edit_periodic_invoices_config calculate_qty follow_up show_history);
$self->setup_edit_action_bar;
}

sub setup_edit_action_bar {
my ($self, %params) = @_;

my $deletion_allowed = (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type()))
|| (($self->type eq sales_order_type()) && $::instance_conf->get_sales_order_show_delete)
|| (($self->type eq purchase_order_type()) && $::instance_conf->get_purchase_order_show_delete);

my @req_trans_cost_art = qw(kivi.Order.check_transport_cost_article_presence) x!!$::instance_conf->get_transport_cost_reminder_article_number_id;
my @req_cusordnumber = qw(kivi.Order.check_cusordnumber_presence) x($self->type eq sales_order_type() && $::instance_conf->get_order_warn_no_cusordnumber);

my $has_invoice_for_advance_payment;
if ($self->order->id && $self->type eq sales_order_type()) {
my $lr = $self->order->linked_records(direction => 'to', to => ['Invoice']);
$has_invoice_for_advance_payment = any {'SL::DB::Invoice' eq ref $_ && "invoice_for_advance_payment" eq $_->type} @$lr;
}

my $has_final_invoice;
if ($self->order->id && $self->type eq sales_order_type()) {
my $lr = $self->order->linked_records(direction => 'to', to => ['Invoice']);
$has_final_invoice = any {'SL::DB::Invoice' eq ref $_ && "final_invoice" eq $_->type} @$lr;
}

my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
my $right = $right_for->{ $self->type };
$right ||= 'DOES_NOT_EXIST';
my $may_edit_create = $::auth->assert($right, 'may fail');

my $is_final_version = $self->is_final_version;

for my $bar ($::request->layout->get('actionbar')) {
$bar->add(
combobox => [
action => [
t8('Save'),
call => [ 'kivi.Order.save', { action => 'save',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts,
warn_on_reqdate => $::instance_conf->get_order_warn_no_deliverydate },
],
checks => [ 'kivi.Order.check_save_active_periodic_invoices', ['kivi.validate_form','#order_form'],
@req_trans_cost_art, @req_cusordnumber,
],
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
: $is_final_version ? t8('This record is the final version. Please create a new sub-version') : undef,
],
action => [
t8('Save and Close'),
call => [ 'kivi.Order.save', { action => 'save',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts,
warn_on_reqdate => $::instance_conf->get_order_warn_no_deliverydate,
back_to_caller => 1 },
],
checks => [ 'kivi.Order.check_save_active_periodic_invoices', ['kivi.validate_form','#order_form'],
@req_trans_cost_art, @req_cusordnumber,
],
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
: $is_final_version ? t8('This record is the final version. Please create a new sub-version') : undef,
],
action => [
t8('Create Sub-Version'),
call => [ 'kivi.Order.save', { action => 'add_subversion' }, ],
only_if => $::instance_conf->get_lock_oe_subversions,
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
: !$is_final_version ? t8('This sub-version is not yet finalized')
: undef,
],
action => [
t8('Save as new'),
call => [ 'kivi.Order.save', { action => 'save_as_new',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts },
],
checks => [ 'kivi.Order.check_save_active_periodic_invoices',
@req_trans_cost_art, @req_cusordnumber,
],
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
: !$self->order->id ? t8('This object has not been saved yet.')
: undef,
],
], # end of combobox "Save"

combobox => [
action => [
t8('Workflow'),
],
action => [
t8('Save and Quotation'),
call => [ 'kivi.submit_ajax_form', $self->url_for(action => "save_and_order_workflow", to_type => sales_quotation_type()), '#order_form' ],
checks => [ @req_trans_cost_art, @req_cusordnumber ],
only_if => (any { $self->type eq $_ } (sales_order_type(), request_quotation_type())),
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
],
action => [
t8('Save and RFQ'),
call => [ 'kivi.Order.purchase_check_for_direct_delivery', { to_type => request_quotation_type() } ],
only_if => (any { $self->type eq $_ } (sales_order_type(), sales_quotation_type(), purchase_order_type())),
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
],
action => [
t8('Save and Sales Order'),
call => [ 'kivi.submit_ajax_form', $self->url_for(action => "save_and_order_workflow", to_type => sales_order_type()), '#order_form' ],
checks => [ @req_trans_cost_art ],
only_if => (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type(), purchase_order_type())),
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
],
action => [
t8('Save and Purchase Order'),
call => [ 'kivi.Order.purchase_check_for_direct_delivery', { to_type => purchase_order_type() } ],
checks => [ @req_trans_cost_art, @req_cusordnumber ],
only_if => (any { $self->type eq $_ } (sales_order_type(), request_quotation_type())),
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
],
action => [
t8('Save and Delivery Order'),
call => [ 'kivi.Order.save', { action => 'save_and_delivery_order',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts,
warn_on_reqdate => $::instance_conf->get_order_warn_no_deliverydate },
],
checks => [ 'kivi.Order.check_save_active_periodic_invoices',
@req_trans_cost_art, @req_cusordnumber,
],
only_if => (any { $self->type eq $_ } (sales_order_type(), purchase_order_type())),
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
],
action => [
t8('Save and Delivery Order with item selection'),
call => [ 'kivi.Order.convert_to_purchase_delivery_order_select_items',
{ action => 'save_and_delivery_order',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts,
warn_on_reqdate => $::instance_conf->get_order_warn_no_deliverydate },
],
checks => [ @req_trans_cost_art, @req_cusordnumber ],
only_if => (any { $self->type eq $_ } (purchase_order_type())),
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
],
action => [
t8('Save and Supplier Delivery Order'),
call => [ 'kivi.Order.save', { action => 'save_and_supplier_delivery_order',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts,
warn_on_reqdate => $::instance_conf->get_order_warn_no_deliverydate },
],
checks => [ 'kivi.Order.check_save_active_periodic_invoices',
@req_trans_cost_art, @req_cusordnumber,
],
only_if => (any { $self->type eq $_ } (purchase_order_type())),
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
],
action => [
t8('Save and Reclamation'),
call => [ 'kivi.Order.save', { action => 'save_and_reclamation',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts },
],
only_if => (any { $self->type eq $_ } (sales_order_type(), purchase_order_type()))
],
action => [
t8('Save and Invoice'),
call => [ 'kivi.Order.save', { action => 'save_and_invoice',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts },
],
checks => [ 'kivi.Order.check_save_active_periodic_invoices',
@req_trans_cost_art, @req_cusordnumber,
],
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
],
action => [
($has_invoice_for_advance_payment ? t8('Save and Further Invoice for Advance Payment') : t8('Save and Invoice for Advance Payment')),
call => [ 'kivi.Order.save', { action => 'save_and_invoice_for_advance_payment',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts },
],
checks => [ 'kivi.Order.check_save_active_periodic_invoices',
@req_trans_cost_art, @req_cusordnumber,
],
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
: $has_final_invoice ? t8('This order has already a final invoice.')
: undef,
only_if => (any { $self->type eq $_ } (sales_order_type())),
],
action => [
t8('Save and Final Invoice'),
call => [ 'kivi.Order.save', { action => 'save_and_final_invoice',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts },
],
checks => [ 'kivi.Order.check_save_active_periodic_invoices',
@req_trans_cost_art, @req_cusordnumber,
],
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
: $has_final_invoice ? t8('This order has already a final invoice.')
: undef,
only_if => (any { $self->type eq $_ } (sales_order_type())) && $has_invoice_for_advance_payment,
],
action => [
t8('Save and AP Transaction'),
call => [ 'kivi.Order.save', { action => 'save_and_ap_transaction',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts },
],
only_if => (any { $self->type eq $_ } (purchase_order_type())),
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
],

], # end of combobox "Workflow"

combobox => [
action => [
t8('Export'),
],
action => [
t8('Save and preview PDF'),
call => [ 'kivi.Order.save', { action => 'preview_pdf',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts,
warn_on_reqdate => $::instance_conf->get_order_warn_no_deliverydate },
],
checks => [ @req_trans_cost_art, @req_cusordnumber ],
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
: $is_final_version ? t8('This record is the final version. Please create a new sub-version') : undef,
],
action => [
t8('Save and print'),
call => [ 'kivi.Order.show_print_options', { warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts,
warn_on_reqdate => $::instance_conf->get_order_warn_no_deliverydate },
],
checks => [ @req_trans_cost_art, @req_cusordnumber ],
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
: $is_final_version ? t8('This record is the final version. Please create a new sub-version') : undef,
],
action => [
($is_final_version ? t8('E-mail') : t8('Save and E-mail')),
id => 'save_and_email_action',
call => [ 'kivi.Order.save', { action => 'save_and_show_email_dialog',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts,
warn_on_reqdate => $::instance_conf->get_order_warn_no_deliverydate },
],
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
: !$self->order->id ? t8('This object has not been saved yet.')
: undef,
],
action => [
t8('Download attachments of all parts'),
call => [ 'kivi.File.downloadOrderitemsFiles', $::form->{type}, $::form->{id} ],
disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
only_if => $::instance_conf->get_doc_storage,
],
], # end of combobox "Export"

action => [
t8('Delete'),
call => [ 'kivi.Order.delete_order' ],
confirm => $::locale->text('Do you really want to delete this object?'),
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
: !$self->order->id ? t8('This object has not been saved yet.')
: undef,
only_if => $deletion_allowed,
],

combobox => [
action => [
t8('more')
],
action => [
t8('History'),
call => [ 'set_history_window', $self->order->id, 'id' ],
disabled => !$self->order->id ? t8('This record has not been saved yet.') : undef,
],
action => [
t8('Follow-Up'),
call => [ 'kivi.Order.follow_up_window' ],
disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
only_if => $::auth->assert('productivity', 1),
],
], # end of combobox "more"
);
}
}

sub generate_doc {
my ($self, $doc_ref, $params) = @_;

my $order = $self->order;
my @errors = ();

my $print_form = Form->new('');
$print_form->{type} = $order->type;
$print_form->{formname} = $params->{formname} || $order->type;
$print_form->{format} = $params->{format} || 'pdf';
$print_form->{media} = $params->{media} || 'file';
$print_form->{groupitems} = $params->{groupitems};
$print_form->{printer_id} = $params->{printer_id};
$print_form->{media} = 'file' if $print_form->{media} eq 'screen';

$order->language($params->{language});
$order->flatten_to_form($print_form, format_amounts => 1);

my $template_ext;
my $template_type;
if ($print_form->{format} =~ /(opendocument|oasis)/i) {
$template_ext = 'odt';
$template_type = 'OpenDocument';
} elsif ($print_form->{format} =~ m{html}i) {
$template_ext = 'html';
$template_type = 'HTML';
}

# search for the template
my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
name => $print_form->{formname},
extension => $template_ext,
email => $print_form->{media} eq 'email',
language => $params->{language},
printer_id => $print_form->{printer_id},
);

if (!defined $template_file) {
push @errors, $::locale->text('Cannot find matching template for this print request. Please contact your template maintainer. I tried these: #1.', join ', ', map { "'$_'"} @template_files);
}

return @errors if scalar @errors;

$print_form->throw_on_error(sub {
eval {
$print_form->prepare_for_printing;

$$doc_ref = SL::Helper::CreatePDF->create_pdf(
format => $print_form->{format},
template_type => $template_type,
template => $template_file,
variables => $print_form,
variable_content_types => {
longdescription => 'html',
partnotes => 'html',
notes => 'html',
$::form->get_variable_content_types_for_cvars,
},
);
1;
} || push @errors, ref($EVAL_ERROR) eq 'SL::X::FormError' ? $EVAL_ERROR->error : $EVAL_ERROR;
});

return @errors;
}

sub get_files_for_email_dialog {
my ($self) = @_;

my %files = map { ($_ => []) } qw(versions files vc_files part_files);

return %files if !$::instance_conf->get_doc_storage;

if ($self->order->id) {
$files{versions} = [ SL::File->get_all_versions(object_id => $self->order->id, object_type => $self->order->type, file_type => 'document') ];
$files{files} = [ SL::File->get_all( object_id => $self->order->id, object_type => $self->order->type, file_type => 'attachment') ];
$files{vc_files} = [ SL::File->get_all( object_id => $self->order->{$self->cv}->id, object_type => $self->cv, file_type => 'attachment') ];
$files{project_files} = [ SL::File->get_all( object_id => $self->order->globalproject_id, object_type => 'project', file_type => 'attachment') ];
}

my @parts =
uniq_by { $_->{id} }
map {
+{ id => $_->part->id,
partnumber => $_->part->partnumber }
} @{$self->order->items_sorted};

foreach my $part (@parts) {
my @pfiles = SL::File->get_all(object_id => $part->{id}, object_type => 'part');
push @{ $files{part_files} }, map { +{ %{ $_ }, partnumber => $part->{partnumber} } } @pfiles;
}

foreach my $key (keys %files) {
$files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
}

return %files;
}

sub make_periodic_invoices_config_from_yaml {
my ($yaml_config) = @_;

return if !$yaml_config;
my $attr = SL::YAML::Load($yaml_config);
return if 'HASH' ne ref $attr;
return SL::DB::PeriodicInvoicesConfig->new(%$attr);
}


sub get_periodic_invoices_status {
my ($self, $config) = @_;

return if $self->type ne sales_order_type();
return t8('not configured') if !$config;

my $active = ('HASH' eq ref $config) ? $config->{active}
: ('SL::DB::PeriodicInvoicesConfig' eq ref $config) ? $config->active
: die "Cannot get status of periodic invoices config";

return $active ? t8('active') : t8('inactive');
}

sub get_title_for {
my ($self, $action) = @_;

return '' if none { lc($action)} qw(add edit);

# for locales:
# $::locale->text("Add Sales Order");
# $::locale->text("Add Purchase Order");
# $::locale->text("Add Quotation");
# $::locale->text("Add Request for Quotation");
# $::locale->text("Edit Sales Order");
# $::locale->text("Edit Purchase Order");
# $::locale->text("Edit Quotation");
# $::locale->text("Edit Request for Quotation");

$action = ucfirst(lc($action));
return $self->type eq sales_order_type() ? $::locale->text("$action Sales Order")
: $self->type eq purchase_order_type() ? $::locale->text("$action Purchase Order")
: $self->type eq sales_quotation_type() ? $::locale->text("$action Quotation")
: $self->type eq request_quotation_type() ? $::locale->text("$action Request for Quotation")
: '';
}

sub get_item_cvpartnumber {
my ($self, $item) = @_;

return if !$self->search_cvpartnumber;
return if !$self->order->customervendor;

if ($self->cv eq 'vendor') {
my @mms = grep { $_->make eq $self->order->customervendor->id } @{$item->part->makemodels};
$item->{cvpartnumber} = $mms[0]->model if scalar @mms;
} elsif ($self->cv eq 'customer') {
my @cps = grep { $_->customer_id eq $self->order->customervendor->id } @{$item->part->customerprices};
$item->{cvpartnumber} = $cps[0]->customer_partnumber if scalar @cps;
}
}

sub get_part_texts {
my ($part_or_id, $language_or_id, %defaults) = @_;

my $part = ref($part_or_id) ? $part_or_id : SL::DB::Part->load_cached($part_or_id);
my $language_id = ref($language_or_id) ? $language_or_id->id : $language_or_id;
my $texts = {
description => $defaults{description} // $part->description,
longdescription => $defaults{longdescription} // $part->notes,
};

return $texts unless $language_id;

my $translation = SL::DB::Manager::Translation->get_first(
where => [
parts_id => $part->id,
language_id => $language_id,
]);

$texts->{description} = $translation->translation if $translation && $translation->translation;
$texts->{longdescription} = $translation->longdescription if $translation && $translation->longdescription;

return $texts;
}

sub get_best_price_and_discount_source {
my ($record, $item, $ignore_given) = @_;

my $price_source = SL::PriceSource->new(record_item => $item, record => $record);

my $price_src;
if ( $item->part->is_assortment ) {
# add assortment items with price 0, as the components carry the price
$price_src = $price_source->price_from_source("");
$price_src->price(0);
} elsif (!$ignore_given && defined $item->sellprice) {
$price_src = $price_source->price_from_source("");
$price_src->price($item->sellprice);
} else {
$price_src = $price_source->best_price
? $price_source->best_price
: $price_source->price_from_source("");
$price_src->price($::form->round_amount($price_src->price / $record->exchangerate, 5)) if $record->exchangerate;
$price_src->price(0) if !$price_source->best_price;
}

my $discount_src;
if (!$ignore_given && defined $item->discount) {
$discount_src = $price_source->discount_from_source("");
$discount_src->discount($item->discount);
} else {
$discount_src = $price_source->best_discount
? $price_source->best_discount
: $price_source->discount_from_source("");
$discount_src->discount(0) if !$price_source->best_discount;
}

return ($price_src, $discount_src);
}

sub sales_order_type {
'sales_order';
}

sub purchase_order_type {
'purchase_order';
}

sub sales_quotation_type {
'sales_quotation';
}

sub request_quotation_type {
'request_quotation';
}

sub nr_key {
return $_[0]->type eq sales_order_type() ? 'ordnumber'
: $_[0]->type eq purchase_order_type() ? 'ordnumber'
: $_[0]->type eq sales_quotation_type() ? 'quonumber'
: $_[0]->type eq request_quotation_type() ? 'quonumber'
: '';
}

sub save_and_redirect_to {
my ($self, %params) = @_;

my $errors = $self->save();

if (scalar @{ $errors }) {
$self->js->flash('error', $_) foreach @{ $errors };
return $self->js->render();
}

my $text = $self->type eq sales_order_type() ? $::locale->text('The order has been saved')
: $self->type eq purchase_order_type() ? $::locale->text('The order has been saved')
: $self->type eq sales_quotation_type() ? $::locale->text('The quotation has been saved')
: $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
: '';
flash_later('info', $text);

$self->redirect_to(%params, id => $self->order->id);
}

sub save_history {
my ($self, $addition) = @_;

my $number_type = $self->order->type =~ m{order} ? 'ordnumber' : 'quonumber';
my $snumbers = $number_type . '_' . $self->order->$number_type;

SL::DB::History->new(
trans_id => $self->order->id,
employee_id => SL::DB::Manager::Employee->current->id,
what_done => $self->order->type,
snumbers => $snumbers,
addition => $addition,
)->save;
}

sub store_doc_to_webdav_and_filemanagement {
my ($self, $content, $filename, $variant) = @_;

my $order = $self->order;
my @errors;

# copy file to webdav folder
if ($order->number && $::instance_conf->get_webdav_documents) {
my $webdav = SL::Webdav->new(
type => $order->type,
number => $order->number,
);
my $webdav_file = SL::Webdav::File->new(
webdav => $webdav,
filename => $filename,
);
eval {
$webdav_file->store(data => \$content);
1;
} or do {
push @errors, t8('Storing the document to the WebDAV folder failed: #1', $@);
};
}
my $file_obj;
if ($order->id && $::instance_conf->get_doc_storage) {
eval {
$file_obj = SL::File->save(object_id => $order->id,
object_type => $order->type,
mime_type => SL::MIME->mime_type_from_ext($filename),
source => 'created',
file_type => 'document',
file_name => $filename,
file_contents => $content,
print_variant => $variant);

$self->{file_id} = $file_obj->id;
1;
} or do {
push @errors, t8('Storing the document in the storage backend failed: #1', $@);
};
}

return @errors;
}

sub link_requirement_specs_linking_to_created_from_objects {
my ($self, @converted_from_oe_ids) = @_;

return unless @converted_from_oe_ids;

my $rs_orders = SL::DB::Manager::RequirementSpecOrder->get_all(where => [ order_id => \@converted_from_oe_ids ]);
foreach my $rs_order (@{ $rs_orders }) {
SL::DB::RequirementSpecOrder->new(
order_id => $self->order->id,
requirement_spec_id => $rs_order->requirement_spec_id,
version_id => $rs_order->version_id,
)->save;
}
}

sub set_project_in_linked_requirement_specs {
my ($self) = @_;

my $rs_orders = SL::DB::Manager::RequirementSpecOrder->get_all(where => [ order_id => $self->order->id ]);
foreach my $rs_order (@{ $rs_orders }) {
next if $rs_order->requirement_spec->project_id == $self->order->globalproject_id;

$rs_order->requirement_spec->update_attributes(project_id => $self->order->globalproject_id);
}
}

1;

__END__

=encoding utf-8

=head1 NAME

SL::Controller::Order - controller for orders

=head1 SYNOPSIS

This is a new form to enter orders, completely rewritten with the use
of controller and java script techniques.

The aim is to provide the user a better experience and a faster workflow. Also
the code should be more readable, more reliable and better to maintain.

=head2 Key Features

=over 4

=item *

One input row, so that input happens every time at the same place.

=item *

Use of pickers where possible.

=item *

Possibility to enter more than one item at once.

=item *

Item list in a scrollable area, so that the workflow buttons stay at
the bottom.

=item *

Reordering item rows with drag and drop is possible. Sorting item rows is
possible (by partnumber, description, qty, sellprice and discount for now).

=item *

No C<update> is necessary. All entries and calculations are managed
with ajax-calls and the page only reloads on C<save>.

=item *

User can see changes immediately, because of the use of java script
and ajax.

=back

=head1 CODE

=head2 Layout

=over 4

=item * C<SL/Controller/Order.pm>

the controller

=item * C<template/webpages/order/form.html>

main form

=item * C<template/webpages/order/tabs/basic_data.html>

Main tab for basic_data.

This is the only tab here for now. "linked records" and "webdav" tabs are
reused from generic code.

=over 4

=item * C<template/webpages/order/tabs/_business_info_row.html>

For displaying information on business type

=item * C<template/webpages/order/tabs/_item_input.html>

The input line for items

=item * C<template/webpages/order/tabs/_row.html>

One row for already entered items

=item * C<template/webpages/order/tabs/_tax_row.html>

Displaying tax information

=item * C<template/webpages/order/tabs/_price_sources_dialog.html>

Dialog for selecting price and discount sources

=back

=item * C<js/kivi.Order.js>

java script functions

=back

=head1 TODO

=over 4

=item * testing

=item * price sources: little symbols showing better price / better discount

=item * select units in input row?

=item * check for direct delivery (workflow sales order -> purchase order)

=item * access rights

=item * display weights

=item * mtime check

=item * optional client/user behaviour

(transactions has to be set - department has to be set -
force project if enabled in client config)

=back

=head1 KNOWN BUGS AND CAVEATS

=over 4

=item *

No indication that <shift>-up/down expands/collapses second row.

=item *

Table header is not sticky in the scrolling area.

=item *

Sorting does not include C<position>, neither does reordering.

This behavior was implemented intentionally. But we can discuss, which behavior
should be implemented.

=back

=head1 To discuss / Nice to have

=over 4

=item *

How to expand/collapse second row. Now it can be done clicking the icon or
<shift>-up/down.

=item *

This controller uses a (changed) copy of the template for the PriceSource
dialog. Maybe there could be used one code source.

=item *

Rounding-differences between this controller (PriceTaxCalculator) and the old
form. This is not only a problem here, but also in all parts using the PTC.
There exists a ticket and a patch. This patch should be testet.

=item *

An indicator, if the actual inputs are saved (like in an
editor or on text processing application).

=item *

A warning when leaving the page without saving unchanged inputs.


=back

=head1 AUTHOR

Bernd Bleßmann E<lt>bernd@kivitendo-premium.deE<gt>

=cut
(45-45/82)