Bug 17981: Add a preview mode for notice templates
[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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
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 Modern::Perl;
44 use CGI qw ( -utf8 );
45 use C4::Auth;
46 use C4::Context;
47 use C4::Output;
48 use C4::Letters;
49 use C4::Members::Attributes;
50
51 # $protected_letters = protected_letters()
52 # - return a hashref of letter_codes representing letters that should never be deleted
53 sub protected_letters {
54     my $dbh = C4::Context->dbh;
55     my $codes = $dbh->selectall_arrayref(q{SELECT DISTINCT letter_code FROM message_transports});
56     return { map { $_->[0] => 1 } @{$codes} };
57 }
58
59 our $input       = new CGI;
60 my $searchfield = $input->param('searchfield');
61 my $script_name = '/cgi-bin/koha/tools/letter.pl';
62 our $branchcode  = $input->param('branchcode');
63 $branchcode = '' if defined $branchcode and $branchcode eq '*';
64 my $code        = $input->param('code');
65 my $module      = $input->param('module') || '';
66 my $content     = $input->param('content');
67 my $op          = $input->param('op') || '';
68 my $redirect      = $input->param('redirect');
69 my $dbh = C4::Context->dbh;
70
71 our ( $template, $borrowernumber, $cookie, $staffflags ) = get_template_and_user(
72     {
73         template_name   => 'tools/letter.tt',
74         query           => $input,
75         type            => 'intranet',
76         authnotrequired => 0,
77         flagsrequired   => { tools => 'edit_notices' },
78         debug           => 1,
79     }
80 );
81
82 our $my_branch = C4::Context->preference("IndependentBranches") && !$staffflags->{'superlibrarian'}
83   ?  C4::Context->userenv()->{'branch'}
84   : undef;
85 # we show only the TMPL_VAR names $op
86
87 $template->param(
88     independant_branch => $my_branch,
89         script_name => $script_name,
90   searchfield => $searchfield,
91     branchcode => $branchcode,
92         action => $script_name
93 );
94
95 if ( $op eq 'add_validate' or $op eq 'copy_validate' ) {
96     add_validate();
97     if( $redirect eq "just_save" ){
98         print $input->redirect("/cgi-bin/koha/tools/letter.pl?op=add_form&branchcode=$branchcode&module=$module&code=$code&redirect=done");
99         exit;
100     } else {
101         $op = q{}; # we return to the default screen for the next operation
102     }
103 }
104 if ($op eq 'copy_form') {
105     my $oldbranchcode = $input->param('oldbranchcode') || q||;
106     my $branchcode = $input->param('branchcode');
107     add_form($oldbranchcode, $module, $code);
108     $template->param(
109         oldbranchcode => $oldbranchcode,
110         branchcode => $branchcode,
111         copying => 1,
112         modify => 0,
113     );
114 }
115 elsif ( $op eq 'add_form' ) {
116     add_form($branchcode, $module, $code);
117 }
118 elsif ( $op eq 'delete_confirm' ) {
119     delete_confirm($branchcode, $module, $code);
120 }
121 elsif ( $op eq 'delete_confirmed' ) {
122     delete_confirmed($branchcode, $module, $code);
123     $op = q{}; # next operation is to return to default screen
124 }
125 else {
126     default_display($branchcode,$searchfield);
127 }
128
129 # Do this last as delete_confirmed resets
130 if ($op) {
131     $template->param($op  => 1);
132 } else {
133     $template->param(no_op_set => 1);
134 }
135
136 output_html_with_http_headers $input, $cookie, $template->output;
137
138 sub add_form {
139     my ( $branchcode,$module, $code ) = @_;
140
141     my $letters;
142     # if code has been passed we can identify letter and its an update action
143     if ($code) {
144         $letters = C4::Letters::GetLetterTemplates(
145             {
146                 branchcode => $branchcode,
147                 module     => $module,
148                 code       => $code,
149             }
150         );
151     }
152
153     my $message_transport_types = GetMessageTransportTypes();
154     my $templates = { map { $_ => { message_transport_type => $_ } } sort @$message_transport_types };
155     my %letters = ( default => { templates => $templates } );
156
157     if ( C4::Context->preference('TranslateNotices') ) {
158         my $translated_languages =
159           C4::Languages::getTranslatedLanguages( 'opac',
160             C4::Context->preference('template') );
161         for my $language (@$translated_languages) {
162             for my $sublanguage( @{ $language->{sublanguages_loop} } ) {
163                 if ( $language->{plural} ) {
164                     $letters{ $sublanguage->{rfc4646_subtag} } = {
165                         description => $sublanguage->{native_description}
166                           . ' '
167                           . $sublanguage->{region_description} . ' ('
168                           . $sublanguage->{rfc4646_subtag} . ')',
169                         templates => { %$templates },
170                     };
171                 }
172                 else {
173                     $letters{ $sublanguage->{rfc4646_subtag} } = {
174                         description => $sublanguage->{native_description}
175                           . ' ('
176                           . $sublanguage->{rfc4646_subtag} . ')',
177                         templates => { %$templates },
178                     };
179                 }
180             }
181         }
182         $template->param( languages => $translated_languages );
183     }
184     if ($letters) {
185         $template->param(
186             modify     => 1,
187             code       => $code,
188         );
189         my $first_flag_name = 1;
190         my ( $lang, @templates );
191         # The letter name is contained into each mtt row.
192         # So we can only sent the first one to the template.
193         for my $letter ( @$letters ) {
194             # The letter_name
195             if ( $first_flag_name and $letter->{name} ) {
196                 $template->param(
197                     letter_name=> $letter->{name},
198                 );
199                 $first_flag_name = 0;
200             }
201
202             my $lang = $letter->{lang};
203             my $mtt = $letter->{message_transport_type};
204             $letters{ $lang }{templates}{$mtt} = {
205                 message_transport_type => $letter->{message_transport_type},
206                 is_html    => $letter->{is_html},
207                 title      => $letter->{title},
208                 content    => $letter->{content} // '',
209             };
210         }
211     }
212     else {
213         $template->param( adding => 1 );
214     }
215
216     $template->param(
217         letters => \%letters,
218     );
219
220     my $field_selection;
221     push @{$field_selection}, add_fields('branches');
222     if ($module eq 'reserves') {
223         push @{$field_selection}, add_fields('borrowers', 'reserves', 'biblio', 'biblioitems', 'items');
224     }
225     elsif ( $module eq 'acquisition' ) {
226         push @{$field_selection}, add_fields('aqbooksellers', 'aqorders', 'biblio', 'items');
227     }
228     elsif ($module eq 'claimacquisition' || $module eq 'orderacquisition') {
229         push @{$field_selection}, add_fields('aqbooksellers', 'aqbasket', 'aqorders', 'biblio', 'biblioitems');
230     }
231     elsif ($module eq 'claimissues') {
232         push @{$field_selection}, add_fields('aqbooksellers', 'serial', 'subscription');
233         push @{$field_selection},
234         {
235             value => q{},
236             text => '---BIBLIO---'
237         };
238         foreach(qw(title author serial)) {
239             push @{$field_selection}, {value => "biblio.$_", text => ucfirst $_ };
240         }
241     }
242     elsif ($module eq 'serial') {
243         push @{$field_selection}, add_fields('branches', 'biblio', 'biblioitems', 'borrowers', 'subscription', 'serial');
244     }
245     elsif ($module eq 'suggestions') {
246         push @{$field_selection}, add_fields('suggestions', 'borrowers', 'biblio');
247     }
248     else {
249         push @{$field_selection}, add_fields('biblio','biblioitems'),
250             add_fields('items'),
251             {value => 'items.content', text => 'items.content'},
252             {value => 'items.fine',    text => 'items.fine'},
253             add_fields('borrowers');
254         if ($module eq 'circulation') {
255             push @{$field_selection}, add_fields('opac_news');
256
257         }
258
259         if ( $module eq 'circulation' and $code and $code eq "CHECKIN" ) {
260             push @{$field_selection}, add_fields('old_issues');
261         } else {
262             push @{$field_selection}, add_fields('issues');
263         }
264
265         if ( $module eq 'circulation' and $code =~ /^AR_/  ) {
266             push @{$field_selection}, add_fields('article_requests');
267         }
268     }
269
270     my $preview_is_available = grep {/^$code$/} qw(
271         CHECKIN CHECKOUT HOLD_SLIP
272     );
273     $template->param(
274         module     => $module,
275         SQLfieldnames => $field_selection,
276         branchcode => $branchcode,
277         preview_is_available => $preview_is_available,
278     );
279     return;
280 }
281
282 sub add_validate {
283     my $dbh        = C4::Context->dbh;
284     my $branchcode    = $input->param('branchcode');
285     my $module        = $input->param('module');
286     my $oldmodule     = $input->param('oldmodule');
287     my $code          = $input->param('code');
288     my $name          = $input->param('name');
289     my @mtt           = $input->multi_param('message_transport_type');
290     my @title         = $input->multi_param('title');
291     my @content       = $input->multi_param('content');
292     my @lang          = $input->multi_param('lang');
293     for my $mtt ( @mtt ) {
294         my $is_html = $input->param("is_html_$mtt");
295         my $title   = shift @title;
296         my $content = shift @content;
297         my $lang = shift @lang;
298         my $letter = C4::Letters::getletter( $oldmodule, $code, $branchcode, $mtt, $lang );
299
300         # getletter can return the default letter even if we pass a branchcode
301         # If we got the default one and we needed the specific one, we didn't get the one we needed!
302         if ( $letter and $branchcode and $branchcode ne $letter->{branchcode} ) {
303             $letter = undef;
304         }
305         unless ( $title and $content ) {
306             # Delete this mtt if no title or content given
307             delete_confirmed( $branchcode, $oldmodule, $code, $mtt, $lang );
308             next;
309         }
310         elsif ( $letter and $letter->{message_transport_type} eq $mtt and $letter->{lang} eq $lang ) {
311             $dbh->do(
312                 q{
313                     UPDATE letter
314                     SET branchcode = ?, module = ?, name = ?, is_html = ?, title = ?, content = ?, lang = ?
315                     WHERE branchcode = ? AND module = ? AND code = ? AND message_transport_type = ? AND lang = ?
316                 },
317                 undef,
318                 $branchcode || '', $module, $name, $is_html || 0, $title, $content, $lang,
319                 $branchcode, $oldmodule, $code, $mtt, $lang
320             );
321         } else {
322             $dbh->do(
323                 q{INSERT INTO letter (branchcode,module,code,name,is_html,title,content,message_transport_type, lang) VALUES (?,?,?,?,?,?,?,?,?)},
324                 undef,
325                 $branchcode || '', $module, $code, $name, $is_html || 0, $title, $content, $mtt, $lang
326             );
327         }
328     }
329     # set up default display
330     default_display($branchcode);
331     return 1;
332 }
333
334 sub delete_confirm {
335     my ($branchcode, $module, $code) = @_;
336     my $dbh = C4::Context->dbh;
337     my $letter = C4::Letters::getletter($module, $code, $branchcode);
338     my @values = values %$letter;
339     $template->param(
340         letter => $letter,
341     );
342     return;
343 }
344
345 sub delete_confirmed {
346     my ($branchcode, $module, $code, $mtt, $lang) = @_;
347     C4::Letters::DelLetter(
348         {
349             branchcode => $branchcode || '',
350             module     => $module,
351             code       => $code,
352             mtt        => $mtt,
353             lang       => $lang,
354         }
355     );
356     # setup default display for screen
357     default_display($branchcode);
358     return;
359 }
360
361 sub retrieve_letters {
362     my ($branchcode, $searchstring) = @_;
363
364     $branchcode = $my_branch if $branchcode && $my_branch;
365
366     my $dbh = C4::Context->dbh;
367     my ($sql, @where, @args);
368     $sql = "SELECT branchcode, module, code, name, branchname
369             FROM letter
370             LEFT OUTER JOIN branches USING (branchcode)
371     ";
372     if ($searchstring && $searchstring=~m/(\S+)/) {
373         $searchstring = $1 . q{%};
374         push @where, 'code LIKE ?';
375         push @args, $searchstring;
376     }
377     elsif ($branchcode) {
378         push @where, 'branchcode = ?';
379         push @args, $branchcode || '';
380     }
381     elsif ($my_branch) {
382         push @where, "(branchcode = ? OR branchcode = '')";
383         push @args, $my_branch;
384     }
385
386     $sql .= " WHERE ".join(" AND ", @where) if @where;
387     $sql .= " GROUP BY branchcode,module,code";
388     $sql .= " ORDER BY module, code, branchcode";
389
390     return $dbh->selectall_arrayref($sql, { Slice => {} }, @args);
391 }
392
393 sub default_display {
394     my ($branchcode, $searchfield) = @_;
395
396     unless ( defined $branchcode ) {
397         if ( C4::Context->preference('DefaultToLoggedInLibraryNoticesSlips') ) {
398             $branchcode = C4::Context::mybranch();
399         }
400     }
401
402     if ( $searchfield  ) {
403         $template->param( search      => 1 );
404     }
405     my $results = retrieve_letters($branchcode,$searchfield);
406
407     my $loop_data = [];
408     my $protected_letters = protected_letters();
409     foreach my $row (@{$results}) {
410         $row->{protected} = !$row->{branchcode} && $protected_letters->{ $row->{code} };
411         push @{$loop_data}, $row;
412
413     }
414
415     $template->param(
416         letter => $loop_data,
417         branchcode => $branchcode,
418     );
419 }
420
421 sub add_fields {
422     my @tables = @_;
423     my @fields = ();
424
425     for my $table (@tables) {
426         push @fields, get_columns_for($table);
427
428     }
429     return @fields;
430 }
431
432 sub get_columns_for {
433     my $table = shift;
434 # FIXME untranslatable
435     my %column_map = (
436         aqbooksellers => '---BOOKSELLERS---',
437         aqorders      => '---ORDERS---',
438         serial        => '---SERIALS---',
439         reserves      => '---HOLDS---',
440         suggestions   => '---SUGGESTIONS---',
441     );
442     my @fields = ();
443     if (exists $column_map{$table} ) {
444         push @fields, {
445             value => q{},
446             text  => $column_map{$table} ,
447         };
448     }
449     else {
450         my $tlabel = '---' . uc $table;
451         $tlabel.= '---';
452         push @fields, {
453             value => q{},
454             text  => $tlabel,
455         };
456     }
457
458     my $sql = "SHOW COLUMNS FROM $table";# TODO not db agnostic
459     my $table_prefix = $table . q|.|;
460     my $rows = C4::Context->dbh->selectall_arrayref($sql, { Slice => {} });
461     for my $row (@{$rows}) {
462         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
463         push @fields, {
464             value => $table_prefix . $row->{Field},
465             text  => $table_prefix . $row->{Field},
466         }
467     }
468     if ($table eq 'borrowers') {
469         if ( my $attributes = C4::Members::Attributes::GetAttributes() ) {
470             foreach (@$attributes) {
471                 push @fields, {
472                     value => "borrower-attribute:$_",
473                     text  => "attribute:$_",
474                 }
475             }
476         }
477     }
478     return @fields;
479 }