1 package OpenILS::Application::Booking;
6 use POSIX qw/strftime/;
7 use OpenILS::Application;
8 use base qw/OpenILS::Application/;
10 use OpenILS::Utils::CStoreEditor qw/:funcs/;
11 use OpenILS::Utils::Fieldmapper;
12 use OpenILS::Application::AppUtils;
13 my $U = "OpenILS::Application::AppUtils";
15 use OpenSRF::Utils::Logger qw/$logger/;
18 my ($record_id, $owning_lib, $mvr) = @_;
20 my $brt = new Fieldmapper::booking::resource_type;
22 $brt->name($mvr->title);
23 $brt->record($record_id);
24 $brt->catalog_item('t');
25 $brt->transferable('t');
26 $brt->owner($owning_lib);
31 sub get_existing_brt {
32 my ($e, $record_id, $owning_lib, $mvr) = @_;
33 my $results = $e->search_booking_resource_type(
34 {name => $mvr->title, owner => $owning_lib, record => $record_id}
37 return $results->[0] if scalar(@$results) > 0;
44 'open-ils.search.biblio.record.mods_slim.retrieve.authoritative',
49 sub get_unique_owning_libs {
51 $hash{$_->call_number->owning_lib} = 1 foreach (@_); # @_ are copies
55 sub fetch_copies_by_ids {
56 my ($e, $copy_ids) = @_;
57 my $results = $e->search_asset_copy([
59 {flesh => 1, flesh_fields => {acp => ['call_number']}}
61 return $results if ref($results) eq 'ARRAY';
65 sub get_single_record_id {
66 my $record_id = undef;
67 foreach (@_) { # @_ are copies
69 (defined $record_id && $record_id != $_->call_number->record);
70 $record_id = $_->call_number->record;
75 # This function generates the correct json_query clause for determining
76 # whether two given ranges overlap. Each range is composed of a start
77 # and an end point. All four points should be the same type (could be int,
78 # date, time, timestamp, or perhaps other types).
80 # The first range (or the first two points) should be specified as
81 # literal values. The second range (or the last two points) should be
82 # specified as the names of columns, the values of which in a given row
83 # will constitute the second range in the comparison.
85 # ALSO: PostgreSQL includes an OVERLAPS operator which provides the same
86 # functionality in a much more concise way, but json_query does not (yet).
87 sub json_query_ranges_overlap {
89 { '-and' => [{$_[2] => {'>=', $_[0]}}, {$_[2] => {'<', $_[1]}}]},
90 { '-and' => [{$_[3] => {'>', $_[0]}}, {$_[3] => {'<', $_[1]}}]},
91 { '-and' => { $_[3] => {'>', $_[0]}, $_[2] => {'<=', $_[0]}}},
92 { '-and' => { $_[3] => {'>', $_[1]}, $_[2] => {'<', $_[1]}}},
96 sub create_brt_and_brsrc {
97 my ($self, $conn, $authtoken, $copy_ids) = @_;
98 my (@created_brt, @created_brsrc);
101 my $e = new_editor(xact => 1, authtoken => $authtoken);
102 return $e->die_event unless $e->checkauth;
104 my @copies = @{fetch_copies_by_ids($e, $copy_ids)};
105 my $record_id = get_single_record_id(@copies) or return $e->die_event;
106 my $mvr = get_mvr($record_id) or return $e->die_event;
108 foreach (get_unique_owning_libs(@copies)) {
109 $brt_table{$_} = get_existing_brt($e, $record_id, $_, $mvr) ||
110 prepare_new_brt($record_id, $_, $mvr);
113 while (my ($owning_lib, $brt) = each %brt_table) {
114 my $pre_existing = 1;
116 if ($e->allowed('ADMIN_BOOKING_RESOURCE_TYPE', $owning_lib)) {
118 return $e->die_event unless (
119 # v-- Important: assignment modifies original hash
120 $brt = $e->create_booking_resource_type($brt)
124 push @created_brt, [$brt->id, $brt->record, $pre_existing];
129 'ADMIN_BOOKING_RESOURCE', $_->call_number->owning_lib
131 # This block needs to disregard any cstore failures and just
132 # return what results it can.
133 my $brsrc = new Fieldmapper::booking::resource;
135 $brsrc->type($brt_table{$_->call_number->owning_lib}->id);
136 $brsrc->owner($_->call_number->owning_lib);
137 $brsrc->barcode($_->barcode);
139 $e->set_savepoint("alpha");
140 my $pre_existing = 0;
141 my $usable_result = undef;
142 if (!($usable_result = $e->create_booking_resource($brsrc))) {
143 $e->rollback_savepoint("alpha");
144 if (($usable_result = $e->search_booking_resource(
145 +{ map { ($_, $brsrc->$_()) } qw/type owner barcode/ }
147 $usable_result = $usable_result->[0];
150 # So we failed to create a booking resource for this copy.
151 # For now, let's just keep going. If the calling app wants
152 # to consider this an error, it can notice the absence
153 # of a booking resource for the copy in the returned
156 "Couldn't create or find brsrc for acp #" . $_->id
160 $e->release_savepoint("alpha");
163 if ($usable_result) {
165 [$usable_result->id, $_->id, $pre_existing];
171 return {brt => \@created_brt, brsrc => \@created_brsrc} or
172 return $e->die_event;
174 __PACKAGE__->register_method(
175 method => "create_brt_and_brsrc",
176 api_name => "open-ils.booking.resources.create_from_copies",
179 {type => 'string', desc => 'Authentication token'},
180 {type => 'array', desc => 'Copy IDs'},
182 return => { desc => "A two-element hash. The 'brt' element " .
183 "is a list of created booking resource types described by " .
184 "3-tuples (id, copy id, was pre-existing). The 'brsrc' " .
185 "element is a similar list of created booking resources " .
186 "described by (id, record id, was pre-existing) 3-tuples."}
192 my ($self, $client, $authtoken,
193 $target_user_barcode, $datetime_range, $pickup_lib,
194 $brt, $brsrc_list, $attr_values) = @_;
196 $brsrc_list = [ undef ] if not defined $brsrc_list;
197 return undef if scalar(@$brsrc_list) < 1; # Empty list not ok.
199 my $e = new_editor(xact => 1, authtoken => $authtoken);
200 return $e->die_event unless (
202 $e->allowed("ADMIN_BOOKING_RESERVATION") and
203 $e->allowed("ADMIN_BOOKING_RESERVATION_ATTR_MAP")
206 my $usr = $U->fetch_user_by_barcode($target_user_barcode);
207 return $usr if ref($usr) eq 'HASH' and exists($usr->{"ilsevent"});
210 foreach my $brsrc (@$brsrc_list) {
211 my $bresv = new Fieldmapper::booking::reservation;
212 $bresv->usr($usr->id);
213 $bresv->request_lib($e->requestor->ws_ou);
214 $bresv->pickup_lib($pickup_lib);
215 $bresv->start_time($datetime_range->[0]);
216 $bresv->end_time($datetime_range->[1]);
218 # A little sanity checking: don't agree to put a reservation on a
219 # brsrc and a brt when they don't match. In fact, bomb out of
220 # this transaction entirely.
222 my $brsrc_itself = $e->retrieve_booking_resource([
225 "flesh_fields" => {"brsrc" => ["type"]}
229 if (not $brsrc_itself) {
230 my $ev = new OpenILS::Event(
231 "RESERVATION_BAD_PARAMS",
232 desc => "brsrc $brsrc doesn't exist"
237 elsif ($brsrc_itself->type->id != $brt) {
238 my $ev = new OpenILS::Event(
239 "RESERVATION_BAD_PARAMS",
240 desc => "brsrc $brsrc doesn't match given brt $brt"
246 # Also bail if the user is trying to create a reservation at
247 # a pickup lib to which our resource won't go.
249 $brsrc_itself->owner != $pickup_lib and
250 not $brsrc_itself->type->transferable
252 my $ev = new OpenILS::Event(
253 "RESERVATION_BAD_PARAMS",
254 desc => "brsrc $brsrc doesn't belong to $pickup_lib and " .
255 "is not transferable"
261 $bresv->target_resource($brsrc); # undef is ok here
262 $bresv->target_resource_type($brt);
264 ($bresv = $e->create_booking_reservation($bresv)) or
265 return $e->die_event;
267 # We could/should do some sanity checking on this too: namely, on
268 # whether the attribute values given actually apply to the relevant
269 # brt. Not seeing any grievous side effects of not checking, though.
271 foreach my $value (@$attr_values) {
272 my $bravm = new Fieldmapper::booking::reservation_attr_value_map;
273 $bravm->reservation($bresv->id);
274 $bravm->attr_value($value);
275 $bravm = $e->create_booking_reservation_attr_value_map($bravm) or
276 return $e->die_event;
280 "bresv" => $bresv->id,
285 $e->commit or return $e->die_event;
287 # Targeting must be tacked on _after_ committing the transaction where the
288 # reservations are actually created.
289 foreach (@$results) {
290 $_->{"targeting"} = $U->storagereq(
291 "open-ils.storage.booking.reservation.resource_targeter",
297 __PACKAGE__->register_method(
298 method => "create_bresv",
299 api_name => "open-ils.booking.reservations.create",
302 {type => 'string', desc => 'Authentication token'},
303 {type => 'string', desc => 'Barcode of user for whom to reserve'},
304 {type => 'array', desc => 'Two elements: start and end timestamp'},
305 {type => 'int', desc => 'Desired reservation pickup lib'},
306 {type => 'int', desc => 'Booking resource type'},
307 {type => 'list', desc => 'Booking resource (undef ok; empty not ok)'},
308 {type => 'array', desc => 'Attribute values selected'},
310 return => { desc => "A hash containing the new bresv and a list " .
316 sub resource_list_by_attrs {
319 my $auth = shift; # Keep as argument, though not used just now.
322 return undef unless ($filters->{type} || $filters->{attribute_values});
325 "select" => {brsrc => ["id"]},
326 "from" => {brsrc => {"brt" => {}}},
331 $query->{where} = {"-and" => []};
332 if ($filters->{type}) {
333 push @{$query->{where}->{"-and"}}, {"type" => $filters->{type}};
336 if ($filters->{pickup_lib}) {
337 push @{$query->{where}->{"-and"}},
339 {"owner" => $filters->{pickup_lib}},
340 {"+brt" => {"transferable" => "t"}}
344 if ($filters->{attribute_values}) {
346 $query->{from}->{brsrc}->{bram} = { field => 'resource' };
348 $filters->{attribute_values} = [$filters->{attribute_values}]
349 if (!ref($filters->{attribute_values}));
351 $query->{having}->{'+bram'}->{value}->{'@>'} = {
352 transform => 'array_accum',
353 value => '$_' . $$ . '${' .
354 join(',', @{$filters->{attribute_values}}) .
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];
365 push @{$query->{where}->{"-and"}}, {
369 "select" => {"bresv" => ["id"]},
371 "where" => {"-and" => [
372 json_query_ranges_overlap(
373 $filters->{available}->[0],
374 $filters->{available}->[1],
378 {"cancel_time" => undef},
379 {"current_resource" => {"=" => {"+brsrc" => "id"}}}
385 if ($filters->{booked}) {
386 # If only one timestamp has been provided, make it into a range.
387 if (!ref($filters->{booked})) {
388 $filters->{booked} = [($filters->{booked}) x 2];
391 push @{$query->{where}->{"-and"}}, {
393 "select" => {"bresv" => ["id"]},
395 "where" => {"-and" => [
396 json_query_ranges_overlap(
397 $filters->{booked}->[0],
398 $filters->{booked}->[1],
402 {"cancel_time" => undef},
403 {"current_resource" => { "=" => {"+brsrc" => "id"}}}
407 # I think that the "booked" case could be done with a JOIN instead of
408 # an EXISTS, but I'm leaving it this way for symmetry with the
409 # "available" case for now. The available case cannot be done with a
413 my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
414 my $rows = $cstore->request( 'open-ils.cstore.json_query.atomic', $query )->gather(1);
417 return @$rows ? [map { $_->{id} } @$rows] : [];
419 __PACKAGE__->register_method(
420 method => "resource_list_by_attrs",
421 api_name => "open-ils.booking.resources.filtered_id_list",
425 {type => 'string', desc => 'Authentication token (unused for now,' .
426 ' but at least pass undef here)'},
427 {type => 'object', desc => 'Filter object: see notes for details'},
428 {type => 'bool', desc => 'Return whole objects instead of IDs?'}
430 return => { desc => "An array of brsrc ids matching the requested filters." },
434 The filter object parameter can contain the following keys:
435 * type => The id of a booking resource type (brt)
436 * attribute_values => The ids of booking resource type attribute values that the resource must have assigned to it (brav)
437 * available => Either:
438 A timestamp during which the resources are not reserved. If the resource is overbookable, this is ignored.
439 A range of two timestamps which do not overlap any reservations for the resources. If the resource is overbookable, this is ignored.
441 A timestamp during which the resources are reserved.
442 A range of two timestamps which overlap a reservation of the resources.
444 Note that at least one of 'type' or 'attribute_values' is required.
450 sub reservation_list_by_filters {
455 my $whole_obj = shift;
457 return undef unless ($filters->{user} || $filters->{user_barcode} || $filters->{resource} || $filters->{type} || $filters->{attribute_values});
459 my $e = new_editor(authtoken=>$auth);
460 return $e->event unless $e->checkauth;
461 return $e->event unless $e->allowed('VIEW_TRANSACTION');
464 'select' => { bresv => [ 'id', 'start_time' ] },
465 'from' => { bresv => {} },
467 'order_by' => [{ class => bresv => field => start_time => direction => 'asc' }],
471 if ($filters->{fields}) {
472 $query->{where} = $filters->{fields};
476 if ($filters->{user}) {
477 $query->{where}->{usr} = $filters->{user};
479 elsif ($filters->{user_barcode}) { # just one of user and user_barcode
480 my $usr = $U->fetch_user_by_barcode($filters->{user_barcode});
481 return $usr if ref($usr) eq 'HASH' and exists($usr->{"ilsevent"});
482 $query->{where}->{usr} = $usr->id;
486 if ($filters->{type}) {
487 $query->{where}->{target_resource_type} = $filters->{type};
490 if ($filters->{resource}) {
491 $query->{where}->{target_resource} = $filters->{resource};
494 if ($filters->{attribute_values}) {
496 $query->{from}->{bresv}->{bravm} = { field => 'reservation' };
498 $filters->{attribute_values} = [$filters->{attribute_values}]
499 if (!ref($filters->{attribute_values}));
501 $query->{having}->{'+bravm'}->{attr_value}->{'@>'} = {
502 transform => 'array_accum',
503 value => '$_' . $$ . '${' .
504 join(',', @{$filters->{attribute_values}}) .
509 if ($filters->{search_start} || $filters->{search_end}) {
510 $query->{where}->{'-or'} = {};
512 $query->{where}->{'-or'}->{start_time} = { 'between' => [ $filters->{search_start}, $filters->{search_end} ] }
513 if ($filters->{search_start});
515 $query->{where}->{'-or'}->{end_time} = { 'between' => [ $filters->{search_start}, $filters->{search_end} ] }
516 if ($filters->{search_end});
519 my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
520 my $ids = [ map { $_->{id} } @{
522 'open-ils.cstore.json_query.atomic', $query
527 if (not $whole_obj or @$ids < 1) {
532 my $bresv_list = $e->search_booking_reservation([
537 [qw/target_resource current_resource target_resource_type/]
542 return $bresv_list ? $bresv_list : [];
544 __PACKAGE__->register_method(
545 method => "reservation_list_by_filters",
546 api_name => "open-ils.booking.reservations.filtered_id_list",
550 {type => 'string', desc => 'Authentication token'},
551 {type => 'object', desc => 'Filter object -- see notes for details'}
553 return => { desc => "An array of bresv ids matching the requested filters." },
557 The filter object parameter can contain the following keys:
558 * user => The id of a user that has requested a bookable item -- filters on bresv.usr
559 * barcode => The barcode of a user that has requested a bookable item
560 * type => The id of a booking resource type (brt) -- filters on bresv.target_resource_type
561 * resource => The id of a booking resource (brsrc) -- filters on bresv.target_resource
562 * attribute_values => The ids of booking resource type attribute values that the resource must have assigned to it (brav)
563 * search_start => If search_end is not specified, booking interval (start_time to end_time) must contain this timestamp.
564 * search_end => If search_start is not specified, booking interval (start_time to end_time) must contain this timestamp.
565 * fields => An object containing any combination of bresv search filters in standard cstore/pcrud search format.
567 Note that at least one of 'user', 'type', 'resource' or 'attribute_values' is required. If both search_start and search_end are specified,
568 then the result includes any reservations that overlap with that time range. Any filter fields supplied in 'fields' are overridden
569 by the top-level filters ('user', 'type', 'resource').
575 sub naive_ts_string { strftime("%F %T", localtime(shift)); }
576 sub naive_start_of_day { strftime("%F", localtime(shift)) . " 00:00:00"; }
578 # Return a list of bresv or an ilsevent on failure.
579 sub get_uncaptured_bresv_for_brsrc {
580 my ($e, $o) = @_; # o's keys (all optional): owning_lib, barcode, range
584 "brsrc" => {"field" => "id", "fkey" => "current_resource"}
593 "column" => "start_time",
594 "transform" => "min",
599 "from" => $from_clause,
602 {"current_resource" => {"!=" => undef}},
603 {"capture_time" => undef},
604 {"cancel_time" => undef},
605 {"return_time" => undef},
606 {"pickup_time" => undef}
610 if ($o->{"owning_lib"}) {
611 push @{$query->{"where"}->{"-and"}},
612 {"+brsrc" => {"owner" => $o->{"owning_lib"}}};
615 push @{$query->{"where"}->{"-and"}},
616 json_query_ranges_overlap(
617 $o->{"range"}->[0], $o->{"range"}->[1],
618 "start_time", "end_time"
621 if ($o->{"barcode"}) {
622 push @{$query->{"where"}->{"-and"}},
623 {"+brsrc" => {"barcode" => $o->{"barcode"}}};
626 my $rows = $e->json_query($query);
627 my $current_resource_bresv_map = {};
630 "select" => {"bresv" => ["id"]},
631 "from" => $from_clause,
634 {"current_resource" => "PLACEHOLDER"},
635 {"start_time" => "PLACEHOLDER"},
639 if ($o->{"owning_lib"}) {
640 push @{$id_query->{"where"}->{"-and"}},
641 {"+brsrc" => {"owner" => $o->{"owning_lib"}}};
645 $id_query->{"where"}->{"-and"}->[0]->{"current_resource"} =
646 $_->{"current_resource"};
647 $id_query->{"where"}->{"-and"}->[1]->{"start_time"} =
650 my $results = $e->json_query($id_query);
651 if ($results && @$results) {
652 $current_resource_bresv_map->{$_->{"current_resource"}} =
653 [map { $_->{"id"} } @$results];
657 return $current_resource_bresv_map;
661 my ($self, $client, $auth, $range, $interval_secs, $owning_lib) = @_;
663 my $e = new_editor(xact => 1, authtoken => $auth);
664 return $e->die_event unless $e->checkauth;
665 return $e->die_event unless $e->allowed("RETRIEVE_RESERVATION_PULL_LIST");
666 return $e->die_event unless (
667 ref($range) eq "ARRAY" or
668 ($interval_secs = int($interval_secs)) > 0
671 $owning_lib = $e->requestor->ws_ou if not $owning_lib;
672 $range = [ naive_ts_string(time), naive_ts_string(time + $interval_secs) ]
675 my $uncaptured = get_uncaptured_bresv_for_brsrc(
676 $e, {"range" => $range, "owning_lib" => $owning_lib}
679 if (keys(%$uncaptured)) {
680 my @all_bresv_ids = map { @{$_} } values %$uncaptured;
682 map { $_->id => $_ } @{
683 $e->search_booking_reservation([{"id" => [@all_bresv_ids]}, {
685 flesh_fields => { bresv => [
686 "usr", "target_resource_type", "current_resource"
694 my $one = $bresv_lookup{$uncaptured->{$key}->[0]};
696 "current_resource" => $one->current_resource,
697 "target_resource_type" => $one->target_resource_type,
699 map { $bresv_lookup{$_} } @{$uncaptured->{$key}}
702 foreach (@{$result->{"reservations"}}) { # deflesh
703 $_->current_resource($_->current_resource->id);
704 $_->target_resource_type($_->target_resource_type->id);
707 } keys %$uncaptured ];
713 __PACKAGE__->register_method(
714 method => "get_pull_list",
715 api_name => "open-ils.booking.reservations.get_pull_list",
719 {type => "string", desc => "Authentication token"},
720 {type => "array", desc =>
721 "range: Date/time range for reservations (opt)"},
722 {type => "int", desc =>
723 "interval: Seconds from now (instead of range)"},
724 {type => "number", desc => "(Optional) Owning library"}
726 return => { desc => "An array of hashes, each containing key/value " .
727 "pairs describing resource, resource type, and a list of " .
728 "reservations that claim the given resource." }
733 sub get_copy_fleshed_just_right {
734 my ($self, $client, $auth, $barcode) = @_;
736 return undef if not defined $barcode;
737 return {} if ref($barcode) eq "ARRAY" and not @$barcode;
739 my $e = new_editor(authtoken => $auth);
740 my $results = $e->search_asset_copy([
741 {"barcode" => $barcode},
744 "flesh_fields" => {"acp" => [qw/call_number location/]}
748 if (ref($results) eq "ARRAY") {
750 return $results->[0] unless ref $barcode;
751 return +{ map { $_->barcode => $_ } @$results };
753 return $e->die_event;
756 __PACKAGE__->register_method(
757 method => "get_copy_fleshed_just_right",
758 api_name => "open-ils.booking.asset.get_copy_fleshed_just_right",
762 {type => "string", desc => "Authentication token"},
763 {type => "mixed", desc => "One barcode or an array of them"},
766 "A copy, or a hash of copies keyed by barcode if an array of " .
773 sub best_bresv_candidate {
774 my ($e, $id_list) = @_;
776 # This will almost always be the case.
777 return $id_list->[0] if @$id_list == 1;
780 my $this_ou = $e->requestor->ws_ou;
781 my $results = $e->json_query({
782 "select" => {"brsrc" => ["pickup_lib"], "bresv" => ["id"]},
785 "brsrc" => {"field" => "id", "fkey" => "current_resource"}
789 {"+bresv" => {"id" => $id_list}}
793 foreach (@$results) {
794 push @here, $_->{"id"} if $_->{"pickup_lib"} == $this_ou;
798 return pop @here if @here == 1;
799 return (sort @here)[0];
801 return (sort @$id_list)[0];
806 sub capture_resource_for_reservation {
807 my ($self, $client, $auth, $barcode) = @_;
809 my $e = new_editor(xact => 1, authtoken => $auth);
810 return $e->die_event unless $e->checkauth;
811 return $e->die_event unless $e->allowed("CAPTURE_RESERVATION");
813 my $uncaptured = get_uncaptured_bresv_for_brsrc(
814 $e, {"barcode" => $barcode}
818 if (keys %$uncaptured) {
819 # Note this will only capture one reservation at a time, even in
820 # cases with overbooking (multiple "soonest" bresv's on a resource).
821 my $key = (sort(keys %$uncaptured))[0];
822 return capture_reservation(
823 $self, $client, $auth, best_bresv_candidate($e, $uncaptured->{$key})
826 return new OpenILS::Event(
827 "RESERVATION_NOT_FOUND",
828 desc => "No capturable reservation found pertaining " .
829 "to a resource with barcode $barcode",
830 payload => {fail_cause => 'no-reservation', captured => 0}
834 __PACKAGE__->register_method(
835 method => "capture_resource_for_reservation",
836 api_name => "open-ils.booking.resources.capture_for_reservation",
840 {type => "string", desc => "Authentication token"},
841 {type => "string", desc => "Barcode of booked & targeted resource"},
842 {type => "int", desc => "Pickup library (default to client ws_ou)"},
844 return => { desc => "An OpenILS event describing the capture outcome" }
849 sub capture_reservation {
850 my ($self, $client, $auth, $res_id) = @_;
852 my $e = new_editor(xact => 1, authtoken => $auth);
853 return $e->event unless $e->checkauth;
854 return $e->event unless $e->allowed('CAPTURE_RESERVATION');
855 my $here = $e->requestor->ws_ou;
857 my $reservation = $e->retrieve_booking_reservation([
860 flesh_fields => {"bresv" => ["usr"], "au" => ["card"]}
863 return OpenILS::Event->new('RESERVATION_NOT_FOUND') unless $reservation;
865 return OpenILS::Event->new('RESERVATION_CAPTURE_FAILED', payload => { captured => 0, fail_cause => 'no-resource' })
866 if (!$reservation->current_resource); # no resource
868 return OpenILS::Event->new('RESERVATION_CAPTURE_FAILED', payload => { captured => 0, fail_cause => 'cancelled' })
869 if ($reservation->cancel_time); # canceled
871 my $resource = $e->retrieve_booking_resource( $reservation->current_resource );
872 my $type = $e->retrieve_booking_resource_type( $resource->type );
874 $reservation->capture_staff( $e->requestor->id );
875 $reservation->capture_time( 'now' );
877 my $reservation_id = undef;
878 return $e->event unless ( $e->update_booking_reservation( $reservation ) and $reservation_id = $e->data );
880 $reservation->id($reservation_id);
882 my $ret = { captured => 1, reservation => $reservation };
884 if ($here != $reservation->pickup_lib) {
885 return OpenILS::Event->new('RESERVATION_CAPTURE_FAILED', payload => { captured => 0, fail_cause => 'not-transferable' })
886 if (!$U->is_true($type->transferable)); # non-transferable resource
888 # need to transit the item ... is it already in transit?
889 my $transit = $e->search_action_reservation_transit_copy( { reservation => $res_id, dest_recv_time => undef } )->[0];
891 if (!$transit) { # not yet in transit
892 $transit = new Fieldmapper::action::reservation_transit_copy;
894 $transit->target_copy($resource->id);
895 $transit->copy_status(15);
896 $transit->source_send_time('now');
897 $transit->source($here);
898 $transit->dest($reservation->pickup_lib);
900 $e->create_action_reservation_transit_copy( $transit );
902 if ($U->is_true($type->catalog_item)) {
903 my $copy = $e->search_asset_copy( { barcode => $resource->barcode, deleted => 'f' } )->[0];
906 return new OpenILS::Event(
907 "OPEN_CIRCULATION_EXISTS",
908 payload => { captured => 0, copy => $copy }
909 ) if $copy->status == 1;
911 $e->update_asset_copy( $copy );
912 $$ret{catalog_item} = $copy; # $e->data is just id (int)
917 $$ret{transit} = $transit;
918 } elsif ($U->is_true($type->catalog_item)) {
919 my $copy = $e->search_asset_copy( { barcode => $resource->barcode, deleted => 'f' } )->[0];
922 return OpenILS::Event->new('OPEN_CIRCULATION_EXISTS', payload => { captured => 0, copy => $copy }) if ($copy->status == 1);
924 $e->update_asset_copy( $copy );
925 $$ret{catalog_item} = $copy; # $e->data is just id (int)
931 return OpenILS::Event->new('SUCCESS', payload => $ret);
933 __PACKAGE__->register_method(
934 method => "capture_reservation",
935 api_name => "open-ils.booking.reservations.capture",
939 {type => 'string', desc => 'Authentication token'},
940 {type => 'mixed', desc =>
941 'Reservation ID (number) or array of resource barcodes'}
943 return => { desc => "An OpenILS Event object describing the outcome of the capture, with relevant payload." },
948 sub cancel_reservation {
949 my ($self, $client, $auth, $id_list) = @_;
951 my $e = new_editor(xact => 1, authtoken => $auth);
952 return $e->die_event unless $e->checkauth;
953 # Should the following permission really be checked as relates to each
954 # individual reservation's request_lib? Hrmm...
955 return $e->die_event unless $e->allowed("ADMIN_BOOKING_RESERVATION");
957 my $bresv_list = $e->search_booking_reservation([
959 {"flesh" => 1, "flesh_fields" => {"bresv" => [
960 "current_resource", "target_resource_type"
963 return $e->die_event if not $bresv_list;
965 my $circ = OpenSRF::AppSession->connect("open-ils.circ") or
966 return $e->die_event;
968 foreach my $bresv (@$bresv_list) {
970 $bresv->target_resource_type->catalog_item == "t" &&
971 $bresv->current_resource
973 $logger->info("result of no-op checkin (upon cxl bresv) is " .
975 "open-ils.circ.checkin", $auth,
976 {"barcode" => $bresv->current_resource->barcode,
978 )->gather(1)->{"textcode"});
980 $bresv->cancel_time("now");
981 $e->update_booking_reservation($bresv) or do {
983 return $e->die_event;
986 push @results, $bresv->id;
994 __PACKAGE__->register_method(
995 method => "cancel_reservation",
996 api_name => "open-ils.booking.reservations.cancel",
1000 {type => "string", desc => "Authentication token"},
1001 {type => "array", desc => "List of reservation IDs"}
1003 return => { desc => "A list of canceled reservation IDs" },
1008 sub get_captured_reservations {
1009 my ($self, $client, $auth, $barcode, $which) = @_;
1011 my $e = new_editor(xact => 1, authtoken => $auth);
1012 return $e->die_event unless $e->checkauth;
1013 return $e->die_event unless $e->allowed("VIEW_USER");
1014 return $e->die_event unless $e->allowed("ADMIN_BOOKING_RESERVATION");
1016 # fetch the patron for our uses in any case...
1017 my $patron = $U->fetch_user_by_barcode($barcode);
1018 return $patron if ref($patron) eq "HASH" and exists $patron->{"ilsevent"};
1022 "flesh_fields" => {"bresv" => [
1023 qw/target_resource_type current_resource/
1032 return $e->search_booking_reservation([
1034 "usr" => $patron->id,
1035 "capture_time" => {"!=" => undef},
1036 "pickup_time" => undef,
1037 "cancel_time" => undef
1040 ]) or $e->die_event;
1043 return $e->search_booking_reservation([
1045 "usr" => $patron->id,
1046 "pickup_time" => {"!=" => undef},
1047 "return_time" => undef,
1048 "cancel_time" => undef
1051 ]) or $e->die_event;
1054 return $e->search_booking_reservation([
1056 "usr" => $patron->id,
1057 "return_time" => {">=" => naive_start_of_day()},
1058 "cancel_time" => undef
1061 ]) or $e->die_event;
1067 my $f = $dispatch->{$_};
1070 return $r if (ref($r) eq "HASH" and exists $r->{"ilsevent"});
1077 __PACKAGE__->register_method(
1078 method => "get_captured_reservations",
1079 api_name => "open-ils.booking.reservations.get_captured",
1083 {type => "string", desc => "Authentication token"},
1084 {type => "string", desc => "Patron barcode"},
1085 {type => "array", desc => "Parts wanted (patron, ready, out, in?)"}
1087 return => { desc => "A hash of parts." } # XXX describe more fully
1092 sub get_bresv_by_returnable_resource_barcode {
1093 my ($self, $client, $auth, $barcode) = @_;
1095 my $e = new_editor(xact => 1, authtoken => $auth);
1096 return $e->die_event unless $e->checkauth;
1097 return $e->die_event unless $e->allowed("VIEW_USER");
1098 return $e->die_event unless $e->allowed("ADMIN_BOOKING_RESERVATION");
1100 my $rows = $e->json_query({
1101 "select" => {"bresv" => ["id"]},
1104 "brsrc" => {"field" => "id", "fkey" => "current_resource"}
1108 "+brsrc" => {"barcode" => $barcode},
1110 "pickup_time" => {"!=" => undef},
1111 "cancel_time" => undef,
1112 "return_time" => undef
1115 }) or return $e->die_event;
1120 # More than one result might be possible, but we don't want to return
1121 # more than one at this time.
1122 my $id = $rows->[0]->{"id"};
1123 return $e->retrieve_booking_reservation([
1127 "bresv" => [qw/usr target_resource_type current_resource/],
1131 ]) or $e->die_event;
1135 __PACKAGE__->register_method(
1136 method => "get_bresv_by_returnable_resource_barcode",
1137 api_name => "open-ils.booking.reservations.by_returnable_resource_barcode",
1141 {type => "string", desc => "Authentication token"},
1142 {type => "string", desc => "Resource barcode"},
1144 return => { desc => "A fleshed bresv or an ilsevent on error" }