Merge branch 'b-3.6.1' of ../kivitendo-erp_20220811
[kivitendo-erp.git] / SL / Controller / PartsPriceUpdate.pm
1 package SL::Controller::PartsPriceUpdate;
2
3 use strict;
4 use parent qw(SL::Controller::Base);
5
6 use SL::DBUtils qw(prepare_query selectfirst_array_query prepare_query do_statement do_query);
7 use SL::JSON;
8 use SL::Helper::Flash qw(flash);
9 use SL::DB;
10 use SL::DB::Part;
11 use SL::DB::Pricegroup;
12 use SL::Locale::String qw(t8);
13
14 use Rose::Object::MakeMethods::Generic (
15   'scalar --get_set_init' => [ qw(pricegroups pricegroups_by_id filter) ],
16 );
17
18 __PACKAGE__->run_before('check_rights');
19
20
21 sub action_search_update_prices {
22   my ($self) = @_;
23
24   $self->setup_search_update_prices_action_bar;
25   $self->render('ic/search_update_prices',
26     title => t8('Update Prices'),
27   );
28 }
29
30 sub action_confirm_price_update {
31   my ($self) = @_;
32
33   my @errors;
34   my $found;
35
36   for my $key (keys %{ $self->filter->{prices} || {} }) {
37     my $row = $self->filter->{prices}{$key};
38
39     next if $row->{price_as_number} eq '';
40
41     my $type   = $row->{type};
42     my $value  = $::form->parse_amount(\%::myconfig, $row->{price_as_number});
43     my $name   = $key =~ /^\d+$/      ? $self->pricegroups_by_id->{$key}->pricegroup
44                : $key eq 'sellprice'  ? t8('Sell Price')
45                : $key eq 'listprice'  ? t8('List Price')
46                :                        '';
47
48     if (0 > $value && ($type eq 'percent')) {
49       push @errors, t8('You cannot adjust the price for pricegroup "#1" by a negative percentage.', $name);
50     } elsif (!$value) {
51       push @errors, t8('No valid number entered for pricegroup "#1".', $name);
52     } elsif (0 < $value) {
53       $found = 1;
54     }
55   }
56
57   push @errors, t8('No prices will be updated because no prices have been entered.') if !$found;
58
59   my $num_matches = $self->get_num_matches_for_priceupdate();
60
61   if (@errors) {
62     flash('error', $_) for @errors;
63     return $self->action_search_update_prices;
64   } else {
65
66     my $key = $::auth->create_unique_session_value(SL::JSON::to_json($self->filter));
67
68     $self->setup_confirm_price_update_action_bar;
69     $self->render('ic/confirm_price_update',
70       num_matches => $num_matches,
71       filter_key  => $key,
72     );
73   }
74 }
75
76 sub action_update_prices {
77   my ($self) = @_;
78
79   my $num_updated = $self->do_update_prices;
80
81   if ($num_updated) {
82     $::form->redirect(t8('#1 prices were updated.', $num_updated));
83   } else {
84     $::form->error(t8('Could not update prices!'));
85   }
86 }
87
88 sub _create_filter_for_priceupdate {
89   my ($self) = @_;
90   my $filter = $self->filter;
91
92   my @where_values;
93   my $where = '1 = 1';
94
95   for my $item (qw(partnumber drawing microfiche make model pg.partsgroup description serialnumber)) {
96     my $column = $item;
97     $column =~ s/.*\.//;
98     next unless $filter->{$column};
99
100     $where .= qq| AND $item ILIKE ?|;
101     push @where_values, "%$filter->{$column}%";
102   }
103
104   # items which were never bought, sold or on an order
105   if ($filter->{itemstatus} eq 'orphaned') {
106     $where .=
107       qq| AND (p.onhand = 0)
108           AND p.id NOT IN
109             (
110               SELECT DISTINCT parts_id FROM invoice
111               UNION
112               SELECT DISTINCT parts_id FROM assembly
113               UNION
114               SELECT DISTINCT parts_id FROM orderitems
115               UNION
116               SELECT DISTINCT parts_id FROM delivery_order_items
117             )|;
118
119   } elsif ($filter->{itemstatus} eq 'active') {
120     $where .= qq| AND p.obsolete = '0'|;
121
122   } elsif ($filter->{itemstatus} eq 'obsolete') {
123     $where .= qq| AND p.obsolete = '1'|;
124
125   } elsif ($filter->{itemstatus} eq 'onhand') {
126     $where .= qq| AND p.onhand > 0|;
127
128   } elsif ($filter->{itemstatus} eq 'short') {
129     $where .= qq| AND p.onhand < p.rop|;
130
131   }
132
133   for my $column (qw(make model)) {
134     next unless ($filter->{$column});
135     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
136     push @where_values, "%$filter->{$column}%";
137   }
138
139   return ($where, @where_values);
140 }
141
142 sub get_num_matches_for_priceupdate {
143   my ($self)   = @_;
144   my $filter   = $self->filter;
145   my $dbh      = SL::DB->client->dbh;
146   my ($where, @where_values) = $self->_create_filter_for_priceupdate;
147
148   my $num_updated = 0;
149   my $query;
150
151   for my $column (qw(sellprice listprice)) {
152     next if $filter->{prices}{$column}{price_as_number} eq "";
153
154     $query =
155       qq|SELECT COUNT(*)
156          FROM parts
157          WHERE id IN
158            (SELECT p.id
159             FROM parts p
160             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
161             WHERE $where)|;
162     my ($result)  = selectfirst_array_query($::form, $dbh, $query, @where_values);
163     $num_updated += $result if (0 <= $result);
164   }
165
166   my @ids = grep { $filter->{prices}{$_}{price_as_number} } map { $_->id } @{ $self->pricegroups };
167   if (@ids) {
168     $query =
169       qq|SELECT COUNT(*)
170          FROM prices
171          WHERE parts_id IN
172            (SELECT p.id
173             FROM parts p
174             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
175             WHERE $where)
176          AND pricegroup_id IN (@{[ join ',', ('?')x@ids ]})|;
177
178     my ($result)  = selectfirst_array_query($::form, $dbh, $query, @where_values, @ids);
179     $num_updated += $result if (0 <= $result);
180   }
181
182   return $num_updated;
183 }
184
185 sub do_update_prices {
186   SL::DB->client->with_transaction(\&_update_prices, $_[0]);
187 }
188
189 sub _update_prices {
190   my ($self) = @_;
191   my $filter_json = $::auth->get_session_value($::form->{filter_key});
192   my $filter = SL::JSON::from_json($filter_json);
193   $self->filter($filter);
194   die "missing filter" unless $filter;
195
196   my ($where, @where_values) = $self->_create_filter_for_priceupdate;
197   my $num_updated = 0;
198
199   # connect to database
200   my $dbh = SL::DB->client->dbh;
201
202   for my $column (qw(sellprice listprice)) {
203     my $row = $filter->{prices}{$column};
204     next if ($row->{price_as_number} eq "");
205
206     my $value = $::form->parse_amount(\%::myconfig, $row->{price_as_number});
207     my $operator = '+';
208
209     if ($row->{type} eq "percent") {
210       $value = ($value / 100) + 1;
211       $operator = '*';
212     }
213
214     my $query =
215       qq|UPDATE parts SET $column = $column $operator ?
216          WHERE id IN
217            (SELECT p.id
218             FROM parts p
219             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
220             WHERE $where)|;
221     my $result    = do_query($::form, $dbh, $query, $value, @where_values);
222     $num_updated += $result if 0 <= $result;
223   }
224
225   my $q_add =
226     qq|UPDATE prices SET price = price + ?
227        WHERE parts_id IN
228          (SELECT p.id
229           FROM parts p
230           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
231           WHERE $where) AND (pricegroup_id = ?)|;
232   my $sth_add = prepare_query($::form, $dbh, $q_add);
233
234   my $q_multiply =
235     qq|UPDATE prices SET price = price * ?
236        WHERE parts_id IN
237          (SELECT p.id
238           FROM parts p
239           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
240           WHERE $where) AND (pricegroup_id = ?)|;
241   my $sth_multiply = prepare_query($::form, $dbh, $q_multiply);
242
243   for my $pg (@{ $self->pricegroups }) {
244     my $row = $filter->{prices}{$pg->id};
245     next if $row->{price_as_number} eq "";
246
247     my $value = $::form->parse_amount(\%::myconfig, $row->{price_as_number});
248     my $result;
249
250     if ($row->{type} eq "percent") {
251       $result = do_statement($::form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, $pg->id);
252     } else {
253       $result = do_statement($::form, $sth_add, $q_add, $value, @where_values, $pg->id);
254     }
255
256     $num_updated += $result if (0 <= $result);
257   }
258
259   $sth_add->finish;
260   $sth_multiply->finish;
261
262   1;
263 }
264
265 sub init_pricegroups {
266   SL::DB::Manager::Pricegroup->get_all_sorted(query => [
267     obsolete => 0,
268   ]);
269 }
270
271 sub init_pricegroups_by_id {
272   +{ map { $_->id => $_ } @{ $_[0]->pricegroups } }
273 }
274
275 sub check_rights {
276   $::auth->assert('part_service_assembly_edit');
277 }
278
279 sub init_filter {
280   $::form->{filter} || {};
281 }
282
283 sub setup_search_update_prices_action_bar {
284   my ($self, %params) = @_;
285
286   for my $bar ($::request->layout->get('actionbar')) {
287     $bar->add(
288       action => [
289         t8('Continue'),
290         submit    => [ '#form', { action => 'PartsPriceUpdate/confirm_price_update' } ],
291         accesskey => 'enter',
292       ],
293     );
294   }
295 }
296
297 sub setup_confirm_price_update_action_bar {
298   my ($self, %params) = @_;
299
300   for my $bar ($::request->layout->get('actionbar')) {
301     $bar->add(
302       action => [
303         t8('Continue'),
304         submit    => [ '#form', { action => 'PartsPriceUpdate/update_prices' } ],
305         accesskey => 'enter',
306       ],
307
308       action => [
309         t8('Back'),
310         call => [ 'kivi.history_back' ],
311       ],
312     );
313   }
314 }
315
316 1;