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