Bug 9468: use new SUGGEST_FORMAT list
[koha.git] / admin / categorie.pl
1 #!/usr/bin/perl
2
3 #script to administer the categories table
4 #written 20/02/2002 by paul.poulain@free.fr
5
6 # ALGO :
7 # this script use an $op to know what to do.
8 # if $op is empty or none of the above values,
9 #       - the default screen is build (with all records, or filtered datas).
10 #       - the   user can clic on add, modify or delete record.
11 # if $op=add_form
12 #       - if primkey exists, this is a modification,so we read the $primkey record
13 #       - builds the add/modify form
14 # if $op=add_validate
15 #       - the user has just send datas, so we create/modify the record
16 # if $op=delete_form
17 #       - we show the record having primkey=$primkey and ask for deletion validation form
18 # if $op=delete_confirm
19 #       - we delete the record having primkey=$primkey
20
21 # Copyright 2000-2002 Katipo Communications
22 #
23 # This file is part of Koha.
24 #
25 # Koha is free software; you can redistribute it and/or modify it
26 # under the terms of the GNU General Public License as published by
27 # the Free Software Foundation; either version 3 of the License, or
28 # (at your option) any later version.
29 #
30 # Koha is distributed in the hope that it will be useful, but
31 # WITHOUT ANY WARRANTY; without even the implied warranty of
32 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 # GNU General Public License for more details.
34 #
35 # You should have received a copy of the GNU General Public License
36 # along with Koha; if not, see <http://www.gnu.org/licenses>.
37
38 use Modern::Perl;
39
40 use CGI qw ( -utf8 );
41 use C4::Context;
42 use C4::Auth;
43 use C4::Branch;
44 use C4::Output;
45 use C4::Form::MessagingPreferences;
46 use Koha::Database;
47 use Koha::DateUtils;
48
49 sub StringSearch {
50     my ( $searchstring, $type ) = @_;
51     my $dbh = C4::Context->dbh;
52     $searchstring //= '';
53     $searchstring =~ s/\'/\\\'/g;
54     my @data = split( ' ', $searchstring );
55     push @data, q{} if $#data == -1;
56     my $count = @data;
57     my $sth   = $dbh->prepare("Select * from categories where (description like ?) order by category_type,description,categorycode");
58     $sth->execute("$data[0]%");
59     my @results;
60
61     while ( my $data = $sth->fetchrow_hashref ) {
62         push( @results, $data );
63     }
64
65     #  $sth->execute;
66     $sth->finish;
67     return ( scalar(@results), \@results );
68 }
69
70 my $input         = new CGI;
71 my $searchfield   = $input->param('description');
72 my $script_name   = "/cgi-bin/koha/admin/categorie.pl";
73 my $categorycode  = $input->param('categorycode');
74 my $op            = $input->param('op') // 'list';
75 my $block_expired = $input->param("block_expired");
76 my @messages;
77
78 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
79     {
80         template_name   => "admin/categorie.tt",
81         query           => $input,
82         type            => "intranet",
83         authnotrequired => 0,
84         flagsrequired   => { parameters => 'parameters_remaining_permissions' },
85         debug           => 1,
86     }
87 );
88
89 ################## ADD_FORM ##################################
90 # called by default. Used to create form to add or  modify a record
91 if ( $op eq 'add_form' ) {
92     $template->param( add_form => 1 );
93
94     #---- if primkey exists, it's a modify action, so read values to modify...
95     my $data;
96     my @selected_branches;
97     if ($categorycode) {
98         my $dbh = C4::Context->dbh;
99         my $sth =
100           $dbh->prepare("SELECT * FROM categories WHERE categorycode=?");
101         $sth->execute($categorycode);
102         $data = $sth->fetchrow_hashref;
103
104         $sth = $dbh->prepare(
105             "SELECT b.branchcode, b.branchname 
106             FROM categories_branches AS cb, branches AS b 
107             WHERE cb.branchcode = b.branchcode AND cb.categorycode = ?
108         ");
109         $sth->execute($categorycode);
110         while ( my $branch = $sth->fetchrow_hashref ) {
111             push @selected_branches, $branch;
112         }
113         $sth->finish;
114     }
115
116     if (   $data->{'enrolmentperioddate'}
117         && $data->{'enrolmentperioddate'} eq '0000-00-00' )
118     {
119         $data->{'enrolmentperioddate'} = undef;
120     }
121
122     $data->{'category_type'} //= '';
123
124     my $branches = GetBranches();
125     my @branches_loop;
126     foreach my $branch ( sort keys %$branches ) {
127         my $selected =
128           ( grep { $$_{branchcode} eq $branch } @selected_branches ) ? 1 : 0;
129         push @branches_loop,
130           {
131             branchcode => $$branches{$branch}{branchcode},
132             branchname => $$branches{$branch}{branchname},
133             selected   => $selected,
134           };
135     }
136
137     $template->param(
138         branches_loop       => \@branches_loop,
139         description         => $data->{'description'},
140         enrolmentperiod     => $data->{'enrolmentperiod'},
141         enrolmentperioddate => $data->{'enrolmentperioddate'},
142         upperagelimit       => $data->{'upperagelimit'},
143         dateofbirthrequired => $data->{'dateofbirthrequired'},
144         enrolmentfee        => sprintf( "%.2f", $data->{'enrolmentfee'} || 0 ),
145         overduenoticerequired => $data->{'overduenoticerequired'},
146         issuelimit            => $data->{'issuelimit'},
147         reservefee            => sprintf( "%.2f", $data->{'reservefee'} || 0 ),
148         hidelostitems         => $data->{'hidelostitems'},
149         category_type         => $data->{'category_type'},
150         default_privacy       => $data->{'default_privacy'},
151         SMSSendDriver         => C4::Context->preference("SMSSendDriver"),
152         "type_" . $data->{'category_type'} => 1,
153         BlockExpiredPatronOpacActions =>
154           $data->{'BlockExpiredPatronOpacActions'},
155         TalkingTechItivaPhone =>
156           C4::Context->preference("TalkingTechItivaPhoneNotification"),
157     );
158
159     if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
160         C4::Form::MessagingPreferences::set_form_values(
161             { categorycode => $categorycode }, $template );
162     }
163
164     # END $OP eq ADD_FORM
165 ################## ADD_VALIDATE ##################################
166     # called by add_form, used to insert/modify data in DB
167 }
168 elsif ( $op eq 'add_validate' ) {
169
170     my $is_a_modif = $input->param("is_a_modif");
171
172     my $dbh = C4::Context->dbh;
173
174     if ( $input->param('enrolmentperioddate') ) {
175         my $enrolment_dt = eval { dt_from_string( $input->param('enrolmentperioddate') ) };
176         $enrolment_dt = eval { output_pref( { dt => $enrolment_dt, dateonly => 1, dateformat => 'iso' } ) } if ( $enrolment_dt );
177         $input->param( 'enrolmentperioddate' => $enrolment_dt );
178     }
179
180     if ($is_a_modif) {
181         my $sth = $dbh->prepare( "
182                 UPDATE categories
183                 SET description=?,
184                     enrolmentperiod=?,
185                     enrolmentperioddate=?,
186                     upperagelimit=?,
187                     dateofbirthrequired=?,
188                     enrolmentfee=?,
189                     reservefee=?,
190                     hidelostitems=?,
191                     overduenoticerequired=?,
192                     category_type=?,
193                     BlockExpiredPatronOpacActions=?,
194                     default_privacy=?
195                 WHERE categorycode=?"
196         );
197         $sth->execute(
198             map { $input->param($_) } (
199                 'description',           'enrolmentperiod',
200                 'enrolmentperioddate',   'upperagelimit',
201                 'dateofbirthrequired',   'enrolmentfee',
202                 'reservefee',            'hidelostitems',
203                 'overduenoticerequired', 'category_type',
204                 'block_expired',         'default_privacy',
205                 'categorycode'
206             )
207         );
208         $sth->finish;
209     }
210     else {
211         my $sth = $dbh->prepare( "
212             INSERT INTO categories (
213                 categorycode,
214                 description,
215                 enrolmentperiod,
216                 enrolmentperioddate,
217                 upperagelimit,
218                 dateofbirthrequired,
219                 enrolmentfee,
220                 reservefee,
221                 hidelostitems,
222                 overduenoticerequired,
223                 category_type,
224                 BlockExpiredPatronOpacActions,
225                 default_privacy
226             )
227             VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)" );
228         my $inserted = $sth->execute(
229             map { $input->param($_) } (
230                 'categorycode',    'description',
231                 'enrolmentperiod', 'enrolmentperioddate',
232                 'upperagelimit',   'dateofbirthrequired',
233                 'enrolmentfee',    'reservefee',
234                 'hidelostitems',   'overduenoticerequired',
235                 'category_type',   'block_expired',
236                 'default_privacy',
237             )
238         );
239         if ( $inserted ) {
240             push @messages, { type => 'message', code => 'success_on_insert' };
241         } else {
242             push @messages, { type => 'error', code => 'error_on_insert' };
243         }
244     }
245
246     my @branches = $input->param("branches");
247     if (@branches) {
248         my $sth = $dbh->prepare(
249             "DELETE FROM categories_branches WHERE categorycode = ?"
250         );
251         $sth->execute( $input->param("categorycode") );
252         $sth = $dbh->prepare(
253             "INSERT INTO categories_branches ( categorycode, branchcode ) VALUES ( ?, ? )"
254         );
255         for my $branchcode (@branches) {
256             next if not $branchcode;
257             $sth->bind_param( 1, $input->param("categorycode") );
258             $sth->bind_param( 2, $branchcode );
259             $sth->execute;
260         }
261     }
262
263     if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
264         C4::Form::MessagingPreferences::handle_form_action( $input,
265             { categorycode => $input->param('categorycode') }, $template );
266     }
267
268     $searchfield = q||;
269     $op = 'list';
270
271     # END $OP eq ADD_VALIDATE
272 ################## DELETE_CONFIRM ##################################
273     # called by default form, used to confirm deletion of data in DB
274 }
275 elsif ( $op eq 'delete_confirm' ) {
276     my $schema = Koha::Database->new()->schema();
277     $template->param( delete_confirm => 1 );
278
279     my $count =
280       $schema->resultset('Borrower')
281       ->search( { categorycode => $categorycode } )->count();
282
283     my $category = $schema->resultset('Category')->find($categorycode);
284
285     if ( $category->enrolmentperioddate
286         && $category->enrolmentperioddate eq '0000-00-00' )
287     {
288         $category->{'enrolmentperioddate'} = undef;
289     }
290
291     $template->param(
292         category            => $category,
293         description         => $category->description,
294         enrolmentperiod     => $category->enrolmentperiod,
295         enrolmentperioddate => $category->enrolmentperioddate,
296         patrons_in_category => $count,
297     );
298
299     # END $OP eq DELETE_CONFIRM
300 ################## DELETE_CONFIRMED ##################################
301   # called by delete_confirm, used to effectively confirm deletion of data in DB
302 }
303 elsif ( $op eq 'delete_confirmed' ) {
304     $template->param( delete_confirmed => 1 );
305     my $dbh = C4::Context->dbh;
306
307     my $categorycode = uc( $input->param('categorycode') );
308
309     my $sth = $dbh->prepare("delete from categories where categorycode=?");
310
311     my $deleted = $sth->execute($categorycode);
312
313     if ( $deleted ) {
314         push @messages, { type => 'message', code => 'success_on_delete' };
315     } else {
316         push @messages, { type => 'error', code => 'error_on_delete' };
317     }
318
319     $op = 'list';
320
321     # END $OP eq DELETE_CONFIRMED
322 }
323
324 if ( $op eq 'list' ) {
325     $template->param( else => 1 );
326     my @loop;
327     my ( $count, $results ) = StringSearch( $searchfield, 'web' );
328
329     my $dbh = C4::Context->dbh;
330     my $sth = $dbh->prepare("
331         SELECT b.branchcode, b.branchname 
332         FROM categories_branches AS cb, branches AS b 
333         WHERE cb.branchcode = b.branchcode AND cb.categorycode = ?
334     ");
335
336     for ( my $i = 0 ; $i < $count ; $i++ ) {
337         $sth->execute( $results->[$i]{'categorycode'} );
338
339         my @selected_branches;
340         while ( my $branch = $sth->fetchrow_hashref ) {
341             push @selected_branches, $branch;
342         }
343
344         my $enrolmentperioddate = $results->[$i]{'enrolmentperioddate'};
345         if ( $enrolmentperioddate && $enrolmentperioddate eq '0000-00-00' ) {
346             $enrolmentperioddate = undef;
347         }
348
349         $results->[$i]{'category_type'} //= '';
350
351         my %row = (
352             branches              => \@selected_branches,
353             categorycode          => $results->[$i]{'categorycode'},
354             description           => $results->[$i]{'description'},
355             enrolmentperiod       => $results->[$i]{'enrolmentperiod'},
356             enrolmentperioddate   => $enrolmentperioddate,
357             upperagelimit         => $results->[$i]{'upperagelimit'},
358             dateofbirthrequired   => $results->[$i]{'dateofbirthrequired'},
359             overduenoticerequired => $results->[$i]{'overduenoticerequired'},
360             issuelimit            => $results->[$i]{'issuelimit'},
361             hidelostitems         => $results->[$i]{'hidelostitems'},
362             category_type         => $results->[$i]{'category_type'},
363             default_privacy       => $results->[$i]{'default_privacy'},
364             reservefee => sprintf( "%.2f", $results->[$i]{'reservefee'} || 0 ),
365             enrolmentfee =>
366               sprintf( "%.2f", $results->[$i]{'enrolmentfee'} || 0 ),
367             "type_" . $results->[$i]{'category_type'} => 1,
368         );
369
370         if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
371             my $brief_prefs =
372               _get_brief_messaging_prefs( $results->[$i]{'categorycode'} );
373             $row{messaging_prefs} = $brief_prefs if @$brief_prefs;
374         }
375         push @loop, \%row;
376     }
377
378     $template->param( loop => \@loop );
379
380     # check that I (institution) and C (child) exists. otherwise => warning to the user
381     $sth = $dbh->prepare("select category_type from categories where category_type='C'");
382     $sth->execute;
383     my ($categoryChild) = $sth->fetchrow;
384     $template->param( categoryChild => $categoryChild );
385
386     $sth = $dbh->prepare("select category_type from categories where category_type='I'");
387     $sth->execute;
388     my ($categoryInstitution) = $sth->fetchrow;
389     $template->param( categoryInstitution => $categoryInstitution );
390     $sth->finish;
391
392 }    #---- END $OP eq DEFAULT
393
394 $template->param(
395     script_name  => $script_name,
396     categorycode => $categorycode,
397     searchfield  => $searchfield,
398     messages     => \@messages,
399 );
400
401 output_html_with_http_headers $input, $cookie, $template->output;
402
403 exit 0;
404
405 sub _get_brief_messaging_prefs {
406     my $categorycode      = shift;
407     my $messaging_options = C4::Members::Messaging::GetMessagingOptions();
408     my $results           = [];
409     PREF: foreach my $option (@$messaging_options) {
410         my $pref = C4::Members::Messaging::GetMessagingPreferences(
411             {
412                 categorycode => $categorycode,
413                 message_name => $option->{'message_name'}
414             }
415         );
416         next unless $pref->{'transports'};
417         my $brief_pref = {
418             message_attribute_id      => $option->{'message_attribute_id'},
419             message_name              => $option->{'message_name'},
420             $option->{'message_name'} => 1
421         };
422         foreach my $transport ( keys %{ $pref->{'transports'} } ) {
423             push @{ $brief_pref->{'transports'} }, { transport => $transport };
424         }
425         push @$results, $brief_pref;
426     }
427     return $results;
428 }