Projekt

Allgemein

Profil

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

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

use SL::Helper::Flash qw(flash 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::IMAPClient;
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::OrderItem;
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::Shipto;
use SL::DB::Translation;
use SL::DB::EmailJournal;
use SL::DB::ValidityToken;
use SL::DB::Helper::RecordLink qw(set_record_link_conversions RECORD_ID RECORD_TYPE_REF RECORD_ITEM_ID RECORD_ITEM_TYPE_REF);
use SL::DB::Helper::TypeDataProxy;
use SL::DB::Helper::Record qw(get_object_name_from_type get_class_from_type);
use SL::Model::Record;
use SL::DB::Order::TypeData qw(:types);
use SL::DB::DeliveryOrder::TypeData qw(:types);
use SL::DB::Reclamation::TypeData qw(:types);

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(uniq 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 type_data) ],
);


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

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

#
# actions
#

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

$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->type_data->text('add'),
%{$self->{template_args}}
);
}

sub action_add_from_record {
my ($self) = @_;
my $from_type = $::form->{from_type};
my $from_id = $::form->{from_id};

die "No 'from_type' was given." unless ($from_type);
die "No 'from_id' was given." unless ($from_id);

my %flags = ();
if (defined($::form->{from_item_ids})) {
my %use_item = map { $_ => 1 } @{$::form->{from_item_ids}};
$flags{item_filter} = sub {
my ($item) = @_;
return %use_item{$item->{RECORD_ITEM_ID()}};
}
}

my $record = SL::Model::Record->get_record($from_type, $from_id);
my $order = SL::Model::Record->new_from_workflow($record, $self->type, %flags);
$self->order($order);

$self->reinit_after_new_order();

$self->action_add();
}

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

my $basket_item_ids = $::form->{basket_item_ids} || [];
my $vendor_item_ids = $::form->{vendor_item_ids} || [];
my $vendor_id = $::form->{vendor_id};


unless (scalar @{ $basket_item_ids} || scalar @{ $vendor_item_ids}) {
$self->js->flash('error', t8('There are no items selected'));
return $self->js->render();
}

my $order = SL::DB::Order->create_from_purchase_basket(
$basket_item_ids, $vendor_item_ids, $vendor_id
);

$self->order($order);

$self->reinit_after_new_order();

$self->action_add();
}

sub action_add_from_email_journal {
my ($self) = @_;
die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});

$self->action_add();
}

sub action_edit_with_email_journal_workflow {
my ($self) = @_;
die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
$::form->{workflow_email_journal_id} = delete $::form->{email_journal_id};
$::form->{workflow_email_attachment_id} = delete $::form->{email_attachment_id};
$::form->{workflow_email_callback} = delete $::form->{callback};

$self->action_edit();
}

# edit an existing order
sub action_edit {
my ($self) = @_;
die "No 'id' was given." unless $::form->{id};

$self->load_order;

if ($self->order->is_sales && $::lx_office_conf{imap_client}->{enabled}) {
my $imap_client = SL::IMAPClient->new(%{$::lx_office_conf{imap_client}});
if ($imap_client) {
$imap_client->update_email_files_for_record(record => $self->order);
}
}

$self->pre_render();
$self->render(
'order/form',
title => $self->type_data->text('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;
my $target_type = SALES_ORDER_TYPE();
my $order = SL::Model::Record->new_from_workflow_multi(\@multi_orders, $target_type, sort_sources_by => 'transdate');
$self->order($order);
$self->reinit_after_new_order();

$self->action_add();
}

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

SL::Model::Record->delete($self->order);
my $text = $self->type eq SALES_ORDER_INTAKE_TYPE() ? $::locale->text('The order intake has been deleted')
: $self->type eq SALES_ORDER_TYPE() ? $::locale->text('The order confirmation has been deleted')
: $self->type eq PURCHASE_ORDER_TYPE() ? $::locale->text('The order has been deleted')
: $self->type eq PURCHASE_ORDER_CONFIRMATION_TYPE() ? $::locale->text('The order confirmation 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')
: $self->type eq PURCHASE_QUOTATION_INTAKE_TYPE() ? $::locale->text('The quotation intake 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) = @_;

$self->save();

flash_later('info', $self->type_data->text('saved'));

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) = @_;

SL::DB->client->with_transaction(
sub {
SL::Model::Record->increment_subversion($self->order);
$self->save();
1;
}
);

$self->redirect_to(action => 'edit',
type => $self->type,
id => $self->order->id,
);
}

# 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();
}

my $saved_order = SL::DB::Order->new(id => $order->id)->load;

# Create new record from current one
my $new_order = SL::Model::Record->clone_for_save_as_new($saved_order, $order);
$self->order($new_order);

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

# Warn on order locked items if they are not wanted for this record type
if ($self->type_data->no_order_locked_parts) {
my @order_locked_positions = map { $_->position } grep { $_->part->order_locked } @{ $self->order->items_sorted };
flash_later('warning', t8('This record contains not orderable items at position #1', join ', ', @order_locked_positions)) if @order_locked_positions;
}

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) = @_;

$self->save();

$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 <"Order.pm.html#L428" data-txt="428">

# 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) {
$self->save();
$self->js_reset_order_and_item_ids_after_save;
}

my $cv = $self->order->customervendor
or return $self->js->flash('error',
$self->type_data->properties('is_customer') ?
t8('Cannot send E-mail without customer given')
: t8('Cannot send E-mail without vendor given')
)->render($self);

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;

my $email_form;
$email_form->{to} =
($self->order->contact ? $self->order->contact->cp_email : undef)
|| $cv->email;
$email_form->{cc} = $cv->cc;
$email_form->{bcc} = join ', ', grep $_, $cv->bcc;
# Todo: get addresses from shipto, if any
$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 $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->type_data->properties('is_customer'),
ALL_EMPLOYEES => \@employees_with_email,
ALL_PARTNER_EMAIL_ADDRESSES => $cv->get_all_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) {
eval {
$self->save();
1;
} or do {
$self->js->run('kivi.Order.close_email_dialog');
die $EVAL_ERROR;
};
}

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 record 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;
};

# move $::form->{email_form} to $::form
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,
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.'));
$self->save_history('MAILED');

# 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')
->
}

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 || 1), # TODO $item->unit
unit => $assortment_item->unit,
description => $assortment_item->part->description,
};
my $item = new_item($self->order, $attr);

only_if => $self->type_data->show_menu('save_and_sales_delivery_order'),
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
],
action => [
t8('Save and Purchase Delivery Order'),
call => [ 'kivi.Order.save', {
action => 'save_and_new_record',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts,
warn_on_reqdate => $::instance_conf->get_order_warn_no_deliverydate,
form_params => [
{ name => 'to_type', value => PURCHASE_DELIVERY_ORDER_TYPE() },
],
}],
checks => [ 'kivi.Order.check_save_active_periodic_invoices',
@req_trans_cost_art, @req_cusordnumber,
],
only_if => $self->type_data->show_menu('save_and_purchase_delivery_order'),
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
],
action => [
t8('Save and Purchase Delivery Order with item selection'),
call => [
'kivi.Order.show_purchase_delivery_order_select_items', {
action => 'save_and_new_record',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts,
warn_on_reqdate => $::instance_conf->get_order_warn_no_deliverydate,
form_params => [
{ name => 'to_type', value => PURCHASE_DELIVERY_ORDER_TYPE() },
],
}],
checks => [ @req_trans_cost_art, @req_cusordnumber ],
only_if => $self->type_data->show_menu('save_and_purchase_delivery_order'),
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_new_record',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts,
warn_on_reqdate => $::instance_conf->get_order_warn_no_deliverydate,
form_params => [
{ name => 'to_type', value => SUPPLIER_DELIVERY_ORDER_TYPE() },
],
}],
checks => [ 'kivi.Order.check_save_active_periodic_invoices',
@req_trans_cost_art, @req_cusordnumber,
],
only_if => $self->type_data->show_menu('save_and_supplier_delivery_order'),
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_new_record',
warn_on_duplicates => $::instance_conf->get_order_warn_duplicate_parts,
warn_on_reqdate => $::instance_conf->get_order_warn_no_deliverydate,
form_params => [
{ name => 'to_type',
value => $self->order->is_sales ? SALES_RECLAMATION_TYPE()
: PURCHASE_RECLAMATION_TYPE() },
],
}],
only_if => $self->type_data->show_menu('save_and_reclamation'),
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
],
action => [
t8('Save and Invoice'),
call => [ 'kivi.Order.save', {
action => 'save_and_invoice',
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,
],
disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
only_if => $self->type_data->show_menu('save_and_invoice'),
],
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 => $self->type_data->show_menu('save_and_invoice_for_advance_payment'),
],
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 => $self->type_data->show_menu('save_and_final_invoice') && $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 => $self->type_data->show_menu('save_and_ap_transaction'),
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,
only_if => $self->type_data->show_menu('save_and_print'),
],
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,
only_if => $self->type_data->show_menu('save_and_print'),
],
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,
only_if => $self->type_data->show_menu('save_and_email'),
],
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 => $self->type_data->show_menu('delete'),
],

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_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 nr_key {
my ($self) = @_;

return $self->type_data->properties('nr_key');
}

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

$self->save();

flash_later('info', $self->type_data->text('saved'));

$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',