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( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
147 # ---------------------------------------------------------------------------
148 # Checks to see if a user is logged in. Returns the user record on success,
149 # throws an exception on error.
150 # ---------------------------------------------------------------------------
151 sub check_user_session {
152 my( $self, $user_session ) = @_;
154 my $content = $self->simplereq(
156 'open-ils.auth.session.retrieve', $user_session);
158 return undef if (!$content) or $self->event_code($content);
162 # generic simple request returning a scalar value
164 my($self, $service, $method, @params) = @_;
165 return $self->simple_scalar_request($service, $method, @params);
169 sub simple_scalar_request {
170 my($self, $service, $method, @params) = @_;
172 my $session = OpenSRF::AppSession->create( $service );
174 my $request = $session->request( $method, @params );
180 $val = $request->gather(1);
187 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
188 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
195 my( $self, $orglist ) = @_;
197 return $orglist unless ref $orglist;
198 return $$orglist[0] if @$orglist == 1;
201 $a->ou_type <=> $b->ou_type ||
202 $a->name cmp $b->name } @$orglist;
204 for my $org (@list) {
207 next if (!defined($org->parent_ou) || $org->parent_ou eq "");
209 my ($parent) = grep { $_->id == $org->parent_ou } @list;
211 $parent->children([]) unless defined($parent->children);
212 push( @{$parent->children}, $org );
218 sub fetch_closed_date {
219 my( $self, $cd ) = @_;
222 $logger->debug("Fetching closed_date $cd from cstore");
224 my $cd_obj = $self->simplereq(
226 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
229 $logger->info("closed_date $cd not found in the db");
230 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
233 return ($cd_obj, $evt);
237 my( $self, $userid ) = @_;
240 $logger->debug("Fetching user $userid from cstore");
242 $user = $self->simplereq(
244 'open-ils.cstore.direct.actor.user.retrieve', $userid );
247 $logger->info("User $userid not found in the db");
248 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
251 return ($user, $evt);
255 my( $self, $session ) = @_;
256 my $user = $self->check_user_session($session) or
257 return (undef, OpenILS::Event->new('NO_SESSION'));
262 # verifiese the session and checks the permissions agains the
263 # session user and the user's home_ou as the org id
265 my( $self, $session, @perms ) = @_;
266 my $user; my $evt; my $e;
267 $logger->debug("Checking user session $session and perms @perms");
268 ($user, $evt) = $self->checkses($session);
269 return (undef, $evt) if $evt;
270 $evt = $self->check_perms($user->id, $user->home_ou, @perms);
271 return ($user, $evt);
276 my( $self, $staffobj, $userid, @perms ) = @_;
278 $userid = $staffobj->id unless defined $userid;
280 $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
282 if( $userid ne $staffobj->id ) {
283 ($user, $evt) = $self->fetch_user($userid);
284 return (undef, $evt) if $evt;
285 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
291 return ($user, $evt);
294 sub checkses_requestor {
295 my( $self, $authtoken, $targetid, @perms ) = @_;
296 my( $requestor, $target, $evt );
298 ($requestor, $evt) = $self->checkses($authtoken);
299 return (undef, undef, $evt) if $evt;
301 ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
302 return( $requestor, $target, $evt);
306 my( $self, $copyid ) = @_;
309 $logger->debug("Fetching copy $copyid from cstore");
311 $copy = $self->simplereq(
313 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
315 if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
317 return( $copy, $evt );
321 # retrieves a circ object by id
322 sub fetch_circulation {
323 my( $self, $circid ) = @_;
326 $logger->debug("Fetching circ $circid from cstore");
328 $circ = $self->simplereq(
330 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
333 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
336 return ( $circ, $evt );
339 sub fetch_record_by_copy {
340 my( $self, $copyid ) = @_;
343 $logger->debug("Fetching record by copy $copyid from cstore");
345 $record = $self->simplereq(
347 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
349 flesh_fields => { bre => [ 'fixed_fields' ],
351 acp => [ 'call_number' ],
357 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
359 $record = $record->call_number->record;
362 return ($record, $evt);
365 # turns a record object into an mvr (mods) object
367 my( $self, $record ) = @_;
368 return undef unless $record and $record->marc;
369 my $u = OpenILS::Utils::ModsParser->new();
370 $u->start_mods_batch( $record->marc );
371 my $mods = $u->finish_mods_batch();
372 $mods->doc_id($record->id);
373 $mods->tcn($record->tcn_value);
378 my( $self, $holdid ) = @_;
381 $logger->debug("Fetching hold $holdid from cstore");
383 $hold = $self->simplereq(
385 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
387 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
389 return ($hold, $evt);
393 sub fetch_hold_transit_by_hold {
394 my( $self, $holdid ) = @_;
395 my( $transit, $evt );
397 $logger->debug("Fetching transit by hold $holdid from cstore");
399 $transit = $self->simplereq(
401 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
403 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
405 return ($transit, $evt );
408 # fetches the captured, but not fulfilled hold attached to a given copy
409 sub fetch_open_hold_by_copy {
410 my( $self, $copyid ) = @_;
411 $logger->debug("Searching for active hold for copy $copyid");
414 $hold = $self->cstorereq(
415 'open-ils.cstore.direct.action.hold_request.search',
417 current_copy => $copyid ,
418 capture_time => { "!=" => undef },
419 fulfillment_time => undef,
420 cancel_time => undef,
423 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
424 return ($hold, $evt);
427 sub fetch_hold_transit {
428 my( $self, $transid ) = @_;
429 my( $htransit, $evt );
430 $logger->debug("Fetching hold transit with hold id $transid");
431 $htransit = $self->cstorereq(
432 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
433 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
434 return ($htransit, $evt);
437 sub fetch_copy_by_barcode {
438 my( $self, $barcode ) = @_;
441 $logger->debug("Fetching copy by barcode $barcode from cstore");
443 $copy = $self->simplereq( 'open-ils.cstore',
444 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
445 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
447 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
449 return ($copy, $evt);
452 sub fetch_open_billable_transaction {
453 my( $self, $transid ) = @_;
454 my( $transaction, $evt );
456 $logger->debug("Fetching open billable transaction $transid from cstore");
458 $transaction = $self->simplereq(
460 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve', $transid);
462 $evt = OpenILS::Event->new(
463 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
465 return ($transaction, $evt);
471 $buckets{'biblio'} = 'biblio_record_entry_bucket';
472 $buckets{'callnumber'} = 'call_number_bucket';
473 $buckets{'copy'} = 'copy_bucket';
474 $buckets{'user'} = 'user_bucket';
476 sub fetch_container {
477 my( $self, $id, $type ) = @_;
480 $logger->debug("Fetching container $id with type $type");
482 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
483 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
484 $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
485 $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
487 my $meth = $buckets{$type};
488 $bucket = $self->simplereq(
490 "open-ils.cstore.direct.container.$meth.retrieve", $id );
492 $evt = OpenILS::Event->new(
493 $e, container => $id, container_type => $type ) unless $bucket;
495 return ($bucket, $evt);
499 sub fetch_container_e {
500 my( $self, $editor, $id, $type ) = @_;
503 $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
504 $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
505 $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
506 $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
508 $evt = $editor->event unless $bucket;
509 return ($bucket, $evt);
512 sub fetch_container_item_e {
513 my( $self, $editor, $id, $type ) = @_;
516 $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
517 $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
518 $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
519 $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
521 $evt = $editor->event unless $bucket;
522 return ($bucket, $evt);
529 sub fetch_container_item {
530 my( $self, $id, $type ) = @_;
533 $logger->debug("Fetching container item $id with type $type");
535 my $meth = $buckets{$type} . "_item";
537 $bucket = $self->simplereq(
539 "open-ils.cstore.direct.container.$meth.retrieve", $id );
542 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
543 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
544 $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
545 $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
547 $evt = OpenILS::Event->new(
548 $e, itemid => $id, container_type => $type ) unless $bucket;
550 return ($bucket, $evt);
554 sub fetch_patron_standings {
556 $logger->debug("Fetching patron standings");
557 return $self->simplereq(
559 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
563 sub fetch_permission_group_tree {
565 $logger->debug("Fetching patron profiles");
566 return $self->simplereq(
568 'open-ils.actor.groups.tree.retrieve' );
571 sub fetch_permission_group_descendants {
572 my( $self, $profile ) = @_;
573 my $group_tree = $self->fetch_permission_group_tree();
577 # FIXME: okay, so it's not an org tree, but it is compatible
578 $self->walk_org_tree($group_tree, sub {
580 if ($g->id == $profile) {
585 $self->walk_org_tree($start_here, sub {
587 push(@groups,$g->id);
593 sub fetch_patron_circ_summary {
594 my( $self, $userid ) = @_;
595 $logger->debug("Fetching patron summary for $userid");
596 my $summary = $self->simplereq(
598 "open-ils.storage.action.circulation.patron_summary", $userid );
602 $summary->[1] ||= 0.0;
609 sub fetch_copy_statuses {
611 $logger->debug("Fetching copy statuses");
612 return $self->simplereq(
614 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
617 sub fetch_copy_location {
618 my( $self, $id ) = @_;
620 my $cl = $self->cstorereq(
621 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
622 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
626 sub fetch_copy_locations {
628 return $self->simplereq(
630 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
633 sub fetch_copy_location_by_name {
634 my( $self, $name, $org ) = @_;
636 my $cl = $self->cstorereq(
637 'open-ils.cstore.direct.asset.copy_location.search',
638 { name => $name, owning_lib => $org } );
639 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
643 sub fetch_callnumber {
644 my( $self, $id, $flesh, $e ) = @_;
646 $e ||= OpenILS::Utils::CStoreEditor->new;
648 my $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
649 return( undef, $evt ) unless $id;
651 $logger->debug("Fetching callnumber $id");
653 my $cn = $e->retrieve_asset_call_number([
655 { flesh => $flesh, flesh_fields => { acn => [ 'prefix', 'suffix', 'label_class' ] } },
658 return ( $cn, $e->event );
661 my %ORG_CACHE; # - these rarely change, so cache them..
663 my( $self, $id ) = @_;
664 return undef unless $id;
665 return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
666 return $ORG_CACHE{$id} if $ORG_CACHE{$id};
667 $logger->debug("Fetching org unit $id");
670 my $org = $self->simplereq(
672 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
673 $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
674 $ORG_CACHE{$id} = $org;
680 my( $self, $type, $id ) = @_;
682 $logger->debug("Fetching $type stat cat: $id");
683 $cat = $self->simplereq(
685 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
687 my $e = 'ASSET_STAT_CAT_NOT_FOUND';
688 $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
690 $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
691 return ( $cat, $evt );
694 sub fetch_stat_cat_entry {
695 my( $self, $type, $id ) = @_;
697 $logger->debug("Fetching $type stat cat entry: $id");
698 $entry = $self->simplereq(
700 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
702 my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
703 $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
705 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
706 return ( $entry, $evt );
709 sub fetch_stat_cat_entry_default {
710 my( $self, $type, $id ) = @_;
711 my( $entry_default, $evt );
712 $logger->debug("Fetching $type stat cat entry default: $id");
713 $entry_default = $self->simplereq(
715 "open-ils.cstore.direct.$type.stat_cat_entry_default.retrieve", $id );
717 my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
718 $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
720 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry_default;
721 return ( $entry_default, $evt );
724 sub fetch_stat_cat_entry_default_by_stat_cat_and_org {
725 my( $self, $type, $stat_cat, $orgId ) = @_;
727 $logger->info("### Fetching $type stat cat entry default with stat_cat $stat_cat owned by org_unit $orgId");
728 $entry_default = $self->simplereq(
730 "open-ils.cstore.direct.$type.stat_cat_entry_default.search.atomic",
731 { stat_cat => $stat_cat, owner => $orgId } );
733 $entry_default = $entry_default->[0];
734 return ($entry_default, undef) if $entry_default;
736 my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
737 $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
738 return (undef, OpenILS::Event->new($e) );
742 my( $self, $org_tree, $orgid ) = @_;
743 return undef unless $org_tree and defined $orgid;
744 return $org_tree if ( $org_tree->id eq $orgid );
745 return undef unless ref($org_tree->children);
746 for my $c (@{$org_tree->children}) {
747 my $o = $self->find_org($c, $orgid);
753 sub fetch_non_cat_type_by_name_and_org {
754 my( $self, $name, $orgId ) = @_;
755 $logger->debug("Fetching non cat type $name at org $orgId");
756 my $types = $self->simplereq(
758 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
759 { name => $name, owning_lib => $orgId } );
760 return ($types->[0], undef) if($types and @$types);
761 return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
764 sub fetch_non_cat_type {
765 my( $self, $id ) = @_;
766 $logger->debug("Fetching non cat type $id");
768 $type = $self->simplereq(
770 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
771 $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
772 return ($type, $evt);
775 sub DB_UPDATE_FAILED {
776 my( $self, $payload ) = @_;
777 return OpenILS::Event->new('DATABASE_UPDATE_FAILED',
778 payload => ($payload) ? $payload : undef );
781 sub fetch_booking_reservation {
782 my( $self, $id ) = @_;
785 $res = $self->simplereq(
787 'open-ils.cstore.direct.booking.reservation.retrieve', $id
790 # simplereq doesn't know how to flesh so ...
795 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
799 $res->target_resource_type(
802 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
806 if ($res->current_resource) {
807 $res->current_resource(
810 'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
814 if ($self->is_true( $res->target_resource_type->catalog_item )) {
815 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
819 if ($res->target_resource) {
820 $res->target_resource(
823 'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
827 if ($self->is_true( $res->target_resource_type->catalog_item )) {
828 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
833 $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
839 sub fetch_circ_duration_by_name {
840 my( $self, $name ) = @_;
842 $dur = $self->simplereq(
844 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
846 $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
850 sub fetch_recurring_fine_by_name {
851 my( $self, $name ) = @_;
853 $obj = $self->simplereq(
855 'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
857 $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
861 sub fetch_max_fine_by_name {
862 my( $self, $name ) = @_;
864 $obj = $self->simplereq(
866 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
868 $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
872 sub fetch_hard_due_date_by_name {
873 my( $self, $name ) = @_;
875 $obj = $self->simplereq(
877 'open-ils.cstore.direct.config.hard_due_date.search.atomic', { name => $name } );
879 $evt = OpenILS::Event->new('CONFIG_RULES_HARD_DUE_DATE_NOT_FOUND') unless $obj;
884 my( $self, $method, @params ) = @_;
885 return $self->simplereq(
886 'open-ils.storage', $method, @params );
889 sub storagereq_xact {
890 my($self, $method, @params) = @_;
891 my $ses = $self->start_db_session();
892 my $val = $ses->request($method, @params)->gather(1);
893 $self->rollback_db_session($ses);
898 my( $self, $method, @params ) = @_;
899 return $self->simplereq(
900 'open-ils.cstore', $method, @params );
904 my( $self, $e, $name ) = @_;
905 if( $e and ref($e) eq 'HASH' and
906 defined($e->{textcode}) and $e->{textcode} eq $name ) {
913 my( undef, $f, $l ) = caller(0);
914 my( undef, undef, undef, $s ) = caller(1);
917 $logger->debug("LOGMARK: $f:$l:$s");
921 sub fetch_open_circulation {
922 my( $self, $cid ) = @_;
925 my $e = OpenILS::Utils::CStoreEditor->new;
926 my $circ = $e->search_action_circulation({
928 stop_fines_time => undef,
929 checkin_time => undef
932 return ($circ, $e->event);
936 sub copy_status_from_name {
937 my( $self, $name ) = @_;
938 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
939 for my $status (@$copy_statuses) {
940 return $status if( $status->name =~ /$name/i );
945 sub copy_status_to_name {
946 my( $self, $sid ) = @_;
947 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
948 for my $status (@$copy_statuses) {
949 return $status->name if( $status->id == $sid );
956 my( $self, $arg ) = @_;
957 return $arg if ref $arg;
958 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
959 my ($stat) = grep { $_->id == $arg } @$copy_statuses;
963 sub fetch_open_transit_by_copy {
964 my( $self, $copyid ) = @_;
966 $transit = $self->cstorereq(
967 'open-ils.cstore.direct.action.transit_copy.search',
968 { target_copy => $copyid, dest_recv_time => undef });
969 $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
970 return ($transit, $evt);
974 my( $self, $copy ) = @_;
975 return undef unless $copy;
976 $copy->status( $copy->status->id ) if ref($copy->status);
977 $copy->location( $copy->location->id ) if ref($copy->location);
978 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
982 sub unflesh_reservation {
983 my( $self, $reservation ) = @_;
984 return undef unless $reservation;
985 $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
986 $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
987 $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
988 $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
992 # un-fleshes a copy and updates it in the DB
993 # returns a DB_UPDATE_FAILED event on error
994 # returns undef on success
996 my( $self, %params ) = @_;
998 my $copy = $params{copy} || die "update_copy(): copy required";
999 my $editor = $params{editor} || die "update_copy(): copy editor required";
1000 my $session = $params{session};
1002 $logger->debug("Updating copy in the database: " . $copy->id);
1004 $self->unflesh_copy($copy);
1005 $copy->editor( $editor );
1006 $copy->edit_date( 'now' );
1009 my $meth = 'open-ils.storage.direct.asset.copy.update';
1011 $s = $session->request( $meth, $copy )->gather(1) if $session;
1012 $s = $self->storagereq( $meth, $copy ) unless $session;
1014 $logger->debug("Update of copy ".$copy->id." returned: $s");
1016 return $self->DB_UPDATE_FAILED($copy) unless $s;
1020 sub update_reservation {
1021 my( $self, %params ) = @_;
1023 my $reservation = $params{reservation} || die "update_reservation(): reservation required";
1024 my $editor = $params{editor} || die "update_reservation(): copy editor required";
1025 my $session = $params{session};
1027 $logger->debug("Updating copy in the database: " . $reservation->id);
1029 $self->unflesh_reservation($reservation);
1032 my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1034 $s = $session->request( $meth, $reservation )->gather(1) if $session;
1035 $s = $self->cstorereq( $meth, $reservation ) unless $session;
1037 $logger->debug("Update of copy ".$reservation->id." returned: $s");
1039 return $self->DB_UPDATE_FAILED($reservation) unless $s;
1043 sub fetch_billable_xact {
1044 my( $self, $id ) = @_;
1046 $logger->debug("Fetching billable transaction %id");
1047 $xact = $self->cstorereq(
1048 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1049 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1050 return ($xact, $evt);
1053 sub fetch_billable_xact_summary {
1054 my( $self, $id ) = @_;
1056 $logger->debug("Fetching billable transaction summary %id");
1057 $xact = $self->cstorereq(
1058 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1059 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1060 return ($xact, $evt);
1063 sub fetch_fleshed_copy {
1064 my( $self, $id ) = @_;
1066 $logger->info("Fetching fleshed copy $id");
1067 $copy = $self->cstorereq(
1068 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1070 flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1073 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1074 return ($copy, $evt);
1078 # returns the org that owns the callnumber that the copy
1080 sub fetch_copy_owner {
1081 my( $self, $copyid ) = @_;
1082 my( $copy, $cn, $evt );
1083 $logger->debug("Fetching copy owner $copyid");
1084 ($copy, $evt) = $self->fetch_copy($copyid);
1085 return (undef,$evt) if $evt;
1086 ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1087 return (undef,$evt) if $evt;
1088 return ($cn->owning_lib);
1091 sub fetch_copy_note {
1092 my( $self, $id ) = @_;
1094 $logger->debug("Fetching copy note $id");
1095 $note = $self->cstorereq(
1096 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1097 $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1098 return ($note, $evt);
1101 sub fetch_call_numbers_by_title {
1102 my( $self, $titleid ) = @_;
1103 $logger->info("Fetching call numbers by title $titleid");
1104 return $self->cstorereq(
1105 'open-ils.cstore.direct.asset.call_number.search.atomic',
1106 { record => $titleid, deleted => 'f' });
1107 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1110 sub fetch_copies_by_call_number {
1111 my( $self, $cnid ) = @_;
1112 $logger->info("Fetching copies by call number $cnid");
1113 return $self->cstorereq(
1114 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1115 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1118 sub fetch_user_by_barcode {
1119 my( $self, $bc ) = @_;
1120 my $cardid = $self->cstorereq(
1121 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1122 return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1123 my $user = $self->cstorereq(
1124 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1125 return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1131 my( $self, $billid ) = @_;
1132 $logger->debug("Fetching billing $billid");
1133 my $bill = $self->cstorereq(
1134 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1135 my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1136 return($bill, $evt);
1140 my( $self, $node, $callback ) = @_;
1141 return unless $node;
1143 if( $node->children ) {
1144 $self->walk_org_tree($_, $callback) for @{$node->children};
1149 my( $self, $item ) = @_;
1150 return 1 if $item and $item !~ /^f$/i;
1156 my ($self, $client, $service, $method, @params) = @_;
1157 my ($response, $err);
1159 my $session = create OpenSRF::AppSession($service);
1160 my $request = $session->request($method, @params);
1163 my $give_up = time + 1000;
1166 while (time < $give_up) {
1167 $response = $request->recv("timeout" => $spurt);
1168 last if $request->complete;
1170 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1172 } catch Error with {
1177 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
1178 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
1181 return $response->content;
1184 # This logic now lives in storage
1185 sub __patron_money_owed {
1186 my( $self, $patronid ) = @_;
1187 my $ses = OpenSRF::AppSession->create('open-ils.storage');
1188 my $req = $ses->request(
1189 'open-ils.storage.money.billable_transaction.summary.search',
1190 { usr => $patronid, xact_finish => undef } );
1194 while( $data = $req->recv ) {
1195 $data = $data->content;
1196 $total += $data->balance_owed;
1201 sub patron_money_owed {
1202 my( $self, $userid ) = @_;
1203 my $ses = $self->start_db_session();
1204 my $val = $ses->request(
1205 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1206 $self->rollback_db_session($ses);
1210 sub patron_total_items_out {
1211 my( $self, $userid ) = @_;
1212 my $ses = $self->start_db_session();
1213 my $val = $ses->request(
1214 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1215 $self->rollback_db_session($ses);
1222 #---------------------------------------------------------------------
1223 # Returns ($summary, $event)
1224 #---------------------------------------------------------------------
1228 my $e = shift || OpenILS::Utils::CStoreEditor->new;
1229 $id = $id->id if ref($id);
1231 my $xact = $e->retrieve_money_billable_transaction_summary($id)
1232 or return (undef, $e->event);
1238 #---------------------------------------------------------------------
1239 # Given a list of money.billable_transaction objects, this creates
1240 # transaction summary objects for each
1241 #--------------------------------------------------------------------
1246 return () if (!@xacts);
1247 return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1251 sub ou_ancestor_setting_value {
1252 my($self, $org_id, $name, $e) = @_;
1253 $e = $e || OpenILS::Utils::CStoreEditor->new;
1254 my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1255 return $set->{value} if $set;
1260 # If an authentication token is provided AND this org unit setting has a
1261 # view_perm, then make sure the user referenced by the auth token has
1262 # that permission. This means that if you call this method without an
1263 # authtoken param, you can get whatever org unit setting values you want.
1266 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1267 # authtoken is checked, but the $auth arg is NOT checked. To say that another
1268 # way, be sure NOT to pass an editor argument if you want your token checked.
1269 # Otherwise the auth arg is just a flag saying "check the editor".
1271 sub ou_ancestor_setting {
1272 my( $self, $orgid, $name, $e, $auth ) = @_;
1273 $e = $e || OpenILS::Utils::CStoreEditor->new(
1274 (defined $auth) ? (authtoken => $auth) : ()
1276 my $coust = $e->retrieve_config_org_unit_setting_type([
1277 $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1280 if ($auth && $coust && $coust->view_perm) {
1281 # And you can't have permission if you don't have a valid session.
1282 return undef if not $e->checkauth;
1283 # And now that we know you MIGHT have permission, we check it.
1284 return undef if not $e->allowed($coust->view_perm->code, $orgid);
1287 my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1288 my $setting = $e->json_query($query)->[0];
1289 return undef unless $setting;
1290 return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1294 # returns the ISO8601 string representation of the requested epoch in GMT
1296 my( $self, $epoch ) = @_;
1297 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1298 $year += 1900; $mon += 1;
1300 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1301 $year, $mon, $mday, $hour, $min, $sec);
1305 sub find_highest_perm_org {
1306 my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1307 my $org = $self->find_org($org_tree, $start_org );
1311 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1313 $org = $self->find_org( $org_tree, $org->parent_ou() );
1320 # returns the org_unit ID's
1321 sub user_has_work_perm_at {
1322 my($self, $e, $perm, $options, $user_id) = @_;
1324 $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1326 my $func = 'permission.usr_has_perm_at';
1327 $func = $func.'_all' if $$options{descendants};
1329 my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1330 $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1332 return $orgs unless $$options{objects};
1334 return $e->search_actor_org_unit({id => $orgs});
1337 sub get_user_work_ou_ids {
1338 my($self, $e, $userid) = @_;
1339 my $work_orgs = $e->json_query({
1340 select => {puwoum => ['work_ou']},
1342 where => {usr => $e->requestor->id}});
1344 return [] unless @$work_orgs;
1346 push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1354 my($self, $client) = @_;
1355 return $org_types if $org_types;
1356 return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1362 my $locale = shift || '';
1363 my $cache = OpenSRF::Utils::Cache->new("global", 0);
1364 my $tree = $ORG_TREE{$locale} || $cache->get_cache("orgtree.$locale");
1365 return $tree if $tree;
1367 my $ses = OpenILS::Utils::CStoreEditor->new;
1368 $ses->session->session_locale($locale);
1369 $tree = $ses->search_actor_org_unit(
1371 {"parent_ou" => undef },
1374 flesh_fields => { aou => ['children'] },
1375 order_by => { aou => 'name'}
1380 $ORG_TREE{$locale} = $tree;
1381 $cache->put_cache("orgtree.$locale", $tree);
1385 sub get_org_descendants {
1386 my($self, $org_id, $depth) = @_;
1389 transform => 'actor.org_unit_descendants',
1391 result_field => 'id',
1393 $select->{params} = [$depth] if defined $depth;
1395 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1396 select => {aou => [$select]},
1398 where => {id => $org_id}
1401 push(@orgs, $_->{id}) for @$org_list;
1405 sub get_org_ancestors {
1406 my($self, $org_id, $use_cache) = @_;
1411 $cache = OpenSRF::Utils::Cache->new("global", 0);
1412 $orgs = $cache->get_cache("org.ancestors.$org_id");
1413 return $orgs if $orgs;
1416 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1419 transform => 'actor.org_unit_ancestors',
1421 result_field => 'id',
1426 where => {id => $org_id}
1429 $orgs = [ map { $_->{id} } @$org_list ];
1431 $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1435 sub get_org_full_path {
1436 my($self, $org_id, $depth) = @_;
1441 transform => 'actor.org_unit_full_path',
1443 result_field => 'id',
1447 where => {id => $org_id}
1450 $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1451 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1452 return [ map {$_->{id}} @$org_list ];
1455 # returns the ID of the org unit ancestor at the specified depth
1456 sub org_unit_ancestor_at_depth {
1457 my($class, $org_id, $depth) = @_;
1458 my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1459 {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1460 return ($resp) ? $resp->{id} : undef;
1463 # returns the user's configured locale as a string. Defaults to en-US if none is configured.
1464 sub get_user_locale {
1465 my($self, $user_id, $e) = @_;
1466 $e ||= OpenILS::Utils::CStoreEditor->new;
1468 # first, see if the user has an explicit locale set
1469 my $setting = $e->search_actor_user_setting(
1470 {usr => $user_id, name => 'global.locale'})->[0];
1471 return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1473 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1474 return $self->get_org_locale($user->home_ou, $e);
1477 # returns org locale setting
1478 sub get_org_locale {
1479 my($self, $org_id, $e) = @_;
1480 $e ||= OpenILS::Utils::CStoreEditor->new;
1483 if(defined $org_id) {
1484 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1485 return $locale if $locale;
1488 # system-wide default
1489 my $sclient = OpenSRF::Utils::SettingsClient->new;
1490 $locale = $sclient->config_value('default_locale');
1491 return $locale if $locale;
1493 # if nothing else, fallback to locale=cowboy
1498 # xml-escape non-ascii characters
1500 my($self, $string, $form) = @_;
1503 # If we're going to convert non-ASCII characters to XML entities,
1504 # we had better be dealing with a UTF8 string to begin with
1505 $string = decode_utf8($string);
1508 $string = NFD($string);
1510 $string = NFC($string);
1513 # Convert raw ampersands to entities
1514 $string =~ s/&(?!\S+;)/&/gso;
1516 # Convert Unicode characters to entities
1517 $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1522 # x0000-x0008 isn't legal in XML documents
1523 # XXX Perhaps this should just go into our standard entityize method
1524 sub strip_ctrl_chars {
1525 my ($self, $string) = @_;
1527 $string =~ s/([\x{0000}-\x{0008}])//sgoe;
1531 sub get_copy_price {
1532 my($self, $e, $copy, $volume) = @_;
1534 $copy->price(0) if $copy->price and $copy->price < 0;
1536 return $copy->price if $copy->price and $copy->price > 0;
1541 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1542 $owner = $copy->circ_lib;
1544 $owner = $volume->owning_lib;
1547 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1548 $owner = $copy->circ_lib;
1550 $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1554 my $default_price = $self->ou_ancestor_setting_value(
1555 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1557 return $default_price unless defined $copy->price;
1559 # price is 0. Use the default?
1560 my $charge_on_0 = $self->ou_ancestor_setting_value(
1561 $owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e) || 0;
1563 return $default_price if $charge_on_0;
1567 # given a transaction ID, this returns the context org_unit for the transaction
1569 my($self, $xact_id, $e) = @_;
1570 $e ||= OpenILS::Utils::CStoreEditor->new;
1572 my $loc = $e->json_query({
1573 "select" => {circ => ["circ_lib"]},
1575 "where" => {id => $xact_id},
1578 return $loc->[0]->{circ_lib} if @$loc;
1580 $loc = $e->json_query({
1581 "select" => {bresv => ["request_lib"]},
1583 "where" => {id => $xact_id},
1586 return $loc->[0]->{request_lib} if @$loc;
1588 $loc = $e->json_query({
1589 "select" => {mg => ["billing_location"]},
1591 "where" => {id => $xact_id},
1594 return $loc->[0]->{billing_location};
1598 sub find_event_def_by_hook {
1599 my($self, $hook, $context_org, $e) = @_;
1601 $e ||= OpenILS::Utils::CStoreEditor->new;
1603 my $orgs = $self->get_org_ancestors($context_org);
1605 # search from the context org up
1606 for my $org_id (reverse @$orgs) {
1608 my $def = $e->search_action_trigger_event_definition(
1609 {hook => $hook, owner => $org_id})->[0];
1611 return $def if $def;
1619 # If an event_def ID is not provided, use the hook and context org to find the
1620 # most appropriate event. create the event, fire it, then return the resulting
1621 # event with fleshed template_output and error_output
1622 sub fire_object_event {
1623 my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1625 my $e = OpenILS::Utils::CStoreEditor->new;
1628 my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1631 $def = $e->retrieve_action_trigger_event_definition($event_def)
1632 or return $e->event;
1634 $auto_method .= '.include_inactive';
1638 # find the most appropriate event def depending on context org
1639 $def = $self->find_event_def_by_hook($hook, $context_org, $e)
1640 or return $e->event;
1645 if($def->group_field) {
1646 # we have a list of objects
1647 $object = [$object] unless ref $object eq 'ARRAY';
1651 for my $i (0..$#$object) {
1652 my $obj = $$object[$i];
1653 my $udata = $$user_data[$i];
1654 my $event_id = $self->simplereq(
1655 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1656 push(@event_ids, $event_id);
1659 $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1662 if (not defined $client) {
1663 $resp = $self->simplereq(
1665 'open-ils.trigger.event_group.fire',
1668 $resp = $self->patientreq(
1670 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1675 if($resp and $resp->{events} and @{$resp->{events}}) {
1678 $final_resp = $e->retrieve_action_trigger_event([
1679 $resp->{events}->[0]->id,
1680 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1687 $object = $$object[0] if ref $object eq 'ARRAY';
1692 if (not defined $client) {
1693 $event_id = $self->simplereq(
1695 $auto_method, $def->id, $object, $context_org, $user_data
1698 $resp = $self->simplereq(
1700 'open-ils.trigger.event.fire',
1704 $event_id = $self->patientreq(
1707 $auto_method, $def->id, $object, $context_org, $user_data
1710 $resp = $self->patientreq(
1713 'open-ils.trigger.event.fire',
1718 if($resp and $resp->{event}) {
1720 $final_resp = $e->retrieve_action_trigger_event([
1722 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1732 sub create_events_for_hook {
1733 my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1734 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1735 my $req = $ses->request('open-ils.trigger.event.autocreate',
1736 $hook, $obj, $org_id, $granularity, $user_data);
1737 return undef unless $wait;
1738 my $resp = $req->recv;
1739 return $resp->content if $resp;
1742 sub create_uuid_string {
1743 return create_UUID_as_string();
1746 sub create_circ_chain_summary {
1747 my($class, $e, $circ_id) = @_;
1748 my $sum = $e->json_query({from => ['action.summarize_circ_chain', $circ_id]})->[0];
1749 return undef unless $sum;
1750 my $obj = Fieldmapper::action::circ_chain_summary->new;
1751 $obj->$_($sum->{$_}) for keys %$sum;
1756 # Returns "mra" attribute key/value pairs for a set of bre's
1757 # Takes a list of bre IDs, returns a hash of hashes,
1758 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1761 my ($class, $bre_ids, $e) = @_;
1762 $e = $e || OpenILS::Utils::CStoreEditor->new;
1765 return $attrs unless defined $bre_ids;
1766 $bre_ids = [$bre_ids] unless ref $bre_ids;
1768 my $mra = $e->json_query({
1776 transform => 'each',
1777 result_field => 'key',
1781 transform => 'each',
1782 result_field => 'value',
1788 where => {id => $bre_ids}
1791 return $attrs unless $mra;
1793 $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
1795 for my $id (@$bre_ids) {
1797 for my $mra (grep { $_->{bre} eq $id } @$mra) {
1798 my $ctype = $mra->{key};
1799 my $code = $mra->{value};
1800 $attrs->{$id}->{$ctype} = {code => $code};
1802 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
1803 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
1811 # Shorter version of bib_container_items_via_search() below, only using
1812 # the queryparser record_list filter instead of the container filter.
1813 sub bib_record_list_via_search {
1814 my ($class, $search_query, $search_args) = @_;
1816 # First, Use search API to get container items sorted in any way that crad
1818 my $search_result = $class->simplereq(
1819 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1820 $search_args, $search_query
1823 unless ($search_result) {
1824 # empty result sets won't cause this, but actual errors should.
1825 $logger->warn("bib_record_list_via_search() got nothing from search");
1829 # Throw away other junk from search, keeping only bib IDs.
1830 return [ map { pop @$_ } @{$search_result->{ids}} ];
1833 # 'no_flesh' avoids fleshing the target_biblio_record_entry
1834 sub bib_container_items_via_search {
1835 my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
1837 # First, Use search API to get container items sorted in any way that crad
1839 my $search_result = $class->simplereq(
1840 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1841 $search_args, $search_query
1843 unless ($search_result) {
1844 # empty result sets won't cause this, but actual errors should.
1845 $logger->warn("bib_container_items_via_search() got nothing from search");
1849 # Throw away other junk from search, keeping only bib IDs.
1850 my $id_list = [ map { pop @$_ } @{$search_result->{ids}} ];
1852 return [] unless @$id_list;
1854 # Now get the bib container items themselves...
1855 my $e = new OpenILS::Utils::CStoreEditor;
1857 $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
1861 my @flesh_fields = qw/notes/;
1862 push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
1864 my $items = $e->search_container_biblio_record_entry_bucket_item([
1866 "target_biblio_record_entry" => $id_list,
1867 "bucket" => $container_id
1870 flesh_fields => {"cbrebi" => \@flesh_fields}
1875 "bib_container_items_via_search() couldn't get bucket items: " .
1876 $e->die_event->{textcode}
1881 # ... and put them in the same order that the search API said they
1883 my %ordering_hash = map {
1884 ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id,
1888 return [map { $ordering_hash{$_} } @$id_list];
1891 # returns undef on success, Event on error
1892 sub log_user_activity {
1893 my ($class, $user_id, $who, $what, $e, $async) = @_;
1897 $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
1901 my $res = $e->json_query({
1903 'actor.insert_usr_activity',
1904 $user_id, $who, $what, OpenSRF::AppSession->ingress
1908 if ($res) { # call returned OK
1910 $e->commit if $commit and @$res;
1911 $e->rollback if $commit and !@$res;
1914 return $e->die_event;
1920 # I hate to put this here exactly, but this code needs to be shared between
1921 # the TPAC's mod_perl module and open-ils.serial.
1923 # There is a reason every part of the query *except* those parts dealing
1924 # with scope are moved here from the code's origin in TPAC. The serials
1925 # use case does *not* want the same scoping logic.
1927 # Also, note that for the serials uses case, we may filter in OPAC visible
1928 # status and copy/call_number deletedness, but we don't filter on any
1929 # particular values for serial.item.status or serial.item.date_received.
1930 # Since we're only using this *after* winnowing down the set of issuances
1931 # that copies should be related to, I'm not sure we need any such serial.item
1934 sub basic_opac_copy_query {
1935 ######################################################################
1936 # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
1938 ######################################################################
1939 my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
1943 acp => ['id', 'barcode', 'circ_lib', 'create_date',
1944 'age_protect', 'holdable'],
1946 {column => 'name', alias => 'copy_location'},
1947 {column => 'holdable', alias => 'location_holdable'}
1950 {column => 'name', alias => 'copy_status'},
1951 {column => 'holdable', alias => 'status_holdable'}
1954 {column => 'label', alias => 'call_number_label'},
1955 {column => 'id', alias => 'call_number'}
1957 circ => ['due_date'],
1959 {column => 'label', alias => 'call_number_prefix_label'},
1960 {column => 'id', alias => 'call_number_prefix'}
1963 {column => 'label', alias => 'call_number_suffix_label'},
1964 {column => 'id', alias => 'call_number_suffix'}
1967 {column => 'label', alias => 'part_label'},
1969 ($iss_id ? (sitem => ["issuance"]) : ())
1978 filter => {issuance => $iss_id},
1986 acnp => { fkey => 'prefix' },
1987 acns => { fkey => 'suffix' }
1991 ($rec_id ? {record => $rec_id} : ())
1994 circ => { # If the copy is circulating, retrieve the open circ
1996 filter => {checkin_time => undef}
1999 ($staff ? () : (filter => { opac_visible => 't' }))
2002 ($staff ? () : (filter => { opac_visible => 't' }))
2008 bmp => { type => 'left' }
2017 ($staff ? () : (opac_visible => 't'))
2019 ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2020 ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2024 {class => 'aou', field => 'name'},
2025 {class => 'acn', field => 'label'}
2028 limit => $copy_limit,
2029 offset => $copy_offset
2033 # Compare two dates, date1 and date2. If date2 is not defined, then
2034 # DateTime->now will be used. Assumes dates are in ISO8601 format as
2035 # supported by DateTime::Format::ISO8601. (A future enhancement might
2036 # be to support other formats.)
2038 # Returns -1 if $date1 < $date2
2039 # Returns 0 if $date1 == $date2
2040 # Returns 1 if $date1 > $date2
2046 # Check for timezone offsets and limit them to 2 digits:
2047 if ($date1 && $date1 =~ /(?:-|\+)\d\d\d\d$/) {
2048 $date1 = substr($date1, 0, length($date1) - 2);
2050 if ($date2 && $date2 =~ /(?:-|\+)\d\d\d\d$/) {
2051 $date2 = substr($date2, 0, length($date2) - 2);
2055 unless (UNIVERSAL::isa($date1, "DateTime")) {
2056 $date1 = DateTime::Format::ISO8601->parse_datetime($date1);
2061 $date2 = DateTime->now;
2063 unless (UNIVERSAL::isa($date2, "DateTime")) {
2064 $date2 = DateTime::Format::ISO8601->parse_datetime($date2);
2068 return DateTime->compare($date1, $date2);