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