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