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 use DateTime::Format::ISO8601;
21 # ---------------------------------------------------------------------------
22 # Pile of utilty methods used accross applications.
23 # ---------------------------------------------------------------------------
24 my $cache_client = "OpenSRF::Utils::Cache";
27 # ---------------------------------------------------------------------------
28 # on sucess, returns the created session, on failure throws ERROR exception
29 # ---------------------------------------------------------------------------
30 sub start_db_session {
33 my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
34 my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
36 my $trans_resp = $trans_req->recv();
37 if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
38 if( ! $trans_resp->content() ) {
40 ("Unable to Begin Transaction with database" );
44 $logger->debug("Setting global storage session to ".
45 "session: " . $session->session_id . " : " . $session->app );
53 my $authtoken = shift;
57 my $audit_req = $session->request( "open-ils.storage.set_audit_info", $authtoken, $user_id, $ws_id );
58 my $audit_resp = $audit_req->recv();
65 transform => 'permission.usr_has_perm',
76 # returns undef if user has all of the perms provided
77 # returns the first failed perm on failure
78 sub check_user_perms {
79 my($self, $user_id, $org_id, @perm_types ) = @_;
80 $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
82 for my $type (@perm_types) {
83 $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
84 $PERM_QUERY->{where}->{id} = $user_id;
85 return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
90 # checks the list of user perms. The first one that fails returns a new
92 my( $self, $user_id, $org_id, @perm_types ) = @_;
93 my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
94 return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
100 # ---------------------------------------------------------------------------
101 # commits and destroys the session
102 # ---------------------------------------------------------------------------
103 sub commit_db_session {
104 my( $self, $session ) = @_;
106 my $req = $session->request( "open-ils.storage.transaction.commit" );
107 my $resp = $req->recv();
110 throw OpenSRF::EX::ERROR ("Unable to commit db session");
113 if(UNIVERSAL::isa($resp,"Error")) {
114 throw $resp ($resp->stringify);
117 if(!$resp->content) {
118 throw OpenSRF::EX::ERROR ("Unable to commit db session");
122 $session->disconnect();
126 sub rollback_db_session {
127 my( $self, $session ) = @_;
129 my $req = $session->request("open-ils.storage.transaction.rollback");
130 my $resp = $req->recv();
131 if(UNIVERSAL::isa($resp,"Error")) { throw $resp; }
134 $session->disconnect();
139 # returns undef it the event is not an ILS event
140 # returns the event code otherwise
142 my( $self, $evt ) = @_;
143 return $evt->{ilsevent} if $self->is_event($evt);
147 # some events, in particular auto-generated events, don't have an
148 # ilsevent key. treat hashes with a 'textcode' key as events.
150 my ($self, $evt) = @_;
152 ref($evt) eq 'HASH' and (
153 defined $evt->{ilsevent} or
154 defined $evt->{textcode}
159 # ---------------------------------------------------------------------------
160 # Checks to see if a user is logged in. Returns the user record on success,
161 # throws an exception on error.
162 # ---------------------------------------------------------------------------
163 sub check_user_session {
164 my( $self, $user_session ) = @_;
166 my $content = $self->simplereq(
168 'open-ils.auth.session.retrieve', $user_session);
170 return undef if (!$content) or $self->event_code($content);
174 # generic simple request returning a scalar value
176 my($self, $service, $method, @params) = @_;
177 return $self->simple_scalar_request($service, $method, @params);
181 sub simple_scalar_request {
182 my($self, $service, $method, @params) = @_;
184 my $session = OpenSRF::AppSession->create( $service );
186 my $request = $session->request( $method, @params );
192 $val = $request->gather(1);
199 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
200 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
207 my( $self, $orglist ) = @_;
209 return $orglist unless ref $orglist;
210 return $$orglist[0] if @$orglist == 1;
213 $a->ou_type <=> $b->ou_type ||
214 $a->name cmp $b->name } @$orglist;
216 for my $org (@list) {
219 next if (!defined($org->parent_ou) || $org->parent_ou eq "");
221 my ($parent) = grep { $_->id == $org->parent_ou } @list;
223 $parent->children([]) unless defined($parent->children);
224 push( @{$parent->children}, $org );
230 sub fetch_closed_date {
231 my( $self, $cd ) = @_;
234 $logger->debug("Fetching closed_date $cd from cstore");
236 my $cd_obj = $self->simplereq(
238 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
241 $logger->info("closed_date $cd not found in the db");
242 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
245 return ($cd_obj, $evt);
249 my( $self, $userid ) = @_;
252 $logger->debug("Fetching user $userid from cstore");
254 $user = $self->simplereq(
256 'open-ils.cstore.direct.actor.user.retrieve', $userid );
259 $logger->info("User $userid not found in the db");
260 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
263 return ($user, $evt);
267 my( $self, $session ) = @_;
268 my $user = $self->check_user_session($session) or
269 return (undef, OpenILS::Event->new('NO_SESSION'));
274 # verifiese the session and checks the permissions agains the
275 # session user and the user's home_ou as the org id
277 my( $self, $session, @perms ) = @_;
278 my $user; my $evt; my $e;
279 $logger->debug("Checking user session $session and perms @perms");
280 ($user, $evt) = $self->checkses($session);
281 return (undef, $evt) if $evt;
282 $evt = $self->check_perms($user->id, $user->home_ou, @perms);
283 return ($user, $evt);
288 my( $self, $staffobj, $userid, @perms ) = @_;
290 $userid = $staffobj->id unless defined $userid;
292 $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
294 if( $userid ne $staffobj->id ) {
295 ($user, $evt) = $self->fetch_user($userid);
296 return (undef, $evt) if $evt;
297 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
303 return ($user, $evt);
306 sub checkses_requestor {
307 my( $self, $authtoken, $targetid, @perms ) = @_;
308 my( $requestor, $target, $evt );
310 ($requestor, $evt) = $self->checkses($authtoken);
311 return (undef, undef, $evt) if $evt;
313 ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
314 return( $requestor, $target, $evt);
318 my( $self, $copyid ) = @_;
321 $logger->debug("Fetching copy $copyid from cstore");
323 $copy = $self->simplereq(
325 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
327 if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
329 return( $copy, $evt );
333 # retrieves a circ object by id
334 sub fetch_circulation {
335 my( $self, $circid ) = @_;
338 $logger->debug("Fetching circ $circid from cstore");
340 $circ = $self->simplereq(
342 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
345 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
348 return ( $circ, $evt );
351 sub fetch_record_by_copy {
352 my( $self, $copyid ) = @_;
355 $logger->debug("Fetching record by copy $copyid from cstore");
357 $record = $self->simplereq(
359 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
361 flesh_fields => { bre => [ 'fixed_fields' ],
363 acp => [ 'call_number' ],
369 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
371 $record = $record->call_number->record;
374 return ($record, $evt);
377 # turns a record object into an mvr (mods) object
379 my( $self, $record ) = @_;
380 return undef unless $record and $record->marc;
381 my $u = OpenILS::Utils::ModsParser->new();
382 $u->start_mods_batch( $record->marc );
383 my $mods = $u->finish_mods_batch();
384 $mods->doc_id($record->id);
385 $mods->tcn($record->tcn_value);
390 my( $self, $holdid ) = @_;
393 $logger->debug("Fetching hold $holdid from cstore");
395 $hold = $self->simplereq(
397 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
399 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
401 return ($hold, $evt);
405 sub fetch_hold_transit_by_hold {
406 my( $self, $holdid ) = @_;
407 my( $transit, $evt );
409 $logger->debug("Fetching transit by hold $holdid from cstore");
411 $transit = $self->simplereq(
413 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
415 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
417 return ($transit, $evt );
420 # fetches the captured, but not fulfilled hold attached to a given copy
421 sub fetch_open_hold_by_copy {
422 my( $self, $copyid ) = @_;
423 $logger->debug("Searching for active hold for copy $copyid");
426 $hold = $self->cstorereq(
427 'open-ils.cstore.direct.action.hold_request.search',
429 current_copy => $copyid ,
430 capture_time => { "!=" => undef },
431 fulfillment_time => undef,
432 cancel_time => undef,
435 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
436 return ($hold, $evt);
439 sub fetch_hold_transit {
440 my( $self, $transid ) = @_;
441 my( $htransit, $evt );
442 $logger->debug("Fetching hold transit with hold id $transid");
443 $htransit = $self->cstorereq(
444 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
445 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
446 return ($htransit, $evt);
449 sub fetch_copy_by_barcode {
450 my( $self, $barcode ) = @_;
453 $logger->debug("Fetching copy by barcode $barcode from cstore");
455 $copy = $self->simplereq( 'open-ils.cstore',
456 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
457 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
459 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
461 return ($copy, $evt);
464 sub fetch_open_billable_transaction {
465 my( $self, $transid ) = @_;
466 my( $transaction, $evt );
468 $logger->debug("Fetching open billable transaction $transid from cstore");
470 $transaction = $self->simplereq(
472 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve', $transid);
474 $evt = OpenILS::Event->new(
475 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
477 return ($transaction, $evt);
483 $buckets{'biblio'} = 'biblio_record_entry_bucket';
484 $buckets{'callnumber'} = 'call_number_bucket';
485 $buckets{'copy'} = 'copy_bucket';
486 $buckets{'user'} = 'user_bucket';
488 sub fetch_container {
489 my( $self, $id, $type ) = @_;
492 $logger->debug("Fetching container $id with type $type");
494 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
495 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
496 $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
497 $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
499 my $meth = $buckets{$type};
500 $bucket = $self->simplereq(
502 "open-ils.cstore.direct.container.$meth.retrieve", $id );
504 $evt = OpenILS::Event->new(
505 $e, container => $id, container_type => $type ) unless $bucket;
507 return ($bucket, $evt);
511 sub fetch_container_e {
512 my( $self, $editor, $id, $type ) = @_;
515 $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
516 $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
517 $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
518 $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
520 $evt = $editor->event unless $bucket;
521 return ($bucket, $evt);
524 sub fetch_container_item_e {
525 my( $self, $editor, $id, $type ) = @_;
528 $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
529 $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
530 $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
531 $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
533 $evt = $editor->event unless $bucket;
534 return ($bucket, $evt);
541 sub fetch_container_item {
542 my( $self, $id, $type ) = @_;
545 $logger->debug("Fetching container item $id with type $type");
547 my $meth = $buckets{$type} . "_item";
549 $bucket = $self->simplereq(
551 "open-ils.cstore.direct.container.$meth.retrieve", $id );
554 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
555 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
556 $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
557 $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
559 $evt = OpenILS::Event->new(
560 $e, itemid => $id, container_type => $type ) unless $bucket;
562 return ($bucket, $evt);
566 sub fetch_patron_standings {
568 $logger->debug("Fetching patron standings");
569 return $self->simplereq(
571 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
575 sub fetch_permission_group_tree {
577 $logger->debug("Fetching patron profiles");
578 return $self->simplereq(
580 'open-ils.actor.groups.tree.retrieve' );
583 sub fetch_permission_group_descendants {
584 my( $self, $profile ) = @_;
585 my $group_tree = $self->fetch_permission_group_tree();
589 # FIXME: okay, so it's not an org tree, but it is compatible
590 $self->walk_org_tree($group_tree, sub {
592 if ($g->id == $profile) {
597 $self->walk_org_tree($start_here, sub {
599 push(@groups,$g->id);
605 sub fetch_patron_circ_summary {
606 my( $self, $userid ) = @_;
607 $logger->debug("Fetching patron summary for $userid");
608 my $summary = $self->simplereq(
610 "open-ils.storage.action.circulation.patron_summary", $userid );
614 $summary->[1] ||= 0.0;
621 sub fetch_copy_statuses {
623 $logger->debug("Fetching copy statuses");
624 return $self->simplereq(
626 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
629 sub fetch_copy_location {
630 my( $self, $id ) = @_;
632 my $cl = $self->cstorereq(
633 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
634 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
638 sub fetch_copy_locations {
640 return $self->simplereq(
642 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
645 sub fetch_copy_location_by_name {
646 my( $self, $name, $org ) = @_;
648 my $cl = $self->cstorereq(
649 'open-ils.cstore.direct.asset.copy_location.search',
650 { name => $name, owning_lib => $org } );
651 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
655 sub fetch_callnumber {
656 my( $self, $id, $flesh, $e ) = @_;
658 $e ||= OpenILS::Utils::CStoreEditor->new;
660 my $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
661 return( undef, $evt ) unless $id;
663 $logger->debug("Fetching callnumber $id");
665 my $cn = $e->retrieve_asset_call_number([
667 { flesh => $flesh, flesh_fields => { acn => [ 'prefix', 'suffix', 'label_class' ] } },
670 return ( $cn, $e->event );
673 my %ORG_CACHE; # - these rarely change, so cache them..
675 my( $self, $id ) = @_;
676 return undef unless $id;
677 return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
678 return $ORG_CACHE{$id} if $ORG_CACHE{$id};
679 $logger->debug("Fetching org unit $id");
682 my $org = $self->simplereq(
684 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
685 $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
686 $ORG_CACHE{$id} = $org;
692 my( $self, $type, $id ) = @_;
694 $logger->debug("Fetching $type stat cat: $id");
695 $cat = $self->simplereq(
697 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
699 my $e = 'ASSET_STAT_CAT_NOT_FOUND';
700 $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
702 $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
703 return ( $cat, $evt );
706 sub fetch_stat_cat_entry {
707 my( $self, $type, $id ) = @_;
709 $logger->debug("Fetching $type stat cat entry: $id");
710 $entry = $self->simplereq(
712 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
714 my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
715 $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
717 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
718 return ( $entry, $evt );
721 sub fetch_stat_cat_entry_default {
722 my( $self, $type, $id ) = @_;
723 my( $entry_default, $evt );
724 $logger->debug("Fetching $type stat cat entry default: $id");
725 $entry_default = $self->simplereq(
727 "open-ils.cstore.direct.$type.stat_cat_entry_default.retrieve", $id );
729 my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
730 $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
732 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry_default;
733 return ( $entry_default, $evt );
736 sub fetch_stat_cat_entry_default_by_stat_cat_and_org {
737 my( $self, $type, $stat_cat, $orgId ) = @_;
739 $logger->info("### Fetching $type stat cat entry default with stat_cat $stat_cat owned by org_unit $orgId");
740 $entry_default = $self->simplereq(
742 "open-ils.cstore.direct.$type.stat_cat_entry_default.search.atomic",
743 { stat_cat => $stat_cat, owner => $orgId } );
745 $entry_default = $entry_default->[0];
746 return ($entry_default, undef) if $entry_default;
748 my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
749 $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
750 return (undef, OpenILS::Event->new($e) );
754 my( $self, $org_tree, $orgid ) = @_;
755 return undef unless $org_tree and defined $orgid;
756 return $org_tree if ( $org_tree->id eq $orgid );
757 return undef unless ref($org_tree->children);
758 for my $c (@{$org_tree->children}) {
759 my $o = $self->find_org($c, $orgid);
765 sub fetch_non_cat_type_by_name_and_org {
766 my( $self, $name, $orgId ) = @_;
767 $logger->debug("Fetching non cat type $name at org $orgId");
768 my $types = $self->simplereq(
770 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
771 { name => $name, owning_lib => $orgId } );
772 return ($types->[0], undef) if($types and @$types);
773 return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
776 sub fetch_non_cat_type {
777 my( $self, $id ) = @_;
778 $logger->debug("Fetching non cat type $id");
780 $type = $self->simplereq(
782 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
783 $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
784 return ($type, $evt);
787 sub DB_UPDATE_FAILED {
788 my( $self, $payload ) = @_;
789 return OpenILS::Event->new('DATABASE_UPDATE_FAILED',
790 payload => ($payload) ? $payload : undef );
793 sub fetch_booking_reservation {
794 my( $self, $id ) = @_;
797 $res = $self->simplereq(
799 'open-ils.cstore.direct.booking.reservation.retrieve', $id
802 # simplereq doesn't know how to flesh so ...
807 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
811 $res->target_resource_type(
814 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
818 if ($res->current_resource) {
819 $res->current_resource(
822 'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
826 if ($self->is_true( $res->target_resource_type->catalog_item )) {
827 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
831 if ($res->target_resource) {
832 $res->target_resource(
835 'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
839 if ($self->is_true( $res->target_resource_type->catalog_item )) {
840 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
845 $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
851 sub fetch_circ_duration_by_name {
852 my( $self, $name ) = @_;
854 $dur = $self->simplereq(
856 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
858 $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
862 sub fetch_recurring_fine_by_name {
863 my( $self, $name ) = @_;
865 $obj = $self->simplereq(
867 'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
869 $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
873 sub fetch_max_fine_by_name {
874 my( $self, $name ) = @_;
876 $obj = $self->simplereq(
878 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
880 $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
884 sub fetch_hard_due_date_by_name {
885 my( $self, $name ) = @_;
887 $obj = $self->simplereq(
889 'open-ils.cstore.direct.config.hard_due_date.search.atomic', { name => $name } );
891 $evt = OpenILS::Event->new('CONFIG_RULES_HARD_DUE_DATE_NOT_FOUND') unless $obj;
896 my( $self, $method, @params ) = @_;
897 return $self->simplereq(
898 'open-ils.storage', $method, @params );
901 sub storagereq_xact {
902 my($self, $method, @params) = @_;
903 my $ses = $self->start_db_session();
904 my $val = $ses->request($method, @params)->gather(1);
905 $self->rollback_db_session($ses);
910 my( $self, $method, @params ) = @_;
911 return $self->simplereq(
912 'open-ils.cstore', $method, @params );
916 my( $self, $e, $name ) = @_;
917 if( $e and ref($e) eq 'HASH' and
918 defined($e->{textcode}) and $e->{textcode} eq $name ) {
925 my( undef, $f, $l ) = caller(0);
926 my( undef, undef, undef, $s ) = caller(1);
929 $logger->debug("LOGMARK: $f:$l:$s");
933 sub fetch_open_circulation {
934 my( $self, $cid ) = @_;
937 my $e = OpenILS::Utils::CStoreEditor->new;
938 my $circ = $e->search_action_circulation({
940 stop_fines_time => undef,
941 checkin_time => undef
944 return ($circ, $e->event);
948 sub copy_status_from_name {
949 my( $self, $name ) = @_;
950 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
951 for my $status (@$copy_statuses) {
952 return $status if( $status->name =~ /$name/i );
957 sub copy_status_to_name {
958 my( $self, $sid ) = @_;
959 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
960 for my $status (@$copy_statuses) {
961 return $status->name if( $status->id == $sid );
968 my( $self, $arg ) = @_;
969 return $arg if ref $arg;
970 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
971 my ($stat) = grep { $_->id == $arg } @$copy_statuses;
975 sub fetch_open_transit_by_copy {
976 my( $self, $copyid ) = @_;
978 $transit = $self->cstorereq(
979 'open-ils.cstore.direct.action.transit_copy.search',
980 { target_copy => $copyid, dest_recv_time => undef });
981 $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
982 return ($transit, $evt);
986 my( $self, $copy ) = @_;
987 return undef unless $copy;
988 $copy->status( $copy->status->id ) if ref($copy->status);
989 $copy->location( $copy->location->id ) if ref($copy->location);
990 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
994 sub unflesh_reservation {
995 my( $self, $reservation ) = @_;
996 return undef unless $reservation;
997 $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
998 $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
999 $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
1000 $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
1001 return $reservation;
1004 # un-fleshes a copy and updates it in the DB
1005 # returns a DB_UPDATE_FAILED event on error
1006 # returns undef on success
1008 my( $self, %params ) = @_;
1010 my $copy = $params{copy} || die "update_copy(): copy required";
1011 my $editor = $params{editor} || die "update_copy(): copy editor required";
1012 my $session = $params{session};
1014 $logger->debug("Updating copy in the database: " . $copy->id);
1016 $self->unflesh_copy($copy);
1017 $copy->editor( $editor );
1018 $copy->edit_date( 'now' );
1021 my $meth = 'open-ils.storage.direct.asset.copy.update';
1023 $s = $session->request( $meth, $copy )->gather(1) if $session;
1024 $s = $self->storagereq( $meth, $copy ) unless $session;
1026 $logger->debug("Update of copy ".$copy->id." returned: $s");
1028 return $self->DB_UPDATE_FAILED($copy) unless $s;
1032 sub update_reservation {
1033 my( $self, %params ) = @_;
1035 my $reservation = $params{reservation} || die "update_reservation(): reservation required";
1036 my $editor = $params{editor} || die "update_reservation(): copy editor required";
1037 my $session = $params{session};
1039 $logger->debug("Updating copy in the database: " . $reservation->id);
1041 $self->unflesh_reservation($reservation);
1044 my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1046 $s = $session->request( $meth, $reservation )->gather(1) if $session;
1047 $s = $self->cstorereq( $meth, $reservation ) unless $session;
1049 $logger->debug("Update of copy ".$reservation->id." returned: $s");
1051 return $self->DB_UPDATE_FAILED($reservation) unless $s;
1055 sub fetch_billable_xact {
1056 my( $self, $id ) = @_;
1058 $logger->debug("Fetching billable transaction %id");
1059 $xact = $self->cstorereq(
1060 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1061 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1062 return ($xact, $evt);
1065 sub fetch_billable_xact_summary {
1066 my( $self, $id ) = @_;
1068 $logger->debug("Fetching billable transaction summary %id");
1069 $xact = $self->cstorereq(
1070 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1071 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1072 return ($xact, $evt);
1075 sub fetch_fleshed_copy {
1076 my( $self, $id ) = @_;
1078 $logger->info("Fetching fleshed copy $id");
1079 $copy = $self->cstorereq(
1080 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1082 flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1085 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1086 return ($copy, $evt);
1090 # returns the org that owns the callnumber that the copy
1092 sub fetch_copy_owner {
1093 my( $self, $copyid ) = @_;
1094 my( $copy, $cn, $evt );
1095 $logger->debug("Fetching copy owner $copyid");
1096 ($copy, $evt) = $self->fetch_copy($copyid);
1097 return (undef,$evt) if $evt;
1098 ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1099 return (undef,$evt) if $evt;
1100 return ($cn->owning_lib);
1103 sub fetch_copy_note {
1104 my( $self, $id ) = @_;
1106 $logger->debug("Fetching copy note $id");
1107 $note = $self->cstorereq(
1108 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1109 $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1110 return ($note, $evt);
1113 sub fetch_call_numbers_by_title {
1114 my( $self, $titleid ) = @_;
1115 $logger->info("Fetching call numbers by title $titleid");
1116 return $self->cstorereq(
1117 'open-ils.cstore.direct.asset.call_number.search.atomic',
1118 { record => $titleid, deleted => 'f' });
1119 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1122 sub fetch_copies_by_call_number {
1123 my( $self, $cnid ) = @_;
1124 $logger->info("Fetching copies by call number $cnid");
1125 return $self->cstorereq(
1126 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1127 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1130 sub fetch_user_by_barcode {
1131 my( $self, $bc ) = @_;
1132 my $cardid = $self->cstorereq(
1133 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1134 return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1135 my $user = $self->cstorereq(
1136 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1137 return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1143 my( $self, $billid ) = @_;
1144 $logger->debug("Fetching billing $billid");
1145 my $bill = $self->cstorereq(
1146 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1147 my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1148 return($bill, $evt);
1152 my( $self, $node, $callback ) = @_;
1153 return unless $node;
1155 if( $node->children ) {
1156 $self->walk_org_tree($_, $callback) for @{$node->children};
1161 my( $self, $item ) = @_;
1162 return 1 if $item and $item !~ /^f$/i;
1168 my ($self, $client, $service, $method, @params) = @_;
1169 my ($response, $err);
1171 my $session = create OpenSRF::AppSession($service);
1172 my $request = $session->request($method, @params);
1175 my $give_up = time + 1000;
1178 while (time < $give_up) {
1179 $response = $request->recv("timeout" => $spurt);
1180 last if $request->complete;
1182 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1184 } catch Error with {
1189 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
1190 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
1193 return $response->content;
1196 # This logic now lives in storage
1197 sub __patron_money_owed {
1198 my( $self, $patronid ) = @_;
1199 my $ses = OpenSRF::AppSession->create('open-ils.storage');
1200 my $req = $ses->request(
1201 'open-ils.storage.money.billable_transaction.summary.search',
1202 { usr => $patronid, xact_finish => undef } );
1206 while( $data = $req->recv ) {
1207 $data = $data->content;
1208 $total += $data->balance_owed;
1213 sub patron_money_owed {
1214 my( $self, $userid ) = @_;
1215 my $ses = $self->start_db_session();
1216 my $val = $ses->request(
1217 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1218 $self->rollback_db_session($ses);
1222 sub patron_total_items_out {
1223 my( $self, $userid ) = @_;
1224 my $ses = $self->start_db_session();
1225 my $val = $ses->request(
1226 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1227 $self->rollback_db_session($ses);
1234 #---------------------------------------------------------------------
1235 # Returns ($summary, $event)
1236 #---------------------------------------------------------------------
1240 my $e = shift || OpenILS::Utils::CStoreEditor->new;
1241 $id = $id->id if ref($id);
1243 my $xact = $e->retrieve_money_billable_transaction_summary($id)
1244 or return (undef, $e->event);
1250 #---------------------------------------------------------------------
1251 # Given a list of money.billable_transaction objects, this creates
1252 # transaction summary objects for each
1253 #--------------------------------------------------------------------
1258 return () if (!@xacts);
1259 return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1263 sub ou_ancestor_setting_value {
1264 my($self, $org_id, $name, $e) = @_;
1265 $e = $e || OpenILS::Utils::CStoreEditor->new;
1266 my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1267 return $set->{value} if $set;
1272 # If an authentication token is provided AND this org unit setting has a
1273 # view_perm, then make sure the user referenced by the auth token has
1274 # that permission. This means that if you call this method without an
1275 # authtoken param, you can get whatever org unit setting values you want.
1278 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1279 # authtoken is checked, but the $auth arg is NOT checked. To say that another
1280 # way, be sure NOT to pass an editor argument if you want your token checked.
1281 # Otherwise the auth arg is just a flag saying "check the editor".
1283 sub ou_ancestor_setting {
1284 my( $self, $orgid, $name, $e, $auth ) = @_;
1285 $e = $e || OpenILS::Utils::CStoreEditor->new(
1286 (defined $auth) ? (authtoken => $auth) : ()
1288 my $coust = $e->retrieve_config_org_unit_setting_type([
1289 $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1292 if ($auth && $coust && $coust->view_perm) {
1293 # And you can't have permission if you don't have a valid session.
1294 return undef if not $e->checkauth;
1295 # And now that we know you MIGHT have permission, we check it.
1296 return undef if not $e->allowed($coust->view_perm->code, $orgid);
1299 my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1300 my $setting = $e->json_query($query)->[0];
1301 return undef unless $setting;
1302 return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1306 # returns the ISO8601 string representation of the requested epoch in GMT
1308 my( $self, $epoch ) = @_;
1309 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1310 $year += 1900; $mon += 1;
1312 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1313 $year, $mon, $mday, $hour, $min, $sec);
1317 sub find_highest_perm_org {
1318 my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1319 my $org = $self->find_org($org_tree, $start_org );
1323 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1325 $org = $self->find_org( $org_tree, $org->parent_ou() );
1332 # returns the org_unit ID's
1333 sub user_has_work_perm_at {
1334 my($self, $e, $perm, $options, $user_id) = @_;
1336 $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1338 my $func = 'permission.usr_has_perm_at';
1339 $func = $func.'_all' if $$options{descendants};
1341 my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1342 $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1344 return $orgs unless $$options{objects};
1346 return $e->search_actor_org_unit({id => $orgs});
1349 sub get_user_work_ou_ids {
1350 my($self, $e, $userid) = @_;
1351 my $work_orgs = $e->json_query({
1352 select => {puwoum => ['work_ou']},
1354 where => {usr => $e->requestor->id}});
1356 return [] unless @$work_orgs;
1358 push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1366 my($self, $client) = @_;
1367 return $org_types if $org_types;
1368 return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1374 my $locale = shift || '';
1375 my $cache = OpenSRF::Utils::Cache->new("global", 0);
1376 my $tree = $ORG_TREE{$locale} || $cache->get_cache("orgtree.$locale");
1377 return $tree if $tree;
1379 my $ses = OpenILS::Utils::CStoreEditor->new;
1380 $ses->session->session_locale($locale);
1381 $tree = $ses->search_actor_org_unit(
1383 {"parent_ou" => undef },
1386 flesh_fields => { aou => ['children'] },
1387 order_by => { aou => 'name'}
1392 $ORG_TREE{$locale} = $tree;
1393 $cache->put_cache("orgtree.$locale", $tree);
1397 sub get_org_descendants {
1398 my($self, $org_id, $depth) = @_;
1401 transform => 'actor.org_unit_descendants',
1403 result_field => 'id',
1405 $select->{params} = [$depth] if defined $depth;
1407 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1408 select => {aou => [$select]},
1410 where => {id => $org_id}
1413 push(@orgs, $_->{id}) for @$org_list;
1417 sub get_org_ancestors {
1418 my($self, $org_id, $use_cache) = @_;
1423 $cache = OpenSRF::Utils::Cache->new("global", 0);
1424 $orgs = $cache->get_cache("org.ancestors.$org_id");
1425 return $orgs if $orgs;
1428 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1431 transform => 'actor.org_unit_ancestors',
1433 result_field => 'id',
1438 where => {id => $org_id}
1441 $orgs = [ map { $_->{id} } @$org_list ];
1443 $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1447 sub get_org_full_path {
1448 my($self, $org_id, $depth) = @_;
1453 transform => 'actor.org_unit_full_path',
1455 result_field => 'id',
1459 where => {id => $org_id}
1462 $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1463 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1464 return [ map {$_->{id}} @$org_list ];
1467 # returns the ID of the org unit ancestor at the specified depth
1468 sub org_unit_ancestor_at_depth {
1469 my($class, $org_id, $depth) = @_;
1470 my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1471 {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1472 return ($resp) ? $resp->{id} : undef;
1475 # returns the user's configured locale as a string. Defaults to en-US if none is configured.
1476 sub get_user_locale {
1477 my($self, $user_id, $e) = @_;
1478 $e ||= OpenILS::Utils::CStoreEditor->new;
1480 # first, see if the user has an explicit locale set
1481 my $setting = $e->search_actor_user_setting(
1482 {usr => $user_id, name => 'global.locale'})->[0];
1483 return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1485 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1486 return $self->get_org_locale($user->home_ou, $e);
1489 # returns org locale setting
1490 sub get_org_locale {
1491 my($self, $org_id, $e) = @_;
1492 $e ||= OpenILS::Utils::CStoreEditor->new;
1495 if(defined $org_id) {
1496 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1497 return $locale if $locale;
1500 # system-wide default
1501 my $sclient = OpenSRF::Utils::SettingsClient->new;
1502 $locale = $sclient->config_value('default_locale');
1503 return $locale if $locale;
1505 # if nothing else, fallback to locale=cowboy
1510 # xml-escape non-ascii characters
1512 my($self, $string, $form) = @_;
1515 # If we're going to convert non-ASCII characters to XML entities,
1516 # we had better be dealing with a UTF8 string to begin with
1517 $string = decode_utf8($string);
1520 $string = NFD($string);
1522 $string = NFC($string);
1525 # Convert raw ampersands to entities
1526 $string =~ s/&(?!\S+;)/&/gso;
1528 # Convert Unicode characters to entities
1529 $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1534 # x0000-x0008 isn't legal in XML documents
1535 # XXX Perhaps this should just go into our standard entityize method
1536 sub strip_ctrl_chars {
1537 my ($self, $string) = @_;
1539 $string =~ s/([\x{0000}-\x{0008}])//sgoe;
1543 sub get_copy_price {
1544 my($self, $e, $copy, $volume) = @_;
1546 $copy->price(0) if $copy->price and $copy->price < 0;
1548 return $copy->price if $copy->price and $copy->price > 0;
1553 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1554 $owner = $copy->circ_lib;
1556 $owner = $volume->owning_lib;
1559 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1560 $owner = $copy->circ_lib;
1562 $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1566 my $default_price = $self->ou_ancestor_setting_value(
1567 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1569 return $default_price unless defined $copy->price;
1571 # price is 0. Use the default?
1572 my $charge_on_0 = $self->ou_ancestor_setting_value(
1573 $owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e) || 0;
1575 return $default_price if $charge_on_0;
1579 # given a transaction ID, this returns the context org_unit for the transaction
1581 my($self, $xact_id, $e) = @_;
1582 $e ||= OpenILS::Utils::CStoreEditor->new;
1584 my $loc = $e->json_query({
1585 "select" => {circ => ["circ_lib"]},
1587 "where" => {id => $xact_id},
1590 return $loc->[0]->{circ_lib} if @$loc;
1592 $loc = $e->json_query({
1593 "select" => {bresv => ["request_lib"]},
1595 "where" => {id => $xact_id},
1598 return $loc->[0]->{request_lib} if @$loc;
1600 $loc = $e->json_query({
1601 "select" => {mg => ["billing_location"]},
1603 "where" => {id => $xact_id},
1606 return $loc->[0]->{billing_location};
1610 sub find_event_def_by_hook {
1611 my($self, $hook, $context_org, $e) = @_;
1613 $e ||= OpenILS::Utils::CStoreEditor->new;
1615 my $orgs = $self->get_org_ancestors($context_org);
1617 # search from the context org up
1618 for my $org_id (reverse @$orgs) {
1620 my $def = $e->search_action_trigger_event_definition(
1621 {hook => $hook, owner => $org_id})->[0];
1623 return $def if $def;
1631 # If an event_def ID is not provided, use the hook and context org to find the
1632 # most appropriate event. create the event, fire it, then return the resulting
1633 # event with fleshed template_output and error_output
1634 sub fire_object_event {
1635 my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1637 my $e = OpenILS::Utils::CStoreEditor->new;
1640 my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1643 $def = $e->retrieve_action_trigger_event_definition($event_def)
1644 or return $e->event;
1646 $auto_method .= '.include_inactive';
1650 # find the most appropriate event def depending on context org
1651 $def = $self->find_event_def_by_hook($hook, $context_org, $e)
1652 or return $e->event;
1657 if($def->group_field) {
1658 # we have a list of objects
1659 $object = [$object] unless ref $object eq 'ARRAY';
1663 for my $i (0..$#$object) {
1664 my $obj = $$object[$i];
1665 my $udata = $$user_data[$i];
1666 my $event_id = $self->simplereq(
1667 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1668 push(@event_ids, $event_id);
1671 $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1674 if (not defined $client) {
1675 $resp = $self->simplereq(
1677 'open-ils.trigger.event_group.fire',
1680 $resp = $self->patientreq(
1682 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1687 if($resp and $resp->{events} and @{$resp->{events}}) {
1690 $final_resp = $e->retrieve_action_trigger_event([
1691 $resp->{events}->[0]->id,
1692 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1699 $object = $$object[0] if ref $object eq 'ARRAY';
1704 if (not defined $client) {
1705 $event_id = $self->simplereq(
1707 $auto_method, $def->id, $object, $context_org, $user_data
1710 $resp = $self->simplereq(
1712 'open-ils.trigger.event.fire',
1716 $event_id = $self->patientreq(
1719 $auto_method, $def->id, $object, $context_org, $user_data
1722 $resp = $self->patientreq(
1725 'open-ils.trigger.event.fire',
1730 if($resp and $resp->{event}) {
1732 $final_resp = $e->retrieve_action_trigger_event([
1734 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1744 sub create_events_for_hook {
1745 my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1746 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1747 my $req = $ses->request('open-ils.trigger.event.autocreate',
1748 $hook, $obj, $org_id, $granularity, $user_data);
1749 return undef unless $wait;
1750 my $resp = $req->recv;
1751 return $resp->content if $resp;
1754 sub create_uuid_string {
1755 return create_UUID_as_string();
1758 sub create_circ_chain_summary {
1759 my($class, $e, $circ_id) = @_;
1760 my $sum = $e->json_query({from => ['action.summarize_circ_chain', $circ_id]})->[0];
1761 return undef unless $sum;
1762 my $obj = Fieldmapper::action::circ_chain_summary->new;
1763 $obj->$_($sum->{$_}) for keys %$sum;
1768 # Returns "mra" attribute key/value pairs for a set of bre's
1769 # Takes a list of bre IDs, returns a hash of hashes,
1770 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1773 my ($class, $bre_ids, $e) = @_;
1774 $e = $e || OpenILS::Utils::CStoreEditor->new;
1777 return $attrs unless defined $bre_ids;
1778 $bre_ids = [$bre_ids] unless ref $bre_ids;
1780 my $mra = $e->json_query({
1788 transform => 'each',
1789 result_field => 'key',
1793 transform => 'each',
1794 result_field => 'value',
1800 where => {id => $bre_ids}
1803 return $attrs unless $mra;
1805 $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
1807 for my $id (@$bre_ids) {
1809 for my $mra (grep { $_->{bre} eq $id } @$mra) {
1810 my $ctype = $mra->{key};
1811 my $code = $mra->{value};
1812 $attrs->{$id}->{$ctype} = {code => $code};
1814 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
1815 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
1823 # Shorter version of bib_container_items_via_search() below, only using
1824 # the queryparser record_list filter instead of the container filter.
1825 sub bib_record_list_via_search {
1826 my ($class, $search_query, $search_args) = @_;
1828 # First, Use search API to get container items sorted in any way that crad
1830 my $search_result = $class->simplereq(
1831 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1832 $search_args, $search_query
1835 unless ($search_result) {
1836 # empty result sets won't cause this, but actual errors should.
1837 $logger->warn("bib_record_list_via_search() got nothing from search");
1841 # Throw away other junk from search, keeping only bib IDs.
1842 return [ map { pop @$_ } @{$search_result->{ids}} ];
1845 # 'no_flesh' avoids fleshing the target_biblio_record_entry
1846 sub bib_container_items_via_search {
1847 my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
1849 # First, Use search API to get container items sorted in any way that crad
1851 my $search_result = $class->simplereq(
1852 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1853 $search_args, $search_query
1855 unless ($search_result) {
1856 # empty result sets won't cause this, but actual errors should.
1857 $logger->warn("bib_container_items_via_search() got nothing from search");
1861 # Throw away other junk from search, keeping only bib IDs.
1862 my $id_list = [ map { pop @$_ } @{$search_result->{ids}} ];
1864 return [] unless @$id_list;
1866 # Now get the bib container items themselves...
1867 my $e = new OpenILS::Utils::CStoreEditor;
1869 $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
1873 my @flesh_fields = qw/notes/;
1874 push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
1876 my $items = $e->search_container_biblio_record_entry_bucket_item([
1878 "target_biblio_record_entry" => $id_list,
1879 "bucket" => $container_id
1882 flesh_fields => {"cbrebi" => \@flesh_fields}
1884 ], {substream => 1});
1888 "bib_container_items_via_search() couldn't get bucket items: " .
1889 $e->die_event->{textcode}
1894 # ... and put them in the same order that the search API said they
1896 my %ordering_hash = map {
1897 ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id,
1901 return [map { $ordering_hash{$_} } @$id_list];
1904 # returns undef on success, Event on error
1905 sub log_user_activity {
1906 my ($class, $user_id, $who, $what, $e, $async) = @_;
1910 $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
1914 my $res = $e->json_query({
1916 'actor.insert_usr_activity',
1917 $user_id, $who, $what, OpenSRF::AppSession->ingress
1921 if ($res) { # call returned OK
1923 $e->commit if $commit and @$res;
1924 $e->rollback if $commit and !@$res;
1927 return $e->die_event;
1933 # I hate to put this here exactly, but this code needs to be shared between
1934 # the TPAC's mod_perl module and open-ils.serial.
1936 # There is a reason every part of the query *except* those parts dealing
1937 # with scope are moved here from the code's origin in TPAC. The serials
1938 # use case does *not* want the same scoping logic.
1940 # Also, note that for the serials uses case, we may filter in OPAC visible
1941 # status and copy/call_number deletedness, but we don't filter on any
1942 # particular values for serial.item.status or serial.item.date_received.
1943 # Since we're only using this *after* winnowing down the set of issuances
1944 # that copies should be related to, I'm not sure we need any such serial.item
1947 sub basic_opac_copy_query {
1948 ######################################################################
1949 # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
1951 ######################################################################
1952 my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
1956 acp => ['id', 'barcode', 'circ_lib', 'create_date',
1957 'age_protect', 'holdable'],
1959 {column => 'name', alias => 'copy_location'},
1960 {column => 'holdable', alias => 'location_holdable'}
1963 {column => 'name', alias => 'copy_status'},
1964 {column => 'holdable', alias => 'status_holdable'}
1967 {column => 'label', alias => 'call_number_label'},
1968 {column => 'id', alias => 'call_number'}
1970 circ => ['due_date'],
1972 {column => 'label', alias => 'call_number_prefix_label'},
1973 {column => 'id', alias => 'call_number_prefix'}
1976 {column => 'label', alias => 'call_number_suffix_label'},
1977 {column => 'id', alias => 'call_number_suffix'}
1980 {column => 'label', alias => 'part_label'},
1982 ($iss_id ? (sitem => ["issuance"]) : ())
1991 filter => {issuance => $iss_id},
1999 acnp => { fkey => 'prefix' },
2000 acns => { fkey => 'suffix' }
2004 ($rec_id ? {record => $rec_id} : ())
2007 circ => { # If the copy is circulating, retrieve the open circ
2009 filter => {checkin_time => undef}
2012 ($staff ? () : (filter => { opac_visible => 't' }))
2015 ($staff ? () : (filter => { opac_visible => 't' }))
2021 bmp => { type => 'left' }
2030 ($staff ? () : (opac_visible => 't'))
2032 ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2033 ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2037 {class => 'aou', field => 'name'},
2038 {class => 'acn', field => 'label'}
2041 limit => $copy_limit,
2042 offset => $copy_offset
2046 # Compare two dates, date1 and date2. If date2 is not defined, then
2047 # DateTime->now will be used. Assumes dates are in ISO8601 format as
2048 # supported by DateTime::Format::ISO8601. (A future enhancement might
2049 # be to support other formats.)
2051 # Returns -1 if $date1 < $date2
2052 # Returns 0 if $date1 == $date2
2053 # Returns 1 if $date1 > $date2
2059 # Check for timezone offsets and limit them to 2 digits:
2060 if ($date1 && $date1 =~ /(?:-|\+)\d\d\d\d$/) {
2061 $date1 = substr($date1, 0, length($date1) - 2);
2063 if ($date2 && $date2 =~ /(?:-|\+)\d\d\d\d$/) {
2064 $date2 = substr($date2, 0, length($date2) - 2);
2068 unless (UNIVERSAL::isa($date1, "DateTime")) {
2069 $date1 = DateTime::Format::ISO8601->parse_datetime($date1);
2074 $date2 = DateTime->now;
2076 unless (UNIVERSAL::isa($date2, "DateTime")) {
2077 $date2 = DateTime::Format::ISO8601->parse_datetime($date2);
2081 return DateTime->compare($date1, $date2);
2085 # marcdoc is an XML::LibXML document
2086 # updates the doc and returns the entityized MARC string
2087 sub strip_marc_fields {
2088 my ($class, $e, $marcdoc, $grps) = @_;
2090 my $orgs = $class->get_org_ancestors($e->requestor->ws_ou);
2093 select => {vibtf => ['field']},
2094 from => {vibtf => 'vibtg'},
2095 where => {'+vibtg' => {owner => $orgs}},
2099 # give me always-apply groups plus any selected groups
2100 if ($grps and @$grps) {
2101 $query->{where}->{'+vibtg'}->{'-or'} = [
2103 {always_apply => 't'}
2107 $query->{where}->{'+vibtg'}->{always_apply} = 't';
2110 my $fields = $e->json_query($query);
2112 for my $field (@$fields) {
2113 my $tag = $field->{field};
2114 for my $node ($marcdoc->findnodes('//*[@tag="'.$tag.'"]')) {
2115 $node->parentNode->removeChild($node);
2119 return $class->entityize($marcdoc->documentElement->toString);