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