5c8513264ae697b8245c8aae184c4ccc2c5f1e82
[kivitendo-erp.git] / SL / Controller / Order.pm
1 package SL::Controller::Order;
2
3 use strict;
4 use parent qw(SL::Controller::Base);
5
6 use SL::Helper::Flash;
7 use SL::ClientJS;
8 use SL::Presenter;
9
10 use SL::DB::Order;
11 use SL::DB::Customer;
12 use SL::DB::Vendor;
13 use SL::DB::TaxZone;
14 use SL::DB::Employee;
15 use SL::DB::Project;
16 use SL::DB::Default;
17 use SL::DB::Unit;
18
19 use SL::Helper::DateTime;
20
21 use List::Util qw(max first);
22 use List::MoreUtils qw(none pairwise);
23
24 use Rose::Object::MakeMethods::Generic
25 (
26  'scalar --get_set_init' => [ qw(order valid_types type cv js p) ],
27 );
28
29
30 # safety
31 __PACKAGE__->run_before('_check_auth');
32
33 __PACKAGE__->run_before('_setup',
34                         only => [ qw(edit update save) ]);
35
36
37 #
38 # actions
39 #
40
41 sub action_add {
42   my ($self) = @_;
43
44   $self->order->transdate(DateTime->now_local());
45
46   $self->_pre_render();
47   $self->render(
48     'order/form',
49     title => $self->type eq _sales_order_type()    ? $::locale->text('Add Sales Order')
50            : $self->type eq _purchase_order_type() ? $::locale->text('Add Purchase Order')
51            : '',
52     %{$self->{template_args}}
53   );
54 }
55
56 sub action_edit {
57   my ($self) = @_;
58
59   $self->_pre_render();
60   $self->render(
61     'order/form',
62     title => $self->type eq _sales_order_type()    ? $::locale->text('Edit Sales Order')
63            : $self->type eq _purchase_order_type() ? $::locale->text('Edit Purchase Order')
64            : '',
65     %{$self->{template_args}}
66   );
67 }
68
69 sub action_update {
70   my ($self) = @_;
71
72   $self->_pre_render();
73   $self->render(
74     'order/form',
75     title => $self->type eq _sales_order_type()    ? $::locale->text('Edit Sales Order')
76            : $self->type eq _purchase_order_type() ? $::locale->text('Edit Purchase Order')
77            : '',
78     %{$self->{template_args}}
79   );
80 }
81
82 sub action_save {
83   my ($self) = @_;
84
85   $self->_save();
86
87   my @redirect_params = (
88     action => 'edit',
89     type   => $self->type,
90     id     => $self->order->id,
91   );
92
93   $self->redirect_to(@redirect_params);
94 }
95
96 sub action_customer_vendor_changed {
97   my ($self) = @_;
98
99   if ($self->cv eq 'customer') {
100     $self->order->customer(SL::DB::Manager::Customer->find_by_or_create(id => $::form->{cv_id}));
101
102   } elsif ($self->cv eq 'vendor') {
103     $self->order->vendor(SL::DB::Manager::Vendor->find_by_or_create(id => $::form->{cv_id}));
104   }
105
106   if ($self->order->{$self->cv}->contacts && scalar @{ $self->order->{$self->cv}->contacts } > 0) {
107     $self->js->show('#cp_row');
108   } else {
109     $self->js->hide('#cp_row');
110   }
111
112   if ($self->order->{$self->cv}->shipto && scalar @{ $self->order->{$self->cv}->shipto } > 0) {
113     $self->js->show('#shipto_row');
114   } else {
115     $self->js->hide('#shipto_row');
116   }
117
118   $self->js
119     ->replaceWith('#order_cp_id',     $self->build_contact_select)
120     ->replaceWith('#order_shipto_id', $self->build_shipto_select)
121     ->val('#order_taxzone_id', $self->order->{$self->cv}->taxzone_id)
122     ->focus('#order_' . $self->cv . ' _id')
123     ->render($self);
124 }
125
126 sub action_add_item {
127   my ($self) = @_;
128
129   my $form_attr = $::form->{add_item};
130   my $item      = SL::DB::OrderItem->new;
131   $item->assign_attributes(%$form_attr);
132
133   my $part        = SL::DB::Part->new(id => $form_attr->{parts_id})->load;
134   my $cv_class    = "SL::DB::" . ucfirst($self->cv);
135   my $cv_discount = $::form->{$self->cv . '_id'}? $cv_class->new(id => $::form->{$self->cv . '_id'})->load->discount :0.0;
136
137   my %new_attr;
138   $new_attr{id}        = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
139   $new_attr{part}      = $part;
140   $new_attr{qty}       = 1.0               if ! $item->{qty};
141   $new_attr{unit}      = $part->unit;
142   $new_attr{sellprice} = $part->sellprice  if ! $item->{sellprice};
143   $new_attr{discount}  = $cv_discount      if ! $item->{discount};
144   $item->assign_attributes(%new_attr);
145
146   # add_items seems to fail if no items had been added before
147   if ($self->order->items) {
148     $self->order->add_items($item);
149   } else {
150     $self->order->items([$item]);
151   }
152
153   $self->_setup();
154
155   my $row_as_html = $self->p->render('order/tabs/_row', ITEM => $item);
156
157   $self->js
158     ->append('#row_table_id tbody', $row_as_html)
159     ->focus('#row_table_id tr:last [id$="parts_id_name"]')
160     ->off('[id^="order_orderitems"][id$="parts_id"]', 'change', 'set_item_values')
161     ->on('[id^="order_orderitems"][id$="parts_id"]', 'change', 'set_item_values')
162     ->html('#netamount_id', $::form->format_amount(\%::myconfig, $self->order->netamount, -2))
163     ->html('#amount_id',    $::form->format_amount(\%::myconfig, $self->order->amount,    -2))
164     ->remove('.tax_row')
165     ->insertBefore($self->build_tax_rows, '#amount_row_id')
166     ->render($self);
167 }
168
169 sub action_set_item_values {
170   my ($self) = @_;
171
172   my $is_new  = $::form->{item_id} =~ m{^new_};
173   my $item_id = $::form->{item_id};
174
175   my $item      = first {$_->id   eq $::form->{item_id}} @{$self->order->items};
176   my $form_attr = first {$_->{id} eq $::form->{item_id}} @{ $::form->{order}->{orderitems} };
177
178   delete $form_attr->{id};
179
180   my $part = SL::DB::Part->new(id => $form_attr->{parts_id})->load;
181
182   my $cv_class    = "SL::DB::" . ucfirst($self->cv);
183   my $cv_discount = $::form->{cv_id}? $cv_class->new(id => $::form->{$self->cv . '_id'})->load->discount :0.0;
184
185
186   my %new_attr;
187   $new_attr{sellprice} = $part->sellprice  if ! $form_attr->{sellprice_as_number};
188   $new_attr{discount}  = $cv_discount      if ! $form_attr->{discount_as_percent};
189   $new_attr{unit}      = $part->unit       if ! $form_attr->{unit};
190   $new_attr{qty}       = 1.0               if ! $form_attr->{qty_as_number};
191
192   $item->assign_attributes(%new_attr);
193
194
195   $self->_setup();
196
197   $self->js
198     ->val( '#' . $::form->{qty_dom_id},       $item->qty_as_number)
199     ->val( '#' . $::form->{unit_dom_id},      $item->unit)
200     ->val( '#' . $::form->{sellprice_dom_id}, $item->sellprice_as_number)
201     ->val( '#' . $::form->{discount_dom_id},  $item->discount_as_percent)
202     ->run('display_linetotal', $::form->{item_id}, $::form->format_amount(\%::myconfig, $item->{linetotal}, -2))
203     ->html('#netamount_id', $::form->format_amount(\%::myconfig, $self->order->netamount, -2))
204     ->html('#amount_id',    $::form->format_amount(\%::myconfig, $self->order->amount,    -2))
205     ->remove('.tax_row')
206     ->insertBefore($self->build_tax_rows, '#amount_row_id')
207     ->render($self);
208 }
209
210
211 #
212 # helpers
213 #
214
215 sub init_valid_types {
216   [ _sales_order_type(), _purchase_order_type() ];
217 }
218
219 sub init_type {
220   my ($self) = @_;
221
222   if (none { $::form->{type} eq $_ } @{$self->valid_types}) {
223     die "Not a valid type for order";
224   }
225
226   $self->type($::form->{type});
227 }
228
229 sub init_cv {
230   my ($self) = @_;
231
232   my $cv = $self->type eq _sales_order_type()    ? 'customer'
233          : $self->type eq _purchase_order_type() ? 'vendor'
234          : die "Not a valid type for order";
235
236   return $cv;
237 }
238
239 sub init_js {
240   SL::ClientJS->new;
241 }
242
243 sub init_p {
244   SL::Presenter->get;
245 }
246
247 sub init_order {
248   _make_order();
249 }
250
251 sub _check_auth {
252   my ($self) = @_;
253
254   my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
255
256   my $right   = $right_for->{ $self->type };
257   $right    ||= 'DOES_NOT_EXIST';
258
259   $::auth->assert($right);
260 }
261
262 sub build_contact_select {
263   my ($self) = @_;
264
265   $self->p->select_tag('order.cp_id', [ $self->order->{$self->cv}->contacts ],
266                        value_key  => 'cp_id',
267                        title_key  => 'full_name_dep',
268                        default    => $self->order->cp_id,
269                        with_empty => 1,
270                        style      => 'width: 300px',
271   );
272 }
273
274 sub build_shipto_select {
275   my ($self) = @_;
276
277   $self->p->select_tag('order.shipto_id', [ $self->order->{$self->cv}->shipto ],
278                        value_key  => 'shipto_id',
279                        title_key  => 'displayable_id',
280                        default    => $self->order->shipto_id,
281                        with_empty => 1,
282                        style      => 'width: 300px',
283   );
284 }
285
286 sub build_tax_rows {
287   my ($self) = @_;
288
289   my $rows_as_html;
290   foreach my $tax (@{ $self->{taxes} }) {
291     $rows_as_html .= $self->p->render('order/tabs/_tax_row', TAX => $tax);
292   }
293   return $rows_as_html;
294 }
295
296
297 sub _make_order {
298   my ($self) = @_;
299
300   my $order = SL::DB::Manager::Order->find_by_or_create(id => $::form->{id});
301
302   $order->assign_attributes(%{$::form->{order}});
303
304   return $order;
305 }
306
307
308 sub _setup {
309   my ($self) = @_;
310
311   # bb: todo: currency later
312   $self->order->currency_id($::instance_conf->get_currency_id());
313
314   my %pat = $self->order->calculate_prices_and_taxes();
315
316   foreach my $tax_chart_id (keys %{ $pat{taxes} }) {
317     my $tax = SL::DB::Manager::Tax->find_by(chart_id => $tax_chart_id);
318     push(@{ $self->{taxes} }, { amount => $pat{taxes}->{$tax_chart_id},
319                                 tax    => $tax });
320   }
321
322   pairwise { $a->{linetotal} = $b->{linetotal} } @{$self->order->items}, @{$pat{items}};
323 }
324
325 sub _save {
326   my ($self) = @_;
327
328   my $db = $self->order->db;
329
330   $db->do_transaction(
331     sub {
332       $self->order->save();
333   }) || die($db->error);
334 }
335
336
337 sub _pre_render {
338   my ($self) = @_;
339
340   $self->{all_taxzones}  = SL::DB::Manager::TaxZone->get_all_sorted();
341   $self->{all_employees} = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->employee_id,
342                                                                                  deleted => 0 ] ],
343                                                               sort_by => 'name');
344   $self->{all_projects}  = SL::DB::Manager::Project->get_all(where => [ or => [ id => $self->order->globalproject_id,
345                                                                                 active => 1 ] ],
346                                                              sort_by => 'projectnumber');
347
348   $self->{current_employee_id} = SL::DB::Manager::Employee->current->id;
349 }
350
351 sub _sales_order_type {
352   'sales_order';
353 }
354
355 sub _purchase_order_type {
356   'purchase_order';
357 }
358
359 1;