Bug 7848 - Issues data missing from circulation notices
[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
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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
40 # TODO This script drives the CRUD operations on the letter table
41 # The DB interaction should be handled by calls to C4/Letters.pm
42
43 use strict;
44 use warnings;
45 use CGI;
46 use C4::Auth;
47 use C4::Context;
48 use C4::Output;
49 use C4::Branch; # GetBranches
50 use C4::Members::Attributes;
51
52 # _letter_from_where($branchcode,$module, $code)
53 # - return FROM WHERE clause and bind args for a letter
54 sub _letter_from_where {
55     my ($branchcode, $module, $code) = @_;
56     my $sql = q{FROM letter WHERE branchcode = ? AND module = ? AND code = ?};
57     my @args = ($branchcode || '', $module, $code);
58 # Mysql is retarded. cause branchcode is part of the primary key it cannot be null. How does that
59 # work with foreign key constraint I wonder...
60
61 #   if ($branchcode) {
62 #       $sql .= " AND branchcode = ?";
63 #       push @args, $branchcode;
64 #   } else {
65 #       $sql .= " AND branchcode IS NULL";
66 #   }
67
68     return ($sql, \@args);
69 }
70
71 # letter_exists($branchcode,$module, $code)
72 # - return true if a letter with the given $branchcode, $module and $code exists
73 sub letter_exists {
74     my ($sql, $args) = _letter_from_where(@_);
75     my $dbh = C4::Context->dbh;
76     my $letter = $dbh->selectrow_hashref("SELECT * $sql", undef, @$args);
77     return $letter;
78 }
79
80 # $protected_letters = protected_letters()
81 # - return a hashref of letter_codes representing letters that should never be deleted
82 sub protected_letters {
83     my $dbh = C4::Context->dbh;
84     my $codes = $dbh->selectall_arrayref(q{SELECT DISTINCT letter_code FROM message_transports});
85     return { map { $_->[0] => 1 } @{$codes} };
86 }
87
88 our $input       = new CGI;
89 my $searchfield = $input->param('searchfield');
90 my $script_name = '/cgi-bin/koha/tools/letter.pl';
91 our $branchcode  = $input->param('branchcode');
92 my $code        = $input->param('code');
93 my $module      = $input->param('module');
94 my $content     = $input->param('content');
95 my $op          = $input->param('op') || '';
96 my $dbh = C4::Context->dbh;
97
98 our ( $template, $borrowernumber, $cookie, $staffflags ) = get_template_and_user(
99     {
100         template_name   => 'tools/letter.tmpl',
101         query           => $input,
102         type            => 'intranet',
103         authnotrequired => 0,
104         flagsrequired   => { tools => 'edit_notices' },
105         debug           => 1,
106     }
107 );
108
109 our $my_branch = C4::Context->preference("IndependantBranches") && !$staffflags->{'superlibrarian'}
110   ?  C4::Context->userenv()->{'branch'}
111   : undef;
112 # we show only the TMPL_VAR names $op
113
114 $template->param(
115     independant_branch => $my_branch,
116         script_name => $script_name,
117   searchfield => $searchfield,
118         action => $script_name
119 );
120
121 if ($op eq 'copy') {
122     add_copy();
123     $op = 'add_form';
124 }
125
126 if ($op eq 'add_form') {
127     add_form($branchcode, $module, $code);
128 }
129 elsif ( $op eq 'add_validate' ) {
130     add_validate();
131     $op = q{}; # next operation is to return to default screen
132 }
133 elsif ( $op eq 'delete_confirm' ) {
134     delete_confirm($branchcode, $module, $code);
135 }
136 elsif ( $op eq 'delete_confirmed' ) {
137     delete_confirmed($branchcode, $module, $code);
138     $op = q{}; # next operation is to return to default screen
139 }
140 else {
141     default_display($branchcode,$searchfield);
142 }
143
144 # Do this last as delete_confirmed resets
145 if ($op) {
146     $template->param($op  => 1);
147 } else {
148     $template->param(no_op_set => 1);
149 }
150
151 output_html_with_http_headers $input, $cookie, $template->output;
152
153 sub add_form {
154     my ($branchcode,$module, $code ) = @_;
155
156     my $letter;
157     # if code has been passed we can identify letter and its an update action
158     if ($code) {
159         $letter = letter_exists($branchcode,$module, $code);
160     }
161     if ($letter) {
162         $template->param( modify => 1 );
163         $template->param( code   => $letter->{code} );
164     }
165     else { # initialize the new fields
166         $letter = {
167             branchcode => $branchcode,
168             module     => $module,
169         };
170         $template->param( adding => 1 );
171     }
172
173     my $field_selection;
174     push @{$field_selection}, add_fields('branches');
175     if ($module eq 'reserves') {
176         push @{$field_selection}, add_fields('borrowers', 'reserves', 'biblio', 'items');
177     }
178     elsif ($module eq 'claimacquisition') {
179         push @{$field_selection}, add_fields('aqbooksellers', 'aqorders', 'biblio', 'biblioitems');
180     }
181     elsif ($module eq 'claimissues') {
182         push @{$field_selection}, add_fields('aqbooksellers', 'serial', 'subscription');
183         push @{$field_selection},
184         {
185             value => q{},
186             text => '---BIBLIO---'
187         };
188         foreach(qw(title author serial)) {
189             push @{$field_selection}, {value => "biblio.$_", text => ucfirst $_ };
190         }
191     }
192     elsif ($module eq 'suggestions') {
193         push @{$field_selection}, add_fields('suggestions', 'borrowers', 'biblio');
194     }
195     else {
196         push @{$field_selection}, add_fields('biblio','biblioitems'),
197             {value => q{},             text => '---ITEMS---'  },
198             {value => 'items.content', text => 'items.content'},
199             add_fields('borrowers');
200         if ($module eq 'circulation') {
201             push @{$field_selection}, add_fields('opac_news');
202
203         }
204
205         if ( $module eq 'circulation' && $code eq "CHECKIN" ) {
206             push @{$field_selection}, add_fields('old_issues');
207         } else {
208             push @{$field_selection}, add_fields('issues');
209         }
210     }
211
212     $template->param(
213         branchcode => $letter->{branchcode},
214         name       => $letter->{name},
215         is_html    => $letter->{is_html},
216         title      => $letter->{title},
217         content    => $letter->{content},
218         module     => $module,
219         $module    => 1,
220         branchloop => _branchloop($branchcode),
221         SQLfieldname => $field_selection,
222     );
223     return;
224 }
225
226 sub add_validate {
227     my $dbh        = C4::Context->dbh;
228     my $oldbranchcode = $input->param('oldbranchcode');
229     my $branchcode    = $input->param('branchcode') || '';
230     my $module        = $input->param('module');
231     my $oldmodule     = $input->param('oldmodule');
232     my $code          = $input->param('code');
233     my $name          = $input->param('name');
234     my $is_html       = $input->param('is_html');
235     my $title         = $input->param('title');
236     my $content       = $input->param('content');
237     if (letter_exists($oldbranchcode,$oldmodule, $code)) {
238         $dbh->do(
239             q{UPDATE letter SET branchcode = ?, module = ?, name = ?, is_html = ?, title = ?, content = ? WHERE branchcode = ? AND module = ? AND code = ?},
240             undef,
241             $branchcode, $module, $name, $is_html || 0, $title, $content,
242             $oldbranchcode, $oldmodule, $code
243         );
244     } else {
245         $dbh->do(
246             q{INSERT INTO letter (branchcode,module,code,name,is_html,title,content) VALUES (?,?,?,?,?,?,?)},
247             undef,
248             $branchcode, $module, $code, $name, $is_html || 0, $title, $content
249         );
250     }
251     # set up default display
252     default_display($branchcode);
253 }
254
255 sub add_copy {
256     my $dbh        = C4::Context->dbh;
257     my $oldbranchcode = $input->param('oldbranchcode');
258     my $branchcode    = $input->param('branchcode');
259     my $module        = $input->param('module');
260     my $code          = $input->param('code');
261
262     return if letter_exists($branchcode,$module, $code);
263
264     my $old_letter = letter_exists($oldbranchcode,$module, $code);
265
266     $dbh->do(
267         q{INSERT INTO letter (branchcode,module,code,name,is_html,title,content) VALUES (?,?,?,?,?,?,?)},
268         undef,
269         $branchcode, $module, $code, $old_letter->{name}, $old_letter->{is_html}, $old_letter->{title}, $old_letter->{content}
270     );
271 }
272
273 sub delete_confirm {
274     my ($branchcode, $module, $code) = @_;
275     my $dbh = C4::Context->dbh;
276     my $letter = letter_exists($branchcode, $module, $code);
277     $template->param( branchcode => $branchcode, branchname => GetBranchName($branchcode) );
278     $template->param( code => $code );
279     $template->param( module => $module);
280     $template->param( name => $letter->{name});
281     return;
282 }
283
284 sub delete_confirmed {
285     my ($branchcode, $module, $code) = @_;
286     my ($sql, $args) = _letter_from_where($branchcode, $module, $code);
287     my $dbh    = C4::Context->dbh;
288     $dbh->do("DELETE $sql", undef, @$args);
289     # setup default display for screen
290     default_display($branchcode);
291     return;
292 }
293
294 sub retrieve_letters {
295     my ($branchcode, $searchstring) = @_;
296
297     $branchcode = $my_branch if $branchcode && $my_branch;
298
299     my $dbh = C4::Context->dbh;
300     my ($sql, @where, @args);
301     $sql = "SELECT branchcode, module, code, name, branchname
302             FROM letter
303             LEFT OUTER JOIN branches USING (branchcode)";
304     if ($searchstring && $searchstring=~m/(\S+)/) {
305         $searchstring = $1 . q{%};
306         push @where, 'code LIKE ?';
307         push @args, $searchstring;
308     }
309     elsif ($branchcode) {
310         push @where, 'branchcode = ?';
311         push @args, $branchcode || '';
312     }
313     elsif ($my_branch) {
314         push @where, "(branchcode = ? OR branchcode = '')";
315         push @args, $my_branch;
316     }
317
318     $sql .= " WHERE ".join(" AND ", @where) if @where;
319     $sql .= " ORDER BY module, code, branchcode";
320 #   use Data::Dumper; die Dumper($sql, \@args);
321     return $dbh->selectall_arrayref($sql, { Slice => {} }, @args);
322 }
323
324 sub default_display {
325     my ($branchcode, $searchfield) = @_;
326
327     if ( $searchfield  ) {
328         $template->param( search      => 1 );
329     }
330     my $results = retrieve_letters($branchcode,$searchfield);
331
332     my $loop_data = [];
333     my $protected_letters = protected_letters();
334     foreach my $row (@{$results}) {
335         $row->{protected} = !$row->{branchcode} && $protected_letters->{ $row->{code} };
336         push @{$loop_data}, $row;
337
338     }
339
340     $template->param(
341         letter => $loop_data,
342         branchloop => _branchloop($branchcode),
343     );
344 }
345
346 sub _branchloop {
347     my ($branchcode) = @_;
348
349     my $branches = GetBranches();
350     my @branchloop;
351     for my $thisbranch (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %$branches) {
352         push @branchloop, {
353             value      => $thisbranch,
354             selected   => $branchcode && $thisbranch eq $branchcode,
355             branchname => $branches->{$thisbranch}->{'branchname'},
356         };
357     }
358
359     return \@branchloop;
360 }
361
362 sub add_fields {
363     my @tables = @_;
364     my @fields = ();
365
366     for my $table (@tables) {
367         push @fields, get_columns_for($table);
368
369     }
370     return @fields;
371 }
372
373 sub get_columns_for {
374     my $table = shift;
375 # FIXME untranslateable
376     my %column_map = (
377         aqbooksellers => '---BOOKSELLERS---',
378         aqorders      => '---ORDERS---',
379         serial        => '---SERIALS---',
380         reserves      => '---HOLDS---',
381         suggestions   => '---SUGGESTIONS---',
382     );
383     my @fields = ();
384     if (exists $column_map{$table} ) {
385         push @fields, {
386             value => q{},
387             text  => $column_map{$table} ,
388         };
389     }
390     else {
391         my $tlabel = '---' . uc $table;
392         $tlabel.= '---';
393         push @fields, {
394             value => q{},
395             text  => $tlabel,
396         };
397     }
398
399     my $sql = "SHOW COLUMNS FROM $table";# TODO not db agnostic
400     my $table_prefix = $table . q|.|;
401     my $rows = C4::Context->dbh->selectall_arrayref($sql, { Slice => {} });
402     for my $row (@{$rows}) {
403         next if $row->{'Field'} eq 'timestamp'; # this is really an irrelevant field and there may be other common fields that should be excluded from the list
404         push @fields, {
405             value => $table_prefix . $row->{Field},
406             text  => $table_prefix . $row->{Field},
407         }
408     }
409     if ($table eq 'borrowers') {
410         if ( my $attributes = C4::Members::Attributes::GetAttributes() ) {
411             foreach (@$attributes) {
412                 push @fields, {
413                     value => "borrower-attribute:$_",
414                     text  => "attribute:$_",
415                 }
416             }
417         }
418     }
419     return @fields;
420 }