]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/AppUtils.pm
updated xact retrieval to do a ranged retrieval by org and not just org id
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / AppUtils.pm
1 package OpenILS::Application::AppUtils;
2 use strict; use warnings;
3 use base qw/OpenSRF::Application/;
4 use OpenSRF::Utils::Cache;
5 use OpenSRF::Utils::Logger qw/$logger/;
6 use OpenILS::Utils::ModsParser;
7 use OpenSRF::EX qw(:try);
8 use OpenILS::Event;
9 use Data::Dumper;
10 use OpenILS::Utils::CStoreEditor;
11
12
13 my $cache_client = "OpenSRF::Utils::Cache";
14
15 my $storage_session = undef;
16
17 # ---------------------------------------------------------------------------
18 # Pile of utilty methods used accross applications.
19 # ---------------------------------------------------------------------------
20
21
22 # ---------------------------------------------------------------------------
23 # on sucess, returns the created session, on failure throws ERROR exception
24 # ---------------------------------------------------------------------------
25 sub start_db_session {
26
27         my $self = shift;
28         my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
29         my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
30
31         my $trans_resp = $trans_req->recv();
32         if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
33         if( ! $trans_resp->content() ) {
34                 throw OpenSRF::ERROR 
35                         ("Unable to Begin Transaction with database" );
36         }
37         $trans_req->finish();
38
39         $logger->debug("Setting global storage session to ".
40                 "session: " . $session->session_id . " : " . $session->app );
41
42         $storage_session = $session;
43         return $session;
44 }
45
46
47 # returns undef if user has all of the perms provided
48 # returns the first failed perm on failure
49 sub check_user_perms {
50         my($self, $user_id, $org_id, @perm_types ) = @_;
51         $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
52         for my $type (@perm_types) {
53                 return $type unless ($self->storagereq(
54                         "open-ils.storage.permission.user_has_perm", 
55                         $user_id, $type, $org_id ));
56         }
57         return undef;
58 }
59
60 # checks the list of user perms.  The first one that fails returns a new
61 sub check_perms {
62         my( $self, $user_id, $org_id, @perm_types ) = @_;
63         my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
64         return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
65         return undef;
66 }
67
68
69
70 # ---------------------------------------------------------------------------
71 # commits and destroys the session
72 # ---------------------------------------------------------------------------
73 sub commit_db_session {
74         my( $self, $session ) = @_;
75
76         my $req = $session->request( "open-ils.storage.transaction.commit" );
77         my $resp = $req->recv();
78
79         if(!$resp) {
80                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
81         }
82
83         if(UNIVERSAL::isa($resp,"Error")) { 
84                 throw $resp ($resp->stringify); 
85         }
86
87         if(!$resp->content) {
88                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
89         }
90
91         $session->finish();
92         $session->disconnect();
93         $session->kill_me();
94         $storage_session = undef;
95 }
96
97 sub rollback_db_session {
98         my( $self, $session ) = @_;
99
100         my $req = $session->request("open-ils.storage.transaction.rollback");
101         my $resp = $req->recv();
102         if(UNIVERSAL::isa($resp,"Error")) { throw $resp;  }
103
104         $session->finish();
105         $session->disconnect();
106         $session->kill_me();
107         $storage_session = undef;
108 }
109
110
111 # returns undef it the event is not an ILS event
112 # returns the event code otherwise
113 sub event_code {
114         my( $self, $evt ) = @_;
115         return $evt->{ilsevent} if( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
116         return undef;
117 }
118
119 # ---------------------------------------------------------------------------
120 # Checks to see if a user is logged in.  Returns the user record on success,
121 # throws an exception on error.
122 # ---------------------------------------------------------------------------
123 sub check_user_session {
124
125         my( $self, $user_session ) = @_;
126
127         my $content = $self->simplereq( 
128                 'open-ils.auth', 
129                 'open-ils.auth.session.retrieve', $user_session );
130
131
132         if(! $content or $self->event_code($content)) {
133                 throw OpenSRF::EX::ERROR 
134                         ("Session [$user_session] cannot be authenticated" );
135         }
136
137         $logger->debug("Fetch user session $user_session found user " . $content->id );
138
139         return $content;
140 }
141
142 # generic simple request returning a scalar value
143 sub simplereq {
144         my($self, $service, $method, @params) = @_;
145         return $self->simple_scalar_request($service, $method, @params);
146 }
147
148 sub get_storage_session {
149
150         return undef; # XXX testing
151
152         if(     $storage_session and 
153                         $storage_session->connected and
154                         $storage_session->transport_connected and
155                         $storage_session->app eq 'open-ils.storage' ) {
156
157                 $logger->debug("get_storage_session(): returning existing session");
158                 return $storage_session;
159         }
160         $logger->debug("get_storage_session(): returning undef");
161         $storage_session = undef;
162         return undef;
163 }
164
165
166 sub simple_scalar_request {
167         my($self, $service, $method, @params) = @_;
168
169         my $session = undef;
170
171         if( $service eq 'open-ils.storage' ) {
172                 if( $session = get_storage_session() ) {
173                         $logger->debug("simple request using existing storage session ".$session->session_id);
174                 } else { $session = undef; }
175         }
176
177         $session = OpenSRF::AppSession->create( $service ) unless $session;
178
179         my $request = $session->request( $method, @params );
180
181         my $val;
182         my $err;
183         try  {
184
185                 $val = $request->gather(1);     
186
187         } catch Error with {
188                 $err = shift;
189         };
190
191         if( $err ) {
192                 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
193                 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
194         }
195
196         return $val;
197 }
198
199
200
201
202
203 my $tree                                                = undef;
204 my $orglist                                     = undef;
205 my $org_typelist                        = undef;
206 my $org_typelist_hash   = {};
207
208 sub get_org_tree {
209
210         my $self = shift;
211         if($tree) { return $tree; }
212
213         # see if it's in the cache
214         $tree = $cache_client->new()->get_cache('_orgtree');
215         if($tree) { return $tree; }
216
217         if(!$orglist) {
218                 warn "Retrieving Org Tree\n";
219                 $orglist = $self->simple_scalar_request( 
220                         "open-ils.storage", 
221                         "open-ils.storage.direct.actor.org_unit.retrieve.all.atomic" );
222         }
223
224         if( ! $org_typelist ) {
225                 warn "Retrieving org types\n";
226                 $org_typelist = $self->simple_scalar_request( 
227                         "open-ils.storage", 
228                         "open-ils.storage.direct.actor.org_unit_type.retrieve.all.atomic" );
229                 $self->build_org_type($org_typelist);
230         }
231
232         $tree = $self->build_org_tree($orglist,1);
233         $cache_client->new()->put_cache('_orgtree', $tree);
234         return $tree;
235
236 }
237
238 my $slimtree = undef;
239 sub get_slim_org_tree {
240
241         my $self = shift;
242         if($slimtree) { return $slimtree; }
243
244         # see if it's in the cache
245         $slimtree = $cache_client->new()->get_cache('slimorgtree');
246         if($slimtree) { return $slimtree; }
247
248         if(!$orglist) {
249                 warn "Retrieving Org Tree\n";
250                 $orglist = $self->simple_scalar_request( 
251                         "open-ils.storage", 
252                         "open-ils.storage.direct.actor.org_unit.retrieve.all.atomic" );
253         }
254
255         $slimtree = $self->build_org_tree($orglist);
256         $cache_client->new->put_cache('slimorgtree', $slimtree);
257         return $slimtree;
258
259 }
260
261
262 sub build_org_type { 
263         my($self, $org_typelist)  = @_;
264         for my $type (@$org_typelist) {
265                 $org_typelist_hash->{$type->id()} = $type;
266         }
267 }
268
269
270
271 sub build_org_tree {
272
273         my( $self, $orglist, $add_types ) = @_;
274
275         return $orglist unless ( 
276                         ref($orglist) and @$orglist > 1 );
277
278         my @list = sort { 
279                 $a->ou_type <=> $b->ou_type ||
280                 $a->name cmp $b->name } @$orglist;
281
282         for my $org (@list) {
283
284                 next unless ($org);
285
286                 if(!ref($org->ou_type()) and $add_types) {
287                         $org->ou_type( $org_typelist_hash->{$org->ou_type()});
288                 }
289
290                 next unless (defined($org->parent_ou));
291
292                 my ($parent) = grep { $_->id == $org->parent_ou } @list;
293                 next unless $parent;
294                 $parent->children([]) unless defined($parent->children); 
295                 push( @{$parent->children}, $org );
296         }
297
298         return $list[0];
299
300 }
301
302 sub fetch_closed_date {
303         my( $self, $cd ) = @_;
304         my $evt;
305         
306         $logger->debug("Fetching closed_date $cd from storage");
307
308         my $cd_obj = $self->simplereq(
309                 'open-ils.storage',
310                 'open-ils.storage.direct.actor.org_unit.closed_date.retrieve', $cd );
311
312         if(!$cd_obj) {
313                 $logger->info("closed_date $cd not found in the db");
314                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
315         }
316
317         return ($cd_obj, $evt);
318 }
319
320 sub fetch_user {
321         my( $self, $userid ) = @_;
322         my( $user, $evt );
323         
324         $logger->debug("Fetching user $userid from storage");
325
326         $user = $self->simplereq(
327                 'open-ils.storage',
328                 'open-ils.storage.direct.actor.user.retrieve', $userid );
329
330         if(!$user) {
331                 $logger->info("User $userid not found in the db");
332                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
333         }
334
335         return ($user, $evt);
336 }
337
338 sub checkses {
339         my( $self, $session ) = @_;
340         my $user; my $evt; my $e; 
341
342         $logger->debug("Checking user session $session");
343
344         try {
345                 $user = $self->check_user_session($session);
346         } catch Error with { $e = 1; };
347
348         if( $e or !$user ) { $evt = OpenILS::Event->new('NO_SESSION'); }
349         return ( $user, $evt );
350 }
351
352
353 # verifiese the session and checks the permissions agains the
354 # session user and the user's home_ou as the org id
355 sub checksesperm {
356         my( $self, $session, @perms ) = @_;
357         my $user; my $evt; my $e; 
358         $logger->debug("Checking user session $session and perms @perms");
359         ($user, $evt) = $self->checkses($session);
360         return (undef, $evt) if $evt;
361         $evt = $self->check_perms($user->id, $user->home_ou, @perms);
362         return ($user, $evt);
363 }
364
365
366 sub checkrequestor {
367         my( $self, $staffobj, $userid, @perms ) = @_;
368         my $user; my $evt;
369         $userid = $staffobj->id unless defined $userid;
370
371         $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
372
373         if( $userid ne $staffobj->id ) {
374                 ($user, $evt) = $self->fetch_user($userid);
375                 return (undef, $evt) if $evt;
376                 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
377
378         } else {
379                 $user = $staffobj;
380         }
381
382         return ($user, $evt);
383 }
384
385 sub checkses_requestor {
386         my( $self, $authtoken, $targetid, @perms ) = @_;
387         my( $requestor, $target, $evt );
388
389         ($requestor, $evt) = $self->checkses($authtoken);
390         return (undef, undef, $evt) if $evt;
391
392         ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
393         return( $requestor, $target, $evt);
394 }
395
396 sub fetch_copy {
397         my( $self, $copyid ) = @_;
398         my( $copy, $evt );
399
400         $logger->debug("Fetching copy $copyid from storage");
401
402         $copy = $self->simplereq(
403                 'open-ils.storage',
404                 'open-ils.storage.direct.asset.copy.retrieve', $copyid );
405
406         if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
407
408         return( $copy, $evt );
409 }
410
411
412 # retrieves a circ object by id
413 sub fetch_circulation {
414         my( $self, $circid ) = @_;
415         my $circ; my $evt;
416         
417         $logger->debug("Fetching circ $circid from storage");
418
419         $circ = $self->simplereq(
420                 'open-ils.storage',
421                 "open-ils.storage.direct.action.circulation.retrieve", $circid );
422
423         if(!$circ) {
424                 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
425         }
426
427         return ( $circ, $evt );
428 }
429
430 sub fetch_record_by_copy {
431         my( $self, $copyid ) = @_;
432         my( $record, $evt );
433
434         $logger->debug("Fetching record by copy $copyid from storage");
435
436         $record = $self->simplereq(
437                 'open-ils.storage',
438                 'open-ils.storage.fleshed.biblio.record_entry.retrieve_by_copy', $copyid );
439
440         if(!$record) {
441                 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
442         }
443
444         return ($record, $evt);
445 }
446
447 # turns a record object into an mvr (mods) object
448 sub record_to_mvr {
449         my( $self, $record ) = @_;
450         my $u = OpenILS::Utils::ModsParser->new();
451         $u->start_mods_batch( $record->marc );
452         my $mods = $u->finish_mods_batch();
453         $mods->doc_id($record->id);
454         return $mods;
455 }
456
457 sub fetch_hold {
458         my( $self, $holdid ) = @_;
459         my( $hold, $evt );
460
461         $logger->debug("Fetching hold $holdid from storage");
462
463         $hold = $self->simplereq(
464                 'open-ils.storage',
465                 'open-ils.storage.direct.action.hold_request.retrieve', $holdid);
466
467         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
468
469         return ($hold, $evt);
470 }
471
472
473 sub fetch_hold_transit_by_hold {
474         my( $self, $holdid ) = @_;
475         my( $transit, $evt );
476
477         $logger->debug("Fetching transit by hold $holdid from storage");
478
479         $transit = $self->simplereq(
480                 'open-ils.storage',
481                 'open-ils.storage.direct.action.hold_transit_copy.search.hold', $holdid );
482
483         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
484
485         return ($transit, $evt );
486 }
487
488 # fetches the captured, but not fulfilled hold attached to a given copy
489 sub fetch_open_hold_by_copy {
490         my( $self, $copyid ) = @_;
491         $logger->debug("Searching for active hold for copy $copyid");
492         my( $hold, $evt );
493
494         $hold = $self->storagereq(
495                 'open-ils.storage.direct.action.hold_request.search_where',
496                 { 
497                         current_copy            => $copyid , 
498                         capture_time            => { "!=" => undef }, 
499                         fulfillment_time        => undef 
500                 } );
501
502         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
503         return ($hold, $evt);
504 }
505
506 sub fetch_hold_transit {
507         my( $self, $transid ) = @_;
508         my( $htransit, $evt );
509         $logger->debug("Fetching hold transit with hold id $transid");
510         $htransit = $self->storagereq(
511                 'open-ils.storage.direct.action.hold_transit_copy.retrieve', $transid );
512         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
513         return ($htransit, $evt);
514 }
515
516 sub fetch_copy_by_barcode {
517         my( $self, $barcode ) = @_;
518         my( $copy, $evt );
519
520         $logger->debug("Fetching copy by barcode $barcode from storage");
521
522         $copy = $self->simplereq( 'open-ils.storage',
523                 'open-ils.storage.direct.asset.copy.search_where', { barcode => $barcode, deleted => 'f'} );
524                 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
525
526         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
527
528         return ($copy, $evt);
529 }
530
531 sub fetch_open_billable_transaction {
532         my( $self, $transid ) = @_;
533         my( $transaction, $evt );
534
535         $logger->debug("Fetching open billable transaction $transid from storage");
536
537         $transaction = $self->simplereq(
538                 'open-ils.storage',
539                 'open-ils.storage.direct.money.open_billable_transaction_summary.retrieve',  $transid);
540
541         $evt = OpenILS::Event->new(
542                 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
543
544         return ($transaction, $evt);
545 }
546
547
548
549 my %buckets;
550 $buckets{'biblio'} = 'biblio_record_entry_bucket';
551 $buckets{'callnumber'} = 'call_number_bucket';
552 $buckets{'copy'} = 'copy_bucket';
553 $buckets{'user'} = 'user_bucket';
554
555 sub fetch_container {
556         my( $self, $id, $type ) = @_;
557         my( $bucket, $evt );
558
559         $logger->debug("Fetching container $id with type $type");
560
561         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
562         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
563         $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
564         $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
565
566         my $meth = $buckets{$type};
567         $bucket = $self->simplereq(
568                 'open-ils.storage',
569                 "open-ils.storage.direct.container.$meth.retrieve", $id );
570
571         $evt = OpenILS::Event->new(
572                 $e, container => $id, container_type => $type ) unless $bucket;
573
574         return ($bucket, $evt);
575 }
576
577
578 sub fetch_container_item {
579         my( $self, $id, $type ) = @_;
580         my( $bucket, $evt );
581
582         $logger->debug("Fetching container item $id with type $type");
583
584         my $meth = $buckets{$type} . "_item";
585
586         $bucket = $self->simplereq(
587                 'open-ils.storage',
588                 "open-ils.storage.direct.container.$meth.retrieve", $id );
589
590
591         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
592         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
593         $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
594         $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
595
596
597         $evt = OpenILS::Event->new(
598                 $e, itemid => $id, container_type => $type ) unless $bucket;
599
600         return ($bucket, $evt);
601 }
602
603
604 sub fetch_patron_standings {
605         my $self = shift;
606         $logger->debug("Fetching patron standings");    
607         return $self->simplereq(
608                 'open-ils.storage', 
609                 'open-ils.storage.direct.config.standing.retrieve.all.atomic');
610 }
611
612
613 sub fetch_permission_group_tree {
614         my $self = shift;
615         $logger->debug("Fetching patron profiles");     
616         return $self->simplereq(
617                 'open-ils.actor', 
618                 'open-ils.actor.groups.tree.retrieve' );
619 }
620
621
622 sub fetch_patron_circ_summary {
623         my( $self, $userid ) = @_;
624         $logger->debug("Fetching patron summary for $userid");
625         my $summary = $self->simplereq(
626                 'open-ils.storage', 
627                 "open-ils.storage.action.circulation.patron_summary", $userid );
628
629         if( $summary ) {
630                 $summary->[0] ||= 0;
631                 $summary->[1] ||= 0.0;
632                 return $summary;
633         }
634         return undef;
635 }
636
637
638 sub fetch_copy_statuses {
639         my( $self ) = @_;
640         $logger->debug("Fetching copy statuses");
641         return $self->simplereq(
642                 'open-ils.storage', 
643                 'open-ils.storage.direct.config.copy_status.retrieve.all.atomic' );
644 }
645
646 sub fetch_copy_location {
647         my( $self, $id ) = @_;
648         my $evt;
649         my $cl = $self->storagereq(
650                 'open-ils.storage.direct.asset.copy_location.retrieve', $id );
651         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
652         return ($cl, $evt);
653 }
654
655 sub fetch_copy_locations {
656         my $self = shift; 
657         return $self->simplereq(
658                 'open-ils.storage', 
659                 'open-ils.storage.direct.asset.copy_location.retrieve.all.atomic');
660 }
661
662 sub fetch_copy_location_by_name {
663         my( $self, $name, $org ) = @_;
664         my $evt;
665         my $cl = $self->storagereq(
666                 'open-ils.storage.direct.asset.copy_location.search_where',
667                         { name => $name, owning_lib => $org } );
668         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
669         return ($cl, $evt);
670 }
671
672 sub fetch_callnumber {
673         my( $self, $id ) = @_;
674         my $evt = undef;
675         $logger->debug("Fetching callnumber $id");
676
677         my $cn = $self->simplereq(
678                 'open-ils.storage',
679                 'open-ils.storage.direct.asset.call_number.retrieve', $id );
680         $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id ) unless $cn;
681
682         return ( $cn, $evt );
683 }
684
685 my %ORG_CACHE; # - these rarely change, so cache them..
686 sub fetch_org_unit {
687         my( $self, $id ) = @_;
688         return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
689         return $ORG_CACHE{$id} if $ORG_CACHE{$id};
690         $logger->debug("Fetching org unit $id");
691         my $evt = undef;
692
693         my $org = $self->simplereq(
694                 'open-ils.storage', 
695                 'open-ils.storage.direct.actor.org_unit.retrieve', $id );
696         $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
697         $ORG_CACHE{$id}  = $org;
698
699         return ($org, $evt);
700 }
701
702 sub fetch_stat_cat {
703         my( $self, $type, $id ) = @_;
704         my( $cat, $evt );
705         $logger->debug("Fetching $type stat cat: $id");
706         $cat = $self->simplereq(
707                 'open-ils.storage', 
708                 "open-ils.storage.direct.$type.stat_cat.retrieve", $id );
709
710         my $e = 'ASSET_STAT_CAT_NOT_FOUND';
711         $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
712
713         $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
714         return ( $cat, $evt );
715 }
716
717 sub fetch_stat_cat_entry {
718         my( $self, $type, $id ) = @_;
719         my( $entry, $evt );
720         $logger->debug("Fetching $type stat cat entry: $id");
721         $entry = $self->simplereq(
722                 'open-ils.storage', 
723                 "open-ils.storage.direct.$type.stat_cat_entry.retrieve", $id );
724
725         my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
726         $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
727
728         $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
729         return ( $entry, $evt );
730 }
731
732
733 sub find_org {
734         my( $self, $org_tree, $orgid )  = @_;
735         return $org_tree if ( $org_tree->id eq $orgid );
736         return undef unless ref($org_tree->children);
737         for my $c (@{$org_tree->children}) {
738                 my $o = $self->find_org($c, $orgid);
739                 return $o if $o;
740         }
741         return undef;
742 }
743
744 sub fetch_non_cat_type_by_name_and_org {
745         my( $self, $name, $orgId ) = @_;
746         $logger->debug("Fetching non cat type $name at org $orgId");
747         my $types = $self->simplereq(
748                 'open-ils.storage',
749                 'open-ils.storage.direct.config.non_cataloged_type.search_where.atomic',
750                 { name => $name, owning_lib => $orgId } );
751         return ($types->[0], undef) if($types and @$types);
752         return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
753 }
754
755 sub fetch_non_cat_type {
756         my( $self, $id ) = @_;
757         $logger->debug("Fetching non cat type $id");
758         my( $type, $evt );
759         $type = $self->simplereq(
760                 'open-ils.storage', 
761                 'open-ils.storage.direct.config.non_cataloged_type.retrieve', $id );
762         $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
763         return ($type, $evt);
764 }
765
766 sub DB_UPDATE_FAILED { 
767         my( $self, $payload ) = @_;
768         return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
769                 payload => ($payload) ? $payload : undef ); 
770 }
771
772 sub fetch_circ_duration_by_name {
773         my( $self, $name ) = @_;
774         my( $dur, $evt );
775         $dur = $self->simplereq(
776                 'open-ils.storage', 
777                 'open-ils.storage.direct.config.rules.circ_duration.search.name.atomic', $name );
778         $dur = $dur->[0];
779         $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
780         return ($dur, $evt);
781 }
782
783 sub fetch_recurring_fine_by_name {
784         my( $self, $name ) = @_;
785         my( $obj, $evt );
786         $obj = $self->simplereq(
787                 'open-ils.storage', 
788                 'open-ils.storage.direct.config.rules.recuring_fine.search.name.atomic', $name );
789         $obj = $obj->[0];
790         $evt = OpenILS::Event->new('CONFIG_RULES_RECURING_FINE_NOT_FOUND') unless $obj;
791         return ($obj, $evt);
792 }
793
794 sub fetch_max_fine_by_name {
795         my( $self, $name ) = @_;
796         my( $obj, $evt );
797         $obj = $self->simplereq(
798                 'open-ils.storage', 
799                 'open-ils.storage.direct.config.rules.max_fine.search.name.atomic', $name );
800         $obj = $obj->[0];
801         $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
802         return ($obj, $evt);
803 }
804
805 sub storagereq {
806         my( $self, $method, @params ) = @_;
807         return $self->simplereq(
808                 'open-ils.storage', $method, @params );
809 }
810
811 sub event_equals {
812         my( $self, $e, $name ) =  @_;
813         if( $e and ref($e) eq 'HASH' and 
814                 defined($e->{textcode}) and $e->{textcode} eq $name ) {
815                 return 1 ;
816         }
817         return 0;
818 }
819
820 sub logmark {
821         my( undef, $f, $l ) = caller(0);
822         my( undef, undef, undef, $s ) = caller(1);
823         $s =~ s/.*:://g;
824         $f =~ s/.*\///g;
825         $logger->debug("LOGMARK: $f:$l:$s");
826 }
827
828 # takes a copy id 
829 sub fetch_open_circulation {
830         my( $self, $cid ) = @_;
831         my $evt;
832         $self->logmark;
833         my $circ = $self->storagereq(
834                 'open-ils.storage.direct.action.open_circulation.search_where',
835                 { target_copy => $cid, stop_fines_time => undef } );
836         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
837         return ($circ, $evt);
838 }
839
840 sub fetch_all_open_circulation {
841         my( $self, $cid ) = @_;
842         my $evt;
843         $self->logmark;
844         my $circ = $self->storagereq(
845                 'open-ils.storage.direct.action.open_circulation.search_where',
846                 { target_copy => $cid, xact_finish => undef } );
847         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
848         return ($circ, $evt);
849 }
850
851 my $copy_statuses;
852 sub copy_status_from_name {
853         my( $self, $name ) = @_;
854         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
855         for my $status (@$copy_statuses) { 
856                 return $status if( $status->name =~ /$name/i );
857         }
858         return undef;
859 }
860
861 sub copy_status_to_name {
862         my( $self, $sid ) = @_;
863         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
864         for my $status (@$copy_statuses) { 
865                 return $status->name if( $status->id == $sid );
866         }
867         return undef;
868 }
869
870 sub fetch_open_transit_by_copy {
871         my( $self, $copyid ) = @_;
872         my($transit, $evt);
873         $transit = $self->storagereq(
874                 'open-ils.storage.direct.action.transit_copy.search_where',
875                 { target_copy => $copyid, dest_recv_time => undef });
876         $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
877         return ($transit, $evt);
878 }
879
880 sub unflesh_copy {
881         my( $self, $copy ) = @_;
882         return undef unless $copy;
883         $copy->status( $copy->status->id ) if ref($copy->status);
884         $copy->location( $copy->location->id ) if ref($copy->location);
885         $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
886         return $copy;
887 }
888
889 # un-fleshes a copy and updates it in the DB
890 # returns a DB_UPDATE_FAILED event on error
891 # returns undef on success
892 sub update_copy {
893         my( $self, %params ) = @_;
894
895         my $copy                = $params{copy} || die "update_copy(): copy required";
896         my $editor      = $params{editor} || die "update_copy(): copy editor required";
897         my $session = $params{session};
898
899         $logger->debug("Updating copy in the database: " . $copy->id);
900
901         $self->unflesh_copy($copy);
902         $copy->editor( $editor );
903         $copy->edit_date( 'now' );
904
905         my $s;
906         my $meth = 'open-ils.storage.direct.asset.copy.update';
907
908         $s = $session->request( $meth, $copy )->gather(1) if $session;
909         $s = $self->storagereq( $meth, $copy ) unless $session;
910
911         $logger->debug("Update of copy ".$copy->id." returned: $s");
912
913         return $self->DB_UPDATE_FAILED($copy) unless $s;
914         return undef;
915 }
916
917 sub fetch_billable_xact {
918         my( $self, $id ) = @_;
919         my($xact, $evt);
920         $logger->debug("Fetching billable transaction %id");
921         $xact = $self->storagereq(
922                 'open-ils.storage.direct.money.billable_transaction.retrieve', $id );
923         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
924         return ($xact, $evt);
925 }
926
927
928 sub fetch_fleshed_copy {
929         my( $self, $id ) = @_;
930         my( $copy, $evt );
931         $logger->info("Fetching fleshed copy $id");
932         $copy = $self->storagereq(
933                 "open-ils.storage.fleshed.asset.copy.retrieve", $id );
934         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
935         return ($copy, $evt);
936 }
937
938
939 # returns the org that owns the callnumber that the copy
940 # is attached to
941 sub fetch_copy_owner {
942         my( $self, $copyid ) = @_;
943         my( $copy, $cn, $evt );
944         $logger->debug("Fetching copy owner $copyid");
945         ($copy, $evt) = $self->fetch_copy($copyid);
946         return (undef,$evt) if $evt;
947         ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
948         return (undef,$evt) if $evt;
949         return ($cn->owning_lib);
950 }
951
952 sub fetch_copy_note {
953         my( $self, $id ) = @_;
954         my( $note, $evt );
955         $logger->debug("Fetching copy note $id");
956         $note = $self->storagereq(
957                 'open-ils.storage.direct.asset.copy_note.retrieve', $id );
958         $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
959         return ($note, $evt);
960 }
961
962 sub fetch_call_numbers_by_title {
963         my( $self, $titleid ) = @_;
964         $logger->info("Fetching call numbers by title $titleid");
965         return $self->storagereq(
966                 'open-ils.storage.direct.asset.call_number.search_where.atomic', 
967                 { record => $titleid, deleted => 'f' });
968                 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
969 }
970
971 sub fetch_copies_by_call_number {
972         my( $self, $cnid ) = @_;
973         $logger->info("Fetching copies by call number $cnid");
974         return $self->storagereq(
975                 'open-ils.storage.direct.asset.copy.search_where.atomic', { call_number => $cnid, deleted => 'f' } );
976                 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
977 }
978
979 sub fetch_user_by_barcode {
980         my( $self, $bc ) = @_;
981         my $cardid = $self->storagereq(
982                 'open-ils.storage.id_list.actor.card.search.barcode', $bc );
983         return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
984         my $user = $self->storagereq(
985                 'open-ils.storage.direct.actor.user.search.card', $cardid );
986         return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
987         return ($user);
988         
989 }
990
991
992 # ---------------------------------------------------------------------
993 # Updates and returns the patron penalties
994 # ---------------------------------------------------------------------
995 sub update_patron_penalties {
996         my( $self, %args ) = @_;
997         return $self->simplereq(
998                 'open-ils.penalty',
999                 'open-ils.penalty.patron_penalty.calculate', 
1000                 { update => 1, %args }
1001         );
1002 }
1003
1004 sub fetch_bill {
1005         my( $self, $billid ) = @_;
1006         $logger->debug("Fetching billing $billid");
1007         my $bill = $self->storagereq(
1008                 'open-ils.storage.direct.money.billing.retrieve', $billid );
1009         my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1010         return($bill, $evt);
1011 }
1012
1013
1014
1015 my $ORG_TREE;
1016 sub fetch_org_tree {
1017         my $self = shift;
1018         return $ORG_TREE if $ORG_TREE;
1019         return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit( 
1020                 [
1021                         {"parent_ou" => undef },
1022                         {
1023                                 flesh                           => 2,
1024                                 flesh_fields    => { aou =>  ['children'] },
1025                                 order_by       => { aou => 'name'}
1026                         }
1027                 ]
1028         )->[0];
1029 }
1030
1031 sub walk_org_tree {
1032         my( $self, $node, $callback ) = @_;
1033         return unless $node;
1034         $callback->($node);
1035         if( $node->children ) {
1036                 $self->walk_org_tree($_, $callback) for @{$node->children};
1037         }
1038 }
1039
1040
1041
1042
1043 1;
1044