Adding Letters management to Suggestions.
[koha.git] / tools / letter.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 =head1 tools/letter.pl
21
22  ALGO :
23  this script use an $op to know what to do.
24  if $op is empty or none of the values listed below,
25         - the default screen is built (with all or filtered (if search string is set) records).
26         - the   user can click on add, modify or delete record.
27     - filtering is done on the code field
28  if $op=add_form
29         - if primary key (module + code) exists, this is a modification,so we read the required record
30         - builds the add/modify form
31  if $op=add_validate
32         - the user has just send data, so we create/modify the record
33  if $op=delete_form
34         - we show the record selected and ask for confirmation
35  if $op=delete_confirm
36         - we delete the designated record
37
38 =cut
39 # TODO This script drives the CRUD operations on the letter table
40 # The DB interaction should be handled by calls to C4/Letters.pm
41
42 use strict;
43 use warnings;
44 use CGI;
45 use C4::Auth;
46 use C4::Context;
47 use C4::Output;
48
49 sub StringSearch {
50     my ($searchstring) = @_;
51     my $dbh = C4::Context->dbh;
52     $searchstring =~ s/\'/\\\'/g;
53     my @data = split( ' ', $searchstring );
54     $data[0] = '' unless @data;
55     my $sth = $dbh->prepare("SELECT * FROM letter WHERE (code LIKE ?) ORDER BY module, code");
56     $sth->execute("$data[0]%");     # slightly bogus, only searching on first string.
57     return $sth->fetchall_arrayref({});
58 }
59
60 # FIXME untranslateable
61 our %column_map = (
62     aqbooksellers => 'BOOKSELLERS',
63     aqorders => 'ORDERS',
64     serial => 'SERIALS',
65     reserves => 'HOLDS',
66     suggestions => 'SUGGESTIONS',
67 );
68
69 sub column_picks ($) {
70     # returns @array of values
71     my $table = shift or return ();
72     my $sth = C4::Context->dbh->prepare("SHOW COLUMNS FROM $table");
73     $sth->execute;
74     my @SQLfieldname = ();
75     push @SQLfieldname, {'value' => "", 'text' => '---' . uc($column_map{$table} || $table) . '---'};
76     while (my ($field) = $sth->fetchrow_array) {
77         push @SQLfieldname, {
78             value => $table . ".$field",
79              text => $table . ".$field"
80         };
81     }
82     return @SQLfieldname;
83 }
84
85 # letter_exists($module, $code)
86 # - return true if a letter with the given $module and $code exists
87 sub letter_exists {
88     my ($module, $code) = @_;
89     my $dbh = C4::Context->dbh;
90     my $letters = $dbh->selectall_arrayref(q{SELECT name FROM letter WHERE module = ? AND code = ?}, undef, $module, $code);
91     return @{$letters};
92 }
93
94 # $protected_letters = protected_letters()
95 # - return a hashref of letter_codes representing letters that should never be deleted
96 sub protected_letters {
97     my $dbh = C4::Context->dbh;
98     my $codes = $dbh->selectall_arrayref(q{SELECT DISTINCT letter_code FROM message_transports});
99     return { map { $_->[0] => 1 } @{$codes} };
100 }
101
102 my $input       = new CGI;
103 my $searchfield = $input->param('searchfield');
104 my $script_name = '/cgi-bin/koha/tools/letter.pl';
105 my $code        = $input->param('code');
106 my $module      = $input->param('module');
107 my $content     = $input->param('content');
108 my $op          = $input->param('op');
109 my $dbh = C4::Context->dbh;
110 if (!defined $module ) {
111     $module = q{};
112 }
113
114 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
115     {
116         template_name   => 'tools/letter.tmpl',
117         query           => $input,
118         type            => 'intranet',
119         authnotrequired => 0,
120         flagsrequired   => { tools => 'edit_notices' },
121         debug           => 1,
122     }
123 );
124
125 if (!defined $op) {
126     $op = q{}; # silence errors from eq
127 }
128 # we show only the TMPL_VAR names $op
129
130 $template->param(
131         script_name => $script_name,
132         action => $script_name
133 );
134
135 if ($op eq 'add_form') {
136     add_form($module, $code);
137 }
138 elsif ( $op eq 'add_validate' ) {
139     add_validate();
140     $op = q{}; # next operation is to return to default screen
141 }
142 elsif ( $op eq 'delete_confirm' ) {
143     delete_confirm($module, $code);
144 }
145 elsif ( $op eq 'delete_confirmed' ) {
146     delete_confirmed($module, $code);
147     $op = q{}; # next operation is to return to default screen
148 }
149 else {
150     default_display($searchfield);
151 }
152
153 # Do this last as delete_confirmed resets
154 if ($op) {
155     $template->param($op  => 1);
156 } else {
157     $template->param(no_op_set => 1);
158 }
159
160 output_html_with_http_headers $input, $cookie, $template->output;
161
162 sub add_form {
163     my ($module, $code ) = @_;
164
165     my $letter;
166     # if code has been passed we can identify letter and its an update action
167     if ($code) {
168         $letter = $dbh->selectrow_hashref(q{SELECT module, code, name, title, content FROM letter WHERE module=? AND code=?},
169             undef, $module, $code);
170         $template->param( modify => 1 );
171         $template->param( code   => $letter->{code} );
172     }
173     else { # initialize the new fields
174         $letter = {
175             module  => $module,
176             code    => q{},
177             name    => q{},
178             title   => q{},
179             content => q{},
180         };
181         $template->param( adding => 1 );
182     }
183
184     # add acquisition specific tables
185     if ( $module eq "suggestions" ) {
186         push @SQLfieldname, column_picks('borrowers'),
187                             column_picks('suggestions'),
188                             column_picks('aqbooksellers'),
189                             column_picks('biblio'),
190                             column_picks('items');
191         }
192     elsif ( $module eq "reserves" ) {
193         push @SQLfieldname, column_picks('borrowers'),
194                             column_picks('reserves'),
195                             column_picks('biblio'),
196                             column_picks('items');
197     }
198     elsif ( index( $module, "acquisition" ) > 0 ) {     # FIXME: imprecise comparison
199         push @SQLfieldname, column_picks('aqbooksellers'), column_picks('aqorders');
200         # add issues specific tables
201     }
202     ];
203     push @{$field_selection}, add_fields('branches');
204     if ($module eq 'reserves') {
205         push @{$field_selection}, add_fields('borrowers', 'reserves', 'biblio', 'items');
206     }
207     elsif ($module eq 'claimacquisition') {
208         push @{$field_selection}, add_fields('aqbooksellers', 'aqorders');
209     }
210     elsif ($module eq 'claimissues') {
211         push @{$field_selection}, add_fields('aqbooksellers', 'serial', 'subscription');
212         push @{$field_selection},
213         {
214             value => q{},
215             text => '---BIBLIO---'
216         };
217         foreach(qw(title author serial)) {
218             push @{$field_selection}, {value => "biblio.$_", text => ucfirst $_ };
219         }
220     }
221     else {
222         push @{$field_selection}, add_fields('biblio','biblioitems'),
223             {value => q{},             text => '---ITEMS---'  },
224             {value => 'items.content', text => 'items.content'},
225             add_fields('borrowers');
226     }
227
228     $template->param(
229         name    => $letter->{name},
230         title   => $letter->{title},
231         content => $letter->{content},
232         $module => 1,
233         SQLfieldname => $field_selection,
234     );
235     return;
236 }
237
238 sub add_validate {
239     my $dbh     = C4::Context->dbh;
240     my $module  = $input->param('module');
241     my $code    = $input->param('code');
242     my $name    = $input->param('name');
243     my $title   = $input->param('title');
244     my $content = $input->param('content');
245     if (letter_exists($module, $code)) {
246         $dbh->do(
247             q{UPDATE letter SET module = ?, code = ?, name = ?, title = ?, content = ? WHERE module = ? AND code = ?},
248             undef,
249             $module, $code, $name, $title, $content,
250             $module, $code
251         );
252     } else {
253         $dbh->do(
254             q{INSERT INTO letter (module,code,name,title,content) VALUES (?,?,?,?,?)},
255             undef,
256             $module, $code, $name, $title, $content
257         );
258     }
259     # set up default display
260     default_display();
261     return;
262 }
263
264 sub delete_confirm {
265     my ($module, $code) = @_;
266     my $dbh = C4::Context->dbh;
267     my $letter = $dbh->selectrow_hashref(q|SELECT  name FROM letter WHERE module = ? AND code = ?|,
268         { Slice => {} },
269         $module, $code);
270     $template->param( code => $code );
271     $template->param( module => $module);
272     $template->param( name => $letter->{name});
273     return;
274 }
275
276 sub delete_confirmed {
277     my ($module, $code) = @_;
278     my $dbh    = C4::Context->dbh;
279     $dbh->do('DELETE FROM letter WHERE module=? AND code=?',{},$module,$code);
280     # setup default display for screen
281     default_display();
282     return;
283 }
284
285 sub retrieve_letters {
286     my $searchstring = shift;
287     my $dbh = C4::Context->dbh;
288     if ($searchstring) {
289         if ($searchstring=~m/(\S+)/) {
290             $searchstring = $1 . q{%};
291             return $dbh->selectall_arrayref('SELECT module, code, name FROM letter WHERE code LIKE ? ORDER BY module, code',
292                 { Slice => {} }, $searchstring);
293         }
294     }
295     else {
296         return $dbh->selectall_arrayref('SELECT module, code, name FROM letter ORDER BY module, code', { Slice => {} });
297     }
298     return;
299 }
300
301 sub default_display {
302     my $searchfield = shift;
303     my $results;
304     if ( $searchfield  ) {
305         $template->param( search      => 1 );
306         $template->param( searchfield => $searchfield );
307         $results = retrieve_letters($searchfield);
308     } else {
309         $results = retrieve_letters();
310     }
311     my $loop_data = [];
312     my $protected_letters = protected_letters();
313     foreach my $row (@{$results}) {
314         $row->{protected} = $protected_letters->{ $row->{code}};
315         push @{$loop_data}, $row;
316
317     }
318     $template->param( letter => $loop_data );
319     return;
320 }
321
322 sub add_fields {
323     my @tables = @_;
324     my @fields = ();
325
326     for my $table (@tables) {
327         push @fields, get_columns_for($table);
328
329     }
330     return @fields;
331 }
332
333 sub get_columns_for {
334     my $table = shift;
335 # FIXME untranslateable
336     my %column_map = (
337         aqbooksellers => '---BOOKSELLERS---',
338         aqorders      => '---ORDERS---',
339         serial        => '---SERIALS---',
340         reserves      => '---HOLDS---',
341     );
342     my @fields = ();
343     if (exists $column_map{$table} ) {
344         push @fields, {
345             value => q{},
346             text  => $column_map{$table} ,
347         };
348     }
349     else {
350         my $tlabel = '---' . uc $table;
351         $tlabel.= '---';
352         push @fields, {
353             value => q{},
354             text  => $tlabel,
355         };
356     }
357     my $sql = "SHOW COLUMNS FROM $table";# TODO not db agnostic
358     my $table_prefix = $table . q|.|;
359     my $rows = C4::Context->dbh->selectall_arrayref($sql, { Slice => {} });
360     for my $row (@{$rows}) {
361         push @fields, {
362             value => $table_prefix . $row->{Field},
363             text  => $table_prefix . $row->{Field},
364         }
365     }
366     return @fields;
367 }