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