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