Small change to make branches order by branchcode in the list
[koha.git] / admin / branches.pl
1 #!/usr/bin/perl
2 # NOTE: Use standard 8-space tabs for this file (indents are 4 spaces)
3
4 #require '/u/acli/lib/cvs.pl';#DEBUG
5 #open(DEBUG,'>/tmp/koha.debug');
6
7 # FIXME: individual fields in branch address need to be exported to templates,
8 #        in order to fix bug 180; need to notify translators
9 # FIXME: looped html (e.g., list of checkboxes) need to be properly
10 #        TMPL_LOOP'ized; doing this properly will fix bug 130; need to
11 #        notify translators
12 # FIXME: need to implement the branch categories stuff
13 # FIXME: heading() need to be moved to templates, need to notify translators
14 # FIXME: there are too many TMPL_IF's; the proper way to do it is to have
15 #        separate templates for each individual action; need to notify
16 #        translators
17 # FIXME: there are lots of error messages exported to the template; a lot
18 #        of these should be converted into exported booleans / counters etc
19 #        so that the error messages can be localized; need to notify translators
20
21 # Finlay working on this file from 26-03-2002
22 # Reorganising this branches admin page.....
23
24
25 # Copyright 2000-2002 Katipo Communications
26 #
27 # This file is part of Koha.
28 #
29 # Koha is free software; you can redistribute it and/or modify it under the
30 # terms of the GNU General Public License as published by the Free Software
31 # Foundation; either version 2 of the License, or (at your option) any later
32 # version.
33 #
34 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
35 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
36 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
37 #
38 # You should have received a copy of the GNU General Public License along with
39 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
40 # Suite 330, Boston, MA  02111-1307 USA
41
42 use strict;
43 use CGI;
44 use C4::Auth;
45 use C4::Context;
46 use C4::Output;
47 use C4::Interface::CGI::Output;
48 use HTML::Template;
49
50 # Fixed variables
51 my $linecolor1='#ffffcc';
52 my $linecolor2='white';
53 my $backgroundimage="/images/background-mem.gif";
54 my $script_name="/cgi-bin/koha/admin/branches.pl";
55 my $pagesize=20;
56
57
58 #######################################################################################
59 # Main loop....
60 my $input = new CGI;
61 my $branchcode=$input->param('branchcode');
62 my $categorycode = $input->param('categorycode');
63 my $op = $input->param('op');
64
65 my ($template, $borrowernumber, $cookie)
66     = get_template_and_user({template_name => "parameters/branches.tmpl",
67                              query => $input,
68                              type => "intranet",
69                              authnotrequired => 0,
70                              flagsrequired => {parameters => 1},
71                              debug => 1,
72                              });
73 if ($op) {
74         $template->param(script_name => $script_name,
75                                 $op         => 1); # we show only the TMPL_VAR names $op
76 } else {
77         $template->param(script_name => $script_name,
78                                 else        => 1); # we show only the TMPL_VAR names $op
79 }
80 $template->param(action => $script_name);
81
82 if ($op eq 'add') {
83         # If the user has pressed the "add new branch" button.
84         heading("Branches: Add Branch");
85         editbranchform();
86
87 } elsif ($op eq 'edit') {
88         # if the user has pressed the "edit branch settings" button.
89         heading("Branches: Edit Branch");
90         $template->param(add => 1);
91         editbranchform($branchcode);
92 } elsif ($op eq 'add_validate') {
93         # confirm settings change...
94         my $params = $input->Vars;
95         unless ($params->{'branchcode'} && $params->{'branchname'}) {
96                 default ("Cannot change branch record: You must specify a Branchname and a Branchcode");
97         } else {
98                 setbranchinfo($params);
99                 $template->param(else => 1);
100                 default ("Branch record changed for branch: $params->{'branchname'}");
101         }
102 } elsif ($op eq 'delete') {
103         # if the user has pressed the "delete branch" button.
104         my $message = checkdatabasefor($branchcode);
105         if ($message) {
106                 $template->param(else => 1);
107                 default($message);
108         } else {
109                 $template->param(delete_confirm => 1);
110                 $template->param(branchcode => $branchcode);
111         }
112 } elsif ($op eq 'delete_confirmed') {
113         # actually delete branch and return to the main screen....
114         deletebranch($branchcode);
115         $template->param(else => 1);
116         default("The branch with code $branchcode has been deleted.");
117 } elsif ($op eq 'editcategory') {
118         # If the user has pressed the "add new category" button.
119         heading("Branches: Edit Category");
120         editcatform($categorycode);
121 } elsif ($op eq 'addcategory_validate') {
122         # confirm settings change...
123         my $params = $input->Vars;
124         unless ($params->{'categorycode'} && $params->{'categoryname'}) {
125                 default ("Cannot change branch record: You must specify a Branchname and a Branchcode");
126         } else {
127                 setcategoryinfo($params);
128                 $template->param(else => 1);
129                 default ("Category record changed for category $params->{'categoryname'}");
130         }
131 } elsif ($op eq 'delete_category') {
132         # if the user has pressed the "delete branch" button.
133         my $message = checkcategorycode($categorycode);
134         if ($message) {
135                 $template->param(else => 1);
136                 default($message);
137         } else {
138                 $template->param(delete_category => 1);
139                 $template->param(categorycode => $categorycode);
140         }
141 } elsif ($op eq 'categorydelete_confirmed') {
142         # actually delete branch and return to the main screen....
143         deletecategory($categorycode);
144         $template->param(else => 1);
145         default("The category with code $categorycode has been deleted.");
146
147 } else {
148         # if no operation has been set...
149         default();
150 }
151
152
153
154 ######################################################################################################
155 #
156 # html output functions....
157
158 sub default {
159         my ($message) = @_;
160         heading("Branches");
161         $template->param(message => $message);
162         $template->param(action => $script_name);
163         branchinfotable();
164 }
165
166 # FIXME: this function should not exist; otherwise headings are untranslatable
167 sub heading {
168         my ($head) = @_;
169         $template->param(head => $head);
170 }
171
172 sub editbranchform {
173         # prepares the edit form...
174         my ($branchcode) = @_;
175         my $data;
176         if ($branchcode) {
177                 $data = getbranchinfo($branchcode);
178                 $data = $data->[0];
179                 $template->param(branchcode => $data->{'branchcode'});
180                 $template->param(branchname => $data->{'branchname'});
181                 $template->param(branchaddress1 => $data->{'branchaddress1'});
182                 $template->param(branchaddress2 => $data->{'branchaddress2'});
183                 $template->param(branchaddress3 => $data->{'branchaddress3'});
184                 $template->param(branchphone => $data->{'branchphone'});
185                 $template->param(branchfax => $data->{'branchfax'});
186                 $template->param(branchemail => $data->{'branchemail'});
187     }
188
189     # make the checkboxs.....
190     #
191     # We export a "categoryloop" array to the template, each element of which
192     # contains separate 'categoryname', 'categorycode', 'codedescription', and
193     # 'checked' fields. The $checked field is either '' or 'checked'
194     # (see bug 130)
195     #
196     my $catinfo = getcategoryinfo();
197     my $catcheckbox;
198 #    print DEBUG "catinfo=".cvs($catinfo)."\n";
199     my @categoryloop = ();
200     foreach my $cat (@$catinfo) {
201         my $checked = "";
202         my $tmp = quotemeta($cat->{'categorycode'});
203         if (grep {/^$tmp$/} @{$data->{'categories'}}) {
204                 $checked = "CHECKED";
205         }
206         push @categoryloop, {
207                 categoryname    => $cat->{'categoryname'},
208                 categorycode    => $cat->{'categorycode'},
209                 codedescription => $cat->{'codedescription'},
210                 checked         => $checked,
211             };
212         }
213         $template->param(categoryloop => \@categoryloop);
214
215     # {{{ Leave this here until bug 130 is completely resolved in the templates
216         for my $obsolete ('categoryname', 'categorycode', 'codedescription') {
217                 $template->param($obsolete => 'Your template is out of date (bug 130)');
218         }
219     # }}}
220 }
221
222 sub editcatform {
223         # prepares the edit form...
224         my ($categorycode) = @_;
225         warn "cat : $categorycode";
226         my $data;
227         if ($categorycode) {
228                 $data = getcategoryinfo($categorycode);
229                 $data = $data->[0];
230                 $template->param(categorycode => $data->{'categorycode'});
231                 $template->param(categoryname => $data->{'categoryname'});
232                 $template->param(codedescription => $data->{'codedescription'});
233     }
234 }
235
236 sub deleteconfirm {
237 # message to print if the
238     my ($branchcode) = @_;
239 }
240
241
242 sub branchinfotable {
243 # makes the html for a table of branch info from reference to an array of hashs.
244
245         my ($branchcode) = @_;
246         my $branchinfo;
247         if ($branchcode) {
248                 $branchinfo = getbranchinfo($branchcode);
249         } else {
250                 $branchinfo = getbranchinfo();
251         }
252         my $color;
253         my @loop_data =();
254         foreach my $branch (@$branchinfo) {
255                 ($color eq $linecolor1) ? ($color=$linecolor2) : ($color=$linecolor1);
256                 #
257                 # We export the following fields to the template. These are not
258                 # pre-composed as a single "address" field because the template
259                 # might (and should) escape what is exported here. (See bug 180)
260                 #
261                 # - color
262                 # - branch_name     (Note: not "branchname")
263                 # - branch_code     (Note: not "branchcode")
264                 # - address         (containing a static error message)
265                 # - branchaddress1 \
266                 # - branchaddress2  |
267                 # - branchaddress3  | comprising the old "address" field
268                 # - branchphone     |
269                 # - branchfax       |
270                 # - branchemail    /
271                 # - address-empty-p (1 if no address information, 0 otherwise)
272                 # - categories      (containing a static error message)
273                 # - category_list   (loop containing "categoryname")
274                 # - no-categories-p (1 if no categories set, 0 otherwise)
275                 # - value
276                 # - action
277                 #
278                 my %row = ();
279
280                 # Handle address fields separately
281                 my $address_empty_p = 1;
282                 for my $field ('branchaddress1', 'branchaddress2', 'branchaddress3',
283                         'branchphone', 'branchfax', 'branchemail') {
284                         $row{$field} = $branch->{$field};
285                         if ( $branch->{$field} ) {
286                                 $address_empty_p = 0;
287                         }
288                 }
289                 $row{'address-empty-p'} = $address_empty_p;
290                 # {{{ Leave this here until bug 180 is completely resolved in templates
291                 $row{'address'} = 'Your template is out of date (see bug 180)';
292                 # }}}
293
294                 # Handle categories
295                 my $no_categories_p = 1;
296                 my @categories = '';
297                 foreach my $cat (@{$branch->{'categories'}}) {
298                         my ($catinfo) = @{getcategoryinfo($cat)};
299                         push @categories, {'categoryname' => $catinfo->{'categoryname'}};
300                         $no_categories_p = 0;
301                 }
302                 # {{{ Leave this here until bug 180 is completely resolved in templates
303                 $row{'categories'} = 'Your template is out of date (see bug 180)';
304                 # }}}
305                 $row{'category_list'} = \@categories;
306                 $row{'no-categories-p'} = $no_categories_p;
307
308                 # Handle all other fields
309                 $row{'branch_name'} = $branch->{'branchname'};
310                 $row{'branch_code'} = $branch->{'branchcode'};
311                 $row{'color'} = $color;
312                 $row{'value'} = $branch->{'branchcode'};
313                 $row{'action'} = '/cgi-bin/koha/admin/branches.pl';
314
315                 push @loop_data, { %row };
316         }
317         my @branchcategories =();
318         my $catinfo = getcategoryinfo();
319         foreach my $cat (@$catinfo) {
320                 push @branchcategories, {
321                         categoryname    => $cat->{'categoryname'},
322                         categorycode    => $cat->{'categorycode'},
323                         codedescription => $cat->{'codedescription'},
324                 };
325         }
326
327         $template->param(branches => \@loop_data,
328                                                         branchcategories => \@branchcategories);
329
330 }
331
332 # FIXME logic seems wrong
333 sub branchcategoriestable {
334 #Needs to be implemented...
335
336     my $categoryinfo = getcategoryinfo();
337     my $color;
338     foreach my $cat (@$categoryinfo) {
339         ($color eq $linecolor1) ? ($color=$linecolor2) : ($color=$linecolor1);
340         $template->param(color => $color);
341         $template->param(categoryname => $cat->{'categoryname'});
342         $template->param(categorycode => $cat->{'categorycode'});
343         $template->param(codedescription => $cat->{'codedescription'});
344     }
345 }
346
347 ######################################################################################################
348 #
349 # Database functions....
350
351 sub getbranchinfo {
352 # returns a reference to an array of hashes containing branches,
353
354     my ($branchcode) = @_;
355     my $dbh = C4::Context->dbh;
356     my ($query, @query_args);
357     if ($branchcode) {
358         $query = "Select * from branches where branchcode = ?";
359         @query_args = ($branchcode);
360     } else {
361         $query = "Select * from branches";
362     }
363     $query.=" order by branchcode";
364     my $sth = $dbh->prepare($query);
365     $sth->execute(@query_args);
366     my @results;
367     while (my $data = $sth->fetchrow_hashref) {
368         $query = "select categorycode from branchrelations where branchcode = ?";
369         my $nsth = $dbh->prepare($query);
370         $nsth->execute($data->{'branchcode'});;
371         my @cats = ();
372         while (my ($cat) = $nsth->fetchrow_array) {
373             push(@cats, $cat);
374         }
375         $nsth->finish;
376         $data->{'categories'} = \@cats;
377         push(@results, $data);
378     }
379     $sth->finish;
380     return \@results;
381 }
382
383 # FIXME This doesn't belong here; it should be moved into a module
384 sub getcategoryinfo {
385 # returns a reference to an array of hashes containing branches,
386         my ($catcode) = @_;
387         my $dbh = C4::Context->dbh;
388         my ($query, @query_args);
389         #    print DEBUG "getcategoryinfo: entry: catcode=".cvs($catcode)."\n";
390         if ($catcode) {
391                 $query = "select * from branchcategories where categorycode = ?";
392                 @query_args = ($catcode);
393         } else {
394                 $query = "Select * from branchcategories";
395         }
396         #    print DEBUG "getcategoryinfo: query=".cvs($query)."\n";
397         my $sth = $dbh->prepare($query);
398         $sth->execute(@query_args);
399         my @results;
400         while (my $data = $sth->fetchrow_hashref) {
401                 push(@results, $data);
402         }
403         $sth->finish;
404         #    print DEBUG "getcategoryinfo: exit: returning ".cvs(\@results)."\n";
405         return \@results;
406 }
407
408 # FIXME This doesn't belong here; it should be moved into a module
409 sub setbranchinfo {
410 # sets the data from the editbranch form, and writes to the database...
411         my ($data) = @_;
412         my $dbh = C4::Context->dbh;
413         my $query = "replace branches (branchcode,branchname,branchaddress1,branchaddress2,branchaddress3,branchphone,branchfax,branchemail) values (?,?,?,?,?,?,?,?)";
414         my $sth=$dbh->prepare($query);
415         $sth->execute(uc($data->{'branchcode'}), $data->{'branchname'},
416                 $data->{'branchaddress1'}, $data->{'branchaddress2'},
417                 $data->{'branchaddress3'}, $data->{'branchphone'},
418                 $data->{'branchfax'}, $data->{'branchemail'});
419
420         $sth->finish;
421         # sort out the categories....
422         my @checkedcats;
423         my $cats = getcategoryinfo();
424         foreach my $cat (@$cats) {
425                 my $code = $cat->{'categorycode'};
426                 if ($data->{$code}) {
427                         push(@checkedcats, $code);
428                 }
429         }
430         my $branchcode =uc($data->{'branchcode'});
431         my $branch = getbranchinfo($branchcode);
432         $branch = $branch->[0];
433         my $branchcats = $branch->{'categories'};
434         my @addcats;
435         my @removecats;
436         foreach my $bcat (@$branchcats) {
437                 unless (grep {/^$bcat$/} @checkedcats) {
438                         push(@removecats, $bcat);
439                 }
440         }
441         foreach my $ccat (@checkedcats){
442                 unless (grep {/^$ccat$/} @$branchcats) {
443                         push(@addcats, $ccat);
444                 }
445         }
446         # FIXME - There's already a $dbh in this scope.
447         my $dbh = C4::Context->dbh;
448         foreach my $cat (@addcats) {
449                 my $query = "insert into branchrelations (branchcode, categorycode) values(?, ?)";
450                 my $sth = $dbh->prepare($query);
451                 $sth->execute($branchcode, $cat);
452                 $sth->finish;
453         }
454         foreach my $cat (@removecats) {
455                 my $query = "delete from branchrelations where branchcode=? and categorycode=?";
456                 my $sth = $dbh->prepare($query);
457                 $sth->execute($branchcode, $cat);
458                 $sth->finish;
459         }
460 }
461
462 sub deletebranch {
463 # delete branch...
464     my ($branchcode) = @_;
465     my $query = "delete from branches where branchcode = ?";
466     my $dbh = C4::Context->dbh;
467     my $sth=$dbh->prepare($query);
468     $sth->execute($branchcode);
469     $sth->finish;
470 }
471
472 sub setcategoryinfo {
473 # sets the data from the editbranch form, and writes to the database...
474         my ($data) = @_;
475         my $dbh = C4::Context->dbh;
476         my $query = "replace branchcategories (categorycode,categoryname,codedescription) values (?,?,?)";
477         my $sth=$dbh->prepare($query);
478         $sth->execute(uc($data->{'categorycode'}), $data->{'categoryname'},$data->{'codedescription'});
479
480         $sth->finish;
481 }
482 sub deletecategory {
483 # delete branch...
484     my ($categorycode) = @_;
485     my $query = "delete from branchcategories where categorycode = ?";
486     my $dbh = C4::Context->dbh;
487     my $sth=$dbh->prepare($query);
488     $sth->execute($categorycode);
489     $sth->finish;
490 }
491
492 sub checkdatabasefor {
493 # check to see if the branchcode is being used in the database somewhere....
494     my ($branchcode) = @_;
495     my $dbh = C4::Context->dbh;
496     my $sth=$dbh->prepare("select count(*) from items where holdingbranch=? or homebranch=?");
497     $sth->execute($branchcode, $branchcode);
498     my ($total) = $sth->fetchrow_array;
499     $sth->finish;
500     my $message;
501     if ($total) {
502         # FIXME: need to be replaced by an exported boolean parameter
503         $message = "Branch cannot be deleted because there are $total items using that branch.";
504     }
505     return $message;
506 }
507
508 sub checkcategorycode {
509 # check to see if the branchcode is being used in the database somewhere....
510     my ($categorycode) = @_;
511     my $dbh = C4::Context->dbh;
512     my $sth=$dbh->prepare("select count(*) from branchrelations where categorycode=?");
513     $sth->execute($categorycode);
514     my ($total) = $sth->fetchrow_array;
515     $sth->finish;
516     my $message;
517     if ($total) {
518         # FIXME: need to be replaced by an exported boolean parameter
519         $message = "Category cannot be deleted because there are $total branches using that category.";
520     }
521     return $message;
522 }
523
524 output_html_with_http_headers $input, $cookie, $template->output;
525
526 # Local Variables:
527 # tab-width: 8
528 # End: