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;
16 # ---------------------------------------------------------------------------
17 # Pile of utilty methods used accross applications.
18 # ---------------------------------------------------------------------------
19 my $cache_client = "OpenSRF::Utils::Cache";
22 # ---------------------------------------------------------------------------
23 # on sucess, returns the created session, on failure throws ERROR exception
24 # ---------------------------------------------------------------------------
25 sub start_db_session {
28 my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
29 my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
31 my $trans_resp = $trans_req->recv();
32 if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
33 if( ! $trans_resp->content() ) {
35 ("Unable to Begin Transaction with database" );
39 $logger->debug("Setting global storage session to ".
40 "session: " . $session->session_id . " : " . $session->app );
48 transform => 'permission.usr_has_perm',
59 # returns undef if user has all of the perms provided
60 # returns the first failed perm on failure
61 sub check_user_perms {
62 my($self, $user_id, $org_id, @perm_types ) = @_;
63 $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
65 for my $type (@perm_types) {
66 $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
67 $PERM_QUERY->{where}->{id} = $user_id;
68 return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
73 # checks the list of user perms. The first one that fails returns a new
75 my( $self, $user_id, $org_id, @perm_types ) = @_;
76 my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
77 return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
83 # ---------------------------------------------------------------------------
84 # commits and destroys the session
85 # ---------------------------------------------------------------------------
86 sub commit_db_session {
87 my( $self, $session ) = @_;
89 my $req = $session->request( "open-ils.storage.transaction.commit" );
90 my $resp = $req->recv();
93 throw OpenSRF::EX::ERROR ("Unable to commit db session");
96 if(UNIVERSAL::isa($resp,"Error")) {
97 throw $resp ($resp->stringify);
100 if(!$resp->content) {
101 throw OpenSRF::EX::ERROR ("Unable to commit db session");
105 $session->disconnect();
109 sub rollback_db_session {
110 my( $self, $session ) = @_;
112 my $req = $session->request("open-ils.storage.transaction.rollback");
113 my $resp = $req->recv();
114 if(UNIVERSAL::isa($resp,"Error")) { throw $resp; }
117 $session->disconnect();
122 # returns undef it the event is not an ILS event
123 # returns the event code otherwise
125 my( $self, $evt ) = @_;
126 return $evt->{ilsevent} if( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
130 # ---------------------------------------------------------------------------
131 # Checks to see if a user is logged in. Returns the user record on success,
132 # throws an exception on error.
133 # ---------------------------------------------------------------------------
134 sub check_user_session {
136 my( $self, $user_session ) = @_;
138 my $content = $self->simplereq(
140 'open-ils.auth.session.retrieve', $user_session );
142 if(! $content or $self->event_code($content)) {
143 throw OpenSRF::EX::ERROR
144 ("Session [$user_session] cannot be authenticated" );
147 $logger->debug("Fetch user session $user_session found user " . $content->id );
152 # generic simple request returning a scalar value
154 my($self, $service, $method, @params) = @_;
155 return $self->simple_scalar_request($service, $method, @params);
159 sub simple_scalar_request {
160 my($self, $service, $method, @params) = @_;
162 my $session = OpenSRF::AppSession->create( $service );
164 my $request = $session->request( $method, @params );
170 $val = $request->gather(1);
177 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
178 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
190 my $org_typelist = undef;
191 my $org_typelist_hash = {};
195 # can we throw this version away??
198 if($tree) { return $tree; }
200 # see if it's in the cache
201 $tree = $cache_client->new()->get_cache('_orgtree');
202 if($tree) { return $tree; }
205 warn "Retrieving Org Tree\n";
206 $orglist = $self->simple_scalar_request(
208 "open-ils.cstore.direct.actor.org_unit.search.atomic",
209 { id => { '!=' => undef } }
213 if( ! $org_typelist ) {
214 warn "Retrieving org types\n";
215 $org_typelist = $self->simple_scalar_request(
217 "open-ils.cstore.direct.actor.org_unit_type.search.atomic",
218 { id => { '!=' => undef } }
220 $self->build_org_type($org_typelist);
223 $tree = $self->build_org_tree($orglist,1);
224 $cache_client->new()->put_cache('_orgtree', $tree);
229 my $slimtree = undef;
230 sub get_slim_org_tree {
233 if($slimtree) { return $slimtree; }
235 # see if it's in the cache
236 $slimtree = $cache_client->new()->get_cache('slimorgtree');
237 if($slimtree) { return $slimtree; }
240 warn "Retrieving Org Tree\n";
241 $orglist = $self->simple_scalar_request(
243 "open-ils.cstore.direct.actor.org_unit.search.atomic",
244 { id => { '!=' => undef } }
248 $slimtree = $self->build_org_tree($orglist);
249 $cache_client->new->put_cache('slimorgtree', $slimtree);
256 my($self, $org_typelist) = @_;
257 for my $type (@$org_typelist) {
258 $org_typelist_hash->{$type->id()} = $type;
266 my( $self, $orglist, $add_types ) = @_;
268 return $orglist unless ref $orglist;
269 return $$orglist[0] if @$orglist == 1;
272 $a->ou_type <=> $b->ou_type ||
273 $a->name cmp $b->name } @$orglist;
275 for my $org (@list) {
279 if(!ref($org->ou_type()) and $add_types) {
280 $org->ou_type( $org_typelist_hash->{$org->ou_type()});
283 next unless (defined($org->parent_ou));
285 my ($parent) = grep { $_->id == $org->parent_ou } @list;
287 $parent->children([]) unless defined($parent->children);
288 push( @{$parent->children}, $org );
294 sub fetch_closed_date {
295 my( $self, $cd ) = @_;
298 $logger->debug("Fetching closed_date $cd from cstore");
300 my $cd_obj = $self->simplereq(
302 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
305 $logger->info("closed_date $cd not found in the db");
306 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
309 return ($cd_obj, $evt);
313 my( $self, $userid ) = @_;
316 $logger->debug("Fetching user $userid from cstore");
318 $user = $self->simplereq(
320 'open-ils.cstore.direct.actor.user.retrieve', $userid );
323 $logger->info("User $userid not found in the db");
324 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
327 return ($user, $evt);
331 my( $self, $session ) = @_;
332 my $user; my $evt; my $e;
334 $logger->debug("Checking user session $session");
337 $user = $self->check_user_session($session);
338 } catch Error with { $e = 1; };
340 $logger->debug("Done checking user session $session " . (($e) ? "error = $e" : "") );
342 if( $e or !$user ) { $evt = OpenILS::Event->new('NO_SESSION'); }
343 return ( $user, $evt );
347 # verifiese the session and checks the permissions agains the
348 # session user and the user's home_ou as the org id
350 my( $self, $session, @perms ) = @_;
351 my $user; my $evt; my $e;
352 $logger->debug("Checking user session $session and perms @perms");
353 ($user, $evt) = $self->checkses($session);
354 return (undef, $evt) if $evt;
355 $evt = $self->check_perms($user->id, $user->home_ou, @perms);
356 return ($user, $evt);
361 my( $self, $staffobj, $userid, @perms ) = @_;
363 $userid = $staffobj->id unless defined $userid;
365 $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
367 if( $userid ne $staffobj->id ) {
368 ($user, $evt) = $self->fetch_user($userid);
369 return (undef, $evt) if $evt;
370 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
376 return ($user, $evt);
379 sub checkses_requestor {
380 my( $self, $authtoken, $targetid, @perms ) = @_;
381 my( $requestor, $target, $evt );
383 ($requestor, $evt) = $self->checkses($authtoken);
384 return (undef, undef, $evt) if $evt;
386 ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
387 return( $requestor, $target, $evt);
391 my( $self, $copyid ) = @_;
394 $logger->debug("Fetching copy $copyid from cstore");
396 $copy = $self->simplereq(
398 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
400 if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
402 return( $copy, $evt );
406 # retrieves a circ object by id
407 sub fetch_circulation {
408 my( $self, $circid ) = @_;
411 $logger->debug("Fetching circ $circid from cstore");
413 $circ = $self->simplereq(
415 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
418 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
421 return ( $circ, $evt );
424 sub fetch_record_by_copy {
425 my( $self, $copyid ) = @_;
428 $logger->debug("Fetching record by copy $copyid from cstore");
430 $record = $self->simplereq(
432 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
434 flesh_fields => { bre => [ 'fixed_fields' ],
436 acp => [ 'call_number' ],
442 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
444 $record = $record->call_number->record;
447 return ($record, $evt);
450 # turns a record object into an mvr (mods) object
452 my( $self, $record ) = @_;
453 return undef unless $record and $record->marc;
454 my $u = OpenILS::Utils::ModsParser->new();
455 $u->start_mods_batch( $record->marc );
456 my $mods = $u->finish_mods_batch();
457 $mods->doc_id($record->id);
458 $mods->tcn($record->tcn_value);
463 my( $self, $holdid ) = @_;
466 $logger->debug("Fetching hold $holdid from cstore");
468 $hold = $self->simplereq(
470 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
472 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
474 return ($hold, $evt);
478 sub fetch_hold_transit_by_hold {
479 my( $self, $holdid ) = @_;
480 my( $transit, $evt );
482 $logger->debug("Fetching transit by hold $holdid from cstore");
484 $transit = $self->simplereq(
486 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
488 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
490 return ($transit, $evt );
493 # fetches the captured, but not fulfilled hold attached to a given copy
494 sub fetch_open_hold_by_copy {
495 my( $self, $copyid ) = @_;
496 $logger->debug("Searching for active hold for copy $copyid");
499 $hold = $self->cstorereq(
500 'open-ils.cstore.direct.action.hold_request.search',
502 current_copy => $copyid ,
503 capture_time => { "!=" => undef },
504 fulfillment_time => undef,
505 cancel_time => undef,
508 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
509 return ($hold, $evt);
512 sub fetch_hold_transit {
513 my( $self, $transid ) = @_;
514 my( $htransit, $evt );
515 $logger->debug("Fetching hold transit with hold id $transid");
516 $htransit = $self->cstorereq(
517 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
518 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
519 return ($htransit, $evt);
522 sub fetch_copy_by_barcode {
523 my( $self, $barcode ) = @_;
526 $logger->debug("Fetching copy by barcode $barcode from cstore");
528 $copy = $self->simplereq( 'open-ils.cstore',
529 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
530 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
532 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
534 return ($copy, $evt);
537 sub fetch_open_billable_transaction {
538 my( $self, $transid ) = @_;
539 my( $transaction, $evt );
541 $logger->debug("Fetching open billable transaction $transid from cstore");
543 $transaction = $self->simplereq(
545 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve', $transid);
547 $evt = OpenILS::Event->new(
548 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
550 return ($transaction, $evt);
556 $buckets{'biblio'} = 'biblio_record_entry_bucket';
557 $buckets{'callnumber'} = 'call_number_bucket';
558 $buckets{'copy'} = 'copy_bucket';
559 $buckets{'user'} = 'user_bucket';
561 sub fetch_container {
562 my( $self, $id, $type ) = @_;
565 $logger->debug("Fetching container $id with type $type");
567 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
568 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
569 $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
570 $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
572 my $meth = $buckets{$type};
573 $bucket = $self->simplereq(
575 "open-ils.cstore.direct.container.$meth.retrieve", $id );
577 $evt = OpenILS::Event->new(
578 $e, container => $id, container_type => $type ) unless $bucket;
580 return ($bucket, $evt);
584 sub fetch_container_e {
585 my( $self, $editor, $id, $type ) = @_;
588 $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
589 $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
590 $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
591 $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
593 $evt = $editor->event unless $bucket;
594 return ($bucket, $evt);
597 sub fetch_container_item_e {
598 my( $self, $editor, $id, $type ) = @_;
601 $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
602 $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
603 $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
604 $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
606 $evt = $editor->event unless $bucket;
607 return ($bucket, $evt);
614 sub fetch_container_item {
615 my( $self, $id, $type ) = @_;
618 $logger->debug("Fetching container item $id with type $type");
620 my $meth = $buckets{$type} . "_item";
622 $bucket = $self->simplereq(
624 "open-ils.cstore.direct.container.$meth.retrieve", $id );
627 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
628 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
629 $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
630 $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
632 $evt = OpenILS::Event->new(
633 $e, itemid => $id, container_type => $type ) unless $bucket;
635 return ($bucket, $evt);
639 sub fetch_patron_standings {
641 $logger->debug("Fetching patron standings");
642 return $self->simplereq(
644 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
648 sub fetch_permission_group_tree {
650 $logger->debug("Fetching patron profiles");
651 return $self->simplereq(
653 'open-ils.actor.groups.tree.retrieve' );
657 sub fetch_patron_circ_summary {
658 my( $self, $userid ) = @_;
659 $logger->debug("Fetching patron summary for $userid");
660 my $summary = $self->simplereq(
662 "open-ils.storage.action.circulation.patron_summary", $userid );
666 $summary->[1] ||= 0.0;
673 sub fetch_copy_statuses {
675 $logger->debug("Fetching copy statuses");
676 return $self->simplereq(
678 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
681 sub fetch_copy_location {
682 my( $self, $id ) = @_;
684 my $cl = $self->cstorereq(
685 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
686 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
690 sub fetch_copy_locations {
692 return $self->simplereq(
694 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
697 sub fetch_copy_location_by_name {
698 my( $self, $name, $org ) = @_;
700 my $cl = $self->cstorereq(
701 'open-ils.cstore.direct.asset.copy_location.search',
702 { name => $name, owning_lib => $org } );
703 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
707 sub fetch_callnumber {
708 my( $self, $id ) = @_;
711 my $e = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
712 return( undef, $e ) unless $id;
714 $logger->debug("Fetching callnumber $id");
716 my $cn = $self->simplereq(
718 'open-ils.cstore.direct.asset.call_number.retrieve', $id );
719 $evt = $e unless $cn;
721 return ( $cn, $evt );
724 my %ORG_CACHE; # - these rarely change, so cache them..
726 my( $self, $id ) = @_;
727 return undef unless $id;
728 return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
729 return $ORG_CACHE{$id} if $ORG_CACHE{$id};
730 $logger->debug("Fetching org unit $id");
733 my $org = $self->simplereq(
735 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
736 $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
737 $ORG_CACHE{$id} = $org;
743 my( $self, $type, $id ) = @_;
745 $logger->debug("Fetching $type stat cat: $id");
746 $cat = $self->simplereq(
748 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
750 my $e = 'ASSET_STAT_CAT_NOT_FOUND';
751 $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
753 $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
754 return ( $cat, $evt );
757 sub fetch_stat_cat_entry {
758 my( $self, $type, $id ) = @_;
760 $logger->debug("Fetching $type stat cat entry: $id");
761 $entry = $self->simplereq(
763 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
765 my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
766 $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
768 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
769 return ( $entry, $evt );
774 my( $self, $org_tree, $orgid ) = @_;
776 $logger->warn("find_org() did not receive a value for \$org_tree");
779 $logger->warn("find_org() did not receive a value for \$orgid");
782 return $org_tree if ( $org_tree->id eq $orgid );
783 return undef unless ref($org_tree->children);
784 for my $c (@{$org_tree->children}) {
785 my $o = $self->find_org($c, $orgid);
791 sub fetch_non_cat_type_by_name_and_org {
792 my( $self, $name, $orgId ) = @_;
793 $logger->debug("Fetching non cat type $name at org $orgId");
794 my $types = $self->simplereq(
796 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
797 { name => $name, owning_lib => $orgId } );
798 return ($types->[0], undef) if($types and @$types);
799 return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
802 sub fetch_non_cat_type {
803 my( $self, $id ) = @_;
804 $logger->debug("Fetching non cat type $id");
806 $type = $self->simplereq(
808 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
809 $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
810 return ($type, $evt);
813 sub DB_UPDATE_FAILED {
814 my( $self, $payload ) = @_;
815 return OpenILS::Event->new('DATABASE_UPDATE_FAILED',
816 payload => ($payload) ? $payload : undef );
819 sub fetch_circ_duration_by_name {
820 my( $self, $name ) = @_;
822 $dur = $self->simplereq(
824 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
826 $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
830 sub fetch_recurring_fine_by_name {
831 my( $self, $name ) = @_;
833 $obj = $self->simplereq(
835 'open-ils.cstore.direct.config.rules.recuring_fine.search.atomic', { name => $name } );
837 $evt = OpenILS::Event->new('CONFIG_RULES_RECURING_FINE_NOT_FOUND') unless $obj;
841 sub fetch_max_fine_by_name {
842 my( $self, $name ) = @_;
844 $obj = $self->simplereq(
846 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
848 $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
853 my( $self, $method, @params ) = @_;
854 return $self->simplereq(
855 'open-ils.storage', $method, @params );
859 my( $self, $method, @params ) = @_;
860 return $self->simplereq(
861 'open-ils.cstore', $method, @params );
865 my( $self, $e, $name ) = @_;
866 if( $e and ref($e) eq 'HASH' and
867 defined($e->{textcode}) and $e->{textcode} eq $name ) {
874 my( undef, $f, $l ) = caller(0);
875 my( undef, undef, undef, $s ) = caller(1);
878 $logger->debug("LOGMARK: $f:$l:$s");
882 sub fetch_open_circulation {
883 my( $self, $cid ) = @_;
886 my $circ = $self->cstorereq(
887 'open-ils.cstore.direct.action.open_circulation.search',
888 { target_copy => $cid, stop_fines_time => undef } );
889 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;
890 return ($circ, $evt);
893 sub fetch_all_open_circulation {
894 my( $self, $cid ) = @_;
897 my $circ = $self->cstorereq(
898 'open-ils.cstore.direct.action.open_circulation.search',
899 { target_copy => $cid, xact_finish => undef } );
900 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;
901 return ($circ, $evt);
905 sub copy_status_from_name {
906 my( $self, $name ) = @_;
907 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
908 for my $status (@$copy_statuses) {
909 return $status if( $status->name =~ /$name/i );
914 sub copy_status_to_name {
915 my( $self, $sid ) = @_;
916 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
917 for my $status (@$copy_statuses) {
918 return $status->name if( $status->id == $sid );
925 my( $self, $arg ) = @_;
926 return $arg if ref $arg;
927 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
928 my ($stat) = grep { $_->id == $arg } @$copy_statuses;
932 sub fetch_open_transit_by_copy {
933 my( $self, $copyid ) = @_;
935 $transit = $self->cstorereq(
936 'open-ils.cstore.direct.action.transit_copy.search',
937 { target_copy => $copyid, dest_recv_time => undef });
938 $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
939 return ($transit, $evt);
943 my( $self, $copy ) = @_;
944 return undef unless $copy;
945 $copy->status( $copy->status->id ) if ref($copy->status);
946 $copy->location( $copy->location->id ) if ref($copy->location);
947 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
951 # un-fleshes a copy and updates it in the DB
952 # returns a DB_UPDATE_FAILED event on error
953 # returns undef on success
955 my( $self, %params ) = @_;
957 my $copy = $params{copy} || die "update_copy(): copy required";
958 my $editor = $params{editor} || die "update_copy(): copy editor required";
959 my $session = $params{session};
961 $logger->debug("Updating copy in the database: " . $copy->id);
963 $self->unflesh_copy($copy);
964 $copy->editor( $editor );
965 $copy->edit_date( 'now' );
968 my $meth = 'open-ils.storage.direct.asset.copy.update';
970 $s = $session->request( $meth, $copy )->gather(1) if $session;
971 $s = $self->storagereq( $meth, $copy ) unless $session;
973 $logger->debug("Update of copy ".$copy->id." returned: $s");
975 return $self->DB_UPDATE_FAILED($copy) unless $s;
979 sub fetch_billable_xact {
980 my( $self, $id ) = @_;
982 $logger->debug("Fetching billable transaction %id");
983 $xact = $self->cstorereq(
984 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
985 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
986 return ($xact, $evt);
989 sub fetch_billable_xact_summary {
990 my( $self, $id ) = @_;
992 $logger->debug("Fetching billable transaction summary %id");
993 $xact = $self->cstorereq(
994 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
995 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
996 return ($xact, $evt);
999 sub fetch_fleshed_copy {
1000 my( $self, $id ) = @_;
1002 $logger->info("Fetching fleshed copy $id");
1003 $copy = $self->cstorereq(
1004 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1006 flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1009 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1010 return ($copy, $evt);
1014 # returns the org that owns the callnumber that the copy
1016 sub fetch_copy_owner {
1017 my( $self, $copyid ) = @_;
1018 my( $copy, $cn, $evt );
1019 $logger->debug("Fetching copy owner $copyid");
1020 ($copy, $evt) = $self->fetch_copy($copyid);
1021 return (undef,$evt) if $evt;
1022 ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1023 return (undef,$evt) if $evt;
1024 return ($cn->owning_lib);
1027 sub fetch_copy_note {
1028 my( $self, $id ) = @_;
1030 $logger->debug("Fetching copy note $id");
1031 $note = $self->cstorereq(
1032 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1033 $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1034 return ($note, $evt);
1037 sub fetch_call_numbers_by_title {
1038 my( $self, $titleid ) = @_;
1039 $logger->info("Fetching call numbers by title $titleid");
1040 return $self->cstorereq(
1041 'open-ils.cstore.direct.asset.call_number.search.atomic',
1042 { record => $titleid, deleted => 'f' });
1043 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1046 sub fetch_copies_by_call_number {
1047 my( $self, $cnid ) = @_;
1048 $logger->info("Fetching copies by call number $cnid");
1049 return $self->cstorereq(
1050 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1051 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1054 sub fetch_user_by_barcode {
1055 my( $self, $bc ) = @_;
1056 my $cardid = $self->cstorereq(
1057 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1058 return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1059 my $user = $self->cstorereq(
1060 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1061 return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1067 # ---------------------------------------------------------------------
1068 # Updates and returns the patron penalties
1069 # ---------------------------------------------------------------------
1070 sub update_patron_penalties {
1071 my( $self, %args ) = @_;
1072 return $self->simplereq(
1074 'open-ils.penalty.patron_penalty.calculate',
1075 { update => 1, %args }
1080 my( $self, $billid ) = @_;
1081 $logger->debug("Fetching billing $billid");
1082 my $bill = $self->cstorereq(
1083 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1084 my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1085 return($bill, $evt);
1091 sub fetch_org_tree {
1093 return $ORG_TREE if $ORG_TREE;
1094 return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit(
1096 {"parent_ou" => undef },
1099 flesh_fields => { aou => ['children'] },
1100 order_by => { aou => 'name'}
1107 my( $self, $node, $callback ) = @_;
1108 return unless $node;
1110 if( $node->children ) {
1111 $self->walk_org_tree($_, $callback) for @{$node->children};
1116 my( $self, $item ) = @_;
1117 return 1 if $item and $item !~ /^f$/i;
1122 # This logic now lives in storage
1123 sub __patron_money_owed {
1124 my( $self, $patronid ) = @_;
1125 my $ses = OpenSRF::AppSession->create('open-ils.storage');
1126 my $req = $ses->request(
1127 'open-ils.storage.money.billable_transaction.summary.search',
1128 { usr => $patronid, xact_finish => undef } );
1132 while( $data = $req->recv ) {
1133 $data = $data->content;
1134 $total += $data->balance_owed;
1139 sub patron_money_owed {
1140 my( $self, $userid ) = @_;
1141 return $self->storagereq(
1142 'open-ils.storage.actor.user.total_owed', $userid);
1145 sub patron_total_items_out {
1146 my( $self, $userid ) = @_;
1147 return $self->storagereq(
1148 'open-ils.storage.actor.user.total_out', $userid);
1154 #---------------------------------------------------------------------
1155 # Returns ($summary, $event)
1156 #---------------------------------------------------------------------
1160 my $editor = shift || OpenILS::Utils::CStoreEditor->new;
1162 $id = $id->id if (ref($id));
1164 my $xact = $editor->retrieve_money_billable_transaction(
1168 flesh_fields => { mbt => [ qw/billings payments grocery circulation/ ] }
1171 ) or return (undef, $editor->event);
1173 return $self->make_mbts($xact);
1177 #---------------------------------------------------------------------
1178 # Given a list of money.billable_transaction objects, this creates
1179 # transaction summary objects for each
1180 #--------------------------------------------------------------------
1186 for my $x (@xacts) {
1188 my $s = new Fieldmapper::money::billable_transaction_summary;
1192 $s->xact_start( $x->xact_start );
1193 $s->xact_finish( $x->xact_finish );
1197 for my $b (@{ $x->billings }) {
1198 next if ($self->is_true($b->voided));
1199 $to += ($b->amount * 100);
1200 $lb ||= $b->billing_ts;
1201 if ($b->billing_ts ge $lb) {
1202 $lb = $b->billing_ts;
1203 $s->last_billing_note($b->note);
1204 $s->last_billing_ts($b->billing_ts);
1205 $s->last_billing_type($b->billing_type);
1209 $s->total_owed( sprintf('%0.2f', $to / 100 ) );
1213 for my $p (@{ $x->payments }) {
1214 next if ($self->is_true($p->voided));
1215 $tp += ($p->amount * 100);
1216 $lp ||= $p->payment_ts;
1217 if ($p->payment_ts ge $lp) {
1218 $lp = $p->payment_ts;
1219 $s->last_payment_note($p->note);
1220 $s->last_payment_ts($p->payment_ts);
1221 $s->last_payment_type($p->payment_type);
1225 $s->total_paid( sprintf('%0.2f', $tp / 100 ) );
1226 $s->balance_owed( sprintf('%0.2f', ($to - $tp) / 100) );
1227 $s->xact_type('grocery') if ($x->grocery);
1228 $s->xact_type('circulation') if ($x->circulation);
1230 $logger->debug("Created mbts with balance_owed = ". $s->balance_owed);
1239 sub ou_ancestor_setting_value {
1240 my $obj = ou_ancestor_setting(@_);
1241 return ($obj) ? $obj->{value} : undef;
1244 sub ou_ancestor_setting {
1245 my( $self, $orgid, $name, $e ) = @_;
1246 $e = $e || OpenILS::Utils::CStoreEditor->new;
1249 my $setting = $e->search_actor_org_unit_setting({org_unit=>$orgid, name=>$name})->[0];
1252 $logger->info("found org_setting $name at org $orgid : " . $setting->value);
1253 return { org => $orgid, value => OpenSRF::Utils::JSON->JSON2perl($setting->value) };
1256 my $org = $e->retrieve_actor_org_unit($orgid) or return $e->event;
1257 $orgid = $org->parent_ou or return undef;
1265 # returns the ISO8601 string representation of the requested epoch in GMT
1267 my( $self, $epoch ) = @_;
1268 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1269 $year += 1900; $mon += 1;
1271 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1272 $year, $mon, $mday, $hour, $min, $sec);
1276 sub find_highest_perm_org {
1277 my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1278 my $org = $self->find_org($org_tree, $start_org );
1282 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1284 $org = $self->find_org( $org_tree, $org->parent_ou() );
1291 sub find_highest_work_orgs {
1292 my($self, $e, $perm, $options) = @_;
1293 my $work_orgs = $self->get_user_work_ou_ids($e, $e->requestor->id);
1294 $logger->debug("found work orgs @$work_orgs");
1298 my $org_tree = $self->get_org_tree();
1299 my $org_types = $self->get_org_types();
1301 # use the first work org to determine the highest depth at which
1302 # the user has the requested permission
1303 my $first_org = shift @$work_orgs;
1304 my $high_org_id = $self->find_highest_perm_org($perm, $e->requestor->id, $first_org, $org_tree);
1305 $logger->debug("found highest work org $high_org_id");
1308 return [] if $high_org_id == -1; # not allowed anywhere
1310 my $high_org = $self->find_org($org_tree, $high_org_id);
1311 my ($high_org_type) = grep { $_->id == $high_org->ou_type } @$org_types;
1312 my $org_depth = $high_org_type->depth;
1314 if($$options{descendants}) {
1315 push(@allowed_orgs, @{$self->get_org_descendants($high_org_id, $org_depth)});
1317 push(@allowed_orgs, $high_org_id);
1320 return \@allowed_orgs if $org_depth == 0;
1322 for my $org (@$work_orgs) {
1324 $logger->debug("work org looking at $org");
1325 my $org_list = $self->get_org_full_path($org, $org_depth);
1328 for my $sub_org (@$org_list) {
1330 $logger->debug("work org looking at sub-org $sub_org");
1331 my $org_unit = $self->find_org($org_tree, $sub_org);
1332 my ($ou_type) = grep { $_->id == $org_unit->ou_type } @$org_types;
1333 if($ou_type->depth >= $org_depth) {
1334 push(@allowed_orgs, $sub_org);
1338 last unless $$options{descendants};
1339 push(@allowed_orgs, $sub_org);
1345 $de_dupe{$_} = 1 for @allowed_orgs;
1346 return [keys %de_dupe];
1350 sub get_user_work_ou_ids {
1351 my($self, $e, $userid) = @_;
1352 my $work_orgs = $e->json_query({
1353 select => {puwoum => ['work_ou']},
1355 where => {usr => $e->requestor->id}});
1357 return [] unless @$work_orgs;
1359 push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1367 my($self, $client) = @_;
1368 return $org_types if $org_types;
1369 return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1373 my $cache_diff = shift || '';
1374 my $cache = OpenSRF::Utils::Cache->new("global", 0);
1375 my $tree = $cache->get_cache("orgtree.$cache_diff");
1376 return $tree if $tree;
1378 $tree = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit(
1380 {"parent_ou" => undef },
1383 flesh_fields => { aou => ['children'] },
1384 order_by => { aou => 'name'}
1389 $cache->put_cache("orgtree.$cache_diff", $tree);
1393 sub get_org_descendants {
1394 my($self, $org_id, $depth) = @_;
1397 transform => 'actor.org_unit_descendants',
1399 result_field => 'id',
1401 $select->{params} = [$depth] if defined $depth;
1403 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1404 select => {aou => [$select]},
1406 where => {id => $org_id}
1409 push(@orgs, $_->{id}) for @$org_list;
1413 sub get_org_ancestors {
1414 my($self, $org_id, $depth) = @_;
1417 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1420 transform => 'actor.org_unit_ancestors',
1422 result_field => 'id',
1427 where => {id => $org_id}
1431 push(@orgs, $_->{id}) for @$org_list;
1435 sub get_org_full_path {
1436 my($self, $org_id, $depth) = @_;
1439 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1442 transform => 'actor.org_unit_full_path',
1444 result_field => 'id',
1449 where => {id => $org_id}
1453 push(@orgs, $_->{id}) for @$org_list;
1457 # returns the user's configured locale as a string. Defaults to en-US if none is configured.
1458 sub get_user_locale {
1459 my($self, $user_id, $e) = @_;
1460 $e ||=OpenILS::Utils::CStoreEditor->new;
1462 # first, see if the user has an explicit locale set
1463 my $setting = $e->search_actor_user_setting(
1464 {usr => $user_id, name => 'global.locale'})->[0];
1465 return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1467 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1469 # next see if their home org specifies a default locale
1470 $setting = $e->search_actor_org_unit_setting(
1471 {org_unit => $user->home_ou, name => 'global.default_locale'})->[0];
1472 return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1474 # if nothing else, fallback to locale=cowboy
1479 # xml-escape non-ascii characters
1481 my($self, $string, $form) = @_;
1485 $string = NFD($string);
1487 $string = NFC($string);
1490 $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;