1 package OpenILS::Application::Circ::Circulate;
2 use base 'OpenSRF::Application';
3 use strict; use warnings;
4 use OpenSRF::EX qw(:try);
6 use OpenSRF::Utils::Cache;
7 use OpenSRF::AppSession;
8 use Digest::MD5 qw(md5_hex);
9 use OpenILS::Utils::ScriptRunner;
10 use OpenILS::Application::AppUtils;
11 use OpenILS::Application::Circ::Holds;
12 use OpenILS::Application::Circ::Transit;
13 use OpenILS::Utils::PermitHold;
14 use OpenSRF::Utils::Logger qw(:logger);
16 use DateTime::Format::ISO8601;
17 use OpenSRF::Utils qw/:datetime/;
19 $Data::Dumper::Indent = 0;
20 my $apputils = "OpenILS::Application::AppUtils";
22 my $holdcode = "OpenILS::Application::Circ::Holds";
23 my $transcode = "OpenILS::Application::Circ::Transit";
25 my %scripts; # - circulation script filenames
26 my $script_libs; # - any additional script libraries
27 my %cache; # - db objects cache
28 my %contexts; # - Script runner contexts
29 my $cache_handle; # - memcache handle
31 sub PRECAT_FINE_LEVEL { return 2; }
32 sub PRECAT_LOAN_DURATION { return 2; }
34 my %RECORD_FROM_COPY_CACHE;
37 # for security, this is a process-defined and not
38 # a client-defined variable
41 # ------------------------------------------------------------------------------
42 # Load the circ script from the config
43 # ------------------------------------------------------------------------------
47 $cache_handle = OpenSRF::Utils::Cache->new('global');
48 my $conf = OpenSRF::Utils::SettingsClient->new;
49 my @pfx2 = ( "apps", "open-ils.circ","app_settings" );
50 my @pfx = ( @pfx2, "scripts" );
52 my $p = $conf->config_value( @pfx, 'circ_permit_patron' );
53 my $c = $conf->config_value( @pfx, 'circ_permit_copy' );
54 my $d = $conf->config_value( @pfx, 'circ_duration' );
55 my $f = $conf->config_value( @pfx, 'circ_recurring_fines' );
56 my $m = $conf->config_value( @pfx, 'circ_max_fines' );
57 my $pr = $conf->config_value( @pfx, 'circ_permit_renew' );
58 my $lb = $conf->config_value( @pfx2, 'script_path' );
60 $logger->error( "Missing circ script(s)" )
61 unless( $p and $c and $d and $f and $m and $pr );
63 $scripts{circ_permit_patron} = $p;
64 $scripts{circ_permit_copy} = $c;
65 $scripts{circ_duration} = $d;
66 $scripts{circ_recurring_fines}= $f;
67 $scripts{circ_max_fines} = $m;
68 $scripts{circ_permit_renew} = $pr;
70 $lb = [ $lb ] unless ref($lb);
73 $logger->debug("Loaded rules scripts for circ: " .
74 "circ permit patron: $p, circ permit copy: $c, ".
75 "circ duration :$d , circ recurring fines : $f, " .
76 "circ max fines : $m, circ renew permit : $pr");
80 # ------------------------------------------------------------------------------
81 # Loads the necessary circ objects and pushes them into the script environment
82 # Returns ( $data, $evt ). if $evt is defined, then an
83 # unexpedted event occurred and should be dealt with / returned to the caller
84 # ------------------------------------------------------------------------------
92 $evt = _ctx_add_patron_objects($ctx, %params);
93 return (undef,$evt) if $evt;
95 if(!$params{noncat}) {
96 if( $evt = _ctx_add_copy_objects($ctx, %params) ) {
97 $ctx->{precat} = 1 if($evt->{textcode} eq 'ASSET_COPY_NOT_FOUND')
99 $ctx->{precat} = 1 if ( $ctx->{copy}->call_number == -1 ); # special case copy
103 _doctor_patron_object($ctx) if $ctx->{patron};
104 _doctor_copy_object($ctx) if $ctx->{copy};
106 if(!$ctx->{no_runner}) {
107 _build_circ_script_runner($ctx);
108 _add_script_runner_methods($ctx);
114 sub _ctx_add_patron_objects {
115 my( $ctx, %params) = @_;
118 # - patron standings are now handled in the penalty server...
120 #if(!defined($cache{patron_standings})) {
121 # $cache{patron_standings} = $U->fetch_patron_standings();
123 #$ctx->{patron_standings} = $cache{patron_standings};
125 $cache{group_tree} = $U->fetch_permission_group_tree() unless $cache{group_tree};
126 $ctx->{group_tree} = $cache{group_tree};
128 $ctx->{patron_circ_summary} =
129 $U->fetch_patron_circ_summary($ctx->{patron}->id)
130 if $params{fetch_patron_circsummary};
136 sub _find_copy_by_attr {
141 my $copy = $params{copy} || undef;
146 $U->fetch_copy($params{copyid}) if $params{copyid};
147 return (undef,$evt) if $evt;
151 $U->fetch_copy_by_barcode( $params{barcode} ) if $params{barcode};
152 return (undef,$evt) if $evt;
155 return ( $copy, $evt );
158 sub _ctx_add_copy_objects {
159 my($ctx, %params) = @_;
164 $cache{copy_statuses} = $U->fetch_copy_statuses
165 if( $params{fetch_copy_statuses} and !defined($cache{copy_statuses}) );
167 $cache{copy_locations} = $U->fetch_copy_locations
168 if( $params{fetch_copy_locations} and !defined($cache{copy_locations}));
170 $ctx->{copy_statuses} = $cache{copy_statuses};
171 $ctx->{copy_locations} = $cache{copy_locations};
173 ($copy, $evt) = _find_copy_by_attr(%params);
176 if( $copy and !$ctx->{title} ) {
177 $logger->debug("Copy status: " . $copy->status);
179 my $r = $RECORD_FROM_COPY_CACHE{$copy->id};
180 ($r, $evt) = $U->fetch_record_by_copy( $copy->id ) unless $r;
182 $RECORD_FROM_COPY_CACHE{$copy->id} = $r;
185 $ctx->{copy} = $copy;
192 # ------------------------------------------------------------------------------
193 # Fleshes parts of the patron object
194 # ------------------------------------------------------------------------------
195 sub _doctor_copy_object {
198 my $copy = $ctx->{copy} || return undef;
200 $logger->debug("Doctoring copy object...");
202 # set the copy status to a status name
203 $copy->status( _get_copy_status( $copy, $ctx->{copy_statuses} ) );
205 # set the copy location to the location object
206 $copy->location( _get_copy_location( $copy, $ctx->{copy_locations} ) );
208 $copy->circ_lib( $U->fetch_org_unit($copy->circ_lib) );
212 # ------------------------------------------------------------------------------
213 # Fleshes parts of the patron object
214 # ------------------------------------------------------------------------------
215 sub _doctor_patron_object {
218 my $patron = $ctx->{patron} || return undef;
220 # push the standing object into the patron
221 # if(ref($ctx->{patron_standings})) {
222 # for my $s (@{$ctx->{patron_standings}}) {
223 # if( $s->id eq $ctx->{patron}->standing ) {
224 # $patron->standing($s);
225 # $logger->debug("Set patron standing to ". $s->value);
230 # set the patron ptofile to the profile name
231 $patron->profile( _get_patron_profile(
232 $patron, $ctx->{group_tree} ) ) if $ctx->{group_tree};
236 $U->fetch_org_unit( $patron->home_ou ) ) if $patron;
240 # recurse and find the patron profile name from the tree
241 # another option would be to grab the groups for the patron
242 # and cycle through those until the "profile" group has been found
243 sub _get_patron_profile {
244 my( $patron, $group_tree ) = @_;
245 return $group_tree if ($group_tree->id eq $patron->profile);
246 return undef unless ($group_tree->children);
248 for my $child (@{$group_tree->children}) {
249 my $ret = _get_patron_profile( $patron, $child );
255 sub _get_copy_status {
256 my( $copy, $cstatus ) = @_;
259 for my $status (@$cstatus) {
260 $s = $status if( $status->id eq $copy->status )
262 $logger->debug("Retrieving copy status: " . $s->name) if $s;
266 sub _get_copy_location {
267 my( $copy, $locations ) = @_;
270 for my $loc (@$locations) {
271 $l = $loc if $loc->id eq $copy->location;
273 $logger->debug("Retrieving copy location: " . $l->name ) if $l;
278 # ------------------------------------------------------------------------------
279 # Constructs and shoves data into the script environment
280 # ------------------------------------------------------------------------------
281 sub _build_circ_script_runner {
285 $logger->debug("Loading script environment for circulation");
288 if( $runner = $contexts{$ctx->{type}} ) {
289 $runner->refresh_context;
291 $runner = OpenILS::Utils::ScriptRunner->new;
292 $contexts{type} = $runner;
296 $logger->debug("Loading circ script lib path $_");
297 $runner->add_path( $_ );
300 # Note: inserting the number 0 into the script turns into the
301 # string "0", and thus evaluates to true in JS land
302 # inserting undef will insert "", which evaluates to false
304 $runner->insert( 'environment.patron', $ctx->{patron}, 1);
305 $runner->insert( 'environment.title', $ctx->{title}, 1);
306 $runner->insert( 'environment.copy', $ctx->{copy}, 1);
309 $runner->insert( 'result', {} );
310 #$runner->insert( 'result.event', 'SUCCESS' );
311 $runner->insert( 'result.events', [] );
314 $runner->insert('environment.isRenewal', 1);
316 $runner->insert('environment.isRenewal', undef);
319 if($ctx->{ishold} ) {
320 $runner->insert('environment.isHold', 1);
322 $runner->insert('environment.isHold', undef)
325 if( $ctx->{noncat} ) {
326 $runner->insert('environment.isNonCat', 1);
327 $runner->insert('environment.nonCatType', $ctx->{noncat_type});
329 $runner->insert('environment.isNonCat', undef);
332 # if(ref($ctx->{patron_circ_summary})) {
333 # $runner->insert( 'environment.patronItemsOut', $ctx->{patron_circ_summary}->[0], 1 );
334 # $runner->insert( 'environment.patronFines', $ctx->{patron_circ_summary}->[1], 1 );
337 $ctx->{runner} = $runner;
342 sub _add_script_runner_methods {
345 my $runner = $ctx->{runner};
349 # allows a script to fetch a hold that is currently targeting the
351 $runner->insert_method( 'environment.copy', '__OILS_FUNC_fetch_hold', sub {
353 my $hold = $holdcode->fetch_related_holds($ctx->{copy}->id);
354 $hold = undef unless $hold;
355 $runner->insert( $key, $hold, 1 );
361 # ------------------------------------------------------------------------------
363 __PACKAGE__->register_method(
364 method => "permit_circ",
365 api_name => "open-ils.circ.checkout.permit",
367 Determines if the given checkout can occur
368 @param authtoken The login session key
369 @param params A trailing hash of named params including
370 barcode : The copy barcode,
371 patron : The patron the checkout is occurring for,
372 renew : true or false - whether or not this is a renewal
373 @return The event that occurred during the permit check.
376 __PACKAGE__->register_method (
377 method => 'permit_circ',
378 api_name => 'open-ils.circ.checkout.permit.override',
379 signature => q/@see open-ils.circ.checkout.permit/,
383 my( $self, $client, $authtoken, $params ) = @_;
386 my $override = $params->{override} = 1 if $self->api_name =~ /override/o;
388 my ( $requestor, $patron, $ctx, $evt, $circ );
390 # check permisson of the requestor
391 ( $requestor, $patron, $evt ) =
392 $U->checkses_requestor(
393 $authtoken, $params->{patron}, 'VIEW_PERMIT_CHECKOUT' );
397 # fetch and build the circulation environment
398 if( !( $ctx = $params->{_ctx}) ) {
400 ( $ctx, $evt ) = create_circ_ctx( %$params,
402 requestor => $requestor,
404 #fetch_patron_circ_summary => 1,
405 fetch_copy_statuses => 1,
406 fetch_copy_locations => 1,
411 my $copy = $ctx->{copy};
413 my $stat = (ref $copy->status) ? $copy->status->id : $copy->status;
414 return OpenILS::Event->new('COPY_IN_TRANSIT')
415 if $stat == $U->copy_status_from_name('in transit')->id;
418 $ctx->{authtoken} = $authtoken;
421 if( $ctx->{copy} and ($evt = _handle_claims_returned($ctx)) ) {
422 return $evt unless $U->event_equals($evt, 'SUCCESS');
430 # no claims returned circ was found, check if there is any open circ
431 if( !$ctx->{ishold} and !$__isrenewal and $ctx->{copy} ) {
432 ($circ, $evt) = $U->fetch_open_circulation($ctx->{copy}->id);
433 return OpenILS::Event->new('OPEN_CIRCULATION_EXISTS') if $circ;
438 $ctx->{permit_key} = _cache_permit_key();
439 my $events = _run_permit_scripts($ctx);
442 $evt = override_events($requestor, $requestor->ws_ou,
443 $events, $authtoken, $ctx->{copy}->id, $client);
445 return OpenILS::Event->new('SUCCESS', payload => $ctx->{permit_key} );
451 sub override_events {
453 my( $requestor, $org, $events, $authtoken, $copyid, $conn ) = @_;
454 $events = [ $events ] unless ref($events) eq 'ARRAY';
457 for my $e (@$events) {
458 my $tc = $e->{textcode};
459 next if $tc eq 'SUCCESS';
460 my $ov = "$tc.override";
461 $logger->info("attempting to override event $ov");
462 my $evt = $U->check_perms( $requestor->id, $org, $ov );
470 __PACKAGE__->register_method(
471 method => "check_title_hold",
472 api_name => "open-ils.circ.title_hold.is_possible",
474 Determines if a hold were to be placed by a given user,
475 whether or not said hold would have any potential copies
477 @param authtoken The login session key
478 @param params A hash of named params including:
479 patronid - the id of the hold recipient
480 titleid (brn) - the id of the title to be held
481 depth - the hold range depth (defaults to 0)
484 # XXX add pickup lib to the call to test for perms
486 sub check_title_hold {
487 my( $self, $client, $authtoken, $params ) = @_;
488 my %params = %$params;
489 my $titleid = $params{titleid};
491 my ( $requestor, $patron, $evt ) = $U->checkses_requestor(
492 $authtoken, $params{patronid}, 'VIEW_HOLD_PERMIT' );
495 my $rangelib = $patron->home_ou;
496 my $depth = $params{depth} || 0;
497 my $pickup = $params{pickup_lib};
499 $logger->debug("Fetching ranged title tree for title $titleid, org $rangelib, depth $depth");
501 my $org = $U->simplereq(
503 'open-ils.actor.org_unit.retrieve',
504 $authtoken, $requestor->home_ou );
510 while( $title = $U->storagereq(
511 'open-ils.storage.biblio.record_entry.ranged_tree',
512 $titleid, $rangelib, $depth, $limit, $offset ) ) {
516 ref($title->call_numbers) and
517 @{$title->call_numbers};
519 for my $cn (@{$title->call_numbers}) {
521 $logger->debug("Checking callnumber ".$cn->id." for hold fulfillment possibility");
523 for my $copy (@{$cn->copies}) {
525 $logger->debug("Checking copy ".$copy->id." for hold fulfillment possibility");
527 return 1 if OpenILS::Utils::PermitHold::permit_copy_hold(
529 requestor => $requestor,
532 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
533 pickup_lib => $pickup,
534 request_lib => $org } );
536 $logger->debug("Copy ".$copy->id." for hold fulfillment possibility failed...");
547 # Runs the patron and copy permit scripts
548 # if this is a non-cat circulation, the copy permit script
550 sub _run_permit_scripts {
553 my $runner = $ctx->{runner};
554 my $patronid = $ctx->{patron}->id;
555 my $barcode = ($ctx->{copy}) ? $ctx->{copy}->barcode : undef;
556 my $key = $ctx->{permit_key};
558 my $penalties = $U->update_patron_penalties(
559 authtoken => $ctx->{authtoken},
560 patron => $ctx->{patron}
563 $penalties = $penalties->{fatal_penalties};
565 $logger->info("circ patron penalties user $patronid: @$penalties");
567 if( $ctx->{noncat} ) {
568 $logger->debug("Exiting circ permit early because item is a non-cataloged item");
569 return OpenILS::Event->new('SUCCESS', payload => $key);
573 $logger->debug("Exiting circ permit early because copy is pre-cataloged");
574 return OpenILS::Event->new('ITEM_NOT_CATALOGED', payload => $key);
578 $logger->debug("Exiting circ permit early because request is for hold patron permit");
579 return OpenILS::Event->new('SUCCESS');
582 $runner->load($scripts{circ_permit_copy});
583 $runner->run or throw OpenSRF::EX::ERROR ("Circ Permit Copy Script Died: $@");
585 # ---------------------------------------------------------------------
586 # Capture all of the copy permit events
587 # ---------------------------------------------------------------------
588 my $copy_events = $runner->retrieve('result.events');
589 $copy_events = [ split(/,/, $copy_events) ];
590 $ctx->{circ_permit_copy_events} = $copy_events;
591 $logger->activity("circ_permit_copy for copy ".
592 "$barcode returned events: @$copy_events") if @$copy_events;
595 push( @allevents, OpenILS::Event->new($_)) for @$penalties;
596 push( @allevents, OpenILS::Event->new($_)) for @$copy_events;
598 my $ae = _check_copy_alert($ctx->{copy});
599 push( @allevents, $ae ) if $ae;
601 return OpenILS::Event->new('SUCCESS', payload => $key) unless (@allevents);
603 # uniquify the events
604 my %hash = map { ($_->{ilsevent} => $_) } @allevents;
605 @allevents = values %hash;
608 $_->{payload} = $ctx->{copy}->status->id
609 if ($_->{textcode} eq 'COPY_NOT_AVAILABLE');
615 sub _check_copy_alert {
617 return OpenILS::Event->new('COPY_ALERT_MESSAGE',
618 payload => $copy->alert_message) if $copy->alert_message;
622 # takes copyid, patronid, and requestor id
623 sub _cache_permit_key {
624 my $key = md5_hex( time() . rand() . "$$" );
625 $logger->debug("Setting circ permit key to $key");
626 $cache_handle->put_cache( "oils_permit_key_$key", 1, 300 );
630 sub _check_permit_key {
632 $logger->debug("Fetching circ permit key $key");
633 my $k = "oils_permit_key_$key";
634 my $one = $cache_handle->get_cache($k);
635 $cache_handle->delete_cache($k);
636 return ($one) ? 1 : 0;
640 # ------------------------------------------------------------------------------
642 __PACKAGE__->register_method(
643 method => "checkout",
644 api_name => "open-ils.circ.checkout",
647 @param authtoken The login session key
648 @param params A named hash of params including:
650 barcode If no copy is provided, the copy is retrieved via barcode
651 copyid If no copy or barcode is provide, the copy id will be use
652 patron The patron's id
653 noncat True if this is a circulation for a non-cataloted item
654 noncat_type The non-cataloged type id
655 noncat_circ_lib The location for the noncat circ.
656 precat The item has yet to be cataloged
657 dummy_title The temporary title of the pre-cataloded item
658 dummy_author The temporary authr of the pre-cataloded item
659 Default is the home org of the staff member
660 @return The SUCCESS event on success, any other event depending on the error
664 my( $self, $client, $authtoken, $params ) = @_;
667 my ( $requestor, $patron, $ctx, $evt, $circ, $copy );
668 my $key = $params->{permit_key};
670 # if this is a renewal, then the requestor does not have to
671 # have checkout privelages
672 ( $requestor, $evt ) = $U->checkses($authtoken) if $__isrenewal;
673 ( $requestor, $evt ) = $U->checksesperm( $authtoken, 'COPY_CHECKOUT' ) unless $__isrenewal;
676 if( $params->{patron} ) {
677 ( $patron, $evt ) = $U->fetch_user($params->{patron});
680 ( $patron, $evt ) = $U->fetch_user_by_barcode($params->{patron_barcode});
684 # set the circ lib to the home org of the requestor if not specified
685 my $circlib = (defined($params->{circ_lib})) ?
686 $params->{circ_lib} : $requestor->ws_ou;
689 # Make sure the caller has a valid permit key or is
690 # overriding the permit can
691 if( $params->{permit_override} ) {
692 $evt = $U->check_perms(
693 $requestor->id, $requestor->ws_ou, 'CIRC_PERMIT_OVERRIDE');
697 return OpenILS::Event->new('CIRC_PERMIT_BAD_KEY')
698 unless _check_permit_key($key);
701 # if this is a non-cataloged item, check it out and return
702 return _checkout_noncat(
703 $key, $requestor, $patron, %$params ) if $params->{noncat};
705 # if this item has yet to be cataloged, make sure a dummy copy exists
706 ( $params->{copy}, $evt ) = _make_precat_copy(
707 $requestor, $circlib, $params ) if $params->{precat};
711 # fetch and build the circulation environment
712 if( !( $ctx = $params->{_ctx}) ) {
713 ( $ctx, $evt ) = create_circ_ctx( %$params,
715 requestor => $requestor,
716 session => $U->start_db_session(),
718 #fetch_patron_circ_summary => 1,
719 fetch_copy_statuses => 1,
720 fetch_copy_locations => 1,
724 $ctx->{session} = $U->start_db_session() unless $ctx->{session};
726 # if the call doesn't know it's not cataloged..
727 if(!$params->{precat}) {
728 if( $ctx->{copy}->call_number eq '-1' ) {
729 return OpenILS::Event->new('ITEM_NOT_CATALOGED');
734 $copy = $ctx->{copy};
736 my $stat = (ref $copy->status) ? $copy->status->id : $copy->status;
737 return OpenILS::Event->new('COPY_IN_TRANSIT')
738 if $stat == $U->copy_status_from_name('in transit')->id;
741 # this happens in permit.. but we need to check here for 'offline' requests
742 ($circ) = $U->fetch_open_circulation($ctx->{copy}->id);
743 return OpenILS::Event->new('OPEN_CIRCULATION_EXISTS') if $circ;
745 my $cid = ($params->{precat}) ? -1 : $ctx->{copy}->id;
748 $ctx->{circ_lib} = $circlib;
750 $evt = _run_checkout_scripts($ctx);
754 _build_checkout_circ_object($ctx);
756 $evt = _apply_modified_due_date($ctx);
759 $evt = _commit_checkout_circ_object($ctx);
762 $evt = _update_checkout_copy($ctx);
766 ($holds, $evt) = _handle_related_holds($ctx);
770 $logger->debug("Checkout committing objects with session thread trace: ".$ctx->{session}->session_id);
771 $U->commit_db_session($ctx->{session});
772 my $record = $U->record_to_mvr($ctx->{title}) unless $ctx->{precat};
774 $logger->activity("user ".$requestor->id." successfully checked out item ".
775 $ctx->{copy}->barcode." to user ".$ctx->{patron}->id );
778 # ------------------------------------------------------------------------------
779 # Update the patron penalty info in the DB
780 # ------------------------------------------------------------------------------
781 $U->update_patron_penalties(
782 authtoken => $authtoken,
783 patron => $ctx->{patron} ,
787 return OpenILS::Event->new('SUCCESS',
789 copy => $U->unflesh_copy($ctx->{copy}),
790 circ => $ctx->{circ},
792 holds_fulfilled => $holds,
798 sub _make_precat_copy {
799 my ( $requestor, $circlib, $params ) = @_;
801 my( $copy, undef ) = _find_copy_by_attr(%$params);
804 $logger->debug("Pre-cat copy already exists in checkout: ID=" . $copy->id);
806 $copy->editor($requestor->id);
807 $copy->edit_date('now');
808 $copy->dummy_title($params->{dummy_title});
809 $copy->dummy_author($params->{dummy_author});
811 my $stat = $U->storagereq(
812 'open-ils.storage.direct.asset.copy.update', $copy );
814 return (undef, $U->DB_UPDATE_FAILED($copy)) unless $stat;
818 $logger->debug("Creating a new precataloged copy in checkout with barcode " . $params->{barcode});
820 my $evt = OpenILS::Event->new(
821 'BAD_PARAMS', desc => "Dummy title or author not provided" )
822 unless ( $params->{dummy_title} and $params->{dummy_author} );
823 return (undef, $evt) if $evt;
825 $copy = Fieldmapper::asset::copy->new;
826 $copy->circ_lib($circlib);
827 $copy->creator($requestor->id);
828 $copy->editor($requestor->id);
829 $copy->barcode($params->{barcode});
830 $copy->call_number(-1); #special CN for precat materials
831 $copy->loan_duration(&PRECAT_LOAN_DURATION);
832 $copy->fine_level(&PRECAT_FINE_LEVEL);
834 $copy->dummy_title($params->{dummy_title});
835 $copy->dummy_author($params->{dummy_author});
837 my $id = $U->storagereq(
838 'open-ils.storage.direct.asset.copy.create', $copy );
839 return (undef, $U->DB_UPDATE_FAILED($copy)) unless $copy;
841 $logger->debug("Pre-cataloged copy successfully created");
842 return ($U->fetch_copy($id));
846 sub _run_checkout_scripts {
852 my $runner = $ctx->{runner};
854 $runner->insert('result.durationLevel');
855 $runner->insert('result.durationRule');
856 $runner->insert('result.recurringFinesRule');
857 $runner->insert('result.recurringFinesLevel');
858 $runner->insert('result.maxFine');
860 $runner->load($scripts{circ_duration});
861 $runner->run or throw OpenSRF::EX::ERROR ("Circ Duration Script Died: $@");
862 my $duration = $runner->retrieve('result.durationRule');
863 $logger->debug("Circ duration script yielded a duration rule of: $duration");
865 $runner->load($scripts{circ_recurring_fines});
866 $runner->run or throw OpenSRF::EX::ERROR ("Circ Recurring Fines Script Died: $@");
867 my $recurring = $runner->retrieve('result.recurringFinesRule');
868 $logger->debug("Circ recurring fines script yielded a rule of: $recurring");
870 $runner->load($scripts{circ_max_fines});
871 $runner->run or throw OpenSRF::EX::ERROR ("Circ Max Fine Script Died: $@");
872 my $max_fine = $runner->retrieve('result.maxFine');
873 $logger->debug("Circ max_fine fines script yielded a rule of: $max_fine");
875 ($duration, $evt) = $U->fetch_circ_duration_by_name($duration);
877 ($recurring, $evt) = $U->fetch_recurring_fine_by_name($recurring);
879 ($max_fine, $evt) = $U->fetch_max_fine_by_name($max_fine);
882 $ctx->{duration_level} = $runner->retrieve('result.durationLevel');
883 $ctx->{recurring_fines_level} = $runner->retrieve('result.recurringFinesLevel');
884 $ctx->{duration_rule} = $duration;
885 $ctx->{recurring_fines_rule} = $recurring;
886 $ctx->{max_fine_rule} = $max_fine;
891 sub _build_checkout_circ_object {
895 my $circ = new Fieldmapper::action::circulation;
896 my $duration = $ctx->{duration_rule};
897 my $max = $ctx->{max_fine_rule};
898 my $recurring = $ctx->{recurring_fines_rule};
899 my $copy = $ctx->{copy};
900 my $patron = $ctx->{patron};
901 my $dur_level = $ctx->{duration_level};
902 my $rec_level = $ctx->{recurring_fines_level};
904 $circ->duration( $duration->shrt ) if ($dur_level == 1);
905 $circ->duration( $duration->normal ) if ($dur_level == 2);
906 $circ->duration( $duration->extended ) if ($dur_level == 3);
908 $circ->recuring_fine( $recurring->low ) if ($rec_level =~ /low/io);
909 $circ->recuring_fine( $recurring->normal ) if ($rec_level =~ /normal/io);
910 $circ->recuring_fine( $recurring->high ) if ($rec_level =~ /high/io);
912 $circ->duration_rule( $duration->name );
913 $circ->recuring_fine_rule( $recurring->name );
914 $circ->max_fine_rule( $max->name );
915 $circ->max_fine( $max->amount );
917 $circ->fine_interval($recurring->recurance_interval);
918 $circ->renewal_remaining( $duration->max_renewals );
919 $circ->target_copy( $copy->id );
920 $circ->usr( $patron->id );
921 $circ->circ_lib( $ctx->{circ_lib} );
924 $logger->debug("Circ is a renewal. Setting renewal_remaining to " . $ctx->{renewal_remaining} );
925 $circ->opac_renewal(1);
926 $circ->renewal_remaining($ctx->{renewal_remaining});
927 $circ->circ_staff($ctx->{requestor}->id);
931 # if the user provided an overiding checkout time,
932 # (e.g. the checkout really happened several hours ago), then
933 # we apply that here. Does this need a perm??
934 if( my $ds = _create_date_stamp($ctx->{checkout_time}) ) {
935 $logger->debug("circ setting checkout_time to $ds");
936 $circ->xact_start($ds);
939 # if a patron is renewing, 'requestor' will be the patron
940 $circ->circ_staff($ctx->{requestor}->id );
941 _set_circ_due_date($circ);
942 $ctx->{circ} = $circ;
945 sub _apply_modified_due_date {
947 my $circ = $ctx->{circ};
951 if( $ctx->{due_date} ) {
953 my $evt = $U->check_perms(
954 $ctx->{requestor}->id, $ctx->{circ_lib}, 'CIRC_OVERRIDE_DUE_DATE');
957 my $ds = _create_date_stamp($ctx->{due_date});
958 $logger->debug("circ modifying due_date to $ds");
959 $circ->due_date($ds);
963 # if the due_date lands on a day when the location is closed
964 my $copy = $ctx->{copy};
967 $logger->info("circ searching for closed date overlap on lib ".
968 $copy->circ_lib->id ." with an item due date of ".$circ->due_date );
970 my $dateinfo = $ctx->{session}->request(
971 'open-ils.storage.actor.org_unit.closed_date.overlap',
972 $copy->circ_lib->id, $circ->due_date )->gather(1);
976 $logger->info("$dateinfo : circ due data / close date overlap found : due_date=".
977 $circ->due_date." start=". $dateinfo->{start}.", end=".$dateinfo->{end});
979 # XXX make the behavior more dynamic
980 # for now, we just push the due date to after the close date
981 $circ->due_date($dateinfo->{end});
988 sub _create_date_stamp {
989 my $datestring = shift;
990 return undef unless $datestring;
991 $datestring = clense_ISO8601($datestring);
992 $logger->debug("circ created date stamp => $datestring");
996 sub _create_due_date {
997 my $duration = shift;
999 my ($sec,$min,$hour,$mday,$mon,$year) =
1000 gmtime(OpenSRF::Utils->interval_to_seconds($duration) + int(time()));
1001 $year += 1900; $mon += 1;
1002 my $due_date = sprintf(
1003 '%s-%0.2d-%0.2dT%s:%0.2d:%0.2d-00',
1004 $year, $mon, $mday, $hour, $min, $sec);
1008 sub _set_circ_due_date {
1011 my $dd = _create_due_date($circ->duration);
1012 $logger->debug("Checkout setting due date on circ to: $dd");
1013 $circ->due_date($dd);
1016 # Sets the editor, edit_date, un-fleshes the copy, and updates the copy in the DB
1017 sub _update_checkout_copy {
1020 my $copy = $ctx->{copy};
1022 my $s = $U->copy_status_from_name('checked out');
1023 $copy->status( $s->id ) if $s;
1025 my $evt = $U->update_copy( session => $ctx->{session},
1026 copy => $copy, editor => $ctx->{requestor}->id );
1027 return (undef,$evt) if $evt;
1032 # commits the circ object to the db then fleshes the circ with rules objects
1033 sub _commit_checkout_circ_object {
1036 my $circ = $ctx->{circ};
1040 my $r = $ctx->{session}->request(
1041 "open-ils.storage.direct.action.circulation.create", $circ )->gather(1);
1043 return $U->DB_UPDATE_FAILED($circ) unless $r;
1045 $logger->debug("Created a new circ object in checkout: $r");
1048 $circ->duration_rule($ctx->{duration_rule});
1049 $circ->max_fine_rule($ctx->{max_fine_rule});
1050 $circ->recuring_fine_rule($ctx->{recurring_fines_rule});
1056 # sees if there are any holds that this copy
1057 sub _handle_related_holds {
1060 my $copy = $ctx->{copy};
1061 my $patron = $ctx->{patron};
1062 my $holds = $holdcode->fetch_related_holds($copy->id);
1066 # XXX We should only fulfill one hold here...
1067 # XXX If a hold was transited to the user who is checking out
1068 # the item, we need to make sure that hold is what's grabbed
1069 if(ref($holds) && @$holds) {
1071 # for now, just sort by id to get what should be the oldest hold
1072 $holds = [ sort { $a->id <=> $b->id } @$holds ];
1073 my @myholds = grep { $_->usr eq $patron->id } @$holds;
1074 my @altholds = grep { $_->usr ne $patron->id } @$holds;
1077 my $hold = $myholds[0];
1079 $logger->debug("Related hold found in checkout: " . $hold->id );
1081 $hold->current_copy($copy->id); # just make sure it's set
1082 # if the hold was never officially captured, capture it.
1083 $hold->capture_time('now') unless $hold->capture_time;
1084 $hold->fulfillment_time('now');
1085 my $r = $ctx->{session}->request(
1086 "open-ils.storage.direct.action.hold_request.update", $hold )->gather(1);
1087 return (undef,$U->DB_UPDATE_FAILED( $hold )) unless $r;
1088 push( @fulfilled, $hold->id );
1091 # If there are any holds placed for other users that point to this copy,
1092 # then we need to un-target those holds so the targeter can pick a new copy
1095 $logger->info("Un-targeting hold ".$_->id.
1096 " because copy ".$copy->id." is getting checked out");
1098 $_->clear_current_copy;
1099 my $r = $ctx->{session}->request(
1100 "open-ils.storage.direct.action.hold_request.update", $_ )->gather(1);
1101 return (undef,$U->DB_UPDATE_FAILED( $_ )) unless $r;
1105 return (\@fulfilled, undef);
1108 sub _checkout_noncat {
1109 my ( $key, $requestor, $patron, %params ) = @_;
1110 my( $circ, $circlib, $evt );
1113 $circlib = $params{noncat_circ_lib} || $requestor->ws_ou;
1115 my $count = $params{noncat_count} || 1;
1116 my $cotime = _create_date_stamp($params{checkout_time}) || "";
1117 $logger->info("circ creating $count noncat circs with checkout time $cotime");
1119 ( $circ, $evt ) = OpenILS::Application::Circ::NonCat::create_non_cat_circ(
1120 $requestor->id, $patron->id, $circlib, $params{noncat_type}, $cotime );
1121 return $evt if $evt;
1124 return OpenILS::Event->new(
1125 'SUCCESS', payload => { noncat_circ => $circ } );
1129 __PACKAGE__->register_method(
1130 method => "generic_receive",
1131 api_name => "open-ils.circ.checkin",
1134 Generic super-method for handling all copies
1135 @param authtoken The login session key
1136 @param params Hash of named parameters including:
1137 barcode - The copy barcode
1138 force - If true, copies in bad statuses will be checked in and give good statuses
1143 __PACKAGE__->register_method(
1144 method => "generic_receive",
1145 api_name => "open-ils.circ.checkin.override",
1146 signature => q/@see open-ils.circ.checkin/
1149 sub generic_receive {
1150 my( $self, $conn, $authtoken, $params ) = @_;
1151 my( $ctx, $requestor, $evt );
1153 ( $requestor, $evt ) = $U->checkses($authtoken) if $__isrenewal;
1154 ( $requestor, $evt ) = $U->checksesperm(
1155 $authtoken, 'COPY_CHECKIN' ) unless $__isrenewal;
1156 return $evt if $evt;
1158 # load up the circ objects
1159 if( !( $ctx = $params->{_ctx}) ) {
1160 ( $ctx, $evt ) = create_circ_ctx( %$params,
1161 requestor => $requestor,
1162 session => $U->start_db_session(),
1164 fetch_copy_statuses => 1,
1165 fetch_copy_locations => 1,
1168 return $evt if $evt;
1170 $ctx->{override} = 1 if $self->api_name =~ /override/o;
1171 $ctx->{session} = $U->start_db_session() unless $ctx->{session};
1172 $ctx->{authtoken} = $authtoken;
1173 my $session = $ctx->{session};
1175 my $copy = $ctx->{copy};
1176 $U->unflesh_copy($copy);
1177 return OpenILS::Event->new('ASSET_COPY_NOT_FOUND') unless $copy;
1179 $logger->info("Checkin copy called by user ".
1180 $requestor->id." for copy ".$copy->id);
1182 # ------------------------------------------------------------------------------
1183 # Update the patron penalty info in the DB
1184 # ------------------------------------------------------------------------------
1185 $U->update_patron_penalties(
1186 authtoken => $authtoken,
1187 patron => $ctx->{patron},
1191 return $self->checkin_do_receive($conn, $ctx);
1194 sub checkin_do_receive {
1196 my( $self, $connection, $ctx ) = @_;
1199 my $copy = $ctx->{copy};
1200 my $session = $ctx->{session};
1201 my $requestor = $ctx->{requestor};
1202 my $change = 0; # did we actually do anything?
1207 # does the copy have an attached alert message?
1208 my $ae = _check_copy_alert($copy);
1209 push(@eventlist, $ae) if $ae;
1211 # is the copy is an a status we can't automatically resolve?
1212 $evt = _checkin_check_copy_status($ctx);
1213 push( @eventlist, $evt ) if $evt;
1216 # - see if the copy has an open circ attached
1217 ($ctx->{circ}, $evt) = $U->fetch_open_circulation($copy->id);
1218 return $evt if ($evt and $__isrenewal); # renewals require a circulation
1220 $circ = $ctx->{circ};
1222 # if the circ is marked as 'claims returned', add the event to the list
1223 push( @eventlist, 'CIRC_CLAIMS_RETURNED' )
1224 if ($circ and $circ->stop_fines and $circ->stop_fines eq 'CLAIMSRETURNED');
1228 if($ctx->{override}) {
1229 $evt = override_events($requestor, $requestor->ws_ou, \@eventlist );
1230 return $evt if $evt;
1236 ($ctx->{transit}) = $U->fetch_open_transit_by_copy($copy->id);
1238 if( $ctx->{circ} ) {
1240 # There is an open circ on this item, close it out.
1242 $evt = _checkin_handle_circ($ctx);
1243 return $evt if $evt;
1245 } elsif( $ctx->{transit} ) {
1247 # is this item currently in transit?
1249 $evt = $transcode->transit_receive( $copy, $requestor, $session );
1250 my $holdtrans = $evt->{holdtransit};
1251 ($ctx->{hold}) = $U->fetch_hold($holdtrans->hold) if $holdtrans;
1253 if( ! $U->event_equals($evt, 'SUCCESS') ) {
1255 # either an error occurred or a ROUTE_ITEM was generated and the
1256 # item must be forwarded on to its destination.
1257 return _checkin_flesh_event($ctx, $evt);
1261 # Transit has been closed, now let's see if the copy's original
1262 # status is something the staff should be warned of
1263 my $e = _checkin_check_copy_status($ctx);
1268 # copy was received as a hold transit. Copy is at target lib
1269 # and hold transit is complete. We're done here...
1270 $U->commit_db_session($session);
1271 return _checkin_flesh_event($ctx, $evt);
1277 # ------------------------------------------------------------------------------
1278 # Circulations and transits are now closed where necessary. Now go on to see if
1279 # this copy can fulfill a hold or needs to be routed to a different location
1280 # ------------------------------------------------------------------------------
1283 # If it's a renewal, we're done
1286 #my ($cc, $ee) = _reshelve_copy($ctx);
1288 #delete $$ctx{force};
1289 $U->commit_db_session($session);
1290 return OpenILS::Event->new('SUCCESS');
1293 # Now, let's see if this copy is needed for a hold
1294 my ($hold) = $holdcode->find_local_hold( $session, $copy, $requestor );
1298 $ctx->{hold} = $hold;
1301 # Capture the hold with this copy
1302 return $evt if ($evt = _checkin_capture_hold($ctx));
1304 if( $hold->pickup_lib == $requestor->ws_ou ) {
1306 # This hold was captured in the correct location
1307 $evt = OpenILS::Event->new('SUCCESS');
1311 # Hold needs to be picked up elsewhere. Build a hold
1312 # transit and route the item.
1313 return $evt if ($evt =_checkin_build_hold_transit($ctx));
1314 $evt = OpenILS::Event->new('ROUTE_ITEM', org => $hold->pickup_lib);
1317 } else { # not needed for a hold
1319 if( $copy->circ_lib == $requestor->ws_ou ) {
1321 # Copy is in the right place.
1322 $evt = OpenILS::Event->new('SUCCESS');
1324 # if the item happens to be a pre-cataloged item, send it
1325 # to cataloging and return the event
1326 my( $e, $c, $err ) = _checkin_handle_precat($ctx);
1327 return $err if $err;
1333 # Copy wants to go home. Transit it there.
1334 return $evt if ( $evt = _checkin_build_generic_copy_transit($ctx) );
1335 $evt = OpenILS::Event->new('ROUTE_ITEM', org => $copy->circ_lib);
1341 # ------------------------------------------------------------------
1342 # if the copy is not in a state that should persist,
1343 # set the copy to reshelving if it's not already there
1344 # ------------------------------------------------------------------
1345 my ($c, $e) = _reshelve_copy($ctx);
1347 $change = $c unless $change;
1351 $evt = OpenILS::Event->new('NO_CHANGE');
1352 ($ctx->{hold}) = $U->fetch_open_hold_by_copy($copy->id)
1353 if( $copy->status == $U->copy_status_from_name('on holds shelf')->id );
1357 $U->commit_db_session($session);
1360 $logger->activity("checkin by user ".$requestor->id." on item ".
1361 $ctx->{copy}->barcode." completed with event ".$evt->{textcode});
1363 return _checkin_flesh_event($ctx, $evt);
1366 sub _reshelve_copy {
1369 my $copy = $ctx->{copy};
1370 my $reqr = $ctx->{requestor};
1371 my $session = $ctx->{session};
1372 my $force = $ctx->{force};
1374 my $stat = ref($copy->status) ? $copy->status->id : $copy->status;
1377 $stat != $U->copy_status_from_name('on holds shelf')->id and
1378 $stat != $U->copy_status_from_name('available')->id and
1379 $stat != $U->copy_status_from_name('cataloging')->id and
1380 $stat != $U->copy_status_from_name('in transit')->id and
1381 $stat != $U->copy_status_from_name('reshelving')->id) ) {
1383 $copy->status( $U->copy_status_from_name('reshelving')->id );
1385 my $evt = $U->update_copy(
1387 editor => $reqr->id,
1388 session => $session,
1399 # returns undef if there are no 'open' claims-returned circs attached
1400 # to the given copy. if there is an open claims-returned circ,
1401 # then we check for override mode. if in override, mark the claims-returned
1402 # circ as checked in. if not, return event.
1403 sub _handle_claims_returned {
1405 my $copy = $ctx->{copy};
1407 my $CR = _fetch_open_claims_returned($copy->id);
1408 return undef unless $CR;
1410 # - If the caller has set the override flag, we will check the item in
1411 if($ctx->{override}) {
1413 $CR->checkin_time('now');
1414 $CR->checkin_lib($ctx->{requestor}->ws_ou);
1415 $CR->checkin_staff($ctx->{requestor}->id);
1417 my $stat = $U->storagereq(
1418 'open-ils.storage.direct.action.circulation.update', $CR);
1419 return $U->DB_UPDATE_FAILED($CR) unless $stat;
1420 return OpenILS::Event->new('SUCCESS');
1423 # - if not in override mode, return the CR event
1424 return OpenILS::Event->new('CIRC_CLAIMS_RETURNED');
1429 sub _fetch_open_claims_returned {
1431 my $trans = $U->storagereq(
1432 'open-ils.storage.direct.action.circulation.search_where',
1434 target_copy => $copyid,
1435 stop_fines => 'CLAIMSRETURNED',
1436 checkin_time => undef,
1439 return $$trans[0] if $trans && $$trans[0];
1443 # - if the copy is has the 'in process' status, set it to reshelving
1444 #sub _check_in_process {
1447 #my $copy = $ctx->{copy};
1448 #my $reqr = $ctx->{requestor};
1449 #my $ses = $ctx->{session};
1451 #my $stat = $U->copy_status_from_name('in process');
1452 #my $rstat = $U->copy_status_from_name('reshelving');
1454 #if( $stat->id == $copy->status->id ) {
1455 #$logger->info("marking 'in-process' copy ".$copy->id." as 'reshelving'");
1456 #$copy->status( $rstat->id );
1457 #my $evt = $U->update_copy(
1459 #editor => $reqr->id,
1462 #return $evt if $evt;
1464 #$copy->status( $rstat ); # - reflesh the copy status
1470 # returns (ITEM_NOT_CATALOGED, change_occurred, $error_event) where necessary
1471 sub _checkin_handle_precat {
1474 my $copy = $ctx->{copy};
1479 my $catstat = $U->copy_status_from_name('cataloging');
1481 if( $ctx->{precat} ) {
1483 $evt = OpenILS::Event->new('ITEM_NOT_CATALOGED');
1485 if( $copy->status != $catstat->id ) {
1486 $copy->status($catstat->id);
1488 return (undef, 0, $errevt) if (
1489 $errevt = $U->update_copy(
1491 editor => $ctx->{requestor}->id,
1492 session => $ctx->{session} ));
1498 return ($evt, $change, undef);
1502 # returns the appropriate event for the given copy status
1503 # if the copy is not in a 'special' status, undef is returned
1504 sub _checkin_check_copy_status {
1506 my $copy = $ctx->{copy};
1507 my $reqr = $ctx->{requestor};
1508 my $ses = $ctx->{session};
1514 my $status = ref($copy->status) ? $copy->status->id : $copy->status;
1517 if( $status == $U->copy_status_from_name('available')->id ||
1518 $status == $U->copy_status_from_name('checked out')->id ||
1519 $status == $U->copy_status_from_name('in process')->id ||
1520 $status == $U->copy_status_from_name('in transit')->id ||
1521 $status == $U->copy_status_from_name('reshelving')->id );
1523 return OpenILS::Event->new('COPY_STATUS_LOST', payload => $copy )
1524 if( $status == $U->copy_status_from_name('lost')->id );
1526 return OpenILS::Event->new('COPY_STATUS_MISSING', payload => $copy )
1527 if( $status == $U->copy_status_from_name('missing')->id );
1529 return OpenILS::Event->new('COPY_BAD_STATUS', payload => $copy );
1533 # my $rstat = $U->copy_status_from_name('reshelving');
1534 # my $stat = (ref($copy->status)) ? $copy->status->id : $copy->status;
1536 # if( $stat == $U->copy_status_from_name('lost')->id ) {
1538 # $evt = OpenILS::Event->new('COPY_STATUS_LOST', payload => $copy );
1540 # } elsif( $stat == $U->copy_status_from_name('missing')->id) {
1542 # $evt = OpenILS::Event->new('COPY_STATUS_MISSING', payload => $copy );
1545 # return (undef,$evt) if(!$ctx->{override});
1547 # # we're are now going to attempt to override the failure
1548 # # and set the copy to reshelving
1550 # my $copyid = $copy->id;
1551 # my $userid = $reqr->id;
1554 # # - make sure we have permission
1555 # $e = $U->check_perms( $reqr->id,
1556 # $copy->circ_lib, 'COPY_STATUS_LOST.override');
1557 # return (undef,$e) if $e;
1558 # $copy->status( $rstat->id );
1560 # # XXX if no fines are owed in the circ, close it out - will this happen later anyway?
1561 # #my $circ = $U->storagereq(
1562 # # 'open-ils.storage.direct.action.circulation
1564 # $logger->activity("user $userid overriding 'lost' copy status for copy $copyid");
1566 # } elsif( $ismissing ) {
1568 # # - make sure we have permission
1569 # $e = $U->check_perms( $reqr->id,
1570 # $copy->circ_lib, 'COPY_STATUS_MISSING.override');
1571 # return (undef,$e) if $e;
1572 # $copy->status( $rstat->id );
1573 # $logger->activity("user $userid overriding 'missing' copy status for copy $copyid");
1576 # if( $islost or $ismissing ) {
1578 # # - update the copy with the new status
1579 # $evt = $U->update_copy(
1581 # editor => $reqr->id,
1584 # return (undef,$evt) if $evt;
1585 # $copy->status( $rstat );
1593 # Just gets the copy back home. Returns undef on success, event on error
1594 sub _checkin_build_generic_copy_transit {
1597 my $requestor = $ctx->{requestor};
1598 my $copy = $ctx->{copy};
1599 my $transit = Fieldmapper::action::transit_copy->new;
1600 my $session = $ctx->{session};
1602 $logger->activity("User ". $requestor->id ." creating a ".
1603 " new copy transit for copy ".$copy->id." to org ".$copy->circ_lib);
1605 $transit->source($requestor->ws_ou);
1606 $transit->dest($copy->circ_lib);
1607 $transit->target_copy($copy->id);
1608 $transit->source_send_time('now');
1609 $transit->copy_status($copy->status);
1611 $logger->debug("Creating new copy_transit in DB");
1613 my $s = $session->request(
1614 "open-ils.storage.direct.action.transit_copy.create", $transit )->gather(1);
1615 return $U->DB_UPDATE_FAILED($transit) unless $s;
1617 $logger->info("Checkin copy successfully created new transit: $s");
1619 $copy->status($U->copy_status_from_name('in transit')->id );
1621 return $U->update_copy( copy => $copy,
1622 editor => $requestor->id, session => $session );
1627 # returns event on error, undef on success
1628 sub _checkin_build_hold_transit {
1631 my $copy = $ctx->{copy};
1632 my $hold = $ctx->{hold};
1633 my $trans = Fieldmapper::action::hold_transit_copy->new;
1635 $trans->hold($hold->id);
1636 $trans->source($ctx->{requestor}->ws_ou);
1637 $trans->dest($hold->pickup_lib);
1638 $trans->source_send_time("now");
1639 $trans->target_copy($copy->id);
1640 $trans->copy_status($copy->status);
1642 my $id = $ctx->{session}->request(
1643 "open-ils.storage.direct.action.hold_transit_copy.create", $trans )->gather(1);
1644 return $U->DB_UPDATE_FAILED($trans) unless $id;
1646 $logger->info("Checkin copy successfully created hold transit: $id");
1648 $copy->status($U->copy_status_from_name('in transit')->id );
1649 return $U->update_copy( copy => $copy,
1650 editor => $ctx->{requestor}->id, session => $ctx->{session} );
1653 # Returns event on error, undef on success
1654 sub _checkin_capture_hold {
1656 my $copy = $ctx->{copy};
1657 my $hold = $ctx->{hold};
1659 $logger->debug("Checkin copy capturing hold ".$hold->id);
1661 $hold->current_copy($copy->id);
1662 $hold->capture_time('now');
1664 my $stat = $ctx->{session}->request(
1665 "open-ils.storage.direct.action.hold_request.update", $hold)->gather(1);
1666 return $U->DB_UPDATE_FAILED($hold) unless $stat;
1668 $copy->status( $U->copy_status_from_name('on holds shelf')->id );
1670 return $U->update_copy( copy => $copy,
1671 editor => $ctx->{requestor}->id, session => $ctx->{session} );
1674 # fleshes an event with the relevant objects from the context
1675 sub _checkin_flesh_event {
1680 $payload->{copy} = $U->unflesh_copy($ctx->{copy});
1681 $payload->{record} = $U->record_to_mvr($ctx->{title}) if($ctx->{title} and !$ctx->{precat});
1682 $payload->{circ} = $ctx->{circ} if $ctx->{circ};
1683 $payload->{transit} = $ctx->{transit} if $ctx->{transit};
1684 $payload->{hold} = $ctx->{hold} if $ctx->{hold};
1686 $evt->{payload} = $payload;
1691 # Closes out the circulation, puts the copy into reshelving.
1692 # Voids any bills attached to this circ after the backdate time
1693 # if a backdate is provided
1694 sub _checkin_handle_circ {
1698 my $circ = $ctx->{circ};
1699 my $copy = $ctx->{copy};
1700 my $requestor = $ctx->{requestor};
1701 my $session = $ctx->{session};
1705 $logger->info("Handling circulation [".$circ->id."] found in checkin...");
1707 # backdate the circ if necessary
1708 if(my $backdate = $ctx->{backdate}) {
1709 return $evt if ($evt =
1710 _checkin_handle_backdate($backdate, $circ, $requestor, $session, 1));
1714 if(!$circ->stop_fines) {
1715 $circ->stop_fines('CHECKIN');
1716 $circ->stop_fines('RENEW') if $__isrenewal;
1717 $circ->stop_fines_time('now');
1720 # see if there are any fines owed on this circ. if not, close it
1721 ( $obt, $evt ) = $U->fetch_open_billable_transaction($circ->id);
1722 return $evt if $evt;
1723 $circ->xact_finish('now') if( $obt->balance_owed != 0 );
1725 # Set the checkin vars since we have the item
1726 $circ->checkin_time('now');
1727 $circ->checkin_staff($requestor->id);
1728 $circ->checkin_lib($requestor->ws_ou);
1730 $evt = _set_copy_reshelving($copy, $requestor->id, $ctx->{session});
1731 return $evt if $evt;
1733 # $copy->status($U->copy_status_from_name('reshelving')->id);
1734 # $evt = $U->update_copy( session => $session,
1735 # copy => $copy, editor => $requestor->id );
1736 # return $evt if $evt;
1738 $ctx->{session}->request(
1739 'open-ils.storage.direct.action.circulation.update', $circ )->gather(1);
1744 sub _set_copy_reshelving {
1745 my( $copy, $reqr, $session ) = @_;
1747 $logger->info("Setting copy ".$copy->id." to reshelving");
1748 $copy->status($U->copy_status_from_name('reshelving')->id);
1750 my $evt = $U->update_copy(
1751 session => $session,
1755 return $evt if $evt;
1758 # returns event on error, undef on success
1759 # This voids all bills attached to the given circulation that occurred
1760 # after the backdate
1761 # THIS DOES NOT CLOSE THE CIRC if there are no more fines on the item
1762 sub _checkin_handle_backdate {
1763 my( $backdate, $circ, $requestor, $session, $closecirc ) = @_;
1765 $logger->activity("User ".$requestor->id.
1766 " backdating circ [".$circ->target_copy."] to date: $backdate");
1768 my $bills = $session->request( # XXX Verify this call is correct
1769 "open-ils.storage.direct.money.billing.search_where.atomic",
1770 billing_ts => { ">=" => $backdate }, "xact" => $circ->id )->gather(1);
1773 for my $bill (@$bills) {
1775 my $s = $session->request(
1776 "open-ils.storage.direct.money.billing.update", $bill)->gather(1);
1777 return $U->DB_UPDATE_FAILED($bill) unless $s;
1781 # if the caller elects to attempt to close the circulation
1782 # transaction, then it will be closed if there are not further
1783 # charges on the transaction
1785 #my ( $obt, $evt ) = $U->fetch_open_billable_transaction($circ->id);
1786 #return $evt if $evt;
1787 #$circ->xact_finish($backdate) if $obt->balance_owed <= 0;
1794 sub _find_patron_from_params {
1802 if(my $barcode = $params->{barcode}) {
1803 $logger->debug("circ finding user from params with barcode $barcode");
1804 ($copy, $evt) = $U->fetch_copy_by_barcode($barcode);
1805 return (undef, undef, $evt) if $evt;
1806 ($circ, $evt) = $U->fetch_open_circulation($copy->id);
1807 return (undef, undef, $evt) if $evt;
1808 ($patron, $evt) = $U->fetch_user($circ->usr);
1809 return (undef, undef, $evt) if $evt;
1811 return ($patron, $copy);
1815 # ------------------------------------------------------------------------------
1817 __PACKAGE__->register_method(
1819 api_name => "open-ils.circ.renew.override",
1820 signature => q/@see open-ils.circ.renew/,
1824 __PACKAGE__->register_method(
1826 api_name => "open-ils.circ.renew",
1827 notes => <<" NOTES");
1828 PARAMS( authtoken, circ => circ_id );
1829 open-ils.circ.renew(login_session, circ_object);
1830 Renews the provided circulation. login_session is the requestor of the
1831 renewal and if the logged in user is not the same as circ->usr, then
1832 the logged in user must have RENEW_CIRC permissions.
1836 my( $self, $client, $authtoken, $params ) = @_;
1839 my ( $requestor, $patron, $ctx, $evt, $circ, $copy );
1842 $params->{override} = 1 if $self->api_name =~ /override/o;
1844 # fetch the patron object one way or another
1845 if( $params->{patron} ) {
1846 ( $patron, $evt ) = $U->fetch_user($params->{patron});
1847 if($evt) { $__isrenewal = 0; return $evt; }
1849 } elsif( $params->{patron_barcode} ) {
1850 ( $patron, $evt ) = $U->fetch_user_by_barcode($params->{patron_barcode});
1851 if($evt) { $__isrenewal = 0; return $evt; }
1854 ($patron, $copy, $evt) = _find_patron_from_params($params);
1855 return $evt if $evt;
1856 $params->{copy} = $copy;
1859 # verify our login session
1860 ($requestor, $evt) = $U->checkses($authtoken);
1861 if($evt) { $__isrenewal = 0; return $evt; }
1863 # make sure we have permission to perform a renewal
1864 if( $requestor->id ne $patron->id ) {
1865 $evt = $U->check_perms($requestor->id, $requestor->ws_ou, 'RENEW_CIRC');
1866 if($evt) { $__isrenewal = 0; return $evt; }
1870 # fetch and build the circulation environment
1871 ( $ctx, $evt ) = create_circ_ctx( %$params,
1873 requestor => $requestor,
1876 #fetch_patron_circ_summary => 1,
1877 fetch_copy_statuses => 1,
1878 fetch_copy_locations => 1,
1880 if($evt) { $__isrenewal = 0; return $evt; }
1881 $params->{_ctx} = $ctx;
1883 # make sure they have some renewals left and make sure the circulation exists
1884 ($circ, $evt) = _check_renewal_remaining($ctx);
1885 if($evt) { $__isrenewal = 0; return $evt; }
1886 $ctx->{old_circ} = $circ;
1887 my $renewals = $circ->renewal_remaining - 1;
1889 # run the renew permit script
1890 $evt = _run_renew_scripts($ctx);
1891 if($evt) { $__isrenewal = 0; return $evt; }
1894 #$ctx->{patron} = $ctx->{patron}->id;
1895 $evt = $self->generic_receive($client, $authtoken, $ctx );
1896 #{ barcode => $params->{barcode}, patron => $params->{patron}} );
1898 if( !$U->event_equals($evt, 'SUCCESS') ) {
1899 $__isrenewal = 0; return $evt;
1902 # re-fetch the context since objects have changed in the checkin
1903 ( $ctx, $evt ) = create_circ_ctx( %$params,
1905 requestor => $requestor,
1908 #fetch_patron_circ_summary => 1,
1909 fetch_copy_statuses => 1,
1910 fetch_copy_locations => 1,
1912 if($evt) { $__isrenewal = 0; return $evt; }
1913 $params->{_ctx} = $ctx;
1914 $ctx->{renewal_remaining} = $renewals;
1916 # run the circ permit scripts
1917 if( $ctx->{permit_override} ) {
1918 $evt = $U->check_perms(
1919 $requestor->id, $ctx->{copy}->circ_lib->id, 'CIRC_PERMIT_OVERRIDE');
1920 if($evt) { $__isrenewal = 0; return $evt; }
1923 $evt = $self->permit_circ( $client, $authtoken, $params );
1924 if( $U->event_equals($evt, 'ITEM_NOT_CATALOGED')) {
1925 #$ctx->{precat} = 1;
1926 $params->{precat} = 1;
1929 if(!$U->event_equals($evt, 'SUCCESS')) {
1930 if($evt) { $__isrenewal = 0; return $evt; }
1933 $params->{permit_key} = $evt->{payload};
1937 # checkout the item again
1938 $params->{patron} = $ctx->{patron}->id;
1939 $evt = $self->checkout($client, $authtoken, $params );
1941 $logger->activity("user ".$requestor->id." renewl of item ".
1942 $ctx->{copy}->barcode." completed with event ".$evt->{textcode});
1948 sub _check_renewal_remaining {
1951 my( $circ, $evt ) = $U->fetch_open_circulation($ctx->{copy}->id);
1952 return (undef, $evt) if $evt;
1953 $evt = OpenILS::Event->new(
1954 'MAX_RENEWALS_REACHED') if $circ->renewal_remaining < 1;
1955 return ($circ, $evt);
1958 sub _run_renew_scripts {
1960 my $runner = $ctx->{runner};
1963 $runner->load($scripts{circ_permit_renew});
1964 $runner->run or throw OpenSRF::EX::ERROR ("Circ Permit Renew Script Died: $@");
1966 my $events = $runner->retrieve('result.events');
1967 $events = [ split(/,/, $events) ];
1968 $logger->activity("circ_permit_renew for user ".
1969 $ctx->{patron}->id." returned events: @$events") if @$events;
1972 push( @allevents, OpenILS::Event->new($_)) for @$events;
1973 return \@allevents if @allevents;