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