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 : " );
193 my( $self, $orglist ) = @_;
195 return $orglist unless ref $orglist;
196 return $$orglist[0] if @$orglist == 1;
199 $a->ou_type <=> $b->ou_type ||
200 $a->name cmp $b->name } @$orglist;
202 for my $org (@list) {
205 next if (!defined($org->parent_ou) || $org->parent_ou eq "");
207 my ($parent) = grep { $_->id == $org->parent_ou } @list;
209 $parent->children([]) unless defined($parent->children);
210 push( @{$parent->children}, $org );
216 sub fetch_closed_date {
217 my( $self, $cd ) = @_;
220 $logger->debug("Fetching closed_date $cd from cstore");
222 my $cd_obj = $self->simplereq(
224 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
227 $logger->info("closed_date $cd not found in the db");
228 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
231 return ($cd_obj, $evt);
235 my( $self, $userid ) = @_;
238 $logger->debug("Fetching user $userid from cstore");
240 $user = $self->simplereq(
242 'open-ils.cstore.direct.actor.user.retrieve', $userid );
245 $logger->info("User $userid not found in the db");
246 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
249 return ($user, $evt);
253 my( $self, $session ) = @_;
254 my $user = $self->check_user_session($session) or
255 return (undef, OpenILS::Event->new('NO_SESSION'));
260 # verifiese the session and checks the permissions agains the
261 # session user and the user's home_ou as the org id
263 my( $self, $session, @perms ) = @_;
264 my $user; my $evt; my $e;
265 $logger->debug("Checking user session $session and perms @perms");
266 ($user, $evt) = $self->checkses($session);
267 return (undef, $evt) if $evt;
268 $evt = $self->check_perms($user->id, $user->home_ou, @perms);
269 return ($user, $evt);
274 my( $self, $staffobj, $userid, @perms ) = @_;
276 $userid = $staffobj->id unless defined $userid;
278 $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
280 if( $userid ne $staffobj->id ) {
281 ($user, $evt) = $self->fetch_user($userid);
282 return (undef, $evt) if $evt;
283 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
289 return ($user, $evt);
292 sub checkses_requestor {
293 my( $self, $authtoken, $targetid, @perms ) = @_;
294 my( $requestor, $target, $evt );
296 ($requestor, $evt) = $self->checkses($authtoken);
297 return (undef, undef, $evt) if $evt;
299 ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
300 return( $requestor, $target, $evt);
304 my( $self, $copyid ) = @_;
307 $logger->debug("Fetching copy $copyid from cstore");
309 $copy = $self->simplereq(
311 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
313 if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
315 return( $copy, $evt );
319 # retrieves a circ object by id
320 sub fetch_circulation {
321 my( $self, $circid ) = @_;
324 $logger->debug("Fetching circ $circid from cstore");
326 $circ = $self->simplereq(
328 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
331 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
334 return ( $circ, $evt );
337 sub fetch_record_by_copy {
338 my( $self, $copyid ) = @_;
341 $logger->debug("Fetching record by copy $copyid from cstore");
343 $record = $self->simplereq(
345 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
347 flesh_fields => { bre => [ 'fixed_fields' ],
349 acp => [ 'call_number' ],
355 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
357 $record = $record->call_number->record;
360 return ($record, $evt);
363 # turns a record object into an mvr (mods) object
365 my( $self, $record ) = @_;
366 return undef unless $record and $record->marc;
367 my $u = OpenILS::Utils::ModsParser->new();
368 $u->start_mods_batch( $record->marc );
369 my $mods = $u->finish_mods_batch();
370 $mods->doc_id($record->id);
371 $mods->tcn($record->tcn_value);
376 my( $self, $holdid ) = @_;
379 $logger->debug("Fetching hold $holdid from cstore");
381 $hold = $self->simplereq(
383 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
385 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
387 return ($hold, $evt);
391 sub fetch_hold_transit_by_hold {
392 my( $self, $holdid ) = @_;
393 my( $transit, $evt );
395 $logger->debug("Fetching transit by hold $holdid from cstore");
397 $transit = $self->simplereq(
399 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
401 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
403 return ($transit, $evt );
406 # fetches the captured, but not fulfilled hold attached to a given copy
407 sub fetch_open_hold_by_copy {
408 my( $self, $copyid ) = @_;
409 $logger->debug("Searching for active hold for copy $copyid");
412 $hold = $self->cstorereq(
413 'open-ils.cstore.direct.action.hold_request.search',
415 current_copy => $copyid ,
416 capture_time => { "!=" => undef },
417 fulfillment_time => undef,
418 cancel_time => undef,
421 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
422 return ($hold, $evt);
425 sub fetch_hold_transit {
426 my( $self, $transid ) = @_;
427 my( $htransit, $evt );
428 $logger->debug("Fetching hold transit with hold id $transid");
429 $htransit = $self->cstorereq(
430 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
431 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
432 return ($htransit, $evt);
435 sub fetch_copy_by_barcode {
436 my( $self, $barcode ) = @_;
439 $logger->debug("Fetching copy by barcode $barcode from cstore");
441 $copy = $self->simplereq( 'open-ils.cstore',
442 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
443 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
445 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
447 return ($copy, $evt);
450 sub fetch_open_billable_transaction {
451 my( $self, $transid ) = @_;
452 my( $transaction, $evt );
454 $logger->debug("Fetching open billable transaction $transid from cstore");
456 $transaction = $self->simplereq(
458 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve', $transid);
460 $evt = OpenILS::Event->new(
461 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
463 return ($transaction, $evt);
469 $buckets{'biblio'} = 'biblio_record_entry_bucket';
470 $buckets{'callnumber'} = 'call_number_bucket';
471 $buckets{'copy'} = 'copy_bucket';
472 $buckets{'user'} = 'user_bucket';
474 sub fetch_container {
475 my( $self, $id, $type ) = @_;
478 $logger->debug("Fetching container $id with type $type");
480 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
481 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
482 $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
483 $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
485 my $meth = $buckets{$type};
486 $bucket = $self->simplereq(
488 "open-ils.cstore.direct.container.$meth.retrieve", $id );
490 $evt = OpenILS::Event->new(
491 $e, container => $id, container_type => $type ) unless $bucket;
493 return ($bucket, $evt);
497 sub fetch_container_e {
498 my( $self, $editor, $id, $type ) = @_;
501 $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
502 $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
503 $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
504 $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
506 $evt = $editor->event unless $bucket;
507 return ($bucket, $evt);
510 sub fetch_container_item_e {
511 my( $self, $editor, $id, $type ) = @_;
514 $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
515 $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
516 $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
517 $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
519 $evt = $editor->event unless $bucket;
520 return ($bucket, $evt);
527 sub fetch_container_item {
528 my( $self, $id, $type ) = @_;
531 $logger->debug("Fetching container item $id with type $type");
533 my $meth = $buckets{$type} . "_item";
535 $bucket = $self->simplereq(
537 "open-ils.cstore.direct.container.$meth.retrieve", $id );
540 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
541 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
542 $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
543 $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
545 $evt = OpenILS::Event->new(
546 $e, itemid => $id, container_type => $type ) unless $bucket;
548 return ($bucket, $evt);
552 sub fetch_patron_standings {
554 $logger->debug("Fetching patron standings");
555 return $self->simplereq(
557 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
561 sub fetch_permission_group_tree {
563 $logger->debug("Fetching patron profiles");
564 return $self->simplereq(
566 'open-ils.actor.groups.tree.retrieve' );
569 sub fetch_permission_group_descendants {
570 my( $self, $profile ) = @_;
571 my $group_tree = $self->fetch_permission_group_tree();
575 # FIXME: okay, so it's not an org tree, but it is compatible
576 $self->walk_org_tree($group_tree, sub {
578 if ($g->id == $profile) {
583 $self->walk_org_tree($start_here, sub {
585 push(@groups,$g->id);
591 sub fetch_patron_circ_summary {
592 my( $self, $userid ) = @_;
593 $logger->debug("Fetching patron summary for $userid");
594 my $summary = $self->simplereq(
596 "open-ils.storage.action.circulation.patron_summary", $userid );
600 $summary->[1] ||= 0.0;
607 sub fetch_copy_statuses {
609 $logger->debug("Fetching copy statuses");
610 return $self->simplereq(
612 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
615 sub fetch_copy_location {
616 my( $self, $id ) = @_;
618 my $cl = $self->cstorereq(
619 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
620 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
624 sub fetch_copy_locations {
626 return $self->simplereq(
628 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
631 sub fetch_copy_location_by_name {
632 my( $self, $name, $org ) = @_;
634 my $cl = $self->cstorereq(
635 'open-ils.cstore.direct.asset.copy_location.search',
636 { name => $name, owning_lib => $org } );
637 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
641 sub fetch_callnumber {
642 my( $self, $id, $flesh, $e ) = @_;
644 $e ||= OpenILS::Utils::CStoreEditor->new;
646 my $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
647 return( undef, $evt ) unless $id;
649 $logger->debug("Fetching callnumber $id");
651 my $cn = $e->retrieve_asset_call_number([
653 { flesh => $flesh, flesh_fields => { acn => [ 'prefix', 'suffix', 'label_class' ] } },
656 return ( $cn, $e->event );
659 my %ORG_CACHE; # - these rarely change, so cache them..
661 my( $self, $id ) = @_;
662 return undef unless $id;
663 return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
664 return $ORG_CACHE{$id} if $ORG_CACHE{$id};
665 $logger->debug("Fetching org unit $id");
668 my $org = $self->simplereq(
670 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
671 $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
672 $ORG_CACHE{$id} = $org;
678 my( $self, $type, $id ) = @_;
680 $logger->debug("Fetching $type stat cat: $id");
681 $cat = $self->simplereq(
683 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
685 my $e = 'ASSET_STAT_CAT_NOT_FOUND';
686 $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
688 $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
689 return ( $cat, $evt );
692 sub fetch_stat_cat_entry {
693 my( $self, $type, $id ) = @_;
695 $logger->debug("Fetching $type stat cat entry: $id");
696 $entry = $self->simplereq(
698 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
700 my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
701 $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
703 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
704 return ( $entry, $evt );
707 sub fetch_stat_cat_entry_default {
708 my( $self, $type, $id ) = @_;
709 my( $entry_default, $evt );
710 $logger->debug("Fetching $type stat cat entry default: $id");
711 $entry_default = $self->simplereq(
713 "open-ils.cstore.direct.$type.stat_cat_entry_default.retrieve", $id );
715 my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
716 $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
718 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry_default;
719 return ( $entry_default, $evt );
722 sub fetch_stat_cat_entry_default_by_stat_cat_and_org {
723 my( $self, $type, $stat_cat, $orgId ) = @_;
725 $logger->info("### Fetching $type stat cat entry default with stat_cat $stat_cat owned by org_unit $orgId");
726 $entry_default = $self->simplereq(
728 "open-ils.cstore.direct.$type.stat_cat_entry_default.search.atomic",
729 { stat_cat => $stat_cat, owner => $orgId } );
731 $entry_default = $entry_default->[0];
732 return ($entry_default, undef) if $entry_default;
734 my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
735 $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
736 return (undef, OpenILS::Event->new($e) );
740 my( $self, $org_tree, $orgid ) = @_;
741 return undef unless $org_tree and defined $orgid;
742 return $org_tree if ( $org_tree->id eq $orgid );
743 return undef unless ref($org_tree->children);
744 for my $c (@{$org_tree->children}) {
745 my $o = $self->find_org($c, $orgid);
751 sub fetch_non_cat_type_by_name_and_org {
752 my( $self, $name, $orgId ) = @_;
753 $logger->debug("Fetching non cat type $name at org $orgId");
754 my $types = $self->simplereq(
756 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
757 { name => $name, owning_lib => $orgId } );
758 return ($types->[0], undef) if($types and @$types);
759 return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
762 sub fetch_non_cat_type {
763 my( $self, $id ) = @_;
764 $logger->debug("Fetching non cat type $id");
766 $type = $self->simplereq(
768 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
769 $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
770 return ($type, $evt);
773 sub DB_UPDATE_FAILED {
774 my( $self, $payload ) = @_;
775 return OpenILS::Event->new('DATABASE_UPDATE_FAILED',
776 payload => ($payload) ? $payload : undef );
779 sub fetch_booking_reservation {
780 my( $self, $id ) = @_;
783 $res = $self->simplereq(
785 'open-ils.cstore.direct.booking.reservation.retrieve', $id
788 # simplereq doesn't know how to flesh so ...
793 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
797 $res->target_resource_type(
800 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
804 if ($res->current_resource) {
805 $res->current_resource(
808 'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
812 if ($self->is_true( $res->target_resource_type->catalog_item )) {
813 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
817 if ($res->target_resource) {
818 $res->target_resource(
821 'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
825 if ($self->is_true( $res->target_resource_type->catalog_item )) {
826 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
831 $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
837 sub fetch_circ_duration_by_name {
838 my( $self, $name ) = @_;
840 $dur = $self->simplereq(
842 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
844 $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
848 sub fetch_recurring_fine_by_name {
849 my( $self, $name ) = @_;
851 $obj = $self->simplereq(
853 'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
855 $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
859 sub fetch_max_fine_by_name {
860 my( $self, $name ) = @_;
862 $obj = $self->simplereq(
864 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
866 $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
870 sub fetch_hard_due_date_by_name {
871 my( $self, $name ) = @_;
873 $obj = $self->simplereq(
875 'open-ils.cstore.direct.config.hard_due_date.search.atomic', { name => $name } );
877 $evt = OpenILS::Event->new('CONFIG_RULES_HARD_DUE_DATE_NOT_FOUND') unless $obj;
882 my( $self, $method, @params ) = @_;
883 return $self->simplereq(
884 'open-ils.storage', $method, @params );
887 sub storagereq_xact {
888 my($self, $method, @params) = @_;
889 my $ses = $self->start_db_session();
890 my $val = $ses->request($method, @params)->gather(1);
891 $self->rollback_db_session($ses);
896 my( $self, $method, @params ) = @_;
897 return $self->simplereq(
898 'open-ils.cstore', $method, @params );
902 my( $self, $e, $name ) = @_;
903 if( $e and ref($e) eq 'HASH' and
904 defined($e->{textcode}) and $e->{textcode} eq $name ) {
911 my( undef, $f, $l ) = caller(0);
912 my( undef, undef, undef, $s ) = caller(1);
915 $logger->debug("LOGMARK: $f:$l:$s");
919 sub fetch_open_circulation {
920 my( $self, $cid ) = @_;
923 my $e = OpenILS::Utils::CStoreEditor->new;
924 my $circ = $e->search_action_circulation({
926 stop_fines_time => undef,
927 checkin_time => undef
930 return ($circ, $e->event);
934 sub copy_status_from_name {
935 my( $self, $name ) = @_;
936 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
937 for my $status (@$copy_statuses) {
938 return $status if( $status->name =~ /$name/i );
943 sub copy_status_to_name {
944 my( $self, $sid ) = @_;
945 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
946 for my $status (@$copy_statuses) {
947 return $status->name if( $status->id == $sid );
954 my( $self, $arg ) = @_;
955 return $arg if ref $arg;
956 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
957 my ($stat) = grep { $_->id == $arg } @$copy_statuses;
961 sub fetch_open_transit_by_copy {
962 my( $self, $copyid ) = @_;
964 $transit = $self->cstorereq(
965 'open-ils.cstore.direct.action.transit_copy.search',
966 { target_copy => $copyid, dest_recv_time => undef });
967 $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
968 return ($transit, $evt);
972 my( $self, $copy ) = @_;
973 return undef unless $copy;
974 $copy->status( $copy->status->id ) if ref($copy->status);
975 $copy->location( $copy->location->id ) if ref($copy->location);
976 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
980 sub unflesh_reservation {
981 my( $self, $reservation ) = @_;
982 return undef unless $reservation;
983 $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
984 $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
985 $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
986 $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
990 # un-fleshes a copy and updates it in the DB
991 # returns a DB_UPDATE_FAILED event on error
992 # returns undef on success
994 my( $self, %params ) = @_;
996 my $copy = $params{copy} || die "update_copy(): copy required";
997 my $editor = $params{editor} || die "update_copy(): copy editor required";
998 my $session = $params{session};
1000 $logger->debug("Updating copy in the database: " . $copy->id);
1002 $self->unflesh_copy($copy);
1003 $copy->editor( $editor );
1004 $copy->edit_date( 'now' );
1007 my $meth = 'open-ils.storage.direct.asset.copy.update';
1009 $s = $session->request( $meth, $copy )->gather(1) if $session;
1010 $s = $self->storagereq( $meth, $copy ) unless $session;
1012 $logger->debug("Update of copy ".$copy->id." returned: $s");
1014 return $self->DB_UPDATE_FAILED($copy) unless $s;
1018 sub update_reservation {
1019 my( $self, %params ) = @_;
1021 my $reservation = $params{reservation} || die "update_reservation(): reservation required";
1022 my $editor = $params{editor} || die "update_reservation(): copy editor required";
1023 my $session = $params{session};
1025 $logger->debug("Updating copy in the database: " . $reservation->id);
1027 $self->unflesh_reservation($reservation);
1030 my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1032 $s = $session->request( $meth, $reservation )->gather(1) if $session;
1033 $s = $self->cstorereq( $meth, $reservation ) unless $session;
1035 $logger->debug("Update of copy ".$reservation->id." returned: $s");
1037 return $self->DB_UPDATE_FAILED($reservation) unless $s;
1041 sub fetch_billable_xact {
1042 my( $self, $id ) = @_;
1044 $logger->debug("Fetching billable transaction %id");
1045 $xact = $self->cstorereq(
1046 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1047 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1048 return ($xact, $evt);
1051 sub fetch_billable_xact_summary {
1052 my( $self, $id ) = @_;
1054 $logger->debug("Fetching billable transaction summary %id");
1055 $xact = $self->cstorereq(
1056 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1057 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1058 return ($xact, $evt);
1061 sub fetch_fleshed_copy {
1062 my( $self, $id ) = @_;
1064 $logger->info("Fetching fleshed copy $id");
1065 $copy = $self->cstorereq(
1066 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1068 flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1071 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1072 return ($copy, $evt);
1076 # returns the org that owns the callnumber that the copy
1078 sub fetch_copy_owner {
1079 my( $self, $copyid ) = @_;
1080 my( $copy, $cn, $evt );
1081 $logger->debug("Fetching copy owner $copyid");
1082 ($copy, $evt) = $self->fetch_copy($copyid);
1083 return (undef,$evt) if $evt;
1084 ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1085 return (undef,$evt) if $evt;
1086 return ($cn->owning_lib);
1089 sub fetch_copy_note {
1090 my( $self, $id ) = @_;
1092 $logger->debug("Fetching copy note $id");
1093 $note = $self->cstorereq(
1094 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1095 $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1096 return ($note, $evt);
1099 sub fetch_call_numbers_by_title {
1100 my( $self, $titleid ) = @_;
1101 $logger->info("Fetching call numbers by title $titleid");
1102 return $self->cstorereq(
1103 'open-ils.cstore.direct.asset.call_number.search.atomic',
1104 { record => $titleid, deleted => 'f' });
1105 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1108 sub fetch_copies_by_call_number {
1109 my( $self, $cnid ) = @_;
1110 $logger->info("Fetching copies by call number $cnid");
1111 return $self->cstorereq(
1112 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1113 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1116 sub fetch_user_by_barcode {
1117 my( $self, $bc ) = @_;
1118 my $cardid = $self->cstorereq(
1119 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1120 return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1121 my $user = $self->cstorereq(
1122 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1123 return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1129 my( $self, $billid ) = @_;
1130 $logger->debug("Fetching billing $billid");
1131 my $bill = $self->cstorereq(
1132 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1133 my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1134 return($bill, $evt);
1138 my( $self, $node, $callback ) = @_;
1139 return unless $node;
1141 if( $node->children ) {
1142 $self->walk_org_tree($_, $callback) for @{$node->children};
1147 my( $self, $item ) = @_;
1148 return 1 if $item and $item !~ /^f$/i;
1154 my ($self, $client, $service, $method, @params) = @_;
1155 my ($response, $err);
1157 my $session = create OpenSRF::AppSession($service);
1158 my $request = $session->request($method, @params);
1161 my $give_up = time + 1000;
1164 while (time < $give_up) {
1165 $response = $request->recv("timeout" => $spurt);
1166 last if $request->complete;
1168 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1170 } catch Error with {
1175 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
1176 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
1179 return $response->content;
1182 # This logic now lives in storage
1183 sub __patron_money_owed {
1184 my( $self, $patronid ) = @_;
1185 my $ses = OpenSRF::AppSession->create('open-ils.storage');
1186 my $req = $ses->request(
1187 'open-ils.storage.money.billable_transaction.summary.search',
1188 { usr => $patronid, xact_finish => undef } );
1192 while( $data = $req->recv ) {
1193 $data = $data->content;
1194 $total += $data->balance_owed;
1199 sub patron_money_owed {
1200 my( $self, $userid ) = @_;
1201 my $ses = $self->start_db_session();
1202 my $val = $ses->request(
1203 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1204 $self->rollback_db_session($ses);
1208 sub patron_total_items_out {
1209 my( $self, $userid ) = @_;
1210 my $ses = $self->start_db_session();
1211 my $val = $ses->request(
1212 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1213 $self->rollback_db_session($ses);
1220 #---------------------------------------------------------------------
1221 # Returns ($summary, $event)
1222 #---------------------------------------------------------------------
1226 my $e = shift || OpenILS::Utils::CStoreEditor->new;
1227 $id = $id->id if ref($id);
1229 my $xact = $e->retrieve_money_billable_transaction_summary($id)
1230 or return (undef, $e->event);
1236 #---------------------------------------------------------------------
1237 # Given a list of money.billable_transaction objects, this creates
1238 # transaction summary objects for each
1239 #--------------------------------------------------------------------
1244 return () if (!@xacts);
1245 return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1249 sub ou_ancestor_setting_value {
1250 my($self, $org_id, $name, $e) = @_;
1251 $e = $e || OpenILS::Utils::CStoreEditor->new;
1252 my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1253 return $set->{value} if $set;
1258 # If an authentication token is provided AND this org unit setting has a
1259 # view_perm, then make sure the user referenced by the auth token has
1260 # that permission. This means that if you call this method without an
1261 # authtoken param, you can get whatever org unit setting values you want.
1264 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1265 # authtoken is checked, but the $auth arg is NOT checked. To say that another
1266 # way, be sure NOT to pass an editor argument if you want your token checked.
1267 # Otherwise the auth arg is just a flag saying "check the editor".
1269 sub ou_ancestor_setting {
1270 my( $self, $orgid, $name, $e, $auth ) = @_;
1271 $e = $e || OpenILS::Utils::CStoreEditor->new(
1272 (defined $auth) ? (authtoken => $auth) : ()
1274 my $coust = $e->retrieve_config_org_unit_setting_type([
1275 $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1278 if ($auth && $coust && $coust->view_perm) {
1279 # And you can't have permission if you don't have a valid session.
1280 return undef if not $e->checkauth;
1281 # And now that we know you MIGHT have permission, we check it.
1282 return undef if not $e->allowed($coust->view_perm->code, $orgid);
1285 my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1286 my $setting = $e->json_query($query)->[0];
1287 return undef unless $setting;
1288 return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1292 # returns the ISO8601 string representation of the requested epoch in GMT
1294 my( $self, $epoch ) = @_;
1295 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1296 $year += 1900; $mon += 1;
1298 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1299 $year, $mon, $mday, $hour, $min, $sec);
1303 sub find_highest_perm_org {
1304 my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1305 my $org = $self->find_org($org_tree, $start_org );
1309 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1311 $org = $self->find_org( $org_tree, $org->parent_ou() );
1318 # returns the org_unit ID's
1319 sub user_has_work_perm_at {
1320 my($self, $e, $perm, $options, $user_id) = @_;
1322 $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1324 my $func = 'permission.usr_has_perm_at';
1325 $func = $func.'_all' if $$options{descendants};
1327 my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1328 $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1330 return $orgs unless $$options{objects};
1332 return $e->search_actor_org_unit({id => $orgs});
1335 sub get_user_work_ou_ids {
1336 my($self, $e, $userid) = @_;
1337 my $work_orgs = $e->json_query({
1338 select => {puwoum => ['work_ou']},
1340 where => {usr => $e->requestor->id}});
1342 return [] unless @$work_orgs;
1344 push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1352 my($self, $client) = @_;
1353 return $org_types if $org_types;
1354 return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1360 my $locale = shift || '';
1361 my $cache = OpenSRF::Utils::Cache->new("global", 0);
1362 my $tree = $ORG_TREE{$locale} || $cache->get_cache("orgtree.$locale");
1363 return $tree if $tree;
1365 my $ses = OpenILS::Utils::CStoreEditor->new;
1366 $ses->session->session_locale($locale);
1367 $tree = $ses->search_actor_org_unit(
1369 {"parent_ou" => undef },
1372 flesh_fields => { aou => ['children'] },
1373 order_by => { aou => 'name'}
1378 $ORG_TREE{$locale} = $tree;
1379 $cache->put_cache("orgtree.$locale", $tree);
1383 sub get_org_descendants {
1384 my($self, $org_id, $depth) = @_;
1387 transform => 'actor.org_unit_descendants',
1389 result_field => 'id',
1391 $select->{params} = [$depth] if defined $depth;
1393 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1394 select => {aou => [$select]},
1396 where => {id => $org_id}
1399 push(@orgs, $_->{id}) for @$org_list;
1403 sub get_org_ancestors {
1404 my($self, $org_id, $use_cache) = @_;
1409 $cache = OpenSRF::Utils::Cache->new("global", 0);
1410 $orgs = $cache->get_cache("org.ancestors.$org_id");
1411 return $orgs if $orgs;
1414 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1417 transform => 'actor.org_unit_ancestors',
1419 result_field => 'id',
1424 where => {id => $org_id}
1427 $orgs = [ map { $_->{id} } @$org_list ];
1429 $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1433 sub get_org_full_path {
1434 my($self, $org_id, $depth) = @_;
1439 transform => 'actor.org_unit_full_path',
1441 result_field => 'id',
1445 where => {id => $org_id}
1448 $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1449 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1450 return [ map {$_->{id}} @$org_list ];
1453 # returns the ID of the org unit ancestor at the specified depth
1454 sub org_unit_ancestor_at_depth {
1455 my($class, $org_id, $depth) = @_;
1456 my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1457 {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1458 return ($resp) ? $resp->{id} : undef;
1461 # returns the user's configured locale as a string. Defaults to en-US if none is configured.
1462 sub get_user_locale {
1463 my($self, $user_id, $e) = @_;
1464 $e ||= OpenILS::Utils::CStoreEditor->new;
1466 # first, see if the user has an explicit locale set
1467 my $setting = $e->search_actor_user_setting(
1468 {usr => $user_id, name => 'global.locale'})->[0];
1469 return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1471 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1472 return $self->get_org_locale($user->home_ou, $e);
1475 # returns org locale setting
1476 sub get_org_locale {
1477 my($self, $org_id, $e) = @_;
1478 $e ||= OpenILS::Utils::CStoreEditor->new;
1481 if(defined $org_id) {
1482 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1483 return $locale if $locale;
1486 # system-wide default
1487 my $sclient = OpenSRF::Utils::SettingsClient->new;
1488 $locale = $sclient->config_value('default_locale');
1489 return $locale if $locale;
1491 # if nothing else, fallback to locale=cowboy
1496 # xml-escape non-ascii characters
1498 my($self, $string, $form) = @_;
1501 # If we're going to convert non-ASCII characters to XML entities,
1502 # we had better be dealing with a UTF8 string to begin with
1503 $string = decode_utf8($string);
1506 $string = NFD($string);
1508 $string = NFC($string);
1511 # Convert raw ampersands to entities
1512 $string =~ s/&(?!\S+;)/&/gso;
1514 # Convert Unicode characters to entities
1515 $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1520 # x0000-x0008 isn't legal in XML documents
1521 # XXX Perhaps this should just go into our standard entityize method
1522 sub strip_ctrl_chars {
1523 my ($self, $string) = @_;
1525 $string =~ s/([\x{0000}-\x{0008}])//sgoe;
1529 sub get_copy_price {
1530 my($self, $e, $copy, $volume) = @_;
1532 $copy->price(0) if $copy->price and $copy->price < 0;
1534 return $copy->price if $copy->price and $copy->price > 0;
1539 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1540 $owner = $copy->circ_lib;
1542 $owner = $volume->owning_lib;
1545 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1546 $owner = $copy->circ_lib;
1548 $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1552 my $default_price = $self->ou_ancestor_setting_value(
1553 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1555 return $default_price unless defined $copy->price;
1557 # price is 0. Use the default?
1558 my $charge_on_0 = $self->ou_ancestor_setting_value(
1559 $owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e) || 0;
1561 return $default_price if $charge_on_0;
1565 # given a transaction ID, this returns the context org_unit for the transaction
1567 my($self, $xact_id, $e) = @_;
1568 $e ||= OpenILS::Utils::CStoreEditor->new;
1570 my $loc = $e->json_query({
1571 "select" => {circ => ["circ_lib"]},
1573 "where" => {id => $xact_id},
1576 return $loc->[0]->{circ_lib} if @$loc;
1578 $loc = $e->json_query({
1579 "select" => {bresv => ["request_lib"]},
1581 "where" => {id => $xact_id},
1584 return $loc->[0]->{request_lib} if @$loc;
1586 $loc = $e->json_query({
1587 "select" => {mg => ["billing_location"]},
1589 "where" => {id => $xact_id},
1592 return $loc->[0]->{billing_location};
1596 sub find_event_def_by_hook {
1597 my($self, $hook, $context_org, $e) = @_;
1599 $e ||= OpenILS::Utils::CStoreEditor->new;
1601 my $orgs = $self->get_org_ancestors($context_org);
1603 # search from the context org up
1604 for my $org_id (reverse @$orgs) {
1606 my $def = $e->search_action_trigger_event_definition(
1607 {hook => $hook, owner => $org_id})->[0];
1609 return $def if $def;
1617 # If an event_def ID is not provided, use the hook and context org to find the
1618 # most appropriate event. create the event, fire it, then return the resulting
1619 # event with fleshed template_output and error_output
1620 sub fire_object_event {
1621 my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1623 my $e = OpenILS::Utils::CStoreEditor->new;
1626 my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1629 $def = $e->retrieve_action_trigger_event_definition($event_def)
1630 or return $e->event;
1632 $auto_method .= '.include_inactive';
1636 # find the most appropriate event def depending on context org
1637 $def = $self->find_event_def_by_hook($hook, $context_org, $e)
1638 or return $e->event;
1643 if($def->group_field) {
1644 # we have a list of objects
1645 $object = [$object] unless ref $object eq 'ARRAY';
1649 for my $i (0..$#$object) {
1650 my $obj = $$object[$i];
1651 my $udata = $$user_data[$i];
1652 my $event_id = $self->simplereq(
1653 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1654 push(@event_ids, $event_id);
1657 $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1660 if (not defined $client) {
1661 $resp = $self->simplereq(
1663 'open-ils.trigger.event_group.fire',
1666 $resp = $self->patientreq(
1668 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1673 if($resp and $resp->{events} and @{$resp->{events}}) {
1676 $final_resp = $e->retrieve_action_trigger_event([
1677 $resp->{events}->[0]->id,
1678 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1685 $object = $$object[0] if ref $object eq 'ARRAY';
1690 if (not defined $client) {
1691 $event_id = $self->simplereq(
1693 $auto_method, $def->id, $object, $context_org, $user_data
1696 $resp = $self->simplereq(
1698 'open-ils.trigger.event.fire',
1702 $event_id = $self->patientreq(
1705 $auto_method, $def->id, $object, $context_org, $user_data
1708 $resp = $self->patientreq(
1711 'open-ils.trigger.event.fire',
1716 if($resp and $resp->{event}) {
1718 $final_resp = $e->retrieve_action_trigger_event([
1720 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1730 sub create_events_for_hook {
1731 my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1732 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1733 my $req = $ses->request('open-ils.trigger.event.autocreate',
1734 $hook, $obj, $org_id, $granularity, $user_data);
1735 return undef unless $wait;
1736 my $resp = $req->recv;
1737 return $resp->content if $resp;
1740 sub create_uuid_string {
1741 return create_UUID_as_string();
1744 sub create_circ_chain_summary {
1745 my($class, $e, $circ_id) = @_;
1746 my $sum = $e->json_query({from => ['action.summarize_circ_chain', $circ_id]})->[0];
1747 return undef unless $sum;
1748 my $obj = Fieldmapper::action::circ_chain_summary->new;
1749 $obj->$_($sum->{$_}) for keys %$sum;
1754 # Returns "mra" attribute key/value pairs for a set of bre's
1755 # Takes a list of bre IDs, returns a hash of hashes,
1756 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1759 my ($class, $bre_ids, $e) = @_;
1760 $e = $e || OpenILS::Utils::CStoreEditor->new;
1763 return $attrs unless defined $bre_ids;
1764 $bre_ids = [$bre_ids] unless ref $bre_ids;
1766 my $mra = $e->json_query({
1774 transform => 'each',
1775 result_field => 'key',
1779 transform => 'each',
1780 result_field => 'value',
1786 where => {id => $bre_ids}
1789 return $attrs unless $mra;
1791 $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
1793 for my $id (@$bre_ids) {
1795 for my $mra (grep { $_->{bre} eq $id } @$mra) {
1796 my $ctype = $mra->{key};
1797 my $code = $mra->{value};
1798 $attrs->{$id}->{$ctype} = {code => $code};
1800 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
1801 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
1809 # Shorter version of bib_container_items_via_search() below, only using
1810 # the queryparser record_list filter instead of the container filter.
1811 sub bib_record_list_via_search {
1812 my ($class, $search_query, $search_args) = @_;
1814 # First, Use search API to get container items sorted in any way that crad
1816 my $search_result = $class->simplereq(
1817 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1818 $search_args, $search_query
1821 unless ($search_result) {
1822 # empty result sets won't cause this, but actual errors should.
1823 $logger->warn("bib_record_list_via_search() got nothing from search");
1827 # Throw away other junk from search, keeping only bib IDs.
1828 return [ map { pop @$_ } @{$search_result->{ids}} ];
1831 # 'no_flesh' avoids fleshing the target_biblio_record_entry
1832 sub bib_container_items_via_search {
1833 my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
1835 # First, Use search API to get container items sorted in any way that crad
1837 my $search_result = $class->simplereq(
1838 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1839 $search_args, $search_query
1841 unless ($search_result) {
1842 # empty result sets won't cause this, but actual errors should.
1843 $logger->warn("bib_container_items_via_search() got nothing from search");
1847 # Throw away other junk from search, keeping only bib IDs.
1848 my $id_list = [ map { pop @$_ } @{$search_result->{ids}} ];
1850 return [] unless @$id_list;
1852 # Now get the bib container items themselves...
1853 my $e = new OpenILS::Utils::CStoreEditor;
1855 $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
1859 my @flesh_fields = qw/notes/;
1860 push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
1862 my $items = $e->search_container_biblio_record_entry_bucket_item([
1864 "target_biblio_record_entry" => $id_list,
1865 "bucket" => $container_id
1868 flesh_fields => {"cbrebi" => \@flesh_fields}
1873 "bib_container_items_via_search() couldn't get bucket items: " .
1874 $e->die_event->{textcode}
1879 # ... and put them in the same order that the search API said they
1881 my %ordering_hash = map {
1882 ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id,
1886 return [map { $ordering_hash{$_} } @$id_list];
1889 # returns undef on success, Event on error
1890 sub log_user_activity {
1891 my ($class, $user_id, $who, $what, $e, $async) = @_;
1895 $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
1899 my $res = $e->json_query({
1901 'actor.insert_usr_activity',
1902 $user_id, $who, $what, OpenSRF::AppSession->ingress
1906 if ($res) { # call returned OK
1908 $e->commit if $commit and @$res;
1909 $e->rollback if $commit and !@$res;
1912 return $e->die_event;
1918 # I hate to put this here exactly, but this code needs to be shared between
1919 # the TPAC's mod_perl module and open-ils.serial.
1921 # There is a reason every part of the query *except* those parts dealing
1922 # with scope are moved here from the code's origin in TPAC. The serials
1923 # use case does *not* want the same scoping logic.
1925 # Also, note that for the serials uses case, we may filter in OPAC visible
1926 # status and copy/call_number deletedness, but we don't filter on any
1927 # particular values for serial.item.status or serial.item.date_received.
1928 # Since we're only using this *after* winnowing down the set of issuances
1929 # that copies should be related to, I'm not sure we need any such serial.item
1932 sub basic_opac_copy_query {
1933 ######################################################################
1934 # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
1936 ######################################################################
1937 my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
1941 acp => ['id', 'barcode', 'circ_lib', 'create_date',
1942 'age_protect', 'holdable'],
1944 {column => 'name', alias => 'copy_location'},
1945 {column => 'holdable', alias => 'location_holdable'}
1948 {column => 'name', alias => 'copy_status'},
1949 {column => 'holdable', alias => 'status_holdable'}
1952 {column => 'label', alias => 'call_number_label'},
1953 {column => 'id', alias => 'call_number'}
1955 circ => ['due_date'],
1957 {column => 'label', alias => 'call_number_prefix_label'},
1958 {column => 'id', alias => 'call_number_prefix'}
1961 {column => 'label', alias => 'call_number_suffix_label'},
1962 {column => 'id', alias => 'call_number_suffix'}
1965 {column => 'label', alias => 'part_label'},
1967 ($iss_id ? (sitem => ["issuance"]) : ())
1976 filter => {issuance => $iss_id},
1984 acnp => { fkey => 'prefix' },
1985 acns => { fkey => 'suffix' }
1989 ($rec_id ? {record => $rec_id} : ())
1992 circ => { # If the copy is circulating, retrieve the open circ
1994 filter => {checkin_time => undef}
1997 ($staff ? () : (filter => { opac_visible => 't' }))
2000 ($staff ? () : (filter => { opac_visible => 't' }))
2006 bmp => { type => 'left' }
2015 ($staff ? () : (opac_visible => 't'))
2017 ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2018 ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2022 {class => 'aou', field => 'name'},
2023 {class => 'acn', field => 'label'}
2026 limit => $copy_limit,
2027 offset => $copy_offset