]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Booking.pm
Merge branch 'master' of git.evergreen-ils.org:Evergreen into template-toolkit-opac...
[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 OpenSRF::Utils 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 __PACKAGE__->register_method(
459     method   => "resource_list_by_attrs",
460     api_name => "open-ils.booking.resources.filtered_id_list",
461     argc     => 2,
462     signature=> {
463         params => [
464             {type => 'string', desc => 'Authentication token (unused for now,' .
465                ' but at least pass undef here)'},
466             {type => 'object', desc => 'Filter object: see notes for details'},
467         ],
468         return => { desc => "An array of brsrc ids matching the requested filters." },
469     },
470     notes    => <<'NOTES'
471
472 The filter object parameter can contain the following keys:
473  * type             => The id of a booking resource type (brt)
474  * attribute_values => The ids of booking resource type attribute values that the resource must have assigned to it (brav)
475  * available        => Either:
476                         A timestamp during which the resources are not reserved.  If the resource is overbookable, this is ignored.
477                         A range of two timestamps which do not overlap any reservations for the resources.  If the resource is overbookable, this is ignored.
478  * booked           => Either:
479                         A timestamp during which the resources are reserved.
480                         A range of two timestamps which overlap a reservation of the resources.
481
482 Note that at least one of 'type' or 'attribute_values' is required.
483
484 NOTES
485 );
486
487
488 sub reservation_list_by_filters {
489     my $self = shift;
490     my $client = shift;
491     my $auth = shift;
492     my $filters = shift;
493     my $whole_obj = shift;
494
495     return undef unless ($filters->{user} || $filters->{user_barcode} || $filters->{resource} || $filters->{type} || $filters->{attribute_values});
496
497     my $e = new_editor(authtoken=>$auth);
498     return $e->event unless $e->checkauth;
499     return $e->event unless $e->allowed('VIEW_TRANSACTION');
500
501     my $query = {
502         'select'   => { bresv => [ 'id', 'start_time' ] },
503         'from'     => { bresv => {} },
504         'where'    => {},
505         'order_by' => [{ class => bresv => field => start_time => direction => 'asc' }],
506         'distinct' => 1
507     };
508
509     if ($filters->{fields}) {
510         $query->{where} = $filters->{fields};
511     }
512
513
514     if ($filters->{user}) {
515         $query->{where}->{usr} = $filters->{user};
516     }
517     elsif ($filters->{user_barcode}) {  # just one of user and user_barcode
518         my $usr = $U->fetch_user_by_barcode($filters->{user_barcode});
519         return $usr if ref($usr) eq 'HASH' and exists($usr->{"ilsevent"});
520         $query->{where}->{usr} = $usr->id;
521     }
522
523
524     if ($filters->{type}) {
525         $query->{where}->{target_resource_type} = $filters->{type};
526     }
527
528     $query->{where}->{"-and"} = [];
529     if ($filters->{resource}) {
530 #       $query->{where}->{target_resource} = $filters->{resource};
531         push @{$query->{where}->{"-and"}}, {
532             "-or" => {
533                 "target_resource" => $filters->{resource},
534                 "current_resource" => $filters->{resource}
535             }
536         };
537     }
538
539     if ($filters->{attribute_values}) {
540
541         $query->{from}->{bresv}->{bravm} = { field => 'reservation' };
542
543         $filters->{attribute_values} = [$filters->{attribute_values}]
544             if (!ref($filters->{attribute_values}));
545
546         $query->{having}->{'+bravm'}->{attr_value}->{'@>'} = {
547             transform => 'array_accum',
548             value => '$_' . $$ . '${' .
549                 join(',', @{$filters->{attribute_values}}) .
550                 '}$_' . $$ . '$'
551         };
552     }
553
554     if ($filters->{search_start} || $filters->{search_end}) {
555         my $or = {};
556
557         $or->{start_time} =
558             {'between' => [ $filters->{search_start}, $filters->{search_end}]}
559                 if $filters->{search_start};
560
561         $or->{end_time} =
562             {'between' =>[$filters->{search_start}, $filters->{search_end}]}
563                 if $filters->{search_end};
564
565         push @{$query->{where}->{"-and"}}, {"-or" => $or};
566     }
567
568     if (not scalar @{$query->{"where"}->{"-and"}}) {
569         delete $query->{"where"}->{"-and"};
570     }
571
572     my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
573     my $ids = [ map { $_->{id} } @{
574         $cstore->request(
575             'open-ils.cstore.json_query.atomic', $query
576         )->gather(1)
577     } ];
578     $cstore->disconnect;
579
580     if (not $whole_obj or @$ids < 1) {
581         $e->disconnect;
582         return $ids;
583     }
584
585     my $bresv_list = $e->search_booking_reservation([
586         {"id" => $ids},
587         {"flesh" => 1,
588             "flesh_fields" => {
589                 "bresv" =>
590                     [qw/target_resource current_resource target_resource_type/]
591             }
592         }]
593     );
594     $e->disconnect;
595     return $bresv_list ? $bresv_list : [];
596 }
597 __PACKAGE__->register_method(
598     method   => "reservation_list_by_filters",
599     api_name => "open-ils.booking.reservations.filtered_id_list",
600     argc     => 3,
601     signature=> {
602         params => [
603             {type => 'string', desc => 'Authentication token'},
604             {type => "object", desc => "Filter object: see notes for details"},
605             {type => "bool", desc => "Return whole object instead of ID? (default false)"}
606         ],
607         return => { desc => "An array of bresv ids matching the requested filters." },
608     },
609     notes    => <<'NOTES'
610
611 The filter object parameter can contain the following keys:
612  * user             => The id of a user that has requested a bookable item -- filters on bresv.usr
613  * barcode          => The barcode of a user that has requested a bookable item
614  * type             => The id of a booking resource type (brt) -- filters on bresv.target_resource_type
615  * resource         => The id of a booking resource (brsrc) -- filters on bresv.target_resource
616  * attribute_values => The ids of booking resource type attribute values that the resource must have assigned to it (brav)
617  * search_start     => If search_end is not specified, booking interval (start_time to end_time) must contain this timestamp.
618  * search_end       => If search_start is not specified, booking interval (start_time to end_time) must contain this timestamp.
619  * fields           => An object containing any combination of bresv search filters in standard cstore/pcrud search format.
620
621 Note that at least one of 'user', 'type', 'resource' or 'attribute_values' is required.  If both search_start and search_end are specified,
622 then the result includes any reservations that overlap with that time range.  Any filter fields supplied in 'fields' are overridden
623 by the top-level filters ('user', 'type', 'resource').
624
625 NOTES
626 );
627
628
629 sub naive_ts_string {strftime("%F %T", localtime($_[0] || time));}
630 sub naive_start_of_day {strftime("%F", localtime($_[0] || time))." 00:00:00";}
631
632 # Return a map of bresv or an ilsevent on failure.
633 sub get_uncaptured_bresv_for_brsrc {
634     my ($e, $o) = @_; # o's keys (all optional): owning_lib, barcode, range
635
636     my $from_clause = {
637         "bresv" => {
638             "brsrc" => {"field" => "id", "fkey" => "current_resource"}
639         }
640     };
641
642     my $query = {
643         "select" => {
644             "bresv" => [
645                 "current_resource",
646                 {
647                     "column" => "start_time",
648                     "transform" => "min",
649                     "aggregate" => 1
650                 }
651             ]
652         },
653         "from" => $from_clause,
654         "where" => {
655             "-and" => [
656                 {"current_resource" => {"!=" => undef}},
657                 {"capture_time" => undef},
658                 {"cancel_time" => undef},
659                 {"return_time" => undef},
660                 {"pickup_time" => undef}
661             ]
662         }
663     };
664     if ($o->{"owning_lib"}) {
665         push @{$query->{"where"}->{"-and"}},
666             {"+brsrc" => {"owner" => $o->{"owning_lib"}}};
667     }
668     if ($o->{"range"}) {
669         push @{$query->{"where"}->{"-and"}},
670             json_query_ranges_overlap(
671                 $o->{"range"}->[0], $o->{"range"}->[1],
672                 "start_time", "end_time"
673             );
674     }
675     if ($o->{"barcode"}) {
676         push @{$query->{"where"}->{"-and"}},
677             {"+brsrc" => {"barcode" => $o->{"barcode"}}};
678     }
679
680     my $rows = $e->json_query($query);
681     my $current_resource_bresv_map = {};
682     if (@$rows) {
683         my $id_query = {
684             "select" => {"bresv" => ["id"]},
685             "from" => $from_clause,
686             "where" => {
687                 "-and" => [
688                     {"current_resource" => "PLACEHOLDER"},
689                     {"start_time" => "PLACEHOLDER"},
690                     {"capture_time" => undef},
691                     {"cancel_time" => undef},
692                     {"return_time" => undef},
693                     {"pickup_time" => undef}
694                 ]
695             }
696         };
697         if ($o->{"owning_lib"}) {
698             push @{$id_query->{"where"}->{"-and"}},
699                 {"+brsrc" => {"owner" => $o->{"owning_lib"}}};
700         }
701
702         foreach (@$rows) {
703             $id_query->{"where"}->{"-and"}->[0]->{"current_resource"} =
704                 $_->{"current_resource"};
705             $id_query->{"where"}->{"-and"}->[1]->{"start_time"} =
706                 $_->{"start_time"};
707
708             my $results = $e->json_query($id_query);
709             if ($results && @$results) {
710                 $current_resource_bresv_map->{$_->{"current_resource"}} =
711                     [map { $_->{"id"} } @$results];
712             }
713         }
714     }
715     return $current_resource_bresv_map;
716 }
717
718 sub get_pull_list {
719     my ($self, $client, $auth, $range, $interval_secs, $owning_lib) = @_;
720
721     my $e = new_editor(xact => 1, authtoken => $auth);
722     return $e->die_event unless $e->checkauth;
723     return $e->die_event unless $e->allowed("RETRIEVE_RESERVATION_PULL_LIST");
724     return $e->die_event unless (
725         ref($range) eq "ARRAY" or
726         ($interval_secs = int($interval_secs)) > 0
727     );
728
729     $owning_lib = $e->requestor->ws_ou if not $owning_lib;
730     $range = [ naive_ts_string(time), naive_ts_string(time + $interval_secs) ]
731         if not $range;
732
733     my $uncaptured = get_uncaptured_bresv_for_brsrc(
734         $e, {"range" => $range, "owning_lib" => $owning_lib}
735     );
736
737     if (keys(%$uncaptured)) {
738         my @all_bresv_ids = map { @{$_} } values %$uncaptured;
739         my %bresv_lookup = (
740             map { $_->id => $_ } @{
741                 $e->search_booking_reservation([{"id" => [@all_bresv_ids]}, {
742                     flesh => 1,
743                     flesh_fields => { bresv => [
744                         "usr", "target_resource_type", "current_resource"
745                     ]}
746                 }])
747             }
748         );
749         $e->disconnect;
750         return [ map {
751             my $key = $_;
752             my $one = $bresv_lookup{$uncaptured->{$key}->[0]};
753             my $result = {
754                 "current_resource" => $one->current_resource,
755                 "target_resource_type" => $one->target_resource_type,
756                 "reservations" => [
757                     map { $bresv_lookup{$_} } @{$uncaptured->{$key}}
758                 ]
759             };
760             foreach (@{$result->{"reservations"}}) {    # deflesh
761                 $_->current_resource($_->current_resource->id);
762                 $_->target_resource_type($_->target_resource_type->id);
763             }
764             $result;
765         } keys %$uncaptured ];
766     } else {
767         $e->disconnect;
768         return [];
769     }
770 }
771 __PACKAGE__->register_method(
772     method   => "get_pull_list",
773     api_name => "open-ils.booking.reservations.get_pull_list",
774     argc     => 4,
775     signature=> {
776         params => [
777             {type => "string", desc => "Authentication token"},
778             {type => "array", desc =>
779                 "range: Date/time range for reservations (opt)"},
780             {type => "int", desc =>
781                 "interval: Seconds from now (instead of range)"},
782             {type => "number", desc => "(Optional) Owning library"}
783         ],
784         return => { desc => "An array of hashes, each containing key/value " .
785             "pairs describing resource, resource type, and a list of " .
786             "reservations that claim the given resource." }
787     }
788 );
789
790
791 sub could_capture {
792     my ($self, $client, $auth, $barcode) = @_;
793
794     my $e = new_editor("authtoken" => $auth);
795     return $e->die_event unless $e->checkauth;
796     return $e->die_event unless $e->allowed("COPY_CHECKIN");
797
798     my $dt_parser = new DateTime::Format::ISO8601;
799     my $now = now DateTime; # sic
800     my $res = get_uncaptured_bresv_for_brsrc($e, {"barcode" => $barcode});
801
802     if ($res and keys %$res) {
803         my $id;
804         while ((undef, $id) = each %$res) {
805             my $bresv = $e->retrieve_booking_reservation([
806                 $id, {
807                     "flesh" => 1, "flesh_fields" => {
808                         "bresv" => [qw(
809                             usr target_resource_type
810                             target_resource current_resource
811                         )]
812                     }
813                 }
814             ]);
815             my $elbow_room = interval_to_seconds(
816                 $bresv->target_resource_type->elbow_room ||
817                 $U->ou_ancestor_setting_value(
818                     $bresv->pickup_lib,
819                     "circ.booking_reservation.default_elbow_room"
820                 ) ||
821                 "0 seconds"
822             );
823
824             unless ($elbow_room) {
825                 $client->respond($bresv);
826             } else {
827                 my $start_time = $dt_parser->parse_datetime(
828                     clense_ISO8601($bresv->start_time)
829                 );
830
831                 if ($now >= $start_time->subtract("seconds" => $elbow_room)) {
832                     $client->respond($bresv);
833                 } else {
834                     $logger->info(
835                         "not within elbow room: $elbow_room, " .
836                         "else would have returned bresv " . $bresv->id
837                     );
838                 }
839             }
840         }
841     }
842     $e->disconnect;
843     undef;
844 }
845 __PACKAGE__->register_method(
846     method   => "could_capture",
847     api_name => "open-ils.booking.reservations.could_capture",
848     argc     => 2,
849     streaming=> 1,
850     signature=> {
851         params => [
852             {type => "string", desc => "Authentication token"},
853             {type => "string", desc => "Resource barcode"}
854         ],
855         return => {desc => "One or zero reservations; event on error."}
856     }
857 );
858
859
860 sub get_copy_fleshed_just_right {
861     my ($self, $client, $auth, $barcode) = @_;
862
863     return undef if not defined $barcode;
864     return {} if ref($barcode) eq "ARRAY" and not @$barcode;
865
866     my $e = new_editor(authtoken => $auth);
867     my $results = $e->search_asset_copy([
868         {"barcode" => $barcode},
869         {
870             "flesh" => 1,
871             "flesh_fields" => {"acp" => [qw/call_number location/]}
872         }
873     ]);
874
875     if (ref($results) eq "ARRAY") {
876         $e->disconnect;
877         return $results->[0] unless ref $barcode;
878         return +{ map { $_->barcode => $_ } @$results };
879     } else {
880         return $e->die_event;
881     }
882 }
883 __PACKAGE__->register_method(
884     method   => "get_copy_fleshed_just_right",
885     api_name => "open-ils.booking.asset.get_copy_fleshed_just_right",
886     argc     => 2,
887     signature=> {
888         params => [
889             {type => "string", desc => "Authentication token"},
890             {type => "mixed", desc => "One barcode or an array of them"},
891         ],
892         return => { desc =>
893             "A copy, or a hash of copies keyed by barcode if an array of " .
894             "barcodes was given"
895         }
896     }
897 );
898
899
900 sub best_bresv_candidate {
901     my ($e, $id_list) = @_;
902
903     # This will almost always be the case.
904     if (@$id_list == 1) {
905         $logger->info("best_bresv_candidate (only) " . $id_list->[0]);
906         return $id_list->[0];
907     }
908
909     my @here = ();
910     my $this_ou = $e->requestor->ws_ou;
911     my $results = $e->json_query({
912         "select" => {"brsrc" => ["pickup_lib"], "bresv" => ["id"]},
913         "from" => {
914             "bresv" => {
915                 "brsrc" => {"field" => "id", "fkey" => "current_resource"}
916             }
917         },
918         "where" => {
919             {"+bresv" => {"id" => $id_list}}
920         }
921     });
922
923     foreach (@$results) {
924         push @here, $_->{"id"} if $_->{"pickup_lib"} == $this_ou;
925     }
926
927     my $result;
928     if (@here > 0) {
929         $result = @here == 1 ? pop @here : (sort @here)[0];
930     } else {
931         $result = (sort @$id_list)[0];
932     }
933     $logger->info(
934         "best_bresv_candidate from " . join(",", @$id_list) . ": $result"
935     );
936     return $result;
937 }
938
939
940 sub capture_resource_for_reservation {
941     my ($self, $client, $auth, $barcode, $no_update_copy) = @_;
942
943     my $e = new_editor(authtoken => $auth);
944     return $e->die_event unless $e->checkauth;
945     return $e->die_event unless $e->allowed("COPY_CHECKIN");
946
947     my $uncaptured = get_uncaptured_bresv_for_brsrc(
948         $e, {"barcode" => $barcode}
949     );
950
951     if (keys %$uncaptured) {
952         # Note this will only capture one reservation at a time, even in
953         # cases with overbooking (multiple "soonest" bresv's on a resource).
954         my $bresv = best_bresv_candidate(
955             $e, $uncaptured->{
956                 (sort(keys %$uncaptured))[0]
957             }
958         );
959         $e->disconnect;
960         return capture_reservation(
961             $self, $client, $auth, $bresv, $no_update_copy
962         );
963     } else {
964         return new OpenILS::Event(
965             "RESERVATION_NOT_FOUND",
966             "desc" => "No capturable reservation found pertaining " .
967                 "to a resource with barcode $barcode",
968             "payload" => {"fail_cause" => "no-reservation", "captured" => 0}
969         );
970     }
971 }
972 __PACKAGE__->register_method(
973     method   => "capture_resource_for_reservation",
974     api_name => "open-ils.booking.resources.capture_for_reservation",
975     argc     => 3,
976     signature=> {
977         params => [
978             {type => "string", desc => "Authentication token"},
979             {type => "string", desc => "Barcode of booked & targeted resource"},
980             {type => "number", desc => "(optional) 1 to not update copy"}
981         ],
982         return => { desc => "An OpenILS event describing the capture outcome" }
983     }
984 );
985
986
987 sub capture_reservation {
988     my ($self, $client, $auth, $res_id, $no_update_copy) = @_;
989
990     my $e = new_editor("xact" => 1, "authtoken" => $auth);
991     return $e->die_event unless $e->checkauth;
992     return $e->die_event unless $e->allowed("COPY_CHECKIN");
993     my $here = $e->requestor->ws_ou;
994
995     my $reservation = $e->retrieve_booking_reservation([
996         $res_id, {
997             "flesh" => 2, "flesh_fields" => {
998                 "bresv" => [qw/usr current_resource type/],
999                 "au" => ["card"],
1000                 "brsrc" => ["type"]
1001             }
1002         }
1003     ]);
1004
1005     return new OpenILS::Event("RESERVATION_NOT_FOUND") unless $reservation;
1006     return new OpenILS::Event(
1007         "RESERVATION_CAPTURE_FAILED",
1008         payload => {"captured" => 0, "fail_cause" => "no-resource"}
1009     ) unless $reservation->current_resource;
1010
1011     return new OpenILS::Event(
1012         "RESERVATION_CAPTURE_FAILED",
1013         "payload" => {"captured" => 0, "fail_cause" => "cancelled"}
1014     ) if $reservation->cancel_time;
1015
1016     $reservation->capture_staff($e->requestor->id);
1017     $reservation->capture_time("now");
1018
1019     $e->update_booking_reservation($reservation) or return $e->die_event;
1020
1021     my $ret = {"captured" => 1, "reservation" => $reservation};
1022
1023     my $search_acp_like_this = [
1024         {
1025             "barcode" => $reservation->current_resource->barcode,
1026             "deleted" => "f"
1027         },
1028         {"flesh" => 1, "flesh_fields" => {"acp" => ["call_number"]}}
1029     ];
1030
1031     if ($here != $reservation->pickup_lib) {
1032         $logger->info("resource isn't at the reservation's pickup lib...");
1033         return new OpenILS::Event(
1034             "RESERVATION_CAPTURE_FAILED",
1035             "payload" => {"captured" => 0, "fail_cause" => "not-transferable"}
1036         ) unless $U->is_true(
1037             $reservation->current_resource->type->transferable
1038         );
1039
1040         # need to transit the item ... is it already in transit?
1041         my $transit = $e->search_action_reservation_transit_copy(
1042             {"reservation" => $res_id, "dest_recv_time" => undef}
1043         )->[0];
1044
1045         if (!$transit) { # not yet in transit
1046             $transit = new Fieldmapper::action::reservation_transit_copy;
1047
1048             $transit->reservation($reservation->id);
1049             $transit->target_copy($reservation->current_resource->id);
1050             $transit->copy_status(15);
1051             $transit->source_send_time("now");
1052             $transit->source($here);
1053             $transit->dest($reservation->pickup_lib);
1054
1055             $e->create_action_reservation_transit_copy($transit);
1056
1057             if ($U->is_true(
1058                 $reservation->current_resource->type->catalog_item
1059             )) {
1060                 my $copy = $e->search_asset_copy($search_acp_like_this)->[0];
1061
1062                 if ($copy) {
1063                     return new OpenILS::Event(
1064                         "OPEN_CIRCULATION_EXISTS",
1065                         "payload" => {"captured" => 0, "copy" => $copy}
1066                     ) if $copy->status == 1 and not $no_update_copy;
1067
1068                     $ret->{"mvr"} = get_mvr($copy->call_number->record);
1069                     if ($no_update_copy) {
1070                         $ret->{"new_copy_status"} = 6;
1071                     } else {
1072                         $copy->status(6);
1073                         $e->update_asset_copy($copy) or return $e->die_event;
1074                     }
1075                 }
1076             }
1077         }
1078
1079         $ret->{"transit"} = $transit;
1080     } elsif ($U->is_true($reservation->current_resource->type->catalog_item)) {
1081         $logger->info("resource is a catalog item...");
1082         my $copy = $e->search_asset_copy($search_acp_like_this)->[0];
1083
1084         if ($copy) {
1085             return new OpenILS::Event(
1086                 "OPEN_CIRCULATION_EXISTS",
1087                 "payload" => {"captured" => 0, "copy" => $copy}
1088             ) if $copy->status == 1 and not $no_update_copy;
1089
1090             $ret->{"mvr"} = get_mvr($copy->call_number->record);
1091             if ($no_update_copy) {
1092                 $ret->{"new_copy_status"} = 15;
1093             } else {
1094                 $copy->status(15);
1095                 $e->update_asset_copy($copy) or return $e->die_event;
1096             }
1097         }
1098     }
1099
1100     $e->commit or return $e->die_event;
1101
1102     # create action trigger event to notify that reservation is available
1103     if ($reservation->email_notify) {
1104         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1105         $ses->request('open-ils.trigger.event.autocreate', 'reservation.available', $reservation, $reservation->pickup_lib);
1106     }
1107
1108     # XXX I'm not sure whether these last two elements of the payload
1109     # actually get used anywhere.
1110     $ret->{"resource"} = $reservation->current_resource;
1111     $ret->{"type"} = $reservation->current_resource->type;
1112     return new OpenILS::Event("SUCCESS", "payload" => $ret);
1113 }
1114 __PACKAGE__->register_method(
1115     method   => "capture_reservation",
1116     api_name => "open-ils.booking.reservations.capture",
1117     argc     => 2,
1118     signature=> {
1119         params => [
1120             {type => 'string', desc => 'Authentication token'},
1121             {type => 'mixed', desc =>
1122                 'Reservation ID (number) or array of resource barcodes'}
1123         ],
1124         return => { desc => "An OpenILS Event object describing the outcome of the capture, with relevant payload." },
1125     }
1126 );
1127
1128
1129 sub cancel_reservation {
1130     my ($self, $client, $auth, $id_list) = @_;
1131
1132     my $e = new_editor(xact => 1, authtoken => $auth);
1133     return $e->die_event unless $e->checkauth;
1134     # Should the following permission really be checked as relates to each
1135     # individual reservation's request_lib?  Hrmm...
1136     return $e->die_event unless $e->allowed("ADMIN_BOOKING_RESERVATION");
1137
1138     my $bresv_list = $e->search_booking_reservation([
1139         {"id" => $id_list},
1140         {"flesh" => 1, "flesh_fields" => {"bresv" => [
1141             "current_resource", "target_resource_type"
1142         ]}}
1143     ]);
1144     return $e->die_event if not $bresv_list;
1145
1146     my @results = ();
1147     my $circ = OpenSRF::AppSession->connect("open-ils.circ") or
1148         return $e->die_event;
1149     foreach my $bresv (@$bresv_list) {
1150         $bresv->cancel_time("now");
1151         $e->update_booking_reservation($bresv) or do {
1152             $circ->disconnect;
1153             return $e->die_event;
1154         };
1155         $e->xact_commit;
1156         $e->xact_begin;
1157
1158         if (
1159             $bresv->target_resource_type->catalog_item == "t" &&
1160             $bresv->current_resource
1161         ) {
1162             $logger->info("result of no-op checkin (upon cxl bresv) is " .
1163                 $circ->request(
1164                     "open-ils.circ.checkin", $auth,
1165                     {"barcode" => $bresv->current_resource->barcode,
1166                         "noop" => 1}
1167                 )->gather(1)->{"textcode"});
1168         }
1169         push @results, $bresv->id;
1170     }
1171
1172     $e->disconnect;
1173     $circ->disconnect;
1174
1175     return \@results;
1176 }
1177 __PACKAGE__->register_method(
1178     method   => "cancel_reservation",
1179     api_name => "open-ils.booking.reservations.cancel",
1180     argc     => 2,
1181     signature=> {
1182         params => [
1183             {type => "string", desc => "Authentication token"},
1184             {type => "array", desc => "List of reservation IDs"}
1185         ],
1186         return => { desc => "A list of canceled reservation IDs" },
1187     }
1188 );
1189
1190
1191 sub get_captured_reservations {
1192     my ($self, $client, $auth, $barcode, $which) = @_;
1193
1194     my $e = new_editor(xact => 1, authtoken => $auth);
1195     return $e->die_event unless $e->checkauth;
1196     return $e->die_event unless $e->allowed("VIEW_USER");
1197     return $e->die_event unless $e->allowed("ADMIN_BOOKING_RESERVATION");
1198
1199     # fetch the patron for our uses in any case...
1200     my $patron = $U->fetch_user_by_barcode($barcode);
1201     return $patron if ref($patron) eq "HASH" and exists $patron->{"ilsevent"};
1202
1203     my $bresv_flesh = {
1204         "flesh" => 1,
1205         "flesh_fields" => {"bresv" => [
1206             qw/target_resource_type current_resource/
1207         ]}
1208     };
1209
1210     my $dispatch = {
1211         "patron" => sub {
1212             return $patron;
1213         },
1214         "ready" => sub {
1215             return $e->search_booking_reservation([
1216                 {
1217                     "usr" => $patron->id,
1218                     "capture_time" => {"!=" => undef},
1219                     "pickup_time" => undef,
1220                     "start_time" => {">=" => naive_start_of_day()},
1221                     "cancel_time" => undef
1222                 },
1223                 $bresv_flesh
1224             ]) or $e->die_event;
1225         },
1226         "out" => sub {
1227             return $e->search_booking_reservation([
1228                 {
1229                     "usr" => $patron->id,
1230                     "pickup_time" => {"!=" => undef},
1231                     "return_time" => undef,
1232                     "cancel_time" => undef
1233                 },
1234                 $bresv_flesh
1235             ]) or $e->die_event;
1236         },
1237         "in" => sub {
1238             return $e->search_booking_reservation([
1239                 {
1240                     "usr" => $patron->id,
1241                     "return_time" => {">=" => naive_start_of_day()},
1242                     "cancel_time" => undef
1243                 },
1244                 $bresv_flesh
1245             ]) or $e->die_event;
1246         }
1247     };
1248
1249     my $result = {};
1250     foreach (@$which) {
1251         my $f = $dispatch->{$_};
1252         if ($f) {
1253             my $r = &{$f}();
1254             return $r if (ref($r) eq "HASH" and exists $r->{"ilsevent"});
1255             $result->{$_} = $r;
1256         }
1257     }
1258
1259     return $result;
1260 }
1261 __PACKAGE__->register_method(
1262     method   => "get_captured_reservations",
1263     api_name => "open-ils.booking.reservations.get_captured",
1264     argc     => 3,
1265     signature=> {
1266         params => [
1267             {type => "string", desc => "Authentication token"},
1268             {type => "string", desc => "Patron barcode"},
1269             {type => "array", desc => "Parts wanted (patron, ready, out, in?)"}
1270         ],
1271         return => { desc => "A hash of parts." } # XXX describe more fully
1272     }
1273 );
1274
1275
1276 sub get_bresv_by_returnable_resource_barcode {
1277     my ($self, $client, $auth, $barcode) = @_;
1278
1279     my $e = new_editor(xact => 1, authtoken => $auth);
1280     return $e->die_event unless $e->checkauth;
1281     return $e->die_event unless $e->allowed("VIEW_USER");
1282 #    return $e->die_event unless $e->allowed("ADMIN_BOOKING_RESERVATION");
1283
1284     my $rows = $e->json_query({
1285         "select" => {"bresv" => ["id"]},
1286         "from" => {
1287             "bresv" => {
1288                 "brsrc" => {"field" => "id", "fkey" => "current_resource"}
1289             }
1290         },
1291         "where" => {
1292             "+brsrc" => {"barcode" => $barcode},
1293             "-and" => {
1294                 "pickup_time" => {"!=" => undef},
1295                 "cancel_time" => undef,
1296                 "return_time" => undef
1297             }
1298         }
1299     }) or return $e->die_event;
1300
1301     if (@$rows < 1) {
1302         $e->rollback;
1303         return $rows;
1304     } else {
1305         # More than one result might be possible, but we don't want to return
1306         # more than one at this time.
1307         my $id = $rows->[0]->{"id"};
1308         my $resp =$e->retrieve_booking_reservation([
1309             $id, {
1310                 "flesh" => 2,
1311                 "flesh_fields" => {
1312                     "bresv" => [qw/usr target_resource_type current_resource/],
1313                     "au" => ["card"]
1314                 }
1315             }
1316         ]) or $e->die_event;
1317         $e->rollback;
1318         return $resp;
1319     }
1320 }
1321
1322 __PACKAGE__->register_method(
1323     method   => "get_bresv_by_returnable_resource_barcode",
1324     api_name => "open-ils.booking.reservations.by_returnable_resource_barcode",
1325     argc     => 2,
1326     signature=> {
1327         params => [
1328             {type => "string", desc => "Authentication token"},
1329             {type => "string", desc => "Resource barcode"},
1330         ],
1331         return => { desc => "A fleshed bresv or an ilsevent on error" }
1332     }
1333 );
1334
1335
1336 1;