]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Booking.pm
LP1797934: Add a patron's booking reservations to their OPAC account
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Booking.pm
1 package OpenILS::Application::Booking;
2
3 use strict;
4 use warnings;
5
6 use POSIX qw/strftime/;
7 use OpenILS::Application;
8 use base qw/OpenILS::Application/;
9
10 use OpenILS::Utils::DateTime qw/:datetime/;
11 use OpenILS::Utils::CStoreEditor qw/:funcs/;
12 use OpenILS::Utils::Fieldmapper;
13 use OpenILS::Application::AppUtils;
14 my $U = "OpenILS::Application::AppUtils";
15
16 use OpenSRF::Utils::Logger qw/$logger/;
17
18 sub prepare_new_brt {
19     my ($record_id, $owning_lib, $mvr) = @_;
20
21     my $brt = new Fieldmapper::booking::resource_type;
22     $brt->isnew(1);
23     $brt->name($mvr->title);
24     $brt->record($record_id);
25     $brt->catalog_item('t');
26     $brt->transferable('t');
27     $brt->owner($owning_lib);
28
29     return $brt;
30 }
31
32 sub get_existing_brt {
33     my ($e, $record_id, $owning_lib, $mvr) = @_;
34     my $results = $e->search_booking_resource_type(
35         {name => $mvr->title, owner => $owning_lib, record => $record_id}
36     );
37
38     return $results->[0] if scalar(@$results) > 0;
39     return undef;
40 }
41
42 sub get_mvr {
43     return $U->simplereq(
44         'open-ils.search',
45         'open-ils.search.biblio.record.mods_slim.retrieve.authoritative',
46         shift # record id
47     );
48 }
49
50 sub get_unique_owning_libs {
51     my %hash = ();
52     $hash{$_->call_number->owning_lib} = 1 foreach (@_);    # @_ are copies
53     return keys %hash;
54 }
55
56 sub fetch_copies_by_ids {
57     my ($e, $copy_ids) = @_;
58     my $results = $e->search_asset_copy([
59         {id => $copy_ids},
60         {flesh => 1, flesh_fields => {acp => ['call_number']}}
61     ]);
62     return $results if ref($results) eq 'ARRAY';
63     return [];
64 }
65
66 sub get_single_record_id {
67     my $record_id = undef;
68     foreach (@_) {  # @_ are copies
69         return undef if
70             (defined $record_id && $record_id != $_->call_number->record);
71         $record_id = $_->call_number->record;
72     }
73     return $record_id;
74 }
75
76 # This function generates the correct json_query clause for determining
77 # whether two given ranges overlap.  Each range is composed of a start
78 # and an end point.  All four points should be the same type (could be int,
79 # date, time, timestamp, or perhaps other types).
80 #
81 # The first range (or the first two points) should be specified as
82 # literal values.  The second range (or the last two points) should be
83 # specified as the names of columns, the values of which in a given row
84 # will constitute the second range in the comparison.
85 #
86 # ALSO: PostgreSQL includes an OVERLAPS operator which provides the same
87 # functionality in a much more concise way, but json_query does not (yet).
88 sub json_query_ranges_overlap {
89     +{ '-or' => [
90         { '-and' => [{$_[2] => {'>=', $_[0]}}, {$_[2] => {'<',  $_[1]}}]},
91         { '-and' => [{$_[3] => {'>',  $_[0]}}, {$_[3] => {'<',  $_[1]}}]},
92         { '-and' => { $_[3] => {'>',  $_[0]},   $_[2] => {'<=', $_[0]}}},
93         { '-and' => { $_[3] => {'>',  $_[1]},   $_[2] => {'<',  $_[1]}}},
94     ]};
95 }
96
97 sub create_brt_and_brsrc {
98     my ($self, $conn, $authtoken, $copy_ids) = @_;
99     my (@created_brt, @created_brsrc);
100     my %brt_table = ();
101
102     my $e = new_editor(xact => 1, authtoken => $authtoken);
103     return $e->die_event unless $e->checkauth;
104
105     my @copies = @{fetch_copies_by_ids($e, $copy_ids)};
106     my $record_id = get_single_record_id(@copies) or return $e->die_event;
107     my $mvr = get_mvr($record_id) or return $e->die_event;
108
109     foreach (get_unique_owning_libs(@copies)) {
110         $brt_table{$_} = get_existing_brt($e, $record_id, $_, $mvr) ||
111             prepare_new_brt($record_id, $_, $mvr);
112     }
113
114     while (my ($owning_lib, $brt) = each %brt_table) {
115         my $pre_existing = 1;
116         if ($brt->isnew) {
117             if ($e->allowed('ADMIN_BOOKING_RESOURCE_TYPE', $owning_lib)) {
118                 $pre_existing = 0;
119                 return $e->die_event unless (
120                     #    v-- Important: assignment modifies original hash
121                     $brt = $e->create_booking_resource_type($brt)
122                 );
123             }
124         }
125         push @created_brt, [$brt->id, $brt->record, $pre_existing];
126     }
127
128     foreach (@copies) {
129         if ($e->allowed(
130             'ADMIN_BOOKING_RESOURCE', $_->call_number->owning_lib
131         )) {
132             # This block needs to disregard any cstore failures and just
133             # return what results it can.
134             my $brsrc = new Fieldmapper::booking::resource;
135             $brsrc->isnew(1);
136             $brsrc->type($brt_table{$_->call_number->owning_lib}->id);
137             $brsrc->owner($_->call_number->owning_lib);
138             $brsrc->barcode($_->barcode);
139
140             $e->set_savepoint("alpha");
141             my $pre_existing = 0;
142             my $usable_result = undef;
143             if (!($usable_result = $e->create_booking_resource($brsrc))) {
144                 $e->rollback_savepoint("alpha");
145                 if (($usable_result = $e->search_booking_resource(
146                     +{ map { ($_, $brsrc->$_()) } qw/type owner barcode/ }
147                 ))) {
148                     $usable_result = $usable_result->[0];
149                     $pre_existing = 1;
150                 } else {
151                     # So we failed to create a booking resource for this copy.
152                     # For now, let's just keep going.  If the calling app wants
153                     # to consider this an error, it can notice the absence
154                     # of a booking resource for the copy in the returned
155                     # results.
156                     $logger->warn(
157                         "Couldn't create or find brsrc for acp #" .  $_->id
158                     );
159                 }
160             } else {
161                 $e->release_savepoint("alpha");
162             }
163
164             if ($usable_result) {
165                 push @created_brsrc,
166                     [$usable_result->id, $_->id, $pre_existing];
167             }
168         }
169     }
170
171     $e->commit and
172         return {brt => \@created_brt, brsrc => \@created_brsrc} or
173         return $e->die_event;
174 }
175 __PACKAGE__->register_method(
176     method   => "create_brt_and_brsrc",
177     api_name => "open-ils.booking.resources.create_from_copies",
178     signature => {
179         params => [
180             {type => 'string', desc => 'Authentication token'},
181             {type => 'array', desc => 'Copy IDs'},
182         ],
183         return => { desc => "A two-element hash. The 'brt' element " .
184             "is a list of created booking resource types described by " .
185             "3-tuples (id, copy id, was pre-existing).  The 'brsrc' " .
186             "element is a similar list of created booking resources " .
187             "described by (id, record id, was pre-existing) 3-tuples."}
188     }
189 );
190
191
192 sub create_bresv {
193     my ($self, $client, $authtoken,
194         $target_user_barcode, $datetime_range, $pickup_lib,
195         $brt, $brsrc_list, $attr_values, $email_notify) = @_;
196
197     $brsrc_list = [ undef ] if not defined $brsrc_list;
198     return undef if scalar(@$brsrc_list) < 1; # Empty list not ok.
199
200     my $e = new_editor(xact => 1, authtoken => $authtoken);
201     return $e->die_event unless $e->checkauth;
202     return $e->die_event unless $e->allowed("ADMIN_BOOKING_RESERVATION");
203
204     my $usr = $U->fetch_user_by_barcode($target_user_barcode);
205     return $usr if ref($usr) eq 'HASH' and exists($usr->{"ilsevent"});
206
207     my $results = [];
208     foreach my $brsrc (@$brsrc_list) {
209         my $bresv = new Fieldmapper::booking::reservation;
210         $bresv->usr($usr->id);
211         $bresv->request_lib($e->requestor->ws_ou);
212         $bresv->pickup_lib($pickup_lib);
213         $bresv->start_time($datetime_range->[0]);
214         $bresv->end_time($datetime_range->[1]);
215         $bresv->email_notify(1) if $email_notify;
216
217         # A little sanity checking: don't agree to put a reservation on a
218         # brsrc and a brt when they don't match.  In fact, bomb out of
219         # this transaction entirely.
220         if ($brsrc) {
221             my $brsrc_itself = $e->retrieve_booking_resource([
222                 $brsrc, {
223                     "flesh" => 1,
224                     "flesh_fields" => {"brsrc" => ["type"]}
225                 }
226             ]);
227
228             if (not $brsrc_itself) {
229                 my $ev = new OpenILS::Event(
230                     "RESERVATION_BAD_PARAMS",
231                     desc => "brsrc $brsrc doesn't exist"
232                 );
233                 $e->disconnect;
234                 return $ev;
235             }
236             elsif ($brsrc_itself->type->id != $brt) {
237                 my $ev = new OpenILS::Event(
238                     "RESERVATION_BAD_PARAMS",
239                     desc => "brsrc $brsrc doesn't match given brt $brt"
240                 );
241                 $e->disconnect;
242                 return $ev;
243             }
244
245             # Also bail if the user is trying to create a reservation at
246             # a pickup lib to which our resource won't go.
247             if (
248                 $brsrc_itself->owner != $pickup_lib and
249                     not $brsrc_itself->type->transferable
250             ) {
251                 my $ev = new OpenILS::Event(
252                     "RESERVATION_BAD_PARAMS",
253                     desc => "brsrc $brsrc doesn't belong to $pickup_lib and " .
254                         "is not transferable"
255                 );
256                 $e->disconnect;
257                 return $ev;
258             }
259         }
260         $bresv->target_resource($brsrc);    # undef is ok here
261         $bresv->target_resource_type($brt);
262
263         ($bresv = $e->create_booking_reservation($bresv)) or
264             return $e->die_event;
265
266         # We could/should do some sanity checking on this too: namely, on
267         # whether the attribute values given actually apply to the relevant
268         # brt.  Not seeing any grievous side effects of not checking, though.
269         my @bravm = ();
270         foreach my $value (@$attr_values) {
271             my $bravm = new Fieldmapper::booking::reservation_attr_value_map;
272             $bravm->reservation($bresv->id);
273             $bravm->attr_value($value);
274             $bravm = $e->create_booking_reservation_attr_value_map($bravm) or
275                 return $e->die_event;
276             push @bravm, $bravm;
277         }
278         push @$results, {
279             "bresv" => $bresv->id,
280             "bravm" => \@bravm,
281         };
282     }
283
284     $e->commit or return $e->die_event;
285
286     # Targeting must be tacked on _after_ committing the transaction where the
287     # reservations are actually created.
288     foreach (@$results) {
289         $_->{"targeting"} = $U->storagereq(
290             "open-ils.storage.booking.reservation.resource_targeter",
291             $_->{"bresv"}
292         )->[0];
293     }
294     return $results;
295 }
296 __PACKAGE__->register_method(
297     method   => "create_bresv",
298     api_name => "open-ils.booking.reservations.create",
299     signature => {
300         params => [
301             {type => 'string', desc => 'Authentication token'},
302             {type => 'string', desc => 'Barcode of user for whom to reserve'},
303             {type => 'array', desc => 'Two elements: start and end timestamp'},
304             {type => 'int', desc => 'Desired reservation pickup lib'},
305             {type => 'int', desc => 'Booking resource type'},
306             {type => 'list', desc => 'Booking resource (undef ok; empty not ok)'},
307             {type => 'array', desc => 'Attribute values selected'},
308             {type => 'bool', desc => 'Email notification?'},
309         ],
310         return => { desc => "A hash containing the new bresv and a list " .
311             "of new bravm"}
312     }
313 );
314
315
316 sub resource_list_by_attrs {
317     my $self = shift;
318     my $client = shift;
319     my $auth = shift; # Keep as argument, though not used just now.
320     my $filters = shift;
321
322     return undef unless ($filters->{type} || $filters->{attribute_values});
323
324     my $query = {
325         "select"   => {brsrc => [qw/id owner/], brt => ["elbow_room"]},
326         "from"     => {brsrc => {"brt" => {}}},
327         "where"    => {},
328         "distinct" => 1
329     };
330
331     $query->{where} = {"-and" => []};
332     if ($filters->{type}) {
333         push @{$query->{where}->{"-and"}}, {"type" => $filters->{type}};
334     }
335
336     if ($filters->{pickup_lib}) {
337         push @{$query->{where}->{"-and"}},
338             {"-or" => [
339                 {"owner" => $filters->{pickup_lib}},
340                 {"+brt" => {"transferable" => "t"}}
341             ]};
342     }
343
344     if ($filters->{attribute_values}) {
345
346         $query->{from}->{brsrc}->{bram} = { field => 'resource' };
347
348         $filters->{attribute_values} = [$filters->{attribute_values}]
349             if (!ref($filters->{attribute_values}));
350
351         $query->{having}->{'+bram'}->{value}->{'@>'} = {
352             transform => 'array_accum',
353             value => '$_' . $$ . '${' .
354                 join(',', @{$filters->{attribute_values}}) .
355                 '}$_' . $$ . '$'
356         };
357     }
358
359     if ($filters->{available}) {
360         # If only one timestamp has been provided, make it into a range.
361         if (!ref($filters->{available})) {
362             $filters->{available} = [($filters->{available}) x 2];
363         }
364
365         push @{$query->{where}->{"-and"}}, {
366             "-or" => [
367                 {"overbook" => "t"},
368                 {"-not-exists" => {
369                     "select" => {"bresv" => ["id"]},
370                     "from" => "bresv",
371                     "where" => {"-and" => [
372                         json_query_ranges_overlap(
373                             $filters->{available}->[0],
374                             $filters->{available}->[1],
375                             "start_time",
376                             "end_time"
377                         ),
378                         {"cancel_time" => undef},
379                         {"return_time" => undef},
380                         {"current_resource" => {"=" => {"+brsrc" => "id"}}}
381                     ]},
382                 }}
383             ]
384         };
385     }
386     if ($filters->{booked}) {
387         # If only one timestamp has been provided, make it into a range.
388         if (!ref($filters->{booked})) {
389             $filters->{booked} = [($filters->{booked}) x 2];
390         }
391
392         push @{$query->{where}->{"-and"}}, {
393             "-exists" => {
394                 "select" => {"bresv" => ["id"]},
395                 "from" => "bresv",
396                 "where" => {"-and" => [
397                     json_query_ranges_overlap(
398                         $filters->{booked}->[0],
399                         $filters->{booked}->[1],
400                         "start_time",
401                         "end_time"
402                     ),
403                     {"cancel_time" => undef},
404                     {"current_resource" => { "=" => {"+brsrc" => "id"}}}
405                 ]},
406             }
407         };
408         # I think that the "booked" case could be done with a JOIN instead of
409         # an EXISTS, but I'm leaving it this way for symmetry with the
410         # "available" case for now.  The available case cannot be done with a
411         # join.
412     }
413
414     my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
415     my $rows = $cstore->request(
416         "open-ils.cstore.json_query.atomic", $query
417     )->gather(1);
418     $cstore->disconnect;
419
420     return [] if not @$rows;
421
422     if ($filters->{"pickup_lib"} && $filters->{"available"}) {
423         my @new_rows = ();
424         my $general_elbow_room = $U->ou_ancestor_setting_value(
425             $filters->{"pickup_lib"},
426             "circ.booking_reservation.default_elbow_room"
427         ) || '0 seconds';
428         my $would_start = $filters->{"available"}->[0];
429         my $dt_parser = new DateTime::Format::ISO8601;
430
431         $logger->info(
432             "general_elbow_room: '$general_elbow_room', " .
433             "would_start: '$would_start'"
434         );
435
436         # Here, elbow_room will double as required transit time padding.
437         foreach (@$rows) {
438             my $elbow_room = $_->{"elbow_room"} || $general_elbow_room;
439             if ($_->{"owner"} != $filters->{"pickup_lib"}) {
440                 (my $ws = $would_start) =~ s/ /T/;
441                 push @new_rows, $_ if DateTime->compare(
442                     $dt_parser->parse_datetime($ws),
443                     DateTime->now(
444                         "time_zone" => DateTime::TimeZone->new(
445                             "name" => "local"
446                         )
447                     )->add(seconds => interval_to_seconds($elbow_room))
448                 ) >= 0;
449             } else {
450                 push @new_rows, $_;
451             }
452         }
453         return [map { $_->{id} } @new_rows];
454     } else {
455         return [map { $_->{id} } @$rows];
456     }
457 }
458
459
460 __PACKAGE__->register_method(
461     method   => "resource_list_by_attrs",
462     api_name => "open-ils.booking.resources.filtered_id_list",
463     argc     => 2,
464     signature=> {
465         params => [
466             {type => 'string', desc => 'Authentication token (unused for now,' .
467                ' but at least pass undef here)'},
468             {type => 'object', desc => 'Filter object: see notes for details'},
469         ],
470         return => { desc => "An array of brsrc ids matching the requested filters." },
471     },
472     notes    => <<'NOTES'
473
474 The filter object parameter can contain the following keys:
475  * type             => The id of a booking resource type (brt)
476  * attribute_values => The ids of booking resource type attribute values that the resource must have assigned to it (brav)
477  * available        => Either:
478                         A timestamp during which the resources are not reserved.  If the resource is overbookable, this is ignored.
479                         A range of two timestamps which do not overlap any reservations for the resources.  If the resource is overbookable, this is ignored.
480  * booked           => Either:
481                         A timestamp during which the resources are reserved.
482                         A range of two timestamps which overlap a reservation of the resources.
483
484 Note that at least one of 'type' or 'attribute_values' is required.
485
486 NOTES
487 );
488
489
490 sub reservation_list_by_filters {
491     my $self = shift;
492     my $client = shift;
493     my $auth = shift;
494     my $filters = shift;
495     my $whole_obj = shift;
496
497     return undef unless (
498            $filters->{user}
499         || $filters->{user_barcode}
500         || $filters->{resource}
501         || $filters->{type}
502         || $filters->{attribute_values}
503     );
504
505     my $e = new_editor(authtoken=>$auth);
506     return $e->event unless $e->checkauth;
507     return $e->event unless $e->allowed('VIEW_TRANSACTION');
508
509     my $query = {
510         'select'   => { bresv => [ 'id', 'start_time' ] },
511         'from'     => { bresv => {} },
512         'where'    => {},
513         'order_by' => [{ class => bresv => field => start_time => direction => 'asc' }],
514         'distinct' => 1
515     };
516
517     if ($filters->{fields}) {
518         $query->{where} = $filters->{fields};
519     }
520
521
522     if ($filters->{user}) {
523         $query->{where}->{usr} = $filters->{user};
524     }
525     elsif ($filters->{user_barcode}) {  # just one of user and user_barcode
526         my $usr = $U->fetch_user_by_barcode($filters->{user_barcode});
527         return $usr if ref($usr) eq 'HASH' and exists($usr->{"ilsevent"});
528         $query->{where}->{usr} = $usr->id;
529     }
530
531
532     if ($filters->{type}) {
533         $query->{where}->{target_resource_type} = $filters->{type};
534     }
535
536     $query->{where}->{"-and"} = [];
537     if ($filters->{resource}) {
538 #       $query->{where}->{target_resource} = $filters->{resource};
539         push @{$query->{where}->{"-and"}}, {
540             "-or" => {
541                 "target_resource" => $filters->{resource},
542                 "current_resource" => $filters->{resource}
543             }
544         };
545     }
546
547     if ($filters->{attribute_values}) {
548
549         $query->{from}->{bresv}->{bravm} = { field => 'reservation' };
550
551         $filters->{attribute_values} = [$filters->{attribute_values}]
552             if (!ref($filters->{attribute_values}));
553
554         $query->{having}->{'+bravm'}->{attr_value}->{'@>'} = {
555             transform => 'array_accum',
556             value => '$_' . $$ . '${' .
557                 join(',', @{$filters->{attribute_values}}) .
558                 '}$_' . $$ . '$'
559         };
560     }
561
562     if ($filters->{search_start} || $filters->{search_end}) {
563         my $or = {};
564
565         $or->{start_time} =
566             {'between' => [ $filters->{search_start}, $filters->{search_end}]}
567                 if $filters->{search_start};
568
569         $or->{end_time} =
570             {'between' =>[$filters->{search_start}, $filters->{search_end}]}
571                 if $filters->{search_end};
572
573         push @{$query->{where}->{"-and"}}, {"-or" => $or};
574     }
575
576     if (not scalar @{$query->{"where"}->{"-and"}}) {
577         delete $query->{"where"}->{"-and"};
578     }
579
580     my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
581     my $ids = [ map { $_->{id} } @{
582         $cstore->request(
583             'open-ils.cstore.json_query.atomic', $query
584         )->gather(1)
585     } ];
586     $cstore->disconnect;
587
588     if (not $whole_obj or @$ids < 1) {
589         $e->disconnect;
590         return $ids;
591     }
592
593     my $bresv_list = $e->search_booking_reservation([
594         {"id" => $ids},
595         {"flesh" => 1,
596             "flesh_fields" => {
597                 "bresv" =>
598                     [qw/target_resource current_resource target_resource_type/]
599             }
600         }]
601     );
602     $e->disconnect;
603     return $bresv_list ? $bresv_list : [];
604 }
605
606 __PACKAGE__->register_method(
607     method   => "upcoming_reservation_list_by_user",
608     api_name => "open-ils.booking.reservations.upcoming_reservation_list_by_user",
609     argc     => 2,
610     signature=> {
611         params => [
612             {type => 'string', desc => 'Authentication token'},
613             {type => 'User ID', type => 'number', desc => 'User ID'},
614         ],
615         return => { desc => "Information about all reservations for a user that haven't yet ended." },
616     },
617     notes    => "You can send undef/NULL as the User ID to get reservations for the logged in user."
618 );
619
620 sub upcoming_reservation_list_by_user {
621     my ($self, $conn, $auth, $user_id) = @_;
622     my $e = new_editor(authtoken => $auth);
623     return $e->event unless $e->checkauth;
624
625     $user_id = $e->requestor->id unless defined $user_id;
626     
627     unless($e->requestor->id == $user_id) {
628         my $user = $e->retrieve_actor_user($user_id) or return $e->event;
629         return $e->event unless $e->allowed('VIEW_TRANSACTION');
630     }
631
632     my $select = { 'bresv' => [qw/start_time end_time cancel_time capture_time pickup_time pickup_lib/],
633         'brsrc' => [ 'barcode' ],
634         'brt' => [{'column' => 'name', 'alias' => 'resource_type_name'}],
635         'aou' => ['shortname', {'column' => 'name', 'alias' => 'pickup_name'}] };
636
637     my $from = { 'bresv' => {'brsrc' => {'field' => 'id', 'fkey' => 'current_resource'},
638         'brt' => {'field' => 'id', 'fkey' => 'target_resource_type'},
639         'aou' => {'field' => 'id', 'fkey' => 'pickup_lib'}} };
640
641     my $query = {
642         'select'   => $select,
643         'from'     => $from,
644         'where'    => { 'usr' => $user_id, 'return_time' => undef, 'end_time' => {'>' => gmtime_ISO8601() }},
645         'order_by' => [{ class => bresv => field => start_time => direction => 'asc' }]
646     };
647
648     my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
649     my $rows = $cstore->request(
650         'open-ils.cstore.json_query.atomic', $query
651     )->gather(1);
652     $cstore->disconnect;
653     $e->disconnect;
654     return [] if not @$rows;
655     return $rows;
656 }
657
658 __PACKAGE__->register_method(
659     method   => "reservation_list_by_filters",
660     api_name => "open-ils.booking.reservations.filtered_id_list",
661     argc     => 3,
662     signature=> {
663         params => [
664             {type => 'string', desc => 'Authentication token'},
665             {type => "object", desc => "Filter object: see notes for details"},
666             {type => "bool", desc => "Return whole object instead of ID? (default false)"}
667         ],
668         return => { desc => "An array of bresv ids matching the requested filters." },
669     },
670     notes    => <<'NOTES'
671
672 The filter object parameter can contain the following keys:
673  * user             => The id of a user that has requested a bookable item -- filters on bresv.usr
674  * barcode          => The barcode of a user that has requested a bookable item
675  * type             => The id of a booking resource type (brt) -- filters on bresv.target_resource_type
676  * resource         => The id of a booking resource (brsrc) -- filters on bresv.target_resource
677  * attribute_values => The ids of booking resource type attribute values that the resource must have assigned to it (brav)
678  * search_start     => If search_end is not specified, booking interval (start_time to end_time) must contain this timestamp.
679  * search_end       => If search_start is not specified, booking interval (start_time to end_time) must contain this timestamp.
680  * fields           => An object containing any combination of bresv search filters in standard cstore/pcrud search format.
681
682 Note that at least one of 'user', 'type', 'resource' or 'attribute_values' is required.  If both search_start and search_end are specified,
683 then the result includes any reservations that overlap with that time range.  Any filter fields supplied in 'fields' are overridden
684 by the top-level filters ('user', 'type', 'resource').
685
686 NOTES
687 );
688
689
690 sub naive_ts_string {strftime("%F %T", localtime($_[0] || time));}
691
692 # Return a map of bresv or an ilsevent on failure.
693 sub get_uncaptured_bresv_for_brsrc {
694     my ($e, $o) = @_; # o's keys (all optional): owning_lib, barcode, range
695
696     my $from_clause = {
697         "bresv" => {
698             "brsrc" => {"field" => "id", "fkey" => "current_resource"}
699         }
700     };
701
702     my $query = {
703         "select" => {
704             "bresv" => [
705                 "current_resource",
706                 {
707                     "column" => "start_time",
708                     "transform" => "min",
709                     "aggregate" => 1
710                 }
711             ]
712         },
713         "from" => $from_clause,
714         "where" => {
715             "-and" => [
716                 {"current_resource" => {"!=" => undef}},
717                 {"capture_time" => undef},
718                 {"cancel_time" => undef},
719                 {"return_time" => undef},
720                 {"pickup_time" => undef}
721             ]
722         }
723     };
724     if ($o->{"owning_lib"}) {
725         push @{$query->{"where"}->{"-and"}},
726             {"+brsrc" => {"owner" => $o->{"owning_lib"}}};
727     }
728     if ($o->{"range"}) {
729         push @{$query->{"where"}->{"-and"}},
730             json_query_ranges_overlap(
731                 $o->{"range"}->[0], $o->{"range"}->[1],
732                 "start_time", "end_time"
733             );
734     }
735     if ($o->{"barcode"}) {
736         push @{$query->{"where"}->{"-and"}},
737             {"+brsrc" => {"barcode" => $o->{"barcode"}}};
738     }
739
740     my $rows = $e->json_query($query);
741     my $current_resource_bresv_map = {};
742     if (@$rows) {
743         my $id_query = {
744             "select" => {"bresv" => ["id"]},
745             "from" => $from_clause,
746             "where" => {
747                 "-and" => [
748                     {"current_resource" => "PLACEHOLDER"},
749                     {"start_time" => "PLACEHOLDER"},
750                     {"capture_time" => undef},
751                     {"cancel_time" => undef},
752                     {"return_time" => undef},
753                     {"pickup_time" => undef}
754                 ]
755             }
756         };
757         if ($o->{"owning_lib"}) {
758             push @{$id_query->{"where"}->{"-and"}},
759                 {"+brsrc" => {"owner" => $o->{"owning_lib"}}};
760         }
761
762         foreach (@$rows) {
763             $id_query->{"where"}->{"-and"}->[0]->{"current_resource"} =
764                 $_->{"current_resource"};
765             $id_query->{"where"}->{"-and"}->[1]->{"start_time"} =
766                 $_->{"start_time"};
767
768             my $results = $e->json_query($id_query);
769             if ($results && @$results) {
770                 $current_resource_bresv_map->{$_->{"current_resource"}} =
771                     [map { $_->{"id"} } @$results];
772             }
773         }
774     }
775     return $current_resource_bresv_map;
776 }
777
778 sub get_pull_list {
779     my ($self, $client, $auth, $range, $interval_secs, $owning_lib) = @_;
780
781     my $e = new_editor(xact => 1, authtoken => $auth);
782     return $e->die_event unless $e->checkauth;
783     return $e->die_event unless $e->allowed("RETRIEVE_RESERVATION_PULL_LIST");
784     return $e->die_event unless (
785         ref($range) eq "ARRAY" or
786         ($interval_secs = int($interval_secs)) > 0
787     );
788
789     $owning_lib = $e->requestor->ws_ou if not $owning_lib;
790     $range = [ naive_ts_string(time), naive_ts_string(time + $interval_secs) ]
791         if not $range;
792
793     my $uncaptured = get_uncaptured_bresv_for_brsrc(
794         $e, {"range" => $range, "owning_lib" => $owning_lib}
795     );
796
797     if (keys(%$uncaptured)) {
798         my @all_bresv_ids = map { @{$_} } values %$uncaptured;
799         my %bresv_lookup = (
800             map { $_->id => $_ } @{
801                 $e->search_booking_reservation([{"id" => [@all_bresv_ids]}, {
802                     flesh => 1,
803                     flesh_fields => { bresv => [
804                         "usr", "target_resource_type", "current_resource"
805                     ]}
806                 }])
807             }
808         );
809         $e->disconnect;
810         return [ map {
811             my $key = $_;
812             my $one = $bresv_lookup{$uncaptured->{$key}->[0]};
813             my $result = {
814                 "current_resource" => $one->current_resource,
815                 "target_resource_type" => $one->target_resource_type,
816                 "reservations" => [
817                     map { $bresv_lookup{$_} } @{$uncaptured->{$key}}
818                 ]
819             };
820             foreach (@{$result->{"reservations"}}) {    # deflesh
821                 $_->current_resource($_->current_resource->id);
822                 $_->target_resource_type($_->target_resource_type->id);
823             }
824             $result;
825         } keys %$uncaptured ];
826     } else {
827         $e->disconnect;
828         return [];
829     }
830 }
831 __PACKAGE__->register_method(
832     method   => "get_pull_list",
833     api_name => "open-ils.booking.reservations.get_pull_list",
834     argc     => 4,
835     signature=> {
836         params => [
837             {type => "string", desc => "Authentication token"},
838             {type => "array", desc =>
839                 "range: Date/time range for reservations (opt)"},
840             {type => "int", desc =>
841                 "interval: Seconds from now (instead of range)"},
842             {type => "number", desc => "(Optional) Owning library"}
843         ],
844         return => { desc => "An array of hashes, each containing key/value " .
845             "pairs describing resource, resource type, and a list of " .
846             "reservations that claim the given resource." }
847     }
848 );
849
850
851 sub could_capture {
852     my ($self, $client, $auth, $barcode) = @_;
853
854     my $e = new_editor("authtoken" => $auth);
855     return $e->die_event unless $e->checkauth;
856     return $e->die_event unless $e->allowed("COPY_CHECKIN");
857
858     my $dt_parser = new DateTime::Format::ISO8601;
859     my $now = now DateTime; # sic
860     my $res = get_uncaptured_bresv_for_brsrc($e, {"barcode" => $barcode});
861
862     if ($res and keys %$res) {
863         my $id;
864         while ((undef, $id) = each %$res) {
865             my $bresv = $e->retrieve_booking_reservation([
866                 $id, {
867                     "flesh" => 1, "flesh_fields" => {
868                         "bresv" => [qw(
869                             usr target_resource_type
870                             target_resource current_resource
871                         )]
872                     }
873                 }
874             ]);
875             my $elbow_room = interval_to_seconds(
876                 $bresv->target_resource_type->elbow_room ||
877                 $U->ou_ancestor_setting_value(
878                     $bresv->pickup_lib,
879                     "circ.booking_reservation.default_elbow_room"
880                 ) ||
881                 "0 seconds"
882             );
883
884             unless ($elbow_room) {
885                 $client->respond($bresv);
886             } else {
887                 my $start_time = $dt_parser->parse_datetime(
888                     clean_ISO8601($bresv->start_time)
889                 );
890
891                 if ($now >= $start_time->subtract("seconds" => $elbow_room)) {
892                     $client->respond($bresv);
893                 } else {
894                     $logger->info(
895                         "not within elbow room: $elbow_room, " .
896                         "else would have returned bresv " . $bresv->id
897                     );
898                 }
899             }
900         }
901     }
902     $e->disconnect;
903     undef;
904 }
905 __PACKAGE__->register_method(
906     method   => "could_capture",
907     api_name => "open-ils.booking.reservations.could_capture",
908     argc     => 2,
909     streaming=> 1,
910     signature=> {
911         params => [
912             {type => "string", desc => "Authentication token"},
913             {type => "string", desc => "Resource barcode"}
914         ],
915         return => {desc => "One or zero reservations; event on error."}
916     }
917 );
918
919
920 sub get_copy_fleshed_just_right {
921     my ($self, $client, $auth, $barcode) = @_;
922
923     return undef if not defined $barcode;
924     return {} if ref($barcode) eq "ARRAY" and not @$barcode;
925
926     my $e = new_editor(authtoken => $auth);
927     my $results = $e->search_asset_copy([
928         {"barcode" => $barcode},
929         {
930             "flesh" => 1,
931             "flesh_fields" => {"acp" => [qw/call_number location/]}
932         }
933     ]);
934
935     if (ref($results) eq "ARRAY") {
936         $e->disconnect;
937         return $results->[0] unless ref $barcode;
938         return +{ map { $_->barcode => $_ } @$results };
939     } else {
940         return $e->die_event;
941     }
942 }
943 __PACKAGE__->register_method(
944     method   => "get_copy_fleshed_just_right",
945     api_name => "open-ils.booking.asset.get_copy_fleshed_just_right",
946     argc     => 2,
947     signature=> {
948         params => [
949             {type => "string", desc => "Authentication token"},
950             {type => "mixed", desc => "One barcode or an array of them"},
951         ],
952         return => { desc =>
953             "A copy, or a hash of copies keyed by barcode if an array of " .
954             "barcodes was given"
955         }
956     }
957 );
958
959
960 sub best_bresv_candidate {
961     my ($e, $id_list) = @_;
962
963     # This will almost always be the case.
964     if (@$id_list == 1) {
965         $logger->info("best_bresv_candidate (only) " . $id_list->[0]);
966         return $id_list->[0];
967     }
968
969     my @here = ();
970     my $this_ou = $e->requestor->ws_ou;
971     my $results = $e->json_query({
972         "select" => {"brsrc" => ["pickup_lib"], "bresv" => ["id"]},
973         "from" => {
974             "bresv" => {
975                 "brsrc" => {"field" => "id", "fkey" => "current_resource"}
976             }
977         },
978         "where" => {
979             {"+bresv" => {"id" => $id_list}}
980         }
981     });
982
983     foreach (@$results) {
984         push @here, $_->{"id"} if $_->{"pickup_lib"} == $this_ou;
985     }
986
987     my $result;
988     if (@here > 0) {
989         $result = @here == 1 ? pop @here : (sort @here)[0];
990     } else {
991         $result = (sort @$id_list)[0];
992     }
993     $logger->info(
994         "best_bresv_candidate from " . join(",", @$id_list) . ": $result"
995     );
996     return $result;
997 }
998
999
1000 sub capture_resource_for_reservation {
1001     my ($self, $client, $auth, $barcode, $no_update_copy) = @_;
1002
1003     my $e = new_editor(authtoken => $auth);
1004     return $e->die_event unless $e->checkauth;
1005     return $e->die_event unless $e->allowed("COPY_CHECKIN");
1006
1007     my $uncaptured = get_uncaptured_bresv_for_brsrc(
1008         $e, {"barcode" => $barcode}
1009     );
1010
1011     if (keys %$uncaptured) {
1012         # Note this will only capture one reservation at a time, even in
1013         # cases with overbooking (multiple "soonest" bresv's on a resource).
1014         my $bresv = best_bresv_candidate(
1015             $e, $uncaptured->{
1016                 (sort(keys %$uncaptured))[0]
1017             }
1018         );
1019         $e->disconnect;
1020         return capture_reservation(
1021             $self, $client, $auth, $bresv, $no_update_copy
1022         );
1023     } else {
1024         return new OpenILS::Event(
1025             "RESERVATION_NOT_FOUND",
1026             "desc" => "No capturable reservation found pertaining " .
1027                 "to a resource with barcode $barcode",
1028             "payload" => {"fail_cause" => "no-reservation", "captured" => 0}
1029         );
1030     }
1031 }
1032 __PACKAGE__->register_method(
1033     method   => "capture_resource_for_reservation",
1034     api_name => "open-ils.booking.resources.capture_for_reservation",
1035     argc     => 3,
1036     signature=> {
1037         params => [
1038             {type => "string", desc => "Authentication token"},
1039             {type => "string", desc => "Barcode of booked & targeted resource"},
1040             {type => "number", desc => "(optional) 1 to not update copy"}
1041         ],
1042         return => { desc => "An OpenILS event describing the capture outcome" }
1043     }
1044 );
1045
1046
1047 sub capture_reservation {
1048     my ($self, $client, $auth, $res_id, $no_update_copy) = @_;
1049
1050     my $e = new_editor("xact" => 1, "authtoken" => $auth);
1051     return $e->die_event unless $e->checkauth;
1052     return $e->die_event unless $e->allowed("COPY_CHECKIN");
1053     my $here = $e->requestor->ws_ou;
1054
1055     my $reservation = $e->retrieve_booking_reservation([
1056         $res_id, {
1057             "flesh" => 2, "flesh_fields" => {
1058                 "bresv" => [qw/usr current_resource type/],
1059                 "au" => ["card"],
1060                 "brsrc" => ["type"]
1061             }
1062         }
1063     ]);
1064
1065     return new OpenILS::Event("RESERVATION_NOT_FOUND") unless $reservation;
1066     return new OpenILS::Event(
1067         "RESERVATION_CAPTURE_FAILED",
1068         payload => {"captured" => 0, "fail_cause" => "no-resource"}
1069     ) unless $reservation->current_resource;
1070
1071     return new OpenILS::Event(
1072         "RESERVATION_CAPTURE_FAILED",
1073         "payload" => {"captured" => 0, "fail_cause" => "cancelled"}
1074     ) if $reservation->cancel_time;
1075
1076     $reservation->capture_staff($e->requestor->id);
1077     $reservation->capture_time("now");
1078
1079     $e->update_booking_reservation($reservation) or return $e->die_event;
1080
1081     my $ret = {"captured" => 1, "reservation" => $reservation};
1082
1083     my $search_acp_like_this = [
1084         {
1085             "barcode" => $reservation->current_resource->barcode,
1086             "deleted" => "f"
1087         },
1088         {"flesh" => 1, "flesh_fields" => {"acp" => ["call_number"]}}
1089     ];
1090
1091     if ($here != $reservation->pickup_lib) {
1092         $logger->info("resource isn't at the reservation's pickup lib...");
1093         return new OpenILS::Event(
1094             "RESERVATION_CAPTURE_FAILED",
1095             "payload" => {"captured" => 0, "fail_cause" => "not-transferable"}
1096         ) unless $U->is_true(
1097             $reservation->current_resource->type->transferable
1098         );
1099
1100         # need to transit the item ... is it already in transit?
1101         my $transit = $e->search_action_reservation_transit_copy(
1102             {"reservation" => $res_id, "dest_recv_time" => undef, cancel_time => undef}
1103         )->[0];
1104
1105         if (!$transit) { # not yet in transit
1106             $transit = new Fieldmapper::action::reservation_transit_copy;
1107
1108             $transit->reservation($reservation->id);
1109             $transit->target_copy($reservation->current_resource->id);
1110             $transit->copy_status(15);
1111             $transit->source_send_time("now");
1112             $transit->source($here);
1113             $transit->dest($reservation->pickup_lib);
1114
1115             $e->create_action_reservation_transit_copy($transit);
1116
1117             if ($U->is_true(
1118                 $reservation->current_resource->type->catalog_item
1119             )) {
1120                 my $copy = $e->search_asset_copy($search_acp_like_this)->[0];
1121
1122                 if ($copy) {
1123                     return new OpenILS::Event(
1124                         "OPEN_CIRCULATION_EXISTS",
1125                         "payload" => {"captured" => 0, "copy" => $copy}
1126                     ) if $copy->status == 1 and not $no_update_copy;
1127
1128                     $ret->{"mvr"} = get_mvr($copy->call_number->record);
1129                     if ($no_update_copy) {
1130                         $ret->{"new_copy_status"} = 6;
1131                     } else {
1132                         $copy->status(6);
1133                         $e->update_asset_copy($copy) or return $e->die_event;
1134                     }
1135                 }
1136             }
1137         }
1138
1139         $ret->{"transit"} = $transit;
1140     } elsif ($U->is_true($reservation->current_resource->type->catalog_item)) {
1141         $logger->info("resource is a catalog item...");
1142         my $copy = $e->search_asset_copy($search_acp_like_this)->[0];
1143
1144         if ($copy) {
1145             return new OpenILS::Event(
1146                 "OPEN_CIRCULATION_EXISTS",
1147                 "payload" => {"captured" => 0, "copy" => $copy}
1148             ) if $copy->status == 1 and not $no_update_copy;
1149
1150             $ret->{"mvr"} = get_mvr($copy->call_number->record);
1151             if ($no_update_copy) {
1152                 $ret->{"new_copy_status"} = 15;
1153             } else {
1154                 $copy->status(15);
1155                 $e->update_asset_copy($copy) or return $e->die_event;
1156             }
1157         }
1158     }
1159
1160     $e->commit or return $e->die_event;
1161
1162     # create action trigger event to notify that reservation is available
1163     if ($reservation->email_notify) {
1164         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1165         $ses->request('open-ils.trigger.event.autocreate', 'reservation.available', $reservation, $reservation->pickup_lib);
1166     }
1167
1168     # XXX I'm not sure whether these last two elements of the payload
1169     # actually get used anywhere.
1170     $ret->{"resource"} = $reservation->current_resource;
1171     $ret->{"type"} = $reservation->current_resource->type;
1172     return new OpenILS::Event("SUCCESS", "payload" => $ret);
1173 }
1174 __PACKAGE__->register_method(
1175     method   => "capture_reservation",
1176     api_name => "open-ils.booking.reservations.capture",
1177     argc     => 2,
1178     signature=> {
1179         params => [
1180             {type => 'string', desc => 'Authentication token'},
1181             {type => 'mixed', desc =>
1182                 'Reservation ID (number) or array of resource barcodes'}
1183         ],
1184         return => { desc => "An OpenILS Event object describing the outcome of the capture, with relevant payload." },
1185     }
1186 );
1187
1188
1189 sub cancel_reservation {
1190     my ($self, $client, $auth, $id_list) = @_;
1191
1192     my $e = new_editor(xact => 1, authtoken => $auth);
1193     return $e->die_event unless $e->checkauth;
1194     # Should the following permission really be checked as relates to each
1195     # individual reservation's request_lib?  Hrmm...
1196     return $e->die_event unless $e->allowed("ADMIN_BOOKING_RESERVATION");
1197
1198     my $bresv_list = $e->search_booking_reservation([
1199         {"id" => $id_list},
1200         {"flesh" => 1, "flesh_fields" => {"bresv" => [
1201             "current_resource", "target_resource_type"
1202         ]}}
1203     ]);
1204     return $e->die_event if not $bresv_list;
1205
1206     my @results = ();
1207     my $circ = OpenSRF::AppSession->connect("open-ils.circ") or
1208         return $e->die_event;
1209     foreach my $bresv (@$bresv_list) {
1210         $bresv->cancel_time("now");
1211         $e->update_booking_reservation($bresv) or do {
1212             $circ->disconnect;
1213             return $e->die_event;
1214         };
1215         $e->xact_commit;
1216         $e->xact_begin;
1217
1218         if (
1219             $bresv->target_resource_type->catalog_item == "t" &&
1220             $bresv->current_resource
1221         ) {
1222             $logger->info("result of no-op checkin (upon cxl bresv) is " .
1223                 $circ->request(
1224                     "open-ils.circ.checkin", $auth,
1225                     {"barcode" => $bresv->current_resource->barcode,
1226                         "noop" => 1}
1227                 )->gather(1)->{"textcode"});
1228         }
1229         push @results, $bresv->id;
1230     }
1231
1232     $e->disconnect;
1233     $circ->disconnect;
1234
1235     return \@results;
1236 }
1237 __PACKAGE__->register_method(
1238     method   => "cancel_reservation",
1239     api_name => "open-ils.booking.reservations.cancel",
1240     argc     => 2,
1241     signature=> {
1242         params => [
1243             {type => "string", desc => "Authentication token"},
1244             {type => "array", desc => "List of reservation IDs"}
1245         ],
1246         return => { desc => "A list of canceled reservation IDs" },
1247     }
1248 );
1249
1250
1251 sub get_captured_reservations {
1252     my ($self, $client, $auth, $barcode, $which) = @_;
1253
1254     my $e = new_editor(xact => 1, authtoken => $auth);
1255     return $e->die_event unless $e->checkauth;
1256     return $e->die_event unless $e->allowed("VIEW_USER");
1257     return $e->die_event unless $e->allowed("ADMIN_BOOKING_RESERVATION");
1258
1259     # fetch the patron for our uses in any case...
1260     my $patron = $U->fetch_user_by_barcode($barcode);
1261     return $patron if ref($patron) eq "HASH" and exists $patron->{"ilsevent"};
1262
1263     my $bresv_flesh = {
1264         "flesh" => 1,
1265         "flesh_fields" => {"bresv" => [
1266             qw/target_resource_type current_resource/
1267         ]}
1268     };
1269
1270     my $dispatch = {
1271         "patron" => sub {
1272             return $patron;
1273         },
1274         "ready" => sub {
1275             return $e->search_booking_reservation([
1276                 {
1277                     "usr" => $patron->id,
1278                     "capture_time" => {"!=" => undef},
1279                     "pickup_time" => undef,
1280                     "start_time" => {"!=" => undef},
1281                     "cancel_time" => undef
1282                 },
1283                 $bresv_flesh
1284             ]) or $e->die_event;
1285         },
1286         "out" => sub {
1287             return $e->search_booking_reservation([
1288                 {
1289                     "usr" => $patron->id,
1290                     "pickup_time" => {"!=" => undef},
1291                     "return_time" => undef,
1292                     "cancel_time" => undef
1293                 },
1294                 $bresv_flesh
1295             ]) or $e->die_event;
1296         },
1297         "in" => sub {
1298             return $e->search_booking_reservation([
1299                 {
1300                     "usr" => $patron->id,
1301                     "return_time" => {">=" => "today"},
1302                     "cancel_time" => undef
1303                 },
1304                 $bresv_flesh
1305             ]) or $e->die_event;
1306         }
1307     };
1308
1309     my $result = {};
1310     foreach (@$which) {
1311         my $f = $dispatch->{$_};
1312         if ($f) {
1313             my $r = &{$f}();
1314             return $r if (ref($r) eq "HASH" and exists $r->{"ilsevent"});
1315             $result->{$_} = $r;
1316         }
1317     }
1318
1319     return $result;
1320 }
1321 __PACKAGE__->register_method(
1322     method   => "get_captured_reservations",
1323     api_name => "open-ils.booking.reservations.get_captured",
1324     argc     => 3,
1325     signature=> {
1326         params => [
1327             {type => "string", desc => "Authentication token"},
1328             {type => "string", desc => "Patron barcode"},
1329             {type => "array", desc => "Parts wanted (patron, ready, out, in?)"}
1330         ],
1331         return => { desc => "A hash of parts." } # XXX describe more fully
1332     }
1333 );
1334
1335
1336 sub get_bresv_by_returnable_resource_barcode {
1337     my ($self, $client, $auth, $barcode) = @_;
1338
1339     my $e = new_editor(xact => 1, authtoken => $auth);
1340     return $e->die_event unless $e->checkauth;
1341     return $e->die_event unless $e->allowed("VIEW_USER");
1342 #    return $e->die_event unless $e->allowed("ADMIN_BOOKING_RESERVATION");
1343
1344     my $rows = $e->json_query({
1345         "select" => {"bresv" => ["id"]},
1346         "from" => {
1347             "bresv" => {
1348                 "brsrc" => {"field" => "id", "fkey" => "current_resource"}
1349             }
1350         },
1351         "where" => {
1352             "+brsrc" => {"barcode" => $barcode},
1353             "-and" => {
1354                 "pickup_time" => {"!=" => undef},
1355                 "cancel_time" => undef,
1356                 "return_time" => undef
1357             }
1358         }
1359     }) or return $e->die_event;
1360
1361     if (@$rows < 1) {
1362         $e->rollback;
1363         return $rows;
1364     } else {
1365         # More than one result might be possible, but we don't want to return
1366         # more than one at this time.
1367         my $id = $rows->[0]->{"id"};
1368         my $resp =$e->retrieve_booking_reservation([
1369             $id, {
1370                 "flesh" => 2,
1371                 "flesh_fields" => {
1372                     "bresv" => [qw/usr target_resource_type current_resource/],
1373                     "au" => ["card"]
1374                 }
1375             }
1376         ]) or $e->die_event;
1377         $e->rollback;
1378         return $resp;
1379     }
1380 }
1381
1382 __PACKAGE__->register_method(
1383     method   => "get_bresv_by_returnable_resource_barcode",
1384     api_name => "open-ils.booking.reservations.by_returnable_resource_barcode",
1385     argc     => 2,
1386     signature=> {
1387         params => [
1388             {type => "string", desc => "Authentication token"},
1389             {type => "string", desc => "Resource barcode"},
1390         ],
1391         return => { desc => "A fleshed bresv or an ilsevent on error" }
1392     }
1393 );
1394
1395
1396 1;