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