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