Bug 12740: Make the error message translatable
[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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 strict;
44 use warnings;
45 use CGI;
46 use C4::Auth;
47 use C4::Context;
48 use C4::Output;
49 use C4::Branch; # GetBranches
50 use C4::Letters;
51 use C4::Members::Attributes;
52
53 # _letter_from_where($branchcode,$module, $code, $mtt)
54 # - return FROM WHERE clause and bind args for a letter
55 sub _letter_from_where {
56     my ($branchcode, $module, $code, $mtt) = @_;
57     my $sql = q{FROM letter WHERE branchcode = ? AND module = ? AND code = ?};
58     $sql .= q{ AND message_transport_type = ?} if $mtt ne '*';
59     my @args = ( $branchcode || '', $module, $code, ($mtt ne '*' ? $mtt : ()) );
60 # Mysql is retarded. cause branchcode is part of the primary key it cannot be null. How does that
61 # work with foreign key constraint I wonder...
62
63 #   if ($branchcode) {
64 #       $sql .= " AND branchcode = ?";
65 #       push @args, $branchcode;
66 #   } else {
67 #       $sql .= " AND branchcode IS NULL";
68 #   }
69
70     return ($sql, \@args);
71 }
72
73 # get_letters($branchcode,$module, $code, $mtt)
74 # - return letters with the given $branchcode, $module, $code and $mtt exists
75 sub get_letters {
76     my ($sql, $args) = _letter_from_where(@_);
77     my $dbh = C4::Context->dbh;
78     my $letter = $dbh->selectall_hashref("SELECT * $sql", 'message_transport_type', undef, @$args);
79     return $letter;
80 }
81 # $protected_letters = protected_letters()
82 # - return a hashref of letter_codes representing letters that should never be deleted
83 sub protected_letters {
84     my $dbh = C4::Context->dbh;
85     my $codes = $dbh->selectall_arrayref(q{SELECT DISTINCT letter_code FROM message_transports});
86     return { map { $_->[0] => 1 } @{$codes} };
87 }
88
89 our $input       = new CGI;
90 my $searchfield = $input->param('searchfield');
91 my $script_name = '/cgi-bin/koha/tools/letter.pl';
92 our $branchcode  = $input->param('branchcode');
93 my $code        = $input->param('code');
94 my $module      = $input->param('module') || '';
95 my $content     = $input->param('content');
96 my $op          = $input->param('op') || '';
97 my $dbh = C4::Context->dbh;
98
99 our ( $template, $borrowernumber, $cookie, $staffflags ) = get_template_and_user(
100     {
101         template_name   => 'tools/letter.tt',
102         query           => $input,
103         type            => 'intranet',
104         authnotrequired => 0,
105         flagsrequired   => { tools => 'edit_notices' },
106         debug           => 1,
107     }
108 );
109
110 our $my_branch = C4::Context->preference("IndependentBranches") && !$staffflags->{'superlibrarian'}
111   ?  C4::Context->userenv()->{'branch'}
112   : undef;
113 # we show only the TMPL_VAR names $op
114
115 $template->param(
116     independant_branch => $my_branch,
117         script_name => $script_name,
118   searchfield => $searchfield,
119     branchcode => $branchcode,
120         action => $script_name
121 );
122
123 if ( $op eq 'add_validate' or $op eq 'copy_validate' ) {
124     add_validate();
125     $op = q{}; # we return to the default screen for the next operation
126 }
127 if ($op eq 'copy_form') {
128     my $oldbranchcode = $input->param('oldbranchcode') || q||;
129     my $branchcode = $input->param('branchcode') || q||;
130     my $oldcode = $input->param('oldcode') || $input->param('code');
131     add_form($oldbranchcode, $module, $code);
132     $template->param(
133         oldbranchcode => $oldbranchcode,
134         branchcode => $branchcode,
135         branchloop => _branchloop($branchcode),
136         oldcode => $oldcode,
137         copying => 1,
138         modify => 0,
139     );
140 }
141 elsif ( $op eq 'add_form' ) {
142     add_form($branchcode, $module, $code);
143 }
144 elsif ( $op eq 'delete_confirm' ) {
145     delete_confirm($branchcode, $module, $code);
146 }
147 elsif ( $op eq 'delete_confirmed' ) {
148     my $mtt = $input->param('message_transport_type');
149     delete_confirmed($branchcode, $module, $code, $mtt);
150     $op = q{}; # next operation is to return to default screen
151 }
152 else {
153     default_display($branchcode,$searchfield);
154 }
155
156 # Do this last as delete_confirmed resets
157 if ($op) {
158     $template->param($op  => 1);
159 } else {
160     $template->param(no_op_set => 1);
161 }
162
163 output_html_with_http_headers $input, $cookie, $template->output;
164
165 sub add_form {
166     my ( $branchcode,$module, $code ) = @_;
167
168     my $letters;
169     # if code has been passed we can identify letter and its an update action
170     if ($code) {
171         $letters = get_letters($branchcode,$module, $code, '*');
172     }
173
174     my $message_transport_types = GetMessageTransportTypes();
175     my @letter_loop;
176     if ($letters) {
177         $template->param(
178             modify     => 1,
179             code       => $code,
180             branchcode => $branchcode,
181         );
182         my $first_flag = 1;
183         # The letter name is contained into each mtt row.
184         # So we can only sent the first one to the template.
185         for my $mtt ( @$message_transport_types ) {
186             # The letter_name
187             if ( $first_flag and $letters->{$mtt}{name} ) {
188                 $template->param(
189                     letter_name=> $letters->{$mtt}{name},
190                 );
191                 $first_flag = 0;
192             }
193
194             push @letter_loop, {
195                 message_transport_type => $mtt,
196                 is_html    => $letters->{$mtt}{is_html},
197                 title      => $letters->{$mtt}{title},
198                 content    => $letters->{$mtt}{content}//'',
199             };
200         }
201     }
202     else { # initialize the new fields
203         for my $mtt ( @$message_transport_types ) {
204             push @letter_loop, {
205                 message_transport_type => $mtt,
206             }
207         }
208         $template->param(
209             branchcode => $branchcode,
210             module     => $module,
211         );
212         $template->param( adding => 1 );
213     }
214
215     $template->param(
216         letters => \@letter_loop,
217     );
218
219     my $field_selection;
220     push @{$field_selection}, add_fields('branches');
221     if ($module eq 'reserves') {
222         push @{$field_selection}, add_fields('borrowers', 'reserves', 'biblio', 'items');
223     }
224     elsif ($module eq 'claimacquisition') {
225         push @{$field_selection}, add_fields('aqbooksellers', 'aqorders', 'biblio', 'biblioitems');
226     }
227     elsif ($module eq 'claimissues') {
228         push @{$field_selection}, add_fields('aqbooksellers', 'serial', 'subscription');
229         push @{$field_selection},
230         {
231             value => q{},
232             text => '---BIBLIO---'
233         };
234         foreach(qw(title author serial)) {
235             push @{$field_selection}, {value => "biblio.$_", text => ucfirst $_ };
236         }
237     }
238     elsif ($module eq 'suggestions') {
239         push @{$field_selection}, add_fields('suggestions', 'borrowers', 'biblio');
240     }
241     else {
242         push @{$field_selection}, add_fields('biblio','biblioitems'),
243             add_fields('items'),
244             {value => 'items.content', text => 'items.content'},
245             {value => 'items.fine',    text => 'items.fine'},
246             add_fields('borrowers');
247         if ($module eq 'circulation') {
248             push @{$field_selection}, add_fields('opac_news');
249
250         }
251
252         if ( $module eq 'circulation' && $code eq "CHECKIN" ) {
253             push @{$field_selection}, add_fields('old_issues');
254         } else {
255             push @{$field_selection}, add_fields('issues');
256         }
257     }
258
259     $template->param(
260         module     => $module,
261         branchloop => _branchloop($branchcode),
262         SQLfieldname => $field_selection,
263     );
264     return;
265 }
266
267 sub add_validate {
268     my $dbh        = C4::Context->dbh;
269     my $branchcode    = $input->param('branchcode') || '';
270     my $module        = $input->param('module');
271     my $oldmodule     = $input->param('oldmodule');
272     my $code          = $input->param('code');
273     my $name          = $input->param('name');
274     my @mtt           = $input->param('message_transport_type');
275     my @title         = $input->param('title');
276     my @content       = $input->param('content');
277     for my $mtt ( @mtt ) {
278         my $is_html = $input->param("is_html_$mtt");
279         my $title   = shift @title;
280         my $content = shift @content;
281         my $letter = get_letters($branchcode,$oldmodule, $code, $mtt);
282         unless ( $title and $content ) {
283             delete_confirmed( $branchcode, $oldmodule, $code, $mtt );
284             next;
285         }
286         elsif ( exists $letter->{$mtt} ) {
287             $dbh->do(
288                 q{
289                     UPDATE letter
290                     SET branchcode = ?, module = ?, name = ?, is_html = ?, title = ?, content = ?
291                     WHERE branchcode = ? AND module = ? AND code = ? AND message_transport_type = ?
292                 },
293                 undef,
294                 $branchcode, $module, $name, $is_html || 0, $title, $content,
295                 $branchcode, $oldmodule, $code, $mtt
296             );
297         } else {
298             $dbh->do(
299                 q{INSERT INTO letter (branchcode,module,code,name,is_html,title,content,message_transport_type) VALUES (?,?,?,?,?,?,?,?)},
300                 undef,
301                 $branchcode, $module, $code, $name, $is_html || 0, $title, $content, $mtt
302             );
303         }
304     }
305     # set up default display
306     default_display($branchcode);
307     return 1;
308 }
309
310 sub delete_confirm {
311     my ($branchcode, $module, $code) = @_;
312     my $dbh = C4::Context->dbh;
313     my $letter = get_letters($branchcode, $module, $code, '*');
314     my @values = values %$letter;
315     $template->param(
316         branchcode => $branchcode,
317         branchname => GetBranchName($branchcode),
318         code => $code,
319         module => $module,
320         name => $values[0]->{name},
321     );
322     return;
323 }
324
325 sub delete_confirmed {
326     my ($branchcode, $module, $code, $mtt) = @_;
327     my ($sql, $args) = _letter_from_where($branchcode, $module, $code, $mtt);
328     my $dbh    = C4::Context->dbh;
329     $dbh->do("DELETE $sql", undef, @$args);
330     # setup default display for screen
331     default_display($branchcode);
332     return;
333 }
334
335 sub retrieve_letters {
336     my ($branchcode, $searchstring) = @_;
337
338     $branchcode = $my_branch if $branchcode && $my_branch;
339
340     my $dbh = C4::Context->dbh;
341     my ($sql, @where, @args);
342     $sql = "SELECT branchcode, module, code, name, branchname
343             FROM letter
344             LEFT OUTER JOIN branches USING (branchcode)
345     ";
346     if ($searchstring && $searchstring=~m/(\S+)/) {
347         $searchstring = $1 . q{%};
348         push @where, 'code LIKE ?';
349         push @args, $searchstring;
350     }
351     elsif ($branchcode) {
352         push @where, 'branchcode = ?';
353         push @args, $branchcode || '';
354     }
355     elsif ($my_branch) {
356         push @where, "(branchcode = ? OR branchcode = '')";
357         push @args, $my_branch;
358     }
359
360     $sql .= " WHERE ".join(" AND ", @where) if @where;
361     $sql .= " GROUP BY branchcode,module,code";
362     $sql .= " ORDER BY module, code, branchcode";
363
364     return $dbh->selectall_arrayref($sql, { Slice => {} }, @args);
365 }
366
367 sub default_display {
368     my ($branchcode, $searchfield) = @_;
369
370     if ( $searchfield  ) {
371         $template->param( search      => 1 );
372     }
373     my $results = retrieve_letters($branchcode,$searchfield);
374
375     my $loop_data = [];
376     my $protected_letters = protected_letters();
377     foreach my $row (@{$results}) {
378         $row->{protected} = !$row->{branchcode} && $protected_letters->{ $row->{code} };
379         push @{$loop_data}, $row;
380
381     }
382
383     $template->param(
384         letter => $loop_data,
385         branchloop => _branchloop($branchcode),
386     );
387 }
388
389 sub _branchloop {
390     my ($branchcode) = @_;
391
392     my $branches = GetBranches();
393     my @branchloop;
394     for my $thisbranch (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %$branches) {
395         push @branchloop, {
396             value      => $thisbranch,
397             selected   => $branchcode && $thisbranch eq $branchcode,
398             branchname => $branches->{$thisbranch}->{'branchname'},
399         };
400     }
401
402     return \@branchloop;
403 }
404
405 sub add_fields {
406     my @tables = @_;
407     my @fields = ();
408
409     for my $table (@tables) {
410         push @fields, get_columns_for($table);
411
412     }
413     return @fields;
414 }
415
416 sub get_columns_for {
417     my $table = shift;
418 # FIXME untranslateable
419     my %column_map = (
420         aqbooksellers => '---BOOKSELLERS---',
421         aqorders      => '---ORDERS---',
422         serial        => '---SERIALS---',
423         reserves      => '---HOLDS---',
424         suggestions   => '---SUGGESTIONS---',
425     );
426     my @fields = ();
427     if (exists $column_map{$table} ) {
428         push @fields, {
429             value => q{},
430             text  => $column_map{$table} ,
431         };
432     }
433     else {
434         my $tlabel = '---' . uc $table;
435         $tlabel.= '---';
436         push @fields, {
437             value => q{},
438             text  => $tlabel,
439         };
440     }
441
442     my $sql = "SHOW COLUMNS FROM $table";# TODO not db agnostic
443     my $table_prefix = $table . q|.|;
444     my $rows = C4::Context->dbh->selectall_arrayref($sql, { Slice => {} });
445     for my $row (@{$rows}) {
446         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
447         push @fields, {
448             value => $table_prefix . $row->{Field},
449             text  => $table_prefix . $row->{Field},
450         }
451     }
452     if ($table eq 'borrowers') {
453         if ( my $attributes = C4::Members::Attributes::GetAttributes() ) {
454             foreach (@$attributes) {
455                 push @fields, {
456                     value => "borrower-attribute:$_",
457                     text  => "attribute:$_",
458                 }
459             }
460         }
461     }
462     return @fields;
463 }