Bug 17132 - Availability search broken when using Elastic
[koha.git] / t / db_dependent / Letters.t
blob9b5c46997cfa8c73e61d0e6b0990e34bead695d2
1 #!/usr/bin/perl
3 # This file is part of Koha.
5 # Copyright (C) 2013 Equinox Software, Inc.
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20 use Modern::Perl;
21 use Test::More tests => 80;
22 use Test::MockModule;
23 use Test::Warn;
25 use MARC::Record;
27 my %mail;
28 my $module = new Test::MockModule('Mail::Sendmail');
29 $module->mock(
30 'sendmail',
31 sub {
32 warn "Fake sendmail";
33 %mail = @_;
37 use_ok('C4::Context');
38 use_ok('C4::Members');
39 use_ok('C4::Acquisition');
40 use_ok('C4::Biblio');
41 use_ok('C4::Bookseller');
42 use_ok('C4::Letters');
43 use t::lib::Mocks;
44 use t::lib::TestBuilder;
45 use Koha::Database;
46 use Koha::DateUtils qw( dt_from_string output_pref );
47 use Koha::Acquisition::Order;
48 use Koha::Acquisition::Bookseller;
49 use Koha::Libraries;
50 my $schema = Koha::Database->schema;
51 $schema->storage->txn_begin();
53 my $builder = t::lib::TestBuilder->new;
54 my $dbh = C4::Context->dbh;
55 $dbh->{RaiseError} = 1;
57 $dbh->do(q|DELETE FROM letter|);
58 $dbh->do(q|DELETE FROM message_queue|);
59 $dbh->do(q|DELETE FROM message_transport_types|);
61 my $library = $builder->build({
62 source => 'Branch',
63 });
64 my $patron_category = $builder->build({ source => 'Category' });
65 my $date = dt_from_string;
66 my $borrowernumber = AddMember(
67 firstname => 'Jane',
68 surname => 'Smith',
69 categorycode => $patron_category,,
70 branchcode => $library->{branchcode},
71 dateofbirth => $date,
74 my $marc_record = MARC::Record->new;
75 my( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' );
77 # GetMessageTransportTypes
78 my $mtts = C4::Letters::GetMessageTransportTypes();
79 is( @$mtts, 0, 'GetMessageTransportTypes returns the correct number of message types' );
81 $dbh->do(q|
82 INSERT INTO message_transport_types( message_transport_type ) VALUES ('email'), ('phone'), ('print'), ('sms')
83 |);
84 $mtts = C4::Letters::GetMessageTransportTypes();
85 is_deeply( $mtts, ['email', 'phone', 'print', 'sms'], 'GetMessageTransportTypes returns all values' );
88 # EnqueueLetter
89 is( C4::Letters::EnqueueLetter(), undef, 'EnqueueLetter without argument returns undef' );
91 my $my_message = {
92 borrowernumber => $borrowernumber,
93 message_transport_type => 'sms',
94 to_address => 'to@example.com',
95 from_address => 'from@example.com',
97 my $message_id = C4::Letters::EnqueueLetter($my_message);
98 is( $message_id, undef, 'EnqueueLetter without the letter argument returns undef' );
100 delete $my_message->{message_transport_type};
101 $my_message->{letter} = {
102 content => 'a message',
103 title => 'message title',
104 metadata => 'metadata',
105 code => 'TEST_MESSAGE',
106 content_type => 'text/plain',
108 $message_id = C4::Letters::EnqueueLetter($my_message);
109 is( $message_id, undef, 'EnqueueLetter without the message type argument argument returns undef' );
111 $my_message->{message_transport_type} = 'sms';
112 $message_id = C4::Letters::EnqueueLetter($my_message);
113 ok(defined $message_id && $message_id > 0, 'new message successfully queued');
116 # GetQueuedMessages
117 my $messages = C4::Letters::GetQueuedMessages();
118 is( @$messages, 1, 'GetQueuedMessages without argument returns all the entries' );
120 $messages = C4::Letters::GetQueuedMessages({ borrowernumber => $borrowernumber });
121 is( @$messages, 1, 'one message stored for the borrower' );
122 is( $messages->[0]->{message_id}, $message_id, 'EnqueueLetter returns the message id correctly' );
123 is( $messages->[0]->{borrowernumber}, $borrowernumber, 'EnqueueLetter stores the borrower number correctly' );
124 is( $messages->[0]->{subject}, $my_message->{letter}->{title}, 'EnqueueLetter stores the subject correctly' );
125 is( $messages->[0]->{content}, $my_message->{letter}->{content}, 'EnqueueLetter stores the content correctly' );
126 is( $messages->[0]->{message_transport_type}, $my_message->{message_transport_type}, 'EnqueueLetter stores the message type correctly' );
127 is( $messages->[0]->{status}, 'pending', 'EnqueueLetter stores the status pending correctly' );
130 # SendQueuedMessages
131 my $messages_processed = C4::Letters::SendQueuedMessages();
132 is($messages_processed, 1, 'all queued messages processed');
134 $messages = C4::Letters::GetQueuedMessages({ borrowernumber => $borrowernumber });
136 $messages->[0]->{status},
137 'failed',
138 'message marked failed if tried to send SMS message for borrower with no smsalertnumber set (bug 11208)'
141 # ResendMessage
142 my $resent = C4::Letters::ResendMessage($messages->[0]->{message_id});
143 my $message = C4::Letters::GetMessage( $messages->[0]->{message_id});
144 is( $resent, 1, 'The message should have been resent' );
145 is($message->{status},'pending', 'ResendMessage sets status to pending correctly (bug 12426)');
146 $resent = C4::Letters::ResendMessage($messages->[0]->{message_id});
147 is( $resent, 0, 'The message should not have been resent again' );
148 $resent = C4::Letters::ResendMessage();
149 is( $resent, undef, 'ResendMessage should return undef if not message_id given' );
151 # GetLetters
152 my $letters = C4::Letters::GetLetters();
153 is( @$letters, 0, 'GetLetters returns the correct number of letters' );
155 my $title = q|<<branches.branchname>> - <<status>>|;
156 my $content = q{Dear <<borrowers.firstname>> <<borrowers.surname>>,
157 According to our current records, you have items that are overdue.Your library does not charge late fines, but please return or renew them at the branch below as soon as possible.
159 <<branches.branchname>>
160 <<branches.branchaddress1>>
161 URL: <<OPACBaseURL>>
163 The following item(s) is/are currently <<status>>:
165 <item> <<count>>. <<items.itemcallnumber>>, Barcode: <<items.barcode>> </item>
167 Thank-you for your prompt attention to this matter.
168 Don't forget your date of birth: <<borrowers.dateofbirth>>.
169 Look at this wonderful biblio timestamp: <<biblio.timestamp>>.
172 $dbh->do( q|INSERT INTO letter(branchcode,module,code,name,is_html,title,content,message_transport_type) VALUES (?,'my module','my code','my name',1,?,?,'email')|, undef, $library->{branchcode}, $title, $content );
173 $letters = C4::Letters::GetLetters();
174 is( @$letters, 1, 'GetLetters returns the correct number of letters' );
175 is( $letters->[0]->{branchcode}, $library->{branchcode}, 'GetLetters gets the branch code correctly' );
176 is( $letters->[0]->{module}, 'my module', 'GetLetters gets the module correctly' );
177 is( $letters->[0]->{code}, 'my code', 'GetLetters gets the code correctly' );
178 is( $letters->[0]->{name}, 'my name', 'GetLetters gets the name correctly' );
181 # getletter
182 my $letter = C4::Letters::getletter('my module', 'my code', $library->{branchcode}, 'email');
183 is( $letter->{branchcode}, $library->{branchcode}, 'GetLetters gets the branch code correctly' );
184 is( $letter->{module}, 'my module', 'GetLetters gets the module correctly' );
185 is( $letter->{code}, 'my code', 'GetLetters gets the code correctly' );
186 is( $letter->{name}, 'my name', 'GetLetters gets the name correctly' );
187 is( $letter->{is_html}, 1, 'GetLetters gets the boolean is_html correctly' );
188 is( $letter->{title}, $title, 'GetLetters gets the title correctly' );
189 is( $letter->{content}, $content, 'GetLetters gets the content correctly' );
190 is( $letter->{message_transport_type}, 'email', 'GetLetters gets the message type correctly' );
192 # Regression test for Bug 14206
193 $dbh->do( q|INSERT INTO letter(branchcode,module,code,name,is_html,title,content,message_transport_type) VALUES ('FFL','my module','my code','my name',1,?,?,'print')|, undef, $title, $content );
194 my $letter14206_a = C4::Letters::getletter('my module', 'my code', 'FFL' );
195 is( $letter14206_a->{message_transport_type}, 'print', 'Bug 14206 - message_transport_type not passed, correct mtt detected' );
196 my $letter14206_b = C4::Letters::getletter('my module', 'my code', 'FFL', 'print');
197 is( $letter14206_b->{message_transport_type}, 'print', 'Bug 14206 - message_transport_type passed, correct mtt detected' );
199 # test for overdue_notices.pl
200 my $overdue_rules = {
201 letter1 => 'my code',
203 my $i = 1;
204 my $branchcode = 'FFL';
205 my $letter14206_c = C4::Letters::getletter('my module', $overdue_rules->{"letter$i"}, $branchcode);
206 is( $letter14206_c->{message_transport_type}, 'print', 'Bug 14206 - correct mtt detected for call from overdue_notices.pl' );
208 # addalert
209 my $type = 'my type';
210 my $externalid = 'my external id';
211 my $alert_id = C4::Letters::addalert($borrowernumber, $type, $externalid);
212 isnt( $alert_id, undef, 'addalert does not return undef' );
215 # getalert
216 my $alerts = C4::Letters::getalert();
217 is( @$alerts, 1, 'getalert should not fail without parameter' );
218 $alerts = C4::Letters::getalert($borrowernumber);
219 is( @$alerts, 1, 'addalert adds an alert' );
220 is( $alerts->[0]->{alertid}, $alert_id, 'addalert returns the alert id correctly' );
221 is( $alerts->[0]->{type}, $type, 'addalert stores the type correctly' );
222 is( $alerts->[0]->{externalid}, $externalid, 'addalert stores the externalid correctly' );
224 $alerts = C4::Letters::getalert($borrowernumber, $type);
225 is( @$alerts, 1, 'getalert returns the correct number of alerts' );
226 $alerts = C4::Letters::getalert($borrowernumber, $type, $externalid);
227 is( @$alerts, 1, 'getalert returns the correct number of alerts' );
228 $alerts = C4::Letters::getalert($borrowernumber, 'another type');
229 is( @$alerts, 0, 'getalert returns the correct number of alerts' );
230 $alerts = C4::Letters::getalert($borrowernumber, $type, 'another external id');
231 is( @$alerts, 0, 'getalert returns the correct number of alerts' );
234 # delalert
235 eval {
236 C4::Letters::delalert();
238 isnt( $@, undef, 'delalert without argument returns an error' );
239 $alerts = C4::Letters::getalert($borrowernumber);
240 is( @$alerts, 1, 'delalert without argument does not remove an alert' );
242 C4::Letters::delalert($alert_id);
243 $alerts = C4::Letters::getalert($borrowernumber);
244 is( @$alerts, 0, 'delalert removes an alert' );
247 # GetPreparedLetter
248 t::lib::Mocks::mock_preference('OPACBaseURL', 'http://thisisatest.com');
250 my $sms_content = 'This is a SMS for an <<status>>';
251 $dbh->do( q|INSERT INTO letter(branchcode,module,code,name,is_html,title,content,message_transport_type) VALUES (?,'my module','my code','my name',1,'my title',?,'sms')|, undef, $library->{branchcode}, $sms_content );
253 my $tables = {
254 borrowers => $borrowernumber,
255 branches => $library->{branchcode},
256 biblio => $biblionumber,
258 my $substitute = {
259 status => 'overdue',
261 my $repeat = [
263 itemcallnumber => 'my callnumber1',
264 barcode => '1234',
267 itemcallnumber => 'my callnumber2',
268 barcode => '5678',
271 my $prepared_letter = GetPreparedLetter((
272 module => 'my module',
273 branchcode => $library->{branchcode},
274 letter_code => 'my code',
275 tables => $tables,
276 substitute => $substitute,
277 repeat => $repeat,
279 my $retrieved_library = Koha::Libraries->find($library->{branchcode});
280 my $my_title_letter = $retrieved_library->branchname . qq| - $substitute->{status}|;
281 my $my_content_letter = qq|Dear Jane Smith,
282 According to our current records, you have items that are overdue.Your library does not charge late fines, but please return or renew them at the branch below as soon as possible.
284 |.$retrieved_library->branchname.qq|
285 |.$retrieved_library->branchaddress1.qq|
286 URL: http://thisisatest.com
288 The following item(s) is/are currently $substitute->{status}:
290 <item> 1. $repeat->[0]->{itemcallnumber}, Barcode: $repeat->[0]->{barcode} </item>
291 <item> 2. $repeat->[1]->{itemcallnumber}, Barcode: $repeat->[1]->{barcode} </item>
293 Thank-you for your prompt attention to this matter.
294 Don't forget your date of birth: | . output_pref({ dt => $date, dateonly => 1 }) . q|.
295 Look at this wonderful biblio timestamp: | . output_pref({ dt => $date }) . ".\n";
297 is( $prepared_letter->{title}, $my_title_letter, 'GetPreparedLetter returns the title correctly' );
298 is( $prepared_letter->{content}, $my_content_letter, 'GetPreparedLetter returns the content correctly' );
300 $prepared_letter = GetPreparedLetter((
301 module => 'my module',
302 branchcode => $library->{branchcode},
303 letter_code => 'my code',
304 tables => $tables,
305 substitute => $substitute,
306 repeat => $repeat,
307 message_transport_type => 'sms',
309 $my_content_letter = qq|This is a SMS for an $substitute->{status}|;
310 is( $prepared_letter->{content}, $my_content_letter, 'GetPreparedLetter returns the content correctly' );
312 $dbh->do(q{INSERT INTO letter (module, code, name, title, content) VALUES ('test_date','TEST_DATE','Test dates','A title with a timestamp: <<biblio.timestamp>>','This one only contains the date: <<biblio.timestamp | dateonly>>.');});
313 $prepared_letter = GetPreparedLetter((
314 module => 'test_date',
315 branchcode => '',
316 letter_code => 'test_date',
317 tables => $tables,
318 substitute => $substitute,
319 repeat => $repeat,
321 is( $prepared_letter->{content}, q|This one only contains the date: | . output_pref({ dt => $date, dateonly => 1 }) . q|.|, 'dateonly test 1' );
323 $dbh->do(q{UPDATE letter SET content = 'And also this one:<<timestamp | dateonly>>.' WHERE code = 'test_date';});
324 $prepared_letter = GetPreparedLetter((
325 module => 'test_date',
326 branchcode => '',
327 letter_code => 'test_date',
328 tables => $tables,
329 substitute => $substitute,
330 repeat => $repeat,
332 is( $prepared_letter->{content}, q|And also this one:| . output_pref({ dt => $date, dateonly => 1 }) . q|.|, 'dateonly test 2' );
334 $dbh->do(q{UPDATE letter SET content = 'And also this one:<<timestamp|dateonly >>.' WHERE code = 'test_date';});
335 $prepared_letter = GetPreparedLetter((
336 module => 'test_date',
337 branchcode => '',
338 letter_code => 'test_date',
339 tables => $tables,
340 substitute => $substitute,
341 repeat => $repeat,
343 is( $prepared_letter->{content}, q|And also this one:| . output_pref({ dt => $date, dateonly => 1 }) . q|.|, 'dateonly test 3' );
345 t::lib::Mocks::mock_preference( 'TimeFormat', '12hr' );
346 my $yesterday_night = $date->clone->add( days => -1 )->set_hour(22);
347 $dbh->do(q|UPDATE biblio SET timestamp = ? WHERE biblionumber = ?|, undef, $yesterday_night, $biblionumber );
348 $dbh->do(q{UPDATE letter SET content = 'And also this one:<<timestamp>>.' WHERE code = 'test_date';});
349 $prepared_letter = GetPreparedLetter((
350 module => 'test_date',
351 branchcode => '',
352 letter_code => 'test_date',
353 tables => $tables,
354 substitute => $substitute,
355 repeat => $repeat,
357 is( $prepared_letter->{content}, q|And also this one:| . output_pref({ dt => $yesterday_night }) . q|.|, 'dateonly test 3' );
359 $dbh->do(q{INSERT INTO letter (module, code, name, title, content) VALUES ('claimacquisition','TESTACQCLAIM','Acquisition Claim','Item Not Received','<<aqbooksellers.name>>|<<aqcontacts.name>>|<order>Ordernumber <<aqorders.ordernumber>> (<<biblio.title>>) (<<aqorders.quantity>> ordered)</order>');});
360 $dbh->do(q{INSERT INTO letter (module, code, name, title, content) VALUES ('orderacquisition','TESTACQORDER','Acquisition Order','Order','<<aqbooksellers.name>>|<<aqcontacts.name>>|<order>Ordernumber <<aqorders.ordernumber>> (<<biblio.title>>) (<<aqorders.quantity>> ordered)</order>');});
362 # Test that _parseletter doesn't modify its parameters bug 15429
364 my $values = { dateexpiry => '2015-12-13', };
365 C4::Letters::_parseletter($prepared_letter, 'borrowers', $values);
366 is( $values->{dateexpiry}, '2015-12-13', "_parseletter doesn't modify its parameters" );
369 my $booksellerid = C4::Bookseller::AddBookseller(
371 name => "my vendor",
372 address1 => "bookseller's address",
373 phone => "0123456",
374 active => 1,
375 deliverytime => 5,
378 { name => 'John Smith', acqprimary => 1, phone => '0123456x1', claimacquisition => 1, orderacquisition => 1 },
379 { name => 'Leo Tolstoy', phone => '0123456x2', claimissues => 1 },
382 my $basketno = NewBasket($booksellerid, 1);
384 my $budgetid = C4::Budgets::AddBudget({
385 budget_code => "budget_code_test_letters",
386 budget_name => "budget_name_test_letters",
389 my $bib = MARC::Record->new();
390 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
391 $bib->append_fields(
392 MARC::Field->new('200', ' ', ' ', a => 'Silence in the library'),
394 } else {
395 $bib->append_fields(
396 MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
400 ($biblionumber, $biblioitemnumber) = AddBiblio($bib, '');
401 my $order = Koha::Acquisition::Order->new(
403 basketno => $basketno,
404 quantity => 1,
405 biblionumber => $biblionumber,
406 budget_id => $budgetid,
408 )->insert;
409 my $ordernumber = $order->{ordernumber};
411 C4::Acquisition::CloseBasket( $basketno );
412 my $err;
413 warning_like {
414 $err = SendAlerts( 'claimacquisition', [ $ordernumber ], 'TESTACQCLAIM' ) }
415 qr/^Bookseller .* without emails at/,
416 "SendAlerts prints a warning";
417 is($err->{'error'}, 'no_email', "Trying to send an alert when there's no e-mail results in an error");
419 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
420 $bookseller->contacts->[0]->email('testemail@mydomain.com');
421 C4::Bookseller::ModBookseller($bookseller);
422 $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
424 # Ensure that the preference 'LetterLog' is set to logging
425 t::lib::Mocks::mock_preference( 'LetterLog', 'on' );
428 warning_is {
429 $err = SendAlerts( 'orderacquisition', $basketno , 'TESTACQORDER' ) }
430 "Fake sendmail",
431 "SendAlerts is using the mocked sendmail routine (orderacquisition)";
432 is($err, 1, "Successfully sent order.");
433 is($mail{'To'}, 'testemail@mydomain.com', "mailto correct in sent order");
434 is($mail{'Message'}, 'my vendor|John Smith|Ordernumber ' . $ordernumber . ' (Silence in the library) (1 ordered)', 'Order notice text constructed successfully');
436 $dbh->do(q{DELETE FROM letter WHERE code = 'TESTACQORDER';});
437 warning_like {
438 $err = SendAlerts( 'orderacquisition', $basketno , 'TESTACQORDER' ) }
439 qr/No orderacquisition TESTACQORDER letter transported by email/,
440 "GetPreparedLetter warns about missing notice template";
441 is($err->{'error'}, 'no_letter', "No TESTACQORDER letter was defined.");
446 warning_is {
447 $err = SendAlerts( 'claimacquisition', [ $ordernumber ], 'TESTACQCLAIM' ) }
448 "Fake sendmail",
449 "SendAlerts is using the mocked sendmail routine";
451 is($err, 1, "Successfully sent claim");
452 is($mail{'To'}, 'testemail@mydomain.com', "mailto correct in sent claim");
453 is($mail{'Message'}, 'my vendor|John Smith|Ordernumber ' . $ordernumber . ' (Silence in the library) (1 ordered)', 'Claim notice text constructed successfully');
457 use C4::Serials;
459 my $notes = 'notes';
460 my $internalnotes = 'intnotes';
461 $dbh->do(q|UPDATE subscription_numberpatterns SET numberingmethod='No. {X}' WHERE id=1|);
462 my $subscriptionid = NewSubscription(
463 undef, "", undef, undef, undef, $biblionumber,
464 '2013-01-01', 1, undef, undef, undef,
465 undef, undef, undef, undef, undef, undef,
466 1, $notes,undef, '2013-01-01', undef, 1,
467 undef, undef, 0, $internalnotes, 0,
468 undef, undef, 0, undef, '2013-12-31', 0
470 $dbh->do(q{INSERT INTO letter (module, code, name, title, content) VALUES ('serial','RLIST','Serial issue notification','Serial issue notification','<<biblio.title>>,<<subscription.subscriptionid>>,<<serial.serialseq>>');});
471 my ($serials_count, @serials) = GetSerials($subscriptionid);
472 my $serial = $serials[0];
474 my $borrowernumber = AddMember(
475 firstname => 'John',
476 surname => 'Smith',
477 categorycode => $patron_category,
478 branchcode => $library->{branchcode},
479 dateofbirth => $date,
480 email => 'john.smith@test.de',
482 my $alert_id = C4::Letters::addalert($borrowernumber, 'issue', $subscriptionid);
485 my $err2;
486 warning_is {
487 $err2 = SendAlerts( 'issue', $serial->{serialid}, 'RLIST' ) }
488 "Fake sendmail",
489 "SendAlerts is using the mocked sendmail routine";
490 is($err2, 1, "Successfully sent serial notification");
491 is($mail{'To'}, 'john.smith@test.de', "mailto correct in sent serial notification");
492 is($mail{'Message'}, 'Silence in the library,'.$subscriptionid.',No. 0', 'Serial notification text constructed successfully');