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