]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/AppUtils.pm
Added a stored procedure to find the first occurrence of an org-unit setting for...
[working/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 use OpenSRF::Utils::SettingsClient;
16
17 # ---------------------------------------------------------------------------
18 # Pile of utilty methods used accross applications.
19 # ---------------------------------------------------------------------------
20 my $cache_client = "OpenSRF::Utils::Cache";
21
22
23 # ---------------------------------------------------------------------------
24 # on sucess, returns the created session, on failure throws ERROR exception
25 # ---------------------------------------------------------------------------
26 sub start_db_session {
27
28         my $self = shift;
29         my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
30         my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
31
32         my $trans_resp = $trans_req->recv();
33         if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
34         if( ! $trans_resp->content() ) {
35                 throw OpenSRF::ERROR 
36                         ("Unable to Begin Transaction with database" );
37         }
38         $trans_req->finish();
39
40         $logger->debug("Setting global storage session to ".
41                 "session: " . $session->session_id . " : " . $session->app );
42
43         return $session;
44 }
45
46 my $PERM_QUERY = {
47     select => {
48         au => [ {
49             transform => 'permission.usr_has_perm',
50             alias => 'has_perm',
51             column => 'id',
52             params => []
53         } ]
54     },
55     from => 'au',
56     where => {},
57 };
58
59
60 # returns undef if user has all of the perms provided
61 # returns the first failed perm on failure
62 sub check_user_perms {
63         my($self, $user_id, $org_id, @perm_types ) = @_;
64         $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
65
66         for my $type (@perm_types) {
67             $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
68                 $PERM_QUERY->{where}->{id} = $user_id;
69                 return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
70         }
71         return undef;
72 }
73
74 # checks the list of user perms.  The first one that fails returns a new
75 sub check_perms {
76         my( $self, $user_id, $org_id, @perm_types ) = @_;
77         my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
78         return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
79         return undef;
80 }
81
82
83
84 # ---------------------------------------------------------------------------
85 # commits and destroys the session
86 # ---------------------------------------------------------------------------
87 sub commit_db_session {
88         my( $self, $session ) = @_;
89
90         my $req = $session->request( "open-ils.storage.transaction.commit" );
91         my $resp = $req->recv();
92
93         if(!$resp) {
94                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
95         }
96
97         if(UNIVERSAL::isa($resp,"Error")) { 
98                 throw $resp ($resp->stringify); 
99         }
100
101         if(!$resp->content) {
102                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
103         }
104
105         $session->finish();
106         $session->disconnect();
107         $session->kill_me();
108 }
109
110 sub rollback_db_session {
111         my( $self, $session ) = @_;
112
113         my $req = $session->request("open-ils.storage.transaction.rollback");
114         my $resp = $req->recv();
115         if(UNIVERSAL::isa($resp,"Error")) { throw $resp;  }
116
117         $session->finish();
118         $session->disconnect();
119         $session->kill_me();
120 }
121
122
123 # returns undef it the event is not an ILS event
124 # returns the event code otherwise
125 sub event_code {
126         my( $self, $evt ) = @_;
127         return $evt->{ilsevent} if( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
128         return undef;
129 }
130
131 # ---------------------------------------------------------------------------
132 # Checks to see if a user is logged in.  Returns the user record on success,
133 # throws an exception on error.
134 # ---------------------------------------------------------------------------
135 sub check_user_session {
136
137         my( $self, $user_session ) = @_;
138
139         my $content = $self->simplereq( 
140                 'open-ils.auth', 
141                 'open-ils.auth.session.retrieve', $user_session );
142
143         if(! $content or $self->event_code($content)) {
144                 throw OpenSRF::EX::ERROR 
145                         ("Session [$user_session] cannot be authenticated" );
146         }
147
148         $logger->debug("Fetch user session $user_session found user " . $content->id );
149
150         return $content;
151 }
152
153 # generic simple request returning a scalar value
154 sub simplereq {
155         my($self, $service, $method, @params) = @_;
156         return $self->simple_scalar_request($service, $method, @params);
157 }
158
159
160 sub simple_scalar_request {
161         my($self, $service, $method, @params) = @_;
162
163         my $session = OpenSRF::AppSession->create( $service );
164
165         my $request = $session->request( $method, @params );
166
167         my $val;
168         my $err;
169         try  {
170
171                 $val = $request->gather(1);     
172
173         } catch Error with {
174                 $err = shift;
175         };
176
177         if( $err ) {
178                 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
179                 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
180         }
181
182         return $val;
183 }
184
185
186
187
188
189 my $tree                                                = undef;
190 my $orglist                                     = undef;
191 my $org_typelist                        = undef;
192 my $org_typelist_hash   = {};
193
194 sub __get_org_tree {
195         
196         # can we throw this version away??
197
198         my $self = shift;
199         if($tree) { return $tree; }
200
201         # see if it's in the cache
202         $tree = $cache_client->new()->get_cache('_orgtree');
203         if($tree) { return $tree; }
204
205         if(!$orglist) {
206                 warn "Retrieving Org Tree\n";
207                 $orglist = $self->simple_scalar_request( 
208                         "open-ils.cstore", 
209                         "open-ils.cstore.direct.actor.org_unit.search.atomic",
210                         { id => { '!=' => undef } }
211                 );
212         }
213
214         if( ! $org_typelist ) {
215                 warn "Retrieving org types\n";
216                 $org_typelist = $self->simple_scalar_request( 
217                         "open-ils.cstore", 
218                         "open-ils.cstore.direct.actor.org_unit_type.search.atomic",
219                         { id => { '!=' => undef } }
220                 );
221                 $self->build_org_type($org_typelist);
222         }
223
224         $tree = $self->build_org_tree($orglist,1);
225         $cache_client->new()->put_cache('_orgtree', $tree);
226         return $tree;
227
228 }
229
230 my $slimtree = undef;
231 sub get_slim_org_tree {
232
233         my $self = shift;
234         if($slimtree) { return $slimtree; }
235
236         # see if it's in the cache
237         $slimtree = $cache_client->new()->get_cache('slimorgtree');
238         if($slimtree) { return $slimtree; }
239
240         if(!$orglist) {
241                 warn "Retrieving Org Tree\n";
242                 $orglist = $self->simple_scalar_request( 
243                         "open-ils.cstore", 
244                         "open-ils.cstore.direct.actor.org_unit.search.atomic",
245                         { id => { '!=' => undef } }
246                 );
247         }
248
249         $slimtree = $self->build_org_tree($orglist);
250         $cache_client->new->put_cache('slimorgtree', $slimtree);
251         return $slimtree;
252
253 }
254
255
256 sub build_org_type { 
257         my($self, $org_typelist)  = @_;
258         for my $type (@$org_typelist) {
259                 $org_typelist_hash->{$type->id()} = $type;
260         }
261 }
262
263
264
265 sub build_org_tree {
266
267         my( $self, $orglist, $add_types ) = @_;
268
269         return $orglist unless ref $orglist; 
270     return $$orglist[0] if @$orglist == 1;
271
272         my @list = sort { 
273                 $a->ou_type <=> $b->ou_type ||
274                 $a->name cmp $b->name } @$orglist;
275
276         for my $org (@list) {
277
278                 next unless ($org);
279
280                 if(!ref($org->ou_type()) and $add_types) {
281                         $org->ou_type( $org_typelist_hash->{$org->ou_type()});
282                 }
283
284                 next unless (defined($org->parent_ou));
285
286                 my ($parent) = grep { $_->id == $org->parent_ou } @list;
287                 next unless $parent;
288                 $parent->children([]) unless defined($parent->children); 
289                 push( @{$parent->children}, $org );
290         }
291
292         return $list[0];
293 }
294
295 sub fetch_closed_date {
296         my( $self, $cd ) = @_;
297         my $evt;
298         
299         $logger->debug("Fetching closed_date $cd from cstore");
300
301         my $cd_obj = $self->simplereq(
302                 'open-ils.cstore',
303                 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
304
305         if(!$cd_obj) {
306                 $logger->info("closed_date $cd not found in the db");
307                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
308         }
309
310         return ($cd_obj, $evt);
311 }
312
313 sub fetch_user {
314         my( $self, $userid ) = @_;
315         my( $user, $evt );
316         
317         $logger->debug("Fetching user $userid from cstore");
318
319         $user = $self->simplereq(
320                 'open-ils.cstore',
321                 'open-ils.cstore.direct.actor.user.retrieve', $userid );
322
323         if(!$user) {
324                 $logger->info("User $userid not found in the db");
325                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
326         }
327
328         return ($user, $evt);
329 }
330
331 sub checkses {
332         my( $self, $session ) = @_;
333         my $user; my $evt; my $e; 
334
335         $logger->debug("Checking user session $session");
336
337         try {
338                 $user = $self->check_user_session($session);
339         } catch Error with { $e = 1; };
340
341         $logger->debug("Done checking user session $session " . (($e) ? "error = $e" : "") );
342
343         if( $e or !$user ) { $evt = OpenILS::Event->new('NO_SESSION'); }
344         return ( $user, $evt );
345 }
346
347
348 # verifiese the session and checks the permissions agains the
349 # session user and the user's home_ou as the org id
350 sub checksesperm {
351         my( $self, $session, @perms ) = @_;
352         my $user; my $evt; my $e; 
353         $logger->debug("Checking user session $session and perms @perms");
354         ($user, $evt) = $self->checkses($session);
355         return (undef, $evt) if $evt;
356         $evt = $self->check_perms($user->id, $user->home_ou, @perms);
357         return ($user, $evt);
358 }
359
360
361 sub checkrequestor {
362         my( $self, $staffobj, $userid, @perms ) = @_;
363         my $user; my $evt;
364         $userid = $staffobj->id unless defined $userid;
365
366         $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
367
368         if( $userid ne $staffobj->id ) {
369                 ($user, $evt) = $self->fetch_user($userid);
370                 return (undef, $evt) if $evt;
371                 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
372
373         } else {
374                 $user = $staffobj;
375         }
376
377         return ($user, $evt);
378 }
379
380 sub checkses_requestor {
381         my( $self, $authtoken, $targetid, @perms ) = @_;
382         my( $requestor, $target, $evt );
383
384         ($requestor, $evt) = $self->checkses($authtoken);
385         return (undef, undef, $evt) if $evt;
386
387         ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
388         return( $requestor, $target, $evt);
389 }
390
391 sub fetch_copy {
392         my( $self, $copyid ) = @_;
393         my( $copy, $evt );
394
395         $logger->debug("Fetching copy $copyid from cstore");
396
397         $copy = $self->simplereq(
398                 'open-ils.cstore',
399                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
400
401         if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
402
403         return( $copy, $evt );
404 }
405
406
407 # retrieves a circ object by id
408 sub fetch_circulation {
409         my( $self, $circid ) = @_;
410         my $circ; my $evt;
411         
412         $logger->debug("Fetching circ $circid from cstore");
413
414         $circ = $self->simplereq(
415                 'open-ils.cstore',
416                 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
417
418         if(!$circ) {
419                 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
420         }
421
422         return ( $circ, $evt );
423 }
424
425 sub fetch_record_by_copy {
426         my( $self, $copyid ) = @_;
427         my( $record, $evt );
428
429         $logger->debug("Fetching record by copy $copyid from cstore");
430
431         $record = $self->simplereq(
432                 'open-ils.cstore',
433                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
434                 { flesh => 3,
435                   flesh_fields => {     bre => [ 'fixed_fields' ],
436                                         acn => [ 'record' ],
437                                         acp => [ 'call_number' ],
438                                   }
439                 }
440         );
441
442         if(!$record) {
443                 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
444         } else {
445                 $record = $record->call_number->record;
446         }
447
448         return ($record, $evt);
449 }
450
451 # turns a record object into an mvr (mods) object
452 sub record_to_mvr {
453         my( $self, $record ) = @_;
454         return undef unless $record and $record->marc;
455         my $u = OpenILS::Utils::ModsParser->new();
456         $u->start_mods_batch( $record->marc );
457         my $mods = $u->finish_mods_batch();
458         $mods->doc_id($record->id);
459    $mods->tcn($record->tcn_value);
460         return $mods;
461 }
462
463 sub fetch_hold {
464         my( $self, $holdid ) = @_;
465         my( $hold, $evt );
466
467         $logger->debug("Fetching hold $holdid from cstore");
468
469         $hold = $self->simplereq(
470                 'open-ils.cstore',
471                 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
472
473         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
474
475         return ($hold, $evt);
476 }
477
478
479 sub fetch_hold_transit_by_hold {
480         my( $self, $holdid ) = @_;
481         my( $transit, $evt );
482
483         $logger->debug("Fetching transit by hold $holdid from cstore");
484
485         $transit = $self->simplereq(
486                 'open-ils.cstore',
487                 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
488
489         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
490
491         return ($transit, $evt );
492 }
493
494 # fetches the captured, but not fulfilled hold attached to a given copy
495 sub fetch_open_hold_by_copy {
496         my( $self, $copyid ) = @_;
497         $logger->debug("Searching for active hold for copy $copyid");
498         my( $hold, $evt );
499
500         $hold = $self->cstorereq(
501                 'open-ils.cstore.direct.action.hold_request.search',
502                 { 
503                         current_copy            => $copyid , 
504                         capture_time            => { "!=" => undef }, 
505                         fulfillment_time        => undef,
506                         cancel_time                     => undef,
507                 } );
508
509         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
510         return ($hold, $evt);
511 }
512
513 sub fetch_hold_transit {
514         my( $self, $transid ) = @_;
515         my( $htransit, $evt );
516         $logger->debug("Fetching hold transit with hold id $transid");
517         $htransit = $self->cstorereq(
518                 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
519         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
520         return ($htransit, $evt);
521 }
522
523 sub fetch_copy_by_barcode {
524         my( $self, $barcode ) = @_;
525         my( $copy, $evt );
526
527         $logger->debug("Fetching copy by barcode $barcode from cstore");
528
529         $copy = $self->simplereq( 'open-ils.cstore',
530                 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
531                 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
532
533         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
534
535         return ($copy, $evt);
536 }
537
538 sub fetch_open_billable_transaction {
539         my( $self, $transid ) = @_;
540         my( $transaction, $evt );
541
542         $logger->debug("Fetching open billable transaction $transid from cstore");
543
544         $transaction = $self->simplereq(
545                 'open-ils.cstore',
546                 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve',  $transid);
547
548         $evt = OpenILS::Event->new(
549                 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
550
551         return ($transaction, $evt);
552 }
553
554
555
556 my %buckets;
557 $buckets{'biblio'} = 'biblio_record_entry_bucket';
558 $buckets{'callnumber'} = 'call_number_bucket';
559 $buckets{'copy'} = 'copy_bucket';
560 $buckets{'user'} = 'user_bucket';
561
562 sub fetch_container {
563         my( $self, $id, $type ) = @_;
564         my( $bucket, $evt );
565
566         $logger->debug("Fetching container $id with type $type");
567
568         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
569         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
570         $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
571         $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
572
573         my $meth = $buckets{$type};
574         $bucket = $self->simplereq(
575                 'open-ils.cstore',
576                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
577
578         $evt = OpenILS::Event->new(
579                 $e, container => $id, container_type => $type ) unless $bucket;
580
581         return ($bucket, $evt);
582 }
583
584
585 sub fetch_container_e {
586         my( $self, $editor, $id, $type ) = @_;
587
588         my( $bucket, $evt );
589         $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
590         $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
591         $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
592         $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
593
594         $evt = $editor->event unless $bucket;
595         return ($bucket, $evt);
596 }
597
598 sub fetch_container_item_e {
599         my( $self, $editor, $id, $type ) = @_;
600
601         my( $bucket, $evt );
602         $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
603         $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
604         $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
605         $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
606
607         $evt = $editor->event unless $bucket;
608         return ($bucket, $evt);
609 }
610
611
612
613
614
615 sub fetch_container_item {
616         my( $self, $id, $type ) = @_;
617         my( $bucket, $evt );
618
619         $logger->debug("Fetching container item $id with type $type");
620
621         my $meth = $buckets{$type} . "_item";
622
623         $bucket = $self->simplereq(
624                 'open-ils.cstore',
625                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
626
627
628         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
629         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
630         $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
631         $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
632
633         $evt = OpenILS::Event->new(
634                 $e, itemid => $id, container_type => $type ) unless $bucket;
635
636         return ($bucket, $evt);
637 }
638
639
640 sub fetch_patron_standings {
641         my $self = shift;
642         $logger->debug("Fetching patron standings");    
643         return $self->simplereq(
644                 'open-ils.cstore', 
645                 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
646 }
647
648
649 sub fetch_permission_group_tree {
650         my $self = shift;
651         $logger->debug("Fetching patron profiles");     
652         return $self->simplereq(
653                 'open-ils.actor', 
654                 'open-ils.actor.groups.tree.retrieve' );
655 }
656
657
658 sub fetch_patron_circ_summary {
659         my( $self, $userid ) = @_;
660         $logger->debug("Fetching patron summary for $userid");
661         my $summary = $self->simplereq(
662                 'open-ils.storage', 
663                 "open-ils.storage.action.circulation.patron_summary", $userid );
664
665         if( $summary ) {
666                 $summary->[0] ||= 0;
667                 $summary->[1] ||= 0.0;
668                 return $summary;
669         }
670         return undef;
671 }
672
673
674 sub fetch_copy_statuses {
675         my( $self ) = @_;
676         $logger->debug("Fetching copy statuses");
677         return $self->simplereq(
678                 'open-ils.cstore', 
679                 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
680 }
681
682 sub fetch_copy_location {
683         my( $self, $id ) = @_;
684         my $evt;
685         my $cl = $self->cstorereq(
686                 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
687         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
688         return ($cl, $evt);
689 }
690
691 sub fetch_copy_locations {
692         my $self = shift; 
693         return $self->simplereq(
694                 'open-ils.cstore', 
695                 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
696 }
697
698 sub fetch_copy_location_by_name {
699         my( $self, $name, $org ) = @_;
700         my $evt;
701         my $cl = $self->cstorereq(
702                 'open-ils.cstore.direct.asset.copy_location.search',
703                         { name => $name, owning_lib => $org } );
704         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
705         return ($cl, $evt);
706 }
707
708 sub fetch_callnumber {
709         my( $self, $id ) = @_;
710         my $evt = undef;
711
712         my $e = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
713         return( undef, $e ) unless $id;
714
715         $logger->debug("Fetching callnumber $id");
716
717         my $cn = $self->simplereq(
718                 'open-ils.cstore',
719                 'open-ils.cstore.direct.asset.call_number.retrieve', $id );
720         $evt = $e  unless $cn;
721
722         return ( $cn, $evt );
723 }
724
725 my %ORG_CACHE; # - these rarely change, so cache them..
726 sub fetch_org_unit {
727         my( $self, $id ) = @_;
728         return undef unless $id;
729         return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
730         return $ORG_CACHE{$id} if $ORG_CACHE{$id};
731         $logger->debug("Fetching org unit $id");
732         my $evt = undef;
733
734         my $org = $self->simplereq(
735                 'open-ils.cstore', 
736                 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
737         $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
738         $ORG_CACHE{$id}  = $org;
739
740         return ($org, $evt);
741 }
742
743 sub fetch_stat_cat {
744         my( $self, $type, $id ) = @_;
745         my( $cat, $evt );
746         $logger->debug("Fetching $type stat cat: $id");
747         $cat = $self->simplereq(
748                 'open-ils.cstore', 
749                 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
750
751         my $e = 'ASSET_STAT_CAT_NOT_FOUND';
752         $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
753
754         $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
755         return ( $cat, $evt );
756 }
757
758 sub fetch_stat_cat_entry {
759         my( $self, $type, $id ) = @_;
760         my( $entry, $evt );
761         $logger->debug("Fetching $type stat cat entry: $id");
762         $entry = $self->simplereq(
763                 'open-ils.cstore', 
764                 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
765
766         my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
767         $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
768
769         $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
770         return ( $entry, $evt );
771 }
772
773
774 sub find_org {
775         my( $self, $org_tree, $orgid )  = @_;
776         if (!$org_tree) {
777                 $logger->warn("find_org() did not receive a value for \$org_tree");
778                 return undef;
779         } elsif (!$orgid) {
780                 $logger->warn("find_org() did not receive a value for \$orgid");
781                 return undef;
782     }
783         return $org_tree if ( $org_tree->id eq $orgid );
784         return undef unless ref($org_tree->children);
785         for my $c (@{$org_tree->children}) {
786                 my $o = $self->find_org($c, $orgid);
787                 return $o if $o;
788         }
789         return undef;
790 }
791
792 sub fetch_non_cat_type_by_name_and_org {
793         my( $self, $name, $orgId ) = @_;
794         $logger->debug("Fetching non cat type $name at org $orgId");
795         my $types = $self->simplereq(
796                 'open-ils.cstore',
797                 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
798                 { name => $name, owning_lib => $orgId } );
799         return ($types->[0], undef) if($types and @$types);
800         return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
801 }
802
803 sub fetch_non_cat_type {
804         my( $self, $id ) = @_;
805         $logger->debug("Fetching non cat type $id");
806         my( $type, $evt );
807         $type = $self->simplereq(
808                 'open-ils.cstore', 
809                 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
810         $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
811         return ($type, $evt);
812 }
813
814 sub DB_UPDATE_FAILED { 
815         my( $self, $payload ) = @_;
816         return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
817                 payload => ($payload) ? $payload : undef ); 
818 }
819
820 sub fetch_circ_duration_by_name {
821         my( $self, $name ) = @_;
822         my( $dur, $evt );
823         $dur = $self->simplereq(
824                 'open-ils.cstore', 
825                 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
826         $dur = $dur->[0];
827         $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
828         return ($dur, $evt);
829 }
830
831 sub fetch_recurring_fine_by_name {
832         my( $self, $name ) = @_;
833         my( $obj, $evt );
834         $obj = $self->simplereq(
835                 'open-ils.cstore', 
836                 'open-ils.cstore.direct.config.rules.recuring_fine.search.atomic', { name => $name } );
837         $obj = $obj->[0];
838         $evt = OpenILS::Event->new('CONFIG_RULES_RECURING_FINE_NOT_FOUND') unless $obj;
839         return ($obj, $evt);
840 }
841
842 sub fetch_max_fine_by_name {
843         my( $self, $name ) = @_;
844         my( $obj, $evt );
845         $obj = $self->simplereq(
846                 'open-ils.cstore', 
847                 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
848         $obj = $obj->[0];
849         $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
850         return ($obj, $evt);
851 }
852
853 sub storagereq {
854         my( $self, $method, @params ) = @_;
855         return $self->simplereq(
856                 'open-ils.storage', $method, @params );
857 }
858
859 sub cstorereq {
860         my( $self, $method, @params ) = @_;
861         return $self->simplereq(
862                 'open-ils.cstore', $method, @params );
863 }
864
865 sub event_equals {
866         my( $self, $e, $name ) =  @_;
867         if( $e and ref($e) eq 'HASH' and 
868                 defined($e->{textcode}) and $e->{textcode} eq $name ) {
869                 return 1 ;
870         }
871         return 0;
872 }
873
874 sub logmark {
875         my( undef, $f, $l ) = caller(0);
876         my( undef, undef, undef, $s ) = caller(1);
877         $s =~ s/.*:://g;
878         $f =~ s/.*\///g;
879         $logger->debug("LOGMARK: $f:$l:$s");
880 }
881
882 # takes a copy id 
883 sub fetch_open_circulation {
884         my( $self, $cid ) = @_;
885         my $evt;
886         $self->logmark;
887         my $circ = $self->cstorereq(
888                 'open-ils.cstore.direct.action.open_circulation.search',
889                 { target_copy => $cid, stop_fines_time => undef } );
890         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
891         return ($circ, $evt);
892 }
893
894 sub fetch_all_open_circulation {
895         my( $self, $cid ) = @_;
896         my $evt;
897         $self->logmark;
898         my $circ = $self->cstorereq(
899                 'open-ils.cstore.direct.action.open_circulation.search',
900                 { target_copy => $cid, xact_finish => undef } );
901         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
902         return ($circ, $evt);
903 }
904
905 my $copy_statuses;
906 sub copy_status_from_name {
907         my( $self, $name ) = @_;
908         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
909         for my $status (@$copy_statuses) { 
910                 return $status if( $status->name =~ /$name/i );
911         }
912         return undef;
913 }
914
915 sub copy_status_to_name {
916         my( $self, $sid ) = @_;
917         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
918         for my $status (@$copy_statuses) { 
919                 return $status->name if( $status->id == $sid );
920         }
921         return undef;
922 }
923
924
925 sub copy_status {
926         my( $self, $arg ) = @_;
927         return $arg if ref $arg;
928         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
929         my ($stat) = grep { $_->id == $arg } @$copy_statuses;
930         return $stat;
931 }
932
933 sub fetch_open_transit_by_copy {
934         my( $self, $copyid ) = @_;
935         my($transit, $evt);
936         $transit = $self->cstorereq(
937                 'open-ils.cstore.direct.action.transit_copy.search',
938                 { target_copy => $copyid, dest_recv_time => undef });
939         $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
940         return ($transit, $evt);
941 }
942
943 sub unflesh_copy {
944         my( $self, $copy ) = @_;
945         return undef unless $copy;
946         $copy->status( $copy->status->id ) if ref($copy->status);
947         $copy->location( $copy->location->id ) if ref($copy->location);
948         $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
949         return $copy;
950 }
951
952 # un-fleshes a copy and updates it in the DB
953 # returns a DB_UPDATE_FAILED event on error
954 # returns undef on success
955 sub update_copy {
956         my( $self, %params ) = @_;
957
958         my $copy                = $params{copy} || die "update_copy(): copy required";
959         my $editor      = $params{editor} || die "update_copy(): copy editor required";
960         my $session = $params{session};
961
962         $logger->debug("Updating copy in the database: " . $copy->id);
963
964         $self->unflesh_copy($copy);
965         $copy->editor( $editor );
966         $copy->edit_date( 'now' );
967
968         my $s;
969         my $meth = 'open-ils.storage.direct.asset.copy.update';
970
971         $s = $session->request( $meth, $copy )->gather(1) if $session;
972         $s = $self->storagereq( $meth, $copy ) unless $session;
973
974         $logger->debug("Update of copy ".$copy->id." returned: $s");
975
976         return $self->DB_UPDATE_FAILED($copy) unless $s;
977         return undef;
978 }
979
980 sub fetch_billable_xact {
981         my( $self, $id ) = @_;
982         my($xact, $evt);
983         $logger->debug("Fetching billable transaction %id");
984         $xact = $self->cstorereq(
985                 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
986         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
987         return ($xact, $evt);
988 }
989
990 sub fetch_billable_xact_summary {
991         my( $self, $id ) = @_;
992         my($xact, $evt);
993         $logger->debug("Fetching billable transaction summary %id");
994         $xact = $self->cstorereq(
995                 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
996         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
997         return ($xact, $evt);
998 }
999
1000 sub fetch_fleshed_copy {
1001         my( $self, $id ) = @_;
1002         my( $copy, $evt );
1003         $logger->info("Fetching fleshed copy $id");
1004         $copy = $self->cstorereq(
1005                 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1006                 { flesh => 1,
1007                   flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1008                 }
1009         );
1010         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1011         return ($copy, $evt);
1012 }
1013
1014
1015 # returns the org that owns the callnumber that the copy
1016 # is attached to
1017 sub fetch_copy_owner {
1018         my( $self, $copyid ) = @_;
1019         my( $copy, $cn, $evt );
1020         $logger->debug("Fetching copy owner $copyid");
1021         ($copy, $evt) = $self->fetch_copy($copyid);
1022         return (undef,$evt) if $evt;
1023         ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1024         return (undef,$evt) if $evt;
1025         return ($cn->owning_lib);
1026 }
1027
1028 sub fetch_copy_note {
1029         my( $self, $id ) = @_;
1030         my( $note, $evt );
1031         $logger->debug("Fetching copy note $id");
1032         $note = $self->cstorereq(
1033                 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1034         $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1035         return ($note, $evt);
1036 }
1037
1038 sub fetch_call_numbers_by_title {
1039         my( $self, $titleid ) = @_;
1040         $logger->info("Fetching call numbers by title $titleid");
1041         return $self->cstorereq(
1042                 'open-ils.cstore.direct.asset.call_number.search.atomic', 
1043                 { record => $titleid, deleted => 'f' });
1044                 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1045 }
1046
1047 sub fetch_copies_by_call_number {
1048         my( $self, $cnid ) = @_;
1049         $logger->info("Fetching copies by call number $cnid");
1050         return $self->cstorereq(
1051                 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1052                 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1053 }
1054
1055 sub fetch_user_by_barcode {
1056         my( $self, $bc ) = @_;
1057         my $cardid = $self->cstorereq(
1058                 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1059         return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1060         my $user = $self->cstorereq(
1061                 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1062         return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1063         return ($user);
1064         
1065 }
1066
1067
1068 # ---------------------------------------------------------------------
1069 # Updates and returns the patron penalties
1070 # ---------------------------------------------------------------------
1071 sub update_patron_penalties {
1072         my( $self, %args ) = @_;
1073         return $self->simplereq(
1074                 'open-ils.penalty',
1075                 'open-ils.penalty.patron_penalty.calculate', 
1076                 { update => 1, %args }
1077         );
1078 }
1079
1080 sub fetch_bill {
1081         my( $self, $billid ) = @_;
1082         $logger->debug("Fetching billing $billid");
1083         my $bill = $self->cstorereq(
1084                 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1085         my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1086         return($bill, $evt);
1087 }
1088
1089
1090
1091 my $ORG_TREE;
1092 sub fetch_org_tree {
1093         my $self = shift;
1094         return $ORG_TREE if $ORG_TREE;
1095         return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit( 
1096                 [
1097                         {"parent_ou" => undef },
1098                         {
1099                                 flesh                           => 2,
1100                                 flesh_fields    => { aou =>  ['children'] },
1101                                 order_by       => { aou => 'name'}
1102                         }
1103                 ]
1104         )->[0];
1105 }
1106
1107 sub walk_org_tree {
1108         my( $self, $node, $callback ) = @_;
1109         return unless $node;
1110         $callback->($node);
1111         if( $node->children ) {
1112                 $self->walk_org_tree($_, $callback) for @{$node->children};
1113         }
1114 }
1115
1116 sub is_true {
1117         my( $self, $item ) = @_;
1118         return 1 if $item and $item !~ /^f$/i;
1119         return 0;
1120 }
1121
1122
1123 # This logic now lives in storage
1124 sub __patron_money_owed {
1125         my( $self, $patronid ) = @_;
1126         my $ses = OpenSRF::AppSession->create('open-ils.storage');
1127         my $req = $ses->request(
1128                 'open-ils.storage.money.billable_transaction.summary.search',
1129                 { usr => $patronid, xact_finish => undef } );
1130
1131         my $total = 0;
1132         my $data;
1133         while( $data = $req->recv ) {
1134                 $data = $data->content;
1135                 $total += $data->balance_owed;
1136         }
1137         return $total;
1138 }
1139
1140 sub patron_money_owed {
1141         my( $self, $userid ) = @_;
1142         my $ses = $self->start_db_session();
1143         my $val = $ses->request(
1144                 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1145         $self->rollback_db_session($ses);
1146         return $val;
1147 }
1148
1149 sub patron_total_items_out {
1150         my( $self, $userid ) = @_;
1151         my $ses = $self->start_db_session();
1152         my $val = $ses->request(
1153                 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1154         $self->rollback_db_session($ses);
1155         return $val;
1156 }
1157
1158
1159
1160
1161 #---------------------------------------------------------------------
1162 # Returns  ($summary, $event) 
1163 #---------------------------------------------------------------------
1164 sub fetch_mbts {
1165         my $self = shift;
1166         my $id  = shift;
1167         my $editor = shift || OpenILS::Utils::CStoreEditor->new;
1168
1169         $id = $id->id if (ref($id));
1170
1171         my $xact = $editor->retrieve_money_billable_transaction(
1172                 [
1173                         $id, {  
1174                                 flesh => 1, 
1175                                 flesh_fields => { mbt => [ qw/billings payments grocery circulation/ ] } 
1176                         }
1177                 ]
1178         ) or return (undef, $editor->event);
1179
1180         return $self->make_mbts($xact);
1181 }
1182
1183
1184 #---------------------------------------------------------------------
1185 # Given a list of money.billable_transaction objects, this creates
1186 # transaction summary objects for each
1187 #--------------------------------------------------------------------
1188 sub make_mbts {
1189         my $self = shift;
1190         my @xacts = @_;
1191
1192         my @mbts;
1193         for my $x (@xacts) {
1194
1195                 my $s = new Fieldmapper::money::billable_transaction_summary;
1196
1197                 $s->id( $x->id );
1198                 $s->usr( $x->usr );
1199                 $s->xact_start( $x->xact_start );
1200                 $s->xact_finish( $x->xact_finish );
1201                 
1202                 my $to = 0;
1203                 my $lb = undef;
1204                 for my $b (@{ $x->billings }) {
1205                         next if ($self->is_true($b->voided));
1206                         $to += ($b->amount * 100);
1207                         $lb ||= $b->billing_ts;
1208                         if ($b->billing_ts ge $lb) {
1209                                 $lb = $b->billing_ts;
1210                                 $s->last_billing_note($b->note);
1211                                 $s->last_billing_ts($b->billing_ts);
1212                                 $s->last_billing_type($b->billing_type);
1213                         }
1214                 }
1215
1216                 $s->total_owed( sprintf('%0.2f', $to / 100 ) );
1217                 
1218                 my $tp = 0;
1219                 my $lp = undef;
1220                 for my $p (@{ $x->payments }) {
1221                         next if ($self->is_true($p->voided));
1222                         $tp += ($p->amount * 100);
1223                         $lp ||= $p->payment_ts;
1224                         if ($p->payment_ts ge $lp) {
1225                                 $lp = $p->payment_ts;
1226                                 $s->last_payment_note($p->note);
1227                                 $s->last_payment_ts($p->payment_ts);
1228                                 $s->last_payment_type($p->payment_type);
1229                         }
1230                 }
1231
1232                 $s->total_paid( sprintf('%0.2f', $tp / 100 ) );
1233                 $s->balance_owed( sprintf('%0.2f', ($to - $tp) / 100) );
1234                 $s->xact_type('grocery') if ($x->grocery);
1235                 $s->xact_type('circulation') if ($x->circulation);
1236
1237                 $logger->debug("Created mbts with balance_owed = ". $s->balance_owed);
1238                 
1239                 push @mbts, $s;
1240         }
1241                 
1242         return @mbts;
1243 }
1244                 
1245                 
1246 sub ou_ancestor_setting_value {
1247     my($self, $org_id, $name, $e) = @_;
1248     $e = $e || OpenILS::Utils::CStoreEditor->new;
1249     my $query = {
1250         select => {
1251             aous => [ {
1252                 transform => 'actor.org_unit_ancestor_setting',
1253                 params => [$org_id],
1254                 column => 'name',
1255                 result_field => 'value',
1256                 alias => 'value'
1257             } ]
1258         },
1259         from => 'aous',
1260         where => {name => $name},
1261         limit => 1 # since name is not required to be unique, this approach could return duplicate rows
1262     };
1263
1264     my $obj = $e->json_query($query);
1265     return OpenSRF::Utils::JSON->JSON2perl($obj->[0]->{value}) if @$obj;
1266     return undef;
1267 }
1268
1269 sub ou_ancestor_setting {
1270     my( $self, $orgid, $name, $e ) = @_;
1271     $e = $e || OpenILS::Utils::CStoreEditor->new;
1272
1273     my $query = {
1274         select => {
1275             aous => [ {
1276                 transform => 'actor.org_unit_ancestor_setting',
1277                 params => [$orgid],
1278                 column => 'name',
1279                 result_field => 'id',
1280                 alias => 'id'
1281             } ]
1282         },
1283         from => 'aous',
1284         where => {name => $name},
1285         limit => 1 # since name is not required to be unique, this approach could return duplicate rows
1286     };
1287
1288     my $obj = $e->json_query($query);
1289     return undef unless @$obj;
1290     my $setting = $e->retrieve_actor_org_unit_setting($obj->[0]->{id});
1291     return { org => $setting->org_unit, value => OpenSRF::Utils::JSON->JSON2perl($setting->value) };
1292 }       
1293                 
1294
1295 # returns the ISO8601 string representation of the requested epoch in GMT
1296 sub epoch2ISO8601 {
1297     my( $self, $epoch ) = @_;
1298     my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1299     $year += 1900; $mon += 1;
1300     my $date = sprintf(
1301         '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1302         $year, $mon, $mday, $hour, $min, $sec);
1303     return $date;
1304 }
1305                         
1306 sub find_highest_perm_org {
1307         my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1308         my $org = $self->find_org($org_tree, $start_org );
1309
1310         my $lastid = -1;
1311         while( $org ) {
1312                 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1313                 $lastid = $org->id;
1314                 $org = $self->find_org( $org_tree, $org->parent_ou() );
1315         }
1316
1317         return $lastid;
1318 }
1319
1320
1321 sub find_highest_work_orgs {
1322     my($self, $e, $perm, $options) = @_;
1323     my $work_orgs = $self->get_user_work_ou_ids($e, $e->requestor->id);
1324     $logger->debug("found work orgs @$work_orgs");
1325         $options ||= {};
1326
1327     my @allowed_orgs;
1328         my $org_tree = $self->get_org_tree();
1329     my $org_types = $self->get_org_types();
1330
1331     # use the first work org to determine the highest depth at which 
1332     # the user has the requested permission
1333     my $first_org = shift @$work_orgs;
1334     my $high_org_id = $self->find_highest_perm_org($perm, $e->requestor->id, $first_org, $org_tree);
1335     $logger->debug("found highest work org $high_org_id");
1336
1337     
1338     return [] if $high_org_id == -1; # not allowed anywhere
1339
1340     my $high_org = $self->find_org($org_tree, $high_org_id);
1341     my ($high_org_type) = grep { $_->id == $high_org->ou_type } @$org_types;
1342     my $org_depth = $high_org_type->depth;
1343
1344         if($$options{descendants}) {
1345                 push(@allowed_orgs, @{$self->get_org_descendants($high_org_id, $org_depth)});
1346         } else {
1347                 push(@allowed_orgs, $high_org_id);
1348         }
1349
1350         return \@allowed_orgs if $org_depth == 0;
1351
1352     for my $org (@$work_orgs) {
1353
1354         $logger->debug("work org looking at $org");
1355                 my $org_list = $self->get_org_full_path($org, $org_depth);
1356
1357                 my $found = 0;
1358         for my $sub_org (@$org_list) {
1359                         if(not $found) {
1360                                 $logger->debug("work org looking at sub-org $sub_org");
1361                                 my $org_unit = $self->find_org($org_tree, $sub_org);
1362                                 my ($ou_type) = grep { $_->id == $org_unit->ou_type } @$org_types;
1363                                 if($ou_type->depth >= $org_depth) {
1364                                         push(@allowed_orgs, $sub_org);
1365                                         $found = 1;
1366                                 }
1367                         } else {
1368                                 last unless $$options{descendants}; 
1369                                 push(@allowed_orgs, $sub_org);
1370                         }
1371         }
1372     }
1373
1374     my %de_dupe;
1375     $de_dupe{$_} = 1 for @allowed_orgs;
1376     return [keys %de_dupe];
1377 }
1378
1379
1380 sub get_user_work_ou_ids {
1381     my($self, $e, $userid) = @_;
1382     my $work_orgs = $e->json_query({
1383         select => {puwoum => ['work_ou']},
1384         from => 'puwoum',
1385         where => {usr => $e->requestor->id}});
1386
1387     return [] unless @$work_orgs;
1388     my @work_orgs;
1389     push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1390
1391     return \@work_orgs;
1392 }
1393
1394
1395 my $org_types;
1396 sub get_org_types {
1397         my($self, $client) = @_;
1398         return $org_types if $org_types;
1399         return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1400 }
1401
1402 sub get_org_tree {
1403         my $cache_diff = shift || '';
1404         my $cache = OpenSRF::Utils::Cache->new("global", 0);
1405         my $tree = $cache->get_cache("orgtree.$cache_diff");
1406         return $tree if $tree;
1407
1408         $tree = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit( 
1409                 [
1410                         {"parent_ou" => undef },
1411                         {
1412                                 flesh                           => -1,
1413                                 flesh_fields    => { aou =>  ['children'] },
1414                                 order_by                        => { aou => 'name'}
1415                         }
1416                 ]
1417         )->[0];
1418
1419         $cache->put_cache("orgtree.$cache_diff", $tree);
1420         return $tree;
1421 }
1422
1423 sub get_org_descendants {
1424         my($self, $org_id, $depth) = @_;
1425
1426         my $select = {
1427                 transform => 'actor.org_unit_descendants',
1428                 column => 'id',
1429                 result_field => 'id',
1430         };
1431         $select->{params} = [$depth] if defined $depth;
1432
1433         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1434                 select => {aou => [$select]},
1435         from => 'aou',
1436                 where => {id => $org_id}
1437         });
1438         my @orgs;
1439         push(@orgs, $_->{id}) for @$org_list;
1440         return \@orgs;
1441 }
1442
1443 sub get_org_ancestors {
1444         my($self, $org_id, $depth) = @_;
1445         $depth ||= 0;
1446
1447         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1448                 select => {
1449                         aou => [{
1450                                 transform => 'actor.org_unit_ancestors',
1451                                 column => 'id',
1452                                 result_field => 'id',
1453                                 params => [$depth]
1454                         }],
1455                 },
1456                 from => 'aou',
1457                 where => {id => $org_id}
1458         });
1459
1460         my @orgs;
1461         push(@orgs, $_->{id}) for @$org_list;
1462         return \@orgs;
1463 }
1464
1465 sub get_org_full_path {
1466         my($self, $org_id, $depth) = @_;
1467         $depth ||= 0;
1468
1469         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1470                 select => {
1471                         aou => [{
1472                                 transform => 'actor.org_unit_full_path',
1473                                 column => 'id',
1474                                 result_field => 'id',
1475                                 params => [$depth]
1476                         }],
1477                 },
1478                 from => 'aou',
1479                 where => {id => $org_id}
1480         });
1481
1482         my @orgs;
1483         push(@orgs, $_->{id}) for @$org_list;
1484         return \@orgs;
1485 }
1486
1487 # returns the user's configured locale as a string.  Defaults to en-US if none is configured.
1488 sub get_user_locale {
1489         my($self, $user_id, $e) = @_;
1490         $e ||= OpenILS::Utils::CStoreEditor->new;
1491
1492         # first, see if the user has an explicit locale set
1493         my $setting = $e->search_actor_user_setting(
1494                 {usr => $user_id, name => 'global.locale'})->[0];
1495         return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1496
1497         my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1498         return $self->get_org_locale($user->home_ou, $e);
1499 }
1500
1501 # returns org locale setting
1502 sub get_org_locale {
1503         my($self, $org_id, $e) = @_;
1504         $e ||= OpenILS::Utils::CStoreEditor->new;
1505
1506         my $locale;
1507         if(defined $org_id) {
1508                 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1509                 return $locale if $locale;
1510         }
1511
1512         # system-wide default
1513         my $sclient = OpenSRF::Utils::SettingsClient->new;
1514         $locale = $sclient->config_value('default_locale');
1515     return $locale if $locale;
1516
1517         # if nothing else, fallback to locale=cowboy
1518         return 'en-US';
1519 }
1520
1521
1522 # xml-escape non-ascii characters
1523 sub entityize { 
1524     my($self, $string, $form) = @_;
1525         $form ||= "";
1526
1527         if ($form eq 'D') {
1528                 $string = NFD($string);
1529         } else {
1530                 $string = NFC($string);
1531         }
1532
1533         $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1534         return $string;
1535 }
1536
1537
1538 sub get_copy_price {
1539         my($self, $e, $copy, $volume) = @_;
1540
1541         $copy->price(0) if $copy->price < 0;
1542
1543         return $copy->price if $copy->price and $copy->price > 0;
1544
1545
1546         my $owner;
1547         if(ref $volume) {
1548                 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1549                         $owner = $copy->circ_lib;
1550                 } else {
1551                         $owner = $volume->owning_lib;
1552                 }
1553         } else {
1554                 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1555                         $owner = $copy->circ_lib;
1556                 } else {
1557                         $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1558                 }
1559         }
1560
1561         my $default_price = $self->ou_ancestor_setting_value(
1562                 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1563
1564         return $default_price unless defined $copy->price;
1565
1566         # price is 0.  Use the default?
1567     my $charge_on_0 = $self->ou_ancestor_setting_value(
1568         $owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e) || 0;
1569
1570         return $default_price if $charge_on_0;
1571         return 0;
1572 }
1573
1574 1;
1575