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