1 package OpenILS::Application::AppUtils;
2 use strict; use warnings;
4 use MARC::File::XML (BinaryEncoding => 'utf8', RecordFormat => 'USMARC');
5 use OpenILS::Application;
6 use base qw/OpenILS::Application/;
7 use OpenSRF::Utils::Cache;
8 use OpenSRF::Utils::Logger qw/$logger/;
9 use OpenILS::Utils::ModsParser;
10 use OpenSRF::EX qw(:try);
13 use OpenILS::Utils::CStoreEditor;
14 use OpenILS::Const qw/:const/;
15 use Unicode::Normalize;
16 use OpenSRF::Utils::SettingsClient;
20 use DateTime::Format::ISO8601;
21 use List::MoreUtils qw/uniq/;
22 use Digest::MD5 qw(md5_hex);
24 # ---------------------------------------------------------------------------
25 # Pile of utilty methods used accross applications.
26 # ---------------------------------------------------------------------------
27 my $cache_client = "OpenSRF::Utils::Cache";
29 # ---------------------------------------------------------------------------
30 # on sucess, returns the created session, on failure throws ERROR exception
31 # ---------------------------------------------------------------------------
32 sub start_db_session {
35 my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
36 my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
38 my $trans_resp = $trans_req->recv();
39 if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
40 if( ! $trans_resp->content() ) {
42 ("Unable to Begin Transaction with database" );
46 $logger->debug("Setting global storage session to ".
47 "session: " . $session->session_id . " : " . $session->app );
55 my $authtoken = shift;
59 my $audit_req = $session->request( "open-ils.storage.set_audit_info", $authtoken, $user_id, $ws_id );
60 my $audit_resp = $audit_req->recv();
67 transform => 'permission.usr_has_perm',
78 # returns undef if user has all of the perms provided
79 # returns the first failed perm on failure
80 sub check_user_perms {
81 my($self, $user_id, $org_id, @perm_types ) = @_;
82 $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
84 for my $type (@perm_types) {
85 $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
86 $PERM_QUERY->{where}->{id} = $user_id;
87 return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
92 # checks the list of user perms. The first one that fails returns a new
94 my( $self, $user_id, $org_id, @perm_types ) = @_;
95 my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
96 return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
102 # ---------------------------------------------------------------------------
103 # commits and destroys the session
104 # ---------------------------------------------------------------------------
105 sub commit_db_session {
106 my( $self, $session ) = @_;
108 my $req = $session->request( "open-ils.storage.transaction.commit" );
109 my $resp = $req->recv();
112 throw OpenSRF::EX::ERROR ("Unable to commit db session");
115 if(UNIVERSAL::isa($resp,"Error")) {
116 throw $resp ($resp->stringify);
119 if(!$resp->content) {
120 throw OpenSRF::EX::ERROR ("Unable to commit db session");
124 $session->disconnect();
128 sub rollback_db_session {
129 my( $self, $session ) = @_;
131 my $req = $session->request("open-ils.storage.transaction.rollback");
132 my $resp = $req->recv();
133 if(UNIVERSAL::isa($resp,"Error")) { throw $resp; }
136 $session->disconnect();
141 # returns undef it the event is not an ILS event
142 # returns the event code otherwise
144 my( $self, $evt ) = @_;
145 return $evt->{ilsevent} if $self->is_event($evt);
149 # some events, in particular auto-generated events, don't have an
150 # ilsevent key. treat hashes with a 'textcode' key as events.
152 my ($self, $evt) = @_;
154 ref($evt) eq 'HASH' and (
155 defined $evt->{ilsevent} or
156 defined $evt->{textcode}
161 # ---------------------------------------------------------------------------
162 # Checks to see if a user is logged in. Returns the user record on success,
163 # throws an exception on error.
164 # ---------------------------------------------------------------------------
165 sub check_user_session {
166 my( $self, $user_session ) = @_;
168 my $content = $self->simplereq(
170 'open-ils.auth.session.retrieve', $user_session);
172 return undef if (!$content) or $self->event_code($content);
176 # generic simple request returning a scalar value
178 my($self, $service, $method, @params) = @_;
179 return $self->simple_scalar_request($service, $method, @params);
183 sub simple_scalar_request {
184 my($self, $service, $method, @params) = @_;
186 my $session = OpenSRF::AppSession->create( $service );
188 my $request = $session->request( $method, @params );
194 $val = $request->gather(1);
201 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
202 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
209 my( $self, $orglist ) = @_;
211 return $orglist unless ref $orglist;
212 return $$orglist[0] if @$orglist == 1;
215 $a->ou_type <=> $b->ou_type ||
216 $a->name cmp $b->name } @$orglist;
218 for my $org (@list) {
221 next if (!defined($org->parent_ou) || $org->parent_ou eq "");
223 my ($parent) = grep { $_->id == $org->parent_ou } @list;
225 $parent->children([]) unless defined($parent->children);
226 push( @{$parent->children}, $org );
232 sub fetch_closed_date {
233 my( $self, $cd ) = @_;
236 $logger->debug("Fetching closed_date $cd from cstore");
238 my $cd_obj = $self->simplereq(
240 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
243 $logger->info("closed_date $cd not found in the db");
244 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
247 return ($cd_obj, $evt);
251 my( $self, $userid ) = @_;
254 $logger->debug("Fetching user $userid from cstore");
256 $user = $self->simplereq(
258 'open-ils.cstore.direct.actor.user.retrieve', $userid );
261 $logger->info("User $userid not found in the db");
262 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
265 return ($user, $evt);
269 my( $self, $session ) = @_;
270 my $user = $self->check_user_session($session) or
271 return (undef, OpenILS::Event->new('NO_SESSION'));
276 # verifiese the session and checks the permissions agains the
277 # session user and the user's home_ou as the org id
279 my( $self, $session, @perms ) = @_;
280 my $user; my $evt; my $e;
281 $logger->debug("Checking user session $session and perms @perms");
282 ($user, $evt) = $self->checkses($session);
283 return (undef, $evt) if $evt;
284 $evt = $self->check_perms($user->id, $user->home_ou, @perms);
285 return ($user, $evt);
290 my( $self, $staffobj, $userid, @perms ) = @_;
292 $userid = $staffobj->id unless defined $userid;
294 $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
296 if( $userid ne $staffobj->id ) {
297 ($user, $evt) = $self->fetch_user($userid);
298 return (undef, $evt) if $evt;
299 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
305 return ($user, $evt);
308 sub checkses_requestor {
309 my( $self, $authtoken, $targetid, @perms ) = @_;
310 my( $requestor, $target, $evt );
312 ($requestor, $evt) = $self->checkses($authtoken);
313 return (undef, undef, $evt) if $evt;
315 ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
316 return( $requestor, $target, $evt);
320 my( $self, $copyid ) = @_;
323 $logger->debug("Fetching copy $copyid from cstore");
325 $copy = $self->simplereq(
327 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
329 if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
331 return( $copy, $evt );
335 # retrieves a circ object by id
336 sub fetch_circulation {
337 my( $self, $circid ) = @_;
340 $logger->debug("Fetching circ $circid from cstore");
342 $circ = $self->simplereq(
344 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
347 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
350 return ( $circ, $evt );
353 sub fetch_record_by_copy {
354 my( $self, $copyid ) = @_;
357 $logger->debug("Fetching record by copy $copyid from cstore");
359 $record = $self->simplereq(
361 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
363 flesh_fields => { bre => [ 'fixed_fields' ],
365 acp => [ 'call_number' ],
371 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
373 $record = $record->call_number->record;
376 return ($record, $evt);
379 # turns a record object into an mvr (mods) object
381 my( $self, $record ) = @_;
382 return undef unless $record and $record->marc;
383 my $u = OpenILS::Utils::ModsParser->new();
384 $u->start_mods_batch( $record->marc );
385 my $mods = $u->finish_mods_batch();
386 $mods->doc_id($record->id);
387 $mods->tcn($record->tcn_value);
392 my( $self, $holdid ) = @_;
395 $logger->debug("Fetching hold $holdid from cstore");
397 $hold = $self->simplereq(
399 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
401 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
403 return ($hold, $evt);
407 sub fetch_hold_transit_by_hold {
408 my( $self, $holdid ) = @_;
409 my( $transit, $evt );
411 $logger->debug("Fetching transit by hold $holdid from cstore");
413 $transit = $self->simplereq(
415 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid, cancel_time => undef } );
417 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
419 return ($transit, $evt );
422 # fetches the captured, but not fulfilled hold attached to a given copy
423 sub fetch_open_hold_by_copy {
424 my( $self, $copyid ) = @_;
425 $logger->debug("Searching for active hold for copy $copyid");
428 $hold = $self->cstorereq(
429 'open-ils.cstore.direct.action.hold_request.search',
431 current_copy => $copyid ,
432 capture_time => { "!=" => undef },
433 fulfillment_time => undef,
434 cancel_time => undef,
437 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
438 return ($hold, $evt);
441 sub fetch_hold_transit {
442 my( $self, $transid ) = @_;
443 my( $htransit, $evt );
444 $logger->debug("Fetching hold transit with hold id $transid");
445 $htransit = $self->cstorereq(
446 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
447 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
448 return ($htransit, $evt);
451 sub fetch_copy_by_barcode {
452 my( $self, $barcode ) = @_;
455 $logger->debug("Fetching copy by barcode $barcode from cstore");
457 $copy = $self->simplereq( 'open-ils.cstore',
458 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
459 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
461 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
463 return ($copy, $evt);
466 sub fetch_open_billable_transaction {
467 my( $self, $transid ) = @_;
468 my( $transaction, $evt );
470 $logger->debug("Fetching open billable transaction $transid from cstore");
472 $transaction = $self->simplereq(
474 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve', $transid);
476 $evt = OpenILS::Event->new(
477 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
479 return ($transaction, $evt);
485 $buckets{'biblio'} = 'biblio_record_entry_bucket';
486 $buckets{'callnumber'} = 'call_number_bucket';
487 $buckets{'copy'} = 'copy_bucket';
488 $buckets{'user'} = 'user_bucket';
490 sub fetch_container {
491 my( $self, $id, $type ) = @_;
494 $logger->debug("Fetching container $id with type $type");
496 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
497 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
498 $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
499 $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
501 my $meth = $buckets{$type};
502 $bucket = $self->simplereq(
504 "open-ils.cstore.direct.container.$meth.retrieve", $id );
506 $evt = OpenILS::Event->new(
507 $e, container => $id, container_type => $type ) unless $bucket;
509 return ($bucket, $evt);
513 sub fetch_container_e {
514 my( $self, $editor, $id, $type ) = @_;
517 $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
518 $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
519 $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
520 $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
522 $evt = $editor->event unless $bucket;
523 return ($bucket, $evt);
526 sub fetch_container_item_e {
527 my( $self, $editor, $id, $type ) = @_;
530 $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
531 $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
532 $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
533 $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
535 $evt = $editor->event unless $bucket;
536 return ($bucket, $evt);
543 sub fetch_container_item {
544 my( $self, $id, $type ) = @_;
547 $logger->debug("Fetching container item $id with type $type");
549 my $meth = $buckets{$type} . "_item";
551 $bucket = $self->simplereq(
553 "open-ils.cstore.direct.container.$meth.retrieve", $id );
556 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
557 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
558 $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
559 $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
561 $evt = OpenILS::Event->new(
562 $e, itemid => $id, container_type => $type ) unless $bucket;
564 return ($bucket, $evt);
568 sub fetch_patron_standings {
570 $logger->debug("Fetching patron standings");
571 return $self->simplereq(
573 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
577 sub fetch_permission_group_tree {
579 $logger->debug("Fetching patron profiles");
580 return $self->simplereq(
582 'open-ils.actor.groups.tree.retrieve' );
585 sub fetch_permission_group_descendants {
586 my( $self, $profile ) = @_;
587 my $group_tree = $self->fetch_permission_group_tree();
591 # FIXME: okay, so it's not an org tree, but it is compatible
592 $self->walk_org_tree($group_tree, sub {
594 if ($g->id == $profile) {
599 $self->walk_org_tree($start_here, sub {
601 push(@groups,$g->id);
607 sub fetch_patron_circ_summary {
608 my( $self, $userid ) = @_;
609 $logger->debug("Fetching patron summary for $userid");
610 my $summary = $self->simplereq(
612 "open-ils.storage.action.circulation.patron_summary", $userid );
616 $summary->[1] ||= 0.0;
623 sub fetch_copy_statuses {
625 $logger->debug("Fetching copy statuses");
626 return $self->simplereq(
628 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
631 sub fetch_copy_location {
632 my( $self, $id ) = @_;
634 my $cl = $self->cstorereq(
635 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
636 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
640 sub fetch_copy_locations {
642 return $self->simplereq(
644 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef }, deleted => 'f' });
647 sub fetch_copy_location_by_name {
648 my( $self, $name, $org ) = @_;
650 my $cl = $self->cstorereq(
651 'open-ils.cstore.direct.asset.copy_location.search',
652 { name => $name, owning_lib => $org, deleted => 'f' } );
653 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
657 sub fetch_callnumber {
658 my( $self, $id, $flesh, $e ) = @_;
660 $e ||= OpenILS::Utils::CStoreEditor->new;
662 my $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
663 return( undef, $evt ) unless $id;
665 $logger->debug("Fetching callnumber $id");
667 my $cn = $e->retrieve_asset_call_number([
669 { flesh => $flesh, flesh_fields => { acn => [ 'prefix', 'suffix', 'label_class' ] } },
672 return ( $cn, $e->event );
675 my %ORG_CACHE; # - these rarely change, so cache them..
677 my( $self, $id ) = @_;
678 return undef unless $id;
679 return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
680 return $ORG_CACHE{$id} if $ORG_CACHE{$id};
681 $logger->debug("Fetching org unit $id");
684 my $org = $self->simplereq(
686 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
687 $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
688 $ORG_CACHE{$id} = $org;
694 my( $self, $type, $id ) = @_;
696 $logger->debug("Fetching $type stat cat: $id");
697 $cat = $self->simplereq(
699 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
701 my $e = 'ASSET_STAT_CAT_NOT_FOUND';
702 $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
704 $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
705 return ( $cat, $evt );
708 sub fetch_stat_cat_entry {
709 my( $self, $type, $id ) = @_;
711 $logger->debug("Fetching $type stat cat entry: $id");
712 $entry = $self->simplereq(
714 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
716 my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
717 $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
719 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
720 return ( $entry, $evt );
723 sub fetch_stat_cat_entry_default {
724 my( $self, $type, $id ) = @_;
725 my( $entry_default, $evt );
726 $logger->debug("Fetching $type stat cat entry default: $id");
727 $entry_default = $self->simplereq(
729 "open-ils.cstore.direct.$type.stat_cat_entry_default.retrieve", $id );
731 my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
732 $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
734 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry_default;
735 return ( $entry_default, $evt );
738 sub fetch_stat_cat_entry_default_by_stat_cat_and_org {
739 my( $self, $type, $stat_cat, $orgId ) = @_;
741 $logger->info("### Fetching $type stat cat entry default with stat_cat $stat_cat owned by org_unit $orgId");
742 $entry_default = $self->simplereq(
744 "open-ils.cstore.direct.$type.stat_cat_entry_default.search.atomic",
745 { stat_cat => $stat_cat, owner => $orgId } );
747 $entry_default = $entry_default->[0];
748 return ($entry_default, undef) if $entry_default;
750 my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
751 $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
752 return (undef, OpenILS::Event->new($e) );
756 my( $self, $org_tree, $orgid ) = @_;
757 return undef unless $org_tree and defined $orgid;
758 return $org_tree if ( $org_tree->id eq $orgid );
759 return undef unless ref($org_tree->children);
760 for my $c (@{$org_tree->children}) {
761 my $o = $self->find_org($c, $orgid);
767 sub find_org_by_shortname {
768 my( $self, $org_tree, $shortname ) = @_;
769 return undef unless $org_tree and defined $shortname;
770 return $org_tree if ( $org_tree->shortname eq $shortname );
771 return undef unless ref($org_tree->children);
772 for my $c (@{$org_tree->children}) {
773 my $o = $self->find_org_by_shortname($c, $shortname);
779 sub find_lasso_by_name {
780 my( $self, $name ) = @_;
781 return $self->simplereq(
783 'open-ils.cstore.direct.actor.org_lasso.search.atomic', { name => $name } )->[0];
786 sub fetch_lasso_org_maps {
787 my( $self, $lasso ) = @_;
788 return $self->simplereq(
790 'open-ils.cstore.direct.actor.org_lasso_map.search.atomic', { lasso => $lasso } );
793 sub fetch_non_cat_type_by_name_and_org {
794 my( $self, $name, $orgId ) = @_;
795 $logger->debug("Fetching non cat type $name at org $orgId");
796 my $types = $self->simplereq(
798 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
799 { name => $name, owning_lib => $orgId } );
800 return ($types->[0], undef) if($types and @$types);
801 return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
804 sub fetch_non_cat_type {
805 my( $self, $id ) = @_;
806 $logger->debug("Fetching non cat type $id");
808 $type = $self->simplereq(
810 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
811 $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
812 return ($type, $evt);
815 sub DB_UPDATE_FAILED {
816 my( $self, $payload ) = @_;
817 return OpenILS::Event->new('DATABASE_UPDATE_FAILED',
818 payload => ($payload) ? $payload : undef );
821 sub fetch_booking_reservation {
822 my( $self, $id ) = @_;
825 $res = $self->simplereq(
827 'open-ils.cstore.direct.booking.reservation.retrieve', $id
830 # simplereq doesn't know how to flesh so ...
835 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
839 $res->target_resource_type(
842 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
846 if ($res->current_resource) {
847 $res->current_resource(
850 'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
854 if ($self->is_true( $res->target_resource_type->catalog_item )) {
855 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
859 if ($res->target_resource) {
860 $res->target_resource(
863 'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
867 if ($self->is_true( $res->target_resource_type->catalog_item )) {
868 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
873 $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
879 sub fetch_circ_duration_by_name {
880 my( $self, $name ) = @_;
882 $dur = $self->simplereq(
884 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
886 $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
890 sub fetch_recurring_fine_by_name {
891 my( $self, $name ) = @_;
893 $obj = $self->simplereq(
895 'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
897 $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
901 sub fetch_max_fine_by_name {
902 my( $self, $name ) = @_;
904 $obj = $self->simplereq(
906 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
908 $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
912 sub fetch_hard_due_date_by_name {
913 my( $self, $name ) = @_;
915 $obj = $self->simplereq(
917 'open-ils.cstore.direct.config.hard_due_date.search.atomic', { name => $name } );
919 $evt = OpenILS::Event->new('CONFIG_RULES_HARD_DUE_DATE_NOT_FOUND') unless $obj;
924 my( $self, $method, @params ) = @_;
925 return $self->simplereq(
926 'open-ils.storage', $method, @params );
929 sub storagereq_xact {
930 my($self, $method, @params) = @_;
931 my $ses = $self->start_db_session();
932 my $val = $ses->request($method, @params)->gather(1);
933 $self->rollback_db_session($ses);
938 my( $self, $method, @params ) = @_;
939 return $self->simplereq(
940 'open-ils.cstore', $method, @params );
944 my( $self, $e, $name ) = @_;
945 if( $e and ref($e) eq 'HASH' and
946 defined($e->{textcode}) and $e->{textcode} eq $name ) {
953 my( undef, $f, $l ) = caller(0);
954 my( undef, undef, undef, $s ) = caller(1);
957 $logger->debug("LOGMARK: $f:$l:$s");
961 sub fetch_open_circulation {
962 my( $self, $cid ) = @_;
965 my $e = OpenILS::Utils::CStoreEditor->new;
966 my $circ = $e->search_action_circulation({
968 stop_fines_time => undef,
969 checkin_time => undef
972 return ($circ, $e->event);
976 sub copy_status_from_name {
977 my( $self, $name ) = @_;
978 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
979 for my $status (@$copy_statuses) {
980 return $status if( $status->name =~ /$name/i );
985 sub copy_status_to_name {
986 my( $self, $sid ) = @_;
987 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
988 for my $status (@$copy_statuses) {
989 return $status->name if( $status->id == $sid );
996 my( $self, $arg ) = @_;
997 return $arg if ref $arg;
998 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
999 my ($stat) = grep { $_->id == $arg } @$copy_statuses;
1003 sub fetch_open_transit_by_copy {
1004 my( $self, $copyid ) = @_;
1006 $transit = $self->cstorereq(
1007 'open-ils.cstore.direct.action.transit_copy.search',
1008 { target_copy => $copyid, dest_recv_time => undef, cancel_time => undef });
1009 $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
1010 return ($transit, $evt);
1014 my( $self, $copy ) = @_;
1015 return undef unless $copy;
1016 $copy->status( $copy->status->id ) if ref($copy->status);
1017 $copy->location( $copy->location->id ) if ref($copy->location);
1018 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1022 sub unflesh_reservation {
1023 my( $self, $reservation ) = @_;
1024 return undef unless $reservation;
1025 $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
1026 $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
1027 $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
1028 $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
1029 return $reservation;
1032 # un-fleshes a copy and updates it in the DB
1033 # returns a DB_UPDATE_FAILED event on error
1034 # returns undef on success
1036 my( $self, %params ) = @_;
1038 my $copy = $params{copy} || die "update_copy(): copy required";
1039 my $editor = $params{editor} || die "update_copy(): copy editor required";
1040 my $session = $params{session};
1042 $logger->debug("Updating copy in the database: " . $copy->id);
1044 $self->unflesh_copy($copy);
1045 $copy->editor( $editor );
1046 $copy->edit_date( 'now' );
1049 my $meth = 'open-ils.storage.direct.asset.copy.update';
1051 $s = $session->request( $meth, $copy )->gather(1) if $session;
1052 $s = $self->storagereq( $meth, $copy ) unless $session;
1054 $logger->debug("Update of copy ".$copy->id." returned: $s");
1056 return $self->DB_UPDATE_FAILED($copy) unless $s;
1060 sub update_reservation {
1061 my( $self, %params ) = @_;
1063 my $reservation = $params{reservation} || die "update_reservation(): reservation required";
1064 my $editor = $params{editor} || die "update_reservation(): copy editor required";
1065 my $session = $params{session};
1067 $logger->debug("Updating copy in the database: " . $reservation->id);
1069 $self->unflesh_reservation($reservation);
1072 my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1074 $s = $session->request( $meth, $reservation )->gather(1) if $session;
1075 $s = $self->cstorereq( $meth, $reservation ) unless $session;
1077 $logger->debug("Update of copy ".$reservation->id." returned: $s");
1079 return $self->DB_UPDATE_FAILED($reservation) unless $s;
1083 sub fetch_billable_xact {
1084 my( $self, $id ) = @_;
1086 $logger->debug("Fetching billable transaction %id");
1087 $xact = $self->cstorereq(
1088 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1089 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1090 return ($xact, $evt);
1093 sub fetch_billable_xact_summary {
1094 my( $self, $id ) = @_;
1096 $logger->debug("Fetching billable transaction summary %id");
1097 $xact = $self->cstorereq(
1098 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1099 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1100 return ($xact, $evt);
1103 sub fetch_fleshed_copy {
1104 my( $self, $id ) = @_;
1106 $logger->info("Fetching fleshed copy $id");
1107 $copy = $self->cstorereq(
1108 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1110 flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1113 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1114 return ($copy, $evt);
1118 # returns the org that owns the callnumber that the copy
1120 sub fetch_copy_owner {
1121 my( $self, $copyid ) = @_;
1122 my( $copy, $cn, $evt );
1123 $logger->debug("Fetching copy owner $copyid");
1124 ($copy, $evt) = $self->fetch_copy($copyid);
1125 return (undef,$evt) if $evt;
1126 ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1127 return (undef,$evt) if $evt;
1128 return ($cn->owning_lib);
1131 sub fetch_copy_note {
1132 my( $self, $id ) = @_;
1134 $logger->debug("Fetching copy note $id");
1135 $note = $self->cstorereq(
1136 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1137 $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1138 return ($note, $evt);
1141 sub fetch_call_numbers_by_title {
1142 my( $self, $titleid ) = @_;
1143 $logger->info("Fetching call numbers by title $titleid");
1144 return $self->cstorereq(
1145 'open-ils.cstore.direct.asset.call_number.search.atomic',
1146 { record => $titleid, deleted => 'f' });
1147 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1150 sub fetch_copies_by_call_number {
1151 my( $self, $cnid ) = @_;
1152 $logger->info("Fetching copies by call number $cnid");
1153 return $self->cstorereq(
1154 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1155 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1158 sub fetch_user_by_barcode {
1159 my( $self, $bc ) = @_;
1160 my $cardid = $self->cstorereq(
1161 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1162 return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1163 my $user = $self->cstorereq(
1164 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1165 return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1171 my( $self, $billid ) = @_;
1172 $logger->debug("Fetching billing $billid");
1173 my $bill = $self->cstorereq(
1174 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1175 my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1176 return($bill, $evt);
1180 my( $self, $node, $callback ) = @_;
1181 return unless $node;
1183 if( $node->children ) {
1184 $self->walk_org_tree($_, $callback) for @{$node->children};
1189 my( $self, $item ) = @_;
1190 return 1 if $item and $item !~ /^f$/i;
1196 my ($self, $client, $service, $method, @params) = @_;
1197 my ($response, $err);
1199 my $session = create OpenSRF::AppSession($service);
1200 my $request = $session->request($method, @params);
1203 my $give_up = time + 1000;
1206 while (time < $give_up) {
1207 $response = $request->recv("timeout" => $spurt);
1208 last if $request->complete;
1210 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1212 } catch Error with {
1217 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
1218 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
1221 return $response->content;
1224 # This logic now lives in storage
1225 sub __patron_money_owed {
1226 my( $self, $patronid ) = @_;
1227 my $ses = OpenSRF::AppSession->create('open-ils.storage');
1228 my $req = $ses->request(
1229 'open-ils.storage.money.billable_transaction.summary.search',
1230 { usr => $patronid, xact_finish => undef } );
1234 while( $data = $req->recv ) {
1235 $data = $data->content;
1236 $total += $data->balance_owed;
1241 sub patron_money_owed {
1242 my( $self, $userid ) = @_;
1243 my $ses = $self->start_db_session();
1244 my $val = $ses->request(
1245 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1246 $self->rollback_db_session($ses);
1250 sub patron_total_items_out {
1251 my( $self, $userid ) = @_;
1252 my $ses = $self->start_db_session();
1253 my $val = $ses->request(
1254 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1255 $self->rollback_db_session($ses);
1262 #---------------------------------------------------------------------
1263 # Returns ($summary, $event)
1264 #---------------------------------------------------------------------
1268 my $e = shift || OpenILS::Utils::CStoreEditor->new;
1269 $id = $id->id if ref($id);
1271 my $xact = $e->retrieve_money_billable_transaction_summary($id)
1272 or return (undef, $e->event);
1278 #---------------------------------------------------------------------
1279 # Given a list of money.billable_transaction objects, this creates
1280 # transaction summary objects for each
1281 #--------------------------------------------------------------------
1286 return () if (!@xacts);
1287 return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1291 sub ou_ancestor_setting_value {
1292 my($self, $org_id, $name, $e) = @_;
1293 $e = $e || OpenILS::Utils::CStoreEditor->new;
1294 my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1295 return $set->{value} if $set;
1300 # If an authentication token is provided AND this org unit setting has a
1301 # view_perm, then make sure the user referenced by the auth token has
1302 # that permission. This means that if you call this method without an
1303 # authtoken param, you can get whatever org unit setting values you want.
1306 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1307 # authtoken is checked, but the $auth arg is NOT checked. To say that another
1308 # way, be sure NOT to pass an editor argument if you want your token checked.
1309 # Otherwise the auth arg is just a flag saying "check the editor".
1311 sub ou_ancestor_setting {
1312 my( $self, $orgid, $name, $e, $auth ) = @_;
1313 $e = $e || OpenILS::Utils::CStoreEditor->new(
1314 (defined $auth) ? (authtoken => $auth) : ()
1318 my $coust = $e->retrieve_config_org_unit_setting_type([
1319 $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1321 return undef unless defined $coust;
1322 if ($coust->view_perm) {
1323 return undef unless $self->ou_ancestor_setting_perm_check($orgid, $coust->view_perm->code, $e, $auth);
1327 my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1328 my $setting = $e->json_query($query)->[0];
1329 return undef unless $setting;
1330 return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1333 # Returns the org id if the requestor has the permissions required
1334 # to view the ou setting.
1335 sub ou_ancestor_setting_perm_check {
1336 my( $self, $orgid, $view_perm, $e, $auth ) = @_;
1337 $e = $e || OpenILS::Utils::CStoreEditor->new(
1338 (defined $auth) ? (authtoken => $auth) : ()
1341 # And you can't have permission if you don't have a valid session.
1342 return undef if not $e->checkauth;
1343 # And now that we know you MIGHT have permission, we check it.
1345 return undef unless $e->allowed($view_perm, $orgid);
1351 sub ou_ancestor_setting_log {
1352 my ( $self, $orgid, $name, $e, $auth ) = @_;
1353 $e = $e || OpenILS::Utils::CStoreEditor->new(
1354 (defined $auth) ? (authtoken => $auth, xact => 1) : ()
1359 $coust = $e->retrieve_config_org_unit_setting_type([
1360 $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1363 my $perm_code = $coust->view_perm ? $coust->view_perm->code : undef;
1364 my $qorg = $self->ou_ancestor_setting_perm_check(
1370 my $sort = { order_by => { coustl => 'date_applied DESC' } };
1371 return $e->json_query({
1374 field_name => $name,
1382 # This fetches a set of OU settings in one fell swoop,
1383 # which can be significantly faster than invoking
1384 # $U->ou_ancestor_setting() one setting at a time.
1385 # As the "_insecure" implies, however, callers are
1386 # responsible for ensuring that the settings to be
1387 # fetch do not need view permission checks.
1388 sub ou_ancestor_setting_batch_insecure {
1389 my( $self, $orgid, $names ) = @_;
1391 my %result = map { $_ => undef } @$names;
1394 'actor.org_unit_ancestor_setting_batch',
1396 '{' . join(',', @$names) . '}'
1399 my $e = OpenILS::Utils::CStoreEditor->new();
1400 my $settings = $e->json_query($query);
1401 foreach my $setting (@$settings) {
1402 $result{$setting->{name}} = {
1403 org => $setting->{org_unit},
1404 value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})
1410 # Returns a hash of hashes like so:
1412 # $lookup_org_id => {org => $context_org, value => $setting_value},
1413 # $lookup_org_id2 => {org => $context_org2, value => $setting_value2},
1414 # $lookup_org_id3 => {} # example of no setting value exists
1417 sub ou_ancestor_setting_batch_by_org_insecure {
1418 my ($self, $org_ids, $name, $e) = @_;
1420 $e ||= OpenILS::Utils::CStoreEditor->new();
1421 my %result = map { $_ => {value => undef} } @$org_ids;
1425 'actor.org_unit_ancestor_setting_batch_by_org',
1426 $name, '{' . join(',', @$org_ids) . '}'
1430 # DB func returns an array of settings matching the order of the
1431 # list of org unit IDs. If the setting does not contain a valid
1432 # ->id value, then no setting value exists for that org unit.
1433 my $settings = $e->json_query($query);
1434 for my $idx (0 .. $#$org_ids) {
1435 my $setting = $settings->[$idx];
1436 my $org_id = $org_ids->[$idx];
1438 next unless $setting->{id}; # null ID means no value is present.
1440 $result{$org_id}->{org} = $setting->{org_unit};
1441 $result{$org_id}->{value} =
1442 OpenSRF::Utils::JSON->JSON2perl($setting->{value});
1448 # returns the ISO8601 string representation of the requested epoch in GMT
1450 my( $self, $epoch ) = @_;
1451 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1452 $year += 1900; $mon += 1;
1454 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1455 $year, $mon, $mday, $hour, $min, $sec);
1459 sub find_highest_perm_org {
1460 my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1461 my $org = $self->find_org($org_tree, $start_org );
1465 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1467 $org = $self->find_org( $org_tree, $org->parent_ou() );
1474 # returns the org_unit ID's
1475 sub user_has_work_perm_at {
1476 my($self, $e, $perm, $options, $user_id) = @_;
1478 $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1480 my $func = 'permission.usr_has_perm_at';
1481 $func = $func.'_all' if $$options{descendants};
1483 my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1484 $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1486 return $orgs unless $$options{objects};
1488 return $e->search_actor_org_unit({id => $orgs});
1491 sub get_user_work_ou_ids {
1492 my($self, $e, $userid) = @_;
1493 my $work_orgs = $e->json_query({
1494 select => {puwoum => ['work_ou']},
1496 where => {usr => $e->requestor->id}});
1498 return [] unless @$work_orgs;
1500 push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1508 my($self, $client) = @_;
1509 return $org_types if $org_types;
1510 return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1516 my $locale = shift || '';
1517 my $cache = OpenSRF::Utils::Cache->new("global", 0);
1518 my $tree = $ORG_TREE{$locale} || $cache->get_cache("orgtree.$locale");
1519 $ORG_TREE{$locale} = $tree; # make sure to populate the process-local cache
1520 return $tree if $tree;
1522 my $ses = OpenILS::Utils::CStoreEditor->new;
1523 $ses->session->session_locale($locale);
1524 $tree = $ses->search_actor_org_unit(
1526 {"parent_ou" => undef },
1529 flesh_fields => { aou => ['children'] },
1530 order_by => { aou => 'name'}
1535 $ORG_TREE{$locale} = $tree;
1536 $cache->put_cache("orgtree.$locale", $tree);
1540 sub get_global_flag {
1541 my($self, $flag) = @_;
1542 return undef unless ($flag);
1543 return OpenILS::Utils::CStoreEditor->new->retrieve_config_global_flag($flag);
1546 sub get_org_descendants {
1547 my($self, $org_id, $depth) = @_;
1550 transform => 'actor.org_unit_descendants',
1552 result_field => 'id',
1554 $select->{params} = [$depth] if defined $depth;
1556 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1557 select => {aou => [$select]},
1559 where => {id => $org_id}
1562 push(@orgs, $_->{id}) for @$org_list;
1566 sub get_org_ancestors {
1567 my($self, $org_id, $use_cache) = @_;
1572 $cache = OpenSRF::Utils::Cache->new("global", 0);
1573 $orgs = $cache->get_cache("org.ancestors.$org_id");
1574 return $orgs if $orgs;
1577 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1580 transform => 'actor.org_unit_ancestors',
1582 result_field => 'id',
1587 where => {id => $org_id}
1590 $orgs = [ map { $_->{id} } @$org_list ];
1592 $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1596 sub get_org_full_path {
1597 my($self, $org_id, $depth) = @_;
1602 transform => 'actor.org_unit_full_path',
1604 result_field => 'id',
1608 where => {id => $org_id}
1611 $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1612 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1613 return [ map {$_->{id}} @$org_list ];
1616 # returns the ID of the org unit ancestor at the specified depth
1617 sub org_unit_ancestor_at_depth {
1618 my($class, $org_id, $depth) = @_;
1619 my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1620 {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1621 return ($resp) ? $resp->{id} : undef;
1624 # returns the ID of the org unit ancestor at the specified distance
1625 sub get_org_unit_ancestor_at_distance {
1626 my ($class, $org_id, $distance) = @_;
1627 my $ancestors = OpenILS::Utils::CStoreEditor->new->json_query(
1628 { from => ['actor.org_unit_ancestors_distance', $org_id] });
1629 my @match = grep { $_->{distance} == $distance } @{$ancestors};
1630 return (@match) ? $match[0]->{id} : undef;
1633 # returns the ID of the org unit parent
1634 sub get_org_unit_parent {
1635 my ($class, $org_id) = @_;
1636 return $class->get_org_unit_ancestor_at_distance($org_id, 1);
1639 # Returns the proximity value between two org units.
1640 sub get_org_unit_proximity {
1641 my ($class, $e, $from_org, $to_org) = @_;
1642 $e = OpenILS::Utils::CStoreEditor->new unless ($e);
1643 my $r = $e->json_query(
1645 select => {aoup => ['prox']},
1647 where => {from_org => $from_org, to_org => $to_org}
1650 if (ref($r) eq 'ARRAY' && @$r) {
1651 return $r->[0]->{prox};
1656 # returns the user's configured locale as a string. Defaults to en-US if none is configured.
1657 sub get_user_locale {
1658 my($self, $user_id, $e) = @_;
1659 $e ||= OpenILS::Utils::CStoreEditor->new;
1661 # first, see if the user has an explicit locale set
1662 my $setting = $e->search_actor_user_setting(
1663 {usr => $user_id, name => 'global.locale'})->[0];
1664 return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1666 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1667 return $self->get_org_locale($user->home_ou, $e);
1670 # returns org locale setting
1671 sub get_org_locale {
1672 my($self, $org_id, $e) = @_;
1673 $e ||= OpenILS::Utils::CStoreEditor->new;
1676 if(defined $org_id) {
1677 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1678 return $locale if $locale;
1681 # system-wide default
1682 my $sclient = OpenSRF::Utils::SettingsClient->new;
1683 $locale = $sclient->config_value('default_locale');
1684 return $locale if $locale;
1686 # if nothing else, fallback to locale=cowboy
1691 # xml-escape non-ascii characters
1693 my($self, $string, $form) = @_;
1697 $string = NFD($string);
1699 $string = NFC($string);
1702 # Convert raw ampersands to entities
1703 $string =~ s/&(?!\S+;)/&/gso;
1705 # Convert Unicode characters to entities
1706 $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1711 # x0000-x0008 isn't legal in XML documents
1712 # XXX Perhaps this should just go into our standard entityize method
1713 sub strip_ctrl_chars {
1714 my ($self, $string) = @_;
1716 $string =~ s/([\x{0000}-\x{0008}])//sgoe;
1720 sub get_copy_price {
1721 my($self, $e, $copy, $volume) = @_;
1723 $copy->price(0) if $copy->price and $copy->price < 0;
1728 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1729 $owner = $copy->circ_lib;
1731 $owner = $volume->owning_lib;
1734 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1735 $owner = $copy->circ_lib;
1737 $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1741 my $min_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MIN_ITEM_PRICE);
1742 my $max_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MAX_ITEM_PRICE);
1743 my $charge_on_0 = $self->ou_ancestor_setting_value($owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e);
1744 my $primary_field = $self->ou_ancestor_setting_value($owner, OILS_SETTING_PRIMARY_ITEM_VALUE_FIELD, $e);
1745 my $backup_field = $self->ou_ancestor_setting_value($owner, OILS_SETTING_SECONDARY_ITEM_VALUE_FIELD, $e);
1747 my $price = defined $primary_field && $primary_field eq 'cost'
1751 # set the default price if needed
1752 if (!defined $price or ($price == 0 and $charge_on_0)) {
1753 if (defined $backup_field && $backup_field eq 'cost') {
1754 $price = $copy->cost;
1755 } elsif (defined $backup_field && $backup_field eq 'price') {
1756 $price = $copy->price;
1759 # possible fallthrough to original default item price behavior
1760 if (!defined $price or ($price == 0 and $charge_on_0)) {
1761 # set to default price
1762 $price = $self->ou_ancestor_setting_value(
1763 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1766 # adjust to min/max range if needed
1767 if (defined $max_price and $price > $max_price) {
1768 $price = $max_price;
1769 } elsif (defined $min_price and $price < $min_price
1770 and ($price != 0 or $charge_on_0 or !defined $charge_on_0)) {
1771 # default to raising the price to the minimum,
1772 # but let 0 fall through if $charge_on_0 is set and is false
1773 $price = $min_price;
1779 # given a transaction ID, this returns the context org_unit for the transaction
1781 my($self, $xact_id, $e) = @_;
1782 $e ||= OpenILS::Utils::CStoreEditor->new;
1784 my $loc = $e->json_query({
1785 "select" => {circ => ["circ_lib"]},
1787 "where" => {id => $xact_id},
1790 return $loc->[0]->{circ_lib} if @$loc;
1792 $loc = $e->json_query({
1793 "select" => {bresv => ["request_lib"]},
1795 "where" => {id => $xact_id},
1798 return $loc->[0]->{request_lib} if @$loc;
1800 $loc = $e->json_query({
1801 "select" => {mg => ["billing_location"]},
1803 "where" => {id => $xact_id},
1806 return $loc->[0]->{billing_location};
1810 sub find_event_def_by_hook {
1811 my($self, $hook, $context_org, $e) = @_;
1813 $e ||= OpenILS::Utils::CStoreEditor->new;
1815 my $orgs = $self->get_org_ancestors($context_org);
1817 # search from the context org up
1818 for my $org_id (reverse @$orgs) {
1820 my $def = $e->search_action_trigger_event_definition(
1821 {hook => $hook, owner => $org_id, active => 't'})->[0];
1823 return $def if $def;
1831 # If an event_def ID is not provided, use the hook and context org to find the
1832 # most appropriate event. create the event, fire it, then return the resulting
1833 # event with fleshed template_output and error_output
1834 sub fire_object_event {
1835 my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1837 my $e = OpenILS::Utils::CStoreEditor->new;
1840 my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1843 $def = $e->retrieve_action_trigger_event_definition($event_def)
1844 or return $e->event;
1846 $auto_method .= '.include_inactive';
1850 # find the most appropriate event def depending on context org
1851 $def = $self->find_event_def_by_hook($hook, $context_org, $e)
1852 or return $e->event;
1857 if($def->group_field) {
1858 # we have a list of objects
1859 $object = [$object] unless ref $object eq 'ARRAY';
1863 for my $i (0..$#$object) {
1864 my $obj = $$object[$i];
1865 my $udata = $$user_data[$i];
1866 my $event_id = $self->simplereq(
1867 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1868 push(@event_ids, $event_id);
1871 $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1874 if (not defined $client) {
1875 $resp = $self->simplereq(
1877 'open-ils.trigger.event_group.fire',
1880 $resp = $self->patientreq(
1882 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1887 if($resp and $resp->{events} and @{$resp->{events}}) {
1890 $final_resp = $e->retrieve_action_trigger_event([
1891 $resp->{events}->[0]->id,
1892 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1899 $object = $$object[0] if ref $object eq 'ARRAY';
1904 if (not defined $client) {
1905 $event_id = $self->simplereq(
1907 $auto_method, $def->id, $object, $context_org, $user_data
1910 $resp = $self->simplereq(
1912 'open-ils.trigger.event.fire',
1916 $event_id = $self->patientreq(
1919 $auto_method, $def->id, $object, $context_org, $user_data
1922 $resp = $self->patientreq(
1925 'open-ils.trigger.event.fire',
1930 if($resp and $resp->{event}) {
1932 $final_resp = $e->retrieve_action_trigger_event([
1934 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1944 sub create_events_for_hook {
1945 my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1946 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1947 my $req = $ses->request('open-ils.trigger.event.autocreate',
1948 $hook, $obj, $org_id, $granularity, $user_data);
1949 return undef unless $wait;
1950 my $resp = $req->recv;
1951 return $resp->content if $resp;
1954 sub create_uuid_string {
1955 return create_UUID_as_string();
1958 sub create_circ_chain_summary {
1959 my($class, $e, $circ_id) = @_;
1960 my $sum = $e->json_query({from => ['action.summarize_all_circ_chain', $circ_id]})->[0];
1961 return undef unless $sum;
1962 my $obj = Fieldmapper::action::circ_chain_summary->new;
1963 $obj->$_($sum->{$_}) for keys %$sum;
1968 # Returns "mra" attribute key/value pairs for a set of bre's
1969 # Takes a list of bre IDs, returns a hash of hashes,
1970 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1973 my ($class, $bre_ids, $e) = @_;
1974 $e = $e || OpenILS::Utils::CStoreEditor->new;
1977 return $attrs unless defined $bre_ids;
1978 $bre_ids = [$bre_ids] unless ref $bre_ids;
1980 my $mra = $e->json_query({
1988 transform => 'each',
1989 result_field => 'key',
1993 transform => 'each',
1994 result_field => 'value',
2000 where => {id => $bre_ids}
2003 return $attrs unless $mra;
2005 $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
2007 for my $id (@$bre_ids) {
2009 for my $mra (grep { $_->{bre} eq $id } @$mra) {
2010 my $ctype = $mra->{key};
2011 my $code = $mra->{value};
2012 $attrs->{$id}->{$ctype} = {code => $code};
2014 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
2015 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
2023 # Shorter version of bib_container_items_via_search() below, only using
2024 # the queryparser record_list filter instead of the container filter.
2025 sub bib_record_list_via_search {
2026 my ($class, $search_query, $search_args) = @_;
2028 # First, Use search API to get container items sorted in any way that crad
2030 my $search_result = $class->simplereq(
2031 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2032 $search_args, $search_query
2035 unless ($search_result) {
2036 # empty result sets won't cause this, but actual errors should.
2037 $logger->warn("bib_record_list_via_search() got nothing from search");
2041 # Throw away other junk from search, keeping only bib IDs.
2042 return [ map { shift @$_ } @{$search_result->{ids}} ];
2045 # 'no_flesh' avoids fleshing the target_biblio_record_entry
2046 sub bib_container_items_via_search {
2047 my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
2049 # First, Use search API to get container items sorted in any way that crad
2051 my $search_result = $class->simplereq(
2052 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2053 $search_args, $search_query
2055 unless ($search_result) {
2056 # empty result sets won't cause this, but actual errors should.
2057 $logger->warn("bib_container_items_via_search() got nothing from search");
2061 # Throw away other junk from search, keeping only bib IDs.
2062 my $id_list = [ map { shift @$_ } @{$search_result->{ids}} ];
2064 return [] unless @$id_list;
2066 # Now get the bib container items themselves...
2067 my $e = new OpenILS::Utils::CStoreEditor;
2069 $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
2073 my @flesh_fields = qw/notes/;
2074 push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
2076 my $items = $e->search_container_biblio_record_entry_bucket_item([
2078 "target_biblio_record_entry" => $id_list,
2079 "bucket" => $container_id
2082 flesh_fields => {"cbrebi" => \@flesh_fields}
2084 ], {substream => 1});
2088 "bib_container_items_via_search() couldn't get bucket items: " .
2089 $e->die_event->{textcode}
2094 # ... and put them in the same order that the search API said they
2096 my %ordering_hash = map {
2097 ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id,
2101 return [map { $ordering_hash{$_} } @$id_list];
2104 # returns undef on success, Event on error
2105 sub log_user_activity {
2106 my ($class, $user_id, $who, $what, $e, $async) = @_;
2110 $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
2114 my $res = $e->json_query({
2116 'actor.insert_usr_activity',
2117 $user_id, $who, $what, OpenSRF::AppSession->ingress
2121 if ($res) { # call returned OK
2123 $e->commit if $commit and @$res;
2124 $e->rollback if $commit and !@$res;
2127 return $e->die_event;
2133 # I hate to put this here exactly, but this code needs to be shared between
2134 # the TPAC's mod_perl module and open-ils.serial.
2136 # There is a reason every part of the query *except* those parts dealing
2137 # with scope are moved here from the code's origin in TPAC. The serials
2138 # use case does *not* want the same scoping logic.
2140 # Also, note that for the serials uses case, we may filter in OPAC visible
2141 # status and copy/call_number deletedness, but we don't filter on any
2142 # particular values for serial.item.status or serial.item.date_received.
2143 # Since we're only using this *after* winnowing down the set of issuances
2144 # that copies should be related to, I'm not sure we need any such serial.item
2147 sub basic_opac_copy_query {
2148 ######################################################################
2149 # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
2151 ######################################################################
2152 my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
2156 acp => ['id', 'barcode', 'circ_lib', 'create_date', 'active_date',
2157 'age_protect', 'holdable', 'copy_number', 'circ_modifier'],
2159 {column => 'name', alias => 'copy_location'},
2160 {column => 'holdable', alias => 'location_holdable'},
2161 {column => 'url', alias => 'location_url'}
2164 {column => 'id', alias => 'status_code'},
2165 {column => 'name', alias => 'copy_status'},
2166 {column => 'holdable', alias => 'status_holdable'},
2167 {column => 'is_available', alias => 'is_available'}
2170 {column => 'label', alias => 'call_number_label'},
2171 {column => 'id', alias => 'call_number'},
2172 {column => 'owning_lib', alias => 'call_number_owning_lib'}
2174 circ => ['due_date',{column => 'circ_lib', alias => 'circ_circ_lib'}],
2176 {column => 'label', alias => 'call_number_prefix_label'},
2177 {column => 'id', alias => 'call_number_prefix'}
2180 {column => 'label', alias => 'call_number_suffix_label'},
2181 {column => 'id', alias => 'call_number_suffix'}
2184 {column => 'label', alias => 'part_label'},
2186 ($staff ? (erfcc => ['circ_count']) : ()),
2188 {column => 'name', alias => 'age_protect_label'}
2190 ($iss_id ? (sitem => ["issuance"]) : ())
2197 acnp => { fkey => 'prefix' },
2198 acns => { fkey => 'suffix' }
2202 ($rec_id ? {record => $rec_id} : ())
2206 {circ => { # 2 If the copy is circulating, retrieve the open circ
2208 filter => {checkin_time => undef}
2213 ($staff ? () : ( opac_visible => 't' )),
2217 ($staff ? () : (filter => { opac_visible => 't' }))
2222 bmp => { type => 'left', filter => { deleted => 'f' } }
2232 filter => {issuance => $iss_id},
2250 ($staff ? () : (opac_visible => 't'))
2252 ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2253 ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2257 {class => 'aou', field => 'name'},
2258 {class => 'acn', field => 'label_sortkey'},
2259 {class => 'acns', field => 'label_sortkey'},
2260 {class => 'bmp', field => 'label_sortkey'},
2261 {class => 'acp', field => 'copy_number'},
2262 {class => 'acp', field => 'barcode'}
2265 limit => $copy_limit,
2266 offset => $copy_offset
2270 # Compare two dates, date1 and date2. If date2 is not defined, then
2271 # DateTime->now will be used. Assumes dates are in ISO8601 format as
2272 # supported by DateTime::Format::ISO8601. (A future enhancement might
2273 # be to support other formats.)
2275 # Returns -1 if $date1 < $date2
2276 # Returns 0 if $date1 == $date2
2277 # Returns 1 if $date1 > $date2
2283 # Check for timezone offsets and limit them to 2 digits:
2284 if ($date1 && $date1 =~ /(?:-|\+)\d\d\d\d$/) {
2285 $date1 = substr($date1, 0, length($date1) - 2);
2287 if ($date2 && $date2 =~ /(?:-|\+)\d\d\d\d$/) {
2288 $date2 = substr($date2, 0, length($date2) - 2);
2292 unless (UNIVERSAL::isa($date1, "DateTime")) {
2293 $date1 = DateTime::Format::ISO8601->parse_datetime($date1);
2298 $date2 = DateTime->now;
2300 unless (UNIVERSAL::isa($date2, "DateTime")) {
2301 $date2 = DateTime::Format::ISO8601->parse_datetime($date2);
2305 return DateTime->compare($date1, $date2);
2309 # marcdoc is an XML::LibXML document
2310 # updates the doc and returns the entityized MARC string
2311 sub strip_marc_fields {
2312 my ($class, $e, $marcdoc, $grps) = @_;
2314 my $orgs = $class->get_org_ancestors($e->requestor->ws_ou);
2317 select => {vibtf => ['field']},
2318 from => {vibtf => 'vibtg'},
2319 where => {'+vibtg' => {owner => $orgs}},
2323 # give me always-apply groups plus any selected groups
2324 if ($grps and @$grps) {
2325 $query->{where}->{'+vibtg'}->{'-or'} = [
2327 {always_apply => 't'}
2331 $query->{where}->{'+vibtg'}->{always_apply} = 't';
2334 my $fields = $e->json_query($query);
2336 for my $field (@$fields) {
2337 my $tag = $field->{field};
2338 for my $node ($marcdoc->findnodes('//*[@tag="'.$tag.'"]')) {
2339 $node->parentNode->removeChild($node);
2343 return $class->entityize($marcdoc->documentElement->toString);
2346 # marcdoc is an XML::LibXML document
2347 # updates the document and returns the entityized MARC string.
2349 my ($class, $marcdoc, $username) = @_;
2351 # Look for existing 905$u subfields. If any exist, do nothing.
2352 my @nodes = $marcdoc->findnodes('//*[@tag="905"]/*[@code="u"]');
2354 # We create a new 905 and the subfield u to that.
2355 my $parentNode = $marcdoc->createElement('datafield');
2356 $parentNode->setAttribute('tag', '905');
2357 $parentNode->setAttribute('ind1', '');
2358 $parentNode->setAttribute('ind2', '');
2359 $marcdoc->documentElement->addChild($parentNode);
2360 my $node = $marcdoc->createElement('subfield');
2361 $node->setAttribute('code', 'u');
2362 $node->appendTextNode($username);
2363 $parentNode->addChild($node);
2367 return $class->entityize($marcdoc->documentElement->toString);
2370 # Given a list of PostgreSQL arrays of numbers,
2371 # unnest the numbers and return a unique set, skipping any list elements
2372 # that are just '{NULL}'.
2373 sub unique_unnested_numbers {
2376 no warnings 'numeric';
2378 return undef unless ( scalar @_ );
2383 map { $_ eq 'NULL' ? undef : (split /,/, $_) }
2384 map { substr($_, 1, -1) } @_
2389 # Given a list of numbers, turn them into a PG array, skipping undef's
2390 sub intarray2pgarray {
2392 no warnings 'numeric';
2394 return '{' . join( ',', map(int, grep { defined && /^\d+$/ } @_) ) . '}';
2397 # Check if a transaction should be left open or closed. Close the
2398 # transaction if it should be closed or open it otherwise. Returns
2399 # undef on success or a failure event.
2400 sub check_open_xact {
2401 my( $self, $editor, $xactid, $xact ) = @_;
2403 # Grab the transaction
2404 $xact ||= $editor->retrieve_money_billable_transaction($xactid);
2405 return $editor->event unless $xact;
2406 $xactid ||= $xact->id;
2408 # grab the summary and see how much is owed on this transaction
2409 my ($summary) = $self->fetch_mbts($xactid, $editor);
2411 # grab the circulation if it is a circ;
2412 my $circ = $editor->retrieve_action_circulation($xactid);
2414 # If nothing is owed on the transaction but it is still open
2415 # and this transaction is not an open circulation, close it
2417 ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
2418 ( !$circ or $circ->stop_fines )) {
2420 $logger->info("closing transaction ".$xact->id. ' because balance_owed == 0');
2421 $xact->xact_finish('now');
2422 $editor->update_money_billable_transaction($xact)
2423 or return $editor->event;
2427 # If money is owed or a refund is due on the xact and xact_finish
2428 # is set, clear it (to reopen the xact) and update
2429 if( $summary->balance_owed != 0 and $xact->xact_finish ) {
2430 $logger->info("re-opening transaction ".$xact->id. ' because balance_owed != 0');
2431 $xact->clear_xact_finish;
2432 $editor->update_money_billable_transaction($xact)
2433 or return $editor->event;
2439 # Because floating point math has rounding issues, and Dyrcona gets
2440 # tired of typing out the code to multiply floating point numbers
2441 # before adding and subtracting them and then dividing the result by
2442 # 100 each time, he wrote this little subroutine for subtracting
2443 # floating point values. It can serve as a model for the other
2444 # operations if you like.
2446 # It takes a list of floating point values as arguments. The rest are
2447 # all subtracted from the first and the result is returned. The
2448 # values are all multiplied by 100 before being used, and the result
2449 # is divided by 100 in order to avoid decimal rounding errors inherent
2450 # in floating point math.
2452 # XXX shifting using multiplication/division *may* still introduce
2453 # rounding errors -- better to implement using string manipulation?
2455 my ($class, @args) = @_;
2456 my $result = shift(@args) * 100;
2457 while (my $arg = shift(@args)) {
2458 $result -= $arg * 100;
2460 return $result / 100;
2464 my ($class, @args) = @_;
2465 my $result = shift(@args) * 100;
2466 while (my $arg = shift(@args)) {
2467 $result += $arg * 100;
2469 return $result / 100;
2472 # Non-migrated passwords can be verified directly in the DB
2473 # with any extra hashing.
2474 sub verify_user_password {
2475 my ($class, $e, $user_id, $passwd, $pw_type) = @_;
2477 $pw_type ||= 'main'; # primary login password
2479 my $verify = $e->json_query({
2481 'actor.verify_passwd',
2482 $user_id, $pw_type, $passwd
2486 return $class->is_true($verify->{'actor.verify_passwd'});
2489 # Passwords migrated from the original MD5 scheme are passed through 2
2490 # extra layers of MD5 hashing for backwards compatibility with the
2491 # MD5 passwords of yore and the MD5-based chap-style authentication.
2492 # Passwords are stored in the DB like this:
2493 # CRYPT( MD5( pw_salt || MD5(real_password) ), pw_salt )
2495 # If 'as_md5' is true, the password provided has already been
2497 sub verify_migrated_user_password {
2498 my ($class, $e, $user_id, $passwd, $as_md5) = @_;
2500 # 'main' is the primary login password. This is the only password
2501 # type that requires the additional MD5 hashing.
2502 my $pw_type = 'main';
2504 # Sometimes we have the bare password, sometimes the MD5 version.
2505 my $md5_pass = $as_md5 ? $passwd : md5_hex($passwd);
2507 my $salt = $e->json_query({
2515 $salt = $salt->{'actor.get_salt'};
2517 return $class->verify_user_password(
2518 $e, $user_id, md5_hex($salt . $md5_pass), $pw_type);
2522 # generate a MARC XML document from a MARC XML string
2523 sub marc_xml_to_doc {
2524 my ($class, $xml) = @_;
2525 my $marc_doc = XML::LibXML->new->parse_string($xml);
2526 $marc_doc->documentElement->setNamespace(MARC_NAMESPACE, 'marc', 1);
2527 $marc_doc->documentElement->setNamespace(MARC_NAMESPACE);