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