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