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/;
15 # ---------------------------------------------------------------------------
16 # Pile of utilty methods used accross applications.
17 # ---------------------------------------------------------------------------
18 my $cache_client = "OpenSRF::Utils::Cache";
21 # ---------------------------------------------------------------------------
22 # on sucess, returns the created session, on failure throws ERROR exception
23 # ---------------------------------------------------------------------------
24 sub start_db_session {
27 my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
28 my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
30 my $trans_resp = $trans_req->recv();
31 if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
32 if( ! $trans_resp->content() ) {
34 ("Unable to Begin Transaction with database" );
38 $logger->debug("Setting global storage session to ".
39 "session: " . $session->session_id . " : " . $session->app );
47 transform => 'permission.usr_has_perm',
58 # returns undef if user has all of the perms provided
59 # returns the first failed perm on failure
60 sub check_user_perms {
61 my($self, $user_id, $org_id, @perm_types ) = @_;
62 $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
64 for my $type (@perm_types) {
65 $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
66 $PERM_QUERY->{where}->{id} = $user_id;
67 return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
72 # checks the list of user perms. The first one that fails returns a new
74 my( $self, $user_id, $org_id, @perm_types ) = @_;
75 my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
76 return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
82 # ---------------------------------------------------------------------------
83 # commits and destroys the session
84 # ---------------------------------------------------------------------------
85 sub commit_db_session {
86 my( $self, $session ) = @_;
88 my $req = $session->request( "open-ils.storage.transaction.commit" );
89 my $resp = $req->recv();
92 throw OpenSRF::EX::ERROR ("Unable to commit db session");
95 if(UNIVERSAL::isa($resp,"Error")) {
96 throw $resp ($resp->stringify);
100 throw OpenSRF::EX::ERROR ("Unable to commit db session");
104 $session->disconnect();
108 sub rollback_db_session {
109 my( $self, $session ) = @_;
111 my $req = $session->request("open-ils.storage.transaction.rollback");
112 my $resp = $req->recv();
113 if(UNIVERSAL::isa($resp,"Error")) { throw $resp; }
116 $session->disconnect();
121 # returns undef it the event is not an ILS event
122 # returns the event code otherwise
124 my( $self, $evt ) = @_;
125 return $evt->{ilsevent} if( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
129 # ---------------------------------------------------------------------------
130 # Checks to see if a user is logged in. Returns the user record on success,
131 # throws an exception on error.
132 # ---------------------------------------------------------------------------
133 sub check_user_session {
135 my( $self, $user_session ) = @_;
137 my $content = $self->simplereq(
139 'open-ils.auth.session.retrieve', $user_session );
141 if(! $content or $self->event_code($content)) {
142 throw OpenSRF::EX::ERROR
143 ("Session [$user_session] cannot be authenticated" );
146 $logger->debug("Fetch user session $user_session found user " . $content->id );
151 # generic simple request returning a scalar value
153 my($self, $service, $method, @params) = @_;
154 return $self->simple_scalar_request($service, $method, @params);
158 sub simple_scalar_request {
159 my($self, $service, $method, @params) = @_;
161 my $session = OpenSRF::AppSession->create( $service );
163 my $request = $session->request( $method, @params );
169 $val = $request->gather(1);
176 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
177 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
189 my $org_typelist = undef;
190 my $org_typelist_hash = {};
194 # can we throw this version away??
197 if($tree) { return $tree; }
199 # see if it's in the cache
200 $tree = $cache_client->new()->get_cache('_orgtree');
201 if($tree) { return $tree; }
204 warn "Retrieving Org Tree\n";
205 $orglist = $self->simple_scalar_request(
207 "open-ils.cstore.direct.actor.org_unit.search.atomic",
208 { id => { '!=' => undef } }
212 if( ! $org_typelist ) {
213 warn "Retrieving org types\n";
214 $org_typelist = $self->simple_scalar_request(
216 "open-ils.cstore.direct.actor.org_unit_type.search.atomic",
217 { id => { '!=' => undef } }
219 $self->build_org_type($org_typelist);
222 $tree = $self->build_org_tree($orglist,1);
223 $cache_client->new()->put_cache('_orgtree', $tree);
228 my $slimtree = undef;
229 sub get_slim_org_tree {
232 if($slimtree) { return $slimtree; }
234 # see if it's in the cache
235 $slimtree = $cache_client->new()->get_cache('slimorgtree');
236 if($slimtree) { return $slimtree; }
239 warn "Retrieving Org Tree\n";
240 $orglist = $self->simple_scalar_request(
242 "open-ils.cstore.direct.actor.org_unit.search.atomic",
243 { id => { '!=' => undef } }
247 $slimtree = $self->build_org_tree($orglist);
248 $cache_client->new->put_cache('slimorgtree', $slimtree);
255 my($self, $org_typelist) = @_;
256 for my $type (@$org_typelist) {
257 $org_typelist_hash->{$type->id()} = $type;
265 my( $self, $orglist, $add_types ) = @_;
267 return $orglist unless ref $orglist;
268 return $$orglist[0] if @$orglist == 1;
271 $a->ou_type <=> $b->ou_type ||
272 $a->name cmp $b->name } @$orglist;
274 for my $org (@list) {
278 if(!ref($org->ou_type()) and $add_types) {
279 $org->ou_type( $org_typelist_hash->{$org->ou_type()});
282 next unless (defined($org->parent_ou));
284 my ($parent) = grep { $_->id == $org->parent_ou } @list;
286 $parent->children([]) unless defined($parent->children);
287 push( @{$parent->children}, $org );
293 sub fetch_closed_date {
294 my( $self, $cd ) = @_;
297 $logger->debug("Fetching closed_date $cd from cstore");
299 my $cd_obj = $self->simplereq(
301 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
304 $logger->info("closed_date $cd not found in the db");
305 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
308 return ($cd_obj, $evt);
312 my( $self, $userid ) = @_;
315 $logger->debug("Fetching user $userid from cstore");
317 $user = $self->simplereq(
319 'open-ils.cstore.direct.actor.user.retrieve', $userid );
322 $logger->info("User $userid not found in the db");
323 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
326 return ($user, $evt);
330 my( $self, $session ) = @_;
331 my $user; my $evt; my $e;
333 $logger->debug("Checking user session $session");
336 $user = $self->check_user_session($session);
337 } catch Error with { $e = 1; };
339 $logger->debug("Done checking user session $session " . (($e) ? "error = $e" : "") );
341 if( $e or !$user ) { $evt = OpenILS::Event->new('NO_SESSION'); }
342 return ( $user, $evt );
346 # verifiese the session and checks the permissions agains the
347 # session user and the user's home_ou as the org id
349 my( $self, $session, @perms ) = @_;
350 my $user; my $evt; my $e;
351 $logger->debug("Checking user session $session and perms @perms");
352 ($user, $evt) = $self->checkses($session);
353 return (undef, $evt) if $evt;
354 $evt = $self->check_perms($user->id, $user->home_ou, @perms);
355 return ($user, $evt);
360 my( $self, $staffobj, $userid, @perms ) = @_;
362 $userid = $staffobj->id unless defined $userid;
364 $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
366 if( $userid ne $staffobj->id ) {
367 ($user, $evt) = $self->fetch_user($userid);
368 return (undef, $evt) if $evt;
369 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
375 return ($user, $evt);
378 sub checkses_requestor {
379 my( $self, $authtoken, $targetid, @perms ) = @_;
380 my( $requestor, $target, $evt );
382 ($requestor, $evt) = $self->checkses($authtoken);
383 return (undef, undef, $evt) if $evt;
385 ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
386 return( $requestor, $target, $evt);
390 my( $self, $copyid ) = @_;
393 $logger->debug("Fetching copy $copyid from cstore");
395 $copy = $self->simplereq(
397 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
399 if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
401 return( $copy, $evt );
405 # retrieves a circ object by id
406 sub fetch_circulation {
407 my( $self, $circid ) = @_;
410 $logger->debug("Fetching circ $circid from cstore");
412 $circ = $self->simplereq(
414 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
417 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
420 return ( $circ, $evt );
423 sub fetch_record_by_copy {
424 my( $self, $copyid ) = @_;
427 $logger->debug("Fetching record by copy $copyid from cstore");
429 $record = $self->simplereq(
431 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
433 flesh_fields => { bre => [ 'fixed_fields' ],
435 acp => [ 'call_number' ],
441 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
443 $record = $record->call_number->record;
446 return ($record, $evt);
449 # turns a record object into an mvr (mods) object
451 my( $self, $record ) = @_;
452 return undef unless $record and $record->marc;
453 my $u = OpenILS::Utils::ModsParser->new();
454 $u->start_mods_batch( $record->marc );
455 my $mods = $u->finish_mods_batch();
456 $mods->doc_id($record->id);
457 $mods->tcn($record->tcn_value);
462 my( $self, $holdid ) = @_;
465 $logger->debug("Fetching hold $holdid from cstore");
467 $hold = $self->simplereq(
469 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
471 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
473 return ($hold, $evt);
477 sub fetch_hold_transit_by_hold {
478 my( $self, $holdid ) = @_;
479 my( $transit, $evt );
481 $logger->debug("Fetching transit by hold $holdid from cstore");
483 $transit = $self->simplereq(
485 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
487 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
489 return ($transit, $evt );
492 # fetches the captured, but not fulfilled hold attached to a given copy
493 sub fetch_open_hold_by_copy {
494 my( $self, $copyid ) = @_;
495 $logger->debug("Searching for active hold for copy $copyid");
498 $hold = $self->cstorereq(
499 'open-ils.cstore.direct.action.hold_request.search',
501 current_copy => $copyid ,
502 capture_time => { "!=" => undef },
503 fulfillment_time => undef,
504 cancel_time => undef,
507 $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
508 return ($hold, $evt);
511 sub fetch_hold_transit {
512 my( $self, $transid ) = @_;
513 my( $htransit, $evt );
514 $logger->debug("Fetching hold transit with hold id $transid");
515 $htransit = $self->cstorereq(
516 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
517 $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
518 return ($htransit, $evt);
521 sub fetch_copy_by_barcode {
522 my( $self, $barcode ) = @_;
525 $logger->debug("Fetching copy by barcode $barcode from cstore");
527 $copy = $self->simplereq( 'open-ils.cstore',
528 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
529 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
531 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
533 return ($copy, $evt);
536 sub fetch_open_billable_transaction {
537 my( $self, $transid ) = @_;
538 my( $transaction, $evt );
540 $logger->debug("Fetching open billable transaction $transid from cstore");
542 $transaction = $self->simplereq(
544 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve', $transid);
546 $evt = OpenILS::Event->new(
547 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
549 return ($transaction, $evt);
555 $buckets{'biblio'} = 'biblio_record_entry_bucket';
556 $buckets{'callnumber'} = 'call_number_bucket';
557 $buckets{'copy'} = 'copy_bucket';
558 $buckets{'user'} = 'user_bucket';
560 sub fetch_container {
561 my( $self, $id, $type ) = @_;
564 $logger->debug("Fetching container $id with type $type");
566 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
567 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
568 $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
569 $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
571 my $meth = $buckets{$type};
572 $bucket = $self->simplereq(
574 "open-ils.cstore.direct.container.$meth.retrieve", $id );
576 $evt = OpenILS::Event->new(
577 $e, container => $id, container_type => $type ) unless $bucket;
579 return ($bucket, $evt);
583 sub fetch_container_e {
584 my( $self, $editor, $id, $type ) = @_;
587 $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
588 $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
589 $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
590 $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
592 $evt = $editor->event unless $bucket;
593 return ($bucket, $evt);
596 sub fetch_container_item_e {
597 my( $self, $editor, $id, $type ) = @_;
600 $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
601 $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
602 $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
603 $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
605 $evt = $editor->event unless $bucket;
606 return ($bucket, $evt);
613 sub fetch_container_item {
614 my( $self, $id, $type ) = @_;
617 $logger->debug("Fetching container item $id with type $type");
619 my $meth = $buckets{$type} . "_item";
621 $bucket = $self->simplereq(
623 "open-ils.cstore.direct.container.$meth.retrieve", $id );
626 my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
627 $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
628 $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
629 $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
631 $evt = OpenILS::Event->new(
632 $e, itemid => $id, container_type => $type ) unless $bucket;
634 return ($bucket, $evt);
638 sub fetch_patron_standings {
640 $logger->debug("Fetching patron standings");
641 return $self->simplereq(
643 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
647 sub fetch_permission_group_tree {
649 $logger->debug("Fetching patron profiles");
650 return $self->simplereq(
652 'open-ils.actor.groups.tree.retrieve' );
656 sub fetch_patron_circ_summary {
657 my( $self, $userid ) = @_;
658 $logger->debug("Fetching patron summary for $userid");
659 my $summary = $self->simplereq(
661 "open-ils.storage.action.circulation.patron_summary", $userid );
665 $summary->[1] ||= 0.0;
672 sub fetch_copy_statuses {
674 $logger->debug("Fetching copy statuses");
675 return $self->simplereq(
677 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
680 sub fetch_copy_location {
681 my( $self, $id ) = @_;
683 my $cl = $self->cstorereq(
684 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
685 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
689 sub fetch_copy_locations {
691 return $self->simplereq(
693 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
696 sub fetch_copy_location_by_name {
697 my( $self, $name, $org ) = @_;
699 my $cl = $self->cstorereq(
700 'open-ils.cstore.direct.asset.copy_location.search',
701 { name => $name, owning_lib => $org } );
702 $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
706 sub fetch_callnumber {
707 my( $self, $id ) = @_;
710 my $e = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
711 return( undef, $e ) unless $id;
713 $logger->debug("Fetching callnumber $id");
715 my $cn = $self->simplereq(
717 'open-ils.cstore.direct.asset.call_number.retrieve', $id );
718 $evt = $e unless $cn;
720 return ( $cn, $evt );
723 my %ORG_CACHE; # - these rarely change, so cache them..
725 my( $self, $id ) = @_;
726 return undef unless $id;
727 return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
728 return $ORG_CACHE{$id} if $ORG_CACHE{$id};
729 $logger->debug("Fetching org unit $id");
732 my $org = $self->simplereq(
734 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
735 $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
736 $ORG_CACHE{$id} = $org;
742 my( $self, $type, $id ) = @_;
744 $logger->debug("Fetching $type stat cat: $id");
745 $cat = $self->simplereq(
747 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
749 my $e = 'ASSET_STAT_CAT_NOT_FOUND';
750 $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
752 $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
753 return ( $cat, $evt );
756 sub fetch_stat_cat_entry {
757 my( $self, $type, $id ) = @_;
759 $logger->debug("Fetching $type stat cat entry: $id");
760 $entry = $self->simplereq(
762 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
764 my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
765 $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
767 $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
768 return ( $entry, $evt );
773 my( $self, $org_tree, $orgid ) = @_;
775 $logger->warn("find_org() did not receive a value for \$org_tree");
778 $logger->warn("find_org() did not receive a value for \$orgid");
781 return $org_tree if ( $org_tree->id eq $orgid );
782 return undef unless ref($org_tree->children);
783 for my $c (@{$org_tree->children}) {
784 my $o = $self->find_org($c, $orgid);
790 sub fetch_non_cat_type_by_name_and_org {
791 my( $self, $name, $orgId ) = @_;
792 $logger->debug("Fetching non cat type $name at org $orgId");
793 my $types = $self->simplereq(
795 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
796 { name => $name, owning_lib => $orgId } );
797 return ($types->[0], undef) if($types and @$types);
798 return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
801 sub fetch_non_cat_type {
802 my( $self, $id ) = @_;
803 $logger->debug("Fetching non cat type $id");
805 $type = $self->simplereq(
807 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
808 $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
809 return ($type, $evt);
812 sub DB_UPDATE_FAILED {
813 my( $self, $payload ) = @_;
814 return OpenILS::Event->new('DATABASE_UPDATE_FAILED',
815 payload => ($payload) ? $payload : undef );
818 sub fetch_circ_duration_by_name {
819 my( $self, $name ) = @_;
821 $dur = $self->simplereq(
823 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
825 $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
829 sub fetch_recurring_fine_by_name {
830 my( $self, $name ) = @_;
832 $obj = $self->simplereq(
834 'open-ils.cstore.direct.config.rules.recuring_fine.search.atomic', { name => $name } );
836 $evt = OpenILS::Event->new('CONFIG_RULES_RECURING_FINE_NOT_FOUND') unless $obj;
840 sub fetch_max_fine_by_name {
841 my( $self, $name ) = @_;
843 $obj = $self->simplereq(
845 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
847 $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
852 my( $self, $method, @params ) = @_;
853 return $self->simplereq(
854 'open-ils.storage', $method, @params );
858 my( $self, $method, @params ) = @_;
859 return $self->simplereq(
860 'open-ils.cstore', $method, @params );
864 my( $self, $e, $name ) = @_;
865 if( $e and ref($e) eq 'HASH' and
866 defined($e->{textcode}) and $e->{textcode} eq $name ) {
873 my( undef, $f, $l ) = caller(0);
874 my( undef, undef, undef, $s ) = caller(1);
877 $logger->debug("LOGMARK: $f:$l:$s");
881 sub fetch_open_circulation {
882 my( $self, $cid ) = @_;
885 my $circ = $self->cstorereq(
886 'open-ils.cstore.direct.action.open_circulation.search',
887 { target_copy => $cid, stop_fines_time => undef } );
888 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;
889 return ($circ, $evt);
892 sub fetch_all_open_circulation {
893 my( $self, $cid ) = @_;
896 my $circ = $self->cstorereq(
897 'open-ils.cstore.direct.action.open_circulation.search',
898 { target_copy => $cid, xact_finish => undef } );
899 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;
900 return ($circ, $evt);
904 sub copy_status_from_name {
905 my( $self, $name ) = @_;
906 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
907 for my $status (@$copy_statuses) {
908 return $status if( $status->name =~ /$name/i );
913 sub copy_status_to_name {
914 my( $self, $sid ) = @_;
915 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
916 for my $status (@$copy_statuses) {
917 return $status->name if( $status->id == $sid );
924 my( $self, $arg ) = @_;
925 return $arg if ref $arg;
926 $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
927 my ($stat) = grep { $_->id == $arg } @$copy_statuses;
931 sub fetch_open_transit_by_copy {
932 my( $self, $copyid ) = @_;
934 $transit = $self->cstorereq(
935 'open-ils.cstore.direct.action.transit_copy.search',
936 { target_copy => $copyid, dest_recv_time => undef });
937 $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
938 return ($transit, $evt);
942 my( $self, $copy ) = @_;
943 return undef unless $copy;
944 $copy->status( $copy->status->id ) if ref($copy->status);
945 $copy->location( $copy->location->id ) if ref($copy->location);
946 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
950 # un-fleshes a copy and updates it in the DB
951 # returns a DB_UPDATE_FAILED event on error
952 # returns undef on success
954 my( $self, %params ) = @_;
956 my $copy = $params{copy} || die "update_copy(): copy required";
957 my $editor = $params{editor} || die "update_copy(): copy editor required";
958 my $session = $params{session};
960 $logger->debug("Updating copy in the database: " . $copy->id);
962 $self->unflesh_copy($copy);
963 $copy->editor( $editor );
964 $copy->edit_date( 'now' );
967 my $meth = 'open-ils.storage.direct.asset.copy.update';
969 $s = $session->request( $meth, $copy )->gather(1) if $session;
970 $s = $self->storagereq( $meth, $copy ) unless $session;
972 $logger->debug("Update of copy ".$copy->id." returned: $s");
974 return $self->DB_UPDATE_FAILED($copy) unless $s;
978 sub fetch_billable_xact {
979 my( $self, $id ) = @_;
981 $logger->debug("Fetching billable transaction %id");
982 $xact = $self->cstorereq(
983 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
984 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
985 return ($xact, $evt);
988 sub fetch_billable_xact_summary {
989 my( $self, $id ) = @_;
991 $logger->debug("Fetching billable transaction summary %id");
992 $xact = $self->cstorereq(
993 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
994 $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
995 return ($xact, $evt);
998 sub fetch_fleshed_copy {
999 my( $self, $id ) = @_;
1001 $logger->info("Fetching fleshed copy $id");
1002 $copy = $self->cstorereq(
1003 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1005 flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1008 $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1009 return ($copy, $evt);
1013 # returns the org that owns the callnumber that the copy
1015 sub fetch_copy_owner {
1016 my( $self, $copyid ) = @_;
1017 my( $copy, $cn, $evt );
1018 $logger->debug("Fetching copy owner $copyid");
1019 ($copy, $evt) = $self->fetch_copy($copyid);
1020 return (undef,$evt) if $evt;
1021 ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1022 return (undef,$evt) if $evt;
1023 return ($cn->owning_lib);
1026 sub fetch_copy_note {
1027 my( $self, $id ) = @_;
1029 $logger->debug("Fetching copy note $id");
1030 $note = $self->cstorereq(
1031 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1032 $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1033 return ($note, $evt);
1036 sub fetch_call_numbers_by_title {
1037 my( $self, $titleid ) = @_;
1038 $logger->info("Fetching call numbers by title $titleid");
1039 return $self->cstorereq(
1040 'open-ils.cstore.direct.asset.call_number.search.atomic',
1041 { record => $titleid, deleted => 'f' });
1042 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1045 sub fetch_copies_by_call_number {
1046 my( $self, $cnid ) = @_;
1047 $logger->info("Fetching copies by call number $cnid");
1048 return $self->cstorereq(
1049 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1050 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1053 sub fetch_user_by_barcode {
1054 my( $self, $bc ) = @_;
1055 my $cardid = $self->cstorereq(
1056 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1057 return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1058 my $user = $self->cstorereq(
1059 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1060 return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1066 # ---------------------------------------------------------------------
1067 # Updates and returns the patron penalties
1068 # ---------------------------------------------------------------------
1069 sub update_patron_penalties {
1070 my( $self, %args ) = @_;
1071 return $self->simplereq(
1073 'open-ils.penalty.patron_penalty.calculate',
1074 { update => 1, %args }
1079 my( $self, $billid ) = @_;
1080 $logger->debug("Fetching billing $billid");
1081 my $bill = $self->cstorereq(
1082 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1083 my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1084 return($bill, $evt);
1090 sub fetch_org_tree {
1092 return $ORG_TREE if $ORG_TREE;
1093 return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit(
1095 {"parent_ou" => undef },
1098 flesh_fields => { aou => ['children'] },
1099 order_by => { aou => 'name'}
1106 my( $self, $node, $callback ) = @_;
1107 return unless $node;
1109 if( $node->children ) {
1110 $self->walk_org_tree($_, $callback) for @{$node->children};
1115 my( $self, $item ) = @_;
1116 return 1 if $item and $item !~ /^f$/i;
1121 # This logic now lives in storage
1122 sub __patron_money_owed {
1123 my( $self, $patronid ) = @_;
1124 my $ses = OpenSRF::AppSession->create('open-ils.storage');
1125 my $req = $ses->request(
1126 'open-ils.storage.money.billable_transaction.summary.search',
1127 { usr => $patronid, xact_finish => undef } );
1131 while( $data = $req->recv ) {
1132 $data = $data->content;
1133 $total += $data->balance_owed;
1138 sub patron_money_owed {
1139 my( $self, $userid ) = @_;
1140 return $self->storagereq(
1141 'open-ils.storage.actor.user.total_owed', $userid);
1144 sub patron_total_items_out {
1145 my( $self, $userid ) = @_;
1146 return $self->storagereq(
1147 'open-ils.storage.actor.user.total_out', $userid);
1153 #---------------------------------------------------------------------
1154 # Returns ($summary, $event)
1155 #---------------------------------------------------------------------
1159 my $editor = shift || OpenILS::Utils::CStoreEditor->new;
1161 $id = $id->id if (ref($id));
1163 my $xact = $editor->retrieve_money_billable_transaction(
1167 flesh_fields => { mbt => [ qw/billings payments grocery circulation/ ] }
1170 ) or return (undef, $editor->event);
1172 return $self->make_mbts($xact);
1176 #---------------------------------------------------------------------
1177 # Given a list of money.billable_transaction objects, this creates
1178 # transaction summary objects for each
1179 #--------------------------------------------------------------------
1185 for my $x (@xacts) {
1187 my $s = new Fieldmapper::money::billable_transaction_summary;
1191 $s->xact_start( $x->xact_start );
1192 $s->xact_finish( $x->xact_finish );
1196 for my $b (@{ $x->billings }) {
1197 next if ($self->is_true($b->voided));
1198 $to += ($b->amount * 100);
1199 $lb ||= $b->billing_ts;
1200 if ($b->billing_ts ge $lb) {
1201 $lb = $b->billing_ts;
1202 $s->last_billing_note($b->note);
1203 $s->last_billing_ts($b->billing_ts);
1204 $s->last_billing_type($b->billing_type);
1208 $s->total_owed( sprintf('%0.2f', $to / 100 ) );
1212 for my $p (@{ $x->payments }) {
1213 next if ($self->is_true($p->voided));
1214 $tp += ($p->amount * 100);
1215 $lp ||= $p->payment_ts;
1216 if ($p->payment_ts ge $lp) {
1217 $lp = $p->payment_ts;
1218 $s->last_payment_note($p->note);
1219 $s->last_payment_ts($p->payment_ts);
1220 $s->last_payment_type($p->payment_type);
1224 $s->total_paid( sprintf('%0.2f', $tp / 100 ) );
1225 $s->balance_owed( sprintf('%0.2f', ($to - $tp) / 100) );
1226 $s->xact_type('grocery') if ($x->grocery);
1227 $s->xact_type('circulation') if ($x->circulation);
1229 $logger->debug("Created mbts with balance_owed = ". $s->balance_owed);
1238 sub ou_ancestor_setting_value {
1239 my $obj = ou_ancestor_setting(@_);
1240 return ($obj) ? $obj->{value} : undef;
1243 sub ou_ancestor_setting {
1244 my( $self, $orgid, $name, $e ) = @_;
1245 $e = $e || OpenILS::Utils::CStoreEditor->new;
1248 my $setting = $e->search_actor_org_unit_setting({org_unit=>$orgid, name=>$name})->[0];
1251 $logger->info("found org_setting $name at org $orgid : " . $setting->value);
1252 return { org => $orgid, value => OpenSRF::Utils::JSON->JSON2perl($setting->value) };
1255 my $org = $e->retrieve_actor_org_unit($orgid) or return $e->event;
1256 $orgid = $org->parent_ou or return undef;
1264 # returns the ISO8601 string representation of the requested epoch in GMT
1266 my( $self, $epoch ) = @_;
1267 my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1268 $year += 1900; $mon += 1;
1270 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1271 $year, $mon, $mday, $hour, $min, $sec);
1275 sub find_highest_perm_org {
1276 my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1277 my $org = $self->find_org($org_tree, $start_org );
1281 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1283 $org = $self->find_org( $org_tree, $org->parent_ou() );
1290 sub find_highest_work_orgs {
1291 my($self, $e, $perm, $options) = @_;
1292 my $work_orgs = $self->get_user_work_ou_ids($e, $e->requestor->id);
1293 $logger->debug("found work orgs @$work_orgs");
1296 my $org_tree = $self->get_org_tree();
1297 my $org_types = $self->get_org_types();
1299 # use the first work org to determine the highest depth at which
1300 # the user has the requested permission
1301 my $first_org = shift @$work_orgs;
1302 my $high_org_id = $self->find_highest_perm_org($perm, $e->requestor->id, $first_org, $org_tree);
1303 $logger->debug("found highest work org $high_org_id");
1306 return [] if $high_org_id == -1; # not allowed anywhere
1308 my $high_org = $self->find_org($org_tree, $high_org_id);
1309 my ($high_org_type) = grep { $_->id == $high_org->ou_type } @$org_types;
1310 my $org_depth = $high_org_type->depth;
1312 if($$options{descendants}) {
1313 push(@allowed_orgs, @{$self->get_org_descendants($high_org_id, $org_depth)});
1315 push(@allowed_orgs, $high_org_id);
1318 return \@allowed_orgs if $org_depth == 0;
1320 for my $org (@$work_orgs) {
1322 $logger->debug("work org looking at $org");
1323 my $org_list = $self->get_org_full_path($org, $org_depth);
1326 for my $sub_org (@$org_list) {
1328 $logger->debug("work org looking at sub-org $sub_org");
1329 my $org_unit = $self->find_org($org_tree, $sub_org);
1330 my ($ou_type) = grep { $_->id == $org_unit->ou_type } @$org_types;
1331 if($ou_type->depth >= $org_depth) {
1332 push(@allowed_orgs, $sub_org);
1336 last unless $$options{descendants};
1337 push(@allowed_orgs, $sub_org);
1343 $de_dupe{$_} = 1 for @allowed_orgs;
1344 return [keys %de_dupe];
1348 sub get_user_work_ou_ids {
1349 my($self, $e, $userid) = @_;
1350 my $work_orgs = $e->json_query({
1351 select => {puwoum => ['work_ou']},
1353 where => {usr => $e->requestor->id}});
1355 return [] unless @$work_orgs;
1357 push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1365 my($self, $client) = @_;
1366 return $org_types if $org_types;
1367 return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1371 my $cache_diff = shift || '';
1372 my $cache = OpenSRF::Utils::Cache->new("global", 0);
1373 my $tree = $cache->get_cache("orgtree.$cache_diff");
1374 return $tree if $tree;
1376 $tree = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit(
1378 {"parent_ou" => undef },
1381 flesh_fields => { aou => ['children'] },
1382 order_by => { aou => 'name'}
1387 $cache->put_cache("orgtree.$cache_diff", $tree);
1391 sub get_org_descendants {
1392 my($self, $org_id, $depth) = @_;
1395 transform => 'actor.org_unit_descendants',
1397 result_field => 'id',
1399 $select->{params} = [$depth] if defined $depth;
1401 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1402 select => {aou => [$select]},
1404 where => {id => $org_id}
1407 push(@orgs, $_->{id}) for @$org_list;
1411 sub get_org_ancestors {
1412 my($self, $org_id, $depth) = @_;
1415 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1418 transform => 'actor.org_unit_ancestors',
1420 result_field => 'id',
1425 where => {id => $org_id}
1429 push(@orgs, $_->{id}) for @$org_list;
1433 sub get_org_full_path {
1434 my($self, $org_id, $depth) = @_;
1437 my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1440 transform => 'actor.org_unit_full_path',
1442 result_field => 'id',
1447 where => {id => $org_id}
1451 push(@orgs, $_->{id}) for @$org_list;