]> wagnertech.de Git - mfinanz.git/blob - SL/Controller/RequirementSpecOrder.pm
restart apache2 in postinst
[mfinanz.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::DB::Customer;
12 use SL::DB::Order;
13 use SL::DB::Order::TypeData qw(:types);
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 h_unit_name all_customers all_parts_time_unit section_order_part) ],
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;
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;
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;
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_sorted);
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;
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->type_data->rights('edit'), 1)) {
98     return $self->js->flash('error', t8("You do not have the permissions to access this function."))->render;
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;
120 }
121
122 sub action_do_update {
123   my ($self)         = @_;
124
125   my $order          = $self->rs_order->order;
126   my @new_orderitems =  $self->do_update_sections;
127   push @new_orderitems, $self->do_update_additional_parts;
128
129   $order->add_orderitems(\@new_orderitems) if @new_orderitems;
130
131   $order->calculate_prices_and_taxes;
132
133   $order->db->with_transaction(sub {
134     $order->save;
135     $self->requirement_spec->link_to_record($order);
136   }) or do {
137     $::lxdebug->message(LXDebug::WARN(), "Error updating the order object: $@");
138   };
139
140   $self->init_requirement_spec;
141
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))
146            ->render;
147 }
148
149 sub action_edit_assignment {
150   my ($self) = @_;
151
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;
154   }
155
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)
159            ->reinit_widgets
160            ->render;
161 }
162
163 sub action_save_assignment {
164   my ($self)   = @_;
165   my $sections = $::form->{sections} || [];
166   SL::DB::RequirementSpecItem->new(id => $_->{id})->load->update_attributes(order_part_id => ($_->{order_part_id} || undef)) for @{ $sections };
167
168   my $html = $self->render('requirement_spec_order/list', { output => 0 });
169   $self->js->replaceWith(LIST_SELECTOR(), $html)
170            ->remove(FORMS_SELECTOR())
171            ->render;
172 }
173
174 sub action_delete {
175   my ($self) = @_;
176
177   my $order  = $self->rs_order->order;
178
179   $order->delete;
180   $self->init_requirement_spec;
181
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))
185            ->render;
186 }
187
188 #
189 # filters
190 #
191
192 sub setup {
193   my ($self) = @_;
194
195   $::auth->assert('requirement_spec_edit');
196   $::request->{layout}->use_stylesheet("${_}.css") for qw(jquery.contextMenu requirement_spec);
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_all_customers { SL::DB::Manager::Customer->get_all_sorted }
208 sub init_h_unit_name   { SL::DB::Manager::Unit->find_h_unit->name };
209 sub init_rs_order      { SL::DB::RequirementSpecOrder->new(id => $::form->{rs_order_id})->load };
210 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
212 sub init_all_parts_time_unit {
213   my ($self) = @_;
214
215   return [] unless $self->h_unit_name;
216
217   my @convertible_unit_names = map { $_->name } @{ SL::DB::Manager::Unit->time_based_units };
218
219   return SL::DB::Manager::Part->get_all_sorted(where => [ unit => \@convertible_unit_names ]);
220 }
221
222 #
223 # helpers
224 #
225
226 sub cache_parts {
227   my ($self, @ids) = @_;
228
229   my $parts = !@ids ? [] : SL::DB::Manager::Part->get_all(
230     where        => [ id => \@ids ],
231     with_objects => [ qw(unit_obj) ],
232   );
233
234   $self->parts({ map { ($_->id => $_) } @{ $parts } });
235 }
236
237 sub do_update_sections {
238   my ($self)           = @_;
239
240   my $order            = $self->rs_order->order;
241   my $sections         = $self->requirement_spec->sections_sorted;
242   my %orderitems_by_id = map { ($_->id => $_) } @{ $order->orderitems };
243   my %sections_by_id   = map { ($_->id => $_) } @{ $sections };
244   my $language_id      = $self->requirement_spec->customer->language_id;
245
246   $self->cache_parts(uniq map { $_->order_part_id } @{ $sections });
247
248   my %sections_seen;
249
250   foreach my $attributes (@{ $::form->{orderitems} || [] }) {
251     my $orderitem = $orderitems_by_id{ $attributes->{id}         };
252     my $section   = $sections_by_id{   $attributes->{section_id} };
253     next unless $orderitem && $section;
254
255     $self->create_order_item(section => $section, item => $orderitem, language_id => $language_id)->save;
256     $sections_seen{ $section->id } = 1;
257   }
258
259   my @new_orderitems = map  { $self->create_order_item(section => $_, language_id => $language_id) }
260                        grep { !$sections_seen{ $_->id } }
261                        @{ $sections };
262
263   return @new_orderitems;
264 }
265
266 sub do_update_additional_parts {
267   my ($self)        = @_;
268
269   my $order         = $self->rs_order->order;
270   my $add_parts     = $self->requirement_spec->parts_sorted;
271   my %orderitems_by = map { (($_->parts_id . '-' . $_->description) => $_) } @{ $order->items };
272   my $language_id   = $self->requirement_spec->customer->language_id;
273
274   $self->cache_parts(uniq map { $_->part_id } @{ $add_parts });
275
276   my %add_part_seen;
277   my @new_orderitems;
278
279   foreach my $add_part (@{ $add_parts }) {
280     my $key       = $add_part->part_id . '-' . $add_part->description;
281     my $orderitem = $orderitems_by{$key};
282
283     if ($orderitem) {
284       $self->create_additional_part_order_item(additional_part => $add_part, item => $orderitem, language_id => $language_id)->save;
285
286     } else {
287       push @new_orderitems, $self->create_additional_part_order_item(additional_part => $add_part, language_id => $language_id);
288     }
289   }
290
291   return @new_orderitems;
292 }
293
294 sub create_order_item {
295   my ($self, %params) = @_;
296
297   my $section         = $params{section};
298   my $item            = $params{item} || SL::DB::OrderItem->new;
299   my $part            = $self->parts->{ $section->order_part_id };
300   my $is_time_based   = $part->unit_obj->is_time_based;
301   my $translation     = $params{language_id} ? first { $params{language_id} == $_->language_id } @{ $part->translations } : {};
302   my $description     = $section->{keep_description} ? $item->description : ($translation->{translation} || $part->description);
303   my $longdescription = $translation->{longdescription} || $part->notes;
304
305   if (!$section->{keep_description}) {
306     $description     = '<%fb_number%> <%title%>' unless $description =~ m{<%};
307     $longdescription = '&lt;%description%&gt;'   unless $longdescription =~ m{&lt;%};
308
309     $description     =~ s{<% (.+?) %>}{ $section->can($1) ? $section->$1 : '<' . t8('Invalid variable #1', $1) . '>' }egx;
310     $longdescription =~ s{\&lt;\% description \%\&gt;}{!!!!DESCRIPTION!!!!}gx;
311     $longdescription =~ s{<[pP]> !!!!DESCRIPTION!!!! </[pP]>}{!!!!DESCRIPTION!!!!}gx;
312     $longdescription =~ s{\&lt;\% (.+?) \%\&gt;}{ $section->can($1) ? $::locale->quote_special_chars('HTML', $section->$1 // '') : '<' . t8('Invalid variable #1', $1) . '>' }egx;
313     $longdescription =~ s{!!!!DESCRIPTION!!!!}{ $section->description // '' }egx;
314   }
315
316   $item->assign_attributes(
317     parts_id        => $part->id,
318     description     => $description,
319     longdescription => $longdescription,
320     qty             => $is_time_based ? $section->time_estimation * 1 : 1,
321     unit            => $is_time_based ? $self->h_unit_name            : $part->unit,
322     sellprice       => $::form->round_amount($self->requirement_spec->hourly_rate * ($is_time_based ? 1 : $section->time_estimation * $section->sellprice_factor), 2),
323     lastcost        => $part->lastcost * $section->sellprice_factor,
324     discount        => 0,
325     project_id      => $self->requirement_spec->project_id,
326   );
327
328   return $item;
329 }
330
331 sub create_additional_part_order_item {
332   my ($self, %params) = @_;
333
334   my $add_part        = $params{additional_part};
335   my $item            = $params{item} || SL::DB::OrderItem->new;
336   my $part            = $self->parts->{ $add_part->part_id };
337   my $translation     = $params{language_id} ? first { $params{language_id} == $_->language_id } @{ $part->translations } : {};
338   my $description     = $item->description              || $add_part->description;
339   my $longdescription = $translation->{longdescription} || $part->notes;
340
341   $item->assign_attributes(
342     parts_id        => $part->id,
343     description     => $description,
344     longdescription => $longdescription,
345     qty             => $add_part->qty,
346     unit            => $add_part->unit->name,
347     sellprice       => $add_part->unit->convert_to($part->sellprice, $part->unit_obj),
348     lastcost        => $part->lastcost,
349     discount        => 0,
350     project_id      => $self->requirement_spec->project_id,
351   );
352
353   return $item;
354 }
355
356 sub create_order {
357   my ($self, %params) = @_;
358
359   my @part_ids = (
360     map({ $_->{order_part_id} } @{ $params{sections} }),
361     map({ $_->part_id         } @{ $params{additional_parts} }),
362   );
363   $self->{parts} = { map { ($_->{id} => $_) } @{ SL::DB::Manager::Part->get_all(where => [ id => [ uniq @part_ids ] ]) } };
364
365   my $customer   = SL::DB::Customer->new(id => $::form->{customer_id})->load;
366   my @orderitems = map { $self->create_order_item(                section => $_,         language_id => $customer->language_id) } @{ $params{sections} };
367   my @add_items  = map { $self->create_additional_part_order_item(additional_part => $_, language_id => $customer->language_id) } @{ $params{additional_parts} };
368   my $employee   = SL::DB::Manager::Employee->current;
369   my $reqdate    = !$::form->{quotation} ? undef
370                  : $customer->payment_id ? $customer->payment->calc_date
371                  :                         DateTime->today_local->next_workday(extra_days => $::instance_conf->get_reqdate_interval)->to_kivitendo;
372   my $record_type = $::form->{quotation} ? SALES_QUOTATION_TYPE() : SALES_ORDER_TYPE();
373   my $order      = SL::DB::Order->new(
374     record_type             => $record_type,
375     globalproject_id        => $self->requirement_spec->project_id,
376     transdate               => DateTime->today_local,
377     reqdate                 => $reqdate,
378     orderitems              => [ @orderitems, @add_items ],
379     customer_id             => $customer->id,
380     taxincluded             => $customer->taxincluded,
381     intnotes                => $customer->notes,
382     language_id             => $customer->language_id,
383     payment_id              => $customer->payment_id,
384     taxzone_id              => $customer->taxzone_id,
385     employee_id             => $employee->id,
386     salesman_id             => $employee->id,
387     transaction_description => $self->requirement_spec->displayable_name,
388     currency_id             => $::instance_conf->get_currency_id,
389   );
390
391   $order->calculate_prices_and_taxes;
392
393   return $order;
394 }
395
396 1;