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