]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/AppUtils.pm
Org unit retrieval cleanup
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / 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 use Encode;
18
19 # ---------------------------------------------------------------------------
20 # Pile of utilty methods used accross applications.
21 # ---------------------------------------------------------------------------
22 my $cache_client = "OpenSRF::Utils::Cache";
23
24
25 # ---------------------------------------------------------------------------
26 # on sucess, returns the created session, on failure throws ERROR exception
27 # ---------------------------------------------------------------------------
28 sub start_db_session {
29
30         my $self = shift;
31         my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
32         my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
33
34         my $trans_resp = $trans_req->recv();
35         if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
36         if( ! $trans_resp->content() ) {
37                 throw OpenSRF::ERROR 
38                         ("Unable to Begin Transaction with database" );
39         }
40         $trans_req->finish();
41
42         $logger->debug("Setting global storage session to ".
43                 "session: " . $session->session_id . " : " . $session->app );
44
45         return $session;
46 }
47
48 sub set_audit_info {
49         my $self = shift;
50         my $session = shift;
51         my $authtoken = shift;
52         my $user_id = shift;
53         my $ws_id = shift;
54         
55         my $audit_req = $session->request( "open-ils.storage.set_audit_info", $authtoken, $user_id, $ws_id );
56         my $audit_resp = $audit_req->recv();
57         $audit_req->finish();
58 }
59
60 my $PERM_QUERY = {
61     select => {
62         au => [ {
63             transform => 'permission.usr_has_perm',
64             alias => 'has_perm',
65             column => 'id',
66             params => []
67         } ]
68     },
69     from => 'au',
70     where => {},
71 };
72
73
74 # returns undef if user has all of the perms provided
75 # returns the first failed perm on failure
76 sub check_user_perms {
77         my($self, $user_id, $org_id, @perm_types ) = @_;
78         $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
79
80         for my $type (@perm_types) {
81             $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
82                 $PERM_QUERY->{where}->{id} = $user_id;
83                 return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
84         }
85         return undef;
86 }
87
88 # checks the list of user perms.  The first one that fails returns a new
89 sub check_perms {
90         my( $self, $user_id, $org_id, @perm_types ) = @_;
91         my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
92         return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
93         return undef;
94 }
95
96
97
98 # ---------------------------------------------------------------------------
99 # commits and destroys the session
100 # ---------------------------------------------------------------------------
101 sub commit_db_session {
102         my( $self, $session ) = @_;
103
104         my $req = $session->request( "open-ils.storage.transaction.commit" );
105         my $resp = $req->recv();
106
107         if(!$resp) {
108                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
109         }
110
111         if(UNIVERSAL::isa($resp,"Error")) { 
112                 throw $resp ($resp->stringify); 
113         }
114
115         if(!$resp->content) {
116                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
117         }
118
119         $session->finish();
120         $session->disconnect();
121         $session->kill_me();
122 }
123
124 sub rollback_db_session {
125         my( $self, $session ) = @_;
126
127         my $req = $session->request("open-ils.storage.transaction.rollback");
128         my $resp = $req->recv();
129         if(UNIVERSAL::isa($resp,"Error")) { throw $resp;  }
130
131         $session->finish();
132         $session->disconnect();
133         $session->kill_me();
134 }
135
136
137 # returns undef it the event is not an ILS event
138 # returns the event code otherwise
139 sub event_code {
140         my( $self, $evt ) = @_;
141         return $evt->{ilsevent} if( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
142         return undef;
143 }
144
145 # ---------------------------------------------------------------------------
146 # Checks to see if a user is logged in.  Returns the user record on success,
147 # throws an exception on error.
148 # ---------------------------------------------------------------------------
149 sub check_user_session {
150         my( $self, $user_session ) = @_;
151
152         my $content = $self->simplereq( 
153                 'open-ils.auth', 
154                 'open-ils.auth.session.retrieve', $user_session);
155
156     return undef if (!$content) or $self->event_code($content);
157         return $content;
158 }
159
160 # generic simple request returning a scalar value
161 sub simplereq {
162         my($self, $service, $method, @params) = @_;
163         return $self->simple_scalar_request($service, $method, @params);
164 }
165
166
167 sub simple_scalar_request {
168         my($self, $service, $method, @params) = @_;
169
170         my $session = OpenSRF::AppSession->create( $service );
171
172         my $request = $session->request( $method, @params );
173
174         my $val;
175         my $err;
176         try  {
177
178                 $val = $request->gather(1);     
179
180         } catch Error with {
181                 $err = shift;
182         };
183
184         if( $err ) {
185                 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
186                 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
187         }
188
189         return $val;
190 }
191
192 sub build_org_tree {
193         my( $self, $orglist ) = @_;
194
195         return $orglist unless ref $orglist; 
196     return $$orglist[0] if @$orglist == 1;
197
198         my @list = sort { 
199                 $a->ou_type <=> $b->ou_type ||
200                 $a->name cmp $b->name } @$orglist;
201
202         for my $org (@list) {
203
204                 next unless ($org);
205         next if (!defined($org->parent_ou) || $org->parent_ou eq "");
206
207                 my ($parent) = grep { $_->id == $org->parent_ou } @list;
208                 next unless $parent;
209                 $parent->children([]) unless defined($parent->children); 
210                 push( @{$parent->children}, $org );
211         }
212
213         return $list[0];
214 }
215
216 sub fetch_closed_date {
217         my( $self, $cd ) = @_;
218         my $evt;
219         
220         $logger->debug("Fetching closed_date $cd from cstore");
221
222         my $cd_obj = $self->simplereq(
223                 'open-ils.cstore',
224                 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
225
226         if(!$cd_obj) {
227                 $logger->info("closed_date $cd not found in the db");
228                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
229         }
230
231         return ($cd_obj, $evt);
232 }
233
234 sub fetch_user {
235         my( $self, $userid ) = @_;
236         my( $user, $evt );
237         
238         $logger->debug("Fetching user $userid from cstore");
239
240         $user = $self->simplereq(
241                 'open-ils.cstore',
242                 'open-ils.cstore.direct.actor.user.retrieve', $userid );
243
244         if(!$user) {
245                 $logger->info("User $userid not found in the db");
246                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
247         }
248
249         return ($user, $evt);
250 }
251
252 sub checkses {
253         my( $self, $session ) = @_;
254         my $user = $self->check_user_session($session) or 
255         return (undef, OpenILS::Event->new('NO_SESSION'));
256     return ($user);
257 }
258
259
260 # verifiese the session and checks the permissions agains the
261 # session user and the user's home_ou as the org id
262 sub checksesperm {
263         my( $self, $session, @perms ) = @_;
264         my $user; my $evt; my $e; 
265         $logger->debug("Checking user session $session and perms @perms");
266         ($user, $evt) = $self->checkses($session);
267         return (undef, $evt) if $evt;
268         $evt = $self->check_perms($user->id, $user->home_ou, @perms);
269         return ($user, $evt);
270 }
271
272
273 sub checkrequestor {
274         my( $self, $staffobj, $userid, @perms ) = @_;
275         my $user; my $evt;
276         $userid = $staffobj->id unless defined $userid;
277
278         $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
279
280         if( $userid ne $staffobj->id ) {
281                 ($user, $evt) = $self->fetch_user($userid);
282                 return (undef, $evt) if $evt;
283                 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
284
285         } else {
286                 $user = $staffobj;
287         }
288
289         return ($user, $evt);
290 }
291
292 sub checkses_requestor {
293         my( $self, $authtoken, $targetid, @perms ) = @_;
294         my( $requestor, $target, $evt );
295
296         ($requestor, $evt) = $self->checkses($authtoken);
297         return (undef, undef, $evt) if $evt;
298
299         ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
300         return( $requestor, $target, $evt);
301 }
302
303 sub fetch_copy {
304         my( $self, $copyid ) = @_;
305         my( $copy, $evt );
306
307         $logger->debug("Fetching copy $copyid from cstore");
308
309         $copy = $self->simplereq(
310                 'open-ils.cstore',
311                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
312
313         if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
314
315         return( $copy, $evt );
316 }
317
318
319 # retrieves a circ object by id
320 sub fetch_circulation {
321         my( $self, $circid ) = @_;
322         my $circ; my $evt;
323         
324         $logger->debug("Fetching circ $circid from cstore");
325
326         $circ = $self->simplereq(
327                 'open-ils.cstore',
328                 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
329
330         if(!$circ) {
331                 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
332         }
333
334         return ( $circ, $evt );
335 }
336
337 sub fetch_record_by_copy {
338         my( $self, $copyid ) = @_;
339         my( $record, $evt );
340
341         $logger->debug("Fetching record by copy $copyid from cstore");
342
343         $record = $self->simplereq(
344                 'open-ils.cstore',
345                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
346                 { flesh => 3,
347                   flesh_fields => {     bre => [ 'fixed_fields' ],
348                                         acn => [ 'record' ],
349                                         acp => [ 'call_number' ],
350                                   }
351                 }
352         );
353
354         if(!$record) {
355                 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
356         } else {
357                 $record = $record->call_number->record;
358         }
359
360         return ($record, $evt);
361 }
362
363 # turns a record object into an mvr (mods) object
364 sub record_to_mvr {
365         my( $self, $record ) = @_;
366         return undef unless $record and $record->marc;
367         my $u = OpenILS::Utils::ModsParser->new();
368         $u->start_mods_batch( $record->marc );
369         my $mods = $u->finish_mods_batch();
370         $mods->doc_id($record->id);
371    $mods->tcn($record->tcn_value);
372         return $mods;
373 }
374
375 sub fetch_hold {
376         my( $self, $holdid ) = @_;
377         my( $hold, $evt );
378
379         $logger->debug("Fetching hold $holdid from cstore");
380
381         $hold = $self->simplereq(
382                 'open-ils.cstore',
383                 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
384
385         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
386
387         return ($hold, $evt);
388 }
389
390
391 sub fetch_hold_transit_by_hold {
392         my( $self, $holdid ) = @_;
393         my( $transit, $evt );
394
395         $logger->debug("Fetching transit by hold $holdid from cstore");
396
397         $transit = $self->simplereq(
398                 'open-ils.cstore',
399                 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
400
401         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
402
403         return ($transit, $evt );
404 }
405
406 # fetches the captured, but not fulfilled hold attached to a given copy
407 sub fetch_open_hold_by_copy {
408         my( $self, $copyid ) = @_;
409         $logger->debug("Searching for active hold for copy $copyid");
410         my( $hold, $evt );
411
412         $hold = $self->cstorereq(
413                 'open-ils.cstore.direct.action.hold_request.search',
414                 { 
415                         current_copy            => $copyid , 
416                         capture_time            => { "!=" => undef }, 
417                         fulfillment_time        => undef,
418                         cancel_time                     => undef,
419                 } );
420
421         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
422         return ($hold, $evt);
423 }
424
425 sub fetch_hold_transit {
426         my( $self, $transid ) = @_;
427         my( $htransit, $evt );
428         $logger->debug("Fetching hold transit with hold id $transid");
429         $htransit = $self->cstorereq(
430                 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
431         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
432         return ($htransit, $evt);
433 }
434
435 sub fetch_copy_by_barcode {
436         my( $self, $barcode ) = @_;
437         my( $copy, $evt );
438
439         $logger->debug("Fetching copy by barcode $barcode from cstore");
440
441         $copy = $self->simplereq( 'open-ils.cstore',
442                 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
443                 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
444
445         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
446
447         return ($copy, $evt);
448 }
449
450 sub fetch_open_billable_transaction {
451         my( $self, $transid ) = @_;
452         my( $transaction, $evt );
453
454         $logger->debug("Fetching open billable transaction $transid from cstore");
455
456         $transaction = $self->simplereq(
457                 'open-ils.cstore',
458                 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve',  $transid);
459
460         $evt = OpenILS::Event->new(
461                 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
462
463         return ($transaction, $evt);
464 }
465
466
467
468 my %buckets;
469 $buckets{'biblio'} = 'biblio_record_entry_bucket';
470 $buckets{'callnumber'} = 'call_number_bucket';
471 $buckets{'copy'} = 'copy_bucket';
472 $buckets{'user'} = 'user_bucket';
473
474 sub fetch_container {
475         my( $self, $id, $type ) = @_;
476         my( $bucket, $evt );
477
478         $logger->debug("Fetching container $id with type $type");
479
480         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
481         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
482         $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
483         $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
484
485         my $meth = $buckets{$type};
486         $bucket = $self->simplereq(
487                 'open-ils.cstore',
488                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
489
490         $evt = OpenILS::Event->new(
491                 $e, container => $id, container_type => $type ) unless $bucket;
492
493         return ($bucket, $evt);
494 }
495
496
497 sub fetch_container_e {
498         my( $self, $editor, $id, $type ) = @_;
499
500         my( $bucket, $evt );
501         $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
502         $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
503         $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
504         $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
505
506         $evt = $editor->event unless $bucket;
507         return ($bucket, $evt);
508 }
509
510 sub fetch_container_item_e {
511         my( $self, $editor, $id, $type ) = @_;
512
513         my( $bucket, $evt );
514         $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
515         $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
516         $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
517         $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
518
519         $evt = $editor->event unless $bucket;
520         return ($bucket, $evt);
521 }
522
523
524
525
526
527 sub fetch_container_item {
528         my( $self, $id, $type ) = @_;
529         my( $bucket, $evt );
530
531         $logger->debug("Fetching container item $id with type $type");
532
533         my $meth = $buckets{$type} . "_item";
534
535         $bucket = $self->simplereq(
536                 'open-ils.cstore',
537                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
538
539
540         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
541         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
542         $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
543         $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
544
545         $evt = OpenILS::Event->new(
546                 $e, itemid => $id, container_type => $type ) unless $bucket;
547
548         return ($bucket, $evt);
549 }
550
551
552 sub fetch_patron_standings {
553         my $self = shift;
554         $logger->debug("Fetching patron standings");    
555         return $self->simplereq(
556                 'open-ils.cstore', 
557                 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
558 }
559
560
561 sub fetch_permission_group_tree {
562         my $self = shift;
563         $logger->debug("Fetching patron profiles");     
564         return $self->simplereq(
565                 'open-ils.actor', 
566                 'open-ils.actor.groups.tree.retrieve' );
567 }
568
569 sub fetch_permission_group_descendants {
570     my( $self, $profile ) = @_;
571     my $group_tree = $self->fetch_permission_group_tree();
572     my $start_here;
573     my @groups;
574
575     # FIXME: okay, so it's not an org tree, but it is compatible
576     $self->walk_org_tree($group_tree, sub {
577         my $g = shift;
578         if ($g->id == $profile) {
579             $start_here = $g;
580         }
581     });
582
583     $self->walk_org_tree($start_here, sub {
584         my $g = shift;
585         push(@groups,$g->id);
586     });
587
588     return \@groups;
589 }
590
591 sub fetch_patron_circ_summary {
592         my( $self, $userid ) = @_;
593         $logger->debug("Fetching patron summary for $userid");
594         my $summary = $self->simplereq(
595                 'open-ils.storage', 
596                 "open-ils.storage.action.circulation.patron_summary", $userid );
597
598         if( $summary ) {
599                 $summary->[0] ||= 0;
600                 $summary->[1] ||= 0.0;
601                 return $summary;
602         }
603         return undef;
604 }
605
606
607 sub fetch_copy_statuses {
608         my( $self ) = @_;
609         $logger->debug("Fetching copy statuses");
610         return $self->simplereq(
611                 'open-ils.cstore', 
612                 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
613 }
614
615 sub fetch_copy_location {
616         my( $self, $id ) = @_;
617         my $evt;
618         my $cl = $self->cstorereq(
619                 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
620         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
621         return ($cl, $evt);
622 }
623
624 sub fetch_copy_locations {
625         my $self = shift; 
626         return $self->simplereq(
627                 'open-ils.cstore', 
628                 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
629 }
630
631 sub fetch_copy_location_by_name {
632         my( $self, $name, $org ) = @_;
633         my $evt;
634         my $cl = $self->cstorereq(
635                 'open-ils.cstore.direct.asset.copy_location.search',
636                         { name => $name, owning_lib => $org } );
637         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
638         return ($cl, $evt);
639 }
640
641 sub fetch_callnumber {
642         my( $self, $id, $flesh, $e ) = @_;
643
644         $e ||= OpenILS::Utils::CStoreEditor->new;
645
646         my $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
647         return( undef, $evt ) unless $id;
648
649         $logger->debug("Fetching callnumber $id");
650
651     my $cn = $e->retrieve_asset_call_number([
652         $id,
653         { flesh => $flesh, flesh_fields => { acn => [ 'prefix', 'suffix', 'label_class' ] } },
654     ]);
655
656         return ( $cn, $e->event );
657 }
658
659 my %ORG_CACHE; # - these rarely change, so cache them..
660 sub fetch_org_unit {
661         my( $self, $id ) = @_;
662         return undef unless $id;
663         return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
664         return $ORG_CACHE{$id} if $ORG_CACHE{$id};
665         $logger->debug("Fetching org unit $id");
666         my $evt = undef;
667
668         my $org = $self->simplereq(
669                 'open-ils.cstore', 
670                 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
671         $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
672         $ORG_CACHE{$id}  = $org;
673
674         return ($org, $evt);
675 }
676
677 sub fetch_stat_cat {
678         my( $self, $type, $id ) = @_;
679         my( $cat, $evt );
680         $logger->debug("Fetching $type stat cat: $id");
681         $cat = $self->simplereq(
682                 'open-ils.cstore', 
683                 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
684
685         my $e = 'ASSET_STAT_CAT_NOT_FOUND';
686         $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
687
688         $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
689         return ( $cat, $evt );
690 }
691
692 sub fetch_stat_cat_entry {
693         my( $self, $type, $id ) = @_;
694         my( $entry, $evt );
695         $logger->debug("Fetching $type stat cat entry: $id");
696         $entry = $self->simplereq(
697                 'open-ils.cstore', 
698                 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
699
700         my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
701         $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
702
703         $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
704         return ( $entry, $evt );
705 }
706
707 sub fetch_stat_cat_entry_default {
708     my( $self, $type, $id ) = @_;
709     my( $entry_default, $evt );
710     $logger->debug("Fetching $type stat cat entry default: $id");
711     $entry_default = $self->simplereq(
712         'open-ils.cstore', 
713         "open-ils.cstore.direct.$type.stat_cat_entry_default.retrieve", $id );
714
715     my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
716     $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
717
718     $evt = OpenILS::Event->new( $e, id => $id ) unless $entry_default;
719     return ( $entry_default, $evt );
720 }
721
722 sub fetch_stat_cat_entry_default_by_stat_cat_and_org {
723     my( $self, $type, $stat_cat, $orgId ) = @_;
724     my $entry_default;
725     $logger->info("### Fetching $type stat cat entry default with stat_cat $stat_cat owned by org_unit $orgId");
726     $entry_default = $self->simplereq(
727         'open-ils.cstore', 
728         "open-ils.cstore.direct.$type.stat_cat_entry_default.search.atomic", 
729         { stat_cat => $stat_cat, owner => $orgId } );
730
731     $entry_default = $entry_default->[0];
732     return ($entry_default, undef) if $entry_default;
733
734     my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
735     $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
736     return (undef, OpenILS::Event->new($e) );
737 }
738
739 sub find_org {
740         my( $self, $org_tree, $orgid )  = @_;
741     return undef unless $org_tree and defined $orgid;
742         return $org_tree if ( $org_tree->id eq $orgid );
743         return undef unless ref($org_tree->children);
744         for my $c (@{$org_tree->children}) {
745                 my $o = $self->find_org($c, $orgid);
746                 return $o if $o;
747         }
748         return undef;
749 }
750
751 sub fetch_non_cat_type_by_name_and_org {
752         my( $self, $name, $orgId ) = @_;
753         $logger->debug("Fetching non cat type $name at org $orgId");
754         my $types = $self->simplereq(
755                 'open-ils.cstore',
756                 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
757                 { name => $name, owning_lib => $orgId } );
758         return ($types->[0], undef) if($types and @$types);
759         return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
760 }
761
762 sub fetch_non_cat_type {
763         my( $self, $id ) = @_;
764         $logger->debug("Fetching non cat type $id");
765         my( $type, $evt );
766         $type = $self->simplereq(
767                 'open-ils.cstore', 
768                 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
769         $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
770         return ($type, $evt);
771 }
772
773 sub DB_UPDATE_FAILED { 
774         my( $self, $payload ) = @_;
775         return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
776                 payload => ($payload) ? $payload : undef ); 
777 }
778
779 sub fetch_booking_reservation {
780         my( $self, $id ) = @_;
781         my( $res, $evt );
782
783         $res = $self->simplereq(
784                 'open-ils.cstore', 
785                 'open-ils.cstore.direct.booking.reservation.retrieve', $id
786         );
787
788         # simplereq doesn't know how to flesh so ...
789         if ($res) {
790                 $res->usr(
791                         $self->simplereq(
792                                 'open-ils.cstore', 
793                                 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
794                         )
795                 );
796
797                 $res->target_resource_type(
798                         $self->simplereq(
799                                 'open-ils.cstore', 
800                                 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
801                         )
802                 );
803
804                 if ($res->current_resource) {
805                         $res->current_resource(
806                                 $self->simplereq(
807                                         'open-ils.cstore', 
808                                         'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
809                                 )
810                         );
811
812                         if ($self->is_true( $res->target_resource_type->catalog_item )) {
813                                 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
814                         }
815                 }
816
817                 if ($res->target_resource) {
818                         $res->target_resource(
819                                 $self->simplereq(
820                                         'open-ils.cstore', 
821                                         'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
822                                 )
823                         );
824
825                         if ($self->is_true( $res->target_resource_type->catalog_item )) {
826                                 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
827                         }
828                 }
829
830         } else {
831                 $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
832         }
833
834         return ($res, $evt);
835 }
836
837 sub fetch_circ_duration_by_name {
838         my( $self, $name ) = @_;
839         my( $dur, $evt );
840         $dur = $self->simplereq(
841                 'open-ils.cstore', 
842                 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
843         $dur = $dur->[0];
844         $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
845         return ($dur, $evt);
846 }
847
848 sub fetch_recurring_fine_by_name {
849         my( $self, $name ) = @_;
850         my( $obj, $evt );
851         $obj = $self->simplereq(
852                 'open-ils.cstore', 
853                 'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
854         $obj = $obj->[0];
855         $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
856         return ($obj, $evt);
857 }
858
859 sub fetch_max_fine_by_name {
860         my( $self, $name ) = @_;
861         my( $obj, $evt );
862         $obj = $self->simplereq(
863                 'open-ils.cstore', 
864                 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
865         $obj = $obj->[0];
866         $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
867         return ($obj, $evt);
868 }
869
870 sub fetch_hard_due_date_by_name {
871         my( $self, $name ) = @_;
872         my( $obj, $evt );
873         $obj = $self->simplereq(
874                 'open-ils.cstore', 
875                 'open-ils.cstore.direct.config.hard_due_date.search.atomic', { name => $name } );
876         $obj = $obj->[0];
877         $evt = OpenILS::Event->new('CONFIG_RULES_HARD_DUE_DATE_NOT_FOUND') unless $obj;
878         return ($obj, $evt);
879 }
880
881 sub storagereq {
882         my( $self, $method, @params ) = @_;
883         return $self->simplereq(
884                 'open-ils.storage', $method, @params );
885 }
886
887 sub storagereq_xact {
888         my($self, $method, @params) = @_;
889         my $ses = $self->start_db_session();
890         my $val = $ses->request($method, @params)->gather(1);
891         $self->rollback_db_session($ses);
892     return $val;
893 }
894
895 sub cstorereq {
896         my( $self, $method, @params ) = @_;
897         return $self->simplereq(
898                 'open-ils.cstore', $method, @params );
899 }
900
901 sub event_equals {
902         my( $self, $e, $name ) =  @_;
903         if( $e and ref($e) eq 'HASH' and 
904                 defined($e->{textcode}) and $e->{textcode} eq $name ) {
905                 return 1 ;
906         }
907         return 0;
908 }
909
910 sub logmark {
911         my( undef, $f, $l ) = caller(0);
912         my( undef, undef, undef, $s ) = caller(1);
913         $s =~ s/.*:://g;
914         $f =~ s/.*\///g;
915         $logger->debug("LOGMARK: $f:$l:$s");
916 }
917
918 # takes a copy id 
919 sub fetch_open_circulation {
920         my( $self, $cid ) = @_;
921         $self->logmark;
922
923         my $e = OpenILS::Utils::CStoreEditor->new;
924     my $circ = $e->search_action_circulation({
925         target_copy => $cid, 
926         stop_fines_time => undef, 
927         checkin_time => undef
928     })->[0];
929     
930     return ($circ, $e->event);
931 }
932
933 my $copy_statuses;
934 sub copy_status_from_name {
935         my( $self, $name ) = @_;
936         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
937         for my $status (@$copy_statuses) { 
938                 return $status if( $status->name =~ /$name/i );
939         }
940         return undef;
941 }
942
943 sub copy_status_to_name {
944         my( $self, $sid ) = @_;
945         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
946         for my $status (@$copy_statuses) { 
947                 return $status->name if( $status->id == $sid );
948         }
949         return undef;
950 }
951
952
953 sub copy_status {
954         my( $self, $arg ) = @_;
955         return $arg if ref $arg;
956         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
957         my ($stat) = grep { $_->id == $arg } @$copy_statuses;
958         return $stat;
959 }
960
961 sub fetch_open_transit_by_copy {
962         my( $self, $copyid ) = @_;
963         my($transit, $evt);
964         $transit = $self->cstorereq(
965                 'open-ils.cstore.direct.action.transit_copy.search',
966                 { target_copy => $copyid, dest_recv_time => undef });
967         $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
968         return ($transit, $evt);
969 }
970
971 sub unflesh_copy {
972         my( $self, $copy ) = @_;
973         return undef unless $copy;
974         $copy->status( $copy->status->id ) if ref($copy->status);
975         $copy->location( $copy->location->id ) if ref($copy->location);
976         $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
977         return $copy;
978 }
979
980 sub unflesh_reservation {
981         my( $self, $reservation ) = @_;
982         return undef unless $reservation;
983         $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
984         $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
985         $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
986         $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
987         return $reservation;
988 }
989
990 # un-fleshes a copy and updates it in the DB
991 # returns a DB_UPDATE_FAILED event on error
992 # returns undef on success
993 sub update_copy {
994         my( $self, %params ) = @_;
995
996         my $copy                = $params{copy} || die "update_copy(): copy required";
997         my $editor      = $params{editor} || die "update_copy(): copy editor required";
998         my $session = $params{session};
999
1000         $logger->debug("Updating copy in the database: " . $copy->id);
1001
1002         $self->unflesh_copy($copy);
1003         $copy->editor( $editor );
1004         $copy->edit_date( 'now' );
1005
1006         my $s;
1007         my $meth = 'open-ils.storage.direct.asset.copy.update';
1008
1009         $s = $session->request( $meth, $copy )->gather(1) if $session;
1010         $s = $self->storagereq( $meth, $copy ) unless $session;
1011
1012         $logger->debug("Update of copy ".$copy->id." returned: $s");
1013
1014         return $self->DB_UPDATE_FAILED($copy) unless $s;
1015         return undef;
1016 }
1017
1018 sub update_reservation {
1019         my( $self, %params ) = @_;
1020
1021         my $reservation = $params{reservation}  || die "update_reservation(): reservation required";
1022         my $editor              = $params{editor} || die "update_reservation(): copy editor required";
1023         my $session             = $params{session};
1024
1025         $logger->debug("Updating copy in the database: " . $reservation->id);
1026
1027         $self->unflesh_reservation($reservation);
1028
1029         my $s;
1030         my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1031
1032         $s = $session->request( $meth, $reservation )->gather(1) if $session;
1033         $s = $self->cstorereq( $meth, $reservation ) unless $session;
1034
1035         $logger->debug("Update of copy ".$reservation->id." returned: $s");
1036
1037         return $self->DB_UPDATE_FAILED($reservation) unless $s;
1038         return undef;
1039 }
1040
1041 sub fetch_billable_xact {
1042         my( $self, $id ) = @_;
1043         my($xact, $evt);
1044         $logger->debug("Fetching billable transaction %id");
1045         $xact = $self->cstorereq(
1046                 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1047         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1048         return ($xact, $evt);
1049 }
1050
1051 sub fetch_billable_xact_summary {
1052         my( $self, $id ) = @_;
1053         my($xact, $evt);
1054         $logger->debug("Fetching billable transaction summary %id");
1055         $xact = $self->cstorereq(
1056                 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1057         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1058         return ($xact, $evt);
1059 }
1060
1061 sub fetch_fleshed_copy {
1062         my( $self, $id ) = @_;
1063         my( $copy, $evt );
1064         $logger->info("Fetching fleshed copy $id");
1065         $copy = $self->cstorereq(
1066                 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1067                 { flesh => 1,
1068                   flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1069                 }
1070         );
1071         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1072         return ($copy, $evt);
1073 }
1074
1075
1076 # returns the org that owns the callnumber that the copy
1077 # is attached to
1078 sub fetch_copy_owner {
1079         my( $self, $copyid ) = @_;
1080         my( $copy, $cn, $evt );
1081         $logger->debug("Fetching copy owner $copyid");
1082         ($copy, $evt) = $self->fetch_copy($copyid);
1083         return (undef,$evt) if $evt;
1084         ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1085         return (undef,$evt) if $evt;
1086         return ($cn->owning_lib);
1087 }
1088
1089 sub fetch_copy_note {
1090         my( $self, $id ) = @_;
1091         my( $note, $evt );
1092         $logger->debug("Fetching copy note $id");
1093         $note = $self->cstorereq(
1094                 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1095         $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1096         return ($note, $evt);
1097 }
1098
1099 sub fetch_call_numbers_by_title {
1100         my( $self, $titleid ) = @_;
1101         $logger->info("Fetching call numbers by title $titleid");
1102         return $self->cstorereq(
1103                 'open-ils.cstore.direct.asset.call_number.search.atomic', 
1104                 { record => $titleid, deleted => 'f' });
1105                 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1106 }
1107
1108 sub fetch_copies_by_call_number {
1109         my( $self, $cnid ) = @_;
1110         $logger->info("Fetching copies by call number $cnid");
1111         return $self->cstorereq(
1112                 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1113                 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1114 }
1115
1116 sub fetch_user_by_barcode {
1117         my( $self, $bc ) = @_;
1118         my $cardid = $self->cstorereq(
1119                 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1120         return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1121         my $user = $self->cstorereq(
1122                 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1123         return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1124         return ($user);
1125         
1126 }
1127
1128 sub fetch_bill {
1129         my( $self, $billid ) = @_;
1130         $logger->debug("Fetching billing $billid");
1131         my $bill = $self->cstorereq(
1132                 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1133         my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1134         return($bill, $evt);
1135 }
1136
1137 sub walk_org_tree {
1138         my( $self, $node, $callback ) = @_;
1139         return unless $node;
1140         $callback->($node);
1141         if( $node->children ) {
1142                 $self->walk_org_tree($_, $callback) for @{$node->children};
1143         }
1144 }
1145
1146 sub is_true {
1147         my( $self, $item ) = @_;
1148         return 1 if $item and $item !~ /^f$/i;
1149         return 0;
1150 }
1151
1152
1153 sub patientreq {
1154     my ($self, $client, $service, $method, @params) = @_;
1155     my ($response, $err);
1156
1157     my $session = create OpenSRF::AppSession($service);
1158     my $request = $session->request($method, @params);
1159
1160     my $spurt = 10;
1161     my $give_up = time + 1000;
1162
1163     try {
1164         while (time < $give_up) {
1165             $response = $request->recv("timeout" => $spurt);
1166             last if $request->complete;
1167
1168             $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1169         }
1170     } catch Error with {
1171         $err = shift;
1172     };
1173
1174     if ($err) {
1175         warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
1176         throw $err ("Call to $service for method $method \n failed with exception: $err : " );
1177     }
1178
1179     return $response->content;
1180 }
1181
1182 # This logic now lives in storage
1183 sub __patron_money_owed {
1184         my( $self, $patronid ) = @_;
1185         my $ses = OpenSRF::AppSession->create('open-ils.storage');
1186         my $req = $ses->request(
1187                 'open-ils.storage.money.billable_transaction.summary.search',
1188                 { usr => $patronid, xact_finish => undef } );
1189
1190         my $total = 0;
1191         my $data;
1192         while( $data = $req->recv ) {
1193                 $data = $data->content;
1194                 $total += $data->balance_owed;
1195         }
1196         return $total;
1197 }
1198
1199 sub patron_money_owed {
1200         my( $self, $userid ) = @_;
1201         my $ses = $self->start_db_session();
1202         my $val = $ses->request(
1203                 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1204         $self->rollback_db_session($ses);
1205         return $val;
1206 }
1207
1208 sub patron_total_items_out {
1209         my( $self, $userid ) = @_;
1210         my $ses = $self->start_db_session();
1211         my $val = $ses->request(
1212                 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1213         $self->rollback_db_session($ses);
1214         return $val;
1215 }
1216
1217
1218
1219
1220 #---------------------------------------------------------------------
1221 # Returns  ($summary, $event) 
1222 #---------------------------------------------------------------------
1223 sub fetch_mbts {
1224         my $self = shift;
1225         my $id  = shift;
1226         my $e = shift || OpenILS::Utils::CStoreEditor->new;
1227         $id = $id->id if ref($id);
1228     
1229     my $xact = $e->retrieve_money_billable_transaction_summary($id)
1230             or return (undef, $e->event);
1231
1232     return ($xact);
1233 }
1234
1235
1236 #---------------------------------------------------------------------
1237 # Given a list of money.billable_transaction objects, this creates
1238 # transaction summary objects for each
1239 #--------------------------------------------------------------------
1240 sub make_mbts {
1241         my $self = shift;
1242     my $e = shift;
1243         my @xacts = @_;
1244         return () if (!@xacts);
1245     return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1246 }
1247                 
1248                 
1249 sub ou_ancestor_setting_value {
1250     my($self, $org_id, $name, $e) = @_;
1251     $e = $e || OpenILS::Utils::CStoreEditor->new;
1252     my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1253     return $set->{value} if $set;
1254     return undef;
1255 }
1256
1257
1258 # If an authentication token is provided AND this org unit setting has a
1259 # view_perm, then make sure the user referenced by the auth token has
1260 # that permission.  This means that if you call this method without an
1261 # authtoken param, you can get whatever org unit setting values you want.
1262 # API users beware.
1263 #
1264 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1265 # authtoken is checked, but the $auth arg is NOT checked.  To say that another
1266 # way, be sure NOT to pass an editor argument if you want your token checked.
1267 # Otherwise the auth arg is just a flag saying "check the editor".  
1268
1269 sub ou_ancestor_setting {
1270     my( $self, $orgid, $name, $e, $auth ) = @_;
1271     $e = $e || OpenILS::Utils::CStoreEditor->new(
1272         (defined $auth) ? (authtoken => $auth) : ()
1273     );
1274     my $coust = $e->retrieve_config_org_unit_setting_type([
1275         $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1276     ]);
1277
1278     if ($auth && $coust && $coust->view_perm) {
1279         # And you can't have permission if you don't have a valid session.
1280         return undef if not $e->checkauth;
1281         # And now that we know you MIGHT have permission, we check it.
1282         return undef if not $e->allowed($coust->view_perm->code, $orgid);
1283     }
1284
1285     my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1286     my $setting = $e->json_query($query)->[0];
1287     return undef unless $setting;
1288     return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1289 }       
1290                 
1291
1292 # returns the ISO8601 string representation of the requested epoch in GMT
1293 sub epoch2ISO8601 {
1294     my( $self, $epoch ) = @_;
1295     my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1296     $year += 1900; $mon += 1;
1297     my $date = sprintf(
1298         '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1299         $year, $mon, $mday, $hour, $min, $sec);
1300     return $date;
1301 }
1302                         
1303 sub find_highest_perm_org {
1304         my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1305         my $org = $self->find_org($org_tree, $start_org );
1306
1307         my $lastid = -1;
1308         while( $org ) {
1309                 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1310                 $lastid = $org->id;
1311                 $org = $self->find_org( $org_tree, $org->parent_ou() );
1312         }
1313
1314         return $lastid;
1315 }
1316
1317
1318 # returns the org_unit ID's 
1319 sub user_has_work_perm_at {
1320     my($self, $e, $perm, $options, $user_id) = @_;
1321     $options ||= {};
1322     $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1323
1324     my $func = 'permission.usr_has_perm_at';
1325     $func = $func.'_all' if $$options{descendants};
1326
1327     my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1328     $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1329
1330     return $orgs unless $$options{objects};
1331
1332     return $e->search_actor_org_unit({id => $orgs});
1333 }
1334
1335 sub get_user_work_ou_ids {
1336     my($self, $e, $userid) = @_;
1337     my $work_orgs = $e->json_query({
1338         select => {puwoum => ['work_ou']},
1339         from => 'puwoum',
1340         where => {usr => $e->requestor->id}});
1341
1342     return [] unless @$work_orgs;
1343     my @work_orgs;
1344     push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1345
1346     return \@work_orgs;
1347 }
1348
1349
1350 my $org_types;
1351 sub get_org_types {
1352         my($self, $client) = @_;
1353         return $org_types if $org_types;
1354         return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1355 }
1356
1357 my %ORG_TREE;
1358 sub get_org_tree {
1359         my $self = shift;
1360         my $locale = shift || '';
1361         my $cache = OpenSRF::Utils::Cache->new("global", 0);
1362         my $tree = $ORG_TREE{$locale} || $cache->get_cache("orgtree.$locale");
1363         return $tree if $tree;
1364
1365         my $ses = OpenILS::Utils::CStoreEditor->new;
1366         $ses->session->session_locale($locale);
1367         $tree = $ses->search_actor_org_unit( 
1368                 [
1369                         {"parent_ou" => undef },
1370                         {
1371                                 flesh                           => -1,
1372                                 flesh_fields    => { aou =>  ['children'] },
1373                                 order_by                        => { aou => 'name'}
1374                         }
1375                 ]
1376         )->[0];
1377
1378     $ORG_TREE{$locale} = $tree;
1379         $cache->put_cache("orgtree.$locale", $tree);
1380         return $tree;
1381 }
1382
1383 sub get_org_descendants {
1384         my($self, $org_id, $depth) = @_;
1385
1386         my $select = {
1387                 transform => 'actor.org_unit_descendants',
1388                 column => 'id',
1389                 result_field => 'id',
1390         };
1391         $select->{params} = [$depth] if defined $depth;
1392
1393         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1394                 select => {aou => [$select]},
1395         from => 'aou',
1396                 where => {id => $org_id}
1397         });
1398         my @orgs;
1399         push(@orgs, $_->{id}) for @$org_list;
1400         return \@orgs;
1401 }
1402
1403 sub get_org_ancestors {
1404         my($self, $org_id, $use_cache) = @_;
1405
1406     my ($cache, $orgs);
1407
1408     if ($use_cache) {
1409         $cache = OpenSRF::Utils::Cache->new("global", 0);
1410         $orgs = $cache->get_cache("org.ancestors.$org_id");
1411         return $orgs if $orgs;
1412     }
1413
1414         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1415                 select => {
1416                         aou => [{
1417                                 transform => 'actor.org_unit_ancestors',
1418                                 column => 'id',
1419                                 result_field => 'id',
1420                                 params => []
1421                         }],
1422                 },
1423                 from => 'aou',
1424                 where => {id => $org_id}
1425         });
1426
1427         $orgs = [ map { $_->{id} } @$org_list ];
1428
1429     $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1430         return $orgs;
1431 }
1432
1433 sub get_org_full_path {
1434         my($self, $org_id, $depth) = @_;
1435
1436     my $query = {
1437         select => {
1438                         aou => [{
1439                                 transform => 'actor.org_unit_full_path',
1440                                 column => 'id',
1441                                 result_field => 'id',
1442                         }],
1443                 },
1444                 from => 'aou',
1445                 where => {id => $org_id}
1446         };
1447
1448     $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1449         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1450     return [ map {$_->{id}} @$org_list ];
1451 }
1452
1453 # returns the ID of the org unit ancestor at the specified depth
1454 sub org_unit_ancestor_at_depth {
1455     my($class, $org_id, $depth) = @_;
1456     my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1457         {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1458     return ($resp) ? $resp->{id} : undef;
1459 }
1460
1461 # returns the user's configured locale as a string.  Defaults to en-US if none is configured.
1462 sub get_user_locale {
1463         my($self, $user_id, $e) = @_;
1464         $e ||= OpenILS::Utils::CStoreEditor->new;
1465
1466         # first, see if the user has an explicit locale set
1467         my $setting = $e->search_actor_user_setting(
1468                 {usr => $user_id, name => 'global.locale'})->[0];
1469         return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1470
1471         my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1472         return $self->get_org_locale($user->home_ou, $e);
1473 }
1474
1475 # returns org locale setting
1476 sub get_org_locale {
1477         my($self, $org_id, $e) = @_;
1478         $e ||= OpenILS::Utils::CStoreEditor->new;
1479
1480         my $locale;
1481         if(defined $org_id) {
1482                 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1483                 return $locale if $locale;
1484         }
1485
1486         # system-wide default
1487         my $sclient = OpenSRF::Utils::SettingsClient->new;
1488         $locale = $sclient->config_value('default_locale');
1489     return $locale if $locale;
1490
1491         # if nothing else, fallback to locale=cowboy
1492         return 'en-US';
1493 }
1494
1495
1496 # xml-escape non-ascii characters
1497 sub entityize { 
1498     my($self, $string, $form) = @_;
1499         $form ||= "";
1500
1501         # If we're going to convert non-ASCII characters to XML entities,
1502         # we had better be dealing with a UTF8 string to begin with
1503         $string = decode_utf8($string);
1504
1505         if ($form eq 'D') {
1506                 $string = NFD($string);
1507         } else {
1508                 $string = NFC($string);
1509         }
1510
1511         # Convert raw ampersands to entities
1512         $string =~ s/&(?!\S+;)/&amp;/gso;
1513
1514         # Convert Unicode characters to entities
1515         $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1516
1517         return $string;
1518 }
1519
1520 # x0000-x0008 isn't legal in XML documents
1521 # XXX Perhaps this should just go into our standard entityize method
1522 sub strip_ctrl_chars {
1523         my ($self, $string) = @_;
1524
1525         $string =~ s/([\x{0000}-\x{0008}])//sgoe; 
1526         return $string;
1527 }
1528
1529 sub get_copy_price {
1530         my($self, $e, $copy, $volume) = @_;
1531
1532         $copy->price(0) if $copy->price and $copy->price < 0;
1533
1534         return $copy->price if $copy->price and $copy->price > 0;
1535
1536
1537         my $owner;
1538         if(ref $volume) {
1539                 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1540                         $owner = $copy->circ_lib;
1541                 } else {
1542                         $owner = $volume->owning_lib;
1543                 }
1544         } else {
1545                 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1546                         $owner = $copy->circ_lib;
1547                 } else {
1548                         $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1549                 }
1550         }
1551
1552         my $default_price = $self->ou_ancestor_setting_value(
1553                 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1554
1555         return $default_price unless defined $copy->price;
1556
1557         # price is 0.  Use the default?
1558     my $charge_on_0 = $self->ou_ancestor_setting_value(
1559         $owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e) || 0;
1560
1561         return $default_price if $charge_on_0;
1562         return 0;
1563 }
1564
1565 # given a transaction ID, this returns the context org_unit for the transaction
1566 sub xact_org {
1567     my($self, $xact_id, $e) = @_;
1568     $e ||= OpenILS::Utils::CStoreEditor->new;
1569     
1570     my $loc = $e->json_query({
1571         "select" => {circ => ["circ_lib"]},
1572         from     => "circ",
1573         "where"  => {id => $xact_id},
1574     });
1575
1576     return $loc->[0]->{circ_lib} if @$loc;
1577
1578     $loc = $e->json_query({
1579         "select" => {bresv => ["request_lib"]},
1580         from     => "bresv",
1581         "where"  => {id => $xact_id},
1582     });
1583
1584     return $loc->[0]->{request_lib} if @$loc;
1585
1586     $loc = $e->json_query({
1587         "select" => {mg => ["billing_location"]},
1588         from     => "mg",
1589         "where"  => {id => $xact_id},
1590     });
1591
1592     return $loc->[0]->{billing_location};
1593 }
1594
1595
1596 sub find_event_def_by_hook {
1597     my($self, $hook, $context_org, $e) = @_;
1598
1599     $e ||= OpenILS::Utils::CStoreEditor->new;
1600
1601     my $orgs = $self->get_org_ancestors($context_org);
1602
1603     # search from the context org up
1604     for my $org_id (reverse @$orgs) {
1605
1606         my $def = $e->search_action_trigger_event_definition(
1607             {hook => $hook, owner => $org_id})->[0];
1608
1609         return $def if $def;
1610     }
1611
1612     return undef;
1613 }
1614
1615
1616
1617 # If an event_def ID is not provided, use the hook and context org to find the 
1618 # most appropriate event.  create the event, fire it, then return the resulting
1619 # event with fleshed template_output and error_output
1620 sub fire_object_event {
1621     my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1622
1623     my $e = OpenILS::Utils::CStoreEditor->new;
1624     my $def;
1625
1626     my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1627
1628     if($event_def) {
1629         $def = $e->retrieve_action_trigger_event_definition($event_def)
1630             or return $e->event;
1631
1632         $auto_method .= '.include_inactive';
1633
1634     } else {
1635
1636         # find the most appropriate event def depending on context org
1637         $def = $self->find_event_def_by_hook($hook, $context_org, $e) 
1638             or return $e->event;
1639     }
1640
1641     my $final_resp;
1642
1643     if($def->group_field) {
1644         # we have a list of objects
1645         $object = [$object] unless ref $object eq 'ARRAY';
1646
1647         my @event_ids;
1648         $user_data ||= [];
1649         for my $i (0..$#$object) {
1650             my $obj = $$object[$i];
1651             my $udata = $$user_data[$i];
1652             my $event_id = $self->simplereq(
1653                 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1654             push(@event_ids, $event_id);
1655         }
1656
1657         $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1658
1659         my $resp;
1660         if (not defined $client) {
1661             $resp = $self->simplereq(
1662                 'open-ils.trigger',
1663                 'open-ils.trigger.event_group.fire',
1664                 \@event_ids);
1665         } else {
1666             $resp = $self->patientreq(
1667                 $client,
1668                 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1669                 \@event_ids
1670             );
1671         }
1672
1673         if($resp and $resp->{events} and @{$resp->{events}}) {
1674
1675             $e->xact_begin;
1676             $final_resp = $e->retrieve_action_trigger_event([
1677                 $resp->{events}->[0]->id,
1678                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1679             ]);
1680             $e->rollback;
1681         }
1682
1683     } else {
1684
1685         $object = $$object[0] if ref $object eq 'ARRAY';
1686
1687         my $event_id;
1688         my $resp;
1689
1690         if (not defined $client) {
1691             $event_id = $self->simplereq(
1692                 'open-ils.trigger',
1693                 $auto_method, $def->id, $object, $context_org, $user_data
1694             );
1695
1696             $resp = $self->simplereq(
1697                 'open-ils.trigger',
1698                 'open-ils.trigger.event.fire',
1699                 $event_id
1700             );
1701         } else {
1702             $event_id = $self->patientreq(
1703                 $client,
1704                 'open-ils.trigger',
1705                 $auto_method, $def->id, $object, $context_org, $user_data
1706             );
1707
1708             $resp = $self->patientreq(
1709                 $client,
1710                 'open-ils.trigger',
1711                 'open-ils.trigger.event.fire',
1712                 $event_id
1713             );
1714         }
1715         
1716         if($resp and $resp->{event}) {
1717             $e->xact_begin;
1718             $final_resp = $e->retrieve_action_trigger_event([
1719                 $resp->{event}->id,
1720                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1721             ]);
1722             $e->rollback;
1723         }
1724     }
1725
1726     return $final_resp;
1727 }
1728
1729
1730 sub create_events_for_hook {
1731     my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1732     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1733     my $req = $ses->request('open-ils.trigger.event.autocreate', 
1734         $hook, $obj, $org_id, $granularity, $user_data);
1735     return undef unless $wait;
1736     my $resp = $req->recv;
1737     return $resp->content if $resp;
1738 }
1739
1740 sub create_uuid_string {
1741     return create_UUID_as_string();
1742 }
1743
1744 sub create_circ_chain_summary {
1745     my($class, $e, $circ_id) = @_;
1746     my $sum = $e->json_query({from => ['action.summarize_circ_chain', $circ_id]})->[0];
1747     return undef unless $sum;
1748     my $obj = Fieldmapper::action::circ_chain_summary->new;
1749     $obj->$_($sum->{$_}) for keys %$sum;
1750     return $obj;
1751 }
1752
1753
1754 # Returns "mra" attribute key/value pairs for a set of bre's
1755 # Takes a list of bre IDs, returns a hash of hashes,
1756 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1757 my $ccvm_cache;
1758 sub get_bre_attrs {
1759     my ($class, $bre_ids, $e) = @_;
1760     $e = $e || OpenILS::Utils::CStoreEditor->new;
1761
1762     my $attrs = {};
1763     return $attrs unless defined $bre_ids;
1764     $bre_ids = [$bre_ids] unless ref $bre_ids;
1765
1766     my $mra = $e->json_query({
1767         select => {
1768             mra => [
1769                 {
1770                     column => 'id',
1771                     alias => 'bre'
1772                 }, {
1773                     column => 'attrs',
1774                     transform => 'each',
1775                     result_field => 'key',
1776                     alias => 'key'
1777                 },{
1778                     column => 'attrs',
1779                     transform => 'each',
1780                     result_field => 'value',
1781                     alias => 'value'
1782                 }
1783             ]
1784         },
1785         from => 'mra',
1786         where => {id => $bre_ids}
1787     });
1788
1789     return $attrs unless $mra;
1790
1791     $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
1792
1793     for my $id (@$bre_ids) {
1794         $attrs->{$id} = {};
1795         for my $mra (grep { $_->{bre} eq $id } @$mra) {
1796             my $ctype = $mra->{key};
1797             my $code = $mra->{value};
1798             $attrs->{$id}->{$ctype} = {code => $code};
1799             if($code) {
1800                 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
1801                 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
1802             }
1803         }
1804     }
1805
1806     return $attrs;
1807 }
1808
1809 # Shorter version of bib_container_items_via_search() below, only using
1810 # the queryparser record_list filter instead of the container filter.
1811 sub bib_record_list_via_search {
1812     my ($class, $search_query, $search_args) = @_;
1813
1814     # First, Use search API to get container items sorted in any way that crad
1815     # sorters support.
1816     my $search_result = $class->simplereq(
1817         "open-ils.search", "open-ils.search.biblio.multiclass.query",
1818         $search_args, $search_query
1819     );
1820
1821     unless ($search_result) {
1822         # empty result sets won't cause this, but actual errors should.
1823         $logger->warn("bib_record_list_via_search() got nothing from search");
1824         return;
1825     }
1826
1827     # Throw away other junk from search, keeping only bib IDs.
1828     return [ map { pop @$_ } @{$search_result->{ids}} ];
1829 }
1830
1831 # 'no_flesh' avoids fleshing the target_biblio_record_entry
1832 sub bib_container_items_via_search {
1833     my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
1834
1835     # First, Use search API to get container items sorted in any way that crad
1836     # sorters support.
1837     my $search_result = $class->simplereq(
1838         "open-ils.search", "open-ils.search.biblio.multiclass.query",
1839         $search_args, $search_query
1840     );
1841     unless ($search_result) {
1842         # empty result sets won't cause this, but actual errors should.
1843         $logger->warn("bib_container_items_via_search() got nothing from search");
1844         return;
1845     }
1846
1847     # Throw away other junk from search, keeping only bib IDs.
1848     my $id_list = [ map { pop @$_ } @{$search_result->{ids}} ];
1849
1850     return [] unless @$id_list;
1851
1852     # Now get the bib container items themselves...
1853     my $e = new OpenILS::Utils::CStoreEditor;
1854     unless ($e) {
1855         $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
1856         return;
1857     }
1858
1859     my @flesh_fields = qw/notes/;
1860     push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
1861
1862     my $items = $e->search_container_biblio_record_entry_bucket_item([
1863         {
1864             "target_biblio_record_entry" => $id_list,
1865             "bucket" => $container_id
1866         }, {
1867             flesh => 1,
1868             flesh_fields => {"cbrebi" => \@flesh_fields}
1869         }
1870     ]);
1871     unless ($items) {
1872         $logger->warn(
1873             "bib_container_items_via_search() couldn't get bucket items: " .
1874             $e->die_event->{textcode}
1875         );
1876         return;
1877     }
1878
1879     # ... and put them in the same order that the search API said they
1880     # should be in.
1881     my %ordering_hash = map { 
1882         ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id, 
1883         $_ 
1884     } @$items;
1885
1886     return [map { $ordering_hash{$_} } @$id_list];
1887 }
1888
1889 # returns undef on success, Event on error
1890 sub log_user_activity {
1891     my ($class, $user_id, $who, $what, $e, $async) = @_;
1892
1893     my $commit = 0;
1894     if (!$e) {
1895         $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
1896         $commit = 1;
1897     }
1898
1899     my $res = $e->json_query({
1900         from => [
1901             'actor.insert_usr_activity', 
1902             $user_id, $who, $what, OpenSRF::AppSession->ingress
1903         ]
1904     });
1905
1906     if ($res) { # call returned OK
1907
1908         $e->commit   if $commit and @$res;
1909         $e->rollback if $commit and !@$res;
1910
1911     } else {
1912         return $e->die_event;
1913     }
1914
1915     return undef;
1916 }
1917
1918 # I hate to put this here exactly, but this code needs to be shared between
1919 # the TPAC's mod_perl module and open-ils.serial.
1920 #
1921 # There is a reason every part of the query *except* those parts dealing
1922 # with scope are moved here from the code's origin in TPAC.  The serials
1923 # use case does *not* want the same scoping logic.
1924 #
1925 # Also, note that for the serials uses case, we may filter in OPAC visible
1926 # status and copy/call_number deletedness, but we don't filter on any
1927 # particular values for serial.item.status or serial.item.date_received.
1928 # Since we're only using this *after* winnowing down the set of issuances
1929 # that copies should be related to, I'm not sure we need any such serial.item
1930 # filters.
1931
1932 sub basic_opac_copy_query {
1933     ######################################################################
1934     # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
1935     # not both.                                                          #
1936     ######################################################################
1937     my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
1938
1939     return {
1940         select => {
1941             acp => ['id', 'barcode', 'circ_lib', 'create_date',
1942                     'age_protect', 'holdable'],
1943             acpl => [
1944                 {column => 'name', alias => 'copy_location'},
1945                 {column => 'holdable', alias => 'location_holdable'}
1946             ],
1947             ccs => [
1948                 {column => 'name', alias => 'copy_status'},
1949                 {column => 'holdable', alias => 'status_holdable'}
1950             ],
1951             acn => [
1952                 {column => 'label', alias => 'call_number_label'},
1953                 {column => 'id', alias => 'call_number'}
1954             ],
1955             circ => ['due_date'],
1956             acnp => [
1957                 {column => 'label', alias => 'call_number_prefix_label'},
1958                 {column => 'id', alias => 'call_number_prefix'}
1959             ],
1960             acns => [
1961                 {column => 'label', alias => 'call_number_suffix_label'},
1962                 {column => 'id', alias => 'call_number_suffix'}
1963             ],
1964             bmp => [
1965                 {column => 'label', alias => 'part_label'},
1966             ],
1967             ($iss_id ? (sitem => ["issuance"]) : ())
1968         },
1969
1970         from => {
1971             acp => {
1972                 ($iss_id ? (
1973                     sitem => {
1974                         fkey => 'id',
1975                         field => 'unit',
1976                         filter => {issuance => $iss_id},
1977                         join => {
1978                             sstr => { }
1979                         }
1980                     }
1981                 ) : ()),
1982                 acn => {
1983                     join => {
1984                         acnp => { fkey => 'prefix' },
1985                         acns => { fkey => 'suffix' }
1986                     },
1987                     filter => [
1988                         {deleted => 'f'},
1989                         ($rec_id ? {record => $rec_id} : ())
1990                     ],
1991                 },
1992                 circ => { # If the copy is circulating, retrieve the open circ
1993                     type => 'left',
1994                     filter => {checkin_time => undef}
1995                 },
1996                 acpl => {
1997                     ($staff ? () : (filter => { opac_visible => 't' }))
1998                 },
1999                 ccs => {
2000                     ($staff ? () : (filter => { opac_visible => 't' }))
2001                 },
2002                 aou => {},
2003                 acpm => {
2004                     type => 'left',
2005                     join => {
2006                         bmp => { type => 'left' }
2007                     }
2008                 }
2009             }
2010         },
2011
2012         where => {
2013             '+acp' => {
2014                 deleted => 'f',
2015                 ($staff ? () : (opac_visible => 't'))
2016             },
2017             ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2018             ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2019         },
2020
2021         order_by => [
2022             {class => 'aou', field => 'name'},
2023             {class => 'acn', field => 'label'}
2024         ],
2025
2026         limit => $copy_limit,
2027         offset => $copy_offset
2028     };
2029 }
2030
2031 1;
2032