1 package SL::Controller::RequirementSpecOrder;
 
   6 use parent qw(SL::Controller::Base);
 
   8 use List::MoreUtils qw(uniq);
 
   9 use List::Util qw(first);
 
  14 use SL::DB::RequirementSpec;
 
  15 use SL::DB::RequirementSpecOrder;
 
  16 use SL::Helper::Flash;
 
  17 use SL::Locale::String;
 
  19 use constant LIST_SELECTOR  => '#quotations_and_orders';
 
  20 use constant FORMS_SELECTOR => '#quotations_and_orders_article_assignment,#quotations_and_orders_new,#quotations_and_orders_update';
 
  22 use Rose::Object::MakeMethods::Generic
 
  24   scalar                  => [ qw(parts) ],
 
  25   'scalar --get_set_init' => [ qw(requirement_spec rs_order h_unit_name all_customers all_parts_time_unit section_order_part) ],
 
  28 __PACKAGE__->run_before('setup');
 
  37   $self->render('requirement_spec_order/list', { layout => 0 });
 
  43   if (!@{ $self->all_parts_time_unit }) {
 
  44     return $self->js->flash('error', t8('This function requires the presence of articles with a time-based unit such as "h" or "min".'))->render;
 
  47   my $html = $self->render('requirement_spec_order/new', { output => 0 }, make_part_title => sub { $_[0]->partnumber . ' ' . $_[0]->description });
 
  48   $self->js->hide(LIST_SELECTOR())
 
  49            ->after(LIST_SELECTOR(), $html)
 
  56   if (!$::auth->assert($::form->{quotation} ? 'sales_quotation_edit' : 'sales_order_edit', 1)) {
 
  57     return $self->js->flash('error', t8("You do not have the permissions to access this function."))->render;
 
  60   # 1. Update sections with selected part IDs.
 
  61   my $section_attrs  = $::form->{sections} || [];
 
  62   my $sections       = SL::DB::Manager::RequirementSpecItem->get_all_sorted(where => [ id => [ map { $_->{id} } @{ $section_attrs } ] ]);
 
  63   my %sections_by_id = map { ($_->{id} => $_) } @{ $sections };
 
  65   $sections_by_id{ $_->{id} }->update_attributes(order_part_id => $_->{order_part_id}) for @{ $section_attrs };
 
  67   # 2. Create actual quotation/order.
 
  68   my $order = $self->create_order(sections => $sections, additional_parts => $self->requirement_spec->parts_sorted);
 
  69   $order->db->with_transaction(sub {
 
  72     $self->requirement_spec->add_orders(SL::DB::RequirementSpecOrder->new(order => $order, version => $self->requirement_spec->version));
 
  73     $self->requirement_spec->save;
 
  75     $self->requirement_spec->link_to_record($order);
 
  77     $::lxdebug->message(LXDebug::WARN(), "Error creating the order object: $@");
 
  80   $self->init_requirement_spec;
 
  82   # 3. Notify the user and return to list.
 
  83   my $html = $self->render('requirement_spec_order/list', { output => 0 });
 
  84   $self->js->replaceWith(LIST_SELECTOR(), $html)
 
  85            ->remove(FORMS_SELECTOR())
 
  86            ->flash('info', $::form->{quotation} ? t8('Sales quotation #1 has been created.', $order->quonumber) : t8('Sales order #1 has been created.', $order->ordnumber))
 
  93   my $order    = $self->rs_order->order;
 
  94   my $sections = $self->requirement_spec->sections_sorted;
 
  96   if (!$::auth->assert($order->quotation ? 'sales_quotation_edit' : 'sales_order_edit', 1)) {
 
  97     return $self->js->flash('error', t8("You do not have the permissions to access this function."))->render;
 
 100   my (@orderitems, %sections_seen);
 
 101   foreach my $item (@{ $order->items_sorted }) {
 
 102     my $section = first { my $num = $_->fb_number; $item->description =~ m{\b\Q${num}\E\b} && !$sections_seen{ $_->id } } @{ $sections };
 
 104     $sections_seen{ $section->id } = 1 if $section;
 
 106     push @orderitems, { item => $item, section => $section };
 
 109   my $html = $self->render(
 
 110     'requirement_spec_order/update', { output => 0 },
 
 111     orderitems         => \@orderitems,
 
 112     sections           => $sections,
 
 113     make_section_title => sub { $_[0]->fb_number . ' ' . $_[0]->title },
 
 116   $self->js->hide(LIST_SELECTOR())
 
 117            ->after(LIST_SELECTOR(), $html)
 
 121 sub action_do_update {
 
 124   my $order          = $self->rs_order->order;
 
 125   my @new_orderitems =  $self->do_update_sections;
 
 126   push @new_orderitems, $self->do_update_additional_parts;
 
 128   $order->add_orderitems(\@new_orderitems) if @new_orderitems;
 
 130   $order->calculate_prices_and_taxes;
 
 132   $order->db->with_transaction(sub {
 
 134     $self->requirement_spec->link_to_record($order);
 
 136     $::lxdebug->message(LXDebug::WARN(), "Error updating the order object: $@");
 
 139   $self->init_requirement_spec;
 
 141   my $html = $self->render('requirement_spec_order/list', { output => 0 });
 
 142   $self->js->replaceWith(LIST_SELECTOR(), $html)
 
 143            ->remove(FORMS_SELECTOR())
 
 144            ->flash('info', $::form->{quotation} ? t8('Sales quotation #1 has been updated.', $order->quonumber) : t8('Sales order #1 has been updated.', $order->ordnumber))
 
 148 sub action_edit_assignment {
 
 151   if (!@{ $self->all_parts_time_unit }) {
 
 152     return $self->js->flash('error', t8('This function requires the presence of articles with a time-based unit such as "h" or "min".'))->render;
 
 155   my $html   = $self->render('requirement_spec_order/edit_assignment', { output => 0 }, make_part_title => sub { $_[0]->partnumber . ' ' . $_[0]->description });
 
 156   $self->js->hide(LIST_SELECTOR())
 
 157            ->after(LIST_SELECTOR(), $html)
 
 162 sub action_save_assignment {
 
 164   my $sections = $::form->{sections} || [];
 
 165   SL::DB::RequirementSpecItem->new(id => $_->{id})->load->update_attributes(order_part_id => ($_->{order_part_id} || undef)) for @{ $sections };
 
 167   my $html = $self->render('requirement_spec_order/list', { output => 0 });
 
 168   $self->js->replaceWith(LIST_SELECTOR(), $html)
 
 169            ->remove(FORMS_SELECTOR())
 
 176   my $order  = $self->rs_order->order;
 
 179   $self->init_requirement_spec;
 
 181   my $html = $self->render('requirement_spec_order/list', { output => 0 });
 
 182   $self->js->replaceWith(LIST_SELECTOR(), $html)
 
 183            ->flash('info', $order->quotation ? t8('Sales quotation #1 has been deleted.', $order->quonumber) : t8('Sales order #1 has been deleted.', $order->ordnumber))
 
 194   $::auth->assert('requirement_spec_edit');
 
 195   $::request->{layout}->use_stylesheet("${_}.css") for qw(jquery.contextMenu requirement_spec);
 
 196   $::request->{layout}->use_javascript("${_}.js")  for qw(jquery.jstree jquery/jquery.contextMenu client_js requirement_spec);
 
 201 sub init_requirement_spec {
 
 203   $self->requirement_spec(SL::DB::RequirementSpec->new(id => $::form->{requirement_spec_id})->load) if $::form->{requirement_spec_id};
 
 206 sub init_all_customers { SL::DB::Manager::Customer->get_all_sorted }
 
 207 sub init_h_unit_name   { SL::DB::Manager::Unit->find_h_unit->name };
 
 208 sub init_rs_order      { SL::DB::RequirementSpecOrder->new(id => $::form->{rs_order_id})->load };
 
 209 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 }
 
 211 sub init_all_parts_time_unit {
 
 214   return [] unless $self->h_unit_name;
 
 216   my @convertible_unit_names = map { $_->name } @{ SL::DB::Manager::Unit->time_based_units };
 
 218   return SL::DB::Manager::Part->get_all_sorted(where => [ unit => \@convertible_unit_names ]);
 
 226   my ($self, @ids) = @_;
 
 228   my $parts = !@ids ? [] : SL::DB::Manager::Part->get_all(
 
 229     where        => [ id => \@ids ],
 
 230     with_objects => [ qw(unit_obj) ],
 
 233   $self->parts({ map { ($_->id => $_) } @{ $parts } });
 
 236 sub do_update_sections {
 
 239   my $order            = $self->rs_order->order;
 
 240   my $sections         = $self->requirement_spec->sections_sorted;
 
 241   my %orderitems_by_id = map { ($_->id => $_) } @{ $order->orderitems };
 
 242   my %sections_by_id   = map { ($_->id => $_) } @{ $sections };
 
 243   my $language_id      = $self->requirement_spec->customer->language_id;
 
 245   $self->cache_parts(uniq map { $_->order_part_id } @{ $sections });
 
 249   foreach my $attributes (@{ $::form->{orderitems} || [] }) {
 
 250     my $orderitem = $orderitems_by_id{ $attributes->{id}         };
 
 251     my $section   = $sections_by_id{   $attributes->{section_id} };
 
 252     next unless $orderitem && $section;
 
 254     $self->create_order_item(section => $section, item => $orderitem, language_id => $language_id)->save;
 
 255     $sections_seen{ $section->id } = 1;
 
 258   my @new_orderitems = map  { $self->create_order_item(section => $_, language_id => $language_id) }
 
 259                        grep { !$sections_seen{ $_->id } }
 
 262   return @new_orderitems;
 
 265 sub do_update_additional_parts {
 
 268   my $order         = $self->rs_order->order;
 
 269   my $add_parts     = $self->requirement_spec->parts_sorted;
 
 270   my %orderitems_by = map { (($_->parts_id . '-' . $_->description) => $_) } @{ $order->items };
 
 271   my $language_id   = $self->requirement_spec->customer->language_id;
 
 273   $self->cache_parts(uniq map { $_->part_id } @{ $add_parts });
 
 278   foreach my $add_part (@{ $add_parts }) {
 
 279     my $key       = $add_part->part_id . '-' . $add_part->description;
 
 280     my $orderitem = $orderitems_by{$key};
 
 283       $self->create_additional_part_order_item(additional_part => $add_part, item => $orderitem, language_id => $language_id)->save;
 
 286       push @new_orderitems, $self->create_additional_part_order_item(additional_part => $add_part, language_id => $language_id);
 
 290   return @new_orderitems;
 
 293 sub create_order_item {
 
 294   my ($self, %params) = @_;
 
 296   my $section         = $params{section};
 
 297   my $item            = $params{item} || SL::DB::OrderItem->new;
 
 298   my $part            = $self->parts->{ $section->order_part_id };
 
 299   my $is_time_based   = $part->unit_obj->is_time_based;
 
 300   my $translation     = $params{language_id} ? first { $params{language_id} == $_->language_id } @{ $part->translations } : {};
 
 301   my $description     = $section->{keep_description} ? $item->description : ($translation->{translation} || $part->description);
 
 302   my $longdescription = $translation->{longdescription} || $part->notes;
 
 304   if (!$section->{keep_description}) {
 
 305     $description     = '<%fb_number%> <%title%>' unless $description =~ m{<%};
 
 306     $longdescription = '<%description%>'   unless $longdescription =~ m{<%};
 
 308     $description     =~ s{<% (.+?) %>}{ $section->can($1) ? $section->$1 : '<' . t8('Invalid variable #1', $1) . '>' }egx;
 
 309     $longdescription =~ s{\<\% description \%\>}{!!!!DESCRIPTION!!!!}gx;
 
 310     $longdescription =~ s{<[pP]> !!!!DESCRIPTION!!!! </[pP]>}{!!!!DESCRIPTION!!!!}gx;
 
 311     $longdescription =~ s{\<\% (.+?) \%\>}{ $section->can($1) ? $::locale->quote_special_chars('HTML', $section->$1 // '') : '<' . t8('Invalid variable #1', $1) . '>' }egx;
 
 312     $longdescription =~ s{!!!!DESCRIPTION!!!!}{ $section->description // '' }egx;
 
 315   $item->assign_attributes(
 
 316     parts_id        => $part->id,
 
 317     description     => $description,
 
 318     longdescription => $longdescription,
 
 319     qty             => $is_time_based ? $section->time_estimation * 1 : 1,
 
 320     unit            => $is_time_based ? $self->h_unit_name            : $part->unit,
 
 321     sellprice       => $::form->round_amount($self->requirement_spec->hourly_rate * ($is_time_based ? 1 : $section->time_estimation), 2),
 
 322     lastcost        => $part->lastcost,
 
 324     project_id      => $self->requirement_spec->project_id,
 
 330 sub create_additional_part_order_item {
 
 331   my ($self, %params) = @_;
 
 333   my $add_part        = $params{additional_part};
 
 334   my $item            = $params{item} || SL::DB::OrderItem->new;
 
 335   my $part            = $self->parts->{ $add_part->part_id };
 
 336   my $translation     = $params{language_id} ? first { $params{language_id} == $_->language_id } @{ $part->translations } : {};
 
 337   my $description     = $item->description              || $add_part->description;
 
 338   my $longdescription = $translation->{longdescription} || $part->notes;
 
 340   $item->assign_attributes(
 
 341     parts_id        => $part->id,
 
 342     description     => $description,
 
 343     longdescription => $longdescription,
 
 344     qty             => $add_part->qty,
 
 345     unit            => $add_part->unit->name,
 
 346     sellprice       => $add_part->unit->convert_to($part->sellprice, $part->unit_obj),
 
 347     lastcost        => $part->lastcost,
 
 349     project_id      => $self->requirement_spec->project_id,
 
 356   my ($self, %params) = @_;
 
 359     map({ $_->{order_part_id} } @{ $params{sections} }),
 
 360     map({ $_->part_id         } @{ $params{additional_parts} }),
 
 362   $self->{parts} = { map { ($_->{id} => $_) } @{ SL::DB::Manager::Part->get_all(where => [ id => [ uniq @part_ids ] ]) } };
 
 364   my $customer   = SL::DB::Customer->new(id => $::form->{customer_id})->load;
 
 365   my @orderitems = map { $self->create_order_item(                section => $_,         language_id => $customer->language_id) } @{ $params{sections} };
 
 366   my @add_items  = map { $self->create_additional_part_order_item(additional_part => $_, language_id => $customer->language_id) } @{ $params{additional_parts} };
 
 367   my $employee   = SL::DB::Manager::Employee->current;
 
 368   my $order      = SL::DB::Order->new(
 
 369     globalproject_id        => $self->requirement_spec->project_id,
 
 370     transdate               => DateTime->today_local,
 
 371     reqdate                 => $::form->{quotation} && $customer->payment_id ? $customer->payment->calc_date : undef,
 
 372     quotation               => !!$::form->{quotation},
 
 373     orderitems              => [ @orderitems, @add_items ],
 
 374     customer_id             => $customer->id,
 
 375     taxincluded             => $customer->taxincluded,
 
 376     intnotes                => $customer->notes,
 
 377     language_id             => $customer->language_id,
 
 378     payment_id              => $customer->payment_id,
 
 379     taxzone_id              => $customer->taxzone_id,
 
 380     employee_id             => $employee->id,
 
 381     salesman_id             => $employee->id,
 
 382     transaction_description => $self->requirement_spec->displayable_name,
 
 383     currency_id             => $::instance_conf->get_currency_id,
 
 386   $order->calculate_prices_and_taxes;