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