Pflichtenhefte: beim Erstellen von Aufträgen zus. Artikel anlegen
[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 LIST_SELECTOR  => '#quotations_and_orders';
21 use constant FORMS_SELECTOR => '#quotations_and_orders_article_assignment,#quotations_and_orders_new,#quotations_and_orders_update';
22
23 use Rose::Object::MakeMethods::Generic
24 (
25   scalar                  => [ qw(parts) ],
26   'scalar --get_set_init' => [ qw(requirement_spec rs_order js h_unit_name all_customers all_parts_time_unit) ],
27 );
28
29 __PACKAGE__->run_before('setup');
30
31 #
32 # actions
33 #
34
35 sub action_list {
36   my ($self) = @_;
37
38   $self->render('requirement_spec_order/list', { layout => 0 });
39 }
40
41 sub action_new {
42   my ($self) = @_;
43
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);
46   }
47
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)
51            ->render($self);
52 }
53
54 sub action_create {
55   my ($self)         = @_;
56
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);
59   }
60
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 };
65
66   $sections_by_id{ $_->{id} }->update_attributes(order_part_id => $_->{order_part_id}) for @{ $section_attrs };
67
68   # 2. Create actual quotation/order.
69   my $order = $self->create_order(sections => $sections, additional_parts => [ $self->requirement_spec->parts ]);
70   $order->db->with_transaction(sub {
71     $order->save;
72
73     $self->requirement_spec->add_orders(SL::DB::RequirementSpecOrder->new(order => $order, version => $self->requirement_spec->version));
74     $self->requirement_spec->save;
75
76     $self->requirement_spec->link_to_record($order);
77   }) or do {
78     $::lxdebug->message(LXDebug::WARN(), "Error creating the order object: $@");
79   };
80
81   $self->init_requirement_spec;
82
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))
88            ->render($self);
89 }
90
91 sub action_update {
92   my ($self)   = @_;
93
94   my $order    = $self->rs_order->order;
95   my $sections = $self->requirement_spec->sections_sorted;
96
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);
99   }
100
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 };
104
105     $sections_seen{ $section->id } = 1 if $section;
106
107     push @orderitems, { item => $item, section => $section };
108   }
109
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 },
115   );
116
117   $self->js->hide(LIST_SELECTOR())
118            ->after(LIST_SELECTOR(), $html)
119            ->render($self);
120 }
121
122 sub action_do_update {
123   my ($self)           = @_;
124
125   my $order            = $self->rs_order->order;
126   my $sections         = $self->requirement_spec->sections_sorted;
127   my %orderitems_by_id = map { ($_->id => $_) } @{ $order->orderitems };
128   my %sections_by_id   = map { ($_->id => $_) } @{ $sections };
129   $self->{parts}       = { map { ($_->id => $_) } @{ SL::DB::Manager::Part->get_all(where => [ id => [ uniq map { $_->order_part_id } @{ $sections } ] ]) } };
130   my $language_id      = $self->requirement_spec->customer->language_id;
131
132   my %sections_seen;
133
134   foreach my $attributes (@{ $::form->{orderitems} || [] }) {
135     my $orderitem = $orderitems_by_id{ $attributes->{id}         };
136     my $section   = $sections_by_id{   $attributes->{section_id} };
137     next unless $orderitem && $section;
138
139     $self->create_order_item(section => $section, item => $orderitem, language_id => $language_id)->save;
140     $sections_seen{ $section->id } = 1;
141   }
142
143   my @new_orderitems = map  { $self->create_order_item(section => $_, language_id => $language_id) }
144                        grep { !$sections_seen{ $_->id } }
145                        @{ $sections };
146
147   $order->orderitems([ @{ $order->orderitems }, @new_orderitems ]) if @new_orderitems;
148
149   $order->calculate_prices_and_taxes;
150
151   $order->db->with_transaction(sub {
152     $order->save;
153     $self->requirement_spec->link_to_record($order);
154   }) or do {
155     $::lxdebug->message(LXDebug::WARN(), "Error updating the order object: $@");
156   };
157
158   $self->init_requirement_spec;
159
160   my $html = $self->render('requirement_spec_order/list', { output => 0 });
161   $self->js->replaceWith(LIST_SELECTOR(), $html)
162            ->remove(FORMS_SELECTOR())
163            ->flash('info', $::form->{quotation} ? t8('Sales quotation #1 has been updated.', $order->quonumber) : t8('Sales order #1 has been updated.', $order->ordnumber))
164            ->render($self);
165 }
166
167 sub action_edit_assignment {
168   my ($self) = @_;
169
170   if (!@{ $self->all_parts_time_unit }) {
171     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);
172   }
173
174   my $html   = $self->render('requirement_spec_order/edit_assignment', { output => 0 }, make_part_title => sub { $_[0]->partnumber . ' ' . $_[0]->description });
175   $self->js->hide(LIST_SELECTOR())
176            ->after(LIST_SELECTOR(), $html)
177            ->render($self);
178 }
179
180 sub action_save_assignment {
181   my ($self)   = @_;
182   my $sections = $::form->{sections} || [];
183   SL::DB::RequirementSpecItem->new(id => $_->{id})->load->update_attributes(order_part_id => ($_->{order_part_id} || undef)) for @{ $sections };
184
185   my $html = $self->render('requirement_spec_order/list', { output => 0 });
186   $self->js->replaceWith(LIST_SELECTOR(), $html)
187            ->remove(FORMS_SELECTOR())
188            ->render($self);
189 }
190
191 sub action_delete {
192   my ($self) = @_;
193
194   my $order  = $self->rs_order->order;
195
196   $order->delete;
197   $self->init_requirement_spec;
198
199   my $html = $self->render('requirement_spec_order/list', { output => 0 });
200   $self->js->replaceWith(LIST_SELECTOR(), $html)
201            ->flash('info', $order->quotation ? t8('Sales quotation #1 has been deleted.', $order->quonumber) : t8('Sales order #1 has been deleted.', $order->ordnumber))
202            ->render($self);
203 }
204
205 #
206 # filters
207 #
208
209 sub setup {
210   my ($self) = @_;
211
212   $::auth->assert('requirement_spec_edit');
213   $::request->{layout}->use_stylesheet("${_}.css") for qw(jquery.contextMenu requirement_spec autocomplete_part);
214   $::request->{layout}->use_javascript("${_}.js")  for qw(jquery.jstree jquery/jquery.contextMenu client_js requirement_spec);
215
216   return 1;
217 }
218
219 sub init_requirement_spec {
220   my ($self) = @_;
221   $self->requirement_spec(SL::DB::RequirementSpec->new(id => $::form->{requirement_spec_id})->load) if $::form->{requirement_spec_id};
222 }
223
224 sub init_js {
225   my ($self) = @_;
226   $self->js(SL::ClientJS->new);
227 }
228
229 sub init_all_customers { SL::DB::Manager::Customer->get_all_sorted }
230 sub init_h_unit_name   { first { SL::DB::Manager::Unit->find_by(name => $_) } qw(Std h Stunde) };
231 sub init_rs_order      { SL::DB::RequirementSpecOrder->new(id => $::form->{rs_order_id})->load };
232
233 sub init_all_parts_time_unit {
234   my ($self) = @_;
235
236   return [] unless $self->h_unit_name;
237
238   my @convertible_unit_names = map { $_->name } @{ SL::DB::Manager::Unit->find_by(name => $self->h_unit_name)->convertible_units };
239
240   return SL::DB::Manager::Part->get_all_sorted(where => [ unit => \@convertible_unit_names ]);
241 }
242
243 #
244 # helpers
245 #
246
247 sub create_order_item {
248   my ($self, %params) = @_;
249
250   my $section         = $params{section};
251   my $item            = $params{item} || SL::DB::OrderItem->new;
252   my $part            = $self->parts->{ $section->order_part_id };
253   my $translation     = $params{language_id} ? first { $params{language_id} == $_->language_id } @{ $part->translations } : {};
254   my $description     = $section->{keep_description} ? $item->description : ($translation->{translation} || $part->description);
255   my $longdescription = $translation->{longdescription} || $part->notes;
256
257   if (!$section->{keep_description}) {
258     $description     = '<%fb_number%> <%title%>' unless $description =~ m{<%};
259     $longdescription = '&lt;%description%&gt;'   unless $longdescription =~ m{&lt;%};
260
261     $description     =~ s{<% (.+?) %>}{ $section->can($1) ? $section->$1 : '<' . t8('Invalid variable #1', $1) . '>' }egx;
262     $longdescription =~ s{\&lt;\% description \%\&gt;}{!!!!DESCRIPTION!!!!}gx;
263     $longdescription =~ s{<[pP]> !!!!DESCRIPTION!!!! </[pP]>}{!!!!DESCRIPTION!!!!}gx;
264     $longdescription =~ s{\&lt;\% (.+?) \%\&gt;}{ $section->can($1) ? $::locale->quote_special_chars('HTML', $section->$1 // '') : '<' . t8('Invalid variable #1', $1) . '>' }egx;
265     $longdescription =~ s{!!!!DESCRIPTION!!!!}{ $section->description // '' }egx;
266   }
267
268   $item->assign_attributes(
269     parts_id        => $part->id,
270     description     => $description,
271     longdescription => $longdescription,
272     qty             => $section->time_estimation * 1,
273     unit            => $self->h_unit_name,
274     sellprice       => $::form->round_amount($self->requirement_spec->hourly_rate, 2),
275     lastcost        => $part->lastcost,
276     discount        => 0,
277     project_id      => $self->requirement_spec->project_id,
278   );
279
280   return $item;
281 }
282
283 sub create_additional_part_order_item {
284   my ($self, %params) = @_;
285
286   my $add_part        = $params{additional_part};
287   my $item            = $params{item} || SL::DB::OrderItem->new;
288   my $part            = $self->parts->{ $add_part->part_id };
289   my $translation     = $params{language_id} ? first { $params{language_id} == $_->language_id } @{ $part->translations } : {};
290   my $description     = $item->description              || $add_part->description;
291   my $longdescription = $translation->{longdescription} || $part->notes;
292
293   $item->assign_attributes(
294     parts_id        => $part->id,
295     description     => $description,
296     longdescription => $longdescription,
297     qty             => $add_part->qty,
298     unit            => $add_part->unit->name,
299     sellprice       => $add_part->unit->convert_to($part->sellprice, $part->unit_obj),
300     lastcost        => $part->lastcost,
301     discount        => 0,
302     project_id      => $self->requirement_spec->project_id,
303   );
304
305   return $item;
306 }
307
308 sub create_order {
309   my ($self, %params) = @_;
310
311   my @part_ids = (
312     map({ $_->{order_part_id} } @{ $params{sections} }),
313     map({ $_->part_id         } @{ $params{additional_parts} }),
314   );
315   $self->{parts} = { map { ($_->{id} => $_) } @{ SL::DB::Manager::Part->get_all(where => [ id => [ uniq @part_ids ] ]) } };
316
317   my $customer   = SL::DB::Customer->new(id => $::form->{customer_id})->load;
318   my @orderitems = map { $self->create_order_item(                section => $_,         language_id => $customer->language_id) } @{ $params{sections} };
319   my @add_items  = map { $self->create_additional_part_order_item(additional_part => $_, language_id => $customer->language_id) } @{ $params{additional_parts} };
320   my $employee   = SL::DB::Manager::Employee->current;
321   my $order      = SL::DB::Order->new(
322     globalproject_id        => $self->requirement_spec->project_id,
323     transdate               => DateTime->today_local,
324     reqdate                 => $::form->{quotation} && $customer->payment_id ? $customer->payment->calc_date : undef,
325     quotation               => !!$::form->{quotation},
326     orderitems              => [ @orderitems, @add_items ],
327     customer_id             => $customer->id,
328     taxincluded             => $customer->taxincluded,
329     intnotes                => $customer->notes,
330     language_id             => $customer->language_id,
331     payment_id              => $customer->payment_id,
332     taxzone_id              => $customer->taxzone_id,
333     employee_id             => $employee->id,
334     salesman_id             => $employee->id,
335     transaction_description => $self->requirement_spec->displayable_name,
336     currency_id             => $::instance_conf->get_currency_id,
337   );
338
339   $order->calculate_prices_and_taxes;
340
341   return $order;
342 }
343
344 1;