1 package SL::Controller::Order;
4 use parent qw(SL::Controller::Base);
9 use SL::Locale::String;
10 use SL::SessionFile::Random;
22 use SL::Helper::DateTime;
23 use SL::Helper::CreatePDF qw(:all);
25 use List::Util qw(max first);
26 use List::MoreUtils qw(none pairwise);
27 use English qw(-no_match_vars);
29 use Rose::Object::MakeMethods::Generic
31 'scalar --get_set_init' => [ qw(order valid_types type cv js p) ],
36 __PACKAGE__->run_before('_check_auth');
38 __PACKAGE__->run_before('_recalc',
39 only => [ qw(edit update save create_pdf) ]);
49 $self->order->transdate(DateTime->now_local());
54 title => $self->type eq _sales_order_type() ? $::locale->text('Add Sales Order')
55 : $self->type eq _purchase_order_type() ? $::locale->text('Add Purchase Order')
57 %{$self->{template_args}}
67 title => $self->type eq _sales_order_type() ? $::locale->text('Edit Sales Order')
68 : $self->type eq _purchase_order_type() ? $::locale->text('Edit Purchase Order')
70 %{$self->{template_args}}
80 title => $self->type eq _sales_order_type() ? $::locale->text('Edit Sales Order')
81 : $self->type eq _purchase_order_type() ? $::locale->text('Edit Purchase Order')
83 %{$self->{template_args}}
90 my $errors = $self->_save();
92 if (scalar @{ $errors }) {
93 $self->js->flash('error', $_) foreach @{ $errors };
94 return $self->js->render($self);
97 flash_later('info', $::locale->text('The order has been saved'));
98 my @redirect_params = (
101 id => $self->order->id,
104 $self->redirect_to(@redirect_params);
107 sub action_create_pdf {
110 my $print_form = Form->new('');
111 $print_form->{type} = 'sales_order';
112 $print_form->{formname} = 'sales_order',
113 $print_form->{format} = 'pdf',
114 $print_form->{media} = 'file';
116 $self->order->flatten_to_form($print_form, format_amounts => 1);
120 $print_form->throw_on_error(sub {
122 $print_form->prepare_for_printing;
124 $pdf = SL::Helper::CreatePDF->create_pdf(
125 template => SL::Helper::CreatePDF->find_template(name => $print_form->{formname}),
126 variables => $print_form,
129 } || push @errors, ref($EVAL_ERROR) eq 'SL::X::FormError' ? $EVAL_ERROR->getMessage : $EVAL_ERROR;
132 if (scalar @errors) {
133 return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render($self);
136 my $sfile = SL::SessionFile::Random->new(mode => "w");
137 $sfile->fh->print($pdf);
140 my $tmp_filename = $sfile->file_name;
141 my $pdf_filename = t8('Sales Order') . '_' . $self->order->ordnumber . '.pdf';
144 ->run('download_pdf', $tmp_filename, $pdf_filename)
145 ->flash('info', t8('The PDF has been created'))->render($self);
148 sub action_download_pdf {
151 return $self->send_file(
152 $::form->{tmp_filename},
153 type => 'application/pdf',
154 name => $::form->{pdf_filename},
158 sub action_customer_vendor_changed {
161 if ($self->cv eq 'customer') {
162 $self->order->customer(SL::DB::Manager::Customer->find_by_or_create(id => $::form->{cv_id}));
164 } elsif ($self->cv eq 'vendor') {
165 $self->order->vendor(SL::DB::Manager::Vendor->find_by_or_create(id => $::form->{cv_id}));
168 if ($self->order->{$self->cv}->contacts && scalar @{ $self->order->{$self->cv}->contacts } > 0) {
169 $self->js->show('#cp_row');
171 $self->js->hide('#cp_row');
174 if ($self->order->{$self->cv}->shipto && scalar @{ $self->order->{$self->cv}->shipto } > 0) {
175 $self->js->show('#shipto_row');
177 $self->js->hide('#shipto_row');
181 ->replaceWith('#order_cp_id', $self->build_contact_select)
182 ->replaceWith('#order_shipto_id', $self->build_shipto_select)
183 ->val('#order_taxzone_id', $self->order->{$self->cv}->taxzone_id)
184 ->focus('#order_' . $self->cv . '_id')
188 sub action_add_item {
191 my $form_attr = $::form->{add_item};
193 return unless $form_attr->{parts_id};
195 my $item = SL::DB::OrderItem->new;
196 $item->assign_attributes(%$form_attr);
198 my $part = SL::DB::Part->new(id => $form_attr->{parts_id})->load;
199 my $cv_method = $self->cv;
200 my $cv_discount = $self->order->$cv_method? $self->order->$cv_method->discount : 0.0;
203 $new_attr{part} = $part;
204 $new_attr{description} = $part->description if ! $item->description;
205 $new_attr{qty} = 1.0 if ! $item->qty;
206 $new_attr{unit} = $part->unit;
207 $new_attr{sellprice} = $part->sellprice if ! $item->sellprice;
208 $new_attr{discount} = $cv_discount if ! $item->discount;
210 # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
211 # they cannot be retrieved via custom_variables until the order/orderitem is
212 # saved. Adding empty custom_variables to new orderitem here solves this problem.
213 $new_attr{custom_variables} = [];
215 $item->assign_attributes(%new_attr);
217 $self->order->add_items($item);
221 my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
222 my $row_as_html = $self->p->render('order/tabs/_row', ITEM => $item, ID => $item_id);
225 ->append('#row_table_id', $row_as_html)
226 ->val('#add_item_parts_id', '')
227 ->val('#add_item_parts_id_name', '')
228 ->val('#add_item_description', '')
229 ->val('#add_item_qty_as_number', '')
230 ->val('#add_item_sellprice_as_number', '')
231 ->val('#add_item_discount_as_percent', '')
232 ->run('row_table_scroll_down')
233 ->run('row_set_keyboard_events_by_id', $item_id)
234 ->on('.recalc', 'change', 'recalc_amounts_and_taxes')
235 ->focus('#add_item_parts_id_name');
237 $self->_js_redisplay_amounts_and_taxes;
238 $self->js->render($self);
241 sub action_recalc_amounts_and_taxes {
246 $self->_js_redisplay_linetotals;
247 $self->_js_redisplay_amounts_and_taxes;
248 $self->js->render($self);
251 sub _js_redisplay_linetotals {
254 my @data = map {$::form->format_amount(\%::myconfig, $_->{linetotal}, 2, 0)} @{ $self->order->items };
256 ->run('redisplay_linetotals', \@data);
259 sub _js_redisplay_amounts_and_taxes {
263 ->html('#netamount_id', $::form->format_amount(\%::myconfig, $self->order->netamount, -2))
264 ->html('#amount_id', $::form->format_amount(\%::myconfig, $self->order->amount, -2))
266 ->insertBefore($self->build_tax_rows, '#amount_row_id');
273 sub init_valid_types {
274 [ _sales_order_type(), _purchase_order_type() ];
280 if (none { $::form->{type} eq $_ } @{$self->valid_types}) {
281 die "Not a valid type for order";
284 $self->type($::form->{type});
290 my $cv = $self->type eq _sales_order_type() ? 'customer'
291 : $self->type eq _purchase_order_type() ? 'vendor'
292 : die "Not a valid type for order";
312 my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
314 my $right = $right_for->{ $self->type };
315 $right ||= 'DOES_NOT_EXIST';
317 $::auth->assert($right);
320 sub build_contact_select {
323 $self->p->select_tag('order.cp_id', [ $self->order->{$self->cv}->contacts ],
324 value_key => 'cp_id',
325 title_key => 'full_name_dep',
326 default => $self->order->cp_id,
328 style => 'width: 300px',
332 sub build_shipto_select {
335 $self->p->select_tag('order.shipto_id', [ $self->order->{$self->cv}->shipto ],
336 value_key => 'shipto_id',
337 title_key => 'displayable_id',
338 default => $self->order->shipto_id,
340 style => 'width: 300px',
348 foreach my $tax (@{ $self->{taxes} }) {
349 $rows_as_html .= $self->p->render('order/tabs/_tax_row', TAX => $tax);
351 return $rows_as_html;
358 # add_items adds items to an order with no items for saving, but they cannot
359 # be retrieved via items until the order is saved. Adding empty items to new
360 # order here solves this problem.
362 $order = SL::DB::Manager::Order->find_by(id => $::form->{id}) if $::form->{id};
363 $order ||= SL::DB::Order->new(orderitems => []);
365 $order->assign_attributes(%{$::form->{order}});
374 # bb: todo: currency later
375 $self->order->currency_id($::instance_conf->get_currency_id());
377 my %pat = $self->order->calculate_prices_and_taxes();
379 foreach my $tax_chart_id (keys %{ $pat{taxes} }) {
380 my $tax = SL::DB::Manager::Tax->find_by(chart_id => $tax_chart_id);
381 push(@{ $self->{taxes} }, { amount => $pat{taxes}->{$tax_chart_id},
385 pairwise { $a->{linetotal} = $b->{linetotal} } @{$self->order->items}, @{$pat{items}};
391 # autovivify all cvars that are not in the form (cvars_by_config can do it)
392 foreach my $item (@{ $self->order->items }) {
393 $item->cvars_by_config;
397 my $db = $self->order->db;
401 $self->order->save();
402 }) || push(@{$errors}, $db->error);
411 $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
412 $self->{all_employees} = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->employee_id,
415 $self->{all_projects} = SL::DB::Manager::Project->get_all(where => [ or => [ id => $self->order->globalproject_id,
417 sort_by => 'projectnumber');
418 $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all_sorted();
419 $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
421 $self->{current_employee_id} = SL::DB::Manager::Employee->current->id;
423 $::request->{layout}->use_javascript("${_}.js") for qw(ckeditor/ckeditor ckeditor/adapters/jquery);
426 sub _sales_order_type {
430 sub _purchase_order_type {