Bug 17600: Standardize our EXPORT_OK
[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 => 106;
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( NewSuggestion GetSuggestion ModSuggestion GetSuggestionInfo GetSuggestionFromBiblionumber GetSuggestionInfoFromBiblionumber GetSuggestionByStatus ConnectSuggestionAndBiblio SearchSuggestion 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_suggestionid = NewSuggestion($my_suggestion);
163 isnt( $my_suggestionid, 0, 'NewSuggestion returns an not null id' );
164 my $my_suggestionid_with_budget = NewSuggestion($my_suggestion_with_budget);
165
166 is( GetSuggestion(), undef, 'GetSuggestion without the suggestion id returns undef' );
167 my $suggestion = GetSuggestion($my_suggestionid);
168 is( $suggestion->{title}, $my_suggestion->{title}, 'NewSuggestion stores the title correctly' );
169 is( $suggestion->{author}, $my_suggestion->{author}, 'NewSuggestion stores the author correctly' );
170 is( $suggestion->{publishercode}, $my_suggestion->{publishercode}, 'NewSuggestion stores the publishercode correctly' );
171 is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'NewSuggestion stores the borrower number correctly' );
172 is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'NewSuggestion stores the biblio number correctly' );
173 is( $suggestion->{STATUS}, 'ASKED', 'NewSuggestion stores a suggestion with the status ASKED by default' );
174 is( $suggestion->{managedby}, undef, 'NewSuggestion stores empty string as undef for non existent foreign key (integer)' );
175 is( $suggestion->{manageddate}, undef, 'NewSuggestion stores empty string as undef for date' );
176 is( $suggestion->{budgetid}, undef, 'NewSuggestion should set budgetid to NULL if not given' );
177
178 is( ModSuggestion(), undef, 'ModSuggestion without the suggestion returns undef' );
179 my $mod_suggestion1 = {
180     title         => 'my modified title',
181     author        => 'my modified author',
182     publishercode => 'my modified publishercode',
183     managedby     => '',
184     manageddate   => '',
185 };
186 my $status = ModSuggestion($mod_suggestion1);
187 is( $status, undef, 'ModSuggestion without the suggestion id returns undef' );
188
189 $mod_suggestion1->{suggestionid} = $my_suggestionid;
190 $status = ModSuggestion($mod_suggestion1);
191 is( $status, 1, 'ModSuggestion modifies one entry' );
192 $suggestion = GetSuggestion($my_suggestionid);
193 is( $suggestion->{title}, $mod_suggestion1->{title}, 'ModSuggestion modifies the title  correctly' );
194 is( $suggestion->{author}, $mod_suggestion1->{author}, 'ModSuggestion modifies the author correctly' );
195 is( $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, 'ModSuggestion modifies the publishercode correctly' );
196 is( $suggestion->{managedby}, undef, 'ModSuggestion stores empty string as undef for non existent foreign key (integer)' );
197 is( $suggestion->{manageddate}, undef, 'ModSuggestion stores empty string as undef for date' );
198 isnt( $suggestion->{accepteddate}, undef, 'ModSuggestion does not update a non given date value' );
199 is( $suggestion->{note}, 'my note', 'ModSuggestion should not erase data if not given' );
200
201 my $messages = C4::Letters::GetQueuedMessages({
202     borrowernumber => $borrowernumber
203 });
204 is( @$messages, 0, 'ModSuggestions does not send an email if the status is not updated' );
205
206 my $mod_suggestion2 = {
207     STATUS       => 'STALLED',
208     suggestionid => $my_suggestionid,
209 };
210 warning_is { $status = ModSuggestion($mod_suggestion2) }
211            "No suggestions STALLED letter transported by email",
212            "ModSuggestion status warning is correct";
213 is( $status, 1, "ModSuggestion Status OK");
214
215 my $mod_suggestion3 = {
216     STATUS       => 'CHECKED',
217     suggestionid => $my_suggestionid,
218 };
219
220 #Test the message_transport_type of suggestion notices
221
222 #Check the message_transport_type when the 'FallbackToSMSIfNoEmail' syspref is disabled
223 t::lib::Mocks::mock_preference( 'FallbackToSMSIfNoEmail', 0 );
224 $status = ModSuggestion($mod_suggestion3);
225 is( $status, 1, 'ModSuggestion modifies one entry' );
226 $suggestion = GetSuggestion($my_suggestionid);
227 is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'ModSuggestion modifies the status correctly' );
228 $messages = C4::Letters::GetQueuedMessages({
229     borrowernumber => $borrowernumber
230 });
231 is( @$messages, 1, 'ModSuggestion sends an email if the status is updated' );
232 is ($messages->[0]->{message_transport_type}, 'email', 'When FallbackToSMSIfNoEmail syspref is disabled the suggestion message_transport_type is always email');
233
234 #Check the message_transport_type when the 'FallbackToSMSIfNoEmail' syspref is enabled and the borrower has a smsalertnumber and no email
235 t::lib::Mocks::mock_preference( 'FallbackToSMSIfNoEmail', 1 );
236 ModSuggestion($mod_suggestion3);
237 $messages = C4::Letters::GetQueuedMessages({
238     borrowernumber => $borrowernumber
239 });
240 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');
241
242 #Make a new suggestion for a borrower with defined email and no smsalertnumber
243 my $my_suggestion_2_id = NewSuggestion($my_suggestion_with_budget2);
244
245 #Check the message_transport_type when the 'FallbackToSMSIfNoEmail' syspref is enabled and the borrower has a defined email and no smsalertnumber
246 t::lib::Mocks::mock_preference( 'FallbackToSMSIfNoEmail', 1 );
247 my $mod_suggestion4 = {
248     STATUS       => 'CHECKED',
249     suggestionid => $my_suggestion_2_id,
250 };
251 ModSuggestion($mod_suggestion4);
252 $messages = C4::Letters::GetQueuedMessages({
253     borrowernumber => $borrowernumber2
254 });
255 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');
256
257 {
258     # Hiding the expected warning displayed by DBI
259     # DBD::mysql::st execute failed: Incorrect date value: 'invalid date!' for column 'manageddate'
260     local *STDERR;
261     open STDERR, '>', '/dev/null';
262
263     $mod_suggestion4->{manageddate} = 'invalid date!';
264     ModSuggestion($mod_suggestion4);
265     $messages = C4::Letters::GetQueuedMessages({
266         borrowernumber => $borrowernumber2
267     });
268
269     close STDERR;
270     is (scalar(@$messages), 1, 'No new letter should have been generated if the update raised an error');
271 }
272
273 is( GetSuggestionInfo(), undef, 'GetSuggestionInfo without the suggestion id returns undef' );
274 $suggestion = GetSuggestionInfo($my_suggestionid);
275 is( $suggestion->{suggestionid}, $my_suggestionid, 'GetSuggestionInfo returns the suggestion id correctly' );
276 is( $suggestion->{title}, $mod_suggestion1->{title}, 'GetSuggestionInfo returns the title correctly' );
277 is( $suggestion->{author}, $mod_suggestion1->{author}, 'GetSuggestionInfo returns the author correctly' );
278 is( $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, 'GetSuggestionInfo returns the publisher code correctly' );
279 is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfo returns the borrower number correctly' );
280 is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'GetSuggestionInfo returns the biblio number correctly' );
281 is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionInfo returns the status correctly' );
282 is( $suggestion->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionInfo returns the surname correctly' );
283 is( $suggestion->{firstnamesuggestedby}, $member->{firstname}, 'GetSuggestionInfo returns the firstname correctly' );
284 is( $suggestion->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfo returns the borrower number correctly' );
285
286
287 is( GetSuggestionFromBiblionumber(), undef, 'GetSuggestionFromBiblionumber without the biblio number returns undef' );
288 is( GetSuggestionFromBiblionumber(2), undef, 'GetSuggestionFromBiblionumber with an invalid biblio number returns undef' );
289 is( GetSuggestionFromBiblionumber($biblio_1->biblionumber), $my_suggestionid, 'GetSuggestionFromBiblionumber functions correctly' );
290
291
292 is( GetSuggestionInfoFromBiblionumber(), undef, 'GetSuggestionInfoFromBiblionumber without the biblio number returns undef' );
293 is( GetSuggestionInfoFromBiblionumber(2), undef, 'GetSuggestionInfoFromBiblionumber with an invalid biblio number returns undef' );
294 $suggestion = GetSuggestionInfoFromBiblionumber($biblio_1->biblionumber);
295 is( $suggestion->{suggestionid}, $my_suggestionid, 'GetSuggestionInfoFromBiblionumber returns the suggestion id correctly' );
296 is( $suggestion->{title}, $mod_suggestion1->{title}, 'GetSuggestionInfoFromBiblionumber returns the title correctly' );
297 is( $suggestion->{author}, $mod_suggestion1->{author}, 'GetSuggestionInfoFromBiblionumber returns the author correctly' );
298 is( $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, 'GetSuggestionInfoFromBiblionumber returns the publisher code correctly' );
299 is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfoFromBiblionumber returns the borrower number correctly' );
300 is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'GetSuggestionInfoFromBiblionumber returns the biblio number correctly' );
301 is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionInfoFromBiblionumber returns the status correctly' );
302 is( $suggestion->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionInfoFromBiblionumber returns the surname correctly' );
303 is( $suggestion->{firstnamesuggestedby}, $member->{firstname}, 'GetSuggestionInfoFromBiblionumber returns the firstname correctly' );
304 is( $suggestion->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfoFromBiblionumeber returns the borrower number correctly' );
305
306
307 my $suggestions = GetSuggestionByStatus();
308 is( @$suggestions, 0, 'GetSuggestionByStatus without the status returns an empty array' );
309 $suggestions = GetSuggestionByStatus('CHECKED');
310 is( @$suggestions, 2, 'GetSuggestionByStatus returns the correct number of suggestions' );
311 is( $suggestions->[0]->{suggestionid}, $my_suggestionid, 'GetSuggestionByStatus returns the suggestion id correctly' );
312 is( $suggestions->[0]->{title}, $mod_suggestion1->{title}, 'GetSuggestionByStatus returns the title correctly' );
313 is( $suggestions->[0]->{author}, $mod_suggestion1->{author}, 'GetSuggestionByStatus returns the author correctly' );
314 is( $suggestions->[0]->{publishercode}, $mod_suggestion1->{publishercode}, 'GetSuggestionByStatus returns the publisher code correctly' );
315 is( $suggestions->[0]->{suggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionByStatus returns the borrower number correctly' );
316 is( $suggestions->[0]->{biblionumber}, $my_suggestion->{biblionumber}, 'GetSuggestionByStatus returns the biblio number correctly' );
317 is( $suggestions->[0]->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionByStatus returns the status correctly' );
318 is( $suggestions->[0]->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionByStatus returns the surname correctly' );
319 is( $suggestions->[0]->{firstnamesuggestedby}, $member->{firstname}, 'GetSuggestionByStatus returns the firstname correctly' );
320 is( $suggestions->[0]->{branchcodesuggestedby}, $member->{branchcode}, 'GetSuggestionByStatus returns the branch code correctly' );
321 is( $suggestions->[0]->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionByStatus returns the borrower number correctly' );
322 is( $suggestions->[0]->{categorycodesuggestedby}, $member->{categorycode}, 'GetSuggestionByStatus returns the category code correctly' );
323
324
325 is( ConnectSuggestionAndBiblio(), '0E0', 'ConnectSuggestionAndBiblio without arguments returns 0E0' );
326 my $biblio_2 = $builder->build_object({ class => 'Koha::Biblios' });
327 my $connect_suggestion_and_biblio = ConnectSuggestionAndBiblio($my_suggestionid, $biblio_2->biblionumber);
328 is( $connect_suggestion_and_biblio, '1', 'ConnectSuggestionAndBiblio returns 1' );
329 $suggestion = GetSuggestion($my_suggestionid);
330 is( $suggestion->{biblionumber}, $biblio_2->biblionumber, 'ConnectSuggestionAndBiblio updates the biblio number correctly' );
331
332 my $search_suggestion = SearchSuggestion();
333 is( @$search_suggestion, 3, 'SearchSuggestion without arguments returns all suggestions' );
334
335 $search_suggestion = SearchSuggestion({
336     title => $mod_suggestion1->{title},
337 });
338 is( @$search_suggestion, 1, 'SearchSuggestion returns the correct number of suggestions' );
339 $search_suggestion = SearchSuggestion({
340     title => 'another title',
341 });
342 is( @$search_suggestion, 0, 'SearchSuggestion returns the correct number of suggestions' );
343
344 $search_suggestion = SearchSuggestion({
345     author => $mod_suggestion1->{author},
346 });
347 is( @$search_suggestion, 1, 'SearchSuggestion returns the correct number of suggestions' );
348 $search_suggestion = SearchSuggestion({
349     author => 'another author',
350 });
351 is( @$search_suggestion, 0, 'SearchSuggestion returns the correct number of suggestions' );
352
353 $search_suggestion = SearchSuggestion({
354     publishercode => $mod_suggestion1->{publishercode},
355 });
356 is( @$search_suggestion, 1, 'SearchSuggestion returns the correct number of suggestions' );
357 $search_suggestion = SearchSuggestion({
358     publishercode => 'another publishercode',
359 });
360 is( @$search_suggestion, 0, 'SearchSuggestion returns the correct number of suggestions' );
361
362 $search_suggestion = SearchSuggestion({
363     STATUS => $mod_suggestion3->{STATUS},
364 });
365 is( @$search_suggestion, 2, 'SearchSuggestion returns the correct number of suggestions' );
366
367 $search_suggestion = SearchSuggestion({
368     STATUS => q||
369 });
370 is( @$search_suggestion, 0, 'SearchSuggestion should not return all suggestions if we want the suggestions with a STATUS=""' );
371 $search_suggestion = SearchSuggestion({
372     STATUS => 'REJECTED',
373 });
374 is( @$search_suggestion, 0, 'SearchSuggestion returns the correct number of suggestions' );
375
376 $search_suggestion = SearchSuggestion({
377     budgetid => '',
378 });
379 is( @$search_suggestion, 3, 'SearchSuggestion (budgetid = "") returns the correct number of suggestions' );
380 $search_suggestion = SearchSuggestion({
381     budgetid => $budget_id,
382 });
383 is( @$search_suggestion, 2, 'SearchSuggestion (budgetid = $budgetid) returns the correct number of suggestions' );
384 $search_suggestion = SearchSuggestion({
385     budgetid => '__NONE__',
386 });
387 is( @$search_suggestion, 1, 'SearchSuggestion (budgetid = "__NONE__") returns the correct number of suggestions' );
388 $search_suggestion = SearchSuggestion({
389     budgetid => '__ANY__',
390 });
391 is( @$search_suggestion, 3, 'SearchSuggestion (budgetid = "__ANY__") returns the correct number of suggestions' );
392
393 $search_suggestion = SearchSuggestion({ budgetid => $budget_id });
394 is( @$search_suggestion[0]->{budget_name}, GetBudget($budget_id)->{budget_name}, 'SearchSuggestion returns the correct budget name');
395 $search_suggestion = SearchSuggestion({ budgetid => "__NONE__" });
396 is( @$search_suggestion[0]->{budget_name}, undef, 'SearchSuggestion returns the correct budget name');
397
398
399 my $del_suggestion = {
400     title => 'my deleted title',
401     STATUS => 'CHECKED',
402     suggestedby => $borrowernumber,
403 };
404 my $del_suggestionid = NewSuggestion($del_suggestion);
405
406 is( DelSuggestion(), '0E0', 'DelSuggestion without arguments returns 0E0' );
407 is( DelSuggestion($borrowernumber), '', 'DelSuggestion without the suggestion id returns an empty string' );
408 is( DelSuggestion(undef, $my_suggestionid), '', 'DelSuggestion with an invalid borrower number returns an empty string' );
409 $suggestion = DelSuggestion($borrowernumber, $my_suggestionid);
410 is( $suggestion, 1, 'DelSuggestion deletes one suggestion' );
411
412 $suggestions = GetSuggestionByStatus('CHECKED');
413 is( @$suggestions, 2, 'DelSuggestion deletes one suggestion' );
414 is( $suggestions->[1]->{title}, $del_suggestion->{title}, 'DelSuggestion deletes the correct suggestion' );
415
416 # Test budgetid fk
417 $my_suggestion->{budgetid} = ''; # If budgetid == '', NULL should be set in DB
418 my $my_suggestionid_test_budgetid = NewSuggestion($my_suggestion);
419 $suggestion = GetSuggestion($my_suggestionid_test_budgetid);
420 is( $suggestion->{budgetid}, undef, 'NewSuggestion Should set budgetid to NULL if equals an empty string' );
421
422 $my_suggestion->{budgetid} = ''; # If budgetid == '', NULL should be set in DB
423 ModSuggestion( $my_suggestion );
424 $suggestion = GetSuggestion($my_suggestionid_test_budgetid);
425 is( $suggestion->{budgetid}, undef, 'NewSuggestion Should set budgetid to NULL if equals an empty string' );
426
427 my $suggestion2 = {
428     title => "Cuisine d'automne",
429     author => "Catherine",
430     itemtype => "LIV"
431 };
432
433 my $record = MarcRecordFromNewSuggestion($suggestion2);
434
435 is("MARC::Record", ref($record), "MarcRecordFromNewSuggestion should return a MARC::Record object");
436
437 my ($title_tag, $title_subfield) = C4::Biblio::GetMarcFromKohaField('biblio.title', '');
438
439 is($record->field( $title_tag )->subfield( $title_subfield ), "Cuisine d'automne", "Record from suggestion title should be 'Cuisine d'automne'");
440
441 my ($author_tag, $author_subfield) = C4::Biblio::GetMarcFromKohaField('biblio.author', '');
442
443 is($record->field( $author_tag )->subfield( $author_subfield ), "Catherine", "Record from suggestion author should be 'Catherine'");
444
445 subtest 'GetUnprocessedSuggestions' => sub {
446     plan tests => 11;
447     $dbh->do(q|DELETE FROM suggestions|);
448     my $my_suggestionid         = NewSuggestion($my_suggestion);
449     my $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions;
450     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should return 0 if a suggestion has been processed but not linked to a fund' );
451     my $status     = ModSuggestion($mod_suggestion1);
452     my $suggestion = GetSuggestion($my_suggestionid);
453     is( $suggestion->{budgetid}, undef, 'ModSuggestion should set budgetid to NULL if not given' );
454     ModSuggestion( { suggestionid => $my_suggestionid, budgetid => $budget_id } );
455     $suggestion = GetSuggestion($my_suggestionid);
456     is( $suggestion->{budgetid}, $budget_id, 'ModSuggestion should modify budgetid if given' );
457
458     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions;
459     is( scalar(@$unprocessed_suggestions), 1, 'GetUnprocessedSuggestions should return the suggestion if the suggestion is linked to a fund and has not been processed yet' );
460
461     warning_is { ModSuggestion( { suggestionid => $my_suggestionid, STATUS => 'REJECTED' } ) }
462                 'No suggestions REJECTED letter transported by email',
463                 'Warning raised if no REJECTED letter by email';
464     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions;
465     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should return the suggestion if the suggestion is linked to a fund and has not been processed yet' );
466
467     warning_is { ModSuggestion( { suggestionid => $my_suggestionid, STATUS => 'ASKED', suggesteddate => dt_from_string->add_duration( DateTime::Duration->new( days => -4 ) ) } ); }
468                 'No suggestions ASKED letter transported by email',
469                 'Warning raised if no ASKED letter by email';
470     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions;
471     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should use 0 as default value for days' );
472     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions(4);
473     is( scalar(@$unprocessed_suggestions), 1, 'GetUnprocessedSuggestions should return the suggestion suggested 4 days ago' );
474     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions(3);
475     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should not return the suggestion, it has not been suggested 3 days ago' );
476     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions(5);
477     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should not return the suggestion, it has not been suggested 5 days ago' );
478 };
479
480 subtest 'DelSuggestionsOlderThan' => sub {
481     plan tests => 6;
482
483     Koha::Suggestions->delete;
484
485     # Add four suggestions; note that STATUS needs uppercase (FIXME)
486     my $d1 = output_pref({ dt => dt_from_string->add(days => -2), dateformat => 'sql' });
487     my $d2 = output_pref({ dt => dt_from_string->add(days => -4), dateformat => 'sql' });
488     my $sugg01 = $builder->build({ source => 'Suggestion', value => { date => $d1, STATUS => 'ASKED' }});
489     my $sugg02 = $builder->build({ source => 'Suggestion', value => { date => $d1, STATUS => 'CHECKED' }});
490     my $sugg03 = $builder->build({ source => 'Suggestion', value => { date => $d2, STATUS => 'ASKED' }});
491     my $sugg04 = $builder->build({ source => 'Suggestion', value => { date => $d2, STATUS => 'ACCEPTED' }});
492
493     # Test no parameter: should do nothing
494     C4::Suggestions::DelSuggestionsOlderThan();
495     is( Koha::Suggestions->count, 4, 'No suggestions deleted' );
496     # Test zero: should do nothing too
497     C4::Suggestions::DelSuggestionsOlderThan(0);
498     is( Koha::Suggestions->count, 4, 'No suggestions deleted again' );
499     # Test negative value
500     C4::Suggestions::DelSuggestionsOlderThan(-1);
501     is( Koha::Suggestions->count, 4, 'No suggestions deleted for -1' );
502
503     # Test positive values
504     C4::Suggestions::DelSuggestionsOlderThan(5);
505     is( Koha::Suggestions->count, 4, 'No suggestions>5d deleted' );
506     C4::Suggestions::DelSuggestionsOlderThan(3);
507     is( Koha::Suggestions->count, 3, '1 suggestions>3d deleted' );
508     C4::Suggestions::DelSuggestionsOlderThan(1);
509     is( Koha::Suggestions->count, 2, '1 suggestions>1d deleted' );
510 };
511
512 subtest 'EmailPurchaseSuggestions' => sub {
513     plan tests => 11;
514
515     $dbh->do(q|DELETE FROM message_queue|);
516
517     t::lib::Mocks::mock_preference( "KohaAdminEmailAddress",
518         'noreply@hosting.com' );
519
520     # EmailPurchaseSuggestions set to disabled
521     t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "0" );
522     NewSuggestion($my_suggestion);
523     my $newsuggestions_messages = C4::Letters::GetQueuedMessages(
524         {
525             borrowernumber => $borrowernumber
526         }
527     );
528     is( @$newsuggestions_messages, 0,
529         'NewSuggestions does not send an email when disabled' );
530
531     # EmailPurchaseSuggestions set to BranchEmailAddress
532     t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions",
533         "BranchEmailAddress" );
534     NewSuggestion($my_suggestion);
535
536     t::lib::Mocks::mock_preference( "ReplytoDefault", 'library@b.c' );
537     NewSuggestion($my_suggestion);
538
539     Koha::Libraries->find('CPL')->update( { branchemail => 'branchemail@hosting.com' } );
540     NewSuggestion($my_suggestion);
541
542     Koha::Libraries->find('CPL')->update( { branchreplyto => 'branchemail@b.c' } );
543     NewSuggestion($my_suggestion);
544
545     $newsuggestions_messages = C4::Letters::GetQueuedMessages(
546         {
547             borrowernumber => $borrowernumber
548         }
549     );
550     isnt( @$newsuggestions_messages, 0, 'NewSuggestions sends an email' );
551     my $message1 =
552       C4::Letters::GetMessage( $newsuggestions_messages->[0]->{message_id} );
553     is( $message1->{to_address}, 'noreply@hosting.com',
554 'BranchEmailAddress falls back to KohaAdminEmailAddress if branchreplyto, branchemail and ReplytoDefault are not set'
555     );
556     my $message2 =
557       C4::Letters::GetMessage( $newsuggestions_messages->[1]->{message_id} );
558     is( $message2->{to_address}, 'library@b.c',
559 'BranchEmailAddress falls back to ReplytoDefault if neither branchreplyto or branchemail are set'
560     );
561     my $message3 =
562       C4::Letters::GetMessage( $newsuggestions_messages->[2]->{message_id} );
563     is( $message3->{to_address}, 'branchemail@hosting.com',
564 'BranchEmailAddress uses branchemail if branch_replto is not set'
565     );
566     my $message4 =
567       C4::Letters::GetMessage( $newsuggestions_messages->[3]->{message_id} );
568     is( $message4->{to_address}, 'branchemail@b.c',
569 'BranchEmailAddress uses branchreplyto in preference to branchemail when set'
570     );
571
572     # EmailPurchaseSuggestions set to KohaAdminEmailAddress
573     t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions",
574         "KohaAdminEmailAddress" );
575
576     t::lib::Mocks::mock_preference( "ReplytoDefault", undef );
577     NewSuggestion($my_suggestion);
578
579     t::lib::Mocks::mock_preference( "ReplytoDefault", 'library@b.c' );
580     NewSuggestion($my_suggestion);
581
582     $newsuggestions_messages = C4::Letters::GetQueuedMessages(
583         {
584             borrowernumber => $borrowernumber
585         }
586     );
587     my $message5 =
588       C4::Letters::GetMessage( $newsuggestions_messages->[4]->{message_id} );
589     is( $message5->{to_address},
590         'noreply@hosting.com', 'KohaAdminEmailAddress uses KohaAdminEmailAddress when ReplytoDefault is not set' );
591     my $message6 =
592       C4::Letters::GetMessage( $newsuggestions_messages->[5]->{message_id} );
593     is( $message6->{to_address},
594         'library@b.c', 'KohaAdminEmailAddress uses ReplytoDefualt when ReplytoDefault is set' );
595
596     # EmailPurchaseSuggestions set to EmailAddressForSuggestions
597     t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions",
598         "EmailAddressForSuggestions" );
599
600     t::lib::Mocks::mock_preference( "ReplytoDefault", undef );
601     NewSuggestion($my_suggestion);
602
603     t::lib::Mocks::mock_preference( "ReplytoDefault", 'library@b.c' );
604     NewSuggestion($my_suggestion);
605
606     t::lib::Mocks::mock_preference( "EmailAddressForSuggestions",
607         'suggestions@b.c' );
608     NewSuggestion($my_suggestion);
609
610     $newsuggestions_messages = C4::Letters::GetQueuedMessages(
611         {
612             borrowernumber => $borrowernumber
613         }
614     );
615     my $message7 =
616       C4::Letters::GetMessage( $newsuggestions_messages->[6]->{message_id} );
617     is( $message7->{to_address},
618         'noreply@hosting.com', 'EmailAddressForSuggestions uses KohaAdminEmailAddress when neither EmailAddressForSuggestions or ReplytoDefault are set' );
619
620     my $message8 =
621       C4::Letters::GetMessage( $newsuggestions_messages->[7]->{message_id} );
622     is( $message8->{to_address},
623         'library@b.c', 'EmailAddressForSuggestions uses ReplytoDefault when EmailAddressForSuggestions is not set' );
624
625     my $message9 =
626       C4::Letters::GetMessage( $newsuggestions_messages->[8]->{message_id} );
627     is( $message9->{to_address},
628         'suggestions@b.c', 'EmailAddressForSuggestions uses EmailAddressForSuggestions when set' );
629 };
630
631 subtest 'ModSuggestion should work on suggestions without a suggester' => sub {
632     plan tests => 2;
633
634     $dbh->do(q|DELETE FROM suggestions|);
635     my $my_suggestionid = NewSuggestion($my_suggestion_without_suggestedby);
636     $suggestion = GetSuggestion($my_suggestionid);
637     is( $suggestion->{suggestedby}, undef, "Suggestedby is undef" );
638
639     ModSuggestion(
640         {
641             suggestionid => $my_suggestionid,
642             STATUS       => 'CHECKED',
643             note         => "Test note"
644         }
645     );
646     $suggestion = GetSuggestion($my_suggestionid);
647
648     is( $suggestion->{note}, "Test note", "ModSuggestion works on suggestions without a suggester" );
649 };
650
651 $schema->storage->txn_rollback;