Bug 36508: Unit tests
[koha.git] / t / db_dependent / Suggestions.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use DateTime::Duration;
21 use Test::More tests => 91;
22 use Test::Warn;
23
24 use t::lib::Mocks;
25 use t::lib::TestBuilder;
26
27 use C4::Context;
28 use C4::Letters qw( GetQueuedMessages GetMessage );
29 use C4::Budgets qw( AddBudgetPeriod AddBudget GetBudget );
30 use Koha::Database;
31 use Koha::DateUtils qw( dt_from_string output_pref );
32 use Koha::Libraries;
33 use Koha::Patrons;
34 use Koha::Suggestions;
35
36 BEGIN {
37     use_ok('C4::Suggestions', qw( GetSuggestion ModSuggestion GetSuggestionInfo GetSuggestionFromBiblionumber GetSuggestionInfoFromBiblionumber GetSuggestionByStatus ConnectSuggestionAndBiblio DelSuggestion MarcRecordFromNewSuggestion GetUnprocessedSuggestions DelSuggestionsOlderThan ));
38 }
39
40 my $schema  = Koha::Database->new->schema;
41 $schema->storage->txn_begin;
42 my $dbh = C4::Context->dbh;
43 my $builder = t::lib::TestBuilder->new;
44
45 t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "0");
46
47 # Reset item types to only the default ones
48 $dbh->do(q|DELETE FROM itemtypes;|);
49 my $sql = qq|
50 INSERT INTO itemtypes (itemtype, description, rentalcharge, notforloan, imageurl, summary) VALUES
51 ('BK', 'Books',5,0,'bridge/book.png',''),
52 ('MX', 'Mixed Materials',5,0,'bridge/kit.png',''),
53 ('CF', 'Computer Files',5,0,'bridge/computer_file.png',''),
54 ('MP', 'Maps',5,0,'bridge/map.png',''),
55 ('VM', 'Visual Materials',5,1,'bridge/dvd.png',''),
56 ('MU', 'Music',5,0,'bridge/sound.png',''),
57 ('CR', 'Continuing Resources',5,0,'bridge/periodical.png',''),
58 ('REF', 'Reference',0,1,'bridge/reference.png','');|;
59 $dbh->do($sql);
60 $dbh->do(q|DELETE FROM suggestions|);
61 $dbh->do(q|DELETE FROM issues|);
62 $dbh->do(q|DELETE FROM borrowers|);
63 $dbh->do(q|DELETE FROM letter|);
64 $dbh->do(q|DELETE FROM message_queue|);
65 $dbh->do(q|INSERT INTO letter(module, code, content) VALUES ('suggestions', 'CHECKED', 'my content')|);
66 $dbh->do(q|INSERT INTO letter(module, code, content) VALUES ('suggestions', 'NEW_SUGGESTION', 'Content for new suggestion')|);
67
68 # Add CPL if missing.
69 if (not defined Koha::Libraries->find('CPL')) {
70     Koha::Library->new({ branchcode => 'CPL', branchname => 'Centerville' })->store;
71 }
72
73 my $patron_category = $builder->build({ source => 'Category' });
74
75 my $member = {
76     firstname => 'my firstname',
77     surname => 'my surname',
78     categorycode => $patron_category->{categorycode},
79     branchcode => 'CPL',
80     smsalertnumber => 12345,
81 };
82
83 my $member2 = {
84     firstname => 'my firstname',
85     surname => 'my surname',
86     categorycode => $patron_category->{categorycode},
87     branchcode => 'CPL',
88     email => 'to@example.com',
89 };
90
91 my $borrowernumber = Koha::Patron->new($member)->store->borrowernumber;
92 my $borrowernumber2 = Koha::Patron->new($member2)->store->borrowernumber;
93
94 my $biblio_1 = $builder->build_object({ class => 'Koha::Biblios' });
95 my $my_suggestion = {
96     title         => 'my title',
97     author        => 'my author',
98     publishercode => 'my publishercode',
99     suggestedby   => $borrowernumber,
100     biblionumber  => $biblio_1->biblionumber,
101     branchcode    => 'CPL',
102     managedby     => '',
103     manageddate   => '',
104     accepteddate  => dt_from_string,
105     note          => 'my note',
106     quantity      => '', # Insert an empty string into int to catch strict SQL modes errors
107 };
108
109 my $budgetperiod_id = AddBudgetPeriod({
110     budget_period_startdate   => '2008-01-01',
111     budget_period_enddate     => '2008-12-31',
112     budget_period_description => 'MAPERI',
113     budget_period_active      => 1,
114 });
115
116 my $budget_id = AddBudget({
117     budget_code      => 'ABCD',
118     budget_amount    => '123.132000',
119     budget_name      => 'ABCD',
120     budget_notes     => 'This is a note',
121     budget_period_id => $budgetperiod_id,
122 });
123 my $my_suggestion_with_budget = {
124     title         => 'my title 2',
125     author        => 'my author 2',
126     publishercode => 'my publishercode 2',
127     suggestedby   => $borrowernumber,
128     branchcode    => '', # This should not fail be set to undef instead
129     biblionumber  => $biblio_1->biblionumber,
130     managedby     => '',
131     manageddate   => '',
132     accepteddate  => dt_from_string,
133     note          => 'my note',
134     budgetid      => $budget_id,
135 };
136 my $my_suggestion_with_budget2 = {
137     title         => 'my title 3',
138     author        => 'my author 3',
139     publishercode => 'my publishercode 3',
140     suggestedby   => $borrowernumber2,
141     biblionumber  => $biblio_1->biblionumber,
142     managedby     => '',
143     manageddate   => '',
144     accepteddate  => dt_from_string,
145     note          => 'my note',
146     budgetid      => $budget_id,
147 };
148 my $my_suggestion_without_suggestedby = {
149     title         => 'my title',
150     author        => 'my author',
151     publishercode => 'my publishercode',
152     suggestedby   => undef,
153     biblionumber  => $biblio_1->biblionumber,
154     branchcode    => 'CPL',
155     managedby     => '',
156     manageddate   => '',
157     accepteddate  => dt_from_string,
158     note          => 'my note',
159     quantity      => '', # Insert an empty string into int to catch strict SQL modes errors
160 };
161
162 my $my_suggestion_object = Koha::Suggestion->new($my_suggestion)->store;
163 my $my_suggestionid = $my_suggestion_object->id;
164 isnt( $my_suggestionid, 0, 'Suggestion is correctly saved' );
165 my $my_suggestion_with_budget_object = Koha::Suggestion->new($my_suggestion_with_budget)->store;
166 my $my_suggestionid_with_budget = $my_suggestion_with_budget_object->id;
167
168 is( GetSuggestion(), undef, 'GetSuggestion without the suggestion id returns undef' );
169 my $suggestion = GetSuggestion($my_suggestionid);
170 is( $suggestion->{title}, $my_suggestion->{title}, 'Suggestion stores the title correctly' );
171 is( $suggestion->{author}, $my_suggestion->{author}, 'Suggestion stores the author correctly' );
172 is( $suggestion->{publishercode}, $my_suggestion->{publishercode}, 'Suggestion stores the publishercode correctly' );
173 is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'Suggestion stores the borrower number correctly' );
174 is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'Suggestion stores the biblio number correctly' );
175 is( $suggestion->{STATUS}, 'ASKED', 'Suggestion stores a suggestion with the status ASKED by default' );
176 is( $suggestion->{managedby}, undef, 'Suggestion stores empty string as undef for non existent foreign key (integer)' );
177 is( $suggestion->{manageddate}, undef, 'Suggestion stores empty string as undef for date' );
178 is( $suggestion->{budgetid}, undef, 'Suggestion should set budgetid to NULL if not given' );
179
180 is( ModSuggestion(), undef, 'ModSuggestion without the suggestion returns undef' );
181 my $mod_suggestion1 = {
182     title         => 'my modified title',
183     author        => 'my modified author',
184     publishercode => 'my modified publishercode',
185     managedby     => '',
186     manageddate   => '',
187 };
188 my $status = ModSuggestion($mod_suggestion1);
189 is( $status, undef, 'ModSuggestion without the suggestion id returns undef' );
190
191 $mod_suggestion1->{suggestionid} = $my_suggestionid;
192 $status = ModSuggestion($mod_suggestion1);
193 is( $status, 1, 'ModSuggestion modifies one entry' );
194 $suggestion = GetSuggestion($my_suggestionid);
195 is( $suggestion->{title}, $mod_suggestion1->{title}, 'ModSuggestion modifies the title  correctly' );
196 is( $suggestion->{author}, $mod_suggestion1->{author}, 'ModSuggestion modifies the author correctly' );
197 is( $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, 'ModSuggestion modifies the publishercode correctly' );
198 is( $suggestion->{managedby}, undef, 'ModSuggestion stores empty string as undef for non existent foreign key (integer)' );
199 is( $suggestion->{manageddate}, undef, 'ModSuggestion stores empty string as undef for date' );
200 isnt( $suggestion->{accepteddate}, undef, 'ModSuggestion does not update a non given date value' );
201 is( $suggestion->{note}, 'my note', 'ModSuggestion should not erase data if not given' );
202
203 my $messages = C4::Letters::GetQueuedMessages({
204     borrowernumber => $borrowernumber
205 });
206 is( @$messages, 0, 'ModSuggestions does not send an email if the status is not updated' );
207
208 my $authorised_value = Koha::AuthorisedValue->new(
209     {
210         category         => 'SUGGEST_STATUS',
211         authorised_value => 'STALLED'
212     }
213 )->store;
214 my $mod_suggestion2 = {
215     STATUS       => 'STALLED',
216     suggestionid => $my_suggestionid,
217 };
218 warning_is { $status = ModSuggestion($mod_suggestion2) }
219            "No suggestions STALLED letter transported by email",
220            "ModSuggestion status warning is correct";
221 is( $status, 1, "ModSuggestion Status OK");
222
223 my $mod_suggestion3 = {
224     STATUS       => 'CHECKED',
225     suggestionid => $my_suggestionid,
226 };
227
228 #Test the message_transport_type of suggestion notices
229
230 #Check the message_transport_type when the 'FallbackToSMSIfNoEmail' syspref is disabled
231 t::lib::Mocks::mock_preference( 'FallbackToSMSIfNoEmail', 0 );
232 $status = ModSuggestion($mod_suggestion3);
233 is( $status, 1, 'ModSuggestion modifies one entry' );
234 $suggestion = GetSuggestion($my_suggestionid);
235 is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'ModSuggestion modifies the status correctly' );
236 $messages = C4::Letters::GetQueuedMessages({
237     borrowernumber => $borrowernumber
238 });
239 is( @$messages, 1, 'ModSuggestion sends an email if the status is updated' );
240 is ($messages->[0]->{message_transport_type}, 'email', 'When FallbackToSMSIfNoEmail syspref is disabled the suggestion message_transport_type is always email');
241
242 #Check the message_transport_type when the 'FallbackToSMSIfNoEmail' syspref is enabled and the borrower has a smsalertnumber and no email
243 t::lib::Mocks::mock_preference( 'FallbackToSMSIfNoEmail', 1 );
244 ModSuggestion($mod_suggestion3);
245 $messages = C4::Letters::GetQueuedMessages({
246     borrowernumber => $borrowernumber
247 });
248 is ($messages->[1]->{message_transport_type}, 'sms', 'When FallbackToSMSIfNoEmail syspref is enabled the suggestion message_transport_type is sms if the borrower has no email');
249
250 #Make a new suggestion for a borrower with defined email and no smsalertnumber
251 my $my_suggestion_2_object = Koha::Suggestion->new($my_suggestion_with_budget2)->store();
252 my $my_suggestion_2_id = $my_suggestion_2_object->id;
253
254 #Check the message_transport_type when the 'FallbackToSMSIfNoEmail' syspref is enabled and the borrower has a defined email and no smsalertnumber
255 t::lib::Mocks::mock_preference( 'FallbackToSMSIfNoEmail', 1 );
256 my $mod_suggestion4 = {
257     STATUS       => 'CHECKED',
258     suggestionid => $my_suggestion_2_id,
259 };
260 ModSuggestion($mod_suggestion4);
261 $messages = C4::Letters::GetQueuedMessages({
262     borrowernumber => $borrowernumber2
263 });
264 is ($messages->[0]->{message_transport_type}, 'email', 'When FallbackToSMSIfNoEmail syspref is enabled the suggestion message_transport_type is email if the borrower has an email');
265
266 {
267     # Hiding the expected warning displayed by DBI
268     # DBD::mysql::st execute failed: Incorrect date value: 'invalid date!' for column 'manageddate'
269     local *STDERR;
270     open STDERR, '>', '/dev/null';
271
272     $mod_suggestion4->{manageddate} = 'invalid date!';
273     ModSuggestion($mod_suggestion4);
274     $messages = C4::Letters::GetQueuedMessages({
275         borrowernumber => $borrowernumber2
276     });
277
278     close STDERR;
279     is (scalar(@$messages), 1, 'No new letter should have been generated if the update raised an error');
280 }
281
282 is( GetSuggestionInfo(), undef, 'GetSuggestionInfo without the suggestion id returns undef' );
283 $suggestion = GetSuggestionInfo($my_suggestionid);
284 is( $suggestion->{suggestionid}, $my_suggestionid, 'GetSuggestionInfo returns the suggestion id correctly' );
285 is( $suggestion->{title}, $mod_suggestion1->{title}, 'GetSuggestionInfo returns the title correctly' );
286 is( $suggestion->{author}, $mod_suggestion1->{author}, 'GetSuggestionInfo returns the author correctly' );
287 is( $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, 'GetSuggestionInfo returns the publisher code correctly' );
288 is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfo returns the borrower number correctly' );
289 is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'GetSuggestionInfo returns the biblio number correctly' );
290 is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionInfo returns the status correctly' );
291 is( $suggestion->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionInfo returns the surname correctly' );
292 is( $suggestion->{firstnamesuggestedby}, $member->{firstname}, 'GetSuggestionInfo returns the firstname correctly' );
293 is( $suggestion->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfo returns the borrower number correctly' );
294
295
296 is( GetSuggestionFromBiblionumber(), undef, 'GetSuggestionFromBiblionumber without the biblio number returns undef' );
297 is( GetSuggestionFromBiblionumber(2), undef, 'GetSuggestionFromBiblionumber with an invalid biblio number returns undef' );
298 is( GetSuggestionFromBiblionumber($biblio_1->biblionumber), $my_suggestionid, 'GetSuggestionFromBiblionumber functions correctly' );
299
300
301 is( GetSuggestionInfoFromBiblionumber(), undef, 'GetSuggestionInfoFromBiblionumber without the biblio number returns undef' );
302 is( GetSuggestionInfoFromBiblionumber(2), undef, 'GetSuggestionInfoFromBiblionumber with an invalid biblio number returns undef' );
303 $suggestion = GetSuggestionInfoFromBiblionumber($biblio_1->biblionumber);
304 is( $suggestion->{suggestionid}, $my_suggestionid, 'GetSuggestionInfoFromBiblionumber returns the suggestion id correctly' );
305 is( $suggestion->{title}, $mod_suggestion1->{title}, 'GetSuggestionInfoFromBiblionumber returns the title correctly' );
306 is( $suggestion->{author}, $mod_suggestion1->{author}, 'GetSuggestionInfoFromBiblionumber returns the author correctly' );
307 is( $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, 'GetSuggestionInfoFromBiblionumber returns the publisher code correctly' );
308 is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfoFromBiblionumber returns the borrower number correctly' );
309 is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'GetSuggestionInfoFromBiblionumber returns the biblio number correctly' );
310 is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionInfoFromBiblionumber returns the status correctly' );
311 is( $suggestion->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionInfoFromBiblionumber returns the surname correctly' );
312 is( $suggestion->{firstnamesuggestedby}, $member->{firstname}, 'GetSuggestionInfoFromBiblionumber returns the firstname correctly' );
313 is( $suggestion->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfoFromBiblionumeber returns the borrower number correctly' );
314
315
316 my $suggestions = GetSuggestionByStatus();
317 is( @$suggestions, 0, 'GetSuggestionByStatus without the status returns an empty array' );
318 $suggestions = GetSuggestionByStatus('CHECKED');
319 is( @$suggestions, 2, 'GetSuggestionByStatus returns the correct number of suggestions' );
320 is( $suggestions->[0]->{suggestionid}, $my_suggestionid, 'GetSuggestionByStatus returns the suggestion id correctly' );
321 is( $suggestions->[0]->{title}, $mod_suggestion1->{title}, 'GetSuggestionByStatus returns the title correctly' );
322 is( $suggestions->[0]->{author}, $mod_suggestion1->{author}, 'GetSuggestionByStatus returns the author correctly' );
323 is( $suggestions->[0]->{publishercode}, $mod_suggestion1->{publishercode}, 'GetSuggestionByStatus returns the publisher code correctly' );
324 is( $suggestions->[0]->{suggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionByStatus returns the borrower number correctly' );
325 is( $suggestions->[0]->{biblionumber}, $my_suggestion->{biblionumber}, 'GetSuggestionByStatus returns the biblio number correctly' );
326 is( $suggestions->[0]->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionByStatus returns the status correctly' );
327 is( $suggestions->[0]->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionByStatus returns the surname correctly' );
328 is( $suggestions->[0]->{firstnamesuggestedby}, $member->{firstname}, 'GetSuggestionByStatus returns the firstname correctly' );
329 is( $suggestions->[0]->{branchcodesuggestedby}, $member->{branchcode}, 'GetSuggestionByStatus returns the branch code correctly' );
330 is( $suggestions->[0]->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionByStatus returns the borrower number correctly' );
331 is( $suggestions->[0]->{categorycodesuggestedby}, $member->{categorycode}, 'GetSuggestionByStatus returns the category code correctly' );
332
333
334 is( ConnectSuggestionAndBiblio(), '0E0', 'ConnectSuggestionAndBiblio without arguments returns 0E0' );
335 my $biblio_2 = $builder->build_object({ class => 'Koha::Biblios' });
336 my $connect_suggestion_and_biblio = ConnectSuggestionAndBiblio($my_suggestionid, $biblio_2->biblionumber);
337 is( $connect_suggestion_and_biblio, '1', 'ConnectSuggestionAndBiblio returns 1' );
338 $suggestion = GetSuggestion($my_suggestionid);
339 is( $suggestion->{biblionumber}, $biblio_2->biblionumber, 'ConnectSuggestionAndBiblio updates the biblio number correctly' );
340
341 my $del_suggestion = {
342     title => 'my deleted title',
343     STATUS => 'CHECKED',
344     suggestedby => $borrowernumber,
345 };
346 my $del_suggestion_object = Koha::Suggestion->new($del_suggestion)->store();
347 my $del_suggestionid = $del_suggestion_object->id;
348
349 is( DelSuggestion(), '0E0', 'DelSuggestion without arguments returns 0E0' );
350 is( DelSuggestion($borrowernumber), '', 'DelSuggestion without the suggestion id returns an empty string' );
351 is( DelSuggestion(undef, $my_suggestionid), '', 'DelSuggestion with an invalid borrower number returns an empty string' );
352 $suggestion = DelSuggestion($borrowernumber, $my_suggestionid);
353 is( $suggestion, 1, 'DelSuggestion deletes one suggestion' );
354
355 $suggestions = GetSuggestionByStatus('CHECKED');
356 is( @$suggestions, 2, 'DelSuggestion deletes one suggestion' );
357 is( $suggestions->[1]->{title}, $del_suggestion->{title}, 'DelSuggestion deletes the correct suggestion' );
358
359 # Test budgetid fk
360 $my_suggestion->{budgetid} = ''; # If budgetid == '', NULL should be set in DB
361 my $my_suggestionid_test_budget_object = Koha::Suggestion->new($my_suggestion)->store;
362 my $my_suggestionid_test_budgetid = $my_suggestionid_test_budget_object->id;
363 $suggestion = GetSuggestion($my_suggestionid_test_budgetid);
364 is( $suggestion->{budgetid}, undef, 'Suggestion Should set budgetid to NULL if equals an empty string' );
365
366 $my_suggestion->{budgetid} = ''; # If budgetid == '', NULL should be set in DB
367 ModSuggestion( $my_suggestion );
368 $suggestion = GetSuggestion($my_suggestionid_test_budgetid);
369 is( $suggestion->{budgetid}, undef, 'Suggestion Should set budgetid to NULL if equals an empty string' );
370
371 my $suggestion2 = {
372     title => "Cuisine d'automne",
373     author => "Catherine",
374     itemtype => "LIV"
375 };
376
377 my $record = MarcRecordFromNewSuggestion($suggestion2);
378
379 is("MARC::Record", ref($record), "MarcRecordFromNewSuggestion should return a MARC::Record object");
380
381 my ($title_tag, $title_subfield) = C4::Biblio::GetMarcFromKohaField('biblio.title', '');
382
383 is($record->field( $title_tag )->subfield( $title_subfield ), "Cuisine d'automne", "Record from suggestion title should be 'Cuisine d'automne'");
384
385 my ($author_tag, $author_subfield) = C4::Biblio::GetMarcFromKohaField('biblio.author', '');
386
387 is($record->field( $author_tag )->subfield( $author_subfield ), "Catherine", "Record from suggestion author should be 'Catherine'");
388
389 subtest 'GetUnprocessedSuggestions' => sub {
390     plan tests => 11;
391     $dbh->do(q|DELETE FROM suggestions|);
392     my $my_suggestionid         = Koha::Suggestion->new($my_suggestion)->store->id;
393     my $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions;
394     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should return 0 if a suggestion has been processed but not linked to a fund' );
395     my $status     = ModSuggestion($mod_suggestion1);
396     my $suggestion = GetSuggestion($my_suggestionid);
397     is( $suggestion->{budgetid}, undef, 'ModSuggestion should set budgetid to NULL if not given' );
398     ModSuggestion( { suggestionid => $my_suggestionid, budgetid => $budget_id } );
399     $suggestion = GetSuggestion($my_suggestionid);
400     is( $suggestion->{budgetid}, $budget_id, 'ModSuggestion should modify budgetid if given' );
401
402     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions;
403     is( scalar(@$unprocessed_suggestions), 1, 'GetUnprocessedSuggestions should return the suggestion if the suggestion is linked to a fund and has not been processed yet' );
404
405     warning_is { ModSuggestion( { suggestionid => $my_suggestionid, STATUS => 'REJECTED' } ) }
406                 'No suggestions REJECTED letter transported by email',
407                 'Warning raised if no REJECTED letter by email';
408     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions;
409     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should return the suggestion if the suggestion is linked to a fund and has not been processed yet' );
410
411     warning_is { ModSuggestion( { suggestionid => $my_suggestionid, STATUS => 'ASKED', suggesteddate => dt_from_string->add_duration( DateTime::Duration->new( days => -4 ) ) } ); }
412                 'No suggestions ASKED letter transported by email',
413                 'Warning raised if no ASKED letter by email';
414     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions;
415     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should use 0 as default value for days' );
416     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions(4);
417     is( scalar(@$unprocessed_suggestions), 1, 'GetUnprocessedSuggestions should return the suggestion suggested 4 days ago' );
418     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions(3);
419     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should not return the suggestion, it has not been suggested 3 days ago' );
420     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions(5);
421     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should not return the suggestion, it has not been suggested 5 days ago' );
422 };
423
424 subtest 'DelSuggestionsOlderThan' => sub {
425     plan tests => 6;
426
427     Koha::Suggestions->delete;
428
429     # Add four suggestions; note that STATUS needs uppercase (FIXME)
430     my $d1 = output_pref({ dt => dt_from_string->add(days => -2), dateformat => 'sql' });
431     my $d2 = output_pref({ dt => dt_from_string->add(days => -4), dateformat => 'sql' });
432     my $sugg01 = $builder->build({ source => 'Suggestion', value => { manageddate => $d1, date => $d2, STATUS => 'ASKED' }});
433     my $sugg02 = $builder->build({ source => 'Suggestion', value => { manageddate => $d1, date => $d2, STATUS => 'CHECKED' }});
434     my $sugg03 = $builder->build({ source => 'Suggestion', value => { manageddate => $d2, date => $d2, STATUS => 'ASKED' }});
435     my $sugg04 = $builder->build({ source => 'Suggestion', value => { manageddate => $d2, date => $d2, STATUS => 'ACCEPTED' }});
436
437     # Test no parameter: should do nothing
438     C4::Suggestions::DelSuggestionsOlderThan();
439     is( Koha::Suggestions->count, 4, 'No suggestions deleted' );
440     # Test zero: should do nothing too
441     C4::Suggestions::DelSuggestionsOlderThan(0);
442     is( Koha::Suggestions->count, 4, 'No suggestions deleted again' );
443     # Test negative value
444     C4::Suggestions::DelSuggestionsOlderThan(-1);
445     is( Koha::Suggestions->count, 4, 'No suggestions deleted for -1' );
446
447     # Test positive values
448     C4::Suggestions::DelSuggestionsOlderThan(5);
449     is( Koha::Suggestions->count, 4, 'No suggestions>5d deleted' );
450     C4::Suggestions::DelSuggestionsOlderThan(3);
451     is( Koha::Suggestions->count, 3, '1 suggestions>3d deleted' );
452     C4::Suggestions::DelSuggestionsOlderThan(1);
453     is( Koha::Suggestions->count, 2, '1 suggestions>1d deleted' );
454 };
455
456 subtest 'EmailPurchaseSuggestions' => sub {
457     plan tests => 11;
458
459     $dbh->do(q|DELETE FROM message_queue|);
460
461     t::lib::Mocks::mock_preference( "KohaAdminEmailAddress",
462         'noreply@hosting.com' );
463
464     # EmailPurchaseSuggestions set to disabled
465     t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "0" );
466     Koha::Suggestion->new($my_suggestion)->store;
467     my $newsuggestions_messages = C4::Letters::GetQueuedMessages(
468         {
469             borrowernumber => $borrowernumber
470         }
471     );
472     is( @$newsuggestions_messages, 0,
473         'New suggestion does not send an email when EmailPurchaseSuggestions disabled' );
474
475     # EmailPurchaseSuggestions set to BranchEmailAddress
476     t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "BranchEmailAddress" );
477     t::lib::Mocks::mock_preference( "ReplytoDefault", "" );
478     t::lib::Mocks::mock_preference( "EmailAddressForSuggestions", "" );
479     Koha::Libraries->find('CPL')->update( { branchemail => '', branchreplyto => '' } );
480     Koha::Suggestion->new($my_suggestion)->store;
481
482     t::lib::Mocks::mock_preference( "ReplytoDefault", 'library@b.c' );
483     Koha::Suggestion->new($my_suggestion)->store;
484
485     Koha::Libraries->find('CPL')->update( { branchemail => 'branchemail@hosting.com' } );
486     Koha::Suggestion->new($my_suggestion)->store;
487
488     Koha::Libraries->find('CPL')->update( { branchreplyto => 'branchemail@b.c' } );
489     Koha::Suggestion->new($my_suggestion)->store;
490
491     $newsuggestions_messages = C4::Letters::GetQueuedMessages(
492         {
493             borrowernumber => $borrowernumber
494         }
495     );
496     isnt( @$newsuggestions_messages, 0, 'New suggestions sends an email wne EmailPurchaseSuggestions enabled' );
497     my $message1 =
498       C4::Letters::GetMessage( $newsuggestions_messages->[0]->{message_id} );
499     is( $message1->{to_address}, 'noreply@hosting.com',
500 'BranchEmailAddress falls back to KohaAdminEmailAddress if branchreplyto, branchemail and ReplytoDefault are not set'
501     );
502     my $message2 =
503       C4::Letters::GetMessage( $newsuggestions_messages->[1]->{message_id} );
504     is( $message2->{to_address}, 'library@b.c',
505 'BranchEmailAddress falls back to ReplytoDefault if neither branchreplyto or branchemail are set'
506     );
507     my $message3 =
508       C4::Letters::GetMessage( $newsuggestions_messages->[2]->{message_id} );
509     is( $message3->{to_address}, 'branchemail@hosting.com',
510 'BranchEmailAddress uses branchemail if branch_replto is not set'
511     );
512     my $message4 =
513       C4::Letters::GetMessage( $newsuggestions_messages->[3]->{message_id} );
514     is( $message4->{to_address}, 'branchemail@b.c',
515 'BranchEmailAddress uses branchreplyto in preference to branchemail when set'
516     );
517
518     # EmailPurchaseSuggestions set to KohaAdminEmailAddress
519     t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions",
520         "KohaAdminEmailAddress" );
521
522     t::lib::Mocks::mock_preference( "ReplytoDefault", undef );
523     Koha::Suggestion->new($my_suggestion)->store;
524
525     t::lib::Mocks::mock_preference( "ReplytoDefault", 'library@b.c' );
526     Koha::Suggestion->new($my_suggestion)->store;
527
528     $newsuggestions_messages = C4::Letters::GetQueuedMessages(
529         {
530             borrowernumber => $borrowernumber
531         }
532     );
533     my $message5 =
534       C4::Letters::GetMessage( $newsuggestions_messages->[4]->{message_id} );
535     is( $message5->{to_address},
536         'noreply@hosting.com', 'KohaAdminEmailAddress uses KohaAdminEmailAddress when ReplytoDefault is not set' );
537     my $message6 =
538       C4::Letters::GetMessage( $newsuggestions_messages->[5]->{message_id} );
539     is( $message6->{to_address},
540         'library@b.c', 'KohaAdminEmailAddress uses ReplytoDefualt when ReplytoDefault is set' );
541
542     # EmailPurchaseSuggestions set to EmailAddressForSuggestions
543     t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions",
544         "EmailAddressForSuggestions" );
545
546     t::lib::Mocks::mock_preference( "ReplytoDefault", undef );
547     Koha::Suggestion->new($my_suggestion)->store;
548
549     t::lib::Mocks::mock_preference( "ReplytoDefault", 'library@b.c' );
550     Koha::Suggestion->new($my_suggestion)->store;
551
552     t::lib::Mocks::mock_preference( "EmailAddressForSuggestions",
553         'suggestions@b.c' );
554     Koha::Suggestion->new($my_suggestion)->store;
555
556     $newsuggestions_messages = C4::Letters::GetQueuedMessages(
557         {
558             borrowernumber => $borrowernumber
559         }
560     );
561     my $message7 =
562       C4::Letters::GetMessage( $newsuggestions_messages->[6]->{message_id} );
563     is( $message7->{to_address},
564         'noreply@hosting.com', 'EmailAddressForSuggestions uses KohaAdminEmailAddress when neither EmailAddressForSuggestions or ReplytoDefault are set' );
565
566     my $message8 =
567       C4::Letters::GetMessage( $newsuggestions_messages->[7]->{message_id} );
568     is( $message8->{to_address},
569         'library@b.c', 'EmailAddressForSuggestions uses ReplytoDefault when EmailAddressForSuggestions is not set' );
570
571     my $message9 =
572       C4::Letters::GetMessage( $newsuggestions_messages->[8]->{message_id} );
573     is( $message9->{to_address},
574         'suggestions@b.c', 'EmailAddressForSuggestions uses EmailAddressForSuggestions when set' );
575 };
576
577 subtest 'ModSuggestion should work on suggestions without a suggester' => sub {
578     plan tests => 2;
579
580     $dbh->do(q|DELETE FROM suggestions|);
581     my $my_suggestionid = Koha::Suggestion->new($my_suggestion_without_suggestedby)->store()->id;
582     $suggestion = GetSuggestion($my_suggestionid);
583     is( $suggestion->{suggestedby}, undef, "Suggestedby is undef" );
584
585     ModSuggestion(
586         {
587             suggestionid => $my_suggestionid,
588             STATUS       => 'CHECKED',
589             note         => "Test note"
590         }
591     );
592     $suggestion = GetSuggestion($my_suggestionid);
593
594     is( $suggestion->{note}, "Test note", "ModSuggestion works on suggestions without a suggester" );
595 };
596
597 subtest 'Suggestion with ISBN' => sub {
598     my $suggestion_with_isbn = {
599         isbn     => '1940997232',
600         title    => "The Clouds",
601         author   => "Aristophanes",
602     };
603     my $record = MarcRecordFromNewSuggestion( $suggestion_with_isbn );
604     is("MARC::Record", ref($record), "MarcRecordFromNewSuggestion should return a MARC::Record object");
605
606     my ($isbn_tag, $isbn_subfield) = C4::Biblio::GetMarcFromKohaField('biblioitems.isbn', '');
607     is($record->field( $isbn_tag )->subfield( $isbn_subfield ), "1940997232", "ISBN Record from suggestion ISBN should be '1940997232'");
608
609     my ($issn_tag, $issn_subfield) = C4::Biblio::GetMarcFromKohaField('biblioitems.issn', '');
610     is($record->field( $issn_tag )->subfield( $issn_subfield ), "1940997232", "ISSN Record from suggestion ISBN should also be '1940997232'");
611
612     my ($title_tag, $title_subfield) = C4::Biblio::GetMarcFromKohaField('biblio.title', '');
613     is($record->field( $title_tag), undef, "Record from suggestion title should be empty");
614
615     my ($author_tag, $author_subfield) = C4::Biblio::GetMarcFromKohaField('biblio.author', '');
616     is($record->field( $author_tag), undef, "Record from suggestion author should be empty");
617 };
618
619 $schema->storage->txn_rollback;