Refactoring
[kivitendo-erp.git] / SL / Controller / RequirementSpecOrder.pm
1 package SL::Controller::RequirementSpecOrder;
2
3 use strict;
4 use utf8;
5
6 use parent qw(SL::Controller::Base);
7
8 use List::MoreUtils qw(uniq);
9 use List::Util qw(first);
10
11 use SL::ClientJS;
12 use SL::DB::Customer;
13 use SL::DB::Order;
14 use SL::DB::Part;
15 use SL::DB::RequirementSpec;
16 use SL::DB::RequirementSpecOrder;
17 use SL::Helper::Flash;
18 use SL::Locale::String;
19
20 use constant TAB_ID => 'ui-tabs-4';
21
22 use Rose::Object::MakeMethods::Generic
23 (
24   scalar                  => [ qw(parts) ],
25   'scalar --get_set_init' => [ qw(requirement_spec rs_order js h_unit_name all_customers all_parts_time_unit) ],
26 );
27
28 __PACKAGE__->run_before('setup');
29
30 #
31 # actions
32 #
33
34 sub action_list {
35   my ($self) = @_;
36
37   $self->render('requirement_spec_order/list', { layout => 0 });
38 }
39
40 sub action_new {
41   my ($self) = @_;
42
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($self);
45   }
46
47   my $html   = $self->render('requirement_spec_order/new', { output => 0 }, make_part_title => sub { $_[0]->partnumber . ' ' . $_[0]->description });
48   $self->js->html('#' . TAB_ID(), $html)
49            ->render($self);
50 }
51
52 sub action_create {
53   my ($self)         = @_;
54
55   # 1. Update sections with selected part IDs.
56   my $section_attrs  = $::form->{sections} || [];
57   my $sections       = SL::DB::Manager::RequirementSpecItem->get_all(where => [ id => [ map { $_->{id} } @{ $section_attrs } ] ]);
58   my %sections_by_id = map { ($_->{id} => $_) } @{ $sections };
59
60   $sections_by_id{ $_->{id} }->update_attributes(order_part_id => $_->{order_part_id}) for @{ $section_attrs };
61
62   # 2. Create actual quotation/order.
63   my $order = $self->create_order(sections => $sections);
64   $order->save;
65
66   $self->requirement_spec->orders(
67     @{ $self->requirement_spec->orders },
68     SL::DB::RequirementSpecOrder->new(order => $order, version => $self->requirement_spec->version)
69   );
70   $self->requirement_spec->save;
71   $self->init_requirement_spec;
72
73   # 3. Notify the user and return to list.
74   my $html = $self->render('requirement_spec_order/list', { output => 0 });
75   $self->js->html('#' . TAB_ID(), $html)
76            ->flash('info', $::form->{quotation} ? t8('Sales quotation #1 has been created.', $order->quonumber) : t8('Sales order #1 has been created.', $order->ordnumber))
77            ->render($self);
78 }
79
80 sub action_update {
81   my ($self)   = @_;
82
83   my $order    = $self->rs_order->order;
84   my $sections = $self->requirement_spec->sections_sorted;
85
86   my (@orderitems, %sections_seen);
87   foreach my $item (@{ $order->items_sorted }) {
88     my $section = first { my $num = $_->fb_number; $item->description =~ m{\b\Q${num}\E\b} && !$sections_seen{ $_->id } } @{ $sections };
89
90     $sections_seen{ $section->id } = 1 if $section;
91
92     push @orderitems, { item => $item, section => $section };
93   }
94
95   my $html = $self->render(
96     'requirement_spec_order/update', { output => 0 },
97     orderitems         => \@orderitems,
98     sections           => $sections,
99     make_section_title => sub { $_[0]->fb_number . ' ' . $_[0]->title },
100   );
101
102   $self->js->html('#' . TAB_ID(), $html)
103            ->render($self);
104 }
105
106 sub action_do_update {
107   my ($self)           = @_;
108
109   my $order            = $self->rs_order->order;
110   my $sections         = $self->requirement_spec->sections_sorted;
111   my %orderitems_by_id = map { ($_->id => $_) } @{ $order->orderitems };
112   my %sections_by_id   = map { ($_->id => $_) } @{ $sections };
113   $self->{parts}       = { map { ($_->id => $_) } @{ SL::DB::Manager::Part->get_all(where => [ id => [ uniq map { $_->order_part_id } @{ $sections } ] ]) } };
114   my $language_id      = $self->requirement_spec->customer->language_id;
115
116   my %sections_seen;
117
118   foreach my $attributes (@{ $::form->{orderitems} || [] }) {
119     my $orderitem = $orderitems_by_id{ $attributes->{id}         };
120     my $section   = $sections_by_id{   $attributes->{section_id} };
121     next unless $orderitem && $section;
122
123     $self->create_order_item(section => $section, item => $orderitem, language_id => $language_id)->save;
124     $sections_seen{ $section->id } = 1;
125   }
126
127   my @new_orderitems = map  { $self->create_order_item(section => $_, language_id => $language_id) }
128                        grep { !$sections_seen{ $_->id } }
129                        @{ $sections };
130
131   $order->orderitems([ @{ $order->orderitems }, @new_orderitems ]) if @new_orderitems;
132
133   $order->calculate_prices_and_taxes;
134   $order->save;
135
136   $self->init_requirement_spec;
137
138   my $html = $self->render('requirement_spec_order/list', { output => 0 });
139   $self->js->html('#' . TAB_ID(), $html)
140            ->flash('info', $::form->{quotation} ? t8('Sales quotation #1 has been updated.', $order->quonumber) : t8('Sales order #1 has been updated.', $order->ordnumber))
141            ->render($self);
142 }
143
144 sub action_edit_assignment {
145   my ($self) = @_;
146
147   if (!@{ $self->all_parts_time_unit }) {
148     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);
149   }
150
151   my $html   = $self->render('requirement_spec_order/edit_assignment', { output => 0 }, make_part_title => sub { $_[0]->partnumber . ' ' . $_[0]->description });
152   $self->js->html('#' . TAB_ID(), $html)
153            ->render($self);
154 }
155
156 sub action_save_assignment {
157   my ($self)   = @_;
158   my $sections = $::form->{sections} || [];
159   SL::DB::RequirementSpecItem->new(id => $_->{id})->load->update_attributes(order_part_id => ($_->{order_part_id} || undef)) for @{ $sections };
160
161   my $html = $self->render('requirement_spec_order/list', { output => 0 });
162   $self->js->html('#' . TAB_ID(), $html)
163            ->render($self);
164 }
165
166 sub action_delete {
167   my ($self) = @_;
168
169   my $order  = $self->rs_order->order;
170
171   $order->delete;
172   $self->init_requirement_spec;
173
174   my $html = $self->render('requirement_spec_order/list', { output => 0 });
175   $self->js->html('#' . TAB_ID(), $html)
176            ->flash('info', $order->quotation ? t8('Sales quotation #1 has been deleted.', $order->quonumber) : t8('Sales order #1 has been deleted.', $order->ordnumber))
177            ->render($self);
178 }
179
180 sub action_cancel {
181   my ($self) = @_;
182
183   my $html = $self->render('requirement_spec_order/list', { output => 0 });
184   $self->js->html('#' . TAB_ID(), $html)
185            ->render($self);
186 }
187
188 #
189 # filters
190 #
191
192 sub setup {
193   my ($self) = @_;
194
195   $::auth->assert('sales_quotation_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);
198
199   return 1;
200 }
201
202 sub init_requirement_spec {
203   my ($self) = @_;
204   $self->requirement_spec(SL::DB::RequirementSpec->new(id => $::form->{requirement_spec_id})->load) if $::form->{requirement_spec_id};
205 }
206
207 sub init_js {
208   my ($self) = @_;
209   $self->js(SL::ClientJS->new);
210 }
211
212 sub init_all_customers { SL::DB::Manager::Customer->get_all_sorted }
213 sub init_h_unit_name   { first { SL::DB::Manager::Unit->find_by(name => $_) } qw(Std h Stunde) };
214 sub init_rs_order      { SL::DB::RequirementSpecOrder->new(id => $::form->{rs_order_id})->load };
215
216 sub init_all_parts_time_unit {
217   my ($self) = @_;
218
219   return [] unless $self->h_unit_name;
220
221   my @convertible_unit_names = map { $_->name } @{ SL::DB::Manager::Unit->find_by(name => $self->h_unit_name)->convertible_units };
222
223   return SL::DB::Manager::Part->get_all_sorted(where => [ unit => \@convertible_unit_names ]);
224 }
225
226 #
227 # helpers
228 #
229
230 sub load_parts_for_sections {
231   my ($self, %params) = @_;
232
233 }
234
235 sub create_order_item {
236   my ($self, %params) = @_;
237
238   my $section         = $params{section};
239   my $item            = $params{item} || SL::DB::OrderItem->new;
240   my $part            = $self->parts->{ $section->order_part_id };
241   my $translation     = $params{language_id} ? first { $params{language_id} == $_->language_id } @{ $part->translations } : {};
242   my $description     = $section->{keep_description} ? $item->description : ($translation->{translation} || $part->description);
243   my $longdescription = $translation->{longdescription} || $part->notes;
244
245   if (!$section->{keep_description}) {
246     foreach my $field (\$description, \$longdescription) {
247       $$field =  '<%fb_number%> <%title%>' unless $$field =~ m{<%};
248       $$field =~ s{<% (.+?) %>}{ $section->can($1) ? $section->$1 : '<' . t8('Invalid variable #1', $1) . '>' }egx;
249     }
250   }
251
252   $item->assign_attributes(
253     parts_id        => $part->id,
254     description     => $description,
255     longdescription => $longdescription,
256     qty             => $section->time_estimation * 1,
257     unit            => $self->h_unit_name,
258     sellprice       => $::form->round_amount($self->requirement_spec->hourly_rate, 2),
259     lastcost        => $part->lastcost,
260     discount        => 0,
261     project_id      => $self->requirement_spec->project_id,
262   );
263
264   return $item;
265 }
266
267 sub create_order {
268   my ($self, %params) = @_;
269
270   $self->{parts} = { map { ($_->{id} => $_) } @{ SL::DB::Manager::Part->get_all(where => [ id => [ uniq map { $_->{order_part_id} } @{ $params{sections} } ] ]) } };
271
272   my $customer   = SL::DB::Customer->new(id => $::form->{customer_id})->load;
273   my @orderitems = map { $self->create_order_item(section => $_, language_id => $customer->language_id) } @{ $params{sections} };
274   my $employee   = SL::DB::Manager::Employee->current;
275   my $order      = SL::DB::Order->new(
276     globalproject_id        => $self->requirement_spec->project_id,
277     transdate               => DateTime->today_local,
278     reqdate                 => $::form->{quotation} && $customer->payment_id ? $customer->payment->calc_date : undef,
279     quotation               => !!$::form->{quotation},
280     orderitems              => \@orderitems,
281     customer_id             => $customer->id,
282     taxincluded             => $customer->taxincluded,
283     intnotes                => $customer->notes,
284     language_id             => $customer->language_id,
285     payment_id              => $customer->payment_id,
286     taxzone_id              => $customer->taxzone_id,
287     employee_id             => $employee->id,
288     salesman_id             => $employee->id,
289     transaction_description => $self->requirement_spec->displayable_name,
290     currency_id             => $::instance_conf->get_currency_id,
291   );
292
293   $order->calculate_prices_and_taxes;
294
295   return $order;
296 }
297
298 1;