Bug 15295: Koha::Libraries - Remove CheckBranchCategorycode
[koha.git] / C4 / Branch.pm
1 package C4::Branch;
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18
19 use strict;
20 #use warnings; FIXME - Bug 2505
21 require Exporter;
22 use C4::Context;
23
24 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
25
26 BEGIN {
27         # set the version for version checking
28     $VERSION = 3.07.00.049;
29         @ISA    = qw(Exporter);
30         @EXPORT = qw(
31                 &GetBranchCategory
32                 &GetBranchName
33                 &GetBranch
34                 &GetBranches
35                 &GetBranchesLoop
36                 &GetBranchDetail
37                 &get_branchinfos_of
38                 &ModBranch
39                 &GetBranchInfo
40                 &GetCategoryTypes
41                 &GetBranchCategories
42                 &GetBranchesInCategory
43                 &ModBranchCategoryInfo
44                 &mybranch
45                 &GetBranchesCount
46         );
47     @EXPORT_OK = qw( &onlymine &mybranch );
48 }
49
50 =head1 NAME
51
52 C4::Branch - Koha branch module
53
54 =head1 SYNOPSIS
55
56 use C4::Branch;
57
58 =head1 DESCRIPTION
59
60 The functions in this module deal with branches.
61
62 =head1 FUNCTIONS
63
64 =head2 GetBranches
65
66   $branches = &GetBranches();
67
68 Returns informations about ALL branches, IndependentBranches Insensitive.
69 GetBranchInfo() returns the same information.
70
71 Create a branch selector with the following code.
72
73 =head3 in PERL SCRIPT
74
75     my $branches = GetBranches;
76     my @branchloop;
77     foreach my $thisbranch (sort keys %$branches) {
78         my $selected = 1 if $thisbranch eq $branch;
79         my %row =(value => $thisbranch,
80                     selected => $selected,
81                     branchname => $branches->{$thisbranch}->{branchname},
82                 );
83         push @branchloop, \%row;
84     }
85
86 =head3 in TEMPLATE
87
88     <select name="branch" id="branch">
89         <option value=""></option>
90             [% FOREACH branchloo IN branchloop %]
91                 [% IF ( branchloo.selected ) %]
92                     <option value="[% branchloo.value %]" selected="selected">[% branchloo.branchname %]</option>
93                 [% ELSE %]
94                     <option value="[% branchloo.value %]" >[% branchloo.branchname %]</option>
95                 [% END %]
96             [% END %]
97     </select>
98
99 =head4 Note that you often will want to just use GetBranchesLoop, for exactly the example above.
100
101 =cut
102
103 sub GetBranches {
104     my ($onlymine) = @_;
105
106     # returns a reference to a hash of references to ALL branches...
107     my %branches;
108     my $dbh = C4::Context->dbh;
109     my $sth;
110     my $query = "SELECT * FROM branches";
111     my @bind_parameters;
112     if ( $onlymine && C4::Context->userenv && C4::Context->userenv->{branch} ) {
113         $query .= ' WHERE branchcode = ? ';
114         push @bind_parameters, C4::Context->userenv->{branch};
115     }
116     $query .= " ORDER BY branchname";
117     $sth = $dbh->prepare($query);
118     $sth->execute(@bind_parameters);
119
120     my $relations_sth =
121       $dbh->prepare("SELECT branchcode,categorycode FROM branchrelations");
122     $relations_sth->execute();
123     my %relations;
124     while ( my $rel = $relations_sth->fetchrow_hashref ) {
125         push @{ $relations{ $rel->{branchcode} } }, $rel->{categorycode};
126     }
127
128     while ( my $branch = $sth->fetchrow_hashref ) {
129         foreach my $cat ( @{ $relations{ $branch->{branchcode} } } ) {
130             $branch->{category}{$cat} = 1;
131         }
132         $branches{ $branch->{'branchcode'} } = $branch;
133     }
134     return ( \%branches );
135 }
136
137 sub onlymine {
138     return
139          C4::Context->preference('IndependentBranches')
140       && C4::Context->userenv
141       && !C4::Context->IsSuperLibrarian()
142       && C4::Context->userenv->{branch};
143 }
144
145 # always returns a string for OK comparison via "eq" or "ne"
146 sub mybranch {
147     C4::Context->userenv           or return '';
148     return C4::Context->userenv->{branch} || '';
149 }
150
151 sub GetBranchesLoop {  # since this is what most pages want anyway
152     my $branch   = @_ ? shift : mybranch();     # optional first argument is branchcode of "my branch", if preselection is wanted.
153     my $onlymine = @_ ? shift : onlymine();
154     my $branches = GetBranches($onlymine);
155     my @loop;
156     foreach my $branchcode ( sort { uc($branches->{$a}->{branchname}) cmp uc($branches->{$b}->{branchname}) } keys %$branches ) {
157         push @loop, {
158             value      => $branchcode,
159             branchcode => $branchcode,
160             selected   => ($branchcode eq $branch) ? 1 : 0,
161             branchname => $branches->{$branchcode}->{branchname},
162         };
163     }
164     return \@loop;
165 }
166
167 =head2 GetBranchName
168
169 =cut
170
171 sub GetBranchName {
172     my ($branchcode) = @_;
173     my $dbh = C4::Context->dbh;
174     my $sth;
175     $sth = $dbh->prepare("Select branchname from branches where branchcode=?");
176     $sth->execute($branchcode);
177     my $branchname = $sth->fetchrow_array;
178     return ($branchname);
179 }
180
181 =head2 ModBranch
182
183 $error = &ModBranch($newvalue);
184
185 This function modifies an existing branch
186
187 C<$newvalue> is a ref to an array which contains all the columns from branches table.
188
189 =cut
190
191 sub ModBranch {
192     my ($data) = @_;
193     
194     my $dbh    = C4::Context->dbh;
195     if ($data->{add}) {
196         my $query  = "
197             INSERT INTO branches
198             (branchcode,branchname,branchaddress1,
199             branchaddress2,branchaddress3,branchzip,branchcity,branchstate,
200             branchcountry,branchphone,branchfax,branchemail,
201             branchurl,branchip,branchprinter,branchnotes,opac_info,
202             branchreplyto, branchreturnpath)
203             VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
204         ";
205         my $sth    = $dbh->prepare($query);
206         $sth->execute(
207             $data->{'branchcode'},       $data->{'branchname'},
208             $data->{'branchaddress1'},   $data->{'branchaddress2'},
209             $data->{'branchaddress3'},   $data->{'branchzip'},
210             $data->{'branchcity'},       $data->{'branchstate'},
211             $data->{'branchcountry'},
212             $data->{'branchphone'},      $data->{'branchfax'},
213             $data->{'branchemail'},      $data->{'branchurl'},
214             $data->{'branchip'},         $data->{'branchprinter'},
215             $data->{'branchnotes'},      $data->{opac_info},
216             $data->{'branchreplyto'},    $data->{'branchreturnpath'}
217         );
218         return 1 if $dbh->err;
219     } else {
220         my $query  = "
221             UPDATE branches
222             SET branchname=?,branchaddress1=?,
223                 branchaddress2=?,branchaddress3=?,branchzip=?,
224                 branchcity=?,branchstate=?,branchcountry=?,branchphone=?,
225                 branchfax=?,branchemail=?,branchurl=?,branchip=?,
226                 branchprinter=?,branchnotes=?,opac_info=?,
227                 branchreplyto=?, branchreturnpath=?
228             WHERE branchcode=?
229         ";
230         my $sth    = $dbh->prepare($query);
231         $sth->execute(
232             $data->{'branchname'},
233             $data->{'branchaddress1'},   $data->{'branchaddress2'},
234             $data->{'branchaddress3'},   $data->{'branchzip'},
235             $data->{'branchcity'},       $data->{'branchstate'},       
236             $data->{'branchcountry'},
237             $data->{'branchphone'},      $data->{'branchfax'},
238             $data->{'branchemail'},      $data->{'branchurl'},
239             $data->{'branchip'},         $data->{'branchprinter'},
240             $data->{'branchnotes'},      $data->{opac_info},
241             $data->{'branchreplyto'},    $data->{'branchreturnpath'},
242             $data->{'branchcode'},
243         );
244     }
245     # sort out the categories....
246     my @checkedcats;
247     my $cats = GetBranchCategories();
248     foreach my $cat (@$cats) {
249         my $code = $cat->{'categorycode'};
250         if ( $data->{$code} ) {
251             push( @checkedcats, $code );
252         }
253     }
254     my $branchcode = uc( $data->{'branchcode'} );
255     my $branch     = GetBranchInfo($branchcode);
256     $branch = $branch->[0];
257     my $branchcats = $branch->{'categories'};
258     my @addcats;
259     my @removecats;
260     foreach my $bcat (@$branchcats) {
261
262         unless ( grep { /^$bcat$/ } @checkedcats ) {
263             push( @removecats, $bcat );
264         }
265     }
266     foreach my $ccat (@checkedcats) {
267         unless ( grep { /^$ccat$/ } @$branchcats ) {
268             push( @addcats, $ccat );
269         }
270     }
271     foreach my $cat (@addcats) {
272         my $sth =
273           $dbh->prepare(
274 "insert into branchrelations (branchcode, categorycode) values(?, ?)"
275           );
276         $sth->execute( $branchcode, $cat );
277     }
278     foreach my $cat (@removecats) {
279         my $sth =
280           $dbh->prepare(
281             "delete from branchrelations where branchcode=? and categorycode=?"
282           );
283         $sth->execute( $branchcode, $cat );
284     }
285 }
286
287 =head2 GetBranchCategory
288
289 $results = GetBranchCategory($categorycode);
290
291 C<$results> is an hashref
292
293 =cut
294
295 sub GetBranchCategory {
296     my ($catcode) = @_;
297     return unless $catcode;
298
299     my $dbh = C4::Context->dbh;
300     my $sth;
301
302     $sth = $dbh->prepare(q{
303         SELECT *
304         FROM branchcategories
305         WHERE categorycode = ?
306     });
307     $sth->execute( $catcode );
308     return $sth->fetchrow_hashref;
309 }
310
311 =head2 GetBranchCategories
312
313   my $categories = GetBranchCategories($categorytype,$show_in_pulldown,$selected_in_pulldown);
314
315 Returns a list ref of anon hashrefs with keys eq columns of branchcategories table,
316 i.e. categorydescription, categorytype, categoryname.
317
318 =cut
319
320 sub GetBranchCategories {
321     my ( $categorytype, $show_in_pulldown, $selected_in_pulldown ) = @_;
322     my $dbh = C4::Context->dbh();
323
324     my $query = "SELECT * FROM branchcategories ";
325
326     my ( @where, @bind );
327     if ( $categorytype ) {
328         push @where, " categorytype = ? ";
329         push @bind, $categorytype;
330     }
331
332     if ( defined( $show_in_pulldown ) ) {
333         push( @where, " show_in_pulldown = ? " );
334         push( @bind, $show_in_pulldown );
335     }
336
337     $query .= " WHERE " . join(" AND ", @where) if(@where);
338     $query .= " ORDER BY categorytype, categorycode";
339     my $sth=$dbh->prepare( $query);
340     $sth->execute(@bind);
341
342     my $branchcats = $sth->fetchall_arrayref({});
343
344     if ( $selected_in_pulldown ) {
345         foreach my $bc ( @$branchcats ) {
346             $bc->{selected} = 1 if $bc->{categorycode} eq $selected_in_pulldown;
347         }
348     }
349
350     return $branchcats;
351 }
352
353 =head2 GetCategoryTypes
354
355 $categorytypes = GetCategoryTypes;
356 returns a list of category types.
357 Currently these types are HARDCODED.
358 type: 'searchdomain' defines a group of agencies that the calling library may search in.
359 Other usage of agency categories falls under type: 'properties'.
360         to allow for other uses of categories.
361 The searchdomain bit may be better implemented as a separate module, but
362 the categories were already here, and minimally used.
363
364 =cut
365
366         #TODO  manage category types.  rename possibly to 'agency domains' ? as borrowergroups are called categories.
367 sub GetCategoryTypes {
368         return ( 'searchdomain','properties');
369 }
370
371 =head2 GetBranch
372
373 $branch = GetBranch( $query, $branches );
374
375 =cut
376
377 sub GetBranch {
378     my ( $query, $branches ) = @_;    # get branch for this query from branches
379     my $branch = $query->param('branch');
380     my %cookie = $query->cookie('userenv');
381     ($branch)                || ($branch = $cookie{'branchname'});
382     ( $branches->{$branch} ) || ( $branch = ( keys %$branches )[0] );
383     return $branch;
384 }
385
386 =head2 GetBranchDetail
387
388     $branch = &GetBranchDetail($branchcode);
389
390 Given the branch code, the function returns a
391 hashref for the corresponding row in the branches table.
392
393 =cut
394
395 sub GetBranchDetail {
396     my ($branchcode) = shift or return;
397     my $sth = C4::Context->dbh->prepare("SELECT * FROM branches WHERE branchcode = ?");
398     $sth->execute($branchcode);
399     return $sth->fetchrow_hashref();
400 }
401
402 =head2 GetBranchesInCategory
403
404   my $branches = GetBranchesInCategory($categorycode);
405
406 Returns a href:  keys %$branches eq (branchcode,branchname) .
407
408 =cut
409
410 sub GetBranchesInCategory {
411     my ($categorycode) = @_;
412         my @branches;
413         my $dbh = C4::Context->dbh();
414         my $sth=$dbh->prepare( "SELECT b.branchcode FROM branchrelations r, branches b 
415                                                         where r.branchcode=b.branchcode and r.categorycode=?");
416     $sth->execute($categorycode);
417         while (my $branch = $sth->fetchrow) {
418                 push @branches, $branch;
419         }
420         return( \@branches );
421 }
422
423 =head2 GetBranchInfo
424
425 $results = GetBranchInfo($branchcode);
426
427 returns C<$results>, a reference to an array of hashes containing branches.
428 if $branchcode, just this branch, with associated categories.
429 if ! $branchcode && $categorytype, all branches in the category.
430
431 =cut
432
433 sub GetBranchInfo {
434     my ($branchcode,$categorytype) = @_;
435     my $dbh = C4::Context->dbh;
436     my $sth;
437
438
439         if ($branchcode) {
440         $sth =
441           $dbh->prepare(
442             "Select * from branches where branchcode = ? order by branchcode");
443         $sth->execute($branchcode);
444     }
445     else {
446         $sth = $dbh->prepare("Select * from branches order by branchcode");
447         $sth->execute();
448     }
449     my @results;
450     while ( my $data = $sth->fetchrow_hashref ) {
451                 my @bind = ($data->{'branchcode'});
452         my $query= "select r.categorycode from branchrelations r";
453                 $query .= ", branchcategories c " if($categorytype);
454                 $query .= " where  branchcode=? ";
455                 if($categorytype) { 
456                         $query .= " and c.categorytype=? and r.categorycode=c.categorycode";
457                         push @bind, $categorytype;
458                 }
459         my $nsth=$dbh->prepare($query);
460                 $nsth->execute( @bind );
461         my @cats = ();
462         while ( my ($cat) = $nsth->fetchrow_array ) {
463             push( @cats, $cat );
464         }
465         $data->{'categories'} = \@cats;
466         push( @results, $data );
467     }
468     return \@results;
469 }
470
471 =head2 ModBranchCategoryInfo
472
473 &ModBranchCategoryInfo($data);
474 sets the data from the editbranch form, and writes to the database...
475
476 =cut
477
478 sub ModBranchCategoryInfo {
479     my ($data) = @_;
480     my $dbh    = C4::Context->dbh;
481     if ($data->{'add'}){
482         # we are doing an insert
483   my $sth   = $dbh->prepare("INSERT INTO branchcategories (categorycode,categoryname,codedescription,categorytype,show_in_pulldown) VALUES (?,?,?,?,?)");
484         $sth->execute(uc( $data->{'categorycode'} ),$data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'},$data->{'show_in_pulldown'} );
485     }
486     else {
487         # modifying
488         my $sth = $dbh->prepare("UPDATE branchcategories SET categoryname=?,codedescription=?,categorytype=?,show_in_pulldown=? WHERE categorycode=?");
489         $sth->execute($data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'},$data->{'show_in_pulldown'},uc( $data->{'categorycode'} ) );
490     }
491 }
492 sub GetBranchesCount {
493     my $dbh = C4::Context->dbh();
494     my $query = "SELECT COUNT(*) AS branches_count FROM branches";
495     my $sth = $dbh->prepare( $query );
496     $sth->execute();
497     my $row = $sth->fetchrow_hashref();
498     return $row->{'branches_count'};
499 }
500
501 1;
502 __END__
503
504 =head1 AUTHOR
505
506 Koha Development Team <http://koha-community.org/>
507
508 =cut