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