Projekt

Allgemein

Profil

Herunterladen (115 KB) Statistiken
| Zweig: | Markierung: | Revision:
package SL::Controller::Order;

use strict;
use parent qw(SL::Controller::Base);

use SL::Helper::Flash qw(flash_later);
use SL::HTML::Util;
use SL::Presenter::Tag qw(select_tag hidden_tag div_tag);
use SL::Locale::String qw(t8);
use SL::SessionFile::Random;
use SL::PriceSource;
use SL::Webdav;
use SL::File;
use SL::MIME;
use SL::Util qw(trim);
use SL::YAML;
use SL::DB::AdditionalBillingAddress;
use SL::DB::AuthUser;
use SL::DB::History;
use SL::DB::Order;
use SL::DB::Default;
use SL::DB::Unit;
use SL::DB::Part;
use SL::DB::PartClassification;
use SL::DB::PartsGroup;
use SL::DB::Printer;
use SL::DB::Note;
use SL::DB::Language;
use SL::DB::Reclamation;
use SL::DB::RecordLink;
use SL::DB::RequirementSpec;
use SL::DB::Shipto;
use SL::DB::Translation;
use SL::DB::ValidityToken;
use SL::Model::Record;

use SL::Helper::CreatePDF qw(:all);
use SL::Helper::PrintOptions;
use SL::Helper::ShippedQty;
use SL::Helper::UserPreferences::DisplayPreferences;
use SL::Helper::UserPreferences::PositionsScrollbar;
use SL::Helper::UserPreferences::UpdatePositions;

use SL::Controller::Helper::GetModels;

use List::Util qw(first sum0);
use List::UtilsBy qw(sort_by uniq_by);
use List::MoreUtils qw(any none pairwise first_index);
use English qw(-no_match_vars);
use File::Spec;
use Cwd;
use Sort::Naturally;

use Rose::Object::MakeMethods::Generic
(
scalar => [ qw(item_ids_to_delete is_custom_shipto_to_delete) ],
'scalar --get_set_init' => [ qw(order valid_types type cv p all_price_factors
search_cvpartnumber show_update_button
part_picker_classification_ids
is_final_version) ],
);


# safety
__PACKAGE__->run_before('check_auth',
except => [ qw(close_quotations) ]);

__PACKAGE__->run_before('check_auth_for_edit',
except => [ qw(edit show_customer_vendor_details_dialog price_popup load_second_rows close_quotations) ]);

#
# actions
#

# add a new order
sub action_add {
my ($self) = @_;

$self->order->transdate(DateTime->now_local());
my $extra_days = $self->type eq sales_quotation_type() ? $::instance_conf->get_reqdate_interval :
$self->type eq sales_order_type() ? $::instance_conf->get_delivery_date_interval : 1;

if ( ($self->type eq sales_order_type() && $::instance_conf->get_deliverydate_on)
|| ($self->type eq sales_quotation_type() && $::instance_conf->get_reqdate_on)
&& (!$self->order->reqdate)) {
$self->order->reqdate(DateTime->today_local->next_workday(extra_days => $extra_days));
}


$self->pre_render();

if (!$::form->{form_validity_token}) {
$::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_ORDER_SAVE())->token;
}

$self->render(
'order/form',
title => $self->get_title_for('add'),
%{$self->{template_args}}
);
}

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

my $reclamation = SL::DB::Reclamation->new(id => $::form->{from_id})->load;
my %params;
my $target_type = $reclamation->is_sales ? 'sales_order'
: 'purchase_order';
my $order = SL::Model::Record->new_from_workflow($reclamation, $target_type);
$self->{converted_from_reclamation_id} = $::form->{from_id};

$self->order($order);

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

if (!$::form->{form_validity_token}) {
$::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_ORDER_SAVE())->token;
}

$self->render(
'order/form',
title => $self->get_title_for('edit'),
%{$self->{template_args}}
);
}

# edit an existing order
sub action_edit {
my ($self) = @_;

if ($::form->{id}) {
$self->load_order;

} else {
# this is to edit an order from an unsaved order object

# set item ids to new fake id, to identify them as new items
foreach my $item (@{$self->order->items_sorted}) {
$item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
}
# trigger rendering values for second row as hidden, because they
# are loaded only on demand. So we need to keep the values from
# the source.
$_->{render_second_row} = 1 for @{ $self->order->items_sorted };

if (!$::form->{form_validity_token}) {
$::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_ORDER_SAVE())->token;
}
}

$self->recalc();
$self->pre_render();
$self->render(
'order/form',
title => $self->get_title_for('edit'),
%{$self->{template_args}}
);
}

# edit a collective order (consisting of one or more existing orders)
sub action_edit_collective {
my ($self) = @_;

# collect order ids
my @multi_ids = map {
$_ =~ m{^multi_id_(\d+)$} && $::form->{'multi_id_' . $1} && $::form->{'trans_id_' . $1} && $::form->{'trans_id_' . $1}
} grep { $_ =~ m{^multi_id_\d+$} } keys %$::form;

# fall back to add if no ids are given
if (scalar @multi_ids == 0) {
$self->action_add();
return;
}

# fall back to save as new if only one id is given
if (scalar @multi_ids == 1) {
$self->order(SL::DB::Order->new(id => $multi_ids[0])->load);
$self->action_save_as_new();
return;
}

# make new order from given orders
my @multi_orders = map { SL::DB::Order->new(id => $_)->load } @multi_ids;
$self->{converted_from_oe_id} = join ' ', map { $_->id } @multi_orders;
$self->order(SL::DB::Order->new_from_multi(\@multi_orders, sort_sources_by => 'transdate'));

$self->action_edit();
}

# delete the order
sub action_delete {
my ($self) = @_;

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

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 deleted')
: $self->type eq purchase_order_type() ? $::locale->text('The order has been deleted')
: $self->type eq sales_quotation_type() ? $::locale->text('The quotation has been deleted')
: $self->type eq request_quotation_type() ? $::locale->text('The rfq has been deleted')
: '';
flash_later('info', $text);

my @redirect_params = (
action => 'add',
type => $self->type,
);

$self->redirect_to(@redirect_params);
}

# save the order
sub action_save {
my ($self) = @_;

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);

my @redirect_params;
if ($::form->{back_to_caller}) {
@redirect_params = $::form->{callback} ? ($::form->{callback})
: (controller => 'LoginScreen', action => 'user_login');

} else {
@redirect_params = (
action => 'edit',
type => $self->type,
id => $self->order->id,
callback => $::form->{callback},
);
}

$self->redirect_to(@redirect_params);
}

# create new version and set version number
sub action_add_subversion {
my ($self) = @_;

my $current_version_number = $self->order->current_version_number;
my $new_version_number = $current_version_number + 1;

my $new_number = $self->order->number;
$new_number =~ s/-$current_version_number$//;
$self->order->number($new_number . '-' . $new_version_number);
$self->order->add_order_version(SL::DB::OrderVersion->new(oe_id => $self->order->id,
version => $new_version_number));

# call the save action
$self->action_save();

}

# save the order as new document and open it for edit
sub action_save_as_new {
my ($self) = @_;

my $order = $self->order;

if (!$order->id) {
$self->js->flash('error', t8('This object has not been saved yet.'));
return $self->js->render();
}

# load order from db to check if values changed
my $saved_order = SL::DB::Order->new(id => $order->id)->load;

my %new_attrs;
# Lets assign a new number if the user hasn't changed the previous one.
# If it has been changed manually then use it as-is.
$new_attrs{number} = (trim($order->number) eq $saved_order->number)
? ''
: trim($order->number);

# Clear transdate unless changed
$new_attrs{transdate} = ($order->transdate == $saved_order->transdate)
? DateTime->today_local
: $order->transdate;

# Set new reqdate unless changed if it is enabled in client config
if ($order->reqdate == $saved_order->reqdate) {
my $extra_days = $self->type eq sales_quotation_type() ? $::instance_conf->get_reqdate_interval :
$self->type eq sales_order_type() ? $::instance_conf->get_delivery_date_interval : 1;

if ( ($self->type eq sales_order_type() && !$::instance_conf->get_deliverydate_on)
|| ($self->type eq sales_quotation_type() && !$::instance_conf->get_reqdate_on)) {
$new_attrs{reqdate} = '';
} else {
$new_attrs{reqdate} = DateTime->today_local->next_workday(extra_days => $extra_days);
}
} else {
$new_attrs{reqdate} = $order->reqdate;
}

# Update employee
$new_attrs{employee} = SL::DB::Manager::Employee->current;

# Warn on obsolete items
my @obsolete_positions = map { $_->position } grep { $_->part->obsolete } @{ $order->items_sorted };
flash_later('warning', t8('This record containts obsolete items at position #1', join ', ', @obsolete_positions)) if @obsolete_positions;

# Create new record from current one
$self->order(SL::DB::Order->new_from($order, destination_type => $order->type, attributes => \%new_attrs));

# no linked records on save as new
delete $::form->{$_} for qw(converted_from_oe_id converted_from_orderitems_ids);

if (!$::form->{form_validity_token}) {
$::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_ORDER_SAVE())->token;
}

# save
$self->action_save();
}

# print the order
#
# This is called if "print" is pressed in the print dialog.
# If PDF creation was requested and succeeded, the pdf is offered for download
# via send_file (which uses ajax in this case).
sub action_print {
my ($self) = @_;

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

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

$self->js_reset_order_and_item_ids_after_save;

my $redirect_url = $self->url_for(
action => 'edit',
type => $self->type,
id => $self->order->id,
);

my $format = $::form->{print_options}->{format};
my $media = $::form->{print_options}->{media};
my $formname = $::form->{print_options}->{formname};
my $copies = $::form->{print_options}->{copies};
my $groupitems = $::form->{print_options}->{groupitems};
my $printer_id = $::form->{print_options}->{printer_id};

# only PDF, OpenDocument & HTML for now
if (none { $format eq $_ } qw(pdf opendocument opendocument_pdf html)) {
flash_later('error', t8('Format \'#1\' is not supported yet/anymore.', $format));
return $self->js->redirect_to($redirect_url)->render;
}

# only screen or printer by now
if (none { $media eq $_ } qw(screen printer)) {
flash_later('error', t8('Media \'#1\' is not supported yet/anymore.', $media));
return $self->js->redirect_to($redirect_url)->render;
}

# create a form for generate_attachment_filename
my $form = Form->new;
$form->{$self->nr_key()} = $self->order->number;
$form->{type} = $self->type;
$form->{format} = $format;
$form->{formname} = $formname;
$form->{language} = '_' . $self->order->language->template_code if $self->order->language;
my $doc_filename = $form->generate_attachment_filename();

my $doc;
my @errors = $self->generate_doc(\$doc, { media => $media,
format => $format,
formname => $formname,
language => $self->order->language,
printer_id => $printer_id,
groupitems => $groupitems });
if (scalar @errors) {
flash_later('error', t8('Generating the document failed: #1', $errors[0]));
return $self->js->redirect_to($redirect_url)->render;
}

if ($media eq 'screen') {
# screen/download
flash_later('info', t8('The document has been created.'));
$self->send_file(
\$doc,
type => SL::MIME->mime_type_from_ext($doc_filename),
name => $doc_filename,
js_no_render => 1,
);

} elsif ($media eq 'printer') {
# printer
my $printer_id = $::form->{print_options}->{printer_id};
SL::DB::Printer->new(id => $printer_id)->load->print_document(
copies => $copies,
content => $doc,
);

flash_later('info', t8('The document has been printed.'));
}

my @warnings = $self->store_doc_to_webdav_and_filemanagement($doc, $doc_filename, $formname);
if (scalar @warnings) {
flash_later('warning', $_) for @warnings;
}

$self->save_history('PRINTED');

$self->js->redirect_to($redirect_url)->render;
}

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

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

$self->js_reset_order_and_item_ids_after_save;

my $redirect_url = $self->url_for(
action => 'edit',
type => $self->type,
id => $self->order->id,
);

my $format = 'pdf';
my $media = 'screen';
my $formname = $self->type;

# only pdf
# create a form for generate_attachment_filename
my $form = Form->new;
$form->{$self->nr_key()} = $self->order->number;
$form->{type} = $self->type;
$form->{format} = $format;
$form->{formname} = $formname;
$form->{language} = '_' . $self->order->language->template_code if $self->order->language;
my $pdf_filename = $form->generate_attachment_filename();

my $pdf;
my @errors = $self->generate_doc(\$pdf, { media => $media,
format => $format,
formname => $formname,
language => $self->order->language,
});
if (scalar @errors) {
flash_later('error', t8('Conversion to PDF failed: #1', $errors[0]));
return $self->js->redirect_to($redirect_url)->render;
}

$self->save_history('PREVIEWED');

flash_later('info', t8('The PDF has been previewed'));

# screen/download
$self->send_file(
\$pdf,
type => SL::MIME->mime_type_from_ext($pdf_filename),
name => $pdf_filename,
js_no_render => 1,
);

$self->js->redirect_to($redirect_url)->render;
}

# open the email dialog
sub action_save_and_show_email_dialog {
my ($self) = @_;

if (!$self->is_final_version) {
my $errors = $self->save();

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

$self->js_reset_order_and_item_ids_after_save;
}

my $cv_method = $self->cv;

if (!$self->order->$cv_method) {
return $self->js->flash('error', $self->cv eq 'customer' ? t8('Cannot send E-mail without customer given') : t8('Cannot send E-mail without vendor given'))
->render($self);
}

my $email_form;
$email_form->{to} = $self->order->contact->cp_email if $self->order->contact;
$email_form->{to} ||= $self->order->$cv_method->email;
$email_form->{cc} = $self->order->$cv_method->cc;
$email_form->{bcc} = join ', ', grep $_, $self->order->$cv_method->bcc;
# Todo: get addresses from shipto, if any

my $form = Form->new;
$form->{$self->nr_key()} = $self->order->number;
$form->{cusordnumber} = $self->order->cusordnumber;
$form->{formname} = $self->type;
$form->{type} = $self->type;
$form->{language} = '_' . $self->order->language->template_code if $self->order->language;
$form->{language_id} = $self->order->language->id if $self->order->language;
$form->{format} = 'pdf';
$form->{cp_id} = $self->order->contact->cp_id if $self->order->contact;

$email_form->{subject} = $form->generate_email_subject();
$email_form->{attachment_filename} = $form->generate_attachment_filename();
$email_form->{message} = $form->generate_email_body();
$email_form->{js_send_function} = 'kivi.Order.send_email()';

my %files = $self->get_files_for_email_dialog();

my @employees_with_email = grep {
my $user = SL::DB::Manager::AuthUser->find_by(login => $_->login);
$user && !!trim($user->get_config_value('email'));
} @{ SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]) };


my $all_partner_email_addresses = $self->order->customervendor->get_all_email_addresses();

my $dialog_html = $self->render('common/_send_email_dialog', { output => 0 },
email_form => $email_form,
show_bcc => $::auth->assert('email_bcc', 'may fail'),
FILES => \%files,
is_customer => $self->cv eq 'customer',
ALL_EMPLOYEES => \@employees_with_email,
ALL_PARTNER_EMAIL_ADDRESSES => $all_partner_email_addresses,
is_final_version => $self->is_final_version,
);

$self->js
->run('kivi.Order.show_email_dialog', $dialog_html)
->reinit_widgets
->render($self);
}

# send email
sub action_send_email {
my ($self) = @_;

if (!$self->is_final_version) {
my $errors = $self->save();

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

$self->js_reset_order_and_item_ids_after_save;
}

my @redirect_params = (
action => 'edit',
type => $self->type,
id => $self->order->id,
);

# Set the error handler to reload the document and display errors later,
# because the document is already saved and saving can have some side effects
# such as generating a document number, project number or reocrd links,
# which will be up to date when the document is reloaded.
# Hint: Do not use "die" here and try to catch exceptions in subroutine
# calls. You should use "$::form->error" which respects the error handler.
local $::form->{__ERROR_HANDLER} = sub {
flash_later('error', $_[0]);
$self->redirect_to(@redirect_params);
$::dispatcher->end_request;
};

my $email_form = delete $::form->{email_form};

if ($email_form->{additional_to}) {
$email_form->{to} = join ', ', grep { $_ } $email_form->{to}, @{$email_form->{additional_to}};
delete $email_form->{additional_to};
}

my %field_names = (to => 'email');

$::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };

# for Form::cleanup which may be called in Form::send_email
$::form->{cwd} = getcwd();
$::form->{tmpdir} = $::lx_office_conf{paths}->{userspath};

$::form->{$_} = $::form->{print_options}->{$_} for keys %{ $::form->{print_options} };
$::form->{media} = 'email';

$::form->{attachment_policy} //= '';

# Is an old file version available?
my $attfile;
if ($::form->{attachment_policy} eq 'old_file') {
$attfile = SL::File->get_all(object_id => $self->order->id,
object_type => $self->type,
file_type => 'document',
print_variant => $::form->{formname});
}

if ($self->is_final_version && $::form->{attachment_policy} eq 'old_file' && !$attfile) {
$::form->error(t8('Re-sending a final version was requested, but the latest version of the document could not be found'));
}

if (!$self->is_final_version && $::form->{attachment_policy} ne 'no_file' && !($::form->{attachment_policy} eq 'old_file' && $attfile)) {
my $doc;
my @errors = $self->generate_doc(\$doc, {media => $::form->{media},
format => $::form->{print_options}->{format},
formname => $::form->{print_options}->{formname},
language => $self->order->language,
printer_id => $::form->{print_options}->{printer_id},
groupitems => $::form->{print_options}->{groupitems}});
if (scalar @errors) {
$::form->error(t8('Generating the document failed: #1', $errors[0]));
}

my @warnings = $self->store_doc_to_webdav_and_filemanagement($doc, $::form->{attachment_filename}, $::form->{formname});
if (scalar @warnings) {
flash_later('warning', $_) for @warnings;
}

my $sfile = SL::SessionFile::Random->new(mode => "w");
$sfile->fh->print($doc);
$sfile->fh->close;

$::form->{tmpfile} = $sfile->file_name;
$::form->{tmpdir} = $sfile->get_path; # for Form::cleanup which may be called in Form::send_email
}

$::form->{id} = $self->order->id; # this is used in SL::Mailer to create a linked record to the mail
$::form->send_email(\%::myconfig, $::form->{print_options}->{format});

flash_later('info', t8('The email has been sent.'));

# internal notes unless no email journal
unless ($::instance_conf->get_email_journal) {
my $intnotes = $self->order->intnotes;
$intnotes .= "\n\n" if $self->order->intnotes;
$intnotes .= t8('[email]') . "\n";
$intnotes .= t8('Date') . ": " . $::locale->format_date_object(DateTime->now_local, precision => 'seconds') . "\n";
$intnotes .= t8('To (email)') . ": " . $::form->{email} . "\n";
$intnotes .= t8('Cc') . ": " . $::form->{cc} . "\n" if $::form->{cc};
$intnotes .= t8('Bcc') . ": " . $::form->{bcc} . "\n" if $::form->{bcc};
$intnotes .= t8('Subject') . ": " . $::form->{subject} . "\n\n";
$intnotes .= t8('Message') . ": " . SL::HTML::Util->strip($::form->{message});

$self->order->update_attributes(intnotes => $intnotes);
}

if ($::instance_conf->get_lock_oe_subversions && !$self->is_final_version) {
my $file_id;
if ($::instance_conf->get_doc_storage && $::form->{attachment_policy} ne 'no_file') {
# self is generated on the fly. form is a file from the dms
# TODO: for the case Filesystem and Webdav we want the real file from the filesystem
# for the nyi case DMS/CMIS we need a gloid or whatever the system offers (elo_id for ELO)
# DMS kivi version should have a record_link to email_journal
# the record link has to refer to the correct version -> helper table file <-> file_version
$file_id = $self->{file_id} || $::form->{file_id};
$::form->error("No file id") unless $file_id;
}

# email is sent -> set this version to final and link to journal and file
my $current_version = SL::DB::Manager::OrderVersion->get_all(where => [oe_id => $self->order->id, final_version => 0]);
$::form->error("Invalid version state") unless scalar @{ $current_version } == 1;
$current_version->[0]->update_attributes(file_id => $file_id,
email_journal_id => $::form->{email_journal_id},
final_version => 1);
}

$self->redirect_to(@redirect_params);
}

# open the periodic invoices config dialog
#
# If there are values in the form (i.e. dialog was opened before),
# then use this values. Create new ones, else.
sub action_show_periodic_invoices_config_dialog {
my ($self) = @_;

my $config = make_periodic_invoices_config_from_yaml(delete $::form->{config});
$config ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
$config ||= SL::DB::PeriodicInvoicesConfig->new(periodicity => 'm',
order_value_periodicity => 'p', # = same as periodicity
start_date_as_date => $::form->{transdate_as_date} || $::form->current_date,
extend_automatically_by => 12,
active => 1,
email_subject => GenericTranslations->get(
language_id => $::form->{language_id},
translation_type =>"preset_text_periodic_invoices_email_subject"),
email_body => GenericTranslations->get(
language_id => $::form->{language_id},
translation_type => "salutation_general")
. GenericTranslations->get(
language_id => $::form->{language_id},
translation_type => "salutation_punctuation_mark") . "\n\n"
. GenericTranslations->get(
language_id => $::form->{language_id},
translation_type =>"preset_text_periodic_invoices_email_body"),
);
# for older configs, replace email preset text if not yet set.
$config->email_subject(GenericTranslations->get(
language_id => $::form->{language_id},
translation_type =>"preset_text_periodic_invoices_email_subject")
) unless $config->email_subject;

$config->email_body(GenericTranslations->get(
language_id => $::form->{language_id},
translation_type => "salutation_general")
. GenericTranslations->get(
language_id => $::form->{language_id},
translation_type => "salutation_punctuation_mark") . "\n\n"
. GenericTranslations->get(
language_id => $::form->{language_id},
translation_type =>"preset_text_periodic_invoices_email_body")
) unless $config->email_body;

$config->periodicity('m') if none { $_ eq $config->periodicity } @SL::DB::PeriodicInvoicesConfig::PERIODICITIES;
$config->order_value_periodicity('p') if none { $_ eq $config->order_value_periodicity } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES);

$::form->get_lists(printers => "ALL_PRINTERS",
charts => { key => 'ALL_CHARTS',
transdate => 'current_date' });

$::form->{AR} = [ grep { $_->{link} =~ m/(?:^|:)AR(?::|$)/ } @{ $::form->{ALL_CHARTS} } ];

if ($::form->{customer_id}) {
$::form->{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(where => [ cp_cv_id => $::form->{customer_id} ]);
my $customer_object = SL::DB::Manager::Customer->find_by(id => $::form->{customer_id});
$::form->{postal_invoice} = $customer_object->postal_invoice;
$::form->{email_recipient_invoice_address} = $::form->{postal_invoice} ? '' : $customer_object->invoice_mail;
$config->send_email(0) if $::form->{postal_invoice};
}

$self->render('oe/edit_periodic_invoices_config', { layout => 0 },
popup_dialog => 1,
popup_js_close_function => 'kivi.Order.close_periodic_invoices_config_dialog()',
popup_js_assign_function => 'kivi.Order.assign_periodic_invoices_config()',
config => $config,
%$::form);
}

# assign the values of the periodic invoices config dialog
# as yaml in the hidden tag and set the status.
sub action_assign_periodic_invoices_config {
my ($self) = @_;

$::form->isblank('start_date_as_date', $::locale->text('The start date is missing.'));

my $config = { active => $::form->{active} ? 1 : 0,
terminated => $::form->{terminated} ? 1 : 0,
direct_debit => $::form->{direct_debit} ? 1 : 0,
periodicity => (any { $_ eq $::form->{periodicity} } @SL::DB::PeriodicInvoicesConfig::PERIODICITIES) ? $::form->{periodicity} : 'm',
order_value_periodicity => (any { $_ eq $::form->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES)) ? $::form->{order_value_periodicity} : 'p',
start_date_as_date => $::form->{start_date_as_date},
end_date_as_date => $::form->{end_date_as_date},
first_billing_date_as_date => $::form->{first_billing_date_as_date},
print => $::form->{print} ? 1 : 0,
printer_id => $::form->{print} ? $::form->{printer_id} * 1 : undef,
copies => $::form->{copies} * 1 ? $::form->{copies} : 1,
extend_automatically_by => $::form->{extend_automatically_by} * 1 || undef,
ar_chart_id => $::form->{ar_chart_id} * 1,
send_email => $::form->{send_email} ? 1 : 0,
email_recipient_contact_id => $::form->{email_recipient_contact_id} * 1 || undef,
email_recipient_address => $::form->{email_recipient_address},
email_sender => $::form->{email_sender},
email_subject => $::form->{email_subject},
email_body => $::form->{email_body},
};

my $periodic_invoices_config = SL::YAML::Dump($config);

my $status = $self->get_periodic_invoices_status($config);

$self->js
->remove('#order_periodic_invoices_config')
->insertAfter(hidden_tag('order.periodic_invoices_config', $periodic_invoices_config), '#periodic_invoices_status')
->run('kivi.Order.close_periodic_invoices_config_dialog')
->html('#periodic_invoices_status', $status)
->flash('info', t8('The periodic invoices config has been assigned.'))
->render($self);
}

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

my $config = make_periodic_invoices_config_from_yaml(delete $::form->{config});
$config ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};

my $has_active_periodic_invoices =
$self->type eq sales_order_type()
&& $config
&& $config->active
&& (!$config->end_date || ($config->end_date > DateTime->today_local))
&& $config->get_previous_billed_period_start_date;

$_[0]->render(\ !!$has_active_periodic_invoices, { type => 'text' });
}

# save the order and redirect to the frontend subroutine for a new
# delivery order
sub action_save_and_delivery_order {
my ($self) = @_;

$self->save_and_redirect_to(
controller => 'oe.pl',
action => 'oe_delivery_order_from_order',
);
}

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

$self->save_and_redirect_to(
controller => 'controller.pl',
action => 'DeliveryOrder/add_from_order',
type => 'supplier_delivery_order',
);
}

# save the order and redirect to the frontend subroutine for a new reclamation
sub action_save_and_reclamation {
my ($self) = @_;

# cann't use save_and_redirect_to, because id is set!
my $errors = $self->save();
if (scalar @{ $errors }) {
$self->js->flash('error', $_) foreach @{ $errors };
return $self->js->render();
}

my $to_type = $self->order->is_sales ? 'sales_reclamation'
: 'purchase_reclamation';
$self->redirect_to(
controller => 'Reclamation',
action => 'add_from_order',
type => $to_type,
from_id => $self->order->id,
);
}

# save the order and redirect to the frontend subroutine for a new
# invoice
sub action_save_and_invoice {
my ($self) = @_;

$self->save_and_redirect_to(
controller => 'oe.pl',
action => 'oe_invoice_from_order',
);
}

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

$self->save_and_redirect_to(
controller => 'oe.pl',
action => 'oe_invoice_from_order',
new_invoice_type => 'invoice_for_advance_payment',
);
}

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

$self->save_and_redirect_to(
controller => 'oe.pl',
action => 'oe_invoice_from_order',
new_invoice_type => 'final_invoice',
);
}

# workflows to all types of this controller
sub action_save_and_order_workflow {
$_[0]->save_and_redirect_to(
action => 'order_workflow',
type => $_[0]->type,
to_type => $::form->{to_type},
use_shipto => $::form->{use_shipto},
);
}

# workflow from purchase order to ap transaction
sub action_save_and_ap_transaction {
my ($self) = @_;

$self->save_and_redirect_to(
controller => 'ap.pl',
action => 'add_from_purchase_order',
);
}

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

$self->load_order;

my $destination_type = $::form->{to_type} ? $::form->{to_type} : '';

my $from_side = $self->order->is_sales ? 'sales' : 'purchase';
my $to_side = (any { $destination_type eq $_ } (sales_order_type(), sales_quotation_type())) ? 'sales' : 'purchase';

# check for direct delivery
# copy shipto in custom shipto (custom shipto will be copied by new_from() in case)
my $custom_shipto;
if ( $from_side eq 'sales' && $to_side eq 'purchase'
&& $::form->{use_shipto} && $self->order->shipto) {
$custom_shipto = $self->order->shipto->clone('SL::DB::Order');
}

$self->order(SL::DB::Order->new_from($self->order, destination_type => $destination_type));

# no linked records to quotations from the same side (sales -> sales or purchase -> purchase)
if ( (any { $destination_type eq $_ } (sales_quotation_type(), request_quotation_type()))
&& $from_side eq $to_side) {
delete $::form->{id};
delete $::form->{$_} for qw(converted_from_oe_id converted_from_orderitems_ids);
} else {
$self->{converted_from_oe_id} = delete $::form->{id};
}

# set item ids to new fake id, to identify them as new items
foreach my $item (@{$self->order->items_sorted}) {
$item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
}

if ($from_side eq 'sales' && $to_side eq 'purchase') {
if ($::form->{use_shipto}) {
$self->order->custom_shipto($custom_shipto) if $custom_shipto;
} else {
# remove any custom shipto if not wanted
$self->order->custom_shipto(SL::DB::Shipto->new(module => 'OE', custom_variables => []));
}
}

# change form type
$::form->{type} = $destination_type;
$self->type($self->init_type);
$self->cv ($self->init_cv);
$self->check_auth;

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

# trigger rendering values for second row as hidden, because they
# are loaded only on demand. So we need to keep the values from the
# source.
$_->{render_second_row} = 1 for @{ $self->order->items_sorted };

if (!$::form->{form_validity_token}) {
$::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_ORDER_SAVE())->token;
}

$self->render(
'order/form',
title => $self->get_title_for('edit'),
%{$self->{template_args}}
);
}

# set form elements in respect to a changed customer or vendor
#
# This action is called on an change of the customer/vendor picker.
sub action_customer_vendor_changed {
my ($self) = @_;

setup_order_from_cv($self->order);
$self->recalc();

my $cv_method = $self->cv;

if ($self->order->$cv_method->contacts && scalar @{ $self->order->$cv_method->contacts } > 0) {
$self->js->show('#cp_row');
} else {
$self->js->hide('#cp_row');
}

if ($self->order->$cv_method->shipto && scalar @{ $self->order->$cv_method->shipto } > 0) {
$self->js->show('#shipto_selection');
} else {
$self->js->hide('#shipto_selection');
}

if ($cv_method eq 'customer') {
my $show_hide = scalar @{ $self->order->customer->additional_billing_addresses } > 0 ? 'show' : 'hide';
$self->js->$show_hide('#billing_address_row');
}

$self->js->val( '#order_salesman_id', $self->order->salesman_id) if $self->order->is_sales;

$self->js
->replaceWith('#order_cp_id', $self->build_contact_select)
->replaceWith('#order_shipto_id', $self->build_shipto_select)
->replaceWith('#shipto_inputs ', $self->build_shipto_inputs)
->replaceWith('#order_billing_address_id', $self->build_billing_address_select)
->replaceWith('#business_info_row', $self->build_business_info_row)
->val( '#order_taxzone_id', $self->order->taxzone_id)
->val( '#order_taxincluded', $self->order->taxincluded)
->val( '#order_currency_id', $self->order->currency_id)
->val( '#order_payment_id', $self->order->payment_id)
->val( '#order_delivery_term_id', $self->order->delivery_term_id)
->val( '#order_intnotes', $self->order->intnotes)
->val( '#order_language_id', $self->order->$cv_method->language_id)
->focus( '#order_' . $self->cv . '_id')
->run('kivi.Order.update_exchangerate');

$self->js_redisplay_amounts_and_taxes;
$self->js_redisplay_cvpartnumbers;
$self->js->render();
}

# open the dialog for customer/vendor details
sub action_show_customer_vendor_details_dialog {
my ($self) = @_;

my $is_customer = 'customer' eq $::form->{vc};
my $cv;
if ($is_customer) {
$cv = SL::DB::Customer->new(id => $::form->{vc_id})->load;
} else {
$cv = SL::DB::Vendor->new(id => $::form->{vc_id})->load;
}

my %details = map { $_ => $cv->$_ } @{$cv->meta->columns};
$details{discount_as_percent} = $cv->discount_as_percent;
$details{creditlimt} = $cv->creditlimit_as_number;
$details{business} = $cv->business->description if $cv->business;
$details{language} = $cv->language_obj->description if $cv->language_obj;
$details{delivery_terms} = $cv->delivery_term->description if $cv->delivery_term;
$details{payment_terms} = $cv->payment->description if $cv->payment;
$details{pricegroup} = $cv->pricegroup->pricegroup if $is_customer && $cv->pricegroup;

if ($is_customer) {
foreach my $entry (@{ $cv->additional_billing_addresses }) {
push @{ $details{ADDITIONAL_BILLING_ADDRESSES} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
}
}
foreach my $entry (@{ $cv->shipto }) {
push @{ $details{SHIPTO} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
}
foreach my $entry (@{ $cv->contacts }) {
push @{ $details{CONTACTS} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
}

$_[0]->render('common/show_vc_details', { layout => 0 },
is_customer => $is_customer,
%details);

}

# called if a unit in an existing item row is changed
sub action_unit_changed {
my ($self) = @_;

my $idx = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
my $item = $self->order->items_sorted->[$idx];

my $old_unit_obj = SL::DB::Unit->new(name => $::form->{old_unit})->load;
$item->sellprice($item->unit_obj->convert_to($item->sellprice, $old_unit_obj));

$self->recalc();

$self->js
->run('kivi.Order.update_sellprice', $::form->{item_id}, $item->sellprice_as_number);
$self->js_redisplay_line_values;
$self->js_redisplay_amounts_and_taxes;
$self->js->render();
}

# update item input row when a part ist picked
sub action_update_item_input_row {
my ($self) = @_;

delete $::form->{add_item}->{$_} for qw(create_part_type sellprice_as_number discount_as_percent);

my $form_attr = $::form->{add_item};

return unless $form_attr->{parts_id};

my $record = $self->order;
my $item = SL::DB::OrderItem->new(%$form_attr);
$item->qty(1) if !$item->qty;
$item->unit($item->part->unit);

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

$self->js
->val ('#add_item_unit', $item->unit)
->val ('#add_item_description', $item->part->description)
->val ('#add_item_sellprice_as_number', '')
->attr ('#add_item_sellprice_as_number', 'placeholder', $price_src->price_as_number)
->attr ('#add_item_sellprice_as_number', 'title', $price_src->source_description)
->val ('#add_item_discount_as_percent', '')
->attr ('#add_item_discount_as_percent', 'placeholder', $discount_src->discount_as_percent)
->attr ('#add_item_discount_as_percent', 'title', $discount_src->source_description)
->render;
}

# add an item row for a new item entered in the input row
sub action_add_item {
my ($self) = @_;

delete $::form->{add_item}->{create_part_type};

my $form_attr = $::form->{add_item};

return unless $form_attr->{parts_id};

my $item = new_item($self->order, $form_attr);

$self->order->add_items($item);

$self->recalc();

$self->get_item_cvpartnumber($item);

my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
my $row_as_html = $self->p->render('order/tabs/_row',
ITEM => $item,
ID => $item_id,
SELF => $self,
);

if ($::form->{insert_before_item_id}) {
$self->js
->before ('.row_entry:has(#item_' . $::form->{insert_before_item_id} . ')', $row_as_html);
} else {
$self->js
->append('#row_table_id', $row_as_html);
}

if ( $item->part->is_assortment ) {
$form_attr->{qty_as_number} = 1 unless $form_attr->{qty_as_number};
foreach my $assortment_item ( @{$item->part->assortment_items} ) {
my $attr = { parts_id => $assortment_item->parts_id,
qty => $assortment_item->qty * $::form->parse_amount(\%::myconfig, $form_attr->{qty_as_number}), # TODO $form_attr->{unit}
unit => $assortment_item->unit,
description => $assortment_item->part->description,
};
my $item = new_item($self->order, $attr);

# set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
$item->discount(1) unless $assortment_item->charge;

$self->order->add_items( $item );
$self->recalc();
$self->get_item_cvpartnumber($item);
my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
my $row_as_html = $self->p->render('order/tabs/_row',
ITEM => $item,
ID => $item_id,
SELF => $self,
);
if ($::form->{insert_before_item_id}) {
$self->js
->before ('.row_entry:has(#item_' . $::form->{insert_before_item_id} . ')', $row_as_html);
} else {
$self->js
->append('#row_table_id', $row_as_html);
}
};
};

$self->js
->val('.add_item_input', '')
->attr('.add_item_input', 'placeholder', '')
->attr('.add_item_input', 'title', '')
->attr('#add_item_qty_as_number', 'placeholder', '1')
->run('kivi.Order.init_row_handlers')
->run('kivi.Order.renumber_positions')
->focus('#add_item_parts_id_name');

$self->js->run('kivi.Order.row_table_scroll_down') if !$::form->{insert_before_item_id};

$self->js_redisplay_amounts_and_taxes;
$self->js->render();
}

# add item rows for multiple items at once
sub action_add_multi_items {
my ($self) = @_;

my @form_attr = grep { $_->{qty_as_number} } @{ $::form->{add_items} };
return $self->js->render() unless scalar @form_attr;

my @items;
foreach my $attr (@form_attr) {
my $item = new_item($self->order, $attr);
push @items, $item;
if ( $item->part->is_assortment ) {
foreach my $assortment_item ( @{$item->part->assortment_items} ) {
my $attr = { parts_id => $assortment_item->parts_id,
qty => $assortment_item->qty * $item->qty, # TODO $form_attr->{unit}
unit => $assortment_item->unit,
description => $assortment_item->part->description,
};
my $item = new_item($self->order, $attr);

# set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
$item->discount(1) unless $assortment_item->charge;
push @items, $item;
}
}
}
$self->order->add_items(@items);

$self->recalc();

foreach my $item (@items) {
$self->get_item_cvpartnumber($item);
my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
my $row_as_html = $self->p->render('order/tabs/_row',
ITEM => $item,
ID => $item_id,
SELF => $self,
);

if ($::form->{insert_before_item_id}) {
$self->js
->before ('.row_entry:has(#item_' . $::form->{insert_before_item_id} . ')', $row_as_html);
} else {
$self->js
->append('#row_table_id', $row_as_html);
}
}

$self->js
->run('kivi.Part.close_picker_dialogs')
->run('kivi.Order.init_row_handlers')
->run('kivi.Order.renumber_positions')
->focus('#add_item_parts_id_name');

$self->js->run('kivi.Order.row_table_scroll_down') if !$::form->{insert_before_item_id};

$self->js_redisplay_amounts_and_taxes;
$self->js->render();
}

# recalculate all linetotals, amounts and taxes and redisplay them
sub action_recalc_amounts_and_taxes {
my ($self) = @_;

$self->recalc();

$self->js_redisplay_line_values;
$self->js_redisplay_amounts_and_taxes;
$self->js->render();
}

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

my $data = {
is_standard => $self->order->currency_id == $::instance_conf->get_currency_id,
currency_name => $self->order->currency->name,
exchangerate => $self->order->daily_exchangerate_as_null_number,
};

$self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
}

# redisplay item rows if they are sorted by an attribute
sub action_reorder_items {
my ($self) = @_;

my %sort_keys = (
partnumber => sub { $_[0]->part->partnumber },
description => sub { $_[0]->description },
qty => sub { $_[0]->qty },
sellprice => sub { $_[0]->sellprice },
discount => sub { $_[0]->discount },
cvpartnumber => sub { $_[0]->{cvpartnumber} },
);

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

my $method = $sort_keys{$::form->{order_by}};
my @to_sort = map { { old_pos => $_->position, order_by => $method->($_) } } @{ $self->order->items_sorted };
if ($::form->{sort_dir}) {
if ( $::form->{order_by} =~ m/qty|sellprice|discount/ ){
@to_sort = sort { $a->{order_by} <=> $b->{order_by} } @to_sort;
} else {
@to_sort = sort { $a->{order_by} cmp $b->{order_by} } @to_sort;
}
} else {
if ( $::form->{order_by} =~ m/qty|sellprice|discount/ ){
@to_sort = sort { $b->{order_by} <=> $a->{order_by} } @to_sort;
} else {
@to_sort = sort { $b->{order_by} cmp $a->{order_by} } @to_sort;
}
}
$self->js
->run('kivi.Order.redisplay_items', \@to_sort)
->render;
}

# show the popup to choose a price/discount source
sub action_price_popup {
my ($self) = @_;

my $idx = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
my $item = $self->order->items_sorted->[$idx];

$self->render_price_dialog($item);
}

# save the order in a session variable and redirect to the part controller
sub action_create_part {
my ($self) = @_;

my $previousform = $::auth->save_form_in_session(non_scalars => 1);

my $callback = $self->url_for(
action => 'return_from_create_part',
type => $self->type, # type is needed for check_auth on return
previousform => $previousform,
);

flash_later('info', t8('You are adding a new part while you are editing another document. You will be redirected to your document when saving the new part or aborting this form.'));

my @redirect_params = (
controller => 'Part',
action => 'add',
part_type => $::form->{add_item}->{create_part_type},
callback => $callback,
inline_create => 1,
);

$self->redirect_to(@redirect_params);
}

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

$self->{created_part} = SL::DB::Part->new(id => delete $::form->{new_parts_id})->load if $::form->{new_parts_id};

$::auth->restore_form_from_session(delete $::form->{previousform});

# set item ids to new fake id, to identify them as new items
foreach my $item (@{$self->order->items_sorted}) {
$item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
}

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

# trigger rendering values for second row/longdescription as hidden,
# because they are loaded only on demand. So we need to keep the values
# from the source.
$_->{render_second_row} = 1 for @{ $self->order->items_sorted };
$_->{render_longdescription} = 1 for @{ $self->order->items_sorted };

$self->render(
'order/form',
title => $self->get_title_for('edit'),
%{$self->{template_args}}
);

}

# load the second row for one or more items
#
# This action gets the html code for all items second rows by rendering a template for
# the second row and sets the html code via client js.
sub action_load_second_rows {
my ($self) = @_;

$self->recalc() if $self->order->is_sales; # for margin calculation

foreach my $item_id (@{ $::form->{item_ids} }) {
my $idx = first_index { $_ eq $item_id } @{ $::form->{orderitem_ids} };
my $item = $self->order->items_sorted->[$idx];

$self->js_load_second_row($item, $item_id, 0);
}

$self->js->run('kivi.Order.init_row_handlers') if $self->order->is_sales; # for lastcosts change-callback

$self->js->render();
}

# update description, notes and sellprice from master data
sub action_update_row_from_master_data {
my ($self) = @_;

foreach my $item_id (@{ $::form->{item_ids} }) {
my $idx = first_index { $_ eq $item_id } @{ $::form->{orderitem_ids} };
my $item = $self->order->items_sorted->[$idx];
my $texts = get_part_texts($item->part, $self->order->language_id);

$item->description($texts->{description});
$item->longdescription($texts->{longdescription});

my ($price_src, $discount_src) = get_best_price_and_discount_source($self->order, $item, 1);

$item->sellprice($price_src->price);
$item->active_price_source($price_src);
$item->discount($discount_src->discount);
$item->active_discount_source($discount_src);

my $price_editable = $self->order->is_sales ? $::auth->assert('sales_edit_prices', 1) : $::auth->assert('purchase_edit_prices', 1);

$self->js
->run('kivi.Order.set_price_and_source_text', $item_id, $price_src ->source, $price_src ->source_description, $item->sellprice_as_number, $price_editable)
->run('kivi.Order.set_discount_and_source_text', $item_id, $discount_src->source, $discount_src->source_description, $item->discount_as_percent, $price_editable)
->html('.row_entry:has(#item_' . $item_id . ') [name = "partnumber"] a', $item->part->partnumber)
->val ('.row_entry:has(#item_' . $item_id . ') [name = "order.orderitems[].description"]', $item->description)
->val ('.row_entry:has(#item_' . $item_id . ') [name = "order.orderitems[].longdescription"]', $item->longdescription);

if ($self->search_cvpartnumber) {
$self->get_item_cvpartnumber($item);
$self->js->html('.row_entry:has(#item_' . $item_id . ') [name = "cvpartnumber"]', $item->{cvpartnumber});
}
}

$self->recalc();
$self->js_redisplay_line_values;
$self->js_redisplay_amounts_and_taxes;

$self->js->render();
}

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

if (!$::form->{phone_note}->{subject} || !$::form->{phone_note}->{body}) {
return $self->js->flash('error', t8('Phone note needs a subject and a body.'))->render;
}

my $phone_note;
if ($::form->{phone_note}->{id}) {
$phone_note = first { $_->id == $::form->{phone_note}->{id} } @{$self->order->phone_notes};
return $self->js->flash('error', t8('Phone note not found for this order.'))->render 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);

$phone_note->save;
$self->order(SL::DB::Order->new(id => $self->order->id)->load);

my $tab_as_html = $self->p->render('order/tabs/phone_notes', SELF => $self);

return $self->js
->replaceWith('#phone-notes', $tab_as_html)
->html('#num_phone_notes', (scalar @{$self->order->phone_notes}) ? ' (' . scalar @{$self->order->phone_notes} . ')' : '')
->flash('info', $is_new ? t8('Phone note has been created.') : t8('Phone note has been updated.'))
->reinit_widgets
->render;
}

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

my $phone_note = first { $_->id == $::form->{phone_note}->{id} } @{$self->order->phone_notes};

return $self->js->flash('error', t8('Phone note not found for this order.'))->render if !$phone_note;

$phone_note->delete;
$self->order(SL::DB::Order->new(id => $self->order->id)->load);

my $tab_as_html = $self->p->render('order/tabs/phone_notes', SELF => $self);

return $self->js
->replaceWith('#phone-notes', $tab_as_html)
->html('#num_phone_notes', (scalar @{$self->order->phone_notes}) ? ' (' . scalar @{$self->order->phone_notes} . ')' : '')
->flash('info', t8('Phone note has been deleted.'))
->reinit_widgets
->render;
}

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

my @redirect_params = $::form->{callback} ? ($::form->{callback})
: (controller => 'LoginScreen', action => 'user_login');

if (!$::form->{ids} || !@{$::form->{ids}}) {
flash_later('info', t8('Nothing selected!'));
$self->redirect_to(@redirect_params);
$::dispatcher->end_request;
}

my $sales_quotations = SL::DB::Manager::Order->get_all(where => [id => $::form->{ids},
or => [closed => 0, closed => undef],
quotation => 1,
'!customer_id' => undef]);

my $request_quotations = SL::DB::Manager::Order->get_all(where => [id => $::form->{ids},
or => [closed => 0, closed => undef],
quotation => 1,
'!vendor_id' => undef]);

$::auth->assert('sales_quotation_edit') if scalar @$sales_quotations;
$::auth->assert('request_quotation_edit') if scalar @$request_quotations;

my $employee_id = SL::DB::Manager::Employee->current->id;
SL::DB->client->with_transaction(sub {
SL::DB::Manager::Order->update_all(set => {closed => 1},
where => [id => $::form->{ids}]);

foreach my $quotation (@$sales_quotations, @$request_quotations) {
SL::DB::History->new(
trans_id => $quotation->id,
employee_id => $employee_id,
what_done => $quotation->type,
snumbers => 'quonumber_' . $quotation->number,
addition => 'SAVED',
)->save;
}

1;
}) || do {
$::form->error(t8('Closing the selected quotations failed: #1', SL::DB->client->error));
};

flash_later('info', t8('The selected quotations where closed.'));
$self->redirect_to(@redirect_params);
}

sub js_load_second_row {
my ($self, $item, $item_id, $do_parse) = @_;

if ($do_parse) {
# Parse values from form (they are formated while rendering (template)).
# Workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
# This parsing is not necessary at all, if we assure that the second row/cvars are only loaded once.
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;
}

my $row_as_html = $self->p->render('order/tabs/_second_row', ITEM => $item, TYPE => $self->type);

$self->js
->html('#second_row_' . $item_id, $row_as_html)
->data('#second_row_' . $item_id, 'loaded', 1);
}

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

my $is_sales = $self->order->is_sales;

# sales orders with margins
my @data;
if ($is_sales) {
@data = map {
[
$::form->format_amount(\%::myconfig, $_->{linetotal}, 2, 0),
$::form->format_amount(\%::myconfig, $_->{marge_total}, 2, 0),
$::form->format_amount(\%::myconfig, $_->{marge_percent}, 2, 0),
]} @{ $self->order->items_sorted };
} else {
@data = map {
[
$::form->format_amount(\%::myconfig, $_->{linetotal}, 2, 0),
]} @{ $self->order->items_sorted };
}

$self->js
->run('kivi.Order.redisplay_line_values', $is_sales, \@data);
}

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

if (scalar @{ $self->{taxes} }) {
$self->js->show('#taxincluded_row_id');
} else {
$self->js->hide('#taxincluded_row_id');
}

if ($self->order->taxincluded) {
$self->js->hide('#subtotal_row_id');
} else {
$self->js->show('#subtotal_row_id');
}

if ($self->order->is_sales) {
my $is_neg = $self->order->marge_total < 0;
$self->js
->html('#marge_total_id', $::form->format_amount(\%::myconfig, $self->order->marge_total, 2))
->html('#marge_percent_id', $::form->format_amount(\%::myconfig, $self->order->marge_percent, 2))
->action_if( $is_neg, 'addClass', '#marge_total_id', 'plus0')
->action_if( $is_neg, 'addClass', '#marge_percent_id', 'plus0')
->action_if( $is_neg, 'addClass', '#marge_percent_sign_id', 'plus0')
->action_if(!$is_neg, 'removeClass', '#marge_total_id', 'plus0')
->action_if(!$is_neg, 'removeClass', '#marge_percent_id', 'plus0')
->action_if(!$is_neg, 'removeClass', '#marge_percent_sign_id', 'plus0');
}

$self->js
->html('#netamount_id', $::form->format_amount(\%::myconfig, $self->order->netamount, -2))
->html('#amount_id', $::form->format_amount(\%::myconfig, $self->order->amount, -2))
->remove('.tax_row')
->insertBefore($self->build_tax_rows, '#amount_row_id');
}

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

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

my @data = map {[$_->{cvpartnumber}]} @{ $self->order->items_sorted };

$self->js
->run('kivi.Order.redisplay_cvpartnumbers', \@data);
}

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

$self->js
->val('#id', $self->order->id)
->val('#converted_from_oe_id', '')
->val('#converted_from_reclamation_id', '')
->val('#order_' . $self->nr_key(), $self->order->number);

my $idx = 0;
foreach my $form_item_id (@{ $::form->{orderitem_ids} }) {
next if !$self->order->items_sorted->[$idx]->id;
next if $form_item_id !~ m{^new};
$self->js