Bug 24165: Add ability to send any item field in a library chosen SIP field
[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 => 7;
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 Koha::Database;
33 use Koha::AuthUtils qw(hash_password);
34 use Koha::DateUtils;
35 use Koha::Items;
36 use Koha::Checkouts;
37 use Koha::Old::Checkouts;
38 use Koha::Patrons;
39
40 use C4::SIP::ILS;
41 use C4::SIP::ILS::Patron;
42 use C4::SIP::Sip qw(write_msg);
43 use C4::SIP::Sip::Constants qw(:all);
44 use C4::SIP::Sip::MsgType;
45
46 use constant PATRON_PW => 'do_not_ever_use_this_one';
47
48 # START testing
49 subtest 'Testing Patron Status Request V2' => sub {
50     my $schema = Koha::Database->new->schema;
51     $schema->storage->txn_begin;
52     plan tests => 13;
53     $C4::SIP::Sip::protocol_version = 2;
54     test_request_patron_status_v2();
55     $schema->storage->txn_rollback;
56 };
57
58 subtest 'Testing Patron Info Request V2' => sub {
59     my $schema = Koha::Database->new->schema;
60     $schema->storage->txn_begin;
61     plan tests => 24;
62     $C4::SIP::Sip::protocol_version = 2;
63     test_request_patron_info_v2();
64     $schema->storage->txn_rollback;
65 };
66
67 subtest 'Checkin V2' => sub {
68     my $schema = Koha::Database->new->schema;
69     $schema->storage->txn_begin;
70     plan tests => 29;
71     $C4::SIP::Sip::protocol_version = 2;
72     test_checkin_v2();
73     $schema->storage->txn_rollback;
74 };
75
76 subtest 'Test hold_patron_bcode' => sub {
77     my $schema = Koha::Database->new->schema;
78     $schema->storage->txn_begin;
79     plan tests => 2;
80     $C4::SIP::Sip::protocol_version = 2;
81     test_hold_patron_bcode();
82     $schema->storage->txn_rollback;
83 };
84
85 subtest 'hold_patron_name() tests' => sub {
86
87     plan tests => 2;
88
89     my $schema = Koha::Database->new->schema;
90     $schema->storage->txn_begin;
91
92     my $builder = t::lib::TestBuilder->new();
93
94     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
95     my ( $response, $findpatron );
96     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
97
98     my $item = $builder->build_sample_item(
99         {
100             damaged       => 0,
101             withdrawn     => 0,
102             itemlost      => 0,
103             restricted    => 0,
104             homebranch    => $branchcode,
105             holdingbranch => $branchcode
106         }
107     );
108
109     my $server = { ils => $mocks->{ils} };
110     my $sip_item = C4::SIP::ILS::Item->new( $item->barcode );
111
112     is( $sip_item->hold_patron_name, q{}, "SIP item with no hold returns empty string for patron name" );
113
114     my $resp .= C4::SIP::Sip::maybe_add( FID_CALL_NUMBER, $sip_item->hold_patron_name, $server );
115     is( $resp, q{}, "maybe_add returns empty string for SIP item with no hold returns empty string" );
116
117     $schema->storage->txn_rollback;
118 };
119
120 subtest 'Lastseen response' => sub {
121
122     my $schema = Koha::Database->new->schema;
123     $schema->storage->txn_begin;
124
125     plan tests => 6;
126     my $builder = t::lib::TestBuilder->new();
127     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
128     my ( $response, $findpatron );
129     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
130     my $seen_patron = $builder->build({
131         source => 'Borrower',
132         value  => {
133             lastseen => '2001-01-01',
134             password => hash_password( PATRON_PW ),
135             branchcode => $branchcode,
136         },
137     });
138     my $cardnum = $seen_patron->{cardnumber};
139     my $sip_patron = C4::SIP::ILS::Patron->new( $cardnum );
140     $findpatron = $sip_patron;
141
142     my $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y         '.
143         FID_INST_ID. $branchcode. '|'.
144         FID_PATRON_ID. $cardnum. '|'.
145         FID_PATRON_PWD. PATRON_PW. '|';
146     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
147
148     my $server = { ils => $mocks->{ils} };
149     undef $response;
150     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '' );
151     $msg->handle_patron_info( $server );
152
153     isnt( $response, undef, 'At least we got a response.' );
154     my $respcode = substr( $response, 0, 2 );
155     is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
156     $seen_patron = Koha::Patrons->find({ cardnumber => $seen_patron->{cardnumber} });
157     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');
158     undef $response;
159     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
160     $msg->handle_patron_info( $server );
161
162     isnt( $response, undef, 'At least we got a response.' );
163     $respcode = substr( $response, 0, 2 );
164     is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
165     $seen_patron = Koha::Patrons->find({ cardnumber => $seen_patron->cardnumber() });
166     is( output_pref({str => $seen_patron->lastseen(), dateonly => 1}), output_pref({dt => dt_from_string(), dateonly => 1}),'Last seen updated if tracking patrons');
167     $schema->storage->txn_rollback;
168
169 };
170
171 subtest "Test build_additional_item_fields_string" => sub {
172     my $schema = Koha::Database->new->schema;
173     $schema->storage->txn_begin;
174
175     plan tests => 2;
176
177     my $builder = t::lib::TestBuilder->new();
178
179     my $item = $builder->build( { source => 'Item' } );
180     my $ils_item = C4::SIP::ILS::Item->new( $item->{barcode} );
181
182     my $server = {};
183     $server->{account}->{item_field}->{code} = 'itemnumber';
184     $server->{account}->{item_field}->{field} = 'XY';
185     my $attribute_string = $ils_item->build_additional_item_fields_string( $server );
186     is( $attribute_string, "XY$item->{itemnumber}|", 'Attribute field generated correctly with single param' );
187
188     $server = {};
189     $server->{account}->{item_field}->[0]->{code} = 'itemnumber';
190     $server->{account}->{item_field}->[0]->{field} = 'XY';
191     $server->{account}->{item_field}->[1]->{code} = 'biblionumber';
192     $server->{account}->{item_field}->[1]->{field} = 'YZ';
193     $attribute_string = $ils_item->build_additional_item_fields_string( $server );
194     is( $attribute_string, "XY$item->{itemnumber}|YZ$item->{biblionumber}|", 'Attribute field generated correctly with multiple params' );
195
196     $schema->storage->txn_rollback;
197 };
198
199 # Here is room for some more subtests
200
201 # END of main code
202
203 sub test_request_patron_status_v2 {
204     my $builder = t::lib::TestBuilder->new();
205     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
206     my ( $response, $findpatron );
207     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
208
209     my $patron1 = $builder->build({
210         source => 'Borrower',
211         value  => {
212             password => hash_password( PATRON_PW ),
213         },
214     });
215     my $card1 = $patron1->{cardnumber};
216     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
217     $findpatron = $sip_patron1;
218
219     my $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
220         FID_INST_ID. $branchcode. '|'.
221         FID_PATRON_ID. $card1. '|'.
222         FID_PATRON_PWD. PATRON_PW. '|';
223     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
224
225     my $server = { ils => $mocks->{ils} };
226     undef $response;
227     $msg->handle_patron_status( $server );
228
229     isnt( $response, undef, 'At least we got a response.' );
230     my $respcode = substr( $response, 0, 2 );
231     is( $respcode, PATRON_STATUS_RESP, 'Response code fine' );
232
233     check_field( $respcode, $response, FID_INST_ID, $branchcode , 'Verified institution id' );
234     check_field( $respcode, $response, FID_PATRON_ID, $card1, 'Verified patron id' );
235     check_field( $respcode, $response, FID_PERSONAL_NAME, $patron1->{surname}, 'Verified patron name', 'contains' );
236     check_field( $respcode, $response, FID_VALID_PATRON, 'Y', 'Verified code BL' );
237     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'Verified code CQ' );
238     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'Verified non-empty screen message', 'regex' );
239
240     # Now, we pass a wrong password and verify CQ again
241     $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
242         FID_INST_ID. $branchcode. '|'.
243         FID_PATRON_ID. $card1. '|'.
244         FID_PATRON_PWD. 'wrong_password'. '|';
245     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
246     undef $response;
247     $msg->handle_patron_status( $server );
248     $respcode = substr( $response, 0, 2 );
249     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'Verified code CQ for wrong pw' );
250
251     # Check empty password and verify CQ again
252     $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
253         FID_INST_ID. $branchcode. '|'.
254         FID_PATRON_ID. $card1. '|'.
255         FID_PATRON_PWD. '|';
256     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
257     undef $response;
258     $msg->handle_patron_status( $server );
259     $respcode = substr( $response, 0, 2 );
260     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'code CQ should be N for empty AD' );
261
262     # Finally, we send a wrong card number and check AE, BL
263     # This is done by removing the new patron first
264     Koha::Patrons->search({ cardnumber => $card1 })->delete;
265     undef $findpatron;
266     $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
267         FID_INST_ID. $branchcode. '|'.
268         FID_PATRON_ID. $card1. '|'.
269         FID_PATRON_PWD. PATRON_PW. '|';
270     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
271     undef $response;
272     $msg->handle_patron_status( $server );
273     $respcode = substr( $response, 0, 2 );
274     check_field( $respcode, $response, FID_VALID_PATRON, 'N', 'Verified code BL for wrong cardnumber' );
275     check_field( $respcode, $response, FID_PERSONAL_NAME, '', 'Name should be empty now' );
276     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'But we have a screen msg', 'regex' );
277 }
278
279 sub test_request_patron_info_v2 {
280     my $builder = t::lib::TestBuilder->new();
281     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
282     my ( $response, $findpatron );
283     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
284
285     my $patron2 = $builder->build({
286         source => 'Borrower',
287         value  => {
288             password => hash_password( PATRON_PW ),
289         },
290     });
291     my $card = $patron2->{cardnumber};
292     my $sip_patron2 = C4::SIP::ILS::Patron->new( $card );
293     $findpatron = $sip_patron2;
294     my $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y         '.
295         FID_INST_ID. $branchcode. '|'.
296         FID_PATRON_ID. $card. '|'.
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     isnt( $response, undef, 'At least we got a response.' );
304     my $respcode = substr( $response, 0, 2 );
305     is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
306
307     check_field( $respcode, $response, FID_INST_ID, $branchcode , 'Verified institution id' );
308     check_field( $respcode, $response, FID_PATRON_ID, $card, 'Verified patron id' );
309     check_field( $respcode, $response, FID_PERSONAL_NAME, $patron2->{surname}, 'Verified patron name', 'contains' );
310     check_field( $respcode, $response, FID_VALID_PATRON, 'Y', 'Verified code BL' );
311     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'Verified code CQ' );
312     check_field( $respcode, $response, FID_FEE_LMT, '.*', 'Checked existence of fee limit', 'regex' );
313     check_field( $respcode, $response, FID_HOME_ADDR, $patron2->{address}, 'Address in BD', 'contains' );
314     check_field( $respcode, $response, FID_EMAIL, $patron2->{email}, 'Verified email in BE' );
315     check_field( $respcode, $response, FID_HOME_PHONE, $patron2->{phone}, 'Verified home phone in BF' );
316     # No check for custom fields here (unofficial PB, PC and PI)
317     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'We have a screen msg', 'regex' );
318
319     # Test customized patron name in AE with same sip request
320     # This implicitly tests C4::SIP::ILS::Patron->name
321     $server->{account}->{ae_field_template} = "X[% patron.surname %]Y";
322     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
323     undef $response;
324     $msg->handle_patron_info( $server );
325     $respcode = substr( $response, 0, 2 );
326     check_field( $respcode, $response, FID_PERSONAL_NAME, 'X' . $patron2->{surname} . 'Y', 'Check customized patron name' );
327
328     undef $response;
329     $server->{account}->{hide_fields} = "BD,BE,BF,PB";
330     $msg->handle_patron_info( $server );
331     $respcode = substr( $response, 0, 2 );
332     check_field( $respcode, $response, FID_HOME_ADDR, undef, 'Home address successfully stripped from response' );
333     check_field( $respcode, $response, FID_EMAIL, undef, 'Email address successfully stripped from response' );
334     check_field( $respcode, $response, FID_HOME_PHONE, undef, 'Home phone successfully stripped from response' );
335     check_field( $respcode, $response, FID_PATRON_BIRTHDATE, undef, 'Date of birth successfully stripped from response' );
336     $server->{account}->{hide_fields} = "";
337
338     # Check empty password and verify CQ again
339     $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y         '.
340         FID_INST_ID. $branchcode. '|'.
341         FID_PATRON_ID. $card. '|'.
342         FID_PATRON_PWD. '|';
343     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
344     undef $response;
345     $msg->handle_patron_info( $server );
346     $respcode = substr( $response, 0, 2 );
347     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'code CQ should be N for empty AD' );
348     # Test empty password is OK if account configured to allow
349     $server->{account}->{allow_empty_passwords} = 1;
350     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
351     undef $response;
352     $msg->handle_patron_info( $server );
353     $respcode = substr( $response, 0, 2 );
354     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'code CQ should be Y if empty AD allowed' );
355
356     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', '1' );
357     my $patron = Koha::Patrons->find({ cardnumber => $card });
358     $patron->update({ login_attempts => 0 });
359     is( $patron->account_locked, 0, "Patron account not locked already" );
360     $msg->handle_patron_info( $server );
361     $patron = Koha::Patrons->find({ cardnumber => $card });
362     is( $patron->account_locked, 0, "Patron account is not locked by patron info messages with empty password" );
363
364     # Finally, we send a wrong card number
365     Koha::Patrons->search({ cardnumber => $card })->delete;
366     undef $findpatron;
367     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
368     undef $response;
369     $msg->handle_patron_info( $server );
370     $respcode = substr( $response, 0, 2 );
371     check_field( $respcode, $response, FID_VALID_PATRON, 'N', 'Verified code BL for wrong cardnumber' );
372     check_field( $respcode, $response, FID_PERSONAL_NAME, '', 'Name should be empty now' );
373     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'But we have a screen msg', 'regex' );
374 }
375
376 sub test_checkin_v2 {
377     my $builder = t::lib::TestBuilder->new();
378     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
379     my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode};
380     my ( $response, $findpatron );
381     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
382
383     # create some data
384     my $patron1 = $builder->build({
385         source => 'Borrower',
386         value  => {
387             password => hash_password( PATRON_PW ),
388         },
389     });
390     my $card1 = $patron1->{cardnumber};
391     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
392     $findpatron = $sip_patron1;
393     my $item_object = $builder->build_sample_item({
394         damaged => 0,
395         withdrawn => 0,
396         itemlost => 0,
397         restricted => 0,
398         homebranch => $branchcode,
399         holdingbranch => $branchcode,
400     });
401
402     my $mockILS = $mocks->{ils};
403     my $server = { ils => $mockILS, account => {} };
404     $mockILS->mock( 'institution', sub { $branchcode; } );
405     $mockILS->mock( 'supports', sub { return; } );
406     $mockILS->mock( 'checkin', sub {
407         shift;
408         return C4::SIP::ILS->checkin(@_);
409     });
410     my $today = dt_from_string;
411
412     # Checkin invalid barcode
413     Koha::Items->search({ barcode => 'not_to_be_found' })->delete;
414     my $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' .
415         siprequestdate( $today->clone->add( days => 1) ) .
416         FID_INST_ID . $branchcode . '|'.
417         FID_ITEM_ID . 'not_to_be_found' . '|' .
418         FID_TERMINAL_PWD . 'ignored' . '|';
419     undef $response;
420     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
421     warnings_like { $msg->handle_checkin( $server ); }
422         [ qr/No item 'not_to_be_found'/, qr/no item found in object to resensitize/ ],
423         'Checkin of invalid item with two warnings';
424     my $respcode = substr( $response, 0, 2 );
425     is( $respcode, CHECKIN_RESP, 'Response code fine' );
426     is( substr($response,2,1), '0', 'OK flag is false' );
427     is( substr($response,5,1), 'Y', 'Alert flag is set' );
428     check_field( $respcode, $response, FID_SCREEN_MSG, 'Invalid Item', 'Check screen msg', 'regex' );
429
430     # Not checked out, toggle option checked_in_ok
431     $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' .
432         siprequestdate( $today->clone->add( days => 1) ) .
433         FID_INST_ID . $branchcode . '|'.
434         FID_ITEM_ID . $item_object->barcode . '|' .
435         FID_TERMINAL_PWD . 'ignored' . '|';
436     undef $response;
437     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
438     $msg->handle_checkin( $server );
439     $respcode = substr( $response, 0, 2 );
440     is( substr($response,2,1), '0', 'OK flag is false when checking in an item that was not checked out' );
441     is( substr($response,5,1), 'Y', 'Alert flag is set' );
442     check_field( $respcode, $response, FID_SCREEN_MSG, 'not checked out', 'Check screen msg', 'regex' );
443     # Toggle option
444     $server->{account}->{checked_in_ok} = 1;
445     undef $response;
446     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
447     $msg->handle_checkin( $server );
448     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' );
449     is( substr($response,5,1), 'N', 'Alert flag no longer set' );
450     check_field( $respcode, $response, FID_SCREEN_MSG, undef, 'No screen msg' );
451
452     # Move item to another holding branch to trigger CV of 04 with alert flag
453     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
454     $item_object->holdingbranch( $branchcode2 )->store();
455     undef $response;
456     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
457     $msg->handle_checkin( $server );
458     is( substr($response,5,1), 'Y', 'Alert flag is set with check_in_ok, item is checked in but needs transfer' );
459     check_field( $respcode, $response, FID_ALERT_TYPE, '04', 'Got FID_ALERT_TYPE (CV) field with value 04 ( needs transfer )' );
460     $item_object->holdingbranch( $branchcode )->store();
461     t::lib::Mocks::mock_preference( ' AllowReturnToBranch ', 'anywhere' );
462
463     $server->{account}->{cv_send_00_on_success} = 0;
464     undef $response;
465     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
466     $msg->handle_checkin( $server );
467     $respcode = substr( $response, 0, 2 );
468     check_field( $respcode, $response, FID_ALERT_TYPE, undef, 'No FID_ALERT_TYPE (CV) field' );
469     $server->{account}->{cv_send_00_on_success} = 1;
470     undef $response;
471     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
472     $msg->handle_checkin( $server );
473     $respcode = substr( $response, 0, 2 );
474     check_field( $respcode, $response, FID_ALERT_TYPE, '00', 'FID_ALERT_TYPE (CV) field is 00' );
475     $server->{account}->{checked_in_ok} = 0;
476     $server->{account}->{cv_send_00_on_success} = 0;
477
478     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '1' );
479     $server->{account}->{checked_in_ok} = 0;
480     $server->{account}->{cv_triggers_alert} = 0;
481     undef $response;
482     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
483     $msg->handle_checkin( $server );
484     $respcode = substr( $response, 0, 2 );
485     is( substr( $response, 5, 1 ), 'Y', 'Checkin without CV triggers alert flag when cv_triggers_alert is off' );
486     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '0' );
487     $server->{account}->{cv_triggers_alert} = 1;
488     undef $response;
489     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
490     $msg->handle_checkin( $server );
491     $respcode = substr( $response, 0, 2 );
492     is( substr( $response, 5, 1 ), 'N', 'Checkin without CV does not trigger alert flag when cv_triggers_alert is on' );
493     $server->{account}->{cv_triggers_alert} = 0;
494     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '1' );
495
496     $server->{account}->{checked_in_ok} = 1;
497     $server->{account}->{ct_always_send} = 0;
498     undef $response;
499     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
500     $msg->handle_checkin( $server );
501     $respcode = substr( $response, 0, 2 );
502     check_field( $respcode, $response, FID_DESTINATION_LOCATION, undef, 'No FID_DESTINATION_LOCATION (CT) field' );
503     $server->{account}->{ct_always_send} = 1;
504     undef $response;
505     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
506     $msg->handle_checkin( $server );
507     $respcode = substr( $response, 0, 2 );
508     check_field( $respcode, $response, FID_DESTINATION_LOCATION, q{}, 'FID_DESTINATION_LOCATION (CT) field is empty but present' );
509     $server->{account}->{checked_in_ok} = 0;
510     $server->{account}->{ct_always_send} = 0;
511
512     # Checkin at wrong branch: issue item and switch branch, and checkin
513     my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store;
514     $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
515     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
516     undef $response;
517     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
518     $msg->handle_checkin( $server );
519     is( substr($response,2,1), '0', 'OK flag is false when we check in at the wrong branch and we do not allow it' );
520     is( substr($response,5,1), 'Y', 'Alert flag is set' );
521     check_field( $respcode, $response, FID_SCREEN_MSG, 'Checkin failed', 'Check screen msg' );
522     $branchcode = $item_object->homebranch;  # switch back
523     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
524
525     # Data corrupted: add same issue_id to old_issues
526     Koha::Old::Checkout->new({ issue_id => $issue->issue_id })->store;
527     undef $response;
528     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
529     warnings_like { $msg->handle_checkin( $server ); }
530         [ qr/Duplicate entry/, qr/data corrupted/ ],
531         'DBIx error on duplicate issue_id';
532     is( substr($response,2,1), '0', 'OK flag is false when we encounter data corruption in old_issues' );
533     is( substr($response,5,1), 'Y', 'Alert flag is set' );
534     check_field( $respcode, $response, FID_SCREEN_MSG, 'Checkin failed: data problem', 'Check screen msg' );
535
536     # Finally checkin without problems (remove duplicate id)
537     Koha::Old::Checkouts->search({ issue_id => $issue->issue_id })->delete;
538     undef $response;
539     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
540     $msg->handle_checkin( $server );
541     is( substr($response,2,1), '1', 'OK flag is true when we checkin after removing the duplicate' );
542     is( substr($response,5,1), 'N', 'Alert flag is not set' );
543     is( Koha::Checkouts->find( $issue->issue_id ), undef,
544         'Issue record is gone now' );
545 }
546
547 sub test_hold_patron_bcode {
548     my $builder = t::lib::TestBuilder->new();
549     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
550     my ( $response, $findpatron );
551     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
552
553     my $item = $builder->build({
554         source => 'Item',
555         value => { damaged => 0, withdrawn => 0, itemlost => 0, restricted => 0, homebranch => $branchcode, holdingbranch => $branchcode },
556     });
557     my $item_object = Koha::Items->find( $item->{itemnumber} );
558
559     my $server = { ils => $mocks->{ils} };
560     my $sip_item = C4::SIP::ILS::Item->new( $item->{barcode} );
561
562     is( $sip_item->hold_patron_bcode, q{}, "SIP item with no hold returns empty string" );
563
564     my $resp .= C4::SIP::Sip::maybe_add( FID_CALL_NUMBER, $sip_item->hold_patron_bcode, $server );
565     is( $resp, q{}, "maybe_add returns empty string for SIP item with no hold returns empty string" );
566 }
567
568 # Helper routines
569
570 sub create_mocks {
571     my ( $response, $findpatron, $branchcode ) = @_; # referenced variables !
572
573     # mock write_msg (imported from Sip.pm into Message.pm)
574     my $mockMsg = Test::MockModule->new( 'C4::SIP::Sip::MsgType' );
575     $mockMsg->mock( 'write_msg', sub { $$response = $_[1]; } ); # save response
576
577     # mock ils object
578     my $mockILS = Test::MockObject->new;
579     $mockILS->mock( 'check_inst_id', sub {} );
580     $mockILS->mock( 'institution_id', sub { $$branchcode; } );
581     $mockILS->mock( 'find_patron', sub { $$findpatron; } );
582
583     return { ils => $mockILS, message => $mockMsg };
584 }
585
586 sub check_field {
587     my ( $code, $resp, $fld, $expr, $msg, $mode ) = @_;
588     # mode: contains || equals || regex (by default: equals)
589
590     # strip fixed part; prefix to simplify next regex
591     $resp = '|'. substr( $resp, fixed_length( $code ) );
592     my $fldval;
593     if( $resp =~ /\|$fld([^\|]*)\|/ ) {
594         $fldval = $1;
595     } elsif( !defined($expr) ) { # field should not be found
596         ok( 1, $msg );
597         return;
598     } else { # test fails
599         is( 0, 1, "Code $fld not found in '$resp'?" );
600         return;
601     }
602
603     if( !$mode || $mode eq 'equals' ) { # default
604         is( $fldval, $expr, $msg );
605     } elsif( $mode eq 'regex' ) {
606         is( $fldval =~ /$expr/, 1, $msg );
607     } else { # contains
608         is( index( $fldval, $expr ) > -1, 1, $msg );
609     }
610 }
611
612 sub siprequestdate {
613     my ( $dt ) = @_;
614     return $dt->ymd('').(' 'x4).$dt->hms('');
615 }
616
617 sub fixed_length { #length of fixed fields including response code
618     return {
619       ( PATRON_STATUS_RESP )  => 37,
620       ( PATRON_INFO_RESP )    => 61,
621       ( CHECKIN_RESP )        => 24,
622     }->{$_[0]};
623 }