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