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