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;
19 # ---------------------------------------------------------------------------
20 # Pile of utilty methods used accross applications.
21 # ---------------------------------------------------------------------------
22 my $cache_client = "OpenSRF::Utils::Cache";
25 # ---------------------------------------------------------------------------
26 # on sucess, returns the created session, on failure throws ERROR exception
27 # ---------------------------------------------------------------------------
28 sub start_db_session {
31 my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
32 my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
34 my $trans_resp = $trans_req->recv();
35 if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
36 if( ! $trans_resp->content() ) {
38 ("Unable to Begin Transaction with database" );
42 $logger->debug("Setting global storage session to ".
43 "session: " . $session->session_id . " : " . $session->app );
51 my $authtoken = shift;
55 my $audit_req = $session->request( "open-ils.storage.set_audit_info", $authtoken, $user_id, $ws_id );
56 my $audit_resp = $audit_req->recv();
63 transform => 'permission.usr_has_perm',
74 # returns undef if user has all of the perms provided
75 # returns the first failed perm on failure
76 sub check_user_perms {
77 my($self, $user_id, $org_id, @perm_types ) = @_;
78 $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
80 for my $type (@perm_types) {
81 $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
82 $PERM_QUERY->{where}->{id} = $user_id;
83 return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
88 # checks the list of user perms. The first one that fails returns a new
90 my( $self, $user_id, $org_id, @perm_types ) = @_;
91 my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
92 return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
98 # ---------------------------------------------------------------------------
99 # commits and destroys the session
100 # ---------------------------------------------------------------------------
101 sub commit_db_session {
102 my( $self, $session ) = @_;
104 my $req = $session->request( "open-ils.storage.transaction.commit" );
105 my $resp = $req->recv();
108 throw OpenSRF::EX::ERROR ("Unable to commit db session");
111 if(UNIVERSAL::isa($resp,"Error")) {
112 throw $resp ($resp->stringify);
115 if(!$resp->content) {
116 throw OpenSRF::EX::ERROR ("Unable to commit db session");
120 $session->disconnect();
124 sub rollback_db_session {
125 my( $self, $session ) = @_;
127 my $req = $session->request("open-ils.storage.transaction.rollback");
128 my $resp = $req->recv();
129 if(UNIVERSAL::isa($resp,"Error")) { throw $resp; }
132 $session->disconnect();
137 # returns undef it the event is not an ILS event
138 # returns the event code otherwise
140 my( $self, $evt ) = @_;
141 return $evt->{ilsevent} if( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
145 # ---------------------------------------------------------------------------
146 # Checks to see if a user is logged in. Returns the user record on success,
147 # throws an exception on error.
148 # ---------------------------------------------------------------------------
149 sub check_user_session {
150 my( $self, $user_session ) = @_;
152 my $content = $self->simplereq(
154 'open-ils.auth.session.retrieve', $user_session);
156 return undef if (!$content) or $self->event_code($content);
160 # generic simple request returning a scalar value
162 my($self, $service, $method, @params) = @_;
163 return $self->simple_scalar_request($service, $method, @params);
167 sub simple_scalar_request {
168 my($self, $service, $method, @params) = @_;
170 my $session = OpenSRF::AppSession->create( $service );
172 my $request = $session->request( $method, @params );
178 $val = $request->gather(1);
185 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
186 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
198 my $org_typelist = undef;
199 my $org_typelist_hash = {};
203 # can we throw this version away??
206 if($tree) { return $tree; }
208 # see if it's in the cache
209 $tree = $cache_client->new()->get_cache('_orgtree');
210 if($tree) { return $tree; }
213 warn "Retrieving Org Tree\n";
214 $orglist = $self->simple_scalar_request(
216 "open-ils.cstore.direct.actor.org_unit.search.atomic",
217 { id => { '!=' => undef } }
221 if( ! $org_typelist ) {
222 warn "Retrieving org types\n";
223 $org_typelist = $self->simple_scalar_request(
225 "open-ils.cstore.direct.actor.org_unit_type.search.atomic",
226 { id => { '!=' => undef } }
228 $self->build_org_type($org_typelist);
231 $tree = $self->build_org_tree($orglist,1);
232 $cache_client->new()->put_cache('_orgtree', $tree);
237 my $slimtree = undef;
238 sub get_slim_org_tree {
241 if($slimtree) { return $slimtree; }
243 # see if it's in the cache
244 $slimtree = $cache_client->new()->get_cache('slimorgtree');
245 if($slimtree) { return $slimtree; }
248 warn "Retrieving Org Tree\n";
249 $orglist = $self->simple_scalar_request(
251 "open-ils.cstore.direct.actor.org_unit.search.atomic",
252 { id => { '!=' => undef } }
256 $slimtree = $self->build_org_tree($orglist);
257 $cache_client->new->put_cache('slimorgtree', $slimtree);
264 my($self, $org_typelist) = @_;
265 for my $type (@$org_typelist) {
266 $org_typelist_hash->{$type->id()} = $type;
274 my( $self, $orglist, $add_types ) = @_;
276 return $orglist unless ref $orglist;
277 return $$orglist[0] if @$orglist == 1;
280 $a->ou_type <=> $b->ou_type ||
281 $a->name cmp $b->name } @$orglist;
283 for my $org (@list) {
287 if(!ref($org->ou_type()) and $add_types) {
288 $org->ou_type( $org_typelist_hash->{$org->ou_type()});
291 next if (!defined($org->parent_ou) || $org->parent_ou eq "");
293 my ($parent) = grep { $_->id == $org->parent_ou } @list;
295 $parent->children([]) unless defined($parent->children);
296 push( @{$parent->children}, $org );
302 sub fetch_closed_date {
303 my( $self, $cd ) = @_;
306 $logger->debug("Fetching closed_date $cd from cstore");
308 my $cd_obj = $self->simplereq(
310 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
313 $logger->info("closed_date $cd not found in the db");
314 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
317 return ($cd_obj, $evt);
321 my( $self, $userid ) = @_;
324 $logger->debug("Fetching user $userid from cstore");
326 $user = $self->simplereq(
328 'open-ils.cstore.direct.actor.user.retrieve', $userid );
331 $logger->info("User $userid not found in the db");
332 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
335 return ($user, $evt);
339 my( $self, $session ) = @_;
340 my $user = $self->check_user_session($session) or
341 return (undef, OpenILS::Event->new('NO_SESSION'));
346 # verifiese the session and checks the permissions agains the
347 # session user and the user's home_ou as the org id
349 my( $self, $session, @perms ) = @_;
350 my $user; my $evt; my $e;
351 $logger->debug("Checking user session $session and perms @perms");
352 ($user, $evt) = $self->checkses($session);
353 return (undef, $evt) if $evt;
354 $evt = $self->check_perms($user->id, $user->home_ou, @perms);
355 return ($user, $evt);
360 my( $self, $staffobj, $userid, @perms ) = @_;
362 $userid = $staffobj->id unless defined $userid;
364 $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
366 if( $userid ne $staffobj->id ) {
367 ($user, $evt) = $self->fetch_user($userid);
368 return (undef, $evt) if $evt;
369 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
375 return ($user, $evt);
378 sub checkses_requestor {
379 my( $self, $authtoken, $targetid, @perms ) = @_;
380 my( $requestor, $target, $evt );
382 ($requestor, $evt) = $self->checkses($authtoken);
383 return (undef, undef, $evt) if $evt;
385 ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
386 return( $requestor, $target, $evt);
390 my( $self, $copyid ) = @_;
393 $logger->debug("Fetching copy $copyid from cstore");
395 $copy = $self->simplereq(
397 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
399 if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
401 return( $copy, $evt );
405 # retrieves a circ object by id
406 sub fetch_circulation {
407 my( $self, $circid ) = @_;
410 $logger->debug("Fetching circ $circid from cstore");
412 $circ = $self->simplereq(
414 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
417 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
420 return ( $circ, $evt );
423 sub fetch_record_by_copy {
424 my( $self, $copyid ) = @_;
427 $logger->debug("Fetching record by copy $copyid from cstore");
429 $record = $self->simplereq(
431 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
433 flesh_fields => { bre => [ 'fixed_fields' ],
435 acp => [ 'call_number' ],
441 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
443 $record = $record->call_number->record;
446 return ($record, $evt);
449 # turns a record object into an mvr (mods) object
451 my( $self, $record ) = @_;
452 return undef unless $record and $record->marc;
453 my $u = OpenILS::Utils::ModsParser->new();
454 $u->start_mods_batch( $record->marc );
455 my $mods = $u->finish_mods_batch();
456 $mods->doc_id($record->id);
457 $mods->tcn($record->tcn_value);
462 my( $self, $holdid ) = @_;
465 $logger->debug("Fetching hold $holdid from cstore");
467 $hold = $self->simplereq(
469 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
471 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
473 return ($hold, $evt);
477 sub fetch_hold_transit_by_hold {
478 my( $self, $holdid ) = @_;
479 my( $transit, $evt );
481 $logger->debug("Fetching transit by hold $holdid from cstore");
483 $transit = $self->simplereq(
485 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
487 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
489 return ($transit, $evt );
492 # fetches the captured, but not fulfilled hold attached to a given copy
493 sub fetch_open_hold_by_copy {
494 my( $self, $copyid ) = @_;
495 $logger->debug("Searching for active hold for copy $copyid");
498 $hold = $self->cstorereq(
499 'open-ils.cstore.direct.action.hold_request.search',
501 current_copy => $copyid ,
502 capture_time => { "!=" => undef },
503 fulfillment_time => undef,
504 cancel_time => undef,
507 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
508 return ($hold, $evt);
511 sub fetch_hold_transit {
512 my( $self, $transid ) = @_;
513 my( $htransit, $evt );
514 $logger->debug("Fetching hold transit with hold id $transid");
515 $htransit = $self->cstorereq(
516 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
517 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
518 return ($htransit, $evt);
521 sub fetch_copy_by_barcode {
522 my( $self, $barcode ) = @_;
525 $logger->debug("Fetching copy by barcode $barcode from cstore");
527 $copy = $self->simplereq( 'open-ils.cstore',
528 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
529 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
531 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
533 return ($copy, $evt);
536 sub fetch_open_billable_transaction {
537 my( $self, $transid ) = @_;
538 my( $transaction, $evt );
540 $logger->debug("Fetching open billable transaction $transid from cstore");
542 $transaction = $self->simplereq(
544 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve', $transid);
546 $evt = OpenILS::Event->new(
547 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
549 return ($transaction, $evt);
555 $buckets{'biblio'} = 'biblio_record_entry_bucket';
556 $buckets{'callnumber'} = 'call_number_bucket';
557 $buckets{'copy'} = 'copy_bucket';
558 $buckets{'user'} = 'user_bucket';
560 sub fetch_container {
561 my( $self, $id, $type ) = @_;
564 $logger->debug("Fetching container $id with type $type");
566 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
567 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
568 $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
569 $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
571 my $meth = $buckets{$type};
572 $bucket = $self->simplereq(
574 "open-ils.cstore.direct.container.$meth.retrieve", $id );
576 $evt = OpenILS::Event->new(
577 $e, container => $id, container_type => $type ) unless $bucket;
579 return ($bucket, $evt);
583 sub fetch_container_e {
584 my( $self, $editor, $id, $type ) = @_;
587 $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
588 $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
589 $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
590 $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
592 $evt = $editor->event unless $bucket;
593 return ($bucket, $evt);
596 sub fetch_container_item_e {
597 my( $self, $editor, $id, $type ) = @_;
600 $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
601 $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
602 $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
603 $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
605 $evt = $editor->event unless $bucket;
606 return ($bucket, $evt);
613 sub fetch_container_item {
614 my( $self, $id, $type ) = @_;
617 $logger->debug("Fetching container item $id with type $type");
619 my $meth = $buckets{$type} . "_item";
621 $bucket = $self->simplereq(
623 "open-ils.cstore.direct.container.$meth.retrieve", $id );
626 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
627 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
628 $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
629 $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
631 $evt = OpenILS::Event->new(
632 $e, itemid => $id, container_type => $type ) unless $bucket;
634 return ($bucket, $evt);
638 sub fetch_patron_standings {
640 $logger->debug("Fetching patron standings");
641 return $self->simplereq(
643 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
647 sub fetch_permission_group_tree {
649 $logger->debug("Fetching patron profiles");
650 return $self->simplereq(
652 'open-ils.actor.groups.tree.retrieve' );
655 sub fetch_permission_group_descendants {
656 my( $self, $profile ) = @_;
657 my $group_tree = $self->fetch_permission_group_tree();
661 # FIXME: okay, so it's not an org tree, but it is compatible
662 $self->walk_org_tree($group_tree, sub {
664 if ($g->id == $profile) {
669 $self->walk_org_tree($start_here, sub {
671 push(@groups,$g->id);
677 sub fetch_patron_circ_summary {
678 my( $self, $userid ) = @_;
679 $logger->debug("Fetching patron summary for $userid");
680 my $summary = $self->simplereq(
682 "open-ils.storage.action.circulation.patron_summary", $userid );
686 $summary->[1] ||= 0.0;
693 sub fetch_copy_statuses {
695 $logger->debug("Fetching copy statuses");
696 return $self->simplereq(
698 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
701 sub fetch_copy_location {
702 my( $self, $id ) = @_;
704 my $cl = $self->cstorereq(
705 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
706 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
710 sub fetch_copy_locations {
712 return $self->simplereq(
714 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
717 sub fetch_copy_location_by_name {
718 my( $self, $name, $org ) = @_;
720 my $cl = $self->cstorereq(
721 'open-ils.cstore.direct.asset.copy_location.search',
722 { name => $name, owning_lib => $org } );
723 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
727 sub fetch_callnumber {
728 my( $self, $id, $flesh, $e ) = @_;
730 $e ||= OpenILS::Utils::CStoreEditor->new;
732 my $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
733 return( undef, $evt ) unless $id;
735 $logger->debug("Fetching callnumber $id");
737 my $cn = $e->retrieve_asset_call_number([
739 { flesh => $flesh, flesh_fields => { acn => [ 'prefix', 'suffix', 'label_class' ] } },
742 return ( $cn, $e->event );
745 my %ORG_CACHE; # - these rarely change, so cache them..
747 my( $self, $id ) = @_;
748 return undef unless $id;
749 return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
750 return $ORG_CACHE{$id} if $ORG_CACHE{$id};
751 $logger->debug("Fetching org unit $id");
754 my $org = $self->simplereq(
756 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
757 $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
758 $ORG_CACHE{$id} = $org;
764 my( $self, $type, $id ) = @_;
766 $logger->debug("Fetching $type stat cat: $id");
767 $cat = $self->simplereq(
769 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
771 my $e = 'ASSET_STAT_CAT_NOT_FOUND';
772 $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
774 $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
775 return ( $cat, $evt );
778 sub fetch_stat_cat_entry {
779 my( $self, $type, $id ) = @_;
781 $logger->debug("Fetching $type stat cat entry: $id");
782 $entry = $self->simplereq(
784 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
786 my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
787 $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
789 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
790 return ( $entry, $evt );
793 sub fetch_stat_cat_entry_default {
794 my( $self, $type, $id ) = @_;
795 my( $entry_default, $evt );
796 $logger->debug("Fetching $type stat cat entry default: $id");
797 $entry_default = $self->simplereq(
799 "open-ils.cstore.direct.$type.stat_cat_entry_default.retrieve", $id );
801 my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
802 $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
804 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry_default;
805 return ( $entry_default, $evt );
808 sub fetch_stat_cat_entry_default_by_stat_cat_and_org {
809 my( $self, $type, $stat_cat, $orgId ) = @_;
811 $logger->info("### Fetching $type stat cat entry default with stat_cat $stat_cat owned by org_unit $orgId");
812 $entry_default = $self->simplereq(
814 "open-ils.cstore.direct.$type.stat_cat_entry_default.search.atomic",
815 { stat_cat => $stat_cat, owner => $orgId } );
817 $entry_default = $entry_default->[0];
818 return ($entry_default, undef) if $entry_default;
820 my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
821 $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
822 return (undef, OpenILS::Event->new($e) );
826 my( $self, $org_tree, $orgid ) = @_;
827 return undef unless $org_tree and defined $orgid;
828 return $org_tree if ( $org_tree->id eq $orgid );
829 return undef unless ref($org_tree->children);
830 for my $c (@{$org_tree->children}) {
831 my $o = $self->find_org($c, $orgid);
837 sub fetch_non_cat_type_by_name_and_org {
838 my( $self, $name, $orgId ) = @_;
839 $logger->debug("Fetching non cat type $name at org $orgId");
840 my $types = $self->simplereq(
842 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
843 { name => $name, owning_lib => $orgId } );
844 return ($types->[0], undef) if($types and @$types);
845 return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
848 sub fetch_non_cat_type {
849 my( $self, $id ) = @_;
850 $logger->debug("Fetching non cat type $id");
852 $type = $self->simplereq(
854 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
855 $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
856 return ($type, $evt);
859 sub DB_UPDATE_FAILED {
860 my( $self, $payload ) = @_;
861 return OpenILS::Event->new('DATABASE_UPDATE_FAILED',
862 payload => ($payload) ? $payload : undef );
865 sub fetch_booking_reservation {
866 my( $self, $id ) = @_;
869 $res = $self->simplereq(
871 'open-ils.cstore.direct.booking.reservation.retrieve', $id
874 # simplereq doesn't know how to flesh so ...
879 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
883 $res->target_resource_type(
886 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
890 if ($res->current_resource) {
891 $res->current_resource(
894 'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
898 if ($self->is_true( $res->target_resource_type->catalog_item )) {
899 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
903 if ($res->target_resource) {
904 $res->target_resource(
907 'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
911 if ($self->is_true( $res->target_resource_type->catalog_item )) {
912 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
917 $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
923 sub fetch_circ_duration_by_name {
924 my( $self, $name ) = @_;
926 $dur = $self->simplereq(
928 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
930 $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
934 sub fetch_recurring_fine_by_name {
935 my( $self, $name ) = @_;
937 $obj = $self->simplereq(
939 'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
941 $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
945 sub fetch_max_fine_by_name {
946 my( $self, $name ) = @_;
948 $obj = $self->simplereq(
950 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
952 $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
956 sub fetch_hard_due_date_by_name {
957 my( $self, $name ) = @_;
959 $obj = $self->simplereq(
961 'open-ils.cstore.direct.config.hard_due_date.search.atomic', { name => $name } );
963 $evt = OpenILS::Event->new('CONFIG_RULES_HARD_DUE_DATE_NOT_FOUND') unless $obj;
968 my( $self, $method, @params ) = @_;
969 return $self->simplereq(
970 'open-ils.storage', $method, @params );
973 sub storagereq_xact {
974 my($self, $method, @params) = @_;
975 my $ses = $self->start_db_session();
976 my $val = $ses->request($method, @params)->gather(1);
977 $self->rollback_db_session($ses);
982 my( $self, $method, @params ) = @_;
983 return $self->simplereq(
984 'open-ils.cstore', $method, @params );
988 my( $self, $e, $name ) = @_;
989 if( $e and ref($e) eq 'HASH' and
990 defined($e->{textcode}) and $e->{textcode} eq $name ) {
997 my( undef, $f, $l ) = caller(0);
998 my( undef, undef, undef, $s ) = caller(1);
1001 $logger->debug("LOGMARK: $f:$l:$s");
1005 sub fetch_open_circulation {
1006 my( $self, $cid ) = @_;
1009 my $e = OpenILS::Utils::CStoreEditor->new;
1010 my $circ = $e->search_action_circulation({
1011 target_copy => $cid,
1012 stop_fines_time => undef,
1013 checkin_time => undef
1016 return ($circ, $e->event);
1020 sub copy_status_from_name {
1021 my( $self, $name ) = @_;
1022 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
1023 for my $status (@$copy_statuses) {
1024 return $status if( $status->name =~ /$name/i );
1029 sub copy_status_to_name {
1030 my( $self, $sid ) = @_;
1031 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
1032 for my $status (@$copy_statuses) {
1033 return $status->name if( $status->id == $sid );
1040 my( $self, $arg ) = @_;
1041 return $arg if ref $arg;
1042 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
1043 my ($stat) = grep { $_->id == $arg } @$copy_statuses;
1047 sub fetch_open_transit_by_copy {
1048 my( $self, $copyid ) = @_;
1050 $transit = $self->cstorereq(
1051 'open-ils.cstore.direct.action.transit_copy.search',
1052 { target_copy => $copyid, dest_recv_time => undef });
1053 $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
1054 return ($transit, $evt);
1058 my( $self, $copy ) = @_;
1059 return undef unless $copy;
1060 $copy->status( $copy->status->id ) if ref($copy->status);
1061 $copy->location( $copy->location->id ) if ref($copy->location);
1062 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1066 sub unflesh_reservation {
1067 my( $self, $reservation ) = @_;
1068 return undef unless $reservation;
1069 $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
1070 $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
1071 $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
1072 $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
1073 return $reservation;
1076 # un-fleshes a copy and updates it in the DB
1077 # returns a DB_UPDATE_FAILED event on error
1078 # returns undef on success
1080 my( $self, %params ) = @_;
1082 my $copy = $params{copy} || die "update_copy(): copy required";
1083 my $editor = $params{editor} || die "update_copy(): copy editor required";
1084 my $session = $params{session};
1086 $logger->debug("Updating copy in the database: " . $copy->id);
1088 $self->unflesh_copy($copy);
1089 $copy->editor( $editor );
1090 $copy->edit_date( 'now' );
1093 my $meth = 'open-ils.storage.direct.asset.copy.update';
1095 $s = $session->request( $meth, $copy )->gather(1) if $session;
1096 $s = $self->storagereq( $meth, $copy ) unless $session;
1098 $logger->debug("Update of copy ".$copy->id." returned: $s");
1100 return $self->DB_UPDATE_FAILED($copy) unless $s;
1104 sub update_reservation {
1105 my( $self, %params ) = @_;
1107 my $reservation = $params{reservation} || die "update_reservation(): reservation required";
1108 my $editor = $params{editor} || die "update_reservation(): copy editor required";
1109 my $session = $params{session};
1111 $logger->debug("Updating copy in the database: " . $reservation->id);
1113 $self->unflesh_reservation($reservation);
1116 my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1118 $s = $session->request( $meth, $reservation )->gather(1) if $session;
1119 $s = $self->cstorereq( $meth, $reservation ) unless $session;
1121 $logger->debug("Update of copy ".$reservation->id." returned: $s");
1123 return $self->DB_UPDATE_FAILED($reservation) unless $s;
1127 sub fetch_billable_xact {
1128 my( $self, $id ) = @_;
1130 $logger->debug("Fetching billable transaction %id");
1131 $xact = $self->cstorereq(
1132 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1133 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1134 return ($xact, $evt);
1137 sub fetch_billable_xact_summary {
1138 my( $self, $id ) = @_;
1140 $logger->debug("Fetching billable transaction summary %id");
1141 $xact = $self->cstorereq(
1142 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1143 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1144 return ($xact, $evt);
1147 sub fetch_fleshed_copy {
1148 my( $self, $id ) = @_;
1150 $logger->info("Fetching fleshed copy $id");
1151 $copy = $self->cstorereq(
1152 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1154 flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1157 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1158 return ($copy, $evt);
1162 # returns the org that owns the callnumber that the copy
1164 sub fetch_copy_owner {
1165 my( $self, $copyid ) = @_;
1166 my( $copy, $cn, $evt );
1167 $logger->debug("Fetching copy owner $copyid");
1168 ($copy, $evt) = $self->fetch_copy($copyid);
1169 return (undef,$evt) if $evt;
1170 ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1171 return (undef,$evt) if $evt;
1172 return ($cn->owning_lib);
1175 sub fetch_copy_note {
1176 my( $self, $id ) = @_;
1178 $logger->debug("Fetching copy note $id");
1179 $note = $self->cstorereq(
1180 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1181 $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1182 return ($note, $evt);
1185 sub fetch_call_numbers_by_title {
1186 my( $self, $titleid ) = @_;
1187 $logger->info("Fetching call numbers by title $titleid");
1188 return $self->cstorereq(
1189 'open-ils.cstore.direct.asset.call_number.search.atomic',
1190 { record => $titleid, deleted => 'f' });
1191 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1194 sub fetch_copies_by_call_number {
1195 my( $self, $cnid ) = @_;
1196 $logger->info("Fetching copies by call number $cnid");
1197 return $self->cstorereq(
1198 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1199 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1202 sub fetch_user_by_barcode {
1203 my( $self, $bc ) = @_;
1204 my $cardid = $self->cstorereq(
1205 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1206 return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1207 my $user = $self->cstorereq(
1208 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1209 return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1215 my( $self, $billid ) = @_;
1216 $logger->debug("Fetching billing $billid");
1217 my $bill = $self->cstorereq(
1218 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1219 my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1220 return($bill, $evt);
1224 sub fetch_org_tree {
1226 return $ORG_TREE if $ORG_TREE;
1227 return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit(
1229 {"parent_ou" => undef },
1232 flesh_fields => { aou => ['children'] },
1233 order_by => { aou => 'name'}
1240 my( $self, $node, $callback ) = @_;
1241 return unless $node;
1243 if( $node->children ) {
1244 $self->walk_org_tree($_, $callback) for @{$node->children};
1249 my( $self, $item ) = @_;
1250 return 1 if $item and $item !~ /^f$/i;
1256 my ($self, $client, $service, $method, @params) = @_;
1257 my ($response, $err);
1259 my $session = create OpenSRF::AppSession($service);
1260 my $request = $session->request($method, @params);
1263 my $give_up = time + 1000;
1266 while (time < $give_up) {
1267 $response = $request->recv("timeout" => $spurt);
1268 last if $request->complete;
1270 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1272 } catch Error with {
1277 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
1278 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
1281 return $response->content;
1284 # This logic now lives in storage
1285 sub __patron_money_owed {
1286 my( $self, $patronid ) = @_;
1287 my $ses = OpenSRF::AppSession->create('open-ils.storage');
1288 my $req = $ses->request(
1289 'open-ils.storage.money.billable_transaction.summary.search',
1290 { usr => $patronid, xact_finish => undef } );
1294 while( $data = $req->recv ) {
1295 $data = $data->content;
1296 $total += $data->balance_owed;
1301 sub patron_money_owed {
1302 my( $self, $userid ) = @_;
1303 my $ses = $self->start_db_session();
1304 my $val = $ses->request(
1305 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1306 $self->rollback_db_session($ses);
1310 sub patron_total_items_out {
1311 my( $self, $userid ) = @_;
1312 my $ses = $self->start_db_session();
1313 my $val = $ses->request(
1314 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1315 $self->rollback_db_session($ses);
1322 #---------------------------------------------------------------------
1323 # Returns ($summary, $event)
1324 #---------------------------------------------------------------------
1328 my $e = shift || OpenILS::Utils::CStoreEditor->new;
1329 $id = $id->id if ref($id);
1331 my $xact = $e->retrieve_money_billable_transaction_summary($id)
1332 or return (undef, $e->event);
1338 #---------------------------------------------------------------------
1339 # Given a list of money.billable_transaction objects, this creates
1340 # transaction summary objects for each
1341 #--------------------------------------------------------------------
1346 return () if (!@xacts);
1347 return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1351 sub ou_ancestor_setting_value {
1352 my($self, $org_id, $name, $e) = @_;
1353 $e = $e || OpenILS::Utils::CStoreEditor->new;
1354 my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1355 return $set->{value} if $set;
1360 # If an authentication token is provided AND this org unit setting has a
1361 # view_perm, then make sure the user referenced by the auth token has
1362 # that permission. This means that if you call this method without an
1363 # authtoken param, you can get whatever org unit setting values you want.
1366 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1367 # authtoken is checked, but the $auth arg is NOT checked. To say that another
1368 # way, be sure NOT to pass an editor argument if you want your token checked.
1369 # Otherwise the auth arg is just a flag saying "check the editor".
1371 sub ou_ancestor_setting {
1372 my( $self, $orgid, $name, $e, $auth ) = @_;
1373 $e = $e || OpenILS::Utils::CStoreEditor->new(
1374 (defined $auth) ? (authtoken => $auth) : ()
1376 my $coust = $e->retrieve_config_org_unit_setting_type([
1377 $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1380 if ($auth && $coust && $coust->view_perm) {
1381 # And you can't have permission if you don't have a valid session.
1382 return undef if not $e->checkauth;
1383 # And now that we know you MIGHT have permission, we check it.
1384 return undef if not $e->allowed($coust->view_perm->code, $orgid);
1387 my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1388 my $setting = $e->json_query($query)->[0];
1389 return undef unless $setting;
1390 return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1394 # returns the ISO8601 string representation of the requested epoch in GMT
1396 my( $self, $epoch ) = @_;
1397 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1398 $year += 1900; $mon += 1;
1400 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1401 $year, $mon, $mday, $hour, $min, $sec);
1405 sub find_highest_perm_org {
1406 my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1407 my $org = $self->find_org($org_tree, $start_org );
1411 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1413 $org = $self->find_org( $org_tree, $org->parent_ou() );
1420 # returns the org_unit ID's
1421 sub user_has_work_perm_at {
1422 my($self, $e, $perm, $options, $user_id) = @_;
1424 $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1426 my $func = 'permission.usr_has_perm_at';
1427 $func = $func.'_all' if $$options{descendants};
1429 my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1430 $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1432 return $orgs unless $$options{objects};
1434 return $e->search_actor_org_unit({id => $orgs});
1437 sub get_user_work_ou_ids {
1438 my($self, $e, $userid) = @_;
1439 my $work_orgs = $e->json_query({
1440 select => {puwoum => ['work_ou']},
1442 where => {usr => $e->requestor->id}});
1444 return [] unless @$work_orgs;
1446 push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1454 my($self, $client) = @_;
1455 return $org_types if $org_types;
1456 return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1461 my $locale = shift || '';
1462 my $cache = OpenSRF::Utils::Cache->new("global", 0);
1463 my $tree = $cache->get_cache("orgtree.$locale");
1464 return $tree if $tree;
1466 my $ses = OpenILS::Utils::CStoreEditor->new;
1467 $ses->session->session_locale($locale);
1468 $tree = $ses->search_actor_org_unit(
1470 {"parent_ou" => undef },
1473 flesh_fields => { aou => ['children'] },
1474 order_by => { aou => 'name'}
1479 $cache->put_cache("orgtree.$locale", $tree);
1483 sub get_org_descendants {
1484 my($self, $org_id, $depth) = @_;
1487 transform => 'actor.org_unit_descendants',
1489 result_field => 'id',
1491 $select->{params} = [$depth] if defined $depth;
1493 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1494 select => {aou => [$select]},
1496 where => {id => $org_id}
1499 push(@orgs, $_->{id}) for @$org_list;
1503 sub get_org_ancestors {
1504 my($self, $org_id, $use_cache) = @_;
1509 $cache = OpenSRF::Utils::Cache->new("global", 0);
1510 $orgs = $cache->get_cache("org.ancestors.$org_id");
1511 return $orgs if $orgs;
1514 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1517 transform => 'actor.org_unit_ancestors',
1519 result_field => 'id',
1524 where => {id => $org_id}
1527 $orgs = [ map { $_->{id} } @$org_list ];
1529 $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1533 sub get_org_full_path {
1534 my($self, $org_id, $depth) = @_;
1539 transform => 'actor.org_unit_full_path',
1541 result_field => 'id',
1545 where => {id => $org_id}
1548 $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1549 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1550 return [ map {$_->{id}} @$org_list ];
1553 # returns the ID of the org unit ancestor at the specified depth
1554 sub org_unit_ancestor_at_depth {
1555 my($class, $org_id, $depth) = @_;
1556 my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1557 {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1558 return ($resp) ? $resp->{id} : undef;
1561 # returns the user's configured locale as a string. Defaults to en-US if none is configured.
1562 sub get_user_locale {
1563 my($self, $user_id, $e) = @_;
1564 $e ||= OpenILS::Utils::CStoreEditor->new;
1566 # first, see if the user has an explicit locale set
1567 my $setting = $e->search_actor_user_setting(
1568 {usr => $user_id, name => 'global.locale'})->[0];
1569 return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1571 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1572 return $self->get_org_locale($user->home_ou, $e);
1575 # returns org locale setting
1576 sub get_org_locale {
1577 my($self, $org_id, $e) = @_;
1578 $e ||= OpenILS::Utils::CStoreEditor->new;
1581 if(defined $org_id) {
1582 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1583 return $locale if $locale;
1586 # system-wide default
1587 my $sclient = OpenSRF::Utils::SettingsClient->new;
1588 $locale = $sclient->config_value('default_locale');
1589 return $locale if $locale;
1591 # if nothing else, fallback to locale=cowboy
1596 # xml-escape non-ascii characters
1598 my($self, $string, $form) = @_;
1601 # If we're going to convert non-ASCII characters to XML entities,
1602 # we had better be dealing with a UTF8 string to begin with
1603 $string = decode_utf8($string);
1606 $string = NFD($string);
1608 $string = NFC($string);
1611 # Convert raw ampersands to entities
1612 $string =~ s/&(?!\S+;)/&/gso;
1614 # Convert Unicode characters to entities
1615 $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1620 # x0000-x0008 isn't legal in XML documents
1621 # XXX Perhaps this should just go into our standard entityize method
1622 sub strip_ctrl_chars {
1623 my ($self, $string) = @_;
1625 $string =~ s/([\x{0000}-\x{0008}])//sgoe;
1629 sub get_copy_price {
1630 my($self, $e, $copy, $volume) = @_;
1632 $copy->price(0) if $copy->price and $copy->price < 0;
1634 return $copy->price if $copy->price and $copy->price > 0;
1639 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1640 $owner = $copy->circ_lib;
1642 $owner = $volume->owning_lib;
1645 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1646 $owner = $copy->circ_lib;
1648 $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1652 my $default_price = $self->ou_ancestor_setting_value(
1653 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1655 return $default_price unless defined $copy->price;
1657 # price is 0. Use the default?
1658 my $charge_on_0 = $self->ou_ancestor_setting_value(
1659 $owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e) || 0;
1661 return $default_price if $charge_on_0;
1665 # given a transaction ID, this returns the context org_unit for the transaction
1667 my($self, $xact_id, $e) = @_;
1668 $e ||= OpenILS::Utils::CStoreEditor->new;
1670 my $loc = $e->json_query({
1671 "select" => {circ => ["circ_lib"]},
1673 "where" => {id => $xact_id},
1676 return $loc->[0]->{circ_lib} if @$loc;
1678 $loc = $e->json_query({
1679 "select" => {bresv => ["request_lib"]},
1681 "where" => {id => $xact_id},
1684 return $loc->[0]->{request_lib} if @$loc;
1686 $loc = $e->json_query({
1687 "select" => {mg => ["billing_location"]},
1689 "where" => {id => $xact_id},
1692 return $loc->[0]->{billing_location};
1696 sub find_event_def_by_hook {
1697 my($self, $hook, $context_org, $e) = @_;
1699 $e ||= OpenILS::Utils::CStoreEditor->new;
1701 my $orgs = $self->get_org_ancestors($context_org);
1703 # search from the context org up
1704 for my $org_id (reverse @$orgs) {
1706 my $def = $e->search_action_trigger_event_definition(
1707 {hook => $hook, owner => $org_id})->[0];
1709 return $def if $def;
1717 # If an event_def ID is not provided, use the hook and context org to find the
1718 # most appropriate event. create the event, fire it, then return the resulting
1719 # event with fleshed template_output and error_output
1720 sub fire_object_event {
1721 my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1723 my $e = OpenILS::Utils::CStoreEditor->new;
1726 my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1729 $def = $e->retrieve_action_trigger_event_definition($event_def)
1730 or return $e->event;
1732 $auto_method .= '.include_inactive';
1736 # find the most appropriate event def depending on context org
1737 $def = $self->find_event_def_by_hook($hook, $context_org, $e)
1738 or return $e->event;
1743 if($def->group_field) {
1744 # we have a list of objects
1745 $object = [$object] unless ref $object eq 'ARRAY';
1749 for my $i (0..$#$object) {
1750 my $obj = $$object[$i];
1751 my $udata = $$user_data[$i];
1752 my $event_id = $self->simplereq(
1753 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1754 push(@event_ids, $event_id);
1757 $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1760 if (not defined $client) {
1761 $resp = $self->simplereq(
1763 'open-ils.trigger.event_group.fire',
1766 $resp = $self->patientreq(
1768 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1773 if($resp and $resp->{events} and @{$resp->{events}}) {
1776 $final_resp = $e->retrieve_action_trigger_event([
1777 $resp->{events}->[0]->id,
1778 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1785 $object = $$object[0] if ref $object eq 'ARRAY';
1790 if (not defined $client) {
1791 $event_id = $self->simplereq(
1793 $auto_method, $def->id, $object, $context_org, $user_data
1796 $resp = $self->simplereq(
1798 'open-ils.trigger.event.fire',
1802 $event_id = $self->patientreq(
1805 $auto_method, $def->id, $object, $context_org, $user_data
1808 $resp = $self->patientreq(
1811 'open-ils.trigger.event.fire',
1816 if($resp and $resp->{event}) {
1818 $final_resp = $e->retrieve_action_trigger_event([
1820 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1830 sub create_events_for_hook {
1831 my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1832 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1833 my $req = $ses->request('open-ils.trigger.event.autocreate',
1834 $hook, $obj, $org_id, $granularity, $user_data);
1835 return undef unless $wait;
1836 my $resp = $req->recv;
1837 return $resp->content if $resp;
1840 sub create_uuid_string {
1841 return create_UUID_as_string();
1844 sub create_circ_chain_summary {
1845 my($class, $e, $circ_id) = @_;
1846 my $sum = $e->json_query({from => ['action.summarize_circ_chain', $circ_id]})->[0];
1847 return undef unless $sum;
1848 my $obj = Fieldmapper::action::circ_chain_summary->new;
1849 $obj->$_($sum->{$_}) for keys %$sum;
1854 # Returns "mra" attribute key/value pairs for a set of bre's
1855 # Takes a list of bre IDs, returns a hash of hashes,
1856 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1859 my ($class, $bre_ids, $e) = @_;
1860 $e = $e || OpenILS::Utils::CStoreEditor->new;
1863 return $attrs unless defined $bre_ids;
1864 $bre_ids = [$bre_ids] unless ref $bre_ids;
1866 my $mra = $e->json_query({
1874 transform => 'each',
1875 result_field => 'key',
1879 transform => 'each',
1880 result_field => 'value',
1886 where => {id => $bre_ids}
1889 return $attrs unless $mra;
1891 $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
1893 for my $id (@$bre_ids) {
1895 for my $mra (grep { $_->{bre} eq $id } @$mra) {
1896 my $ctype = $mra->{key};
1897 my $code = $mra->{value};
1898 $attrs->{$id}->{$ctype} = {code => $code};
1900 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
1901 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
1909 # Shorter version of bib_container_items_via_search() below, only using
1910 # the queryparser record_list filter instead of the container filter.
1911 sub bib_record_list_via_search {
1912 my ($class, $search_query, $search_args) = @_;
1914 # First, Use search API to get container items sorted in any way that crad
1916 my $search_result = $class->simplereq(
1917 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1918 $search_args, $search_query
1921 unless ($search_result) {
1922 # empty result sets won't cause this, but actual errors should.
1923 $logger->warn("bib_record_list_via_search() got nothing from search");
1927 # Throw away other junk from search, keeping only bib IDs.
1928 return [ map { pop @$_ } @{$search_result->{ids}} ];
1931 # 'no_flesh' avoids fleshing the target_biblio_record_entry
1932 sub bib_container_items_via_search {
1933 my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
1935 # First, Use search API to get container items sorted in any way that crad
1937 my $search_result = $class->simplereq(
1938 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1939 $search_args, $search_query
1941 unless ($search_result) {
1942 # empty result sets won't cause this, but actual errors should.
1943 $logger->warn("bib_container_items_via_search() got nothing from search");
1947 # Throw away other junk from search, keeping only bib IDs.
1948 my $id_list = [ map { pop @$_ } @{$search_result->{ids}} ];
1950 return [] unless @$id_list;
1952 # Now get the bib container items themselves...
1953 my $e = new OpenILS::Utils::CStoreEditor;
1955 $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
1959 my @flesh_fields = qw/notes/;
1960 push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
1962 my $items = $e->search_container_biblio_record_entry_bucket_item([
1964 "target_biblio_record_entry" => $id_list,
1965 "bucket" => $container_id
1968 flesh_fields => {"cbrebi" => \@flesh_fields}
1973 "bib_container_items_via_search() couldn't get bucket items: " .
1974 $e->die_event->{textcode}
1979 # ... and put them in the same order that the search API said they
1981 my %ordering_hash = map {
1982 ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id,
1986 return [map { $ordering_hash{$_} } @$id_list];
1989 # returns undef on success, Event on error
1990 sub log_user_activity {
1991 my ($class, $user_id, $who, $what, $e, $async) = @_;
1995 $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
1999 my $res = $e->json_query({
2001 'actor.insert_usr_activity',
2002 $user_id, $who, $what, OpenSRF::AppSession->ingress
2006 if ($res) { # call returned OK
2008 $e->commit if $commit and @$res;
2009 $e->rollback if $commit and !@$res;
2012 return $e->die_event;
2018 # I hate to put this here exactly, but this code needs to be shared between
2019 # the TPAC's mod_perl module and open-ils.serial.
2021 # There is a reason every part of the query *except* those parts dealing
2022 # with scope are moved here from the code's origin in TPAC. The serials
2023 # use case does *not* want the same scoping logic.
2025 # Also, note that for the serials uses case, we may filter in OPAC visible
2026 # status and copy/call_number deletedness, but we don't filter on any
2027 # particular values for serial.item.status or serial.item.date_received.
2028 # Since we're only using this *after* winnowing down the set of issuances
2029 # that copies should be related to, I'm not sure we need any such serial.item
2032 sub basic_opac_copy_query {
2033 ######################################################################
2034 # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
2036 ######################################################################
2037 my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
2041 acp => ['id', 'barcode', 'circ_lib', 'create_date',
2042 'age_protect', 'holdable'],
2044 {column => 'name', alias => 'copy_location'},
2045 {column => 'holdable', alias => 'location_holdable'}
2048 {column => 'name', alias => 'copy_status'},
2049 {column => 'holdable', alias => 'status_holdable'}
2052 {column => 'label', alias => 'call_number_label'},
2053 {column => 'id', alias => 'call_number'}
2055 circ => ['due_date'],
2057 {column => 'label', alias => 'call_number_prefix_label'},
2058 {column => 'id', alias => 'call_number_prefix'}
2061 {column => 'label', alias => 'call_number_suffix_label'},
2062 {column => 'id', alias => 'call_number_suffix'}
2065 {column => 'label', alias => 'part_label'},
2067 ($iss_id ? (sitem => ["issuance"]) : ())
2076 filter => {issuance => $iss_id},
2084 acnp => { fkey => 'prefix' },
2085 acns => { fkey => 'suffix' }
2089 ($rec_id ? {record => $rec_id} : ())
2092 circ => { # If the copy is circulating, retrieve the open circ
2094 filter => {checkin_time => undef}
2097 ($staff ? () : (filter => { opac_visible => 't' }))
2100 ($staff ? () : (filter => { opac_visible => 't' }))
2106 bmp => { type => 'left' }
2115 ($staff ? () : (opac_visible => 't'))
2117 ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2118 ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2122 {class => 'aou', field => 'name'},
2123 {class => 'acn', field => 'label'}
2126 limit => $copy_limit,
2127 offset => $copy_offset