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