bug 3263: Staff Search Results Interface Changes
[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 under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
16 # Suite 330, Boston, MA  02111-1307 USA
17
18
19 use strict;
20 require Exporter;
21 use C4::Context;
22 use C4::Koha;
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.02;
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                 &CheckBranchCategorycode
40                 &GetBranchInfo
41                 &GetCategoryTypes
42                 &GetBranchCategories
43                 &GetBranchesInCategory
44                 &ModBranchCategoryInfo
45                 &DelBranch
46                 &DelBranchCategory
47         );
48         @EXPORT_OK = qw( &onlymine );
49 }
50
51 =head1 NAME
52
53 C4::Branch - Koha branch module
54
55 =head1 SYNOPSIS
56
57 use C4::Branch;
58
59 =head1 DESCRIPTION
60
61 The functions in this module deal with branches.
62
63 =head1 FUNCTIONS
64
65 =head2 GetBranches
66
67   $branches = &GetBranches();
68
69   Returns informations about ALL branches, IndependantBranches Insensitive.
70   GetBranchInfo() returns the same information without the problems of this function 
71   (namespace collision, mainly).
72   Create a branch selector with the following code.
73   
74 =head3 in PERL SCRIPT
75
76     my $branches = GetBranches;
77     my @branchloop;
78     foreach my $thisbranch (sort keys %$branches) {
79         my $selected = 1 if $thisbranch eq $branch;
80         my %row =(value => $thisbranch,
81                     selected => $selected,
82                     branchname => $branches->{$thisbranch}->{branchname},
83                 );
84         push @branchloop, \%row;
85     }
86
87 =head3 in TEMPLATE
88
89     <select name="branch">
90         <option value="">Default</option>
91         <!-- TMPL_LOOP name="branchloop" -->
92         <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="branchname" --></option>
93         <!-- /TMPL_LOOP -->
94     </select>
95
96 =head4 Note that you often will want to just use GetBranchesLoop, for exactly the example above.
97
98 =cut
99
100 sub GetBranches {
101     my ($onlymine)=@_;
102     # returns a reference to a hash of references to ALL branches...
103     my %branches;
104     my $dbh = C4::Context->dbh;
105     my $sth;
106     my $query="SELECT * FROM branches";
107     my @bind_parameters;
108     if ($onlymine && C4::Context->userenv && C4::Context->userenv->{branch}){
109       $query .= ' WHERE branchcode = ? ';
110       push @bind_parameters, C4::Context->userenv->{branch};
111     }
112         $query.=" ORDER BY branchname";
113     $sth = $dbh->prepare($query);
114     $sth->execute( @bind_parameters );
115
116     my $nsth = $dbh->prepare(
117         "SELECT categorycode FROM branchrelations WHERE branchcode = ?"
118     );  # prepare once, outside while loop
119
120     while ( my $branch = $sth->fetchrow_hashref ) {
121         $nsth->execute( $branch->{'branchcode'} );
122         while ( my ($cat) = $nsth->fetchrow_array ) {
123             # FIXME - This seems wrong. It ought to be
124             # $branch->{categorycodes}{$cat} = 1;
125             # otherwise, there's a namespace collision if there's a
126             # category with the same name as a field in the 'branches'
127             # table (i.e., don't create a category called "issuing").
128             # In addition, the current structure doesn't really allow
129             # you to list the categories that a branch belongs to:
130             # you'd have to list keys %$branch, and remove those keys
131             # that aren't fields in the "branches" table.
132          #   $branch->{$cat} = 1;
133             $branch->{category}{$cat} = 1;
134         }
135         $branches{ $branch->{'branchcode'} } = $branch;
136     }
137     return ( \%branches );
138 }
139
140 sub onlymine {
141     return 
142     C4::Context->preference('IndependantBranches') &&
143     C4::Context->userenv                           &&
144     C4::Context->userenv->{flags}!=1               &&
145     C4::Context->userenv->{branch}                 ;
146 }
147
148 sub GetBranchesLoop (;$$) {  # since this is what most pages want anyway
149     my $branch   = @_ ? shift : '';     # optional first argument is branchcode of "my branch", if preselection is wanted.
150     my $onlymine = @_ ? shift : onlymine();
151     my $branches = GetBranches($onlymine);
152     my @loop;
153     foreach (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %$branches) {
154         push @loop, {
155             value => $_,
156             selected => ($_ eq $branch) ? 1 : 0, 
157             branchname => $branches->{$_}->{branchname},
158         };
159     }
160     return \@loop;
161 }
162
163 =head2 GetBranchName
164
165 =cut
166
167 sub GetBranchName {
168     my ($branchcode) = @_;
169     my $dbh = C4::Context->dbh;
170     my $sth;
171     $sth = $dbh->prepare("Select branchname from branches where branchcode=?");
172     $sth->execute($branchcode);
173     my $branchname = $sth->fetchrow_array;
174     $sth->finish;
175     return ($branchname);
176 }
177
178 =head2 ModBranch
179
180 &ModBranch($newvalue);
181
182 This function modify an existing branches.
183
184 C<$newvalue> is a ref to an array wich is containt all the column from branches table.
185
186 =cut
187
188 sub ModBranch {
189     my ($data) = @_;
190     
191     my $dbh    = C4::Context->dbh;
192     if ($data->{add}) {
193         my $query  = "
194             INSERT INTO branches
195             (branchcode,branchname,branchaddress1,
196             branchaddress2,branchaddress3,branchphone,
197             branchfax,branchemail,branchip,branchprinter)
198             VALUES (?,?,?,?,?,?,?,?,?,?)
199         ";
200         my $sth    = $dbh->prepare($query);
201         $sth->execute(
202             $data->{'branchcode'},       $data->{'branchname'},
203             $data->{'branchaddress1'},   $data->{'branchaddress2'},
204             $data->{'branchaddress3'},   $data->{'branchphone'},
205             $data->{'branchfax'},        $data->{'branchemail'},
206             $data->{'branchip'},         $data->{'branchprinter'},
207         );
208     } else {
209         my $query  = "
210             UPDATE branches
211             SET branchname=?,branchaddress1=?,
212                 branchaddress2=?,branchaddress3=?,branchphone=?,
213                 branchfax=?,branchemail=?,branchip=?,branchprinter=?
214             WHERE branchcode=?
215         ";
216         my $sth    = $dbh->prepare($query);
217         $sth->execute(
218             $data->{'branchname'},
219             $data->{'branchaddress1'},   $data->{'branchaddress2'},
220             $data->{'branchaddress3'},   $data->{'branchphone'},
221             $data->{'branchfax'},        $data->{'branchemail'},
222             $data->{'branchip'},         $data->{'branchprinter'},
223             $data->{'branchcode'},
224         );
225     }
226     # sort out the categories....
227     my @checkedcats;
228     my $cats = GetBranchCategory();
229     foreach my $cat (@$cats) {
230         my $code = $cat->{'categorycode'};
231         if ( $data->{$code} ) {
232             push( @checkedcats, $code );
233         }
234     }
235     my $branchcode = uc( $data->{'branchcode'} );
236     my $branch     = GetBranchInfo($branchcode);
237     $branch = $branch->[0];
238     my $branchcats = $branch->{'categories'};
239     my @addcats;
240     my @removecats;
241     foreach my $bcat (@$branchcats) {
242
243         unless ( grep { /^$bcat$/ } @checkedcats ) {
244             push( @removecats, $bcat );
245         }
246     }
247     foreach my $ccat (@checkedcats) {
248         unless ( grep { /^$ccat$/ } @$branchcats ) {
249             push( @addcats, $ccat );
250         }
251     }
252     foreach my $cat (@addcats) {
253         my $sth =
254           $dbh->prepare(
255 "insert into branchrelations (branchcode, categorycode) values(?, ?)"
256           );
257         $sth->execute( $branchcode, $cat );
258         $sth->finish;
259     }
260     foreach my $cat (@removecats) {
261         my $sth =
262           $dbh->prepare(
263             "delete from branchrelations where branchcode=? and categorycode=?"
264           );
265         $sth->execute( $branchcode, $cat );
266         $sth->finish;
267     }
268 }
269
270 =head2 GetBranchCategory
271
272 $results = GetBranchCategory($categorycode);
273
274 C<$results> is an ref to an array.
275
276 =cut
277
278 sub GetBranchCategory {
279
280     # returns a reference to an array of hashes containing branches,
281     my ($catcode) = @_;
282     my $dbh = C4::Context->dbh;
283     my $sth;
284
285     #    print DEBUG "GetBranchCategory: entry: catcode=".cvs($catcode)."\n";
286     if ($catcode) {
287         $sth =
288           $dbh->prepare(
289             "select * from branchcategories where categorycode = ?");
290         $sth->execute($catcode);
291     }
292     else {
293         $sth = $dbh->prepare("Select * from branchcategories");
294         $sth->execute();
295     }
296     my @results;
297     while ( my $data = $sth->fetchrow_hashref ) {
298         push( @results, $data );
299     }
300     $sth->finish;
301
302     #    print DEBUG "GetBranchCategory: exit: returning ".cvs(\@results)."\n";
303     return \@results;
304 }
305
306 =head2 GetBranchCategories
307
308   my $categories = GetBranchCategories($branchcode,$categorytype);
309
310 Returns a list ref of anon hashrefs with keys eq columns of branchcategories table,
311 i.e. categorycode, categorydescription, categorytype, categoryname.
312 if $branchcode and/or $categorytype are passed, limit set to categories that
313 $branchcode is a member of , and to $categorytype.
314
315 =cut
316
317 sub GetBranchCategories {
318     my ($branchcode,$categorytype) = @_;
319         my $dbh = C4::Context->dbh();
320         my $query = "SELECT c.* FROM branchcategories c";
321         my (@where, @bind);
322         if($branchcode) {
323                 $query .= ",branchrelations r, branches b ";
324                 push @where, "c.categorycode=r.categorycode and r.branchcode=? ";  
325                 push @bind , $branchcode;
326         }
327         if ($categorytype) {
328                 push @where, " c.categorytype=? ";
329                 push @bind, $categorytype;
330         }
331         $query .= " where " . join(" and ", @where) if(@where);
332         $query .= " order by categorytype,c.categorycode";
333         my $sth=$dbh->prepare( $query);
334         $sth->execute(@bind);
335         
336         my $branchcats = $sth->fetchall_arrayref({});
337         $sth->finish();
338         return( $branchcats );
339 }
340
341 =head2 GetCategoryTypes
342
343 $categorytypes = GetCategoryTypes;
344 returns a list of category types.
345 Currently these types are HARDCODED.
346 type: 'searchdomain' defines a group of agencies that the calling library may search in.
347 Other usage of agency categories falls under type: 'properties'.
348         to allow for other uses of categories.
349 The searchdomain bit may be better implemented as a separate module, but
350 the categories were already here, and minimally used.
351 =cut
352
353         #TODO  manage category types.  rename possibly to 'agency domains' ? as borrowergroups are called categories.
354 sub GetCategoryTypes() {
355         return ( 'searchdomain','properties');
356 }
357
358 =head2 GetBranch
359
360 $branch = GetBranch( $query, $branches );
361
362 =cut
363
364 sub GetBranch ($$) {
365     my ( $query, $branches ) = @_;    # get branch for this query from branches
366     my $branch = $query->param('branch');
367     my %cookie = $query->cookie('userenv');
368     ($branch)                || ($branch = $cookie{'branchname'});
369     ( $branches->{$branch} ) || ( $branch = ( keys %$branches )[0] );
370     return $branch;
371 }
372
373 =head2 GetBranchDetail
374
375   $branchname = &GetBranchDetail($branchcode);
376
377 Given the branch code, the function returns the corresponding
378 branch name for a comprehensive information display
379
380 =cut
381
382 sub GetBranchDetail {
383     my ($branchcode) = @_;
384     my $dbh = C4::Context->dbh;
385     my $sth = $dbh->prepare("SELECT * FROM branches WHERE branchcode = ?");
386     $sth->execute($branchcode);
387     my $branchname = $sth->fetchrow_hashref();
388     $sth->finish();
389     return $branchname;
390 }
391
392 =head2 get_branchinfos_of
393
394   my $branchinfos_of = get_branchinfos_of(@branchcodes);
395
396 Associates a list of branchcodes to the information of the branch, taken in
397 branches table.
398
399 Returns a href where keys are branchcodes and values are href where keys are
400 branch information key.
401
402   print 'branchname is ', $branchinfos_of->{$code}->{branchname};
403
404 =cut
405
406 sub get_branchinfos_of {
407     my @branchcodes = @_;
408
409     my $query = '
410     SELECT branchcode,
411        branchname
412     FROM branches
413     WHERE branchcode IN ('
414       . join( ',', map( { "'" . $_ . "'" } @branchcodes ) ) . ')
415 ';
416     return C4::Koha::get_infos_of( $query, 'branchcode' );
417 }
418
419
420 =head2 GetBranchesInCategory
421
422   my $branches = GetBranchesInCategory($categorycode);
423
424 Returns a href:  keys %$branches eq (branchcode,branchname) .
425
426 =cut
427
428 sub GetBranchesInCategory($) {
429     my ($categorycode) = @_;
430         my @branches;
431         my $dbh = C4::Context->dbh();
432         my $sth=$dbh->prepare( "SELECT b.branchcode FROM branchrelations r, branches b 
433                                                         where r.branchcode=b.branchcode and r.categorycode=?");
434     $sth->execute($categorycode);
435         while (my $branch = $sth->fetchrow) {
436                 push @branches, $branch;
437         }
438         $sth->finish();
439         return( \@branches );
440 }
441
442 =head2 GetBranchInfo
443
444 $results = GetBranchInfo($branchcode);
445
446 returns C<$results>, a reference to an array of hashes containing branches.
447 if $branchcode, just this branch, with associated categories.
448 if ! $branchcode && $categorytype, all branches in the category.
449 =cut
450
451 sub GetBranchInfo {
452     my ($branchcode,$categorytype) = @_;
453     my $dbh = C4::Context->dbh;
454     my $sth;
455
456
457         if ($branchcode) {
458         $sth =
459           $dbh->prepare(
460             "Select * from branches where branchcode = ? order by branchcode");
461         $sth->execute($branchcode);
462     }
463     else {
464         $sth = $dbh->prepare("Select * from branches order by branchcode");
465         $sth->execute();
466     }
467     my @results;
468     while ( my $data = $sth->fetchrow_hashref ) {
469                 my @bind = ($data->{'branchcode'});
470         my $query= "select r.categorycode from branchrelations r";
471                 $query .= ", branchcategories c " if($categorytype);
472                 $query .= " where  branchcode=? ";
473                 if($categorytype) { 
474                         $query .= " and c.categorytype=? and r.categorycode=c.categorycode";
475                         push @bind, $categorytype;
476                 }
477         my $nsth=$dbh->prepare($query);
478                 $nsth->execute( @bind );
479         my @cats = ();
480         while ( my ($cat) = $nsth->fetchrow_array ) {
481             push( @cats, $cat );
482         }
483         $nsth->finish;
484         $data->{'categories'} = \@cats;
485         push( @results, $data );
486     }
487     $sth->finish;
488     return \@results;
489 }
490
491 =head2 DelBranch
492
493 &DelBranch($branchcode);
494
495 =cut
496
497 sub DelBranch {
498     my ($branchcode) = @_;
499     my $dbh = C4::Context->dbh;
500     my $sth = $dbh->prepare("delete from branches where branchcode = ?");
501     $sth->execute($branchcode);
502     $sth->finish;
503 }
504
505 =head2 ModBranchCategoryInfo
506
507 &ModBranchCategoryInfo($data);
508 sets the data from the editbranch form, and writes to the database...
509
510 =cut
511
512 sub ModBranchCategoryInfo {
513     my ($data) = @_;
514     my $dbh    = C4::Context->dbh;
515         if ($data->{'add'}){
516                 # we are doing an insert
517                 my $sth   = $dbh->prepare("INSERT INTO branchcategories (categorycode,categoryname,codedescription,categorytype) VALUES (?,?,?,?)");
518                 $sth->execute(uc( $data->{'categorycode'} ),$data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'} );
519                 $sth->finish();         
520         }
521         else {
522                 # modifying
523                 my $sth = $dbh->prepare("UPDATE branchcategories SET categoryname=?,codedescription=?,categorytype=? WHERE categorycode=?");
524                 $sth->execute($data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'},uc( $data->{'categorycode'} ) );
525                 $sth->finish();
526         }
527 }
528
529 =head2 DeleteBranchCategory
530
531 DeleteBranchCategory($categorycode);
532
533 =cut
534
535 sub DelBranchCategory {
536     my ($categorycode) = @_;
537     my $dbh = C4::Context->dbh;
538     my $sth = $dbh->prepare("delete from branchcategories where categorycode = ?");
539     $sth->execute($categorycode);
540     $sth->finish;
541 }
542
543 =head2 CheckBranchCategorycode
544
545 $number_rows_affected = CheckBranchCategorycode($categorycode);
546
547 =cut
548
549 sub CheckBranchCategorycode {
550
551     # check to see if the branchcode is being used in the database somewhere....
552     my ($categorycode) = @_;
553     my $dbh            = C4::Context->dbh;
554     my $sth            =
555       $dbh->prepare(
556         "select count(*) from branchrelations where categorycode=?");
557     $sth->execute($categorycode);
558     my ($total) = $sth->fetchrow_array;
559     return $total;
560 }
561
562 1;
563 __END__
564
565 =head1 AUTHOR
566
567 Koha Developement team <info@koha.org>
568
569 =cut