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