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