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