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