Bug 18478 - Unit tests
[koha.git] / t / db_dependent / Letters.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Copyright (C) 2013 Equinox Software, Inc.
6 #
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.
11 #
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.
16 #
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>.
19
20 use Modern::Perl;
21 use Test::More tests => 82;
22 use Test::MockModule;
23 use Test::Warn;
24
25 use MARC::Record;
26
27 my %mail;
28 my $module = new Test::MockModule('Mail::Sendmail');
29 $module->mock(
30     'sendmail',
31     sub {
32         warn "Fake sendmail";
33         %mail = @_;
34     }
35 );
36
37 use_ok('C4::Context');
38 use_ok('C4::Members');
39 use_ok('C4::Acquisition');
40 use_ok('C4::Biblio');
41 use_ok('C4::Letters');
42 use t::lib::Mocks;
43 use t::lib::TestBuilder;
44 use Koha::Database;
45 use Koha::DateUtils qw( dt_from_string output_pref );
46 use Koha::Acquisition::Order;
47 use Koha::Acquisition::Booksellers;
48 use Koha::Acquisition::Bookseller::Contacts;
49 use Koha::Libraries;
50 use Koha::Notice::Templates;
51 my $schema = Koha::Database->schema;
52 $schema->storage->txn_begin();
53
54 my $builder = t::lib::TestBuilder->new;
55 my $dbh = C4::Context->dbh;
56 $dbh->{RaiseError} = 1;
57
58 $dbh->do(q|DELETE FROM letter|);
59 $dbh->do(q|DELETE FROM message_queue|);
60 $dbh->do(q|DELETE FROM message_transport_types|);
61
62 my $library = $builder->build({
63     source => 'Branch',
64 });
65 my $patron_category = $builder->build({ source => 'Category' })->{categorycode};
66 my $date = dt_from_string;
67 my $borrowernumber = AddMember(
68     firstname    => 'Jane',
69     surname      => 'Smith',
70     categorycode => $patron_category,
71     branchcode   => $library->{branchcode},
72     dateofbirth  => $date,
73     smsalertnumber => undef,
74 );
75
76 my $marc_record = MARC::Record->new;
77 my( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' );
78
79
80
81 # GetMessageTransportTypes
82 my $mtts = C4::Letters::GetMessageTransportTypes();
83 is( @$mtts, 0, 'GetMessageTransportTypes returns the correct number of message types' );
84
85 $dbh->do(q|
86     INSERT INTO message_transport_types( message_transport_type ) VALUES ('email'), ('phone'), ('print'), ('sms')
87 |);
88 $mtts = C4::Letters::GetMessageTransportTypes();
89 is_deeply( $mtts, ['email', 'phone', 'print', 'sms'], 'GetMessageTransportTypes returns all values' );
90
91
92 # EnqueueLetter
93 is( C4::Letters::EnqueueLetter(), undef, 'EnqueueLetter without argument returns undef' );
94
95 my $my_message = {
96     borrowernumber         => $borrowernumber,
97     message_transport_type => 'sms',
98     to_address             => undef,
99     from_address           => 'from@example.com',
100 };
101 my $message_id = C4::Letters::EnqueueLetter($my_message);
102 is( $message_id, undef, 'EnqueueLetter without the letter argument returns undef' );
103
104 delete $my_message->{message_transport_type};
105 $my_message->{letter} = {
106     content      => 'a message',
107     title        => 'message title',
108     metadata     => 'metadata',
109     code         => 'TEST_MESSAGE',
110     content_type => 'text/plain',
111 };
112 $message_id = C4::Letters::EnqueueLetter($my_message);
113 is( $message_id, undef, 'EnqueueLetter without the message type argument argument returns undef' );
114
115 $my_message->{message_transport_type} = 'sms';
116 $message_id = C4::Letters::EnqueueLetter($my_message);
117 ok(defined $message_id && $message_id > 0, 'new message successfully queued');
118
119
120 # GetQueuedMessages
121 my $messages = C4::Letters::GetQueuedMessages();
122 is( @$messages, 1, 'GetQueuedMessages without argument returns all the entries' );
123
124 $messages = C4::Letters::GetQueuedMessages({ borrowernumber => $borrowernumber });
125 is( @$messages, 1, 'one message stored for the borrower' );
126 is( $messages->[0]->{message_id}, $message_id, 'EnqueueLetter returns the message id correctly' );
127 is( $messages->[0]->{borrowernumber}, $borrowernumber, 'EnqueueLetter stores the borrower number correctly' );
128 is( $messages->[0]->{subject}, $my_message->{letter}->{title}, 'EnqueueLetter stores the subject correctly' );
129 is( $messages->[0]->{content}, $my_message->{letter}->{content}, 'EnqueueLetter stores the content correctly' );
130 is( $messages->[0]->{message_transport_type}, $my_message->{message_transport_type}, 'EnqueueLetter stores the message type correctly' );
131 is( $messages->[0]->{status}, 'pending', 'EnqueueLetter stores the status pending correctly' );
132
133
134 # SendQueuedMessages
135 my $messages_processed = C4::Letters::SendQueuedMessages();
136 is($messages_processed, 1, 'all queued messages processed');
137 $messages = C4::Letters::GetQueuedMessages({ borrowernumber => $borrowernumber });
138 is(
139     $messages->[0]->{status},
140     'failed',
141     'message marked failed if tried to send SMS message for borrower with no smsalertnumber set (bug 11208)'
142 );
143
144 # ResendMessage
145 my $resent = C4::Letters::ResendMessage($messages->[0]->{message_id});
146 my $message = C4::Letters::GetMessage( $messages->[0]->{message_id});
147 is( $resent, 1, 'The message should have been resent' );
148 is($message->{status},'pending', 'ResendMessage sets status to pending correctly (bug 12426)');
149 $resent = C4::Letters::ResendMessage($messages->[0]->{message_id});
150 is( $resent, 0, 'The message should not have been resent again' );
151 $resent = C4::Letters::ResendMessage();
152 is( $resent, undef, 'ResendMessage should return undef if not message_id given' );
153
154 # GetLetters
155 my $letters = C4::Letters::GetLetters();
156 is( @$letters, 0, 'GetLetters returns the correct number of letters' );
157
158 my $title = q|<<branches.branchname>> - <<status>>|;
159 my $content = q{Dear <<borrowers.firstname>> <<borrowers.surname>>,
160 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.
161
162 <<branches.branchname>>
163 <<branches.branchaddress1>>
164 URL: <<OPACBaseURL>>
165
166 The following item(s) is/are currently <<status>>:
167
168 <item> <<count>>. <<items.itemcallnumber>>, Barcode: <<items.barcode>> </item>
169
170 Thank-you for your prompt attention to this matter.
171 Don't forget your date of birth: <<borrowers.dateofbirth>>.
172 Look at this wonderful biblio timestamp: <<biblio.timestamp>>.
173 };
174
175 $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 );
176 $letters = C4::Letters::GetLetters();
177 is( @$letters, 1, 'GetLetters returns the correct number of letters' );
178 is( $letters->[0]->{branchcode}, $library->{branchcode}, 'GetLetters gets the branch code correctly' );
179 is( $letters->[0]->{module}, 'my module', 'GetLetters gets the module correctly' );
180 is( $letters->[0]->{code}, 'my code', 'GetLetters gets the code correctly' );
181 is( $letters->[0]->{name}, 'my name', 'GetLetters gets the name correctly' );
182
183
184 # getletter
185 my $letter = C4::Letters::getletter('my module', 'my code', $library->{branchcode}, 'email');
186 is( $letter->{branchcode}, $library->{branchcode}, 'GetLetters gets the branch code correctly' );
187 is( $letter->{module}, 'my module', 'GetLetters gets the module correctly' );
188 is( $letter->{code}, 'my code', 'GetLetters gets the code correctly' );
189 is( $letter->{name}, 'my name', 'GetLetters gets the name correctly' );
190 is( $letter->{is_html}, 1, 'GetLetters gets the boolean is_html correctly' );
191 is( $letter->{title}, $title, 'GetLetters gets the title correctly' );
192 is( $letter->{content}, $content, 'GetLetters gets the content correctly' );
193 is( $letter->{message_transport_type}, 'email', 'GetLetters gets the message type correctly' );
194
195 # Regression test for Bug 14206
196 $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 );
197 my $letter14206_a = C4::Letters::getletter('my module', 'my code', 'FFL' );
198 is( $letter14206_a->{message_transport_type}, 'print', 'Bug 14206 - message_transport_type not passed, correct mtt detected' );
199 my $letter14206_b = C4::Letters::getletter('my module', 'my code', 'FFL', 'print');
200 is( $letter14206_b->{message_transport_type}, 'print', 'Bug 14206 - message_transport_type passed, correct mtt detected'  );
201
202 # test for overdue_notices.pl
203 my $overdue_rules = {
204     letter1         => 'my code',
205 };
206 my $i = 1;
207 my $branchcode = 'FFL';
208 my $letter14206_c = C4::Letters::getletter('my module', $overdue_rules->{"letter$i"}, $branchcode);
209 is( $letter14206_c->{message_transport_type}, 'print', 'Bug 14206 - correct mtt detected for call from overdue_notices.pl' );
210
211 # addalert
212 my $type = 'my type';
213 my $externalid = 'my external id';
214 my $alert_id = C4::Letters::addalert($borrowernumber, $type, $externalid);
215 isnt( $alert_id, undef, 'addalert does not return undef' );
216
217
218 # getalert
219 my $alerts = C4::Letters::getalert();
220 is( @$alerts, 1, 'getalert should not fail without parameter' );
221 $alerts = C4::Letters::getalert($borrowernumber);
222 is( @$alerts, 1, 'addalert adds an alert' );
223 is( $alerts->[0]->{alertid}, $alert_id, 'addalert returns the alert id correctly' );
224 is( $alerts->[0]->{type}, $type, 'addalert stores the type correctly' );
225 is( $alerts->[0]->{externalid}, $externalid, 'addalert stores the externalid correctly' );
226
227 $alerts = C4::Letters::getalert($borrowernumber, $type);
228 is( @$alerts, 1, 'getalert returns the correct number of alerts' );
229 $alerts = C4::Letters::getalert($borrowernumber, $type, $externalid);
230 is( @$alerts, 1, 'getalert returns the correct number of alerts' );
231 $alerts = C4::Letters::getalert($borrowernumber, 'another type');
232 is( @$alerts, 0, 'getalert returns the correct number of alerts' );
233 $alerts = C4::Letters::getalert($borrowernumber, $type, 'another external id');
234 is( @$alerts, 0, 'getalert returns the correct number of alerts' );
235
236
237 # delalert
238 eval {
239     C4::Letters::delalert();
240 };
241 isnt( $@, undef, 'delalert without argument returns an error' );
242 $alerts = C4::Letters::getalert($borrowernumber);
243 is( @$alerts, 1, 'delalert without argument does not remove an alert' );
244
245 C4::Letters::delalert($alert_id);
246 $alerts = C4::Letters::getalert($borrowernumber);
247 is( @$alerts, 0, 'delalert removes an alert' );
248
249
250 # GetPreparedLetter
251 t::lib::Mocks::mock_preference('OPACBaseURL', 'http://thisisatest.com');
252
253 my $sms_content = 'This is a SMS for an <<status>>';
254 $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 );
255
256 my $tables = {
257     borrowers => $borrowernumber,
258     branches => $library->{branchcode},
259     biblio => $biblionumber,
260 };
261 my $substitute = {
262     status => 'overdue',
263 };
264 my $repeat = [
265     {
266         itemcallnumber => 'my callnumber1',
267         barcode        => '1234',
268     },
269     {
270         itemcallnumber => 'my callnumber2',
271         barcode        => '5678',
272     },
273 ];
274 my $prepared_letter = GetPreparedLetter((
275     module      => 'my module',
276     branchcode  => $library->{branchcode},
277     letter_code => 'my code',
278     tables      => $tables,
279     substitute  => $substitute,
280     repeat      => $repeat,
281 ));
282 my $retrieved_library = Koha::Libraries->find($library->{branchcode});
283 my $my_title_letter = $retrieved_library->branchname . qq| - $substitute->{status}|;
284 my $biblio_timestamp = dt_from_string( GetBiblioData($biblionumber)->{timestamp} );
285 my $my_content_letter = qq|Dear Jane Smith,
286 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.
287
288 |.$retrieved_library->branchname.qq|
289 |.$retrieved_library->branchaddress1.qq|
290 URL: http://thisisatest.com
291
292 The following item(s) is/are currently $substitute->{status}:
293
294 <item> 1. $repeat->[0]->{itemcallnumber}, Barcode: $repeat->[0]->{barcode} </item>
295 <item> 2. $repeat->[1]->{itemcallnumber}, Barcode: $repeat->[1]->{barcode} </item>
296
297 Thank-you for your prompt attention to this matter.
298 Don't forget your date of birth: | . output_pref({ dt => $date, dateonly => 1 }) . q|.
299 Look at this wonderful biblio timestamp: | . output_pref({ dt => $biblio_timestamp })  . ".\n";
300
301 is( $prepared_letter->{title}, $my_title_letter, 'GetPreparedLetter returns the title correctly' );
302 is( $prepared_letter->{content}, $my_content_letter, 'GetPreparedLetter returns the content correctly' );
303
304 $prepared_letter = GetPreparedLetter((
305     module                 => 'my module',
306     branchcode             => $library->{branchcode},
307     letter_code            => 'my code',
308     tables                 => $tables,
309     substitute             => $substitute,
310     repeat                 => $repeat,
311     message_transport_type => 'sms',
312 ));
313 $my_content_letter = qq|This is a SMS for an $substitute->{status}|;
314 is( $prepared_letter->{content}, $my_content_letter, 'GetPreparedLetter returns the content correctly' );
315
316 $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>>.');});
317 $prepared_letter = GetPreparedLetter((
318     module                 => 'test_date',
319     branchcode             => '',
320     letter_code            => 'test_date',
321     tables                 => $tables,
322     substitute             => $substitute,
323     repeat                 => $repeat,
324 ));
325 is( $prepared_letter->{content}, q|This one only contains the date: | . output_pref({ dt => $date, dateonly => 1 }) . q|.|, 'dateonly test 1' );
326
327 $dbh->do(q{UPDATE letter SET content = 'And also this one:<<timestamp | dateonly>>.' WHERE code = 'test_date';});
328 $prepared_letter = GetPreparedLetter((
329     module                 => 'test_date',
330     branchcode             => '',
331     letter_code            => 'test_date',
332     tables                 => $tables,
333     substitute             => $substitute,
334     repeat                 => $repeat,
335 ));
336 is( $prepared_letter->{content}, q|And also this one:| . output_pref({ dt => $date, dateonly => 1 }) . q|.|, 'dateonly test 2' );
337
338 $dbh->do(q{UPDATE letter SET content = 'And also this one:<<timestamp|dateonly >>.' WHERE code = 'test_date';});
339 $prepared_letter = GetPreparedLetter((
340     module                 => 'test_date',
341     branchcode             => '',
342     letter_code            => 'test_date',
343     tables                 => $tables,
344     substitute             => $substitute,
345     repeat                 => $repeat,
346 ));
347 is( $prepared_letter->{content}, q|And also this one:| . output_pref({ dt => $date, dateonly => 1 }) . q|.|, 'dateonly test 3' );
348
349 t::lib::Mocks::mock_preference( 'TimeFormat', '12hr' );
350 my $yesterday_night = $date->clone->add( days => -1 )->set_hour(22);
351 $dbh->do(q|UPDATE biblio SET timestamp = ? WHERE biblionumber = ?|, undef, $yesterday_night, $biblionumber );
352 $dbh->do(q{UPDATE letter SET content = 'And also this one:<<timestamp>>.' WHERE code = 'test_date';});
353 $prepared_letter = GetPreparedLetter((
354     module                 => 'test_date',
355     branchcode             => '',
356     letter_code            => 'test_date',
357     tables                 => $tables,
358     substitute             => $substitute,
359     repeat                 => $repeat,
360 ));
361 is( $prepared_letter->{content}, q|And also this one:| . output_pref({ dt => $yesterday_night }) . q|.|, 'dateonly test 3' );
362
363 $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>');});
364 $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>');});
365
366 # Test that _parseletter doesn't modify its parameters bug 15429
367 {
368     my $values = { dateexpiry => '2015-12-13', };
369     C4::Letters::_parseletter($prepared_letter, 'borrowers', $values);
370     is( $values->{dateexpiry}, '2015-12-13', "_parseletter doesn't modify its parameters" );
371 }
372
373 my $bookseller = Koha::Acquisition::Bookseller->new(
374     {
375         name => "my vendor",
376         address1 => "bookseller's address",
377         phone => "0123456",
378         active => 1,
379         deliverytime => 5,
380     }
381 )->store;
382 my $booksellerid = $bookseller->id;
383
384 Koha::Acquisition::Bookseller::Contact->new( { name => 'John Smith',  phone => '0123456x1', claimacquisition => 1, orderacquisition => 1, booksellerid => $booksellerid } )->store;
385 Koha::Acquisition::Bookseller::Contact->new( { name => 'Leo Tolstoy', phone => '0123456x2', claimissues      => 1, booksellerid => $booksellerid } )->store;
386 my $basketno = NewBasket($booksellerid, 1);
387
388 my $budgetid = C4::Budgets::AddBudget({
389     budget_code => "budget_code_test_letters",
390     budget_name => "budget_name_test_letters",
391 });
392
393 my $bib = MARC::Record->new();
394 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
395     $bib->append_fields(
396         MARC::Field->new('200', ' ', ' ', a => 'Silence in the library'),
397     );
398 } else {
399     $bib->append_fields(
400         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
401     );
402 }
403
404 ($biblionumber, $biblioitemnumber) = AddBiblio($bib, '');
405 my $order = Koha::Acquisition::Order->new(
406     {
407         basketno => $basketno,
408         quantity => 1,
409         biblionumber => $biblionumber,
410         budget_id => $budgetid,
411     }
412 )->insert;
413 my $ordernumber = $order->{ordernumber};
414
415 C4::Acquisition::CloseBasket( $basketno );
416 my $err;
417 warning_like {
418     $err = SendAlerts( 'claimacquisition', [ $ordernumber ], 'TESTACQCLAIM' ) }
419     qr/^Bookseller .* without emails at/,
420     "SendAlerts prints a warning";
421 is($err->{'error'}, 'no_email', "Trying to send an alert when there's no e-mail results in an error");
422
423 $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid );
424 $bookseller->contacts->next->email('testemail@mydomain.com')->store;
425
426 # Ensure that the preference 'LetterLog' is set to logging
427 t::lib::Mocks::mock_preference( 'LetterLog', 'on' );
428
429 # SendAlerts needs branchemail or KohaAdminEmailAddress as sender
430 C4::Context->_new_userenv('DUMMY');
431 C4::Context->set_userenv( 0, 0, 0, 'firstname', 'surname', $library->{branchcode}, 'My Library', 0, '', '');
432 t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'library@domain.com' );
433
434 {
435 warning_is {
436     $err = SendAlerts( 'orderacquisition', $basketno , 'TESTACQORDER' ) }
437     "Fake sendmail",
438     "SendAlerts is using the mocked sendmail routine (orderacquisition)";
439 is($err, 1, "Successfully sent order.");
440 is($mail{'To'}, 'testemail@mydomain.com', "mailto correct in sent order");
441 is($mail{'Message'}, 'my vendor|John Smith|Ordernumber ' . $ordernumber . ' (Silence in the library) (1 ordered)', 'Order notice text constructed successfully');
442
443 $dbh->do(q{DELETE FROM letter WHERE code = 'TESTACQORDER';});
444 warning_like {
445     $err = SendAlerts( 'orderacquisition', $basketno , 'TESTACQORDER' ) }
446     qr/No orderacquisition TESTACQORDER letter transported by email/,
447     "GetPreparedLetter warns about missing notice template";
448 is($err->{'error'}, 'no_letter', "No TESTACQORDER letter was defined.");
449 }
450
451 {
452 warning_is {
453     $err = SendAlerts( 'claimacquisition', [ $ordernumber ], 'TESTACQCLAIM' ) }
454     "Fake sendmail",
455     "SendAlerts is using the mocked sendmail routine";
456
457 is($err, 1, "Successfully sent claim");
458 is($mail{'To'}, 'testemail@mydomain.com', "mailto correct in sent claim");
459 is($mail{'Message'}, 'my vendor|John Smith|Ordernumber ' . $ordernumber . ' (Silence in the library) (1 ordered)', 'Claim notice text constructed successfully');
460 }
461
462 {
463 use C4::Serials;
464
465 my $notes = 'notes';
466 my $internalnotes = 'intnotes';
467 $dbh->do(q|UPDATE subscription_numberpatterns SET numberingmethod='No. {X}' WHERE id=1|);
468 my $subscriptionid = NewSubscription(
469      undef,      "",     undef, undef, undef, $biblionumber,
470     '2013-01-01', 1, undef, undef,  undef,
471     undef,      undef,  undef, undef, undef, undef,
472     1,          $notes,undef, '2013-01-01', undef, 1,
473     undef,       undef,  0,    $internalnotes,  0,
474     undef, undef, 0,          undef,         '2013-12-31', 0
475 );
476 $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>>');});
477 my ($serials_count, @serials) = GetSerials($subscriptionid);
478 my $serial = $serials[0];
479
480 my $borrowernumber = AddMember(
481     firstname    => 'John',
482     surname      => 'Smith',
483     categorycode => $patron_category,
484     branchcode   => $library->{branchcode},
485     dateofbirth  => $date,
486     email        => 'john.smith@test.de',
487 );
488 my $alert_id = C4::Letters::addalert($borrowernumber, 'issue', $subscriptionid);
489
490
491 my $err2;
492 warning_is {
493 $err2 = SendAlerts( 'issue', $serial->{serialid}, 'RLIST' ) }
494     "Fake sendmail",
495     "SendAlerts is using the mocked sendmail routine";
496 is($err2, 1, "Successfully sent serial notification");
497 is($mail{'To'}, 'john.smith@test.de', "mailto correct in sent serial notification");
498 is($mail{'Message'}, 'Silence in the library,'.$subscriptionid.',No. 0', 'Serial notification text constructed successfully');
499 }
500
501 subtest 'GetPreparedLetter' => sub {
502     plan tests => 4;
503
504     Koha::Notice::Template->new(
505         {
506             module                 => 'test',
507             code                   => 'test',
508             branchcode             => '',
509             message_transport_type => 'email'
510         }
511     )->store;
512     my $letter;
513     warning_like {
514         $letter = C4::Letters::GetPreparedLetter(
515             module      => 'test',
516             letter_code => 'test',
517         );
518     }
519     qr{^ERROR: nothing to substitute},
520 'GetPreparedLetter should warn if tables, substiture and repeat are not set';
521     is( $letter, undef,
522 'No letter should be returned by GetPreparedLetter if something went wrong'
523     );
524
525     warning_like {
526         $letter = C4::Letters::GetPreparedLetter(
527             module      => 'test',
528             letter_code => 'test',
529             substitute  => {}
530         );
531     }
532     qr{^ERROR: nothing to substitute},
533 'GetPreparedLetter should warn if tables, substiture and repeat are not set, even if the key is passed';
534     is( $letter, undef,
535 'No letter should be returned by GetPreparedLetter if something went wrong'
536     );
537
538 };
539
540
541
542 subtest 'TranslateNotices' => sub {
543     plan tests => 4;
544
545     t::lib::Mocks::mock_preference( 'TranslateNotices', '1' );
546
547     $dbh->do(
548         q|
549         INSERT INTO letter (module, code, branchcode, name, title, content, message_transport_type, lang) VALUES
550         ('test', 'code', '', 'test', 'a test', 'just a test', 'email', 'default'),
551         ('test', 'code', '', 'test', 'una prueba', 'solo una prueba', 'email', 'es-ES');
552     | );
553     my $substitute = {};
554     my $letter = C4::Letters::GetPreparedLetter(
555             module                 => 'test',
556             tables                 => $tables,
557             letter_code            => 'code',
558             message_transport_type => 'email',
559             substitute             => $substitute,
560     );
561     is(
562         $letter->{title},
563         'a test',
564         'GetPreparedLetter should return the default one if the lang parameter is not provided'
565     );
566
567     $letter = C4::Letters::GetPreparedLetter(
568             module                 => 'test',
569             tables                 => $tables,
570             letter_code            => 'code',
571             message_transport_type => 'email',
572             substitute             => $substitute,
573             lang                   => 'es-ES',
574     );
575     is( $letter->{title}, 'una prueba',
576         'GetPreparedLetter should return the required notice if it exists' );
577
578     $letter = C4::Letters::GetPreparedLetter(
579             module                 => 'test',
580             tables                 => $tables,
581             letter_code            => 'code',
582             message_transport_type => 'email',
583             substitute             => $substitute,
584             lang                   => 'fr-FR',
585     );
586     is(
587         $letter->{title},
588         'a test',
589         'GetPreparedLetter should return the default notice if the one required does not exist'
590     );
591
592     t::lib::Mocks::mock_preference( 'TranslateNotices', '' );
593
594     $letter = C4::Letters::GetPreparedLetter(
595             module                 => 'test',
596             tables                 => $tables,
597             letter_code            => 'code',
598             message_transport_type => 'email',
599             substitute             => $substitute,
600             lang                   => 'es-ES',
601     );
602     is( $letter->{title}, 'a test',
603         'GetPreparedLetter should return the default notice if pref disabled but additional language exists' );
604
605 };
606
607 subtest 'SendQueuedMessages' => sub {
608
609     plan tests => 2;
610     t::lib::Mocks::mock_preference( 'SMSSendDriver', 'Email' );
611     my $patron = Koha::Patrons->find($borrowernumber);
612     $dbh->do(q|
613         INSERT INTO message_queue(borrowernumber, subject, content, message_transport_type, status, letter_code)
614         VALUES (?, 'subject', 'content', 'sms', 'pending', 'just_a_code')
615         |, undef, $borrowernumber
616     );
617     eval { C4::Letters::SendQueuedMessages(); };
618     is( $@, '', 'SendQueuedMessages should not explode if the patron does not have a sms provider set' );
619
620     my $sms_pro = $builder->build_object({ class => 'Koha::SMS::Providers', value => { domain => 'kidclamp.rocks' } });
621     ModMember( borrowernumber => $borrowernumber, smsalertnumber => '5555555555', sms_provider_id => $sms_pro->id() );
622     $message_id = C4::Letters::EnqueueLetter($my_message); #using datas set around line 95 and forward
623     C4::Letters::SendQueuedMessages();
624     my $sms_message_address = $schema->resultset('MessageQueue')->search({
625         borrowernumber => $borrowernumber,
626         status => 'sent'
627     })->next()->to_address();
628     is( $sms_message_address, '5555555555@kidclamp.rocks', 'SendQueuedMessages populates the to address correctly for SMS by email' );
629
630 };