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