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