Bug 6679 - [SIGNED-OFF] fix 4 perlcritic violations in C4/Branch.pm
[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 ( sort { uc($branches->{$a}->{branchname}) cmp uc($branches->{$b}->{branchname}) } keys %$branches ) {
164         push @loop, {
165             value => $_,
166             selected => ($_ eq $branch) ? 1 : 0, 
167             branchname => $branches->{$_}->{branchname},
168         };
169     }
170     return \@loop;
171 }
172
173 =head2 GetBranchName
174
175 =cut
176
177 sub GetBranchName {
178     my ($branchcode) = @_;
179     my $dbh = C4::Context->dbh;
180     my $sth;
181     $sth = $dbh->prepare("Select branchname from branches where branchcode=?");
182     $sth->execute($branchcode);
183     my $branchname = $sth->fetchrow_array;
184     $sth->finish;
185     return ($branchname);
186 }
187
188 =head2 ModBranch
189
190 $error = &ModBranch($newvalue);
191
192 This function modify an existing branch
193
194 C<$newvalue> is a ref to an array wich is containt all the column from branches table.
195
196 =cut
197
198 sub ModBranch {
199     my ($data) = @_;
200     
201     my $dbh    = C4::Context->dbh;
202     if ($data->{add}) {
203         my $query  = "
204             INSERT INTO branches
205             (branchcode,branchname,branchaddress1,
206             branchaddress2,branchaddress3,branchzip,branchcity,branchstate,
207             branchcountry,branchphone,branchfax,branchemail,
208             branchurl,branchip,branchprinter,branchnotes,opac_info)
209             VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
210         ";
211         my $sth    = $dbh->prepare($query);
212         $sth->execute(
213             $data->{'branchcode'},       $data->{'branchname'},
214             $data->{'branchaddress1'},   $data->{'branchaddress2'},
215             $data->{'branchaddress3'},   $data->{'branchzip'},
216             $data->{'branchcity'},       $data->{'branchstate'},
217             $data->{'branchcountry'},
218             $data->{'branchphone'},      $data->{'branchfax'},
219             $data->{'branchemail'},      $data->{'branchurl'},
220             $data->{'branchip'},         $data->{'branchprinter'},
221             $data->{'branchnotes'},      $data->{opac_info},
222         );
223         return 1 if $dbh->err;
224     } else {
225         my $query  = "
226             UPDATE branches
227             SET branchname=?,branchaddress1=?,
228                 branchaddress2=?,branchaddress3=?,branchzip=?,
229                 branchcity=?,branchstate=?,branchcountry=?,branchphone=?,
230                 branchfax=?,branchemail=?,branchurl=?,branchip=?,
231                 branchprinter=?,branchnotes=?,opac_info=?
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->{'branchcode'},
246         );
247     }
248     # sort out the categories....
249     my @checkedcats;
250     my $cats = GetBranchCategory();
251     foreach my $cat (@$cats) {
252         my $code = $cat->{'categorycode'};
253         if ( $data->{$code} ) {
254             push( @checkedcats, $code );
255         }
256     }
257     my $branchcode = uc( $data->{'branchcode'} );
258     my $branch     = GetBranchInfo($branchcode);
259     $branch = $branch->[0];
260     my $branchcats = $branch->{'categories'};
261     my @addcats;
262     my @removecats;
263     foreach my $bcat (@$branchcats) {
264
265         unless ( grep { /^$bcat$/ } @checkedcats ) {
266             push( @removecats, $bcat );
267         }
268     }
269     foreach my $ccat (@checkedcats) {
270         unless ( grep { /^$ccat$/ } @$branchcats ) {
271             push( @addcats, $ccat );
272         }
273     }
274     foreach my $cat (@addcats) {
275         my $sth =
276           $dbh->prepare(
277 "insert into branchrelations (branchcode, categorycode) values(?, ?)"
278           );
279         $sth->execute( $branchcode, $cat );
280         $sth->finish;
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         $sth->finish;
289     }
290 }
291
292 =head2 GetBranchCategory
293
294 $results = GetBranchCategory($categorycode);
295
296 C<$results> is an ref to an array.
297
298 =cut
299
300 sub GetBranchCategory {
301
302     # returns a reference to an array of hashes containing branches,
303     my ($catcode) = @_;
304     my $dbh = C4::Context->dbh;
305     my $sth;
306
307     #    print DEBUG "GetBranchCategory: entry: catcode=".cvs($catcode)."\n";
308     if ($catcode) {
309         $sth =
310           $dbh->prepare(
311             "select * from branchcategories where categorycode = ?");
312         $sth->execute($catcode);
313     }
314     else {
315         $sth = $dbh->prepare("Select * from branchcategories");
316         $sth->execute();
317     }
318     my @results;
319     while ( my $data = $sth->fetchrow_hashref ) {
320         push( @results, $data );
321     }
322     $sth->finish;
323
324     #    print DEBUG "GetBranchCategory: exit: returning ".cvs(\@results)."\n";
325     return \@results;
326 }
327
328 =head2 GetBranchCategories
329
330   my $categories = GetBranchCategories($branchcode,$categorytype);
331
332 Returns a list ref of anon hashrefs with keys eq columns of branchcategories table,
333 i.e. categorycode, categorydescription, categorytype, categoryname.
334 if $branchcode and/or $categorytype are passed, limit set to categories that
335 $branchcode is a member of , and to $categorytype.
336
337 =cut
338
339 sub GetBranchCategories {
340     my ($branchcode,$categorytype) = @_;
341         my $dbh = C4::Context->dbh();
342         my $query = "SELECT c.* FROM branchcategories c";
343         my (@where, @bind);
344         if($branchcode) {
345                 $query .= ",branchrelations r, branches b ";
346                 push @where, "c.categorycode=r.categorycode and r.branchcode=? ";  
347                 push @bind , $branchcode;
348         }
349         if ($categorytype) {
350                 push @where, " c.categorytype=? ";
351                 push @bind, $categorytype;
352         }
353         $query .= " where " . join(" and ", @where) if(@where);
354         $query .= " order by categorytype,c.categorycode";
355         my $sth=$dbh->prepare( $query);
356         $sth->execute(@bind);
357         
358         my $branchcats = $sth->fetchall_arrayref({});
359         $sth->finish();
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) VALUES (?,?,?,?)");
509         $sth->execute(uc( $data->{'categorycode'} ),$data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'} );
510         $sth->finish();         
511     }
512     else {
513         # modifying
514         my $sth = $dbh->prepare("UPDATE branchcategories SET categoryname=?,codedescription=?,categorytype=? WHERE categorycode=?");
515         $sth->execute($data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'},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 get_branch_code_from_name {
576    my @branch_name = @_;
577    my $query = "SELECT branchcode FROM branches WHERE branchname=?;";
578    my $dbh = C4::Context->dbh();
579    my $sth = $dbh->prepare($query);
580    $sth->execute(@branch_name);
581    return $sth->fetchrow_array;
582 }
583
584 sub GetBranchesCount {
585     my $dbh = C4::Context->dbh();
586     my $query = "SELECT COUNT(*) AS branches_count FROM branches";
587     my $sth = $dbh->prepare( $query );
588     $sth->execute();
589     my $row = $sth->fetchrow_hashref();
590     return $row->{'branches_count'};
591 }
592
593 1;
594 __END__
595
596 =head1 AUTHOR
597
598 Koha Development Team <http://koha-community.org/>
599
600 =cut