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