1 package OpenILS::Application::AppUtils;
3 use strict; use warnings;
4 use OpenILS::Application;
5 use base qw/OpenILS::Application/;
6 use OpenSRF::Utils::Cache;
7 use OpenSRF::Utils::Logger qw/$logger/;
8 use OpenILS::Utils::ModsParser;
9 use OpenSRF::EX qw(:try);
12 use OpenILS::Utils::CStoreEditor;
13 use OpenILS::Const qw/:const/;
14 use Unicode::Normalize;
15 use OpenSRF::Utils::SettingsClient;
18 # ---------------------------------------------------------------------------
19 # Pile of utilty methods used accross applications.
20 # ---------------------------------------------------------------------------
21 my $cache_client = "OpenSRF::Utils::Cache";
24 # ---------------------------------------------------------------------------
25 # on sucess, returns the created session, on failure throws ERROR exception
26 # ---------------------------------------------------------------------------
27 sub start_db_session {
30 my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
31 my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
33 my $trans_resp = $trans_req->recv();
34 if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
35 if( ! $trans_resp->content() ) {
37 ("Unable to Begin Transaction with database" );
41 $logger->debug("Setting global storage session to ".
42 "session: " . $session->session_id . " : " . $session->app );
50 transform => 'permission.usr_has_perm',
61 # returns undef if user has all of the perms provided
62 # returns the first failed perm on failure
63 sub check_user_perms {
64 my($self, $user_id, $org_id, @perm_types ) = @_;
65 $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
67 for my $type (@perm_types) {
68 $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
69 $PERM_QUERY->{where}->{id} = $user_id;
70 return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
75 # checks the list of user perms. The first one that fails returns a new
77 my( $self, $user_id, $org_id, @perm_types ) = @_;
78 my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
79 return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
85 # ---------------------------------------------------------------------------
86 # commits and destroys the session
87 # ---------------------------------------------------------------------------
88 sub commit_db_session {
89 my( $self, $session ) = @_;
91 my $req = $session->request( "open-ils.storage.transaction.commit" );
92 my $resp = $req->recv();
95 throw OpenSRF::EX::ERROR ("Unable to commit db session");
98 if(UNIVERSAL::isa($resp,"Error")) {
99 throw $resp ($resp->stringify);
102 if(!$resp->content) {
103 throw OpenSRF::EX::ERROR ("Unable to commit db session");
107 $session->disconnect();
111 sub rollback_db_session {
112 my( $self, $session ) = @_;
114 my $req = $session->request("open-ils.storage.transaction.rollback");
115 my $resp = $req->recv();
116 if(UNIVERSAL::isa($resp,"Error")) { throw $resp; }
119 $session->disconnect();
124 # returns undef it the event is not an ILS event
125 # returns the event code otherwise
127 my( $self, $evt ) = @_;
128 return $evt->{ilsevent} if( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
132 # ---------------------------------------------------------------------------
133 # Checks to see if a user is logged in. Returns the user record on success,
134 # throws an exception on error.
135 # ---------------------------------------------------------------------------
136 sub check_user_session {
137 my( $self, $user_session ) = @_;
139 my $content = $self->simplereq(
141 'open-ils.auth.session.retrieve', $user_session);
143 return undef if (!$content) or $self->event_code($content);
147 # generic simple request returning a scalar value
149 my($self, $service, $method, @params) = @_;
150 return $self->simple_scalar_request($service, $method, @params);
154 sub simple_scalar_request {
155 my($self, $service, $method, @params) = @_;
157 my $session = OpenSRF::AppSession->create( $service );
159 my $request = $session->request( $method, @params );
165 $val = $request->gather(1);
172 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
173 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
185 my $org_typelist = undef;
186 my $org_typelist_hash = {};
190 # can we throw this version away??
193 if($tree) { return $tree; }
195 # see if it's in the cache
196 $tree = $cache_client->new()->get_cache('_orgtree');
197 if($tree) { return $tree; }
200 warn "Retrieving Org Tree\n";
201 $orglist = $self->simple_scalar_request(
203 "open-ils.cstore.direct.actor.org_unit.search.atomic",
204 { id => { '!=' => undef } }
208 if( ! $org_typelist ) {
209 warn "Retrieving org types\n";
210 $org_typelist = $self->simple_scalar_request(
212 "open-ils.cstore.direct.actor.org_unit_type.search.atomic",
213 { id => { '!=' => undef } }
215 $self->build_org_type($org_typelist);
218 $tree = $self->build_org_tree($orglist,1);
219 $cache_client->new()->put_cache('_orgtree', $tree);
224 my $slimtree = undef;
225 sub get_slim_org_tree {
228 if($slimtree) { return $slimtree; }
230 # see if it's in the cache
231 $slimtree = $cache_client->new()->get_cache('slimorgtree');
232 if($slimtree) { return $slimtree; }
235 warn "Retrieving Org Tree\n";
236 $orglist = $self->simple_scalar_request(
238 "open-ils.cstore.direct.actor.org_unit.search.atomic",
239 { id => { '!=' => undef } }
243 $slimtree = $self->build_org_tree($orglist);
244 $cache_client->new->put_cache('slimorgtree', $slimtree);
251 my($self, $org_typelist) = @_;
252 for my $type (@$org_typelist) {
253 $org_typelist_hash->{$type->id()} = $type;
261 my( $self, $orglist, $add_types ) = @_;
263 return $orglist unless ref $orglist;
264 return $$orglist[0] if @$orglist == 1;
267 $a->ou_type <=> $b->ou_type ||
268 $a->name cmp $b->name } @$orglist;
270 for my $org (@list) {
274 if(!ref($org->ou_type()) and $add_types) {
275 $org->ou_type( $org_typelist_hash->{$org->ou_type()});
278 next unless (defined($org->parent_ou));
280 my ($parent) = grep { $_->id == $org->parent_ou } @list;
282 $parent->children([]) unless defined($parent->children);
283 push( @{$parent->children}, $org );
289 sub fetch_closed_date {
290 my( $self, $cd ) = @_;
293 $logger->debug("Fetching closed_date $cd from cstore");
295 my $cd_obj = $self->simplereq(
297 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
300 $logger->info("closed_date $cd not found in the db");
301 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
304 return ($cd_obj, $evt);
308 my( $self, $userid ) = @_;
311 $logger->debug("Fetching user $userid from cstore");
313 $user = $self->simplereq(
315 'open-ils.cstore.direct.actor.user.retrieve', $userid );
318 $logger->info("User $userid not found in the db");
319 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
322 return ($user, $evt);
326 my( $self, $session ) = @_;
327 my $user = $self->check_user_session($session) or
328 return (undef, OpenILS::Event->new('NO_SESSION'));
333 # verifiese the session and checks the permissions agains the
334 # session user and the user's home_ou as the org id
336 my( $self, $session, @perms ) = @_;
337 my $user; my $evt; my $e;
338 $logger->debug("Checking user session $session and perms @perms");
339 ($user, $evt) = $self->checkses($session);
340 return (undef, $evt) if $evt;
341 $evt = $self->check_perms($user->id, $user->home_ou, @perms);
342 return ($user, $evt);
347 my( $self, $staffobj, $userid, @perms ) = @_;
349 $userid = $staffobj->id unless defined $userid;
351 $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
353 if( $userid ne $staffobj->id ) {
354 ($user, $evt) = $self->fetch_user($userid);
355 return (undef, $evt) if $evt;
356 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
362 return ($user, $evt);
365 sub checkses_requestor {
366 my( $self, $authtoken, $targetid, @perms ) = @_;
367 my( $requestor, $target, $evt );
369 ($requestor, $evt) = $self->checkses($authtoken);
370 return (undef, undef, $evt) if $evt;
372 ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
373 return( $requestor, $target, $evt);
377 my( $self, $copyid ) = @_;
380 $logger->debug("Fetching copy $copyid from cstore");
382 $copy = $self->simplereq(
384 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
386 if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
388 return( $copy, $evt );
392 # retrieves a circ object by id
393 sub fetch_circulation {
394 my( $self, $circid ) = @_;
397 $logger->debug("Fetching circ $circid from cstore");
399 $circ = $self->simplereq(
401 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
404 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
407 return ( $circ, $evt );
410 sub fetch_record_by_copy {
411 my( $self, $copyid ) = @_;
414 $logger->debug("Fetching record by copy $copyid from cstore");
416 $record = $self->simplereq(
418 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
420 flesh_fields => { bre => [ 'fixed_fields' ],
422 acp => [ 'call_number' ],
428 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
430 $record = $record->call_number->record;
433 return ($record, $evt);
436 # turns a record object into an mvr (mods) object
438 my( $self, $record ) = @_;
439 return undef unless $record and $record->marc;
440 my $u = OpenILS::Utils::ModsParser->new();
441 $u->start_mods_batch( $record->marc );
442 my $mods = $u->finish_mods_batch();
443 $mods->doc_id($record->id);
444 $mods->tcn($record->tcn_value);
449 my( $self, $holdid ) = @_;
452 $logger->debug("Fetching hold $holdid from cstore");
454 $hold = $self->simplereq(
456 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
458 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
460 return ($hold, $evt);
464 sub fetch_hold_transit_by_hold {
465 my( $self, $holdid ) = @_;
466 my( $transit, $evt );
468 $logger->debug("Fetching transit by hold $holdid from cstore");
470 $transit = $self->simplereq(
472 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
474 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
476 return ($transit, $evt );
479 # fetches the captured, but not fulfilled hold attached to a given copy
480 sub fetch_open_hold_by_copy {
481 my( $self, $copyid ) = @_;
482 $logger->debug("Searching for active hold for copy $copyid");
485 $hold = $self->cstorereq(
486 'open-ils.cstore.direct.action.hold_request.search',
488 current_copy => $copyid ,
489 capture_time => { "!=" => undef },
490 fulfillment_time => undef,
491 cancel_time => undef,
494 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
495 return ($hold, $evt);
498 sub fetch_hold_transit {
499 my( $self, $transid ) = @_;
500 my( $htransit, $evt );
501 $logger->debug("Fetching hold transit with hold id $transid");
502 $htransit = $self->cstorereq(
503 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
504 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
505 return ($htransit, $evt);
508 sub fetch_copy_by_barcode {
509 my( $self, $barcode ) = @_;
512 $logger->debug("Fetching copy by barcode $barcode from cstore");
514 $copy = $self->simplereq( 'open-ils.cstore',
515 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
516 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
518 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
520 return ($copy, $evt);
523 sub fetch_open_billable_transaction {
524 my( $self, $transid ) = @_;
525 my( $transaction, $evt );
527 $logger->debug("Fetching open billable transaction $transid from cstore");
529 $transaction = $self->simplereq(
531 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve', $transid);
533 $evt = OpenILS::Event->new(
534 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
536 return ($transaction, $evt);
542 $buckets{'biblio'} = 'biblio_record_entry_bucket';
543 $buckets{'callnumber'} = 'call_number_bucket';
544 $buckets{'copy'} = 'copy_bucket';
545 $buckets{'user'} = 'user_bucket';
547 sub fetch_container {
548 my( $self, $id, $type ) = @_;
551 $logger->debug("Fetching container $id with type $type");
553 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
554 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
555 $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
556 $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
558 my $meth = $buckets{$type};
559 $bucket = $self->simplereq(
561 "open-ils.cstore.direct.container.$meth.retrieve", $id );
563 $evt = OpenILS::Event->new(
564 $e, container => $id, container_type => $type ) unless $bucket;
566 return ($bucket, $evt);
570 sub fetch_container_e {
571 my( $self, $editor, $id, $type ) = @_;
574 $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
575 $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
576 $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
577 $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
579 $evt = $editor->event unless $bucket;
580 return ($bucket, $evt);
583 sub fetch_container_item_e {
584 my( $self, $editor, $id, $type ) = @_;
587 $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
588 $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
589 $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
590 $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
592 $evt = $editor->event unless $bucket;
593 return ($bucket, $evt);
600 sub fetch_container_item {
601 my( $self, $id, $type ) = @_;
604 $logger->debug("Fetching container item $id with type $type");
606 my $meth = $buckets{$type} . "_item";
608 $bucket = $self->simplereq(
610 "open-ils.cstore.direct.container.$meth.retrieve", $id );
613 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
614 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
615 $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
616 $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
618 $evt = OpenILS::Event->new(
619 $e, itemid => $id, container_type => $type ) unless $bucket;
621 return ($bucket, $evt);
625 sub fetch_patron_standings {
627 $logger->debug("Fetching patron standings");
628 return $self->simplereq(
630 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
634 sub fetch_permission_group_tree {
636 $logger->debug("Fetching patron profiles");
637 return $self->simplereq(
639 'open-ils.actor.groups.tree.retrieve' );
643 sub fetch_patron_circ_summary {
644 my( $self, $userid ) = @_;
645 $logger->debug("Fetching patron summary for $userid");
646 my $summary = $self->simplereq(
648 "open-ils.storage.action.circulation.patron_summary", $userid );
652 $summary->[1] ||= 0.0;
659 sub fetch_copy_statuses {
661 $logger->debug("Fetching copy statuses");
662 return $self->simplereq(
664 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
667 sub fetch_copy_location {
668 my( $self, $id ) = @_;
670 my $cl = $self->cstorereq(
671 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
672 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
676 sub fetch_copy_locations {
678 return $self->simplereq(
680 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
683 sub fetch_copy_location_by_name {
684 my( $self, $name, $org ) = @_;
686 my $cl = $self->cstorereq(
687 'open-ils.cstore.direct.asset.copy_location.search',
688 { name => $name, owning_lib => $org } );
689 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
693 sub fetch_callnumber {
694 my( $self, $id ) = @_;
697 my $e = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
698 return( undef, $e ) unless $id;
700 $logger->debug("Fetching callnumber $id");
702 my $cn = $self->simplereq(
704 'open-ils.cstore.direct.asset.call_number.retrieve', $id );
705 $evt = $e unless $cn;
707 return ( $cn, $evt );
710 my %ORG_CACHE; # - these rarely change, so cache them..
712 my( $self, $id ) = @_;
713 return undef unless $id;
714 return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
715 return $ORG_CACHE{$id} if $ORG_CACHE{$id};
716 $logger->debug("Fetching org unit $id");
719 my $org = $self->simplereq(
721 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
722 $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
723 $ORG_CACHE{$id} = $org;
729 my( $self, $type, $id ) = @_;
731 $logger->debug("Fetching $type stat cat: $id");
732 $cat = $self->simplereq(
734 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
736 my $e = 'ASSET_STAT_CAT_NOT_FOUND';
737 $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
739 $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
740 return ( $cat, $evt );
743 sub fetch_stat_cat_entry {
744 my( $self, $type, $id ) = @_;
746 $logger->debug("Fetching $type stat cat entry: $id");
747 $entry = $self->simplereq(
749 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
751 my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
752 $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
754 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
755 return ( $entry, $evt );
760 my( $self, $org_tree, $orgid ) = @_;
761 return undef unless $org_tree and defined $orgid;
762 return $org_tree if ( $org_tree->id eq $orgid );
763 return undef unless ref($org_tree->children);
764 for my $c (@{$org_tree->children}) {
765 my $o = $self->find_org($c, $orgid);
771 sub fetch_non_cat_type_by_name_and_org {
772 my( $self, $name, $orgId ) = @_;
773 $logger->debug("Fetching non cat type $name at org $orgId");
774 my $types = $self->simplereq(
776 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
777 { name => $name, owning_lib => $orgId } );
778 return ($types->[0], undef) if($types and @$types);
779 return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
782 sub fetch_non_cat_type {
783 my( $self, $id ) = @_;
784 $logger->debug("Fetching non cat type $id");
786 $type = $self->simplereq(
788 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
789 $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
790 return ($type, $evt);
793 sub DB_UPDATE_FAILED {
794 my( $self, $payload ) = @_;
795 return OpenILS::Event->new('DATABASE_UPDATE_FAILED',
796 payload => ($payload) ? $payload : undef );
799 sub fetch_circ_duration_by_name {
800 my( $self, $name ) = @_;
802 $dur = $self->simplereq(
804 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
806 $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
810 sub fetch_recurring_fine_by_name {
811 my( $self, $name ) = @_;
813 $obj = $self->simplereq(
815 'open-ils.cstore.direct.config.rules.recuring_fine.search.atomic', { name => $name } );
817 $evt = OpenILS::Event->new('CONFIG_RULES_RECURING_FINE_NOT_FOUND') unless $obj;
821 sub fetch_max_fine_by_name {
822 my( $self, $name ) = @_;
824 $obj = $self->simplereq(
826 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
828 $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
833 my( $self, $method, @params ) = @_;
834 return $self->simplereq(
835 'open-ils.storage', $method, @params );
838 sub storagereq_xact {
839 my($self, $method, @params) = @_;
840 my $ses = $self->start_db_session();
841 my $val = $ses->request($method, @params)->gather(1);
842 $self->rollback_db_session($ses);
847 my( $self, $method, @params ) = @_;
848 return $self->simplereq(
849 'open-ils.cstore', $method, @params );
853 my( $self, $e, $name ) = @_;
854 if( $e and ref($e) eq 'HASH' and
855 defined($e->{textcode}) and $e->{textcode} eq $name ) {
862 my( undef, $f, $l ) = caller(0);
863 my( undef, undef, undef, $s ) = caller(1);
866 $logger->debug("LOGMARK: $f:$l:$s");
870 sub fetch_open_circulation {
871 my( $self, $cid ) = @_;
874 my $circ = $self->cstorereq(
875 'open-ils.cstore.direct.action.open_circulation.search',
876 { target_copy => $cid, stop_fines_time => undef } );
877 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;
878 return ($circ, $evt);
881 sub fetch_all_open_circulation {
882 my( $self, $cid ) = @_;
885 my $circ = $self->cstorereq(
886 'open-ils.cstore.direct.action.open_circulation.search',
887 { target_copy => $cid, xact_finish => undef } );
888 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;
889 return ($circ, $evt);
893 sub copy_status_from_name {
894 my( $self, $name ) = @_;
895 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
896 for my $status (@$copy_statuses) {
897 return $status if( $status->name =~ /$name/i );
902 sub copy_status_to_name {
903 my( $self, $sid ) = @_;
904 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
905 for my $status (@$copy_statuses) {
906 return $status->name if( $status->id == $sid );
913 my( $self, $arg ) = @_;
914 return $arg if ref $arg;
915 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
916 my ($stat) = grep { $_->id == $arg } @$copy_statuses;
920 sub fetch_open_transit_by_copy {
921 my( $self, $copyid ) = @_;
923 $transit = $self->cstorereq(
924 'open-ils.cstore.direct.action.transit_copy.search',
925 { target_copy => $copyid, dest_recv_time => undef });
926 $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
927 return ($transit, $evt);
931 my( $self, $copy ) = @_;
932 return undef unless $copy;
933 $copy->status( $copy->status->id ) if ref($copy->status);
934 $copy->location( $copy->location->id ) if ref($copy->location);
935 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
939 # un-fleshes a copy and updates it in the DB
940 # returns a DB_UPDATE_FAILED event on error
941 # returns undef on success
943 my( $self, %params ) = @_;
945 my $copy = $params{copy} || die "update_copy(): copy required";
946 my $editor = $params{editor} || die "update_copy(): copy editor required";
947 my $session = $params{session};
949 $logger->debug("Updating copy in the database: " . $copy->id);
951 $self->unflesh_copy($copy);
952 $copy->editor( $editor );
953 $copy->edit_date( 'now' );
956 my $meth = 'open-ils.storage.direct.asset.copy.update';
958 $s = $session->request( $meth, $copy )->gather(1) if $session;
959 $s = $self->storagereq( $meth, $copy ) unless $session;
961 $logger->debug("Update of copy ".$copy->id." returned: $s");
963 return $self->DB_UPDATE_FAILED($copy) unless $s;
967 sub fetch_billable_xact {
968 my( $self, $id ) = @_;
970 $logger->debug("Fetching billable transaction %id");
971 $xact = $self->cstorereq(
972 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
973 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
974 return ($xact, $evt);
977 sub fetch_billable_xact_summary {
978 my( $self, $id ) = @_;
980 $logger->debug("Fetching billable transaction summary %id");
981 $xact = $self->cstorereq(
982 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
983 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
984 return ($xact, $evt);
987 sub fetch_fleshed_copy {
988 my( $self, $id ) = @_;
990 $logger->info("Fetching fleshed copy $id");
991 $copy = $self->cstorereq(
992 "open-ils.cstore.direct.asset.copy.retrieve", $id,
994 flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
997 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
998 return ($copy, $evt);
1002 # returns the org that owns the callnumber that the copy
1004 sub fetch_copy_owner {
1005 my( $self, $copyid ) = @_;
1006 my( $copy, $cn, $evt );
1007 $logger->debug("Fetching copy owner $copyid");
1008 ($copy, $evt) = $self->fetch_copy($copyid);
1009 return (undef,$evt) if $evt;
1010 ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1011 return (undef,$evt) if $evt;
1012 return ($cn->owning_lib);
1015 sub fetch_copy_note {
1016 my( $self, $id ) = @_;
1018 $logger->debug("Fetching copy note $id");
1019 $note = $self->cstorereq(
1020 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1021 $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1022 return ($note, $evt);
1025 sub fetch_call_numbers_by_title {
1026 my( $self, $titleid ) = @_;
1027 $logger->info("Fetching call numbers by title $titleid");
1028 return $self->cstorereq(
1029 'open-ils.cstore.direct.asset.call_number.search.atomic',
1030 { record => $titleid, deleted => 'f' });
1031 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1034 sub fetch_copies_by_call_number {
1035 my( $self, $cnid ) = @_;
1036 $logger->info("Fetching copies by call number $cnid");
1037 return $self->cstorereq(
1038 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1039 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1042 sub fetch_user_by_barcode {
1043 my( $self, $bc ) = @_;
1044 my $cardid = $self->cstorereq(
1045 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1046 return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1047 my $user = $self->cstorereq(
1048 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1049 return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1055 my( $self, $billid ) = @_;
1056 $logger->debug("Fetching billing $billid");
1057 my $bill = $self->cstorereq(
1058 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1059 my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1060 return($bill, $evt);
1064 sub fetch_org_tree {
1066 return $ORG_TREE if $ORG_TREE;
1067 return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit(
1069 {"parent_ou" => undef },
1072 flesh_fields => { aou => ['children'] },
1073 order_by => { aou => 'name'}
1080 my( $self, $node, $callback ) = @_;
1081 return unless $node;
1083 if( $node->children ) {
1084 $self->walk_org_tree($_, $callback) for @{$node->children};
1089 my( $self, $item ) = @_;
1090 return 1 if $item and $item !~ /^f$/i;
1095 # This logic now lives in storage
1096 sub __patron_money_owed {
1097 my( $self, $patronid ) = @_;
1098 my $ses = OpenSRF::AppSession->create('open-ils.storage');
1099 my $req = $ses->request(
1100 'open-ils.storage.money.billable_transaction.summary.search',
1101 { usr => $patronid, xact_finish => undef } );
1105 while( $data = $req->recv ) {
1106 $data = $data->content;
1107 $total += $data->balance_owed;
1112 sub patron_money_owed {
1113 my( $self, $userid ) = @_;
1114 my $ses = $self->start_db_session();
1115 my $val = $ses->request(
1116 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1117 $self->rollback_db_session($ses);
1121 sub patron_total_items_out {
1122 my( $self, $userid ) = @_;
1123 my $ses = $self->start_db_session();
1124 my $val = $ses->request(
1125 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1126 $self->rollback_db_session($ses);
1133 #---------------------------------------------------------------------
1134 # Returns ($summary, $event)
1135 #---------------------------------------------------------------------
1139 my $e = shift || OpenILS::Utils::CStoreEditor->new;
1140 $id = $id->id if ref($id);
1142 my $xact = $e->retrieve_money_billable_transaction_summary($id)
1143 or return (undef, $e->event);
1149 #---------------------------------------------------------------------
1150 # Given a list of money.billable_transaction objects, this creates
1151 # transaction summary objects for each
1152 #--------------------------------------------------------------------
1157 return () if (!@xacts);
1158 return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1162 sub ou_ancestor_setting_value {
1163 my($self, $org_id, $name, $e) = @_;
1164 $e = $e || OpenILS::Utils::CStoreEditor->new;
1165 my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1166 return $set->{value} if $set;
1171 # If an authentication token is provided AND this org unit setting has a
1172 # view_perm, then make sure the user referenced by the auth token has
1173 # that permission. This means that if you call this method without an
1174 # authtoken param, you can get whatever org unit setting values you want.
1176 sub ou_ancestor_setting {
1177 my( $self, $orgid, $name, $e, $auth ) = @_;
1178 $e = $e || OpenILS::Utils::CStoreEditor->new(
1179 (defined $auth) ? (authtoken => $auth) : ()
1181 my $coust = $e->retrieve_config_org_unit_setting_type([
1182 $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1185 if ($auth && $coust && $coust->view_perm) {
1186 # And you can't have permission if you don't have a valid session.
1187 return undef if not $e->checkauth;
1188 # And now that we know you MIGHT have permission, we check it.
1189 return undef if not $e->allowed($coust->view_perm->code, $orgid);
1192 my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1193 my $setting = $e->json_query($query)->[0];
1194 return undef unless $setting;
1195 return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1199 # returns the ISO8601 string representation of the requested epoch in GMT
1201 my( $self, $epoch ) = @_;
1202 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1203 $year += 1900; $mon += 1;
1205 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1206 $year, $mon, $mday, $hour, $min, $sec);
1210 sub find_highest_perm_org {
1211 my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1212 my $org = $self->find_org($org_tree, $start_org );
1216 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1218 $org = $self->find_org( $org_tree, $org->parent_ou() );
1225 # returns the org_unit ID's
1226 sub user_has_work_perm_at {
1227 my($self, $e, $perm, $options, $user_id) = @_;
1229 $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1231 my $func = 'permission.usr_has_perm_at';
1232 $func = $func.'_all' if $$options{descendants};
1234 my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1235 $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1237 return $orgs unless $$options{objects};
1239 return $e->search_actor_org_unit({id => $orgs});
1242 sub get_user_work_ou_ids {
1243 my($self, $e, $userid) = @_;
1244 my $work_orgs = $e->json_query({
1245 select => {puwoum => ['work_ou']},
1247 where => {usr => $e->requestor->id}});
1249 return [] unless @$work_orgs;
1251 push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1259 my($self, $client) = @_;
1260 return $org_types if $org_types;
1261 return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1266 my $locale = shift || '';
1267 my $cache = OpenSRF::Utils::Cache->new("global", 0);
1268 my $tree = $cache->get_cache("orgtree.$locale");
1269 return $tree if $tree;
1271 my $ses = OpenILS::Utils::CStoreEditor->new;
1272 $ses->session->session_locale($locale);
1273 $tree = $ses->search_actor_org_unit(
1275 {"parent_ou" => undef },
1278 flesh_fields => { aou => ['children'] },
1279 order_by => { aou => 'name'}
1284 $cache->put_cache("orgtree.$locale", $tree);
1288 sub get_org_descendants {
1289 my($self, $org_id, $depth) = @_;
1292 transform => 'actor.org_unit_descendants',
1294 result_field => 'id',
1296 $select->{params} = [$depth] if defined $depth;
1298 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1299 select => {aou => [$select]},
1301 where => {id => $org_id}
1304 push(@orgs, $_->{id}) for @$org_list;
1308 sub get_org_ancestors {
1309 my($self, $org_id) = @_;
1311 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1314 transform => 'actor.org_unit_ancestors',
1316 result_field => 'id',
1321 where => {id => $org_id}
1325 push(@orgs, $_->{id}) for @$org_list;
1329 sub get_org_full_path {
1330 my($self, $org_id, $depth) = @_;
1335 transform => 'actor.org_unit_full_path',
1337 result_field => 'id',
1341 where => {id => $org_id}
1344 $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1345 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1346 return [ map {$_->{id}} @$org_list ];
1349 # returns the ID of the org unit ancestor at the specified depth
1350 sub org_unit_ancestor_at_depth {
1351 my($class, $org_id, $depth) = @_;
1352 my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1353 {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1354 return ($resp) ? $resp->{id} : undef;
1357 # returns the user's configured locale as a string. Defaults to en-US if none is configured.
1358 sub get_user_locale {
1359 my($self, $user_id, $e) = @_;
1360 $e ||= OpenILS::Utils::CStoreEditor->new;
1362 # first, see if the user has an explicit locale set
1363 my $setting = $e->search_actor_user_setting(
1364 {usr => $user_id, name => 'global.locale'})->[0];
1365 return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1367 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1368 return $self->get_org_locale($user->home_ou, $e);
1371 # returns org locale setting
1372 sub get_org_locale {
1373 my($self, $org_id, $e) = @_;
1374 $e ||= OpenILS::Utils::CStoreEditor->new;
1377 if(defined $org_id) {
1378 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1379 return $locale if $locale;
1382 # system-wide default
1383 my $sclient = OpenSRF::Utils::SettingsClient->new;
1384 $locale = $sclient->config_value('default_locale');
1385 return $locale if $locale;
1387 # if nothing else, fallback to locale=cowboy
1392 # xml-escape non-ascii characters
1394 my($self, $string, $form) = @_;
1398 $string = NFD($string);
1400 $string = NFC($string);
1403 # Convert raw ampersands to entities
1404 $string =~ s/&(?!\S+;)/&/gso;
1406 # Convert Unicode characters to entities
1407 $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1412 # x0000-x0008 isn't legal in XML documents
1413 # XXX Perhaps this should just go into our standard entityize method
1414 sub strip_ctrl_chars {
1415 my ($self, $string) = @_;
1417 $string =~ s/([\x{0000}-\x{0008}])//sgoe;
1421 sub get_copy_price {
1422 my($self, $e, $copy, $volume) = @_;
1424 $copy->price(0) if $copy->price and $copy->price < 0;
1426 return $copy->price if $copy->price and $copy->price > 0;
1431 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1432 $owner = $copy->circ_lib;
1434 $owner = $volume->owning_lib;
1437 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1438 $owner = $copy->circ_lib;
1440 $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1444 my $default_price = $self->ou_ancestor_setting_value(
1445 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1447 return $default_price unless defined $copy->price;
1449 # price is 0. Use the default?
1450 my $charge_on_0 = $self->ou_ancestor_setting_value(
1451 $owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e) || 0;
1453 return $default_price if $charge_on_0;
1457 # given a transaction ID, this returns the context org_unit for the transaction
1459 my($self, $xact_id, $e) = @_;
1460 $e ||= OpenILS::Utils::CStoreEditor->new;
1462 my $loc = $e->json_query({
1463 "select" => {circ => ["circ_lib"]},
1465 "where" => {id => $xact_id},
1468 return $loc->[0]->{circ_lib} if @$loc;
1470 $loc = $e->json_query({
1471 "select" => {mg => ["billing_location"]},
1473 "where" => {id => $xact_id},
1476 return $loc->[0]->{billing_location};
1480 # If an event_def ID is not provided, use the hook and context org to find the
1481 # most appropriate event. create the event, fire it, then return the resulting
1482 # event with fleshed template_output and error_output
1483 sub fire_object_event {
1484 my($self, $event_def, $hook, $object, $context_org) = @_;
1486 my $e = OpenILS::Utils::CStoreEditor->new;
1489 my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1492 $def = $e->retrieve_action_trigger_event_definition($event_def)
1493 or return $e->event;
1495 $auto_method .= '.include_inactive';
1498 # find the most appropriate event def depending on context org
1499 my $orgs = $self->get_org_ancestors($context_org);
1500 $orgs = $e->search_actor_org_unit(
1501 [{id => $orgs}, {flesh => 1, flesh_fields => {aou => ['ou_type']}}]);
1502 $orgs = [ sort { $a->ou_type->depth cmp $b->ou_type->depth } @$orgs ];
1504 for my $org (reverse @$orgs) {
1505 $def = $e->search_action_trigger_event_definition(
1506 {hook => $hook, owner => $org->id}
1511 return $e->event unless $def;
1514 my $event_id = $self->simplereq(
1515 'open-ils.trigger', $auto_method, $def->id, $object, $context_org);
1517 my $fire = 'open-ils.trigger.event.fire';
1519 if($def->group_field) {
1520 $fire =~ s/event/event_group/o;
1521 $event_id = [$event_id];
1524 my $resp = $self->simplereq('open-ils.trigger', $fire, $event_id);
1525 return 0 unless $resp and ($resp->{event} or $resp->{events});
1526 my $evt = $resp->{event} ? $resp->{event} : $resp->{events}->[0];
1528 return 0 unless $evt;
1530 return $e->retrieve_action_trigger_event([
1532 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1537 sub create_trigger_event {
1538 my($self, $hook, $obj, $org_id) = @_;
1539 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1540 $ses->request('open-ils.trigger.event.autocreate', $hook, $obj, $org_id);
1543 sub create_uuid_string {
1544 return create_UUID_as_string();