fix for #184
[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 $op = $input->param('op');
63
64 my ($template, $borrowernumber, $cookie)
65     = get_template_and_user({template_name => "parameters/branches.tmpl",
66                              query => $input,
67                              type => "intranet",
68                              authnotrequired => 0,
69                              flagsrequired => {parameters => 1},
70                              debug => 1,
71                              });
72 if ($op) {
73     $template->param(script_name => $script_name,
74                      $op         => 1); # we show only the TMPL_VAR names $op
75 } else {
76     $template->param(script_name => $script_name,
77                      else        => 1); # we show only the TMPL_VAR names $op
78 }
79 $template->param(action => $script_name);
80
81 if ($op eq 'add') {
82 # If the user has pressed the "add new branch" button.
83     heading("Branches: Add Branch");
84     editbranchform();
85
86 } elsif ($op eq 'edit') {
87 # if the user has pressed the "edit branch settings" button.
88     heading("Branches: Edit Branch");
89     $template->param(add => 1);
90     editbranchform($branchcode);
91
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
103 } elsif ($op eq 'delete') {
104 # if the user has pressed the "delete branch" button.
105     my $message = checkdatabasefor($branchcode);
106     if ($message) {
107         $template->param(else => 1);
108         default($message);
109     } else {
110         deleteconfirm($branchcode);
111         $template->param(delete_confirm => 1);
112         $template->param(branchcode => $branchcode);
113     }
114
115 } elsif ($op eq 'delete_confirmed') {
116 # actually delete branch and return to the main screen....
117     deletebranch($branchcode);
118     $template->param(else => 1);
119     default("The branch with code $branchcode has been deleted.");
120
121 } elsif ($op eq 'add_cat') {
122 # If the user has pressed the "add new category" button.
123     heading("Branches: Add Branch");
124     editcatform();
125
126 } else {
127 # if no operation has been set...
128     default();
129 }
130
131
132
133 ######################################################################################################
134 #
135 # html output functions....
136
137 sub default {
138     my ($message) = @_;
139     heading("Branches");
140     $template->param(message => $message);
141     $template->param(action => $script_name);
142     branchinfotable();
143     
144     
145 }
146
147 # FIXME: this function should not exist; otherwise headings are untranslatable
148 sub heading {
149     my ($head) = @_;
150     $template->param(head => $head);
151 }
152
153 sub editbranchform {
154 # prepares the edit form...
155     my ($branchcode) = @_;
156     my $data;
157     if ($branchcode) {
158         $data = getbranchinfo($branchcode);
159         $data = $data->[0];
160         $template->param(branchcode => $data->{'branchcode'});
161         $template->param(branchname => $data->{'branchname'});
162         $template->param(branchaddress1 => $data->{'branchaddress1'});
163         $template->param(branchaddress2 => $data->{'branchaddress2'});
164         $template->param(branchaddress3 => $data->{'branchaddress3'});
165         $template->param(branchphone => $data->{'branchphone'});
166         $template->param(branchfax => $data->{'branchfax'});
167         $template->param(branchemail => $data->{'branchemail'});
168     }
169
170     # make the checkboxs.....
171     #
172     # We export a "categoryloop" array to the template, each element of which
173     # contains separate 'categoryname', 'categorycode', 'codedescription', and
174     # 'checked' fields. The $checked field is either '' or 'checked'
175     # (see bug 130)
176     #
177     my $catinfo = getcategoryinfo();
178     my $catcheckbox;
179 #    print DEBUG "catinfo=".cvs($catinfo)."\n";
180     my @categoryloop = ();
181     foreach my $cat (@$catinfo) {
182         my $checked = "";
183         my $tmp = quotemeta($cat->{'categorycode'});
184         if (grep {/^$tmp$/} @{$data->{'categories'}}) {
185             $checked = "CHECKED";
186         }
187         push @categoryloop, {
188                 categoryname    => $cat->{'categoryname'},
189                 categorycode    => $cat->{'categorycode'},
190                 codedescription => $cat->{'codedescription'},
191                 checked         => $checked,
192             };
193     }
194     $template->param(categoryloop => \@categoryloop);
195
196     # {{{ Leave this here until bug 130 is completely resolved in the templates
197     for my $obsolete ('categoryname', 'categorycode', 'codedescription') {
198         $template->param($obsolete => 'Your template is out of date (bug 130)');
199     }
200     # }}}
201 }
202
203 sub deleteconfirm {
204 # message to print if the 
205     my ($branchcode) = @_;
206 }
207
208
209 sub branchinfotable {
210 # makes the html for a table of branch info from reference to an array of hashs.
211
212     my ($branchcode) = @_;
213     my $branchinfo;
214     if ($branchcode) {
215         $branchinfo = getbranchinfo($branchcode);
216     } else {
217         $branchinfo = getbranchinfo();
218     }
219     my $color;
220     my @loop_data =();
221     foreach my $branch (@$branchinfo) {
222         ($color eq $linecolor1) ? ($color=$linecolor2) : ($color=$linecolor1);
223         #
224         # We export the following fields to the template. These are not
225         # pre-composed as a single "address" field because the template
226         # might (and should) escape what is exported here. (See bug 180)
227         #
228         # - color
229         # - branch_name     (Note: not "branchname")
230         # - branch_code     (Note: not "branchcode")
231         # - address         (containing a static error message)
232         # - branchaddress1 \
233         # - branchaddress2  |
234         # - branchaddress3  | comprising the old "address" field
235         # - branchphone     |
236         # - branchfax       |
237         # - branchemail    /
238         # - address-empty-p (1 if no address information, 0 otherwise)
239         # - categories      (containing a static error message)
240         # - category_list   (loop containing "categoryname")
241         # - no-categories-p (1 if no categories set, 0 otherwise)
242         # - value
243         # - action
244         #
245         my %row = ();
246
247         # Handle address fields separately
248         my $address_empty_p = 1;
249         for my $field ('branchaddress1', 'branchaddress2', 'branchaddress3',
250                 'branchphone', 'branchfax', 'branchemail') {
251
252             $row{$field} = $branch->{$field};
253             $address_empty_p = 0;
254         }
255         $row{'address-empty-p'} = $address_empty_p;
256         # {{{ Leave this here until bug 180 is completely resolved in templates
257         $row{'address'} = 'Your template is out of date (see bug 180)';
258         # }}}
259
260         # Handle categories
261         my $no_categories_p = 1;
262         my @categories = '';
263         foreach my $cat (@{$branch->{'categories'}}) {
264             my ($catinfo) = @{getcategoryinfo($cat)};
265             push @categories, {'categoryname' => $catinfo->{'categoryname'}};
266             $no_categories_p = 0;
267         }
268         # {{{ Leave this here until bug 180 is completely resolved in templates
269         $row{'categories'} = 'Your template is out of date (see bug 180)';
270         # }}}
271         $row{'category_list'} = \@categories;
272         $row{'no-categories-p'} = $no_categories_p;
273
274         # Handle all other fields
275         $row{'branch_name'} = $branch->{'branchname'};
276         $row{'branch_code'} = $branch->{'branchcode'};
277         $row{'color'} = $color;
278         $row{'value'} = $branch->{'branchcode'};
279         $row{'action'} = '/cgi-bin/koha/admin/branches.pl';
280
281         push @loop_data, { %row };
282     }
283     $template->param(branches => \@loop_data);
284
285 }
286
287 # FIXME logic seems wrong
288 sub branchcategoriestable {
289 #Needs to be implemented...
290
291     my $categoryinfo = getcategoryinfo();
292     my $color;
293     foreach my $cat (@$categoryinfo) {
294         ($color eq $linecolor1) ? ($color=$linecolor2) : ($color=$linecolor1);
295         $template->param(color => $color);
296         $template->param(categoryname => $cat->{'categoryname'});
297         $template->param(categorycode => $cat->{'categorycode'});
298         $template->param(codedescription => $cat->{'codedescription'});
299     }
300 }
301
302 ######################################################################################################
303 #
304 # Database functions....
305
306 sub getbranchinfo {
307 # returns a reference to an array of hashes containing branches,
308
309     my ($branchcode) = @_;
310     my $dbh = C4::Context->dbh;
311     my ($query, @query_args);
312     if ($branchcode) {
313         $query = "Select * from branches where branchcode = ?";
314         @query_args = ($branchcode);
315     } else {
316         $query = "Select * from branches";
317     }
318     my $sth = $dbh->prepare($query);
319     $sth->execute(@query_args);
320     my @results;
321     while (my $data = $sth->fetchrow_hashref) { 
322         $query = "select categorycode from branchrelations where branchcode = ?";
323         my $nsth = $dbh->prepare($query);
324         $nsth->execute($data->{'branchcode'});;
325         my @cats = ();
326         while (my ($cat) = $nsth->fetchrow_array) {
327             push(@cats, $cat);
328         }
329         $nsth->finish;
330         $data->{'categories'} = \@cats;
331         push(@results, $data);
332     }
333     $sth->finish;
334     return \@results;
335 }
336
337 # FIXME This doesn't belong here; it should be moved into a module
338 sub getcategoryinfo {
339 # returns a reference to an array of hashes containing branches,
340     my ($catcode) = @_;
341     my $dbh = C4::Context->dbh;
342     my ($query, @query_args);
343 #    print DEBUG "getcategoryinfo: entry: catcode=".cvs($catcode)."\n";
344     if ($catcode) {
345         $query = "select * from branchcategories where categorycode = ?";
346         @query_args = ($catcode);
347     } else {
348         $query = "Select * from branchcategories";
349     }
350 #    print DEBUG "getcategoryinfo: query=".cvs($query)."\n";
351     my $sth = $dbh->prepare($query);
352     $sth->execute(@query_args);
353     my @results;
354     while (my $data = $sth->fetchrow_hashref) {
355         push(@results, $data);
356     }
357     $sth->finish;
358 #    print DEBUG "getcategoryinfo: exit: returning ".cvs(\@results)."\n";
359     return \@results;
360 }
361
362 # FIXME This doesn't belong here; it should be moved into a module
363 sub setbranchinfo {
364 # sets the data from the editbranch form, and writes to the database...
365     my ($data) = @_;
366     my $dbh = C4::Context->dbh;
367     my $query = "replace branches (branchcode,branchname,branchaddress1,branchaddress2,branchaddress3,branchphone,branchfax,branchemail) values (?,?,?,?,?,?,?,?)";
368     my $sth=$dbh->prepare($query);
369     $sth->execute(uc($data->{'branchcode'}), $data->{'branchname'},
370             $data->{'branchaddress1'}, $data->{'branchaddress2'},
371             $data->{'branchaddress3'}, $data->{'branchphone'},
372             $data->{'branchfax'}, $data->{'branchemail'});
373
374     $sth->finish;
375 # sort out the categories....
376     my @checkedcats;
377     my $cats = getcategoryinfo();
378     foreach my $cat (@$cats) {
379         my $code = $cat->{'categorycode'};
380         if ($data->{$code}) {
381             push(@checkedcats, $code);
382         }
383     }
384     my $branchcode =uc($data->{'branchcode'});
385     my $branch = getbranchinfo($branchcode);
386     $branch = $branch->[0];
387     my $branchcats = $branch->{'categories'};
388     my @addcats;
389     my @removecats;
390     foreach my $bcat (@$branchcats) {
391         unless (grep {/^$bcat$/} @checkedcats) {
392             push(@removecats, $bcat);
393         }
394     }
395     foreach my $ccat (@checkedcats){
396         unless (grep {/^$ccat$/} @$branchcats) {
397             push(@addcats, $ccat);
398         }
399     }
400     # FIXME - There's already a $dbh in this scope.
401     my $dbh = C4::Context->dbh;
402     foreach my $cat (@addcats) {
403         my $query = "insert into branchrelations (branchcode, categorycode) values(?, ?)";
404         my $sth = $dbh->prepare($query);
405         $sth->execute($branchcode, $cat);
406         $sth->finish;
407     }
408     foreach my $cat (@removecats) {
409         my $query = "delete from branchrelations where branchcode=? and categorycode=?";
410         my $sth = $dbh->prepare($query);
411         $sth->execute($branchcode, $cat);
412         $sth->finish;
413     }
414 }
415
416 sub deletebranch {
417 # delete branch...
418     my ($branchcode) = @_;
419     my $query = "delete from branches where branchcode = ?";
420     my $dbh = C4::Context->dbh;
421     my $sth=$dbh->prepare($query);
422     $sth->execute($branchcode);
423     $sth->finish;
424 }
425
426 sub checkdatabasefor {
427 # check to see if the branchcode is being used in the database somewhere....
428     my ($branchcode) = @_;
429     my $dbh = C4::Context->dbh;
430     my $sth=$dbh->prepare("select count(*) from items where holdingbranch=? or homebranch=?");
431     $sth->execute($branchcode, $branchcode);
432     my ($total) = $sth->fetchrow_array;
433     $sth->finish;
434     my $message;
435     if ($total) {
436         # FIXME: need to be replaced by an exported boolean parameter
437         $message = "Branch cannot be deleted because there are $total items using that branch.";
438     } 
439     return $message;
440 }
441
442 output_html_with_http_headers $input, $cookie, $template->output;
443
444 # Local Variables:
445 # tab-width: 8
446 # End: