GDPDU: DATEV-ähnlicher Buchungsexport Rohversion
[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::DB::Customer;
12 use SL::DB::Order;
13 use SL::DB::Part;
14 use SL::DB::RequirementSpec;
15 use SL::DB::RequirementSpecOrder;
16 use SL::Helper::Flash;
17 use SL::Locale::String;
18
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';
21
22 use Rose::Object::MakeMethods::Generic
23 (
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) ],
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;
45   }
46
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)
50            ->render;
51 }
52
53 sub action_create {
54   my ($self)         = @_;
55
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;
58   }
59
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 };
64
65   $sections_by_id{ $_->{id} }->update_attributes(order_part_id => $_->{order_part_id}) for @{ $section_attrs };
66
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 {
70     $order->save;
71
72     $self->requirement_spec->add_orders(SL::DB::RequirementSpecOrder->new(order => $order, version => $self->requirement_spec->version));
73     $self->requirement_spec->save;
74
75     $self->requirement_spec->link_to_record($order);
76   }) or do {
77     $::lxdebug->message(LXDebug::WARN(), "Error creating the order object: $@");
78   };
79
80   $self->init_requirement_spec;
81
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))
87            ->render;
88 }
89
90 sub action_update {
91   my ($self)   = @_;
92
93   my $order    = $self->rs_order->order;
94   my $sections = $self->requirement_spec->sections_sorted;
95
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;
98   }
99
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 };
103
104     $sections_seen{ $section->id } = 1 if $section;
105
106     push @orderitems, { item => $item, section => $section };
107   }
108
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 },
114   );
115
116   $self->js->hide(LIST_SELECTOR())
117            ->after(LIST_SELECTOR(), $html)
118            ->render;
119 }
120
121 sub action_do_update {
122   my ($self)         = @_;
123
124   my $order          = $self->rs_order->order;
125   my @new_orderitems =  $self->do_update_sections;
126   push @new_orderitems, $self->do_update_additional_parts;
127
128   $order->add_orderitems(\@new_orderitems) if @new_orderitems;
129
130   $order->calculate_prices_and_taxes;
131
132   $order->db->with_transaction(sub {
133     $order->save;
134     $self->requirement_spec->link_to_record($order);
135   }) or do {
136     $::lxdebug->message(LXDebug::WARN(), "Error updating the order object: $@");
137   };
138
139   $self->init_requirement_spec;
140
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))
145            ->render;
146 }
147
148 sub action_edit_assignment {
149   my ($self) = @_;
150
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;
153   }
154
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)
158            ->reinit_widgets
159            ->render;
160 }
161
162 sub action_save_assignment {
163   my ($self)   = @_;
164   my $sections = $::form->{sections} || [];
165   SL::DB::RequirementSpecItem->new(id => $_->{id})->load->update_attributes(order_part_id => ($_->{order_part_id} || undef)) for @{ $sections };
166
167   my $html = $self->render('requirement_spec_order/list', { output => 0 });
168   $self->js->replaceWith(LIST_SELECTOR(), $html)
169            ->remove(FORMS_SELECTOR())
170            ->render;
171 }
172
173 sub action_delete {
174   my ($self) = @_;
175
176   my $order  = $self->rs_order->order;
177
178   $order->delete;
179   $self->init_requirement_spec;
180
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))
184            ->render;
185 }
186
187 #
188 # filters
189 #
190
191 sub setup {
192   my ($self) = @_;
193
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);
197
198   return 1;
199 }
200
201 sub init_requirement_spec {
202   my ($self) = @_;
203   $self->requirement_spec(SL::DB::RequirementSpec->new(id => $::form->{requirement_spec_id})->load) if $::form->{requirement_spec_id};
204 }
205
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 }
210
211 sub init_all_parts_time_unit {
212   my ($self) = @_;
213
214   return [] unless $self->h_unit_name;
215
216   my @convertible_unit_names = map { $_->name } @{ SL::DB::Manager::Unit->time_based_units };
217
218   return SL::DB::Manager::Part->get_all_sorted(where => [ unit => \@convertible_unit_names ]);
219 }
220
221 #
222 # helpers
223 #
224
225 sub cache_parts {
226   my ($self, @ids) = @_;
227
228   my $parts = !@ids ? [] : SL::DB::Manager::Part->get_all(
229     where        => [ id => \@ids ],
230     with_objects => [ qw(unit_obj) ],
231   );
232
233   $self->parts({ map { ($_->id => $_) } @{ $parts } });
234 }
235
236 sub do_update_sections {
237   my ($self)           = @_;
238
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;
244
245   $self->cache_parts(uniq map { $_->order_part_id } @{ $sections });
246
247   my %sections_seen;
248
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;
253
254     $self->create_order_item(section => $section, item => $orderitem, language_id => $language_id)->save;
255     $sections_seen{ $section->id } = 1;
256   }
257
258   my @new_orderitems = map  { $self->create_order_item(section => $_, language_id => $language_id) }
259                        grep { !$sections_seen{ $_->id } }
260                        @{ $sections };
261
262   return @new_orderitems;
263 }
264
265 sub do_update_additional_parts {
266   my ($self)        = @_;
267
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;
272
273   $self->cache_parts(uniq map { $_->part_id } @{ $add_parts });
274
275   my %add_part_seen;
276   my @new_orderitems;
277
278   foreach my $add_part (@{ $add_parts }) {
279     my $key       = $add_part->part_id . '-' . $add_part->description;
280     my $orderitem = $orderitems_by{$key};
281
282     if ($orderitem) {
283       $self->create_additional_part_order_item(additional_part => $add_part, item => $orderitem, language_id => $language_id)->save;
284
285     } else {
286       push @new_orderitems, $self->create_additional_part_order_item(additional_part => $add_part, language_id => $language_id);
287     }
288   }
289
290   return @new_orderitems;
291 }
292
293 sub create_order_item {
294   my ($self, %params) = @_;
295
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;
303
304   if (!$section->{keep_description}) {
305     $description     = '<%fb_number%> <%title%>' unless $description =~ m{<%};
306     $longdescription = '&lt;%description%&gt;'   unless $longdescription =~ m{&lt;%};
307
308     $description     =~ s{<% (.+?) %>}{ $section->can($1) ? $section->$1 : '<' . t8('Invalid variable #1', $1) . '>' }egx;
309     $longdescription =~ s{\&lt;\% description \%\&gt;}{!!!!DESCRIPTION!!!!}gx;
310     $longdescription =~ s{<[pP]> !!!!DESCRIPTION!!!! </[pP]>}{!!!!DESCRIPTION!!!!}gx;
311     $longdescription =~ s{\&lt;\% (.+?) \%\&gt;}{ $section->can($1) ? $::locale->quote_special_chars('HTML', $section->$1 // '') : '<' . t8('Invalid variable #1', $1) . '>' }egx;
312     $longdescription =~ s{!!!!DESCRIPTION!!!!}{ $section->description // '' }egx;
313   }
314
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,
323     discount        => 0,
324     project_id      => $self->requirement_spec->project_id,
325   );
326
327   return $item;
328 }
329
330 sub create_additional_part_order_item {
331   my ($self, %params) = @_;
332
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;
339
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,
348     discount        => 0,
349     project_id      => $self->requirement_spec->project_id,
350   );
351
352   return $item;
353 }
354
355 sub create_order {
356   my ($self, %params) = @_;
357
358   my @part_ids = (
359     map({ $_->{order_part_id} } @{ $params{sections} }),
360     map({ $_->part_id         } @{ $params{additional_parts} }),
361   );
362   $self->{parts} = { map { ($_->{id} => $_) } @{ SL::DB::Manager::Part->get_all(where => [ id => [ uniq @part_ids ] ]) } };
363
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,
384   );
385
386   $order->calculate_prices_and_taxes;
387
388   return $order;
389 }
390
391 1;