Merge commit 'kc/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 #use warnings; FIXME - Bug 2505
21 require Exporter;
22 use C4::Context;
23 use C4::Koha;
24
25 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
26
27 BEGIN {
28         # set the version for version checking
29         $VERSION = 3.02;
30         @ISA    = qw(Exporter);
31         @EXPORT = qw(
32                 &GetBranchCategory
33                 &GetBranchName
34                 &GetBranch
35                 &GetBranches
36                 &GetBranchesLoop
37                 &GetBranchDetail
38                 &get_branchinfos_of
39                 &ModBranch
40                 &CheckBranchCategorycode
41                 &GetBranchInfo
42                 &GetCategoryTypes
43                 &GetBranchCategories
44                 &GetBranchesInCategory
45                 &ModBranchCategoryInfo
46                 &DelBranch
47                 &DelBranchCategory
48                 &CheckCategoryUnique
49         );
50         @EXPORT_OK = qw( &onlymine &mybranch get_branch_code_from_name );
51 }
52
53 =head1 NAME
54
55 C4::Branch - Koha branch module
56
57 =head1 SYNOPSIS
58
59 use C4::Branch;
60
61 =head1 DESCRIPTION
62
63 The functions in this module deal with branches.
64
65 =head1 FUNCTIONS
66
67 =head2 GetBranches
68
69   $branches = &GetBranches();
70
71 Returns informations about ALL branches, IndependantBranches Insensitive.
72 GetBranchInfo() returns the same information without the problems of this function 
73 (namespace collision, mainly).
74
75 Create a branch selector with the following code.
76
77 =head3 in PERL SCRIPT
78
79     my $branches = GetBranches;
80     my @branchloop;
81     foreach my $thisbranch (sort keys %$branches) {
82         my $selected = 1 if $thisbranch eq $branch;
83         my %row =(value => $thisbranch,
84                     selected => $selected,
85                     branchname => $branches->{$thisbranch}->{branchname},
86                 );
87         push @branchloop, \%row;
88     }
89
90 =head3 in TEMPLATE
91
92     <select name="branch">
93         <option value="">Default</option>
94         <!-- TMPL_LOOP name="branchloop" -->
95         <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="branchname" --></option>
96         <!-- /TMPL_LOOP -->
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     # returns a reference to a hash of references to ALL branches...
106     my %branches;
107     my $dbh = C4::Context->dbh;
108     my $sth;
109     my $query="SELECT * FROM branches";
110     my @bind_parameters;
111     if ($onlymine && C4::Context->userenv && C4::Context->userenv->{branch}){
112       $query .= ' WHERE branchcode = ? ';
113       push @bind_parameters, C4::Context->userenv->{branch};
114     }
115         $query.=" ORDER BY branchname";
116     $sth = $dbh->prepare($query);
117     $sth->execute( @bind_parameters );
118
119     my $nsth = $dbh->prepare(
120         "SELECT categorycode FROM branchrelations WHERE branchcode = ?"
121     );  # prepare once, outside while loop
122
123     while ( my $branch = $sth->fetchrow_hashref ) {
124         $nsth->execute( $branch->{'branchcode'} );
125         while ( my ($cat) = $nsth->fetchrow_array ) {
126             # FIXME - This seems wrong. It ought to be
127             # $branch->{categorycodes}{$cat} = 1;
128             # otherwise, there's a namespace collision if there's a
129             # category with the same name as a field in the 'branches'
130             # table (i.e., don't create a category called "issuing").
131             # In addition, the current structure doesn't really allow
132             # you to list the categories that a branch belongs to:
133             # you'd have to list keys %$branch, and remove those keys
134             # that aren't fields in the "branches" table.
135          #   $branch->{$cat} = 1;
136             $branch->{category}{$cat} = 1;
137         }
138         $branches{ $branch->{'branchcode'} } = $branch;
139     }
140     return ( \%branches );
141 }
142
143 sub onlymine {
144     return 
145     C4::Context->preference('IndependantBranches') &&
146     C4::Context->userenv                           &&
147     C4::Context->userenv->{flags} %2 != 1          &&
148     C4::Context->userenv->{branch}                 ;
149 }
150
151 # always returns a string for OK comparison via "eq" or "ne"
152 sub mybranch {
153     C4::Context->userenv           or return '';
154     return C4::Context->userenv->{branch} || '';
155 }
156
157 sub GetBranchesLoop (;$$) {  # since this is what most pages want anyway
158     my $branch   = @_ ? shift : mybranch();     # optional first argument is branchcode of "my branch", if preselection is wanted.
159     my $onlymine = @_ ? shift : onlymine();
160     my $branches = GetBranches($onlymine);
161     my @loop;
162     foreach (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %$branches) {
163         push @loop, {
164             value => $_,
165             selected => ($_ eq $branch) ? 1 : 0, 
166             branchname => $branches->{$_}->{branchname},
167         };
168     }
169     return \@loop;
170 }
171
172 =head2 GetBranchName
173
174 =cut
175
176 sub GetBranchName {
177     my ($branchcode) = @_;
178     my $dbh = C4::Context->dbh;
179     my $sth;
180     $sth = $dbh->prepare("Select branchname from branches where branchcode=?");
181     $sth->execute($branchcode);
182     my $branchname = $sth->fetchrow_array;
183     $sth->finish;
184     return ($branchname);
185 }
186
187 =head2 ModBranch
188
189 $error = &ModBranch($newvalue);
190
191 This function modify an existing branch
192
193 C<$newvalue> is a ref to an array wich is containt all the column from branches table.
194
195 =cut
196
197 sub ModBranch {
198     my ($data) = @_;
199     
200     my $dbh    = C4::Context->dbh;
201     if ($data->{add}) {
202         my $query  = "
203             INSERT INTO branches
204             (branchcode,branchname,branchaddress1,
205             branchaddress2,branchaddress3,branchzip,branchcity,
206             branchcountry,branchphone,branchfax,branchemail,
207             branchurl,branchip,branchprinter,branchnotes)
208             VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
209         ";
210         my $sth    = $dbh->prepare($query);
211         $sth->execute(
212             $data->{'branchcode'},       $data->{'branchname'},
213             $data->{'branchaddress1'},   $data->{'branchaddress2'},
214             $data->{'branchaddress3'},   $data->{'branchzip'},
215             $data->{'branchcity'},       $data->{'branchcountry'},
216             $data->{'branchphone'},      $data->{'branchfax'},
217             $data->{'branchemail'},      $data->{'branchurl'},
218             $data->{'branchip'},         $data->{'branchprinter'},
219             $data->{'branchnotes'},
220         );
221         return 1 if $dbh->err;
222     } else {
223         my $query  = "
224             UPDATE branches
225             SET branchname=?,branchaddress1=?,
226                 branchaddress2=?,branchaddress3=?,branchzip=?,
227                 branchcity=?,branchcountry=?,branchphone=?,
228                 branchfax=?,branchemail=?,branchurl=?,branchip=?,
229                 branchprinter=?,branchnotes=?
230             WHERE branchcode=?
231         ";
232         my $sth    = $dbh->prepare($query);
233         $sth->execute(
234             $data->{'branchname'},
235             $data->{'branchaddress1'},   $data->{'branchaddress2'},
236             $data->{'branchaddress3'},   $data->{'branchzip'},
237             $data->{'branchcity'},       $data->{'branchcountry'},
238             $data->{'branchphone'},      $data->{'branchfax'},
239             $data->{'branchemail'},      $data->{'branchurl'},
240             $data->{'branchip'},         $data->{'branchprinter'},
241             $data->{'branchnotes'},
242             $data->{'branchcode'},
243         );
244     }
245     # sort out the categories....
246     my @checkedcats;
247     my $cats = GetBranchCategory();
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         $sth->finish;
278     }
279     foreach my $cat (@removecats) {
280         my $sth =
281           $dbh->prepare(
282             "delete from branchrelations where branchcode=? and categorycode=?"
283           );
284         $sth->execute( $branchcode, $cat );
285         $sth->finish;
286     }
287 }
288
289 =head2 GetBranchCategory
290
291 $results = GetBranchCategory($categorycode);
292
293 C<$results> is an ref to an array.
294
295 =cut
296
297 sub GetBranchCategory {
298
299     # returns a reference to an array of hashes containing branches,
300     my ($catcode) = @_;
301     my $dbh = C4::Context->dbh;
302     my $sth;
303
304     #    print DEBUG "GetBranchCategory: entry: catcode=".cvs($catcode)."\n";
305     if ($catcode) {
306         $sth =
307           $dbh->prepare(
308             "select * from branchcategories where categorycode = ?");
309         $sth->execute($catcode);
310     }
311     else {
312         $sth = $dbh->prepare("Select * from branchcategories");
313         $sth->execute();
314     }
315     my @results;
316     while ( my $data = $sth->fetchrow_hashref ) {
317         push( @results, $data );
318     }
319     $sth->finish;
320
321     #    print DEBUG "GetBranchCategory: exit: returning ".cvs(\@results)."\n";
322     return \@results;
323 }
324
325 =head2 GetBranchCategories
326
327   my $categories = GetBranchCategories($branchcode,$categorytype);
328
329 Returns a list ref of anon hashrefs with keys eq columns of branchcategories table,
330 i.e. categorycode, categorydescription, categorytype, categoryname.
331 if $branchcode and/or $categorytype are passed, limit set to categories that
332 $branchcode is a member of , and to $categorytype.
333
334 =cut
335
336 sub GetBranchCategories {
337     my ($branchcode,$categorytype) = @_;
338         my $dbh = C4::Context->dbh();
339         my $query = "SELECT c.* FROM branchcategories c";
340         my (@where, @bind);
341         if($branchcode) {
342                 $query .= ",branchrelations r, branches b ";
343                 push @where, "c.categorycode=r.categorycode and r.branchcode=? ";  
344                 push @bind , $branchcode;
345         }
346         if ($categorytype) {
347                 push @where, " c.categorytype=? ";
348                 push @bind, $categorytype;
349         }
350         $query .= " where " . join(" and ", @where) if(@where);
351         $query .= " order by categorytype,c.categorycode";
352         my $sth=$dbh->prepare( $query);
353         $sth->execute(@bind);
354         
355         my $branchcats = $sth->fetchall_arrayref({});
356         $sth->finish();
357         return( $branchcats );
358 }
359
360 =head2 GetCategoryTypes
361
362 $categorytypes = GetCategoryTypes;
363 returns a list of category types.
364 Currently these types are HARDCODED.
365 type: 'searchdomain' defines a group of agencies that the calling library may search in.
366 Other usage of agency categories falls under type: 'properties'.
367         to allow for other uses of categories.
368 The searchdomain bit may be better implemented as a separate module, but
369 the categories were already here, and minimally used.
370 =cut
371
372         #TODO  manage category types.  rename possibly to 'agency domains' ? as borrowergroups are called categories.
373 sub GetCategoryTypes() {
374         return ( 'searchdomain','properties');
375 }
376
377 =head2 GetBranch
378
379 $branch = GetBranch( $query, $branches );
380
381 =cut
382
383 sub GetBranch ($$) {
384     my ( $query, $branches ) = @_;    # get branch for this query from branches
385     my $branch = $query->param('branch');
386     my %cookie = $query->cookie('userenv');
387     ($branch)                || ($branch = $cookie{'branchname'});
388     ( $branches->{$branch} ) || ( $branch = ( keys %$branches )[0] );
389     return $branch;
390 }
391
392 =head2 GetBranchDetail
393
394     $branch = &GetBranchDetail($branchcode);
395
396 Given the branch code, the function returns a
397 hashref for the corresponding row in the branches table.
398
399 =cut
400
401 sub GetBranchDetail {
402     my ($branchcode) = shift or return;
403     my $sth = C4::Context->dbh->prepare("SELECT * FROM branches WHERE branchcode = ?");
404     $sth->execute($branchcode);
405     return $sth->fetchrow_hashref();
406 }
407
408 =head2 get_branchinfos_of
409
410   my $branchinfos_of = get_branchinfos_of(@branchcodes);
411
412 Associates a list of branchcodes to the information of the branch, taken in
413 branches table.
414
415 Returns a href where keys are branchcodes and values are href where keys are
416 branch information key.
417
418   print 'branchname is ', $branchinfos_of->{$code}->{branchname};
419
420 =cut
421
422 sub get_branchinfos_of {
423     my @branchcodes = @_;
424
425     my $query = '
426     SELECT branchcode,
427        branchname
428     FROM branches
429     WHERE branchcode IN ('
430       . join( ',', map( { "'" . $_ . "'" } @branchcodes ) ) . ')
431 ';
432     return C4::Koha::get_infos_of( $query, 'branchcode' );
433 }
434
435
436 =head2 GetBranchesInCategory
437
438   my $branches = GetBranchesInCategory($categorycode);
439
440 Returns a href:  keys %$branches eq (branchcode,branchname) .
441
442 =cut
443
444 sub GetBranchesInCategory($) {
445     my ($categorycode) = @_;
446         my @branches;
447         my $dbh = C4::Context->dbh();
448         my $sth=$dbh->prepare( "SELECT b.branchcode FROM branchrelations r, branches b 
449                                                         where r.branchcode=b.branchcode and r.categorycode=?");
450     $sth->execute($categorycode);
451         while (my $branch = $sth->fetchrow) {
452                 push @branches, $branch;
453         }
454         $sth->finish();
455         return( \@branches );
456 }
457
458 =head2 GetBranchInfo
459
460 $results = GetBranchInfo($branchcode);
461
462 returns C<$results>, a reference to an array of hashes containing branches.
463 if $branchcode, just this branch, with associated categories.
464 if ! $branchcode && $categorytype, all branches in the category.
465 =cut
466
467 sub GetBranchInfo {
468     my ($branchcode,$categorytype) = @_;
469     my $dbh = C4::Context->dbh;
470     my $sth;
471
472
473         if ($branchcode) {
474         $sth =
475           $dbh->prepare(
476             "Select * from branches where branchcode = ? order by branchcode");
477         $sth->execute($branchcode);
478     }
479     else {
480         $sth = $dbh->prepare("Select * from branches order by branchcode");
481         $sth->execute();
482     }
483     my @results;
484     while ( my $data = $sth->fetchrow_hashref ) {
485                 my @bind = ($data->{'branchcode'});
486         my $query= "select r.categorycode from branchrelations r";
487                 $query .= ", branchcategories c " if($categorytype);
488                 $query .= " where  branchcode=? ";
489                 if($categorytype) { 
490                         $query .= " and c.categorytype=? and r.categorycode=c.categorycode";
491                         push @bind, $categorytype;
492                 }
493         my $nsth=$dbh->prepare($query);
494                 $nsth->execute( @bind );
495         my @cats = ();
496         while ( my ($cat) = $nsth->fetchrow_array ) {
497             push( @cats, $cat );
498         }
499         $nsth->finish;
500         $data->{'categories'} = \@cats;
501         push( @results, $data );
502     }
503     $sth->finish;
504     return \@results;
505 }
506
507 =head2 DelBranch
508
509 &DelBranch($branchcode);
510
511 =cut
512
513 sub DelBranch {
514     my ($branchcode) = @_;
515     my $dbh = C4::Context->dbh;
516     my $sth = $dbh->prepare("delete from branches where branchcode = ?");
517     $sth->execute($branchcode);
518     $sth->finish;
519 }
520
521 =head2 ModBranchCategoryInfo
522
523 &ModBranchCategoryInfo($data);
524 sets the data from the editbranch form, and writes to the database...
525
526 =cut
527
528 sub ModBranchCategoryInfo {
529     my ($data) = @_;
530     my $dbh    = C4::Context->dbh;
531     if ($data->{'add'}){
532         # we are doing an insert
533         my $sth   = $dbh->prepare("INSERT INTO branchcategories (categorycode,categoryname,codedescription,categorytype) VALUES (?,?,?,?)");
534         $sth->execute(uc( $data->{'categorycode'} ),$data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'} );
535         $sth->finish();         
536     }
537     else {
538         # modifying
539         my $sth = $dbh->prepare("UPDATE branchcategories SET categoryname=?,codedescription=?,categorytype=? WHERE categorycode=?");
540         $sth->execute($data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'},uc( $data->{'categorycode'} ) );
541         $sth->finish();
542     }
543 }
544
545 =head2 CheckCategoryUnique
546
547 if (CheckCategoryUnique($categorycode)){
548   # do something
549 }
550
551 =cut
552
553 sub CheckCategoryUnique {
554     my $categorycode = shift;
555     my $dbh    = C4::Context->dbh;
556     my $sth = $dbh->prepare("SELECT categorycode FROM branchcategories WHERE categorycode = ?");
557     $sth->execute(uc( $categorycode) );
558     if (my $data = $sth->fetchrow_hashref){
559         return 0;
560     }
561     else {
562         return 1;
563     }
564 }
565
566     
567 =head2 DeleteBranchCategory
568
569 DeleteBranchCategory($categorycode);
570
571 =cut
572
573 sub DelBranchCategory {
574     my ($categorycode) = @_;
575     my $dbh = C4::Context->dbh;
576     my $sth = $dbh->prepare("delete from branchcategories where categorycode = ?");
577     $sth->execute($categorycode);
578     $sth->finish;
579 }
580
581 =head2 CheckBranchCategorycode
582
583 $number_rows_affected = CheckBranchCategorycode($categorycode);
584
585 =cut
586
587 sub CheckBranchCategorycode {
588
589     # check to see if the branchcode is being used in the database somewhere....
590     my ($categorycode) = @_;
591     my $dbh            = C4::Context->dbh;
592     my $sth            =
593       $dbh->prepare(
594         "select count(*) from branchrelations where categorycode=?");
595     $sth->execute($categorycode);
596     my ($total) = $sth->fetchrow_array;
597     return $total;
598 }
599
600 sub get_branch_code_from_name {
601    my @branch_name = @_;
602    my $query = "SELECT branchcode FROM branches WHERE branchname=?;";
603    my $dbh = C4::Context->dbh();
604    my $sth = $dbh->prepare($query);
605    $sth->execute(@branch_name);
606    return $sth->fetchrow_array;
607 }
608
609 1;
610 __END__
611
612 =head1 AUTHOR
613
614 Koha Development Team <info@koha.org>
615
616 =cut