[followup](bug #3348) fix spent values and spent resume
[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 require Exporter;
21 use C4::Context;
22 use C4::Koha;
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.02;
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         );
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, IndependantBranches Insensitive.
70   GetBranchInfo() returns the same information without the problems of this function 
71   (namespace collision, mainly).
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">
90         <option value="">Default</option>
91         <!-- TMPL_LOOP name="branchloop" -->
92         <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="branchname" --></option>
93         <!-- /TMPL_LOOP -->
94     </select>
95
96 =head4 Note that you often will want to just use GetBranchesLoop, for exactly the example above.
97
98 =cut
99
100 sub GetBranches {
101     my ($onlymine)=@_;
102     # returns a reference to a hash of references to ALL branches...
103     my %branches;
104     my $dbh = C4::Context->dbh;
105     my $sth;
106     my $query="SELECT * FROM branches";
107     my @bind_parameters;
108     if ($onlymine && C4::Context->userenv && C4::Context->userenv->{branch}){
109       $query .= ' WHERE branchcode = ? ';
110       push @bind_parameters, C4::Context->userenv->{branch};
111     }
112         $query.=" ORDER BY branchname";
113     $sth = $dbh->prepare($query);
114     $sth->execute( @bind_parameters );
115
116     my $nsth = $dbh->prepare(
117         "SELECT categorycode FROM branchrelations WHERE branchcode = ?"
118     );  # prepare once, outside while loop
119
120     while ( my $branch = $sth->fetchrow_hashref ) {
121         $nsth->execute( $branch->{'branchcode'} );
122         while ( my ($cat) = $nsth->fetchrow_array ) {
123             # FIXME - This seems wrong. It ought to be
124             # $branch->{categorycodes}{$cat} = 1;
125             # otherwise, there's a namespace collision if there's a
126             # category with the same name as a field in the 'branches'
127             # table (i.e., don't create a category called "issuing").
128             # In addition, the current structure doesn't really allow
129             # you to list the categories that a branch belongs to:
130             # you'd have to list keys %$branch, and remove those keys
131             # that aren't fields in the "branches" table.
132          #   $branch->{$cat} = 1;
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('IndependantBranches') &&
143     C4::Context->userenv                           &&
144     C4::Context->userenv->{flags} %2 != 1          &&
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     my $searchMyLibraryFirst = C4::Context->preference("SearchMyLibraryFirst");;
160     foreach (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %$branches) {
161         push @loop, {
162             value => $_,
163             selected => (($_ eq $branch) && $searchMyLibraryFirst ) ? 1 : 0, 
164             branchname => $branches->{$_}->{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     $sth->finish;
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,branchphone,
204             branchfax,branchemail,branchip,branchprinter)
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->{'branchphone'},
212             $data->{'branchfax'},        $data->{'branchemail'},
213             $data->{'branchip'},         $data->{'branchprinter'},
214         );
215         return 1 if $dbh->err;
216     } else {
217         my $query  = "
218             UPDATE branches
219             SET branchname=?,branchaddress1=?,
220                 branchaddress2=?,branchaddress3=?,branchphone=?,
221                 branchfax=?,branchemail=?,branchip=?,branchprinter=?
222             WHERE branchcode=?
223         ";
224         my $sth    = $dbh->prepare($query);
225         $sth->execute(
226             $data->{'branchname'},
227             $data->{'branchaddress1'},   $data->{'branchaddress2'},
228             $data->{'branchaddress3'},   $data->{'branchphone'},
229             $data->{'branchfax'},        $data->{'branchemail'},
230             $data->{'branchip'},         $data->{'branchprinter'},
231             $data->{'branchcode'},
232         );
233     }
234     # sort out the categories....
235     my @checkedcats;
236     my $cats = GetBranchCategory();
237     foreach my $cat (@$cats) {
238         my $code = $cat->{'categorycode'};
239         if ( $data->{$code} ) {
240             push( @checkedcats, $code );
241         }
242     }
243     my $branchcode = uc( $data->{'branchcode'} );
244     my $branch     = GetBranchInfo($branchcode);
245     $branch = $branch->[0];
246     my $branchcats = $branch->{'categories'};
247     my @addcats;
248     my @removecats;
249     foreach my $bcat (@$branchcats) {
250
251         unless ( grep { /^$bcat$/ } @checkedcats ) {
252             push( @removecats, $bcat );
253         }
254     }
255     foreach my $ccat (@checkedcats) {
256         unless ( grep { /^$ccat$/ } @$branchcats ) {
257             push( @addcats, $ccat );
258         }
259     }
260     foreach my $cat (@addcats) {
261         my $sth =
262           $dbh->prepare(
263 "insert into branchrelations (branchcode, categorycode) values(?, ?)"
264           );
265         $sth->execute( $branchcode, $cat );
266         $sth->finish;
267     }
268     foreach my $cat (@removecats) {
269         my $sth =
270           $dbh->prepare(
271             "delete from branchrelations where branchcode=? and categorycode=?"
272           );
273         $sth->execute( $branchcode, $cat );
274         $sth->finish;
275     }
276 }
277
278 =head2 GetBranchCategory
279
280 $results = GetBranchCategory($categorycode);
281
282 C<$results> is an ref to an array.
283
284 =cut
285
286 sub GetBranchCategory {
287
288     # returns a reference to an array of hashes containing branches,
289     my ($catcode) = @_;
290     my $dbh = C4::Context->dbh;
291     my $sth;
292
293     #    print DEBUG "GetBranchCategory: entry: catcode=".cvs($catcode)."\n";
294     if ($catcode) {
295         $sth =
296           $dbh->prepare(
297             "select * from branchcategories where categorycode = ?");
298         $sth->execute($catcode);
299     }
300     else {
301         $sth = $dbh->prepare("Select * from branchcategories");
302         $sth->execute();
303     }
304     my @results;
305     while ( my $data = $sth->fetchrow_hashref ) {
306         push( @results, $data );
307     }
308     $sth->finish;
309
310     #    print DEBUG "GetBranchCategory: exit: returning ".cvs(\@results)."\n";
311     return \@results;
312 }
313
314 =head2 GetBranchCategories
315
316   my $categories = GetBranchCategories($branchcode,$categorytype);
317
318 Returns a list ref of anon hashrefs with keys eq columns of branchcategories table,
319 i.e. categorycode, categorydescription, categorytype, categoryname.
320 if $branchcode and/or $categorytype are passed, limit set to categories that
321 $branchcode is a member of , and to $categorytype.
322
323 =cut
324
325 sub GetBranchCategories {
326     my ($branchcode,$categorytype) = @_;
327         my $dbh = C4::Context->dbh();
328         my $query = "SELECT c.* FROM branchcategories c";
329         my (@where, @bind);
330         if($branchcode) {
331                 $query .= ",branchrelations r, branches b ";
332                 push @where, "c.categorycode=r.categorycode and r.branchcode=? ";  
333                 push @bind , $branchcode;
334         }
335         if ($categorytype) {
336                 push @where, " c.categorytype=? ";
337                 push @bind, $categorytype;
338         }
339         $query .= " where " . join(" and ", @where) if(@where);
340         $query .= " order by categorytype,c.categorycode";
341         my $sth=$dbh->prepare( $query);
342         $sth->execute(@bind);
343         
344         my $branchcats = $sth->fetchall_arrayref({});
345         $sth->finish();
346         return( $branchcats );
347 }
348
349 =head2 GetCategoryTypes
350
351 $categorytypes = GetCategoryTypes;
352 returns a list of category types.
353 Currently these types are HARDCODED.
354 type: 'searchdomain' defines a group of agencies that the calling library may search in.
355 Other usage of agency categories falls under type: 'properties'.
356         to allow for other uses of categories.
357 The searchdomain bit may be better implemented as a separate module, but
358 the categories were already here, and minimally used.
359 =cut
360
361         #TODO  manage category types.  rename possibly to 'agency domains' ? as borrowergroups are called categories.
362 sub GetCategoryTypes() {
363         return ( 'searchdomain','properties');
364 }
365
366 =head2 GetBranch
367
368 $branch = GetBranch( $query, $branches );
369
370 =cut
371
372 sub GetBranch ($$) {
373     my ( $query, $branches ) = @_;    # get branch for this query from branches
374     my $branch = $query->param('branch');
375     my %cookie = $query->cookie('userenv');
376     ($branch)                || ($branch = $cookie{'branchname'});
377     ( $branches->{$branch} ) || ( $branch = ( keys %$branches )[0] );
378     return $branch;
379 }
380
381 =head2 GetBranchDetail
382
383     $branch = &GetBranchDetail($branchcode);
384
385 Given the branch code, the function returns a
386 hashref for the corresponding row in the branches table.
387
388 =cut
389
390 sub GetBranchDetail {
391     my ($branchcode) = shift or return;
392     my $sth = C4::Context->dbh->prepare("SELECT * FROM branches WHERE branchcode = ?");
393     $sth->execute($branchcode);
394     return $sth->fetchrow_hashref();
395 }
396
397 =head2 get_branchinfos_of
398
399   my $branchinfos_of = get_branchinfos_of(@branchcodes);
400
401 Associates a list of branchcodes to the information of the branch, taken in
402 branches table.
403
404 Returns a href where keys are branchcodes and values are href where keys are
405 branch information key.
406
407   print 'branchname is ', $branchinfos_of->{$code}->{branchname};
408
409 =cut
410
411 sub get_branchinfos_of {
412     my @branchcodes = @_;
413
414     my $query = '
415     SELECT branchcode,
416        branchname
417     FROM branches
418     WHERE branchcode IN ('
419       . join( ',', map( { "'" . $_ . "'" } @branchcodes ) ) . ')
420 ';
421     return C4::Koha::get_infos_of( $query, 'branchcode' );
422 }
423
424
425 =head2 GetBranchesInCategory
426
427   my $branches = GetBranchesInCategory($categorycode);
428
429 Returns a href:  keys %$branches eq (branchcode,branchname) .
430
431 =cut
432
433 sub GetBranchesInCategory($) {
434     my ($categorycode) = @_;
435         my @branches;
436         my $dbh = C4::Context->dbh();
437         my $sth=$dbh->prepare( "SELECT b.branchcode FROM branchrelations r, branches b 
438                                                         where r.branchcode=b.branchcode and r.categorycode=?");
439     $sth->execute($categorycode);
440         while (my $branch = $sth->fetchrow) {
441                 push @branches, $branch;
442         }
443         $sth->finish();
444         return( \@branches );
445 }
446
447 =head2 GetBranchInfo
448
449 $results = GetBranchInfo($branchcode);
450
451 returns C<$results>, a reference to an array of hashes containing branches.
452 if $branchcode, just this branch, with associated categories.
453 if ! $branchcode && $categorytype, all branches in the category.
454 =cut
455
456 sub GetBranchInfo {
457     my ($branchcode,$categorytype) = @_;
458     my $dbh = C4::Context->dbh;
459     my $sth;
460
461
462         if ($branchcode) {
463         $sth =
464           $dbh->prepare(
465             "Select * from branches where branchcode = ? order by branchcode");
466         $sth->execute($branchcode);
467     }
468     else {
469         $sth = $dbh->prepare("Select * from branches order by branchcode");
470         $sth->execute();
471     }
472     my @results;
473     while ( my $data = $sth->fetchrow_hashref ) {
474                 my @bind = ($data->{'branchcode'});
475         my $query= "select r.categorycode from branchrelations r";
476                 $query .= ", branchcategories c " if($categorytype);
477                 $query .= " where  branchcode=? ";
478                 if($categorytype) { 
479                         $query .= " and c.categorytype=? and r.categorycode=c.categorycode";
480                         push @bind, $categorytype;
481                 }
482         my $nsth=$dbh->prepare($query);
483                 $nsth->execute( @bind );
484         my @cats = ();
485         while ( my ($cat) = $nsth->fetchrow_array ) {
486             push( @cats, $cat );
487         }
488         $nsth->finish;
489         $data->{'categories'} = \@cats;
490         push( @results, $data );
491     }
492     $sth->finish;
493     return \@results;
494 }
495
496 =head2 DelBranch
497
498 &DelBranch($branchcode);
499
500 =cut
501
502 sub DelBranch {
503     my ($branchcode) = @_;
504     my $dbh = C4::Context->dbh;
505     my $sth = $dbh->prepare("delete from branches where branchcode = ?");
506     $sth->execute($branchcode);
507     $sth->finish;
508 }
509
510 =head2 ModBranchCategoryInfo
511
512 &ModBranchCategoryInfo($data);
513 sets the data from the editbranch form, and writes to the database...
514
515 =cut
516
517 sub ModBranchCategoryInfo {
518     my ($data) = @_;
519     my $dbh    = C4::Context->dbh;
520         if ($data->{'add'}){
521                 # we are doing an insert
522                 my $sth   = $dbh->prepare("INSERT INTO branchcategories (categorycode,categoryname,codedescription,categorytype) VALUES (?,?,?,?)");
523                 $sth->execute(uc( $data->{'categorycode'} ),$data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'} );
524                 $sth->finish();         
525         }
526         else {
527                 # modifying
528                 my $sth = $dbh->prepare("UPDATE branchcategories SET categoryname=?,codedescription=?,categorytype=? WHERE categorycode=?");
529                 $sth->execute($data->{'categoryname'}, $data->{'codedescription'},$data->{'categorytype'},uc( $data->{'categorycode'} ) );
530                 $sth->finish();
531         }
532 }
533
534 =head2 DeleteBranchCategory
535
536 DeleteBranchCategory($categorycode);
537
538 =cut
539
540 sub DelBranchCategory {
541     my ($categorycode) = @_;
542     my $dbh = C4::Context->dbh;
543     my $sth = $dbh->prepare("delete from branchcategories where categorycode = ?");
544     $sth->execute($categorycode);
545     $sth->finish;
546 }
547
548 =head2 CheckBranchCategorycode
549
550 $number_rows_affected = CheckBranchCategorycode($categorycode);
551
552 =cut
553
554 sub CheckBranchCategorycode {
555
556     # check to see if the branchcode is being used in the database somewhere....
557     my ($categorycode) = @_;
558     my $dbh            = C4::Context->dbh;
559     my $sth            =
560       $dbh->prepare(
561         "select count(*) from branchrelations where categorycode=?");
562     $sth->execute($categorycode);
563     my ($total) = $sth->fetchrow_array;
564     return $total;
565 }
566
567 1;
568 __END__
569
570 =head1 AUTHOR
571
572 Koha Developement team <info@koha.org>
573
574 =cut