Bug 11559: Supporting changes for Rancor
[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
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
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.
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" id="branch">
93         <option value=""></option>
94             [% FOREACH branchloo IN branchloop %]
95                 [% IF ( branchloo.selected ) %]
96                     <option value="[% branchloo.value %]" selected="selected">[% branchloo.branchname %]</option>
97                 [% ELSE %]
98                     <option value="[% branchloo.value %]" >[% branchloo.branchname %]</option>
99                 [% END %]
100             [% END %]
101     </select>
102
103 =head4 Note that you often will want to just use GetBranchesLoop, for exactly the example above.
104
105 =cut
106
107 sub GetBranches {
108     my ($onlymine) = @_;
109
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 $relations_sth =
125       $dbh->prepare("SELECT branchcode,categorycode FROM branchrelations");
126     $relations_sth->execute();
127     my %relations;
128     while ( my $rel = $relations_sth->fetchrow_hashref ) {
129         push @{ $relations{ $rel->{branchcode} } }, $rel->{categorycode};
130     }
131
132     while ( my $branch = $sth->fetchrow_hashref ) {
133         foreach my $cat ( @{ $relations{ $branch->{branchcode} } } ) {
134             $branch->{category}{$cat} = 1;
135         }
136         $branches{ $branch->{'branchcode'} } = $branch;
137     }
138     return ( \%branches );
139 }
140
141 sub onlymine {
142     return
143          C4::Context->preference('IndependentBranches')
144       && C4::Context->userenv
145       && !C4::Context->IsSuperLibrarian()
146       && C4::Context->userenv->{branch};
147 }
148
149 # always returns a string for OK comparison via "eq" or "ne"
150 sub mybranch {
151     C4::Context->userenv           or return '';
152     return C4::Context->userenv->{branch} || '';
153 }
154
155 sub GetBranchesLoop {  # since this is what most pages want anyway
156     my $branch   = @_ ? shift : mybranch();     # optional first argument is branchcode of "my branch", if preselection is wanted.
157     my $onlymine = @_ ? shift : onlymine();
158     my $branches = GetBranches($onlymine);
159     my @loop;
160     foreach my $branchcode ( sort { uc($branches->{$a}->{branchname}) cmp uc($branches->{$b}->{branchname}) } keys %$branches ) {
161         push @loop, {
162             value      => $branchcode,
163             branchcode => $branchcode,
164             selected   => ($branchcode eq $branch) ? 1 : 0,
165             branchname => $branches->{$branchcode}->{branchname},
166         };
167     }
168     return \@loop;
169 }
170
171 =head2 GetBranchName
172
173 =cut
174
175 sub GetBranchName {
176     my ($branchcode) = @_;
177     my $dbh = C4::Context->dbh;
178     my $sth;
179     $sth = $dbh->prepare("Select branchname from branches where branchcode=?");
180     $sth->execute($branchcode);
181     my $branchname = $sth->fetchrow_array;
182     return ($branchname);
183 }
184
185 =head2 ModBranch
186
187 $error = &ModBranch($newvalue);
188
189 This function modifies an existing branch
190
191 C<$newvalue> is a ref to an array which contains all the columns 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,branchstate,
204             branchcountry,branchphone,branchfax,branchemail,
205             branchurl,branchip,branchprinter,branchnotes,opac_info,
206             branchreplyto, branchreturnpath)
207             VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
208         ";
209         my $sth    = $dbh->prepare($query);
210         $sth->execute(
211             $data->{'branchcode'},       $data->{'branchname'},
212             $data->{'branchaddress1'},   $data->{'branchaddress2'},
213             $data->{'branchaddress3'},   $data->{'branchzip'},
214             $data->{'branchcity'},       $data->{'branchstate'},
215             $data->{'branchcountry'},
216             $data->{'branchphone'},      $data->{'branchfax'},
217             $data->{'branchemail'},      $data->{'branchurl'},
218             $data->{'branchip'},         $data->{'branchprinter'},
219             $data->{'branchnotes'},      $data->{opac_info},
220             $data->{'branchreplyto'},    $data->{'branchreturnpath'}
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=?,opac_info=?,
231                 branchreplyto=?, branchreturnpath=?
232             WHERE branchcode=?
233         ";
234         my $sth    = $dbh->prepare($query);
235         $sth->execute(
236             $data->{'branchname'},
237             $data->{'branchaddress1'},   $data->{'branchaddress2'},
238             $data->{'branchaddress3'},   $data->{'branchzip'},
239             $data->{'branchcity'},       $data->{'branchstate'},       
240             $data->{'branchcountry'},
241             $data->{'branchphone'},      $data->{'branchfax'},
242             $data->{'branchemail'},      $data->{'branchurl'},
243             $data->{'branchip'},         $data->{'branchprinter'},
244             $data->{'branchnotes'},      $data->{opac_info},
245             $data->{'branchreplyto'},    $data->{'branchreturnpath'},
246             $data->{'branchcode'},
247         );
248     }
249     # sort out the categories....
250     my @checkedcats;
251     my $cats = GetBranchCategories();
252     foreach my $cat (@$cats) {
253         my $code = $cat->{'categorycode'};
254         if ( $data->{$code} ) {
255             push( @checkedcats, $code );
256         }
257     }
258     my $branchcode = uc( $data->{'branchcode'} );
259     my $branch     = GetBranchInfo($branchcode);
260     $branch = $branch->[0];
261     my $branchcats = $branch->{'categories'};
262     my @addcats;
263     my @removecats;
264     foreach my $bcat (@$branchcats) {
265
266         unless ( grep { /^$bcat$/ } @checkedcats ) {
267             push( @removecats, $bcat );
268         }
269     }
270     foreach my $ccat (@checkedcats) {
271         unless ( grep { /^$ccat$/ } @$branchcats ) {
272             push( @addcats, $ccat );
273         }
274     }
275     foreach my $cat (@addcats) {
276         my $sth =
277           $dbh->prepare(
278 "insert into branchrelations (branchcode, categorycode) values(?, ?)"
279           );
280         $sth->execute( $branchcode, $cat );
281     }
282     foreach my $cat (@removecats) {
283         my $sth =
284           $dbh->prepare(
285             "delete from branchrelations where branchcode=? and categorycode=?"
286           );
287         $sth->execute( $branchcode, $cat );
288     }
289 }
290
291 =head2 GetBranchCategory
292
293 $results = GetBranchCategory($categorycode);
294
295 C<$results> is an hashref
296
297 =cut
298
299 sub GetBranchCategory {
300     my ($catcode) = @_;
301     return unless $catcode;
302
303     my $dbh = C4::Context->dbh;
304     my $sth;
305
306     $sth = $dbh->prepare(q{
307         SELECT *
308         FROM branchcategories
309         WHERE categorycode = ?
310     });
311     $sth->execute( $catcode );
312     return $sth->fetchrow_hashref;
313 }
314
315 =head2 GetBranchCategories
316
317   my $categories = GetBranchCategories($categorytype,$show_in_pulldown,$selected_in_pulldown);
318
319 Returns a list ref of anon hashrefs with keys eq columns of branchcategories table,
320 i.e. categorydescription, categorytype, categoryname.
321
322 =cut
323
324 sub GetBranchCategories {
325     my ( $categorytype, $show_in_pulldown, $selected_in_pulldown ) = @_;
326     my $dbh = C4::Context->dbh();
327
328     my $query = "SELECT * FROM branchcategories ";
329
330     my ( @where, @bind );
331     if ( $categorytype ) {
332         push @where, " categorytype = ? ";
333         push @bind, $categorytype;
334     }
335
336     if ( defined( $show_in_pulldown ) ) {
337         push( @where, " show_in_pulldown = ? " );
338         push( @bind, $show_in_pulldown );
339     }
340
341     $query .= " WHERE " . join(" AND ", @where) if(@where);
342     $query .= " ORDER BY categorytype, categorycode";
343     my $sth=$dbh->prepare( $query);
344     $sth->execute(@bind);
345
346     my $branchcats = $sth->fetchall_arrayref({});
347
348     if ( $selected_in_pulldown ) {
349         foreach my $bc ( @$branchcats ) {
350             $bc->{selected} = 1 if $bc->{categorycode} eq $selected_in_pulldown;
351         }
352     }
353
354     return $branchcats;
355 }
356
357 =head2 GetCategoryTypes
358
359 $categorytypes = GetCategoryTypes;
360 returns a list of category types.
361 Currently these types are HARDCODED.
362 type: 'searchdomain' defines a group of agencies that the calling library may search in.
363 Other usage of agency categories falls under type: 'properties'.
364         to allow for other uses of categories.
365 The searchdomain bit may be better implemented as a separate module, but
366 the categories were already here, and minimally used.
367
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 GetBranchesInCategory
407
408   my $branches = GetBranchesInCategory($categorycode);
409
410 Returns a href:  keys %$branches eq (branchcode,branchname) .
411
412 =cut
413
414 sub GetBranchesInCategory {
415     my ($categorycode) = @_;
416         my @branches;
417         my $dbh = C4::Context->dbh();
418         my $sth=$dbh->prepare( "SELECT b.branchcode FROM branchrelations r, branches b 
419                                                         where r.branchcode=b.branchcode and r.categorycode=?");
420     $sth->execute($categorycode);
421         while (my $branch = $sth->fetchrow) {
422                 push @branches, $branch;
423         }
424         return( \@branches );
425 }
426
427 =head2 GetBranchInfo
428
429 $results = GetBranchInfo($branchcode);
430
431 returns C<$results>, a reference to an array of hashes containing branches.
432 if $branchcode, just this branch, with associated categories.
433 if ! $branchcode && $categorytype, all branches in the category.
434
435 =cut
436
437 sub GetBranchInfo {
438     my ($branchcode,$categorytype) = @_;
439     my $dbh = C4::Context->dbh;
440     my $sth;
441
442
443         if ($branchcode) {
444         $sth =
445           $dbh->prepare(
446             "Select * from branches where branchcode = ? order by branchcode");
447         $sth->execute($branchcode);
448     }
449     else {
450         $sth = $dbh->prepare("Select * from branches order by branchcode");
451         $sth->execute();
452     }
453     my @results;
454     while ( my $data = $sth->fetchrow_hashref ) {
455                 my @bind = ($data->{'branchcode'});
456         my $query= "select r.categorycode from branchrelations r";
457                 $query .= ", branchcategories c " if($categorytype);
458                 $query .= " where  branchcode=? ";
459                 if($categorytype) { 
460                         $query .= " and c.categorytype=? and r.categorycode=c.categorycode";
461                         push @bind, $categorytype;
462                 }
463         my $nsth=$dbh->prepare($query);
464                 $nsth->execute( @bind );
465         my @cats = ();
466         while ( my ($cat) = $nsth->fetchrow_array ) {
467             push( @cats, $cat );
468         }
469         $data->{'categories'} = \@cats;
470         push( @results, $data );
471     }
472     return \@results;
473 }
474
475 =head2 DelBranch
476
477 &DelBranch($branchcode);
478
479 =cut
480
481 sub DelBranch {
482     my ($branchcode) = @_;
483     my $dbh = C4::Context->dbh;
484     my $sth = $dbh->prepare("delete from branches where branchcode = ?");
485     $sth->execute($branchcode);
486 }
487
488 =head2 ModBranchCategoryInfo
489
490 &ModBranchCategoryInfo($data);
491 sets the data from the editbranch form, and writes to the database...
492
493 =cut
494
495 sub ModBranchCategoryInfo {
496     my ($data) = @_;
497     my $dbh    = C4::Context->dbh;
498     if ($data->{'add'}){
499         # we are doing an insert
500   my $sth   = $dbh->prepare("INSERT INTO branchcategories (categorycode,categoryname,codedescription,categorytype,show_in_pulldown) VALUES (?,?,?,?,?)");
501         $sth->execute(uc( $data->{'categorycode'} ),$data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'},$data->{'show_in_pulldown'} );
502     }
503     else {
504         # modifying
505         my $sth = $dbh->prepare("UPDATE branchcategories SET categoryname=?,codedescription=?,categorytype=?,show_in_pulldown=? WHERE categorycode=?");
506         $sth->execute($data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'},$data->{'show_in_pulldown'},uc( $data->{'categorycode'} ) );
507     }
508 }
509
510 =head2 CheckCategoryUnique
511
512 if (CheckCategoryUnique($categorycode)){
513   # do something
514 }
515
516 =cut
517
518 sub CheckCategoryUnique {
519     my $categorycode = shift;
520     my $dbh    = C4::Context->dbh;
521     my $sth = $dbh->prepare("SELECT categorycode FROM branchcategories WHERE categorycode = ?");
522     $sth->execute(uc( $categorycode) );
523     if (my $data = $sth->fetchrow_hashref){
524         return 0;
525     }
526     else {
527         return 1;
528     }
529 }
530
531     
532 =head2 DeleteBranchCategory
533
534 DeleteBranchCategory($categorycode);
535
536 =cut
537
538 sub DelBranchCategory {
539     my ($categorycode) = @_;
540     my $dbh = C4::Context->dbh;
541     my $sth = $dbh->prepare("delete from branchcategories where categorycode = ?");
542     $sth->execute($categorycode);
543 }
544
545 =head2 CheckBranchCategorycode
546
547 $number_rows_affected = CheckBranchCategorycode($categorycode);
548
549 =cut
550
551 sub CheckBranchCategorycode {
552
553     # check to see if the branchcode is being used in the database somewhere....
554     my ($categorycode) = @_;
555     my $dbh            = C4::Context->dbh;
556     my $sth            =
557       $dbh->prepare(
558         "select count(*) from branchrelations where categorycode=?");
559     $sth->execute($categorycode);
560     my ($total) = $sth->fetchrow_array;
561     return $total;
562 }
563
564 sub GetBranchesCount {
565     my $dbh = C4::Context->dbh();
566     my $query = "SELECT COUNT(*) AS branches_count FROM branches";
567     my $sth = $dbh->prepare( $query );
568     $sth->execute();
569     my $row = $sth->fetchrow_hashref();
570     return $row->{'branches_count'};
571 }
572
573 1;
574 __END__
575
576 =head1 AUTHOR
577
578 Koha Development Team <http://koha-community.org/>
579
580 =cut