1 package OpenILS::Application::Circ::Circulate;
2 use base 'OpenSRF::Application';
3 use strict; use warnings;
4 use OpenSRF::EX qw(:try);
7 use OpenSRF::Utils::Cache;
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 $Data::Dumper::Indent = 0;
17 my $apputils = "OpenILS::Application::AppUtils";
19 my $holdcode = "OpenILS::Application::Circ::Holds";
20 my $transcode = "OpenILS::Application::Circ::Transit";
22 my %scripts; # - circulation script filenames
23 my $script_libs; # - any additional script libraries
24 my %cache; # - db objects cache
25 my %contexts; # - Script runner contexts
26 my $cache_handle; # - memcache handle
28 sub PRECAT_FINE_LEVEL { return 2; }
29 sub PRECAT_LOAN_DURATION { return 2; }
32 # for security, this is a process-defined and not
33 # a client-defined variable
37 # ------------------------------------------------------------------------------
38 # Load the circ script from the config
39 # ------------------------------------------------------------------------------
43 $cache_handle = OpenSRF::Utils::Cache->new('global');
44 my $conf = OpenSRF::Utils::SettingsClient->new;
45 my @pfx2 = ( "apps", "open-ils.circ","app_settings" );
46 my @pfx = ( @pfx2, "scripts" );
48 my $p = $conf->config_value( @pfx, 'circ_permit_patron' );
49 my $c = $conf->config_value( @pfx, 'circ_permit_copy' );
50 my $d = $conf->config_value( @pfx, 'circ_duration' );
51 my $f = $conf->config_value( @pfx, 'circ_recurring_fines' );
52 my $m = $conf->config_value( @pfx, 'circ_max_fines' );
53 my $pr = $conf->config_value( @pfx, 'circ_permit_renew' );
54 my $lb = $conf->config_value( @pfx2, 'script_path' );
56 $logger->error( "Missing circ script(s)" )
57 unless( $p and $c and $d and $f and $m and $pr );
59 $scripts{circ_permit_patron} = $p;
60 $scripts{circ_permit_copy} = $c;
61 $scripts{circ_duration} = $d;
62 $scripts{circ_recurring_fines}= $f;
63 $scripts{circ_max_fines} = $m;
64 $scripts{circ_permit_renew} = $pr;
66 $lb = [ $lb ] unless ref($lb);
69 $logger->debug("Loaded rules scripts for circ: " .
70 "circ permit patron: $p, circ permit copy: $c, ".
71 "circ duration :$d , circ recurring fines : $f, " .
72 "circ max fines : $m, circ renew permit : $pr");
76 # ------------------------------------------------------------------------------
77 # Loads the necessary circ objects and pushes them into the script environment
78 # Returns ( $data, $evt ). if $evt is defined, then an
79 # unexpedted event occurred and should be dealt with / returned to the caller
80 # ------------------------------------------------------------------------------
88 $evt = _ctx_add_patron_objects($ctx, %params);
89 return (undef,$evt) if $evt;
91 if(!$params{noncat}) {
92 if( $evt = _ctx_add_copy_objects($ctx, %params) ) {
93 $ctx->{precat} = 1 if($evt->{textcode} eq 'COPY_NOT_FOUND')
95 $ctx->{precat} = 1 if ( $ctx->{copy}->call_number == -1 ); # special case copy
99 _doctor_patron_object($ctx) if $ctx->{patron};
100 _doctor_copy_object($ctx) if $ctx->{copy};
102 if(!$ctx->{no_runner}) {
103 _build_circ_script_runner($ctx);
104 _add_script_runner_methods($ctx);
110 sub _ctx_add_patron_objects {
111 my( $ctx, %params) = @_;
114 if(!defined($cache{patron_standings})) {
115 $cache{patron_standings} = $U->fetch_patron_standings();
116 $cache{group_tree} = $U->fetch_permission_group_tree();
119 $ctx->{patron_standings} = $cache{patron_standings};
120 $ctx->{group_tree} = $cache{group_tree};
122 $ctx->{patron_circ_summary} =
123 $U->fetch_patron_circ_summary($ctx->{patron}->id)
124 if $params{fetch_patron_circsummary};
130 sub _find_copy_by_attr {
135 my $copy = $params{copy} || undef;
140 $U->fetch_copy($params{copyid}) if $params{copyid};
141 return (undef,$evt) if $evt;
145 $U->fetch_copy_by_barcode( $params{barcode} ) if $params{barcode};
146 return (undef,$evt) if $evt;
149 return ( $copy, $evt );
152 sub _ctx_add_copy_objects {
153 my($ctx, %params) = @_;
158 $cache{copy_statuses} = $U->fetch_copy_statuses
159 if( $params{fetch_copy_statuses} and !defined($cache{copy_statuses}) );
161 $cache{copy_locations} = $U->fetch_copy_locations
162 if( $params{fetch_copy_locations} and !defined($cache{copy_locations}));
164 $ctx->{copy_statuses} = $cache{copy_statuses};
165 $ctx->{copy_locations} = $cache{copy_locations};
167 ($copy, $evt) = _find_copy_by_attr(%params);
170 if( $copy and !$ctx->{title} ) {
171 $logger->debug("Copy status: " . $copy->status);
172 ( $ctx->{title}, $evt ) = $U->fetch_record_by_copy( $copy->id );
174 $ctx->{copy} = $copy;
181 # ------------------------------------------------------------------------------
182 # Fleshes parts of the patron object
183 # ------------------------------------------------------------------------------
184 sub _doctor_copy_object {
187 my $copy = $ctx->{copy} || return undef;
189 $logger->debug("Doctoring copy object...");
191 # set the copy status to a status name
192 $copy->status( _get_copy_status( $copy, $ctx->{copy_statuses} ) );
194 # set the copy location to the location object
195 $copy->location( _get_copy_location( $copy, $ctx->{copy_locations} ) );
197 $copy->circ_lib( $U->fetch_org_unit($copy->circ_lib) );
201 # ------------------------------------------------------------------------------
202 # Fleshes parts of the patron object
203 # ------------------------------------------------------------------------------
204 sub _doctor_patron_object {
207 my $patron = $ctx->{patron} || return undef;
209 # push the standing object into the patron
210 if(ref($ctx->{patron_standings})) {
211 for my $s (@{$ctx->{patron_standings}}) {
212 if( $s->id eq $ctx->{patron}->standing ) {
213 $patron->standing($s);
214 $logger->debug("Set patron standing to ". $s->value);
219 # set the patron ptofile to the profile name
220 $patron->profile( _get_patron_profile(
221 $patron, $ctx->{group_tree} ) ) if $ctx->{group_tree};
225 $U->fetch_org_unit( $patron->home_ou ) ) if $patron;
229 # recurse and find the patron profile name from the tree
230 # another option would be to grab the groups for the patron
231 # and cycle through those until the "profile" group has been found
232 sub _get_patron_profile {
233 my( $patron, $group_tree ) = @_;
234 return $group_tree if ($group_tree->id eq $patron->profile);
235 return undef unless ($group_tree->children);
237 for my $child (@{$group_tree->children}) {
238 my $ret = _get_patron_profile( $patron, $child );
244 sub _get_copy_status {
245 my( $copy, $cstatus ) = @_;
248 for my $status (@$cstatus) {
249 $s = $status if( $status->id eq $copy->status )
251 $logger->debug("Retrieving copy status: " . $s->name) if $s;
255 sub _get_copy_location {
256 my( $copy, $locations ) = @_;
259 for my $loc (@$locations) {
260 $l = $loc if $loc->id eq $copy->location;
262 $logger->debug("Retrieving copy location: " . $l->name ) if $l;
267 # ------------------------------------------------------------------------------
268 # Constructs and shoves data into the script environment
269 # ------------------------------------------------------------------------------
270 sub _build_circ_script_runner {
274 $logger->debug("Loading script environment for circulation");
277 if( $runner = $contexts{$ctx->{type}} ) {
278 $runner->refresh_context;
280 $runner = OpenILS::Utils::ScriptRunner->new;
281 $contexts{type} = $runner;
285 $logger->debug("Loading circ script lib path $_");
286 $runner->add_path( $_ );
289 # Note: inserting the number 0 into the script turns into the
290 # string "0", and thus evaluates to true in JS land
291 # inserting undef will insert "", which evaluates to false
293 $runner->insert( 'environment.patron', $ctx->{patron}, 1);
294 $runner->insert( 'environment.title', $ctx->{title}, 1);
295 $runner->insert( 'environment.copy', $ctx->{copy}, 1);
298 $runner->insert( 'result', {} );
299 $runner->insert( 'result.event', 'SUCCESS' );
302 $runner->insert('environment.isRenewal', 1);
304 $runner->insert('environment.isRenewal', undef);
307 if($ctx->{ishold} ) {
308 $runner->insert('environment.isHold', 1);
310 $runner->insert('environment.isHold', undef)
313 if( $ctx->{noncat} ) {
314 $runner->insert('environment.isNonCat', 1);
315 $runner->insert('environment.nonCatType', $ctx->{noncat_type});
317 $runner->insert('environment.isNonCat', undef);
320 if(ref($ctx->{patron_circ_summary})) {
321 $runner->insert( 'environment.patronItemsOut', $ctx->{patron_circ_summary}->[0], 1 );
322 $runner->insert( 'environment.patronFines', $ctx->{patron_circ_summary}->[1], 1 );
325 $ctx->{runner} = $runner;
330 sub _add_script_runner_methods {
333 my $runner = $ctx->{runner};
337 # allows a script to fetch a hold that is currently targeting the
339 $runner->insert_method( 'environment.copy', '__OILS_FUNC_fetch_hold', sub {
341 my $hold = $holdcode->fetch_related_holds($ctx->{copy}->id);
342 $hold = undef unless $hold;
343 $runner->insert( $key, $hold, 1 );
349 # ------------------------------------------------------------------------------
351 __PACKAGE__->register_method(
352 method => "permit_circ",
353 api_name => "open-ils.circ.checkout.permit",
355 Determines if the given checkout can occur
356 @param authtoken The login session key
357 @param params A trailing hash of named params including
358 barcode : The copy barcode,
359 patron : The patron the checkout is occurring for,
360 renew : true or false - whether or not this is a renewal
361 @return The event that occurred during the permit check.
365 my( $self, $client, $authtoken, $params ) = @_;
368 my ( $requestor, $patron, $ctx, $evt, $circ );
370 # check permisson of the requestor
371 ( $requestor, $patron, $evt ) =
372 $U->checkses_requestor(
373 $authtoken, $params->{patron}, 'VIEW_PERMIT_CHECKOUT' );
376 # fetch and build the circulation environment
377 if( !( $ctx = $params->{_ctx}) ) {
379 ( $ctx, $evt ) = create_circ_ctx( %$params,
381 requestor => $requestor,
383 fetch_patron_circ_summary => 1,
384 fetch_copy_statuses => 1,
385 fetch_copy_locations => 1,
390 if( !$ctx->{ishold} and !$__isrenewal and $ctx->{copy} ) {
391 ($circ, $evt) = $U->fetch_open_circulation($ctx->{copy}->id);
392 return OpenILS::Event->new('OPEN_CIRCULATION_EXISTS') if $circ;
395 return _run_permit_scripts($ctx);
399 __PACKAGE__->register_method(
400 method => "check_title_hold",
401 api_name => "open-ils.circ.title_hold.is_possible",
403 Determines if a hold were to be placed by a given user,
404 whether or not said hold would have any potential copies
406 @param authtoken The login session key
407 @param params A hash of named params including:
408 patronid - the id of the hold recipient
409 titleid (brn) - the id of the title to be held
410 depth - the hold range depth (defaults to 0)
413 sub check_title_hold {
414 my( $self, $client, $authtoken, $params ) = @_;
415 my %params = %$params;
416 my $titleid = $params{titleid};
418 my ( $requestor, $patron, $evt ) = $U->checkses_requestor(
419 $authtoken, $params{patronid}, 'VIEW_HOLD_PERMIT' );
422 my $rangelib = $patron->home_ou;
423 my $depth = $params{depth} || 0;
425 $logger->debug("Fetching ranged title tree for title $titleid, org $rangelib, depth $depth");
428 my $org = $U->simplereq(
430 'open-ils.actor.org_unit.retrieve',
431 $authtoken, $requestor->home_ou );
437 while( $title = $U->storagereq(
438 'open-ils.storage.biblio.record_entry.ranged_tree',
439 $titleid, $rangelib, $depth, $limit, $offset ) ) {
441 last unless ref($title);
443 for my $cn (@{$title->call_numbers}) {
445 $logger->debug("Checking callnumber ".$cn->id." for hold fulfillment possibility");
447 for my $copy (@{$cn->copies}) {
449 $logger->debug("Checking copy ".$copy->id." for hold fulfillment possibility");
451 return 1 if OpenILS::Utils::PermitHold::permit_copy_hold(
453 requestor => $requestor,
456 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
457 request_lib => $org } );
459 $logger->debug("Copy ".$copy->id." for hold fulfillment possibility failed...");
471 # Runs the patron and copy permit scripts
472 # if this is a non-cat circulation, the copy permit script
474 sub _run_permit_scripts {
476 my $runner = $ctx->{runner};
477 my $patronid = $ctx->{patron}->id;
478 my $barcode = ($ctx->{copy}) ? $ctx->{copy}->barcode : undef;
481 $runner->load($scripts{circ_permit_patron});
482 $runner->run or throw OpenSRF::EX::ERROR ("Circ Permit Patron Script Died: $@");
483 my $evtname = $runner->retrieve('result.event');
484 $logger->activity("circ_permit_patron for user $patronid returned event: $evtname");
486 return OpenILS::Event->new($evtname) if $evtname ne 'SUCCESS';
488 my $key = _cache_permit_key();
490 if( $ctx->{noncat} ) {
491 $logger->debug("Exiting circ permit early because item is a non-cataloged item");
492 return OpenILS::Event->new('SUCCESS', payload => $key);
496 $logger->debug("Exiting circ permit early because copy is pre-cataloged");
497 return OpenILS::Event->new('ITEM_NOT_CATALOGED', payload => $key);
501 $logger->debug("Exiting circ permit early because request is for hold patron permit");
502 return OpenILS::Event->new('SUCCESS');
505 $runner->load($scripts{circ_permit_copy});
506 $runner->run or throw OpenSRF::EX::ERROR ("Circ Permit Copy Script Died: $@");
507 $evtname = $runner->retrieve('result.event');
508 $logger->activity("circ_permit_copy for user $patronid ".
509 "and copy $barcode returned event: $evtname");
511 return OpenILS::Event->new($evtname, payload => $key) if( $evtname eq 'SUCCESS' );
512 return OpenILS::Event->new($evtname);
515 # takes copyid, patronid, and requestor id
516 sub _cache_permit_key {
517 my $key = md5_hex( time() . rand() . "$$" );
518 $logger->debug("Setting circ permit key to $key");
519 $cache_handle->put_cache( "oils_permit_key_$key", 1, 300 );
523 sub _check_permit_key {
525 $logger->debug("Fetching circ permit key $key");
526 my $k = "oils_permit_key_$key";
527 my $one = $cache_handle->get_cache($k);
528 $cache_handle->delete_cache($k);
529 return ($one) ? 1 : 0;
533 # ------------------------------------------------------------------------------
535 __PACKAGE__->register_method(
536 method => "checkout",
537 api_name => "open-ils.circ.checkout",
540 @param authtoken The login session key
541 @param params A named hash of params including:
543 barcode If no copy is provided, the copy is retrieved via barcode
544 copyid If no copy or barcode is provide, the copy id will be use
545 patron The patron's id
546 noncat True if this is a circulation for a non-cataloted item
547 noncat_type The non-cataloged type id
548 noncat_circ_lib The location for the noncat circ.
549 precat The item has yet to be cataloged
550 dummy_title The temporary title of the pre-cataloded item
551 dummy_author The temporary authr of the pre-cataloded item
552 Default is the home org of the staff member
553 @return The SUCCESS event on success, any other event depending on the error
557 my( $self, $client, $authtoken, $params ) = @_;
560 my ( $requestor, $patron, $ctx, $evt, $circ, $copy );
561 my $key = $params->{permit_key};
563 # if this is a renewal, then the requestor does not have to
564 # have checkout privelages
565 ( $requestor, $evt ) = $U->checkses($authtoken) if $__isrenewal;
566 ( $requestor, $evt ) = $U->checksesperm( $authtoken, 'COPY_CHECKOUT' ) unless $__isrenewal;
568 $logger->debug("REQUESTOR event: " . ref($requestor));
571 ( $patron, $evt ) = $U->fetch_user($params->{patron});
575 # set the circ lib to the home org of the requestor if not specified
576 my $circlib = (defined($params->{circ_lib})) ?
577 $params->{circ_lib} : $requestor->home_ou;
579 # if this is a non-cataloged item, check it out and return
580 return _checkout_noncat(
581 $key, $requestor, $patron, %$params ) if $params->{noncat};
583 # if this item has yet to be cataloged, make sure a dummy copy exists
584 ( $params->{copy}, $evt ) = _make_precat_copy(
585 $requestor, $circlib, $params ) if $params->{precat};
588 # fetch and build the circulation environment
589 if( !( $ctx = $params->{_ctx}) ) {
590 ( $ctx, $evt ) = create_circ_ctx( %$params,
592 requestor => $requestor,
593 session => $U->start_db_session(),
595 fetch_patron_circ_summary => 1,
596 fetch_copy_statuses => 1,
597 fetch_copy_locations => 1,
601 $ctx->{session} = $U->start_db_session() unless $ctx->{session};
603 my $cid = ($params->{precat}) ? -1 : $ctx->{copy}->id;
604 return OpenILS::Event->new('CIRC_PERMIT_BAD_KEY')
605 unless _check_permit_key($key);
607 $ctx->{circ_lib} = $circlib;
609 $evt = _run_checkout_scripts($ctx);
612 _build_checkout_circ_object($ctx);
614 $evt = _commit_checkout_circ_object($ctx);
617 $evt = _update_checkout_copy($ctx);
621 ($holds, $evt) = _handle_related_holds($ctx);
625 $logger->debug("Checkin committing objects with session thread trace: ".$ctx->{session}->session_id);
626 $U->commit_db_session($ctx->{session});
627 my $record = $U->record_to_mvr($ctx->{title}) unless $ctx->{precat};
629 return OpenILS::Event->new('SUCCESS',
631 copy => $U->unflesh_copy($ctx->{copy}),
632 circ => $ctx->{circ},
634 holds_fulfilled => $holds,
639 sub _make_precat_copy {
640 my ( $requestor, $circlib, $params ) = @_;
642 my( $copy, undef ) = _find_copy_by_attr(%$params);
645 $logger->debug("Pre-cat copy already exists in checkout: ID=" . $copy->id);
646 return ($copy, undef);
649 $logger->debug("Creating a new precataloged copy in checkout with barcode " . $params->{barcode});
651 my $evt = OpenILS::Event->new(
652 'BAD_PARAMS', desc => "Dummy title or author not provided" )
653 unless ( $params->{dummy_title} and $params->{dummy_author} );
654 return (undef, $evt) if $evt;
656 $copy = Fieldmapper::asset::copy->new;
657 $copy->circ_lib($circlib);
658 $copy->creator($requestor->id);
659 $copy->editor($requestor->id);
660 $copy->barcode($params->{barcode});
661 $copy->call_number(-1); #special CN for precat materials
662 $copy->loan_duration(&PRECAT_LOAN_DURATION); # these two should come from constants
663 $copy->fine_level(&PRECAT_FINE_LEVEL);
665 $copy->dummy_title($params->{dummy_title});
666 $copy->dummy_author($params->{dummy_author});
668 my $id = $U->storagereq(
669 'open-ils.storage.direct.asset.copy.create', $copy );
670 return (undef, $U->DB_UPDATE_FAILED($copy)) unless $copy;
672 $logger->debug("Pre-cataloged copy successfully created");
673 return $U->fetch_copy($id);
677 sub _run_checkout_scripts {
683 my $runner = $ctx->{runner};
685 $runner->insert('result.durationLevel');
686 $runner->insert('result.durationRule');
687 $runner->insert('result.recurringFinesRule');
688 $runner->insert('result.recurringFinesLevel');
689 $runner->insert('result.maxFine');
691 $runner->load($scripts{circ_duration});
692 $runner->run or throw OpenSRF::EX::ERROR ("Circ Duration Script Died: $@");
693 my $duration = $runner->retrieve('result.durationRule');
694 $logger->debug("Circ duration script yielded a duration rule of: $duration");
696 $runner->load($scripts{circ_recurring_fines});
697 $runner->run or throw OpenSRF::EX::ERROR ("Circ Recurring Fines Script Died: $@");
698 my $recurring = $runner->retrieve('result.recurringFinesRule');
699 $logger->debug("Circ recurring fines script yielded a rule of: $recurring");
701 $runner->load($scripts{circ_max_fines});
702 $runner->run or throw OpenSRF::EX::ERROR ("Circ Max Fine Script Died: $@");
703 my $max_fine = $runner->retrieve('result.maxFine');
704 $logger->debug("Circ max_fine fines script yielded a rule of: $max_fine");
706 ($duration, $evt) = $U->fetch_circ_duration_by_name($duration);
708 ($recurring, $evt) = $U->fetch_recurring_fine_by_name($recurring);
710 ($max_fine, $evt) = $U->fetch_max_fine_by_name($max_fine);
713 $ctx->{duration_level} = $runner->retrieve('result.durationLevel');
714 $ctx->{recurring_fines_level} = $runner->retrieve('result.recurringFinesLevel');
715 $ctx->{duration_rule} = $duration;
716 $ctx->{recurring_fines_rule} = $recurring;
717 $ctx->{max_fine_rule} = $max_fine;
722 sub _build_checkout_circ_object {
726 my $circ = new Fieldmapper::action::circulation;
727 my $duration = $ctx->{duration_rule};
728 my $max = $ctx->{max_fine_rule};
729 my $recurring = $ctx->{recurring_fines_rule};
730 my $copy = $ctx->{copy};
731 my $patron = $ctx->{patron};
732 my $dur_level = $ctx->{duration_level};
733 my $rec_level = $ctx->{recurring_fines_level};
735 $circ->duration( $duration->shrt ) if ($dur_level == 1);
736 $circ->duration( $duration->normal ) if ($dur_level == 2);
737 $circ->duration( $duration->extended ) if ($dur_level == 3);
739 $circ->recuring_fine( $recurring->low ) if ($rec_level =~ /low/io);
740 $circ->recuring_fine( $recurring->normal ) if ($rec_level =~ /normal/io);
741 $circ->recuring_fine( $recurring->high ) if ($rec_level =~ /high/io);
743 $circ->duration_rule( $duration->name );
744 $circ->recuring_fine_rule( $recurring->name );
745 $circ->max_fine_rule( $max->name );
746 $circ->max_fine( $max->amount );
748 $circ->fine_interval($recurring->recurance_interval);
749 $circ->renewal_remaining( $duration->max_renewals );
750 $circ->target_copy( $copy->id );
751 $circ->usr( $patron->id );
752 $circ->circ_lib( $ctx->{circ_lib} );
755 $logger->debug("Circ is a renewal. Setting renewal_remaining to " . $ctx->{renewal_remaining} );
756 $circ->opac_renewal(1);
757 $circ->renewal_remaining($ctx->{renewal_remaining});
758 $circ->circ_staff($ctx->{requestor}->id);
761 # if a patron is renewing, 'requestor' will be the patron
762 $circ->circ_staff( $ctx->{requestor}->id );
763 _set_circ_due_date($circ);
764 $ctx->{circ} = $circ;
767 sub _create_due_date {
768 my $duration = shift;
771 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
772 gmtime(OpenSRF::Utils->interval_to_seconds($duration) + int(time()));
774 $year += 1900; $mon += 1;
775 my $due_date = sprintf(
776 '%s-%0.2d-%0.2dT%s:%0.2d:%0.s2-00',
777 $year, $mon, $mday, $hour, $min, $sec);
781 sub _set_circ_due_date {
784 my $dd = _create_due_date($circ->duration);
785 $logger->debug("Checkout setting due date on circ to: $dd");
786 $circ->due_date($dd);
789 # Sets the editor, edit_date, un-fleshes the copy, and updates the copy in the DB
790 sub _update_checkout_copy {
793 my $copy = $ctx->{copy};
795 my $s = $U->copy_status_from_name('checked out');
796 $copy->status( $s->id ) if $s;
798 my $evt = $U->update_copy( session => $ctx->{session},
799 copy => $copy, editor => $ctx->{requestor}->id );
800 return (undef,$evt) if $evt;
805 # commits the circ object to the db then fleshes the circ with rules objects
806 sub _commit_checkout_circ_object {
809 my $circ = $ctx->{circ};
813 my $r = $ctx->{session}->request(
814 "open-ils.storage.direct.action.circulation.create", $circ )->gather(1);
816 return $U->DB_UPDATE_FAILED($circ) unless $r;
818 $logger->debug("Created a new circ object in checkout: $r");
821 $circ->duration_rule($ctx->{duration_rule});
822 $circ->max_fine_rule($ctx->{max_fine_rule});
823 $circ->recuring_fine_rule($ctx->{recurring_fines_rule});
829 # sees if there are any holds that this copy
830 sub _handle_related_holds {
833 my $copy = $ctx->{copy};
834 my $patron = $ctx->{patron};
835 my $holds = $holdcode->fetch_related_holds($copy->id);
839 # XXX We should only fulfill one hold here...
840 # XXX If a hold was transited to the user who is checking out
841 # the item, we need to make sure that hold is what's grabbed
842 if(ref($holds) && @$holds) {
844 # for now, just sort by id to get what should be the oldest hold
845 $holds = [ sort { $a->id <=> $b->id } @$holds ];
846 $holds = [ grep { $_->usr eq $patron->id } @$holds ];
849 my $hold = $holds->[0];
851 $logger->debug("Related hold found in checkout: " . $hold->id );
853 $hold->current_copy($copy->id); # just make sure it's set
854 # if the hold was never officially captured, capture it.
855 $hold->capture_time('now') unless $hold->capture_time;
856 $hold->fulfillment_time('now');
857 my $r = $ctx->{session}->request(
858 "open-ils.storage.direct.action.hold_request.update", $hold )->gather(1);
859 return (undef,$U->DB_UPDATE_FAILED( $hold )) unless $r;
860 push( @fulfilled, $hold->id );
864 return (\@fulfilled, undef);
868 sub _checkout_noncat {
869 my ( $key, $requestor, $patron, %params ) = @_;
870 my( $circ, $circlib, $evt );
873 $circlib = $params{noncat_circ_lib} || $requestor->home_ou;
875 return OpenILS::Event->new('CIRC_PERMIT_BAD_KEY')
876 unless _check_permit_key($key);
878 ( $circ, $evt ) = OpenILS::Application::Circ::NonCat::create_non_cat_circ(
879 $requestor->id, $patron->id, $circlib, $params{noncat_type} );
882 return OpenILS::Event->new(
883 'SUCCESS', payload => { noncat_circ => $circ } );
887 __PACKAGE__->register_method(
888 method => "generic_receive",
889 api_name => "open-ils.circ.checkin",
892 Generic super-method for handling all copies
893 @param authtoken The login session key
894 @param params Hash of named parameters including:
895 barcode - The copy barcode
896 force - If true, copies in bad statuses will be checked in and give good statuses
901 sub generic_receive {
902 my( $self, $connection, $authtoken, $params ) = @_;
903 my( $ctx, $requestor, $evt );
905 ( $requestor, $evt ) = $U->checkses($authtoken) if $__isrenewal;
906 ( $requestor, $evt ) = $U->checksesperm(
907 $authtoken, 'COPY_CHECKIN' ) unless $__isrenewal;
910 # load up the circ objects
911 if( !( $ctx = $params->{_ctx}) ) {
912 ( $ctx, $evt ) = create_circ_ctx( %$params,
913 requestor => $requestor,
914 session => $U->start_db_session(),
916 fetch_copy_statuses => 1,
917 fetch_copy_locations => 1,
922 $ctx->{session} = $U->start_db_session() unless $ctx->{session};
923 $ctx->{authtoken} = $authtoken;
924 my $session = $ctx->{session};
926 my $copy = $ctx->{copy};
927 $U->unflesh_copy($copy);
928 return OpenILS::Event->new('COPY_NOT_FOUND') unless $copy;
929 $logger->info("Checkin copy called by user ".$requestor->id." for copy ".$copy->id);
931 return $self->checkin_do_receive($connection, $ctx);
934 sub checkin_do_receive {
936 my( $self, $connection, $ctx ) = @_;
939 my $copy = $ctx->{copy};
940 my $session = $ctx->{session};
941 my $requestor = $ctx->{requestor};
942 my $change = 0; # did we actually do anything?
945 return $evt if ($evt = _checkin_check_copy_status($copy));
948 ($ctx->{circ}, $evt) = $U->fetch_open_circulation($copy->id);
949 return $evt if ($evt and $__isrenewal); # renewals require a circulation
951 ($ctx->{transit}) = $U->fetch_open_transit_by_copy($copy->id);
955 # There is an open circ on this item, close it out.
957 $evt = _checkin_handle_circ($ctx);
960 } elsif( $ctx->{transit} ) {
962 # is this item currently in transit?
964 $evt = $transcode->transit_receive( $copy, $requestor, $session );
965 my $holdtrans = $evt->{holdtransit};
966 ($ctx->{hold}) = $U->fetch_hold($holdtrans->hold) if $holdtrans;
968 if( ! $U->event_equals($evt, 'SUCCESS') ) {
970 # either an error occurred or a ROUTE_ITEM was generated and the
971 # item must be forwarded on to its destination.
972 return _checkin_flesh_event($ctx, $evt);
978 # copy was received as a hold transit. Copy is at target lib
979 # and hold transit is complete. We're done here...
980 $U->commit_db_session($session);
981 return _checkin_flesh_event($ctx, $evt);
987 # ------------------------------------------------------------------------------
988 # Circulations and transits are now closed where necessary. Now go on to see if
989 # this copy can fulfill a hold or needs to be routed to a different location
990 # ------------------------------------------------------------------------------
993 # If it's a renewal, we're done
995 $U->commit_db_session($session);
996 return OpenILS::Event->new('SUCCESS');
1000 # Now, let's see if this copy is needed for a hold
1001 my ($hold) = $holdcode->find_local_hold( $session, $copy, $requestor );
1005 $ctx->{hold} = $hold;
1008 # Capture the hold with this copy
1009 return $evt if ($evt = _checkin_capture_hold($ctx));
1011 if( $hold->pickup_lib == $requestor->home_ou ) {
1013 # This hold was captured in the correct location
1014 $evt = OpenILS::Event->new('SUCCESS');
1018 # Hold needs to be picked up elsewhere. Build a hold
1019 # transit and route the item.
1020 return $evt if ($evt =_checkin_build_hold_transit($ctx));
1021 $evt = OpenILS::Event->new('ROUTE_ITEM', org => $hold->pickup_lib);
1024 } else { # not needed for a hold
1026 if( $copy->circ_lib == $requestor->home_ou ) {
1028 # Copy is in the right place.
1029 $evt = OpenILS::Event->new('SUCCESS');
1031 # if the item happens to be a pre-cataloged item, send it
1032 # to cataloging and return the event
1033 my( $e, $c, $err ) = _checkin_handle_precat($ctx);
1034 return $err if $err;
1040 # Copy wants to go home. Transit it there.
1041 return $evt if ( $evt = _checkin_build_generic_copy_transit($ctx) );
1042 $evt = OpenILS::Event->new('ROUTE_ITEM', org => $copy->circ_lib);
1047 $logger->info("Copy checkin finished with event: ".$evt->{textcode});
1051 $evt = OpenILS::Event->new('NO_CHANGE');
1052 ($ctx->{hold}) = $U->fetch_open_hold_by_copy($copy->id)
1053 if ($copy->status == $U->copy_status_from_name('on holds shelf')->id);
1057 $U->commit_db_session($session);
1060 return _checkin_flesh_event($ctx, $evt);
1063 # returns (ITEM_NOT_CATALOGED, change_occurred, $error_event) where necessary
1064 sub _checkin_handle_precat {
1067 my $copy = $ctx->{copy};
1072 my $catstat = $U->copy_status_from_name('cataloging');
1074 if( $ctx->{precat} ) {
1076 $evt = OpenILS::Event->new('ITEM_NOT_CATALOGED');
1078 if( $copy->status != $catstat->id ) {
1079 $copy->status($catstat->id);
1081 return (undef, 0, $errevt) if (
1082 $errevt = $U->update_copy(
1084 editor => $ctx->{requestor}->id,
1085 session => $ctx->{session} ));
1091 return ($evt, $change, undef);
1095 sub _checkin_check_copy_status {
1097 my $stat = (ref($copy->status)) ? $copy->status->id : $copy->status;
1098 my $evt = OpenILS::Event->new('COPY_BAD_STATUS', payload => $copy );
1099 return $evt if ($stat == $U->copy_status_from_name('lost')->id);
1100 return $evt if ($stat == $U->copy_status_from_name('missing')->id);
1104 # Just gets the copy back home. Returns undef on success, event on error
1105 sub _checkin_build_generic_copy_transit {
1108 my $requestor = $ctx->{requestor};
1109 my $copy = $ctx->{copy};
1110 my $transit = Fieldmapper::action::transit_copy->new;
1111 my $session = $ctx->{session};
1113 $logger->activity("User ". $requestor->id ." creating a ".
1114 " new copy transit for copy ".$copy->id." to org ".$copy->circ_lib);
1116 $transit->source($requestor->home_ou);
1117 $transit->dest($copy->circ_lib);
1118 $transit->target_copy($copy->id);
1119 $transit->source_send_time('now');
1120 $transit->copy_status($copy->status);
1122 $logger->debug("Creating new copy_transit in DB");
1124 my $s = $session->request(
1125 "open-ils.storage.direct.action.transit_copy.create", $transit )->gather(1);
1126 return $U->DB_UPDATE_FAILED($transit) unless $s;
1128 $logger->info("Checkin copy successfully created new transit: $s");
1130 $copy->status($U->copy_status_from_name('in transit')->id );
1132 return $U->update_copy( copy => $copy,
1133 editor => $requestor->id, session => $session );
1138 # returns event on error, undef on success
1139 sub _checkin_build_hold_transit {
1142 my $copy = $ctx->{copy};
1143 my $hold = $ctx->{hold};
1144 my $trans = Fieldmapper::action::hold_transit_copy->new;
1146 $trans->hold($hold->id);
1147 $trans->source($ctx->{requestor}->home_ou);
1148 $trans->dest($hold->pickup_lib);
1149 $trans->source_send_time("now");
1150 $trans->target_copy($copy->id);
1151 $trans->copy_status($copy->status);
1153 my $id = $ctx->{session}->request(
1154 "open-ils.storage.direct.action.hold_transit_copy.create", $trans )->gather(1);
1155 return $U->DB_UPDATE_FAILED($trans) unless $id;
1157 $logger->info("Checkin copy successfully created hold transit: $id");
1159 $copy->status($U->copy_status_from_name('in transit')->id );
1160 return $U->update_copy( copy => $copy,
1161 editor => $ctx->{requestor}->id, session => $ctx->{session} );
1164 # Returns event on error, undef on success
1165 sub _checkin_capture_hold {
1167 my $copy = $ctx->{copy};
1168 my $hold = $ctx->{hold};
1170 $logger->debug("Checkin copy capturing hold ".$hold->id);
1172 $hold->current_copy($copy->id);
1173 $hold->capture_time('now');
1175 my $stat = $ctx->{session}->request(
1176 "open-ils.storage.direct.action.hold_request.update", $hold)->gather(1);
1177 return $U->DB_UPDATE_FAILED($hold) unless $stat;
1179 $copy->status( $U->copy_status_from_name('on holds shelf')->id );
1181 return $U->update_copy( copy => $copy,
1182 editor => $ctx->{requestor}->id, session => $ctx->{session} );
1185 # fleshes an event with the relevant objects from the context
1186 sub _checkin_flesh_event {
1191 $payload->{copy} = $U->unflesh_copy($ctx->{copy});
1192 $payload->{record} = $U->record_to_mvr($ctx->{title}) if($ctx->{title} and !$ctx->{precat});
1193 $payload->{circ} = $ctx->{circ} if $ctx->{circ};
1194 $payload->{transit} = $ctx->{transit} if $ctx->{transit};
1195 $payload->{hold} = $ctx->{hold} if $ctx->{hold};
1197 $evt->{payload} = $payload;
1202 # Closes out the circulation, puts the copy into reshelving.
1203 # Voids any bills attached to this circ after the backdate time
1204 # if a backdate is provided
1205 sub _checkin_handle_circ {
1209 my $circ = $ctx->{circ};
1210 my $copy = $ctx->{copy};
1211 my $requestor = $ctx->{requestor};
1212 my $session = $ctx->{session};
1214 $logger->info("Handling circulation [".$circ->id."] found in checkin...");
1216 $ctx->{longoverdue} = 1 if ($circ->stop_fines =~ /longoverdue/io);
1217 $ctx->{claimsreturned} = 1 if ($circ->stop_fines =~ /claimsreturned/io);
1219 my ( $obt, $evt ) = $U->fetch_open_billable_transaction($circ->id);
1220 return $evt if $evt;
1222 $circ->stop_fines('CHECKIN');
1223 $circ->stop_fines('RENEW') if $__isrenewal;
1224 $circ->stop_fines('LOST') if($__islost);
1225 $circ->xact_finish('now') if($obt->balance_owed <= 0 and !$__islost);
1226 $circ->stop_fines_time('now');
1227 $circ->checkin_time('now');
1228 $circ->checkin_staff($requestor->id);
1230 if(my $backdate = $ctx->{backdate}) {
1231 return $evt if ($evt =
1232 _checkin_handle_backdate($backdate, $circ, $requestor, $session));
1235 $logger->info("Checkin copy setting status to 'reshelving' and committing...");
1236 $copy->status($U->copy_status_from_name('reshelving')->id);
1237 $evt = $U->update_copy( session => $session,
1238 copy => $copy, editor => $requestor->id );
1239 return $evt if $evt;
1241 $ctx->{session}->request(
1242 'open-ils.storage.direct.action.circulation.update', $circ )->gather(1);
1247 # returns event on error, undef on success
1248 # This voids all bills attached to the given circulation that occurred
1249 # after the backdate
1250 sub _checkin_handle_backdate {
1251 my( $backdate, $circ, $requestor, $session ) = @_;
1253 $logger->activity("User ".$requestor->id.
1254 " backdating checkin copy [".$circ->target_copy."] to date: $backdate");
1256 $circ->xact_finish($backdate);
1258 my $bills = $session->request( # XXX Verify this call is correct
1259 "open-ils.storage.direct.money.billing.search_where.atomic",
1260 billing_ts => { ">=" => $backdate }, "xact" => $circ->id )->gather(1);
1263 for my $bill (@$bills) {
1265 my $s = $session->request(
1266 "open-ils.storage.direct.money.billing.update", $bill)->gather(1);
1267 return $U->DB_UPDATE_FAILED($bill) unless $s;
1276 # ------------------------------------------------------------------------------
1278 __PACKAGE__->register_method(
1280 api_name => "open-ils.circ.renew",
1281 notes => <<" NOTES");
1282 PARAMS( authtoken, circ => circ_id );
1283 open-ils.circ.renew(login_session, circ_object);
1284 Renews the provided circulation. login_session is the requestor of the
1285 renewal and if the logged in user is not the same as circ->usr, then
1286 the logged in user must have RENEW_CIRC permissions.
1290 my( $self, $client, $authtoken, $params ) = @_;
1293 my ( $requestor, $patron, $ctx, $evt, $circ, $copy );
1296 # if requesting a renewal for someone else, you must have
1298 ( $requestor, $patron, $evt ) = $U->checkses_requestor(
1299 $authtoken, $params->{patron}, 'RENEW_CIRC' );
1300 if($evt) { $__isrenewal = 0; return $evt; }
1303 # fetch and build the circulation environment
1304 ( $ctx, $evt ) = create_circ_ctx( %$params,
1306 requestor => $requestor,
1309 fetch_patron_circ_summary => 1,
1310 fetch_copy_statuses => 1,
1311 fetch_copy_locations => 1,
1313 if($evt) { $__isrenewal = 0; return $evt; }
1314 $params->{_ctx} = $ctx;
1316 # make sure they have some renewals left and make sure the circulation exists
1317 ($circ, $evt) = _check_renewal_remaining($ctx);
1318 if($evt) { $__isrenewal = 0; return $evt; }
1319 $ctx->{old_circ} = $circ;
1320 my $renewals = $circ->renewal_remaining - 1;
1322 # run the renew permit script
1323 $evt = _run_renew_scripts($ctx);
1324 if($evt) { $__isrenewal = 0; return $evt; }
1327 #$ctx->{patron} = $ctx->{patron}->id;
1328 $evt = $self->generic_receive($client, $authtoken, $ctx );
1329 #{ barcode => $params->{barcode}, patron => $params->{patron}} );
1331 if( !$U->event_equals($evt, 'SUCCESS') ) {
1332 $__isrenewal = 0; return $evt;
1335 # re-fetch the context since objects have changed in the checkin
1336 ( $ctx, $evt ) = create_circ_ctx( %$params,
1338 requestor => $requestor,
1341 fetch_patron_circ_summary => 1,
1342 fetch_copy_statuses => 1,
1343 fetch_copy_locations => 1,
1345 if($evt) { $__isrenewal = 0; return $evt; }
1346 $params->{_ctx} = $ctx;
1347 $ctx->{renewal_remaining} = $renewals;
1349 # run the circ permit scripts
1350 $evt = $self->permit_circ( $client, $authtoken, $params );
1351 if( $U->event_equals($evt, 'ITEM_NOT_CATALOGED')) {
1354 if(!$U->event_equals($evt, 'SUCCESS')) {
1355 if($evt) { $__isrenewal = 0; return $evt; }
1358 $params->{permit_key} = $evt->{payload};
1361 # checkout the item again
1362 $evt = $self->checkout($client, $authtoken, $params );
1368 sub _check_renewal_remaining {
1371 my( $circ, $evt ) = $U->fetch_open_circulation($ctx->{copy}->id);
1372 return (undef, $evt) if $evt;
1373 $evt = OpenILS::Event->new(
1374 'MAX_RENEWALS_REACHED') if $circ->renewal_remaining < 1;
1375 return ($circ, $evt);
1378 sub _run_renew_scripts {
1380 my $runner = $ctx->{runner};
1383 $runner->load($scripts{circ_permit_renew});
1384 $runner->run or throw OpenSRF::EX::ERROR ("Circ Permit Renew Script Died: $@");
1385 my $evtname = $runner->retrieve('result.event');
1386 $logger->activity("circ_permit_renew for user ".$ctx->{patron}->id." returned event: $evtname");
1388 return OpenILS::Event->new($evtname) if $evtname ne 'SUCCESS';