]> git.koha-community.org Git - koha.git/blob - tools/letter.pl
Bug 33478: Save notice format settings
[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 Try::Tiny;
46
47 use C4::Auth qw( get_template_and_user );
48 use C4::Context;
49 use C4::Output qw( output_html_with_http_headers );
50 use C4::Letters qw( GetMessageTransportTypes );
51 use C4::Log qw( logaction );
52 use Koha::Notice::Templates;
53 use Koha::Patron::Attribute::Types;
54
55 # $protected_letters = protected_letters()
56 # - return a hashref of letter_codes representing letters that should never be deleted
57 sub protected_letters {
58     my $dbh = C4::Context->dbh;
59     my $codes = $dbh->selectall_arrayref(q{SELECT DISTINCT letter_code FROM message_transports});
60     return { map { $_->[0] => 1 } @{$codes} };
61 }
62
63 our $input       = CGI->new;
64 my $searchfield = $input->param('searchfield');
65 my $script_name = '/cgi-bin/koha/tools/letter.pl';
66 our $branchcode  = $input->param('branchcode');
67 $branchcode = '' if defined $branchcode and $branchcode eq '*';
68 my $code        = $input->param('code');
69 my $module      = $input->param('module') || '';
70 my $content     = $input->param('content');
71 my $op          = $input->param('op') || '';
72 my $redirect    = $input->param('redirect');
73 my $section     = $input->param('section');
74 my $langtab     = $input->param('langtab');
75
76 my $dbh = C4::Context->dbh;
77
78 our ( $template, $borrowernumber, $cookie, $staffflags ) = get_template_and_user(
79     {
80         template_name   => 'tools/letter.tt',
81         query           => $input,
82         type            => 'intranet',
83         flagsrequired   => { tools => 'edit_notices' },
84     }
85 );
86
87 our $my_branch = C4::Context->preference("IndependentBranches") && !$staffflags->{'superlibrarian'}
88   ?  C4::Context->userenv()->{'branch'}
89   : undef;
90 # we show only the TMPL_VAR names $op
91
92 $template->param(
93     independant_branch => $my_branch,
94     script_name        => $script_name,
95     searchfield        => $searchfield,
96     branchcode         => $branchcode,
97     section            => $section,
98     langtab            => $langtab,
99     action             => $script_name
100 );
101
102 if ( $op eq 'cud-add_validate' or $op eq 'cud-copy_validate' ) {
103     add_validate();
104     if( $redirect eq "just_save" ){
105         print $input->redirect("/cgi-bin/koha/tools/letter.pl?op=add_form&branchcode=$branchcode&module=$module&code=$code&redirect=done&section=$section&langtab=$langtab");
106         exit;
107     } else {
108         $op = q{}; # we return to the default screen for the next operation
109     }
110 }
111 if ($op eq 'cud-copy_form') {
112     my $oldbranchcode = $input->param('oldbranchcode') || q||;
113     my $branchcode = $input->param('branchcode');
114     add_form($oldbranchcode, $module, $code);
115     $template->param(
116         oldbranchcode => $oldbranchcode,
117         branchcode => $branchcode,
118         copy_form => 1,
119         modify => 0,
120     );
121 }
122 elsif ( $op eq 'add_form' ) {
123     add_form($branchcode, $module, $code);
124 }
125 elsif ( $op eq 'delete_confirm' ) {
126     delete_confirm($branchcode, $module, $code);
127 }
128 elsif ( $op eq 'cud-delete_confirmed' ) {
129     delete_confirmed($branchcode, $module, $code);
130     $op = q{}; # next operation is to return to default screen
131 }
132 else {
133     default_display($branchcode,$searchfield);
134 }
135
136 # Do this last as delete_confirmed resets
137 if ($op) {
138     $template->param($op  => 1);
139 } else {
140     $template->param(no_op_set => 1);
141 }
142
143 output_html_with_http_headers $input, $cookie, $template->output;
144
145 sub add_form {
146     my ( $branchcode,$module, $code ) = @_;
147
148     my $letters;
149     # if code has been passed we can identify letter and its an update action
150     if ($code) {
151         $letters = C4::Letters::GetLetterTemplates(
152             {
153                 branchcode => $branchcode,
154                 module     => $module,
155                 code       => $code,
156             }
157         );
158     }
159
160     my $message_transport_types = GetMessageTransportTypes();
161     my $templates = { map { $_ => { message_transport_type => $_ } } sort @$message_transport_types };
162     my %letters = ( default => { templates => $templates } );
163
164     if ( C4::Context->preference('TranslateNotices') ) {
165         my $translated_languages =
166           C4::Languages::getTranslatedLanguages( 'opac',
167             C4::Context->preference('template') );
168         for my $language (@$translated_languages) {
169             for my $sublanguage( @{ $language->{sublanguages_loop} } ) {
170                 if ( $language->{plural} ) {
171                     $letters{ $sublanguage->{rfc4646_subtag} } = {
172                         description => $sublanguage->{native_description}
173                           . ' '
174                           . $sublanguage->{region_description} . ' ('
175                           . $sublanguage->{rfc4646_subtag} . ')',
176                         templates => { %$templates },
177                     };
178                 }
179                 else {
180                     $letters{ $sublanguage->{rfc4646_subtag} } = {
181                         description => $sublanguage->{native_description}
182                           . ' ('
183                           . $sublanguage->{rfc4646_subtag} . ')',
184                         templates => { %$templates },
185                     };
186                 }
187             }
188         }
189         $template->param( languages => $translated_languages );
190     }
191     if ($letters) {
192         $template->param(
193             modify     => 1,
194             code       => $code,
195         );
196         my $first_flag_name = 1;
197         my $lang;
198
199         # The letter name is contained into each mtt row.
200         # So we can only sent the first one to the template.
201         for my $letter ( @$letters ) {
202             # The letter_name
203             if ( $first_flag_name and $letter->{name} ) {
204                 $template->param(
205                     letter_name=> $letter->{name},
206                 );
207                 $first_flag_name = 0;
208             }
209
210             # Catch template issues
211             try {
212                 C4::Letters::_process_tt($letter);
213             } catch {
214                 my $error = $_;
215                 $error =~ s/^ERROR PROCESSING TEMPLATE: //;
216                 $error =~ s/at .*\/tools\/letter\.pl line 213\.$//;
217                 $letter->{tt_error} = $error;
218             };
219
220             my $lang = $letter->{lang};
221             my $mtt = $letter->{message_transport_type};
222             $letters{ $lang }{templates}{$mtt} = {
223                 message_transport_type => $letter->{message_transport_type},
224                 is_html    => $letter->{is_html},
225                 updated_on => $letter->{updated_on},
226                 title      => $letter->{title},
227                 content    => $letter->{content} // '',
228                 tt_error   => $letter->{tt_error},
229             };
230             $letters{ $lang }{params} = $letter;
231         }
232     }
233     else {
234         $template->param( adding => 1 );
235     }
236
237     $template->param(
238         letters => \%letters,
239     );
240
241     my $field_selection;
242     push @{$field_selection}, add_fields('branches');
243     if ( $module eq 'reserves' ) {
244         push @{$field_selection}, add_fields( 'borrowers', 'reserves', 'biblio', 'biblioitems', 'items' );
245     } elsif ( $module eq 'acquisition' ) {
246         push @{$field_selection}, add_fields( 'aqbooksellers', 'aqorders', 'biblio', 'items' );
247     } elsif ( $module eq 'claimacquisition' || $module eq 'orderacquisition' ) {
248         push @{$field_selection}, add_fields( 'aqbooksellers', 'aqbasket', 'aqorders', 'biblio', 'biblioitems' );
249     } elsif ( $module eq 'claimissues' ) {
250         push @{$field_selection}, add_fields( 'aqbooksellers', 'serial', 'subscription', 'biblio', 'biblioitems' );
251     } elsif ( $module eq 'patron_slip' ) {
252         push @{$field_selection}, add_fields('borrowers');
253     } elsif ( $module eq 'serial' ) {
254         push @{$field_selection},
255             add_fields( 'branches', 'biblio', 'biblioitems', 'borrowers', 'subscription', 'serial' );
256     } elsif ( $module eq 'suggestions' ) {
257         push @{$field_selection}, add_fields( 'suggestions', 'borrowers', 'biblio' );
258     } else {
259         push @{$field_selection}, add_fields( 'biblio', 'biblioitems' ),
260             add_fields('items'),
261             { value => 'items.content', text => 'items.content' },
262             { value => 'items.fine',    text => 'items.fine' },
263             add_fields('borrowers');
264         if ( $module eq 'circulation' ) {
265             push @{$field_selection}, add_fields( 'additional_contents', 'recalls' );
266
267         }
268
269         if ( $module eq 'circulation' and $code and ( $code eq "CHECKIN" or $code eq "CHECKINSLIP" ) ) {
270             push @{$field_selection}, add_fields('old_issues');
271         } else {
272             push @{$field_selection}, add_fields('issues');
273         }
274
275         if ( $module eq 'circulation' and $code and $code =~ /^AR_/ ) {
276             push @{$field_selection}, add_fields('article_requests');
277         }
278
279         if ( $module eq 'members' and $code and $code eq 'PROBLEM_REPORT' ) {
280             push @{$field_selection}, add_fields('problem_reports');
281         }
282
283         if ( $module eq 'ill' ) {
284             push @{$field_selection}, add_fields('illrequests');
285         }
286     }
287
288     my $preview_is_available = 0;
289
290     if ($code) {
291         $preview_is_available = grep {$_ eq $code } qw( CHECKIN CHECKOUT HOLD_SLIP );
292     }
293
294     $template->param(
295         module     => $module,
296         SQLfieldnames => $field_selection,
297         branchcode => $branchcode,
298         preview_is_available => $preview_is_available,
299     );
300     return;
301 }
302
303 sub add_validate {
304     my $dbh        = C4::Context->dbh;
305     my $branchcode    = $input->param('branchcode');
306     my $module        = $input->param('module');
307     my $oldmodule     = $input->param('oldmodule');
308     my $code          = $input->param('code');
309     my $name          = $input->param('name');
310     my $style         = $input->param('style');
311     my $format_all    = $input->param('format_all');
312     my @mtt           = $input->multi_param('message_transport_type');
313     my @title         = $input->multi_param('title');
314     my @content       = $input->multi_param('content');
315     my @lang          = $input->multi_param('lang');
316     for my $mtt ( @mtt ) {
317         my $lang = shift @lang;
318         if ( $format_all ) {
319             my @letters = Koha::Notice::Templates->search({ lang => $lang })->as_list;
320             foreach my $letter ( @letters ) {
321                 $letter->set({ style => $style })->store;
322             }
323         }
324         my $is_html = $input->param("is_html_$mtt\_$lang");
325         my $title   = shift @title;
326         my $content = shift @content;
327         my $letter = Koha::Notice::Templates->find(
328             {
329                 module                 => $oldmodule,
330                 code                   => $code,
331                 branchcode             => $branchcode,
332                 message_transport_type => $mtt,
333                 lang                   => $lang
334             }
335         );
336
337         unless ( $title and $content ) {
338             # Delete this mtt if no title or content given
339             delete_confirmed( $branchcode, $oldmodule, $code, $mtt, $lang );
340             next;
341         }
342         elsif ( $letter ) {
343             logaction( 'NOTICES', 'MODIFY', $letter->id, $content,
344                 'Intranet' )
345               if ( C4::Context->preference("NoticesLog")
346                 && $content ne $letter->content );
347
348             $letter->set(
349                 {
350                     branchcode => $branchcode || '',
351                     module     => $module,
352                     name       => $name,
353                     is_html    => $is_html || 0,
354                     title      => $title,
355                     content    => $content,
356                     lang       => $lang,
357                     style      => $style
358                 }
359             )->store;
360
361         } else {
362             my $letter = Koha::Notice::Template->new(
363                 {
364                     branchcode             => $branchcode,
365                     module                 => $module,
366                     code                   => $code,
367                     name                   => $name,
368                     is_html                => $is_html,
369                     title                  => $title,
370                     content                => $content,
371                     message_transport_type => $mtt,
372                     lang                   => $lang,
373                     style                  => $style
374                 }
375             )->store;
376             logaction( 'NOTICES', 'CREATE', $letter->id, $letter->content,
377                 'Intranet' )
378               if C4::Context->preference("NoticesLog");
379         }
380     }
381     # set up default display
382     default_display($branchcode);
383     return 1;
384 }
385
386 sub delete_confirm {
387     my ($branchcode, $module, $code) = @_;
388     my $dbh = C4::Context->dbh;
389     my $letter = Koha::Notice::Templates->search(
390         { module => $module, code => $code, branchcode => $branchcode } );
391     $template->param(
392         letter => $letter ? $letter->next : undef,
393     );
394     return;
395 }
396
397 sub delete_confirmed {
398     my ( $branchcode, $module, $code, $mtt, $lang ) = @_;
399     my $letters = Koha::Notice::Templates->search(
400         {
401             branchcode => $branchcode || '',
402             module     => $module,
403             code       => $code,
404             ( $mtt ? ( message_transport_type => $mtt ) : () ),
405             ( $lang ? ( lang => $lang ) : () ),
406         }
407     );
408     while ( my $letter = $letters->next ) {
409         logaction( 'NOTICES', 'DELETE', $letter->id, $letter->content,
410             'Intranet' )
411           if C4::Context->preference("NoticesLog");
412         $letter->delete;
413     }
414
415     # setup default display for screen
416     default_display($branchcode);
417     return;
418 }
419
420 sub retrieve_letters {
421     my ($branchcode, $searchstring) = @_;
422
423     $branchcode = $my_branch if $branchcode && $my_branch;
424
425     my $dbh = C4::Context->dbh;
426     my ($sql, @where, @args);
427     $sql = "SELECT branchcode, module, code, name, branchname, MAX(updated_on) as updated_on
428             FROM letter
429             LEFT OUTER JOIN branches USING (branchcode)
430     ";
431     if ($searchstring && $searchstring=~m/(\S+)/) {
432         $searchstring = $1 . q{%};
433         push @where, 'code LIKE ?';
434         push @args, $searchstring;
435     }
436     elsif ($branchcode) {
437         push @where, 'branchcode = ?';
438         push @args, $branchcode || '';
439     }
440     elsif ($my_branch) {
441         push @where, "(branchcode = ? OR branchcode = '')";
442         push @args, $my_branch;
443     }
444
445     $sql .= " WHERE ".join(" AND ", @where) if @where;
446     $sql .= " GROUP BY branchcode,module,code,name,branchname";
447
448     $sql .= " ORDER BY module, code, branchcode";
449
450     return $dbh->selectall_arrayref($sql, { Slice => {} }, @args);
451 }
452
453 sub default_display {
454     my ($branchcode, $searchfield) = @_;
455
456     unless ( defined $branchcode ) {
457         if ( C4::Context->preference('DefaultToLoggedInLibraryNoticesSlips') ) {
458             $branchcode = C4::Context::mybranch();
459         }
460     }
461
462     if ( $searchfield  ) {
463         $template->param( search      => 1 );
464     }
465     my $results = retrieve_letters($branchcode,$searchfield);
466
467     my $loop_data = [];
468     my $protected_letters = protected_letters();
469
470     foreach my $row (@{$results}) {
471         $row->{protected} = !$row->{branchcode} && $protected_letters->{ $row->{code} };
472         push @{$loop_data}, $row;
473
474     }
475
476     $template->param(
477         letter => $loop_data,
478         branchcode => $branchcode,
479     );
480 }
481
482 sub add_fields {
483     my @tables = @_;
484     my @fields = ();
485
486     for my $table (@tables) {
487         push @fields, get_columns_for($table);
488
489     }
490     return @fields;
491 }
492
493 sub get_columns_for {
494     my $table = shift;
495 # FIXME untranslatable
496     my %column_map = (
497         aqbooksellers => '---BOOKSELLERS---',
498         aqorders      => '---ORDERS---',
499         serial        => '---SERIALS---',
500         reserves      => '---HOLDS---',
501         suggestions   => '---SUGGESTIONS---',
502     );
503     my @fields = ();
504     if (exists $column_map{$table} ) {
505         push @fields, {
506             value => q{},
507             text  => $column_map{$table} ,
508         };
509     }
510     else {
511         my $tlabel = '---' . uc $table;
512         $tlabel.= '---';
513         push @fields, {
514             value => q{},
515             text  => $tlabel,
516         };
517     }
518
519     my $sql = "SHOW COLUMNS FROM $table";# TODO not db agnostic
520     my $table_prefix = $table . q|.|;
521     my $rows = C4::Context->dbh->selectall_arrayref($sql, { Slice => {} });
522     for my $row (@{$rows}) {
523         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
524         next if $row->{'Field'} eq 'password'; # passwords can no longer be shown in notices so the password field should be removed as a template option
525         push @fields, {
526             value => $table_prefix . $row->{Field},
527             text  => $table_prefix . $row->{Field},
528         }
529     }
530     if ($table eq 'borrowers') {
531         my $attribute_types = Koha::Patron::Attribute::Types->search(
532             {},
533             { order_by => 'code' },
534         );
535         while ( my $at = $attribute_types->next ) {
536             push @fields, {
537                 value => "borrower-attribute:" . $at->code,
538                 text  => "attribute:" . $at->code,
539             }
540         }
541     }
542     return @fields;
543 }