Bug 33580: Fix tests
[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 => 16;
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( AddIssue 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 'Test checkout desensitize' => sub {
81     my $schema = Koha::Database->new->schema;
82     $schema->storage->txn_begin;
83     plan tests => 6;
84     $C4::SIP::Sip::protocol_version = 2;
85     test_checkout_desensitize();
86     $schema->storage->txn_rollback;
87 };
88
89 subtest 'Test renew desensitize' => sub {
90     my $schema = Koha::Database->new->schema;
91     $schema->storage->txn_begin;
92     plan tests => 6;
93     $C4::SIP::Sip::protocol_version = 2;
94     test_renew_desensitize();
95     $schema->storage->txn_rollback;
96 };
97
98 subtest 'Checkin V2' => sub {
99     my $schema = Koha::Database->new->schema;
100     $schema->storage->txn_begin;
101     plan tests => 39;
102     $C4::SIP::Sip::protocol_version = 2;
103     test_checkin_v2();
104     $schema->storage->txn_rollback;
105 };
106
107 subtest 'Test hold_patron_bcode' => sub {
108     my $schema = Koha::Database->new->schema;
109     $schema->storage->txn_begin;
110     plan tests => 2;
111     $C4::SIP::Sip::protocol_version = 2;
112     test_hold_patron_bcode();
113     $schema->storage->txn_rollback;
114 };
115
116 subtest 'UseLocationAsAQInSIP syspref tests' => sub {
117     plan tests => 2;
118
119     my $schema = Koha::Database->new->schema;
120     $schema->storage->txn_begin;
121
122     my $builder = t::lib::TestBuilder->new();
123
124     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
125
126     t::lib::Mocks::mock_preference('UseLocationAsAQInSIP', 0);
127
128      my $item = $builder->build_sample_item(
129         {
130             damaged       => 0,
131             withdrawn     => 0,
132             itemlost      => 0,
133             restricted    => 0,
134             homebranch    => $branchcode,
135             holdingbranch => $branchcode,
136             permanent_location => "PERMANENT_LOCATION"
137         }
138     );
139
140     my $sip_item = C4::SIP::ILS::Item->new( $item->barcode );
141     is( $sip_item->permanent_location, $branchcode, "When UseLocationAsAQInSIP is not set SIP item has permanent_location set to value of homebranch" );
142
143     t::lib::Mocks::mock_preference('UseLocationAsAQInSIP', 1);
144
145     $sip_item = C4::SIP::ILS::Item->new( $item->barcode );
146     is( $sip_item->permanent_location, "PERMANENT_LOCATION", "When UseLocationAsAQInSIP is set SIP item has permanent_location set to value of item permanent_location" );
147
148     $schema->storage->txn_rollback;
149 };
150
151 subtest 'hold_patron_name() tests' => sub {
152
153     plan tests => 3;
154
155     my $schema = Koha::Database->new->schema;
156     $schema->storage->txn_begin;
157
158     my $builder = t::lib::TestBuilder->new();
159
160     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
161     my ( $response, $findpatron );
162     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
163
164     my $item = $builder->build_sample_item(
165         {
166             damaged       => 0,
167             withdrawn     => 0,
168             itemlost      => 0,
169             restricted    => 0,
170             homebranch    => $branchcode,
171             holdingbranch => $branchcode
172         }
173     );
174
175     my $server = { ils => $mocks->{ils} };
176     my $sip_item = C4::SIP::ILS::Item->new( $item->barcode );
177
178     is( $sip_item->hold_patron_name, q{}, "SIP item with no hold returns empty string for patron name" );
179
180     my $resp = C4::SIP::Sip::maybe_add( FID_CALL_NUMBER, $sip_item->hold_patron_name, $server );
181     is( $resp, q{}, "maybe_add returns empty string for SIP item with no hold returns empty string" );
182
183     $resp = C4::SIP::Sip::maybe_add( FID_CALL_NUMBER, "0", $server );
184     is( $resp, q{CS0|}, "maybe_add will create the field of the string '0'" );
185
186     $schema->storage->txn_rollback;
187 };
188
189 subtest 'Lastseen response' => sub {
190
191     my $schema = Koha::Database->new->schema;
192     $schema->storage->txn_begin;
193
194     plan tests => 6;
195     my $builder = t::lib::TestBuilder->new();
196     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
197     my ( $response, $findpatron );
198     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
199     my $seen_patron = $builder->build({
200         source => 'Borrower',
201         value  => {
202             lastseen => '2001-01-01',
203             password => hash_password( PATRON_PW ),
204             branchcode => $branchcode,
205         },
206     });
207     my $cardnum = $seen_patron->{cardnumber};
208     my $sip_patron = C4::SIP::ILS::Patron->new( $cardnum );
209     $findpatron = $sip_patron;
210
211     my $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y         '.
212         FID_INST_ID. $branchcode. '|'.
213         FID_PATRON_ID. $cardnum. '|'.
214         FID_PATRON_PWD. PATRON_PW. '|';
215     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
216
217     my $server = { ils => $mocks->{ils} };
218     undef $response;
219     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '' );
220     $msg->handle_patron_info( $server );
221
222     isnt( $response, undef, 'At least we got a response.' );
223     my $respcode = substr( $response, 0, 2 );
224     is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
225     $seen_patron = Koha::Patrons->find({ cardnumber => $seen_patron->{cardnumber} });
226     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');
227     undef $response;
228     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
229     $msg->handle_patron_info( $server );
230
231     isnt( $response, undef, 'At least we got a response.' );
232     $respcode = substr( $response, 0, 2 );
233     is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
234     $seen_patron = Koha::Patrons->find({ cardnumber => $seen_patron->cardnumber() });
235     is( output_pref({str => $seen_patron->lastseen(), dateonly => 1}), output_pref({dt => dt_from_string(), dateonly => 1}),'Last seen updated if tracking patrons');
236     $schema->storage->txn_rollback;
237
238 };
239
240 subtest "Test patron_status_string" => sub {
241     my $schema = Koha::Database->new->schema;
242     $schema->storage->txn_begin;
243
244     plan tests => 9;
245
246     my $builder = t::lib::TestBuilder->new();
247     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
248     my $patron = $builder->build({
249         source => 'Borrower',
250         value  => {
251             branchcode => $branchcode,
252         },
253     });
254     my $sip_patron = C4::SIP::ILS::Patron->new( $patron->{cardnumber} );
255
256     t::lib::Mocks::mock_userenv({ branchcode => $branchcode });
257
258      my $item1 = $builder->build_sample_item(
259         {
260             damaged       => 0,
261             withdrawn     => 0,
262             itemlost      => 0,
263             restricted    => 0,
264             homebranch    => $branchcode,
265             holdingbranch => $branchcode,
266             permanent_location => "PERMANENT_LOCATION"
267         }
268     );
269      AddIssue( $patron, $item1->barcode );
270
271      my $item2 = $builder->build_sample_item(
272         {
273             damaged       => 0,
274             withdrawn     => 0,
275             itemlost      => 0,
276             restricted    => 0,
277             homebranch    => $branchcode,
278             holdingbranch => $branchcode,
279             permanent_location => "PERMANENT_LOCATION"
280         }
281     );
282     AddIssue( $patron, $item2->barcode );
283
284     is( Koha::Checkouts->search({ borrowernumber => $patron->{borrowernumber} })->count, 2, "Found 2 checkouts for this patron" );
285
286     $item1->itemlost(1)->store();
287     $item2->itemlost(2)->store();
288
289     is( Koha::Checkouts->search({ borrowernumber => $patron->{borrowernumber}, 'itemlost' => { '>', 0 } }, { join => 'item'} )->count, 2, "Found 2 lost checkouts for this patron" );
290
291     my $server->{account}->{lost_block_checkout} = undef;
292     my $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server );
293     is( substr($patron_status_string, 9, 1), q{ }, "lost_block_checkout = 0 does not block checkouts with 2 lost checkouts" );;
294
295     $server->{account}->{lost_block_checkout} = 0;
296     $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server );
297     is( substr($patron_status_string, 9, 1), q{ }, "lost_block_checkout = 0 does not block checkouts with 2 lost checkouts" );;
298
299     $server->{account}->{lost_block_checkout} = 1;
300     $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server );
301     is( substr($patron_status_string, 9, 1), q{Y}, "lost_block_checkout = 1 does block checkouts with 2 lost checkouts" );;
302
303     $server->{account}->{lost_block_checkout} = 2;
304     $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server );
305     is( substr($patron_status_string, 9, 1), q{Y}, "lost_block_checkout = 2 does block checkouts with 2 lost checkouts" );;
306
307     $server->{account}->{lost_block_checkout} = 3;
308     $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server );
309     is( substr($patron_status_string, 9, 1), q{ }, "lost_block_checkout = 3 does not block checkouts with 2 lost checkouts" );;
310
311     $server->{account}->{lost_block_checkout} = 2;
312     $server->{account}->{lost_block_checkout_value} = 2;
313     $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server );
314     is( substr($patron_status_string, 9, 1), q{ }, "lost_block_checkout = 2, lost_block_checkout_value = 2 does not block checkouts with 2 lost checkouts where only 1 has itemlost = 2" );
315
316     $server->{account}->{lost_block_checkout} = 1;
317     $server->{account}->{lost_block_checkout_value} = 2;
318     $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server );
319     is( substr($patron_status_string, 9, 1), q{Y}, "lost_block_checkout = 2, lost_block_checkout_value = 2 does block checkouts with 2 lost checkouts where only 1 has itemlost = 2" );
320
321     $schema->storage->txn_rollback;
322 };
323
324 subtest "Test build_additional_item_fields_string" => sub {
325     my $schema = Koha::Database->new->schema;
326     $schema->storage->txn_begin;
327
328     plan tests => 2;
329
330     my $builder = t::lib::TestBuilder->new();
331
332     my $item = $builder->build_sample_item;
333     my $ils_item = C4::SIP::ILS::Item->new( $item->barcode );
334
335     my $server = {};
336     $server->{account}->{item_field}->{code} = 'itemnumber';
337     $server->{account}->{item_field}->{field} = 'XY';
338     my $attribute_string = $ils_item->build_additional_item_fields_string( $server );
339     is( $attribute_string, "XY".$item->itemnumber."|", 'Attribute field generated correctly with single param' );
340
341     $server = {};
342     $server->{account}->{item_field}->[0]->{code} = 'itemnumber';
343     $server->{account}->{item_field}->[0]->{field} = 'XY';
344     $server->{account}->{item_field}->[1]->{code} = 'biblionumber';
345     $server->{account}->{item_field}->[1]->{field} = 'YZ';
346     $attribute_string = $ils_item->build_additional_item_fields_string( $server );
347     is( $attribute_string, sprintf("XY%s|YZ%s|", $item->itemnumber, $item->biblionumber), 'Attribute field generated correctly with multiple params' );
348
349     $schema->storage->txn_rollback;
350 };
351
352 subtest "Test build_custom_field_string" => sub {
353     my $schema = Koha::Database->new->schema;
354     $schema->storage->txn_begin;
355
356     plan tests => 2;
357
358     my $builder = t::lib::TestBuilder->new();
359
360     my $item = $builder->build_sample_item;
361     my $item_id = $item->id;
362     my $item_barcode = $item->barcode;
363     my $ils_item = C4::SIP::ILS::Item->new( $item->barcode );
364
365     my $server = {};
366     $server->{account}->{custom_item_field}->{field} = "XY";
367     $server->{account}->{custom_item_field}->{template} = "[% item.id %] [% item.barcode %], woo!";
368     my $attribute_string = $ils_item->build_additional_item_fields_string( $server );
369     is( $attribute_string, "XY$item_id $item_barcode, woo!|", 'Attribute field generated correctly with single param' );
370
371     $server = {};
372     $server->{account}->{custom_item_field}->[0]->{field} = "ZY";
373     $server->{account}->{custom_item_field}->[0]->{template} = "[% item.id %]!";
374     $server->{account}->{custom_item_field}->[1]->{field} = "ZX";
375     $server->{account}->{custom_item_field}->[1]->{template} = "[% item.barcode %]*";
376     $attribute_string = $ils_item->build_additional_item_fields_string( $server );
377     is( $attribute_string, sprintf("ZY%s!|ZX%s*|", $item_id, $item_barcode), 'Attribute field generated correctly with multiple params' );
378
379     $schema->storage->txn_rollback;
380 };
381
382 subtest "Test cr_item_field" => sub {
383     plan tests => 8;
384
385     my $builder = t::lib::TestBuilder->new();
386     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
387     my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode};
388     my ( $response, $findpatron );
389     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
390
391     # create some data
392     my $patron1 = $builder->build({
393         source => 'Borrower',
394         value  => {
395             password => hash_password( PATRON_PW ),
396         },
397     });
398     my $card1 = $patron1->{cardnumber};
399     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
400     $findpatron = $sip_patron1;
401     my $item_object = $builder->build_sample_item({
402         damaged => 0,
403         withdrawn => 0,
404         itemlost => 0,
405         restricted => 0,
406         homebranch => $branchcode,
407         holdingbranch => $branchcode,
408         datelastseen => '1900-01-01',
409     });
410
411     my $mockILS = $mocks->{ils};
412     my $server = { ils => $mockILS, account => {} };
413     $mockILS->mock( 'institution', sub { $branchcode; } );
414     $mockILS->mock( 'supports', sub { return; } );
415     $mockILS->mock( 'checkin', sub {
416         shift;
417         return C4::SIP::ILS->checkin(@_);
418     });
419     my $today = dt_from_string;
420
421     my $respcode;
422
423     # Not checked out, toggle option checked_in_ok
424     my $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' .
425         siprequestdate( $today->clone->add( days => 1) ) .
426         FID_INST_ID . $branchcode . '|'.
427         FID_ITEM_ID . $item_object->barcode . '|' .
428         FID_TERMINAL_PWD . 'ignored' . '|';
429     undef $response;
430     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
431
432     $server->{account}->{cr_item_field} = 'itemnumber';
433
434     $msg->handle_checkin( $server );
435
436     my $id = $item_object->id;
437     ok( $response =~ m/CR$id/, "Found correct CR field in response");
438
439     $siprequest = ITEM_INFORMATION . 'YYYYMMDDZZZZHHMMSS' .
440         FID_INST_ID . $branchcode . '|'.
441         FID_ITEM_ID . $item_object->barcode . '|' .
442         FID_TERMINAL_PWD . 'ignored' . '|';
443     undef $response;
444     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
445
446     $mockILS->mock( 'find_item', sub {
447         return C4::SIP::ILS::Item->new( $item_object->barcode );
448     });
449
450     $server->{account}->{cr_item_field} = 'itype';
451
452     $server->{account}->{seen_on_item_information} = '';
453     $msg->handle_item_information( $server );
454     $item_object->get_from_storage;
455     my $stored_date = "1900-01-01 00:00:00";
456     is( $item_object->datelastseen, $stored_date, "datelastseen remains unchanged" );
457
458     $item_object->update({ itemlost => 1, datelastseen => '1900-01-01' });
459     $server->{account}->{seen_on_item_information} = 'keep_lost';
460     $msg->handle_item_information( $server );
461     $item_object = Koha::Items->find( $item_object->id );
462     isnt( $item_object->datelastseen, $stored_date, "datelastseen updated" );
463     is( $item_object->itemlost, 1, "item remains lost" );
464
465     $item_object->update({ itemlost => 1, datelastseen => '1900-01-01' });
466     $server->{account}->{seen_on_item_information} = 'mark_found';
467     $msg->handle_item_information( $server );
468     $item_object = Koha::Items->find( $item_object->id );
469     isnt( $item_object->datelastseen, $stored_date, "datelastseen updated" );
470     is( $item_object->itemlost, 0, "item is no longer lost" );
471
472     my $itype = $item_object->itype;
473     ok( $response =~ m/CR$itype/, "Found correct CR field in response");
474
475     $server->{account}->{format_due_date} = 1;
476     t::lib::Mocks::mock_preference( 'dateFormat',  'sql' );
477     my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber, date_due => "1999-01-01 12:59:00" })->store;
478     $siprequest = ITEM_INFORMATION . 'YYYYMMDDZZZZHHMMSS' .
479         FID_INST_ID . $branchcode . '|'.
480         FID_ITEM_ID . $item_object->barcode . '|' .
481         FID_TERMINAL_PWD . 'ignored' . '|';
482     undef $response;
483     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
484     $msg->handle_item_information( $server );
485     ok( $response =~ m/AH1999-01-01 12:59/, "Found correct CR field in response");
486 };
487
488 subtest 'Patron info summary > 5 should not crash server' => sub {
489
490     my $schema = Koha::Database->new->schema;
491     $schema->storage->txn_begin;
492
493     plan tests => 22;
494     my $builder = t::lib::TestBuilder->new();
495     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
496     my ( $response, $findpatron );
497     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
498     my $seen_patron = $builder->build({
499         source => 'Borrower',
500         value  => {
501             lastseen => '2001-01-01',
502             password => hash_password( PATRON_PW ),
503             branchcode => $branchcode,
504         },
505     });
506     my $cardnum = $seen_patron->{cardnumber};
507     my $sip_patron = C4::SIP::ILS::Patron->new( $cardnum );
508     $findpatron = $sip_patron;
509
510     my @summaries = (
511         '          ',
512         'Y         ',
513         ' Y        ',
514         '  Y       ',
515         '   Y      ',
516         '    Y     ',
517         '     Y    ',
518         '      Y   ',
519         '       Y  ',
520         '        Y ',
521         '         Y',
522     );
523     for my $summary ( @summaries ) {
524         my $siprequest = PATRON_INFO . 'engYYYYMMDDZZZZHHMMSS' . $summary .
525             FID_INST_ID . $branchcode . '|' .
526             FID_PATRON_ID . $cardnum . '|' .
527             FID_PATRON_PWD . PATRON_PW . '|';
528         my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
529
530         my $server = { ils => $mocks->{ils} };
531         undef $response;
532         $msg->handle_patron_info( $server );
533
534         isnt( $response, undef, 'At least we got a response.' );
535         my $respcode = substr( $response, 0, 2 );
536         is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
537     }
538
539     $schema->storage->txn_rollback;
540 };
541
542 subtest 'SC status tests' => sub {
543
544     my $schema = Koha::Database->new->schema;
545     $schema->storage->txn_begin;
546
547     plan tests => 2;
548
549     my $builder = t::lib::TestBuilder->new();
550     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
551     my $sip_user = $builder->build_object({ class => "Koha::Patrons" });
552
553     my ( $response, $findpatron );
554     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
555     my $mockILS = $mocks->{ils};
556     $mockILS->mock( 'checkout_ok', sub {1} );
557     $mockILS->mock( 'checkin_ok', sub {1} );
558     $mockILS->mock( 'status_update_ok', sub {1} );
559     $mockILS->mock( 'offline_ok', sub {1} );
560     $mockILS->mock( 'supports', sub {1} );
561     my $server = Test::MockObject->new();
562     $server->mock( 'get_timeout', sub {'100'});
563     $server->{ils} = $mockILS;
564     $server->{sip_username} = $sip_user->userid;
565     $server->{account} = {};
566     $server->{policy} = { renewal =>1,retries=>'000'};
567
568     my $siprequest = SC_STATUS . '0' . '030' . '2.00';
569     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
570     $msg->handle_sc_status( $server );
571
572     like( $response, qr/98YYYYYY100000[0-9 ]{19}.00AO|BXYYYYYYYYYYYYYYYY|/, 'At least we got a response.' );
573
574     $sip_user->delete;
575
576     dies_ok{ $msg->handle_sc_status( $server ) } ,"Dies if sip user cannot be found";
577
578 };
579
580 # Here is room for some more subtests
581
582 # END of main code
583
584 sub test_request_patron_status_v2 {
585     my $builder = t::lib::TestBuilder->new();
586     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
587     my ( $response, $findpatron );
588     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
589
590     my $patron1 = $builder->build({
591         source => 'Borrower',
592         value  => {
593             password => hash_password( PATRON_PW ),
594         },
595     });
596     my $card1 = $patron1->{cardnumber};
597     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
598     $findpatron = $sip_patron1;
599
600     my $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
601         FID_INST_ID. $branchcode. '|'.
602         FID_PATRON_ID. $card1. '|'.
603         FID_PATRON_PWD. PATRON_PW. '|';
604     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
605
606     my $server = { ils => $mocks->{ils} };
607     undef $response;
608     $msg->handle_patron_status( $server );
609
610     isnt( $response, undef, 'At least we got a response.' );
611     my $respcode = substr( $response, 0, 2 );
612     is( $respcode, PATRON_STATUS_RESP, 'Response code fine' );
613
614     check_field( $respcode, $response, FID_INST_ID, $branchcode , 'Verified institution id' );
615     check_field( $respcode, $response, FID_PATRON_ID, $card1, 'Verified patron id' );
616     check_field( $respcode, $response, FID_PERSONAL_NAME, $patron1->{surname}, 'Verified patron name', 'contains' );
617     check_field( $respcode, $response, FID_VALID_PATRON, 'Y', 'Verified code BL' );
618     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'Verified code CQ' );
619     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'Verified non-empty screen message', 'regex' );
620
621     # Now, we pass a wrong password and verify CQ again
622     $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
623         FID_INST_ID. $branchcode. '|'.
624         FID_PATRON_ID. $card1. '|'.
625         FID_PATRON_PWD. 'wrong_password'. '|';
626     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
627     undef $response;
628     $msg->handle_patron_status( $server );
629     $respcode = substr( $response, 0, 2 );
630     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'Verified code CQ for wrong pw' );
631
632     # Check empty password and verify CQ again
633     $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
634         FID_INST_ID. $branchcode. '|'.
635         FID_PATRON_ID. $card1. '|'.
636         FID_PATRON_PWD. '|';
637     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
638     undef $response;
639     $msg->handle_patron_status( $server );
640     $respcode = substr( $response, 0, 2 );
641     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'code CQ should be N for empty AD' );
642
643     # Finally, we send a wrong card number and check AE, BL
644     # This is done by removing the new patron first
645     Koha::Patrons->search({ cardnumber => $card1 })->delete;
646     undef $findpatron;
647     $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'.
648         FID_INST_ID. $branchcode. '|'.
649         FID_PATRON_ID. $card1. '|'.
650         FID_PATRON_PWD. PATRON_PW. '|';
651     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
652     undef $response;
653     $msg->handle_patron_status( $server );
654     $respcode = substr( $response, 0, 2 );
655     check_field( $respcode, $response, FID_VALID_PATRON, 'N', 'Verified code BL for wrong cardnumber' );
656     check_field( $respcode, $response, FID_PERSONAL_NAME, '', 'Name should be empty now' );
657     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'But we have a screen msg', 'regex' );
658 }
659
660 sub test_request_patron_info_v2 {
661     my $builder = t::lib::TestBuilder->new();
662     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
663     my ( $response, $findpatron );
664     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
665
666     my $patron2 = $builder->build({
667         source => 'Borrower',
668         value  => {
669             password => hash_password( PATRON_PW ),
670         },
671     });
672     my $card = $patron2->{cardnumber};
673     my $sip_patron2 = C4::SIP::ILS::Patron->new( $card );
674     $findpatron = $sip_patron2;
675     my $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y         '.
676         FID_INST_ID. $branchcode. '|'.
677         FID_PATRON_ID. $card. '|'.
678         FID_PATRON_PWD. PATRON_PW. '|';
679     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
680
681     my $server = { ils => $mocks->{ils} };
682     undef $response;
683     $msg->handle_patron_info( $server );
684     isnt( $response, undef, 'At least we got a response.' );
685     my $respcode = substr( $response, 0, 2 );
686     is( $respcode, PATRON_INFO_RESP, 'Response code fine' );
687
688     check_field( $respcode, $response, FID_INST_ID, $branchcode , 'Verified institution id' );
689     check_field( $respcode, $response, FID_PATRON_ID, $card, 'Verified patron id' );
690     check_field( $respcode, $response, FID_PERSONAL_NAME, $patron2->{surname}, 'Verified patron name', 'contains' );
691     check_field( $respcode, $response, FID_VALID_PATRON, 'Y', 'Verified code BL' );
692     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'Verified code CQ' );
693     check_field( $respcode, $response, FID_FEE_LMT, '.*', 'Checked existence of fee limit', 'regex' );
694     check_field( $respcode, $response, FID_HOME_ADDR, $patron2->{address}, 'Address in BD', 'contains' );
695     check_field( $respcode, $response, FID_EMAIL, $patron2->{email}, 'Verified email in BE' );
696     check_field( $respcode, $response, FID_HOME_PHONE, $patron2->{phone}, 'Verified home phone in BF' );
697     # No check for custom fields here (unofficial PB, PC and PI)
698     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'We have a screen msg', 'regex' );
699
700     # Test customized patron name in AE with same sip request
701     # This implicitly tests C4::SIP::ILS::Patron->name
702     $server->{account}->{ae_field_template} = "X[% patron.surname %]Y";
703     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
704     undef $response;
705     $msg->handle_patron_info( $server );
706     $respcode = substr( $response, 0, 2 );
707     check_field( $respcode, $response, FID_PERSONAL_NAME, 'X' . $patron2->{surname} . 'Y', 'Check customized patron name' );
708
709     undef $response;
710     $server->{account}->{hide_fields} = "BD,BE,BF,PB";
711     $msg->handle_patron_info( $server );
712     $respcode = substr( $response, 0, 2 );
713     check_field( $respcode, $response, FID_HOME_ADDR, undef, 'Home address successfully stripped from response' );
714     check_field( $respcode, $response, FID_EMAIL, undef, 'Email address successfully stripped from response' );
715     check_field( $respcode, $response, FID_HOME_PHONE, undef, 'Home phone successfully stripped from response' );
716     check_field( $respcode, $response, FID_PATRON_BIRTHDATE, undef, 'Date of birth successfully stripped from response' );
717     $server->{account}->{hide_fields} = "";
718
719     # Check empty password and verify CQ again
720     $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y         '.
721         FID_INST_ID. $branchcode. '|'.
722         FID_PATRON_ID. $card. '|'.
723         FID_PATRON_PWD. '|';
724     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
725     undef $response;
726     $msg->handle_patron_info( $server );
727     $respcode = substr( $response, 0, 2 );
728     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'code CQ should be N for empty AD' );
729     # Test empty password is OK if account configured to allow
730     $server->{account}->{allow_empty_passwords} = 1;
731     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
732     undef $response;
733     $msg->handle_patron_info( $server );
734     $respcode = substr( $response, 0, 2 );
735     check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'code CQ should be Y if empty AD allowed' );
736
737     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', '1' );
738     my $patron = Koha::Patrons->find({ cardnumber => $card });
739     $patron->update({ login_attempts => 0 });
740     is( $patron->account_locked, 0, "Patron account not locked already" );
741     $msg->handle_patron_info( $server );
742     $patron = Koha::Patrons->find({ cardnumber => $card });
743     is( $patron->account_locked, 0, "Patron account is not locked by patron info messages with empty password" );
744
745     # Finally, we send a wrong card number
746     Koha::Patrons->search({ cardnumber => $card })->delete;
747     undef $findpatron;
748     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
749     undef $response;
750     $msg->handle_patron_info( $server );
751     $respcode = substr( $response, 0, 2 );
752     check_field( $respcode, $response, FID_VALID_PATRON, 'N', 'Verified code BL for wrong cardnumber' );
753     check_field( $respcode, $response, FID_PERSONAL_NAME, '', 'Name should be empty now' );
754     check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'But we have a screen msg', 'regex' );
755 }
756
757 sub test_checkout_v2 {
758     my $builder = t::lib::TestBuilder->new();
759     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
760     my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode};
761     my ( $response, $findpatron );
762     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
763
764     # create some data
765     my $patron1 = $builder->build({
766         source => 'Borrower',
767         value  => {
768             password => hash_password( PATRON_PW ),
769         },
770     });
771     my $card1 = $patron1->{cardnumber};
772     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
773     $findpatron = $sip_patron1;
774     my $item_object = $builder->build_sample_item({
775         damaged => 0,
776         withdrawn => 0,
777         itemlost => 0,
778         restricted => 0,
779         homebranch => $branchcode,
780         holdingbranch => $branchcode,
781     });
782
783     my $mockILS = $mocks->{ils};
784     my $server = { ils => $mockILS, account => {} };
785     $mockILS->mock( 'institution', sub { $branchcode; } );
786     $mockILS->mock( 'supports', sub { return; } );
787     $mockILS->mock( 'checkout', sub {
788         shift;
789         return C4::SIP::ILS->checkout(@_);
790     });
791     my $today = dt_from_string;
792     t::lib::Mocks::mock_userenv({ branchcode => $branchcode, flags => 1 });
793     t::lib::Mocks::mock_preference( 'CheckPrevCheckout',  'hardyes' );
794
795     my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store;
796     my $return = AddReturn($item_object->barcode, $branchcode);
797
798     my $siprequest = CHECKOUT . 'YN' . siprequestdate($today) .
799     siprequestdate( $today->clone->add( days => 1) ) .
800     FID_INST_ID . $branchcode . '|'.
801     FID_PATRON_ID . $sip_patron1->id . '|' .
802     FID_ITEM_ID . $item_object->barcode . '|' .
803     FID_TERMINAL_PWD . 'ignored' . '|';
804     undef $response;
805
806     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
807     $server->{account}->{prevcheckout_block_checkout} = 1;
808     $msg->handle_checkout( $server );
809     my $respcode = substr( $response, 0, 2 );
810     check_field( $respcode, $response, FID_SCREEN_MSG, 'This item was previously checked out by you', 'Check screen msg', 'equals' );
811
812     is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 0, "Item was not checked out (prevcheckout_block_checkout enabled)");
813
814     $server->{account}->{prevcheckout_block_checkout} = 0;
815     $msg->handle_checkout( $server );
816     $respcode = substr( $response, 0, 2 );
817     is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 1, "Item was checked out (prevcheckout_block_checkout disabled)");
818
819     $msg->handle_checkout( $server );
820     ok( $response =~ m/AH\d{8}    \d{6}/, "Found AH field as timestamp in response");
821     $server->{account}->{format_due_date} = 1;
822     t::lib::Mocks::mock_preference( 'dateFormat',  'sql' );
823     undef $response;
824     $msg->handle_checkout( $server );
825     ok( $response =~ m/AH\d{4}-\d{2}-\d{2}/, "Found AH field as SQL date in response");
826
827 }
828
829 sub test_checkin_v2 {
830     my $builder = t::lib::TestBuilder->new();
831     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
832     my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode};
833     my ( $response, $findpatron );
834     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
835
836     # create some data
837     my $patron1 = $builder->build({
838         source => 'Borrower',
839         value  => {
840             password => hash_password( PATRON_PW ),
841         },
842     });
843     my $card1 = $patron1->{cardnumber};
844     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
845     $findpatron = $sip_patron1;
846     my $item_object = $builder->build_sample_item({
847         damaged => 0,
848         withdrawn => 0,
849         itemlost => 0,
850         restricted => 0,
851         homebranch => $branchcode,
852         holdingbranch => $branchcode,
853     });
854
855     my $mockILS = $mocks->{ils};
856     my $server = { ils => $mockILS, account => {} };
857     $mockILS->mock( 'institution', sub { $branchcode; } );
858     $mockILS->mock( 'supports', sub { return; } );
859     $mockILS->mock( 'checkin', sub {
860         shift;
861         return C4::SIP::ILS->checkin(@_);
862     });
863     my $today = dt_from_string;
864
865     # Checkin invalid barcode
866     Koha::Items->search({ barcode => 'not_to_be_found' })->delete;
867     my $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' .
868         siprequestdate( $today->clone->add( days => 1) ) .
869         FID_INST_ID . $branchcode . '|'.
870         FID_ITEM_ID . 'not_to_be_found' . '|' .
871         FID_TERMINAL_PWD . 'ignored' . '|';
872     undef $response;
873     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
874     warnings_like { $msg->handle_checkin( $server ); }
875         [ qr/No item 'not_to_be_found'/, qr/no item found in object to resensitize/ ],
876         'Checkin of invalid item with two warnings';
877     my $respcode = substr( $response, 0, 2 );
878     is( $respcode, CHECKIN_RESP, 'Response code fine' );
879     is( substr($response,2,1), '0', 'OK flag is false' );
880     is( substr($response,5,1), 'Y', 'Alert flag is set' );
881     check_field( $respcode, $response, FID_SCREEN_MSG, 'Invalid Item', 'Check screen msg', 'regex' );
882
883     # Not checked out, toggle option checked_in_ok
884     $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' .
885         siprequestdate( $today->clone->add( days => 1) ) .
886         FID_INST_ID . $branchcode . '|'.
887         FID_ITEM_ID . $item_object->barcode . '|' .
888         FID_TERMINAL_PWD . 'ignored' . '|';
889     undef $response;
890     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
891     $msg->handle_checkin( $server );
892     $respcode = substr( $response, 0, 2 );
893     is( substr($response,2,1), '0', 'OK flag is false when checking in an item that was not checked out' );
894     is( substr($response,5,1), 'Y', 'Alert flag is set' );
895     check_field( $respcode, $response, FID_SCREEN_MSG, 'not checked out', 'Check screen msg', 'regex' );
896     # Toggle option
897     $server->{account}->{checked_in_ok} = 1;
898     undef $response;
899     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
900     $msg->handle_checkin( $server );
901     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' );
902     is( substr($response,5,1), 'N', 'Alert flag no longer set' );
903     check_field( $respcode, $response, FID_SCREEN_MSG, undef, 'No screen msg' );
904
905     # Move item to another holding branch to trigger CV of 04 with alert flag
906     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
907     $item_object->holdingbranch( $branchcode2 )->store();
908     undef $response;
909     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
910     $msg->handle_checkin( $server );
911     is( substr($response,5,1), 'Y', 'Alert flag is set with check_in_ok, item is checked in but needs transfer' );
912     check_field( $respcode, $response, FID_ALERT_TYPE, '04', 'Got FID_ALERT_TYPE (CV) field with value 04 ( needs transfer )' );
913     $item_object->holdingbranch( $branchcode )->store();
914     t::lib::Mocks::mock_preference( ' AllowReturnToBranch ', 'anywhere' );
915
916     $server->{account}->{cv_send_00_on_success} = 0;
917     undef $response;
918     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
919     $msg->handle_checkin( $server );
920     $respcode = substr( $response, 0, 2 );
921     check_field( $respcode, $response, FID_ALERT_TYPE, undef, 'No FID_ALERT_TYPE (CV) field' );
922     $server->{account}->{cv_send_00_on_success} = 1;
923     undef $response;
924     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
925     $msg->handle_checkin( $server );
926     $respcode = substr( $response, 0, 2 );
927     check_field( $respcode, $response, FID_ALERT_TYPE, '00', 'FID_ALERT_TYPE (CV) field is 00' );
928     $server->{account}->{checked_in_ok} = 0;
929     $server->{account}->{cv_send_00_on_success} = 0;
930
931     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '1' );
932     $server->{account}->{checked_in_ok} = 0;
933     $server->{account}->{cv_triggers_alert} = 0;
934     undef $response;
935     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
936     $msg->handle_checkin( $server );
937     $respcode = substr( $response, 0, 2 );
938     is( substr( $response, 5, 1 ), 'Y', 'Checkin without CV triggers alert flag when cv_triggers_alert is off' );
939     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '0' );
940     $server->{account}->{cv_triggers_alert} = 1;
941     undef $response;
942     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
943     $msg->handle_checkin( $server );
944     $respcode = substr( $response, 0, 2 );
945     is( substr( $response, 5, 1 ), 'N', 'Checkin without CV does not trigger alert flag when cv_triggers_alert is on' );
946     $server->{account}->{cv_triggers_alert} = 0;
947     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '1' );
948
949     $server->{account}->{checked_in_ok} = 1;
950     $server->{account}->{ct_always_send} = 0;
951     undef $response;
952     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
953     $msg->handle_checkin( $server );
954     $respcode = substr( $response, 0, 2 );
955     check_field( $respcode, $response, FID_DESTINATION_LOCATION, undef, 'No FID_DESTINATION_LOCATION (CT) field' );
956     $server->{account}->{ct_always_send} = 1;
957     undef $response;
958     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
959     $msg->handle_checkin( $server );
960     $respcode = substr( $response, 0, 2 );
961     check_field( $respcode, $response, FID_DESTINATION_LOCATION, q{}, 'FID_DESTINATION_LOCATION (CT) field is empty but present' );
962     $server->{account}->{checked_in_ok} = 0;
963     $server->{account}->{ct_always_send} = 0;
964
965     # Checkin at wrong branch: issue item and switch branch, and checkin
966     my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store;
967     $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
968     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
969     undef $response;
970     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
971     $msg->handle_checkin( $server );
972     is( substr($response,2,1), '0', 'OK flag is false when we check in at the wrong branch and we do not allow it' );
973     is( substr($response,5,1), 'Y', 'Alert flag is set' );
974     check_field( $respcode, $response, FID_SCREEN_MSG, 'Checkin failed', 'Check screen msg' );
975     $branchcode = $item_object->homebranch;  # switch back
976     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
977
978     # Data corrupted: add same issue_id to old_issues
979     Koha::Old::Checkout->new({ issue_id => $issue->issue_id })->store;
980     undef $response;
981     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
982     warnings_like { $msg->handle_checkin( $server ); }
983         [ qr/Duplicate entry/, qr/data issues/ ],
984         'DBIx error on duplicate issue_id';
985     is( substr($response,2,1), '0', 'OK flag is false when we encounter data corruption in old_issues' );
986     is( substr($response,5,1), 'Y', 'Alert flag is set' );
987     check_field( $respcode, $response, FID_SCREEN_MSG, 'Checkin failed: data problem', 'Check screen msg' );
988
989     # Finally checkin without problems (remove duplicate id)
990     Koha::Old::Checkouts->search({ issue_id => $issue->issue_id })->delete;
991     undef $response;
992     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
993     $msg->handle_checkin( $server );
994     is( substr($response,2,1), '1', 'OK flag is true when we checkin after removing the duplicate' );
995     is( substr($response,5,1), 'N', 'Alert flag is not set' );
996     is( Koha::Checkouts->find( $issue->issue_id ), undef,
997         'Issue record is gone now' );
998
999     # Test account option no_holds_check that prevents items on hold from being checked in via SIP
1000     $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store;
1001     is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 1, "Item is checked out");
1002     Koha::Old::Checkouts->search({ issue_id => $issue->issue_id })->delete;
1003     $server->{account}->{holds_block_checkin} = 1;
1004     my $reserve_id = AddReserve({
1005         branchcode     => $branchcode,
1006         borrowernumber => $patron1->{borrowernumber},
1007         biblionumber   => $item_object->biblionumber,
1008         priority       => 1,
1009     });
1010     my $hold = Koha::Holds->find( $reserve_id );
1011     is( $hold->id, $reserve_id, "Hold was created successfully" );
1012     undef $response;
1013     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
1014     $msg->handle_checkin( $server );
1015     is( substr($response,2,1), '0', 'OK flag is false when we check in an item on hold and we do not allow it' );
1016     is( substr($response,5,1), 'Y', 'Alert flag is set' );
1017     is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 1, "Item was not checked in");
1018     $hold->discard_changes;
1019     is( $hold->found, undef, "Hold was not marked as found by SIP when holds_block_checkin enabled");
1020     $server->{account}->{holds_block_checkin} = 0;
1021
1022     # Test account option holds_get_captured that automatically sets the hold as found for a hold and possibly sets it to in transit
1023     $server->{account}->{holds_get_captured} = 0;
1024     undef $response;
1025     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
1026     $msg->handle_checkin( $server );
1027     is( substr($response,2,1), '1', 'OK flag is true when we check in an item on hold and we allow it but do not capture it' );
1028     is( substr($response,5,1), 'Y', 'Alert flag is set' );
1029     is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 0, "Item was checked in");
1030     $hold->discard_changes;
1031     is( $hold->found, undef, "Hold was not marked as found by SIP when holds_get_captured disabled");
1032     $hold->delete();
1033     $server->{account}->{holds_get_captured} = 1;
1034 }
1035
1036 sub test_hold_patron_bcode {
1037     my $builder = t::lib::TestBuilder->new();
1038     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
1039     my ( $response, $findpatron );
1040     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
1041
1042     my $item = $builder->build_sample_item(
1043         {
1044             library => $branchcode
1045         }
1046     );
1047
1048     my $server = { ils => $mocks->{ils} };
1049     my $sip_item = C4::SIP::ILS::Item->new( $item->barcode );
1050
1051     is( $sip_item->hold_patron_bcode, q{}, "SIP item with no hold returns empty string" );
1052
1053     my $resp = C4::SIP::Sip::maybe_add( FID_CALL_NUMBER, $sip_item->hold_patron_bcode, $server );
1054     is( $resp, q{}, "maybe_add returns empty string for SIP item with no hold returns empty string" );
1055 }
1056
1057 sub test_checkout_desensitize {
1058     my $builder = t::lib::TestBuilder->new();
1059     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
1060     my ( $response, $findpatron );
1061     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
1062
1063     # create some data
1064     my $patron1 = $builder->build({
1065         source => 'Borrower',
1066         value  => {
1067             password => hash_password( PATRON_PW ),
1068         },
1069     });
1070     my $card1 = $patron1->{cardnumber};
1071     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
1072     my $patron_category = $sip_patron1->ptype();
1073     $findpatron = $sip_patron1;
1074     my $item_object = $builder->build_sample_item({
1075         damaged => 0,
1076         withdrawn => 0,
1077         itemlost => 0,
1078         restricted => 0,
1079         homebranch => $branchcode,
1080         holdingbranch => $branchcode,
1081     });
1082     my $itemtype = $item_object->effective_itemtype;
1083
1084     my $mockILS = $mocks->{ils};
1085     my $server = { ils => $mockILS, account => {} };
1086     $mockILS->mock( 'institution', sub { $branchcode; } );
1087     $mockILS->mock( 'supports', sub { return; } );
1088     $mockILS->mock( 'checkout', sub {
1089         shift;
1090         return C4::SIP::ILS->checkout(@_);
1091     });
1092     my $today = dt_from_string;
1093     t::lib::Mocks::mock_userenv({ branchcode => $branchcode, flags => 1 });
1094     t::lib::Mocks::mock_preference( 'CheckPrevCheckout',  'hardyes' );
1095
1096     my $siprequest = CHECKOUT . 'YN' . siprequestdate($today) .
1097     siprequestdate( $today->clone->add( days => 1) ) .
1098     FID_INST_ID . $branchcode . '|'.
1099     FID_PATRON_ID . $sip_patron1->id . '|' .
1100     FID_ITEM_ID . $item_object->barcode . '|' .
1101     FID_TERMINAL_PWD . 'ignored' . '|';
1102
1103     undef $response;
1104     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
1105     $server->{account}->{inhouse_patron_categories} = "A,$patron_category,Z";
1106     $msg->handle_checkout( $server );
1107     my $respcode = substr( $response, 5, 1 );
1108     is( $respcode, 'N', "Desensitize flag was not set for patron category in inhouse_patron_categories" );
1109
1110     undef $response;
1111     $server->{account}->{inhouse_patron_categories} = "A,B,C";
1112     $msg->handle_checkout( $server );
1113     $respcode = substr( $response, 5, 1 );
1114     is( $respcode, 'Y', "Desensitize flag was set for patron category not in inhouse_patron_categories" );
1115
1116     undef $response;
1117     $server->{account}->{inhouse_patron_categories} = "";
1118     $msg->handle_checkout( $server );
1119     $respcode = substr( $response, 5, 1 );
1120     is( $respcode, 'Y', "Desensitize flag was set for empty inhouse_patron_categories" );
1121
1122     $server->{account}->{inhouse_patron_categories} = "";
1123
1124     undef $response;
1125     $server->{account}->{inhouse_item_types} = "A,$itemtype,Z";
1126     $msg->handle_checkout( $server );
1127     $respcode = substr( $response, 5, 1 );
1128     is( $respcode, 'N', "Desensitize flag was not set for itemtype in inhouse_item_types" );
1129
1130     undef $response;
1131     $server->{account}->{inhouse_item_types} = "A,B,C";
1132     $msg->handle_checkout( $server );
1133     $respcode = substr( $response, 5, 1 );
1134     is( $respcode, 'Y', "Desensitize flag was set for item type not in inhouse_item_types" );
1135
1136     undef $response;
1137     $server->{account}->{inhouse_item_types} = "";
1138     $msg->handle_checkout( $server );
1139     $respcode = substr( $response, 5, 1 );
1140     is( $respcode, 'Y', "Desensitize flag was set for empty inhouse_item_types" );
1141 }
1142
1143 sub test_renew_desensitize {
1144     my $builder = t::lib::TestBuilder->new();
1145     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
1146     my ( $response, $findpatron );
1147     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
1148
1149     # create some data
1150     my $patron1 = $builder->build({
1151         source => 'Borrower',
1152         value  => {
1153             password => hash_password( PATRON_PW ),
1154         },
1155     });
1156     my $card1 = $patron1->{cardnumber};
1157     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
1158     my $patron_category = $sip_patron1->ptype();
1159     $findpatron = $sip_patron1;
1160     my $item_object = $builder->build_sample_item({
1161         damaged => 0,
1162         withdrawn => 0,
1163         itemlost => 0,
1164         restricted => 0,
1165         homebranch => $branchcode,
1166         holdingbranch => $branchcode,
1167     });
1168     my $itemtype = $item_object->effective_itemtype;
1169
1170     my $mockILS = $mocks->{ils};
1171     my $server = { ils => $mockILS, account => {} };
1172     $mockILS->mock( 'institution', sub { $branchcode; } );
1173     $mockILS->mock( 'supports', sub { return; } );
1174     $mockILS->mock( 'checkout', sub {
1175         shift;
1176         return C4::SIP::ILS->checkout(@_);
1177     });
1178     my $today = dt_from_string;
1179     t::lib::Mocks::mock_userenv({ branchcode => $branchcode, flags => 1 });
1180
1181     my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store;
1182
1183     my $siprequest = RENEW . 'YN' . siprequestdate($today) .
1184     siprequestdate( $today->clone->add( days => 1) ) .
1185     FID_INST_ID . $branchcode . '|'.
1186     FID_PATRON_ID . $sip_patron1->id . '|' .
1187     FID_ITEM_ID . $item_object->barcode . '|' .
1188     FID_TERMINAL_PWD . 'ignored' . '|';
1189
1190     undef $response;
1191     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
1192     $server->{account}->{inhouse_patron_categories} = "A,$patron_category,Z";
1193     $msg->handle_checkout( $server );
1194     my $respcode = substr( $response, 5, 1 );
1195     is( $respcode, 'N', "Desensitize flag was not set for patron category in inhouse_patron_categories" );
1196
1197     undef $response;
1198     $server->{account}->{inhouse_patron_categories} = "A,B,C";
1199     $msg->handle_checkout( $server );
1200     $respcode = substr( $response, 5, 1 );
1201     is( $respcode, 'Y', "Desensitize flag was set for patron category not in inhouse_patron_categories" );
1202
1203     undef $response;
1204     $server->{account}->{inhouse_patron_categories} = "";
1205     $msg->handle_checkout( $server );
1206     $respcode = substr( $response, 5, 1 );
1207     is( $respcode, 'Y', "Desensitize flag was set for empty inhouse_patron_categories" );
1208
1209     $server->{account}->{inhouse_patron_categories} = "";
1210
1211     undef $response;
1212     $server->{account}->{inhouse_item_types} = "A,B,C";
1213     $msg->handle_checkout( $server );
1214     $respcode = substr( $response, 5, 1 );
1215     is( $respcode, 'Y', "Desensitize flag was set for item type not in inhouse_item_types" );
1216
1217     undef $response;
1218     $server->{account}->{inhouse_item_types} = "";
1219     $msg->handle_checkout( $server );
1220     $respcode = substr( $response, 5, 1 );
1221     is( $respcode, 'Y', "Desensitize flag was set for empty inhouse_item_types" );
1222
1223     undef $response;
1224     $server->{account}->{inhouse_item_types} = "A,$itemtype,Z";
1225     $msg->handle_checkout( $server );
1226     $respcode = substr( $response, 5, 1 );
1227     is( $respcode, 'N', "Desensitize flag was not set for itemtype in inhouse_item_types" );
1228
1229 }
1230
1231 # Helper routines
1232
1233 sub create_mocks {
1234     my ( $response, $findpatron, $branchcode ) = @_; # referenced variables !
1235
1236     # mock write_msg (imported from Sip.pm into Message.pm)
1237     my $mockMsg = Test::MockModule->new( 'C4::SIP::Sip::MsgType' );
1238     $mockMsg->mock( 'write_msg', sub { $$response = $_[1]; } ); # save response
1239
1240     # mock ils object
1241     my $mockILS = Test::MockObject->new;
1242     $mockILS->mock( 'check_inst_id', sub {} );
1243     $mockILS->mock( 'institution_id', sub { $$branchcode; } );
1244     $mockILS->mock( 'find_patron', sub { $$findpatron; } );
1245
1246     return { ils => $mockILS, message => $mockMsg };
1247 }
1248
1249 sub check_field {
1250     my ( $code, $resp, $fld, $expr, $msg, $mode ) = @_;
1251     # mode: contains || equals || regex (by default: equals)
1252
1253     # strip fixed part; prefix to simplify next regex
1254     $resp = '|'. substr( $resp, fixed_length( $code ) );
1255     my $fldval;
1256     if( $resp =~ /\|$fld([^\|]*)\|/ ) {
1257         $fldval = $1;
1258     } elsif( !defined($expr) ) { # field should not be found
1259         ok( 1, $msg );
1260         return;
1261     } else { # test fails
1262         is( 0, 1, "Code $fld not found in '$resp'?" );
1263         return;
1264     }
1265
1266     if( !$mode || $mode eq 'equals' ) { # default
1267         is( $fldval, $expr, $msg );
1268     } elsif( $mode eq 'regex' ) {
1269         is( $fldval =~ /$expr/, 1, $msg );
1270     } else { # contains
1271         is( index( $fldval, $expr ) > -1, 1, $msg );
1272     }
1273 }
1274
1275 sub siprequestdate {
1276     my ( $dt ) = @_;
1277     return $dt->ymd('').(' 'x4).$dt->hms('');
1278 }
1279
1280 sub fixed_length { #length of fixed fields including response code
1281     return {
1282       ( PATRON_STATUS_RESP )  => 37,
1283       ( PATRON_INFO_RESP )    => 61,
1284       ( CHECKIN_RESP )        => 24,
1285       ( CHECKOUT_RESP )       => 24,
1286     }->{$_[0]};
1287 }