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