1 package OpenILS::Application::AppUtils;
2 use strict; use warnings;
3 use OpenILS::Application;
4 use base qw/OpenILS::Application/;
5 use OpenSRF::Utils::Cache;
6 use OpenSRF::Utils::Logger qw/$logger/;
7 use OpenILS::Utils::ModsParser;
8 use OpenSRF::EX qw(:try);
11 use OpenILS::Utils::CStoreEditor;
12 use OpenILS::Const qw/:const/;
13 use Unicode::Normalize;
14 use OpenSRF::Utils::SettingsClient;
18 use DateTime::Format::ISO8601;
19 use List::MoreUtils qw/uniq/;
20 use Digest::MD5 qw(md5_hex);
22 # ---------------------------------------------------------------------------
23 # Pile of utilty methods used accross applications.
24 # ---------------------------------------------------------------------------
25 my $cache_client = "OpenSRF::Utils::Cache";
28 # ---------------------------------------------------------------------------
29 # on sucess, returns the created session, on failure throws ERROR exception
30 # ---------------------------------------------------------------------------
31 sub start_db_session {
34 my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
35 my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
37 my $trans_resp = $trans_req->recv();
38 if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
39 if( ! $trans_resp->content() ) {
41 ("Unable to Begin Transaction with database" );
45 $logger->debug("Setting global storage session to ".
46 "session: " . $session->session_id . " : " . $session->app );
54 my $authtoken = shift;
58 my $audit_req = $session->request( "open-ils.storage.set_audit_info", $authtoken, $user_id, $ws_id );
59 my $audit_resp = $audit_req->recv();
66 transform => 'permission.usr_has_perm',
77 # returns undef if user has all of the perms provided
78 # returns the first failed perm on failure
79 sub check_user_perms {
80 my($self, $user_id, $org_id, @perm_types ) = @_;
81 $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
83 for my $type (@perm_types) {
84 $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
85 $PERM_QUERY->{where}->{id} = $user_id;
86 return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
91 # checks the list of user perms. The first one that fails returns a new
93 my( $self, $user_id, $org_id, @perm_types ) = @_;
94 my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
95 return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
101 # ---------------------------------------------------------------------------
102 # commits and destroys the session
103 # ---------------------------------------------------------------------------
104 sub commit_db_session {
105 my( $self, $session ) = @_;
107 my $req = $session->request( "open-ils.storage.transaction.commit" );
108 my $resp = $req->recv();
111 throw OpenSRF::EX::ERROR ("Unable to commit db session");
114 if(UNIVERSAL::isa($resp,"Error")) {
115 throw $resp ($resp->stringify);
118 if(!$resp->content) {
119 throw OpenSRF::EX::ERROR ("Unable to commit db session");
123 $session->disconnect();
127 sub rollback_db_session {
128 my( $self, $session ) = @_;
130 my $req = $session->request("open-ils.storage.transaction.rollback");
131 my $resp = $req->recv();
132 if(UNIVERSAL::isa($resp,"Error")) { throw $resp; }
135 $session->disconnect();
140 # returns undef it the event is not an ILS event
141 # returns the event code otherwise
143 my( $self, $evt ) = @_;
144 return $evt->{ilsevent} if $self->is_event($evt);
148 # some events, in particular auto-generated events, don't have an
149 # ilsevent key. treat hashes with a 'textcode' key as events.
151 my ($self, $evt) = @_;
153 ref($evt) eq 'HASH' and (
154 defined $evt->{ilsevent} or
155 defined $evt->{textcode}
160 # ---------------------------------------------------------------------------
161 # Checks to see if a user is logged in. Returns the user record on success,
162 # throws an exception on error.
163 # ---------------------------------------------------------------------------
164 sub check_user_session {
165 my( $self, $user_session ) = @_;
167 my $content = $self->simplereq(
169 'open-ils.auth.session.retrieve', $user_session);
171 return undef if (!$content) or $self->event_code($content);
175 # generic simple request returning a scalar value
177 my($self, $service, $method, @params) = @_;
178 return $self->simple_scalar_request($service, $method, @params);
182 sub simple_scalar_request {
183 my($self, $service, $method, @params) = @_;
185 my $session = OpenSRF::AppSession->create( $service );
187 my $request = $session->request( $method, @params );
193 $val = $request->gather(1);
200 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
201 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
208 my( $self, $orglist ) = @_;
210 return $orglist unless ref $orglist;
211 return $$orglist[0] if @$orglist == 1;
214 $a->ou_type <=> $b->ou_type ||
215 $a->name cmp $b->name } @$orglist;
217 for my $org (@list) {
220 next if (!defined($org->parent_ou) || $org->parent_ou eq "");
222 my ($parent) = grep { $_->id == $org->parent_ou } @list;
224 $parent->children([]) unless defined($parent->children);
225 push( @{$parent->children}, $org );
231 sub fetch_closed_date {
232 my( $self, $cd ) = @_;
235 $logger->debug("Fetching closed_date $cd from cstore");
237 my $cd_obj = $self->simplereq(
239 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
242 $logger->info("closed_date $cd not found in the db");
243 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
246 return ($cd_obj, $evt);
250 my( $self, $userid ) = @_;
253 $logger->debug("Fetching user $userid from cstore");
255 $user = $self->simplereq(
257 'open-ils.cstore.direct.actor.user.retrieve', $userid );
260 $logger->info("User $userid not found in the db");
261 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
264 return ($user, $evt);
268 my( $self, $session ) = @_;
269 my $user = $self->check_user_session($session) or
270 return (undef, OpenILS::Event->new('NO_SESSION'));
275 # verifiese the session and checks the permissions agains the
276 # session user and the user's home_ou as the org id
278 my( $self, $session, @perms ) = @_;
279 my $user; my $evt; my $e;
280 $logger->debug("Checking user session $session and perms @perms");
281 ($user, $evt) = $self->checkses($session);
282 return (undef, $evt) if $evt;
283 $evt = $self->check_perms($user->id, $user->home_ou, @perms);
284 return ($user, $evt);
289 my( $self, $staffobj, $userid, @perms ) = @_;
291 $userid = $staffobj->id unless defined $userid;
293 $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
295 if( $userid ne $staffobj->id ) {
296 ($user, $evt) = $self->fetch_user($userid);
297 return (undef, $evt) if $evt;
298 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
304 return ($user, $evt);
307 sub checkses_requestor {
308 my( $self, $authtoken, $targetid, @perms ) = @_;
309 my( $requestor, $target, $evt );
311 ($requestor, $evt) = $self->checkses($authtoken);
312 return (undef, undef, $evt) if $evt;
314 ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
315 return( $requestor, $target, $evt);
319 my( $self, $copyid ) = @_;
322 $logger->debug("Fetching copy $copyid from cstore");
324 $copy = $self->simplereq(
326 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
328 if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
330 return( $copy, $evt );
334 # retrieves a circ object by id
335 sub fetch_circulation {
336 my( $self, $circid ) = @_;
339 $logger->debug("Fetching circ $circid from cstore");
341 $circ = $self->simplereq(
343 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
346 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
349 return ( $circ, $evt );
352 sub fetch_record_by_copy {
353 my( $self, $copyid ) = @_;
356 $logger->debug("Fetching record by copy $copyid from cstore");
358 $record = $self->simplereq(
360 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
362 flesh_fields => { bre => [ 'fixed_fields' ],
364 acp => [ 'call_number' ],
370 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
372 $record = $record->call_number->record;
375 return ($record, $evt);
378 # turns a record object into an mvr (mods) object
380 my( $self, $record ) = @_;
381 return undef unless $record and $record->marc;
382 my $u = OpenILS::Utils::ModsParser->new();
383 $u->start_mods_batch( $record->marc );
384 my $mods = $u->finish_mods_batch();
385 $mods->doc_id($record->id);
386 $mods->tcn($record->tcn_value);
391 my( $self, $holdid ) = @_;
394 $logger->debug("Fetching hold $holdid from cstore");
396 $hold = $self->simplereq(
398 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
400 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
402 return ($hold, $evt);
406 sub fetch_hold_transit_by_hold {
407 my( $self, $holdid ) = @_;
408 my( $transit, $evt );
410 $logger->debug("Fetching transit by hold $holdid from cstore");
412 $transit = $self->simplereq(
414 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid, cancel_time => undef } );
416 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
418 return ($transit, $evt );
421 # fetches the captured, but not fulfilled hold attached to a given copy
422 sub fetch_open_hold_by_copy {
423 my( $self, $copyid ) = @_;
424 $logger->debug("Searching for active hold for copy $copyid");
427 $hold = $self->cstorereq(
428 'open-ils.cstore.direct.action.hold_request.search',
430 current_copy => $copyid ,
431 capture_time => { "!=" => undef },
432 fulfillment_time => undef,
433 cancel_time => undef,
436 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
437 return ($hold, $evt);
440 sub fetch_hold_transit {
441 my( $self, $transid ) = @_;
442 my( $htransit, $evt );
443 $logger->debug("Fetching hold transit with hold id $transid");
444 $htransit = $self->cstorereq(
445 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
446 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
447 return ($htransit, $evt);
450 sub fetch_copy_by_barcode {
451 my( $self, $barcode ) = @_;
454 $logger->debug("Fetching copy by barcode $barcode from cstore");
456 $copy = $self->simplereq( 'open-ils.cstore',
457 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
458 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
460 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
462 return ($copy, $evt);
465 sub fetch_open_billable_transaction {
466 my( $self, $transid ) = @_;
467 my( $transaction, $evt );
469 $logger->debug("Fetching open billable transaction $transid from cstore");
471 $transaction = $self->simplereq(
473 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve', $transid);
475 $evt = OpenILS::Event->new(
476 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
478 return ($transaction, $evt);
484 $buckets{'biblio'} = 'biblio_record_entry_bucket';
485 $buckets{'callnumber'} = 'call_number_bucket';
486 $buckets{'copy'} = 'copy_bucket';
487 $buckets{'user'} = 'user_bucket';
489 sub fetch_container {
490 my( $self, $id, $type ) = @_;
493 $logger->debug("Fetching container $id with type $type");
495 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
496 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
497 $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
498 $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
500 my $meth = $buckets{$type};
501 $bucket = $self->simplereq(
503 "open-ils.cstore.direct.container.$meth.retrieve", $id );
505 $evt = OpenILS::Event->new(
506 $e, container => $id, container_type => $type ) unless $bucket;
508 return ($bucket, $evt);
512 sub fetch_container_e {
513 my( $self, $editor, $id, $type ) = @_;
516 $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
517 $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
518 $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
519 $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
521 $evt = $editor->event unless $bucket;
522 return ($bucket, $evt);
525 sub fetch_container_item_e {
526 my( $self, $editor, $id, $type ) = @_;
529 $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
530 $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
531 $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
532 $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
534 $evt = $editor->event unless $bucket;
535 return ($bucket, $evt);
542 sub fetch_container_item {
543 my( $self, $id, $type ) = @_;
546 $logger->debug("Fetching container item $id with type $type");
548 my $meth = $buckets{$type} . "_item";
550 $bucket = $self->simplereq(
552 "open-ils.cstore.direct.container.$meth.retrieve", $id );
555 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
556 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
557 $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
558 $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
560 $evt = OpenILS::Event->new(
561 $e, itemid => $id, container_type => $type ) unless $bucket;
563 return ($bucket, $evt);
567 sub fetch_patron_standings {
569 $logger->debug("Fetching patron standings");
570 return $self->simplereq(
572 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
576 sub fetch_permission_group_tree {
578 $logger->debug("Fetching patron profiles");
579 return $self->simplereq(
581 'open-ils.actor.groups.tree.retrieve' );
584 sub fetch_permission_group_descendants {
585 my( $self, $profile ) = @_;
586 my $group_tree = $self->fetch_permission_group_tree();
590 # FIXME: okay, so it's not an org tree, but it is compatible
591 $self->walk_org_tree($group_tree, sub {
593 if ($g->id == $profile) {
598 $self->walk_org_tree($start_here, sub {
600 push(@groups,$g->id);
606 sub fetch_patron_circ_summary {
607 my( $self, $userid ) = @_;
608 $logger->debug("Fetching patron summary for $userid");
609 my $summary = $self->simplereq(
611 "open-ils.storage.action.circulation.patron_summary", $userid );
615 $summary->[1] ||= 0.0;
622 sub fetch_copy_statuses {
624 $logger->debug("Fetching copy statuses");
625 return $self->simplereq(
627 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
630 sub fetch_copy_location {
631 my( $self, $id ) = @_;
633 my $cl = $self->cstorereq(
634 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
635 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
639 sub fetch_copy_locations {
641 return $self->simplereq(
643 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef }, deleted => 'f' });
646 sub fetch_copy_location_by_name {
647 my( $self, $name, $org ) = @_;
649 my $cl = $self->cstorereq(
650 'open-ils.cstore.direct.asset.copy_location.search',
651 { name => $name, owning_lib => $org, deleted => 'f' } );
652 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
656 sub fetch_callnumber {
657 my( $self, $id, $flesh, $e ) = @_;
659 $e ||= OpenILS::Utils::CStoreEditor->new;
661 my $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
662 return( undef, $evt ) unless $id;
664 $logger->debug("Fetching callnumber $id");
666 my $cn = $e->retrieve_asset_call_number([
668 { flesh => $flesh, flesh_fields => { acn => [ 'prefix', 'suffix', 'label_class' ] } },
671 return ( $cn, $e->event );
674 my %ORG_CACHE; # - these rarely change, so cache them..
676 my( $self, $id ) = @_;
677 return undef unless $id;
678 return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
679 return $ORG_CACHE{$id} if $ORG_CACHE{$id};
680 $logger->debug("Fetching org unit $id");
683 my $org = $self->simplereq(
685 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
686 $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
687 $ORG_CACHE{$id} = $org;
693 my( $self, $type, $id ) = @_;
695 $logger->debug("Fetching $type stat cat: $id");
696 $cat = $self->simplereq(
698 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
700 my $e = 'ASSET_STAT_CAT_NOT_FOUND';
701 $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
703 $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
704 return ( $cat, $evt );
707 sub fetch_stat_cat_entry {
708 my( $self, $type, $id ) = @_;
710 $logger->debug("Fetching $type stat cat entry: $id");
711 $entry = $self->simplereq(
713 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
715 my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
716 $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
718 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
719 return ( $entry, $evt );
722 sub fetch_stat_cat_entry_default {
723 my( $self, $type, $id ) = @_;
724 my( $entry_default, $evt );
725 $logger->debug("Fetching $type stat cat entry default: $id");
726 $entry_default = $self->simplereq(
728 "open-ils.cstore.direct.$type.stat_cat_entry_default.retrieve", $id );
730 my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
731 $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
733 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry_default;
734 return ( $entry_default, $evt );
737 sub fetch_stat_cat_entry_default_by_stat_cat_and_org {
738 my( $self, $type, $stat_cat, $orgId ) = @_;
740 $logger->info("### Fetching $type stat cat entry default with stat_cat $stat_cat owned by org_unit $orgId");
741 $entry_default = $self->simplereq(
743 "open-ils.cstore.direct.$type.stat_cat_entry_default.search.atomic",
744 { stat_cat => $stat_cat, owner => $orgId } );
746 $entry_default = $entry_default->[0];
747 return ($entry_default, undef) if $entry_default;
749 my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
750 $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
751 return (undef, OpenILS::Event->new($e) );
755 my( $self, $org_tree, $orgid ) = @_;
756 return undef unless $org_tree and defined $orgid;
757 return $org_tree if ( $org_tree->id eq $orgid );
758 return undef unless ref($org_tree->children);
759 for my $c (@{$org_tree->children}) {
760 my $o = $self->find_org($c, $orgid);
766 sub find_org_by_shortname {
767 my( $self, $org_tree, $shortname ) = @_;
768 return undef unless $org_tree and defined $shortname;
769 return $org_tree if ( $org_tree->shortname eq $shortname );
770 return undef unless ref($org_tree->children);
771 for my $c (@{$org_tree->children}) {
772 my $o = $self->find_org_by_shortname($c, $shortname);
778 sub fetch_non_cat_type_by_name_and_org {
779 my( $self, $name, $orgId ) = @_;
780 $logger->debug("Fetching non cat type $name at org $orgId");
781 my $types = $self->simplereq(
783 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
784 { name => $name, owning_lib => $orgId } );
785 return ($types->[0], undef) if($types and @$types);
786 return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
789 sub fetch_non_cat_type {
790 my( $self, $id ) = @_;
791 $logger->debug("Fetching non cat type $id");
793 $type = $self->simplereq(
795 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
796 $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
797 return ($type, $evt);
800 sub DB_UPDATE_FAILED {
801 my( $self, $payload ) = @_;
802 return OpenILS::Event->new('DATABASE_UPDATE_FAILED',
803 payload => ($payload) ? $payload : undef );
806 sub fetch_booking_reservation {
807 my( $self, $id ) = @_;
810 $res = $self->simplereq(
812 'open-ils.cstore.direct.booking.reservation.retrieve', $id
815 # simplereq doesn't know how to flesh so ...
820 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
824 $res->target_resource_type(
827 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
831 if ($res->current_resource) {
832 $res->current_resource(
835 'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
839 if ($self->is_true( $res->target_resource_type->catalog_item )) {
840 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
844 if ($res->target_resource) {
845 $res->target_resource(
848 'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
852 if ($self->is_true( $res->target_resource_type->catalog_item )) {
853 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
858 $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
864 sub fetch_circ_duration_by_name {
865 my( $self, $name ) = @_;
867 $dur = $self->simplereq(
869 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
871 $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
875 sub fetch_recurring_fine_by_name {
876 my( $self, $name ) = @_;
878 $obj = $self->simplereq(
880 'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
882 $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
886 sub fetch_max_fine_by_name {
887 my( $self, $name ) = @_;
889 $obj = $self->simplereq(
891 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
893 $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
897 sub fetch_hard_due_date_by_name {
898 my( $self, $name ) = @_;
900 $obj = $self->simplereq(
902 'open-ils.cstore.direct.config.hard_due_date.search.atomic', { name => $name } );
904 $evt = OpenILS::Event->new('CONFIG_RULES_HARD_DUE_DATE_NOT_FOUND') unless $obj;
909 my( $self, $method, @params ) = @_;
910 return $self->simplereq(
911 'open-ils.storage', $method, @params );
914 sub storagereq_xact {
915 my($self, $method, @params) = @_;
916 my $ses = $self->start_db_session();
917 my $val = $ses->request($method, @params)->gather(1);
918 $self->rollback_db_session($ses);
923 my( $self, $method, @params ) = @_;
924 return $self->simplereq(
925 'open-ils.cstore', $method, @params );
929 my( $self, $e, $name ) = @_;
930 if( $e and ref($e) eq 'HASH' and
931 defined($e->{textcode}) and $e->{textcode} eq $name ) {
938 my( undef, $f, $l ) = caller(0);
939 my( undef, undef, undef, $s ) = caller(1);
942 $logger->debug("LOGMARK: $f:$l:$s");
946 sub fetch_open_circulation {
947 my( $self, $cid ) = @_;
950 my $e = OpenILS::Utils::CStoreEditor->new;
951 my $circ = $e->search_action_circulation({
953 stop_fines_time => undef,
954 checkin_time => undef
957 return ($circ, $e->event);
961 sub copy_status_from_name {
962 my( $self, $name ) = @_;
963 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
964 for my $status (@$copy_statuses) {
965 return $status if( $status->name =~ /$name/i );
970 sub copy_status_to_name {
971 my( $self, $sid ) = @_;
972 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
973 for my $status (@$copy_statuses) {
974 return $status->name if( $status->id == $sid );
981 my( $self, $arg ) = @_;
982 return $arg if ref $arg;
983 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
984 my ($stat) = grep { $_->id == $arg } @$copy_statuses;
988 sub fetch_open_transit_by_copy {
989 my( $self, $copyid ) = @_;
991 $transit = $self->cstorereq(
992 'open-ils.cstore.direct.action.transit_copy.search',
993 { target_copy => $copyid, dest_recv_time => undef, cancel_time => undef });
994 $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
995 return ($transit, $evt);
999 my( $self, $copy ) = @_;
1000 return undef unless $copy;
1001 $copy->status( $copy->status->id ) if ref($copy->status);
1002 $copy->location( $copy->location->id ) if ref($copy->location);
1003 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1007 sub unflesh_reservation {
1008 my( $self, $reservation ) = @_;
1009 return undef unless $reservation;
1010 $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
1011 $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
1012 $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
1013 $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
1014 return $reservation;
1017 # un-fleshes a copy and updates it in the DB
1018 # returns a DB_UPDATE_FAILED event on error
1019 # returns undef on success
1021 my( $self, %params ) = @_;
1023 my $copy = $params{copy} || die "update_copy(): copy required";
1024 my $editor = $params{editor} || die "update_copy(): copy editor required";
1025 my $session = $params{session};
1027 $logger->debug("Updating copy in the database: " . $copy->id);
1029 $self->unflesh_copy($copy);
1030 $copy->editor( $editor );
1031 $copy->edit_date( 'now' );
1034 my $meth = 'open-ils.storage.direct.asset.copy.update';
1036 $s = $session->request( $meth, $copy )->gather(1) if $session;
1037 $s = $self->storagereq( $meth, $copy ) unless $session;
1039 $logger->debug("Update of copy ".$copy->id." returned: $s");
1041 return $self->DB_UPDATE_FAILED($copy) unless $s;
1045 sub update_reservation {
1046 my( $self, %params ) = @_;
1048 my $reservation = $params{reservation} || die "update_reservation(): reservation required";
1049 my $editor = $params{editor} || die "update_reservation(): copy editor required";
1050 my $session = $params{session};
1052 $logger->debug("Updating copy in the database: " . $reservation->id);
1054 $self->unflesh_reservation($reservation);
1057 my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1059 $s = $session->request( $meth, $reservation )->gather(1) if $session;
1060 $s = $self->cstorereq( $meth, $reservation ) unless $session;
1062 $logger->debug("Update of copy ".$reservation->id." returned: $s");
1064 return $self->DB_UPDATE_FAILED($reservation) unless $s;
1068 sub fetch_billable_xact {
1069 my( $self, $id ) = @_;
1071 $logger->debug("Fetching billable transaction %id");
1072 $xact = $self->cstorereq(
1073 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1074 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1075 return ($xact, $evt);
1078 sub fetch_billable_xact_summary {
1079 my( $self, $id ) = @_;
1081 $logger->debug("Fetching billable transaction summary %id");
1082 $xact = $self->cstorereq(
1083 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1084 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1085 return ($xact, $evt);
1088 sub fetch_fleshed_copy {
1089 my( $self, $id ) = @_;
1091 $logger->info("Fetching fleshed copy $id");
1092 $copy = $self->cstorereq(
1093 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1095 flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1098 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1099 return ($copy, $evt);
1103 # returns the org that owns the callnumber that the copy
1105 sub fetch_copy_owner {
1106 my( $self, $copyid ) = @_;
1107 my( $copy, $cn, $evt );
1108 $logger->debug("Fetching copy owner $copyid");
1109 ($copy, $evt) = $self->fetch_copy($copyid);
1110 return (undef,$evt) if $evt;
1111 ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1112 return (undef,$evt) if $evt;
1113 return ($cn->owning_lib);
1116 sub fetch_copy_note {
1117 my( $self, $id ) = @_;
1119 $logger->debug("Fetching copy note $id");
1120 $note = $self->cstorereq(
1121 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1122 $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1123 return ($note, $evt);
1126 sub fetch_call_numbers_by_title {
1127 my( $self, $titleid ) = @_;
1128 $logger->info("Fetching call numbers by title $titleid");
1129 return $self->cstorereq(
1130 'open-ils.cstore.direct.asset.call_number.search.atomic',
1131 { record => $titleid, deleted => 'f' });
1132 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1135 sub fetch_copies_by_call_number {
1136 my( $self, $cnid ) = @_;
1137 $logger->info("Fetching copies by call number $cnid");
1138 return $self->cstorereq(
1139 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1140 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1143 sub fetch_user_by_barcode {
1144 my( $self, $bc ) = @_;
1145 my $cardid = $self->cstorereq(
1146 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1147 return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1148 my $user = $self->cstorereq(
1149 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1150 return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1156 my( $self, $billid ) = @_;
1157 $logger->debug("Fetching billing $billid");
1158 my $bill = $self->cstorereq(
1159 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1160 my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1161 return($bill, $evt);
1165 my( $self, $node, $callback ) = @_;
1166 return unless $node;
1168 if( $node->children ) {
1169 $self->walk_org_tree($_, $callback) for @{$node->children};
1174 my( $self, $item ) = @_;
1175 return 1 if $item and $item !~ /^f$/i;
1181 my ($self, $client, $service, $method, @params) = @_;
1182 my ($response, $err);
1184 my $session = create OpenSRF::AppSession($service);
1185 my $request = $session->request($method, @params);
1188 my $give_up = time + 1000;
1191 while (time < $give_up) {
1192 $response = $request->recv("timeout" => $spurt);
1193 last if $request->complete;
1195 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1197 } catch Error with {
1202 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
1203 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
1206 return $response->content;
1209 # This logic now lives in storage
1210 sub __patron_money_owed {
1211 my( $self, $patronid ) = @_;
1212 my $ses = OpenSRF::AppSession->create('open-ils.storage');
1213 my $req = $ses->request(
1214 'open-ils.storage.money.billable_transaction.summary.search',
1215 { usr => $patronid, xact_finish => undef } );
1219 while( $data = $req->recv ) {
1220 $data = $data->content;
1221 $total += $data->balance_owed;
1226 sub patron_money_owed {
1227 my( $self, $userid ) = @_;
1228 my $ses = $self->start_db_session();
1229 my $val = $ses->request(
1230 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1231 $self->rollback_db_session($ses);
1235 sub patron_total_items_out {
1236 my( $self, $userid ) = @_;
1237 my $ses = $self->start_db_session();
1238 my $val = $ses->request(
1239 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1240 $self->rollback_db_session($ses);
1247 #---------------------------------------------------------------------
1248 # Returns ($summary, $event)
1249 #---------------------------------------------------------------------
1253 my $e = shift || OpenILS::Utils::CStoreEditor->new;
1254 $id = $id->id if ref($id);
1256 my $xact = $e->retrieve_money_billable_transaction_summary($id)
1257 or return (undef, $e->event);
1263 #---------------------------------------------------------------------
1264 # Given a list of money.billable_transaction objects, this creates
1265 # transaction summary objects for each
1266 #--------------------------------------------------------------------
1271 return () if (!@xacts);
1272 return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1276 sub ou_ancestor_setting_value {
1277 my($self, $org_id, $name, $e) = @_;
1278 $e = $e || OpenILS::Utils::CStoreEditor->new;
1279 my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1280 return $set->{value} if $set;
1285 # If an authentication token is provided AND this org unit setting has a
1286 # view_perm, then make sure the user referenced by the auth token has
1287 # that permission. This means that if you call this method without an
1288 # authtoken param, you can get whatever org unit setting values you want.
1291 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1292 # authtoken is checked, but the $auth arg is NOT checked. To say that another
1293 # way, be sure NOT to pass an editor argument if you want your token checked.
1294 # Otherwise the auth arg is just a flag saying "check the editor".
1296 sub ou_ancestor_setting {
1297 my( $self, $orgid, $name, $e, $auth ) = @_;
1298 $e = $e || OpenILS::Utils::CStoreEditor->new(
1299 (defined $auth) ? (authtoken => $auth) : ()
1303 my $coust = $e->retrieve_config_org_unit_setting_type([
1304 $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1306 if ($coust && $coust->view_perm) {
1307 # And you can't have permission if you don't have a valid session.
1308 return undef if not $e->checkauth;
1309 # And now that we know you MIGHT have permission, we check it.
1310 return undef if not $e->allowed($coust->view_perm->code, $orgid);
1314 my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1315 my $setting = $e->json_query($query)->[0];
1316 return undef unless $setting;
1317 return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1320 # This fetches a set of OU settings in one fell swoop,
1321 # which can be significantly faster than invoking
1322 # $U->ou_ancestor_setting() one setting at a time.
1323 # As the "_insecure" implies, however, callers are
1324 # responsible for ensuring that the settings to be
1325 # fetch do not need view permission checks.
1326 sub ou_ancestor_setting_batch_insecure {
1327 my( $self, $orgid, $names ) = @_;
1329 my %result = map { $_ => undef } @$names;
1332 'actor.org_unit_ancestor_setting_batch',
1334 '{' . join(',', @$names) . '}'
1337 my $e = OpenILS::Utils::CStoreEditor->new();
1338 my $settings = $e->json_query($query);
1339 foreach my $setting (@$settings) {
1340 $result{$setting->{name}} = {
1341 org => $setting->{org_unit},
1342 value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})
1348 # Returns a hash of hashes like so:
1350 # $lookup_org_id => {org => $context_org, value => $setting_value},
1351 # $lookup_org_id2 => {org => $context_org2, value => $setting_value2},
1352 # $lookup_org_id3 => {} # example of no setting value exists
1355 sub ou_ancestor_setting_batch_by_org_insecure {
1356 my ($self, $org_ids, $name, $e) = @_;
1358 $e ||= OpenILS::Utils::CStoreEditor->new();
1359 my %result = map { $_ => {value => undef} } @$org_ids;
1363 'actor.org_unit_ancestor_setting_batch_by_org',
1364 $name, '{' . join(',', @$org_ids) . '}'
1368 # DB func returns an array of settings matching the order of the
1369 # list of org unit IDs. If the setting does not contain a valid
1370 # ->id value, then no setting value exists for that org unit.
1371 my $settings = $e->json_query($query);
1372 for my $idx (0 .. $#$org_ids) {
1373 my $setting = $settings->[$idx];
1374 my $org_id = $org_ids->[$idx];
1376 next unless $setting->{id}; # null ID means no value is present.
1378 $result{$org_id}->{org} = $setting->{org_unit};
1379 $result{$org_id}->{value} =
1380 OpenSRF::Utils::JSON->JSON2perl($setting->{value});
1386 # returns the ISO8601 string representation of the requested epoch in GMT
1388 my( $self, $epoch ) = @_;
1389 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1390 $year += 1900; $mon += 1;
1392 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1393 $year, $mon, $mday, $hour, $min, $sec);
1397 sub find_highest_perm_org {
1398 my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1399 my $org = $self->find_org($org_tree, $start_org );
1403 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1405 $org = $self->find_org( $org_tree, $org->parent_ou() );
1412 # returns the org_unit ID's
1413 sub user_has_work_perm_at {
1414 my($self, $e, $perm, $options, $user_id) = @_;
1416 $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1418 my $func = 'permission.usr_has_perm_at';
1419 $func = $func.'_all' if $$options{descendants};
1421 my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1422 $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1424 return $orgs unless $$options{objects};
1426 return $e->search_actor_org_unit({id => $orgs});
1429 sub get_user_work_ou_ids {
1430 my($self, $e, $userid) = @_;
1431 my $work_orgs = $e->json_query({
1432 select => {puwoum => ['work_ou']},
1434 where => {usr => $e->requestor->id}});
1436 return [] unless @$work_orgs;
1438 push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1446 my($self, $client) = @_;
1447 return $org_types if $org_types;
1448 return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1454 my $locale = shift || '';
1455 my $cache = OpenSRF::Utils::Cache->new("global", 0);
1456 my $tree = $ORG_TREE{$locale} || $cache->get_cache("orgtree.$locale");
1457 $ORG_TREE{$locale} = $tree; # make sure to populate the process-local cache
1458 return $tree if $tree;
1460 my $ses = OpenILS::Utils::CStoreEditor->new;
1461 $ses->session->session_locale($locale);
1462 $tree = $ses->search_actor_org_unit(
1464 {"parent_ou" => undef },
1467 flesh_fields => { aou => ['children'] },
1468 order_by => { aou => 'name'}
1473 $ORG_TREE{$locale} = $tree;
1474 $cache->put_cache("orgtree.$locale", $tree);
1478 sub get_global_flag {
1479 my($self, $flag) = @_;
1480 return undef unless ($flag);
1481 return OpenILS::Utils::CStoreEditor->new->retrieve_config_global_flag($flag);
1484 sub get_org_descendants {
1485 my($self, $org_id, $depth) = @_;
1488 transform => 'actor.org_unit_descendants',
1490 result_field => 'id',
1492 $select->{params} = [$depth] if defined $depth;
1494 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1495 select => {aou => [$select]},
1497 where => {id => $org_id}
1500 push(@orgs, $_->{id}) for @$org_list;
1504 sub get_org_ancestors {
1505 my($self, $org_id, $use_cache) = @_;
1510 $cache = OpenSRF::Utils::Cache->new("global", 0);
1511 $orgs = $cache->get_cache("org.ancestors.$org_id");
1512 return $orgs if $orgs;
1515 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1518 transform => 'actor.org_unit_ancestors',
1520 result_field => 'id',
1525 where => {id => $org_id}
1528 $orgs = [ map { $_->{id} } @$org_list ];
1530 $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1534 sub get_org_full_path {
1535 my($self, $org_id, $depth) = @_;
1540 transform => 'actor.org_unit_full_path',
1542 result_field => 'id',
1546 where => {id => $org_id}
1549 $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1550 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1551 return [ map {$_->{id}} @$org_list ];
1554 # returns the ID of the org unit ancestor at the specified depth
1555 sub org_unit_ancestor_at_depth {
1556 my($class, $org_id, $depth) = @_;
1557 my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1558 {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1559 return ($resp) ? $resp->{id} : undef;
1562 # Returns the proximity value between two org units.
1563 sub get_org_unit_proximity {
1564 my ($class, $e, $from_org, $to_org) = @_;
1565 $e = OpenILS::Utils::CStoreEditor->new unless ($e);
1566 my $r = $e->json_query(
1568 select => {aoup => ['prox']},
1570 where => {from_org => $from_org, to_org => $to_org}
1573 if (ref($r) eq 'ARRAY' && @$r) {
1574 return $r->[0]->{prox};
1579 # returns the user's configured locale as a string. Defaults to en-US if none is configured.
1580 sub get_user_locale {
1581 my($self, $user_id, $e) = @_;
1582 $e ||= OpenILS::Utils::CStoreEditor->new;
1584 # first, see if the user has an explicit locale set
1585 my $setting = $e->search_actor_user_setting(
1586 {usr => $user_id, name => 'global.locale'})->[0];
1587 return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1589 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1590 return $self->get_org_locale($user->home_ou, $e);
1593 # returns org locale setting
1594 sub get_org_locale {
1595 my($self, $org_id, $e) = @_;
1596 $e ||= OpenILS::Utils::CStoreEditor->new;
1599 if(defined $org_id) {
1600 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1601 return $locale if $locale;
1604 # system-wide default
1605 my $sclient = OpenSRF::Utils::SettingsClient->new;
1606 $locale = $sclient->config_value('default_locale');
1607 return $locale if $locale;
1609 # if nothing else, fallback to locale=cowboy
1614 # xml-escape non-ascii characters
1616 my($self, $string, $form) = @_;
1620 $string = NFD($string);
1622 $string = NFC($string);
1625 # Convert raw ampersands to entities
1626 $string =~ s/&(?!\S+;)/&/gso;
1628 # Convert Unicode characters to entities
1629 $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1634 # x0000-x0008 isn't legal in XML documents
1635 # XXX Perhaps this should just go into our standard entityize method
1636 sub strip_ctrl_chars {
1637 my ($self, $string) = @_;
1639 $string =~ s/([\x{0000}-\x{0008}])//sgoe;
1643 sub get_copy_price {
1644 my($self, $e, $copy, $volume) = @_;
1646 $copy->price(0) if $copy->price and $copy->price < 0;
1651 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1652 $owner = $copy->circ_lib;
1654 $owner = $volume->owning_lib;
1657 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1658 $owner = $copy->circ_lib;
1660 $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1664 my $min_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MIN_ITEM_PRICE);
1665 my $max_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MAX_ITEM_PRICE);
1666 my $charge_on_0 = $self->ou_ancestor_setting_value($owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e);
1668 my $price = $copy->price;
1670 # set the default price if needed
1671 if (!defined $price or ($price == 0 and $charge_on_0)) {
1672 # set to default price
1673 $price = $self->ou_ancestor_setting_value(
1674 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1677 # adjust to min/max range if needed
1678 if (defined $max_price and $price > $max_price) {
1679 $price = $max_price;
1680 } elsif (defined $min_price and $price < $min_price
1681 and ($price != 0 or $charge_on_0 or !defined $charge_on_0)) {
1682 # default to raising the price to the minimum,
1683 # but let 0 fall through if $charge_on_0 is set and is false
1684 $price = $min_price;
1690 # given a transaction ID, this returns the context org_unit for the transaction
1692 my($self, $xact_id, $e) = @_;
1693 $e ||= OpenILS::Utils::CStoreEditor->new;
1695 my $loc = $e->json_query({
1696 "select" => {circ => ["circ_lib"]},
1698 "where" => {id => $xact_id},
1701 return $loc->[0]->{circ_lib} if @$loc;
1703 $loc = $e->json_query({
1704 "select" => {bresv => ["request_lib"]},
1706 "where" => {id => $xact_id},
1709 return $loc->[0]->{request_lib} if @$loc;
1711 $loc = $e->json_query({
1712 "select" => {mg => ["billing_location"]},
1714 "where" => {id => $xact_id},
1717 return $loc->[0]->{billing_location};
1721 sub find_event_def_by_hook {
1722 my($self, $hook, $context_org, $e) = @_;
1724 $e ||= OpenILS::Utils::CStoreEditor->new;
1726 my $orgs = $self->get_org_ancestors($context_org);
1728 # search from the context org up
1729 for my $org_id (reverse @$orgs) {
1731 my $def = $e->search_action_trigger_event_definition(
1732 {hook => $hook, owner => $org_id, active => 't'})->[0];
1734 return $def if $def;
1742 # If an event_def ID is not provided, use the hook and context org to find the
1743 # most appropriate event. create the event, fire it, then return the resulting
1744 # event with fleshed template_output and error_output
1745 sub fire_object_event {
1746 my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1748 my $e = OpenILS::Utils::CStoreEditor->new;
1751 my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1754 $def = $e->retrieve_action_trigger_event_definition($event_def)
1755 or return $e->event;
1757 $auto_method .= '.include_inactive';
1761 # find the most appropriate event def depending on context org
1762 $def = $self->find_event_def_by_hook($hook, $context_org, $e)
1763 or return $e->event;
1768 if($def->group_field) {
1769 # we have a list of objects
1770 $object = [$object] unless ref $object eq 'ARRAY';
1774 for my $i (0..$#$object) {
1775 my $obj = $$object[$i];
1776 my $udata = $$user_data[$i];
1777 my $event_id = $self->simplereq(
1778 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1779 push(@event_ids, $event_id);
1782 $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1785 if (not defined $client) {
1786 $resp = $self->simplereq(
1788 'open-ils.trigger.event_group.fire',
1791 $resp = $self->patientreq(
1793 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1798 if($resp and $resp->{events} and @{$resp->{events}}) {
1801 $final_resp = $e->retrieve_action_trigger_event([
1802 $resp->{events}->[0]->id,
1803 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1810 $object = $$object[0] if ref $object eq 'ARRAY';
1815 if (not defined $client) {
1816 $event_id = $self->simplereq(
1818 $auto_method, $def->id, $object, $context_org, $user_data
1821 $resp = $self->simplereq(
1823 'open-ils.trigger.event.fire',
1827 $event_id = $self->patientreq(
1830 $auto_method, $def->id, $object, $context_org, $user_data
1833 $resp = $self->patientreq(
1836 'open-ils.trigger.event.fire',
1841 if($resp and $resp->{event}) {
1843 $final_resp = $e->retrieve_action_trigger_event([
1845 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1855 sub create_events_for_hook {
1856 my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1857 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1858 my $req = $ses->request('open-ils.trigger.event.autocreate',
1859 $hook, $obj, $org_id, $granularity, $user_data);
1860 return undef unless $wait;
1861 my $resp = $req->recv;
1862 return $resp->content if $resp;
1865 sub create_uuid_string {
1866 return create_UUID_as_string();
1869 sub create_circ_chain_summary {
1870 my($class, $e, $circ_id) = @_;
1871 my $sum = $e->json_query({from => ['action.summarize_all_circ_chain', $circ_id]})->[0];
1872 return undef unless $sum;
1873 my $obj = Fieldmapper::action::circ_chain_summary->new;
1874 $obj->$_($sum->{$_}) for keys %$sum;
1879 # Returns "mra" attribute key/value pairs for a set of bre's
1880 # Takes a list of bre IDs, returns a hash of hashes,
1881 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1884 my ($class, $bre_ids, $e) = @_;
1885 $e = $e || OpenILS::Utils::CStoreEditor->new;
1888 return $attrs unless defined $bre_ids;
1889 $bre_ids = [$bre_ids] unless ref $bre_ids;
1891 my $mra = $e->json_query({
1899 transform => 'each',
1900 result_field => 'key',
1904 transform => 'each',
1905 result_field => 'value',
1911 where => {id => $bre_ids}
1914 return $attrs unless $mra;
1916 $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
1918 for my $id (@$bre_ids) {
1920 for my $mra (grep { $_->{bre} eq $id } @$mra) {
1921 my $ctype = $mra->{key};
1922 my $code = $mra->{value};
1923 $attrs->{$id}->{$ctype} = {code => $code};
1925 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
1926 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
1934 # Shorter version of bib_container_items_via_search() below, only using
1935 # the queryparser record_list filter instead of the container filter.
1936 sub bib_record_list_via_search {
1937 my ($class, $search_query, $search_args) = @_;
1939 # First, Use search API to get container items sorted in any way that crad
1941 my $search_result = $class->simplereq(
1942 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1943 $search_args, $search_query
1946 unless ($search_result) {
1947 # empty result sets won't cause this, but actual errors should.
1948 $logger->warn("bib_record_list_via_search() got nothing from search");
1952 # Throw away other junk from search, keeping only bib IDs.
1953 return [ map { shift @$_ } @{$search_result->{ids}} ];
1956 # 'no_flesh' avoids fleshing the target_biblio_record_entry
1957 sub bib_container_items_via_search {
1958 my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
1960 # First, Use search API to get container items sorted in any way that crad
1962 my $search_result = $class->simplereq(
1963 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1964 $search_args, $search_query
1966 unless ($search_result) {
1967 # empty result sets won't cause this, but actual errors should.
1968 $logger->warn("bib_container_items_via_search() got nothing from search");
1972 # Throw away other junk from search, keeping only bib IDs.
1973 my $id_list = [ map { shift @$_ } @{$search_result->{ids}} ];
1975 return [] unless @$id_list;
1977 # Now get the bib container items themselves...
1978 my $e = new OpenILS::Utils::CStoreEditor;
1980 $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
1984 my @flesh_fields = qw/notes/;
1985 push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
1987 my $items = $e->search_container_biblio_record_entry_bucket_item([
1989 "target_biblio_record_entry" => $id_list,
1990 "bucket" => $container_id
1993 flesh_fields => {"cbrebi" => \@flesh_fields}
1995 ], {substream => 1});
1999 "bib_container_items_via_search() couldn't get bucket items: " .
2000 $e->die_event->{textcode}
2005 # ... and put them in the same order that the search API said they
2007 my %ordering_hash = map {
2008 ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id,
2012 return [map { $ordering_hash{$_} } @$id_list];
2015 # returns undef on success, Event on error
2016 sub log_user_activity {
2017 my ($class, $user_id, $who, $what, $e, $async) = @_;
2021 $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
2025 my $res = $e->json_query({
2027 'actor.insert_usr_activity',
2028 $user_id, $who, $what, OpenSRF::AppSession->ingress
2032 if ($res) { # call returned OK
2034 $e->commit if $commit and @$res;
2035 $e->rollback if $commit and !@$res;
2038 return $e->die_event;
2044 # I hate to put this here exactly, but this code needs to be shared between
2045 # the TPAC's mod_perl module and open-ils.serial.
2047 # There is a reason every part of the query *except* those parts dealing
2048 # with scope are moved here from the code's origin in TPAC. The serials
2049 # use case does *not* want the same scoping logic.
2051 # Also, note that for the serials uses case, we may filter in OPAC visible
2052 # status and copy/call_number deletedness, but we don't filter on any
2053 # particular values for serial.item.status or serial.item.date_received.
2054 # Since we're only using this *after* winnowing down the set of issuances
2055 # that copies should be related to, I'm not sure we need any such serial.item
2058 sub basic_opac_copy_query {
2059 ######################################################################
2060 # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
2062 ######################################################################
2063 my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
2067 acp => ['id', 'barcode', 'circ_lib', 'create_date', 'active_date',
2068 'age_protect', 'holdable', 'copy_number', 'circ_modifier'],
2070 {column => 'name', alias => 'copy_location'},
2071 {column => 'holdable', alias => 'location_holdable'},
2072 {column => 'url', alias => 'location_url'}
2075 {column => 'id', alias => 'status_code'},
2076 {column => 'name', alias => 'copy_status'},
2077 {column => 'holdable', alias => 'status_holdable'}
2080 {column => 'label', alias => 'call_number_label'},
2081 {column => 'id', alias => 'call_number'},
2082 {column => 'owning_lib', alias => 'call_number_owning_lib'}
2084 circ => ['due_date',{column => 'circ_lib', alias => 'circ_circ_lib'}],
2086 {column => 'label', alias => 'call_number_prefix_label'},
2087 {column => 'id', alias => 'call_number_prefix'}
2090 {column => 'label', alias => 'call_number_suffix_label'},
2091 {column => 'id', alias => 'call_number_suffix'}
2094 {column => 'label', alias => 'part_label'},
2096 ($iss_id ? (sitem => ["issuance"]) : ())
2103 acnp => { fkey => 'prefix' },
2104 acns => { fkey => 'suffix' }
2108 ($rec_id ? {record => $rec_id} : ())
2112 {circ => { # 2 If the copy is circulating, retrieve the open circ
2114 filter => {checkin_time => undef}
2119 ($staff ? () : ( opac_visible => 't' )),
2123 ($staff ? () : (filter => { opac_visible => 't' }))
2128 bmp => { type => 'left', filter => { deleted => 'f' } }
2135 filter => {issuance => $iss_id},
2147 ($staff ? () : (opac_visible => 't'))
2149 ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2150 ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2154 {class => 'aou', field => 'name'},
2155 {class => 'acn', field => 'label_sortkey'},
2156 {class => 'bmp', field => 'label_sortkey'},
2157 {class => 'acp', field => 'copy_number'},
2158 {class => 'acp', field => 'barcode'}
2161 limit => $copy_limit,
2162 offset => $copy_offset
2166 # Compare two dates, date1 and date2. If date2 is not defined, then
2167 # DateTime->now will be used. Assumes dates are in ISO8601 format as
2168 # supported by DateTime::Format::ISO8601. (A future enhancement might
2169 # be to support other formats.)
2171 # Returns -1 if $date1 < $date2
2172 # Returns 0 if $date1 == $date2
2173 # Returns 1 if $date1 > $date2
2179 # Check for timezone offsets and limit them to 2 digits:
2180 if ($date1 && $date1 =~ /(?:-|\+)\d\d\d\d$/) {
2181 $date1 = substr($date1, 0, length($date1) - 2);
2183 if ($date2 && $date2 =~ /(?:-|\+)\d\d\d\d$/) {
2184 $date2 = substr($date2, 0, length($date2) - 2);
2188 unless (UNIVERSAL::isa($date1, "DateTime")) {
2189 $date1 = DateTime::Format::ISO8601->parse_datetime($date1);
2194 $date2 = DateTime->now;
2196 unless (UNIVERSAL::isa($date2, "DateTime")) {
2197 $date2 = DateTime::Format::ISO8601->parse_datetime($date2);
2201 return DateTime->compare($date1, $date2);
2205 # marcdoc is an XML::LibXML document
2206 # updates the doc and returns the entityized MARC string
2207 sub strip_marc_fields {
2208 my ($class, $e, $marcdoc, $grps) = @_;
2210 my $orgs = $class->get_org_ancestors($e->requestor->ws_ou);
2213 select => {vibtf => ['field']},
2214 from => {vibtf => 'vibtg'},
2215 where => {'+vibtg' => {owner => $orgs}},
2219 # give me always-apply groups plus any selected groups
2220 if ($grps and @$grps) {
2221 $query->{where}->{'+vibtg'}->{'-or'} = [
2223 {always_apply => 't'}
2227 $query->{where}->{'+vibtg'}->{always_apply} = 't';
2230 my $fields = $e->json_query($query);
2232 for my $field (@$fields) {
2233 my $tag = $field->{field};
2234 for my $node ($marcdoc->findnodes('//*[@tag="'.$tag.'"]')) {
2235 $node->parentNode->removeChild($node);
2239 return $class->entityize($marcdoc->documentElement->toString);
2242 # marcdoc is an XML::LibXML document
2243 # updates the document and returns the entityized MARC string.
2245 my ($class, $marcdoc, $username) = @_;
2247 # Look for existing 905$u subfields. If any exist, do nothing.
2248 my @nodes = $marcdoc->findnodes('//*[@tag="905"]/*[@code="u"]');
2250 # We create a new 905 and the subfield u to that.
2251 my $parentNode = $marcdoc->createElement('datafield');
2252 $parentNode->setAttribute('tag', '905');
2253 $parentNode->setAttribute('ind1', '');
2254 $parentNode->setAttribute('ind2', '');
2255 $marcdoc->documentElement->addChild($parentNode);
2256 my $node = $marcdoc->createElement('subfield');
2257 $node->setAttribute('code', 'u');
2258 $node->appendTextNode($username);
2259 $parentNode->addChild($node);
2263 return $class->entityize($marcdoc->documentElement->toString);
2266 # Given a list of PostgreSQL arrays of numbers,
2267 # unnest the numbers and return a unique set, skipping any list elements
2268 # that are just '{NULL}'.
2269 sub unique_unnested_numbers {
2272 no warnings 'numeric';
2277 map { $_ eq 'NULL' ? undef : (split /,/, $_) }
2278 map { substr($_, 1, -1) } @_
2283 # Given a list of numbers, turn them into a PG array, skipping undef's
2284 sub intarray2pgarray {
2286 no warnings 'numeric';
2288 return '{' . join( ',', map(int, grep { defined && /^\d+$/ } @_) ) . '}';
2291 # Check if a transaction should be left open or closed. Close the
2292 # transaction if it should be closed or open it otherwise. Returns
2293 # undef on success or a failure event.
2294 sub check_open_xact {
2295 my( $self, $editor, $xactid, $xact ) = @_;
2297 # Grab the transaction
2298 $xact ||= $editor->retrieve_money_billable_transaction($xactid);
2299 return $editor->event unless $xact;
2300 $xactid ||= $xact->id;
2302 # grab the summary and see how much is owed on this transaction
2303 my ($summary) = $self->fetch_mbts($xactid, $editor);
2305 # grab the circulation if it is a circ;
2306 my $circ = $editor->retrieve_action_circulation($xactid);
2308 # If nothing is owed on the transaction but it is still open
2309 # and this transaction is not an open circulation, close it
2311 ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
2312 ( !$circ or $circ->stop_fines )) {
2314 $logger->info("closing transaction ".$xact->id. ' because balance_owed == 0');
2315 $xact->xact_finish('now');
2316 $editor->update_money_billable_transaction($xact)
2317 or return $editor->event;
2321 # If money is owed or a refund is due on the xact and xact_finish
2322 # is set, clear it (to reopen the xact) and update
2323 if( $summary->balance_owed != 0 and $xact->xact_finish ) {
2324 $logger->info("re-opening transaction ".$xact->id. ' because balance_owed != 0');
2325 $xact->clear_xact_finish;
2326 $editor->update_money_billable_transaction($xact)
2327 or return $editor->event;
2333 # Because floating point math has rounding issues, and Dyrcona gets
2334 # tired of typing out the code to multiply floating point numbers
2335 # before adding and subtracting them and then dividing the result by
2336 # 100 each time, he wrote this little subroutine for subtracting
2337 # floating point values. It can serve as a model for the other
2338 # operations if you like.
2340 # It takes a list of floating point values as arguments. The rest are
2341 # all subtracted from the first and the result is returned. The
2342 # values are all multiplied by 100 before being used, and the result
2343 # is divided by 100 in order to avoid decimal rounding errors inherent
2344 # in floating point math.
2346 # XXX shifting using multiplication/division *may* still introduce
2347 # rounding errors -- better to implement using string manipulation?
2349 my ($class, @args) = @_;
2350 my $result = shift(@args) * 100;
2351 while (my $arg = shift(@args)) {
2352 $result -= $arg * 100;
2354 return $result / 100;
2358 my ($class, @args) = @_;
2359 my $result = shift(@args) * 100;
2360 while (my $arg = shift(@args)) {
2361 $result += $arg * 100;
2363 return $result / 100;
2366 # Non-migrated passwords can be verified directly in the DB
2367 # with any extra hashing.
2368 sub verify_user_password {
2369 my ($class, $e, $user_id, $passwd, $pw_type) = @_;
2371 $pw_type ||= 'main'; # primary login password
2373 my $verify = $e->json_query({
2375 'actor.verify_passwd',
2376 $user_id, $pw_type, $passwd
2380 return $class->is_true($verify->{'actor.verify_passwd'});
2383 # Passwords migrated from the original MD5 scheme are passed through 2
2384 # extra layers of MD5 hashing for backwards compatibility with the
2385 # MD5 passwords of yore and the MD5-based chap-style authentication.
2386 # Passwords are stored in the DB like this:
2387 # CRYPT( MD5( pw_salt || MD5(real_password) ), pw_salt )
2389 # If 'as_md5' is true, the password provided has already been
2391 sub verify_migrated_user_password {
2392 my ($class, $e, $user_id, $passwd, $as_md5) = @_;
2394 # 'main' is the primary login password. This is the only password
2395 # type that requires the additional MD5 hashing.
2396 my $pw_type = 'main';
2398 # Sometimes we have the bare password, sometimes the MD5 version.
2399 my $md5_pass = $as_md5 ? $passwd : md5_hex($passwd);
2401 my $salt = $e->json_query({
2409 $salt = $salt->{'actor.get_salt'};
2411 return $class->verify_user_password(
2412 $e, $user_id, md5_hex($salt . $md5_pass), $pw_type);