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