1 package SL::Controller::RequirementSpecOrder;
 
   6 use parent qw(SL::Controller::Base);
 
   8 use List::MoreUtils qw(uniq);
 
   9 use List::Util qw(first);
 
  15 use SL::DB::RequirementSpec;
 
  16 use SL::DB::RequirementSpecOrder;
 
  17 use SL::Helper::Flash;
 
  18 use SL::Locale::String;
 
  20 use constant LIST_SELECTOR  => '#quotations_and_orders';
 
  21 use constant FORMS_SELECTOR => '#quotations_and_orders_article_assignment,#quotations_and_orders_new,#quotations_and_orders_update';
 
  23 use Rose::Object::MakeMethods::Generic
 
  25   scalar                  => [ qw(parts) ],
 
  26   'scalar --get_set_init' => [ qw(requirement_spec rs_order js h_unit_name all_customers all_parts_time_unit section_order_part) ],
 
  29 __PACKAGE__->run_before('setup');
 
  38   $self->render('requirement_spec_order/list', { layout => 0 });
 
  44   if (!@{ $self->all_parts_time_unit }) {
 
  45     return $self->js->flash('error', t8('This function requires the presence of articles with a time-based unit such as "h" or "min".'))->render($self);
 
  48   my $html = $self->render('requirement_spec_order/new', { output => 0 }, make_part_title => sub { $_[0]->partnumber . ' ' . $_[0]->description });
 
  49   $self->js->hide(LIST_SELECTOR())
 
  50            ->after(LIST_SELECTOR(), $html)
 
  57   if (!$::auth->assert($::form->{quotation} ? 'sales_quotation_edit' : 'sales_order_edit', 1)) {
 
  58     return $self->js->flash('error', t8("You do not have the permissions to access this function."))->render($self);
 
  61   # 1. Update sections with selected part IDs.
 
  62   my $section_attrs  = $::form->{sections} || [];
 
  63   my $sections       = SL::DB::Manager::RequirementSpecItem->get_all_sorted(where => [ id => [ map { $_->{id} } @{ $section_attrs } ] ]);
 
  64   my %sections_by_id = map { ($_->{id} => $_) } @{ $sections };
 
  66   $sections_by_id{ $_->{id} }->update_attributes(order_part_id => $_->{order_part_id}) for @{ $section_attrs };
 
  68   # 2. Create actual quotation/order.
 
  69   my $order = $self->create_order(sections => $sections, additional_parts => $self->requirement_spec->parts_sorted);
 
  70   $order->db->with_transaction(sub {
 
  73     $self->requirement_spec->add_orders(SL::DB::RequirementSpecOrder->new(order => $order, version => $self->requirement_spec->version));
 
  74     $self->requirement_spec->save;
 
  76     $self->requirement_spec->link_to_record($order);
 
  78     $::lxdebug->message(LXDebug::WARN(), "Error creating the order object: $@");
 
  81   $self->init_requirement_spec;
 
  83   # 3. Notify the user and return to list.
 
  84   my $html = $self->render('requirement_spec_order/list', { output => 0 });
 
  85   $self->js->replaceWith(LIST_SELECTOR(), $html)
 
  86            ->remove(FORMS_SELECTOR())
 
  87            ->flash('info', $::form->{quotation} ? t8('Sales quotation #1 has been created.', $order->quonumber) : t8('Sales order #1 has been created.', $order->ordnumber))
 
  94   my $order    = $self->rs_order->order;
 
  95   my $sections = $self->requirement_spec->sections_sorted;
 
  97   if (!$::auth->assert($order->quotation ? 'sales_quotation_edit' : 'sales_order_edit', 1)) {
 
  98     return $self->js->flash('error', t8("You do not have the permissions to access this function."))->render($self);
 
 101   my (@orderitems, %sections_seen);
 
 102   foreach my $item (@{ $order->items_sorted }) {
 
 103     my $section = first { my $num = $_->fb_number; $item->description =~ m{\b\Q${num}\E\b} && !$sections_seen{ $_->id } } @{ $sections };
 
 105     $sections_seen{ $section->id } = 1 if $section;
 
 107     push @orderitems, { item => $item, section => $section };
 
 110   my $html = $self->render(
 
 111     'requirement_spec_order/update', { output => 0 },
 
 112     orderitems         => \@orderitems,
 
 113     sections           => $sections,
 
 114     make_section_title => sub { $_[0]->fb_number . ' ' . $_[0]->title },
 
 117   $self->js->hide(LIST_SELECTOR())
 
 118            ->after(LIST_SELECTOR(), $html)
 
 122 sub action_do_update {
 
 125   my $order          = $self->rs_order->order;
 
 126   my @new_orderitems =  $self->do_update_sections;
 
 127   push @new_orderitems, $self->do_update_additional_parts;
 
 129   $order->add_orderitems(\@new_orderitems) if @new_orderitems;
 
 131   $order->calculate_prices_and_taxes;
 
 133   $order->db->with_transaction(sub {
 
 135     $self->requirement_spec->link_to_record($order);
 
 137     $::lxdebug->message(LXDebug::WARN(), "Error updating the order object: $@");
 
 140   $self->init_requirement_spec;
 
 142   my $html = $self->render('requirement_spec_order/list', { output => 0 });
 
 143   $self->js->replaceWith(LIST_SELECTOR(), $html)
 
 144            ->remove(FORMS_SELECTOR())
 
 145            ->flash('info', $::form->{quotation} ? t8('Sales quotation #1 has been updated.', $order->quonumber) : t8('Sales order #1 has been updated.', $order->ordnumber))
 
 149 sub action_edit_assignment {
 
 152   if (!@{ $self->all_parts_time_unit }) {
 
 153     return $self->js->flash('error', t8('This function requires the presence of articles with a time-based unit such as "h" or "min".'))->render($self);
 
 156   my $html   = $self->render('requirement_spec_order/edit_assignment', { output => 0 }, make_part_title => sub { $_[0]->partnumber . ' ' . $_[0]->description });
 
 157   $self->js->hide(LIST_SELECTOR())
 
 158            ->after(LIST_SELECTOR(), $html)
 
 163 sub action_save_assignment {
 
 165   my $sections = $::form->{sections} || [];
 
 166   SL::DB::RequirementSpecItem->new(id => $_->{id})->load->update_attributes(order_part_id => ($_->{order_part_id} || undef)) for @{ $sections };
 
 168   my $html = $self->render('requirement_spec_order/list', { output => 0 });
 
 169   $self->js->replaceWith(LIST_SELECTOR(), $html)
 
 170            ->remove(FORMS_SELECTOR())
 
 177   my $order  = $self->rs_order->order;
 
 180   $self->init_requirement_spec;
 
 182   my $html = $self->render('requirement_spec_order/list', { output => 0 });
 
 183   $self->js->replaceWith(LIST_SELECTOR(), $html)
 
 184            ->flash('info', $order->quotation ? t8('Sales quotation #1 has been deleted.', $order->quonumber) : t8('Sales order #1 has been deleted.', $order->ordnumber))
 
 195   $::auth->assert('requirement_spec_edit');
 
 196   $::request->{layout}->use_stylesheet("${_}.css") for qw(jquery.contextMenu requirement_spec autocomplete_part);
 
 197   $::request->{layout}->use_javascript("${_}.js")  for qw(jquery.jstree jquery/jquery.contextMenu client_js requirement_spec);
 
 202 sub init_requirement_spec {
 
 204   $self->requirement_spec(SL::DB::RequirementSpec->new(id => $::form->{requirement_spec_id})->load) if $::form->{requirement_spec_id};
 
 209   $self->js(SL::ClientJS->new);
 
 212 sub init_all_customers { SL::DB::Manager::Customer->get_all_sorted }
 
 213 sub init_h_unit_name   { SL::DB::Manager::Unit->find_h_unit->name };
 
 214 sub init_rs_order      { SL::DB::RequirementSpecOrder->new(id => $::form->{rs_order_id})->load };
 
 215 sub init_section_order_part { my $id = $::instance_conf->get_requirement_spec_section_order_part_id; return $id ? SL::DB::Part->new(id => $id)->load : undef }
 
 217 sub init_all_parts_time_unit {
 
 220   return [] unless $self->h_unit_name;
 
 222   my @convertible_unit_names = map { $_->name } @{ SL::DB::Manager::Unit->time_based_units };
 
 224   return SL::DB::Manager::Part->get_all_sorted(where => [ unit => \@convertible_unit_names ]);
 
 232   my ($self, @ids) = @_;
 
 234   my $parts = !@ids ? [] : SL::DB::Manager::Part->get_all(
 
 235     where        => [ id => \@ids ],
 
 236     with_objects => [ qw(unit_obj) ],
 
 239   $self->parts({ map { ($_->id => $_) } @{ $parts } });
 
 242 sub do_update_sections {
 
 245   my $order            = $self->rs_order->order;
 
 246   my $sections         = $self->requirement_spec->sections_sorted;
 
 247   my %orderitems_by_id = map { ($_->id => $_) } @{ $order->orderitems };
 
 248   my %sections_by_id   = map { ($_->id => $_) } @{ $sections };
 
 249   my $language_id      = $self->requirement_spec->customer->language_id;
 
 251   $self->cache_parts(uniq map { $_->order_part_id } @{ $sections });
 
 255   foreach my $attributes (@{ $::form->{orderitems} || [] }) {
 
 256     my $orderitem = $orderitems_by_id{ $attributes->{id}         };
 
 257     my $section   = $sections_by_id{   $attributes->{section_id} };
 
 258     next unless $orderitem && $section;
 
 260     $self->create_order_item(section => $section, item => $orderitem, language_id => $language_id)->save;
 
 261     $sections_seen{ $section->id } = 1;
 
 264   my @new_orderitems = map  { $self->create_order_item(section => $_, language_id => $language_id) }
 
 265                        grep { !$sections_seen{ $_->id } }
 
 268   return @new_orderitems;
 
 271 sub do_update_additional_parts {
 
 274   my $order         = $self->rs_order->order;
 
 275   my $add_parts     = $self->requirement_spec->parts_sorted;
 
 276   my %orderitems_by = map { (($_->parts_id . '-' . $_->description) => $_) } @{ $order->items };
 
 277   my $language_id   = $self->requirement_spec->customer->language_id;
 
 279   $self->cache_parts(uniq map { $_->part_id } @{ $add_parts });
 
 284   foreach my $add_part (@{ $add_parts }) {
 
 285     my $key       = $add_part->part_id . '-' . $add_part->description;
 
 286     my $orderitem = $orderitems_by{$key};
 
 289       $self->create_additional_part_order_item(additional_part => $add_part, item => $orderitem, language_id => $language_id)->save;
 
 292       push @new_orderitems, $self->create_additional_part_order_item(additional_part => $add_part, language_id => $language_id);
 
 296   return @new_orderitems;
 
 299 sub create_order_item {
 
 300   my ($self, %params) = @_;
 
 302   my $section         = $params{section};
 
 303   my $item            = $params{item} || SL::DB::OrderItem->new;
 
 304   my $part            = $self->parts->{ $section->order_part_id };
 
 305   my $is_time_based   = $part->unit_obj->is_time_based;
 
 306   my $translation     = $params{language_id} ? first { $params{language_id} == $_->language_id } @{ $part->translations } : {};
 
 307   my $description     = $section->{keep_description} ? $item->description : ($translation->{translation} || $part->description);
 
 308   my $longdescription = $translation->{longdescription} || $part->notes;
 
 310   if (!$section->{keep_description}) {
 
 311     $description     = '<%fb_number%> <%title%>' unless $description =~ m{<%};
 
 312     $longdescription = '<%description%>'   unless $longdescription =~ m{<%};
 
 314     $description     =~ s{<% (.+?) %>}{ $section->can($1) ? $section->$1 : '<' . t8('Invalid variable #1', $1) . '>' }egx;
 
 315     $longdescription =~ s{\<\% description \%\>}{!!!!DESCRIPTION!!!!}gx;
 
 316     $longdescription =~ s{<[pP]> !!!!DESCRIPTION!!!! </[pP]>}{!!!!DESCRIPTION!!!!}gx;
 
 317     $longdescription =~ s{\<\% (.+?) \%\>}{ $section->can($1) ? $::locale->quote_special_chars('HTML', $section->$1 // '') : '<' . t8('Invalid variable #1', $1) . '>' }egx;
 
 318     $longdescription =~ s{!!!!DESCRIPTION!!!!}{ $section->description // '' }egx;
 
 321   $item->assign_attributes(
 
 322     parts_id        => $part->id,
 
 323     description     => $description,
 
 324     longdescription => $longdescription,
 
 325     qty             => $is_time_based ? $section->time_estimation * 1 : 1,
 
 326     unit            => $is_time_based ? $self->h_unit_name            : $part->unit,
 
 327     sellprice       => $::form->round_amount($self->requirement_spec->hourly_rate * ($is_time_based ? 1 : $section->time_estimation), 2),
 
 328     lastcost        => $part->lastcost,
 
 330     project_id      => $self->requirement_spec->project_id,
 
 336 sub create_additional_part_order_item {
 
 337   my ($self, %params) = @_;
 
 339   my $add_part        = $params{additional_part};
 
 340   my $item            = $params{item} || SL::DB::OrderItem->new;
 
 341   my $part            = $self->parts->{ $add_part->part_id };
 
 342   my $translation     = $params{language_id} ? first { $params{language_id} == $_->language_id } @{ $part->translations } : {};
 
 343   my $description     = $item->description              || $add_part->description;
 
 344   my $longdescription = $translation->{longdescription} || $part->notes;
 
 346   $item->assign_attributes(
 
 347     parts_id        => $part->id,
 
 348     description     => $description,
 
 349     longdescription => $longdescription,
 
 350     qty             => $add_part->qty,
 
 351     unit            => $add_part->unit->name,
 
 352     sellprice       => $add_part->unit->convert_to($part->sellprice, $part->unit_obj),
 
 353     lastcost        => $part->lastcost,
 
 355     project_id      => $self->requirement_spec->project_id,
 
 362   my ($self, %params) = @_;
 
 365     map({ $_->{order_part_id} } @{ $params{sections} }),
 
 366     map({ $_->part_id         } @{ $params{additional_parts} }),
 
 368   $self->{parts} = { map { ($_->{id} => $_) } @{ SL::DB::Manager::Part->get_all(where => [ id => [ uniq @part_ids ] ]) } };
 
 370   my $customer   = SL::DB::Customer->new(id => $::form->{customer_id})->load;
 
 371   my @orderitems = map { $self->create_order_item(                section => $_,         language_id => $customer->language_id) } @{ $params{sections} };
 
 372   my @add_items  = map { $self->create_additional_part_order_item(additional_part => $_, language_id => $customer->language_id) } @{ $params{additional_parts} };
 
 373   my $employee   = SL::DB::Manager::Employee->current;
 
 374   my $order      = SL::DB::Order->new(
 
 375     globalproject_id        => $self->requirement_spec->project_id,
 
 376     transdate               => DateTime->today_local,
 
 377     reqdate                 => $::form->{quotation} && $customer->payment_id ? $customer->payment->calc_date : undef,
 
 378     quotation               => !!$::form->{quotation},
 
 379     orderitems              => [ @orderitems, @add_items ],
 
 380     customer_id             => $customer->id,
 
 381     taxincluded             => $customer->taxincluded,
 
 382     intnotes                => $customer->notes,
 
 383     language_id             => $customer->language_id,
 
 384     payment_id              => $customer->payment_id,
 
 385     taxzone_id              => $customer->taxzone_id,
 
 386     employee_id             => $employee->id,
 
 387     salesman_id             => $employee->id,
 
 388     transaction_description => $self->requirement_spec->displayable_name,
 
 389     currency_id             => $::instance_conf->get_currency_id,
 
 392   $order->calculate_prices_and_taxes;