From b9b38f217ed54a43adcb8d3719a1f399894f20a9 Mon Sep 17 00:00:00 2001
From: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
Date: Mon, 21 Dec 2015 17:04:30 +0000
Subject: [PATCH] Bug 15407: Koha::Patron::Categories - replace
 C4::Category->all

The C4::Category module contained only 1 method to return the patron
categories available for the logged in user.
The new method Koha::Patron::Categories->search_limited does exactly the
same thing (see tests) and must be used in place of it.

Test plan:
- Same prerequisite as before
For the following pages, you should not see patron categories limited to
other libraries.
- On the 'Item circulation alerts' admin page
  (admin/item_circulation_alerts.pl), modify the settings for check-in
  and checkout (NOTE: Should not we display all patron categories on
  this page? If yes, it must be done in another bug report to ease
  backporting it).
- Search for patrons in the admin (budget) and acquisition (order) module.
- On the patron home page (search form in the header)
---
 C4/Category.pm                                     | 181 ---------------------
 C4/ItemCirculationAlertPreference.pm               |   5 +-
 Koha/Patron/Categories.pm                          |  15 ++
 Koha/Template/Plugin/Categories.pm                 |  15 +-
 acqui/add_user_search.pl                           |   6 +-
 admin/add_user_search.pl                           |   6 +-
 admin/item_circulation_alerts.pl                   |   7 +-
 debian/templates/plack.psgi                        |   1 -
 .../prog/en/includes/patron-search.inc             |  10 +-
 .../prog/en/modules/members/member.tt              |   4 +-
 members/guarantor_search.pl                        |   6 +-
 members/member.pl                                  |   1 -
 members/members-home.pl                            |   5 +-
 members/members-update-do.pl                       |   1 -
 members/members-update.pl                          |   1 -
 members/nl-search.pl                               |   7 +-
 misc/plack/koha.psgi                               |   2 +-
 patroncards/add_user_search.pl                     |   6 +-
 reports/reserves_stats.pl                          |   1 -
 serials/add_user_search.pl                         |   6 +-
 t/db_dependent/Category.t                          |  62 -------
 t/db_dependent/Circulation/CheckIfIssuedToPatron.t |   1 -
 t/db_dependent/Circulation/GetIssues.t             |   6 +-
 t/db_dependent/Koha/Patron/Categories.t            |  21 ++-
 t/db_dependent/Members/GetAllIssues.t              |   1 -
 t/db_dependent/Members/GetOverdues.t               |   1 -
 t/db_dependent/Members/GetPendingIssues.t          |   1 -
 t/db_dependent/Members/IssueSlip.t                 |   1 -
 t/db_dependent/Ratings.t                           |   4 +-
 t/db_dependent/Utils/Datatables_Members.t          |   4 +-
 t/db_dependent/Utils/Datatables_Virtualshelves.t   |   3 +-
 31 files changed, 85 insertions(+), 306 deletions(-)
 delete mode 100644 C4/Category.pm
 delete mode 100755 t/db_dependent/Category.t

diff --git a/C4/Category.pm b/C4/Category.pm
deleted file mode 100644
index 72ed424..0000000
--- a/C4/Category.pm
+++ /dev/null
@@ -1,181 +0,0 @@
-package C4::Category;
-
-# Copyright 2009 Liblime
-# Parts Copyright 2011 Tamil
-#
-# This file is part of Koha.
-#
-# Koha is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3 of the License, or
-# (at your option) any later version.
-#
-# Koha is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Koha; if not, see <http://www.gnu.org/licenses>.
-
-use strict;
-use warnings;
-use C4::Context;
-
-our $AUTOLOAD;
-
-
-
-
-=head1 NAME
-
-C4::Category - objects from the categories table
-
-=head1 SYNOPSIS
-
-    use C4::Category;
-    my @categories = C4::Category->all;
-    print join("\n", map { $_->description } @categories), "\n";
-
-=head1 DESCRIPTION
-
-Objects of this class represent a row in the C<categories> table.
-
-Currently, the bare minimum for using this as a read-only data source has
-been implemented.  The API was designed to make it easy to transition to
-an ORM later on.
-
-=head1 API
-
-=head2 Class Methods
-
-=cut
-
-=head3 C4::Category->new(\%opts)
-
-Given a hashref, a new (in-memory) C4::Category object will be instantiated.
-The database is not touched.
-
-=cut
-
-sub new {
-    my ($class, $opts) = @_;
-    bless $opts => $class;
-}
-
-
-
-
-=head3 C4::Category->all
-
-This returns all the categories as objects.  By default they're ordered by
-C<description>.
-
-=cut
-
-sub all {
-    my ( $class ) = @_;
-    my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
-    my $dbh = C4::Context->dbh;
-    # The categories table is small enough for
-    # `SELECT *` to be harmless.
-    my $query = "SELECT categories.* FROM categories";
-    $query .= qq{
-        LEFT JOIN categories_branches ON categories_branches.categorycode = categories.categorycode
-        WHERE categories_branches.branchcode = ? OR categories_branches.branchcode IS NULL
-    } if $branch_limit;
-    $query .= " ORDER BY description";
-    return map { $class->new($_) } @{
-        $dbh->selectall_arrayref(
-            $query,
-            { Slice => {} },
-            $branch_limit ? $branch_limit : ()
-        )
-    };
-}
-
-
-
-
-=head2 Object Methods
-
-These are read-only accessors for attributes of a C4::Category object.
-
-=head3 $category->categorycode
-
-=cut
-
-=head3 $category->description
-
-=cut
-
-=head3 $category->enrolmentperiod
-
-=cut
-
-=head3 $category->upperagelimit
-
-=cut
-
-=head3 $category->dateofbirthrequired
-
-=cut
-
-=head3 $category->finetype
-
-=cut
-
-=head3 $category->bulk
-
-=cut
-
-=head3 $category->enrolmentfee
-
-=cut
-
-=head3 $category->overduenoticerequired
-
-=cut
-
-=head3 $category->issuelimit
-
-=cut
-
-=head3 $category->reservefee
-
-=cut
-
-=head3 $category->category_type
-
-=cut
-
-sub AUTOLOAD {
-    my $self = shift;
-    my $attr = $AUTOLOAD;
-    $attr =~ s/.*://;
-    if (exists $self->{$attr}) {
-        return $self->{$attr};
-    } else {
-        return undef;
-    }
-}
-
-sub DESTROY { }
-
-
-
-
-=head1 SEE ALSO
-
-The following modules make reference to the C<categories> table.
-
-L<C4::Members>, L<C4::Overdues>, L<C4::Reserves>
-
-
-=head1 AUTHOR
-
-John Beppu <john.beppu@liblime.com>
-
-=cut
-
-1;
diff --git a/C4/ItemCirculationAlertPreference.pm b/C4/ItemCirculationAlertPreference.pm
index 90b4cfd..382090f 100644
--- a/C4/ItemCirculationAlertPreference.pm
+++ b/C4/ItemCirculationAlertPreference.pm
@@ -20,10 +20,11 @@ package C4::ItemCirculationAlertPreference;
 use strict;
 use warnings;
 use C4::Context;
-use C4::Category;
 use C4::ItemType;
 use Carp qw(carp croak);
 
+use Koha::Patron::Categories;
+
 our $AUTOLOAD;
 
 # helper function for validating \%opts
@@ -330,7 +331,7 @@ sub grid {
     my ($class, $where) = @_;
     my @branch_prefs = $class->find($where);
     my @default_prefs = $class->find({ branchcode => '*', notification => $where->{notification} });
-    my @cc = C4::Category->all;
+    my @cc = Koha::Patron::Categories->search_limited;
     my @it = C4::ItemType->all;
     my $notification = $where->{notification};
     my %disabled = map {
diff --git a/Koha/Patron/Categories.pm b/Koha/Patron/Categories.pm
index f220028..af01cad 100644
--- a/Koha/Patron/Categories.pm
+++ b/Koha/Patron/Categories.pm
@@ -19,6 +19,8 @@ use Modern::Perl;
 
 use Carp;
 
+use C4::Context; # Sigh...
+
 use Koha::Database;
 
 use Koha::Patron::Category;
@@ -35,6 +37,19 @@ Koha::Patron::Categories - Koha Patron Category Object set class
 
 =cut
 
+sub search_limited {
+    my ( $self ) = @_;
+    my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
+    return $self->search({}, {order_by => ['description']}) unless $branch_limit;
+    return $self->search({
+        'categories_branches.branchcode' => [$branch_limit, undef]},
+        {
+            join => 'categories_branches',
+            order_by => ['description'],
+        }
+    );
+}
+
 =head3 type
 
 =cut
diff --git a/Koha/Template/Plugin/Categories.pm b/Koha/Template/Plugin/Categories.pm
index 86630ca..287b9c2 100644
--- a/Koha/Template/Plugin/Categories.pm
+++ b/Koha/Template/Plugin/Categories.pm
@@ -20,21 +20,10 @@ use Modern::Perl;
 use Template::Plugin;
 use base qw( Template::Plugin );
 
-use C4::Category;
+use Koha::Patron::Categories;
 
 sub all {
-    my ( $self, $params ) = @_;
-    my $selected = $params->{selected};
-
-    my @categories = C4::Category->all;
-    if ( $selected ) {
-        for my $category ( @categories ) {
-            if ( $category->{categorycode} eq $selected ) {
-                $category->{selected} = 1;
-            }
-        }
-    }
-    return @categories;
+    return Koha::Patron::Categories->search_limited;
 }
 
 1;
diff --git a/acqui/add_user_search.pl b/acqui/add_user_search.pl
index ca302e4..ab1f1ca 100755
--- a/acqui/add_user_search.pl
+++ b/acqui/add_user_search.pl
@@ -22,10 +22,11 @@ use Modern::Perl;
 use CGI qw ( -utf8 );
 use C4::Auth;
 use C4::Branch qw( GetBranches );
-use C4::Category;
 use C4::Output;
 use C4::Members;
 
+use Koha::Patron::Categories;
+
 my $input = new CGI;
 
 my $dbh = C4::Context->dbh;
@@ -54,6 +55,7 @@ my $search_patrons_with_acq_perm_only =
 my $onlymine = C4::Branch::onlymine;
 my $branches = C4::Branch::GetBranches( $onlymine );
 
+my $patron_categories = Koha::Patron::Categories->search_limited;
 $template->param(
     patrons_with_acq_perm_only => $search_patrons_with_acq_perm_only,
     view => ( $input->request_method() eq "GET" ) ? "show_form" : "show_results",
@@ -61,7 +63,7 @@ $template->param(
     json_template => 'acqui/tables/members_results.tt',
     selection_type => 'add',
     alphabet        => ( C4::Context->preference('alphabet') || join ' ', 'A' .. 'Z' ),
-    categories      => [ C4::Category->all ],
+    categories      => $patron_categories,
     branches        => [ map { { branchcode => $_->{branchcode}, branchname => $_->{branchname} } } values %$branches ],
     aaSorting       => 1,
 );
diff --git a/admin/add_user_search.pl b/admin/add_user_search.pl
index fdce4be..4f0391a 100755
--- a/admin/add_user_search.pl
+++ b/admin/add_user_search.pl
@@ -22,10 +22,11 @@ use Modern::Perl;
 use CGI qw ( -utf8 );
 use C4::Auth;
 use C4::Branch qw( GetBranches );
-use C4::Category;
 use C4::Output;
 use C4::Members;
 
+use Koha::Patron::Categories;
+
 my $input = new CGI;
 
 my $dbh = C4::Context->dbh;
@@ -55,6 +56,7 @@ my $search_patrons_with_acq_perm_only =
 my $onlymine = C4::Branch::onlymine;
 my $branches = C4::Branch::GetBranches( $onlymine );
 
+my $patron_categories = Koha::Patron::Categories->search_limited;
 $template->param(
     patrons_with_acq_perm_only => $search_patrons_with_acq_perm_only,
     view => ( $input->request_method() eq "GET" ) ? "show_form" : "show_results",
@@ -62,7 +64,7 @@ $template->param(
     json_template => 'acqui/tables/members_results.tt',
     selection_type => $selection_type,
     alphabet        => ( C4::Context->preference('alphabet') || join ' ', 'A' .. 'Z' ),
-    categories      => [ C4::Category->all ],
+    categories      => $patron_categories,
     branches        => [ map { { branchcode => $_->{branchcode}, branchname => $_->{branchname} } } values %$branches ],
     aaSorting       => 1,
 );
diff --git a/admin/item_circulation_alerts.pl b/admin/item_circulation_alerts.pl
index 684a12d..590f154 100755
--- a/admin/item_circulation_alerts.pl
+++ b/admin/item_circulation_alerts.pl
@@ -27,11 +27,12 @@ use JSON;
 use C4::Auth;
 use C4::Context;
 use C4::Branch;
-use C4::Category;
 use C4::ItemType;
 use C4::ItemCirculationAlertPreference;
 use C4::Output;
 
+use Koha::Patron::Categories;
+
 # shortcut for long package name
 our $preferences = 'C4::ItemCirculationAlertPreference';
 
@@ -75,9 +76,7 @@ sub show {
     }
     my $branch_name = exists($br->{$branch}) && $br->{$branch}->{branchname};
 
-    my @categories = (
-        C4::Category->all
-    );
+    my @categories = Koha::Patron::Categories->search_limited;
     my @item_types = map { br($_, 'description') }  (
         C4::ItemType->all
     );
diff --git a/debian/templates/plack.psgi b/debian/templates/plack.psgi
index 9f40d5f..f070b25 100644
--- a/debian/templates/plack.psgi
+++ b/debian/templates/plack.psgi
@@ -28,7 +28,6 @@ use Plack::App::URLMap;
 # Pre-load libraries
 use C4::Boolean;
 use C4::Branch;
-use C4::Category;
 use C4::Koha;
 use C4::Languages;
 use C4::Letters;
diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-search.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-search.inc
index 9b4f19e..03b4004 100644
--- a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-search.inc
+++ b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-search.inc
@@ -97,14 +97,14 @@
 
         <p>
             <label for="categorycode">Category: </label>
-            [% SET categories = Categories.all( selected => categorycode_filter ) %]
+            [% SET categories = Categories.all() %]
             <select name="categorycode_filter" id="categorycode">
                 <option value="">Any</option>
-                [% FOREACH categorie IN categories %]
-                    [% IF ( categorie.selected ) %]
-                        <option value="[% categorie.categorycode %]" selected="selected">[% categorie.description %]</option>
+                [% FOREACH category IN categories %]
+                    [% IF category.categorycode == categorycode_filter %]
+                        <option value="[% category.categorycode %]" selected="selected">[% category.description %]</option>
                     [% ELSE %]
-                        <option value="[% categorie.categorycode %]">[% categorie.description %]</option>
+                        <option value="[% category.categorycode %]">[% category.description %]</option>
                     [% END %]
                 [% END %]
             </select>
diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/member.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/member.tt
index 49971b7..52d7e7e 100644
--- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/member.tt
+++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/member.tt
@@ -469,11 +469,11 @@ function filterByFirstLetterSurname(letter) {
             </li>
             <li>
               <label for="categorycode_filter">Category:</label>
-              [% SET categories = Categories.all( selected => categorycode_filter ) %]
+              [% SET categories = Categories.all() %]
               <select id="categorycode_filter">
                 <option value="">Any</option>
                 [% FOREACH cat IN categories %]
-                  [% IF cat.selected %]
+                  [% IF cat.categorycode == categorycode_filter %]
                     <option selected="selected" value="[% cat.categorycode %]">[% cat.description %]</option>
                   [% ELSE %]
                     <option value="[% cat.categorycode %]">[% cat.description %]</option>
diff --git a/members/guarantor_search.pl b/members/guarantor_search.pl
index 70b28d4..d34b828 100755
--- a/members/guarantor_search.pl
+++ b/members/guarantor_search.pl
@@ -22,10 +22,11 @@ use Modern::Perl;
 use CGI qw ( -utf8 );
 use C4::Auth;
 use C4::Branch qw( GetBranches );
-use C4::Category;
 use C4::Output;
 use C4::Members;
 
+use Koha::Patron::Categories;
+
 my $input = new CGI;
 
 my $dbh = C4::Context->dbh;
@@ -47,13 +48,14 @@ my $referer = $input->referer();
 my $onlymine = C4::Branch::onlymine;
 my $branches = C4::Branch::GetBranches( $onlymine );
 
+my $patron_categories = Koha::Patron::Categories->search_limited;
 $template->param(
     view => ( $input->request_method() eq "GET" ) ? "show_form" : "show_results",
     columns => ['cardnumber', 'name', 'dateofbirth', 'address', 'action' ],
     json_template => 'members/tables/guarantor_search.tt',
     selection_type => 'select',
     alphabet        => ( C4::Context->preference('alphabet') || join ' ', 'A' .. 'Z' ),
-    categories      => [ C4::Category->all ],
+    categories      => $patron_categories,
     branches        => [ map { { branchcode => $_->{branchcode}, branchname => $_->{branchname} } } values %$branches ],
     aaSorting       => 1,
 );
diff --git a/members/member.pl b/members/member.pl
index 1cc5ac5..130486f 100755
--- a/members/member.pl
+++ b/members/member.pl
@@ -28,7 +28,6 @@ use C4::Auth;
 use C4::Output;
 use CGI qw( -utf8 );
 use C4::Branch;
-use C4::Category;
 use C4::Members qw( GetMember );
 use Koha::DateUtils;
 use Koha::List::Patron;
diff --git a/members/members-home.pl b/members/members-home.pl
index b9368f6..cfb0ff6 100755
--- a/members/members-home.pl
+++ b/members/members-home.pl
@@ -25,9 +25,9 @@ use C4::Output;
 use C4::Context;
 use C4::Members;
 use C4::Branch;
-use C4::Category;
 use Koha::Borrower::Modifications;
 use Koha::List::Patron;
+use Koha::Patron::Categories;
 
 my $query = new CGI;
 my $branch = $query->param('branchcode');
@@ -67,7 +67,6 @@ if ( C4::Branch::onlymine ) {
     }
 }
 
-my @categories;
 my $no_add = 0;
 if(scalar(@branchloop) < 1){
     $no_add = 1;
@@ -77,7 +76,7 @@ else {
     $template->param(branchloop=>\@branchloop);
 }
 
-@categories=C4::Category->all;
+my @categories = Koha::Patron::Categories->search_limited;
 if(scalar(@categories) < 1){
     $no_add = 1;
     $template->param(no_categories => 1);
diff --git a/members/members-update-do.pl b/members/members-update-do.pl
index 03af1cd..a071e9f 100755
--- a/members/members-update-do.pl
+++ b/members/members-update-do.pl
@@ -25,7 +25,6 @@ use C4::Output;
 use C4::Context;
 use C4::Members;
 use C4::Branch;
-use C4::Category;
 use Koha::Borrower::Modifications;
 
 my $query = new CGI;
diff --git a/members/members-update.pl b/members/members-update.pl
index 1ab8131..028d043 100755
--- a/members/members-update.pl
+++ b/members/members-update.pl
@@ -25,7 +25,6 @@ use C4::Output;
 use C4::Context;
 use C4::Members;
 use C4::Branch;
-use C4::Category;
 use Koha::Borrower::Modifications;
 
 my $query = new CGI;
diff --git a/members/nl-search.pl b/members/nl-search.pl
index 08f3a04..4e72856 100755
--- a/members/nl-search.pl
+++ b/members/nl-search.pl
@@ -37,7 +37,6 @@ See http://www.lanekortet.no/ for more information (in Norwegian).
 use Modern::Perl;
 use CGI;
 use C4::Auth;
-use C4::Category;
 use C4::Context;
 use C4::Output;
 use C4::Members;
@@ -46,6 +45,7 @@ use C4::Utils::DataTables::Members;
 use Koha::NorwegianPatronDB qw( NLCheckSysprefs NLSearch NLDecodePin NLGetFirstname NLGetSurname NLSync );
 use Koha::Database;
 use Koha::DateUtils;
+use Koha::Patron::Categories;
 
 my $cgi = CGI->new;
 my $dbh = C4::Context->dbh;
@@ -92,11 +92,10 @@ if ( $op && $op eq 'search' ) {
             my $result = NLSearch( $identifier );
             unless ($result->fault) {
                 my $r = $result->result();
-                # Send the data to the template
-                my @categories = C4::Category->all;
+                my $categories = Koha::Patron::Categories->search_limited;
                 $template->param(
                     'result'     => $r,
-                    'categories' => \@categories,
+                    'categories' => $categories,
                 );
             } else {
                 $template->param( 'error' => join ', ', $result->faultcode, $result->faultstring, $result->faultdetail );
diff --git a/misc/plack/koha.psgi b/misc/plack/koha.psgi
index 2415640..a562aa3 100644
--- a/misc/plack/koha.psgi
+++ b/misc/plack/koha.psgi
@@ -43,8 +43,8 @@ use C4::Letters;
 use C4::Koha;
 use C4::XSLT;
 use C4::Branch;
-use C4::Category;
 use Koha::DateUtils;
+use Koha::Patron::Categories;
 =for preload
 use C4::Tags; # FIXME
 =cut
diff --git a/patroncards/add_user_search.pl b/patroncards/add_user_search.pl
index 9bc3685..67fa687 100755
--- a/patroncards/add_user_search.pl
+++ b/patroncards/add_user_search.pl
@@ -22,10 +22,11 @@ use Modern::Perl;
 use CGI qw ( -utf8 );
 use C4::Auth;
 use C4::Branch qw( GetBranches );
-use C4::Category;
 use C4::Output;
 use C4::Members;
 
+use Koha::Patron::Categories;
+
 my $input = new CGI;
 
 my $dbh = C4::Context->dbh;
@@ -47,13 +48,14 @@ my $referer = $input->referer();
 my $onlymine = C4::Branch::onlymine;
 my $branches = C4::Branch::GetBranches( $onlymine );
 
+my $patron_categories = Koha::Patron::Categories->search_limited;
 $template->param(
     view            => ( $input->request_method() eq "GET" ) ? "show_form" : "show_results",
     columns         => ['cardnumber', 'name', 'category', 'branch', 'dateexpiry', 'borrowernotes', 'action'],
     json_template   => 'patroncards/tables/members_results.tt',
     selection_type  => 'add',
     alphabet        => ( C4::Context->preference('alphabet') || join ' ', 'A' .. 'Z' ),
-    categories      => [ C4::Category->all ],
+    categories      => $patron_categories,
     branches        => [ map { { branchcode => $_->{branchcode}, branchname => $_->{branchname} } } values %$branches ],
     aaSorting       => 1,
 );
diff --git a/reports/reserves_stats.pl b/reports/reserves_stats.pl
index 792a772..067b815 100755
--- a/reports/reserves_stats.pl
+++ b/reports/reserves_stats.pl
@@ -31,7 +31,6 @@ use C4::Koha;
 use C4::Output;
 use C4::Reports;
 use C4::Members;
-use C4::Category;
 use Koha::DateUtils;
 use List::MoreUtils qw/any/;
 use YAML;
diff --git a/serials/add_user_search.pl b/serials/add_user_search.pl
index aa7ffaf..6441a78 100755
--- a/serials/add_user_search.pl
+++ b/serials/add_user_search.pl
@@ -22,10 +22,11 @@ use Modern::Perl;
 use CGI qw ( -utf8 );
 use C4::Auth;
 use C4::Branch qw( GetBranches );
-use C4::Category;
 use C4::Output;
 use C4::Members;
 
+use Koha::Patron::Categories;
+
 my $input = new CGI;
 
 my $dbh = C4::Context->dbh;
@@ -46,6 +47,7 @@ my $referer = $input->referer();
 
 my $onlymine = C4::Branch::onlymine;
 my $branches = C4::Branch::GetBranches( $onlymine );
+my $patron_categories = Koha::Patron::Categories->search_limited;
 
 $template->param(
     view => ( $input->request_method() eq "GET" ) ? "show_form" : "show_results",
@@ -53,7 +55,7 @@ $template->param(
     json_template => 'serials/tables/members_results.tt',
     selection_type => 'add',
     alphabet        => ( C4::Context->preference('alphabet') || join ' ', 'A' .. 'Z' ),
-    categories      => [ C4::Category->all ],
+    categories      => $patron_categories,
     branches        => [ map { { branchcode => $_->{branchcode}, branchname => $_->{branchname} } } values %$branches ],
     aaSorting       => 1,
 );
diff --git a/t/db_dependent/Category.t b/t/db_dependent/Category.t
deleted file mode 100755
index 93fd0df..0000000
--- a/t/db_dependent/Category.t
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/perl
-
-# This file is part of Koha.
-#
-# Copyright 2014 - Koha Team
-#
-# Koha is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3 of the License, or
-# (at your option) any later version.
-#
-# Koha is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Koha; if not, see <http://www.gnu.org/licenses>.
-
-use Modern::Perl;
-
-use t::lib::TestBuilder;
-use Test::More tests => 3;
-
-use Koha::Database;
-
-BEGIN {
-    use_ok('C4::Category');
-}
-
-my $schema  = Koha::Database->new->schema;
-$schema->storage->txn_begin;
-
-my $builder = t::lib::TestBuilder->new();
-
-my $nonexistent_categorycode = 'NONEXISTEN';
-$builder->build({
-    source => 'Category',
-    value  => {
-        categorycode          => $nonexistent_categorycode,
-        description           => 'Desc',
-        enrolmentperiod       => 12,
-        enrolementperioddate  => '2014-01-02',
-        upperagelimit         => 99,
-        dateofbirthrequired   => 1,
-        enrolmentfee          => 1.5,
-        reservefee            => 2.5,
-        hidelostitems         => 0,
-        overduenoticerequired => 0,
-        category_type         => 'A',
-    },
-});
-
-my @categories = C4::Category->all;
-ok( @categories, 'all returns categories' );
-
-my $match = grep {$_->{categorycode} eq $nonexistent_categorycode } @categories;
-is( $match, 1, 'all returns the inserted category');
-
-$schema->storage->txn_rollback;
-
-1;
diff --git a/t/db_dependent/Circulation/CheckIfIssuedToPatron.t b/t/db_dependent/Circulation/CheckIfIssuedToPatron.t
index 10e10b6..d84630d 100644
--- a/t/db_dependent/Circulation/CheckIfIssuedToPatron.t
+++ b/t/db_dependent/Circulation/CheckIfIssuedToPatron.t
@@ -24,7 +24,6 @@ use C4::Biblio;
 use C4::Items;
 use C4::Members;
 use C4::Branch;
-use C4::Category;
 use MARC::Record;
 
 BEGIN {
diff --git a/t/db_dependent/Circulation/GetIssues.t b/t/db_dependent/Circulation/GetIssues.t
index ddd5186..eb93f05 100644
--- a/t/db_dependent/Circulation/GetIssues.t
+++ b/t/db_dependent/Circulation/GetIssues.t
@@ -8,8 +8,8 @@ use C4::Biblio;
 use C4::Items;
 use C4::Members;
 use C4::Branch;
-use C4::Category;
 use C4::Circulation;
+use Koha::Patron::Categories;
 use MARC::Record;
 
 my $dbh = C4::Context->dbh;
@@ -43,9 +43,9 @@ my $itemnumber3 = AddItem({ barcode => '0203', %item_branch_infos }, $biblionumb
 
 my $categorycode;
 my $category_created;
-my @categories = C4::Category->all;
+my @categories = Koha::Patron::Categories->search_limited;
 if (@categories) {
-    $categorycode = $categories[0]->{categorycode}
+    $categorycode = $categories[0]->categorycode
 } else {
     $categorycode = 'C';
     C4::Context->dbh->do(
diff --git a/t/db_dependent/Koha/Patron/Categories.t b/t/db_dependent/Koha/Patron/Categories.t
index 974b982..8d87e1e 100644
--- a/t/db_dependent/Koha/Patron/Categories.t
+++ b/t/db_dependent/Koha/Patron/Categories.t
@@ -19,8 +19,9 @@
 
 use Modern::Perl;
 
-use Test::More tests => 5;
+use Test::More tests => 9;
 
+use C4::Context;
 use Koha::Database;
 use Koha::Patron::Category;
 use Koha::Patron::Categories;
@@ -49,8 +50,24 @@ is( $retrieved_category_1->categorycode, $new_category_1->categorycode, 'Find a
 is_deeply( $retrieved_category_1->branch_limitations, [ $branch->{branchcode} ], 'The branch limitation should have been stored and retrieved' );
 is_deeply( $retrieved_category_1->default_messaging, [], 'By default there is not messaging option' );
 
+my $another_branch = $builder->build( { source => 'Branch', } );
+C4::Context->_new_userenv('my_new_userenv');
+C4::Context->set_userenv( 0, 0, 'usercnum', 'firstname', 'surname', $another_branch->{branchcode}, 'My wonderful library', '', '', '' );
+my $new_category_3 = Koha::Patron::Category->new(
+    {   categorycode => 'mycatcodeZ',
+        description  => 'mycatdescZ',
+    }
+)->store;
+$new_category_3->add_branch_limitation( $another_branch->{branchcode} );
+is( Koha::Patron::Categories->search->count, $nb_of_categories + 3, 'The 3rd patron category should have been added' );
+my @limited_categories = Koha::Patron::Categories->search_limited;
+my @limited_category_codes = map { $_->categorycode } @limited_categories;
+is( scalar( grep { $_ eq $new_category_1->categorycode } @limited_category_codes ), 0, 'The first category is limited to another branch' );
+is( scalar( grep { $_ eq $new_category_2->categorycode } @limited_category_codes ), 1, 'The second category is not limited' );
+is( scalar( grep { $_ eq $new_category_3->categorycode } @limited_category_codes ), 1, 'The third category is limited to my branch ' );
+
 $retrieved_category_1->delete;
-is( Koha::Patron::Categories->search->count, $nb_of_categories + 1, 'Delete should have deleted the patron category' );
+is( Koha::Patron::Categories->search->count, $nb_of_categories + 2, 'Delete should have deleted the patron category' );
 
 $schema->storage->txn_rollback;
 
diff --git a/t/db_dependent/Members/GetAllIssues.t b/t/db_dependent/Members/GetAllIssues.t
index 5027b07..2caa539 100644
--- a/t/db_dependent/Members/GetAllIssues.t
+++ b/t/db_dependent/Members/GetAllIssues.t
@@ -9,7 +9,6 @@ use C4::Biblio;
 use C4::Items;
 use C4::Members;
 use C4::Branch;
-use C4::Category;
 use C4::Circulation;
 use MARC::Record;
 
diff --git a/t/db_dependent/Members/GetOverdues.t b/t/db_dependent/Members/GetOverdues.t
index f8a5c6b..b2e5f0c 100644
--- a/t/db_dependent/Members/GetOverdues.t
+++ b/t/db_dependent/Members/GetOverdues.t
@@ -9,7 +9,6 @@ use C4::Biblio;
 use C4::Items;
 use C4::Members;
 use C4::Branch;
-use C4::Category;
 use C4::Circulation;
 use MARC::Record;
 
diff --git a/t/db_dependent/Members/GetPendingIssues.t b/t/db_dependent/Members/GetPendingIssues.t
index 1c1c683..33e17f2 100644
--- a/t/db_dependent/Members/GetPendingIssues.t
+++ b/t/db_dependent/Members/GetPendingIssues.t
@@ -9,7 +9,6 @@ use C4::Biblio;
 use C4::Items;
 use C4::Members;
 use C4::Branch;
-use C4::Category;
 use C4::Circulation;
 use MARC::Record;
 
diff --git a/t/db_dependent/Members/IssueSlip.t b/t/db_dependent/Members/IssueSlip.t
index 8c32c21..d01c9fe 100644
--- a/t/db_dependent/Members/IssueSlip.t
+++ b/t/db_dependent/Members/IssueSlip.t
@@ -9,7 +9,6 @@ use C4::Biblio;
 use C4::Items;
 use C4::Members;
 use C4::Branch;
-use C4::Category;
 use C4::Circulation;
 
 use Koha::DateUtils qw( dt_from_string output_pref );
diff --git a/t/db_dependent/Ratings.t b/t/db_dependent/Ratings.t
index 1f5db0e..dddc104 100755
--- a/t/db_dependent/Ratings.t
+++ b/t/db_dependent/Ratings.t
@@ -22,8 +22,8 @@ use Test::More tests => 14;
 use C4::Biblio qw/AddBiblio/;
 use C4::Members;
 use C4::Context;
-use C4::Category;
 use Koha::Database;
+use Koha::Patron::Categories;
 
 use t::lib::TestBuilder;
 
@@ -41,7 +41,7 @@ my $library = $builder->build({
 
 my ($biblionumber) = AddBiblio( MARC::Record->new, '' );
 
-my @categories   = C4::Category->all;
+my @categories   = Koha::Patron::Categories->search_limited;
 my $categorycode = $categories[0]->categorycode;
 my $branchcode   = $library->{branchcode};
 
diff --git a/t/db_dependent/Utils/Datatables_Members.t b/t/db_dependent/Utils/Datatables_Members.t
index 57b42f7..4fe5510 100644
--- a/t/db_dependent/Utils/Datatables_Members.t
+++ b/t/db_dependent/Utils/Datatables_Members.t
@@ -26,6 +26,8 @@ use C4::Members;
 use C4::Members::Attributes;
 use C4::Members::AttributeTypes;
 
+use Koha::Patron::Categories;
+
 use t::lib::Mocks;
 
 use_ok( "C4::Utils::DataTables::Members" );
@@ -37,7 +39,7 @@ $dbh->{AutoCommit} = 0;
 $dbh->{RaiseError} = 1;
 
 # Pick a categorycode from the DB
-my @categories   = C4::Category->all;
+my @categories   = Koha::Patron::Categories->search_limited;
 my $categorycode = $categories[0]->categorycode;
 # Add a new branch so we control what borrowers it has
 my $branchcode   = "UNC";
diff --git a/t/db_dependent/Utils/Datatables_Virtualshelves.t b/t/db_dependent/Utils/Datatables_Virtualshelves.t
index 0a8f0ab..1101834 100644
--- a/t/db_dependent/Utils/Datatables_Virtualshelves.t
+++ b/t/db_dependent/Utils/Datatables_Virtualshelves.t
@@ -24,6 +24,7 @@ use C4::Context;
 use C4::Branch;
 use C4::Members;
 
+use Koha::Patron::Categories;
 use Koha::Virtualshelf;
 use Koha::Virtualshelves;
 
@@ -38,7 +39,7 @@ $dbh->{RaiseError} = 1;
 $dbh->do(q|DELETE FROM virtualshelves|);
 
 # Pick a categorycode from the DB
-my @categories   = C4::Category->all;
+my @categories   = Koha::Patron::Categories->search_limited;
 my $categorycode = $categories[0]->categorycode;
 my $branchcode   = "ABC";
 my $branch_data = {
-- 
2.1.0