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