Remove unused variable and add FIXME.
[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 &mybranch );
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 # always returns a string for OK comparison via "eq" or "ne"
149 sub mybranch {
150     C4::Context->userenv           or return '';
151     return C4::Context->userenv->{branch} || '';
152 }
153
154 sub GetBranchesLoop (;$$) {  # since this is what most pages want anyway
155     my $branch   = @_ ? shift : mybranch();     # optional first argument is branchcode of "my branch", if preselection is wanted.
156     my $onlymine = @_ ? shift : onlymine();
157     my $branches = GetBranches($onlymine);
158     my @loop;
159     foreach (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %$branches) {
160         push @loop, {
161             value => $_,
162             selected => ($_ eq $branch) ? 1 : 0, 
163             branchname => $branches->{$_}->{branchname},
164         };
165     }
166     return \@loop;
167 }
168
169 =head2 GetBranchName
170
171 =cut
172
173 sub GetBranchName {
174     my ($branchcode) = @_;
175     my $dbh = C4::Context->dbh;
176     my $sth;
177     $sth = $dbh->prepare("Select branchname from branches where branchcode=?");
178     $sth->execute($branchcode);
179     my $branchname = $sth->fetchrow_array;
180     $sth->finish;
181     return ($branchname);
182 }
183
184 =head2 ModBranch
185
186 $error = &ModBranch($newvalue);
187
188 This function modify an existing branch
189
190 C<$newvalue> is a ref to an array wich is containt all the column from branches table.
191
192 =cut
193
194 sub ModBranch {
195     my ($data) = @_;
196     
197     my $dbh    = C4::Context->dbh;
198     if ($data->{add}) {
199         my $query  = "
200             INSERT INTO branches
201             (branchcode,branchname,branchaddress1,
202             branchaddress2,branchaddress3,branchphone,
203             branchfax,branchemail,branchip,branchprinter)
204             VALUES (?,?,?,?,?,?,?,?,?,?)
205         ";
206         my $sth    = $dbh->prepare($query);
207         $sth->execute(
208             $data->{'branchcode'},       $data->{'branchname'},
209             $data->{'branchaddress1'},   $data->{'branchaddress2'},
210             $data->{'branchaddress3'},   $data->{'branchphone'},
211             $data->{'branchfax'},        $data->{'branchemail'},
212             $data->{'branchip'},         $data->{'branchprinter'},
213         );
214         return 1 if $dbh->err;
215     } else {
216         my $query  = "
217             UPDATE branches
218             SET branchname=?,branchaddress1=?,
219                 branchaddress2=?,branchaddress3=?,branchphone=?,
220                 branchfax=?,branchemail=?,branchip=?,branchprinter=?
221             WHERE branchcode=?
222         ";
223         my $sth    = $dbh->prepare($query);
224         $sth->execute(
225             $data->{'branchname'},
226             $data->{'branchaddress1'},   $data->{'branchaddress2'},
227             $data->{'branchaddress3'},   $data->{'branchphone'},
228             $data->{'branchfax'},        $data->{'branchemail'},
229             $data->{'branchip'},         $data->{'branchprinter'},
230             $data->{'branchcode'},
231         );
232     }
233     # sort out the categories....
234     my @checkedcats;
235     my $cats = GetBranchCategory();
236     foreach my $cat (@$cats) {
237         my $code = $cat->{'categorycode'};
238         if ( $data->{$code} ) {
239             push( @checkedcats, $code );
240         }
241     }
242     my $branchcode = uc( $data->{'branchcode'} );
243     my $branch     = GetBranchInfo($branchcode);
244     $branch = $branch->[0];
245     my $branchcats = $branch->{'categories'};
246     my @addcats;
247     my @removecats;
248     foreach my $bcat (@$branchcats) {
249
250         unless ( grep { /^$bcat$/ } @checkedcats ) {
251             push( @removecats, $bcat );
252         }
253     }
254     foreach my $ccat (@checkedcats) {
255         unless ( grep { /^$ccat$/ } @$branchcats ) {
256             push( @addcats, $ccat );
257         }
258     }
259     foreach my $cat (@addcats) {
260         my $sth =
261           $dbh->prepare(
262 "insert into branchrelations (branchcode, categorycode) values(?, ?)"
263           );
264         $sth->execute( $branchcode, $cat );
265         $sth->finish;
266     }
267     foreach my $cat (@removecats) {
268         my $sth =
269           $dbh->prepare(
270             "delete from branchrelations where branchcode=? and categorycode=?"
271           );
272         $sth->execute( $branchcode, $cat );
273         $sth->finish;
274     }
275 }
276
277 =head2 GetBranchCategory
278
279 $results = GetBranchCategory($categorycode);
280
281 C<$results> is an ref to an array.
282
283 =cut
284
285 sub GetBranchCategory {
286
287     # returns a reference to an array of hashes containing branches,
288     my ($catcode) = @_;
289     my $dbh = C4::Context->dbh;
290     my $sth;
291
292     #    print DEBUG "GetBranchCategory: entry: catcode=".cvs($catcode)."\n";
293     if ($catcode) {
294         $sth =
295           $dbh->prepare(
296             "select * from branchcategories where categorycode = ?");
297         $sth->execute($catcode);
298     }
299     else {
300         $sth = $dbh->prepare("Select * from branchcategories");
301         $sth->execute();
302     }
303     my @results;
304     while ( my $data = $sth->fetchrow_hashref ) {
305         push( @results, $data );
306     }
307     $sth->finish;
308
309     #    print DEBUG "GetBranchCategory: exit: returning ".cvs(\@results)."\n";
310     return \@results;
311 }
312
313 =head2 GetBranchCategories
314
315   my $categories = GetBranchCategories($branchcode,$categorytype);
316
317 Returns a list ref of anon hashrefs with keys eq columns of branchcategories table,
318 i.e. categorycode, categorydescription, categorytype, categoryname.
319 if $branchcode and/or $categorytype are passed, limit set to categories that
320 $branchcode is a member of , and to $categorytype.
321
322 =cut
323
324 sub GetBranchCategories {
325     my ($branchcode,$categorytype) = @_;
326         my $dbh = C4::Context->dbh();
327         my $query = "SELECT c.* FROM branchcategories c";
328         my (@where, @bind);
329         if($branchcode) {
330                 $query .= ",branchrelations r, branches b ";
331                 push @where, "c.categorycode=r.categorycode and r.branchcode=? ";  
332                 push @bind , $branchcode;
333         }
334         if ($categorytype) {
335                 push @where, " c.categorytype=? ";
336                 push @bind, $categorytype;
337         }
338         $query .= " where " . join(" and ", @where) if(@where);
339         $query .= " order by categorytype,c.categorycode";
340         my $sth=$dbh->prepare( $query);
341         $sth->execute(@bind);
342         
343         my $branchcats = $sth->fetchall_arrayref({});
344         $sth->finish();
345         return( $branchcats );
346 }
347
348 =head2 GetCategoryTypes
349
350 $categorytypes = GetCategoryTypes;
351 returns a list of category types.
352 Currently these types are HARDCODED.
353 type: 'searchdomain' defines a group of agencies that the calling library may search in.
354 Other usage of agency categories falls under type: 'properties'.
355         to allow for other uses of categories.
356 The searchdomain bit may be better implemented as a separate module, but
357 the categories were already here, and minimally used.
358 =cut
359
360         #TODO  manage category types.  rename possibly to 'agency domains' ? as borrowergroups are called categories.
361 sub GetCategoryTypes() {
362         return ( 'searchdomain','properties');
363 }
364
365 =head2 GetBranch
366
367 $branch = GetBranch( $query, $branches );
368
369 =cut
370
371 sub GetBranch ($$) {
372     my ( $query, $branches ) = @_;    # get branch for this query from branches
373     my $branch = $query->param('branch');
374     my %cookie = $query->cookie('userenv');
375     ($branch)                || ($branch = $cookie{'branchname'});
376     ( $branches->{$branch} ) || ( $branch = ( keys %$branches )[0] );
377     return $branch;
378 }
379
380 =head2 GetBranchDetail
381
382     $branch = &GetBranchDetail($branchcode);
383
384 Given the branch code, the function returns a
385 hashref for the corresponding row in the branches table.
386
387 =cut
388
389 sub GetBranchDetail {
390     my ($branchcode) = shift or return;
391     my $sth = C4::Context->dbh->prepare("SELECT * FROM branches WHERE branchcode = ?");
392     $sth->execute($branchcode);
393     return $sth->fetchrow_hashref();
394 }
395
396 =head2 get_branchinfos_of
397
398   my $branchinfos_of = get_branchinfos_of(@branchcodes);
399
400 Associates a list of branchcodes to the information of the branch, taken in
401 branches table.
402
403 Returns a href where keys are branchcodes and values are href where keys are
404 branch information key.
405
406   print 'branchname is ', $branchinfos_of->{$code}->{branchname};
407
408 =cut
409
410 sub get_branchinfos_of {
411     my @branchcodes = @_;
412
413     my $query = '
414     SELECT branchcode,
415        branchname
416     FROM branches
417     WHERE branchcode IN ('
418       . join( ',', map( { "'" . $_ . "'" } @branchcodes ) ) . ')
419 ';
420     return C4::Koha::get_infos_of( $query, 'branchcode' );
421 }
422
423
424 =head2 GetBranchesInCategory
425
426   my $branches = GetBranchesInCategory($categorycode);
427
428 Returns a href:  keys %$branches eq (branchcode,branchname) .
429
430 =cut
431
432 sub GetBranchesInCategory($) {
433     my ($categorycode) = @_;
434         my @branches;
435         my $dbh = C4::Context->dbh();
436         my $sth=$dbh->prepare( "SELECT b.branchcode FROM branchrelations r, branches b 
437                                                         where r.branchcode=b.branchcode and r.categorycode=?");
438     $sth->execute($categorycode);
439         while (my $branch = $sth->fetchrow) {
440                 push @branches, $branch;
441         }
442         $sth->finish();
443         return( \@branches );
444 }
445
446 =head2 GetBranchInfo
447
448 $results = GetBranchInfo($branchcode);
449
450 returns C<$results>, a reference to an array of hashes containing branches.
451 if $branchcode, just this branch, with associated categories.
452 if ! $branchcode && $categorytype, all branches in the category.
453 =cut
454
455 sub GetBranchInfo {
456     my ($branchcode,$categorytype) = @_;
457     my $dbh = C4::Context->dbh;
458     my $sth;
459
460
461         if ($branchcode) {
462         $sth =
463           $dbh->prepare(
464             "Select * from branches where branchcode = ? order by branchcode");
465         $sth->execute($branchcode);
466     }
467     else {
468         $sth = $dbh->prepare("Select * from branches order by branchcode");
469         $sth->execute();
470     }
471     my @results;
472     while ( my $data = $sth->fetchrow_hashref ) {
473                 my @bind = ($data->{'branchcode'});
474         my $query= "select r.categorycode from branchrelations r";
475                 $query .= ", branchcategories c " if($categorytype);
476                 $query .= " where  branchcode=? ";
477                 if($categorytype) { 
478                         $query .= " and c.categorytype=? and r.categorycode=c.categorycode";
479                         push @bind, $categorytype;
480                 }
481         my $nsth=$dbh->prepare($query);
482                 $nsth->execute( @bind );
483         my @cats = ();
484         while ( my ($cat) = $nsth->fetchrow_array ) {
485             push( @cats, $cat );
486         }
487         $nsth->finish;
488         $data->{'categories'} = \@cats;
489         push( @results, $data );
490     }
491     $sth->finish;
492     return \@results;
493 }
494
495 =head2 DelBranch
496
497 &DelBranch($branchcode);
498
499 =cut
500
501 sub DelBranch {
502     my ($branchcode) = @_;
503     my $dbh = C4::Context->dbh;
504     my $sth = $dbh->prepare("delete from branches where branchcode = ?");
505     $sth->execute($branchcode);
506     $sth->finish;
507 }
508
509 =head2 ModBranchCategoryInfo
510
511 &ModBranchCategoryInfo($data);
512 sets the data from the editbranch form, and writes to the database...
513
514 =cut
515
516 sub ModBranchCategoryInfo {
517     my ($data) = @_;
518     my $dbh    = C4::Context->dbh;
519         if ($data->{'add'}){
520                 # we are doing an insert
521                 my $sth   = $dbh->prepare("INSERT INTO branchcategories (categorycode,categoryname,codedescription,categorytype) VALUES (?,?,?,?)");
522                 $sth->execute(uc( $data->{'categorycode'} ),$data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'} );
523                 $sth->finish();         
524         }
525         else {
526                 # modifying
527                 my $sth = $dbh->prepare("UPDATE branchcategories SET categoryname=?,codedescription=?,categorytype=? WHERE categorycode=?");
528                 $sth->execute($data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'},uc( $data->{'categorycode'} ) );
529                 $sth->finish();
530         }
531 }
532
533 =head2 DeleteBranchCategory
534
535 DeleteBranchCategory($categorycode);
536
537 =cut
538
539 sub DelBranchCategory {
540     my ($categorycode) = @_;
541     my $dbh = C4::Context->dbh;
542     my $sth = $dbh->prepare("delete from branchcategories where categorycode = ?");
543     $sth->execute($categorycode);
544     $sth->finish;
545 }
546
547 =head2 CheckBranchCategorycode
548
549 $number_rows_affected = CheckBranchCategorycode($categorycode);
550
551 =cut
552
553 sub CheckBranchCategorycode {
554
555     # check to see if the branchcode is being used in the database somewhere....
556     my ($categorycode) = @_;
557     my $dbh            = C4::Context->dbh;
558     my $sth            =
559       $dbh->prepare(
560         "select count(*) from branchrelations where categorycode=?");
561     $sth->execute($categorycode);
562     my ($total) = $sth->fetchrow_array;
563     return $total;
564 }
565
566 1;
567 __END__
568
569 =head1 AUTHOR
570
571 Koha Developement team <info@koha.org>
572
573 =cut