Bug 21979: Add unit tests
[srvgit] / t / db_dependent / SIP / Message.t
1 #!/usr/bin/perl
2
3 # Tests for SIP::Sip::MsgType
4 # Please help to extend it!
5
6 # This file is part of Koha.
7 #
8 # Copyright 2016 Rijksmuseum
9 #
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22
23 use Modern::Perl;
24 use Test::More tests => 9;
25 use Test::MockObject;
26 use Test::MockModule;
27 use Test::Warn;
28
29 use t::lib::Mocks;
30 use t::lib::TestBuilder;
31
32 use C4::Reserves qw(AddReserve);
33 use Koha::Database;
34 use Koha::AuthUtils qw(hash_password);
35 use Koha::DateUtils;
36 use Koha::Items;
37 use Koha::Checkouts;
38 use Koha::Old::Checkouts;
39 use Koha::Patrons;
40 use Koha::Holds;
41
42 use C4::SIP::ILS;
43 use C4::SIP::ILS::Patron;
44 use C4::SIP::Sip qw(write_msg);
45 use C4::SIP::Sip::Constants qw(:all);
46 use C4::SIP::Sip::MsgType;
47
48 use constant PATRON_PW => 'do_not_ever_use_this_one';
49
50 # START testing
51 subtest 'Testing Patron Status Request V2' => sub {
52     my $schema = Koha::Database->new->schema;
53     $schema->storage->txn_begin;
54     plan tests => 13;
55     $C4::SIP::Sip::protocol_version = 2;
56     test_request_patron_status_v2();
57     $schema->storage->txn_rollback;
58 };
59
60 subtest 'Testing Patron Info Request V2' => sub {
61     my $schema = Koha::Database->new->schema;
62     $schema->storage->txn_begin;
63     plan tests => 24;
64     $C4::SIP::Sip::protocol_version = 2;
65     test_request_patron_info_v2();
66     $schema->storage->txn_rollback;
67 };
68
69 subtest 'Checkin V2' => sub {
70     my $schema = Koha::Database->new->schema;
71     $schema->storage->txn_begin;
72     plan tests => 33;
73     $C4::SIP::Sip::protocol_version = 2;
74     test_checkin_v2();
75     $schema->storage->txn_rollback;
76 };
77
78 subtest 'Test hold_patron_bcode' => sub {
79     my $schema = Koha::Database->new->schema;
80     $schema->storage->txn_begin;
81     plan tests => 2;
82     $C4::SIP::Sip::protocol_version = 2;
83     test_hold_patron_bcode();
84     $schema->storage->txn_rollback;
85 };
86
87 subtest 'hold_patron_name() tests' => sub {
88
89     plan tests => 2;
90
91     my $schema = Koha::Database->new->schema;
92     $schema->storage->txn_begin;
93
94     my $builder = t::lib::TestBuilder->new();
95
96     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
97     my ( $response, $findpatron );
98     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
99
100     my $item = $builder->build_sample_item(
101         {
102             damaged       => 0,
103             withdrawn     => 0,
104             itemlost      => 0,
105             restricted    => 0,
106             homebranch    => $branchcode,
107             holdingbranch => $branchcode
108         }
109     );
110
111     my $server = { ils => $mocks->{ils} };
112     my $sip_item = C4::SIP::ILS::Item->new( $item->barcode );
113
114     is( $sip_item->hold_patron_name, q{}, "SIP item with no hold returns empty string for patron name" );
115
116     my $resp .= C4::SIP::Sip::maybe_add( FID_CALL_NUMBER, $sip_item->hold_patron_name, $server );
117     is( $resp, q{}, "maybe_add returns empty string for SIP item with no hold returns empty string" );
118
119     $schema->storage->txn_rollback;
120 };
121
122 subtest 'Lastseen response' => sub {
123
124     my $schema = Koha::Database->new->schema;
125     $schema->storage->txn_begin;
126
127     plan tests => 6;
128     my $builder = t::lib::TestBuilder->new();
129     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
130     my ( $response, $findpatron );
131     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
132     my $seen_patron = $builder->build({
133         source => 'Borrower',
134         value  => {
135             lastseen => '2001-01-01',
136             password => hash_password( PATRON_PW ),
137             branchcode => $branchcode,
138         },
139     });
140     my $cardnum = $seen_patron->{cardnumber};
141     my $sip_patron = C4::SIP::ILS::Patron->new( $cardnum );
142     $findpatron = $sip_patron;
143
144     my $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y         '.
145         FID_INST_ID. $branchcode. '|'.
146         FID_PATRON_ID. $cardnum. '|'.
147         FID_PATRON_PWD. PATRON_PW. '|';
148     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
149
150     my $server = { ils => $mocks->{ils} };
151     undef $response;
152     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '' );
153     $msg->handle_patron_info( $server );
154
155     isnt( $response, undef, 'At least we got a response.' );
156     my $respcode = substr( $response, 0, 2 );
157     is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
158     $seen_patron = Koha::Patrons->find({ cardnumber => $seen_patron->{cardnumber} });
159     is( output_pref({str => $seen_patron->lastseen(), dateonly => 1}), output_pref({str => '2001-01-01', dateonly => 1}),'Last seen not updated if not tracking patrons');
160     undef $response;
161     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
162     $msg->handle_patron_info( $server );
163
164     isnt( $response, undef, 'At least we got a response.' );
165     $respcode = substr( $response, 0, 2 );
166     is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
167     $seen_patron = Koha::Patrons->find({ cardnumber => $seen_patron->cardnumber() });
168     is( output_pref({str => $seen_patron->lastseen(), dateonly => 1}), output_pref({dt => dt_from_string(), dateonly => 1}),'Last seen updated if tracking patrons');
169     $schema->storage->txn_rollback;
170
171 };
172
173 subtest "Test build_additional_item_fields_string" => sub {
174     my $schema = Koha::Database->new->schema;
175     $schema->storage->txn_begin;
176
177     plan tests => 2;
178
179     my $builder = t::lib::TestBuilder->new();
180
181     my $item = $builder->build_sample_item;
182     my $ils_item = C4::SIP::ILS::Item->new( $item->barcode );
183
184     my $server = {};
185     $server->{account}->{item_field}->{code} = 'itemnumber';
186     $server->{account}->{item_field}->{field} = 'XY';
187     my $attribute_string = $ils_item->build_additional_item_fields_string( $server );
188     is( $attribute_string, "XY".$item->itemnumber."|", 'Attribute field generated correctly with single param' );
189
190     $server = {};
191     $server->{account}->{item_field}->[0]->{code} = 'itemnumber';
192     $server->{account}->{item_field}->[0]->{field} = 'XY';
193     $server->{account}->{item_field}->[1]->{code} = 'biblionumber';
194     $server->{account}->{item_field}->[1]->{field} = 'YZ';
195     $attribute_string = $ils_item->build_additional_item_fields_string( $server );
196     is( $attribute_string, sprintf("XY%s|YZ%s|", $item->itemnumber, $item->biblionumber), 'Attribute field generated correctly with multiple params' );
197
198     $schema->storage->txn_rollback;
199 };
200
201 subtest "Test cr_item_field" => sub {
202     plan tests => 1;
203
204     my $builder = t::lib::TestBuilder->new();
205     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
206     my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode};
207     my ( $response, $findpatron );
208     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
209
210     # create some data
211     my $patron1 = $builder->build({
212         source => 'Borrower',
213         value  => {
214             password => hash_password( PATRON_PW ),
215         },
216     });
217     my $card1 = $patron1->{cardnumber};
218     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
219     $findpatron = $sip_patron1;
220     my $item_object = $builder->build_sample_item({
221         damaged => 0,
222         withdrawn => 0,
223         itemlost => 0,
224         restricted => 0,
225         homebranch => $branchcode,
226         holdingbranch => $branchcode,
227     });
228
229     my $mockILS = $mocks->{ils};
230     my $server = { ils => $mockILS, account => {} };
231     $mockILS->mock( 'institution', sub { $branchcode; } );
232     $mockILS->mock( 'supports', sub { return; } );
233     $mockILS->mock( 'checkin', sub {
234         shift;
235         return C4::SIP::ILS->checkin(@_);
236     });
237     my $today = dt_from_string;
238
239     my $respcode;
240
241     # Not checked out, toggle option checked_in_ok
242     my $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' .
243         siprequestdate( $today->clone->add( days => 1) ) .
244         FID_INST_ID . $branchcode . '|'.
245         FID_ITEM_ID . $item_object->barcode . '|' .
246         FID_TERMINAL_PWD . 'ignored' . '|';
247     undef $response;
248     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
249
250     $server->{account}->{cr_item_field} = 'itemnumber';
251
252     $msg->handle_checkin( $server );
253
254     my $id = $item_object->id;
255     ok( $response =~ m/CR$id/, "Found correct CR field in response");
256 };
257
258 subtest 'Patron info summary > 5 should not crash server' => sub {
259
260     my $schema = Koha::Database->new->schema;
261     $schema->storage->txn_begin;
262
263     plan tests => 22;
264     my $builder = t::lib::TestBuilder->new();
265     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
266     my ( $response, $findpatron );
267     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
268     my $seen_patron = $builder->build({
269         source => 'Borrower',
270         value  => {
271             lastseen => '2001-01-01',
272             password => hash_password( PATRON_PW ),
273             branchcode => $branchcode,
274         },
275     });
276     my $cardnum = $seen_patron->{cardnumber};
277     my $sip_patron = C4::SIP::ILS::Patron->new( $cardnum );
278     $findpatron = $sip_patron;
279
280     my @summaries = (
281         '          ',
282         'Y         ',
283         ' Y        ',
284         '  Y       ',
285         '   Y      ',
286         '    Y     ',
287         '     Y    ',
288         '      Y   ',
289         '       Y  ',
290         '        Y ',
291         '         Y',
292     );
293     for my $summary ( @summaries ) {
294         my $siprequest = PATRON_INFO . 'engYYYYMMDDZZZZHHMMSS' . $summary .
295             FID_INST_ID . $branchcode . '|' .
296             FID_PATRON_ID . $cardnum . '|' .
297             FID_PATRON_PWD . PATRON_PW . '|';
298         my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
299
300         my $server = { ils => $mocks->{ils} };
301         undef $response;
302         $msg->handle_patron_info( $server );
303
304         isnt( $response, undef, 'At least we got a response.' );
305         my $respcode = substr( $response, 0, 2 );
306         is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
307     }
308
309     $schema->storage->txn_rollback;
310 };
311
312 # Here is room for some more subtests
313
314 # END of main code
315
316 sub test_request_patron_status_v2 {
317     my $builder = t::lib::TestBuilder->new();
318     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
319     my ( $response, $findpatron );
320     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
321
322     my $patron1 = $builder->build({
323         source => 'Borrower',
324         value  => {
325             password => hash_password( PATRON_PW ),
326         },
327     });
328     my $card1 = $patron1->{cardnumber};
329     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
330     $findpatron = $sip_patron1;
331
332     my $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
333         FID_INST_ID. $branchcode. '|'.
334         FID_PATRON_ID. $card1. '|'.
335         FID_PATRON_PWD. PATRON_PW. '|';
336     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
337
338     my $server = { ils => $mocks->{ils} };
339     undef $response;
340     $msg->handle_patron_status( $server );
341
342     isnt( $response, undef, 'At least we got a response.' );
343     my $respcode = substr( $response, 0, 2 );
344     is( $respcode, PATRON_STATUS_RESP, 'Response code fine' );
345
346     check_field( $respcode, $response, FID_INST_ID, $branchcode , 'Verified institution id' );
347     check_field( $respcode, $response, FID_PATRON_ID, $card1, 'Verified patron id' );
348     check_field( $respcode, $response, FID_PERSONAL_NAME, $patron1->{surname}, 'Verified patron name', 'contains' );
349     check_field( $respcode, $response, FID_VALID_PATRON, 'Y', 'Verified code BL' );
350     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'Verified code CQ' );
351     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'Verified non-empty screen message', 'regex' );
352
353     # Now, we pass a wrong password and verify CQ again
354     $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
355         FID_INST_ID. $branchcode. '|'.
356         FID_PATRON_ID. $card1. '|'.
357         FID_PATRON_PWD. 'wrong_password'. '|';
358     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
359     undef $response;
360     $msg->handle_patron_status( $server );
361     $respcode = substr( $response, 0, 2 );
362     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'Verified code CQ for wrong pw' );
363
364     # Check empty password and verify CQ again
365     $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
366         FID_INST_ID. $branchcode. '|'.
367         FID_PATRON_ID. $card1. '|'.
368         FID_PATRON_PWD. '|';
369     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
370     undef $response;
371     $msg->handle_patron_status( $server );
372     $respcode = substr( $response, 0, 2 );
373     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'code CQ should be N for empty AD' );
374
375     # Finally, we send a wrong card number and check AE, BL
376     # This is done by removing the new patron first
377     Koha::Patrons->search({ cardnumber => $card1 })->delete;
378     undef $findpatron;
379     $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
380         FID_INST_ID. $branchcode. '|'.
381         FID_PATRON_ID. $card1. '|'.
382         FID_PATRON_PWD. PATRON_PW. '|';
383     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
384     undef $response;
385     $msg->handle_patron_status( $server );
386     $respcode = substr( $response, 0, 2 );
387     check_field( $respcode, $response, FID_VALID_PATRON, 'N', 'Verified code BL for wrong cardnumber' );
388     check_field( $respcode, $response, FID_PERSONAL_NAME, '', 'Name should be empty now' );
389     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'But we have a screen msg', 'regex' );
390 }
391
392 sub test_request_patron_info_v2 {
393     my $builder = t::lib::TestBuilder->new();
394     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
395     my ( $response, $findpatron );
396     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
397
398     my $patron2 = $builder->build({
399         source => 'Borrower',
400         value  => {
401             password => hash_password( PATRON_PW ),
402         },
403     });
404     my $card = $patron2->{cardnumber};
405     my $sip_patron2 = C4::SIP::ILS::Patron->new( $card );
406     $findpatron = $sip_patron2;
407     my $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y         '.
408         FID_INST_ID. $branchcode. '|'.
409         FID_PATRON_ID. $card. '|'.
410         FID_PATRON_PWD. PATRON_PW. '|';
411     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
412
413     my $server = { ils => $mocks->{ils} };
414     undef $response;
415     $msg->handle_patron_info( $server );
416     isnt( $response, undef, 'At least we got a response.' );
417     my $respcode = substr( $response, 0, 2 );
418     is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
419
420     check_field( $respcode, $response, FID_INST_ID, $branchcode , 'Verified institution id' );
421     check_field( $respcode, $response, FID_PATRON_ID, $card, 'Verified patron id' );
422     check_field( $respcode, $response, FID_PERSONAL_NAME, $patron2->{surname}, 'Verified patron name', 'contains' );
423     check_field( $respcode, $response, FID_VALID_PATRON, 'Y', 'Verified code BL' );
424     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'Verified code CQ' );
425     check_field( $respcode, $response, FID_FEE_LMT, '.*', 'Checked existence of fee limit', 'regex' );
426     check_field( $respcode, $response, FID_HOME_ADDR, $patron2->{address}, 'Address in BD', 'contains' );
427     check_field( $respcode, $response, FID_EMAIL, $patron2->{email}, 'Verified email in BE' );
428     check_field( $respcode, $response, FID_HOME_PHONE, $patron2->{phone}, 'Verified home phone in BF' );
429     # No check for custom fields here (unofficial PB, PC and PI)
430     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'We have a screen msg', 'regex' );
431
432     # Test customized patron name in AE with same sip request
433     # This implicitly tests C4::SIP::ILS::Patron->name
434     $server->{account}->{ae_field_template} = "X[% patron.surname %]Y";
435     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
436     undef $response;
437     $msg->handle_patron_info( $server );
438     $respcode = substr( $response, 0, 2 );
439     check_field( $respcode, $response, FID_PERSONAL_NAME, 'X' . $patron2->{surname} . 'Y', 'Check customized patron name' );
440
441     undef $response;
442     $server->{account}->{hide_fields} = "BD,BE,BF,PB";
443     $msg->handle_patron_info( $server );
444     $respcode = substr( $response, 0, 2 );
445     check_field( $respcode, $response, FID_HOME_ADDR, undef, 'Home address successfully stripped from response' );
446     check_field( $respcode, $response, FID_EMAIL, undef, 'Email address successfully stripped from response' );
447     check_field( $respcode, $response, FID_HOME_PHONE, undef, 'Home phone successfully stripped from response' );
448     check_field( $respcode, $response, FID_PATRON_BIRTHDATE, undef, 'Date of birth successfully stripped from response' );
449     $server->{account}->{hide_fields} = "";
450
451     # Check empty password and verify CQ again
452     $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y         '.
453         FID_INST_ID. $branchcode. '|'.
454         FID_PATRON_ID. $card. '|'.
455         FID_PATRON_PWD. '|';
456     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
457     undef $response;
458     $msg->handle_patron_info( $server );
459     $respcode = substr( $response, 0, 2 );
460     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'code CQ should be N for empty AD' );
461     # Test empty password is OK if account configured to allow
462     $server->{account}->{allow_empty_passwords} = 1;
463     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
464     undef $response;
465     $msg->handle_patron_info( $server );
466     $respcode = substr( $response, 0, 2 );
467     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'code CQ should be Y if empty AD allowed' );
468
469     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', '1' );
470     my $patron = Koha::Patrons->find({ cardnumber => $card });
471     $patron->update({ login_attempts => 0 });
472     is( $patron->account_locked, 0, "Patron account not locked already" );
473     $msg->handle_patron_info( $server );
474     $patron = Koha::Patrons->find({ cardnumber => $card });
475     is( $patron->account_locked, 0, "Patron account is not locked by patron info messages with empty password" );
476
477     # Finally, we send a wrong card number
478     Koha::Patrons->search({ cardnumber => $card })->delete;
479     undef $findpatron;
480     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
481     undef $response;
482     $msg->handle_patron_info( $server );
483     $respcode = substr( $response, 0, 2 );
484     check_field( $respcode, $response, FID_VALID_PATRON, 'N', 'Verified code BL for wrong cardnumber' );
485     check_field( $respcode, $response, FID_PERSONAL_NAME, '', 'Name should be empty now' );
486     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'But we have a screen msg', 'regex' );
487 }
488
489 sub test_checkin_v2 {
490     my $builder = t::lib::TestBuilder->new();
491     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
492     my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode};
493     my ( $response, $findpatron );
494     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
495
496     # create some data
497     my $patron1 = $builder->build({
498         source => 'Borrower',
499         value  => {
500             password => hash_password( PATRON_PW ),
501         },
502     });
503     my $card1 = $patron1->{cardnumber};
504     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
505     $findpatron = $sip_patron1;
506     my $item_object = $builder->build_sample_item({
507         damaged => 0,
508         withdrawn => 0,
509         itemlost => 0,
510         restricted => 0,
511         homebranch => $branchcode,
512         holdingbranch => $branchcode,
513     });
514
515     my $mockILS = $mocks->{ils};
516     my $server = { ils => $mockILS, account => {} };
517     $mockILS->mock( 'institution', sub { $branchcode; } );
518     $mockILS->mock( 'supports', sub { return; } );
519     $mockILS->mock( 'checkin', sub {
520         shift;
521         return C4::SIP::ILS->checkin(@_);
522     });
523     my $today = dt_from_string;
524
525     # Checkin invalid barcode
526     Koha::Items->search({ barcode => 'not_to_be_found' })->delete;
527     my $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' .
528         siprequestdate( $today->clone->add( days => 1) ) .
529         FID_INST_ID . $branchcode . '|'.
530         FID_ITEM_ID . 'not_to_be_found' . '|' .
531         FID_TERMINAL_PWD . 'ignored' . '|';
532     undef $response;
533     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
534     warnings_like { $msg->handle_checkin( $server ); }
535         [ qr/No item 'not_to_be_found'/, qr/no item found in object to resensitize/ ],
536         'Checkin of invalid item with two warnings';
537     my $respcode = substr( $response, 0, 2 );
538     is( $respcode, CHECKIN_RESP, 'Response code fine' );
539     is( substr($response,2,1), '0', 'OK flag is false' );
540     is( substr($response,5,1), 'Y', 'Alert flag is set' );
541     check_field( $respcode, $response, FID_SCREEN_MSG, 'Invalid Item', 'Check screen msg', 'regex' );
542
543     # Not checked out, toggle option checked_in_ok
544     $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' .
545         siprequestdate( $today->clone->add( days => 1) ) .
546         FID_INST_ID . $branchcode . '|'.
547         FID_ITEM_ID . $item_object->barcode . '|' .
548         FID_TERMINAL_PWD . 'ignored' . '|';
549     undef $response;
550     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
551     $msg->handle_checkin( $server );
552     $respcode = substr( $response, 0, 2 );
553     is( substr($response,2,1), '0', 'OK flag is false when checking in an item that was not checked out' );
554     is( substr($response,5,1), 'Y', 'Alert flag is set' );
555     check_field( $respcode, $response, FID_SCREEN_MSG, 'not checked out', 'Check screen msg', 'regex' );
556     # Toggle option
557     $server->{account}->{checked_in_ok} = 1;
558     undef $response;
559     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
560     $msg->handle_checkin( $server );
561     is( substr($response,2,1), '1', 'OK flag is true now with checked_in_ok flag set when checking in an item that was not checked out' );
562     is( substr($response,5,1), 'N', 'Alert flag no longer set' );
563     check_field( $respcode, $response, FID_SCREEN_MSG, undef, 'No screen msg' );
564
565     # Move item to another holding branch to trigger CV of 04 with alert flag
566     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
567     $item_object->holdingbranch( $branchcode2 )->store();
568     undef $response;
569     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
570     $msg->handle_checkin( $server );
571     is( substr($response,5,1), 'Y', 'Alert flag is set with check_in_ok, item is checked in but needs transfer' );
572     check_field( $respcode, $response, FID_ALERT_TYPE, '04', 'Got FID_ALERT_TYPE (CV) field with value 04 ( needs transfer )' );
573     $item_object->holdingbranch( $branchcode )->store();
574     t::lib::Mocks::mock_preference( ' AllowReturnToBranch ', 'anywhere' );
575
576     $server->{account}->{cv_send_00_on_success} = 0;
577     undef $response;
578     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
579     $msg->handle_checkin( $server );
580     $respcode = substr( $response, 0, 2 );
581     check_field( $respcode, $response, FID_ALERT_TYPE, undef, 'No FID_ALERT_TYPE (CV) field' );
582     $server->{account}->{cv_send_00_on_success} = 1;
583     undef $response;
584     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
585     $msg->handle_checkin( $server );
586     $respcode = substr( $response, 0, 2 );
587     check_field( $respcode, $response, FID_ALERT_TYPE, '00', 'FID_ALERT_TYPE (CV) field is 00' );
588     $server->{account}->{checked_in_ok} = 0;
589     $server->{account}->{cv_send_00_on_success} = 0;
590
591     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '1' );
592     $server->{account}->{checked_in_ok} = 0;
593     $server->{account}->{cv_triggers_alert} = 0;
594     undef $response;
595     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
596     $msg->handle_checkin( $server );
597     $respcode = substr( $response, 0, 2 );
598     is( substr( $response, 5, 1 ), 'Y', 'Checkin without CV triggers alert flag when cv_triggers_alert is off' );
599     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '0' );
600     $server->{account}->{cv_triggers_alert} = 1;
601     undef $response;
602     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
603     $msg->handle_checkin( $server );
604     $respcode = substr( $response, 0, 2 );
605     is( substr( $response, 5, 1 ), 'N', 'Checkin without CV does not trigger alert flag when cv_triggers_alert is on' );
606     $server->{account}->{cv_triggers_alert} = 0;
607     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '1' );
608
609     $server->{account}->{checked_in_ok} = 1;
610     $server->{account}->{ct_always_send} = 0;
611     undef $response;
612     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
613     $msg->handle_checkin( $server );
614     $respcode = substr( $response, 0, 2 );
615     check_field( $respcode, $response, FID_DESTINATION_LOCATION, undef, 'No FID_DESTINATION_LOCATION (CT) field' );
616     $server->{account}->{ct_always_send} = 1;
617     undef $response;
618     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
619     $msg->handle_checkin( $server );
620     $respcode = substr( $response, 0, 2 );
621     check_field( $respcode, $response, FID_DESTINATION_LOCATION, q{}, 'FID_DESTINATION_LOCATION (CT) field is empty but present' );
622     $server->{account}->{checked_in_ok} = 0;
623     $server->{account}->{ct_always_send} = 0;
624
625     # Checkin at wrong branch: issue item and switch branch, and checkin
626     my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store;
627     $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
628     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
629     undef $response;
630     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
631     $msg->handle_checkin( $server );
632     is( substr($response,2,1), '0', 'OK flag is false when we check in at the wrong branch and we do not allow it' );
633     is( substr($response,5,1), 'Y', 'Alert flag is set' );
634     check_field( $respcode, $response, FID_SCREEN_MSG, 'Checkin failed', 'Check screen msg' );
635     $branchcode = $item_object->homebranch;  # switch back
636     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
637
638     # Data corrupted: add same issue_id to old_issues
639     Koha::Old::Checkout->new({ issue_id => $issue->issue_id })->store;
640     undef $response;
641     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
642     warnings_like { $msg->handle_checkin( $server ); }
643         [ qr/Duplicate entry/, qr/data corrupted/ ],
644         'DBIx error on duplicate issue_id';
645     is( substr($response,2,1), '0', 'OK flag is false when we encounter data corruption in old_issues' );
646     is( substr($response,5,1), 'Y', 'Alert flag is set' );
647     check_field( $respcode, $response, FID_SCREEN_MSG, 'Checkin failed: data problem', 'Check screen msg' );
648
649     # Finally checkin without problems (remove duplicate id)
650     Koha::Old::Checkouts->search({ issue_id => $issue->issue_id })->delete;
651     undef $response;
652     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
653     $msg->handle_checkin( $server );
654     is( substr($response,2,1), '1', 'OK flag is true when we checkin after removing the duplicate' );
655     is( substr($response,5,1), 'N', 'Alert flag is not set' );
656     is( Koha::Checkouts->find( $issue->issue_id ), undef,
657         'Issue record is gone now' );
658
659     # Test account option no_holds_check that prevents items on hold from being checked in via SIP
660     Koha::Old::Checkouts->search({ issue_id => $issue->issue_id })->delete;
661     $server->{account}->{holds_block_checkin} = 1;
662     my $reserve_id = AddReserve({
663         branchcode     => $branchcode,
664         borrowernumber => $patron1->{borrowernumber},
665         biblionumber   => $item_object->biblionumber,
666         priority       => 1,
667     });
668     my $hold = Koha::Holds->find( $reserve_id );
669     is( $hold->id, $reserve_id, "Hold was created successfully" );
670     undef $response;
671     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
672     $msg->handle_checkin( $server );
673     is( substr($response,2,1), '0', 'OK flag is false when we check in an item on hold and we do not allow it' );
674     is( substr($response,5,1), 'Y', 'Alert flag is set' );
675     check_field( $respcode, $response, FID_SCREEN_MSG, 'Item is on hold, please return to circulation desk', 'Screen message is correct' );
676     $hold->delete();
677     $server->{account}->{holds_block_checkin} = 0;
678
679 }
680
681 sub test_hold_patron_bcode {
682     my $builder = t::lib::TestBuilder->new();
683     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
684     my ( $response, $findpatron );
685     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
686
687     my $item = $builder->build_sample_item(
688         {
689             library => $branchcode
690         }
691     );
692
693     my $server = { ils => $mocks->{ils} };
694     my $sip_item = C4::SIP::ILS::Item->new( $item->barcode );
695
696     is( $sip_item->hold_patron_bcode, q{}, "SIP item with no hold returns empty string" );
697
698     my $resp .= C4::SIP::Sip::maybe_add( FID_CALL_NUMBER, $sip_item->hold_patron_bcode, $server );
699     is( $resp, q{}, "maybe_add returns empty string for SIP item with no hold returns empty string" );
700 }
701
702 # Helper routines
703
704 sub create_mocks {
705     my ( $response, $findpatron, $branchcode ) = @_; # referenced variables !
706
707     # mock write_msg (imported from Sip.pm into Message.pm)
708     my $mockMsg = Test::MockModule->new( 'C4::SIP::Sip::MsgType' );
709     $mockMsg->mock( 'write_msg', sub { $$response = $_[1]; } ); # save response
710
711     # mock ils object
712     my $mockILS = Test::MockObject->new;
713     $mockILS->mock( 'check_inst_id', sub {} );
714     $mockILS->mock( 'institution_id', sub { $$branchcode; } );
715     $mockILS->mock( 'find_patron', sub { $$findpatron; } );
716
717     return { ils => $mockILS, message => $mockMsg };
718 }
719
720 sub check_field {
721     my ( $code, $resp, $fld, $expr, $msg, $mode ) = @_;
722     # mode: contains || equals || regex (by default: equals)
723
724     # strip fixed part; prefix to simplify next regex
725     $resp = '|'. substr( $resp, fixed_length( $code ) );
726     my $fldval;
727     if( $resp =~ /\|$fld([^\|]*)\|/ ) {
728         $fldval = $1;
729     } elsif( !defined($expr) ) { # field should not be found
730         ok( 1, $msg );
731         return;
732     } else { # test fails
733         is( 0, 1, "Code $fld not found in '$resp'?" );
734         return;
735     }
736
737     if( !$mode || $mode eq 'equals' ) { # default
738         is( $fldval, $expr, $msg );
739     } elsif( $mode eq 'regex' ) {
740         is( $fldval =~ /$expr/, 1, $msg );
741     } else { # contains
742         is( index( $fldval, $expr ) > -1, 1, $msg );
743     }
744 }
745
746 sub siprequestdate {
747     my ( $dt ) = @_;
748     return $dt->ymd('').(' 'x4).$dt->hms('');
749 }
750
751 sub fixed_length { #length of fixed fields including response code
752     return {
753       ( PATRON_STATUS_RESP )  => 37,
754       ( PATRON_INFO_RESP )    => 61,
755       ( CHECKIN_RESP )        => 24,
756     }->{$_[0]};
757 }