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