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