Bug 34101: Unit 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 => 8;
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     #returning item and now testing for blocked_item_types
828     t::lib::Mocks::mock_preference( 'CheckPrevCheckout',  'hardno' );
829     AddReturn($item_object->barcode, $branchcode);
830
831     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
832     $server->{account}->{blocked_item_types} = "CR|".$item_object->itype;
833     $msg->handle_checkout( $server );
834     $respcode = substr( $response, 0, 2 );
835     check_field( $respcode, $response, FID_SCREEN_MSG, 'Item type cannot be checked out at this checkout location', 'Check screen msg', 'equals' );
836
837     is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 0, "Item was not checked out (item type matched blocked_item_types)");
838
839     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
840     $server->{account}->{blocked_item_types} = "";
841     $msg->handle_checkout( $server );
842     $respcode = substr( $response, 0, 2 );
843     is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 1, "Item was checked out successfully");
844
845 }
846
847 sub test_checkin_v2 {
848     my $builder = t::lib::TestBuilder->new();
849     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
850     my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode};
851     my ( $response, $findpatron );
852     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
853
854     # create some data
855     my $patron1 = $builder->build({
856         source => 'Borrower',
857         value  => {
858             password => hash_password( PATRON_PW ),
859         },
860     });
861     my $card1 = $patron1->{cardnumber};
862     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
863     $findpatron = $sip_patron1;
864     my $item_object = $builder->build_sample_item({
865         damaged => 0,
866         withdrawn => 0,
867         itemlost => 0,
868         restricted => 0,
869         homebranch => $branchcode,
870         holdingbranch => $branchcode,
871     });
872
873     my $mockILS = $mocks->{ils};
874     my $server = { ils => $mockILS, account => {} };
875     $mockILS->mock( 'institution', sub { $branchcode; } );
876     $mockILS->mock( 'supports', sub { return; } );
877     $mockILS->mock( 'checkin', sub {
878         shift;
879         return C4::SIP::ILS->checkin(@_);
880     });
881     my $today = dt_from_string;
882
883     # Checkin invalid barcode
884     Koha::Items->search({ barcode => 'not_to_be_found' })->delete;
885     my $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' .
886         siprequestdate( $today->clone->add( days => 1) ) .
887         FID_INST_ID . $branchcode . '|'.
888         FID_ITEM_ID . 'not_to_be_found' . '|' .
889         FID_TERMINAL_PWD . 'ignored' . '|';
890     undef $response;
891     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
892     warnings_like { $msg->handle_checkin( $server ); }
893         [ qr/No item 'not_to_be_found'/, qr/no item found in object to resensitize/ ],
894         'Checkin of invalid item with two warnings';
895     my $respcode = substr( $response, 0, 2 );
896     is( $respcode, CHECKIN_RESP, 'Response code fine' );
897     is( substr($response,2,1), '0', 'OK flag is false' );
898     is( substr($response,5,1), 'Y', 'Alert flag is set' );
899     check_field( $respcode, $response, FID_SCREEN_MSG, 'Invalid Item', 'Check screen msg', 'regex' );
900
901     # Not checked out, toggle option checked_in_ok
902     $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' .
903         siprequestdate( $today->clone->add( days => 1) ) .
904         FID_INST_ID . $branchcode . '|'.
905         FID_ITEM_ID . $item_object->barcode . '|' .
906         FID_TERMINAL_PWD . 'ignored' . '|';
907     undef $response;
908     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
909     $msg->handle_checkin( $server );
910     $respcode = substr( $response, 0, 2 );
911     is( substr($response,2,1), '0', 'OK flag is false when checking in an item that was not checked out' );
912     is( substr($response,5,1), 'Y', 'Alert flag is set' );
913     check_field( $respcode, $response, FID_SCREEN_MSG, 'not checked out', 'Check screen msg', 'regex' );
914     # Toggle option
915     $server->{account}->{checked_in_ok} = 1;
916     undef $response;
917     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
918     $msg->handle_checkin( $server );
919     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' );
920     is( substr($response,5,1), 'N', 'Alert flag no longer set' );
921     check_field( $respcode, $response, FID_SCREEN_MSG, undef, 'No screen msg' );
922
923     # Move item to another holding branch to trigger CV of 04 with alert flag
924     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
925     $item_object->holdingbranch( $branchcode2 )->store();
926     undef $response;
927     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
928     $msg->handle_checkin( $server );
929     is( substr($response,5,1), 'Y', 'Alert flag is set with check_in_ok, item is checked in but needs transfer' );
930     check_field( $respcode, $response, FID_ALERT_TYPE, '04', 'Got FID_ALERT_TYPE (CV) field with value 04 ( needs transfer )' );
931     $item_object->holdingbranch( $branchcode )->store();
932     t::lib::Mocks::mock_preference( ' AllowReturnToBranch ', 'anywhere' );
933
934     $server->{account}->{cv_send_00_on_success} = 0;
935     undef $response;
936     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
937     $msg->handle_checkin( $server );
938     $respcode = substr( $response, 0, 2 );
939     check_field( $respcode, $response, FID_ALERT_TYPE, undef, 'No FID_ALERT_TYPE (CV) field' );
940     $server->{account}->{cv_send_00_on_success} = 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     check_field( $respcode, $response, FID_ALERT_TYPE, '00', 'FID_ALERT_TYPE (CV) field is 00' );
946     $server->{account}->{checked_in_ok} = 0;
947     $server->{account}->{cv_send_00_on_success} = 0;
948
949     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '1' );
950     $server->{account}->{checked_in_ok} = 0;
951     $server->{account}->{cv_triggers_alert} = 0;
952     undef $response;
953     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
954     $msg->handle_checkin( $server );
955     $respcode = substr( $response, 0, 2 );
956     is( substr( $response, 5, 1 ), 'Y', 'Checkin without CV triggers alert flag when cv_triggers_alert is off' );
957     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '0' );
958     $server->{account}->{cv_triggers_alert} = 1;
959     undef $response;
960     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
961     $msg->handle_checkin( $server );
962     $respcode = substr( $response, 0, 2 );
963     is( substr( $response, 5, 1 ), 'N', 'Checkin without CV does not trigger alert flag when cv_triggers_alert is on' );
964     $server->{account}->{cv_triggers_alert} = 0;
965     t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '1' );
966
967     $server->{account}->{checked_in_ok} = 1;
968     $server->{account}->{ct_always_send} = 0;
969     undef $response;
970     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
971     $msg->handle_checkin( $server );
972     $respcode = substr( $response, 0, 2 );
973     check_field( $respcode, $response, FID_DESTINATION_LOCATION, undef, 'No FID_DESTINATION_LOCATION (CT) field' );
974     $server->{account}->{ct_always_send} = 1;
975     undef $response;
976     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
977     $msg->handle_checkin( $server );
978     $respcode = substr( $response, 0, 2 );
979     check_field( $respcode, $response, FID_DESTINATION_LOCATION, q{}, 'FID_DESTINATION_LOCATION (CT) field is empty but present' );
980     $server->{account}->{checked_in_ok} = 0;
981     $server->{account}->{ct_always_send} = 0;
982
983     # Checkin at wrong branch: issue item and switch branch, and checkin
984     my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store;
985     $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
986     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
987     undef $response;
988     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
989     $msg->handle_checkin( $server );
990     is( substr($response,2,1), '0', 'OK flag is false when we check in at the wrong branch and we do not allow it' );
991     is( substr($response,5,1), 'Y', 'Alert flag is set' );
992     check_field( $respcode, $response, FID_SCREEN_MSG, 'Checkin failed', 'Check screen msg' );
993     $branchcode = $item_object->homebranch;  # switch back
994     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
995
996     # Data corrupted: add same issue_id to old_issues
997     Koha::Old::Checkout->new({ issue_id => $issue->issue_id })->store;
998     undef $response;
999     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
1000     warnings_like { $msg->handle_checkin( $server ); }
1001         [ qr/Duplicate entry/, qr/data issues/ ],
1002         'DBIx error on duplicate issue_id';
1003     is( substr($response,2,1), '0', 'OK flag is false when we encounter data corruption in old_issues' );
1004     is( substr($response,5,1), 'Y', 'Alert flag is set' );
1005     check_field( $respcode, $response, FID_SCREEN_MSG, 'Checkin failed: data problem', 'Check screen msg' );
1006
1007     # Finally checkin without problems (remove duplicate id)
1008     Koha::Old::Checkouts->search({ issue_id => $issue->issue_id })->delete;
1009     undef $response;
1010     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
1011     $msg->handle_checkin( $server );
1012     is( substr($response,2,1), '1', 'OK flag is true when we checkin after removing the duplicate' );
1013     is( substr($response,5,1), 'N', 'Alert flag is not set' );
1014     is( Koha::Checkouts->find( $issue->issue_id ), undef,
1015         'Issue record is gone now' );
1016
1017     # Test account option no_holds_check that prevents items on hold from being checked in via SIP
1018     $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store;
1019     is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 1, "Item is checked out");
1020     Koha::Old::Checkouts->search({ issue_id => $issue->issue_id })->delete;
1021     $server->{account}->{holds_block_checkin} = 1;
1022     my $reserve_id = AddReserve({
1023         branchcode     => $branchcode,
1024         borrowernumber => $patron1->{borrowernumber},
1025         biblionumber   => $item_object->biblionumber,
1026         priority       => 1,
1027     });
1028     my $hold = Koha::Holds->find( $reserve_id );
1029     is( $hold->id, $reserve_id, "Hold was created successfully" );
1030     undef $response;
1031     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
1032     $msg->handle_checkin( $server );
1033     is( substr($response,2,1), '0', 'OK flag is false when we check in an item on hold and we do not allow it' );
1034     is( substr($response,5,1), 'Y', 'Alert flag is set' );
1035     is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 1, "Item was not checked in");
1036     $hold->discard_changes;
1037     is( $hold->found, undef, "Hold was not marked as found by SIP when holds_block_checkin enabled");
1038     $server->{account}->{holds_block_checkin} = 0;
1039
1040     # Test account option holds_get_captured that automatically sets the hold as found for a hold and possibly sets it to in transit
1041     $server->{account}->{holds_get_captured} = 0;
1042     undef $response;
1043     $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
1044     $msg->handle_checkin( $server );
1045     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' );
1046     is( substr($response,5,1), 'Y', 'Alert flag is set' );
1047     is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 0, "Item was checked in");
1048     $hold->discard_changes;
1049     is( $hold->found, undef, "Hold was not marked as found by SIP when holds_get_captured disabled");
1050     $hold->delete();
1051     $server->{account}->{holds_get_captured} = 1;
1052 }
1053
1054 sub test_hold_patron_bcode {
1055     my $builder = t::lib::TestBuilder->new();
1056     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
1057     my ( $response, $findpatron );
1058     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
1059
1060     my $item = $builder->build_sample_item(
1061         {
1062             library => $branchcode
1063         }
1064     );
1065
1066     my $server = { ils => $mocks->{ils} };
1067     my $sip_item = C4::SIP::ILS::Item->new( $item->barcode );
1068
1069     is( $sip_item->hold_patron_bcode, q{}, "SIP item with no hold returns empty string" );
1070
1071     my $resp = C4::SIP::Sip::maybe_add( FID_CALL_NUMBER, $sip_item->hold_patron_bcode, $server );
1072     is( $resp, q{}, "maybe_add returns empty string for SIP item with no hold returns empty string" );
1073 }
1074
1075 sub test_checkout_desensitize {
1076     my $builder = t::lib::TestBuilder->new();
1077     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
1078     my ( $response, $findpatron );
1079     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
1080
1081     # create some data
1082     my $patron1 = $builder->build({
1083         source => 'Borrower',
1084         value  => {
1085             password => hash_password( PATRON_PW ),
1086         },
1087     });
1088     my $card1 = $patron1->{cardnumber};
1089     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
1090     my $patron_category = $sip_patron1->ptype();
1091     $findpatron = $sip_patron1;
1092     my $item_object = $builder->build_sample_item({
1093         damaged => 0,
1094         withdrawn => 0,
1095         itemlost => 0,
1096         restricted => 0,
1097         homebranch => $branchcode,
1098         holdingbranch => $branchcode,
1099     });
1100     my $itemtype = $item_object->effective_itemtype;
1101
1102     my $mockILS = $mocks->{ils};
1103     my $server = { ils => $mockILS, account => {} };
1104     $mockILS->mock( 'institution', sub { $branchcode; } );
1105     $mockILS->mock( 'supports', sub { return; } );
1106     $mockILS->mock( 'checkout', sub {
1107         shift;
1108         return C4::SIP::ILS->checkout(@_);
1109     });
1110     my $today = dt_from_string;
1111     t::lib::Mocks::mock_userenv({ branchcode => $branchcode, flags => 1 });
1112     t::lib::Mocks::mock_preference( 'CheckPrevCheckout',  'hardyes' );
1113
1114     my $siprequest = CHECKOUT . 'YN' . siprequestdate($today) .
1115     siprequestdate( $today->clone->add( days => 1) ) .
1116     FID_INST_ID . $branchcode . '|'.
1117     FID_PATRON_ID . $sip_patron1->id . '|' .
1118     FID_ITEM_ID . $item_object->barcode . '|' .
1119     FID_TERMINAL_PWD . 'ignored' . '|';
1120
1121     undef $response;
1122     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
1123     $server->{account}->{inhouse_patron_categories} = "A,$patron_category,Z";
1124     $msg->handle_checkout( $server );
1125     my $respcode = substr( $response, 5, 1 );
1126     is( $respcode, 'N', "Desensitize flag was not set for patron category in inhouse_patron_categories" );
1127
1128     undef $response;
1129     $server->{account}->{inhouse_patron_categories} = "A,B,C";
1130     $msg->handle_checkout( $server );
1131     $respcode = substr( $response, 5, 1 );
1132     is( $respcode, 'Y', "Desensitize flag was set for patron category not in inhouse_patron_categories" );
1133
1134     undef $response;
1135     $server->{account}->{inhouse_patron_categories} = "";
1136     $msg->handle_checkout( $server );
1137     $respcode = substr( $response, 5, 1 );
1138     is( $respcode, 'Y', "Desensitize flag was set for empty inhouse_patron_categories" );
1139
1140     $server->{account}->{inhouse_patron_categories} = "";
1141
1142     undef $response;
1143     $server->{account}->{inhouse_item_types} = "A,$itemtype,Z";
1144     $msg->handle_checkout( $server );
1145     $respcode = substr( $response, 5, 1 );
1146     is( $respcode, 'N', "Desensitize flag was not set for itemtype in inhouse_item_types" );
1147
1148     undef $response;
1149     $server->{account}->{inhouse_item_types} = "A,B,C";
1150     $msg->handle_checkout( $server );
1151     $respcode = substr( $response, 5, 1 );
1152     is( $respcode, 'Y', "Desensitize flag was set for item type not in inhouse_item_types" );
1153
1154     undef $response;
1155     $server->{account}->{inhouse_item_types} = "";
1156     $msg->handle_checkout( $server );
1157     $respcode = substr( $response, 5, 1 );
1158     is( $respcode, 'Y', "Desensitize flag was set for empty inhouse_item_types" );
1159 }
1160
1161 sub test_renew_desensitize {
1162     my $builder = t::lib::TestBuilder->new();
1163     my $branchcode  = $builder->build({ source => 'Branch' })->{branchcode};
1164     my ( $response, $findpatron );
1165     my $mocks = create_mocks( \$response, \$findpatron, \$branchcode );
1166
1167     # create some data
1168     my $patron1 = $builder->build({
1169         source => 'Borrower',
1170         value  => {
1171             password => hash_password( PATRON_PW ),
1172         },
1173     });
1174     my $card1 = $patron1->{cardnumber};
1175     my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 );
1176     my $patron_category = $sip_patron1->ptype();
1177     $findpatron = $sip_patron1;
1178     my $item_object = $builder->build_sample_item({
1179         damaged => 0,
1180         withdrawn => 0,
1181         itemlost => 0,
1182         restricted => 0,
1183         homebranch => $branchcode,
1184         holdingbranch => $branchcode,
1185     });
1186     my $itemtype = $item_object->effective_itemtype;
1187
1188     my $mockILS = $mocks->{ils};
1189     my $server = { ils => $mockILS, account => {} };
1190     $mockILS->mock( 'institution', sub { $branchcode; } );
1191     $mockILS->mock( 'supports', sub { return; } );
1192     $mockILS->mock( 'checkout', sub {
1193         shift;
1194         return C4::SIP::ILS->checkout(@_);
1195     });
1196     my $today = dt_from_string;
1197     t::lib::Mocks::mock_userenv({ branchcode => $branchcode, flags => 1 });
1198
1199     my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store;
1200
1201     my $siprequest = RENEW . 'YN' . siprequestdate($today) .
1202     siprequestdate( $today->clone->add( days => 1) ) .
1203     FID_INST_ID . $branchcode . '|'.
1204     FID_PATRON_ID . $sip_patron1->id . '|' .
1205     FID_ITEM_ID . $item_object->barcode . '|' .
1206     FID_TERMINAL_PWD . 'ignored' . '|';
1207
1208     undef $response;
1209     my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 );
1210     $server->{account}->{inhouse_patron_categories} = "A,$patron_category,Z";
1211     $msg->handle_checkout( $server );
1212     my $respcode = substr( $response, 5, 1 );
1213     is( $respcode, 'N', "Desensitize flag was not set for patron category in inhouse_patron_categories" );
1214
1215     undef $response;
1216     $server->{account}->{inhouse_patron_categories} = "A,B,C";
1217     $msg->handle_checkout( $server );
1218     $respcode = substr( $response, 5, 1 );
1219     is( $respcode, 'Y', "Desensitize flag was set for patron category not in inhouse_patron_categories" );
1220
1221     undef $response;
1222     $server->{account}->{inhouse_patron_categories} = "";
1223     $msg->handle_checkout( $server );
1224     $respcode = substr( $response, 5, 1 );
1225     is( $respcode, 'Y', "Desensitize flag was set for empty inhouse_patron_categories" );
1226
1227     $server->{account}->{inhouse_patron_categories} = "";
1228
1229     undef $response;
1230     $server->{account}->{inhouse_item_types} = "A,B,C";
1231     $msg->handle_checkout( $server );
1232     $respcode = substr( $response, 5, 1 );
1233     is( $respcode, 'Y', "Desensitize flag was set for item type not in inhouse_item_types" );
1234
1235     undef $response;
1236     $server->{account}->{inhouse_item_types} = "";
1237     $msg->handle_checkout( $server );
1238     $respcode = substr( $response, 5, 1 );
1239     is( $respcode, 'Y', "Desensitize flag was set for empty inhouse_item_types" );
1240
1241     undef $response;
1242     $server->{account}->{inhouse_item_types} = "A,$itemtype,Z";
1243     $msg->handle_checkout( $server );
1244     $respcode = substr( $response, 5, 1 );
1245     is( $respcode, 'N', "Desensitize flag was not set for itemtype in inhouse_item_types" );
1246
1247 }
1248
1249 # Helper routines
1250
1251 sub create_mocks {
1252     my ( $response, $findpatron, $branchcode ) = @_; # referenced variables !
1253
1254     # mock write_msg (imported from Sip.pm into Message.pm)
1255     my $mockMsg = Test::MockModule->new( 'C4::SIP::Sip::MsgType' );
1256     $mockMsg->mock( 'write_msg', sub { $$response = $_[1]; } ); # save response
1257
1258     # mock ils object
1259     my $mockILS = Test::MockObject->new;
1260     $mockILS->mock( 'check_inst_id', sub {} );
1261     $mockILS->mock( 'institution_id', sub { $$branchcode; } );
1262     $mockILS->mock( 'find_patron', sub { $$findpatron; } );
1263
1264     return { ils => $mockILS, message => $mockMsg };
1265 }
1266
1267 sub check_field {
1268     my ( $code, $resp, $fld, $expr, $msg, $mode ) = @_;
1269     # mode: contains || equals || regex (by default: equals)
1270
1271     # strip fixed part; prefix to simplify next regex
1272     $resp = '|'. substr( $resp, fixed_length( $code ) );
1273     my $fldval;
1274     if( $resp =~ /\|$fld([^\|]*)\|/ ) {
1275         $fldval = $1;
1276     } elsif( !defined($expr) ) { # field should not be found
1277         ok( 1, $msg );
1278         return;
1279     } else { # test fails
1280         is( 0, 1, "Code $fld not found in '$resp'?" );
1281         return;
1282     }
1283
1284     if( !$mode || $mode eq 'equals' ) { # default
1285         is( $fldval, $expr, $msg );
1286     } elsif( $mode eq 'regex' ) {
1287         is( $fldval =~ /$expr/, 1, $msg );
1288     } else { # contains
1289         is( index( $fldval, $expr ) > -1, 1, $msg );
1290     }
1291 }
1292
1293 sub siprequestdate {
1294     my ( $dt ) = @_;
1295     return $dt->ymd('').(' 'x4).$dt->hms('');
1296 }
1297
1298 sub fixed_length { #length of fixed fields including response code
1299     return {
1300       ( PATRON_STATUS_RESP )  => 37,
1301       ( PATRON_INFO_RESP )    => 61,
1302       ( CHECKIN_RESP )        => 24,
1303       ( CHECKOUT_RESP )       => 24,
1304     }->{$_[0]};
1305 }