Merge am123_dev sur Biblibre_head
[koha.git] / C4 / Suggestions.pm
1 package C4::Suggestions;
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 with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20
21 use strict;
22 use CGI;
23 use Mail::Sendmail;
24
25 use C4::Context;
26 use C4::Output;
27 use C4::Dates qw<format_date>;
28 use base 'Exporter';  # parent would be better there
29 our $VERSION = 3.01;
30 our @EXPORT  = qw<
31     &ConnectSuggestionAndBiblio
32     &CountSuggestion
33     &DelSuggestion
34     &GetSuggestion
35     &GetSuggestionByStatus
36     &GetSuggestionFromBiblionumber
37     &ModStatus
38     &ModSuggestion
39     &NewSuggestion
40     &SearchSuggestion
41 >;
42
43 =head1 NAME
44
45 C4::Suggestions - Some useful functions for dealings with suggestions.
46
47 =head1 SYNOPSIS
48
49 use C4::Suggestions;
50
51 =head1 DESCRIPTION
52
53 The functions in this module deal with the suggestions in OPAC and in librarian interface
54
55 A suggestion is done in the OPAC. It has the status "ASKED"
56
57 When a librarian manages the suggestion, he can set the status to "REJECTED" or "ACCEPTED".
58
59 When the book is ordered, the suggestion status becomes "ORDERED"
60
61 When a book is ordered and arrived in the library, the status becomes "AVAILABLE"
62
63 All suggestions of a borrower can be seen by the borrower itself.
64 Suggestions done by other borrowers can be seen when not "AVAILABLE"
65
66 =head1 FUNCTIONS
67
68 =head2 SearchSuggestion
69
70 (\@array) = &SearchSuggestion($user,$author,$title,$publishercode,$status,$suggestedbyme,$branchcode)
71
72 searches for a suggestion
73
74 return :
75 C<\@array> : the suggestions found. Array of hash.
76 Note the status is stored twice :
77 * in the status field
78 * as parameter ( for example ASKED => 1, or REJECTED => 1) . This is for template & translation purposes.
79
80 =cut
81
82 sub SearchSuggestion  {
83     my ($suggestion,$suggestedbyme)=@_;
84     my $dbh = C4::Context->dbh;
85     my @sql_params;
86     my @query = (
87         q{ SELECT suggestions.*,
88             U1.branchcode   AS branchcodesuggestedby,
89             U1.surname   AS surnamesuggestedby,
90             U1.firstname AS firstnamesuggestedby,
91             U1.email AS emailsuggestedby,
92             U1.borrowernumber AS borrnumsuggestedby,
93             U2.surname   AS surnamemanagedby,
94             U2.firstname AS firstnamemanagedby,
95             U2.email AS emailmanagedby,
96             U2.branchcode AS branchcodemanagedby,
97             U2.borrowernumber AS borrnummanagedby
98         FROM suggestions
99         LEFT JOIN borrowers AS U1 ON suggestedby=U1.borrowernumber
100         LEFT JOIN borrowers AS U2 ON managedby=U2.borrowernumber
101         WHERE STATUS NOT IN ('CLAIMED')
102         } , map {
103             if ( my $s = $$suggestion{$_} ) {
104                 push @sql_params,'%'.$s.'%'; 
105                 " and suggestions.$_ like ? ";
106             } else { () }
107         } qw( title author isbn publishercode collectiontitle )
108         );
109
110         my $userenv = C4::Context->userenv;
111     if (C4::Context->preference('IndependantBranches')) {
112                         if ($userenv) {
113                                 if (($userenv->{flags} % 2) != 1 && !$$suggestion{branchcode}){
114                                    push @sql_params,$$userenv{branch};
115                                    push @query,q{ and (branchcode = ? or branchcode ='')};
116                                 }
117                         }
118     }
119
120         if ($suggestedbyme) {
121             if ( 
122                 $suggestedbyme != -1
123                     and $userenv
124             ) {
125                         if ( my $number = $$userenv{number} ) {
126                                 push @sql_params, $number;
127                                 push @query, 'and suggestedby=?';
128                                 delete $$suggestion{suggestedby}
129                         } 
130             } 
131         } 
132     foreach my $field (grep {qw<
133         STATUS branchcode itemtype suggestedby managedby acceptedby
134         bookfundid biblionumber
135         >} keys %$suggestion
136     ) {
137 #               next unless $$suggestion{$field};
138                 if ($$suggestion{$field}){
139                         push @sql_params,$$suggestion{$field};
140                         push @query, " and suggestions.$field=?";
141                 } 
142                 else {
143                         push @query, " and (suggestions.$field='' OR suggestions.$field IS NULL)";
144                 }
145     }
146
147         warn "@query";
148     my $sth=$dbh->prepare("@query");
149     $sth->execute(@sql_params);
150     my @results;
151     my $even=1; # the even variable is used to set even / odd lines, for highlighting
152     while ( my $data=$sth->fetchrow_hashref ){
153         $$data{$$data{STATUS}} = 1;
154         if ($even) {
155             $even=0;
156             $$data{even}=1;
157         } else {
158                 $even=1;
159         }
160                 
161 #        $$data{$_} = format_date($$data{$_}) 
162 #                       foreach qw(suggestioncreatedon suggestionmanagedon suggestionacceptedon date);
163         push(@results,$data);
164     }
165     return (\@results);
166 }
167
168 =head2 GetSuggestion
169
170 \%sth = &GetSuggestion($suggestionid)
171
172 this function get the detail of the suggestion $suggestionid (input arg)
173
174 return :
175     the result of the SQL query as a hash : $sth->fetchrow_hashref.
176
177 =cut
178
179 sub GetSuggestion {
180     my ($suggestionid) = @_;
181     my $dbh = C4::Context->dbh;
182     my $query = q|
183         SELECT *
184         FROM   suggestions
185         WHERE  suggestionid=?
186     |;
187     my $sth = $dbh->prepare($query);
188     $sth->execute($suggestionid);
189     return($sth->fetchrow_hashref);
190 }
191
192 =head2 GetSuggestionFromBiblionumber
193
194 $suggestionid = &GetSuggestionFromBiblionumber($dbh,$biblionumber)
195
196 Get a suggestion from it's biblionumber.
197
198 return :
199 the id of the suggestion which is related to the biblionumber given on input args.
200
201 =cut
202
203 sub GetSuggestionFromBiblionumber {
204     my ($dbh,$biblionumber) = @_;
205     my $query = q{
206         SELECT suggestionid
207         FROM   suggestions
208         WHERE  biblionumber=?
209         };
210     my $sth = $dbh->prepare($query);
211     $sth->execute($biblionumber);
212     my ($suggestionid) = $sth->fetchrow;
213     return $suggestionid;
214 }
215
216 =head2 GetSuggestionByStatus
217
218 $suggestions = &GetSuggestionByStatus($status,[$branchcode])
219
220 Get a suggestion from it's status
221
222 return :
223 all the suggestion with C<$status>
224
225 =cut
226
227 sub GetSuggestionByStatus {
228     my $status = shift;
229     my $branchcode = shift;
230     my $dbh = C4::Context->dbh;
231     my @sql_params=($status);  
232     my @query = (q{
233     SELECT suggestions.*,
234           U1.surname   AS surnamesuggestedby,
235           U1.firstname AS firstnamesuggestedby,
236           U1.email AS emailsuggestedby,
237           U1.branchcode AS branchcodesuggestedby,
238               U1.borrowernumber AS borrnumsuggestedby,
239           U2.surname   AS surnamemanagedby,
240           U2.firstname AS firstnamemanagedby,
241           U2.email AS emailmanagedby,
242               U2.borrowernumber AS borrnummanagedby
243     FROM suggestions
244         LEFT JOIN borrowers AS U1 ON suggestedby=U1.borrowernumber
245         LEFT JOIN borrowers AS U2 ON managedby=U2.borrowernumber
246     WHERE STATUS = ?
247     });
248
249     if (C4::Context->preference("IndependantBranches") || $branchcode) {
250         my $userenv = C4::Context->userenv;
251         if ($userenv) {
252             unless ($userenv->{flags} % 2 == 1){
253                 push @sql_params,$userenv->{branch};
254                 push @query, q{ and (suggestions.branchcode = ? or suggestions.branchcode ='')};
255             }
256         }
257         if ($branchcode) {
258             push @sql_params,$branchcode;
259             push @query, q{ and (suggestions.branchcode = ? )};
260         }
261     }
262     
263     my $sth = $dbh->prepare("@query");
264     $sth->execute(@sql_params);
265     
266     my $results;
267     $results=  $sth->fetchall_arrayref({});
268 #    map{$_->{date} = format_date($_->{date})} @$results;
269     return $results;
270 }
271
272 =head2 CountSuggestion
273
274 &CountSuggestion($status)
275
276 Count the number of suggestions with the status given on input argument.
277 the arg status can be :
278
279 =over 2
280
281 =item * ASKED : asked by the user, not dealed by the librarian
282
283 =item * ACCEPTED : accepted by the librarian, but not yet ordered
284
285 =item * CHECKED : checked by the librarian, but not yet ordered
286
287 =item * REJECTED : rejected by the librarian (definitive status)
288
289 =item * ORDERED : ordered by the librarian (acquisition module)
290
291 =back
292
293 return :
294 the number of suggestion with this status.
295
296 =cut
297
298 sub CountSuggestion {
299     my ($status) = @_;
300     my $dbh = C4::Context->dbh;
301     my $sth;
302     if (C4::Context->preference("IndependantBranches")){
303         my $userenv = C4::Context->userenv;
304         if ($userenv->{flags} % 2 == 1){
305             my $query = q{
306                 SELECT count(*)
307                 FROM   suggestions
308                 WHERE  STATUS=?
309                 };
310             $sth = $dbh->prepare($query);
311             $sth->execute($status);
312         }
313         else {
314             my $query = q{ 
315                 SELECT count(*)
316                 FROM suggestions LEFT JOIN borrowers ON borrowers.borrowernumber=suggestions.suggestedby
317                 WHERE STATUS=?
318                 AND (borrowers.branchcode='' OR borrowers.branchcode =?)
319                 };
320             $sth = $dbh->prepare($query);
321             $sth->execute($status,$userenv->{branch});
322         }
323     }
324     else {
325         my $query = q{
326             SELECT count(*)
327             FROM suggestions
328             WHERE STATUS=?
329             };
330          $sth = $dbh->prepare($query);
331         $sth->execute($status);
332     }
333     my ($result) = $sth->fetchrow;
334     return $result;
335 }
336
337 =head2 NewSuggestion
338
339
340 &NewSuggestion($borrowernumber,$title,$author,$publishercode,$note,$copyrightdate,$volumedesc,$publicationyear,$place,$isbn,$biblionumber)
341
342 Insert a new suggestion on database with value given on input arg.
343
344 =cut
345
346 sub NewSuggestion {
347     my ($suggestion) = @_;
348     my $dbh = C4::Context->dbh;
349     my @keys; my  @values;
350
351     while ( my ($k,$v) = each %$suggestion ) {
352                 next unless $v;
353                 push @values, $v;
354                 push @keys  , "$k = ?";
355     }
356
357     my $query = do {
358                 local $" = ',';
359                 qq{
360                         INSERT INTO suggestions
361                         SET STATUS='ASKED', @keys 
362                 };
363     };
364
365     #warn $query;   
366     my $sth = $dbh->prepare($query);
367     $sth->execute(@values);
368     return $dbh->{'mysql_insertid'};
369 }
370
371 =head2 ModSuggestion
372
373 &ModSuggestion($suggestion)
374
375 Modify the suggestion according to the hash passed by ref.
376 The hash HAS to contain suggestionid
377 Data not defined is not updated unless it is a note or sort1 
378 Send a mail to notify the user that did the suggestion.
379
380 Note that there is no function to modify a suggestion : only the status can be modified, thus the name of the function.
381
382 =cut
383
384 sub ModSuggestion {
385     my ($suggestion) = @_;
386     my $dbh = C4::Context->dbh;
387     my $sth;
388     my $suggestionid=$$suggestion{'suggestionid'};
389     delete $$suggestion{'suggestionid'};
390
391     my @values;
392     my @keys;
393
394     while ( my ($k,$v) = each %$suggestion ) {
395                 next if (not $v and $k!~/sort1|note/);
396                 #next if any { $_ eq $k } qw( sort1 note);
397                 push @values, $v;
398                 push @keys,   "$k=?";
399     }
400
401     my $query = do { local $"=',';
402         qq{
403             UPDATE suggestions
404             SET  @keys
405             WHERE  suggestionid=?
406             };
407     };
408
409         #warn $query;
410     $sth = $dbh->prepare($query);
411     my $result = $sth->execute(@values, $suggestionid);
412     # check mail sending.
413     if ($$suggestion{STATUS}){
414         my $queryMail = q{
415         SELECT suggestions.*,
416             boby.surname AS bysurname,
417             boby.firstname AS byfirstname,
418             boby.email AS byemail,
419             lib.surname AS libsurname,
420             lib.firstname AS libfirstname,
421             lib.email AS libemail
422         FROM suggestions
423         LEFT JOIN borrowers AS boby ON boby.borrowernumber=suggestedby
424         LEFT JOIN borrowers AS lib ON lib.borrowernumber=managedby
425         WHERE suggestionid=?
426         };
427         $sth = $dbh->prepare($queryMail);
428         $sth->execute($suggestionid);
429         my $emailinfo = $sth->fetchrow_hashref;
430         my $template = gettemplate(
431             "suggestion/mail_suggestion_$$suggestion{STATUS}.tmpl"
432             , "intranet"
433             , CGI->new
434         );
435
436         $template->param( %$emailinfo);
437         sendmail(
438             To             => $emailinfo->{byemail}, 
439             From           => $emailinfo->{libemail}, 
440             Subject        => 'Koha suggestion',
441             Message        => ''.$template->output, 
442             'Content-Type' => 'text/plain; charset="utf8"',
443         );
444     }
445     return $result;
446 }
447
448 =head2 ConnectSuggestionAndBiblio
449
450 &ConnectSuggestionAndBiblio($suggestionid,$biblionumber)
451
452 connect a suggestion to an existing biblio
453
454 =cut
455
456 sub ConnectSuggestionAndBiblio {
457     my ($suggestionid,$biblionumber) = @_;
458     my $dbh=C4::Context->dbh;
459     my $query = q{
460         UPDATE suggestions
461         SET    biblionumber=?
462         WHERE  suggestionid=?
463         };
464     my $sth = $dbh->prepare($query);
465     return $sth->execute($biblionumber,$suggestionid);
466 }
467
468 =head2 DelSuggestion
469
470 &DelSuggestion($borrowernumber,$suggestionid)
471
472 Delete a suggestion. A borrower can delete a suggestion only if he is its owner.
473
474 =cut
475
476 sub DelSuggestion {
477     my ($borrowernumber,$suggestionid,$type) = @_;
478     my $dbh = C4::Context->dbh;
479     # check that the suggestion comes from the suggestor
480     my $query = q{
481         SELECT suggestedby
482         FROM   suggestions
483         WHERE  suggestionid=?
484         };
485     my $sth = $dbh->prepare($query);
486     $sth->execute($suggestionid);
487     my ($suggestedby) = $sth->fetchrow;
488     if ($type eq 'intranet' || $suggestedby eq $borrowernumber ) {
489         my $queryDelete = qq{ 
490             DELETE FROM suggestions
491             WHERE suggestionid=$suggestionid
492             };
493         return $dbh->do($queryDelete);
494     }
495 }
496
497 1;
498 __END__
499
500
501 =head1 AUTHOR
502
503 Koha Developement team <info@koha.org>
504
505 =cut
506