]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/AppUtils.pm
made backdating smarter by using the circ interval and parsing the backdate
[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    $mods->tcn($record->tcn_value);
441         return $mods;
442 }
443
444 sub fetch_hold {
445         my( $self, $holdid ) = @_;
446         my( $hold, $evt );
447
448         $logger->debug("Fetching hold $holdid from cstore");
449
450         $hold = $self->simplereq(
451                 'open-ils.cstore',
452                 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
453
454         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
455
456         return ($hold, $evt);
457 }
458
459
460 sub fetch_hold_transit_by_hold {
461         my( $self, $holdid ) = @_;
462         my( $transit, $evt );
463
464         $logger->debug("Fetching transit by hold $holdid from cstore");
465
466         $transit = $self->simplereq(
467                 'open-ils.cstore',
468                 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
469
470         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
471
472         return ($transit, $evt );
473 }
474
475 # fetches the captured, but not fulfilled hold attached to a given copy
476 sub fetch_open_hold_by_copy {
477         my( $self, $copyid ) = @_;
478         $logger->debug("Searching for active hold for copy $copyid");
479         my( $hold, $evt );
480
481         $hold = $self->cstorereq(
482                 'open-ils.cstore.direct.action.hold_request.search',
483                 { 
484                         current_copy            => $copyid , 
485                         capture_time            => { "!=" => undef }, 
486                         fulfillment_time        => undef,
487                         cancel_time                     => undef,
488                 } );
489
490         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
491         return ($hold, $evt);
492 }
493
494 sub fetch_hold_transit {
495         my( $self, $transid ) = @_;
496         my( $htransit, $evt );
497         $logger->debug("Fetching hold transit with hold id $transid");
498         $htransit = $self->cstorereq(
499                 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
500         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
501         return ($htransit, $evt);
502 }
503
504 sub fetch_copy_by_barcode {
505         my( $self, $barcode ) = @_;
506         my( $copy, $evt );
507
508         $logger->debug("Fetching copy by barcode $barcode from cstore");
509
510         $copy = $self->simplereq( 'open-ils.cstore',
511                 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
512                 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
513
514         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
515
516         return ($copy, $evt);
517 }
518
519 sub fetch_open_billable_transaction {
520         my( $self, $transid ) = @_;
521         my( $transaction, $evt );
522
523         $logger->debug("Fetching open billable transaction $transid from cstore");
524
525         $transaction = $self->simplereq(
526                 'open-ils.cstore',
527                 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve',  $transid);
528
529         $evt = OpenILS::Event->new(
530                 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
531
532         return ($transaction, $evt);
533 }
534
535
536
537 my %buckets;
538 $buckets{'biblio'} = 'biblio_record_entry_bucket';
539 $buckets{'callnumber'} = 'call_number_bucket';
540 $buckets{'copy'} = 'copy_bucket';
541 $buckets{'user'} = 'user_bucket';
542
543 sub fetch_container {
544         my( $self, $id, $type ) = @_;
545         my( $bucket, $evt );
546
547         $logger->debug("Fetching container $id with type $type");
548
549         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
550         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
551         $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
552         $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
553
554         my $meth = $buckets{$type};
555         $bucket = $self->simplereq(
556                 'open-ils.cstore',
557                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
558
559         $evt = OpenILS::Event->new(
560                 $e, container => $id, container_type => $type ) unless $bucket;
561
562         return ($bucket, $evt);
563 }
564
565
566 sub fetch_container_e {
567         my( $self, $editor, $id, $type ) = @_;
568
569         my( $bucket, $evt );
570         $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
571         $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
572         $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
573         $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
574
575         $evt = $editor->event unless $bucket;
576         return ($bucket, $evt);
577 }
578
579 sub fetch_container_item_e {
580         my( $self, $editor, $id, $type ) = @_;
581
582         my( $bucket, $evt );
583         $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
584         $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
585         $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
586         $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
587
588         $evt = $editor->event unless $bucket;
589         return ($bucket, $evt);
590 }
591
592
593
594
595
596 sub fetch_container_item {
597         my( $self, $id, $type ) = @_;
598         my( $bucket, $evt );
599
600         $logger->debug("Fetching container item $id with type $type");
601
602         my $meth = $buckets{$type} . "_item";
603
604         $bucket = $self->simplereq(
605                 'open-ils.cstore',
606                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
607
608
609         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
610         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
611         $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
612         $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
613
614         $evt = OpenILS::Event->new(
615                 $e, itemid => $id, container_type => $type ) unless $bucket;
616
617         return ($bucket, $evt);
618 }
619
620
621 sub fetch_patron_standings {
622         my $self = shift;
623         $logger->debug("Fetching patron standings");    
624         return $self->simplereq(
625                 'open-ils.cstore', 
626                 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
627 }
628
629
630 sub fetch_permission_group_tree {
631         my $self = shift;
632         $logger->debug("Fetching patron profiles");     
633         return $self->simplereq(
634                 'open-ils.actor', 
635                 'open-ils.actor.groups.tree.retrieve' );
636 }
637
638
639 sub fetch_patron_circ_summary {
640         my( $self, $userid ) = @_;
641         $logger->debug("Fetching patron summary for $userid");
642         my $summary = $self->simplereq(
643                 'open-ils.storage', 
644                 "open-ils.storage.action.circulation.patron_summary", $userid );
645
646         if( $summary ) {
647                 $summary->[0] ||= 0;
648                 $summary->[1] ||= 0.0;
649                 return $summary;
650         }
651         return undef;
652 }
653
654
655 sub fetch_copy_statuses {
656         my( $self ) = @_;
657         $logger->debug("Fetching copy statuses");
658         return $self->simplereq(
659                 'open-ils.cstore', 
660                 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
661 }
662
663 sub fetch_copy_location {
664         my( $self, $id ) = @_;
665         my $evt;
666         my $cl = $self->cstorereq(
667                 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
668         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
669         return ($cl, $evt);
670 }
671
672 sub fetch_copy_locations {
673         my $self = shift; 
674         return $self->simplereq(
675                 'open-ils.cstore', 
676                 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
677 }
678
679 sub fetch_copy_location_by_name {
680         my( $self, $name, $org ) = @_;
681         my $evt;
682         my $cl = $self->cstorereq(
683                 'open-ils.cstore.direct.asset.copy_location.search',
684                         { name => $name, owning_lib => $org } );
685         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
686         return ($cl, $evt);
687 }
688
689 sub fetch_callnumber {
690         my( $self, $id ) = @_;
691         my $evt = undef;
692
693         my $e = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
694         return( undef, $e ) unless $id;
695
696         $logger->debug("Fetching callnumber $id");
697
698         my $cn = $self->simplereq(
699                 'open-ils.cstore',
700                 'open-ils.cstore.direct.asset.call_number.retrieve', $id );
701         $evt = $e  unless $cn;
702
703         return ( $cn, $evt );
704 }
705
706 my %ORG_CACHE; # - these rarely change, so cache them..
707 sub fetch_org_unit {
708         my( $self, $id ) = @_;
709         return undef unless $id;
710         return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
711         return $ORG_CACHE{$id} if $ORG_CACHE{$id};
712         $logger->debug("Fetching org unit $id");
713         my $evt = undef;
714
715         my $org = $self->simplereq(
716                 'open-ils.cstore', 
717                 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
718         $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
719         $ORG_CACHE{$id}  = $org;
720
721         return ($org, $evt);
722 }
723
724 sub fetch_stat_cat {
725         my( $self, $type, $id ) = @_;
726         my( $cat, $evt );
727         $logger->debug("Fetching $type stat cat: $id");
728         $cat = $self->simplereq(
729                 'open-ils.cstore', 
730                 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
731
732         my $e = 'ASSET_STAT_CAT_NOT_FOUND';
733         $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
734
735         $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
736         return ( $cat, $evt );
737 }
738
739 sub fetch_stat_cat_entry {
740         my( $self, $type, $id ) = @_;
741         my( $entry, $evt );
742         $logger->debug("Fetching $type stat cat entry: $id");
743         $entry = $self->simplereq(
744                 'open-ils.cstore', 
745                 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
746
747         my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
748         $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
749
750         $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
751         return ( $entry, $evt );
752 }
753
754
755 sub find_org {
756         my( $self, $org_tree, $orgid )  = @_;
757         return $org_tree if ( $org_tree->id eq $orgid );
758         return undef unless ref($org_tree->children);
759         for my $c (@{$org_tree->children}) {
760                 my $o = $self->find_org($c, $orgid);
761                 return $o if $o;
762         }
763         return undef;
764 }
765
766 sub fetch_non_cat_type_by_name_and_org {
767         my( $self, $name, $orgId ) = @_;
768         $logger->debug("Fetching non cat type $name at org $orgId");
769         my $types = $self->simplereq(
770                 'open-ils.cstore',
771                 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
772                 { name => $name, owning_lib => $orgId } );
773         return ($types->[0], undef) if($types and @$types);
774         return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
775 }
776
777 sub fetch_non_cat_type {
778         my( $self, $id ) = @_;
779         $logger->debug("Fetching non cat type $id");
780         my( $type, $evt );
781         $type = $self->simplereq(
782                 'open-ils.cstore', 
783                 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
784         $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
785         return ($type, $evt);
786 }
787
788 sub DB_UPDATE_FAILED { 
789         my( $self, $payload ) = @_;
790         return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
791                 payload => ($payload) ? $payload : undef ); 
792 }
793
794 sub fetch_circ_duration_by_name {
795         my( $self, $name ) = @_;
796         my( $dur, $evt );
797         $dur = $self->simplereq(
798                 'open-ils.cstore', 
799                 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
800         $dur = $dur->[0];
801         $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
802         return ($dur, $evt);
803 }
804
805 sub fetch_recurring_fine_by_name {
806         my( $self, $name ) = @_;
807         my( $obj, $evt );
808         $obj = $self->simplereq(
809                 'open-ils.cstore', 
810                 'open-ils.cstore.direct.config.rules.recuring_fine.search.atomic', { name => $name } );
811         $obj = $obj->[0];
812         $evt = OpenILS::Event->new('CONFIG_RULES_RECURING_FINE_NOT_FOUND') unless $obj;
813         return ($obj, $evt);
814 }
815
816 sub fetch_max_fine_by_name {
817         my( $self, $name ) = @_;
818         my( $obj, $evt );
819         $obj = $self->simplereq(
820                 'open-ils.cstore', 
821                 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
822         $obj = $obj->[0];
823         $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
824         return ($obj, $evt);
825 }
826
827 sub storagereq {
828         my( $self, $method, @params ) = @_;
829         return $self->simplereq(
830                 'open-ils.storage', $method, @params );
831 }
832
833 sub cstorereq {
834         my( $self, $method, @params ) = @_;
835         return $self->simplereq(
836                 'open-ils.cstore', $method, @params );
837 }
838
839 sub event_equals {
840         my( $self, $e, $name ) =  @_;
841         if( $e and ref($e) eq 'HASH' and 
842                 defined($e->{textcode}) and $e->{textcode} eq $name ) {
843                 return 1 ;
844         }
845         return 0;
846 }
847
848 sub logmark {
849         my( undef, $f, $l ) = caller(0);
850         my( undef, undef, undef, $s ) = caller(1);
851         $s =~ s/.*:://g;
852         $f =~ s/.*\///g;
853         $logger->debug("LOGMARK: $f:$l:$s");
854 }
855
856 # takes a copy id 
857 sub fetch_open_circulation {
858         my( $self, $cid ) = @_;
859         my $evt;
860         $self->logmark;
861         my $circ = $self->cstorereq(
862                 'open-ils.cstore.direct.action.open_circulation.search',
863                 { target_copy => $cid, stop_fines_time => undef } );
864         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
865         return ($circ, $evt);
866 }
867
868 sub fetch_all_open_circulation {
869         my( $self, $cid ) = @_;
870         my $evt;
871         $self->logmark;
872         my $circ = $self->cstorereq(
873                 'open-ils.cstore.direct.action.open_circulation.search',
874                 { target_copy => $cid, xact_finish => undef } );
875         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
876         return ($circ, $evt);
877 }
878
879 my $copy_statuses;
880 sub copy_status_from_name {
881         my( $self, $name ) = @_;
882         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
883         for my $status (@$copy_statuses) { 
884                 return $status if( $status->name =~ /$name/i );
885         }
886         return undef;
887 }
888
889 sub copy_status_to_name {
890         my( $self, $sid ) = @_;
891         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
892         for my $status (@$copy_statuses) { 
893                 return $status->name if( $status->id == $sid );
894         }
895         return undef;
896 }
897
898
899 sub copy_status {
900         my( $self, $arg ) = @_;
901         return $arg if ref $arg;
902         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
903         my ($stat) = grep { $_->id == $arg } @$copy_statuses;
904         return $stat;
905 }
906
907 sub fetch_open_transit_by_copy {
908         my( $self, $copyid ) = @_;
909         my($transit, $evt);
910         $transit = $self->cstorereq(
911                 'open-ils.cstore.direct.action.transit_copy.search',
912                 { target_copy => $copyid, dest_recv_time => undef });
913         $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
914         return ($transit, $evt);
915 }
916
917 sub unflesh_copy {
918         my( $self, $copy ) = @_;
919         return undef unless $copy;
920         $copy->status( $copy->status->id ) if ref($copy->status);
921         $copy->location( $copy->location->id ) if ref($copy->location);
922         $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
923         return $copy;
924 }
925
926 # un-fleshes a copy and updates it in the DB
927 # returns a DB_UPDATE_FAILED event on error
928 # returns undef on success
929 sub update_copy {
930         my( $self, %params ) = @_;
931
932         my $copy                = $params{copy} || die "update_copy(): copy required";
933         my $editor      = $params{editor} || die "update_copy(): copy editor required";
934         my $session = $params{session};
935
936         $logger->debug("Updating copy in the database: " . $copy->id);
937
938         $self->unflesh_copy($copy);
939         $copy->editor( $editor );
940         $copy->edit_date( 'now' );
941
942         my $s;
943         my $meth = 'open-ils.storage.direct.asset.copy.update';
944
945         $s = $session->request( $meth, $copy )->gather(1) if $session;
946         $s = $self->storagereq( $meth, $copy ) unless $session;
947
948         $logger->debug("Update of copy ".$copy->id." returned: $s");
949
950         return $self->DB_UPDATE_FAILED($copy) unless $s;
951         return undef;
952 }
953
954 sub fetch_billable_xact {
955         my( $self, $id ) = @_;
956         my($xact, $evt);
957         $logger->debug("Fetching billable transaction %id");
958         $xact = $self->cstorereq(
959                 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
960         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
961         return ($xact, $evt);
962 }
963
964 sub fetch_billable_xact_summary {
965         my( $self, $id ) = @_;
966         my($xact, $evt);
967         $logger->debug("Fetching billable transaction summary %id");
968         $xact = $self->cstorereq(
969                 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
970         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
971         return ($xact, $evt);
972 }
973
974 sub fetch_fleshed_copy {
975         my( $self, $id ) = @_;
976         my( $copy, $evt );
977         $logger->info("Fetching fleshed copy $id");
978         $copy = $self->cstorereq(
979                 "open-ils.cstore.direct.asset.copy.retrieve", $id,
980                 { flesh => 1,
981                   flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
982                 }
983         );
984         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
985         return ($copy, $evt);
986 }
987
988
989 # returns the org that owns the callnumber that the copy
990 # is attached to
991 sub fetch_copy_owner {
992         my( $self, $copyid ) = @_;
993         my( $copy, $cn, $evt );
994         $logger->debug("Fetching copy owner $copyid");
995         ($copy, $evt) = $self->fetch_copy($copyid);
996         return (undef,$evt) if $evt;
997         ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
998         return (undef,$evt) if $evt;
999         return ($cn->owning_lib);
1000 }
1001
1002 sub fetch_copy_note {
1003         my( $self, $id ) = @_;
1004         my( $note, $evt );
1005         $logger->debug("Fetching copy note $id");
1006         $note = $self->cstorereq(
1007                 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1008         $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1009         return ($note, $evt);
1010 }
1011
1012 sub fetch_call_numbers_by_title {
1013         my( $self, $titleid ) = @_;
1014         $logger->info("Fetching call numbers by title $titleid");
1015         return $self->cstorereq(
1016                 'open-ils.cstore.direct.asset.call_number.search.atomic', 
1017                 { record => $titleid, deleted => 'f' });
1018                 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1019 }
1020
1021 sub fetch_copies_by_call_number {
1022         my( $self, $cnid ) = @_;
1023         $logger->info("Fetching copies by call number $cnid");
1024         return $self->cstorereq(
1025                 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1026                 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1027 }
1028
1029 sub fetch_user_by_barcode {
1030         my( $self, $bc ) = @_;
1031         my $cardid = $self->cstorereq(
1032                 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1033         return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1034         my $user = $self->cstorereq(
1035                 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1036         return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1037         return ($user);
1038         
1039 }
1040
1041
1042 # ---------------------------------------------------------------------
1043 # Updates and returns the patron penalties
1044 # ---------------------------------------------------------------------
1045 sub update_patron_penalties {
1046         my( $self, %args ) = @_;
1047         return $self->simplereq(
1048                 'open-ils.penalty',
1049                 'open-ils.penalty.patron_penalty.calculate', 
1050                 { update => 1, %args }
1051         );
1052 }
1053
1054 sub fetch_bill {
1055         my( $self, $billid ) = @_;
1056         $logger->debug("Fetching billing $billid");
1057         my $bill = $self->cstorereq(
1058                 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1059         my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1060         return($bill, $evt);
1061 }
1062
1063
1064
1065 my $ORG_TREE;
1066 sub fetch_org_tree {
1067         my $self = shift;
1068         return $ORG_TREE if $ORG_TREE;
1069         return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit( 
1070                 [
1071                         {"parent_ou" => undef },
1072                         {
1073                                 flesh                           => 2,
1074                                 flesh_fields    => { aou =>  ['children'] },
1075                                 order_by       => { aou => 'name'}
1076                         }
1077                 ]
1078         )->[0];
1079 }
1080
1081 sub walk_org_tree {
1082         my( $self, $node, $callback ) = @_;
1083         return unless $node;
1084         $callback->($node);
1085         if( $node->children ) {
1086                 $self->walk_org_tree($_, $callback) for @{$node->children};
1087         }
1088 }
1089
1090 sub is_true {
1091         my( $self, $item ) = @_;
1092         return 1 if $item and $item !~ /^f$/i;
1093         return 0;
1094 }
1095
1096
1097 # This logic now lives in storage
1098 sub __patron_money_owed {
1099         my( $self, $patronid ) = @_;
1100         my $ses = OpenSRF::AppSession->create('open-ils.storage');
1101         my $req = $ses->request(
1102                 'open-ils.storage.money.billable_transaction.summary.search',
1103                 { usr => $patronid, xact_finish => undef } );
1104
1105         my $total = 0;
1106         my $data;
1107         while( $data = $req->recv ) {
1108                 $data = $data->content;
1109                 $total += $data->balance_owed;
1110         }
1111         return $total;
1112 }
1113
1114 sub patron_money_owed {
1115         my( $self, $userid ) = @_;
1116         return $self->storagereq(
1117                 'open-ils.storage.actor.user.total_owed', $userid);
1118 }
1119
1120 sub patron_total_items_out {
1121         my( $self, $userid ) = @_;
1122         return $self->storagereq(
1123                 'open-ils.storage.actor.user.total_out', $userid);
1124 }
1125
1126
1127
1128
1129 #---------------------------------------------------------------------
1130 # Returns  ($summary, $event) 
1131 #---------------------------------------------------------------------
1132 sub fetch_mbts {
1133         my $self = shift;
1134         my $id  = shift;
1135         my $editor = shift || OpenILS::Utils::CStoreEditor->new;
1136
1137         $id = $id->id if (ref($id));
1138
1139         my $xact = $editor->retrieve_money_billable_transaction(
1140                 [
1141                         $id, {  
1142                                 flesh => 1, 
1143                                 flesh_fields => { mbt => [ qw/billings payments grocery circulation/ ] } 
1144                         }
1145                 ]
1146         ) or return (undef, $editor->event);
1147
1148         return $self->make_mbts($xact);
1149 }
1150
1151
1152 #---------------------------------------------------------------------
1153 # Given a list of money.billable_transaction objects, this creates
1154 # transaction summary objects for each
1155 #--------------------------------------------------------------------
1156 sub make_mbts {
1157         my $self = shift;
1158         my @xacts = @_;
1159
1160         my @mbts;
1161         for my $x (@xacts) {
1162
1163                 my $s = new Fieldmapper::money::billable_transaction_summary;
1164
1165                 $s->id( $x->id );
1166                 $s->usr( $x->usr );
1167                 $s->xact_start( $x->xact_start );
1168                 $s->xact_finish( $x->xact_finish );
1169                 
1170                 my $to = 0;
1171                 my $lb = undef;
1172                 for my $b (@{ $x->billings }) {
1173                         next if ($self->is_true($b->voided));
1174                         $to += ($b->amount * 100);
1175                         $lb ||= $b->billing_ts;
1176                         if ($b->billing_ts ge $lb) {
1177                                 $lb = $b->billing_ts;
1178                                 $s->last_billing_note($b->note);
1179                                 $s->last_billing_ts($b->billing_ts);
1180                                 $s->last_billing_type($b->billing_type);
1181                         }
1182                 }
1183
1184                 $s->total_owed( sprintf('%0.2f', $to / 100 ) );
1185                 
1186                 my $tp = 0;
1187                 my $lp = undef;
1188                 for my $p (@{ $x->payments }) {
1189                         next if ($self->is_true($p->voided));
1190                         $tp += ($p->amount * 100);
1191                         $lp ||= $p->payment_ts;
1192                         if ($p->payment_ts ge $lp) {
1193                                 $lp = $p->payment_ts;
1194                                 $s->last_payment_note($p->note);
1195                                 $s->last_payment_ts($p->payment_ts);
1196                                 $s->last_payment_type($p->payment_type);
1197                         }
1198                 }
1199
1200                 $s->total_paid( sprintf('%0.2f', $tp / 100 ) );
1201                 $s->balance_owed( sprintf('%0.2f', ($to - $tp) / 100) );
1202                 $s->xact_type('grocery') if ($x->grocery);
1203                 $s->xact_type('circulation') if ($x->circulation);
1204
1205                 $logger->debug("Created mbts with balance_owed = ". $s->balance_owed);
1206                 
1207                 push @mbts, $s;
1208         }
1209                 
1210         return @mbts;
1211 }
1212                 
1213                 
1214 sub ou_ancestor_setting_value {
1215     my $obj = ou_ancestor_setting(@_);
1216     return ($obj) ? $obj->{value} : undef;
1217 }
1218
1219 sub ou_ancestor_setting {
1220     my( $self, $orgid, $name, $e ) = @_;
1221     $e = $e || OpenILS::Utils::CStoreEditor->new;
1222
1223     do {
1224         my $setting = $e->search_actor_org_unit_setting({org_unit=>$orgid, name=>$name})->[0];
1225
1226         if( $setting ) {
1227             $logger->info("found org_setting $name at org $orgid : " . $setting->value);
1228             return { org => $orgid, value => JSON->JSON2perl($setting->value) };
1229         }
1230
1231         my $org = $e->retrieve_actor_org_unit($orgid) or return $e->event;
1232         $orgid = $org->parent_ou or return undef;
1233
1234     } while(1);
1235
1236     return undef;
1237 }       
1238                 
1239
1240 # returns the ISO8601 string representation of the requested epoch in GMT
1241 sub epoch2ISO8601 {
1242     my( $self, $epoch ) = @_;
1243     my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1244     $year += 1900; $mon += 1;
1245     my $date = sprintf(
1246         '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1247         $year, $mon, $mday, $hour, $min, $sec);
1248     return $date;
1249 }
1250                         
1251         
1252 1;
1253