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