Bug 15295: Koha::Libraries - Remove DelBranch and DelBranchCategory
[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                 &CheckCategoryUnique
46                 &mybranch
47                 &GetBranchesCount
48         );
49     @EXPORT_OK = qw( &onlymine &mybranch );
50 }
51
52 =head1 NAME
53
54 C4::Branch - Koha branch module
55
56 =head1 SYNOPSIS
57
58 use C4::Branch;
59
60 =head1 DESCRIPTION
61
62 The functions in this module deal with branches.
63
64 =head1 FUNCTIONS
65
66 =head2 GetBranches
67
68   $branches = &GetBranches();
69
70 Returns informations about ALL branches, IndependentBranches Insensitive.
71 GetBranchInfo() returns the same information.
72
73 Create a branch selector with the following code.
74
75 =head3 in PERL SCRIPT
76
77     my $branches = GetBranches;
78     my @branchloop;
79     foreach my $thisbranch (sort keys %$branches) {
80         my $selected = 1 if $thisbranch eq $branch;
81         my %row =(value => $thisbranch,
82                     selected => $selected,
83                     branchname => $branches->{$thisbranch}->{branchname},
84                 );
85         push @branchloop, \%row;
86     }
87
88 =head3 in TEMPLATE
89
90     <select name="branch" id="branch">
91         <option value=""></option>
92             [% FOREACH branchloo IN branchloop %]
93                 [% IF ( branchloo.selected ) %]
94                     <option value="[% branchloo.value %]" selected="selected">[% branchloo.branchname %]</option>
95                 [% ELSE %]
96                     <option value="[% branchloo.value %]" >[% branchloo.branchname %]</option>
97                 [% END %]
98             [% END %]
99     </select>
100
101 =head4 Note that you often will want to just use GetBranchesLoop, for exactly the example above.
102
103 =cut
104
105 sub GetBranches {
106     my ($onlymine) = @_;
107
108     # returns a reference to a hash of references to ALL branches...
109     my %branches;
110     my $dbh = C4::Context->dbh;
111     my $sth;
112     my $query = "SELECT * FROM branches";
113     my @bind_parameters;
114     if ( $onlymine && C4::Context->userenv && C4::Context->userenv->{branch} ) {
115         $query .= ' WHERE branchcode = ? ';
116         push @bind_parameters, C4::Context->userenv->{branch};
117     }
118     $query .= " ORDER BY branchname";
119     $sth = $dbh->prepare($query);
120     $sth->execute(@bind_parameters);
121
122     my $relations_sth =
123       $dbh->prepare("SELECT branchcode,categorycode FROM branchrelations");
124     $relations_sth->execute();
125     my %relations;
126     while ( my $rel = $relations_sth->fetchrow_hashref ) {
127         push @{ $relations{ $rel->{branchcode} } }, $rel->{categorycode};
128     }
129
130     while ( my $branch = $sth->fetchrow_hashref ) {
131         foreach my $cat ( @{ $relations{ $branch->{branchcode} } } ) {
132             $branch->{category}{$cat} = 1;
133         }
134         $branches{ $branch->{'branchcode'} } = $branch;
135     }
136     return ( \%branches );
137 }
138
139 sub onlymine {
140     return
141          C4::Context->preference('IndependentBranches')
142       && C4::Context->userenv
143       && !C4::Context->IsSuperLibrarian()
144       && C4::Context->userenv->{branch};
145 }
146
147 # always returns a string for OK comparison via "eq" or "ne"
148 sub mybranch {
149     C4::Context->userenv           or return '';
150     return C4::Context->userenv->{branch} || '';
151 }
152
153 sub GetBranchesLoop {  # since this is what most pages want anyway
154     my $branch   = @_ ? shift : mybranch();     # optional first argument is branchcode of "my branch", if preselection is wanted.
155     my $onlymine = @_ ? shift : onlymine();
156     my $branches = GetBranches($onlymine);
157     my @loop;
158     foreach my $branchcode ( sort { uc($branches->{$a}->{branchname}) cmp uc($branches->{$b}->{branchname}) } keys %$branches ) {
159         push @loop, {
160             value      => $branchcode,
161             branchcode => $branchcode,
162             selected   => ($branchcode eq $branch) ? 1 : 0,
163             branchname => $branches->{$branchcode}->{branchname},
164         };
165     }
166     return \@loop;
167 }
168
169 =head2 GetBranchName
170
171 =cut
172
173 sub GetBranchName {
174     my ($branchcode) = @_;
175     my $dbh = C4::Context->dbh;
176     my $sth;
177     $sth = $dbh->prepare("Select branchname from branches where branchcode=?");
178     $sth->execute($branchcode);
179     my $branchname = $sth->fetchrow_array;
180     return ($branchname);
181 }
182
183 =head2 ModBranch
184
185 $error = &ModBranch($newvalue);
186
187 This function modifies an existing branch
188
189 C<$newvalue> is a ref to an array which contains all the columns from branches table.
190
191 =cut
192
193 sub ModBranch {
194     my ($data) = @_;
195     
196     my $dbh    = C4::Context->dbh;
197     if ($data->{add}) {
198         my $query  = "
199             INSERT INTO branches
200             (branchcode,branchname,branchaddress1,
201             branchaddress2,branchaddress3,branchzip,branchcity,branchstate,
202             branchcountry,branchphone,branchfax,branchemail,
203             branchurl,branchip,branchprinter,branchnotes,opac_info,
204             branchreplyto, branchreturnpath)
205             VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
206         ";
207         my $sth    = $dbh->prepare($query);
208         $sth->execute(
209             $data->{'branchcode'},       $data->{'branchname'},
210             $data->{'branchaddress1'},   $data->{'branchaddress2'},
211             $data->{'branchaddress3'},   $data->{'branchzip'},
212             $data->{'branchcity'},       $data->{'branchstate'},
213             $data->{'branchcountry'},
214             $data->{'branchphone'},      $data->{'branchfax'},
215             $data->{'branchemail'},      $data->{'branchurl'},
216             $data->{'branchip'},         $data->{'branchprinter'},
217             $data->{'branchnotes'},      $data->{opac_info},
218             $data->{'branchreplyto'},    $data->{'branchreturnpath'}
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=?,branchstate=?,branchcountry=?,branchphone=?,
227                 branchfax=?,branchemail=?,branchurl=?,branchip=?,
228                 branchprinter=?,branchnotes=?,opac_info=?,
229                 branchreplyto=?, branchreturnpath=?
230             WHERE branchcode=?
231         ";
232         my $sth    = $dbh->prepare($query);
233         $sth->execute(
234             $data->{'branchname'},
235             $data->{'branchaddress1'},   $data->{'branchaddress2'},
236             $data->{'branchaddress3'},   $data->{'branchzip'},
237             $data->{'branchcity'},       $data->{'branchstate'},       
238             $data->{'branchcountry'},
239             $data->{'branchphone'},      $data->{'branchfax'},
240             $data->{'branchemail'},      $data->{'branchurl'},
241             $data->{'branchip'},         $data->{'branchprinter'},
242             $data->{'branchnotes'},      $data->{opac_info},
243             $data->{'branchreplyto'},    $data->{'branchreturnpath'},
244             $data->{'branchcode'},
245         );
246     }
247     # sort out the categories....
248     my @checkedcats;
249     my $cats = GetBranchCategories();
250     foreach my $cat (@$cats) {
251         my $code = $cat->{'categorycode'};
252         if ( $data->{$code} ) {
253             push( @checkedcats, $code );
254         }
255     }
256     my $branchcode = uc( $data->{'branchcode'} );
257     my $branch     = GetBranchInfo($branchcode);
258     $branch = $branch->[0];
259     my $branchcats = $branch->{'categories'};
260     my @addcats;
261     my @removecats;
262     foreach my $bcat (@$branchcats) {
263
264         unless ( grep { /^$bcat$/ } @checkedcats ) {
265             push( @removecats, $bcat );
266         }
267     }
268     foreach my $ccat (@checkedcats) {
269         unless ( grep { /^$ccat$/ } @$branchcats ) {
270             push( @addcats, $ccat );
271         }
272     }
273     foreach my $cat (@addcats) {
274         my $sth =
275           $dbh->prepare(
276 "insert into branchrelations (branchcode, categorycode) values(?, ?)"
277           );
278         $sth->execute( $branchcode, $cat );
279     }
280     foreach my $cat (@removecats) {
281         my $sth =
282           $dbh->prepare(
283             "delete from branchrelations where branchcode=? and categorycode=?"
284           );
285         $sth->execute( $branchcode, $cat );
286     }
287 }
288
289 =head2 GetBranchCategory
290
291 $results = GetBranchCategory($categorycode);
292
293 C<$results> is an hashref
294
295 =cut
296
297 sub GetBranchCategory {
298     my ($catcode) = @_;
299     return unless $catcode;
300
301     my $dbh = C4::Context->dbh;
302     my $sth;
303
304     $sth = $dbh->prepare(q{
305         SELECT *
306         FROM branchcategories
307         WHERE categorycode = ?
308     });
309     $sth->execute( $catcode );
310     return $sth->fetchrow_hashref;
311 }
312
313 =head2 GetBranchCategories
314
315   my $categories = GetBranchCategories($categorytype,$show_in_pulldown,$selected_in_pulldown);
316
317 Returns a list ref of anon hashrefs with keys eq columns of branchcategories table,
318 i.e. categorydescription, categorytype, categoryname.
319
320 =cut
321
322 sub GetBranchCategories {
323     my ( $categorytype, $show_in_pulldown, $selected_in_pulldown ) = @_;
324     my $dbh = C4::Context->dbh();
325
326     my $query = "SELECT * FROM branchcategories ";
327
328     my ( @where, @bind );
329     if ( $categorytype ) {
330         push @where, " categorytype = ? ";
331         push @bind, $categorytype;
332     }
333
334     if ( defined( $show_in_pulldown ) ) {
335         push( @where, " show_in_pulldown = ? " );
336         push( @bind, $show_in_pulldown );
337     }
338
339     $query .= " WHERE " . join(" AND ", @where) if(@where);
340     $query .= " ORDER BY categorytype, categorycode";
341     my $sth=$dbh->prepare( $query);
342     $sth->execute(@bind);
343
344     my $branchcats = $sth->fetchall_arrayref({});
345
346     if ( $selected_in_pulldown ) {
347         foreach my $bc ( @$branchcats ) {
348             $bc->{selected} = 1 if $bc->{categorycode} eq $selected_in_pulldown;
349         }
350     }
351
352     return $branchcats;
353 }
354
355 =head2 GetCategoryTypes
356
357 $categorytypes = GetCategoryTypes;
358 returns a list of category types.
359 Currently these types are HARDCODED.
360 type: 'searchdomain' defines a group of agencies that the calling library may search in.
361 Other usage of agency categories falls under type: 'properties'.
362         to allow for other uses of categories.
363 The searchdomain bit may be better implemented as a separate module, but
364 the categories were already here, and minimally used.
365
366 =cut
367
368         #TODO  manage category types.  rename possibly to 'agency domains' ? as borrowergroups are called categories.
369 sub GetCategoryTypes {
370         return ( 'searchdomain','properties');
371 }
372
373 =head2 GetBranch
374
375 $branch = GetBranch( $query, $branches );
376
377 =cut
378
379 sub GetBranch {
380     my ( $query, $branches ) = @_;    # get branch for this query from branches
381     my $branch = $query->param('branch');
382     my %cookie = $query->cookie('userenv');
383     ($branch)                || ($branch = $cookie{'branchname'});
384     ( $branches->{$branch} ) || ( $branch = ( keys %$branches )[0] );
385     return $branch;
386 }
387
388 =head2 GetBranchDetail
389
390     $branch = &GetBranchDetail($branchcode);
391
392 Given the branch code, the function returns a
393 hashref for the corresponding row in the branches table.
394
395 =cut
396
397 sub GetBranchDetail {
398     my ($branchcode) = shift or return;
399     my $sth = C4::Context->dbh->prepare("SELECT * FROM branches WHERE branchcode = ?");
400     $sth->execute($branchcode);
401     return $sth->fetchrow_hashref();
402 }
403
404 =head2 GetBranchesInCategory
405
406   my $branches = GetBranchesInCategory($categorycode);
407
408 Returns a href:  keys %$branches eq (branchcode,branchname) .
409
410 =cut
411
412 sub GetBranchesInCategory {
413     my ($categorycode) = @_;
414         my @branches;
415         my $dbh = C4::Context->dbh();
416         my $sth=$dbh->prepare( "SELECT b.branchcode FROM branchrelations r, branches b 
417                                                         where r.branchcode=b.branchcode and r.categorycode=?");
418     $sth->execute($categorycode);
419         while (my $branch = $sth->fetchrow) {
420                 push @branches, $branch;
421         }
422         return( \@branches );
423 }
424
425 =head2 GetBranchInfo
426
427 $results = GetBranchInfo($branchcode);
428
429 returns C<$results>, a reference to an array of hashes containing branches.
430 if $branchcode, just this branch, with associated categories.
431 if ! $branchcode && $categorytype, all branches in the category.
432
433 =cut
434
435 sub GetBranchInfo {
436     my ($branchcode,$categorytype) = @_;
437     my $dbh = C4::Context->dbh;
438     my $sth;
439
440
441         if ($branchcode) {
442         $sth =
443           $dbh->prepare(
444             "Select * from branches where branchcode = ? order by branchcode");
445         $sth->execute($branchcode);
446     }
447     else {
448         $sth = $dbh->prepare("Select * from branches order by branchcode");
449         $sth->execute();
450     }
451     my @results;
452     while ( my $data = $sth->fetchrow_hashref ) {
453                 my @bind = ($data->{'branchcode'});
454         my $query= "select r.categorycode from branchrelations r";
455                 $query .= ", branchcategories c " if($categorytype);
456                 $query .= " where  branchcode=? ";
457                 if($categorytype) { 
458                         $query .= " and c.categorytype=? and r.categorycode=c.categorycode";
459                         push @bind, $categorytype;
460                 }
461         my $nsth=$dbh->prepare($query);
462                 $nsth->execute( @bind );
463         my @cats = ();
464         while ( my ($cat) = $nsth->fetchrow_array ) {
465             push( @cats, $cat );
466         }
467         $data->{'categories'} = \@cats;
468         push( @results, $data );
469     }
470     return \@results;
471 }
472
473 =head2 ModBranchCategoryInfo
474
475 &ModBranchCategoryInfo($data);
476 sets the data from the editbranch form, and writes to the database...
477
478 =cut
479
480 sub ModBranchCategoryInfo {
481     my ($data) = @_;
482     my $dbh    = C4::Context->dbh;
483     if ($data->{'add'}){
484         # we are doing an insert
485   my $sth   = $dbh->prepare("INSERT INTO branchcategories (categorycode,categoryname,codedescription,categorytype,show_in_pulldown) VALUES (?,?,?,?,?)");
486         $sth->execute(uc( $data->{'categorycode'} ),$data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'},$data->{'show_in_pulldown'} );
487     }
488     else {
489         # modifying
490         my $sth = $dbh->prepare("UPDATE branchcategories SET categoryname=?,codedescription=?,categorytype=?,show_in_pulldown=? WHERE categorycode=?");
491         $sth->execute($data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'},$data->{'show_in_pulldown'},uc( $data->{'categorycode'} ) );
492     }
493 }
494
495 =head2 CheckCategoryUnique
496
497 if (CheckCategoryUnique($categorycode)){
498   # do something
499 }
500
501 =cut
502
503 sub CheckCategoryUnique {
504     my $categorycode = shift;
505     my $dbh    = C4::Context->dbh;
506     my $sth = $dbh->prepare("SELECT categorycode FROM branchcategories WHERE categorycode = ?");
507     $sth->execute(uc( $categorycode) );
508     if (my $data = $sth->fetchrow_hashref){
509         return 0;
510     }
511     else {
512         return 1;
513     }
514 }
515
516 =head2 CheckBranchCategorycode
517
518 $number_rows_affected = CheckBranchCategorycode($categorycode);
519
520 =cut
521
522 sub CheckBranchCategorycode {
523
524     # check to see if the branchcode is being used in the database somewhere....
525     my ($categorycode) = @_;
526     my $dbh            = C4::Context->dbh;
527     my $sth            =
528       $dbh->prepare(
529         "select count(*) from branchrelations where categorycode=?");
530     $sth->execute($categorycode);
531     my ($total) = $sth->fetchrow_array;
532     return $total;
533 }
534
535 sub GetBranchesCount {
536     my $dbh = C4::Context->dbh();
537     my $query = "SELECT COUNT(*) AS branches_count FROM branches";
538     my $sth = $dbh->prepare( $query );
539     $sth->execute();
540     my $row = $sth->fetchrow_hashref();
541     return $row->{'branches_count'};
542 }
543
544 1;
545 __END__
546
547 =head1 AUTHOR
548
549 Koha Development Team <http://koha-community.org/>
550
551 =cut