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 );
795 my( $self, $org_tree, $orgid ) = @_;
796 return undef unless $org_tree and defined $orgid;
797 return $org_tree if ( $org_tree->id eq $orgid );
798 return undef unless ref($org_tree->children);
799 for my $c (@{$org_tree->children}) {
800 my $o = $self->find_org($c, $orgid);
806 sub fetch_non_cat_type_by_name_and_org {
807 my( $self, $name, $orgId ) = @_;
808 $logger->debug("Fetching non cat type $name at org $orgId");
809 my $types = $self->simplereq(
811 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
812 { name => $name, owning_lib => $orgId } );
813 return ($types->[0], undef) if($types and @$types);
814 return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
817 sub fetch_non_cat_type {
818 my( $self, $id ) = @_;
819 $logger->debug("Fetching non cat type $id");
821 $type = $self->simplereq(
823 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
824 $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
825 return ($type, $evt);
828 sub DB_UPDATE_FAILED {
829 my( $self, $payload ) = @_;
830 return OpenILS::Event->new('DATABASE_UPDATE_FAILED',
831 payload => ($payload) ? $payload : undef );
834 sub fetch_booking_reservation {
835 my( $self, $id ) = @_;
838 $res = $self->simplereq(
840 'open-ils.cstore.direct.booking.reservation.retrieve', $id
843 # simplereq doesn't know how to flesh so ...
848 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
852 $res->target_resource_type(
855 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
859 if ($res->current_resource) {
860 $res->current_resource(
863 'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
867 if ($self->is_true( $res->target_resource_type->catalog_item )) {
868 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
872 if ($res->target_resource) {
873 $res->target_resource(
876 'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
880 if ($self->is_true( $res->target_resource_type->catalog_item )) {
881 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
886 $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
892 sub fetch_circ_duration_by_name {
893 my( $self, $name ) = @_;
895 $dur = $self->simplereq(
897 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
899 $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
903 sub fetch_recurring_fine_by_name {
904 my( $self, $name ) = @_;
906 $obj = $self->simplereq(
908 'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
910 $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
914 sub fetch_max_fine_by_name {
915 my( $self, $name ) = @_;
917 $obj = $self->simplereq(
919 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
921 $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
925 sub fetch_hard_due_date_by_name {
926 my( $self, $name ) = @_;
928 $obj = $self->simplereq(
930 'open-ils.cstore.direct.config.hard_due_date.search.atomic', { name => $name } );
932 $evt = OpenILS::Event->new('CONFIG_RULES_HARD_DUE_DATE_NOT_FOUND') unless $obj;
937 my( $self, $method, @params ) = @_;
938 return $self->simplereq(
939 'open-ils.storage', $method, @params );
942 sub storagereq_xact {
943 my($self, $method, @params) = @_;
944 my $ses = $self->start_db_session();
945 my $val = $ses->request($method, @params)->gather(1);
946 $self->rollback_db_session($ses);
951 my( $self, $method, @params ) = @_;
952 return $self->simplereq(
953 'open-ils.cstore', $method, @params );
957 my( $self, $e, $name ) = @_;
958 if( $e and ref($e) eq 'HASH' and
959 defined($e->{textcode}) and $e->{textcode} eq $name ) {
966 my( undef, $f, $l ) = caller(0);
967 my( undef, undef, undef, $s ) = caller(1);
970 $logger->debug("LOGMARK: $f:$l:$s");
974 sub fetch_open_circulation {
975 my( $self, $cid ) = @_;
978 my $e = OpenILS::Utils::CStoreEditor->new;
979 my $circ = $e->search_action_circulation({
981 stop_fines_time => undef,
982 checkin_time => undef
985 return ($circ, $e->event);
989 sub copy_status_from_name {
990 my( $self, $name ) = @_;
991 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
992 for my $status (@$copy_statuses) {
993 return $status if( $status->name =~ /$name/i );
998 sub copy_status_to_name {
999 my( $self, $sid ) = @_;
1000 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
1001 for my $status (@$copy_statuses) {
1002 return $status->name if( $status->id == $sid );
1009 my( $self, $arg ) = @_;
1010 return $arg if ref $arg;
1011 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
1012 my ($stat) = grep { $_->id == $arg } @$copy_statuses;
1016 sub fetch_open_transit_by_copy {
1017 my( $self, $copyid ) = @_;
1019 $transit = $self->cstorereq(
1020 'open-ils.cstore.direct.action.transit_copy.search',
1021 { target_copy => $copyid, dest_recv_time => undef });
1022 $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
1023 return ($transit, $evt);
1027 my( $self, $copy ) = @_;
1028 return undef unless $copy;
1029 $copy->status( $copy->status->id ) if ref($copy->status);
1030 $copy->location( $copy->location->id ) if ref($copy->location);
1031 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1035 sub unflesh_reservation {
1036 my( $self, $reservation ) = @_;
1037 return undef unless $reservation;
1038 $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
1039 $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
1040 $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
1041 $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
1042 return $reservation;
1045 # un-fleshes a copy and updates it in the DB
1046 # returns a DB_UPDATE_FAILED event on error
1047 # returns undef on success
1049 my( $self, %params ) = @_;
1051 my $copy = $params{copy} || die "update_copy(): copy required";
1052 my $editor = $params{editor} || die "update_copy(): copy editor required";
1053 my $session = $params{session};
1055 $logger->debug("Updating copy in the database: " . $copy->id);
1057 $self->unflesh_copy($copy);
1058 $copy->editor( $editor );
1059 $copy->edit_date( 'now' );
1062 my $meth = 'open-ils.storage.direct.asset.copy.update';
1064 $s = $session->request( $meth, $copy )->gather(1) if $session;
1065 $s = $self->storagereq( $meth, $copy ) unless $session;
1067 $logger->debug("Update of copy ".$copy->id." returned: $s");
1069 return $self->DB_UPDATE_FAILED($copy) unless $s;
1073 sub update_reservation {
1074 my( $self, %params ) = @_;
1076 my $reservation = $params{reservation} || die "update_reservation(): reservation required";
1077 my $editor = $params{editor} || die "update_reservation(): copy editor required";
1078 my $session = $params{session};
1080 $logger->debug("Updating copy in the database: " . $reservation->id);
1082 $self->unflesh_reservation($reservation);
1085 my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1087 $s = $session->request( $meth, $reservation )->gather(1) if $session;
1088 $s = $self->cstorereq( $meth, $reservation ) unless $session;
1090 $logger->debug("Update of copy ".$reservation->id." returned: $s");
1092 return $self->DB_UPDATE_FAILED($reservation) unless $s;
1096 sub fetch_billable_xact {
1097 my( $self, $id ) = @_;
1099 $logger->debug("Fetching billable transaction %id");
1100 $xact = $self->cstorereq(
1101 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1102 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1103 return ($xact, $evt);
1106 sub fetch_billable_xact_summary {
1107 my( $self, $id ) = @_;
1109 $logger->debug("Fetching billable transaction summary %id");
1110 $xact = $self->cstorereq(
1111 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1112 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1113 return ($xact, $evt);
1116 sub fetch_fleshed_copy {
1117 my( $self, $id ) = @_;
1119 $logger->info("Fetching fleshed copy $id");
1120 $copy = $self->cstorereq(
1121 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1123 flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1126 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1127 return ($copy, $evt);
1131 # returns the org that owns the callnumber that the copy
1133 sub fetch_copy_owner {
1134 my( $self, $copyid ) = @_;
1135 my( $copy, $cn, $evt );
1136 $logger->debug("Fetching copy owner $copyid");
1137 ($copy, $evt) = $self->fetch_copy($copyid);
1138 return (undef,$evt) if $evt;
1139 ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1140 return (undef,$evt) if $evt;
1141 return ($cn->owning_lib);
1144 sub fetch_copy_note {
1145 my( $self, $id ) = @_;
1147 $logger->debug("Fetching copy note $id");
1148 $note = $self->cstorereq(
1149 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1150 $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1151 return ($note, $evt);
1154 sub fetch_call_numbers_by_title {
1155 my( $self, $titleid ) = @_;
1156 $logger->info("Fetching call numbers by title $titleid");
1157 return $self->cstorereq(
1158 'open-ils.cstore.direct.asset.call_number.search.atomic',
1159 { record => $titleid, deleted => 'f' });
1160 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1163 sub fetch_copies_by_call_number {
1164 my( $self, $cnid ) = @_;
1165 $logger->info("Fetching copies by call number $cnid");
1166 return $self->cstorereq(
1167 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1168 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1171 sub fetch_user_by_barcode {
1172 my( $self, $bc ) = @_;
1173 my $cardid = $self->cstorereq(
1174 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1175 return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1176 my $user = $self->cstorereq(
1177 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1178 return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1184 my( $self, $billid ) = @_;
1185 $logger->debug("Fetching billing $billid");
1186 my $bill = $self->cstorereq(
1187 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1188 my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1189 return($bill, $evt);
1193 sub fetch_org_tree {
1195 return $ORG_TREE if $ORG_TREE;
1196 return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit(
1198 {"parent_ou" => undef },
1201 flesh_fields => { aou => ['children'] },
1202 order_by => { aou => 'name'}
1209 my( $self, $node, $callback ) = @_;
1210 return unless $node;
1212 if( $node->children ) {
1213 $self->walk_org_tree($_, $callback) for @{$node->children};
1218 my( $self, $item ) = @_;
1219 return 1 if $item and $item !~ /^f$/i;
1225 my ($self, $client, $service, $method, @params) = @_;
1226 my ($response, $err);
1228 my $session = create OpenSRF::AppSession($service);
1229 my $request = $session->request($method, @params);
1232 my $give_up = time + 1000;
1235 while (time < $give_up) {
1236 $response = $request->recv("timeout" => $spurt);
1237 last if $request->complete;
1239 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1241 } catch Error with {
1246 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
1247 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
1250 return $response->content;
1253 # This logic now lives in storage
1254 sub __patron_money_owed {
1255 my( $self, $patronid ) = @_;
1256 my $ses = OpenSRF::AppSession->create('open-ils.storage');
1257 my $req = $ses->request(
1258 'open-ils.storage.money.billable_transaction.summary.search',
1259 { usr => $patronid, xact_finish => undef } );
1263 while( $data = $req->recv ) {
1264 $data = $data->content;
1265 $total += $data->balance_owed;
1270 sub patron_money_owed {
1271 my( $self, $userid ) = @_;
1272 my $ses = $self->start_db_session();
1273 my $val = $ses->request(
1274 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1275 $self->rollback_db_session($ses);
1279 sub patron_total_items_out {
1280 my( $self, $userid ) = @_;
1281 my $ses = $self->start_db_session();
1282 my $val = $ses->request(
1283 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1284 $self->rollback_db_session($ses);
1291 #---------------------------------------------------------------------
1292 # Returns ($summary, $event)
1293 #---------------------------------------------------------------------
1297 my $e = shift || OpenILS::Utils::CStoreEditor->new;
1298 $id = $id->id if ref($id);
1300 my $xact = $e->retrieve_money_billable_transaction_summary($id)
1301 or return (undef, $e->event);
1307 #---------------------------------------------------------------------
1308 # Given a list of money.billable_transaction objects, this creates
1309 # transaction summary objects for each
1310 #--------------------------------------------------------------------
1315 return () if (!@xacts);
1316 return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1320 sub ou_ancestor_setting_value {
1321 my($self, $org_id, $name, $e) = @_;
1322 $e = $e || OpenILS::Utils::CStoreEditor->new;
1323 my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1324 return $set->{value} if $set;
1329 # If an authentication token is provided AND this org unit setting has a
1330 # view_perm, then make sure the user referenced by the auth token has
1331 # that permission. This means that if you call this method without an
1332 # authtoken param, you can get whatever org unit setting values you want.
1335 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1336 # authtoken is checked, but the $auth arg is NOT checked. To say that another
1337 # way, be sure NOT to pass an editor argument if you want your token checked.
1338 # Otherwise the auth arg is just a flag saying "check the editor".
1340 sub ou_ancestor_setting {
1341 my( $self, $orgid, $name, $e, $auth ) = @_;
1342 $e = $e || OpenILS::Utils::CStoreEditor->new(
1343 (defined $auth) ? (authtoken => $auth) : ()
1345 my $coust = $e->retrieve_config_org_unit_setting_type([
1346 $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1349 if ($auth && $coust && $coust->view_perm) {
1350 # And you can't have permission if you don't have a valid session.
1351 return undef if not $e->checkauth;
1352 # And now that we know you MIGHT have permission, we check it.
1353 return undef if not $e->allowed($coust->view_perm->code, $orgid);
1356 my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1357 my $setting = $e->json_query($query)->[0];
1358 return undef unless $setting;
1359 return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1363 # returns the ISO8601 string representation of the requested epoch in GMT
1365 my( $self, $epoch ) = @_;
1366 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1367 $year += 1900; $mon += 1;
1369 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1370 $year, $mon, $mday, $hour, $min, $sec);
1374 sub find_highest_perm_org {
1375 my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1376 my $org = $self->find_org($org_tree, $start_org );
1380 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1382 $org = $self->find_org( $org_tree, $org->parent_ou() );
1389 # returns the org_unit ID's
1390 sub user_has_work_perm_at {
1391 my($self, $e, $perm, $options, $user_id) = @_;
1393 $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1395 my $func = 'permission.usr_has_perm_at';
1396 $func = $func.'_all' if $$options{descendants};
1398 my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1399 $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1401 return $orgs unless $$options{objects};
1403 return $e->search_actor_org_unit({id => $orgs});
1406 sub get_user_work_ou_ids {
1407 my($self, $e, $userid) = @_;
1408 my $work_orgs = $e->json_query({
1409 select => {puwoum => ['work_ou']},
1411 where => {usr => $e->requestor->id}});
1413 return [] unless @$work_orgs;
1415 push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1423 my($self, $client) = @_;
1424 return $org_types if $org_types;
1425 return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1430 my $locale = shift || '';
1431 my $cache = OpenSRF::Utils::Cache->new("global", 0);
1432 my $tree = $cache->get_cache("orgtree.$locale");
1433 return $tree if $tree;
1435 my $ses = OpenILS::Utils::CStoreEditor->new;
1436 $ses->session->session_locale($locale);
1437 $tree = $ses->search_actor_org_unit(
1439 {"parent_ou" => undef },
1442 flesh_fields => { aou => ['children'] },
1443 order_by => { aou => 'name'}
1448 $cache->put_cache("orgtree.$locale", $tree);
1452 sub get_org_descendants {
1453 my($self, $org_id, $depth) = @_;
1456 transform => 'actor.org_unit_descendants',
1458 result_field => 'id',
1460 $select->{params} = [$depth] if defined $depth;
1462 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1463 select => {aou => [$select]},
1465 where => {id => $org_id}
1468 push(@orgs, $_->{id}) for @$org_list;
1472 sub get_org_ancestors {
1473 my($self, $org_id, $use_cache) = @_;
1478 $cache = OpenSRF::Utils::Cache->new("global", 0);
1479 $orgs = $cache->get_cache("org.ancestors.$org_id");
1480 return $orgs if $orgs;
1483 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1486 transform => 'actor.org_unit_ancestors',
1488 result_field => 'id',
1493 where => {id => $org_id}
1496 $orgs = [ map { $_->{id} } @$org_list ];
1498 $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1502 sub get_org_full_path {
1503 my($self, $org_id, $depth) = @_;
1508 transform => 'actor.org_unit_full_path',
1510 result_field => 'id',
1514 where => {id => $org_id}
1517 $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1518 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1519 return [ map {$_->{id}} @$org_list ];
1522 # returns the ID of the org unit ancestor at the specified depth
1523 sub org_unit_ancestor_at_depth {
1524 my($class, $org_id, $depth) = @_;
1525 my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1526 {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1527 return ($resp) ? $resp->{id} : undef;
1530 # returns the user's configured locale as a string. Defaults to en-US if none is configured.
1531 sub get_user_locale {
1532 my($self, $user_id, $e) = @_;
1533 $e ||= OpenILS::Utils::CStoreEditor->new;
1535 # first, see if the user has an explicit locale set
1536 my $setting = $e->search_actor_user_setting(
1537 {usr => $user_id, name => 'global.locale'})->[0];
1538 return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1540 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1541 return $self->get_org_locale($user->home_ou, $e);
1544 # returns org locale setting
1545 sub get_org_locale {
1546 my($self, $org_id, $e) = @_;
1547 $e ||= OpenILS::Utils::CStoreEditor->new;
1550 if(defined $org_id) {
1551 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1552 return $locale if $locale;
1555 # system-wide default
1556 my $sclient = OpenSRF::Utils::SettingsClient->new;
1557 $locale = $sclient->config_value('default_locale');
1558 return $locale if $locale;
1560 # if nothing else, fallback to locale=cowboy
1565 # xml-escape non-ascii characters
1567 my($self, $string, $form) = @_;
1570 # If we're going to convert non-ASCII characters to XML entities,
1571 # we had better be dealing with a UTF8 string to begin with
1572 $string = decode_utf8($string);
1575 $string = NFD($string);
1577 $string = NFC($string);
1580 # Convert raw ampersands to entities
1581 $string =~ s/&(?!\S+;)/&/gso;
1583 # Convert Unicode characters to entities
1584 $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1589 # x0000-x0008 isn't legal in XML documents
1590 # XXX Perhaps this should just go into our standard entityize method
1591 sub strip_ctrl_chars {
1592 my ($self, $string) = @_;
1594 $string =~ s/([\x{0000}-\x{0008}])//sgoe;
1598 sub get_copy_price {
1599 my($self, $e, $copy, $volume) = @_;
1601 $copy->price(0) if $copy->price and $copy->price < 0;
1603 return $copy->price if $copy->price and $copy->price > 0;
1608 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1609 $owner = $copy->circ_lib;
1611 $owner = $volume->owning_lib;
1614 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1615 $owner = $copy->circ_lib;
1617 $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1621 my $default_price = $self->ou_ancestor_setting_value(
1622 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1624 return $default_price unless defined $copy->price;
1626 # price is 0. Use the default?
1627 my $charge_on_0 = $self->ou_ancestor_setting_value(
1628 $owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e) || 0;
1630 return $default_price if $charge_on_0;
1634 # given a transaction ID, this returns the context org_unit for the transaction
1636 my($self, $xact_id, $e) = @_;
1637 $e ||= OpenILS::Utils::CStoreEditor->new;
1639 my $loc = $e->json_query({
1640 "select" => {circ => ["circ_lib"]},
1642 "where" => {id => $xact_id},
1645 return $loc->[0]->{circ_lib} if @$loc;
1647 $loc = $e->json_query({
1648 "select" => {bresv => ["request_lib"]},
1650 "where" => {id => $xact_id},
1653 return $loc->[0]->{request_lib} if @$loc;
1655 $loc = $e->json_query({
1656 "select" => {mg => ["billing_location"]},
1658 "where" => {id => $xact_id},
1661 return $loc->[0]->{billing_location};
1665 sub find_event_def_by_hook {
1666 my($self, $hook, $context_org, $e) = @_;
1668 $e ||= OpenILS::Utils::CStoreEditor->new;
1670 my $orgs = $self->get_org_ancestors($context_org);
1672 # search from the context org up
1673 for my $org_id (reverse @$orgs) {
1675 my $def = $e->search_action_trigger_event_definition(
1676 {hook => $hook, owner => $org_id})->[0];
1678 return $def if $def;
1686 # If an event_def ID is not provided, use the hook and context org to find the
1687 # most appropriate event. create the event, fire it, then return the resulting
1688 # event with fleshed template_output and error_output
1689 sub fire_object_event {
1690 my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1692 my $e = OpenILS::Utils::CStoreEditor->new;
1695 my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1698 $def = $e->retrieve_action_trigger_event_definition($event_def)
1699 or return $e->event;
1701 $auto_method .= '.include_inactive';
1705 # find the most appropriate event def depending on context org
1706 $def = $self->find_event_def_by_hook($hook, $context_org, $e)
1707 or return $e->event;
1712 if($def->group_field) {
1713 # we have a list of objects
1714 $object = [$object] unless ref $object eq 'ARRAY';
1718 for my $i (0..$#$object) {
1719 my $obj = $$object[$i];
1720 my $udata = $$user_data[$i];
1721 my $event_id = $self->simplereq(
1722 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1723 push(@event_ids, $event_id);
1726 $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1729 if (not defined $client) {
1730 $resp = $self->simplereq(
1732 'open-ils.trigger.event_group.fire',
1735 $resp = $self->patientreq(
1737 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1742 if($resp and $resp->{events} and @{$resp->{events}}) {
1745 $final_resp = $e->retrieve_action_trigger_event([
1746 $resp->{events}->[0]->id,
1747 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1754 $object = $$object[0] if ref $object eq 'ARRAY';
1759 if (not defined $client) {
1760 $event_id = $self->simplereq(
1762 $auto_method, $def->id, $object, $context_org, $user_data
1765 $resp = $self->simplereq(
1767 'open-ils.trigger.event.fire',
1771 $event_id = $self->patientreq(
1774 $auto_method, $def->id, $object, $context_org, $user_data
1777 $resp = $self->patientreq(
1780 'open-ils.trigger.event.fire',
1785 if($resp and $resp->{event}) {
1787 $final_resp = $e->retrieve_action_trigger_event([
1789 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1799 sub create_events_for_hook {
1800 my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1801 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1802 my $req = $ses->request('open-ils.trigger.event.autocreate',
1803 $hook, $obj, $org_id, $granularity, $user_data);
1804 return undef unless $wait;
1805 my $resp = $req->recv;
1806 return $resp->content if $resp;
1809 sub create_uuid_string {
1810 return create_UUID_as_string();
1813 sub create_circ_chain_summary {
1814 my($class, $e, $circ_id) = @_;
1815 my $sum = $e->json_query({from => ['action.summarize_circ_chain', $circ_id]})->[0];
1816 return undef unless $sum;
1817 my $obj = Fieldmapper::action::circ_chain_summary->new;
1818 $obj->$_($sum->{$_}) for keys %$sum;
1823 # Returns "mra" attribute key/value pairs for a set of bre's
1824 # Takes a list of bre IDs, returns a hash of hashes,
1825 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1828 my ($class, $bre_ids, $e) = @_;
1829 $e = $e || OpenILS::Utils::CStoreEditor->new;
1832 return $attrs unless defined $bre_ids;
1833 $bre_ids = [$bre_ids] unless ref $bre_ids;
1835 my $mra = $e->json_query({
1843 transform => 'each',
1844 result_field => 'key',
1848 transform => 'each',
1849 result_field => 'value',
1855 where => {id => $bre_ids}
1858 return $attrs unless $mra;
1860 $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
1862 for my $id (@$bre_ids) {
1864 for my $mra (grep { $_->{bre} eq $id } @$mra) {
1865 my $ctype = $mra->{key};
1866 my $code = $mra->{value};
1867 $attrs->{$id}->{$ctype} = {code => $code};
1869 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
1870 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
1878 # Shorter version of bib_container_items_via_search() below, only using
1879 # the queryparser record_list filter instead of the container filter.
1880 sub bib_record_list_via_search {
1881 my ($class, $search_query, $search_args) = @_;
1883 # First, Use search API to get container items sorted in any way that crad
1885 my $search_result = $class->simplereq(
1886 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1887 $search_args, $search_query
1890 unless ($search_result) {
1891 # empty result sets won't cause this, but actual errors should.
1892 $logger->warn("bib_record_list_via_search() got nothing from search");
1896 # Throw away other junk from search, keeping only bib IDs.
1897 return [ map { pop @$_ } @{$search_result->{ids}} ];
1900 # 'no_flesh' avoids fleshing the target_biblio_record_entry
1901 sub bib_container_items_via_search {
1902 my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
1904 # First, Use search API to get container items sorted in any way that crad
1906 my $search_result = $class->simplereq(
1907 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1908 $search_args, $search_query
1910 unless ($search_result) {
1911 # empty result sets won't cause this, but actual errors should.
1912 $logger->warn("bib_container_items_via_search() got nothing from search");
1916 # Throw away other junk from search, keeping only bib IDs.
1917 my $id_list = [ map { pop @$_ } @{$search_result->{ids}} ];
1919 return [] unless @$id_list;
1921 # Now get the bib container items themselves...
1922 my $e = new OpenILS::Utils::CStoreEditor;
1924 $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
1928 my @flesh_fields = qw/notes/;
1929 push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
1931 my $items = $e->search_container_biblio_record_entry_bucket_item([
1933 "target_biblio_record_entry" => $id_list,
1934 "bucket" => $container_id
1937 flesh_fields => {"cbrebi" => \@flesh_fields}
1942 "bib_container_items_via_search() couldn't get bucket items: " .
1943 $e->die_event->{textcode}
1948 # ... and put them in the same order that the search API said they
1950 my %ordering_hash = map {
1951 ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id,
1955 return [map { $ordering_hash{$_} } @$id_list];
1958 # returns undef on success, Event on error
1959 sub log_user_activity {
1960 my ($class, $user_id, $who, $what, $e, $async) = @_;
1964 $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
1968 my $res = $e->json_query({
1970 'actor.insert_usr_activity',
1971 $user_id, $who, $what, OpenSRF::AppSession->ingress
1975 if ($res) { # call returned OK
1977 $e->commit if $commit and @$res;
1978 $e->rollback if $commit and !@$res;
1981 return $e->die_event;
1987 # I hate to put this here exactly, but this code needs to be shared between
1988 # the TPAC's mod_perl module and open-ils.serial.
1990 # There is a reason every part of the query *except* those parts dealing
1991 # with scope are moved here from the code's origin in TPAC. The serials
1992 # use case does *not* want the same scoping logic.
1994 # Also, note that for the serials uses case, we may filter in OPAC visible
1995 # status and copy/call_number deletedness, but we don't filter on any
1996 # particular values for serial.item.status or serial.item.date_received.
1997 # Since we're only using this *after* winnowing down the set of issuances
1998 # that copies should be related to, I'm not sure we need any such serial.item
2001 sub basic_opac_copy_query {
2002 ######################################################################
2003 # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
2005 ######################################################################
2006 my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
2010 acp => ['id', 'barcode', 'circ_lib', 'create_date',
2011 'age_protect', 'holdable'],
2013 {column => 'name', alias => 'copy_location'},
2014 {column => 'holdable', alias => 'location_holdable'}
2017 {column => 'name', alias => 'copy_status'},
2018 {column => 'holdable', alias => 'status_holdable'}
2021 {column => 'label', alias => 'call_number_label'},
2022 {column => 'id', alias => 'call_number'}
2024 circ => ['due_date'],
2026 {column => 'label', alias => 'call_number_prefix_label'},
2027 {column => 'id', alias => 'call_number_prefix'}
2030 {column => 'label', alias => 'call_number_suffix_label'},
2031 {column => 'id', alias => 'call_number_suffix'}
2034 {column => 'label', alias => 'part_label'},
2036 ($iss_id ? (sitem => ["issuance"]) : ())
2045 filter => {issuance => $iss_id},
2053 acnp => { fkey => 'prefix' },
2054 acns => { fkey => 'suffix' }
2058 ($rec_id ? {record => $rec_id} : ())
2061 circ => { # If the copy is circulating, retrieve the open circ
2063 filter => {checkin_time => undef}
2066 ($staff ? () : (filter => { opac_visible => 't' }))
2069 ($staff ? () : (filter => { opac_visible => 't' }))
2075 bmp => { type => 'left' }
2084 ($staff ? () : (opac_visible => 't'))
2086 ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2087 ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2091 {class => 'aou', field => 'name'},
2092 {class => 'acn', field => 'label'}
2095 limit => $copy_limit,
2096 offset => $copy_offset