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