Bug 15859: Move some basic MARC editor controls into settings menu
[koha.git] / admin / smart-rules.pl
1 #!/usr/bin/perl
2 # Copyright 2000-2002 Katipo Communications
3 # copyright 2010 BibLibre
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use strict;
21 use warnings;
22 use CGI qw ( -utf8 );
23 use C4::Context;
24 use C4::Output;
25 use C4::Auth;
26 use C4::Koha;
27 use C4::Debug;
28 use C4::Branch; # GetBranches
29 use Koha::DateUtils;
30 use Koha::Database;
31 use Koha::IssuingRule;
32 use Koha::IssuingRules;
33 use Koha::Libraries;
34
35 my $input = CGI->new;
36 my $dbh = C4::Context->dbh;
37
38 # my $flagsrequired;
39 # $flagsrequired->{circulation}=1;
40 my ($template, $loggedinuser, $cookie)
41     = get_template_and_user({template_name => "admin/smart-rules.tt",
42                             query => $input,
43                             type => "intranet",
44                             authnotrequired => 0,
45                             flagsrequired => {parameters => 'manage_circ_rules'},
46                             debug => 1,
47                             });
48
49 my $type=$input->param('type');
50
51 my $branch = $input->param('branch');
52 unless ( $branch ) {
53     if ( C4::Context->preference('DefaultToLoggedInLibraryCircRules') ) {
54         $branch = Koha::Libraries->search->count() == 1 ? undef : C4::Branch::mybranch();
55     }
56     else {
57         $branch = C4::Branch::onlymine() ? ( C4::Branch::mybranch() || '*' ) : '*';
58     }
59 }
60 $branch = '*' if $branch eq 'NO_LIBRARY_SET';
61
62 my $op = $input->param('op') || q{};
63 my $language = C4::Languages::getlanguage();
64
65 if ($op eq 'delete') {
66     my $itemtype     = $input->param('itemtype');
67     my $categorycode = $input->param('categorycode');
68     $debug and warn "deleting $1 $2 $branch";
69
70     my $sth_Idelete = $dbh->prepare("delete from issuingrules where branchcode=? and categorycode=? and itemtype=?");
71     $sth_Idelete->execute($branch, $categorycode, $itemtype);
72 }
73 elsif ($op eq 'delete-branch-cat') {
74     my $categorycode  = $input->param('categorycode');
75     if ($branch eq "*") {
76         if ($categorycode eq "*") {
77             my $sth_delete = $dbh->prepare("DELETE FROM default_circ_rules");
78             $sth_delete->execute();
79         } else {
80             my $sth_delete = $dbh->prepare("DELETE FROM default_borrower_circ_rules
81                                             WHERE categorycode = ?");
82             $sth_delete->execute($categorycode);
83         }
84     } elsif ($categorycode eq "*") {
85         my $sth_delete = $dbh->prepare("DELETE FROM default_branch_circ_rules
86                                         WHERE branchcode = ?");
87         $sth_delete->execute($branch);
88     } else {
89         my $sth_delete = $dbh->prepare("DELETE FROM branch_borrower_circ_rules
90                                         WHERE branchcode = ?
91                                         AND categorycode = ?");
92         $sth_delete->execute($branch, $categorycode);
93     }
94 }
95 elsif ($op eq 'delete-branch-item') {
96     my $itemtype  = $input->param('itemtype');
97     if ($branch eq "*") {
98         if ($itemtype eq "*") {
99             my $sth_delete = $dbh->prepare("DELETE FROM default_circ_rules");
100             $sth_delete->execute();
101         } else {
102             my $sth_delete = $dbh->prepare("DELETE FROM default_branch_item_rules
103                                             WHERE itemtype = ?");
104             $sth_delete->execute($itemtype);
105         }
106     } elsif ($itemtype eq "*") {
107         my $sth_delete = $dbh->prepare("DELETE FROM default_branch_circ_rules
108                                         WHERE branchcode = ?");
109         $sth_delete->execute($branch);
110     } else {
111         my $sth_delete = $dbh->prepare("DELETE FROM branch_item_rules
112                                         WHERE branchcode = ?
113                                         AND itemtype = ?");
114         $sth_delete->execute($branch, $itemtype);
115     }
116 }
117 # save the values entered
118 elsif ($op eq 'add') {
119     my $br = $branch; # branch
120     my $bor  = $input->param('categorycode'); # borrower category
121     my $itemtype  = $input->param('itemtype');     # item type
122     my $fine = $input->param('fine');
123     my $finedays     = $input->param('finedays');
124     my $maxsuspensiondays = $input->param('maxsuspensiondays');
125     $maxsuspensiondays = undef if $maxsuspensiondays eq q||;
126     my $firstremind  = $input->param('firstremind');
127     my $chargeperiod = $input->param('chargeperiod');
128     my $chargeperiod_charge_at = $input->param('chargeperiod_charge_at');
129     my $maxissueqty  = $input->param('maxissueqty');
130     my $maxonsiteissueqty  = $input->param('maxonsiteissueqty');
131     my $renewalsallowed  = $input->param('renewalsallowed');
132     my $renewalperiod    = $input->param('renewalperiod');
133     my $norenewalbefore  = $input->param('norenewalbefore');
134     $norenewalbefore = undef if $norenewalbefore =~ /^\s*$/;
135     my $auto_renew = $input->param('auto_renew') eq 'yes' ? 1 : 0;
136     my $reservesallowed  = $input->param('reservesallowed');
137     my $onshelfholds     = $input->param('onshelfholds') || 0;
138     $maxissueqty =~ s/\s//g;
139     $maxissueqty = undef if $maxissueqty !~ /^\d+/;
140     $maxonsiteissueqty =~ s/\s//g;
141     $maxonsiteissueqty = undef if $maxonsiteissueqty !~ /^\d+/;
142     my $issuelength  = $input->param('issuelength');
143     my $lengthunit  = $input->param('lengthunit');
144     my $hardduedate = $input->param('hardduedate') || undef;
145     $hardduedate = eval { dt_from_string( $input->param('hardduedate') ) } if ( $hardduedate );
146     $hardduedate = output_pref( { dt => $hardduedate, dateonly => 1, dateformat => 'iso' } ) if ( $hardduedate );
147     my $hardduedatecompare = $input->param('hardduedatecompare');
148     my $rentaldiscount = $input->param('rentaldiscount');
149     my $opacitemholds = $input->param('opacitemholds') || 0;
150     my $overduefinescap = $input->param('overduefinescap') || undef;
151     my $cap_fine_to_replacement_price = $input->param('cap_fine_to_replacement_price') eq 'on';
152     $debug and warn "Adding $br, $bor, $itemtype, $fine, $maxissueqty, $maxonsiteissueqty, $cap_fine_to_replacement_price";
153
154     my $params = {
155         branchcode                    => $br,
156         categorycode                  => $bor,
157         itemtype                      => $itemtype,
158         fine                          => $fine,
159         finedays                      => $finedays,
160         maxsuspensiondays             => $maxsuspensiondays,
161         firstremind                   => $firstremind,
162         chargeperiod                  => $chargeperiod,
163         chargeperiod_charge_at        => $chargeperiod_charge_at,
164         maxissueqty                   => $maxissueqty,
165         maxonsiteissueqty             => $maxonsiteissueqty,
166         renewalsallowed               => $renewalsallowed,
167         renewalperiod                 => $renewalperiod,
168         norenewalbefore               => $norenewalbefore,
169         auto_renew                    => $auto_renew,
170         reservesallowed               => $reservesallowed,
171         issuelength                   => $issuelength,
172         lengthunit                    => $lengthunit,
173         hardduedate                   => $hardduedate,
174         hardduedatecompare            => $hardduedatecompare,
175         rentaldiscount                => $rentaldiscount,
176         onshelfholds                  => $onshelfholds,
177         opacitemholds                 => $opacitemholds,
178         overduefinescap               => $overduefinescap,
179         cap_fine_to_replacement_price => $cap_fine_to_replacement_price,
180     };
181
182     my $issuingrule = Koha::IssuingRules->find({categorycode => $bor, itemtype => $itemtype, branchcode => $br});
183     if ($issuingrule) {
184         $issuingrule->set($params)->store();
185     } else {
186         Koha::IssuingRule->new()->set($params)->store();
187     }
188
189 }
190 elsif ($op eq "set-branch-defaults") {
191     my $categorycode  = $input->param('categorycode');
192     my $maxissueqty   = $input->param('maxissueqty');
193     my $maxonsiteissueqty = $input->param('maxonsiteissueqty');
194     my $holdallowed   = $input->param('holdallowed');
195     my $returnbranch  = $input->param('returnbranch');
196     $maxissueqty =~ s/\s//g;
197     $maxissueqty = undef if $maxissueqty !~ /^\d+/;
198     $maxonsiteissueqty =~ s/\s//g;
199     $maxonsiteissueqty = undef if $maxonsiteissueqty !~ /^\d+/;
200     $holdallowed =~ s/\s//g;
201     $holdallowed = undef if $holdallowed !~ /^\d+/;
202
203     if ($branch eq "*") {
204         my $sth_search = $dbh->prepare("SELECT count(*) AS total
205                                         FROM default_circ_rules");
206         my $sth_insert = $dbh->prepare("INSERT INTO default_circ_rules
207                                         (maxissueqty, maxonsiteissueqty, holdallowed, returnbranch)
208                                         VALUES (?, ?, ?, ?)");
209         my $sth_update = $dbh->prepare("UPDATE default_circ_rules
210                                         SET maxissueqty = ?, maxonsiteissueqty = ?, holdallowed = ?, returnbranch = ?");
211
212         $sth_search->execute();
213         my $res = $sth_search->fetchrow_hashref();
214         if ($res->{total}) {
215             $sth_update->execute($maxissueqty, $maxonsiteissueqty, $holdallowed, $returnbranch);
216         } else {
217             $sth_insert->execute($maxissueqty, $maxonsiteissueqty, $holdallowed, $returnbranch);
218         }
219     } else {
220         my $sth_search = $dbh->prepare("SELECT count(*) AS total
221                                         FROM default_branch_circ_rules
222                                         WHERE branchcode = ?");
223         my $sth_insert = $dbh->prepare("INSERT INTO default_branch_circ_rules
224                                         (branchcode, maxissueqty, maxonsiteissueqty, holdallowed, returnbranch)
225                                         VALUES (?, ?, ?, ?, ?)");
226         my $sth_update = $dbh->prepare("UPDATE default_branch_circ_rules
227                                         SET maxissueqty = ?, maxonsiteissueqty = ?, holdallowed = ?, returnbranch = ?
228                                         WHERE branchcode = ?");
229         $sth_search->execute($branch);
230         my $res = $sth_search->fetchrow_hashref();
231         if ($res->{total}) {
232             $sth_update->execute($maxissueqty, $maxonsiteissueqty, $holdallowed, $returnbranch, $branch);
233         } else {
234             $sth_insert->execute($branch, $maxissueqty, $maxonsiteissueqty, $holdallowed, $returnbranch);
235         }
236     }
237 }
238 elsif ($op eq "add-branch-cat") {
239     my $categorycode  = $input->param('categorycode');
240     my $maxissueqty   = $input->param('maxissueqty');
241     my $maxonsiteissueqty = $input->param('maxonsiteissueqty');
242     $maxissueqty =~ s/\s//g;
243     $maxissueqty = undef if $maxissueqty !~ /^\d+/;
244     $maxonsiteissueqty =~ s/\s//g;
245     $maxonsiteissueqty = undef if $maxonsiteissueqty !~ /^\d+/;
246
247     if ($branch eq "*") {
248         if ($categorycode eq "*") {
249             my $sth_search = $dbh->prepare("SELECT count(*) AS total
250                                             FROM default_circ_rules");
251             my $sth_insert = $dbh->prepare(q|
252                 INSERT INTO default_circ_rules
253                     (maxissueqty, maxonsiteissueqty)
254                     VALUES (?, ?)
255             |);
256             my $sth_update = $dbh->prepare(q|
257                 UPDATE default_circ_rules
258                 SET maxissueqty = ?,
259                     maxonsiteissueqty = ?
260             |);
261
262             $sth_search->execute();
263             my $res = $sth_search->fetchrow_hashref();
264             if ($res->{total}) {
265                 $sth_update->execute($maxissueqty, $maxonsiteissueqty);
266             } else {
267                 $sth_insert->execute($maxissueqty, $maxonsiteissueqty);
268             }
269         } else {
270             my $sth_search = $dbh->prepare("SELECT count(*) AS total
271                                             FROM default_borrower_circ_rules
272                                             WHERE categorycode = ?");
273             my $sth_insert = $dbh->prepare(q|
274                 INSERT INTO default_borrower_circ_rules
275                     (categorycode, maxissueqty, maxonsiteissueqty)
276                     VALUES (?, ?, ?)
277             |);
278             my $sth_update = $dbh->prepare(q|
279                 UPDATE default_borrower_circ_rules
280                 SET maxissueqty = ?,
281                     maxonsiteissueqty = ?
282                 WHERE categorycode = ?
283             |);
284             $sth_search->execute($branch);
285             my $res = $sth_search->fetchrow_hashref();
286             if ($res->{total}) {
287                 $sth_update->execute($maxissueqty, $maxonsiteissueqty, $categorycode);
288             } else {
289                 $sth_insert->execute($categorycode, $maxissueqty, $maxonsiteissueqty);
290             }
291         }
292     } elsif ($categorycode eq "*") {
293         my $sth_search = $dbh->prepare("SELECT count(*) AS total
294                                         FROM default_branch_circ_rules
295                                         WHERE branchcode = ?");
296         my $sth_insert = $dbh->prepare(q|
297             INSERT INTO default_branch_circ_rules
298             (branchcode, maxissueqty, maxonsiteissueqty)
299             VALUES (?, ?, ?)
300         |);
301         my $sth_update = $dbh->prepare(q|
302             UPDATE default_branch_circ_rules
303             SET maxissueqty = ?,
304                 maxonsiteissueqty = ?
305             WHERE branchcode = ?
306         |);
307         $sth_search->execute($branch);
308         my $res = $sth_search->fetchrow_hashref();
309         if ($res->{total}) {
310             $sth_update->execute($maxissueqty, $maxonsiteissueqty, $branch);
311         } else {
312             $sth_insert->execute($branch, $maxissueqty, $maxonsiteissueqty);
313         }
314     } else {
315         my $sth_search = $dbh->prepare("SELECT count(*) AS total
316                                         FROM branch_borrower_circ_rules
317                                         WHERE branchcode = ?
318                                         AND   categorycode = ?");
319         my $sth_insert = $dbh->prepare(q|
320             INSERT INTO branch_borrower_circ_rules
321             (branchcode, categorycode, maxissueqty, maxonsiteissueqty)
322             VALUES (?, ?, ?, ?)
323         |);
324         my $sth_update = $dbh->prepare(q|
325             UPDATE branch_borrower_circ_rules
326             SET maxissueqty = ?,
327                 maxonsiteissueqty = ?
328             WHERE branchcode = ?
329             AND categorycode = ?
330         |);
331
332         $sth_search->execute($branch, $categorycode);
333         my $res = $sth_search->fetchrow_hashref();
334         if ($res->{total}) {
335             $sth_update->execute($maxissueqty, $maxonsiteissueqty, $branch, $categorycode);
336         } else {
337             $sth_insert->execute($branch, $categorycode, $maxissueqty, $maxonsiteissueqty);
338         }
339     }
340 }
341 elsif ($op eq "add-branch-item") {
342     my $itemtype  = $input->param('itemtype');
343     my $holdallowed   = $input->param('holdallowed');
344     my $returnbranch  = $input->param('returnbranch');
345     $holdallowed =~ s/\s//g;
346     $holdallowed = undef if $holdallowed !~ /^\d+/;
347
348     if ($branch eq "*") {
349         if ($itemtype eq "*") {
350             my $sth_search = $dbh->prepare("SELECT count(*) AS total
351                                             FROM default_circ_rules");
352             my $sth_insert = $dbh->prepare("INSERT INTO default_circ_rules
353                                             (holdallowed, returnbranch)
354                                             VALUES (?, ?)");
355             my $sth_update = $dbh->prepare("UPDATE default_circ_rules
356                                             SET holdallowed = ?, returnbranch = ?");
357
358             $sth_search->execute();
359             my $res = $sth_search->fetchrow_hashref();
360             if ($res->{total}) {
361                 $sth_update->execute($holdallowed, $returnbranch);
362             } else {
363                 $sth_insert->execute($holdallowed, $returnbranch);
364             }
365         } else {
366             my $sth_search = $dbh->prepare("SELECT count(*) AS total
367                                             FROM default_branch_item_rules
368                                             WHERE itemtype = ?");
369             my $sth_insert = $dbh->prepare("INSERT INTO default_branch_item_rules
370                                             (itemtype, holdallowed, returnbranch)
371                                             VALUES (?, ?, ?)");
372             my $sth_update = $dbh->prepare("UPDATE default_branch_item_rules
373                                             SET holdallowed = ?, returnbranch = ?
374                                             WHERE itemtype = ?");
375             $sth_search->execute($itemtype);
376             my $res = $sth_search->fetchrow_hashref();
377             if ($res->{total}) {
378                 $sth_update->execute($holdallowed, $returnbranch, $itemtype);
379             } else {
380                 $sth_insert->execute($itemtype, $holdallowed, $returnbranch);
381             }
382         }
383     } elsif ($itemtype eq "*") {
384         my $sth_search = $dbh->prepare("SELECT count(*) AS total
385                                         FROM default_branch_circ_rules
386                                         WHERE branchcode = ?");
387         my $sth_insert = $dbh->prepare("INSERT INTO default_branch_circ_rules
388                                         (branchcode, holdallowed, returnbranch)
389                                         VALUES (?, ?, ?)");
390         my $sth_update = $dbh->prepare("UPDATE default_branch_circ_rules
391                                         SET holdallowed = ?, returnbranch = ?
392                                         WHERE branchcode = ?");
393         $sth_search->execute($branch);
394         my $res = $sth_search->fetchrow_hashref();
395         if ($res->{total}) {
396             $sth_update->execute($holdallowed, $returnbranch, $branch);
397         } else {
398             $sth_insert->execute($branch, $holdallowed, $returnbranch);
399         }
400     } else {
401         my $sth_search = $dbh->prepare("SELECT count(*) AS total
402                                         FROM branch_item_rules
403                                         WHERE branchcode = ?
404                                         AND   itemtype = ?");
405         my $sth_insert = $dbh->prepare("INSERT INTO branch_item_rules
406                                         (branchcode, itemtype, holdallowed, returnbranch)
407                                         VALUES (?, ?, ?, ?)");
408         my $sth_update = $dbh->prepare("UPDATE branch_item_rules
409                                         SET holdallowed = ?, returnbranch = ?
410                                         WHERE branchcode = ?
411                                         AND itemtype = ?");
412
413         $sth_search->execute($branch, $itemtype);
414         my $res = $sth_search->fetchrow_hashref();
415         if ($res->{total}) {
416             $sth_update->execute($holdallowed, $returnbranch, $branch, $itemtype);
417         } else {
418             $sth_insert->execute($branch, $itemtype, $holdallowed, $returnbranch);
419         }
420     }
421 }
422
423 my $branches = GetBranches();
424 my @branchloop;
425 for my $thisbranch (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %$branches) {
426     push @branchloop, {
427         value      => $thisbranch,
428         selected   => $thisbranch eq $branch,
429         branchname => $branches->{$thisbranch}->{'branchname'},
430     };
431 }
432
433 my $sth=$dbh->prepare("SELECT description,categorycode FROM categories ORDER BY description");
434 $sth->execute;
435 my @category_loop;
436 while (my $data=$sth->fetchrow_hashref){
437     push @category_loop,$data;
438 }
439
440 $sth->finish;
441 my @row_loop;
442 my @itemtypes = @{ GetItemTypes( style => 'array' ) };
443 @itemtypes = sort { lc $a->{translated_description} cmp lc $b->{translated_description} } @itemtypes;
444
445 my $sth2 = $dbh->prepare("
446     SELECT  issuingrules.*,
447             itemtypes.description AS humanitemtype,
448             categories.description AS humancategorycode,
449             COALESCE( localization.translation, itemtypes.description ) AS translated_description
450     FROM issuingrules
451     LEFT JOIN itemtypes
452         ON (itemtypes.itemtype = issuingrules.itemtype)
453     LEFT JOIN categories
454         ON (categories.categorycode = issuingrules.categorycode)
455     LEFT JOIN localization ON issuingrules.itemtype = localization.code
456         AND localization.entity = 'itemtypes'
457         AND localization.lang = ?
458     WHERE issuingrules.branchcode = ?
459 ");
460 $sth2->execute($language, $branch);
461
462 while (my $row = $sth2->fetchrow_hashref) {
463     $row->{'current_branch'} ||= $row->{'branchcode'};
464     $row->{translated_description} ||= $row->{translated_description};
465     $row->{default_translated_description} = 1 if $row->{humanitemtype} eq '*';
466     $row->{'humancategorycode'} ||= $row->{'categorycode'};
467     $row->{'default_humancategorycode'} = 1 if $row->{'humancategorycode'} eq '*';
468     $row->{'fine'} = sprintf('%.2f', $row->{'fine'});
469     if ($row->{'hardduedate'} && $row->{'hardduedate'} ne '0000-00-00') {
470        my $harddue_dt = eval { dt_from_string( $row->{'hardduedate'} ) };
471        $row->{'hardduedate'} = eval { output_pref( { dt => $harddue_dt, dateonly => 1 } ) } if ( $harddue_dt );
472        $row->{'hardduedatebefore'} = 1 if ($row->{'hardduedatecompare'} == -1);
473        $row->{'hardduedateexact'} = 1 if ($row->{'hardduedatecompare'} ==  0);
474        $row->{'hardduedateafter'} = 1 if ($row->{'hardduedatecompare'} ==  1);
475     } else {
476        $row->{'hardduedate'} = 0;
477     }
478     push @row_loop, $row;
479 }
480 $sth->finish;
481
482 my @sorted_row_loop = sort by_category_and_itemtype @row_loop;
483
484 my $sth_branch_cat;
485 if ($branch eq "*") {
486     $sth_branch_cat = $dbh->prepare("
487         SELECT default_borrower_circ_rules.*, categories.description AS humancategorycode
488         FROM default_borrower_circ_rules
489         JOIN categories USING (categorycode)
490
491     ");
492     $sth_branch_cat->execute();
493 } else {
494     $sth_branch_cat = $dbh->prepare("
495         SELECT branch_borrower_circ_rules.*, categories.description AS humancategorycode
496         FROM branch_borrower_circ_rules
497         JOIN categories USING (categorycode)
498         WHERE branch_borrower_circ_rules.branchcode = ?
499     ");
500     $sth_branch_cat->execute($branch);
501 }
502
503 my @branch_cat_rules = ();
504 while (my $row = $sth_branch_cat->fetchrow_hashref) {
505     push @branch_cat_rules, $row;
506 }
507 my @sorted_branch_cat_rules = sort { $a->{'humancategorycode'} cmp $b->{'humancategorycode'} } @branch_cat_rules;
508
509 # note undef maxissueqty so that template can deal with them
510 foreach my $entry (@sorted_branch_cat_rules, @sorted_row_loop) {
511     $entry->{unlimited_maxissueqty} = 1 unless defined($entry->{maxissueqty});
512     $entry->{unlimited_maxonsiteissueqty} = 1 unless defined($entry->{maxonsiteissueqty});
513 }
514
515 @sorted_row_loop = sort by_category_and_itemtype @row_loop;
516
517 my $sth_branch_item;
518 if ($branch eq "*") {
519     $sth_branch_item = $dbh->prepare("
520         SELECT default_branch_item_rules.*,
521             COALESCE( localization.translation, itemtypes.description ) AS translated_description
522         FROM default_branch_item_rules
523         JOIN itemtypes USING (itemtype)
524         LEFT JOIN localization ON itemtypes.itemtype = localization.code
525             AND localization.entity = 'itemtypes'
526             AND localization.lang = ?
527     ");
528     $sth_branch_item->execute($language);
529 } else {
530     $sth_branch_item = $dbh->prepare("
531         SELECT branch_item_rules.*,
532             COALESCE( localization.translation, itemtypes.description ) AS translated_description
533         FROM branch_item_rules
534         JOIN itemtypes USING (itemtype)
535         LEFT JOIN localization ON itemtypes.itemtype = localization.code
536             AND localization.entity = 'itemtypes'
537             AND localization.lang = ?
538         WHERE branch_item_rules.branchcode = ?
539     ");
540     $sth_branch_item->execute($language, $branch);
541 }
542
543 my @branch_item_rules = ();
544 while (my $row = $sth_branch_item->fetchrow_hashref) {
545     push @branch_item_rules, $row;
546 }
547 my @sorted_branch_item_rules = sort { lc $a->{translated_description} cmp lc $b->{translated_description} } @branch_item_rules;
548
549 # note undef holdallowed so that template can deal with them
550 foreach my $entry (@sorted_branch_item_rules) {
551     $entry->{holdallowed_any} = 1 if($entry->{holdallowed} == 2);
552     $entry->{holdallowed_same} = 1 if($entry->{holdallowed} == 1);
553 }
554
555 $template->param(show_branch_cat_rule_form => 1);
556 $template->param(branch_item_rule_loop => \@sorted_branch_item_rules);
557 $template->param(branch_cat_rule_loop => \@sorted_branch_cat_rules);
558
559 my $sth_defaults;
560 if ($branch eq "*") {
561     $sth_defaults = $dbh->prepare("
562         SELECT *
563         FROM default_circ_rules
564     ");
565     $sth_defaults->execute();
566 } else {
567     $sth_defaults = $dbh->prepare("
568         SELECT *
569         FROM default_branch_circ_rules
570         WHERE branchcode = ?
571     ");
572     $sth_defaults->execute($branch);
573 }
574
575 my $defaults = $sth_defaults->fetchrow_hashref;
576
577 if ($defaults) {
578     $template->param(default_holdallowed_none => 1) if($defaults->{holdallowed} == 0);
579     $template->param(default_holdallowed_same => 1) if($defaults->{holdallowed} == 1);
580     $template->param(default_holdallowed_any => 1) if($defaults->{holdallowed} == 2);
581     $template->param(default_maxissueqty => $defaults->{maxissueqty});
582     $template->param(default_maxonsiteissueqty => $defaults->{maxonsiteissueqty});
583     $template->param(default_returnbranch => $defaults->{returnbranch});
584 }
585
586 $template->param(default_rules => ($defaults ? 1 : 0));
587
588 $template->param(categoryloop => \@category_loop,
589                         itemtypeloop => \@itemtypes,
590                         rules => \@sorted_row_loop,
591                         branchloop => \@branchloop,
592                         humanbranch => ($branch ne '*' ? $branches->{$branch}->{branchname} : ''),
593                         current_branch => $branch,
594                         definedbranch => scalar(@sorted_row_loop)>0
595                         );
596 output_html_with_http_headers $input, $cookie, $template->output;
597
598 exit 0;
599
600 # sort by patron category, then item type, putting
601 # default entries at the bottom
602 sub by_category_and_itemtype {
603     unless (by_category($a, $b)) {
604         return by_itemtype($a, $b);
605     }
606 }
607
608 sub by_category {
609     my ($a, $b) = @_;
610     if ($a->{'default_humancategorycode'}) {
611         return ($b->{'default_humancategorycode'} ? 0 : 1);
612     } elsif ($b->{'default_humancategorycode'}) {
613         return -1;
614     } else {
615         return $a->{'humancategorycode'} cmp $b->{'humancategorycode'};
616     }
617 }
618
619 sub by_itemtype {
620     my ($a, $b) = @_;
621     if ($a->{default_translated_description}) {
622         return ($b->{'default_translated_description'} ? 0 : 1);
623     } elsif ($b->{'default_translated_description'}) {
624         return -1;
625     } else {
626         return lc $a->{'translated_description'} cmp lc $b->{'translated_description'};
627     }
628 }