Bug 11349: Change .tmpl -> .tt in scripts using templates
[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 under the
26 # terms of the GNU General Public License as published by the Free Software
27 # Foundation; either version 2 of the License, or (at your option) any later
28 # version.
29 #
30 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
31 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
32 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
33 #
34 # You should have received a copy of the GNU General Public License along
35 # with Koha; if not, write to the Free Software Foundation, Inc.,
36 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
37
38 use Modern::Perl;
39
40 use CGI;
41 use C4::Context;
42 use C4::Auth;
43 use C4::Branch;
44 use C4::Output;
45 use C4::Dates;
46 use C4::Form::MessagingPreferences;
47 use Koha::Database;
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') // '';
75 my $block_expired = $input->param("block_expired");
76
77 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
78     {
79         template_name   => "admin/categorie.tt",
80         query           => $input,
81         type            => "intranet",
82         authnotrequired => 0,
83         flagsrequired   => { parameters => 'parameters_remaining_permissions' },
84         debug           => 1,
85     }
86 );
87
88 $template->param(
89     script_name  => $script_name,
90     categorycode => $categorycode,
91     searchfield  => $searchfield
92 );
93
94 ################## ADD_FORM ##################################
95 # called by default. Used to create form to add or  modify a record
96 if ( $op eq 'add_form' ) {
97     $template->param( add_form => 1 );
98
99     #---- if primkey exists, it's a modify action, so read values to modify...
100     my $data;
101     my @selected_branches;
102     if ($categorycode) {
103         my $dbh = C4::Context->dbh;
104         my $sth =
105           $dbh->prepare("SELECT * FROM categories WHERE categorycode=?");
106         $sth->execute($categorycode);
107         $data = $sth->fetchrow_hashref;
108
109         $sth = $dbh->prepare(
110             "SELECT b.branchcode, b.branchname 
111             FROM categories_branches AS cb, branches AS b 
112             WHERE cb.branchcode = b.branchcode AND cb.categorycode = ?
113         ");
114         $sth->execute($categorycode);
115         while ( my $branch = $sth->fetchrow_hashref ) {
116             push @selected_branches, $branch;
117         }
118         $sth->finish;
119     }
120
121     if (   $data->{'enrolmentperioddate'}
122         && $data->{'enrolmentperioddate'} eq '0000-00-00' )
123     {
124         $data->{'enrolmentperioddate'} = undef;
125     }
126
127     $data->{'category_type'} //= '';
128
129     my $branches = GetBranches();
130     my @branches_loop;
131     foreach my $branch ( sort keys %$branches ) {
132         my $selected =
133           ( grep { $$_{branchcode} eq $branch } @selected_branches ) ? 1 : 0;
134         push @branches_loop,
135           {
136             branchcode => $$branches{$branch}{branchcode},
137             branchname => $$branches{$branch}{branchname},
138             selected   => $selected,
139           };
140     }
141
142     $template->param(
143         branches_loop       => \@branches_loop,
144         description         => $data->{'description'},
145         enrolmentperiod     => $data->{'enrolmentperiod'},
146         enrolmentperioddate => $data->{'enrolmentperioddate'},
147         upperagelimit       => $data->{'upperagelimit'},
148         dateofbirthrequired => $data->{'dateofbirthrequired'},
149         enrolmentfee        => sprintf( "%.2f", $data->{'enrolmentfee'} || 0 ),
150         overduenoticerequired => $data->{'overduenoticerequired'},
151         issuelimit            => $data->{'issuelimit'},
152         reservefee            => sprintf( "%.2f", $data->{'reservefee'} || 0 ),
153         hidelostitems         => $data->{'hidelostitems'},
154         category_type         => $data->{'category_type'},
155         default_privacy       => $data->{'default_privacy'},
156         SMSSendDriver         => C4::Context->preference("SMSSendDriver"),
157         "type_" . $data->{'category_type'} => 1,
158         BlockExpiredPatronOpacActions =>
159           $data->{'BlockExpiredPatronOpacActions'},
160         TalkingTechItivaPhone =>
161           C4::Context->preference("TalkingTechItivaPhoneNotification"),
162     );
163
164     if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
165         C4::Form::MessagingPreferences::set_form_values(
166             { categorycode => $categorycode }, $template );
167     }
168
169     # END $OP eq ADD_FORM
170 ################## ADD_VALIDATE ##################################
171     # called by add_form, used to insert/modify data in DB
172 }
173 elsif ( $op eq 'add_validate' ) {
174     $template->param( add_validate => 1 );
175
176     my $is_a_modif = $input->param("is_a_modif");
177
178     my $dbh = C4::Context->dbh;
179
180     if ( $input->param('enrolmentperioddate') ) {
181         $input->param(
182             'enrolmentperioddate' => C4::Dates::format_date_in_iso(
183                 $input->param('enrolmentperioddate')
184             )
185         );
186     }
187
188     if ($is_a_modif) {
189         my $sth = $dbh->prepare( "
190                 UPDATE categories
191                 SET description=?,
192                     enrolmentperiod=?,
193                     enrolmentperioddate=?,
194                     upperagelimit=?,
195                     dateofbirthrequired=?,
196                     enrolmentfee=?,
197                     reservefee=?,
198                     hidelostitems=?,
199                     overduenoticerequired=?,
200                     category_type=?,
201                     BlockExpiredPatronOpacActions=?,
202                     default_privacy=?
203                 WHERE categorycode=?"
204         );
205         $sth->execute(
206             map { $input->param($_) } (
207                 'description',           'enrolmentperiod',
208                 'enrolmentperioddate',   'upperagelimit',
209                 'dateofbirthrequired',   'enrolmentfee',
210                 'reservefee',            'hidelostitems',
211                 'overduenoticerequired', 'category_type',
212                 'block_expired',         'default_privacy',
213                 'categorycode'
214             )
215         );
216         my @branches = $input->param("branches");
217         if (@branches) {
218             $sth = $dbh->prepare(
219                 "DELETE FROM categories_branches WHERE categorycode = ?"
220             );
221             $sth->execute( $input->param("categorycode") );
222             $sth = $dbh->prepare(
223                 "INSERT INTO categories_branches ( categorycode, branchcode ) VALUES ( ?, ? )"
224             );
225             for my $branchcode (@branches) {
226                 next if not $branchcode;
227                 $sth->bind_param( 1, $input->param("categorycode") );
228                 $sth->bind_param( 2, $branchcode );
229                 $sth->execute;
230             }
231         }
232         $sth->finish;
233     }
234     else {
235         my $sth = $dbh->prepare( "
236             INSERT INTO categories (
237                 categorycode,
238                 description,
239                 enrolmentperiod,
240                 enrolmentperioddate,
241                 upperagelimit,
242                 dateofbirthrequired,
243                 enrolmentfee,
244                 reservefee,
245                 hidelostitems,
246                 overduenoticerequired,
247                 category_type,
248                 BlockExpiredPatronOpacActions,
249                 default_privacy
250             )
251             VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)" );
252         $sth->execute(
253             map { $input->param($_) } (
254                 'categorycode',    'description',
255                 'enrolmentperiod', 'enrolmentperioddate',
256                 'upperagelimit',   'dateofbirthrequired',
257                 'enrolmentfee',    'reservefee',
258                 'hidelostitems',   'overduenoticerequired',
259                 'category_type',   'block_expired',
260                 'default_privacy',
261             )
262         );
263         $sth->finish;
264     }
265
266     if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
267         C4::Form::MessagingPreferences::handle_form_action( $input,
268             { categorycode => $input->param('categorycode') }, $template );
269     }
270
271     print "Content-Type: text/html\n\n<META HTTP-EQUIV=Refresh CONTENT=\"0; URL=categorie.pl\"></html>";
272     exit;
273
274     # END $OP eq ADD_VALIDATE
275 ################## DELETE_CONFIRM ##################################
276     # called by default form, used to confirm deletion of data in DB
277 }
278 elsif ( $op eq 'delete_confirm' ) {
279     my $schema = Koha::Database->new()->schema();
280     $template->param( delete_confirm => 1 );
281
282     my $count =
283       $schema->resultset('Borrower')
284       ->search( { categorycode => $categorycode } )->count();
285
286     my $category = $schema->resultset('Category')->find($categorycode);
287
288     $category->enrolmentperioddate(
289         C4::Dates::format_date( $category->enrolmentperioddate() ) );
290
291     $template->param( category => $category, patrons_in_category => $count );
292
293     # END $OP eq DELETE_CONFIRM
294 ################## DELETE_CONFIRMED ##################################
295   # called by delete_confirm, used to effectively confirm deletion of data in DB
296 }
297 elsif ( $op eq 'delete_confirmed' ) {
298     $template->param( delete_confirmed => 1 );
299     my $dbh = C4::Context->dbh;
300
301     my $categorycode = uc( $input->param('categorycode') );
302
303     my $sth = $dbh->prepare("delete from categories where categorycode=?");
304
305     $sth->execute($categorycode);
306     $sth->finish;
307
308     print "Content-Type: text/html\n\n<META HTTP-EQUIV=Refresh CONTENT=\"0; URL=categorie.pl\"></html>";
309     exit;
310
311     # END $OP eq DELETE_CONFIRMED
312 }
313 else {    # DEFAULT
314     $template->param( else => 1 );
315     my @loop;
316     my ( $count, $results ) = StringSearch( $searchfield, 'web' );
317
318     my $dbh = C4::Context->dbh;
319     my $sth = $dbh->prepare("
320         SELECT b.branchcode, b.branchname 
321         FROM categories_branches AS cb, branches AS b 
322         WHERE cb.branchcode = b.branchcode AND cb.categorycode = ?
323     ");
324
325     for ( my $i = 0 ; $i < $count ; $i++ ) {
326         $sth->execute( $results->[$i]{'categorycode'} );
327
328         my @selected_branches;
329         while ( my $branch = $sth->fetchrow_hashref ) {
330             push @selected_branches, $branch;
331         }
332
333         my $enrolmentperioddate = $results->[$i]{'enrolmentperioddate'};
334         if ( $enrolmentperioddate && $enrolmentperioddate eq '0000-00-00' ) {
335             $enrolmentperioddate = undef;
336         }
337
338         $results->[$i]{'category_type'} //= '';
339
340         my %row = (
341             branches              => \@selected_branches,
342             categorycode          => $results->[$i]{'categorycode'},
343             description           => $results->[$i]{'description'},
344             enrolmentperiod       => $results->[$i]{'enrolmentperiod'},
345             enrolmentperioddate   => $enrolmentperioddate,
346             upperagelimit         => $results->[$i]{'upperagelimit'},
347             dateofbirthrequired   => $results->[$i]{'dateofbirthrequired'},
348             overduenoticerequired => $results->[$i]{'overduenoticerequired'},
349             issuelimit            => $results->[$i]{'issuelimit'},
350             hidelostitems         => $results->[$i]{'hidelostitems'},
351             category_type         => $results->[$i]{'category_type'},
352             default_privacy       => $results->[$i]{'default_privacy'},
353             reservefee => sprintf( "%.2f", $results->[$i]{'reservefee'} || 0 ),
354             enrolmentfee =>
355               sprintf( "%.2f", $results->[$i]{'enrolmentfee'} || 0 ),
356             "type_" . $results->[$i]{'category_type'} => 1,
357         );
358
359         if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
360             my $brief_prefs =
361               _get_brief_messaging_prefs( $results->[$i]{'categorycode'} );
362             $row{messaging_prefs} = $brief_prefs if @$brief_prefs;
363         }
364         push @loop, \%row;
365     }
366
367     $template->param( loop => \@loop );
368
369     # check that I (institution) and C (child) exists. otherwise => warning to the user
370     $sth = $dbh->prepare("select category_type from categories where category_type='C'");
371     $sth->execute;
372     my ($categoryChild) = $sth->fetchrow;
373     $template->param( categoryChild => $categoryChild );
374
375     $sth = $dbh->prepare("select category_type from categories where category_type='I'");
376     $sth->execute;
377     my ($categoryInstitution) = $sth->fetchrow;
378     $template->param( categoryInstitution => $categoryInstitution );
379     $sth->finish;
380
381 }    #---- END $OP eq DEFAULT
382 output_html_with_http_headers $input, $cookie, $template->output;
383
384 exit 0;
385
386 sub _get_brief_messaging_prefs {
387     my $categorycode      = shift;
388     my $messaging_options = C4::Members::Messaging::GetMessagingOptions();
389     my $results           = [];
390     PREF: foreach my $option (@$messaging_options) {
391         my $pref = C4::Members::Messaging::GetMessagingPreferences(
392             {
393                 categorycode => $categorycode,
394                 message_name => $option->{'message_name'}
395             }
396         );
397         next unless $pref->{'transports'};
398         my $brief_pref = {
399             message_attribute_id      => $option->{'message_attribute_id'},
400             message_name              => $option->{'message_name'},
401             $option->{'message_name'} => 1
402         };
403         foreach my $transport ( keys %{ $pref->{'transports'} } ) {
404             push @{ $brief_pref->{'transports'} }, { transport => $transport };
405         }
406         push @$results, $brief_pref;
407     }
408     return $results;
409 }