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