]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/AppUtils.pm
exit early if no event is created
[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 storagereq_xact {
860         my($self, $method, @params) = @_;
861         my $ses = $self->start_db_session();
862         my $val = $ses->request($method, @params)->gather(1);
863         $self->rollback_db_session($ses);
864     return $val;
865 }
866
867 sub cstorereq {
868         my( $self, $method, @params ) = @_;
869         return $self->simplereq(
870                 'open-ils.cstore', $method, @params );
871 }
872
873 sub event_equals {
874         my( $self, $e, $name ) =  @_;
875         if( $e and ref($e) eq 'HASH' and 
876                 defined($e->{textcode}) and $e->{textcode} eq $name ) {
877                 return 1 ;
878         }
879         return 0;
880 }
881
882 sub logmark {
883         my( undef, $f, $l ) = caller(0);
884         my( undef, undef, undef, $s ) = caller(1);
885         $s =~ s/.*:://g;
886         $f =~ s/.*\///g;
887         $logger->debug("LOGMARK: $f:$l:$s");
888 }
889
890 # takes a copy id 
891 sub fetch_open_circulation {
892         my( $self, $cid ) = @_;
893         my $evt;
894         $self->logmark;
895         my $circ = $self->cstorereq(
896                 'open-ils.cstore.direct.action.open_circulation.search',
897                 { target_copy => $cid, stop_fines_time => undef } );
898         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
899         return ($circ, $evt);
900 }
901
902 sub fetch_all_open_circulation {
903         my( $self, $cid ) = @_;
904         my $evt;
905         $self->logmark;
906         my $circ = $self->cstorereq(
907                 'open-ils.cstore.direct.action.open_circulation.search',
908                 { target_copy => $cid, xact_finish => undef } );
909         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
910         return ($circ, $evt);
911 }
912
913 my $copy_statuses;
914 sub copy_status_from_name {
915         my( $self, $name ) = @_;
916         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
917         for my $status (@$copy_statuses) { 
918                 return $status if( $status->name =~ /$name/i );
919         }
920         return undef;
921 }
922
923 sub copy_status_to_name {
924         my( $self, $sid ) = @_;
925         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
926         for my $status (@$copy_statuses) { 
927                 return $status->name if( $status->id == $sid );
928         }
929         return undef;
930 }
931
932
933 sub copy_status {
934         my( $self, $arg ) = @_;
935         return $arg if ref $arg;
936         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
937         my ($stat) = grep { $_->id == $arg } @$copy_statuses;
938         return $stat;
939 }
940
941 sub fetch_open_transit_by_copy {
942         my( $self, $copyid ) = @_;
943         my($transit, $evt);
944         $transit = $self->cstorereq(
945                 'open-ils.cstore.direct.action.transit_copy.search',
946                 { target_copy => $copyid, dest_recv_time => undef });
947         $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
948         return ($transit, $evt);
949 }
950
951 sub unflesh_copy {
952         my( $self, $copy ) = @_;
953         return undef unless $copy;
954         $copy->status( $copy->status->id ) if ref($copy->status);
955         $copy->location( $copy->location->id ) if ref($copy->location);
956         $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
957         return $copy;
958 }
959
960 # un-fleshes a copy and updates it in the DB
961 # returns a DB_UPDATE_FAILED event on error
962 # returns undef on success
963 sub update_copy {
964         my( $self, %params ) = @_;
965
966         my $copy                = $params{copy} || die "update_copy(): copy required";
967         my $editor      = $params{editor} || die "update_copy(): copy editor required";
968         my $session = $params{session};
969
970         $logger->debug("Updating copy in the database: " . $copy->id);
971
972         $self->unflesh_copy($copy);
973         $copy->editor( $editor );
974         $copy->edit_date( 'now' );
975
976         my $s;
977         my $meth = 'open-ils.storage.direct.asset.copy.update';
978
979         $s = $session->request( $meth, $copy )->gather(1) if $session;
980         $s = $self->storagereq( $meth, $copy ) unless $session;
981
982         $logger->debug("Update of copy ".$copy->id." returned: $s");
983
984         return $self->DB_UPDATE_FAILED($copy) unless $s;
985         return undef;
986 }
987
988 sub fetch_billable_xact {
989         my( $self, $id ) = @_;
990         my($xact, $evt);
991         $logger->debug("Fetching billable transaction %id");
992         $xact = $self->cstorereq(
993                 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
994         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
995         return ($xact, $evt);
996 }
997
998 sub fetch_billable_xact_summary {
999         my( $self, $id ) = @_;
1000         my($xact, $evt);
1001         $logger->debug("Fetching billable transaction summary %id");
1002         $xact = $self->cstorereq(
1003                 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1004         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1005         return ($xact, $evt);
1006 }
1007
1008 sub fetch_fleshed_copy {
1009         my( $self, $id ) = @_;
1010         my( $copy, $evt );
1011         $logger->info("Fetching fleshed copy $id");
1012         $copy = $self->cstorereq(
1013                 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1014                 { flesh => 1,
1015                   flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1016                 }
1017         );
1018         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1019         return ($copy, $evt);
1020 }
1021
1022
1023 # returns the org that owns the callnumber that the copy
1024 # is attached to
1025 sub fetch_copy_owner {
1026         my( $self, $copyid ) = @_;
1027         my( $copy, $cn, $evt );
1028         $logger->debug("Fetching copy owner $copyid");
1029         ($copy, $evt) = $self->fetch_copy($copyid);
1030         return (undef,$evt) if $evt;
1031         ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1032         return (undef,$evt) if $evt;
1033         return ($cn->owning_lib);
1034 }
1035
1036 sub fetch_copy_note {
1037         my( $self, $id ) = @_;
1038         my( $note, $evt );
1039         $logger->debug("Fetching copy note $id");
1040         $note = $self->cstorereq(
1041                 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1042         $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1043         return ($note, $evt);
1044 }
1045
1046 sub fetch_call_numbers_by_title {
1047         my( $self, $titleid ) = @_;
1048         $logger->info("Fetching call numbers by title $titleid");
1049         return $self->cstorereq(
1050                 'open-ils.cstore.direct.asset.call_number.search.atomic', 
1051                 { record => $titleid, deleted => 'f' });
1052                 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1053 }
1054
1055 sub fetch_copies_by_call_number {
1056         my( $self, $cnid ) = @_;
1057         $logger->info("Fetching copies by call number $cnid");
1058         return $self->cstorereq(
1059                 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1060                 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1061 }
1062
1063 sub fetch_user_by_barcode {
1064         my( $self, $bc ) = @_;
1065         my $cardid = $self->cstorereq(
1066                 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1067         return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1068         my $user = $self->cstorereq(
1069                 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1070         return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1071         return ($user);
1072         
1073 }
1074
1075 sub fetch_bill {
1076         my( $self, $billid ) = @_;
1077         $logger->debug("Fetching billing $billid");
1078         my $bill = $self->cstorereq(
1079                 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1080         my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1081         return($bill, $evt);
1082 }
1083
1084 my $ORG_TREE;
1085 sub fetch_org_tree {
1086         my $self = shift;
1087         return $ORG_TREE if $ORG_TREE;
1088         return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit( 
1089                 [
1090                         {"parent_ou" => undef },
1091                         {
1092                                 flesh                           => 2,
1093                                 flesh_fields    => { aou =>  ['children'] },
1094                                 order_by       => { aou => 'name'}
1095                         }
1096                 ]
1097         )->[0];
1098 }
1099
1100 sub walk_org_tree {
1101         my( $self, $node, $callback ) = @_;
1102         return unless $node;
1103         $callback->($node);
1104         if( $node->children ) {
1105                 $self->walk_org_tree($_, $callback) for @{$node->children};
1106         }
1107 }
1108
1109 sub is_true {
1110         my( $self, $item ) = @_;
1111         return 1 if $item and $item !~ /^f$/i;
1112         return 0;
1113 }
1114
1115
1116 # This logic now lives in storage
1117 sub __patron_money_owed {
1118         my( $self, $patronid ) = @_;
1119         my $ses = OpenSRF::AppSession->create('open-ils.storage');
1120         my $req = $ses->request(
1121                 'open-ils.storage.money.billable_transaction.summary.search',
1122                 { usr => $patronid, xact_finish => undef } );
1123
1124         my $total = 0;
1125         my $data;
1126         while( $data = $req->recv ) {
1127                 $data = $data->content;
1128                 $total += $data->balance_owed;
1129         }
1130         return $total;
1131 }
1132
1133 sub patron_money_owed {
1134         my( $self, $userid ) = @_;
1135         my $ses = $self->start_db_session();
1136         my $val = $ses->request(
1137                 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1138         $self->rollback_db_session($ses);
1139         return $val;
1140 }
1141
1142 sub patron_total_items_out {
1143         my( $self, $userid ) = @_;
1144         my $ses = $self->start_db_session();
1145         my $val = $ses->request(
1146                 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1147         $self->rollback_db_session($ses);
1148         return $val;
1149 }
1150
1151
1152
1153
1154 #---------------------------------------------------------------------
1155 # Returns  ($summary, $event) 
1156 #---------------------------------------------------------------------
1157 sub fetch_mbts {
1158         my $self = shift;
1159         my $id  = shift;
1160         my $e = shift || OpenILS::Utils::CStoreEditor->new;
1161         $id = $id->id if ref($id);
1162     
1163     my $xact = $e->retrieve_money_billable_transaction_summary($id)
1164             or return (undef, $e->event);
1165
1166     return ($xact);
1167 }
1168
1169
1170 #---------------------------------------------------------------------
1171 # Given a list of money.billable_transaction objects, this creates
1172 # transaction summary objects for each
1173 #--------------------------------------------------------------------
1174 sub make_mbts {
1175         my $self = shift;
1176     my $e = shift;
1177         my @xacts = @_;
1178         return () if (!@xacts);
1179     return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1180 }
1181                 
1182                 
1183 sub ou_ancestor_setting_value {
1184     my($self, $org_id, $name, $e) = @_;
1185     $e = $e || OpenILS::Utils::CStoreEditor->new;
1186     my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1187     return $set->{value} if $set;
1188     return undef;
1189 }
1190
1191 sub ou_ancestor_setting {
1192     my( $self, $orgid, $name, $e ) = @_;
1193     $e = $e || OpenILS::Utils::CStoreEditor->new;
1194     my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1195     my $setting = $e->json_query($query)->[0];
1196     return undef unless $setting;
1197     return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1198 }       
1199                 
1200
1201 # returns the ISO8601 string representation of the requested epoch in GMT
1202 sub epoch2ISO8601 {
1203     my( $self, $epoch ) = @_;
1204     my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1205     $year += 1900; $mon += 1;
1206     my $date = sprintf(
1207         '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1208         $year, $mon, $mday, $hour, $min, $sec);
1209     return $date;
1210 }
1211                         
1212 sub find_highest_perm_org {
1213         my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1214         my $org = $self->find_org($org_tree, $start_org );
1215
1216         my $lastid = -1;
1217         while( $org ) {
1218                 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1219                 $lastid = $org->id;
1220                 $org = $self->find_org( $org_tree, $org->parent_ou() );
1221         }
1222
1223         return $lastid;
1224 }
1225
1226
1227 # returns the org_unit ID's 
1228 sub user_has_work_perm_at {
1229     my($self, $e, $perm, $options) = @_;
1230     $options ||= {};
1231
1232     my $func = 'permission.usr_has_perm_at';
1233     $func = $func.'_all' if $$options{descendants};
1234
1235     my $orgs = $e->json_query({from => [$func, $e->requestor->id, $perm]});
1236     $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1237
1238     return $orgs unless $$options{objects};
1239
1240     return $e->search_actor_org_unit({id => $orgs});
1241 }
1242
1243 sub get_user_work_ou_ids {
1244     my($self, $e, $userid) = @_;
1245     my $work_orgs = $e->json_query({
1246         select => {puwoum => ['work_ou']},
1247         from => 'puwoum',
1248         where => {usr => $e->requestor->id}});
1249
1250     return [] unless @$work_orgs;
1251     my @work_orgs;
1252     push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1253
1254     return \@work_orgs;
1255 }
1256
1257
1258 my $org_types;
1259 sub get_org_types {
1260         my($self, $client) = @_;
1261         return $org_types if $org_types;
1262         return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1263 }
1264
1265 sub get_org_tree {
1266         my $self = shift;
1267         my $locale = shift || '';
1268         my $cache = OpenSRF::Utils::Cache->new("global", 0);
1269         my $tree = $cache->get_cache("orgtree.$locale");
1270         return $tree if $tree;
1271
1272         my $ses = OpenILS::Utils::CStoreEditor->new;
1273         $ses->session->session_locale($locale);
1274         $tree = $ses->search_actor_org_unit( 
1275                 [
1276                         {"parent_ou" => undef },
1277                         {
1278                                 flesh                           => -1,
1279                                 flesh_fields    => { aou =>  ['children'] },
1280                                 order_by                        => { aou => 'name'}
1281                         }
1282                 ]
1283         )->[0];
1284
1285         $cache->put_cache("orgtree.$locale", $tree);
1286         return $tree;
1287 }
1288
1289 sub get_org_descendants {
1290         my($self, $org_id, $depth) = @_;
1291
1292         my $select = {
1293                 transform => 'actor.org_unit_descendants',
1294                 column => 'id',
1295                 result_field => 'id',
1296         };
1297         $select->{params} = [$depth] if defined $depth;
1298
1299         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1300                 select => {aou => [$select]},
1301         from => 'aou',
1302                 where => {id => $org_id}
1303         });
1304         my @orgs;
1305         push(@orgs, $_->{id}) for @$org_list;
1306         return \@orgs;
1307 }
1308
1309 sub get_org_ancestors {
1310         my($self, $org_id) = @_;
1311
1312         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1313                 select => {
1314                         aou => [{
1315                                 transform => 'actor.org_unit_ancestors',
1316                                 column => 'id',
1317                                 result_field => 'id',
1318                                 params => []
1319                         }],
1320                 },
1321                 from => 'aou',
1322                 where => {id => $org_id}
1323         });
1324
1325         my @orgs;
1326         push(@orgs, $_->{id}) for @$org_list;
1327         return \@orgs;
1328 }
1329
1330 sub get_org_full_path {
1331         my($self, $org_id, $depth) = @_;
1332         $depth ||= 0;
1333
1334         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1335                 select => {
1336                         aou => [{
1337                                 transform => 'actor.org_unit_full_path',
1338                                 column => 'id',
1339                                 result_field => 'id',
1340                                 params => [$depth]
1341                         }],
1342                 },
1343                 from => 'aou',
1344                 where => {id => $org_id}
1345         });
1346
1347         my @orgs;
1348         push(@orgs, $_->{id}) for @$org_list;
1349         return \@orgs;
1350 }
1351
1352 # returns the user's configured locale as a string.  Defaults to en-US if none is configured.
1353 sub get_user_locale {
1354         my($self, $user_id, $e) = @_;
1355         $e ||= OpenILS::Utils::CStoreEditor->new;
1356
1357         # first, see if the user has an explicit locale set
1358         my $setting = $e->search_actor_user_setting(
1359                 {usr => $user_id, name => 'global.locale'})->[0];
1360         return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1361
1362         my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1363         return $self->get_org_locale($user->home_ou, $e);
1364 }
1365
1366 # returns org locale setting
1367 sub get_org_locale {
1368         my($self, $org_id, $e) = @_;
1369         $e ||= OpenILS::Utils::CStoreEditor->new;
1370
1371         my $locale;
1372         if(defined $org_id) {
1373                 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1374                 return $locale if $locale;
1375         }
1376
1377         # system-wide default
1378         my $sclient = OpenSRF::Utils::SettingsClient->new;
1379         $locale = $sclient->config_value('default_locale');
1380     return $locale if $locale;
1381
1382         # if nothing else, fallback to locale=cowboy
1383         return 'en-US';
1384 }
1385
1386
1387 # xml-escape non-ascii characters
1388 sub entityize { 
1389     my($self, $string, $form) = @_;
1390         $form ||= "";
1391
1392         if ($form eq 'D') {
1393                 $string = NFD($string);
1394         } else {
1395                 $string = NFC($string);
1396         }
1397
1398         # Convert raw ampersands to ampersand entities
1399         $string =~ s/&(?!\S+;)/&amp;/gso;
1400
1401         $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1402         return $string;
1403 }
1404
1405 # x0000-x0008 isn't legal in XML documents
1406 # XXX Perhaps this should just go into our standard entityize method
1407 sub strip_ctrl_chars {
1408         my ($self, $string) = @_;
1409
1410         $string =~ s/([\x{0000}-\x{0008}])//sgoe; 
1411         return $string;
1412 }
1413
1414 sub get_copy_price {
1415         my($self, $e, $copy, $volume) = @_;
1416
1417         $copy->price(0) if $copy->price and $copy->price < 0;
1418
1419         return $copy->price if $copy->price and $copy->price > 0;
1420
1421
1422         my $owner;
1423         if(ref $volume) {
1424                 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1425                         $owner = $copy->circ_lib;
1426                 } else {
1427                         $owner = $volume->owning_lib;
1428                 }
1429         } else {
1430                 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1431                         $owner = $copy->circ_lib;
1432                 } else {
1433                         $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1434                 }
1435         }
1436
1437         my $default_price = $self->ou_ancestor_setting_value(
1438                 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1439
1440         return $default_price unless defined $copy->price;
1441
1442         # price is 0.  Use the default?
1443     my $charge_on_0 = $self->ou_ancestor_setting_value(
1444         $owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e) || 0;
1445
1446         return $default_price if $charge_on_0;
1447         return 0;
1448 }
1449
1450 # given a transaction ID, this returns the context org_unit for the transaction
1451 sub xact_org {
1452     my($self, $xact_id, $e) = @_;
1453     $e ||= OpenILS::Utils::CStoreEditor->new;
1454     
1455     my $loc = $e->json_query({
1456         "select" => {circ => ["circ_lib"]},
1457         from     => "circ",
1458         "where"  => {id => $xact_id},
1459     });
1460
1461     return $loc->[0]->{circ_lib} if @$loc;
1462
1463     $loc = $e->json_query({
1464         "select" => {mg => ["billing_location"]},
1465         from     => "mg",
1466         "where"  => {id => $xact_id},
1467     });
1468
1469     return $loc->[0]->{billing_location};
1470 }
1471
1472
1473 # If an event_def ID is not provided, use the hook and context org to find the 
1474 # most appropriate event.  create the event, fire it, then return the resulting
1475 # event with fleshed template_output and error_output
1476 sub fire_object_event {
1477     my($self, $event_def, $hook, $object, $context_org) = @_;
1478
1479     my $e = OpenILS::Utils::CStoreEditor->new;
1480     my $def;
1481
1482     if($event_def) {
1483         $def = $e->retrieve_action_trigger_event_definition($event_def)
1484             or return $e->event;
1485
1486     } else {
1487         # find the most appropriate event def depending on context org
1488         my $orgs = $self->get_org_ancestors($context_org);
1489         $orgs = $e->search_actor_org_unit(
1490             [{id => $orgs}, {flesh => 1, flesh_fields => {aou => ['ou_type']}}]);
1491         $orgs = [ sort { $a->ou_type->depth cmp $b->ou_type->depth } @$orgs ];
1492
1493         for my $org (reverse @$orgs) { 
1494             $def = $e->search_action_trigger_event_definition(
1495                 {hook => $hook, owner => $org->id}
1496             )->[0];
1497             last if $def;
1498         }
1499
1500         return $e->event unless $def;
1501     }
1502
1503     my $event_id = $self->simplereq(
1504         'open-ils.trigger',
1505         'open-ils.trigger.event.autocreate.by_definition', 
1506         $def->id, $object, $context_org);
1507
1508     my $fire = 'open-ils.trigger.event.fire';
1509
1510     if($def->group_field) {
1511         $fire =~ s/event/event_group/o;
1512         $event_id = [$event_id];
1513     }
1514
1515     my $resp = $self->simplereq('open-ils.trigger', $fire, $event_id);
1516     return 0 unless $resp and ($resp->{event} or $resp->{events});
1517     my $evt = $resp->{event} ? $resp->{event} : $resp->{events}->[0];
1518
1519     return 0 unless $evt;
1520
1521     return $e->retrieve_action_trigger_event([
1522         $evt->id,
1523         {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1524     ]);
1525 }
1526
1527
1528 1;
1529