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