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