]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/AppUtils.pm
added versions of work perm org fetcher to return flat list of all org units or org...
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / AppUtils.pm
1 package OpenILS::Application::AppUtils;
2 # vim:noet:ts=4
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);
10 use OpenILS::Event;
11 use Data::Dumper;
12 use OpenILS::Utils::CStoreEditor;
13 use OpenILS::Const qw/:const/;
14
15 # ---------------------------------------------------------------------------
16 # Pile of utilty methods used accross applications.
17 # ---------------------------------------------------------------------------
18 my $cache_client = "OpenSRF::Utils::Cache";
19
20
21 # ---------------------------------------------------------------------------
22 # on sucess, returns the created session, on failure throws ERROR exception
23 # ---------------------------------------------------------------------------
24 sub start_db_session {
25
26         my $self = shift;
27         my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
28         my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
29
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() ) {
33                 throw OpenSRF::ERROR 
34                         ("Unable to Begin Transaction with database" );
35         }
36         $trans_req->finish();
37
38         $logger->debug("Setting global storage session to ".
39                 "session: " . $session->session_id . " : " . $session->app );
40
41         return $session;
42 }
43
44 my $PERM_QUERY = {
45     select => {
46         au => [ {
47             transform => 'permission.usr_has_perm',
48             alias => 'has_perm',
49             column => 'id',
50             params => []
51         } ]
52     },
53     from => 'au',
54     where => {},
55 };
56
57
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");
63
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});
68         }
69         return undef;
70 }
71
72 # checks the list of user perms.  The first one that fails returns a new
73 sub check_perms {
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;
77         return undef;
78 }
79
80
81
82 # ---------------------------------------------------------------------------
83 # commits and destroys the session
84 # ---------------------------------------------------------------------------
85 sub commit_db_session {
86         my( $self, $session ) = @_;
87
88         my $req = $session->request( "open-ils.storage.transaction.commit" );
89         my $resp = $req->recv();
90
91         if(!$resp) {
92                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
93         }
94
95         if(UNIVERSAL::isa($resp,"Error")) { 
96                 throw $resp ($resp->stringify); 
97         }
98
99         if(!$resp->content) {
100                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
101         }
102
103         $session->finish();
104         $session->disconnect();
105         $session->kill_me();
106 }
107
108 sub rollback_db_session {
109         my( $self, $session ) = @_;
110
111         my $req = $session->request("open-ils.storage.transaction.rollback");
112         my $resp = $req->recv();
113         if(UNIVERSAL::isa($resp,"Error")) { throw $resp;  }
114
115         $session->finish();
116         $session->disconnect();
117         $session->kill_me();
118 }
119
120
121 # returns undef it the event is not an ILS event
122 # returns the event code otherwise
123 sub event_code {
124         my( $self, $evt ) = @_;
125         return $evt->{ilsevent} if( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
126         return undef;
127 }
128
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 {
134
135         my( $self, $user_session ) = @_;
136
137         my $content = $self->simplereq( 
138                 'open-ils.auth', 
139                 'open-ils.auth.session.retrieve', $user_session );
140
141         if(! $content or $self->event_code($content)) {
142                 throw OpenSRF::EX::ERROR 
143                         ("Session [$user_session] cannot be authenticated" );
144         }
145
146         $logger->debug("Fetch user session $user_session found user " . $content->id );
147
148         return $content;
149 }
150
151 # generic simple request returning a scalar value
152 sub simplereq {
153         my($self, $service, $method, @params) = @_;
154         return $self->simple_scalar_request($service, $method, @params);
155 }
156
157
158 sub simple_scalar_request {
159         my($self, $service, $method, @params) = @_;
160
161         my $session = OpenSRF::AppSession->create( $service );
162
163         my $request = $session->request( $method, @params );
164
165         my $val;
166         my $err;
167         try  {
168
169                 $val = $request->gather(1);     
170
171         } catch Error with {
172                 $err = shift;
173         };
174
175         if( $err ) {
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 : " );
178         }
179
180         return $val;
181 }
182
183
184
185
186
187 my $tree                                                = undef;
188 my $orglist                                     = undef;
189 my $org_typelist                        = undef;
190 my $org_typelist_hash   = {};
191
192 sub __get_org_tree {
193         
194         # can we throw this version away??
195
196         my $self = shift;
197         if($tree) { return $tree; }
198
199         # see if it's in the cache
200         $tree = $cache_client->new()->get_cache('_orgtree');
201         if($tree) { return $tree; }
202
203         if(!$orglist) {
204                 warn "Retrieving Org Tree\n";
205                 $orglist = $self->simple_scalar_request( 
206                         "open-ils.cstore", 
207                         "open-ils.cstore.direct.actor.org_unit.search.atomic",
208                         { id => { '!=' => undef } }
209                 );
210         }
211
212         if( ! $org_typelist ) {
213                 warn "Retrieving org types\n";
214                 $org_typelist = $self->simple_scalar_request( 
215                         "open-ils.cstore", 
216                         "open-ils.cstore.direct.actor.org_unit_type.search.atomic",
217                         { id => { '!=' => undef } }
218                 );
219                 $self->build_org_type($org_typelist);
220         }
221
222         $tree = $self->build_org_tree($orglist,1);
223         $cache_client->new()->put_cache('_orgtree', $tree);
224         return $tree;
225
226 }
227
228 my $slimtree = undef;
229 sub get_slim_org_tree {
230
231         my $self = shift;
232         if($slimtree) { return $slimtree; }
233
234         # see if it's in the cache
235         $slimtree = $cache_client->new()->get_cache('slimorgtree');
236         if($slimtree) { return $slimtree; }
237
238         if(!$orglist) {
239                 warn "Retrieving Org Tree\n";
240                 $orglist = $self->simple_scalar_request( 
241                         "open-ils.cstore", 
242                         "open-ils.cstore.direct.actor.org_unit.search.atomic",
243                         { id => { '!=' => undef } }
244                 );
245         }
246
247         $slimtree = $self->build_org_tree($orglist);
248         $cache_client->new->put_cache('slimorgtree', $slimtree);
249         return $slimtree;
250
251 }
252
253
254 sub build_org_type { 
255         my($self, $org_typelist)  = @_;
256         for my $type (@$org_typelist) {
257                 $org_typelist_hash->{$type->id()} = $type;
258         }
259 }
260
261
262
263 sub build_org_tree {
264
265         my( $self, $orglist, $add_types ) = @_;
266
267         return $orglist unless ref $orglist; 
268     return $$orglist[0] if @$orglist == 1;
269
270         my @list = sort { 
271                 $a->ou_type <=> $b->ou_type ||
272                 $a->name cmp $b->name } @$orglist;
273
274         for my $org (@list) {
275
276                 next unless ($org);
277
278                 if(!ref($org->ou_type()) and $add_types) {
279                         $org->ou_type( $org_typelist_hash->{$org->ou_type()});
280                 }
281
282                 next unless (defined($org->parent_ou));
283
284                 my ($parent) = grep { $_->id == $org->parent_ou } @list;
285                 next unless $parent;
286                 $parent->children([]) unless defined($parent->children); 
287                 push( @{$parent->children}, $org );
288         }
289
290         return $list[0];
291 }
292
293 sub fetch_closed_date {
294         my( $self, $cd ) = @_;
295         my $evt;
296         
297         $logger->debug("Fetching closed_date $cd from cstore");
298
299         my $cd_obj = $self->simplereq(
300                 'open-ils.cstore',
301                 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
302
303         if(!$cd_obj) {
304                 $logger->info("closed_date $cd not found in the db");
305                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
306         }
307
308         return ($cd_obj, $evt);
309 }
310
311 sub fetch_user {
312         my( $self, $userid ) = @_;
313         my( $user, $evt );
314         
315         $logger->debug("Fetching user $userid from cstore");
316
317         $user = $self->simplereq(
318                 'open-ils.cstore',
319                 'open-ils.cstore.direct.actor.user.retrieve', $userid );
320
321         if(!$user) {
322                 $logger->info("User $userid not found in the db");
323                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
324         }
325
326         return ($user, $evt);
327 }
328
329 sub checkses {
330         my( $self, $session ) = @_;
331         my $user; my $evt; my $e; 
332
333         $logger->debug("Checking user session $session");
334
335         try {
336                 $user = $self->check_user_session($session);
337         } catch Error with { $e = 1; };
338
339         $logger->debug("Done checking user session $session " . (($e) ? "error = $e" : "") );
340
341         if( $e or !$user ) { $evt = OpenILS::Event->new('NO_SESSION'); }
342         return ( $user, $evt );
343 }
344
345
346 # verifiese the session and checks the permissions agains the
347 # session user and the user's home_ou as the org id
348 sub checksesperm {
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);
356 }
357
358
359 sub checkrequestor {
360         my( $self, $staffobj, $userid, @perms ) = @_;
361         my $user; my $evt;
362         $userid = $staffobj->id unless defined $userid;
363
364         $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
365
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 );
370
371         } else {
372                 $user = $staffobj;
373         }
374
375         return ($user, $evt);
376 }
377
378 sub checkses_requestor {
379         my( $self, $authtoken, $targetid, @perms ) = @_;
380         my( $requestor, $target, $evt );
381
382         ($requestor, $evt) = $self->checkses($authtoken);
383         return (undef, undef, $evt) if $evt;
384
385         ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
386         return( $requestor, $target, $evt);
387 }
388
389 sub fetch_copy {
390         my( $self, $copyid ) = @_;
391         my( $copy, $evt );
392
393         $logger->debug("Fetching copy $copyid from cstore");
394
395         $copy = $self->simplereq(
396                 'open-ils.cstore',
397                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
398
399         if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
400
401         return( $copy, $evt );
402 }
403
404
405 # retrieves a circ object by id
406 sub fetch_circulation {
407         my( $self, $circid ) = @_;
408         my $circ; my $evt;
409         
410         $logger->debug("Fetching circ $circid from cstore");
411
412         $circ = $self->simplereq(
413                 'open-ils.cstore',
414                 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
415
416         if(!$circ) {
417                 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
418         }
419
420         return ( $circ, $evt );
421 }
422
423 sub fetch_record_by_copy {
424         my( $self, $copyid ) = @_;
425         my( $record, $evt );
426
427         $logger->debug("Fetching record by copy $copyid from cstore");
428
429         $record = $self->simplereq(
430                 'open-ils.cstore',
431                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
432                 { flesh => 3,
433                   flesh_fields => {     bre => [ 'fixed_fields' ],
434                                         acn => [ 'record' ],
435                                         acp => [ 'call_number' ],
436                                   }
437                 }
438         );
439
440         if(!$record) {
441                 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
442         } else {
443                 $record = $record->call_number->record;
444         }
445
446         return ($record, $evt);
447 }
448
449 # turns a record object into an mvr (mods) object
450 sub record_to_mvr {
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);
458         return $mods;
459 }
460
461 sub fetch_hold {
462         my( $self, $holdid ) = @_;
463         my( $hold, $evt );
464
465         $logger->debug("Fetching hold $holdid from cstore");
466
467         $hold = $self->simplereq(
468                 'open-ils.cstore',
469                 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
470
471         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
472
473         return ($hold, $evt);
474 }
475
476
477 sub fetch_hold_transit_by_hold {
478         my( $self, $holdid ) = @_;
479         my( $transit, $evt );
480
481         $logger->debug("Fetching transit by hold $holdid from cstore");
482
483         $transit = $self->simplereq(
484                 'open-ils.cstore',
485                 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
486
487         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
488
489         return ($transit, $evt );
490 }
491
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");
496         my( $hold, $evt );
497
498         $hold = $self->cstorereq(
499                 'open-ils.cstore.direct.action.hold_request.search',
500                 { 
501                         current_copy            => $copyid , 
502                         capture_time            => { "!=" => undef }, 
503                         fulfillment_time        => undef,
504                         cancel_time                     => undef,
505                 } );
506
507         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
508         return ($hold, $evt);
509 }
510
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);
519 }
520
521 sub fetch_copy_by_barcode {
522         my( $self, $barcode ) = @_;
523         my( $copy, $evt );
524
525         $logger->debug("Fetching copy by barcode $barcode from cstore");
526
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 );
530
531         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
532
533         return ($copy, $evt);
534 }
535
536 sub fetch_open_billable_transaction {
537         my( $self, $transid ) = @_;
538         my( $transaction, $evt );
539
540         $logger->debug("Fetching open billable transaction $transid from cstore");
541
542         $transaction = $self->simplereq(
543                 'open-ils.cstore',
544                 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve',  $transid);
545
546         $evt = OpenILS::Event->new(
547                 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
548
549         return ($transaction, $evt);
550 }
551
552
553
554 my %buckets;
555 $buckets{'biblio'} = 'biblio_record_entry_bucket';
556 $buckets{'callnumber'} = 'call_number_bucket';
557 $buckets{'copy'} = 'copy_bucket';
558 $buckets{'user'} = 'user_bucket';
559
560 sub fetch_container {
561         my( $self, $id, $type ) = @_;
562         my( $bucket, $evt );
563
564         $logger->debug("Fetching container $id with type $type");
565
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';
570
571         my $meth = $buckets{$type};
572         $bucket = $self->simplereq(
573                 'open-ils.cstore',
574                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
575
576         $evt = OpenILS::Event->new(
577                 $e, container => $id, container_type => $type ) unless $bucket;
578
579         return ($bucket, $evt);
580 }
581
582
583 sub fetch_container_e {
584         my( $self, $editor, $id, $type ) = @_;
585
586         my( $bucket, $evt );
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';
591
592         $evt = $editor->event unless $bucket;
593         return ($bucket, $evt);
594 }
595
596 sub fetch_container_item_e {
597         my( $self, $editor, $id, $type ) = @_;
598
599         my( $bucket, $evt );
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';
604
605         $evt = $editor->event unless $bucket;
606         return ($bucket, $evt);
607 }
608
609
610
611
612
613 sub fetch_container_item {
614         my( $self, $id, $type ) = @_;
615         my( $bucket, $evt );
616
617         $logger->debug("Fetching container item $id with type $type");
618
619         my $meth = $buckets{$type} . "_item";
620
621         $bucket = $self->simplereq(
622                 'open-ils.cstore',
623                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
624
625
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';
630
631         $evt = OpenILS::Event->new(
632                 $e, itemid => $id, container_type => $type ) unless $bucket;
633
634         return ($bucket, $evt);
635 }
636
637
638 sub fetch_patron_standings {
639         my $self = shift;
640         $logger->debug("Fetching patron standings");    
641         return $self->simplereq(
642                 'open-ils.cstore', 
643                 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
644 }
645
646
647 sub fetch_permission_group_tree {
648         my $self = shift;
649         $logger->debug("Fetching patron profiles");     
650         return $self->simplereq(
651                 'open-ils.actor', 
652                 'open-ils.actor.groups.tree.retrieve' );
653 }
654
655
656 sub fetch_patron_circ_summary {
657         my( $self, $userid ) = @_;
658         $logger->debug("Fetching patron summary for $userid");
659         my $summary = $self->simplereq(
660                 'open-ils.storage', 
661                 "open-ils.storage.action.circulation.patron_summary", $userid );
662
663         if( $summary ) {
664                 $summary->[0] ||= 0;
665                 $summary->[1] ||= 0.0;
666                 return $summary;
667         }
668         return undef;
669 }
670
671
672 sub fetch_copy_statuses {
673         my( $self ) = @_;
674         $logger->debug("Fetching copy statuses");
675         return $self->simplereq(
676                 'open-ils.cstore', 
677                 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
678 }
679
680 sub fetch_copy_location {
681         my( $self, $id ) = @_;
682         my $evt;
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;
686         return ($cl, $evt);
687 }
688
689 sub fetch_copy_locations {
690         my $self = shift; 
691         return $self->simplereq(
692                 'open-ils.cstore', 
693                 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
694 }
695
696 sub fetch_copy_location_by_name {
697         my( $self, $name, $org ) = @_;
698         my $evt;
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;
703         return ($cl, $evt);
704 }
705
706 sub fetch_callnumber {
707         my( $self, $id ) = @_;
708         my $evt = undef;
709
710         my $e = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
711         return( undef, $e ) unless $id;
712
713         $logger->debug("Fetching callnumber $id");
714
715         my $cn = $self->simplereq(
716                 'open-ils.cstore',
717                 'open-ils.cstore.direct.asset.call_number.retrieve', $id );
718         $evt = $e  unless $cn;
719
720         return ( $cn, $evt );
721 }
722
723 my %ORG_CACHE; # - these rarely change, so cache them..
724 sub fetch_org_unit {
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");
730         my $evt = undef;
731
732         my $org = $self->simplereq(
733                 'open-ils.cstore', 
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;
737
738         return ($org, $evt);
739 }
740
741 sub fetch_stat_cat {
742         my( $self, $type, $id ) = @_;
743         my( $cat, $evt );
744         $logger->debug("Fetching $type stat cat: $id");
745         $cat = $self->simplereq(
746                 'open-ils.cstore', 
747                 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
748
749         my $e = 'ASSET_STAT_CAT_NOT_FOUND';
750         $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
751
752         $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
753         return ( $cat, $evt );
754 }
755
756 sub fetch_stat_cat_entry {
757         my( $self, $type, $id ) = @_;
758         my( $entry, $evt );
759         $logger->debug("Fetching $type stat cat entry: $id");
760         $entry = $self->simplereq(
761                 'open-ils.cstore', 
762                 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
763
764         my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
765         $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
766
767         $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
768         return ( $entry, $evt );
769 }
770
771
772 sub find_org {
773         my( $self, $org_tree, $orgid )  = @_;
774         if (!$org_tree) {
775                 $logger->warn("find_org() did not receive a value for \$org_tree");
776                 return undef;
777         } elsif (!$orgid) {
778                 $logger->warn("find_org() did not receive a value for \$orgid");
779                 return undef;
780     }
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);
785                 return $o if $o;
786         }
787         return undef;
788 }
789
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(
794                 'open-ils.cstore',
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') );
799 }
800
801 sub fetch_non_cat_type {
802         my( $self, $id ) = @_;
803         $logger->debug("Fetching non cat type $id");
804         my( $type, $evt );
805         $type = $self->simplereq(
806                 'open-ils.cstore', 
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);
810 }
811
812 sub DB_UPDATE_FAILED { 
813         my( $self, $payload ) = @_;
814         return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
815                 payload => ($payload) ? $payload : undef ); 
816 }
817
818 sub fetch_circ_duration_by_name {
819         my( $self, $name ) = @_;
820         my( $dur, $evt );
821         $dur = $self->simplereq(
822                 'open-ils.cstore', 
823                 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
824         $dur = $dur->[0];
825         $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
826         return ($dur, $evt);
827 }
828
829 sub fetch_recurring_fine_by_name {
830         my( $self, $name ) = @_;
831         my( $obj, $evt );
832         $obj = $self->simplereq(
833                 'open-ils.cstore', 
834                 'open-ils.cstore.direct.config.rules.recuring_fine.search.atomic', { name => $name } );
835         $obj = $obj->[0];
836         $evt = OpenILS::Event->new('CONFIG_RULES_RECURING_FINE_NOT_FOUND') unless $obj;
837         return ($obj, $evt);
838 }
839
840 sub fetch_max_fine_by_name {
841         my( $self, $name ) = @_;
842         my( $obj, $evt );
843         $obj = $self->simplereq(
844                 'open-ils.cstore', 
845                 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
846         $obj = $obj->[0];
847         $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
848         return ($obj, $evt);
849 }
850
851 sub storagereq {
852         my( $self, $method, @params ) = @_;
853         return $self->simplereq(
854                 'open-ils.storage', $method, @params );
855 }
856
857 sub cstorereq {
858         my( $self, $method, @params ) = @_;
859         return $self->simplereq(
860                 'open-ils.cstore', $method, @params );
861 }
862
863 sub event_equals {
864         my( $self, $e, $name ) =  @_;
865         if( $e and ref($e) eq 'HASH' and 
866                 defined($e->{textcode}) and $e->{textcode} eq $name ) {
867                 return 1 ;
868         }
869         return 0;
870 }
871
872 sub logmark {
873         my( undef, $f, $l ) = caller(0);
874         my( undef, undef, undef, $s ) = caller(1);
875         $s =~ s/.*:://g;
876         $f =~ s/.*\///g;
877         $logger->debug("LOGMARK: $f:$l:$s");
878 }
879
880 # takes a copy id 
881 sub fetch_open_circulation {
882         my( $self, $cid ) = @_;
883         my $evt;
884         $self->logmark;
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);
890 }
891
892 sub fetch_all_open_circulation {
893         my( $self, $cid ) = @_;
894         my $evt;
895         $self->logmark;
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);
901 }
902
903 my $copy_statuses;
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 );
909         }
910         return undef;
911 }
912
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 );
918         }
919         return undef;
920 }
921
922
923 sub copy_status {
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;
928         return $stat;
929 }
930
931 sub fetch_open_transit_by_copy {
932         my( $self, $copyid ) = @_;
933         my($transit, $evt);
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);
939 }
940
941 sub unflesh_copy {
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);
947         return $copy;
948 }
949
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
953 sub update_copy {
954         my( $self, %params ) = @_;
955
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};
959
960         $logger->debug("Updating copy in the database: " . $copy->id);
961
962         $self->unflesh_copy($copy);
963         $copy->editor( $editor );
964         $copy->edit_date( 'now' );
965
966         my $s;
967         my $meth = 'open-ils.storage.direct.asset.copy.update';
968
969         $s = $session->request( $meth, $copy )->gather(1) if $session;
970         $s = $self->storagereq( $meth, $copy ) unless $session;
971
972         $logger->debug("Update of copy ".$copy->id." returned: $s");
973
974         return $self->DB_UPDATE_FAILED($copy) unless $s;
975         return undef;
976 }
977
978 sub fetch_billable_xact {
979         my( $self, $id ) = @_;
980         my($xact, $evt);
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);
986 }
987
988 sub fetch_billable_xact_summary {
989         my( $self, $id ) = @_;
990         my($xact, $evt);
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);
996 }
997
998 sub fetch_fleshed_copy {
999         my( $self, $id ) = @_;
1000         my( $copy, $evt );
1001         $logger->info("Fetching fleshed copy $id");
1002         $copy = $self->cstorereq(
1003                 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1004                 { flesh => 1,
1005                   flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1006                 }
1007         );
1008         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1009         return ($copy, $evt);
1010 }
1011
1012
1013 # returns the org that owns the callnumber that the copy
1014 # is attached to
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);
1024 }
1025
1026 sub fetch_copy_note {
1027         my( $self, $id ) = @_;
1028         my( $note, $evt );
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);
1034 }
1035
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);
1043 }
1044
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 );
1051 }
1052
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;
1061         return ($user);
1062         
1063 }
1064
1065
1066 # ---------------------------------------------------------------------
1067 # Updates and returns the patron penalties
1068 # ---------------------------------------------------------------------
1069 sub update_patron_penalties {
1070         my( $self, %args ) = @_;
1071         return $self->simplereq(
1072                 'open-ils.penalty',
1073                 'open-ils.penalty.patron_penalty.calculate', 
1074                 { update => 1, %args }
1075         );
1076 }
1077
1078 sub fetch_bill {
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);
1085 }
1086
1087
1088
1089 my $ORG_TREE;
1090 sub fetch_org_tree {
1091         my $self = shift;
1092         return $ORG_TREE if $ORG_TREE;
1093         return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit( 
1094                 [
1095                         {"parent_ou" => undef },
1096                         {
1097                                 flesh                           => 2,
1098                                 flesh_fields    => { aou =>  ['children'] },
1099                                 order_by       => { aou => 'name'}
1100                         }
1101                 ]
1102         )->[0];
1103 }
1104
1105 sub walk_org_tree {
1106         my( $self, $node, $callback ) = @_;
1107         return unless $node;
1108         $callback->($node);
1109         if( $node->children ) {
1110                 $self->walk_org_tree($_, $callback) for @{$node->children};
1111         }
1112 }
1113
1114 sub is_true {
1115         my( $self, $item ) = @_;
1116         return 1 if $item and $item !~ /^f$/i;
1117         return 0;
1118 }
1119
1120
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 } );
1128
1129         my $total = 0;
1130         my $data;
1131         while( $data = $req->recv ) {
1132                 $data = $data->content;
1133                 $total += $data->balance_owed;
1134         }
1135         return $total;
1136 }
1137
1138 sub patron_money_owed {
1139         my( $self, $userid ) = @_;
1140         return $self->storagereq(
1141                 'open-ils.storage.actor.user.total_owed', $userid);
1142 }
1143
1144 sub patron_total_items_out {
1145         my( $self, $userid ) = @_;
1146         return $self->storagereq(
1147                 'open-ils.storage.actor.user.total_out', $userid);
1148 }
1149
1150
1151
1152
1153 #---------------------------------------------------------------------
1154 # Returns  ($summary, $event) 
1155 #---------------------------------------------------------------------
1156 sub fetch_mbts {
1157         my $self = shift;
1158         my $id  = shift;
1159         my $editor = shift || OpenILS::Utils::CStoreEditor->new;
1160
1161         $id = $id->id if (ref($id));
1162
1163         my $xact = $editor->retrieve_money_billable_transaction(
1164                 [
1165                         $id, {  
1166                                 flesh => 1, 
1167                                 flesh_fields => { mbt => [ qw/billings payments grocery circulation/ ] } 
1168                         }
1169                 ]
1170         ) or return (undef, $editor->event);
1171
1172         return $self->make_mbts($xact);
1173 }
1174
1175
1176 #---------------------------------------------------------------------
1177 # Given a list of money.billable_transaction objects, this creates
1178 # transaction summary objects for each
1179 #--------------------------------------------------------------------
1180 sub make_mbts {
1181         my $self = shift;
1182         my @xacts = @_;
1183
1184         my @mbts;
1185         for my $x (@xacts) {
1186
1187                 my $s = new Fieldmapper::money::billable_transaction_summary;
1188
1189                 $s->id( $x->id );
1190                 $s->usr( $x->usr );
1191                 $s->xact_start( $x->xact_start );
1192                 $s->xact_finish( $x->xact_finish );
1193                 
1194                 my $to = 0;
1195                 my $lb = undef;
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);
1205                         }
1206                 }
1207
1208                 $s->total_owed( sprintf('%0.2f', $to / 100 ) );
1209                 
1210                 my $tp = 0;
1211                 my $lp = undef;
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);
1221                         }
1222                 }
1223
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);
1228
1229                 $logger->debug("Created mbts with balance_owed = ". $s->balance_owed);
1230                 
1231                 push @mbts, $s;
1232         }
1233                 
1234         return @mbts;
1235 }
1236                 
1237                 
1238 sub ou_ancestor_setting_value {
1239     my $obj = ou_ancestor_setting(@_);
1240     return ($obj) ? $obj->{value} : undef;
1241 }
1242
1243 sub ou_ancestor_setting {
1244     my( $self, $orgid, $name, $e ) = @_;
1245     $e = $e || OpenILS::Utils::CStoreEditor->new;
1246
1247     do {
1248         my $setting = $e->search_actor_org_unit_setting({org_unit=>$orgid, name=>$name})->[0];
1249
1250         if( $setting ) {
1251             $logger->info("found org_setting $name at org $orgid : " . $setting->value);
1252             return { org => $orgid, value => OpenSRF::Utils::JSON->JSON2perl($setting->value) };
1253         }
1254
1255         my $org = $e->retrieve_actor_org_unit($orgid) or return $e->event;
1256         $orgid = $org->parent_ou or return undef;
1257
1258     } while(1);
1259
1260     return undef;
1261 }       
1262                 
1263
1264 # returns the ISO8601 string representation of the requested epoch in GMT
1265 sub epoch2ISO8601 {
1266     my( $self, $epoch ) = @_;
1267     my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1268     $year += 1900; $mon += 1;
1269     my $date = sprintf(
1270         '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1271         $year, $mon, $mday, $hour, $min, $sec);
1272     return $date;
1273 }
1274                         
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 );
1278
1279         my $lastid = -1;
1280         while( $org ) {
1281                 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1282                 $lastid = $org->id;
1283                 $org = $self->find_org( $org_tree, $org->parent_ou() );
1284         }
1285
1286         return $lastid;
1287 }
1288
1289
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");
1294
1295     my @allowed_orgs;
1296         my $org_tree = $self->get_org_tree();
1297     my $org_types = $self->get_org_types();
1298
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");
1304
1305     
1306     return [] if $high_org_id == -1; # not allowed anywhere
1307
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;
1311
1312         if($$options{descendants}) {
1313                 push(@allowed_orgs, @{$self->get_org_descendants($high_org_id, $org_depth)});
1314         } else {
1315                 push(@allowed_orgs, $high_org_id);
1316         }
1317
1318         return \@allowed_orgs if $org_depth == 0;
1319
1320     for my $org (@$work_orgs) {
1321
1322         $logger->debug("work org looking at $org");
1323                 my $org_list = $self->get_org_full_path($org, $org_depth);
1324
1325                 my $found = 0;
1326         for my $sub_org (@$org_list) {
1327                         if(not $found) {
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);
1333                                         $found = 1;
1334                                 }
1335                         } else {
1336                                 last unless $$options{descendants}; 
1337                                 push(@allowed_orgs, $sub_org);
1338                         }
1339         }
1340     }
1341
1342     my %de_dupe;
1343     $de_dupe{$_} = 1 for @allowed_orgs;
1344     return [keys %de_dupe];
1345 }
1346
1347
1348 sub get_user_work_ou_ids {
1349     my($self, $e, $userid) = @_;
1350     my $work_orgs = $e->json_query({
1351         select => {puwoum => ['work_ou']},
1352         from => 'puwoum',
1353         where => {usr => $e->requestor->id}});
1354
1355     return [] unless @$work_orgs;
1356     my @work_orgs;
1357     push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1358
1359     return \@work_orgs;
1360 }
1361
1362
1363 my $org_types;
1364 sub get_org_types {
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();
1368 }
1369
1370 sub get_org_tree {
1371         my $cache = OpenSRF::Utils::Cache->new("global", 0);
1372         my $tree = $cache->get_cache('orgtree');
1373         return $tree if $tree;
1374
1375         $tree = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit( 
1376                 [
1377                         {"parent_ou" => undef },
1378                         {
1379                                 flesh                           => -1,
1380                                 flesh_fields    => { aou =>  ['children'] },
1381                                 order_by                        => { aou => 'name'}
1382                         }
1383                 ]
1384         )->[0];
1385
1386         $cache->put_cache('orgtree', $tree);
1387         return $tree;
1388 }
1389
1390 sub get_org_descendants {
1391         my($self, $org_id, $depth) = @_;
1392
1393         my $select = {
1394                 transform => 'actor.org_unit_descendants',
1395                 column => 'id',
1396                 result_field => 'id',
1397         };
1398         $select->{params} = [$depth] if defined $depth;
1399
1400         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1401                 select => {aou => [$select]},
1402         from => 'aou',
1403                 where => {id => $org_id}
1404         });
1405         my @orgs;
1406         push(@orgs, $_->{id}) for @$org_list;
1407         return \@orgs;
1408 }
1409
1410 sub get_org_ancestors {
1411         my($self, $org_id, $depth) = @_;
1412         $depth ||= 0;
1413
1414         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1415                 select => {
1416                         aou => [{
1417                                 transform => 'actor.org_unit_ancestors',
1418                                 column => 'id',
1419                                 result_field => 'id',
1420                                 params => [$depth]
1421                         }],
1422                 },
1423                 from => 'aou',
1424                 where => {id => $org_id}
1425         });
1426
1427         my @orgs;
1428         push(@orgs, $_->{id}) for @$org_list;
1429         return \@orgs;
1430 }
1431
1432 sub get_org_full_path {
1433         my($self, $org_id, $depth) = @_;
1434         $depth ||= 0;
1435
1436         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1437                 select => {
1438                         aou => [{
1439                                 transform => 'actor.org_unit_full_path',
1440                                 column => 'id',
1441                                 result_field => 'id',
1442                                 params => [$depth]
1443                         }],
1444                 },
1445                 from => 'aou',
1446                 where => {id => $org_id}
1447         });
1448
1449         my @orgs;
1450         push(@orgs, $_->{id}) for @$org_list;
1451         return \@orgs;
1452 }
1453
1454 1;
1455