Bug 25541: Add ability to prevent checkin via SIP of items with holds
[koha.git] / 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 => 8;
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 'Patron info summary > 5 should not crash server' => sub {
202
203     my $schema = Koha::Database->new->schema;
204     $schema->storage->txn_begin;
205
206     plan tests => 22;
207     my $builder = t::lib::TestBuilder->new();
208     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
209     my ( $response, $findpatron );
210     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
211     my $seen_patron = $builder->build({
212         source => 'Borrower',
213         value  => {
214             lastseen => '2001-01-01',
215             password => hash_password( PATRON_PW ),
216             branchcode => $branchcode,
217         },
218     });
219     my $cardnum = $seen_patron->{cardnumber};
220     my $sip_patron = C4::SIP::ILS::Patron->new( $cardnum );
221     $findpatron = $sip_patron;
222
223     my @summaries = (
224         '          ',
225         'Y         ',
226         ' Y        ',
227         '  Y       ',
228         '   Y      ',
229         '    Y     ',
230         '     Y    ',
231         '      Y   ',
232         '       Y  ',
233         '        Y ',
234         '         Y',
235     );
236     for my $summary ( @summaries ) {
237         my $siprequest = PATRON_INFO . 'engYYYYMMDDZZZZHHMMSS' . $summary .
238             FID_INST_ID . $branchcode . '|' .
239             FID_PATRON_ID . $cardnum . '|' .
240             FID_PATRON_PWD . PATRON_PW . '|';
241         my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
242
243         my $server = { ils => $mocks->{ils} };
244         undef $response;
245         $msg->handle_patron_info( $server );
246
247         isnt( $response, undef, 'At least we got a response.' );
248         my $respcode = substr( $response, 0, 2 );
249         is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
250     }
251
252     $schema->storage->txn_rollback;
253 };
254
255 # Here is room for some more subtests
256
257 # END of main code
258
259 sub test_request_patron_status_v2 {
260     my $builder = t::lib::TestBuilder->new();
261     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
262     my ( $response, $findpatron );
263     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
264
265     my $patron1 = $builder->build({
266         source => 'Borrower',
267         value  => {
268             password => hash_password( PATRON_PW ),
269         },
270     });
271     my $card1 = $patron1->{cardnumber};
272     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
273     $findpatron = $sip_patron1;
274
275     my $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
276         FID_INST_ID. $branchcode. '|'.
277         FID_PATRON_ID. $card1. '|'.
278         FID_PATRON_PWD. PATRON_PW. '|';
279     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
280
281     my $server = { ils => $mocks->{ils} };
282     undef $response;
283     $msg->handle_patron_status( $server );
284
285     isnt( $response, undef, 'At least we got a response.' );
286     my $respcode = substr( $response, 0, 2 );
287     is( $respcode, PATRON_STATUS_RESP, 'Response code fine' );
288
289     check_field( $respcode, $response, FID_INST_ID, $branchcode , 'Verified institution id' );
290     check_field( $respcode, $response, FID_PATRON_ID, $card1, 'Verified patron id' );
291     check_field( $respcode, $response, FID_PERSONAL_NAME, $patron1->{surname}, 'Verified patron name', 'contains' );
292     check_field( $respcode, $response, FID_VALID_PATRON, 'Y', 'Verified code BL' );
293     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'Verified code CQ' );
294     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'Verified non-empty screen message', 'regex' );
295
296     # Now, we pass a wrong password and verify CQ again
297     $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
298         FID_INST_ID. $branchcode. '|'.
299         FID_PATRON_ID. $card1. '|'.
300         FID_PATRON_PWD. 'wrong_password'. '|';
301     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
302     undef $response;
303     $msg->handle_patron_status( $server );
304     $respcode = substr( $response, 0, 2 );
305     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'Verified code CQ for wrong pw' );
306
307     # Check empty password and verify CQ again
308     $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
309         FID_INST_ID. $branchcode. '|'.
310         FID_PATRON_ID. $card1. '|'.
311         FID_PATRON_PWD. '|';
312     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
313     undef $response;
314     $msg->handle_patron_status( $server );
315     $respcode = substr( $response, 0, 2 );
316     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'code CQ should be N for empty AD' );
317
318     # Finally, we send a wrong card number and check AE, BL
319     # This is done by removing the new patron first
320     Koha::Patrons->search({ cardnumber => $card1 })->delete;
321     undef $findpatron;
322     $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
323         FID_INST_ID. $branchcode. '|'.
324         FID_PATRON_ID. $card1. '|'.
325         FID_PATRON_PWD. PATRON_PW. '|';
326     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
327     undef $response;
328     $msg->handle_patron_status( $server );
329     $respcode = substr( $response, 0, 2 );
330     check_field( $respcode, $response, FID_VALID_PATRON, 'N', 'Verified code BL for wrong cardnumber' );
331     check_field( $respcode, $response, FID_PERSONAL_NAME, '', 'Name should be empty now' );
332     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'But we have a screen msg', 'regex' );
333 }
334
335 sub test_request_patron_info_v2 {
336     my $builder = t::lib::TestBuilder->new();
337     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
338     my ( $response, $findpatron );
339     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
340
341     my $patron2 = $builder->build({
342         source => 'Borrower',
343         value  => {
344             password => hash_password( PATRON_PW ),
345         },
346     });
347     my $card = $patron2->{cardnumber};
348     my $sip_patron2 = C4::SIP::ILS::Patron->new( $card );
349     $findpatron = $sip_patron2;
350     my $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y         '.
351         FID_INST_ID. $branchcode. '|'.
352         FID_PATRON_ID. $card. '|'.
353         FID_PATRON_PWD. PATRON_PW. '|';
354     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
355
356     my $server = { ils => $mocks->{ils} };
357     undef $response;
358     $msg->handle_patron_info( $server );
359     isnt( $response, undef, 'At least we got a response.' );
360     my $respcode = substr( $response, 0, 2 );
361     is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
362
363     check_field( $respcode, $response, FID_INST_ID, $branchcode , 'Verified institution id' );
364     check_field( $respcode, $response, FID_PATRON_ID, $card, 'Verified patron id' );
365     check_field( $respcode, $response, FID_PERSONAL_NAME, $patron2->{surname}, 'Verified patron name', 'contains' );
366     check_field( $respcode, $response, FID_VALID_PATRON, 'Y', 'Verified code BL' );
367     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'Verified code CQ' );
368     check_field( $respcode, $response, FID_FEE_LMT, '.*', 'Checked existence of fee limit', 'regex' );
369     check_field( $respcode, $response, FID_HOME_ADDR, $patron2->{address}, 'Address in BD', 'contains' );
370     check_field( $respcode, $response, FID_EMAIL, $patron2->{email}, 'Verified email in BE' );
371     check_field( $respcode, $response, FID_HOME_PHONE, $patron2->{phone}, 'Verified home phone in BF' );
372     # No check for custom fields here (unofficial PB, PC and PI)
373     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'We have a screen msg', 'regex' );
374
375     # Test customized patron name in AE with same sip request
376     # This implicitly tests C4::SIP::ILS::Patron->name
377     $server->{account}->{ae_field_template} = "X[% patron.surname %]Y";
378     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
379     undef $response;
380     $msg->handle_patron_info( $server );
381     $respcode = substr( $response, 0, 2 );
382     check_field( $respcode, $response, FID_PERSONAL_NAME, 'X' . $patron2->{surname} . 'Y', 'Check customized patron name' );
383
384     undef $response;
385     $server->{account}->{hide_fields} = "BD,BE,BF,PB";
386     $msg->handle_patron_info( $server );
387     $respcode = substr( $response, 0, 2 );
388     check_field( $respcode, $response, FID_HOME_ADDR, undef, 'Home address successfully stripped from response' );
389     check_field( $respcode, $response, FID_EMAIL, undef, 'Email address successfully stripped from response' );
390     check_field( $respcode, $response, FID_HOME_PHONE, undef, 'Home phone successfully stripped from response' );
391     check_field( $respcode, $response, FID_PATRON_BIRTHDATE, undef, 'Date of birth successfully stripped from response' );
392     $server->{account}->{hide_fields} = "";
393
394     # Check empty password and verify CQ again
395     $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y         '.
396         FID_INST_ID. $branchcode. '|'.
397         FID_PATRON_ID. $card. '|'.
398         FID_PATRON_PWD. '|';
399     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
400     undef $response;
401     $msg->handle_patron_info( $server );
402     $respcode = substr( $response, 0, 2 );
403     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'code CQ should be N for empty AD' );
404     # Test empty password is OK if account configured to allow
405     $server->{account}->{allow_empty_passwords} = 1;
406     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
407     undef $response;
408     $msg->handle_patron_info( $server );
409     $respcode = substr( $response, 0, 2 );
410     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'code CQ should be Y if empty AD allowed' );
411
412     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', '1' );
413     my $patron = Koha::Patrons->find({ cardnumber => $card });
414     $patron->update({ login_attempts => 0 });
415     is( $patron->account_locked, 0, "Patron account not locked already" );
416     $msg->handle_patron_info( $server );
417     $patron = Koha::Patrons->find({ cardnumber => $card });
418     is( $patron->account_locked, 0, "Patron account is not locked by patron info messages with empty password" );
419
420     # Finally, we send a wrong card number
421     Koha::Patrons->search({ cardnumber => $card })->delete;
422     undef $findpatron;
423     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
424     undef $response;
425     $msg->handle_patron_info( $server );
426     $respcode = substr( $response, 0, 2 );
427     check_field( $respcode, $response, FID_VALID_PATRON, 'N', 'Verified code BL for wrong cardnumber' );
428     check_field( $respcode, $response, FID_PERSONAL_NAME, '', 'Name should be empty now' );
429     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'But we have a screen msg', 'regex' );
430 }
431
432 sub test_checkin_v2 {
433     my $builder = t::lib::TestBuilder->new();
434     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
435     my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode};
436     my ( $response, $findpatron );
437     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
438
439     # create some data
440     my $patron1 = $builder->build({
441         source => 'Borrower',
442         value  => {
443             password => hash_password( PATRON_PW ),
444         },
445     });
446     my $card1 = $patron1->{cardnumber};
447     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
448     $findpatron = $sip_patron1;
449     my $item_object = $builder->build_sample_item({
450         damaged => 0,
451         withdrawn => 0,
452         itemlost => 0,
453         restricted => 0,
454         homebranch => $branchcode,
455         holdingbranch => $branchcode,
456     });
457
458     my $mockILS = $mocks->{ils};
459     my $server = { ils => $mockILS, account => {} };
460     $mockILS->mock( 'institution', sub { $branchcode; } );
461     $mockILS->mock( 'supports', sub { return; } );
462     $mockILS->mock( 'checkin', sub {
463         shift;
464         return C4::SIP::ILS->checkin(@_);
465     });
466     my $today = dt_from_string;
467
468     # Checkin invalid barcode
469     Koha::Items->search({ barcode => 'not_to_be_found' })->delete;
470     my $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' .
471         siprequestdate( $today->clone->add( days => 1) ) .
472         FID_INST_ID . $branchcode . '|'.
473         FID_ITEM_ID . 'not_to_be_found' . '|' .
474         FID_TERMINAL_PWD . 'ignored' . '|';
475     undef $response;
476     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
477     warnings_like { $msg->handle_checkin( $server ); }
478         [ qr/No item 'not_to_be_found'/, qr/no item found in object to resensitize/ ],
479         'Checkin of invalid item with two warnings';
480     my $respcode = substr( $response, 0, 2 );
481     is( $respcode, CHECKIN_RESP, 'Response code fine' );
482     is( substr($response,2,1), '0', 'OK flag is false' );
483     is( substr($response,5,1), 'Y', 'Alert flag is set' );
484     check_field( $respcode, $response, FID_SCREEN_MSG, 'Invalid Item', 'Check screen msg', 'regex' );
485
486     # Not checked out, toggle option checked_in_ok
487     $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' .
488         siprequestdate( $today->clone->add( days => 1) ) .
489         FID_INST_ID . $branchcode . '|'.
490         FID_ITEM_ID . $item_object->barcode . '|' .
491         FID_TERMINAL_PWD . 'ignored' . '|';
492     undef $response;
493     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
494     $msg->handle_checkin( $server );
495     $respcode = substr( $response, 0, 2 );
496     is( substr($response,2,1), '0', 'OK flag is false when checking in an item that was not checked out' );
497     is( substr($response,5,1), 'Y', 'Alert flag is set' );
498     check_field( $respcode, $response, FID_SCREEN_MSG, 'not checked out', 'Check screen msg', 'regex' );
499     # Toggle option
500     $server->{account}->{checked_in_ok} = 1;
501     undef $response;
502     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
503     $msg->handle_checkin( $server );
504     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' );
505     is( substr($response,5,1), 'N', 'Alert flag no longer set' );
506     check_field( $respcode, $response, FID_SCREEN_MSG, undef, 'No screen msg' );
507
508     # Move item to another holding branch to trigger CV of 04 with alert flag
509     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
510     $item_object->holdingbranch( $branchcode2 )->store();
511     undef $response;
512     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
513     $msg->handle_checkin( $server );
514     is( substr($response,5,1), 'Y', 'Alert flag is set with check_in_ok, item is checked in but needs transfer' );
515     check_field( $respcode, $response, FID_ALERT_TYPE, '04', 'Got FID_ALERT_TYPE (CV) field with value 04 ( needs transfer )' );
516     $item_object->holdingbranch( $branchcode )->store();
517     t::lib::Mocks::mock_preference( ' AllowReturnToBranch ', 'anywhere' );
518
519     $server->{account}->{cv_send_00_on_success} = 0;
520     undef $response;
521     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
522     $msg->handle_checkin( $server );
523     $respcode = substr( $response, 0, 2 );
524     check_field( $respcode, $response, FID_ALERT_TYPE, undef, 'No FID_ALERT_TYPE (CV) field' );
525     $server->{account}->{cv_send_00_on_success} = 1;
526     undef $response;
527     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
528     $msg->handle_checkin( $server );
529     $respcode = substr( $response, 0, 2 );
530     check_field( $respcode, $response, FID_ALERT_TYPE, '00', 'FID_ALERT_TYPE (CV) field is 00' );
531     $server->{account}->{checked_in_ok} = 0;
532     $server->{account}->{cv_send_00_on_success} = 0;
533
534     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '1' );
535     $server->{account}->{checked_in_ok} = 0;
536     $server->{account}->{cv_triggers_alert} = 0;
537     undef $response;
538     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
539     $msg->handle_checkin( $server );
540     $respcode = substr( $response, 0, 2 );
541     is( substr( $response, 5, 1 ), 'Y', 'Checkin without CV triggers alert flag when cv_triggers_alert is off' );
542     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '0' );
543     $server->{account}->{cv_triggers_alert} = 1;
544     undef $response;
545     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
546     $msg->handle_checkin( $server );
547     $respcode = substr( $response, 0, 2 );
548     is( substr( $response, 5, 1 ), 'N', 'Checkin without CV does not trigger alert flag when cv_triggers_alert is on' );
549     $server->{account}->{cv_triggers_alert} = 0;
550     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '1' );
551
552     $server->{account}->{checked_in_ok} = 1;
553     $server->{account}->{ct_always_send} = 0;
554     undef $response;
555     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
556     $msg->handle_checkin( $server );
557     $respcode = substr( $response, 0, 2 );
558     check_field( $respcode, $response, FID_DESTINATION_LOCATION, undef, 'No FID_DESTINATION_LOCATION (CT) field' );
559     $server->{account}->{ct_always_send} = 1;
560     undef $response;
561     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
562     $msg->handle_checkin( $server );
563     $respcode = substr( $response, 0, 2 );
564     check_field( $respcode, $response, FID_DESTINATION_LOCATION, q{}, 'FID_DESTINATION_LOCATION (CT) field is empty but present' );
565     $server->{account}->{checked_in_ok} = 0;
566     $server->{account}->{ct_always_send} = 0;
567
568     # Checkin at wrong branch: issue item and switch branch, and checkin
569     my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store;
570     $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
571     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
572     undef $response;
573     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
574     $msg->handle_checkin( $server );
575     is( substr($response,2,1), '0', 'OK flag is false when we check in at the wrong branch and we do not allow it' );
576     is( substr($response,5,1), 'Y', 'Alert flag is set' );
577     check_field( $respcode, $response, FID_SCREEN_MSG, 'Checkin failed', 'Check screen msg' );
578     $branchcode = $item_object->homebranch;  # switch back
579     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
580
581     # Data corrupted: add same issue_id to old_issues
582     Koha::Old::Checkout->new({ issue_id => $issue->issue_id })->store;
583     undef $response;
584     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
585     warnings_like { $msg->handle_checkin( $server ); }
586         [ qr/Duplicate entry/, qr/data corrupted/ ],
587         'DBIx error on duplicate issue_id';
588     is( substr($response,2,1), '0', 'OK flag is false when we encounter data corruption in old_issues' );
589     is( substr($response,5,1), 'Y', 'Alert flag is set' );
590     check_field( $respcode, $response, FID_SCREEN_MSG, 'Checkin failed: data problem', 'Check screen msg' );
591
592     # Finally checkin without problems (remove duplicate id)
593     Koha::Old::Checkouts->search({ issue_id => $issue->issue_id })->delete;
594     undef $response;
595     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
596     $msg->handle_checkin( $server );
597     is( substr($response,2,1), '1', 'OK flag is true when we checkin after removing the duplicate' );
598     is( substr($response,5,1), 'N', 'Alert flag is not set' );
599     is( Koha::Checkouts->find( $issue->issue_id ), undef,
600         'Issue record is gone now' );
601
602     # Test account option no_holds_check that prevents items on hold from being checked in via SIP
603     Koha::Old::Checkouts->search({ issue_id => $issue->issue_id })->delete;
604     $server->{account}->{no_holds_checkin} = 1;
605     my $reserve_id = AddReserve({
606         branchcode     => $branchcode,
607         borrowernumber => $patron1->{borrowernumber},
608         biblionumber   => $item_object->biblionumber,
609         priority       => 1,
610     });
611     my $hold = Koha::Holds->find( $reserve_id );
612     is( $hold->id, $reserve_id, "Hold was created successfully" );
613     undef $response;
614     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
615     $msg->handle_checkin( $server );
616     is( substr($response,2,1), '0', 'OK flag is false when we check in an item on hold and we do not allow it' );
617     is( substr($response,5,1), 'Y', 'Alert flag is set' );
618     check_field( $respcode, $response, FID_SCREEN_MSG, 'Item is on hold, please return to circulation desk', 'Screen message is correct' );
619     $hold->delete();
620     $server->{account}->{no_holds_checkin} = 0;
621
622 }
623
624 sub test_hold_patron_bcode {
625     my $builder = t::lib::TestBuilder->new();
626     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
627     my ( $response, $findpatron );
628     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
629
630     my $item = $builder->build_sample_item(
631         {
632             library => $branchcode
633         }
634     );
635
636     my $server = { ils => $mocks->{ils} };
637     my $sip_item = C4::SIP::ILS::Item->new( $item->barcode );
638
639     is( $sip_item->hold_patron_bcode, q{}, "SIP item with no hold returns empty string" );
640
641     my $resp .= C4::SIP::Sip::maybe_add( FID_CALL_NUMBER, $sip_item->hold_patron_bcode, $server );
642     is( $resp, q{}, "maybe_add returns empty string for SIP item with no hold returns empty string" );
643 }
644
645 # Helper routines
646
647 sub create_mocks {
648     my ( $response, $findpatron, $branchcode ) = @_; # referenced variables !
649
650     # mock write_msg (imported from Sip.pm into Message.pm)
651     my $mockMsg = Test::MockModule->new( 'C4::SIP::Sip::MsgType' );
652     $mockMsg->mock( 'write_msg', sub { $$response = $_[1]; } ); # save response
653
654     # mock ils object
655     my $mockILS = Test::MockObject->new;
656     $mockILS->mock( 'check_inst_id', sub {} );
657     $mockILS->mock( 'institution_id', sub { $$branchcode; } );
658     $mockILS->mock( 'find_patron', sub { $$findpatron; } );
659
660     return { ils => $mockILS, message => $mockMsg };
661 }
662
663 sub check_field {
664     my ( $code, $resp, $fld, $expr, $msg, $mode ) = @_;
665     # mode: contains || equals || regex (by default: equals)
666
667     # strip fixed part; prefix to simplify next regex
668     $resp = '|'. substr( $resp, fixed_length( $code ) );
669     my $fldval;
670     if( $resp =~ /\|$fld([^\|]*)\|/ ) {
671         $fldval = $1;
672     } elsif( !defined($expr) ) { # field should not be found
673         ok( 1, $msg );
674         return;
675     } else { # test fails
676         is( 0, 1, "Code $fld not found in '$resp'?" );
677         return;
678     }
679
680     if( !$mode || $mode eq 'equals' ) { # default
681         is( $fldval, $expr, $msg );
682     } elsif( $mode eq 'regex' ) {
683         is( $fldval =~ /$expr/, 1, $msg );
684     } else { # contains
685         is( index( $fldval, $expr ) > -1, 1, $msg );
686     }
687 }
688
689 sub siprequestdate {
690     my ( $dt ) = @_;
691     return $dt->ymd('').(' 'x4).$dt->hms('');
692 }
693
694 sub fixed_length { #length of fixed fields including response code
695     return {
696       ( PATRON_STATUS_RESP )  => 37,
697       ( PATRON_INFO_RESP )    => 61,
698       ( CHECKIN_RESP )        => 24,
699     }->{$_[0]};
700 }