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